lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
agpl-3.0
1c4d985c81b36443f4f26bcce5ec298522109223
0
jpaoletti/jPOS-Presentation-Manager,jpaoletti/jPOS-Presentation-Manager
/* * jPOS Presentation Manager [http://jpospm.blogspot.com] * Copyright (C) 2010 Jeronimo Paoletti [[email protected]] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jpos.ee.pm.struts.actions; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.jpos.core.ConfigurationException; import org.jpos.ee.pm.core.Operations; import org.jpos.ee.pm.core.PMException; import org.jpos.ee.pm.core.PMLogger; import org.jpos.ee.pm.core.PaginatedList; import org.jpos.ee.pm.struts.PMEntitySupport; import org.jpos.ee.pm.struts.PMStrutsContext; import org.jpos.util.DisplacedList; public class ListAction extends EntityActionSupport { /**Makes the operation generate an auditory entry*/ protected boolean isAudited() { return false; } /**Forces execute to check if there is an entity defined in parameters*/ protected boolean checkEntity(){ return true; } protected void doExecute(PMStrutsContext ctx) throws PMException { ListActionForm f = (ListActionForm) ctx.getForm(); configureList(ctx,f); boolean searchable = ctx.getOperation().getConfig("searchable", "true").compareTo("true")==0; boolean paginable = ctx.getOperation().getConfig("paginable", "true").compareTo("true")==0; Boolean showRowNumber = ctx.getOperation().getConfig("show-row-number", "false").compareTo("true")==0; String operationColWidth= ctx.getOperation().getConfig("operation-column-width", "50px"); Operations operations = (Operations) ctx.getSession().getAttribute(OPERATIONS); ctx.getRequest().setAttribute("searchable", searchable); ctx.getRequest().setAttribute("paginable", paginable); ctx.getRequest().setAttribute("show_row_number", showRowNumber); ctx.getRequest().setAttribute("operation_column_width", operationColWidth); ctx.getRequest().setAttribute("show_checks", true); ctx.getRequest().setAttribute("has_selected", operations.getOperationsForScope(SCOPE_SELECTED).count() > 0); } private void configureList(PMStrutsContext ctx, ListActionForm f) throws PMException { List<Object> contents = null; Long total = null; Integer rpp = 10; PaginatedList pmlist = ctx.getList(); if(pmlist == null){ pmlist = new PaginatedList(); pmlist.setEntity(ctx.getEntity()); Operations operations = (Operations) ctx.getSession().getAttribute(OPERATIONS); pmlist.setOperations (operations.getOperationsForScope(SCOPE_GRAL, SCOPE_SELECTED)); String sortfield = ctx.getOperation().getConfig("sort-field"); String sortdirection = ctx.getOperation().getConfig("sort-direction"); if(sortfield!=null){ pmlist.setOrder(sortfield); if(sortdirection!=null && sortdirection.toLowerCase().compareTo("desc")==0) pmlist.setDesc(true); } } if(ctx.getParameter(FINISH)!=null){ pmlist.setOrder(f.getOrder()); pmlist.setDesc(f.isDesc()); pmlist.setPage((f.getPage()!=null && f.getPage()>0)?f.getPage():1); pmlist.setRowsPerPage(f.getRowsPerPage()); } if(ctx.isWeak()){ PMLogger.debug(this,"Listing weak entity"); //The list is the collection of the owner. String entity_property = ctx.getEntity().getOwner().getEntityProperty(); Collection<Object> moc = getModifiedOwnerCollection(ctx, entity_property); if(moc == null){ moc = getOwnerCollection(ctx); } contents = new ArrayList<Object>(); try { Collection<Object> result; String collection_class = ctx.getEntity().getOwner().getEntityCollectionClass(); result = (Collection<Object>) PMEntitySupport.getInstance().getPmservice().getFactory().newInstance (collection_class ); if(moc != null) result.addAll(moc); PMLogger.debug(this,"Setting modified owner collection: "+result); setModifiedOwnerCollection(ctx, entity_property, result); contents.addAll(result); } catch (ConfigurationException e) { PMLogger.error(e); } if(!ctx.getEntity().getNoCount()) total = new Long(contents.size()); }else{ ctx.put(PM_LIST_ORDER, pmlist.getOrder()); ctx.put(PM_LIST_ASC, !pmlist.isDesc()); try { contents = (List<Object>) ctx.getEntity().getList(ctx, ctx.getEntityContainer().getFilter(), pmlist.from(), pmlist.rpp()); if(!ctx.getEntity().getNoCount()) total = ctx.getEntity().getDataAccess().count(ctx); } catch (Exception e) { PMLogger.error(e); throw new PMException("pm.operation.cant.load.list"); } rpp = pmlist.rpp(); } PMLogger.debug(this,"List Contents: "+contents); ctx.getEntityContainer().setList(pmlist); pmlist.setContents(new DisplacedList<Object>( contents )); pmlist.setTotal(total); PMLogger.debug(this,"Resulting list: "+pmlist); pmlist.setRowsPerPage (rpp); } }
modules/pm_struts/src/org/jpos/ee/pm/struts/actions/ListAction.java
/* * jPOS Presentation Manager [http://jpospm.blogspot.com] * Copyright (C) 2010 Jeronimo Paoletti [[email protected]] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jpos.ee.pm.struts.actions; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.jpos.core.ConfigurationException; import org.jpos.ee.pm.core.Operations; import org.jpos.ee.pm.core.PMException; import org.jpos.ee.pm.core.PMLogger; import org.jpos.ee.pm.core.PaginatedList; import org.jpos.ee.pm.struts.PMEntitySupport; import org.jpos.ee.pm.struts.PMStrutsContext; import org.jpos.util.DisplacedList; public class ListAction extends EntityActionSupport { /**Makes the operation generate an auditory entry*/ protected boolean isAudited() { return false; } /**Forces execute to check if there is an entity defined in parameters*/ protected boolean checkEntity(){ return true; } protected void doExecute(PMStrutsContext ctx) throws PMException { ListActionForm f = (ListActionForm) ctx.getForm(); configureList(ctx,f); boolean searchable = ctx.getOperation().getConfig("searchable", "true").compareTo("true")==0; boolean paginable = ctx.getOperation().getConfig("paginable", "true").compareTo("true")==0; Boolean showRowNumber = ctx.getOperation().getConfig("show-row-number", "false").compareTo("true")==0; String operationColWidth= ctx.getOperation().getConfig("operation-column-width", "50px"); Operations operations = (Operations) ctx.getSession().getAttribute(OPERATIONS); ctx.getRequest().setAttribute("searchable", searchable); ctx.getRequest().setAttribute("paginable", paginable); ctx.getRequest().setAttribute("show_row_number", showRowNumber); ctx.getRequest().setAttribute("operation_column_width", operationColWidth); ctx.getRequest().setAttribute("show_checks", true); ctx.getRequest().setAttribute("has_selected", operations.getOperationsForScope(SCOPE_SELECTED).count() > 0); } private void configureList(PMStrutsContext ctx, ListActionForm f) throws PMException { List<Object> contents = null; Long total = null; Integer rpp = 10; PaginatedList pmlist = ctx.getList(); if(pmlist == null){ pmlist = new PaginatedList(); pmlist.setEntity(ctx.getEntity()); Operations operations = (Operations) ctx.getSession().getAttribute(OPERATIONS); pmlist.setOperations (operations.getOperationsForScope(SCOPE_GRAL, SCOPE_SELECTED)); String sortfield = ctx.getOperation().getConfig("sort-field"); String sortdirection = ctx.getOperation().getConfig("sort-direction"); if(sortfield!=null){ pmlist.setOrder(sortfield); if(sortdirection!=null && sortdirection.toLowerCase().compareTo("desc")==0) pmlist.setDesc(true); } } if(ctx.getParameter(FINISH)!=null){ pmlist.setOrder(f.getOrder()); pmlist.setDesc(f.isDesc()); pmlist.setPage(f.getPage()); pmlist.setRowsPerPage(f.getRowsPerPage()); } if(ctx.isWeak()){ PMLogger.debug(this,"Listing weak entity"); //The list is the collection of the owner. String entity_property = ctx.getEntity().getOwner().getEntityProperty(); Collection<Object> moc = getModifiedOwnerCollection(ctx, entity_property); if(moc == null){ moc = getOwnerCollection(ctx); } contents = new ArrayList<Object>(); try { Collection<Object> result; String collection_class = ctx.getEntity().getOwner().getEntityCollectionClass(); result = (Collection<Object>) PMEntitySupport.getInstance().getPmservice().getFactory().newInstance (collection_class ); if(moc != null) result.addAll(moc); PMLogger.debug(this,"Setting modified owner collection: "+result); setModifiedOwnerCollection(ctx, entity_property, result); contents.addAll(result); } catch (ConfigurationException e) { PMLogger.error(e); } if(!ctx.getEntity().getNoCount()) total = new Long(contents.size()); }else{ ctx.put(PM_LIST_ORDER, pmlist.getOrder()); ctx.put(PM_LIST_ASC, !pmlist.isDesc()); try { contents = (List<Object>) ctx.getEntity().getList(ctx, ctx.getEntityContainer().getFilter(), pmlist.from(), pmlist.rpp()); if(!ctx.getEntity().getNoCount()) total = ctx.getEntity().getDataAccess().count(ctx); } catch (Exception e) { PMLogger.error(e); throw new PMException("pm.operation.cant.load.list"); } rpp = pmlist.rpp(); } PMLogger.debug(this,"List Contents: "+contents); ctx.getEntityContainer().setList(pmlist); pmlist.setContents(new DisplacedList<Object>( contents )); pmlist.setTotal(total); PMLogger.debug(this,"Resulting list: "+pmlist); pmlist.setRowsPerPage (rpp); } }
BugFix. Now user cant set a 0 or negative page number
modules/pm_struts/src/org/jpos/ee/pm/struts/actions/ListAction.java
BugFix. Now user cant set a 0 or negative page number
<ide><path>odules/pm_struts/src/org/jpos/ee/pm/struts/actions/ListAction.java <ide> if(ctx.getParameter(FINISH)!=null){ <ide> pmlist.setOrder(f.getOrder()); <ide> pmlist.setDesc(f.isDesc()); <del> pmlist.setPage(f.getPage()); <add> pmlist.setPage((f.getPage()!=null && f.getPage()>0)?f.getPage():1); <ide> pmlist.setRowsPerPage(f.getRowsPerPage()); <ide> } <ide>
JavaScript
apache-2.0
0c4ad747889f5dcbe279f33b1b0099a9f0def71b
0
gencer/gitbook,escopecz/documentation,tshoper/gitbook,athiruban/gitbook,gencer/gitbook,npracht/documentation,strawluffy/gitbook,mautic/documentation,escopecz/documentation,tshoper/gitbook,ryanswanson/gitbook,mautic/documentation,sunlianghua/gitbook,megumiteam/documentation,megumiteam/documentation,sunlianghua/gitbook,haamop/documentation,athiruban/gitbook,npracht/documentation,haamop/documentation,GitbookIO/gitbook
var _ = require('lodash'); var Q = require('q'); var npmi = require('npmi'); var npm = require('npm'); var semver = require('semver'); var Plugin = require('./plugin'); var version = require('./version'); var initNPM = _.memoize(function() { return Q.nfcall(npm.load, { silent: true, loglevel: 'silent' }); }); var PluginsList = function(book, plugins) { this.book = book; this.log = this.book.log; // List of Plugin objects this.list = []; // List of names of failed plugins this.failed = []; // Namespaces this.namespaces = _.chain(['website', 'ebook']) .map(function(namespace) { return [ namespace, { html: {}, resources: _.chain(Plugin.RESOURCES) .map(function(type) { return [type, []]; }) .object() .value() } ]; }) .object() .value(); // Bind methods _.bindAll(this); if (plugins) this.load(plugins); }; // return count of plugins PluginsList.prototype.count = function() { return this.list.length; }; // Add and load a plugin PluginsList.prototype.load = function(plugin) { var that = this; if (_.isArray(plugin)) { return _.reduce(plugin, function(prev, p) { return prev.then(function() { return that.load(p); }); }, Q()); } if (_.isObject(plugin) && !(plugin instanceof Plugin)) plugin = plugin.name; if (_.isString(plugin)) plugin = new Plugin(this.book, plugin); that.log.info('load plugin', plugin.name, '....'); if (!plugin.isValid()) { that.log.info.fail(); that.failed.push(plugin.name); return Q(); } else { that.log.info.ok(); // Push in the list that.list.push(plugin); } return Q() // Validate and normalize configuration .then(function() { var config = plugin.getConfig(); return plugin.validateConfig(config); }) .then(function(config) { // Update configuration plugin.setConfig(config); // Extract filters that.book.template.addFilters(plugin.getFilters()); // Extract blocks that.book.template.addBlocks(plugin.getBlocks()); return _.reduce(_.keys(that.namespaces), function(prev, namespaceName) { return prev.then(function() { return plugin.getResources(namespaceName) .then(function(plResources) { var namespace = that.namespaces[namespaceName]; // Extract js and css _.each(Plugin.RESOURCES, function(resourceType) { namespace.resources[resourceType] = (namespace.resources[resourceType] || []).concat(plResources[resourceType] || []); }); // Map of html resources by name added by each plugin _.each(plResources.html || {}, function(value, tag) { // Turn into function if not one already if (!_.isFunction(value)) value = _.constant(value); namespace.html[tag] = namespace.html[tag] || []; namespace.html[tag].push(value); }); }); }); }, Q()); }); }; // Call a hook PluginsList.prototype.hook = function(name, data) { return _.reduce(this.list, function(prev, plugin) { return prev.then(function(ret) { return plugin.callHook(name, ret); }); }, Q(data)); }; // Return a template from a plugin PluginsList.prototype.template = function(name) { var withTpl = _.find(this.list, function(plugin) { return ( plugin.infos.templates && plugin.infos.templates[name] ); }); if (!withTpl) return null; return withTpl.resolveFile(withTpl.infos.templates[name]); }; // Return an html snippet PluginsList.prototype.html = function(namespace, tag, context, options) { var htmlSnippets = this.namespaces[namespace].html[tag]; return _.map(htmlSnippets || [], function(code) { return code.call(context, options); }).join('\n'); }; // Return a resources map for a namespace PluginsList.prototype.resources = function(namespace) { return this.namespaces[namespace].resources; }; // Install plugins from a book PluginsList.prototype.install = function() { var that = this; // Remove defaults (no need to install) var plugins = _.reject(that.book.options.plugins, { isDefault: true }); // Install plugins one by one that.book.log.info.ln(plugins.length+' plugins to install'); return _.reduce(plugins, function(prev, plugin) { return prev.then(function() { var fullname = 'gitbook-plugin-'+plugin.name; return Q() // Resolve version if needed .then(function() { if (plugin.version) return plugin.version; that.book.log.info.ln('No version specified, resolve plugin', plugin.name); return initNPM() .then(function() { return Q.nfcall(npm.commands.view, [fullname+'@*', 'engines'], true); }) .then(function(versions) { return _.chain(versions) .pairs() .map(function(v) { return { version: v[0], gitbook: (v[1].engines || {}).gitbook }; }) .filter(function(v) { return v.gitbook && version.satisfies(v.gitbook); }) .sort(function(v1, v2) { return semver.lt(v1.version, v2.version)? 1 : -1; }) .pluck('version') .first() .value(); }); }) // Install the plugin with the resolved version .then(function(version) { if (!version) { throw 'Found no satisfactory version for plugin '+plugin.name; } that.book.log.info.ln('install plugin', plugin.name, 'from npm ('+fullname+') with version', version); return Q.nfcall(npmi, { 'name': fullname, 'version': version, 'path': that.book.root, 'npmLoad': { 'loglevel': 'silent', 'loaded': true, 'prefix': that.book.root } }); }) .then(function() { that.book.log.info.ok('plugin', plugin.name, 'installed with success'); }); }); }, Q()); }; module.exports = PluginsList;
lib/pluginslist.js
var _ = require('lodash'); var Q = require('q'); var npmi = require('npmi'); var npm = require('npm'); var semver = require('semver'); var Plugin = require('./plugin'); var pkg = require('../package.json'); var initNPM = _.memoize(function() { return Q.nfcall(npm.load, { silent: true, loglevel: 'silent' }); }); var PluginsList = function(book, plugins) { this.book = book; this.log = this.book.log; // List of Plugin objects this.list = []; // List of names of failed plugins this.failed = []; // Namespaces this.namespaces = _.chain(['website', 'ebook']) .map(function(namespace) { return [ namespace, { html: {}, resources: _.chain(Plugin.RESOURCES) .map(function(type) { return [type, []]; }) .object() .value() } ]; }) .object() .value(); // Bind methods _.bindAll(this); if (plugins) this.load(plugins); }; // return count of plugins PluginsList.prototype.count = function() { return this.list.length; }; // Add and load a plugin PluginsList.prototype.load = function(plugin) { var that = this; if (_.isArray(plugin)) { return _.reduce(plugin, function(prev, p) { return prev.then(function() { return that.load(p); }); }, Q()); } if (_.isObject(plugin) && !(plugin instanceof Plugin)) plugin = plugin.name; if (_.isString(plugin)) plugin = new Plugin(this.book, plugin); that.log.info('load plugin', plugin.name, '....'); if (!plugin.isValid()) { that.log.info.fail(); that.failed.push(plugin.name); return Q(); } else { that.log.info.ok(); // Push in the list that.list.push(plugin); } return Q() // Validate and normalize configuration .then(function() { var config = plugin.getConfig(); return plugin.validateConfig(config); }) .then(function(config) { // Update configuration plugin.setConfig(config); // Extract filters that.book.template.addFilters(plugin.getFilters()); // Extract blocks that.book.template.addBlocks(plugin.getBlocks()); return _.reduce(_.keys(that.namespaces), function(prev, namespaceName) { return prev.then(function() { return plugin.getResources(namespaceName) .then(function(plResources) { var namespace = that.namespaces[namespaceName]; // Extract js and css _.each(Plugin.RESOURCES, function(resourceType) { namespace.resources[resourceType] = (namespace.resources[resourceType] || []).concat(plResources[resourceType] || []); }); // Map of html resources by name added by each plugin _.each(plResources.html || {}, function(value, tag) { // Turn into function if not one already if (!_.isFunction(value)) value = _.constant(value); namespace.html[tag] = namespace.html[tag] || []; namespace.html[tag].push(value); }); }); }); }, Q()); }); }; // Call a hook PluginsList.prototype.hook = function(name, data) { return _.reduce(this.list, function(prev, plugin) { return prev.then(function(ret) { return plugin.callHook(name, ret); }); }, Q(data)); }; // Return a template from a plugin PluginsList.prototype.template = function(name) { var withTpl = _.find(this.list, function(plugin) { return ( plugin.infos.templates && plugin.infos.templates[name] ); }); if (!withTpl) return null; return withTpl.resolveFile(withTpl.infos.templates[name]); }; // Return an html snippet PluginsList.prototype.html = function(namespace, tag, context, options) { var htmlSnippets = this.namespaces[namespace].html[tag]; return _.map(htmlSnippets || [], function(code) { return code.call(context, options); }).join('\n'); }; // Return a resources map for a namespace PluginsList.prototype.resources = function(namespace) { return this.namespaces[namespace].resources; }; // Install plugins from a book PluginsList.prototype.install = function() { var that = this; // Remove defaults (no need to install) var plugins = _.reject(that.book.options.plugins, { isDefault: true }); // Install plugins one by one that.book.log.info.ln(plugins.length+' plugins to install'); return _.reduce(plugins, function(prev, plugin) { return prev.then(function() { var fullname = 'gitbook-plugin-'+plugin.name; return Q() // Resolve version if needed .then(function() { if (plugin.version) return plugin.version; that.book.log.info.ln('No version specified, resolve plugin', plugin.name); return initNPM() .then(function() { return Q.nfcall(npm.commands.view, [fullname+'@*', 'engines'], true); }) .then(function(versions) { return _.chain(versions) .pairs() .map(function(v) { return { version: v[0], gitbook: (v[1].engines || {}).gitbook }; }) .filter(function(v) { return v.gitbook && semver.satisfies(pkg.version, v.gitbook); }) .sort(function(v1, v2) { return semver.lt(v1.version, v2.version)? 1 : -1; }) .pluck('version') .first() .value(); }); }) // Install the plugin with the resolved version .then(function(version) { if (!version) { throw 'Found no satisfactory version for plugin '+plugin.name; } that.book.log.info.ln('install plugin', plugin.name, 'from npm ('+fullname+') with version', version); return Q.nfcall(npmi, { 'name': fullname, 'version': version, 'path': that.book.root, 'npmLoad': { 'loglevel': 'silent', 'loaded': true, 'prefix': that.book.root } }); }) .then(function() { that.book.log.info.ok('plugin', plugin.name, 'installed with success'); }); }); }, Q()); }; module.exports = PluginsList;
Fix resolve of plugins for prereleases
lib/pluginslist.js
Fix resolve of plugins for prereleases
<ide><path>ib/pluginslist.js <ide> var semver = require('semver'); <ide> <ide> var Plugin = require('./plugin'); <del>var pkg = require('../package.json'); <add>var version = require('./version'); <ide> <ide> var initNPM = _.memoize(function() { <ide> return Q.nfcall(npm.load, { silent: true, loglevel: 'silent' }); <ide> }; <ide> }) <ide> .filter(function(v) { <del> return v.gitbook && semver.satisfies(pkg.version, v.gitbook); <add> return v.gitbook && version.satisfies(v.gitbook); <ide> }) <ide> .sort(function(v1, v2) { <ide> return semver.lt(v1.version, v2.version)? 1 : -1;
JavaScript
bsd-3-clause
568fb403bfb5b4b92ec912812b00095047d18850
0
pandiaraj44/react-native,skevy/react-native,Livyli/react-native,tsjing/react-native,janicduplessis/react-native,PlexChat/react-native,pandiaraj44/react-native,farazs/react-native,alin23/react-native,kesha-antonov/react-native,kesha-antonov/react-native,tsjing/react-native,adamjmcgrath/react-native,mironiasty/react-native,hammerandchisel/react-native,cdlewis/react-native,thotegowda/react-native,makadaw/react-native,thotegowda/react-native,hoastoolshop/react-native,alin23/react-native,adamjmcgrath/react-native,frantic/react-native,facebook/react-native,happypancake/react-native,makadaw/react-native,ptomasroos/react-native,jasonnoahchoi/react-native,Ehesp/react-native,Guardiannw/react-native,kesha-antonov/react-native,gilesvangruisen/react-native,lprhodes/react-native,hammerandchisel/react-native,cpunion/react-native,exponent/react-native,Maxwell2022/react-native,exponentjs/react-native,Ehesp/react-native,jasonnoahchoi/react-native,arthuralee/react-native,clozr/react-native,Swaagie/react-native,Guardiannw/react-native,rickbeerendonk/react-native,csatf/react-native,exponentjs/react-native,rickbeerendonk/react-native,Maxwell2022/react-native,jasonnoahchoi/react-native,exponentjs/react-native,makadaw/react-native,ptomasroos/react-native,hoangpham95/react-native,Bhullnatik/react-native,doochik/react-native,mironiasty/react-native,chnfeeeeeef/react-native,myntra/react-native,javache/react-native,kesha-antonov/react-native,ptomasroos/react-native,farazs/react-native,exponentjs/react-native,thotegowda/react-native,thotegowda/react-native,skevy/react-native,cpunion/react-native,Livyli/react-native,ndejesus1227/react-native,myntra/react-native,rickbeerendonk/react-native,Ehesp/react-native,lprhodes/react-native,happypancake/react-native,rickbeerendonk/react-native,adamjmcgrath/react-native,Livyli/react-native,exponentjs/react-native,frantic/react-native,Swaagie/react-native,chnfeeeeeef/react-native,mironiasty/react-native,lprhodes/react-native,formatlos/react-native,jasonnoahchoi/react-native,brentvatne/react-native,kesha-antonov/react-native,ptmt/react-native-macos,cdlewis/react-native,happypancake/react-native,skevy/react-native,aljs/react-native,Ehesp/react-native,Bhullnatik/react-native,janicduplessis/react-native,cdlewis/react-native,aljs/react-native,ndejesus1227/react-native,clozr/react-native,janicduplessis/react-native,brentvatne/react-native,javache/react-native,ptmt/react-native-macos,Bhullnatik/react-native,rickbeerendonk/react-native,myntra/react-native,peterp/react-native,Ehesp/react-native,Bhullnatik/react-native,peterp/react-native,dikaiosune/react-native,hoangpham95/react-native,gilesvangruisen/react-native,farazs/react-native,clozr/react-native,exponent/react-native,jevakallio/react-native,farazs/react-native,Livyli/react-native,peterp/react-native,cpunion/react-native,exponent/react-native,myntra/react-native,chnfeeeeeef/react-native,dikaiosune/react-native,happypancake/react-native,chnfeeeeeef/react-native,chnfeeeeeef/react-native,rickbeerendonk/react-native,ptmt/react-native-macos,clozr/react-native,lprhodes/react-native,ptmt/react-native-macos,makadaw/react-native,lprhodes/react-native,Bhullnatik/react-native,mironiasty/react-native,doochik/react-native,ptomasroos/react-native,ptmt/react-native-macos,aljs/react-native,rickbeerendonk/react-native,Maxwell2022/react-native,Maxwell2022/react-native,Guardiannw/react-native,csatf/react-native,pandiaraj44/react-native,adamjmcgrath/react-native,PlexChat/react-native,dikaiosune/react-native,PlexChat/react-native,facebook/react-native,myntra/react-native,Livyli/react-native,farazs/react-native,cpunion/react-native,shrutic123/react-native,lprhodes/react-native,Ehesp/react-native,jevakallio/react-native,tszajna0/react-native,farazs/react-native,jasonnoahchoi/react-native,ptomasroos/react-native,skevy/react-native,doochik/react-native,jevakallio/react-native,javache/react-native,exponent/react-native,ptomasroos/react-native,hoangpham95/react-native,tsjing/react-native,doochik/react-native,skevy/react-native,hoangpham95/react-native,exponent/react-native,makadaw/react-native,makadaw/react-native,PlexChat/react-native,tszajna0/react-native,forcedotcom/react-native,csatf/react-native,shrutic123/react-native,javache/react-native,skevy/react-native,rickbeerendonk/react-native,csatf/react-native,ndejesus1227/react-native,cdlewis/react-native,dikaiosune/react-native,Swaagie/react-native,Maxwell2022/react-native,javache/react-native,javache/react-native,jasonnoahchoi/react-native,hammerandchisel/react-native,happypancake/react-native,janicduplessis/react-native,cdlewis/react-native,thotegowda/react-native,doochik/react-native,Guardiannw/react-native,gilesvangruisen/react-native,chnfeeeeeef/react-native,cpunion/react-native,ptomasroos/react-native,peterp/react-native,tszajna0/react-native,Guardiannw/react-native,hoastoolshop/react-native,mironiasty/react-native,peterp/react-native,cdlewis/react-native,jevakallio/react-native,thotegowda/react-native,tszajna0/react-native,jevakallio/react-native,Bhullnatik/react-native,jasonnoahchoi/react-native,myntra/react-native,javache/react-native,Swaagie/react-native,tsjing/react-native,jevakallio/react-native,alin23/react-native,doochik/react-native,formatlos/react-native,ndejesus1227/react-native,shrutic123/react-native,Swaagie/react-native,Maxwell2022/react-native,thotegowda/react-native,shrutic123/react-native,kesha-antonov/react-native,exponentjs/react-native,hoastoolshop/react-native,Bhullnatik/react-native,mironiasty/react-native,ptomasroos/react-native,farazs/react-native,facebook/react-native,formatlos/react-native,tszajna0/react-native,doochik/react-native,thotegowda/react-native,pandiaraj44/react-native,skevy/react-native,hammerandchisel/react-native,negativetwelve/react-native,ndejesus1227/react-native,pandiaraj44/react-native,PlexChat/react-native,kesha-antonov/react-native,Guardiannw/react-native,mironiasty/react-native,exponent/react-native,clozr/react-native,dikaiosune/react-native,facebook/react-native,happypancake/react-native,brentvatne/react-native,farazs/react-native,exponent/react-native,hammerandchisel/react-native,doochik/react-native,hammerandchisel/react-native,janicduplessis/react-native,hoangpham95/react-native,hammerandchisel/react-native,janicduplessis/react-native,Maxwell2022/react-native,Livyli/react-native,jevakallio/react-native,clozr/react-native,hoastoolshop/react-native,Swaagie/react-native,PlexChat/react-native,gilesvangruisen/react-native,cdlewis/react-native,happypancake/react-native,makadaw/react-native,arthuralee/react-native,shrutic123/react-native,exponentjs/react-native,brentvatne/react-native,aljs/react-native,arthuralee/react-native,gilesvangruisen/react-native,adamjmcgrath/react-native,myntra/react-native,gilesvangruisen/react-native,PlexChat/react-native,ptmt/react-native-macos,kesha-antonov/react-native,tsjing/react-native,facebook/react-native,cdlewis/react-native,kesha-antonov/react-native,ndejesus1227/react-native,facebook/react-native,formatlos/react-native,cpunion/react-native,aljs/react-native,pandiaraj44/react-native,mironiasty/react-native,farazs/react-native,pandiaraj44/react-native,lprhodes/react-native,arthuralee/react-native,tszajna0/react-native,Swaagie/react-native,Ehesp/react-native,myntra/react-native,Swaagie/react-native,hoastoolshop/react-native,hammerandchisel/react-native,PlexChat/react-native,dikaiosune/react-native,peterp/react-native,cpunion/react-native,Maxwell2022/react-native,javache/react-native,cdlewis/react-native,forcedotcom/react-native,formatlos/react-native,negativetwelve/react-native,hoangpham95/react-native,brentvatne/react-native,myntra/react-native,ptmt/react-native-macos,alin23/react-native,aljs/react-native,clozr/react-native,exponent/react-native,makadaw/react-native,hoangpham95/react-native,Guardiannw/react-native,arthuralee/react-native,dikaiosune/react-native,gilesvangruisen/react-native,Livyli/react-native,shrutic123/react-native,csatf/react-native,chnfeeeeeef/react-native,Bhullnatik/react-native,formatlos/react-native,lprhodes/react-native,gilesvangruisen/react-native,forcedotcom/react-native,tsjing/react-native,facebook/react-native,formatlos/react-native,tszajna0/react-native,frantic/react-native,jasonnoahchoi/react-native,hoastoolshop/react-native,alin23/react-native,forcedotcom/react-native,alin23/react-native,jevakallio/react-native,forcedotcom/react-native,adamjmcgrath/react-native,ndejesus1227/react-native,csatf/react-native,cpunion/react-native,alin23/react-native,Guardiannw/react-native,negativetwelve/react-native,facebook/react-native,pandiaraj44/react-native,janicduplessis/react-native,adamjmcgrath/react-native,negativetwelve/react-native,negativetwelve/react-native,doochik/react-native,forcedotcom/react-native,formatlos/react-native,mironiasty/react-native,peterp/react-native,javache/react-native,hoastoolshop/react-native,brentvatne/react-native,exponentjs/react-native,ndejesus1227/react-native,janicduplessis/react-native,shrutic123/react-native,jevakallio/react-native,negativetwelve/react-native,brentvatne/react-native,negativetwelve/react-native,negativetwelve/react-native,happypancake/react-native,shrutic123/react-native,ptmt/react-native-macos,peterp/react-native,aljs/react-native,makadaw/react-native,clozr/react-native,forcedotcom/react-native,tszajna0/react-native,chnfeeeeeef/react-native,brentvatne/react-native,facebook/react-native,frantic/react-native,tsjing/react-native,forcedotcom/react-native,formatlos/react-native,negativetwelve/react-native,rickbeerendonk/react-native,Livyli/react-native,frantic/react-native,tsjing/react-native,alin23/react-native,brentvatne/react-native,adamjmcgrath/react-native,skevy/react-native,Ehesp/react-native,hoastoolshop/react-native,csatf/react-native,csatf/react-native,aljs/react-native,dikaiosune/react-native,hoangpham95/react-native
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; const BatchProcessor = require('./BatchProcessor'); const FetchError = require('node-fetch/lib/fetch-error'); const crypto = require('crypto'); const fetch = require('node-fetch'); const jsonStableStringify = require('json-stable-stringify'); const path = require('path'); import type { Options as TransformWorkerOptions, TransformOptions, } from '../JSTransformer/worker/worker'; import type {CachedResult, GetTransformCacheKey} from './TransformCache'; /** * The API that a global transform cache must comply with. To implement a * custom cache, implement this interface and pass it as argument to the * application's top-level `Server` class. */ export type GlobalTransformCache = { /** * Synchronously determine if it is worth trying to fetch a result from the * cache. This can be used, for instance, to exclude sets of options we know * will never be cached. */ shouldFetch(props: FetchProps): boolean, /** * Try to fetch a result. It doesn't actually need to fetch from a server, * the global cache could be instantiated locally for example. */ fetch(props: FetchProps): Promise<?CachedResult>, /** * Try to store a result, without waiting for the success or failure of the * operation. Consequently, the actual storage operation could be done at a * much later point if desired. It is recommended to actually have this * function be a no-op in production, and only do the storage operation from * a script running on your Continuous Integration platform. */ store(props: FetchProps, result: CachedResult): void, }; type FetchResultURIs = (keys: Array<string>) => Promise<Map<string, string>>; type FetchResultFromURI = (uri: string) => Promise<?CachedResult>; type StoreResults = (resultsByKey: Map<string, CachedResult>) => Promise<void>; export type FetchProps = { filePath: string, sourceCode: string, getTransformCacheKey: GetTransformCacheKey, transformOptions: TransformWorkerOptions, }; type URI = string; /** * We aggregate the requests to do a single request for many keys. It also * ensures we do a single request at a time to avoid pressuring the I/O. */ class KeyURIFetcher { _batchProcessor: BatchProcessor<string, ?URI>; _fetchResultURIs: FetchResultURIs; /** * When a batch request fails for some reason, we process the error locally * and we proceed as if there were no result for these keys instead. That way * a build will not fail just because of the cache. */ async _processKeys(keys: Array<string>): Promise<Array<?URI>> { const URIsByKey = await this._fetchResultURIs(keys); return keys.map(key => URIsByKey.get(key)); } async fetch(key: string): Promise<?string> { return await this._batchProcessor.queue(key); } constructor(fetchResultURIs: FetchResultURIs) { this._fetchResultURIs = fetchResultURIs; this._batchProcessor = new BatchProcessor({ maximumDelayMs: 10, maximumItems: 500, concurrency: 25, }, this._processKeys.bind(this)); } } type KeyedResult = {key: string, result: CachedResult}; class KeyResultStore { _storeResults: StoreResults; _batchProcessor: BatchProcessor<KeyedResult, void>; async _processResults(keyResults: Array<KeyedResult>): Promise<Array<void>> { const resultsByKey = new Map(keyResults.map(pair => [pair.key, pair.result])); await this._storeResults(resultsByKey); return new Array(keyResults.length); } store(key: string, result: CachedResult) { this._batchProcessor.queue({key, result}); } constructor(storeResults: StoreResults) { this._storeResults = storeResults; this._batchProcessor = new BatchProcessor({ maximumDelayMs: 1000, maximumItems: 100, concurrency: 10, }, this._processResults.bind(this)); } } export type TransformProfile = {+dev: boolean, +minify: boolean, +platform: string}; function profileKey({dev, minify, platform}: TransformProfile): string { return jsonStableStringify({dev, minify, platform}); } /** * We avoid doing any request to the server if we know the server is not * going to have any key at all for a particular set of transform options. */ class TransformProfileSet { _profileKeys: Set<string>; constructor(profiles: Iterable<TransformProfile>) { this._profileKeys = new Set(); for (const profile of profiles) { this._profileKeys.add(profileKey(profile)); } } has(profile: TransformProfile): boolean { return this._profileKeys.has(profileKey(profile)); } } type FetchFailedDetails = {+type: 'unhandled_http_status', +statusCode: number} | {+type: 'unspecified'}; class FetchFailedError extends Error { /** Separate object for details allows us to have a type union. */ +details: FetchFailedDetails; constructor(message: string, details: FetchFailedDetails) { super(); this.message = message; (this: any).details = details; } } /** * For some reason the result stored by the server for a key might mismatch what * we expect a result to be. So we need to verify carefully the data. */ function validateCachedResult(cachedResult: mixed): ?CachedResult { if ( cachedResult != null && typeof cachedResult === 'object' && typeof cachedResult.code === 'string' && Array.isArray(cachedResult.dependencies) && cachedResult.dependencies.every(dep => typeof dep === 'string') && Array.isArray(cachedResult.dependencyOffsets) && cachedResult.dependencyOffsets.every(offset => typeof offset === 'number') ) { return (cachedResult: any); } return null; } class URIBasedGlobalTransformCache { _fetcher: KeyURIFetcher; _fetchResultFromURI: FetchResultFromURI; _profileSet: TransformProfileSet; _optionsHasher: OptionsHasher; _store: ?KeyResultStore; static FetchFailedError; /** * For using the global cache one needs to have some kind of central key-value * store that gets prefilled using keyOf() and the transformed results. The * fetching function should provide a mapping of keys to URIs. The files * referred by these URIs contains the transform results. Using URIs instead * of returning the content directly allows for independent and parallel * fetching of each result, that may be arbitrarily large JSON blobs. */ constructor(props: { fetchResultFromURI: FetchResultFromURI, fetchResultURIs: FetchResultURIs, profiles: Iterable<TransformProfile>, rootPath: string, storeResults: StoreResults | null, }) { this._fetcher = new KeyURIFetcher(props.fetchResultURIs); this._profileSet = new TransformProfileSet(props.profiles); this._fetchResultFromURI = props.fetchResultFromURI; this._optionsHasher = new OptionsHasher(props.rootPath); if (props.storeResults != null) { this._store = new KeyResultStore(props.storeResults); } } /** * Return a key for identifying uniquely a source file. */ keyOf(props: FetchProps) { const hash = crypto.createHash('sha1'); const {sourceCode, filePath, transformOptions} = props; this._optionsHasher.hashTransformWorkerOptions(hash, transformOptions); const cacheKey = props.getTransformCacheKey(sourceCode, filePath, transformOptions); hash.update(JSON.stringify(cacheKey)); hash.update(crypto.createHash('sha1').update(sourceCode).digest('hex')); const digest = hash.digest('hex'); return `${digest}-${path.basename(filePath)}`; } /** * We may want to improve that logic to return a stream instead of the whole * blob of transformed results. However the results are generally only a few * megabytes each. */ static async _fetchResultFromURI(uri: string): Promise<CachedResult> { const response = await fetch(uri, {method: 'GET', timeout: 8000}); if (response.status !== 200) { const msg = `Unexpected HTTP status: ${response.status} ${response.statusText} `; throw new FetchFailedError(msg, { type: 'unhandled_http_status', statusCode: response.status, }); } const unvalidatedResult = await response.json(); const result = validateCachedResult(unvalidatedResult); if (result == null) { throw new FetchFailedError('Server returned invalid result.', {type: 'unspecified'}); } return result; } /** * It happens from time to time that a fetch fails, we want to try these again * a second time if we expect them to be transient. We might even consider * waiting a little time before retring if experience shows it's useful. */ static fetchResultFromURI(uri: string): Promise<CachedResult> { return URIBasedGlobalTransformCache._fetchResultFromURI(uri).catch(error => { if (!URIBasedGlobalTransformCache.shouldRetryAfterThatError(error)) { throw error; } return this._fetchResultFromURI(uri); }); } /** * We want to retry timeouts as they're likely temporary. We retry 503 * (Service Unavailable) and 502 (Bad Gateway) because they may be caused by a * some rogue server, or because of throttling. * * There may be other types of error we'd want to retry for, but these are * the ones we experienced the most in practice. */ static shouldRetryAfterThatError(error: Error): boolean { return ( error instanceof FetchError && error.type === 'request-timeout' || ( error instanceof FetchFailedError && error.details.type === 'unhandled_http_status' && (error.details.statusCode === 503 || error.details.statusCode === 502) ) ); } shouldFetch(props: FetchProps): boolean { return this._profileSet.has(props.transformOptions); } /** * This may return `null` if either the cache doesn't have a value for that * key yet, or an error happened, processed separately. */ async fetch(props: FetchProps): Promise<?CachedResult> { const uri = await this._fetcher.fetch(this.keyOf(props)); if (uri == null) { return null; } return await this._fetchResultFromURI(uri); } store(props: FetchProps, result: CachedResult) { if (this._store != null) { this._store.store(this.keyOf(props), result); } } } class OptionsHasher { _rootPath: string; constructor(rootPath: string) { this._rootPath = rootPath; } /** * This function is extra-conservative with how it hashes the transform * options. In particular: * * * we need to hash paths relative to the root, not the absolute paths, * otherwise everyone would have a different cache, defeating the * purpose of global cache; * * we need to reject any additional field we do not know of, because * they could contain absolute path, and we absolutely want to process * these. * * Theorically, Flow could help us prevent any other field from being here by * using *exact* object type. In practice, the transform options are a mix of * many different fields including the optional Babel fields, and some serious * cleanup will be necessary to enable rock-solid typing. */ hashTransformWorkerOptions(hash: crypto$Hash, options: TransformWorkerOptions): crypto$Hash { const {dev, minify, platform, transform, extern, ...unknowns} = options; const unknownKeys = Object.keys(unknowns); if (unknownKeys.length > 0) { const message = `these worker option fields are unknown: ${JSON.stringify(unknownKeys)}`; throw new CannotHashOptionsError(message); } // eslint-disable-next-line no-undef, no-bitwise hash.update(new Buffer([+dev | +minify << 1 | +!!extern << 2])); hash.update(JSON.stringify(platform)); return this.hashTransformOptions(hash, transform); } /** * The transform options contain absolute paths. This can contain, for * example, the username if someone works their home directory (very likely). * We get rid of this local data for the global cache, otherwise nobody would * share the same cache keys. The project roots should not be needed as part * of the cache key as they should not affect the transformation of a single * particular file. */ hashTransformOptions(hash: crypto$Hash, options: TransformOptions): crypto$Hash { const {generateSourceMaps, dev, hot, inlineRequires, platform, preloadedModules, projectRoots, ramGroups, ...unknowns} = options; const unknownKeys = Object.keys(unknowns); if (unknownKeys.length > 0) { const message = `these transform option fields are unknown: ${JSON.stringify(unknownKeys)}`; throw new CannotHashOptionsError(message); } // eslint-disable-next-line no-undef hash.update(new Buffer([ // eslint-disable-next-line no-bitwise +dev | +generateSourceMaps << 1 | +hot << 2 | +!!inlineRequires << 3, ])); hash.update(JSON.stringify(platform)); let relativeBlacklist = []; if (typeof inlineRequires === 'object') { relativeBlacklist = this.relativizeFilePaths(Object.keys(inlineRequires.blacklist)); } const relativeProjectRoots = this.relativizeFilePaths(projectRoots); const optionTuple = [relativeBlacklist, preloadedModules, relativeProjectRoots, ramGroups]; hash.update(JSON.stringify(optionTuple)); return hash; } relativizeFilePaths(filePaths: Array<string>): Array<string> { return filePaths.map(filepath => path.relative(this._rootPath, filepath)); } } class CannotHashOptionsError extends Error { constructor(message: string) { super(); this.message = message; } } URIBasedGlobalTransformCache.FetchFailedError = FetchFailedError; module.exports = {URIBasedGlobalTransformCache, CannotHashOptionsError};
packager/src/lib/GlobalTransformCache.js
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; const BatchProcessor = require('./BatchProcessor'); const FetchError = require('node-fetch/lib/fetch-error'); const crypto = require('crypto'); const fetch = require('node-fetch'); const jsonStableStringify = require('json-stable-stringify'); const path = require('path'); import type { Options as TransformWorkerOptions, TransformOptions, } from '../JSTransformer/worker/worker'; import type {CachedResult, GetTransformCacheKey} from './TransformCache'; /** * The API that a global transform cache must comply with. To implement a * custom cache, implement this interface and pass it as argument to the * application's top-level `Server` class. */ export type GlobalTransformCache = { /** * Synchronously determine if it is worth trying to fetch a result from the * cache. This can be used, for instance, to exclude sets of options we know * will never be cached. */ shouldFetch(props: FetchProps): boolean, /** * Try to fetch a result. It doesn't actually need to fetch from a server, * the global cache could be instantiated locally for example. */ fetch(props: FetchProps): Promise<?CachedResult>, /** * Try to store a result, without waiting for the success or failure of the * operation. Consequently, the actual storage operation could be done at a * much later point if desired. It is recommended to actually have this * function be a no-op in production, and only do the storage operation from * a script running on your Continuous Integration platform. */ store(props: FetchProps, result: CachedResult): void, }; type FetchResultURIs = (keys: Array<string>) => Promise<Map<string, string>>; type FetchResultFromURI = (uri: string) => Promise<?CachedResult>; type StoreResults = (resultsByKey: Map<string, CachedResult>) => Promise<void>; export type FetchProps = { filePath: string, sourceCode: string, getTransformCacheKey: GetTransformCacheKey, transformOptions: TransformWorkerOptions, }; type URI = string; /** * We aggregate the requests to do a single request for many keys. It also * ensures we do a single request at a time to avoid pressuring the I/O. */ class KeyURIFetcher { _batchProcessor: BatchProcessor<string, ?URI>; _fetchResultURIs: FetchResultURIs; /** * When a batch request fails for some reason, we process the error locally * and we proceed as if there were no result for these keys instead. That way * a build will not fail just because of the cache. */ async _processKeys(keys: Array<string>): Promise<Array<?URI>> { const URIsByKey = await this._fetchResultURIs(keys); return keys.map(key => URIsByKey.get(key)); } async fetch(key: string): Promise<?string> { return await this._batchProcessor.queue(key); } constructor(fetchResultURIs: FetchResultURIs) { this._fetchResultURIs = fetchResultURIs; this._batchProcessor = new BatchProcessor({ maximumDelayMs: 10, maximumItems: 500, concurrency: 25, }, this._processKeys.bind(this)); } } type KeyedResult = {key: string, result: CachedResult}; class KeyResultStore { _storeResults: StoreResults; _batchProcessor: BatchProcessor<KeyedResult, void>; async _processResults(keyResults: Array<KeyedResult>): Promise<Array<void>> { const resultsByKey = new Map(keyResults.map(pair => [pair.key, pair.result])); await this._storeResults(resultsByKey); return new Array(keyResults.length); } store(key: string, result: CachedResult) { this._batchProcessor.queue({key, result}); } constructor(storeResults: StoreResults) { this._storeResults = storeResults; this._batchProcessor = new BatchProcessor({ maximumDelayMs: 1000, maximumItems: 100, concurrency: 10, }, this._processResults.bind(this)); } } export type TransformProfile = {+dev: boolean, +minify: boolean, +platform: string}; function profileKey({dev, minify, platform}: TransformProfile): string { return jsonStableStringify({dev, minify, platform}); } /** * We avoid doing any request to the server if we know the server is not * going to have any key at all for a particular set of transform options. */ class TransformProfileSet { _profileKeys: Set<string>; constructor(profiles: Iterable<TransformProfile>) { this._profileKeys = new Set(); for (const profile of profiles) { this._profileKeys.add(profileKey(profile)); } } has(profile: TransformProfile): boolean { return this._profileKeys.has(profileKey(profile)); } } type FetchFailedDetails = {+type: 'unhandled_http_status', +statusCode: number} | {+type: 'unspecified'}; class FetchFailedError extends Error { /** Separate object for details allows us to have a type union. */ +details: FetchFailedDetails; constructor(message: string, details: FetchFailedDetails) { super(); this.message = message; (this: any).details = details; } } /** * For some reason the result stored by the server for a key might mismatch what * we expect a result to be. So we need to verify carefully the data. */ function validateCachedResult(cachedResult: mixed): ?CachedResult { if ( cachedResult != null && typeof cachedResult === 'object' && typeof cachedResult.code === 'string' && Array.isArray(cachedResult.dependencies) && cachedResult.dependencies.every(dep => typeof dep === 'string') && Array.isArray(cachedResult.dependencyOffsets) && cachedResult.dependencyOffsets.every(offset => typeof offset === 'number') ) { return (cachedResult: any); } return null; } class URIBasedGlobalTransformCache { _fetcher: KeyURIFetcher; _fetchResultFromURI: FetchResultFromURI; _profileSet: TransformProfileSet; _optionsHasher: OptionsHasher; _store: ?KeyResultStore; static FetchFailedError; /** * For using the global cache one needs to have some kind of central key-value * store that gets prefilled using keyOf() and the transformed results. The * fetching function should provide a mapping of keys to URIs. The files * referred by these URIs contains the transform results. Using URIs instead * of returning the content directly allows for independent and parallel * fetching of each result, that may be arbitrarily large JSON blobs. */ constructor(props: { fetchResultFromURI: FetchResultFromURI, fetchResultURIs: FetchResultURIs, profiles: Iterable<TransformProfile>, rootPath: string, storeResults: StoreResults | null, }) { this._fetcher = new KeyURIFetcher(props.fetchResultURIs); this._profileSet = new TransformProfileSet(props.profiles); this._fetchResultFromURI = props.fetchResultFromURI; this._optionsHasher = new OptionsHasher(props.rootPath); if (props.storeResults != null) { this._store = new KeyResultStore(props.storeResults); } } /** * Return a key for identifying uniquely a source file. */ keyOf(props: FetchProps) { const hash = crypto.createHash('sha1'); const {sourceCode, filePath, transformOptions} = props; this._optionsHasher.hashTransformWorkerOptions(hash, transformOptions); const cacheKey = props.getTransformCacheKey(sourceCode, filePath, transformOptions); hash.update(JSON.stringify(cacheKey)); hash.update(crypto.createHash('sha1').update(sourceCode).digest('hex')); const digest = hash.digest('hex'); return `${digest}-${path.basename(filePath)}`; } /** * We may want to improve that logic to return a stream instead of the whole * blob of transformed results. However the results are generally only a few * megabytes each. */ static async _fetchResultFromURI(uri: string): Promise<CachedResult> { const response = await fetch(uri, {method: 'GET', timeout: 8000}); if (response.status !== 200) { const msg = `Unexpected HTTP status: ${response.status} ${response.statusText} `; throw new FetchFailedError(msg, { type: 'unhandled_http_status', statusCode: response.status, }); } const unvalidatedResult = await response.json(); const result = validateCachedResult(unvalidatedResult); if (result == null) { throw new FetchFailedError('Server returned invalid result.', {type: 'unspecified'}); } return result; } /** * It happens from time to time that a fetch fails, we want to try these again * a second time if we expect them to be transient. We might even consider * waiting a little time before retring if experience shows it's useful. */ static fetchResultFromURI(uri: string): Promise<CachedResult> { return URIBasedGlobalTransformCache._fetchResultFromURI(uri).catch(error => { if (!URIBasedGlobalTransformCache.shouldRetryAfterThatError(error)) { throw error; } return this._fetchResultFromURI(uri); }); } /** * We want to retry timeouts as they're likely temporary. We retry 503 * (Service Unavailable) and 502 (Bad Gateway) because they may be caused by a * some rogue server, or because of throttling. * * There may be other types of error we'd want to retry for, but these are * the ones we experienced the most in practice. */ static shouldRetryAfterThatError(error: Error): boolean { return ( error instanceof FetchError && error.type === 'request-timeout' || ( error instanceof FetchFailedError && error.details.type === 'wrong_http_status' && (error.details.statusCode === 503 || error.details.statusCode === 502) ) ); } shouldFetch(props: FetchProps): boolean { return this._profileSet.has(props.transformOptions); } /** * This may return `null` if either the cache doesn't have a value for that * key yet, or an error happened, processed separately. */ async fetch(props: FetchProps): Promise<?CachedResult> { const uri = await this._fetcher.fetch(this.keyOf(props)); if (uri == null) { return null; } return await this._fetchResultFromURI(uri); } store(props: FetchProps, result: CachedResult) { if (this._store != null) { this._store.store(this.keyOf(props), result); } } } class OptionsHasher { _rootPath: string; constructor(rootPath: string) { this._rootPath = rootPath; } /** * This function is extra-conservative with how it hashes the transform * options. In particular: * * * we need to hash paths relative to the root, not the absolute paths, * otherwise everyone would have a different cache, defeating the * purpose of global cache; * * we need to reject any additional field we do not know of, because * they could contain absolute path, and we absolutely want to process * these. * * Theorically, Flow could help us prevent any other field from being here by * using *exact* object type. In practice, the transform options are a mix of * many different fields including the optional Babel fields, and some serious * cleanup will be necessary to enable rock-solid typing. */ hashTransformWorkerOptions(hash: crypto$Hash, options: TransformWorkerOptions): crypto$Hash { const {dev, minify, platform, transform, extern, ...unknowns} = options; const unknownKeys = Object.keys(unknowns); if (unknownKeys.length > 0) { const message = `these worker option fields are unknown: ${JSON.stringify(unknownKeys)}`; throw new CannotHashOptionsError(message); } // eslint-disable-next-line no-undef, no-bitwise hash.update(new Buffer([+dev | +minify << 1 | +!!extern << 2])); hash.update(JSON.stringify(platform)); return this.hashTransformOptions(hash, transform); } /** * The transform options contain absolute paths. This can contain, for * example, the username if someone works their home directory (very likely). * We get rid of this local data for the global cache, otherwise nobody would * share the same cache keys. The project roots should not be needed as part * of the cache key as they should not affect the transformation of a single * particular file. */ hashTransformOptions(hash: crypto$Hash, options: TransformOptions): crypto$Hash { const {generateSourceMaps, dev, hot, inlineRequires, platform, preloadedModules, projectRoots, ramGroups, ...unknowns} = options; const unknownKeys = Object.keys(unknowns); if (unknownKeys.length > 0) { const message = `these transform option fields are unknown: ${JSON.stringify(unknownKeys)}`; throw new CannotHashOptionsError(message); } // eslint-disable-next-line no-undef hash.update(new Buffer([ // eslint-disable-next-line no-bitwise +dev | +generateSourceMaps << 1 | +hot << 2 | +!!inlineRequires << 3, ])); hash.update(JSON.stringify(platform)); let relativeBlacklist = []; if (typeof inlineRequires === 'object') { relativeBlacklist = this.relativizeFilePaths(Object.keys(inlineRequires.blacklist)); } const relativeProjectRoots = this.relativizeFilePaths(projectRoots); const optionTuple = [relativeBlacklist, preloadedModules, relativeProjectRoots, ramGroups]; hash.update(JSON.stringify(optionTuple)); return hash; } relativizeFilePaths(filePaths: Array<string>): Array<string> { return filePaths.map(filepath => path.relative(this._rootPath, filepath)); } } class CannotHashOptionsError extends Error { constructor(message: string) { super(); this.message = message; } } URIBasedGlobalTransformCache.FetchFailedError = FetchFailedError; module.exports = {URIBasedGlobalTransformCache, CannotHashOptionsError};
packager: GlobalTransformCache: fix bug in retry logic Reviewed By: bestander Differential Revision: D4850644 fbshipit-source-id: ede9991eaac3c7bfd045f2a9c3e9d0b10d45af0f
packager/src/lib/GlobalTransformCache.js
packager: GlobalTransformCache: fix bug in retry logic
<ide><path>ackager/src/lib/GlobalTransformCache.js <ide> return ( <ide> error instanceof FetchError && error.type === 'request-timeout' || ( <ide> error instanceof FetchFailedError && <del> error.details.type === 'wrong_http_status' && <add> error.details.type === 'unhandled_http_status' && <ide> (error.details.statusCode === 503 || error.details.statusCode === 502) <ide> ) <ide> );
Java
mit
0983057a990c4787614939f0f2ffe3c5df29eba0
0
philippneugebauer/tananzeiger,philippneugebauer/TanManager
package de.uniba.ppn.tananzeiger.model; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Observable; import javax.xml.bind.JAXBException; import org.xml.sax.SAXException; import de.uniba.ppn.tananzeiger.logik.TANSpeicher; import de.uniba.ppn.tananzeiger.logik.TextReader; import de.uniba.ppn.tananzeiger.xml.XMLReader; import de.uniba.ppn.tananzeiger.xml.XMLWriter; public class Model extends Observable { private TANSpeicher tanList; private File file; private XMLWriter writer; private TextReader reader; private XMLReader xmlReader; public Model(File file) { this.file = file; tanList = new TANSpeicher(); writer = new XMLWriter(); reader = new TextReader(); xmlReader = new XMLReader(); } public ArrayList<String> getList() { return tanList.getTanSpeicher(); } public void deleteTan() throws JAXBException { getList().remove(0); this.setChanged(); this.notifyObservers(); writeXml(); } public void readXml() throws JAXBException, SAXException, IOException { this.tanList = xmlReader.readTanXml(file); this.setChanged(); this.notifyObservers(); } public void loadXML(File file) throws JAXBException, SAXException, IOException { readXml(); writeXml(); } public void writeXml() throws JAXBException { writer.writeTanXml(tanList, file); } public int getSize() { return getList().size(); } public void readFile(File file) throws IOException, JAXBException { tanList.setTanSpeicher(reader.readFile(file)); this.setChanged(); this.notifyObservers(); writeXml(); } }
src/de/uniba/ppn/tananzeiger/model/Model.java
package de.uniba.ppn.tananzeiger.model; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Observable; import javax.xml.bind.JAXBException; import de.uniba.ppn.tananzeiger.logik.TANSpeicher; import de.uniba.ppn.tananzeiger.logik.TextReader; import de.uniba.ppn.tananzeiger.xml.XMLReader; import de.uniba.ppn.tananzeiger.xml.XMLWriter; public class Model extends Observable { private TANSpeicher liste = null; private ArrayList<String> speicher = new ArrayList<String>(); private File file = null; private XMLWriter writer = null; private TextReader reader = null; private XMLReader XMLreader = null; public Model(File file) { this.file = file; liste = new TANSpeicher(); writer = new XMLWriter(); reader = new TextReader(); XMLreader = new XMLReader(); } public ArrayList<String> getList() { return speicher; } public void speichereTAN(ArrayList<String> loadSpeicher) { liste.setTanSpeicher(loadSpeicher); this.speicher = loadSpeicher; } public void löscheTan() throws JAXBException { speicher.remove(0); schreibeXML(); } public void readXML() throws Exception { try { this.liste = XMLreader.leseTAN(file); this.speicher = liste.getTanSpeicher(); } catch (Exception e) { throw new Exception("Die Datei konnte nicht geladen werden!"); } } public void loadXML(File file) throws Exception { try { this.liste = XMLreader.leseTAN(file); this.speicher = liste.getTanSpeicher(); schreibeXML(); } catch (Exception e) { throw new Exception("Die Datei konnte nicht geladen werden!"); } } public void schreibeXML() throws JAXBException { writer.schreibeTans(liste, file); } public int getSize() { return speicher.size(); } public void readFile(File file) throws IOException, JAXBException { this.speicher = reader.readFile(file); liste.setTanSpeicher(speicher); schreibeXML(); } }
model revised and translated to english. supports now the observable interface
src/de/uniba/ppn/tananzeiger/model/Model.java
model revised and translated to english. supports now the observable interface
<ide><path>rc/de/uniba/ppn/tananzeiger/model/Model.java <ide> <ide> import javax.xml.bind.JAXBException; <ide> <add>import org.xml.sax.SAXException; <add> <ide> import de.uniba.ppn.tananzeiger.logik.TANSpeicher; <ide> import de.uniba.ppn.tananzeiger.logik.TextReader; <ide> import de.uniba.ppn.tananzeiger.xml.XMLReader; <ide> import de.uniba.ppn.tananzeiger.xml.XMLWriter; <ide> <ide> public class Model extends Observable { <del> private TANSpeicher liste = null; <del> private ArrayList<String> speicher = new ArrayList<String>(); <del> private File file = null; <del> private XMLWriter writer = null; <del> private TextReader reader = null; <del> private XMLReader XMLreader = null; <add> private TANSpeicher tanList; <add> private File file; <add> private XMLWriter writer; <add> private TextReader reader; <add> private XMLReader xmlReader; <ide> <ide> public Model(File file) { <ide> this.file = file; <del> liste = new TANSpeicher(); <add> tanList = new TANSpeicher(); <ide> writer = new XMLWriter(); <ide> reader = new TextReader(); <del> XMLreader = new XMLReader(); <add> xmlReader = new XMLReader(); <ide> } <ide> <ide> public ArrayList<String> getList() { <del> return speicher; <add> return tanList.getTanSpeicher(); <ide> } <ide> <del> public void speichereTAN(ArrayList<String> loadSpeicher) { <del> liste.setTanSpeicher(loadSpeicher); <del> this.speicher = loadSpeicher; <add> public void deleteTan() throws JAXBException { <add> getList().remove(0); <add> this.setChanged(); <add> this.notifyObservers(); <add> writeXml(); <ide> } <ide> <del> public void löscheTan() throws JAXBException { <del> speicher.remove(0); <del> schreibeXML(); <add> public void readXml() throws JAXBException, SAXException, IOException { <add> this.tanList = xmlReader.readTanXml(file); <add> this.setChanged(); <add> this.notifyObservers(); <ide> } <ide> <del> public void readXML() throws Exception { <del> try { <del> this.liste = XMLreader.leseTAN(file); <del> this.speicher = liste.getTanSpeicher(); <del> } catch (Exception e) { <del> throw new Exception("Die Datei konnte nicht geladen werden!"); <del> } <add> public void loadXML(File file) throws JAXBException, SAXException, <add> IOException { <add> readXml(); <add> writeXml(); <ide> } <ide> <del> public void loadXML(File file) throws Exception { <del> try { <del> this.liste = XMLreader.leseTAN(file); <del> this.speicher = liste.getTanSpeicher(); <del> schreibeXML(); <del> } catch (Exception e) { <del> throw new Exception("Die Datei konnte nicht geladen werden!"); <del> } <del> } <del> <del> public void schreibeXML() throws JAXBException { <del> writer.schreibeTans(liste, file); <add> public void writeXml() throws JAXBException { <add> writer.writeTanXml(tanList, file); <ide> } <ide> <ide> public int getSize() { <del> return speicher.size(); <add> return getList().size(); <ide> } <ide> <ide> public void readFile(File file) throws IOException, JAXBException { <del> this.speicher = reader.readFile(file); <del> liste.setTanSpeicher(speicher); <del> schreibeXML(); <add> tanList.setTanSpeicher(reader.readFile(file)); <add> this.setChanged(); <add> this.notifyObservers(); <add> writeXml(); <ide> } <ide> }
Java
mit
c86cc64a433a97715f8bc6eb18e9e491c79ca6cf
0
Daytron/WebCrawler,novoselrok/WebCrawler
package com.redditprog.webcrawler; import java.awt.Desktop; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * * @author Ryan * @author Rok */ public class Extractor { // Instance variables private final int num_pics; private final String sub; private final String dir; private final String type_of_links; private final String top_time; /** * The class constructor with the following parameters: * * @param sub SubReddit name * @param num Number of pictures to extract * @param dir Directory path to save photos * @param type_of_links Reddit's links categories * @param top_time Range of Date/Time for the subreddit * @param scanner Scanner object pass from Launcher */ public Extractor(String sub, int num, String dir, String type_of_links, String top_time) { this.sub = sub; this.num_pics = num; this.dir = dir; this.type_of_links = type_of_links; this.top_time = top_time; } public void beginExtract() { // set the full url of the user input subreddit URL urlJson; String json_url; int numDownloads = 0; ArrayList<String> gildedLinks = new ArrayList<String>(); try { if (type_of_links.equals("top")) { json_url = GlobalConfiguration.REDDIT_PRE_SUB_URL + this.sub + "/" + this.type_of_links + "/.json?sort=top&t=" + this.top_time; } else { json_url = GlobalConfiguration.REDDIT_PRE_SUB_URL + this.sub + "/" + this.type_of_links + "/.json"; } urlJson = new URL(json_url); } catch (MalformedURLException ex) { Logger.getLogger(Extractor.class.getName()).log(Level.SEVERE, null, ex); return; } JSONObject obj; JSONArray childArray; int count = GlobalConfiguration.TOTAL_ITEMS_PER_PAGE; String base_url = json_url; while (true) { String jsonString = this.extractJsonFromUrl(urlJson); try { obj = new JSONObject(jsonString); String after = obj.getJSONObject("data").getString("after"); if (after.equalsIgnoreCase("null") && json_url.contains("after")) { System.out.println(GlobalConfiguration.NO_MORE_PICS_FOUND); break; } childArray = obj.getJSONObject("data").getJSONArray("children"); for (int i = 0; i < childArray.length(); i++) { String urlString = this.getImageURL(childArray, i); URL url = new URL(urlString); boolean isContinue = false; if(this.type_of_links.equals("gilded")){ for (String gildedLink : gildedLinks) { if(urlString.equals(gildedLink)){ isContinue = true; break; } } gildedLinks.add(urlString); } if(isContinue){ continue; } if (urlString.contains("imgur")) { if (urlString.contains(GlobalConfiguration.IMGUR_ALBUM_URL_PATTERN)) { numDownloads = this.extractImgurAlbum(numDownloads, url); } else if (urlString.contains(GlobalConfiguration.IMGUR_SINGLE_URL_PATTERN)) { numDownloads = this.extractSingle(numDownloads, url, "single"); } else if (!isProperImageExtension(urlString)) { String id = urlString.substring(urlString.lastIndexOf("/") + 1); if (id.contains(",")) { String[] arrayOfIds = id.split(","); for (int j = 0; j < arrayOfIds.length; j++) { numDownloads = extractPicFromImgurAPI(arrayOfIds[j], numDownloads); } } else { numDownloads = extractPicFromImgurAPI(id, numDownloads); } } } else if (isProperImageExtension(urlString)) { numDownloads = this.extractSingle(numDownloads, url, "single"); } else { continue; } if (numDownloads >= this.num_pics) { break; } } if (type_of_links.equals("top")) { json_url = base_url + "&count=" + count + "&after=" + after; } else { json_url = base_url + "?count=" + count + "&after=" + after; } urlJson = new URL(json_url); count += GlobalConfiguration.TOTAL_ITEMS_PER_PAGE; if (count >= GlobalConfiguration.TOTAL_SEARCH_LIMIT && numDownloads < this.num_pics) { System.out.println(GlobalConfiguration.RESPONSE_RESULT_FAIL); break; } } catch (JSONException ex) { Logger.getLogger(Extractor.class.getName()).log(Level.SEVERE, null, ex); } catch (MalformedURLException ex) { Logger.getLogger(Extractor.class.getName()).log(Level.SEVERE, null, ex); } if (numDownloads >= this.num_pics) { break; } } if (numDownloads > 0) { this.askUserToOpenFolder(); } } private int extractPicFromImgurAPI(String id, int numDownloads) { try { String extractedJson = extractImgurAPIJson(id, "image"); // This might due to http error code connection // Error code results extractedJson to be empty // Skips extraction if (extractedJson.isEmpty()) { return numDownloads; } JSONObject object = new JSONObject(extractedJson); URL imageURL = new URL(object.getJSONObject("data").getString("link")); numDownloads = this.extractSingle(numDownloads, imageURL, "single"); } catch (JSONException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } return numDownloads; } private boolean isProperImageExtension(String image) { return image.endsWith("jpg") || image.endsWith("png") || image.endsWith("jpeg") || image.endsWith("gif"); } private String getImageURL(JSONArray childArray, int iteration) { String urlString = null; try { if (childArray.getJSONObject(iteration).getJSONObject("data").has("url")) { urlString = childArray.getJSONObject(iteration).getJSONObject("data").getString("url"); } else if (childArray.getJSONObject(iteration).getJSONObject("data").has("link_url")) { // Gilded range change the Data's url child to link_url urlString = childArray.getJSONObject(iteration).getJSONObject("data").getString("link_url"); } else { urlString = ""; } } catch (JSONException e) { e.printStackTrace(); } return urlString; } private int extractSingle(int numDownloads, URL url, String new_map) { String fileName = url.getFile(); // + 1 because this.dir already got "/" as the last character String destName; if (new_map.equals("single")) { destName = this.dir + fileName.substring(fileName.lastIndexOf("/") + 1); } else { destName = this.dir + new_map + File.separator + fileName.substring(fileName.lastIndexOf("/") + 1); } if (destName.contains("?")) { destName = destName.substring(0, destName.length() - 2); } if (imageIsDuplicate(destName, url)) { return numDownloads; } // Verify http connection of the link int httpResponseCode = this.getResponseCode(url); if (httpResponseCode != 200) { return numDownloads; } InputStream is; OutputStream os; try { is = url.openStream(); os = new FileOutputStream(destName); byte[] b = new byte[2048]; int length; while ((length = is.read(b)) != -1) { os.write(b, 0, length); } is.close(); os.close(); this.printDownloadCompleted(numDownloads, destName); } catch (FileNotFoundException ex) { Logger.getLogger(Extractor.class.getName()).log(Level.SEVERE, null, ex); // Invalid file save needs to terminate the application, // saving the next image will result to the same error // Value of 1 (argument) or any > 0 number means building error has occured System.exit(1); } catch (IOException exc) { Logger.getLogger(Extractor.class.getName()).log(Level.SEVERE, null, exc); return numDownloads; } return numDownloads + 1; } private int extractImgurAlbum(int numDownloads, URL url) { String[] urlSplit = url.toString().split("/"); String url_s = urlSplit[urlSplit.length - 1]; JSONObject obj; JSONArray images_array; String extractedJson = extractImgurAPIJson(url_s, "album"); // This might due to http error code connection // Skips album extraction if (extractedJson.isEmpty()) { return numDownloads; } try { obj = new JSONObject(extractedJson); images_array = obj.getJSONObject("data").getJSONArray("images"); String album_title = obj.getJSONObject("data").getString("title"); int album_num_pics = obj.getJSONObject("data").getInt("images_count"); System.out.println("=================="); System.out.println("An album detected! Title is: " + album_title + " Number of pics: " + album_num_pics); boolean isYes = InputValidator.getYesOrNoAnswer(GlobalConfiguration.QUESTION_ALBUM_DOWNLOAD); if (isYes) { new File(this.dir + url_s + File.separator).mkdir(); for (int i = 0; i < images_array.length(); i++) { numDownloads = extractSingle(numDownloads, new URL(images_array.getJSONObject(i).getString("link")), url_s); } } else { return numDownloads; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return numDownloads; } private void printDownloadCompleted(int num, String path) { System.out.println("=================="); System.out.println("Download #" + (num + 1) + " complete:"); System.out.println("Name of the file: " + path); } // Authorisation is done twice, one for checking http connection through HEAD, // the other authorisation for json extraction though GET // Because authorisation is needed for every api service private String extractImgurAPIJson(String id, String apiType) { StringBuilder jsonString = new StringBuilder(); URL jsonUrl; try { if (apiType.equals("album")) { jsonUrl = new URL(GlobalConfiguration.IMGUR_API_ALBUM_URL + id); } else if (apiType.equals("image")) { jsonUrl = new URL(GlobalConfiguration.IMGUR_API_IMAGE_URL + id); } else { return ""; } // Creates new HttpUTLConnection via jsonURL HttpURLConnection conn = (HttpURLConnection) jsonUrl.openConnection(); // Authorize connection first this.authorizeImgurConnection(conn); // Verify http connection of link // Some pictures are private in imgur int responseCode = this.getResponseCode(jsonUrl); if (responseCode != 200) { return ""; } BufferedReader bin = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = bin.readLine()) != null) { jsonString.append(line); } bin.close(); } catch (IOException e) { e.printStackTrace(); return ""; } return jsonString.toString(); } private int getResponseCode(URL jsonUrl) { int responseCode = 0; try { HttpURLConnection aConnection = (HttpURLConnection) jsonUrl.openConnection(); this.authorizeImgurConnection(aConnection); aConnection.setRequestMethod("HEAD"); responseCode = aConnection.getResponseCode(); } catch (IOException ex) { Logger.getLogger(Extractor.class.getName()).log(Level.SEVERE, null, ex); } return responseCode; } private void authorizeImgurConnection(HttpURLConnection aConnection) { boolean isAuthorised = false; try { aConnection.setRequestMethod("GET"); aConnection.setRequestProperty("Authorization", "Client-ID " + ClientIDClass.CLIENT_ID); isAuthorised = true; } catch (ProtocolException ex) { Logger.getLogger(Extractor.class.getName()).log(Level.SEVERE, null, ex); } // Exits application if client id for imgur api is invalid if (!isAuthorised) { System.out.println(GlobalConfiguration.INVALID_CLIENT_ID_IMGUR_AUTHORIZATION); System.exit(1); } } private String extractJsonFromUrl(URL url) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buffer = new StringBuffer(); int read; char[] chars = new char[1024]; while ((read = reader.read(chars)) != -1) { buffer.append(chars, 0, read); } reader.close(); return buffer.toString(); } catch (IOException ex) { Logger.getLogger(Extractor.class.getName()).log(Level.SEVERE, null, ex); } return ""; } private void openFolder() { try { Desktop.getDesktop().open(new File(this.dir)); } catch (IOException e) { System.out.println(GlobalConfiguration.INVALID_RESPONSE_INVALID_FOLDER); e.printStackTrace(); } } /** * Function that makes sure to avoid downloading identical files. If a * conflict is found asks the user to manually solve it. * * @param destName the file destination path * @param url image source * @return if the image download has to be skipped (true) */ private boolean imageIsDuplicate(String destName, URL url) { File file = new File(destName); boolean isImgurLink = url.toString().contains(GlobalConfiguration.IMGUR_CHECK_STRING); //The file exists and it's being downloaded from imgur so its ID is unique -> It's a duplicate. if (file.exists() && isImgurLink) { System.out.println("==================\n" + url + " ---> " + GlobalConfiguration.FILE_ALREADY_EXISTS_NOTIFICATION); return true; } else if (file.exists() && !isImgurLink) { //Asking user if he wants to overwrite. return !InputValidator.getYesOrNoAnswer("==================\n" + url + " --> " + GlobalConfiguration.FILE_ALREADY_EXISTS_DIALOG); } //File doesn't exist. return false; } private void askUserToOpenFolder() { System.out.println(GlobalConfiguration.RESPONSE_RESULT_SUCCESS); boolean isYes = InputValidator.getYesOrNoAnswer("Do you want to open " + this.dir + " in your File Explorer?"); if (isYes) { this.openFolder(); } } }
src/main/java/com/redditprog/webcrawler/Extractor.java
package com.redditprog.webcrawler; import java.awt.Desktop; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * * @author Ryan * @author Rok */ public class Extractor { // Instance variables private final int num_pics; private final String sub; private final String dir; private final String type_of_links; private final String top_time; /** * The class constructor with the following parameters: * * @param sub SubReddit name * @param num Number of pictures to extract * @param dir Directory path to save photos * @param type_of_links Reddit's links categories * @param top_time Range of Date/Time for the subreddit * @param scanner Scanner object pass from Launcher */ public Extractor(String sub, int num, String dir, String type_of_links, String top_time) { this.sub = sub; this.num_pics = num; this.dir = dir; this.type_of_links = type_of_links; this.top_time = top_time; } public void beginExtract() { // set the full url of the user input subreddit URL urlJson; String json_url; int numDownloads = 0; try { if (type_of_links.equals("top")) { json_url = GlobalConfiguration.REDDIT_PRE_SUB_URL + this.sub + "/" + this.type_of_links + "/.json?sort=top&t=" + this.top_time; } else { json_url = GlobalConfiguration.REDDIT_PRE_SUB_URL + this.sub + "/" + this.type_of_links + "/.json"; } urlJson = new URL(json_url); } catch (MalformedURLException ex) { Logger.getLogger(Extractor.class.getName()).log(Level.SEVERE, null, ex); return; } JSONObject obj; JSONArray childArray; int count = GlobalConfiguration.TOTAL_ITEMS_PER_PAGE; String base_url = json_url; while (true) { String jsonString = this.extractJsonFromUrl(urlJson); try { obj = new JSONObject(jsonString); String after = obj.getJSONObject("data").getString("after"); if (after.equalsIgnoreCase("null") && json_url.contains("after")) { System.out.println(GlobalConfiguration.NO_MORE_PICS_FOUND); break; } childArray = obj.getJSONObject("data").getJSONArray("children"); for (int i = 0; i < childArray.length(); i++) { String urlString = this.getImageURL(childArray, i); URL url = new URL(urlString); if (urlString.contains("imgur")) { if (urlString.contains(GlobalConfiguration.IMGUR_ALBUM_URL_PATTERN)) { numDownloads = this.extractImgurAlbum(numDownloads, url); } else if (urlString.contains(GlobalConfiguration.IMGUR_SINGLE_URL_PATTERN)) { numDownloads = this.extractSingle(numDownloads, url, "single"); } else if (!isProperImageExtension(urlString)) { String id = urlString.substring(urlString.lastIndexOf("/") + 1); if (id.contains(",")) { String[] arrayOfIds = id.split(","); for (int j = 0; j < arrayOfIds.length; j++) { numDownloads = extractPicFromImgurAPI(arrayOfIds[j], numDownloads); } } else { numDownloads = extractPicFromImgurAPI(id, numDownloads); } } } else if (isProperImageExtension(urlString)) { numDownloads = this.extractSingle(numDownloads, url, "single"); } else { continue; } if (numDownloads >= this.num_pics) { break; } } if (type_of_links.equals("top")) { json_url = base_url + "&count=" + count + "&after=" + after; } else { json_url = base_url + "?count=" + count + "&after=" + after; } urlJson = new URL(json_url); count += GlobalConfiguration.TOTAL_ITEMS_PER_PAGE; if (count >= GlobalConfiguration.TOTAL_SEARCH_LIMIT && numDownloads < this.num_pics) { System.out.println(GlobalConfiguration.RESPONSE_RESULT_FAIL); break; } } catch (JSONException ex) { Logger.getLogger(Extractor.class.getName()).log(Level.SEVERE, null, ex); } catch (MalformedURLException ex) { Logger.getLogger(Extractor.class.getName()).log(Level.SEVERE, null, ex); } if (numDownloads >= this.num_pics) { break; } } if (numDownloads > 0) { this.askUserToOpenFolder(); } } private int extractPicFromImgurAPI(String id, int numDownloads) { try { String extractedJson = extractImgurAPIJson(id, "image"); // This might due to http error code connection // Error code results extractedJson to be empty // Skips extraction if (extractedJson.isEmpty()) { return numDownloads; } JSONObject object = new JSONObject(extractedJson); URL imageURL = new URL(object.getJSONObject("data").getString("link")); numDownloads = this.extractSingle(numDownloads, imageURL, "single"); } catch (JSONException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } return numDownloads; } private boolean isProperImageExtension(String image) { return image.endsWith("jpg") || image.endsWith("png") || image.endsWith("jpeg") || image.endsWith("gif"); } private String getImageURL(JSONArray childArray, int iteration) { String urlString = null; try { if (childArray.getJSONObject(iteration).getJSONObject("data").has("url")) { urlString = childArray.getJSONObject(iteration).getJSONObject("data").getString("url"); } else if (childArray.getJSONObject(iteration).getJSONObject("data").has("link_url")) { // Gilded range change the Data's url child to link_url urlString = childArray.getJSONObject(iteration).getJSONObject("data").getString("link_url"); } else { urlString = ""; } } catch (JSONException e) { e.printStackTrace(); } return urlString; } private int extractSingle(int numDownloads, URL url, String new_map) { String fileName = url.getFile(); // + 1 because this.dir already got "/" as the last character String destName; if (new_map.equals("single")) { destName = this.dir + fileName.substring(fileName.lastIndexOf("/") + 1); } else { destName = this.dir + new_map + File.separator + fileName.substring(fileName.lastIndexOf("/") + 1); } if (destName.contains("?")) { destName = destName.substring(0, destName.length() - 2); } if (imageIsDuplicate(destName, url)) { return numDownloads; } // Verify http connection of the link int httpResponseCode = this.getResponseCode(url); if (httpResponseCode != 200) { return numDownloads; } InputStream is; OutputStream os; try { is = url.openStream(); os = new FileOutputStream(destName); byte[] b = new byte[2048]; int length; while ((length = is.read(b)) != -1) { os.write(b, 0, length); } is.close(); os.close(); this.printDownloadCompleted(numDownloads, destName); } catch (FileNotFoundException ex) { Logger.getLogger(Extractor.class.getName()).log(Level.SEVERE, null, ex); // Invalid file save needs to terminate the application, // saving the next image will result to the same error // Value of 1 (argument) or any > 0 number means building error has occured System.exit(1); } catch (IOException exc) { Logger.getLogger(Extractor.class.getName()).log(Level.SEVERE, null, exc); return numDownloads; } return numDownloads + 1; } private int extractImgurAlbum(int numDownloads, URL url) { String[] urlSplit = url.toString().split("/"); String url_s = urlSplit[urlSplit.length - 1]; JSONObject obj; JSONArray images_array; String extractedJson = extractImgurAPIJson(url_s, "album"); // This might due to http error code connection // Skips album extraction if (extractedJson.isEmpty()) { return numDownloads; } try { obj = new JSONObject(extractedJson); images_array = obj.getJSONObject("data").getJSONArray("images"); String album_title = obj.getJSONObject("data").getString("title"); int album_num_pics = obj.getJSONObject("data").getInt("images_count"); System.out.println("=================="); System.out.println("An album detected! Title is: " + album_title + " Number of pics: " + album_num_pics); boolean isYes = InputValidator.getYesOrNoAnswer(GlobalConfiguration.QUESTION_ALBUM_DOWNLOAD); if (isYes) { new File(this.dir + url_s + File.separator).mkdir(); for (int i = 0; i < images_array.length(); i++) { numDownloads = extractSingle(numDownloads, new URL(images_array.getJSONObject(i).getString("link")), url_s); } } else { return numDownloads; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return numDownloads; } private void printDownloadCompleted(int num, String path) { System.out.println("=================="); System.out.println("Download #" + (num + 1) + " complete:"); System.out.println("Name of the file: " + path); } // Authorisation is done twice, one for checking http connection through HEAD, // the other authorisation for json extraction though GET // Because authorisation is needed for every api service private String extractImgurAPIJson(String id, String apiType) { StringBuilder jsonString = new StringBuilder(); URL jsonUrl; try { if (apiType.equals("album")) { jsonUrl = new URL(GlobalConfiguration.IMGUR_API_ALBUM_URL + id); } else if (apiType.equals("image")) { jsonUrl = new URL(GlobalConfiguration.IMGUR_API_IMAGE_URL + id); } else { return ""; } // Creates new HttpUTLConnection via jsonURL HttpURLConnection conn = (HttpURLConnection) jsonUrl.openConnection(); // Authorize connection first this.authorizeImgurConnection(conn); // Verify http connection of link // Some pictures are private in imgur int responseCode = this.getResponseCode(jsonUrl); if (responseCode != 200) { return ""; } BufferedReader bin = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = bin.readLine()) != null) { jsonString.append(line); } bin.close(); } catch (IOException e) { e.printStackTrace(); return ""; } return jsonString.toString(); } private int getResponseCode(URL jsonUrl) { int responseCode = 0; try { HttpURLConnection aConnection = (HttpURLConnection) jsonUrl.openConnection(); this.authorizeImgurConnection(aConnection); aConnection.setRequestMethod("HEAD"); responseCode = aConnection.getResponseCode(); } catch (IOException ex) { Logger.getLogger(Extractor.class.getName()).log(Level.SEVERE, null, ex); } return responseCode; } private void authorizeImgurConnection(HttpURLConnection aConnection) { boolean isAuthorised = false; try { aConnection.setRequestMethod("GET"); aConnection.setRequestProperty("Authorization", "Client-ID " + ClientIDClass.CLIENT_ID); isAuthorised = true; } catch (ProtocolException ex) { Logger.getLogger(Extractor.class.getName()).log(Level.SEVERE, null, ex); } // Exits application if client id for imgur api is invalid if (!isAuthorised) { System.out.println(GlobalConfiguration.INVALID_CLIENT_ID_IMGUR_AUTHORIZATION); System.exit(1); } } private String extractJsonFromUrl(URL url) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buffer = new StringBuffer(); int read; char[] chars = new char[1024]; while ((read = reader.read(chars)) != -1) { buffer.append(chars, 0, read); } reader.close(); return buffer.toString(); } catch (IOException ex) { Logger.getLogger(Extractor.class.getName()).log(Level.SEVERE, null, ex); } return ""; } private void openFolder() { try { Desktop.getDesktop().open(new File(this.dir)); } catch (IOException e) { System.out.println(GlobalConfiguration.INVALID_RESPONSE_INVALID_FOLDER); e.printStackTrace(); } } /** * Function that makes sure to avoid downloading identical files. If a * conflict is found asks the user to manually solve it. * * @param destName the file destination path * @param url image source * @return if the image download has to be skipped (true) */ private boolean imageIsDuplicate(String destName, URL url) { File file = new File(destName); boolean isImgurLink = url.toString().contains(GlobalConfiguration.IMGUR_CHECK_STRING); //The file exists and it's being downloaded from imgur so its ID is unique -> It's a duplicate. if (file.exists() && isImgurLink) { System.out.println("==================\n" + url + " ---> " + GlobalConfiguration.FILE_ALREADY_EXISTS_NOTIFICATION); return true; } else if (file.exists() && !isImgurLink) { //Asking user if he wants to overwrite. return !InputValidator.getYesOrNoAnswer("==================\n" + url + " --> " + GlobalConfiguration.FILE_ALREADY_EXISTS_DIALOG); } //File doesn't exist. return false; } private void askUserToOpenFolder() { System.out.println(GlobalConfiguration.RESPONSE_RESULT_SUCCESS); boolean isYes = InputValidator.getYesOrNoAnswer("Do you want to open " + this.dir + " in your File Explorer?"); if (isYes) { this.openFolder(); } } }
fix issue #36
src/main/java/com/redditprog/webcrawler/Extractor.java
fix issue #36
<ide><path>rc/main/java/com/redditprog/webcrawler/Extractor.java <ide> import java.net.MalformedURLException; <ide> import java.net.ProtocolException; <ide> import java.net.URL; <add>import java.util.ArrayList; <ide> import java.util.logging.Level; <ide> import java.util.logging.Logger; <ide> <ide> URL urlJson; <ide> String json_url; <ide> int numDownloads = 0; <add> ArrayList<String> gildedLinks = new ArrayList<String>(); <ide> try { <ide> if (type_of_links.equals("top")) { <ide> json_url = GlobalConfiguration.REDDIT_PRE_SUB_URL + this.sub + "/" <ide> while (true) { <ide> <ide> String jsonString = this.extractJsonFromUrl(urlJson); <del> <add> <ide> try { <ide> obj = new JSONObject(jsonString); <ide> String after = obj.getJSONObject("data").getString("after"); <ide> for (int i = 0; i < childArray.length(); i++) { <ide> String urlString = this.getImageURL(childArray, i); <ide> URL url = new URL(urlString); <del> <add> boolean isContinue = false; <add> if(this.type_of_links.equals("gilded")){ <add> for (String gildedLink : gildedLinks) { <add> if(urlString.equals(gildedLink)){ <add> isContinue = true; <add> break; <add> } <add> } <add> gildedLinks.add(urlString); <add> } <add> if(isContinue){ <add> continue; <add> } <ide> if (urlString.contains("imgur")) { <ide> if (urlString.contains(GlobalConfiguration.IMGUR_ALBUM_URL_PATTERN)) { <ide> numDownloads = this.extractImgurAlbum(numDownloads, url); <ide> } else if (urlString.contains(GlobalConfiguration.IMGUR_SINGLE_URL_PATTERN)) { <ide> numDownloads = this.extractSingle(numDownloads, url, "single"); <ide> } else if (!isProperImageExtension(urlString)) { <del> String id = urlString.substring(urlString.lastIndexOf("/") + 1); <del> if (id.contains(",")) { <del> String[] arrayOfIds = id.split(","); <del> for (int j = 0; j < arrayOfIds.length; j++) { <del> numDownloads = extractPicFromImgurAPI(arrayOfIds[j], numDownloads); <add> String id = urlString.substring(urlString.lastIndexOf("/") + 1); <add> if (id.contains(",")) { <add> String[] arrayOfIds = id.split(","); <add> for (int j = 0; j < arrayOfIds.length; j++) { <add> numDownloads = extractPicFromImgurAPI(arrayOfIds[j], numDownloads); <add> } <add> } else { <add> numDownloads = extractPicFromImgurAPI(id, numDownloads); <add> } <ide> } <del> } else { <del> numDownloads = extractPicFromImgurAPI(id, numDownloads); <del> } <del> } <del> <ide> } else if (isProperImageExtension(urlString)) { <ide> numDownloads = this.extractSingle(numDownloads, url, "single"); <ide> } else {
Java
apache-2.0
d890abf6f7bd6571dda054c20a6cc056ca81fa14
0
3dcitydb/importer-exporter,3dcitydb/importer-exporter,3dcitydb/importer-exporter
/* * 3D City Database - The Open Source CityGML Database * http://www.3dcitydb.org/ * * Copyright 2013 - 2017 * Chair of Geoinformatics * Technical University of Munich, Germany * https://www.gis.bgu.tum.de/ * * The 3D City Database is jointly developed with the following * cooperation partners: * * virtualcitySYSTEMS GmbH, Berlin <http://www.virtualcitysystems.de/> * M.O.S.S. Computer Grafik Systeme GmbH, Taufkirchen <http://www.moss.de/> * * 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. */ package org.citydb.citygml.importer.database.content; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; import org.citydb.citygml.common.database.xlink.DBXlinkSurfaceGeometry; import org.citydb.citygml.importer.CityGMLImportException; import org.citydb.citygml.importer.util.AttributeValueJoiner; import org.citydb.config.Config; import org.citydb.database.schema.TableEnum; import org.citydb.database.schema.mapping.FeatureType; import org.citygml4j.model.citygml.vegetation.PlantCover; import org.citygml4j.model.gml.basicTypes.Code; import org.citygml4j.model.gml.geometry.aggregates.MultiSolidProperty; import org.citygml4j.model.gml.geometry.aggregates.MultiSurfaceProperty; public class DBPlantCover implements DBImporter { private final CityGMLImportManager importer; private PreparedStatement psPlantCover; private DBCityObject cityObjectImporter; private DBSurfaceGeometry surfaceGeometryImporter; private AttributeValueJoiner valueJoiner; private boolean hasObjectClassIdColumn; private int batchCounter; public DBPlantCover(Connection batchConn, Config config, CityGMLImportManager importer) throws CityGMLImportException, SQLException { this.importer = importer; String schema = importer.getDatabaseAdapter().getConnectionDetails().getSchema(); hasObjectClassIdColumn = importer.getDatabaseAdapter().getConnectionMetaData().getCityDBVersion().compareTo(4, 0, 0) >= 0; String stmt = "insert into " + schema + ".plant_cover (id, class, class_codespace, function, function_codespace, usage, usage_codespace, average_height, average_height_unit, " + "lod1_multi_surface_id, lod2_multi_surface_id, lod3_multi_surface_id, lod4_multi_surface_id, " + "lod1_multi_solid_id, lod2_multi_solid_id, lod3_multi_solid_id, lod4_multi_solid_id" + (hasObjectClassIdColumn ? ", objectclass_id) " : ") ") + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?" + (hasObjectClassIdColumn ? ", ?)" : ")"); psPlantCover = batchConn.prepareStatement(stmt); surfaceGeometryImporter = importer.getImporter(DBSurfaceGeometry.class); cityObjectImporter = importer.getImporter(DBCityObject.class); valueJoiner = importer.getAttributeValueJoiner(); } protected long doImport(PlantCover plantCover) throws CityGMLImportException, SQLException { FeatureType featureType = importer.getFeatureType(plantCover); if (featureType == null) throw new SQLException("Failed to retrieve feature type."); // import city object information long plantCoverId = cityObjectImporter.doImport(plantCover, featureType); // import plant cover information // primary id psPlantCover.setLong(1, plantCoverId); // veg:class if (plantCover.isSetClazz() && plantCover.getClazz().isSetValue()) { psPlantCover.setString(2, plantCover.getClazz().getValue()); psPlantCover.setString(3, plantCover.getClazz().getCodeSpace()); } else { psPlantCover.setNull(2, Types.VARCHAR); psPlantCover.setNull(3, Types.VARCHAR); } // veg:function if (plantCover.isSetFunction()) { valueJoiner.join(plantCover.getFunction(), Code::getValue, Code::getCodeSpace); psPlantCover.setString(4, valueJoiner.result(0)); psPlantCover.setString(5, valueJoiner.result(1)); } else { psPlantCover.setNull(4, Types.VARCHAR); psPlantCover.setNull(5, Types.VARCHAR); } // veg:usage if (plantCover.isSetUsage()) { valueJoiner.join(plantCover.getUsage(), Code::getValue, Code::getCodeSpace); psPlantCover.setString(6, valueJoiner.result(0)); psPlantCover.setString(7, valueJoiner.result(1)); } else { psPlantCover.setNull(6, Types.VARCHAR); psPlantCover.setNull(7, Types.VARCHAR); } // veg:averageHeight if (plantCover.isSetAverageHeight() && plantCover.getAverageHeight().isSetValue()) { psPlantCover.setDouble(8, plantCover.getAverageHeight().getValue()); psPlantCover.setString(9, plantCover.getAverageHeight().getUom()); } else { psPlantCover.setNull(8, Types.NULL); psPlantCover.setNull(9, Types.VARCHAR); } // veg:lodXMultiSurface for (int i = 0; i < 4; i++) { MultiSurfaceProperty multiSurfaceProperty = null; long multiGeometryId = 0; switch (i) { case 0: multiSurfaceProperty = plantCover.getLod1MultiSurface(); break; case 1: multiSurfaceProperty = plantCover.getLod2MultiSurface(); break; case 2: multiSurfaceProperty = plantCover.getLod3MultiSurface(); break; case 3: multiSurfaceProperty = plantCover.getLod4MultiSurface(); break; } if (multiSurfaceProperty != null) { if (multiSurfaceProperty.isSetMultiSurface()) { multiGeometryId = surfaceGeometryImporter.doImport(multiSurfaceProperty.getMultiSurface(), plantCoverId); multiSurfaceProperty.unsetMultiSurface(); } else { String href = multiSurfaceProperty.getHref(); if (href != null && href.length() != 0) { importer.propagateXlink(new DBXlinkSurfaceGeometry( featureType.getObjectClassId(), plantCoverId, href, "LOD" + (i + 1) + "_MULTI_SURFACE_ID")); } } } if (multiGeometryId != 0) psPlantCover.setLong(10 + i, multiGeometryId); else psPlantCover.setNull(10 + i, Types.NULL); } // veg:lodXMultiSolid for (int i = 0; i < 4; i++) { MultiSolidProperty multiSolidProperty = null; long solidGeometryId = 0; switch (i) { case 0: multiSolidProperty = plantCover.getLod1MultiSolid(); break; case 1: multiSolidProperty = plantCover.getLod2MultiSolid(); break; case 2: multiSolidProperty = plantCover.getLod3MultiSolid(); break; case 3: multiSolidProperty = plantCover.getLod4MultiSolid(); break; } if (multiSolidProperty != null) { if (multiSolidProperty.isSetMultiSolid()) { solidGeometryId = surfaceGeometryImporter.doImport(multiSolidProperty.getMultiSolid(), plantCoverId); multiSolidProperty.unsetMultiSolid(); } else { String href = multiSolidProperty.getHref(); if (href != null && href.length() != 0) { importer.propagateXlink(new DBXlinkSurfaceGeometry( featureType.getObjectClassId(), plantCoverId, href, "LOD" + (i + 1) + "_MULTI_SOLID_ID")); } } } if (solidGeometryId != 0) psPlantCover.setLong(14 + i, solidGeometryId); else psPlantCover.setNull(14 + i, Types.NULL); } // objectclass id if (hasObjectClassIdColumn) psPlantCover.setLong(18, featureType.getObjectClassId()); psPlantCover.addBatch(); if (++batchCounter == importer.getDatabaseAdapter().getMaxBatchSize()) importer.executeBatch(TableEnum.PLANT_COVER); // ADE-specific extensions if (importer.hasADESupport()) importer.delegateToADEImporter(plantCover, plantCoverId, featureType); return plantCoverId; } @Override public void executeBatch() throws CityGMLImportException, SQLException { if (batchCounter > 0) { psPlantCover.executeBatch(); batchCounter = 0; } } @Override public void close() throws CityGMLImportException, SQLException { psPlantCover.close(); } }
impexp-core/src/main/java/org/citydb/citygml/importer/database/content/DBPlantCover.java
/* * 3D City Database - The Open Source CityGML Database * http://www.3dcitydb.org/ * * Copyright 2013 - 2017 * Chair of Geoinformatics * Technical University of Munich, Germany * https://www.gis.bgu.tum.de/ * * The 3D City Database is jointly developed with the following * cooperation partners: * * virtualcitySYSTEMS GmbH, Berlin <http://www.virtualcitysystems.de/> * M.O.S.S. Computer Grafik Systeme GmbH, Taufkirchen <http://www.moss.de/> * * 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. */ package org.citydb.citygml.importer.database.content; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; import org.citydb.citygml.common.database.xlink.DBXlinkSurfaceGeometry; import org.citydb.citygml.importer.CityGMLImportException; import org.citydb.citygml.importer.util.AttributeValueJoiner; import org.citydb.config.Config; import org.citydb.database.schema.TableEnum; import org.citydb.database.schema.mapping.FeatureType; import org.citygml4j.model.citygml.vegetation.PlantCover; import org.citygml4j.model.gml.basicTypes.Code; import org.citygml4j.model.gml.geometry.aggregates.MultiSolidProperty; import org.citygml4j.model.gml.geometry.aggregates.MultiSurfaceProperty; public class DBPlantCover implements DBImporter { private final CityGMLImportManager importer; private PreparedStatement psPlantCover; private DBCityObject cityObjectImporter; private DBSurfaceGeometry surfaceGeometryImporter; private AttributeValueJoiner valueJoiner; private boolean hasObjectClassIdColumn; private int batchCounter; public DBPlantCover(Connection batchConn, Config config, CityGMLImportManager importer) throws CityGMLImportException, SQLException { this.importer = importer; String schema = importer.getDatabaseAdapter().getConnectionDetails().getSchema(); hasObjectClassIdColumn = importer.getDatabaseAdapter().getConnectionMetaData().getCityDBVersion().compareTo(4, 0, 0) >= 0; String stmt = "insert into " + schema + ".plant_cover (id, class, class_codespace, function, function_codespace, usage, usage_codespace, average_height, average_height_unit, " + "lod1_multi_surface_id, lod2_multi_surface_id, lod3_multi_surface_id, lod4_multi_surface_id, " + "lod1_multi_solid_id, lod2_multi_solid_id, lod3_multi_solid_id, lod4_multi_solid_id" + (hasObjectClassIdColumn ? ", objectclass_id) " : ") ") + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?" + (hasObjectClassIdColumn ? ", ?)" : ")"); psPlantCover = batchConn.prepareStatement(stmt); surfaceGeometryImporter = importer.getImporter(DBSurfaceGeometry.class); cityObjectImporter = importer.getImporter(DBCityObject.class); valueJoiner = importer.getAttributeValueJoiner(); } protected long doImport(PlantCover plantCover) throws CityGMLImportException, SQLException { FeatureType featureType = importer.getFeatureType(plantCover); if (featureType == null) throw new SQLException("Failed to retrieve feature type."); // import city object information long plantCoverId = cityObjectImporter.doImport(plantCover, featureType); // import plant cover information // primary id psPlantCover.setLong(1, plantCoverId); // veg:class if (plantCover.isSetClazz() && plantCover.getClazz().isSetValue()) { psPlantCover.setString(2, plantCover.getClazz().getValue()); psPlantCover.setString(3, plantCover.getClazz().getCodeSpace()); } else { psPlantCover.setNull(2, Types.VARCHAR); psPlantCover.setNull(3, Types.VARCHAR); } // veg:function if (plantCover.isSetFunction()) { valueJoiner.join(plantCover.getFunction(), Code::getValue, Code::getCodeSpace); psPlantCover.setString(4, valueJoiner.result(0)); psPlantCover.setString(5, valueJoiner.result(1)); } else { psPlantCover.setNull(4, Types.VARCHAR); psPlantCover.setNull(5, Types.VARCHAR); } // veg:usage if (plantCover.isSetUsage()) { valueJoiner.join(plantCover.getUsage(), Code::getValue, Code::getCodeSpace); psPlantCover.setString(6, valueJoiner.result(0)); psPlantCover.setString(7, valueJoiner.result(1)); } else { psPlantCover.setNull(6, Types.VARCHAR); psPlantCover.setNull(7, Types.VARCHAR); } // veg:averageHeight if (plantCover.isSetAverageHeight() && plantCover.getAverageHeight().isSetValue()) { psPlantCover.setDouble(8, plantCover.getAverageHeight().getValue()); psPlantCover.setString(9, plantCover.getAverageHeight().getUom()); } else { psPlantCover.setNull(8, Types.NULL); psPlantCover.setNull(9, Types.VARCHAR); } // veg:lodXMultiSurface for (int i = 0; i < 4; i++) { MultiSurfaceProperty multiSurfaceProperty = null; long multiGeometryId = 0; switch (i) { case 0: multiSurfaceProperty = plantCover.getLod1MultiSurface(); break; case 1: multiSurfaceProperty = plantCover.getLod2MultiSurface(); break; case 2: multiSurfaceProperty = plantCover.getLod3MultiSurface(); break; case 3: multiSurfaceProperty = plantCover.getLod4MultiSurface(); break; } if (multiSurfaceProperty != null) { if (multiSurfaceProperty.isSetMultiSurface()) { multiGeometryId = surfaceGeometryImporter.doImport(multiSurfaceProperty.getMultiSurface(), plantCoverId); multiSurfaceProperty.unsetMultiSurface(); } else { String href = multiSurfaceProperty.getHref(); if (href != null && href.length() != 0) { importer.propagateXlink(new DBXlinkSurfaceGeometry( featureType.getObjectClassId(), plantCoverId, href, "LOD" + (i + 1) + "_MULTI_SURFACE_ID")); } } } if (multiGeometryId != 0) psPlantCover.setLong(10 + i, multiGeometryId); else psPlantCover.setNull(10 + i, Types.NULL); } // veg:lodXMultiSolid for (int i = 0; i < 4; i++) { MultiSolidProperty multiSolidProperty = null; long solidGeometryId = 0; switch (i) { case 0: multiSolidProperty = plantCover.getLod1MultiSolid(); break; case 1: multiSolidProperty = plantCover.getLod2MultiSolid(); break; case 2: multiSolidProperty = plantCover.getLod3MultiSolid(); break; case 3: multiSolidProperty = plantCover.getLod4MultiSolid(); break; } if (multiSolidProperty != null) { if (multiSolidProperty.isSetMultiSolid()) { solidGeometryId = surfaceGeometryImporter.doImport(multiSolidProperty.getMultiSolid(), plantCoverId); multiSolidProperty.unsetMultiSolid(); } else { String href = multiSolidProperty.getHref(); if (href != null && href.length() != 0) { importer.propagateXlink(new DBXlinkSurfaceGeometry( featureType.getObjectClassId(), plantCoverId, href, "LOD" + (i + 1) + "_MULTI_SOLID_ID")); } } } if (solidGeometryId != 0) psPlantCover.setLong(14 + i, solidGeometryId); else psPlantCover.setNull(14 + i, Types.NULL); } // objectclass id if (hasObjectClassIdColumn) psPlantCover.setLong(18, featureType.getObjectClassId()); psPlantCover.addBatch(); if (++batchCounter == importer.getDatabaseAdapter().getMaxBatchSize()) importer.executeBatch(TableEnum.PLANT_COVER); // ADE-specific extensions if (importer.hasADESupport()) importer.delegateToADEImporter(plantCover, plantCoverId, featureType); return plantCoverId; } @Override public void executeBatch() throws CityGMLImportException, SQLException { if (batchCounter > 0) { psPlantCover.executeBatch(); batchCounter = 0; } } @Override public void close() throws CityGMLImportException, SQLException { psPlantCover.close(); } }
fixed bug in PlantCover importer
impexp-core/src/main/java/org/citydb/citygml/importer/database/content/DBPlantCover.java
fixed bug in PlantCover importer
<ide><path>mpexp-core/src/main/java/org/citydb/citygml/importer/database/content/DBPlantCover.java <ide> "lod1_multi_surface_id, lod2_multi_surface_id, lod3_multi_surface_id, lod4_multi_surface_id, " + <ide> "lod1_multi_solid_id, lod2_multi_solid_id, lod3_multi_solid_id, lod4_multi_solid_id" + <ide> (hasObjectClassIdColumn ? ", objectclass_id) " : ") ") + <del> "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?" + <add> "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?" + <ide> (hasObjectClassIdColumn ? ", ?)" : ")"); <ide> psPlantCover = batchConn.prepareStatement(stmt); <ide>
Java
apache-2.0
a11bc6a10647f0d74d303a65eeea9ab36270f632
0
gnuhub/intellij-community,caot/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,fnouama/intellij-community,fnouama/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,kool79/intellij-community,allotria/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,consulo/consulo,amith01994/intellij-community,apixandru/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,dslomov/intellij-community,fitermay/intellij-community,holmes/intellij-community,supersven/intellij-community,izonder/intellij-community,xfournet/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,vladmm/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,amith01994/intellij-community,apixandru/intellij-community,FHannes/intellij-community,FHannes/intellij-community,caot/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,caot/intellij-community,samthor/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,adedayo/intellij-community,slisson/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,hurricup/intellij-community,kdwink/intellij-community,kool79/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,supersven/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,fnouama/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,kdwink/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,retomerz/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,signed/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,signed/intellij-community,kdwink/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,adedayo/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,fnouama/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,asedunov/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,samthor/intellij-community,signed/intellij-community,asedunov/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,consulo/consulo,slisson/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,caot/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,izonder/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,da1z/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,robovm/robovm-studio,clumsy/intellij-community,pwoodworth/intellij-community,signed/intellij-community,slisson/intellij-community,nicolargo/intellij-community,allotria/intellij-community,slisson/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,muntasirsyed/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,ernestp/consulo,lucafavatella/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,robovm/robovm-studio,adedayo/intellij-community,da1z/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,diorcety/intellij-community,slisson/intellij-community,blademainer/intellij-community,consulo/consulo,signed/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,dslomov/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,caot/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,consulo/consulo,vvv1559/intellij-community,signed/intellij-community,consulo/consulo,ivan-fedorov/intellij-community,suncycheng/intellij-community,slisson/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,FHannes/intellij-community,izonder/intellij-community,holmes/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,robovm/robovm-studio,xfournet/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,clumsy/intellij-community,dslomov/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,semonte/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,caot/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,ernestp/consulo,fnouama/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,supersven/intellij-community,blademainer/intellij-community,blademainer/intellij-community,signed/intellij-community,izonder/intellij-community,diorcety/intellij-community,caot/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,jagguli/intellij-community,ernestp/consulo,robovm/robovm-studio,apixandru/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,asedunov/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,samthor/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,semonte/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,holmes/intellij-community,semonte/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,da1z/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,consulo/consulo,izonder/intellij-community,petteyg/intellij-community,retomerz/intellij-community,fnouama/intellij-community,FHannes/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,da1z/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,adedayo/intellij-community,supersven/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,holmes/intellij-community,diorcety/intellij-community,semonte/intellij-community,semonte/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,kool79/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,clumsy/intellij-community,signed/intellij-community,supersven/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,ernestp/consulo,signed/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,kdwink/intellij-community,xfournet/intellij-community,adedayo/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,holmes/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,hurricup/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,slisson/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,allotria/intellij-community,ibinti/intellij-community,FHannes/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,ernestp/consulo,clumsy/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,allotria/intellij-community,ryano144/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,supersven/intellij-community,hurricup/intellij-community,da1z/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,da1z/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,fnouama/intellij-community,dslomov/intellij-community,retomerz/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,xfournet/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,holmes/intellij-community,izonder/intellij-community,retomerz/intellij-community,holmes/intellij-community,samthor/intellij-community,nicolargo/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,amith01994/intellij-community,kdwink/intellij-community,signed/intellij-community,suncycheng/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,ryano144/intellij-community,signed/intellij-community,kdwink/intellij-community,blademainer/intellij-community,dslomov/intellij-community,ryano144/intellij-community,kool79/intellij-community,apixandru/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,caot/intellij-community,semonte/intellij-community,blademainer/intellij-community,allotria/intellij-community,ibinti/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,petteyg/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,asedunov/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,samthor/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,allotria/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,FHannes/intellij-community,blademainer/intellij-community,da1z/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,izonder/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,kool79/intellij-community,vladmm/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,allotria/intellij-community,blademainer/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,xfournet/intellij-community
/* * Copyright 2000-2012 JetBrains s.r.o. * * 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. */ package com.intellij.ui.components; import com.intellij.util.IconUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; /** * @author Konstantin Bulenkov */ public class JBPanel extends JPanel { @Nullable private Icon myBackgroundImage; @Nullable private Icon myCenterImage; public JBPanel(LayoutManager layout, boolean isDoubleBuffered) { super(layout, isDoubleBuffered); } public JBPanel(LayoutManager layout) { super(layout); } public JBPanel(boolean isDoubleBuffered) { super(isDoubleBuffered); } public JBPanel() { super(); } @Nullable public Icon getBackgroundImage() { return myBackgroundImage; } public void setBackgroundImage(@Nullable Icon backgroundImage) { myBackgroundImage = backgroundImage; } @Nullable public Icon getCenterImage() { return myCenterImage; } public void setCenterImage(@Nullable Icon centerImage) { myCenterImage = centerImage; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (myBackgroundImage != null) { final int w = myBackgroundImage.getIconWidth(); final int h = myBackgroundImage.getIconHeight(); int x = 0; int y = 0; while (w > 0 && x < getWidth()) { while (h > 0 && y < getHeight()) { myBackgroundImage.paintIcon(this, g, x, y); y+=h; } y=0; x+=w; } } if (myCenterImage != null) { IconUtil.paintInCenterOf(this, g, myCenterImage); } } }
platform/platform-api/src/com/intellij/ui/components/JBPanel.java
/* * Copyright 2000-2012 JetBrains s.r.o. * * 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. */ package com.intellij.ui.components; import com.intellij.util.IconUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; /** * @author Konstantin Bulenkov */ public class JBPanel extends JPanel { @Nullable private Icon myBackgroundImage; @Nullable private Icon myCenterImage; public JBPanel(LayoutManager layout, boolean isDoubleBuffered) { super(layout, isDoubleBuffered); } public JBPanel(LayoutManager layout) { super(layout); } public JBPanel(boolean isDoubleBuffered) { super(isDoubleBuffered); } public JBPanel() { super(); } @Nullable public Icon getBackgroundImage() { return myBackgroundImage; } public void setBackgroundImage(@Nullable Icon backgroundImage) { myBackgroundImage = backgroundImage; } @Nullable public Icon getCenterImage() { return myCenterImage; } public void setCenterImage(@Nullable Icon centerImage) { myCenterImage = centerImage; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (myBackgroundImage != null) { final int w = myBackgroundImage.getIconWidth(); final int h = myBackgroundImage.getIconHeight(); int x = 0; int y = 0; while (x < getWidth()) { while (y < getHeight()) { myBackgroundImage.paintIcon(this, g, x, y); y+=h; } y=0; x+=w; } } if (myCenterImage != null) { IconUtil.paintInCenterOf(this, g, myCenterImage); } } }
endless filling
platform/platform-api/src/com/intellij/ui/components/JBPanel.java
endless filling
<ide><path>latform/platform-api/src/com/intellij/ui/components/JBPanel.java <ide> final int h = myBackgroundImage.getIconHeight(); <ide> int x = 0; <ide> int y = 0; <del> while (x < getWidth()) { <del> while (y < getHeight()) { <add> while (w > 0 && x < getWidth()) { <add> while (h > 0 && y < getHeight()) { <ide> myBackgroundImage.paintIcon(this, g, x, y); <ide> y+=h; <ide> }
Java
lgpl-2.1
844f200f9a631376e208f159f561a188f0f845d2
0
ervandew/formic,ervandew/formic
/** * Formic installer framework. * Copyright (C) 2004 - 2006 Eric Van Dewoestine * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.formic.wizard.impl.models; import java.util.Stack; import org.pietschy.wizard.WizardStep; import org.pietschy.wizard.models.Path; import org.pietschy.wizard.models.SimplePath; /** * Extension to original MultiPathModel that supports paths containing no steps. * * @author Eric Van Dewoestine ([email protected]) * @version $Revision$ */ public class MultiPathModel extends org.pietschy.wizard.models.MultiPathModel { private Stack history = new Stack(); private Path firstPath = null; public MultiPathModel(Path firstPath) { super(firstPath); this.firstPath = firstPath; } /** * {@inheritDoc} */ public void nextStep() { WizardStep currentStep = getActiveStep(); Path currentPath = getPathForStep(currentStep); // CHANGE // NEW CODE if (currentPath.getSteps().size() == 0 || currentPath.isLastStep(currentStep)) { Path nextPath = getNextPath(currentPath); while(nextPath.getSteps().size() == 0){ nextPath = getNextPath(nextPath); } setActiveStep(nextPath.firstStep()); } // OLD CODE /*if (currentPath.isLastStep(currentStep)) { Path nextPath = currentPath.getNextPath(this); setActiveStep(nextPath.firstStep()); }*/ // END CHANGE else { setActiveStep(currentPath.nextStep(currentStep)); } history.push(currentStep); } /** * Gets the next path. */ private Path getNextPath (Path path) { if(path instanceof SimplePath){ return ((SimplePath)path).getNextPath(); } return ((BranchingPath)path).getNextPath(this); } /** * {@inheritDoc} */ public void previousStep() { WizardStep step = (WizardStep) history.pop(); setActiveStep(step); } /** * {@inheritDoc} */ public void lastStep() { history.push(getActiveStep()); WizardStep lastStep = getLastPath().lastStep(); setActiveStep(lastStep); } /** * {@inheritDoc} * @see org.pietschy.wizard.WizardModel#isLastVisible() */ public boolean isLastVisible () { return false; } /** * Determines if the supplied step is the first step. * * @param step The step. * @return true if the first step, false otherwise. */ public boolean isFirstStep (WizardStep step) { Path path = getPathForStep(step); return path.equals(getFirstPath()) && path.isFirstStep(step); } /** * {@inheritDoc} */ public void reset() { history.clear(); WizardStep firstStep = firstPath.firstStep(); setActiveStep(firstStep); history.push(firstStep); } /** * {@inheritDoc} * @see org.pietschy.wizard.AbstractWizardModel#setPreviousAvailable(boolean) */ public void setPreviousAvailable (boolean available) { super.setPreviousAvailable(available); } /** * {@inheritDoc} * @see org.pietschy.wizard.AbstractWizardModel#setCancelAvailable(boolean) */ public void setCancelAvailable (boolean available) { super.setCancelAvailable(available); } }
src/java/org/formic/wizard/impl/models/MultiPathModel.java
/** * Formic installer framework. * Copyright (C) 2004 - 2006 Eric Van Dewoestine * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.formic.wizard.impl.models; import java.util.Stack; import org.pietschy.wizard.WizardStep; import org.pietschy.wizard.models.Path; import org.pietschy.wizard.models.SimplePath; /** * Extension to original MultiPathModel that supports paths containing no steps. * * @author Eric Van Dewoestine ([email protected]) * @version $Revision$ */ public class MultiPathModel extends org.pietschy.wizard.models.MultiPathModel { private Stack history = new Stack(); private Path firstPath = null; public MultiPathModel(Path firstPath) { super(firstPath); this.firstPath = firstPath; } /** * {@inheritDoc} */ public void nextStep() { WizardStep currentStep = getActiveStep(); Path currentPath = getPathForStep(currentStep); // CHANGE // NEW CODE if (currentPath.getSteps().size() == 0 || currentPath.isLastStep(currentStep)) { Path nextPath = getNextPath(currentPath); while(nextPath.getSteps().size() == 0){ nextPath = getNextPath(nextPath); } setActiveStep(nextPath.firstStep()); } // OLD CODE /*if (currentPath.isLastStep(currentStep)) { Path nextPath = currentPath.getNextPath(this); setActiveStep(nextPath.firstStep()); }*/ // END CHANGE else { setActiveStep(currentPath.nextStep(currentStep)); } history.push(currentStep); } /** * Gets the next path. */ private Path getNextPath (Path path) { if(path instanceof SimplePath){ return ((SimplePath)path).getNextPath(); } return ((BranchingPath)path).getNextPath(this); } /** * {@inheritDoc} */ public void previousStep() { WizardStep step = (WizardStep) history.pop(); setActiveStep(step); } /** * {@inheritDoc} */ public void lastStep() { history.push(getActiveStep()); WizardStep lastStep = getLastPath().lastStep(); setActiveStep(lastStep); } /** * {@inheritDoc} * @see org.pietschy.wizard.WizardModel#isLastVisible() */ public boolean isLastVisible () { return false; } /** * Determines if the supplied step is the first step. * * @param step The step. * @return true if the first step, false otherwise. */ public boolean isFirstStep (WizardStep step) { Path path = getPathForStep(step); return path.equals(getFirstPath()) && path.isFirstStep(step); } /** * {@inheritDoc} */ public void reset() { history.clear(); WizardStep firstStep = firstPath.firstStep(); setActiveStep(firstStep); history.push(firstStep); } /** * {@inheritDoc} * @see org.pietschy.wizard.AbstractWizardModel#setPreviousAvailable(boolean) */ public void setPreviousAvailable (boolean available) { super.setPreviousAvailable(available); } }
added public version of setCancelAvailable git-svn-id: 64dca1223d331db67f04737d5e1336182ee12169@49 1a7380c6-1923-0410-bcea-c2eae4ba7d6c
src/java/org/formic/wizard/impl/models/MultiPathModel.java
added public version of setCancelAvailable
<ide><path>rc/java/org/formic/wizard/impl/models/MultiPathModel.java <ide> { <ide> super.setPreviousAvailable(available); <ide> } <add> <add> /** <add> * {@inheritDoc} <add> * @see org.pietschy.wizard.AbstractWizardModel#setCancelAvailable(boolean) <add> */ <add> public void setCancelAvailable (boolean available) <add> { <add> super.setCancelAvailable(available); <add> } <ide> }
JavaScript
agpl-3.0
fe09cc865fd6cd905f021183bcb621bb074867ea
0
baozhoutao/processmaker,hitsumabushi/processmaker,tomolimo/processmaker-server,baozhoutao/processmaker,colosa/processmaker,hitsumabushi/processmaker,baozhoutao/processmaker,colosa/processmaker,colosa/processmaker,colosa/processmaker,hitsumabushi/processmaker,baozhoutao/processmaker,hitsumabushi/processmaker,colosa/processmaker,baozhoutao/processmaker,tomolimo/processmaker-server,baozhoutao/processmaker,hitsumabushi/processmaker,tomolimo/processmaker-server,hitsumabushi/processmaker,tomolimo/processmaker-server,tomolimo/processmaker-server,tomolimo/processmaker-server,colosa/processmaker
/* PACKAGE : GULLIVER FORMS */ function G_Form ( element, id ) { var me=this; this.info = { name:'G_Form', version :'1.0' }; /*this.module=RESERVED*/ this.formula=''; this.element=element; if (!element) return; this.id=id; this.aElements=[]; this.ajaxServer=''; this.getElementIdByName = function (name){ if (name=='') return -1; var j; for(j=0;j<me.aElements.length;j++){ if (me.aElements[j].name===name) return j; } return -1; }; this.getElementByName = function (name) { var i=me.getElementIdByName(name); if (i>=0) return me.aElements[i]; else return null; }; this.hideGroup = function( group, parentLevel ){ if (typeof(parentLevel)==='undefined') parentLevel = 1; for( var r=0 ; r < me.aElements.length ; r++ ) { if ((typeof(me.aElements[r].group)!=='undefined') && (me.aElements[r].group == group )) me.aElements[r].hide(parentLevel); } }; this.showGroup = function( group, parentLevel ){ if (typeof(parentLevel)==='undefined') parentLevel = 1; for( var r=0 ; r < me.aElements.length ; r++ ) { if ((typeof(me.aElements[r].group)!=='undefined') && (me.aElements[r].group == group )) me.aElements[r].show(parentLevel); } }; this.verifyRequiredFields=function(){ var valid=true; for(var i=0;i<me.aElements.length;i++){ var verifiedField=((!me.aElements[i].required)||(me.aElements[i].required && (me.aElements[i].value()!==''))); valid=valid && verifiedField; if (!verifiedField) { me.aElements[i].highLight(); } } return valid; }; } function G_Field ( form, element, name ) { var me=this; this.form=form; this.element=element; this.name=name; this.dependentFields=[]; this.dependentOf=[]; this.hide = function( parentLevel ){ if (typeof(parentLevel)==='undefined') parentLevel = 1; var parent = me.element; for( var r=0; r< parentLevel ; r++ ) parent = parent.parentNode; parent.style.display = 'none'; }; this.show = function( parentLevel ){ if (typeof(parentLevel)==='undefined') parentLevel = 1; var parent = me.element; for( var r=0; r< parentLevel ; r++ ) parent = parent.parentNode; parent.style.display = ''; }; this.setDependentFields = function(dependentFields) { var i; if (dependentFields.indexOf(',') > -1) { dependentFields = dependentFields.split(','); } else { dependentFields = dependentFields.split('|'); } for(i=0;i<dependentFields.length;i++) { if (me.form.getElementIdByName(dependentFields[i])>=0) { me.dependentFields[i] = me.form.getElementByName(dependentFields[i]); me.dependentFields[i].addDependencie(me); } } }; this.addDependencie = function (field) { var exists = false; for (i=0;i<me.dependentOf.length;i++) if (me.dependentOf[i]===field) exists = true; if (!exists) me.dependentOf[i] = field; }; this.updateDepententFields=function(event) { var tempValue; if (me.dependentFields.length===0) return true; var fields=[],Fields = [],i,grid='',row=0; for(i in me.dependentFields) { if (me.dependentFields[i].dependentOf) { for (var j = 0; j < me.dependentFields[i].dependentOf.length; j++) { var oAux = me.dependentFields[i].dependentOf[j]; if (oAux.name.indexOf('][') > -1) { var aAux = oAux.name.split(']['); grid = aAux[0]; row = aAux[1]; fieldName = aAux[2]; if (Fields.length > 0){ aux = Fields; aux.push('?'); if (aux.join('*').indexOf(fieldName + '*') == -1){ Fields.push(fieldName); eval("var oAux2 = {" + fieldName + ":'" + oAux.value() + "'}"); fields = fields.concat(oAux2); } }else{ Fields.push(fieldName); eval("var oAux2 = {" + fieldName + ":'" + oAux.value() + "'}"); fields = fields.concat(oAux2); } } else { aux = Fields; aux.push('?'); oAux = me.dependentFields[i].dependentOf[0]; if (Fields.length > 0){ if (aux.join('*').indexOf(oAux.name + '*') == -1){ Fields.push(oAux.name); fields = fields.concat(me.dependentFields[i].dependentOf); } }else{ Fields.push(oAux.name); fields = fields.concat(me.dependentFields[i].dependentOf); } } } } } var callServer; callServer = new leimnud.module.rpc.xmlhttp({ url : me.form.ajaxServer, async : false, method : "POST", args : "function=reloadField&" + 'form='+encodeURIComponent(me.form.id)+'&fields='+encodeURIComponent(fields.toJSONString())+(grid!=''?'&grid='+grid:'')+(row>0?'&row='+row:'') }); callServer.make(); var response = callServer.xmlhttp.responseText; //Validate the response if (response.substr(0,1)==='[') { var newcont; eval('newcont=' + response + ';'); if (grid == '') { for(var i=0;i<newcont.length;i++) { //alert(newcont[i].name + '-' + newcont[i].value); var j=me.form.getElementIdByName(newcont[i].name); me.form.aElements[j].setValue(newcont[i].value); me.form.aElements[j].setContent(newcont[i].content); me.form.aElements[j].updateDepententFields(); /*if (me.form.aElements[j].element.fireEvent) { me.form.aElements[j].element.fireEvent("onchange"); } else { var evObj = document.createEvent('HTMLEvents'); evObj.initEvent( 'change', true, true ); me.form.aElements[j].element.dispatchEvent(evObj); }*/ } } else { for(var i=0;i<newcont.length;i++) { var oAux = me.form.getElementByName(grid); if (oAux) { var oAux2 = oAux.getElementByName(row, newcont[i].name); if (oAux2) { oAux2.setValue(newcont[i].value); oAux2.setContent(newcont[i].content); oAux2.updateDepententFields(); // this line is also needed to trigger the onchange event to trigger the calculation of // sumatory or average functions in text fields //if (i == (newcont.length-1)){ /* if (oAux2.element.fireEvent) { oAux2.element.fireEvent("onchange"); } else { var evObj = document.createEvent('HTMLEvents'); evObj.initEvent( 'change', true, true ); oAux2.element.dispatchEvent(evObj); }*/ //} } } } } } else { alert('Invalid response: '+response); } // this checks the dependent fields that doesn't have assigned a value // but their master yes and their dependence must be fulfilled within one // onchange event /* if (grid!='') { var checkCallServer; var fieldName ; var index; //fieldName = me.name; checkCallServer = new leimnud.module.rpc.xmlhttp({ url : '../dynaforms/dynaforms_checkDependentFields', async : false, method : "POST", args : 'function=showDependentFields&fields='+response+'&fieldName='+fieldName+'&DYN_UID='+me.form.id+'&form='+encodeURIComponent(fields.toJSONString()) +(grid!=''?'&grid='+grid:'')+(row>0?'&row='+row:'') }); checkCallServer.make(); var dependentList = eval(checkCallServer.xmlhttp.responseText); var field ; var oAuxJs; for ( index in dependentList ){ field = 'form[grid]['+ row +']['+dependentList[index]+']'; oAuxJs = document.getElementById(field); if ( oAuxJs!=null ){ if (oAuxJs.value!="") { if ( oAuxJs.fireEvent ) { oAuxJs.fireEvent("onchange"); } else { var evObj = document.createEvent( 'HTMLEvents' ); evObj.initEvent( 'change', true, true ); oAuxJs.dispatchEvent(evObj); } } } } }*/ return true; }; this.setValue = function(newValue) { me.element.value = newValue; }; this.setContent = function(newContent) { }; this.setAttributes = function (attributes) { for(var a in attributes) { if(a=='formula' && attributes[a]){ //here we called a this function if it has a formula sumaformu(this.element,attributes[a],attributes['mask']); }//end formula switch (typeof(attributes[a])) { case 'string': case 'int': case 'boolean': if (a != 'strTo') { switch (true) { case typeof(me[a])==='undefined': case typeof(me[a])==='object': case typeof(me[a])==='function': case a==='isObject': case a==='isArray': break; default: me[a] = attributes[a]; } } else { me[a] = attributes[a]; } } } }; this.value=function() { return me.element.value; }; this.toJSONString=function() { return '{'+me.name+':'+me.element.value.toJSONString()+'}'; }; this.highLight=function(){ try{ G.highLight(me.element); if (G.autoFirstField) { me.element.focus(); G.autoFirstField=false; setTimeout("G.autoFirstField=true;",1000); } } catch (e){ } }; } function G_DropDown( form, element, name ) { var me=this; this.parent = G_Field; this.parent( form, element, name ); this.setContent=function(content) { var dd=me.element; var browser = getBrowserClient(); if (browser.name=='msie'){ while(dd.options.length>1) dd.remove(0); } else { for (var key in dd.options){ dd.options[key] = null; } } // the remove function is no longer reliable // while(dd.options.length>1) dd.remove(0); for(var o=0;o<content.options.length;o++) { var optn = $dce("OPTION"); optn.text = content.options[o].value; optn.value = content.options[o].key; dd.options[o]=optn; } }; if (!element) return; leimnud.event.add(this.element,'change',this.updateDepententFields); } G_DropDown.prototype=new G_Field(); function G_Text( form, element, name) { var me = this; this.mType = 'text'; this.parent = G_Field; this.browser = {}; this.checkBrowser = function(){ var nVer = navigator.appVersion; var nAgt = navigator.userAgent; //alert(navigator.userAgent); var browserName = navigator.appName; var fullVersion = ''+parseFloat(navigator.appVersion); var majorVersion = parseInt(navigator.appVersion,10); var nameOffset,verOffset,ix; // In Opera, the true version is after "Opera" or after "Version" if ((verOffset=nAgt.indexOf("Opera"))!=-1) { browserName = "Opera"; fullVersion = nAgt.substring(verOffset+6); if ((verOffset=nAgt.indexOf("Version"))!=-1) fullVersion = nAgt.substring(verOffset+8); } // In MSIE, the true version is after "MSIE" in userAgent else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) { browserName = "Microsoft Internet Explorer"; fullVersion = nAgt.substring(verOffset+5); } // In Chrome, the true version is after "Chrome" else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) { browserName = "Chrome"; fullVersion = nAgt.substring(verOffset+7); } // In Safari, the true version is after "Safari" or after "Version" else if ((verOffset=nAgt.indexOf("Safari"))!=-1) { browserName = "Safari"; fullVersion = nAgt.substring(verOffset+7); if ((verOffset=nAgt.indexOf("Version"))!=-1) fullVersion = nAgt.substring(verOffset+8); } // In Firefox, the true version is after "Firefox" else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) { browserName = "Firefox"; fullVersion = nAgt.substring(verOffset+8); } // In most other browsers, "name/version" is at the end of userAgent else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < (verOffset=nAgt.lastIndexOf('/')) ) { browserName = nAgt.substring(nameOffset,verOffset); fullVersion = nAgt.substring(verOffset+1); if (browserName.toLowerCase()==browserName.toUpperCase()) { browserName = navigator.appName; } } // trim the fullVersion string at semicolon/space if present if ((ix=fullVersion.indexOf(";"))!=-1) fullVersion=fullVersion.substring(0,ix); if ((ix=fullVersion.indexOf(" "))!=-1) fullVersion=fullVersion.substring(0,ix); majorVersion = parseInt(''+fullVersion,10); if (isNaN(majorVersion)) { fullVersion = ''+parseFloat(navigator.appVersion); majorVersion = parseInt(navigator.appVersion,10); } this.browser = { name: browserName, fullVersion: fullVersion, majorVersion: majorVersion, userAgent: navigator.userAgent }; }; this.parent( form, element, name ); if (element) { this.prev = element.value; } this.validate = 'Any'; this.mask = ''; this.required = false; this.formula = ''; this.key_Change = false; var doubleChange = false; //FUNCTIONS function IsUnsignedInteger(YourNumber){ var Template = /^d+$/; //Formato de numero entero sin signo return (Template.test(YourNumber)) ? 1 : 0; //Compara "YourNumber" con el formato "Template" y si coincidevuelve verdadero si no devuelve falso } function replaceAll( text, busca, reemplaza ){ while (text.toString().indexOf(busca) != -1){ text = text.toString().replace(busca,reemplaza); } return text; } function isNumberMask (mask){ for ( var key in mask){ if (mask[key]!='#'&&mask[key]!=','&&mask[key]!='.'&&typeof(mask[key])=='string'){ return false; } } return true; } //function renderNewValue(element, keyCode){ /*var myField = element; var myValue = myField.value; var cursorPos = 0; var csel; var newValue = ''; var csel = me.getCursorPosition(); var startPos = csel.selectionStart; var endPos = csel.selectionEnd; var newValue2; switch(keyCode){ case 8: if (startPos>0) { newValue = myValue.substring(0, startPos-1); newValue = newValue + myValue.substring(endPos, myField.value.length); if (mType !== 'text'){ newValue2 = G.toMask(newValue, me.mask, startPos); }else{ newValue2 = G.toMask(newValue, me.mask, startPos, 'normal'); } newValue = newValue2.result; } break; case 46: newValue = myValue.substring(0, startPos); newValue = newValue + myValue.substring(endPos+1, myField.value.length); if (mType !== 'text'){ newValue2 = G.toMask(newValue, me.mask, startPos); }else{ newValue2 = G.toMask(newValue, me.mask, startPos, 'normal'); } newValue = newValue2.result; break; } return {result: newValue, cursor: startPos};*/ //} //MEMBERS this.setContent = function(content) { me.element.value = ''; if (content.options) { if (content.options[0]) { me.element.value = content.options[0].value; } } }; //this.validateKey = function(event){ /* attributes = elementAttributesNS(element, 'pm'); if(me.element.readOnly) return true; me.prev = me.element.value; if (window.event) event=window.event; var keyCode= window.event ? event.keyCode : event.which ; me.mask = typeof(me.mask)==='undefined'?'':me.mask; if(me.mask=='yyyy-mm-dd'){ attributes.mask=attributes.mask.replace('%d','dd'); attributes.mask=attributes.mask.replace('%m','mm'); attributes.mask=attributes.mask.replace('%y','yy'); attributes.mask=attributes.mask.replace('%Y','yyyy'); attributes.mask=attributes.mask.replace('%H','mm'); attributes.mask=attributes.mask.replace('%M','mm'); attributes.mask=attributes.mask.replace('%S','mm'); me.mask=attributes.mask; } //alert(me.mask); if (me.mask !=='' ) { if ((keyCode < 48 || keyCode > 57) && (keyCode != 8 && keyCode != 0 && keyCode != 46)) return false; if((keyCode===118 || keyCode===86) && event.ctrlKey) return false; if (event.ctrlKey) return true; if (event.altKey) return true; if (event.shiftKey) return true; } if ((keyCode===0) ) if (event.keyCode===46) return true; else return true; if ( (keyCode===8)) return true; if (me.mask ==='') { if (me.validate == 'NodeName') { if (me.getCursorPos() == 0) { if ((keyCode >= 48) && (keyCode <= 57)) { return false; } } var k=new leimnud.module.validator({ valid :['Field'], key :event, lang :(typeof(me.language)!=='undefined')?me.language:"en" }); return k.result(); }else{ switch(me.validate){ case "Int": if ((keyCode > 47) && (keyCode < 58) || ( keyCode == 118 && event.ctrlKey)|| (keyCode == 120 && event.ctrlKey)) { return true; }else{ return false; } break; case "Alpha": if (keyCode==8) return true; patron =/[A-Za-z\sáéíóúäëïöüñçÇÑ�É�ÓÚÄË�ÖÜ]/; te = String.fromCharCode(keyCode); return patron.test(te); break; case "AlphaNum": if (keyCode==8) return true; patron =/[A-Za-z0-9\sáéíóúäëïöüñçÇÑ�É�ÓÚÄË�ÖÜ]/; te = String.fromCharCode(keyCode); return patron.test(te); break; default: var k=new leimnud.module.validator({ valid :[me.validate], key :event, lang :(typeof(me.language)!=='undefined')?me.language:"en" }); return k.result(); break; } } }else{ var csel = me.getCursorPosition(); var myValue = String.fromCharCode(keyCode); var startPos = csel.selectionStart; var endPos = csel.selectionEnd; var myField = me.element; var oldValue = myField.value; var newValue = ''; newValue = oldValue.substring(0, startPos); newValue = newValue + myValue; newValue = newValue + oldValue.substring(endPos, oldValue.length); startPos++; var newValue2; if (mType !== 'text'){ newValue2 = G.toMask(newValue, me.mask, startPos); }else{ newValue2 = G.toMask(newValue, me.mask, startPos, 'normal'); } //alert(newValue + ' -> ' + mType + ' -> ' + newValue2.result); //alert(newValue2.result); me.element.value = newValue2.result; //alert(me.element.value); me.setSelectionRange(newValue2.cursor, newValue2.cursor); if (me.element.fireEvent){ me.element.fireEvent("onchange"); }else{ var evObj = document.createEvent('HTMLEvents'); evObj.initEvent( 'change', true, true ); me.element.dispatchEvent(evObj); } return true; }*/ //}; this.putFormatNumber =function (evt) { /* if((typeof(evt)==="undefined" || evt===0) && me.mask!='' ){*/ // var numberSet=me.element.value.split('.'); // maskD = me.mask.split(';'); // maskL = (maskD.length >1)?maskD[1]:maskD[0]; // if (maskL.search(",")==-1){ // return false; // } // maskWithoutC =replaceAll(maskL,",",""); // maskWithoutC =replaceAll(maskWithoutC," ",""); // maskWithoutPto=replaceAll(maskWithoutC,".",""); // if(numberSet.length >=2){ // if(maskWithoutPto.substr( (maskWithoutPto.length -1) ,maskWithoutPto.length) =="%") // me.element.value = me.element.value+' '+maskWithoutPto.substr( (maskWithoutPto.length -1) ,maskWithoutPto.length); // return; // } // // maskElemnts = maskWithoutC.split('.'); // maskpartInt = maskElemnts[0].split(''); // numberwc = replaceAll(me.element.value,",", ""); // numberwc = replaceAll(numberwc,".", ""); // onlynumber = replaceAll(numberwc,".", ""); // onlynumber = replaceAll(numberwc," ", ""); // onlynumber = replaceAll(numberwc,"%", ""); // if(onlynumber=='') return false; // cd = parseInt(Math.log(onlynumber)/Math.LN10+1); // var auxnumber = onlynumber; // var cdaux=0; // while(auxnumber > 0){ // cdaux++; // auxnumber =parseInt(auxnumber / 10); // } // cd=cdaux; // // if (isNumberMask(maskpartInt)){ // if(cd < maskpartInt.length && cd >= 4 && cd !=3){ // var newNumber=''; // var cc=1; // while (onlynumber > 0){ // lastdigito = onlynumber % 10; // if (cc%3==0 && cd != cc){ // newNumber = ','+lastdigito.toString() + newNumber; // } else { // newNumber = lastdigito.toString() + newNumber; // } // onlynumber =parseInt(onlynumber / 10); // cc++; // } // if(maskWithoutPto.substr( (maskWithoutPto.length -1) ,maskWithoutPto.length) =="%") // me.element.value = newNumber+' '+maskWithoutPto.substr( (maskWithoutPto.length -1) ,maskWithoutPto.length); // else // me.element.value = newNumber; // }else{ // if(maskWithoutPto.substr( (maskWithoutPto.length -1) ,maskWithoutPto.length) =="%") // var spaceString; // if (me.element.value.substr( (me.element.value.length -1) ,me.element.value.length) == '%' ){ // spaceString =''; // me.element.value = onlynumber + spaceString + maskWithoutPto.substr( (maskWithoutPto.length -1) ,maskWithoutPto.length); // } else { // spaceString =' '; // me.element.value = onlynumber; // } // } // } //} }; //this.preValidateChange=function(event) { /*var oNewValue; var newValueR; me.putFormatNumber(event); if(me.element.readOnly) return true; if (me.mask ==='') return true; if (event.keyCode === 8){ oNewValue = renderNewValue(me.element,event.keyCode); newValueR = G.toMask(oNewValue.result, me.mask, oNewValue.cursor ); me.element.value=newValueR.result; me.setSelectionRange(oNewValue.cursor - 1, oNewValue.cursor - 1); if (me.element.fireEvent){ me.element.fireEvent("onchange"); }else{ var evObj = document.createEvent('HTMLEvents'); evObj.initEvent( 'change', true, true ); me.element.dispatchEvent(evObj); } return false; } if (event.keyCode === 46){ oNewValue = renderNewValue(me.element,event.keyCode); newValueR = G.toMask(oNewValue.result, me.mask, oNewValue.cursor ); me.element.value=newValueR.result; me.setSelectionRange(oNewValue.cursor, oNewValue.cursor); if (me.element.fireEvent){ me.element.fireEvent("onchange"); }else{ var evObj = document.createEvent('HTMLEvents'); evObj.initEvent( 'change', true, true ); me.element.dispatchEvent(evObj); } return false; } //alert(me.element.value); me.prev=me.element.value; return true;*/ //}; this.execFormula=function(event) { if( me.formula != ''){ leimnud.event.add(getField('faa'),'keypress',function(){ alert(getField('faa').value); }); } return false; }; /*this.validateChange=function(event) { /*if (me.mask ==='') return true; var sel=me.getSelectionRange(); var newValue2=G.cleanMask( me.element.value, me.mask, sel.selectionStart ); newValue2=G.toMask( newValue2.result, me.mask, newValue2.cursor); me.element.value = newValue2.result; me.setSelectionRange(newValue2.cursor, newValue2.cursor); return true;*/ //};*/ this.value = function() { return me.element.value; }; //Get Cursor Position this.getCursorPos = function () { var textElement=me.element; if (!document.selection) return textElement.selectionStart; //save off the current value to restore it later, var sOldText = textElement.value; //create a range object and save off it's text var objRange = document.selection.createRange(); var sOldRange = objRange.text; //set this string to a small string that will not normally be encountered var sWeirdString = '#%~'; //insert the weirdstring where the cursor is at objRange.text = sOldRange + sWeirdString; objRange.moveStart('character', (0 - sOldRange.length - sWeirdString.length)); //save off the new string with the weirdstring in it var sNewText = textElement.value; //set the actual text value back to how it was objRange.text = sOldRange; //look through the new string we saved off and find the location of //the weirdstring that was inserted and return that value for (i=0; i <= sNewText.length; i++) { var sTemp = sNewText.substring(i, i + sWeirdString.length); if (sTemp == sWeirdString) { var cursorPos = (i - sOldRange.length); return cursorPos; } } }; this.setSelectionRange = function(selectionStart, selectionEnd) { var input=me.element; if (input.createTextRange) { //IE var range = input.createTextRange(); range.collapse(true); range.moveEnd('character', selectionEnd); range.moveStart('character', selectionStart); range.select(); } else if (input.setSelectionRange) { //Firefox and others input.focus(); input.setSelectionRange(selectionStart, selectionEnd); } }; //FUNCTION MAYBE IT'S DEPRECATED /*this.getSelectionRange = function() { if (document.selection) { var textElement=me.element; var sOldText = textElement.value; var objRange = document.selection.createRange(); var sOldRange = objRange.text; var sWeirdString = '#%~'; objRange.text = sOldRange + sWeirdString; objRange.moveStart('character', (0 - sOldRange.length - sWeirdString.length)); var sNewText = textElement.value; objRange.text = sOldRange; for (i=0; i <= sNewText.length; i++) { var sTemp = sNewText.substring(i, i + sWeirdString.length); if (sTemp == sWeirdString) { var cursorPos = (i - sOldRange.length); return { selectionStart: cursorPos, selectionEnd: cursorPos+sOldRange.length }; } } }else{ var sel={ selectionStart: 0, selectionEnd: 0 }; sel.selectionStart = me.element.selectionStart; sel.selectionEnd = me.element.selectionEnd; return sel; } }; */ //FUNCTION MAYBE IT'S DEPRECATED /*this.getCursorP =function (field) { if (document.selection) { field.focus(); var oSel = document.selection.createRange(); oSel.moveStart('character', -field.value.length); field.selectionEnd = oSel.text.length; oSel.setEndPoint('EndToStart', document.selection.createRange() ); field.selectionStart = oSel.text.length; } return {selectionStart: field.selectionStart, selectionEnd: field.selectionEnd}; };*/ //Gets cursor position this.getCursorPosition = function(){ if(navigator.appName == 'Microsoft Internet Explorer'){ var field = me.element; if (document.selection) { field.focus(); var oSel = document.selection.createRange(); oSel.moveStart('character', -field.value.length); field.selectionEnd = oSel.text.length; oSel.setEndPoint('EndToStart', document.selection.createRange() ); field.selectionStart = oSel.text.length; } return {selectionStart: field.selectionStart, selectionEnd: field.selectionEnd}; }else{ if (document.selection) { var textElement=me.element; var sOldText = textElement.value; var objRange = document.selection.createRange(); var sOldRange = objRange.text; var sWeirdString = '#%~'; objRange.text = sOldRange + sWeirdString; objRange.moveStart('character', (0 - sOldRange.length - sWeirdString.length)); var sNewText = textElement.value; objRange.text = sOldRange; for (i=0; i <= sNewText.length; i++) { var sTemp = sNewText.substring(i, i + sWeirdString.length); if (sTemp == sWeirdString) { var cursorPos = (i - sOldRange.length); return { selectionStart: cursorPos, selectionEnd: cursorPos+sOldRange.length }; } } }else{ var sel={ selectionStart: 0, selectionEnd: 0 }; sel.selectionStart = me.element.selectionStart; sel.selectionEnd = me.element.selectionEnd; return sel; } } }; this.removeMask = function(){ value = me.element.value; cursor = me.getCursorPosition(); chars = value.split(''); newValue = ''; newCont = 0; newCursor = 0; for(c=0; c < chars.length; c++){ switch(chars[c]){ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case me.comma_separator: newValue += chars[c]; newCont++; if (c + 1 == cursor.selectionStart){ newCursor = newCont; } break; case '-': if (me.validate == 'Real'){ newValue += chars[c]; newCont++; if (c + 1 == cursor.selectionStart){ newCursor = newCont; } } break; } } if (cursor.selectionStart != cursor.selectionEnd){ return {result: newValue, cursor: cursor}; } else{ return {result: newValue, cursor: {selectionStart: newCursor, selectionEnd: newCursor}}; } }; this.replaceMask = function(value, cursor, mask, type, comma){ switch(type){ case 'currency': case 'percentage': dir = 'reverse'; break; default: dir = 'forward'; break; } return G.ApplyMask(value, mask, cursor, dir, comma); }; this.replaceMasks= function(newValue, newCursor){ masks = me.mask; aMasks = masks.split(';'); aResults = []; for(m=0; m < aMasks.length; m++){ mask = aMasks[m]; type = me.mType; comma_sep = me.comma_separator; aResults.push(me.replaceMask(newValue, newCursor, mask, type, comma_sep)); } minIndex = 0; minValue = aResults[0].result; if (aResults.length > 1){ for(i=1; i < aResults.length; i++){ if (aResults[i].result < minValue){ minValue = aResults[i].result; minIndex = i; } } } return aResults[minIndex]; }; this.getCleanMask = function(){ aMask = me.mask.split(''); maskOut = ''; for(i=0; i < aMask.length; i++){ if (me.mType == 'currency' || me.mType == 'percentage'){ switch(aMask[i]){ case '0': case '#': maskOut += aMask[i]; break; case me.comma_separator: maskOut += '_'; break; } } else{ switch(aMask[i]){ case '0': case '#': case 'd': case 'm': case 'y': case 'Y': maskOut += aMask[i]; break; } } } return maskOut; } this.applyMask = function(keyCode){ if (me.mask != ''){ dataWOMask = me.removeMask(); //alert(dataWOMask.result + ', ' + dataWOMask.cursor.selectionStart); currentValue = dataWOMask.result; currentSel = dataWOMask.cursor; cursorStart = currentSel.selectionStart; cursorEnd = currentSel.selectionEnd; action = 'mask'; swPeriod = false; switch(keyCode){ case 0: action = 'none'; break; case 8: newValue = currentValue.substring(0, cursorStart - 1); newValue += currentValue.substring(cursorEnd, currentValue.length); newCursor = cursorStart - 1; //alert('aaa' + newValue + ' , ' + newCursor ); break; case 46: newValue = currentValue.substring(0, cursorStart); newValue += currentValue.substring(cursorEnd + 1, currentValue.length); newCursor = cursorStart; break; case 256: case 44: swPeriod = true; newValue = currentValue.substring(0, cursorStart); if (keyCode == 256) newValue += '.'; else newValue += ','; newValue += currentValue.substring(cursorEnd, currentValue.length); //alert(newValue); newCursor = cursorStart + 1; break; case 35: case 36: case 37: case 38: case 39: case 40: newValue = currentValue; switch(keyCode){ case 36:newCursor = 0;break; case 35:newCursor = currentValue.length;break; case 37:newCursor = cursorStart - 1;break; case 39:newCursor = cursorStart + 1;break; } action = 'move'; break; default: newKey = String.fromCharCode(keyCode); newValue = currentValue.substring(0, cursorStart); newValue += newKey; newValue += currentValue.substring(cursorEnd, currentValue.length); newCursor = cursorStart + 1; break; } if (newCursor < 0) newCursor = 0; if (keyCode != 8 && keyCode != 46 && keyCode != 35 && keyCode != 36 && keyCode != 37 && keyCode != 39){ testData = dataWOMask.result; tamData = testData.length; cleanMask = me.getCleanMask(); tamMask = cleanMask.length; sw = false; if (testData.indexOf(me.comma_separator) == -1){ aux = cleanMask.split('_'); tamMask = aux[0].length; sw = true; } if (tamData >= tamMask){ if (sw && !swPeriod && testData.indexOf(me.comma_separator) == -1){ action = 'none'; } if (!sw) action = 'none'; } } switch(action){ case 'mask': case 'move': dataNewMask = me.replaceMasks(newValue, newCursor); me.element.value = dataNewMask.result; me.setSelectionRange(dataNewMask.cursor,dataNewMask.cursor); break; //case 'move': //alert(newCursor); //me.setSelectionRange(newCursor,newCursor); //break; } } else{ currentValue = me.element.value; currentSel = me.getCursorPosition(); cursorStart = currentSel.selectionStart; cursorEnd = currentSel.selectionEnd; switch(keyCode){ case 8: newValue = currentValue.substring(0, cursorStart - 1); newValue += currentValue.substring(cursorEnd, currentValue.length); newCursor = cursorStart - 1; break; case 46: newValue = currentValue.substring(0, cursorStart); newValue += currentValue.substring(cursorEnd + 1, currentValue.length); newCursor = cursorStart; break; case 256: newValue = currentValue.substring(0, cursorStart); newValue += '.'; newValue += currentValue.substring(cursorEnd, currentValue.length); newCursor = cursorStart + 1; break; case 35: case 36: case 37: case 38: case 39: case 40: newValue = currentValue; switch(keyCode){ case 36:newCursor = 0;break; case 35:newCursor = currentValue.length;break; case 37:newCursor = cursorStart - 1;break; case 39:newCursor = cursorStart + 1;break; } break; default: newKey = String.fromCharCode(keyCode); newValue = currentValue.substring(0, cursorStart); newValue += newKey; newValue += currentValue.substring(cursorEnd, currentValue.length); newCursor = cursorStart + 1; break; } if (newCursor < 0) newCursor = 0; me.element.value = newValue; me.setSelectionRange(newCursor,newCursor); } //Launch OnChange Event /*if (me.element.fireEvent){ me.element.fireEvent("onchange"); }else{ var evObj = document.createEvent('HTMLEvents'); evObj.initEvent( 'change', true, true ); me.element.dispatchEvent(evObj); }*/ }; this.sendOnChange = function(){ if (me.element.fireEvent){ me.element.fireEvent("onchange"); }else{ var evObj = document.createEvent('HTMLEvents'); evObj.initEvent( 'change', true, true ); me.element.dispatchEvent(evObj); } }; this.handleKeyDown = function(event){ //THIS FUNCTION HANDLE BACKSPACE AND DELETE KEYS if (me.validate == 'Any' && me.mask == '') return true; pressKey = event.keyCode; switch(pressKey){ case 8: case 46: //BACKSPACE OR DELETE case 35: case 36: //HOME OR END case 37: case 38: case 39: case 40: // ARROW KEYS me.applyMask(pressKey); if ((pressKey == 8 || pressKey == 46) && (me.validate != 'Login' && me.validate != 'NodeName')) me.sendOnChange(); me.checkBrowser(); if (me.browser.name == 'Chrome'){ event.returnValue = false; } else{ return false; } break; } return true; }; this.handleKeyPress = function(event){ if (me.validate == 'Any' && me.mask == '') return true; //THIS FUNCTION HANDLE ALL KEYS EXCEPT BACKSPACE AND DELETE keyCode = event.keyCode; switch(keyCode){ case 9: case 13: return true; break; } if (event.altKey) return true; if (event.ctrlKey) return true; if (event.shiftKey) return true; me.checkBrowser(); if ((me.browser.name == 'Firefox') && (keyCode == 8 || keyCode == 46)){ if (me.browser.name == 'Chrome'){ event.returnValue = false; } else{ return false; } } else{ pressKey = window.event ? event.keyCode : event.which; if (me.mType == 'date') me.validate = 'Int'; keyValid = true; updateOnChange = true; switch(me.validate){ case 'Any': keyValid = true; break; case 'Int': patron = /[0-9]/; key = String.fromCharCode(pressKey); keyValid = patron.test(key); break; case 'Real': patron = /[0-9]/; key = String.fromCharCode(pressKey); keyValid = patron.test(key); keyValid = keyValid || (pressKey == 45); if (me.comma_separator == '.'){ if (me.element.value.indexOf('.')==-1){ keyValid = keyValid || (pressKey == 46); } } else{ if (me.element.value.indexOf(',')==-1){ keyValid = keyValid || (pressKey == 44); } } break; case 'Alpha': patron =/[a-zA-Z]/; // \sáéíóúäëïöüñçÇÑ�É�ÓÚÄË�ÖÜ]/; key = String.fromCharCode(pressKey); keyValid = patron.test(key); break; case 'AlphaNum': patron =/[a-zA-Z0-9\sáéíóúäëïöüñçÇÑ�É�ÓÚÄË�ÖÜ]/; key = String.fromCharCode(pressKey); keyValid = patron.test(key); break; case 'NodeName': case 'Login': updateOnChange = false; if (me.getCursorPos() == 0) { if ((pressKey >= 48) && (pressKey <= 57)) { keyValid = false; break; } } var k=new leimnud.module.validator({ valid :['Field'], key :event, lang :(typeof(me.language)!=='undefined')?me.language:"en" }); keyValid = k.result(); break; default: var k = new leimnud.module.validator({ valid :[me.validate], key :event, lang :(typeof(me.language)!=='undefined')?me.language:"en" }); keyValid = k.result(); break; } if (keyValid){ //APPLY MASK if (pressKey == 46){ me.applyMask(256); //This code send [.] period to the mask } else{ me.applyMask(pressKey); } if (updateOnChange) me.sendOnChange(); if (me.browser.name == 'Chrome'){ event.returnValue = false; } else{ return false; } }else{ if (me.browser.name == 'Chrome'){ event.returnValue = false; } else{ return false; } } } }; if(this.element) { this.element.onblur = function(event) { var evt = event || window.event; var keyPressed = evt.which || evt.keyCode; me.putFormatNumber(keyPressed); if(this.validate=="Email") { //var pat=/^[\w\_\-\.çñ]{2,255}@[\w\_\-]{2,255}\.[a-z]{1,3}\.?[a-z]{0,3}$/; var pat=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$/; if(!pat.test(this.element.value)) { //old|if(this.required=="0"&&this.element.value=="") { if(this.element.value=="") { this.element.className="module_app_input___gray"; return; } else { this.element.className=this.element.className.split(" ")[0]+" FormFieldInvalid"; } } else { this.element.className=this.element.className.split(" ")[0]+" FormFieldValid"; } } if (this.strTo) { switch (this.strTo){ case 'UPPER': this.element.value = this.element.value.toUpperCase(); break; case 'LOWER': this.element.value = this.element.value.toLowerCase(); break; } } if (this.validate == 'NodeName') { var pat = /^[a-z\_](.)[a-z\d\_]{1,255}$/i; if(!pat.test(this.element.value)) { this.element.value = '_' + this.element.value; } } }.extend(this); } if (!element) return; if (!window.event){ //THIS ASSIGN FUNCTIONS FOR FIREFOX/MOZILLA this.element.onkeydown = this.handleKeyDown; this.element.onkeypress = this.handleKeyPress; this.element.onchange = this.updateDepententFields; //this.element.onblur = this.handleOnChange; }else{ //THIS ASSIGN FUNCTIONS FOR IE/CHROME leimnud.event.add(this.element,'keydown',this.handleKeyDown); leimnud.event.add(this.element,'keypress',this.handleKeyPress); leimnud.event.add(this.element,'change',this.updateDepententFields); } //leimnud.event.add(this.element,'change',this.updateDepententFields); }; G_Text.prototype=new G_Field(); function G_Percentage( form, element, name ) { var me=this; this.parent = G_Text; this.parent( form, element, name); this.validate = 'Int'; this.mType = 'percentage'; this.mask= '###.##'; this.comma_separator = "."; } G_Percentage.prototype=new G_Field(); function G_Currency( form, element, name ) { var me=this; this.parent = G_Text; this.parent( form, element, name); this.validate = 'Int'; this.mType = 'currency'; this.mask= '_###,###,###,###,###;###,###,###,###,###.00'; this.comma_separator = "."; } G_Currency.prototype=new G_Field(); function G_TextArea( form, element, name ) { var me=this; this.parent = G_Text; this.parent( form, element, name ); this.validate = 'Any'; this.mask= ''; } G_TextArea.prototype=new G_Field(); function G_Date( form, element, name ) { var me=this; this.parent = G_Text; this.parent( form, element, name ); this.mType = 'date'; this.mask= 'dd-mm-yyyy'; } G_Date.prototype=new G_Field(); function G() { /*MASK*/ var reserved=['_',';','#','.','0','d','m','y','-']; //Invert String function invertir(num) { var num0=''; num0=num; num=""; for(r=num0.length-1;r>=0;r--) num+= num0.substr(r,1); return num; } function __toMask(num, mask, cursor) { var inv=false; if (mask.substr(0,1)==='_') { mask=mask.substr(1); inv=true; } var re; if (inv) { mask=invertir(mask); num=invertir(num); } var minAdd=-1; var minLoss=-1; var newCursorPosition=cursor; var betterOut=""; for(var r0=0;r0< mask.length; r0++){ var out="";var j=0; var loss=0; var add=0; var cursorPosition=cursor;var i=-1;var dayPosition=0;var mounthPosition=0; var dayAnalized ='';var mounthAnalized =''; var blocks={}; //Declares empty object for(var r=0;r< r0 ;r++) { var e=false; var m=mask.substr(r,1); __parseMask(); } i=0; for(r=r0;r< mask.length;r++) { j++; if (j>200) break; e=num.substr(i,1); e=(e==='')?false:e; m=mask.substr(r,1); __parseMask(); } var io=num.length - i; io=(io<0)?0:io; loss+=io; loss=loss+add/1000; //var_dump(loss); if (loss===0) { betterOut=out; minLoss=0; newCursorPosition=cursorPosition; break; } if ((minLoss===-1)||(loss< minLoss)) { minLoss=loss; betterOut=out; newCursorPosition=cursorPosition; } //echo('min:');var_dump($minLoss); } // var_dump($minLoss); out=betterOut; if (inv) { out=invertir(out); mask=invertir(mask); } return { 'result':out, 'cursor':newCursorPosition, 'value':minLoss, 'mask':mask }; function searchBlock( where , what ) { for(var r=0; r < where.length ; r++ ) { if (where[r].key === what) return where[r]; } } function __parseMask() { var ok=true; switch(false) { case m==='d': dayAnalized=''; break; case m==='m': mounthAnalized=''; break; default: } if ( e!==false ) { if (typeof(blocks[m])==='undefined') blocks[m] = e; else blocks[m] += e; } switch(m) { case '0': if (e===false) { out+='0'; add++; break; } case 'y': case '#': if (e===false) { out+=''; break; } //Use direct comparition to increse speed of processing if ((e==='0')||(e==='1')||(e==='2')||(e==='3')||(e==='4')||(e==='5')||(e==='6')||(e==='7')||(e==='8')||(e==='9')||(e==='-')) { out+=e; i++; } else { //loss loss++; i++; r--; } break; case '(': if (e===false) { out+=''; break; } out+=m; if (i<cursor){ cursorPosition++; } break; case 'd': if (e===false) { out+=''; break; } if ((e==='0')||(e==='1')||(e==='2')||(e==='3')||(e==='4')||(e==='5')||(e==='6')||(e==='7')||(e==='8')||(e==='9')) ok=true; else ok=false; //if (ok) if (dayPosition===0) if (parseInt(e)>3) ok=false //dayPosition=(dayPosition+1) | 1; if (ok) dayAnalized = dayAnalized + e; if ((ok) && (parseInt(dayAnalized)>31)) ok = false; if (ok) { out+=e; i++; } else { //loss loss++; i++; r--; } break; case 'm': if (e===false) { out+=''; break; } if ((e==='0')||(e==='1')||(e==='2')||(e==='3')||(e==='4')||(e==='5')||(e==='6')||(e==='7')||(e==='8')||(e==='9')) ok=true; else ok=false; if (ok) mounthAnalized = mounthAnalized + e; if ((ok) && (parseInt(mounthAnalized)>12)) ok=false; if (ok) { out+=e; i++; } else { //loss loss++; i++; r--; } break; default: if (e===false) { out+=''; break; } if (e===m) { out+=e; i++; }else { //if (m==='.') alert(i.toString() +'.'+ cursor.toString()); out+=m; /////here was krlos add++; if (i<cursor){ cursorPosition++; }; /*if(e!==false && m==="." && m!=="," ){ //alert(m) //out+=m; //alert(m) break }*/ //alert(m+'\n'+mask+'\n'+out+'\n'+num) } /*if(m!='-'){ out+=m;} else {out+=String.fromCharCode(45);} add++;if (i<cursor){cursorPosition++;};*/ } } } } //Get only numbers including decimal separator function _getOnlyNumbers(num, _DEC){ var _num = ''; _aNum = num.split(''); for (var d=0; d < _aNum.length; d++){ switch(_aNum[d]){ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case _DEC: _num = _num + _aNum[d]; break; } } return _num; } //Get only mask characters can be replaced by digits. function _getOnlyMask(mask, _DEC){ var _mask=''; _aMask = mask.split(''); for (var d=0; d < _aMask.length; d++){ switch(_aMask[d]){ case '0': case '#': case 'd': case 'm': case 'y': case '_': case _DEC: _mask += _aMask[d]; break; } } return _mask; } //Check if a new digit can be added to this mask function _checkNumber(num, mask){ var __DECIMAL_SEP = '.'; var aNum = _getOnlyNumbers(num, __DECIMAL_SEP); var _outM = aNum; var aMask = _getOnlyMask(mask, __DECIMAL_SEP); if (aMask.indexOf(__DECIMAL_SEP+'0')>0){ //Mask has .0 eMask = aMask.replace(__DECIMAL_SEP, ''); eNum = aNum.replace(__DECIMAL_SEP, ''); if (eNum.length > eMask.length){ _outM = aNum.substring(0, eMask.length +1); } }else{ //Mask hasn't .0 if (aMask.indexOf(__DECIMAL_SEP)>0){ // Mask contains decimal separator iMask = aMask.split(__DECIMAL_SEP); if (aNum.indexOf(__DECIMAL_SEP)>0){ //Number has decimal separator iNum = aNum.split(__DECIMAL_SEP); if (iNum[1].length > iMask[1].length){ _outM = iNum[0] + __DECIMAL_SEP + iNum[1].substr(0,iMask[1].length); }else{ if (iNum[0].length > iMask[0].length){ _outM = iNum[0].substr(0, iMask[0].length) + __DECIMAL_SEP + iNum[1]; } } }else{ //Number has not decimal separator if (aNum.length > iMask[0].length){ _outM = aNum.substr(0, iMask[0].length); } } }else{ //Mask does not contain decimal separator if (aNum.indexOf(__DECIMAL_SEP)>0){ iNum = aNum.split(__DECIMAL_SEP); if (iNum[0].length > aMask.length){ _outM = iNum[0].substr(0,aMask.length); } }else{ if (aNum.length > aMask.length){ _outM = aNum.substr(0,aMask.length); } } } } //alert(_outM); return _outM; } //Apply a mask to a number this.ApplyMask = function(num, mask, cursor, dir, comma_sep){ myOut = ''; myCursor = cursor; if (num.length == 0) return {result: '', cursor: 0}; switch(dir){ case 'forward': iMask = mask.split(''); value = _getOnlyNumbers(num,''); iNum = value.split(''); for(e=0; e < iMask.length && iNum.length > 0; e++){ switch(iMask[e]){ case '#': case '0': case 'd': case 'm': case 'y': case 'Y': if (iNum.length > 0){ key = iNum.shift(); myOut += key; } break; default: myOut += iMask[e]; if (e < myCursor) myCursor++; break; } } break; case 'reverse': var __DECIMAL_SEP = comma_sep; var osize = num.length; num = _getOnlyNumbers(num,__DECIMAL_SEP); if (num.length == 0) return {result: '', cursor: 0}; var iNum = invertir(num); var iMask = invertir(mask); if (iMask.indexOf('0'+__DECIMAL_SEP)> 0){ //Mask has .0 and will applied complete aMask = iMask; iNum = _getOnlyNumbers(iNum,'*'); aNum = iNum; eMask = aMask.split(''); eNum = aNum.split(''); _cout = ''; for (e=0; e < eMask.length; e++){ switch(eMask[e]){ case '#': case '0': if (eNum.length > 0){ key = eNum.shift(); _cout += key; } break; case '.': case ',': if (eMask[e] != __DECIMAL_SEP){ if (eNum.length > 0){ _cout += eMask[e]; } }else{ _cout += eMask[e]; } break; default: _cout += eMask[e]; break; } } myOut = _cout; }else{ sw_d = false; aMask = iMask.split(__DECIMAL_SEP); aNum = iNum.split(__DECIMAL_SEP); if (aMask.length==1){ dMask = ''; cMask = aMask[0]; }else{ dMask = aMask[0]; cMask = aMask[1]; } if (aNum.length == 1){ dNum = ''; cNum = aNum[0]; }else{ sw_d = true; dNum = aNum[0]; cNum = aNum[1]; } _dout = ''; pMask = dMask.split(''); pNum = dNum.split(''); for (p=0; p < pMask.length; p++){ switch(pMask[p]){ case '#': case '0': if (pNum.length > 0){ key = pNum.shift(); _dout += key; } break; case ',': case '.': if (pMask[p] != __DECIMAL_SEP){ if (pNum.length > 0){ _dout += pMask[p]; } }else{ } break; default: _dout += pMask[p]; break; } } _cout = ''; sw_c = false; pMask = cMask.split(''); pNum = cNum.split(''); for (p=0; p < pMask.length; p++){ switch(pMask[p]){ case '#': case '0': case 'd': case 'm': case 'y': if (pNum.length > 0){ key = pNum.shift(); _cout += key; sw_c = true; } break; case ',': case '.': if (pMask[p] != __DECIMAL_SEP){ if (pNum.length > 0){ _cout += pMask[p]; } } break; default: _cout += pMask[p]; } } if (sw_c && sw_d){ myOut = _dout + __DECIMAL_SEP + _cout; }else{ myOut = _dout + _cout; } } myOut = invertir(myOut); tmpCursor = 0; aOut = myOut.split(''); if (cursor == 0){ for(l=0; l < aOut.length; l++){ switch(aOut[l]){ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case __DECIMAL_SEP: myCursor = l; l = aOut.length; break; } } } else if(cursor == num.length){ for(l=0; l < aOut.length; l++){ switch(aOut[l]){ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case __DECIMAL_SEP: last = l; break; } } myCursor = last + 1; } else{ aNum = num.split(''); offset = 0; aNewNum = myOut.split(''); for (a = 0; a < cursor; a++){ notFinded = false; while (aNum[a] != aNewNum[a + offset] && !notFinded){ offset++; if (a + offset > aNewNum.length){ offset = -1; notFinded = true; } } } myCursor = cursor + offset; } break; } //myCursor += 1; /*if (dir){ var osize = num.length; _out = ''; num = _checkNumber(num, mask); num = _getOnlyNumbers(num,''); if (num.length == 0) return {result: '', cursor: 0}; iNum = num; iMask = mask; eMask = iMask.split(''); eNum = iNum.split(''); for (e=0; e < eMask.length; e++){ switch(eMask[e]){ case '#': case '0': case 'd': case 'm': case 'y': case 'Y': if (eNum.length > 0){ key = eNum.shift(); _out += key; } break; default: _out += eMask[e]; break; } } }else{ var __DECIMAL_SEP = comma_sep; var osize = num.length; num = _checkNumber(num, mask); num = _getOnlyNumbers(num,__DECIMAL_SEP); if (num.length == 0) return {result: '', cursor: 0}; var iNum = invertir(num); var iMask = invertir(mask); if (iMask.indexOf('0'+__DECIMAL_SEP)> 0){ //Mask has .0 and will applied complete aMask = iMask; iNum = _getOnlyNumbers(iNum,'*'); aNum = iNum; eMask = aMask.split(''); eNum = aNum.split(''); _cout = ''; for (e=0; e < eMask.length; e++){ switch(eMask[e]){ case '#': case '0': case 'd': case 'm': case 'y': if (eNum.length > 0){ key = eNum.shift(); _cout += key; } break; case '.': case ',': if (eMask[e] != __DECIMAL_SEP){ if (eNum.length > 0){ _cout += eMask[e]; } }else{ _cout += eMask[e]; } break; default: _cout += eMask[e]; break; } } _out = _cout; }else{ sw_d = false; aMask = iMask.split(__DECIMAL_SEP); aNum = iNum.split(__DECIMAL_SEP); if (aMask.length==1){ dMask = ''; cMask = aMask[0]; }else{ dMask = aMask[0]; cMask = aMask[1]; } if (aNum.length == 1){ dNum = ''; cNum = aNum[0]; }else{ sw_d = true; dNum = aNum[0]; cNum = aNum[1]; } _dout = ''; pMask = dMask.split(''); pNum = dNum.split(''); for (p=0; p < pMask.length; p++){ switch(pMask[p]){ case '#': case '0': if (pNum.length > 0){ key = pNum.shift(); _dout += key; } break; case ',': case '.': if (pMask[p] != __DECIMAL_SEP){ if (pNum.length > 0){ _dout += pMask[p]; } }else{ } break; default: _dout += pMask[p]; break; } } _cout = ''; sw_c = false; pMask = cMask.split(''); pNum = cNum.split(''); for (p=0; p < pMask.length; p++){ switch(pMask[p]){ case '#': case '0': case 'd': case 'm': case 'y': if (pNum.length > 0){ key = pNum.shift(); _cout += key; sw_c = true; } break; case ',': case '.': if (pMask[p] != __DECIMAL_SEP){ if (pNum.length > 0){ _cout += pMask[p]; } } break; default: _cout += pMask[p]; } } if (sw_c && sw_d){ _out = _dout + __DECIMAL_SEP + _cout; }else{ _out = _dout + _cout; } } _out = invertir(_out); } if (_out.length > osize){ cursor = cursor + (_out.length - osize); }*/ return { 'result': myOut, 'cursor': myCursor }; }; //Manage Multiple Mask and Integer/Real Number restrictions this.toMask = function(num, mask, cursor, direction){ if (mask==='') return { 'result': new String(num), 'cursor': cursor }; num = new String(num); var result = []; var subMasks=mask.split(';'); for(var r=0; r<subMasks.length; r++) { typedate = mask.indexOf("#"); //if typedate=='0' is current, else typedate=='-1' is date if ((direction == 'normal')&&(typedate=='0')) result[r]=__toMask(num, subMasks[r], cursor); else result[r]=_ApplyMask(num, subMasks[r], cursor, direction); } var betterResult=0; for(r=1; r<subMasks.length; r++) { if (result[r].value<result[betterResult].value) betterResult=r; } return result[betterResult]; }; //Gets number without mask this.getValue = function(masked_num){ var __DECIMAL_SEP = '.'; var xNum = masked_num.split(''); _num = ''; for (u=0; u < xNum.length; u++){ switch(xNum[u]){ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case __DECIMAL_SEP: _num += xNum[u]; break; } } return _num; }; //DEPRECATED this.toMask2 = function (num, mask, cursor) { if (mask==='') return { 'result':new String(num), 'cursor':cursor }; var subMasks=mask.split(';'); var result = []; num = new String(num); for(var r=0; r<subMasks.length; r++) { result[r]=__toMask(num, subMasks[r], cursor); } var betterResult=0; for(r=1; r<subMasks.length; r++) { if (result[r].value<result[betterResult].value) betterResult=r; } return result[betterResult]; }; //DEPRECATED this.cleanMask = function (num, mask, cursor) { mask = typeof(mask)==='undefined'?'':mask; if (mask==='') return { 'result':new String(num), 'cursor':cursor }; var a,r,others=[]; num = new String(num); //alert(oDebug.var_dump(num)); if (typeof(cursor)==='undefined') cursor=0; a = num.substr(0,cursor); for(r=0; r<reserved.length; r++) mask=mask.split(reserved[r]).join(''); while(mask.length>0) { r=others.length; others[r] = mask.substr(0,1); mask= mask.split(others[r]).join(''); num = num.split(others[r]).join(''); cursor -= a.split(others[r]).length-1;//alert(cursor) } return { 'result':num, 'cursor':cursor }; }; this.getId=function(element){ var re=/(\[(\w+)\])+/; var res=re.exec(element.id); return res?res[2]:element.id; }; this.getObject=function(element){ var objId=G.getId(element); switch (element.tagName){ case 'FORM': return eval('form_' + objId); break; default: if (element.form) { var formId=G.getId(element.form); return eval('form_'+objId+'.getElementByName("'+objId+'")'); } } }; /*BLINK EFECT*/ this.blinked=[]; this.blinkedt0=[]; this.autoFirstField=true; this.pi=Math.atan(1)*4; this.highLight = function(element){ var newdiv = $dce('div'); newdiv.style.position="absolute"; newdiv.style.display="inline"; newdiv.style.height=element.clientHeight+2; newdiv.style.width=element.clientWidth+2; newdiv.style.background = "#FF5555"; element.style.backgroundColor='#FFCACA'; element.parentNode.insertBefore(newdiv,element); G.doBlinkEfect(newdiv,1000); }; this.setOpacity=function(e,o){ e.style.filter='alpha'; if (e.filters) { e.filters['alpha'].opacity=o*100; } else { e.style.opacity=o; } }; this.doBlinkEfect=function(div,T){ var f=1/T; var j=G.blinked.length; G.blinked[j]=div; G.blinkedt0[j]=(new Date()).getTime(); for(var i=1;i<=20;i++){ setTimeout("G.setOpacity(G.blinked["+j+"],0.3-0.3*Math.cos(2*G.pi*((new Date()).getTime()-G.blinkedt0["+j+"])*"+f+"));",T/20*i); } setTimeout("G.blinked["+j+"].parentNode.removeChild(G.blinked["+j+"]);G.blinked["+j+"]=null;",T/20*i); }; var alertPanel; this.alert=function(html, title , width, height, autoSize, modal, showModalColor, runScripts) { html='<div>'+html+'</div>'; width = (width)?width:300; height = (height)?height:200; autoSize = (showModalColor===false)?false:true; modal = (modal===false)?false:true; showModalColor = (showModalColor===true)?true:false; var alertPanel = new leimnud.module.panel(); alertPanel.options = { size:{ w:width, h:height }, position:{ center:true }, title: title, theme: "processmaker", control: { close :true, roll :false, drag :true, resize :true }, fx: { blinkToFront:true, opacity :true, drag:true, modal: modal } }; if(showModalColor===false) { alertPanel.styles.fx.opacityModal.Static='0'; } alertPanel.make(); alertPanel.addContent(html); if(runScripts) { var myScripts=alertPanel.elements.content.getElementsByTagName('SCRIPT'); var sMyScripts=[]; for(var rr=0; rr<myScripts.length ; rr++) sMyScripts.push(myScripts[rr].innerHTML); for(var rr=0; rr<myScripts.length ; rr++){ try { if (sMyScripts[rr]!=='') if (window.execScript) window.execScript( sMyScripts[rr], 'javascript' ); else window.setTimeout( sMyScripts[rr], 0 ); } catch (e) { alert(e.description); } } } /* Autosize of panels, to fill only the first child of the * rendered page (take note) */ var panelNonContentHeight = 44; var panelNonContentWidth = 28; try { if (autoSize) { var newW=alertPanel.elements.content.childNodes[0].clientWidth+panelNonContentWidth; var newH=alertPanel.elements.content.childNodes[0].clientHeight+panelNonContentHeight; alertPanel.resize({ w:((newW<width)?width:newW) }); alertPanel.resize({ h:((newH<height)?height:newH) }); } } catch (e) { alert(var_dump(e)); } delete newdiv; delete myScripts; alertPanel.command(alertPanel.loader.hide); }; } var G = new G(); /* PACKAGE : DEBUG */ function G_Debugger() { this.var_dump = function(obj) { var o,dump; dump=''; if (typeof(obj)=='object') for(o in obj) { dump+='<b>'+o+'</b>:'+obj[o]+"<br>\n"; } else dump=obj; debugDiv = document.getElementById('debug'); if (debugDiv) debugDiv.innerHTML=dump; return dump; }; } var oDebug = new G_Debugger(); /* PACKAGE : date field */ var datePickerPanel; function showDatePicker(ev, formId, idName, value, min, max ) { var coor = leimnud.dom.mouse(ev); var coorx = ( coor.x - 50 ); var coory = ( coor.y - 40 ); datePickerPanel=new leimnud.module.panel(); datePickerPanel.options={ size:{ w:275, h:240 }, position:{ x:coorx, y:coory }, title:"Date Picker", theme:"panel", control:{ close:true, drag:true }, fx:{ modal:true } }; datePickerPanel.setStyle={ containerWindow:{ borderWidth:0 } }; datePickerPanel.make(); datePickerPanel.idName = idName; datePickerPanel.formId = formId; var sUrl = "/controls/calendar.php?v="+value+"&d="+value+"&min="+min+"&max="+max; var r = new leimnud.module.rpc.xmlhttp({ url: sUrl }); r.callback=leimnud.closure({ Function:function(rpc){ datePickerPanel.addContent(rpc.xmlhttp.responseText); }, args:r }); r.make(); } function moveDatePicker( n_datetime ) { var dtmin_value = document.getElementById ( 'dtmin_value' ); var dtmax_value = document.getElementById ( 'dtmax_value' ); var sUrl = "/controls/calendar.php?d="+n_datetime + '&min='+dtmin_value.value + '&max='+dtmax_value.value; var r = new leimnud.module.rpc.xmlhttp({ url:sUrl }); r.callback=leimnud.closure({ Function:function(rpc){ datePickerPanel.clearContent(); datePickerPanel.addContent(rpc.xmlhttp.responseText); }, args:r }); r.make(); } function selectDate( day ) { var obj = document.getElementById ( 'span['+datePickerPanel.formId+'][' + datePickerPanel.idName + ']' ); getField(datePickerPanel.idName, datePickerPanel.formId ).value = day; obj.innerHTML = day; datePickerPanel.remove(); } function set_datetime(n_datetime, b_close) { moveDatePicker(n_datetime); } /* Functions for show and hide rows of a simple xmlform. * @author David Callizaya <[email protected]> */ function getRow( name ){ try{ var element = null; if (typeof(name)==='string'){ element = getField(name); /** Set to hide/show of objects "checkgroup" and "radiogroup" @author: Hector Cortez */ if(element == null){ aElements = document.getElementsByName('form['+ name +'][]'); if( aElements.length == 0) aElements = document.getElementsByName('form['+ name +']'); if( aElements.length ){ element = aElements[aElements.length-1]; } else element = null; } } if( element != null){ while ( element.tagName !== 'TR' ) { element=element.parentNode; } return element; } else { return null; } } catch(e){ alert(e); } } var getRowById=getRow; function hideRow( element ){ //neyek var row=getRow(element); if (row) row.style.display='none'; removeRequiredById(element); delete row; } var hideRowById=hideRow; function showRow( element ){ var row=getRow(element); requiredFields = []; sRequiredFields = document.getElementById('DynaformRequiredFields').value.replace(/%27/gi, '"'); fields = new String(sRequiredFields); fields = stripslashes(fields); requiredFieldsList = eval(fields); for(i=0; i<requiredFieldsList.length; i++){ requiredFields[i] = requiredFieldsList[i].name; } if ( requiredFields.inArray(element) ) { enableRequiredById(element); } if (row) row.style.display=''; delete row; } var showRowById=showRow; function hideShowControl(element , name){ var control; if (element) { control = element.parentNode.getElementsByTagName("div")[0]; control.style.display=control.style.display==='none'?'':'none'; if (control.style.display==='none') getField( name ).value=''; delete control; } } /*SHOW/HIDE A SUBTITLE CONTENT*/ function contractSubtitle( subTitle ){ subTitle=getRow(subTitle); var c=subTitle.cells[0].className; var a=subTitle.rowIndex; var t=subTitle.parentNode; for(var i=a+1,m=t.rows.length;i<m;i++){ if (t.rows[i].cells.length==1) break; t.rows[i].style.display='none'; var aAux = getControlsInTheRow(t.rows[i]); for (var j = 0; j < aAux.length; j++) { removeRequiredById(aAux[j]); } } } function expandSubtitle( subTitle ){ subTitle=getRow(subTitle); var c=subTitle.cells[0].className; var a=subTitle.rowIndex; var t=subTitle.parentNode; for(var i=a+1,m=t.rows.length;i<m;i++){ if (t.rows[i].cells.length==1) break; t.rows[i].style.display=''; var aAux = getControlsInTheRow(t.rows[i]); for (var j = 0; j < aAux.length; j++) { enableRequiredById(aAux[j]); } } } function contractExpandSubtitle(subTitle){ subTitle=getRow(subTitle); var c=subTitle.cells[0].className; var a=subTitle.rowIndex; var t=subTitle.parentNode; var contracted=false; for(var i=a+1,m=t.rows.length;i<m;i++){ if (t.rows[i].cells.length==1) break; if (t.rows[i].style.display==='none'){ contracted=true; } } if (contracted) expandSubtitle(subTitle); else contractSubtitle(subTitle); } var getControlsInTheRow = function(oRow) { var aAux1 = []; if (oRow.cells) { var i; var j; var sFieldName; for (i = 0; i < oRow.cells.length; i++) { var aAux2 = oRow.cells[i].getElementsByTagName('input'); if (aAux2) { for (j = 0; j < aAux2.length; j++) { sFieldName = aAux2[j].id.replace('form[', ''); //sFieldName = sFieldName.replace(']', ''); sFieldName = sFieldName.replace(/]$/, ''); aAux1.push(sFieldName); } } } } return aAux1; }; var notValidateThisFields = []; /** * @function getElementByClassNameCrossBrowser * @sumary independent implementaction of the Firefox getElementsByClassName * for CrossBrowser compatibility * @author gustavo cruz gustavo-at-colosa.com * @parameter className * @parameter node * @parameter tag * @return array * return the elements that are from the className */ function getElementsByClassNameCrossBrowser(searchClass,node,tag) { var classElements = new Array(); if ( node == null ) node = document; if ( tag == null ) tag = '*'; var els = node.getElementsByTagName(tag); var elsLen = els.length; var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"); for (i = 0, j = 0; i < elsLen; i++) { if ( pattern.test(els[i].className) ) { classElements[j] = els[i]; j++; } } return classElements; } /** * @function validateGridForms * @sumary function to validate the elements of a grid form inside a normal * form. * @author gustavo cruz gustavo-at-colosa.com * @parameter invalidFields * @return array * with the grid invalid fields added. * We need the invalidFields as a parameter * **/ var validateGridForms = function(invalidFields){ // alert("doesnt work " + i); grids = getElementsByClassNameCrossBrowser("grid",document,"div"); Tlabels = getElementsByClassNameCrossBrowser("tableGrid",document,"table"); // grids = getElementsByClass("grid",document,"div"); // grids = document.getElementsByClassName("grid"); for(j=0; j<grids.length; j++){ // check all the input fields in the grid fields = grids[j].getElementsByTagName('input'); // labels = ; for(i=0; i<fields.length; i++){ if (fields[i].getAttribute("pm:required")=="1"&&fields[i].value==''){ $label = fields[i].name.split("["); $labelPM = fields[i].getAttribute("pm:label"); if ($labelPM == '' || $labelPM == null){ $fieldName = $label[3].split("]")[0]+ " " + $label[2].split("]")[0]; }else{ $fieldName = $labelPM + " " + $label[2].split("]")[0]; } //$fieldName = labels[i].innerHTML.replace('*','') + " " + $label[2].split("]")[0]; //alert($fieldName+" "+$fieldRow); //alert(fields[i].name); invalidFields.push($fieldName); } } textAreas = grids[j].getElementsByTagName('textarea'); for(i=0; i<textAreas.length; i++){ if (textAreas[i].getAttribute("pm:required")=="1"&&textAreas[i].value==''){ $label = textAreas[i].name.split("["); $fieldName = $label[3].split("]")[0]+ " " + $label[2].split("]")[0]; //alert($fieldName+" "+$fieldRow); //alert(fields[i].name); invalidFields.push($fieldName); } } dropdowns = grids[j].getElementsByTagName('select'); for(i=0; i<dropdowns.length; i++){ if (dropdowns[i].getAttribute("pm:required")=="1"&&dropdowns[i].value==''){ $label = dropdowns[i].name.split("["); $fieldName = $label[3].split("]")[0]+ " " + $label[2].split("]")[0]; //alert($fieldName+" "+$fieldRow); //alert(fields[i].name); invalidFields.push($fieldName); } } } return (invalidFields); }; /** * * This function validates via javascript * the required fields in the Json array in the form tag of a dynaform * now the required fields in a grid have a "required" atribute set in 1 * @param String sRequiredFields * **/ var validateForm = function(sRequiredFields) { /** * replacing the %27 code by " character (if exists), this solve the problem that " broke the properties definition into a html * i.ei <form onsubmit="myaction(MyjsString)" ... with var MyjsString = "some string that is into a variable, so this broke the html"; */ if( typeof(sRequiredFields) != 'object' || sRequiredFields.indexOf("%27") > 0 ){ sRequiredFields = sRequiredFields.replace(/%27/gi, '"'); } if( typeof(sRequiredFields) != 'object' || sRequiredFields.indexOf("%39") > 0 ){ sRequiredFields = sRequiredFields.replace(/%39/gi, "'"); } aRequiredFields = eval(sRequiredFields); var sMessage = ''; var invalid_fields = Array(); var fielEmailInvalid = Array(); for (var i = 0; i < aRequiredFields.length; i++) { aRequiredFields[i].label=(aRequiredFields[i].label=='')?aRequiredFields[i].name:aRequiredFields[i].label; if (!notValidateThisFields.inArray(aRequiredFields[i].name)) { if (typeof aRequiredFields[i].required != 'undefined'){ required = aRequiredFields[i].required; } else { required = 1; } if (typeof aRequiredFields[i].validate != 'undefined') { validate = aRequiredFields[i].validate; } else { validate = ''; } if(required == 1) { switch(aRequiredFields[i].type) { case 'suggest': var vtext1 = new input(getField(aRequiredFields[i].name+'_suggest')); if(getField(aRequiredFields[i].name).value==''){ invalid_fields.push(aRequiredFields[i].label); vtext1.failed(); } else { vtext1.passed(); } break; case 'text': var vtext = new input(getField(aRequiredFields[i].name)); if(getField(aRequiredFields[i].name).value=='') { invalid_fields.push(aRequiredFields[i].label); vtext.failed(); } else { vtext.passed(); } break; case 'dropdown': var vtext = new input(getField(aRequiredFields[i].name)); if(getField(aRequiredFields[i].name).value==''){ invalid_fields.push(aRequiredFields[i].label); vtext.failed(); } else { vtext.passed(); } break; case 'textarea': var vtext = new input(getField(aRequiredFields[i].name)); if(getField(aRequiredFields[i].name).value==''){ invalid_fields.push(aRequiredFields[i].label); vtext.failed(); } else { vtext.passed(); } break; case 'password': var vpass = new input(getField(aRequiredFields[i].name)); if(getField(aRequiredFields[i].name).value==''){ invalid_fields.push(aRequiredFields[i].label); vpass.failed(); } else { vpass.passed(); } break; case 'currency': var vcurr = new input(getField(aRequiredFields[i].name)); if(getField(aRequiredFields[i].name).value==''){ invalid_fields.push(aRequiredFields[i].label); vcurr.failed(); } else { vcurr.passed(); } break; case 'percentage': var vper = new input(getField(aRequiredFields[i].name)); if(getField(aRequiredFields[i].name).value==''){ invalid_fields.push(aRequiredFields[i].label); vper.failed(); } else { vper.passed(); } break; case 'yesno': var vtext = new input(getField(aRequiredFields[i].name)); if(getField(aRequiredFields[i].name).value==''){ invalid_fields.push(aRequiredFields[i].label); vtext.failed(); } else { vtext.passed(); } break; case 'date': var vtext = new input(getField(aRequiredFields[i].name)); if(getField(aRequiredFields[i].name).value==''){ invalid_fields.push(aRequiredFields[i].label); vtext.failed(); } else { vtext.passed(); } break; case 'file': var vtext = new input(getField(aRequiredFields[i].name)); if(getField(aRequiredFields[i].name).value==''){ invalid_fields.push(aRequiredFields[i].label); vtext.failed(); } else { vtext.passed(); } break; case 'listbox': var oAux = getField(aRequiredFields[i].name); var bOneSelected = false; for (var j = 0; j < oAux.options.length; j++) { if (oAux.options[j].selected) { bOneSelected = true; j = oAux.options.length; } } if(bOneSelected == false) invalid_fields.push(aRequiredFields[i].label); break; case 'radiogroup': var x=aRequiredFields[i].name; var oAux = document.getElementsByName('form['+ x +']'); var bOneChecked = false; for (var k = 0; k < oAux.length; k++) { var r = oAux[k]; if (r.checked) { bOneChecked = true; k = oAux.length; } } if(bOneChecked == false) invalid_fields.push(aRequiredFields[i].label); break; case 'checkgroup': var bOneChecked = false; var aAux = document.getElementsByName('form[' + aRequiredFields[i].name + '][]'); for (var k = 0; k < aAux.length; k++) { if (aAux[k].checked) { bOneChecked = true; k = aAux.length; } } if(!bOneChecked) { invalid_fields.push(aRequiredFields[i].label); } break; } } if(validate != '') { //validate_fields switch(aRequiredFields[i].type) { case 'suggest': break; case 'text': if(validate=="Email") { var vtext = new input(getField(aRequiredFields[i].name)); if(getField(aRequiredFields[i].name).value!='') { var email = getField(aRequiredFields[i].name); //var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; //var filter = /^[\w\_\-\.çñ]{2,255}@[\w\_\-]{2,255}\.[a-z]{1,3}\.?[a-z]{0,3}$/; var filter =/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; if (!filter.test(email.value)&&email.value!="") { fielEmailInvalid.push(aRequiredFields[i].label); vtext.failed(); email.focus(); } else { vtext.passed(); } } } break; } } } } // call added by gustavo - cruz, gustavo-at-colosa.com validate grid forms invalid_fields = validateGridForms(invalid_fields); if (invalid_fields.length > 0 ||fielEmailInvalid.length> 0) { //alert(G_STRINGS.ID_REQUIRED_FIELDS + ": \n\n" + sMessage); // loop for invalid_fields for(j=0; j<invalid_fields.length; j++){ sMessage += (j > 0)? ', ': ''; sMessage += invalid_fields[j]; } // Loop for invalid_emails var emailInvalidMessage = ""; for(j=0; j<fielEmailInvalid.length; j++){ emailInvalidMessage += (j > 0)? ', ': ''; emailInvalidMessage += fielEmailInvalid[j]; } /* new leimnud.module.app.alert().make({ label:G_STRINGS.ID_REQUIRED_FIELDS + ": <br/><br/>[ " + sMessage + " ]", width:450, height:140 + (parseInt(invalid_fields.length/10)*10) });*/ //!create systemMessaggeInvalid of field invalids var systemMessaggeInvalid = ""; if(invalid_fields.length > 0) { systemMessaggeInvalid += "\n \n"+G_STRINGS.ID_REQUIRED_FIELDS + ": \n \n [ " + sMessage + " ]"; } if(fielEmailInvalid.length > 0) { systemMessaggeInvalid += "\n \n" + G_STRINGS.ID_VALIDATED_FIELDS + ": \n \n [ " + emailInvalidMessage + " ]"; } alert(systemMessaggeInvalid); return false; } else { return true; } }; var getObject = function(sObject) { var i; var oAux = null; var iLength = __aObjects__.length; for (i = 0; i < iLength; i++) { oAux = __aObjects__[i].getElementByName(sObject); if (oAux) { return oAux; } } return oAux; }; var saveAndRefreshForm = function(oObject) { if (oObject) { oObject.form.action += '&_REFRESH_=1'; oObject.form.submit(); } else { var oAux = window.document.getElementsByTagName('form'); if (oAux.length > 0) { oAux[0].action += '&_REFRESH_=1'; oAux[0].submit(); } } }; /** * @function saveForm * @author gustavo cruz gustavo[at]colosa[dot]com * @param oObject is a reference to the object which is attached to the event, * for example can be a save button, or anything else. * @return This function only makes an ajax post to the form action * @desc saveForm takes a object reference as a parameter, from that extracts * the form and the form action references, then executes an Ajax request * that post the form data to the action url, so the form is never * refreshed or submited, at least not in the traditional sense. **/ var saveForm = function(oObject) { if (oObject) { ajax_post(oObject.form.action,oObject.form,'POST'); } else { var oAux = window.document.getElementsByTagName('form'); if (oAux.length > 0) { ajax_post(oAux[0].action,oAux[0],'POST'); } } }; /** * @function validateUrl * @author gustavo cruz gustavo[at]colosa[dot]com * @param url is the url to be validated. * @return true/false. * @desc takes a url as parameter and check returning a boolean if it's valid or not. **/ var validateURL = function (url){ //var regexp = /https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/; if (regexp.test('https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?')){ return true; } else { return false; } }; /** * @function saveAndRedirectForm * @author gustavo cruz gustavo[at]colosa[dot]com * @param oObject is a reference to the object which is attached to the event, * for example can be a save button, or anything else. * @param oLocation is the url of tha redirect location. * @return This function only makes a non refresh save a redirection action. * @desc saveAndRedirectForm takes a object reference as a parameter, and * then invoques the saveForm() function, so after the form data is saved, * validates the url passed as parameter, if it's valid then redirects * the browser to the oLocation url. **/ var saveAndRedirectForm = function(oObject, oLocation) { saveForm(oObject); if (validateURL(oLocation)){ document.location.href = oLocation; } }; var removeRequiredById = function(sFieldName) { if (!notValidateThisFields.inArray(sFieldName)) { notValidateThisFields.push(sFieldName); var oAux = document.getElementById('__notValidateThisFields__'); if (oAux) { oAux.value = notValidateThisFields.toJSONString(); } } }; var enableRequiredById = function(sFieldName) { if (notValidateThisFields.inArray(sFieldName)) { var i; var aAux = []; for(i = 0; i < notValidateThisFields.length; i++) { if(notValidateThisFields[i] != sFieldName) { aAux.push(notValidateThisFields[i]); } } notValidateThisFields = aAux; var oAux = document.getElementById('__notValidateThisFields__'); if (oAux) { oAux.value = notValidateThisFields.toJSONString(); } } }; function dynaformVerifyFieldName(){ pme_validating = true; setTimeout('verifyFieldName1();',0); return true; } function verifyFieldName1(){ var newFieldName=fieldName.value; var validatedFieldName=getField("PME_VALIDATE_NAME",fieldForm).value; var dField = new input(getField('PME_XMLNODE_NAME')); var valid=(newFieldName!=='')&&(((newFieldName!==savedFieldName)&&(validatedFieldName===''))||((newFieldName===savedFieldName))); if (valid){ dField.passed(); getField("PME_ACCEPT",fieldForm).disabled=false; }else{ getField("PME_ACCEPT",fieldForm).disabled=true; dField.failed(); new leimnud.module.app.alert().make({ label: G_STRINGS.DYNAFIELD_ALREADY_EXIST }); dField.focus(); } pme_validating=false; return valid; } var objectsWithFormula = Array(); function sumaformu(ee,fma,mask){ //copy the formula afma=fma; var operators=['+','-','*','/','(','[','{','}',']',')',',','Math.pow','Math.PI','Math.sqrt']; var wos; //replace the operators symbols for empty space for(var i=0 ; i < operators.length ; i++) { var j=0; while(j < fma.length){ nfma=fma.replace(operators[i]," "); nfma=nfma.replace(" "," "); fma=nfma; j++; } } //without spaces in the inicio of the formula wos=nfma.replace(/^\s+/g,''); nfma=wos.replace(/\s+$/g,''); theelemts=nfma.split(" "); objectsWithFormula[objectsWithFormula.length]= {ee:ee,fma:afma,mask:mask,theElements:theelemts}; for (var i=0; i < theelemts.length; i++){ leimnud.event.add(getField(theelemts[i]),'keyup',function(){ //leimnud.event.add(getField(objectsWithFormula[objectsWithFormula.length-1].theElements[i]),'keyup',function(){ myId=this.id.replace("form[","").replace("]",""); for(i_elements=0;i_elements < objectsWithFormula.length; i_elements++){ for(i_elements2=0;i_elements2 < objectsWithFormula[i_elements].theElements.length;i_elements2++){ if(objectsWithFormula[i_elements].theElements[i_elements2]==myId) { //calValue(afma,nfma,ee,mask); formula = objectsWithFormula[i_elements].fma; ans = objectsWithFormula[i_elements].ee; theelemts=objectsWithFormula[i_elements].theElements; nfk = ''; //to replace the field for the value and to evaluate the formula for (var i=0; i < theelemts.length; i++){ if(!isnumberk(theelemts[i])){//alert(getField(theelemts[i]).name); val = (getField(theelemts[i]).value == '')? 0 : getField(theelemts[i]).value; formula=formula.replace(theelemts[i],val); } } var rstop=eval(formula); if(mask!=''){ putmask(rstop,mask,ans); }else{ ans.value=rstop; } } } } }); } } function calValue(afma,nfma,ans,mask){ theelemts=nfma.split(" "); //to replace the field for the value and to evaluate the formula for (var i=0; i < theelemts.length; i++){ if(!isnumberk(theelemts[i])){//alert(getField(theelemts[i]).name); if(getField(theelemts[i]).value){ nfk=afma.replace(theelemts[i],getField(theelemts[i]).value); afma=nfk; } } } //ans.value=eval(nfk); var rstop=eval(nfk); if(mask!=''){ putmask(rstop,mask,ans); }else{ //alert('without mask'); ans.value=rstop; } } function isnumberk(texto){ var numberk="0123456789."; var letters="abcdefghijklmnopqrstuvwxyz"; var i=0; var sw=1; //for(var i=0; i<texto.length; i++){ while(i++ < texto.length && sw==1){ if (numberk.indexOf(texto.charAt(i),0)==-1){ sw=0; } } return sw; } function putmask(numb,mask,ans){ var nnum=''; var i=0; var j=0; maskDecimal=mask.split(";"); if(maskDecimal.length > 1) { maskDecimal=maskDecimal[1].split("."); } else { maskDecimal=mask.split("."); } numDecimal=maskDecimal[1].length; ans.value=numb.toFixed(numDecimal); return; var nnum='',i=0,j=0; //we get the number of digits cnumb=numb.toString(); cd = parseInt(Math.log(numb)/Math.LN10+1); //now we're runing the mask and cd fnb=cnumb.split("."); maskp=mask.split(";"); mask = (maskp.length > 1)? maskp[1]:mask; while(i < numb.toString().length && j < mask.length){ //alert(cnumb.charAt(i)+' ** '+mask.charAt(i)); switch(mask.charAt(j)){ case '#': if(cnumb.charAt(i)!='.') { nnum+=cnumb.charAt(i).toString(); i++; } break; case '.': nnum+=mask.charAt(j).toString(); i=cd+1; cd=i +4; break; default: //alert(mask.charAt(i)); nnum+=mask.charAt(j).toString(); break; } j++; } ans.value=nnum; } function showRowsById(aFields){ for(i=0; i<aFields.length; i++){ row = getRow(aFields[i]); if( row ){ row.style.display=''; } } } function hideRowsById(aFields){ for(i=0; i<aFields.length; i++){ row = getRow(aFields[i]); if( row ){ row.style.display='none'; } } } /* end file */
gulliver/js/form/core/form.js
/* PACKAGE : GULLIVER FORMS */ function G_Form ( element, id ) { var me=this; this.info = { name:'G_Form', version :'1.0' }; /*this.module=RESERVED*/ this.formula=''; this.element=element; if (!element) return; this.id=id; this.aElements=[]; this.ajaxServer=''; this.getElementIdByName = function (name){ if (name=='') return -1; var j; for(j=0;j<me.aElements.length;j++){ if (me.aElements[j].name===name) return j; } return -1; }; this.getElementByName = function (name) { var i=me.getElementIdByName(name); if (i>=0) return me.aElements[i]; else return null; }; this.hideGroup = function( group, parentLevel ){ if (typeof(parentLevel)==='undefined') parentLevel = 1; for( var r=0 ; r < me.aElements.length ; r++ ) { if ((typeof(me.aElements[r].group)!=='undefined') && (me.aElements[r].group == group )) me.aElements[r].hide(parentLevel); } }; this.showGroup = function( group, parentLevel ){ if (typeof(parentLevel)==='undefined') parentLevel = 1; for( var r=0 ; r < me.aElements.length ; r++ ) { if ((typeof(me.aElements[r].group)!=='undefined') && (me.aElements[r].group == group )) me.aElements[r].show(parentLevel); } }; this.verifyRequiredFields=function(){ var valid=true; for(var i=0;i<me.aElements.length;i++){ var verifiedField=((!me.aElements[i].required)||(me.aElements[i].required && (me.aElements[i].value()!==''))); valid=valid && verifiedField; if (!verifiedField) { me.aElements[i].highLight(); } } return valid; }; } function G_Field ( form, element, name ) { var me=this; this.form=form; this.element=element; this.name=name; this.dependentFields=[]; this.dependentOf=[]; this.hide = function( parentLevel ){ if (typeof(parentLevel)==='undefined') parentLevel = 1; var parent = me.element; for( var r=0; r< parentLevel ; r++ ) parent = parent.parentNode; parent.style.display = 'none'; }; this.show = function( parentLevel ){ if (typeof(parentLevel)==='undefined') parentLevel = 1; var parent = me.element; for( var r=0; r< parentLevel ; r++ ) parent = parent.parentNode; parent.style.display = ''; }; this.setDependentFields = function(dependentFields) { var i; if (dependentFields.indexOf(',') > -1) { dependentFields = dependentFields.split(','); } else { dependentFields = dependentFields.split('|'); } for(i=0;i<dependentFields.length;i++) { if (me.form.getElementIdByName(dependentFields[i])>=0) { me.dependentFields[i] = me.form.getElementByName(dependentFields[i]); me.dependentFields[i].addDependencie(me); } } }; this.addDependencie = function (field) { var exists = false; for (i=0;i<me.dependentOf.length;i++) if (me.dependentOf[i]===field) exists = true; if (!exists) me.dependentOf[i] = field; }; this.updateDepententFields=function(event) { var tempValue; if (me.dependentFields.length===0) return true; var fields=[],Fields = [],i,grid='',row=0; for(i in me.dependentFields) { if (me.dependentFields[i].dependentOf) { for (var j = 0; j < me.dependentFields[i].dependentOf.length; j++) { var oAux = me.dependentFields[i].dependentOf[j]; if (oAux.name.indexOf('][') > -1) { var aAux = oAux.name.split(']['); grid = aAux[0]; row = aAux[1]; fieldName = aAux[2]; if (Fields.length > 0){ aux = Fields; aux.push('?'); if (aux.join('*').indexOf(fieldName + '*') == -1){ Fields.push(fieldName); eval("var oAux2 = {" + fieldName + ":'" + oAux.value() + "'}"); fields = fields.concat(oAux2); } }else{ Fields.push(fieldName); eval("var oAux2 = {" + fieldName + ":'" + oAux.value() + "'}"); fields = fields.concat(oAux2); } } else { aux = Fields; aux.push('?'); oAux = me.dependentFields[i].dependentOf[0]; if (Fields.length > 0){ if (aux.join('*').indexOf(oAux.name + '*') == -1){ Fields.push(oAux.name); fields = fields.concat(me.dependentFields[i].dependentOf); } }else{ Fields.push(oAux.name); fields = fields.concat(me.dependentFields[i].dependentOf); } } } } } var callServer; callServer = new leimnud.module.rpc.xmlhttp({ url : me.form.ajaxServer, async : false, method : "POST", args : "function=reloadField&" + 'form='+encodeURIComponent(me.form.id)+'&fields='+encodeURIComponent(fields.toJSONString())+(grid!=''?'&grid='+grid:'')+(row>0?'&row='+row:'') }); callServer.make(); var response = callServer.xmlhttp.responseText; //Validate the response if (response.substr(0,1)==='[') { var newcont; eval('newcont=' + response + ';'); if (grid == '') { for(var i=0;i<newcont.length;i++) { //alert(newcont[i].name + '-' + newcont[i].value); var j=me.form.getElementIdByName(newcont[i].name); me.form.aElements[j].setValue(newcont[i].value); me.form.aElements[j].setContent(newcont[i].content); me.form.aElements[j].updateDepententFields(); /*if (me.form.aElements[j].element.fireEvent) { me.form.aElements[j].element.fireEvent("onchange"); } else { var evObj = document.createEvent('HTMLEvents'); evObj.initEvent( 'change', true, true ); me.form.aElements[j].element.dispatchEvent(evObj); }*/ } } else { for(var i=0;i<newcont.length;i++) { var oAux = me.form.getElementByName(grid); if (oAux) { var oAux2 = oAux.getElementByName(row, newcont[i].name); if (oAux2) { oAux2.setValue(newcont[i].value); oAux2.setContent(newcont[i].content); oAux2.updateDepententFields(); // this line is also needed to trigger the onchange event to trigger the calculation of // sumatory or average functions in text fields //if (i == (newcont.length-1)){ /* if (oAux2.element.fireEvent) { oAux2.element.fireEvent("onchange"); } else { var evObj = document.createEvent('HTMLEvents'); evObj.initEvent( 'change', true, true ); oAux2.element.dispatchEvent(evObj); }*/ //} } } } } } else { alert('Invalid response: '+response); } // this checks the dependent fields that doesn't have assigned a value // but their master yes and their dependence must be fulfilled within one // onchange event /* if (grid!='') { var checkCallServer; var fieldName ; var index; //fieldName = me.name; checkCallServer = new leimnud.module.rpc.xmlhttp({ url : '../dynaforms/dynaforms_checkDependentFields', async : false, method : "POST", args : 'function=showDependentFields&fields='+response+'&fieldName='+fieldName+'&DYN_UID='+me.form.id+'&form='+encodeURIComponent(fields.toJSONString()) +(grid!=''?'&grid='+grid:'')+(row>0?'&row='+row:'') }); checkCallServer.make(); var dependentList = eval(checkCallServer.xmlhttp.responseText); var field ; var oAuxJs; for ( index in dependentList ){ field = 'form[grid]['+ row +']['+dependentList[index]+']'; oAuxJs = document.getElementById(field); if ( oAuxJs!=null ){ if (oAuxJs.value!="") { if ( oAuxJs.fireEvent ) { oAuxJs.fireEvent("onchange"); } else { var evObj = document.createEvent( 'HTMLEvents' ); evObj.initEvent( 'change', true, true ); oAuxJs.dispatchEvent(evObj); } } } } }*/ return true; }; this.setValue = function(newValue) { me.element.value = newValue; }; this.setContent = function(newContent) { }; this.setAttributes = function (attributes) { for(var a in attributes) { if(a=='formula' && attributes[a]){ //here we called a this function if it has a formula sumaformu(this.element,attributes[a],attributes['mask']); }//end formula switch (typeof(attributes[a])) { case 'string': case 'int': case 'boolean': if (a != 'strTo') { switch (true) { case typeof(me[a])==='undefined': case typeof(me[a])==='object': case typeof(me[a])==='function': case a==='isObject': case a==='isArray': break; default: me[a] = attributes[a]; } } else { me[a] = attributes[a]; } } } }; this.value=function() { return me.element.value; }; this.toJSONString=function() { return '{'+me.name+':'+me.element.value.toJSONString()+'}'; }; this.highLight=function(){ try{ G.highLight(me.element); if (G.autoFirstField) { me.element.focus(); G.autoFirstField=false; setTimeout("G.autoFirstField=true;",1000); } } catch (e){ } }; } function G_DropDown( form, element, name ) { var me=this; this.parent = G_Field; this.parent( form, element, name ); this.setContent=function(content) { var dd=me.element; var browser = getBrowserClient(); if (browser.name=='msie'){ while(dd.options.length>1) dd.remove(0); } else { for (var key in dd.options){ dd.options[key] = null; } } // the remove function is no longer reliable // while(dd.options.length>1) dd.remove(0); for(var o=0;o<content.options.length;o++) { var optn = $dce("OPTION"); optn.text = content.options[o].value; optn.value = content.options[o].key; dd.options[o]=optn; } }; if (!element) return; leimnud.event.add(this.element,'change',this.updateDepententFields); } G_DropDown.prototype=new G_Field(); function G_Text( form, element, name) { var me = this; this.mType = 'text'; this.parent = G_Field; this.browser = {}; this.checkBrowser = function(){ var nVer = navigator.appVersion; var nAgt = navigator.userAgent; //alert(navigator.userAgent); var browserName = navigator.appName; var fullVersion = ''+parseFloat(navigator.appVersion); var majorVersion = parseInt(navigator.appVersion,10); var nameOffset,verOffset,ix; // In Opera, the true version is after "Opera" or after "Version" if ((verOffset=nAgt.indexOf("Opera"))!=-1) { browserName = "Opera"; fullVersion = nAgt.substring(verOffset+6); if ((verOffset=nAgt.indexOf("Version"))!=-1) fullVersion = nAgt.substring(verOffset+8); } // In MSIE, the true version is after "MSIE" in userAgent else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) { browserName = "Microsoft Internet Explorer"; fullVersion = nAgt.substring(verOffset+5); } // In Chrome, the true version is after "Chrome" else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) { browserName = "Chrome"; fullVersion = nAgt.substring(verOffset+7); } // In Safari, the true version is after "Safari" or after "Version" else if ((verOffset=nAgt.indexOf("Safari"))!=-1) { browserName = "Safari"; fullVersion = nAgt.substring(verOffset+7); if ((verOffset=nAgt.indexOf("Version"))!=-1) fullVersion = nAgt.substring(verOffset+8); } // In Firefox, the true version is after "Firefox" else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) { browserName = "Firefox"; fullVersion = nAgt.substring(verOffset+8); } // In most other browsers, "name/version" is at the end of userAgent else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < (verOffset=nAgt.lastIndexOf('/')) ) { browserName = nAgt.substring(nameOffset,verOffset); fullVersion = nAgt.substring(verOffset+1); if (browserName.toLowerCase()==browserName.toUpperCase()) { browserName = navigator.appName; } } // trim the fullVersion string at semicolon/space if present if ((ix=fullVersion.indexOf(";"))!=-1) fullVersion=fullVersion.substring(0,ix); if ((ix=fullVersion.indexOf(" "))!=-1) fullVersion=fullVersion.substring(0,ix); majorVersion = parseInt(''+fullVersion,10); if (isNaN(majorVersion)) { fullVersion = ''+parseFloat(navigator.appVersion); majorVersion = parseInt(navigator.appVersion,10); } this.browser = { name: browserName, fullVersion: fullVersion, majorVersion: majorVersion, userAgent: navigator.userAgent }; }; this.parent( form, element, name ); if (element) { this.prev = element.value; } this.validate = 'Any'; this.mask = ''; this.required = false; this.formula = ''; this.key_Change = false; var doubleChange = false; //FUNCTIONS function IsUnsignedInteger(YourNumber){ var Template = /^d+$/; //Formato de numero entero sin signo return (Template.test(YourNumber)) ? 1 : 0; //Compara "YourNumber" con el formato "Template" y si coincidevuelve verdadero si no devuelve falso } function replaceAll( text, busca, reemplaza ){ while (text.toString().indexOf(busca) != -1){ text = text.toString().replace(busca,reemplaza); } return text; } function isNumberMask (mask){ for ( var key in mask){ if (mask[key]!='#'&&mask[key]!=','&&mask[key]!='.'&&typeof(mask[key])=='string'){ return false; } } return true; } //function renderNewValue(element, keyCode){ /*var myField = element; var myValue = myField.value; var cursorPos = 0; var csel; var newValue = ''; var csel = me.getCursorPosition(); var startPos = csel.selectionStart; var endPos = csel.selectionEnd; var newValue2; switch(keyCode){ case 8: if (startPos>0) { newValue = myValue.substring(0, startPos-1); newValue = newValue + myValue.substring(endPos, myField.value.length); if (mType !== 'text'){ newValue2 = G.toMask(newValue, me.mask, startPos); }else{ newValue2 = G.toMask(newValue, me.mask, startPos, 'normal'); } newValue = newValue2.result; } break; case 46: newValue = myValue.substring(0, startPos); newValue = newValue + myValue.substring(endPos+1, myField.value.length); if (mType !== 'text'){ newValue2 = G.toMask(newValue, me.mask, startPos); }else{ newValue2 = G.toMask(newValue, me.mask, startPos, 'normal'); } newValue = newValue2.result; break; } return {result: newValue, cursor: startPos};*/ //} //MEMBERS this.setContent = function(content) { me.element.value = ''; if (content.options) { if (content.options[0]) { me.element.value = content.options[0].value; } } }; //this.validateKey = function(event){ /* attributes = elementAttributesNS(element, 'pm'); if(me.element.readOnly) return true; me.prev = me.element.value; if (window.event) event=window.event; var keyCode= window.event ? event.keyCode : event.which ; me.mask = typeof(me.mask)==='undefined'?'':me.mask; if(me.mask=='yyyy-mm-dd'){ attributes.mask=attributes.mask.replace('%d','dd'); attributes.mask=attributes.mask.replace('%m','mm'); attributes.mask=attributes.mask.replace('%y','yy'); attributes.mask=attributes.mask.replace('%Y','yyyy'); attributes.mask=attributes.mask.replace('%H','mm'); attributes.mask=attributes.mask.replace('%M','mm'); attributes.mask=attributes.mask.replace('%S','mm'); me.mask=attributes.mask; } //alert(me.mask); if (me.mask !=='' ) { if ((keyCode < 48 || keyCode > 57) && (keyCode != 8 && keyCode != 0 && keyCode != 46)) return false; if((keyCode===118 || keyCode===86) && event.ctrlKey) return false; if (event.ctrlKey) return true; if (event.altKey) return true; if (event.shiftKey) return true; } if ((keyCode===0) ) if (event.keyCode===46) return true; else return true; if ( (keyCode===8)) return true; if (me.mask ==='') { if (me.validate == 'NodeName') { if (me.getCursorPos() == 0) { if ((keyCode >= 48) && (keyCode <= 57)) { return false; } } var k=new leimnud.module.validator({ valid :['Field'], key :event, lang :(typeof(me.language)!=='undefined')?me.language:"en" }); return k.result(); }else{ switch(me.validate){ case "Int": if ((keyCode > 47) && (keyCode < 58) || ( keyCode == 118 && event.ctrlKey)|| (keyCode == 120 && event.ctrlKey)) { return true; }else{ return false; } break; case "Alpha": if (keyCode==8) return true; patron =/[A-Za-z\sáéíóúäëïöüñçÇÑ�É�ÓÚÄË�ÖÜ]/; te = String.fromCharCode(keyCode); return patron.test(te); break; case "AlphaNum": if (keyCode==8) return true; patron =/[A-Za-z0-9\sáéíóúäëïöüñçÇÑ�É�ÓÚÄË�ÖÜ]/; te = String.fromCharCode(keyCode); return patron.test(te); break; default: var k=new leimnud.module.validator({ valid :[me.validate], key :event, lang :(typeof(me.language)!=='undefined')?me.language:"en" }); return k.result(); break; } } }else{ var csel = me.getCursorPosition(); var myValue = String.fromCharCode(keyCode); var startPos = csel.selectionStart; var endPos = csel.selectionEnd; var myField = me.element; var oldValue = myField.value; var newValue = ''; newValue = oldValue.substring(0, startPos); newValue = newValue + myValue; newValue = newValue + oldValue.substring(endPos, oldValue.length); startPos++; var newValue2; if (mType !== 'text'){ newValue2 = G.toMask(newValue, me.mask, startPos); }else{ newValue2 = G.toMask(newValue, me.mask, startPos, 'normal'); } //alert(newValue + ' -> ' + mType + ' -> ' + newValue2.result); //alert(newValue2.result); me.element.value = newValue2.result; //alert(me.element.value); me.setSelectionRange(newValue2.cursor, newValue2.cursor); if (me.element.fireEvent){ me.element.fireEvent("onchange"); }else{ var evObj = document.createEvent('HTMLEvents'); evObj.initEvent( 'change', true, true ); me.element.dispatchEvent(evObj); } return true; }*/ //}; this.putFormatNumber =function (evt) { /* if((typeof(evt)==="undefined" || evt===0) && me.mask!='' ){*/ // var numberSet=me.element.value.split('.'); // maskD = me.mask.split(';'); // maskL = (maskD.length >1)?maskD[1]:maskD[0]; // if (maskL.search(",")==-1){ // return false; // } // maskWithoutC =replaceAll(maskL,",",""); // maskWithoutC =replaceAll(maskWithoutC," ",""); // maskWithoutPto=replaceAll(maskWithoutC,".",""); // if(numberSet.length >=2){ // if(maskWithoutPto.substr( (maskWithoutPto.length -1) ,maskWithoutPto.length) =="%") // me.element.value = me.element.value+' '+maskWithoutPto.substr( (maskWithoutPto.length -1) ,maskWithoutPto.length); // return; // } // // maskElemnts = maskWithoutC.split('.'); // maskpartInt = maskElemnts[0].split(''); // numberwc = replaceAll(me.element.value,",", ""); // numberwc = replaceAll(numberwc,".", ""); // onlynumber = replaceAll(numberwc,".", ""); // onlynumber = replaceAll(numberwc," ", ""); // onlynumber = replaceAll(numberwc,"%", ""); // if(onlynumber=='') return false; // cd = parseInt(Math.log(onlynumber)/Math.LN10+1); // var auxnumber = onlynumber; // var cdaux=0; // while(auxnumber > 0){ // cdaux++; // auxnumber =parseInt(auxnumber / 10); // } // cd=cdaux; // // if (isNumberMask(maskpartInt)){ // if(cd < maskpartInt.length && cd >= 4 && cd !=3){ // var newNumber=''; // var cc=1; // while (onlynumber > 0){ // lastdigito = onlynumber % 10; // if (cc%3==0 && cd != cc){ // newNumber = ','+lastdigito.toString() + newNumber; // } else { // newNumber = lastdigito.toString() + newNumber; // } // onlynumber =parseInt(onlynumber / 10); // cc++; // } // if(maskWithoutPto.substr( (maskWithoutPto.length -1) ,maskWithoutPto.length) =="%") // me.element.value = newNumber+' '+maskWithoutPto.substr( (maskWithoutPto.length -1) ,maskWithoutPto.length); // else // me.element.value = newNumber; // }else{ // if(maskWithoutPto.substr( (maskWithoutPto.length -1) ,maskWithoutPto.length) =="%") // var spaceString; // if (me.element.value.substr( (me.element.value.length -1) ,me.element.value.length) == '%' ){ // spaceString =''; // me.element.value = onlynumber + spaceString + maskWithoutPto.substr( (maskWithoutPto.length -1) ,maskWithoutPto.length); // } else { // spaceString =' '; // me.element.value = onlynumber; // } // } // } //} }; //this.preValidateChange=function(event) { /*var oNewValue; var newValueR; me.putFormatNumber(event); if(me.element.readOnly) return true; if (me.mask ==='') return true; if (event.keyCode === 8){ oNewValue = renderNewValue(me.element,event.keyCode); newValueR = G.toMask(oNewValue.result, me.mask, oNewValue.cursor ); me.element.value=newValueR.result; me.setSelectionRange(oNewValue.cursor - 1, oNewValue.cursor - 1); if (me.element.fireEvent){ me.element.fireEvent("onchange"); }else{ var evObj = document.createEvent('HTMLEvents'); evObj.initEvent( 'change', true, true ); me.element.dispatchEvent(evObj); } return false; } if (event.keyCode === 46){ oNewValue = renderNewValue(me.element,event.keyCode); newValueR = G.toMask(oNewValue.result, me.mask, oNewValue.cursor ); me.element.value=newValueR.result; me.setSelectionRange(oNewValue.cursor, oNewValue.cursor); if (me.element.fireEvent){ me.element.fireEvent("onchange"); }else{ var evObj = document.createEvent('HTMLEvents'); evObj.initEvent( 'change', true, true ); me.element.dispatchEvent(evObj); } return false; } //alert(me.element.value); me.prev=me.element.value; return true;*/ //}; this.execFormula=function(event) { if( me.formula != ''){ leimnud.event.add(getField('faa'),'keypress',function(){ alert(getField('faa').value); }); } return false; }; /*this.validateChange=function(event) { /*if (me.mask ==='') return true; var sel=me.getSelectionRange(); var newValue2=G.cleanMask( me.element.value, me.mask, sel.selectionStart ); newValue2=G.toMask( newValue2.result, me.mask, newValue2.cursor); me.element.value = newValue2.result; me.setSelectionRange(newValue2.cursor, newValue2.cursor); return true;*/ //};*/ this.value = function() { return me.element.value; }; //Get Cursor Position this.getCursorPos = function () { var textElement=me.element; if (!document.selection) return textElement.selectionStart; //save off the current value to restore it later, var sOldText = textElement.value; //create a range object and save off it's text var objRange = document.selection.createRange(); var sOldRange = objRange.text; //set this string to a small string that will not normally be encountered var sWeirdString = '#%~'; //insert the weirdstring where the cursor is at objRange.text = sOldRange + sWeirdString; objRange.moveStart('character', (0 - sOldRange.length - sWeirdString.length)); //save off the new string with the weirdstring in it var sNewText = textElement.value; //set the actual text value back to how it was objRange.text = sOldRange; //look through the new string we saved off and find the location of //the weirdstring that was inserted and return that value for (i=0; i <= sNewText.length; i++) { var sTemp = sNewText.substring(i, i + sWeirdString.length); if (sTemp == sWeirdString) { var cursorPos = (i - sOldRange.length); return cursorPos; } } }; this.setSelectionRange = function(selectionStart, selectionEnd) { var input=me.element; if (input.createTextRange) { //IE var range = input.createTextRange(); range.collapse(true); range.moveEnd('character', selectionEnd); range.moveStart('character', selectionStart); range.select(); } else if (input.setSelectionRange) { //Firefox and others input.focus(); input.setSelectionRange(selectionStart, selectionEnd); } }; //FUNCTION MAYBE IT'S DEPRECATED /*this.getSelectionRange = function() { if (document.selection) { var textElement=me.element; var sOldText = textElement.value; var objRange = document.selection.createRange(); var sOldRange = objRange.text; var sWeirdString = '#%~'; objRange.text = sOldRange + sWeirdString; objRange.moveStart('character', (0 - sOldRange.length - sWeirdString.length)); var sNewText = textElement.value; objRange.text = sOldRange; for (i=0; i <= sNewText.length; i++) { var sTemp = sNewText.substring(i, i + sWeirdString.length); if (sTemp == sWeirdString) { var cursorPos = (i - sOldRange.length); return { selectionStart: cursorPos, selectionEnd: cursorPos+sOldRange.length }; } } }else{ var sel={ selectionStart: 0, selectionEnd: 0 }; sel.selectionStart = me.element.selectionStart; sel.selectionEnd = me.element.selectionEnd; return sel; } }; */ //FUNCTION MAYBE IT'S DEPRECATED /*this.getCursorP =function (field) { if (document.selection) { field.focus(); var oSel = document.selection.createRange(); oSel.moveStart('character', -field.value.length); field.selectionEnd = oSel.text.length; oSel.setEndPoint('EndToStart', document.selection.createRange() ); field.selectionStart = oSel.text.length; } return {selectionStart: field.selectionStart, selectionEnd: field.selectionEnd}; };*/ //Gets cursor position this.getCursorPosition = function(){ if(navigator.appName == 'Microsoft Internet Explorer'){ var field = me.element; if (document.selection) { field.focus(); var oSel = document.selection.createRange(); oSel.moveStart('character', -field.value.length); field.selectionEnd = oSel.text.length; oSel.setEndPoint('EndToStart', document.selection.createRange() ); field.selectionStart = oSel.text.length; } return {selectionStart: field.selectionStart, selectionEnd: field.selectionEnd}; }else{ if (document.selection) { var textElement=me.element; var sOldText = textElement.value; var objRange = document.selection.createRange(); var sOldRange = objRange.text; var sWeirdString = '#%~'; objRange.text = sOldRange + sWeirdString; objRange.moveStart('character', (0 - sOldRange.length - sWeirdString.length)); var sNewText = textElement.value; objRange.text = sOldRange; for (i=0; i <= sNewText.length; i++) { var sTemp = sNewText.substring(i, i + sWeirdString.length); if (sTemp == sWeirdString) { var cursorPos = (i - sOldRange.length); return { selectionStart: cursorPos, selectionEnd: cursorPos+sOldRange.length }; } } }else{ var sel={ selectionStart: 0, selectionEnd: 0 }; sel.selectionStart = me.element.selectionStart; sel.selectionEnd = me.element.selectionEnd; return sel; } } }; this.removeMask = function(){ value = me.element.value; cursor = me.getCursorPosition(); chars = value.split(''); newValue = ''; newCont = 0; newCursor = 0; for(c=0; c < chars.length; c++){ switch(chars[c]){ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case me.comma_separator: newValue += chars[c]; newCont++; if (c + 1 == cursor.selectionStart){ newCursor = newCont; } break; case '-': if (me.validate == 'Real'){ newValue += chars[c]; newCont++; if (c + 1 == cursor.selectionStart){ newCursor = newCont; } } break; } } if (cursor.selectionStart != cursor.selectionEnd){ return {result: newValue, cursor: cursor}; } else{ return {result: newValue, cursor: {selectionStart: newCursor, selectionEnd: newCursor}}; } }; this.replaceMask = function(value, cursor, mask, type, comma){ switch(type){ case 'currency': case 'percentage': dir = 'reverse'; break; default: dir = 'forward'; break; } return G.ApplyMask(value, mask, cursor, dir, comma); }; this.replaceMasks= function(newValue, newCursor){ masks = me.mask; aMasks = masks.split(';'); aResults = []; for(m=0; m < aMasks.length; m++){ mask = aMasks[m]; type = me.mType; comma_sep = me.comma_separator; aResults.push(me.replaceMask(newValue, newCursor, mask, type, comma_sep)); } minIndex = 0; minValue = aResults[0].result; if (aResults.length > 1){ for(i=1; i < aResults.length; i++){ if (aResults[i].result < minValue){ minValue = aResults[i].result; minIndex = i; } } } return aResults[minIndex]; }; this.getCleanMask = function(){ aMask = me.mask.split(''); maskOut = ''; for(i=0; i < aMask.length; i++){ if (me.mType == 'currency' || me.mType == 'percentage'){ switch(aMask[i]){ case '0': case '#': maskOut += aMask[i]; break; case me.comma_separator: maskOut += '_'; break; } } else{ switch(aMask[i]){ case '0': case '#': case 'd': case 'm': case 'y': case 'Y': maskOut += aMask[i]; break; } } } return maskOut; } this.applyMask = function(keyCode){ if (me.mask != ''){ dataWOMask = me.removeMask(); //alert(dataWOMask.result + ', ' + dataWOMask.cursor.selectionStart); currentValue = dataWOMask.result; currentSel = dataWOMask.cursor; cursorStart = currentSel.selectionStart; cursorEnd = currentSel.selectionEnd; action = 'mask'; swPeriod = false; switch(keyCode){ case 0: action = 'none'; break; case 8: newValue = currentValue.substring(0, cursorStart - 1); newValue += currentValue.substring(cursorEnd, currentValue.length); newCursor = cursorStart - 1; //alert('aaa' + newValue + ' , ' + newCursor ); break; case 46: newValue = currentValue.substring(0, cursorStart); newValue += currentValue.substring(cursorEnd + 1, currentValue.length); newCursor = cursorStart; break; case 256: case 44: swPeriod = true; newValue = currentValue.substring(0, cursorStart); if (keyCode == 256) newValue += '.'; else newValue += ','; newValue += currentValue.substring(cursorEnd, currentValue.length); //alert(newValue); newCursor = cursorStart + 1; break; case 35: case 36: case 37: case 38: case 39: case 40: newValue = currentValue; switch(keyCode){ case 36:newCursor = 0;break; case 35:newCursor = currentValue.length;break; case 37:newCursor = cursorStart - 1;break; case 39:newCursor = cursorStart + 1;break; } action = 'move'; break; default: newKey = String.fromCharCode(keyCode); newValue = currentValue.substring(0, cursorStart); newValue += newKey; newValue += currentValue.substring(cursorEnd, currentValue.length); newCursor = cursorStart + 1; break; } if (newCursor < 0) newCursor = 0; if (keyCode != 8 && keyCode != 46 && keyCode != 35 && keyCode != 36 && keyCode != 37 && keyCode != 39){ testData = dataWOMask.result; tamData = testData.length; cleanMask = me.getCleanMask(); tamMask = cleanMask.length; sw = false; if (testData.indexOf(me.comma_separator) == -1){ aux = cleanMask.split('_'); tamMask = aux[0].length; sw = true; } if (tamData >= tamMask){ if (sw && !swPeriod && testData.indexOf(me.comma_separator) == -1){ action = 'none'; } if (!sw) action = 'none'; } } switch(action){ case 'mask': case 'move': dataNewMask = me.replaceMasks(newValue, newCursor); me.element.value = dataNewMask.result; me.setSelectionRange(dataNewMask.cursor,dataNewMask.cursor); break; //case 'move': //alert(newCursor); //me.setSelectionRange(newCursor,newCursor); //break; } } else{ currentValue = me.element.value; currentSel = me.getCursorPosition(); cursorStart = currentSel.selectionStart; cursorEnd = currentSel.selectionEnd; switch(keyCode){ case 8: newValue = currentValue.substring(0, cursorStart - 1); newValue += currentValue.substring(cursorEnd, currentValue.length); newCursor = cursorStart - 1; break; case 46: newValue = currentValue.substring(0, cursorStart); newValue += currentValue.substring(cursorEnd + 1, currentValue.length); newCursor = cursorStart; break; case 256: newValue = currentValue.substring(0, cursorStart); newValue += '.'; newValue += currentValue.substring(cursorEnd, currentValue.length); newCursor = cursorStart + 1; break; case 35: case 36: case 37: case 38: case 39: case 40: newValue = currentValue; switch(keyCode){ case 36:newCursor = 0;break; case 35:newCursor = currentValue.length;break; case 37:newCursor = cursorStart - 1;break; case 39:newCursor = cursorStart + 1;break; } break; default: newKey = String.fromCharCode(keyCode); newValue = currentValue.substring(0, cursorStart); newValue += newKey; newValue += currentValue.substring(cursorEnd, currentValue.length); newCursor = cursorStart + 1; break; } if (newCursor < 0) newCursor = 0; me.element.value = newValue; me.setSelectionRange(newCursor,newCursor); } //Launch OnChange Event /*if (me.element.fireEvent){ me.element.fireEvent("onchange"); }else{ var evObj = document.createEvent('HTMLEvents'); evObj.initEvent( 'change', true, true ); me.element.dispatchEvent(evObj); }*/ }; this.sendOnChange = function(){ if (me.element.fireEvent){ me.element.fireEvent("onchange"); }else{ var evObj = document.createEvent('HTMLEvents'); evObj.initEvent( 'change', true, true ); me.element.dispatchEvent(evObj); } }; this.handleKeyDown = function(event){ //THIS FUNCTION HANDLE BACKSPACE AND DELETE KEYS if (me.validate == 'Any' && me.mask == '') return true; pressKey = event.keyCode; switch(pressKey){ case 8: case 46: //BACKSPACE OR DELETE case 35: case 36: //HOME OR END case 37: case 38: case 39: case 40: // ARROW KEYS me.applyMask(pressKey); if (pressKey == 8 || pressKey == 46) me.sendOnChange(); me.checkBrowser(); if (me.browser.name == 'Chrome'){ event.returnValue = false; } else{ return false; } break; } return true; }; this.handleKeyPress = function(event){ if (me.validate == 'Any' && me.mask == '') return true; //THIS FUNCTION HANDLE ALL KEYS EXCEPT BACKSPACE AND DELETE keyCode = event.keyCode; switch(keyCode){ case 9: case 13: return true; break; } if (event.altKey) return true; if (event.ctrlKey) return true; if (event.shiftKey) return true; me.checkBrowser(); if ((me.browser.name == 'Firefox') && (keyCode == 8 || keyCode == 46)){ if (me.browser.name == 'Chrome'){ event.returnValue = false; } else{ return false; } } else{ pressKey = window.event ? event.keyCode : event.which; if (me.mType == 'date') me.validate = 'Int'; keyValid = true; updateOnChange = true; switch(me.validate){ case 'Any': keyValid = true; break; case 'Int': patron = /[0-9]/; key = String.fromCharCode(pressKey); keyValid = patron.test(key); break; case 'Real': patron = /[0-9]/; key = String.fromCharCode(pressKey); keyValid = patron.test(key); keyValid = keyValid || (pressKey == 45); if (me.comma_separator == '.'){ if (me.element.value.indexOf('.')==-1){ keyValid = keyValid || (pressKey == 46); } } else{ if (me.element.value.indexOf(',')==-1){ keyValid = keyValid || (pressKey == 44); } } break; case 'Alpha': patron =/[a-zA-Z]/; // \sáéíóúäëïöüñçÇÑ�É�ÓÚÄË�ÖÜ]/; key = String.fromCharCode(pressKey); keyValid = patron.test(key); break; case 'AlphaNum': patron =/[a-zA-Z0-9\sáéíóúäëïöüñçÇÑ�É�ÓÚÄË�ÖÜ]/; key = String.fromCharCode(pressKey); keyValid = patron.test(key); break; case 'NodeName': if (me.getCursorPos() == 0) { updateOnChange = false; if ((pressKey >= 48) && (pressKey <= 57)) { keyValid = false; break; } } var k=new leimnud.module.validator({ valid :['Field'], key :event, lang :(typeof(me.language)!=='undefined')?me.language:"en" }); keyValid = k.result(); break; default: var k = new leimnud.module.validator({ valid :[me.validate], key :event, lang :(typeof(me.language)!=='undefined')?me.language:"en" }); keyValid = k.result(); break; } if (keyValid){ //APPLY MASK if (pressKey == 46){ me.applyMask(256); //This code send [.] period to the mask } else{ me.applyMask(pressKey); } if (updateOnChange) me.sendOnChange(); if (me.browser.name == 'Chrome'){ event.returnValue = false; } else{ return false; } }else{ if (me.browser.name == 'Chrome'){ event.returnValue = false; } else{ return false; } } } }; if(this.element) { this.element.onblur = function(event) { var evt = event || window.event; var keyPressed = evt.which || evt.keyCode; me.putFormatNumber(keyPressed); if(this.validate=="Email") { //var pat=/^[\w\_\-\.çñ]{2,255}@[\w\_\-]{2,255}\.[a-z]{1,3}\.?[a-z]{0,3}$/; var pat=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$/; if(!pat.test(this.element.value)) { //old|if(this.required=="0"&&this.element.value=="") { if(this.element.value=="") { this.element.className="module_app_input___gray"; return; } else { this.element.className=this.element.className.split(" ")[0]+" FormFieldInvalid"; } } else { this.element.className=this.element.className.split(" ")[0]+" FormFieldValid"; } } if (this.strTo) { switch (this.strTo){ case 'UPPER': this.element.value = this.element.value.toUpperCase(); break; case 'LOWER': this.element.value = this.element.value.toLowerCase(); break; } } if (this.validate == 'NodeName') { var pat = /^[a-z\_](.)[a-z\d\_]{1,255}$/i; if(!pat.test(this.element.value)) { this.element.value = '_' + this.element.value; } } }.extend(this); } if (!element) return; if (!window.event){ //THIS ASSIGN FUNCTIONS FOR FIREFOX/MOZILLA this.element.onkeydown = this.handleKeyDown; this.element.onkeypress = this.handleKeyPress; this.element.onchange = this.updateDepententFields; //this.element.onblur = this.handleOnChange; }else{ //THIS ASSIGN FUNCTIONS FOR IE/CHROME leimnud.event.add(this.element,'keydown',this.handleKeyDown); leimnud.event.add(this.element,'keypress',this.handleKeyPress); leimnud.event.add(this.element,'change',this.updateDepententFields); } //leimnud.event.add(this.element,'change',this.updateDepententFields); }; G_Text.prototype=new G_Field(); function G_Percentage( form, element, name ) { var me=this; this.parent = G_Text; this.parent( form, element, name); this.validate = 'Int'; this.mType = 'percentage'; this.mask= '###.##'; this.comma_separator = "."; } G_Percentage.prototype=new G_Field(); function G_Currency( form, element, name ) { var me=this; this.parent = G_Text; this.parent( form, element, name); this.validate = 'Int'; this.mType = 'currency'; this.mask= '_###,###,###,###,###;###,###,###,###,###.00'; this.comma_separator = "."; } G_Currency.prototype=new G_Field(); function G_TextArea( form, element, name ) { var me=this; this.parent = G_Text; this.parent( form, element, name ); this.validate = 'Any'; this.mask= ''; } G_TextArea.prototype=new G_Field(); function G_Date( form, element, name ) { var me=this; this.parent = G_Text; this.parent( form, element, name ); this.mType = 'date'; this.mask= 'dd-mm-yyyy'; } G_Date.prototype=new G_Field(); function G() { /*MASK*/ var reserved=['_',';','#','.','0','d','m','y','-']; //Invert String function invertir(num) { var num0=''; num0=num; num=""; for(r=num0.length-1;r>=0;r--) num+= num0.substr(r,1); return num; } function __toMask(num, mask, cursor) { var inv=false; if (mask.substr(0,1)==='_') { mask=mask.substr(1); inv=true; } var re; if (inv) { mask=invertir(mask); num=invertir(num); } var minAdd=-1; var minLoss=-1; var newCursorPosition=cursor; var betterOut=""; for(var r0=0;r0< mask.length; r0++){ var out="";var j=0; var loss=0; var add=0; var cursorPosition=cursor;var i=-1;var dayPosition=0;var mounthPosition=0; var dayAnalized ='';var mounthAnalized =''; var blocks={}; //Declares empty object for(var r=0;r< r0 ;r++) { var e=false; var m=mask.substr(r,1); __parseMask(); } i=0; for(r=r0;r< mask.length;r++) { j++; if (j>200) break; e=num.substr(i,1); e=(e==='')?false:e; m=mask.substr(r,1); __parseMask(); } var io=num.length - i; io=(io<0)?0:io; loss+=io; loss=loss+add/1000; //var_dump(loss); if (loss===0) { betterOut=out; minLoss=0; newCursorPosition=cursorPosition; break; } if ((minLoss===-1)||(loss< minLoss)) { minLoss=loss; betterOut=out; newCursorPosition=cursorPosition; } //echo('min:');var_dump($minLoss); } // var_dump($minLoss); out=betterOut; if (inv) { out=invertir(out); mask=invertir(mask); } return { 'result':out, 'cursor':newCursorPosition, 'value':minLoss, 'mask':mask }; function searchBlock( where , what ) { for(var r=0; r < where.length ; r++ ) { if (where[r].key === what) return where[r]; } } function __parseMask() { var ok=true; switch(false) { case m==='d': dayAnalized=''; break; case m==='m': mounthAnalized=''; break; default: } if ( e!==false ) { if (typeof(blocks[m])==='undefined') blocks[m] = e; else blocks[m] += e; } switch(m) { case '0': if (e===false) { out+='0'; add++; break; } case 'y': case '#': if (e===false) { out+=''; break; } //Use direct comparition to increse speed of processing if ((e==='0')||(e==='1')||(e==='2')||(e==='3')||(e==='4')||(e==='5')||(e==='6')||(e==='7')||(e==='8')||(e==='9')||(e==='-')) { out+=e; i++; } else { //loss loss++; i++; r--; } break; case '(': if (e===false) { out+=''; break; } out+=m; if (i<cursor){ cursorPosition++; } break; case 'd': if (e===false) { out+=''; break; } if ((e==='0')||(e==='1')||(e==='2')||(e==='3')||(e==='4')||(e==='5')||(e==='6')||(e==='7')||(e==='8')||(e==='9')) ok=true; else ok=false; //if (ok) if (dayPosition===0) if (parseInt(e)>3) ok=false //dayPosition=(dayPosition+1) | 1; if (ok) dayAnalized = dayAnalized + e; if ((ok) && (parseInt(dayAnalized)>31)) ok = false; if (ok) { out+=e; i++; } else { //loss loss++; i++; r--; } break; case 'm': if (e===false) { out+=''; break; } if ((e==='0')||(e==='1')||(e==='2')||(e==='3')||(e==='4')||(e==='5')||(e==='6')||(e==='7')||(e==='8')||(e==='9')) ok=true; else ok=false; if (ok) mounthAnalized = mounthAnalized + e; if ((ok) && (parseInt(mounthAnalized)>12)) ok=false; if (ok) { out+=e; i++; } else { //loss loss++; i++; r--; } break; default: if (e===false) { out+=''; break; } if (e===m) { out+=e; i++; }else { //if (m==='.') alert(i.toString() +'.'+ cursor.toString()); out+=m; /////here was krlos add++; if (i<cursor){ cursorPosition++; }; /*if(e!==false && m==="." && m!=="," ){ //alert(m) //out+=m; //alert(m) break }*/ //alert(m+'\n'+mask+'\n'+out+'\n'+num) } /*if(m!='-'){ out+=m;} else {out+=String.fromCharCode(45);} add++;if (i<cursor){cursorPosition++;};*/ } } } } //Get only numbers including decimal separator function _getOnlyNumbers(num, _DEC){ var _num = ''; _aNum = num.split(''); for (var d=0; d < _aNum.length; d++){ switch(_aNum[d]){ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case _DEC: _num = _num + _aNum[d]; break; } } return _num; } //Get only mask characters can be replaced by digits. function _getOnlyMask(mask, _DEC){ var _mask=''; _aMask = mask.split(''); for (var d=0; d < _aMask.length; d++){ switch(_aMask[d]){ case '0': case '#': case 'd': case 'm': case 'y': case '_': case _DEC: _mask += _aMask[d]; break; } } return _mask; } //Check if a new digit can be added to this mask function _checkNumber(num, mask){ var __DECIMAL_SEP = '.'; var aNum = _getOnlyNumbers(num, __DECIMAL_SEP); var _outM = aNum; var aMask = _getOnlyMask(mask, __DECIMAL_SEP); if (aMask.indexOf(__DECIMAL_SEP+'0')>0){ //Mask has .0 eMask = aMask.replace(__DECIMAL_SEP, ''); eNum = aNum.replace(__DECIMAL_SEP, ''); if (eNum.length > eMask.length){ _outM = aNum.substring(0, eMask.length +1); } }else{ //Mask hasn't .0 if (aMask.indexOf(__DECIMAL_SEP)>0){ // Mask contains decimal separator iMask = aMask.split(__DECIMAL_SEP); if (aNum.indexOf(__DECIMAL_SEP)>0){ //Number has decimal separator iNum = aNum.split(__DECIMAL_SEP); if (iNum[1].length > iMask[1].length){ _outM = iNum[0] + __DECIMAL_SEP + iNum[1].substr(0,iMask[1].length); }else{ if (iNum[0].length > iMask[0].length){ _outM = iNum[0].substr(0, iMask[0].length) + __DECIMAL_SEP + iNum[1]; } } }else{ //Number has not decimal separator if (aNum.length > iMask[0].length){ _outM = aNum.substr(0, iMask[0].length); } } }else{ //Mask does not contain decimal separator if (aNum.indexOf(__DECIMAL_SEP)>0){ iNum = aNum.split(__DECIMAL_SEP); if (iNum[0].length > aMask.length){ _outM = iNum[0].substr(0,aMask.length); } }else{ if (aNum.length > aMask.length){ _outM = aNum.substr(0,aMask.length); } } } } //alert(_outM); return _outM; } //Apply a mask to a number this.ApplyMask = function(num, mask, cursor, dir, comma_sep){ myOut = ''; myCursor = cursor; if (num.length == 0) return {result: '', cursor: 0}; switch(dir){ case 'forward': iMask = mask.split(''); value = _getOnlyNumbers(num,''); iNum = value.split(''); for(e=0; e < iMask.length && iNum.length > 0; e++){ switch(iMask[e]){ case '#': case '0': case 'd': case 'm': case 'y': case 'Y': if (iNum.length > 0){ key = iNum.shift(); myOut += key; } break; default: myOut += iMask[e]; if (e < myCursor) myCursor++; break; } } break; case 'reverse': var __DECIMAL_SEP = comma_sep; var osize = num.length; num = _getOnlyNumbers(num,__DECIMAL_SEP); if (num.length == 0) return {result: '', cursor: 0}; var iNum = invertir(num); var iMask = invertir(mask); if (iMask.indexOf('0'+__DECIMAL_SEP)> 0){ //Mask has .0 and will applied complete aMask = iMask; iNum = _getOnlyNumbers(iNum,'*'); aNum = iNum; eMask = aMask.split(''); eNum = aNum.split(''); _cout = ''; for (e=0; e < eMask.length; e++){ switch(eMask[e]){ case '#': case '0': if (eNum.length > 0){ key = eNum.shift(); _cout += key; } break; case '.': case ',': if (eMask[e] != __DECIMAL_SEP){ if (eNum.length > 0){ _cout += eMask[e]; } }else{ _cout += eMask[e]; } break; default: _cout += eMask[e]; break; } } myOut = _cout; }else{ sw_d = false; aMask = iMask.split(__DECIMAL_SEP); aNum = iNum.split(__DECIMAL_SEP); if (aMask.length==1){ dMask = ''; cMask = aMask[0]; }else{ dMask = aMask[0]; cMask = aMask[1]; } if (aNum.length == 1){ dNum = ''; cNum = aNum[0]; }else{ sw_d = true; dNum = aNum[0]; cNum = aNum[1]; } _dout = ''; pMask = dMask.split(''); pNum = dNum.split(''); for (p=0; p < pMask.length; p++){ switch(pMask[p]){ case '#': case '0': if (pNum.length > 0){ key = pNum.shift(); _dout += key; } break; case ',': case '.': if (pMask[p] != __DECIMAL_SEP){ if (pNum.length > 0){ _dout += pMask[p]; } }else{ } break; default: _dout += pMask[p]; break; } } _cout = ''; sw_c = false; pMask = cMask.split(''); pNum = cNum.split(''); for (p=0; p < pMask.length; p++){ switch(pMask[p]){ case '#': case '0': case 'd': case 'm': case 'y': if (pNum.length > 0){ key = pNum.shift(); _cout += key; sw_c = true; } break; case ',': case '.': if (pMask[p] != __DECIMAL_SEP){ if (pNum.length > 0){ _cout += pMask[p]; } } break; default: _cout += pMask[p]; } } if (sw_c && sw_d){ myOut = _dout + __DECIMAL_SEP + _cout; }else{ myOut = _dout + _cout; } } myOut = invertir(myOut); tmpCursor = 0; aOut = myOut.split(''); if (cursor == 0){ for(l=0; l < aOut.length; l++){ switch(aOut[l]){ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case __DECIMAL_SEP: myCursor = l; l = aOut.length; break; } } } else if(cursor == num.length){ for(l=0; l < aOut.length; l++){ switch(aOut[l]){ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case __DECIMAL_SEP: last = l; break; } } myCursor = last + 1; } else{ aNum = num.split(''); offset = 0; aNewNum = myOut.split(''); for (a = 0; a < cursor; a++){ notFinded = false; while (aNum[a] != aNewNum[a + offset] && !notFinded){ offset++; if (a + offset > aNewNum.length){ offset = -1; notFinded = true; } } } myCursor = cursor + offset; } break; } //myCursor += 1; /*if (dir){ var osize = num.length; _out = ''; num = _checkNumber(num, mask); num = _getOnlyNumbers(num,''); if (num.length == 0) return {result: '', cursor: 0}; iNum = num; iMask = mask; eMask = iMask.split(''); eNum = iNum.split(''); for (e=0; e < eMask.length; e++){ switch(eMask[e]){ case '#': case '0': case 'd': case 'm': case 'y': case 'Y': if (eNum.length > 0){ key = eNum.shift(); _out += key; } break; default: _out += eMask[e]; break; } } }else{ var __DECIMAL_SEP = comma_sep; var osize = num.length; num = _checkNumber(num, mask); num = _getOnlyNumbers(num,__DECIMAL_SEP); if (num.length == 0) return {result: '', cursor: 0}; var iNum = invertir(num); var iMask = invertir(mask); if (iMask.indexOf('0'+__DECIMAL_SEP)> 0){ //Mask has .0 and will applied complete aMask = iMask; iNum = _getOnlyNumbers(iNum,'*'); aNum = iNum; eMask = aMask.split(''); eNum = aNum.split(''); _cout = ''; for (e=0; e < eMask.length; e++){ switch(eMask[e]){ case '#': case '0': case 'd': case 'm': case 'y': if (eNum.length > 0){ key = eNum.shift(); _cout += key; } break; case '.': case ',': if (eMask[e] != __DECIMAL_SEP){ if (eNum.length > 0){ _cout += eMask[e]; } }else{ _cout += eMask[e]; } break; default: _cout += eMask[e]; break; } } _out = _cout; }else{ sw_d = false; aMask = iMask.split(__DECIMAL_SEP); aNum = iNum.split(__DECIMAL_SEP); if (aMask.length==1){ dMask = ''; cMask = aMask[0]; }else{ dMask = aMask[0]; cMask = aMask[1]; } if (aNum.length == 1){ dNum = ''; cNum = aNum[0]; }else{ sw_d = true; dNum = aNum[0]; cNum = aNum[1]; } _dout = ''; pMask = dMask.split(''); pNum = dNum.split(''); for (p=0; p < pMask.length; p++){ switch(pMask[p]){ case '#': case '0': if (pNum.length > 0){ key = pNum.shift(); _dout += key; } break; case ',': case '.': if (pMask[p] != __DECIMAL_SEP){ if (pNum.length > 0){ _dout += pMask[p]; } }else{ } break; default: _dout += pMask[p]; break; } } _cout = ''; sw_c = false; pMask = cMask.split(''); pNum = cNum.split(''); for (p=0; p < pMask.length; p++){ switch(pMask[p]){ case '#': case '0': case 'd': case 'm': case 'y': if (pNum.length > 0){ key = pNum.shift(); _cout += key; sw_c = true; } break; case ',': case '.': if (pMask[p] != __DECIMAL_SEP){ if (pNum.length > 0){ _cout += pMask[p]; } } break; default: _cout += pMask[p]; } } if (sw_c && sw_d){ _out = _dout + __DECIMAL_SEP + _cout; }else{ _out = _dout + _cout; } } _out = invertir(_out); } if (_out.length > osize){ cursor = cursor + (_out.length - osize); }*/ return { 'result': myOut, 'cursor': myCursor }; }; //Manage Multiple Mask and Integer/Real Number restrictions this.toMask = function(num, mask, cursor, direction){ if (mask==='') return { 'result': new String(num), 'cursor': cursor }; num = new String(num); var result = []; var subMasks=mask.split(';'); for(var r=0; r<subMasks.length; r++) { typedate = mask.indexOf("#"); //if typedate=='0' is current, else typedate=='-1' is date if ((direction == 'normal')&&(typedate=='0')) result[r]=__toMask(num, subMasks[r], cursor); else result[r]=_ApplyMask(num, subMasks[r], cursor, direction); } var betterResult=0; for(r=1; r<subMasks.length; r++) { if (result[r].value<result[betterResult].value) betterResult=r; } return result[betterResult]; }; //Gets number without mask this.getValue = function(masked_num){ var __DECIMAL_SEP = '.'; var xNum = masked_num.split(''); _num = ''; for (u=0; u < xNum.length; u++){ switch(xNum[u]){ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case __DECIMAL_SEP: _num += xNum[u]; break; } } return _num; }; //DEPRECATED this.toMask2 = function (num, mask, cursor) { if (mask==='') return { 'result':new String(num), 'cursor':cursor }; var subMasks=mask.split(';'); var result = []; num = new String(num); for(var r=0; r<subMasks.length; r++) { result[r]=__toMask(num, subMasks[r], cursor); } var betterResult=0; for(r=1; r<subMasks.length; r++) { if (result[r].value<result[betterResult].value) betterResult=r; } return result[betterResult]; }; //DEPRECATED this.cleanMask = function (num, mask, cursor) { mask = typeof(mask)==='undefined'?'':mask; if (mask==='') return { 'result':new String(num), 'cursor':cursor }; var a,r,others=[]; num = new String(num); //alert(oDebug.var_dump(num)); if (typeof(cursor)==='undefined') cursor=0; a = num.substr(0,cursor); for(r=0; r<reserved.length; r++) mask=mask.split(reserved[r]).join(''); while(mask.length>0) { r=others.length; others[r] = mask.substr(0,1); mask= mask.split(others[r]).join(''); num = num.split(others[r]).join(''); cursor -= a.split(others[r]).length-1;//alert(cursor) } return { 'result':num, 'cursor':cursor }; }; this.getId=function(element){ var re=/(\[(\w+)\])+/; var res=re.exec(element.id); return res?res[2]:element.id; }; this.getObject=function(element){ var objId=G.getId(element); switch (element.tagName){ case 'FORM': return eval('form_' + objId); break; default: if (element.form) { var formId=G.getId(element.form); return eval('form_'+objId+'.getElementByName("'+objId+'")'); } } }; /*BLINK EFECT*/ this.blinked=[]; this.blinkedt0=[]; this.autoFirstField=true; this.pi=Math.atan(1)*4; this.highLight = function(element){ var newdiv = $dce('div'); newdiv.style.position="absolute"; newdiv.style.display="inline"; newdiv.style.height=element.clientHeight+2; newdiv.style.width=element.clientWidth+2; newdiv.style.background = "#FF5555"; element.style.backgroundColor='#FFCACA'; element.parentNode.insertBefore(newdiv,element); G.doBlinkEfect(newdiv,1000); }; this.setOpacity=function(e,o){ e.style.filter='alpha'; if (e.filters) { e.filters['alpha'].opacity=o*100; } else { e.style.opacity=o; } }; this.doBlinkEfect=function(div,T){ var f=1/T; var j=G.blinked.length; G.blinked[j]=div; G.blinkedt0[j]=(new Date()).getTime(); for(var i=1;i<=20;i++){ setTimeout("G.setOpacity(G.blinked["+j+"],0.3-0.3*Math.cos(2*G.pi*((new Date()).getTime()-G.blinkedt0["+j+"])*"+f+"));",T/20*i); } setTimeout("G.blinked["+j+"].parentNode.removeChild(G.blinked["+j+"]);G.blinked["+j+"]=null;",T/20*i); }; var alertPanel; this.alert=function(html, title , width, height, autoSize, modal, showModalColor, runScripts) { html='<div>'+html+'</div>'; width = (width)?width:300; height = (height)?height:200; autoSize = (showModalColor===false)?false:true; modal = (modal===false)?false:true; showModalColor = (showModalColor===true)?true:false; var alertPanel = new leimnud.module.panel(); alertPanel.options = { size:{ w:width, h:height }, position:{ center:true }, title: title, theme: "processmaker", control: { close :true, roll :false, drag :true, resize :true }, fx: { blinkToFront:true, opacity :true, drag:true, modal: modal } }; if(showModalColor===false) { alertPanel.styles.fx.opacityModal.Static='0'; } alertPanel.make(); alertPanel.addContent(html); if(runScripts) { var myScripts=alertPanel.elements.content.getElementsByTagName('SCRIPT'); var sMyScripts=[]; for(var rr=0; rr<myScripts.length ; rr++) sMyScripts.push(myScripts[rr].innerHTML); for(var rr=0; rr<myScripts.length ; rr++){ try { if (sMyScripts[rr]!=='') if (window.execScript) window.execScript( sMyScripts[rr], 'javascript' ); else window.setTimeout( sMyScripts[rr], 0 ); } catch (e) { alert(e.description); } } } /* Autosize of panels, to fill only the first child of the * rendered page (take note) */ var panelNonContentHeight = 44; var panelNonContentWidth = 28; try { if (autoSize) { var newW=alertPanel.elements.content.childNodes[0].clientWidth+panelNonContentWidth; var newH=alertPanel.elements.content.childNodes[0].clientHeight+panelNonContentHeight; alertPanel.resize({ w:((newW<width)?width:newW) }); alertPanel.resize({ h:((newH<height)?height:newH) }); } } catch (e) { alert(var_dump(e)); } delete newdiv; delete myScripts; alertPanel.command(alertPanel.loader.hide); }; } var G = new G(); /* PACKAGE : DEBUG */ function G_Debugger() { this.var_dump = function(obj) { var o,dump; dump=''; if (typeof(obj)=='object') for(o in obj) { dump+='<b>'+o+'</b>:'+obj[o]+"<br>\n"; } else dump=obj; debugDiv = document.getElementById('debug'); if (debugDiv) debugDiv.innerHTML=dump; return dump; }; } var oDebug = new G_Debugger(); /* PACKAGE : date field */ var datePickerPanel; function showDatePicker(ev, formId, idName, value, min, max ) { var coor = leimnud.dom.mouse(ev); var coorx = ( coor.x - 50 ); var coory = ( coor.y - 40 ); datePickerPanel=new leimnud.module.panel(); datePickerPanel.options={ size:{ w:275, h:240 }, position:{ x:coorx, y:coory }, title:"Date Picker", theme:"panel", control:{ close:true, drag:true }, fx:{ modal:true } }; datePickerPanel.setStyle={ containerWindow:{ borderWidth:0 } }; datePickerPanel.make(); datePickerPanel.idName = idName; datePickerPanel.formId = formId; var sUrl = "/controls/calendar.php?v="+value+"&d="+value+"&min="+min+"&max="+max; var r = new leimnud.module.rpc.xmlhttp({ url: sUrl }); r.callback=leimnud.closure({ Function:function(rpc){ datePickerPanel.addContent(rpc.xmlhttp.responseText); }, args:r }); r.make(); } function moveDatePicker( n_datetime ) { var dtmin_value = document.getElementById ( 'dtmin_value' ); var dtmax_value = document.getElementById ( 'dtmax_value' ); var sUrl = "/controls/calendar.php?d="+n_datetime + '&min='+dtmin_value.value + '&max='+dtmax_value.value; var r = new leimnud.module.rpc.xmlhttp({ url:sUrl }); r.callback=leimnud.closure({ Function:function(rpc){ datePickerPanel.clearContent(); datePickerPanel.addContent(rpc.xmlhttp.responseText); }, args:r }); r.make(); } function selectDate( day ) { var obj = document.getElementById ( 'span['+datePickerPanel.formId+'][' + datePickerPanel.idName + ']' ); getField(datePickerPanel.idName, datePickerPanel.formId ).value = day; obj.innerHTML = day; datePickerPanel.remove(); } function set_datetime(n_datetime, b_close) { moveDatePicker(n_datetime); } /* Functions for show and hide rows of a simple xmlform. * @author David Callizaya <[email protected]> */ function getRow( name ){ try{ var element = null; if (typeof(name)==='string'){ element = getField(name); /** Set to hide/show of objects "checkgroup" and "radiogroup" @author: Hector Cortez */ if(element == null){ aElements = document.getElementsByName('form['+ name +'][]'); if( aElements.length == 0) aElements = document.getElementsByName('form['+ name +']'); if( aElements.length ){ element = aElements[aElements.length-1]; } else element = null; } } if( element != null){ while ( element.tagName !== 'TR' ) { element=element.parentNode; } return element; } else { return null; } } catch(e){ alert(e); } } var getRowById=getRow; function hideRow( element ){ //neyek var row=getRow(element); if (row) row.style.display='none'; removeRequiredById(element); delete row; } var hideRowById=hideRow; function showRow( element ){ var row=getRow(element); requiredFields = []; sRequiredFields = document.getElementById('DynaformRequiredFields').value.replace(/%27/gi, '"'); fields = new String(sRequiredFields); fields = stripslashes(fields); requiredFieldsList = eval(fields); for(i=0; i<requiredFieldsList.length; i++){ requiredFields[i] = requiredFieldsList[i].name; } if ( requiredFields.inArray(element) ) { enableRequiredById(element); } if (row) row.style.display=''; delete row; } var showRowById=showRow; function hideShowControl(element , name){ var control; if (element) { control = element.parentNode.getElementsByTagName("div")[0]; control.style.display=control.style.display==='none'?'':'none'; if (control.style.display==='none') getField( name ).value=''; delete control; } } /*SHOW/HIDE A SUBTITLE CONTENT*/ function contractSubtitle( subTitle ){ subTitle=getRow(subTitle); var c=subTitle.cells[0].className; var a=subTitle.rowIndex; var t=subTitle.parentNode; for(var i=a+1,m=t.rows.length;i<m;i++){ if (t.rows[i].cells.length==1) break; t.rows[i].style.display='none'; var aAux = getControlsInTheRow(t.rows[i]); for (var j = 0; j < aAux.length; j++) { removeRequiredById(aAux[j]); } } } function expandSubtitle( subTitle ){ subTitle=getRow(subTitle); var c=subTitle.cells[0].className; var a=subTitle.rowIndex; var t=subTitle.parentNode; for(var i=a+1,m=t.rows.length;i<m;i++){ if (t.rows[i].cells.length==1) break; t.rows[i].style.display=''; var aAux = getControlsInTheRow(t.rows[i]); for (var j = 0; j < aAux.length; j++) { enableRequiredById(aAux[j]); } } } function contractExpandSubtitle(subTitle){ subTitle=getRow(subTitle); var c=subTitle.cells[0].className; var a=subTitle.rowIndex; var t=subTitle.parentNode; var contracted=false; for(var i=a+1,m=t.rows.length;i<m;i++){ if (t.rows[i].cells.length==1) break; if (t.rows[i].style.display==='none'){ contracted=true; } } if (contracted) expandSubtitle(subTitle); else contractSubtitle(subTitle); } var getControlsInTheRow = function(oRow) { var aAux1 = []; if (oRow.cells) { var i; var j; var sFieldName; for (i = 0; i < oRow.cells.length; i++) { var aAux2 = oRow.cells[i].getElementsByTagName('input'); if (aAux2) { for (j = 0; j < aAux2.length; j++) { sFieldName = aAux2[j].id.replace('form[', ''); //sFieldName = sFieldName.replace(']', ''); sFieldName = sFieldName.replace(/]$/, ''); aAux1.push(sFieldName); } } } } return aAux1; }; var notValidateThisFields = []; /** * @function getElementByClassNameCrossBrowser * @sumary independent implementaction of the Firefox getElementsByClassName * for CrossBrowser compatibility * @author gustavo cruz gustavo-at-colosa.com * @parameter className * @parameter node * @parameter tag * @return array * return the elements that are from the className */ function getElementsByClassNameCrossBrowser(searchClass,node,tag) { var classElements = new Array(); if ( node == null ) node = document; if ( tag == null ) tag = '*'; var els = node.getElementsByTagName(tag); var elsLen = els.length; var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"); for (i = 0, j = 0; i < elsLen; i++) { if ( pattern.test(els[i].className) ) { classElements[j] = els[i]; j++; } } return classElements; } /** * @function validateGridForms * @sumary function to validate the elements of a grid form inside a normal * form. * @author gustavo cruz gustavo-at-colosa.com * @parameter invalidFields * @return array * with the grid invalid fields added. * We need the invalidFields as a parameter * **/ var validateGridForms = function(invalidFields){ // alert("doesnt work " + i); grids = getElementsByClassNameCrossBrowser("grid",document,"div"); Tlabels = getElementsByClassNameCrossBrowser("tableGrid",document,"table"); // grids = getElementsByClass("grid",document,"div"); // grids = document.getElementsByClassName("grid"); for(j=0; j<grids.length; j++){ // check all the input fields in the grid fields = grids[j].getElementsByTagName('input'); // labels = ; for(i=0; i<fields.length; i++){ if (fields[i].getAttribute("pm:required")=="1"&&fields[i].value==''){ $label = fields[i].name.split("["); $labelPM = fields[i].getAttribute("pm:label"); if ($labelPM == '' || $labelPM == null){ $fieldName = $label[3].split("]")[0]+ " " + $label[2].split("]")[0]; }else{ $fieldName = $labelPM + " " + $label[2].split("]")[0]; } //$fieldName = labels[i].innerHTML.replace('*','') + " " + $label[2].split("]")[0]; //alert($fieldName+" "+$fieldRow); //alert(fields[i].name); invalidFields.push($fieldName); } } textAreas = grids[j].getElementsByTagName('textarea'); for(i=0; i<textAreas.length; i++){ if (textAreas[i].getAttribute("pm:required")=="1"&&textAreas[i].value==''){ $label = textAreas[i].name.split("["); $fieldName = $label[3].split("]")[0]+ " " + $label[2].split("]")[0]; //alert($fieldName+" "+$fieldRow); //alert(fields[i].name); invalidFields.push($fieldName); } } dropdowns = grids[j].getElementsByTagName('select'); for(i=0; i<dropdowns.length; i++){ if (dropdowns[i].getAttribute("pm:required")=="1"&&dropdowns[i].value==''){ $label = dropdowns[i].name.split("["); $fieldName = $label[3].split("]")[0]+ " " + $label[2].split("]")[0]; //alert($fieldName+" "+$fieldRow); //alert(fields[i].name); invalidFields.push($fieldName); } } } return (invalidFields); }; /** * * This function validates via javascript * the required fields in the Json array in the form tag of a dynaform * now the required fields in a grid have a "required" atribute set in 1 * @param String sRequiredFields * **/ var validateForm = function(sRequiredFields) { /** * replacing the %27 code by " character (if exists), this solve the problem that " broke the properties definition into a html * i.ei <form onsubmit="myaction(MyjsString)" ... with var MyjsString = "some string that is into a variable, so this broke the html"; */ if( typeof(sRequiredFields) != 'object' || sRequiredFields.indexOf("%27") > 0 ){ sRequiredFields = sRequiredFields.replace(/%27/gi, '"'); } if( typeof(sRequiredFields) != 'object' || sRequiredFields.indexOf("%39") > 0 ){ sRequiredFields = sRequiredFields.replace(/%39/gi, "'"); } aRequiredFields = eval(sRequiredFields); var sMessage = ''; var invalid_fields = Array(); var fielEmailInvalid = Array(); for (var i = 0; i < aRequiredFields.length; i++) { aRequiredFields[i].label=(aRequiredFields[i].label=='')?aRequiredFields[i].name:aRequiredFields[i].label; if (!notValidateThisFields.inArray(aRequiredFields[i].name)) { if (typeof aRequiredFields[i].required != 'undefined'){ required = aRequiredFields[i].required; } else { required = 1; } if (typeof aRequiredFields[i].validate != 'undefined') { validate = aRequiredFields[i].validate; } else { validate = ''; } if(required == 1) { switch(aRequiredFields[i].type) { case 'suggest': var vtext1 = new input(getField(aRequiredFields[i].name+'_suggest')); if(getField(aRequiredFields[i].name).value==''){ invalid_fields.push(aRequiredFields[i].label); vtext1.failed(); } else { vtext1.passed(); } break; case 'text': var vtext = new input(getField(aRequiredFields[i].name)); if(getField(aRequiredFields[i].name).value=='') { invalid_fields.push(aRequiredFields[i].label); vtext.failed(); } else { vtext.passed(); } break; case 'dropdown': var vtext = new input(getField(aRequiredFields[i].name)); if(getField(aRequiredFields[i].name).value==''){ invalid_fields.push(aRequiredFields[i].label); vtext.failed(); } else { vtext.passed(); } break; case 'textarea': var vtext = new input(getField(aRequiredFields[i].name)); if(getField(aRequiredFields[i].name).value==''){ invalid_fields.push(aRequiredFields[i].label); vtext.failed(); } else { vtext.passed(); } break; case 'password': var vpass = new input(getField(aRequiredFields[i].name)); if(getField(aRequiredFields[i].name).value==''){ invalid_fields.push(aRequiredFields[i].label); vpass.failed(); } else { vpass.passed(); } break; case 'currency': var vcurr = new input(getField(aRequiredFields[i].name)); if(getField(aRequiredFields[i].name).value==''){ invalid_fields.push(aRequiredFields[i].label); vcurr.failed(); } else { vcurr.passed(); } break; case 'percentage': var vper = new input(getField(aRequiredFields[i].name)); if(getField(aRequiredFields[i].name).value==''){ invalid_fields.push(aRequiredFields[i].label); vper.failed(); } else { vper.passed(); } break; case 'yesno': var vtext = new input(getField(aRequiredFields[i].name)); if(getField(aRequiredFields[i].name).value==''){ invalid_fields.push(aRequiredFields[i].label); vtext.failed(); } else { vtext.passed(); } break; case 'date': var vtext = new input(getField(aRequiredFields[i].name)); if(getField(aRequiredFields[i].name).value==''){ invalid_fields.push(aRequiredFields[i].label); vtext.failed(); } else { vtext.passed(); } break; case 'file': var vtext = new input(getField(aRequiredFields[i].name)); if(getField(aRequiredFields[i].name).value==''){ invalid_fields.push(aRequiredFields[i].label); vtext.failed(); } else { vtext.passed(); } break; case 'listbox': var oAux = getField(aRequiredFields[i].name); var bOneSelected = false; for (var j = 0; j < oAux.options.length; j++) { if (oAux.options[j].selected) { bOneSelected = true; j = oAux.options.length; } } if(bOneSelected == false) invalid_fields.push(aRequiredFields[i].label); break; case 'radiogroup': var x=aRequiredFields[i].name; var oAux = document.getElementsByName('form['+ x +']'); var bOneChecked = false; for (var k = 0; k < oAux.length; k++) { var r = oAux[k]; if (r.checked) { bOneChecked = true; k = oAux.length; } } if(bOneChecked == false) invalid_fields.push(aRequiredFields[i].label); break; case 'checkgroup': var bOneChecked = false; var aAux = document.getElementsByName('form[' + aRequiredFields[i].name + '][]'); for (var k = 0; k < aAux.length; k++) { if (aAux[k].checked) { bOneChecked = true; k = aAux.length; } } if(!bOneChecked) { invalid_fields.push(aRequiredFields[i].label); } break; } } if(validate != '') { //validate_fields switch(aRequiredFields[i].type) { case 'suggest': break; case 'text': if(validate=="Email") { var vtext = new input(getField(aRequiredFields[i].name)); if(getField(aRequiredFields[i].name).value!='') { var email = getField(aRequiredFields[i].name); //var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; //var filter = /^[\w\_\-\.çñ]{2,255}@[\w\_\-]{2,255}\.[a-z]{1,3}\.?[a-z]{0,3}$/; var filter =/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; if (!filter.test(email.value)&&email.value!="") { fielEmailInvalid.push(aRequiredFields[i].label); vtext.failed(); email.focus(); } else { vtext.passed(); } } } break; } } } } // call added by gustavo - cruz, gustavo-at-colosa.com validate grid forms invalid_fields = validateGridForms(invalid_fields); if (invalid_fields.length > 0 ||fielEmailInvalid.length> 0) { //alert(G_STRINGS.ID_REQUIRED_FIELDS + ": \n\n" + sMessage); // loop for invalid_fields for(j=0; j<invalid_fields.length; j++){ sMessage += (j > 0)? ', ': ''; sMessage += invalid_fields[j]; } // Loop for invalid_emails var emailInvalidMessage = ""; for(j=0; j<fielEmailInvalid.length; j++){ emailInvalidMessage += (j > 0)? ', ': ''; emailInvalidMessage += fielEmailInvalid[j]; } /* new leimnud.module.app.alert().make({ label:G_STRINGS.ID_REQUIRED_FIELDS + ": <br/><br/>[ " + sMessage + " ]", width:450, height:140 + (parseInt(invalid_fields.length/10)*10) });*/ //!create systemMessaggeInvalid of field invalids var systemMessaggeInvalid = ""; if(invalid_fields.length > 0) { systemMessaggeInvalid += "\n \n"+G_STRINGS.ID_REQUIRED_FIELDS + ": \n \n [ " + sMessage + " ]"; } if(fielEmailInvalid.length > 0) { systemMessaggeInvalid += "\n \n" + G_STRINGS.ID_VALIDATED_FIELDS + ": \n \n [ " + emailInvalidMessage + " ]"; } alert(systemMessaggeInvalid); return false; } else { return true; } }; var getObject = function(sObject) { var i; var oAux = null; var iLength = __aObjects__.length; for (i = 0; i < iLength; i++) { oAux = __aObjects__[i].getElementByName(sObject); if (oAux) { return oAux; } } return oAux; }; var saveAndRefreshForm = function(oObject) { if (oObject) { oObject.form.action += '&_REFRESH_=1'; oObject.form.submit(); } else { var oAux = window.document.getElementsByTagName('form'); if (oAux.length > 0) { oAux[0].action += '&_REFRESH_=1'; oAux[0].submit(); } } }; /** * @function saveForm * @author gustavo cruz gustavo[at]colosa[dot]com * @param oObject is a reference to the object which is attached to the event, * for example can be a save button, or anything else. * @return This function only makes an ajax post to the form action * @desc saveForm takes a object reference as a parameter, from that extracts * the form and the form action references, then executes an Ajax request * that post the form data to the action url, so the form is never * refreshed or submited, at least not in the traditional sense. **/ var saveForm = function(oObject) { if (oObject) { ajax_post(oObject.form.action,oObject.form,'POST'); } else { var oAux = window.document.getElementsByTagName('form'); if (oAux.length > 0) { ajax_post(oAux[0].action,oAux[0],'POST'); } } }; /** * @function validateUrl * @author gustavo cruz gustavo[at]colosa[dot]com * @param url is the url to be validated. * @return true/false. * @desc takes a url as parameter and check returning a boolean if it's valid or not. **/ var validateURL = function (url){ //var regexp = /https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/; if (regexp.test('https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?')){ return true; } else { return false; } }; /** * @function saveAndRedirectForm * @author gustavo cruz gustavo[at]colosa[dot]com * @param oObject is a reference to the object which is attached to the event, * for example can be a save button, or anything else. * @param oLocation is the url of tha redirect location. * @return This function only makes a non refresh save a redirection action. * @desc saveAndRedirectForm takes a object reference as a parameter, and * then invoques the saveForm() function, so after the form data is saved, * validates the url passed as parameter, if it's valid then redirects * the browser to the oLocation url. **/ var saveAndRedirectForm = function(oObject, oLocation) { saveForm(oObject); if (validateURL(oLocation)){ document.location.href = oLocation; } }; var removeRequiredById = function(sFieldName) { if (!notValidateThisFields.inArray(sFieldName)) { notValidateThisFields.push(sFieldName); var oAux = document.getElementById('__notValidateThisFields__'); if (oAux) { oAux.value = notValidateThisFields.toJSONString(); } } }; var enableRequiredById = function(sFieldName) { if (notValidateThisFields.inArray(sFieldName)) { var i; var aAux = []; for(i = 0; i < notValidateThisFields.length; i++) { if(notValidateThisFields[i] != sFieldName) { aAux.push(notValidateThisFields[i]); } } notValidateThisFields = aAux; var oAux = document.getElementById('__notValidateThisFields__'); if (oAux) { oAux.value = notValidateThisFields.toJSONString(); } } }; function dynaformVerifyFieldName(){ pme_validating = true; setTimeout('verifyFieldName1();',0); return true; } function verifyFieldName1(){ var newFieldName=fieldName.value; var validatedFieldName=getField("PME_VALIDATE_NAME",fieldForm).value; var dField = new input(getField('PME_XMLNODE_NAME')); var valid=(newFieldName!=='')&&(((newFieldName!==savedFieldName)&&(validatedFieldName===''))||((newFieldName===savedFieldName))); if (valid){ dField.passed(); getField("PME_ACCEPT",fieldForm).disabled=false; }else{ getField("PME_ACCEPT",fieldForm).disabled=true; dField.failed(); new leimnud.module.app.alert().make({ label: G_STRINGS.DYNAFIELD_ALREADY_EXIST }); dField.focus(); } pme_validating=false; return valid; } var objectsWithFormula = Array(); function sumaformu(ee,fma,mask){ //copy the formula afma=fma; var operators=['+','-','*','/','(','[','{','}',']',')',',','Math.pow','Math.PI','Math.sqrt']; var wos; //replace the operators symbols for empty space for(var i=0 ; i < operators.length ; i++) { var j=0; while(j < fma.length){ nfma=fma.replace(operators[i]," "); nfma=nfma.replace(" "," "); fma=nfma; j++; } } //without spaces in the inicio of the formula wos=nfma.replace(/^\s+/g,''); nfma=wos.replace(/\s+$/g,''); theelemts=nfma.split(" "); objectsWithFormula[objectsWithFormula.length]= {ee:ee,fma:afma,mask:mask,theElements:theelemts}; for (var i=0; i < theelemts.length; i++){ leimnud.event.add(getField(theelemts[i]),'keyup',function(){ //leimnud.event.add(getField(objectsWithFormula[objectsWithFormula.length-1].theElements[i]),'keyup',function(){ myId=this.id.replace("form[","").replace("]",""); for(i_elements=0;i_elements < objectsWithFormula.length; i_elements++){ for(i_elements2=0;i_elements2 < objectsWithFormula[i_elements].theElements.length;i_elements2++){ if(objectsWithFormula[i_elements].theElements[i_elements2]==myId) { //calValue(afma,nfma,ee,mask); formula = objectsWithFormula[i_elements].fma; ans = objectsWithFormula[i_elements].ee; theelemts=objectsWithFormula[i_elements].theElements; nfk = ''; //to replace the field for the value and to evaluate the formula for (var i=0; i < theelemts.length; i++){ if(!isnumberk(theelemts[i])){//alert(getField(theelemts[i]).name); val = (getField(theelemts[i]).value == '')? 0 : getField(theelemts[i]).value; formula=formula.replace(theelemts[i],val); } } var rstop=eval(formula); if(mask!=''){ putmask(rstop,mask,ans); }else{ ans.value=rstop; } } } } }); } } function calValue(afma,nfma,ans,mask){ theelemts=nfma.split(" "); //to replace the field for the value and to evaluate the formula for (var i=0; i < theelemts.length; i++){ if(!isnumberk(theelemts[i])){//alert(getField(theelemts[i]).name); if(getField(theelemts[i]).value){ nfk=afma.replace(theelemts[i],getField(theelemts[i]).value); afma=nfk; } } } //ans.value=eval(nfk); var rstop=eval(nfk); if(mask!=''){ putmask(rstop,mask,ans); }else{ //alert('without mask'); ans.value=rstop; } } function isnumberk(texto){ var numberk="0123456789."; var letters="abcdefghijklmnopqrstuvwxyz"; var i=0; var sw=1; //for(var i=0; i<texto.length; i++){ while(i++ < texto.length && sw==1){ if (numberk.indexOf(texto.charAt(i),0)==-1){ sw=0; } } return sw; } function putmask(numb,mask,ans){ var nnum=''; var i=0; var j=0; maskDecimal=mask.split(";"); if(maskDecimal.length > 1) { maskDecimal=maskDecimal[1].split("."); } else { maskDecimal=mask.split("."); } numDecimal=maskDecimal[1].length; ans.value=numb.toFixed(numDecimal); return; var nnum='',i=0,j=0; //we get the number of digits cnumb=numb.toString(); cd = parseInt(Math.log(numb)/Math.LN10+1); //now we're runing the mask and cd fnb=cnumb.split("."); maskp=mask.split(";"); mask = (maskp.length > 1)? maskp[1]:mask; while(i < numb.toString().length && j < mask.length){ //alert(cnumb.charAt(i)+' ** '+mask.charAt(i)); switch(mask.charAt(j)){ case '#': if(cnumb.charAt(i)!='.') { nnum+=cnumb.charAt(i).toString(); i++; } break; case '.': nnum+=mask.charAt(j).toString(); i=cd+1; cd=i +4; break; default: //alert(mask.charAt(i)); nnum+=mask.charAt(j).toString(); break; } j++; } ans.value=nnum; } function showRowsById(aFields){ for(i=0; i<aFields.length; i++){ row = getRow(aFields[i]); if( row ){ row.style.display=''; } } } function hideRowsById(aFields){ for(i=0; i<aFields.length; i++){ row = getRow(aFields[i]); if( row ){ row.style.display='none'; } } } /* end file */
BUG 0000 Formula/Functions problem with grids - Take 2
gulliver/js/form/core/form.js
BUG 0000 Formula/Functions problem with grids - Take 2
<ide><path>ulliver/js/form/core/form.js <ide> case 35: case 36: //HOME OR END <ide> case 37: case 38: case 39: case 40: // ARROW KEYS <ide> me.applyMask(pressKey); <del> if (pressKey == 8 || pressKey == 46) me.sendOnChange(); <add> if ((pressKey == 8 || pressKey == 46) && (me.validate != 'Login' && me.validate != 'NodeName')) me.sendOnChange(); <ide> me.checkBrowser(); <ide> if (me.browser.name == 'Chrome'){ <ide> event.returnValue = false; <ide> key = String.fromCharCode(pressKey); <ide> keyValid = patron.test(key); <ide> break; <del> case 'NodeName': <add> case 'NodeName': case 'Login': <add> updateOnChange = false; <ide> if (me.getCursorPos() == 0) { <del> updateOnChange = false; <ide> if ((pressKey >= 48) && (pressKey <= 57)) { <ide> keyValid = false; <ide> break; <ide> lang :(typeof(me.language)!=='undefined')?me.language:"en" <ide> }); <ide> keyValid = k.result(); <add> <ide> break; <ide> } <ide> if (keyValid){
Java
apache-2.0
b7a3df7c30588de1995b18d5c94522f0bd8bd46b
0
sqrlserverjava/sqrl-server-base,dbadia/sqrl-server-base,sqrlserverjava/sqrl-server-base
package com.github.dbadia.sqrl.server.backchannel; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertTrue; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import com.github.dbadia.sqrl.server.backchannel.SqrlTif.TifBuilder; @RunWith(Parameterized.class) public class TifTest { @Parameters(name = "{index}: ipmatch=({0}) expected=({1}) tifArray=({2}) )") public static Collection<Object[]> data() { // @formatter:off return Arrays.asList(new Object[][] { { true, 5, new int[]{SqrlTif.TIF_CURRENT_ID_MATCH }}, { true, -60, new int[]{SqrlTif.TIF_COMMAND_FAILED, SqrlTif.TIF_CLIENT_FAILURE} }, }); } // @formatter:on @Test public void testIt() throws Exception { final TifBuilder builder = new TifBuilder(ipsMatched); final List<Integer> absentTifList = SqrlTif.getAllTifs(); if(ipsMatched) { absentTifList.remove(Integer.valueOf(SqrlTif.TIF_IPS_MATCHED)); } for (final int tif : tifList) { builder.addFlag(tif); absentTifList.remove(Integer.valueOf(tif)); } final SqrlTif tif = builder.createTif(); if (ipsMatched) { assertTrue(isTifPresent(tif, SqrlTif.TIF_IPS_MATCHED)); } for (final int expectedTif : tifList) { assertTrue(isTifPresent(tif, expectedTif)); } assertEquals(expectedValue, tif.getTifInt()); for(final int shouldBeAbsent : absentTifList) { assertTrue("Found " + shouldBeAbsent + " in tif " + tif + " but shouldn't have", isTifAbsent(tif, shouldBeAbsent)); } } /* **************** Util methods *****************/ static final void assertTif(final SqrlTif tif, final int... expectedTifArray) { for (final int expectedTifInt : expectedTifArray) { assertTifPresent(tif, expectedTifInt); } final List<Integer> absentTifList = buildAbsentTifList(expectedTifArray); for (final int absentTifInt : absentTifList) { assertTifAbsent(tif, absentTifInt); } } private static void assertTifAbsent(final SqrlTif tif, final int absentTifInt) { assertTrue("Found expected absent " + absentTifInt + " in tif " + tif, isTifAbsent(tif, absentTifInt)); } static final List<Integer> buildAbsentTifList(final int[] expectedTifArray) { final List<Integer> absentTifList = SqrlTif.getAllTifs(); for (final int tif : expectedTifArray) { absentTifList.remove(Integer.valueOf(tif)); } return absentTifList; } static final void assertTifPresent(final SqrlTif tif, final int tifToLookFor) { assertTrue("Expected " + tifToLookFor + " in tif " + tif, isTifPresent(tif, tifToLookFor)); } static final boolean isTifPresent(final SqrlTif tif, final int tifToLookFor) { return (tif.getTifInt() & tifToLookFor) == tifToLookFor; } static final boolean isTifAbsent(final SqrlTif tif, final int tifToLookFor) { return !isTifPresent(tif, tifToLookFor); } // Instance variables and constructor are all boilerplate for Parameterized test, so put them at the bottom private final boolean ipsMatched; private final int expectedValue; private final int[] tifList; public TifTest(final boolean ipsMatched, final int expectedValue, final int... tifList) { super(); this.ipsMatched = ipsMatched; this.expectedValue = expectedValue; this.tifList = tifList; } }
src/test/java/com/github/dbadia/sqrl/server/backchannel/TifTest.java
package com.github.dbadia.sqrl.server.backchannel; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertTrue; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import com.github.dbadia.sqrl.server.backchannel.SqrlTif.TifBuilder; @RunWith(Parameterized.class) public class TifTest { @Parameters(name = "{index}: url=({0}) escheme=({1}) eurl=({2}) eport=({3}) euri=({4})") public static Collection<Object[]> data() { // @formatter:off return Arrays.asList(new Object[][] { { true, 5, new int[]{SqrlTif.TIF_CURRENT_ID_MATCH }}, { true, -60, new int[]{SqrlTif.TIF_COMMAND_FAILED, SqrlTif.TIF_CLIENT_FAILURE} }, }); } // @formatter:on @Test public void testIt() throws Exception { final TifBuilder builder = new TifBuilder(ipsMatched); final List<Integer> absentTifList = SqrlTif.getAllTifs(); if(ipsMatched) { absentTifList.remove(SqrlTif.TIF_IPS_MATCHED); } for (final int tif : tifList) { builder.addFlag(tif); absentTifList.remove(Integer.valueOf(tif)); } final SqrlTif tif = builder.createTif(); if (ipsMatched) { assertTrue(isTifPresent(tif, SqrlTif.TIF_IPS_MATCHED)); } for (final int expectedTif : tifList) { assertTrue(isTifPresent(tif, expectedTif)); } assertEquals(expectedValue, tif.getTifInt()); // TODO: test with absent } /* **************** Util methods *****************/ static final void assertTif(final SqrlTif tif, final int... expectedTifArray) { for (final int expectedTifInt : expectedTifArray) { assertTifPresent(tif, expectedTifInt); } final List<Integer> absentTifList = buildAbsentTifList(expectedTifArray); for (final int absentTifInt : absentTifList) { assertTifAbsent(tif, absentTifInt); } } private static void assertTifAbsent(final SqrlTif tif, final int absentTifInt) { assertTrue("Found expected absent " + absentTifInt + " in tif " + tif, isTifAbsent(tif, absentTifInt)); } static final List<Integer> buildAbsentTifList(final int[] expectedTifArray) { final List<Integer> absentTifList = SqrlTif.getAllTifs(); for (final int tif : expectedTifArray) { absentTifList.remove(Integer.valueOf(tif)); } return absentTifList; } static final void assertTifPresent(final SqrlTif tif, final int tifToLookFor) { assertTrue("Expected " + tifToLookFor + " in tif " + tif, isTifPresent(tif, tifToLookFor)); } static final boolean isTifPresent(final SqrlTif tif, final int tifToLookFor) { return (tif.getTifInt() & tifToLookFor) == tifToLookFor; } static final boolean isTifAbsent(final SqrlTif tif, final int tifToLookFor) { return !isTifPresent(tif, tifToLookFor); } // Instance variables and constructor are all boilerplate for Parameterized test, so put them at the bottom private final boolean ipsMatched; private final int expectedValue; private final int[] tifList; public TifTest(final boolean ipsMatched, final int expectedValue, final int... tifList) { super(); this.ipsMatched = ipsMatched; this.expectedValue = expectedValue; this.tifList = tifList; } }
working on tif negative tests
src/test/java/com/github/dbadia/sqrl/server/backchannel/TifTest.java
working on tif negative tests
<ide><path>rc/test/java/com/github/dbadia/sqrl/server/backchannel/TifTest.java <ide> <ide> @RunWith(Parameterized.class) <ide> public class TifTest { <del> @Parameters(name = "{index}: url=({0}) escheme=({1}) eurl=({2}) eport=({3}) euri=({4})") <add> @Parameters(name = "{index}: ipmatch=({0}) expected=({1}) tifArray=({2}) )") <ide> public static Collection<Object[]> data() { <ide> // @formatter:off <ide> return Arrays.asList(new Object[][] { <ide> final TifBuilder builder = new TifBuilder(ipsMatched); <ide> final List<Integer> absentTifList = SqrlTif.getAllTifs(); <ide> if(ipsMatched) { <del> absentTifList.remove(SqrlTif.TIF_IPS_MATCHED); <add> absentTifList.remove(Integer.valueOf(SqrlTif.TIF_IPS_MATCHED)); <ide> } <ide> for (final int tif : tifList) { <ide> builder.addFlag(tif); <ide> } <ide> assertEquals(expectedValue, tif.getTifInt()); <ide> <del> // TODO: test with absent <add> for(final int shouldBeAbsent : absentTifList) { <add> assertTrue("Found " + shouldBeAbsent + " in tif " + tif + " but shouldn't have", <add> isTifAbsent(tif, shouldBeAbsent)); <add> } <ide> } <ide> <ide>
Java
apache-2.0
aedb7b2642fba4b93560caa9624f26eacf1ff871
0
IHTSDO/rf2-to-rf1-conversion,IHTSDO/rf2-to-rf1-conversion
package org.ihtsdo.snomed.rf2torf1conversion; import static org.ihtsdo.snomed.rf2torf1conversion.GlobalUtils.*; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.FileUtils; import com.google.common.base.Stopwatch; import com.google.common.io.Files; public class ConversionManager { File rf2Archive; File unzipLocation = null; DBManager db; String releaseDate; boolean includeHistory = false; static Map<String, String> fileToTable = new HashMap<String, String>(); { fileToTable.put("sct2_Concept_Full_INT_DATE.txt", "rf2_concept_sv"); fileToTable.put("sct2_Description_Full-en_INT_DATE.txt", "rf2_term_sv"); fileToTable.put("sct2_Relationship_Full_INT_DATE.txt", "rf2_rel_sv"); fileToTable.put("sct2_StatedRelationship_Full_INT_DATE.txt", "rf2_rel_sv"); fileToTable.put("sct2_Identifier_Full_INT_DATE.txt", "rf2_identifier_sv"); fileToTable.put("sct2_TextDefinition_Full-en_INT_DATE.txt", "rf2_def_sv"); fileToTable.put("der2_cRefset_AssociationReferenceFull_INT_DATE.txt", "rf2_crefset_sv"); fileToTable.put("der2_cRefset_AttributeValueFull_INT_DATE.txt", "rf2_crefset_sv"); fileToTable.put("der2_Refset_SimpleFull_INT_DATE.txt", "rf2_refset_sv"); fileToTable.put("der2_cRefset_LanguageFull-en_INT_DATE.txt", "rf2_crefset_sv"); fileToTable.put("der2_sRefset_SimpleMapFull_INT_DATE.txt", "rf2_srefset_sv"); fileToTable.put("der2_iissscRefset_ComplexMapFull_INT_DATE.txt", "rf2_iissscrefset_sv"); fileToTable.put("der2_iisssccRefset_ExtendedMapFull_INT_DATE.txt", "rf2_iisssccrefset_sv"); fileToTable.put("der2_cciRefset_RefsetDescriptorFull_INT_DATE.txt", "rf2_ccirefset_sv"); fileToTable.put("der2_ciRefset_DescriptionTypeFull_INT_DATE.txt", "rf2_cirefset_sv"); fileToTable.put("der2_ssRefset_ModuleDependencyFull_INT_DATE.txt", "rf2_ssrefset_sv"); } public static final Map<String, String> exportMap = new HashMap<String, String>(); { // The slashes will be replaced with the OS appropriate separator at export time exportMap.put("SnomedCT_RF1Release_INT_DATE/Terminology/Content/sct1_Concepts_Core_INT_DATE.txt", "select CONCEPTID, CONCEPTSTATUS, FULLYSPECIFIEDNAME, CTV3ID, SNOMEDID, ISPRIMITIVE from rf21_concept"); exportMap .put("SnomedCT_RF1Release_INT_DATE/Terminology/Content/sct1_Relationships_Core_INT_DATE.txt", "select RELATIONSHIPID,CONCEPTID1,RELATIONSHIPTYPE,CONCEPTID2,CHARACTERISTICTYPE,REFINABILITY,RELATIONSHIPGROUP from rf21_rel"); exportMap .put("SnomedCT_RF1Release_INT_DATE/Terminology/Content/sct1_Descriptions_en_INT_DATE.txt", "select DESCRIPTIONID, DESCRIPTIONSTATUS, CONCEPTID, TERM, INITIALCAPITALSTATUS, US_DESC_TYPE as DESCRIPTIONTYPE, LANGUAGECODE from rf21_term where languageCode in (''en-US'')" + " UNION " + "select DESCRIPTIONID, DESCRIPTIONSTATUS, CONCEPTID, TERM, INITIALCAPITALSTATUS, GB_DESC_TYPE as DESCRIPTIONTYPE, LANGUAGECODE from rf21_term where languageCode =''en-GB''" + " UNION " + "select DESCRIPTIONID, DESCRIPTIONSTATUS, CONCEPTID, TERM, INITIALCAPITALSTATUS, DESC_TYPE as DESCRIPTIONTYPE, LANGUAGECODE from rf21_term where languageCode =''en''"); exportMap.put("SnomedCT_RF1Release_INT_DATE/Resources/TextDefinitions/sct1_TextDefinitions_en-US_INT_DATE.txt", "select * from rf21_DEF"); exportMap.put("SnomedCT_RF1Release_INT_DATE/Terminology/History/sct1_ComponentHistory_Core_INT_DATE.txt", "select COMPONENTID, RELEASEVERSION, CHANGETYPE, STATUS, REASON from rf21_COMPONENTHISTORY"); exportMap.put("SnomedCT_RF1Release_INT_DATE/Terminology/History/sct1_References_Core_INT_DATE.txt", "select COMPONENTID, REFERENCETYPE, REFERENCEDID from rf21_REFERENCE"); exportMap .put("SnomedCT_RF1Release_INT_DATE/Subsets/Language-en-GB/der1_SubsetMembers_en-GB_INT_DATE.txt", "select s.SubsetId, s.MemberID, s.MemberStatus, s.LinkedID from rf21_SUBSETS s, rf21_SUBSETLIST sl where s.SubsetOriginalId = sl.subsetOriginalId AND sl.languageCode in (''en'',''en-GB'')"); exportMap.put("SnomedCT_RF1Release_INT_DATE/Subsets/Language-en-GB/der1_Subsets_en-GB_INT_DATE.txt", "select sl.* from rf21_SUBSETLIST sl where languagecode like ''%GB%''"); exportMap .put("SnomedCT_RF1Release_INT_DATE/Subsets/Language-en-US/der1_SubsetMembers_en-US_INT_DATE.txt", "select s.SubsetId, s.MemberID, s.MemberStatus, s.LinkedID from rf21_SUBSETS s, rf21_SUBSETLIST sl where s.SubsetOriginalId = sl.subsetOriginalId AND sl.languageCode in (''en'',''en-US'')"); exportMap.put("SnomedCT_RF1Release_INT_DATE/Subsets/Language-en-US/der1_Subsets_en-US_INT_DATE.txt", "select sl.* from rf21_SUBSETLIST sl where languagecode like ''%US%''"); exportMap .put("SnomedCT_RF1Release_INT_DATE/Resources/StatedRelationships/res1_StatedRelationships_Core_INT_DATE.txt", "select RELATIONSHIPID,CONCEPTID1,RELATIONSHIPTYPE,CONCEPTID2,CHARACTERISTICTYPE,REFINABILITY,RELATIONSHIPGROUP from rf21_stated_rel"); // exportMap.put("rf21_XMAPLIST"); // exportMap.put("rf21_XMAPS"); // exportMap.put("rf21_XMAPTARGET"); } public static void main(String[] args) throws RF1ConversionException { ConversionManager cm = new ConversionManager(); File tempDBLocation = Files.createTempDir(); cm.init(args, tempDBLocation); cm.createDatabaseSchema(); File loadingArea = null; File exportArea = null; Stopwatch stopwatch = Stopwatch.createStarted(); String completionStatus = "failed"; try { print("\nExtracting RF2 Data..."); loadingArea = cm.unzipArchive(); print("\nLoading RF2 Data..."); cm.releaseDate = findDateInString(loadingArea.listFiles()[0].getName(), false); cm.loadRF2Data(loadingArea); debug("\nCreating RF2 indexes..."); cm.db.executeResource("create_rf2_indexes.sql"); print("\nCalculating RF2 snapshot..."); cm.calculateRF2Snapshot(); print("\nConverting RF2 to RF1..."); cm.convert(); print("\nExporting RF1 to file..."); exportArea = cm.exportRF1Data(); print("\nZipping archive"); createArchive(exportArea); completionStatus = "completed"; } finally { print("\nProcess " + completionStatus + " in " + stopwatch + " after completing " + getProgress() + "/" + getMaxOperations() + " operations."); print("Cleaning up resources..."); try { cm.db.shutDown(true); // Also deletes all files if (tempDBLocation != null && tempDBLocation.exists()) { tempDBLocation.delete(); } } catch (Exception e) { debug("Error while cleaning up database " + tempDBLocation.getPath() + e.getMessage()); } try { if (loadingArea != null && loadingArea.exists()) { FileUtils.deleteDirectory(loadingArea); } if (exportArea != null && exportArea.exists()) { FileUtils.deleteDirectory(exportArea); } } catch (Exception e) { debug("Error while cleaning up loading/export Areas " + loadingArea.getPath() + e.getMessage()); } } } private File unzipArchive() throws RF1ConversionException { File tempDir = null; try { if (unzipLocation != null) { tempDir = File.createTempFile("rf2-to-rf1", null, unzipLocation); } else { // Work in the traditional temp file location for the OS tempDir = Files.createTempDir(); } } catch (IOException e) { throw new RF1ConversionException("Unable to create temporary directory for archive extration"); } // We only need to work with the full files unzipFlat(rf2Archive, tempDir, "Full"); return tempDir; } private void createDatabaseSchema() throws RF1ConversionException { print("Creating database schema"); db.executeResource("create_rf2_schema.sql"); } private void calculateRF2Snapshot() throws RF1ConversionException { String setDateSql = "SET @RDATE = " + releaseDate; db.runStatement(setDateSql); db.executeResource("create_rf2_snapshot.sql"); db.executeResource("populate_subset_2_refset.sql"); } private void convert() throws RF1ConversionException { db.executeResource("create_rf1_schema.sql"); if (includeHistory) { db.executeResource("populate_rf1_historical.sql"); } else { print("Skipping generation of RF1 History. Set -h parameter if this is required."); } db.executeResource("populate_rf1.sql"); } private void init(String[] args, File dbLocation) throws RF1ConversionException { if (args.length < 1) { print("Usage: java ConversionManager [-v] [-u <unzip location>] <rf2 archive location>"); exit(); } boolean isUnzipLocation = false; for (String thisArg : args) { if (thisArg.equals("-v")) { GlobalUtils.verbose = true; } else if (thisArg.equals("-h")) { includeHistory = true; } else if (thisArg.equals("-u")) { isUnzipLocation = true; } else if (isUnzipLocation) { unzipLocation = new File(thisArg); if (!unzipLocation.isDirectory()) { throw new RF1ConversionException(thisArg + " is an invalid location to unzip archive to!"); } isUnzipLocation = false; } else { File possibleArchive = new File(thisArg); if (possibleArchive.exists() && !possibleArchive.isDirectory() && possibleArchive.canRead()) { rf2Archive = possibleArchive; } } } if (rf2Archive == null) { print("Unable to read RF2 Archive: " + args[args.length - 1]); exit(); } db = new DBManager(); db.init(dbLocation); } private void loadRF2Data(File loadingArea) throws RF1ConversionException { // We can do the load in parallel. Only 3 threads because heavily I/O db.startParallelProcessing(3); for (Map.Entry<String, String> entry : fileToTable.entrySet()) { // Replace DATE in the filename with the actual release date String fileName = entry.getKey().replace("DATE", releaseDate); File file = new File(loadingArea + File.separator + fileName); db.load(file, entry.getValue()); } db.finishParallelProcessing(); } private File exportRF1Data() throws RF1ConversionException { File tempExportLocation = Files.createTempDir(); // We can do the export in parallel. Only 3 threads because heavily I/O db.startParallelProcessing(3); for (Map.Entry<String, String> entry : exportMap.entrySet()) { // Replace DATE in the filename with the actual release date String fileName = entry.getKey().replace("DATE", releaseDate); String filePath = tempExportLocation + "/" + fileName; db.export(filePath, entry.getValue()); } db.finishParallelProcessing(); return tempExportLocation; } }
src/main/java/org/ihtsdo/snomed/rf2torf1conversion/ConversionManager.java
package org.ihtsdo.snomed.rf2torf1conversion; import static org.ihtsdo.snomed.rf2torf1conversion.GlobalUtils.*; import java.io.File; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.FileUtils; import com.google.common.base.Stopwatch; import com.google.common.io.Files; public class ConversionManager { File rf2Archive; DBManager db; String releaseDate; boolean includeHistory = false; static Map<String, String> fileToTable = new HashMap<String, String>(); { fileToTable.put("sct2_Concept_Full_INT_DATE.txt", "rf2_concept_sv"); fileToTable.put("sct2_Description_Full-en_INT_DATE.txt", "rf2_term_sv"); fileToTable.put("sct2_Relationship_Full_INT_DATE.txt", "rf2_rel_sv"); fileToTable.put("sct2_StatedRelationship_Full_INT_DATE.txt", "rf2_rel_sv"); fileToTable.put("sct2_Identifier_Full_INT_DATE.txt", "rf2_identifier_sv"); fileToTable.put("sct2_TextDefinition_Full-en_INT_DATE.txt", "rf2_def_sv"); fileToTable.put("der2_cRefset_AssociationReferenceFull_INT_DATE.txt", "rf2_crefset_sv"); fileToTable.put("der2_cRefset_AttributeValueFull_INT_DATE.txt", "rf2_crefset_sv"); fileToTable.put("der2_Refset_SimpleFull_INT_DATE.txt", "rf2_refset_sv"); fileToTable.put("der2_cRefset_LanguageFull-en_INT_DATE.txt", "rf2_crefset_sv"); fileToTable.put("der2_sRefset_SimpleMapFull_INT_DATE.txt", "rf2_srefset_sv"); fileToTable.put("der2_iissscRefset_ComplexMapFull_INT_DATE.txt", "rf2_iissscrefset_sv"); fileToTable.put("der2_iisssccRefset_ExtendedMapFull_INT_DATE.txt", "rf2_iisssccrefset_sv"); fileToTable.put("der2_cciRefset_RefsetDescriptorFull_INT_DATE.txt", "rf2_ccirefset_sv"); fileToTable.put("der2_ciRefset_DescriptionTypeFull_INT_DATE.txt", "rf2_cirefset_sv"); fileToTable.put("der2_ssRefset_ModuleDependencyFull_INT_DATE.txt", "rf2_ssrefset_sv"); } public static final Map<String, String> exportMap = new HashMap<String, String>(); { // The slashes will be replaced with the OS appropriate separator at export time exportMap.put("SnomedCT_RF1Release_INT_DATE/Terminology/Content/sct1_Concepts_Core_INT_DATE.txt", "select CONCEPTID, CONCEPTSTATUS, FULLYSPECIFIEDNAME, CTV3ID, SNOMEDID, ISPRIMITIVE from rf21_concept"); exportMap .put("SnomedCT_RF1Release_INT_DATE/Terminology/Content/sct1_Relationships_Core_INT_DATE.txt", "select RELATIONSHIPID,CONCEPTID1,RELATIONSHIPTYPE,CONCEPTID2,CHARACTERISTICTYPE,REFINABILITY,RELATIONSHIPGROUP from rf21_rel"); exportMap .put("SnomedCT_RF1Release_INT_DATE/Terminology/Content/sct1_Descriptions_en_INT_DATE.txt", "select DESCRIPTIONID, DESCRIPTIONSTATUS, CONCEPTID, TERM, INITIALCAPITALSTATUS, US_DESC_TYPE as DESCRIPTIONTYPE, LANGUAGECODE from rf21_term where languageCode in (''en-US'')" + " UNION " + "select DESCRIPTIONID, DESCRIPTIONSTATUS, CONCEPTID, TERM, INITIALCAPITALSTATUS, GB_DESC_TYPE as DESCRIPTIONTYPE, LANGUAGECODE from rf21_term where languageCode =''en-GB''" + " UNION " + "select DESCRIPTIONID, DESCRIPTIONSTATUS, CONCEPTID, TERM, INITIALCAPITALSTATUS, DESC_TYPE as DESCRIPTIONTYPE, LANGUAGECODE from rf21_term where languageCode =''en''"); exportMap.put("SnomedCT_RF1Release_INT_DATE/Resources/TextDefinitions/sct1_TextDefinitions_en-US_INT_DATE.txt", "select * from rf21_DEF"); exportMap.put("SnomedCT_RF1Release_INT_DATE/Terminology/History/sct1_ComponentHistory_Core_INT_DATE.txt", "select COMPONENTID, RELEASEVERSION, CHANGETYPE, STATUS, REASON from rf21_COMPONENTHISTORY"); exportMap.put("SnomedCT_RF1Release_INT_DATE/Terminology/History/sct1_References_Core_INT_DATE.txt", "select COMPONENTID, REFERENCETYPE, REFERENCEDID from rf21_REFERENCE"); exportMap .put("SnomedCT_RF1Release_INT_DATE/Subsets/Language-en-GB/der1_SubsetMembers_en-GB_INT_DATE.txt", "select s.SubsetId, s.MemberID, s.MemberStatus, s.LinkedID from rf21_SUBSETS s, rf21_SUBSETLIST sl where s.SubsetOriginalId = sl.subsetOriginalId AND sl.languageCode in (''en'',''en-GB'')"); exportMap.put("SnomedCT_RF1Release_INT_DATE/Subsets/Language-en-GB/der1_Subsets_en-GB_INT_DATE.txt", "select sl.* from rf21_SUBSETLIST sl where languagecode like ''%GB%''"); exportMap .put("SnomedCT_RF1Release_INT_DATE/Subsets/Language-en-US/der1_SubsetMembers_en-US_INT_DATE.txt", "select s.SubsetId, s.MemberID, s.MemberStatus, s.LinkedID from rf21_SUBSETS s, rf21_SUBSETLIST sl where s.SubsetOriginalId = sl.subsetOriginalId AND sl.languageCode in (''en'',''en-US'')"); exportMap.put("SnomedCT_RF1Release_INT_DATE/Subsets/Language-en-US/der1_Subsets_en-US_INT_DATE.txt", "select sl.* from rf21_SUBSETLIST sl where languagecode like ''%US%''"); exportMap .put("SnomedCT_RF1Release_INT_DATE/Resources/StatedRelationships/res1_StatedRelationships_Core_INT_DATE.txt", "select RELATIONSHIPID,CONCEPTID1,RELATIONSHIPTYPE,CONCEPTID2,CHARACTERISTICTYPE,REFINABILITY,RELATIONSHIPGROUP from rf21_stated_rel"); // exportMap.put("rf21_XMAPLIST"); // exportMap.put("rf21_XMAPS"); // exportMap.put("rf21_XMAPTARGET"); } public static void main(String[] args) throws RF1ConversionException { ConversionManager cm = new ConversionManager(); File tempDBLocation = Files.createTempDir(); cm.init(args, tempDBLocation); cm.createDatabaseSchema(); File loadingArea = null; File exportArea = null; Stopwatch stopwatch = Stopwatch.createStarted(); String completionStatus = "failed"; try { print("\nExtracting RF2 Data..."); loadingArea = cm.unzipArchive(); print("\nLoading RF2 Data..."); cm.releaseDate = findDateInString(loadingArea.listFiles()[0].getName(), false); cm.loadRF2Data(loadingArea); debug("\nCreating RF2 indexes..."); cm.db.executeResource("create_rf2_indexes.sql"); print("\nCalculating RF2 snapshot..."); cm.calculateRF2Snapshot(); print("\nConverting RF2 to RF1..."); cm.convert(); print("\nExporting RF1 to file..."); exportArea = cm.exportRF1Data(); print("\nZipping archive"); createArchive(exportArea); completionStatus = "completed"; } finally { print("\nProcess " + completionStatus + " in " + stopwatch + " after completing " + getProgress() + "/" + getMaxOperations() + " operations."); print("Cleaning up resources..."); try { cm.db.shutDown(true); // Also deletes all files if (tempDBLocation != null && tempDBLocation.exists()) { tempDBLocation.delete(); } } catch (Exception e) { debug("Error while cleaning up database " + tempDBLocation.getPath() + e.getMessage()); } try { if (loadingArea != null && loadingArea.exists()) { FileUtils.deleteDirectory(loadingArea); } if (exportArea != null && exportArea.exists()) { FileUtils.deleteDirectory(exportArea); } } catch (Exception e) { debug("Error while cleaning up loading/export Areas " + loadingArea.getPath() + e.getMessage()); } } } private File unzipArchive() throws RF1ConversionException { File tempDir = Files.createTempDir(); // We only need to work with the full files unzipFlat(rf2Archive, tempDir, "Full"); return tempDir; } private void createDatabaseSchema() throws RF1ConversionException { print("Creating database schema"); db.executeResource("create_rf2_schema.sql"); } private void calculateRF2Snapshot() throws RF1ConversionException { String setDateSql = "SET @RDATE = " + releaseDate; db.runStatement(setDateSql); db.executeResource("create_rf2_snapshot.sql"); db.executeResource("populate_subset_2_refset.sql"); } private void convert() throws RF1ConversionException { db.executeResource("create_rf1_schema.sql"); if (includeHistory) { db.executeResource("populate_rf1_historical.sql"); } else { print("Skipping generation of RF1 History. Set -h parameter if this is required."); } db.executeResource("populate_rf1.sql"); } private void init(String[] args, File dbLocation) throws RF1ConversionException { if (args.length < 1) { print("Usage: java ConversionManager [-v] <rf2 archive location>"); exit(); } for (String thisArg : args) { if (thisArg.equals("-v")) { GlobalUtils.verbose = true; } else if (thisArg.equals("-h")) { includeHistory = true; } else { File possibleArchive = new File(thisArg); if (possibleArchive.exists() && !possibleArchive.isDirectory() && possibleArchive.canRead()) { rf2Archive = possibleArchive; } } } if (rf2Archive == null) { print("Unable to read RF2 Archive: " + args[args.length - 1]); exit(); } db = new DBManager(); db.init(dbLocation); } private void loadRF2Data(File loadingArea) throws RF1ConversionException { // We can do the load in parallel. Only 3 threads because heavily I/O db.startParallelProcessing(3); for (Map.Entry<String, String> entry : fileToTable.entrySet()) { // Replace DATE in the filename with the actual release date String fileName = entry.getKey().replace("DATE", releaseDate); File file = new File(loadingArea + File.separator + fileName); db.load(file, entry.getValue()); } db.finishParallelProcessing(); } private File exportRF1Data() throws RF1ConversionException { File tempExportLocation = Files.createTempDir(); // We can do the export in parallel. Only 3 threads because heavily I/O db.startParallelProcessing(3); for (Map.Entry<String, String> entry : exportMap.entrySet()) { // Replace DATE in the filename with the actual release date String fileName = entry.getKey().replace("DATE", releaseDate); String filePath = tempExportLocation + "/" + fileName; db.export(filePath, entry.getValue()); } db.finishParallelProcessing(); return tempExportLocation; } }
Add support for unzipping to specified location, like a RAM Drive
src/main/java/org/ihtsdo/snomed/rf2torf1conversion/ConversionManager.java
Add support for unzipping to specified location, like a RAM Drive
<ide><path>rc/main/java/org/ihtsdo/snomed/rf2torf1conversion/ConversionManager.java <ide> import static org.ihtsdo.snomed.rf2torf1conversion.GlobalUtils.*; <ide> <ide> import java.io.File; <add>import java.io.IOException; <ide> import java.util.HashMap; <ide> import java.util.Map; <ide> <ide> public class ConversionManager { <ide> <ide> File rf2Archive; <add> File unzipLocation = null; <ide> DBManager db; <ide> String releaseDate; <ide> boolean includeHistory = false; <ide> } <ide> <ide> private File unzipArchive() throws RF1ConversionException { <del> File tempDir = Files.createTempDir(); <add> <add> File tempDir = null; <add> try { <add> if (unzipLocation != null) { <add> tempDir = File.createTempFile("rf2-to-rf1", null, unzipLocation); <add> } else { <add> // Work in the traditional temp file location for the OS <add> tempDir = Files.createTempDir(); <add> } <add> } catch (IOException e) { <add> throw new RF1ConversionException("Unable to create temporary directory for archive extration"); <add> } <ide> // We only need to work with the full files <ide> unzipFlat(rf2Archive, tempDir, "Full"); <ide> return tempDir; <ide> <ide> private void init(String[] args, File dbLocation) throws RF1ConversionException { <ide> if (args.length < 1) { <del> print("Usage: java ConversionManager [-v] <rf2 archive location>"); <add> print("Usage: java ConversionManager [-v] [-u <unzip location>] <rf2 archive location>"); <ide> exit(); <ide> } <add> boolean isUnzipLocation = false; <ide> <ide> for (String thisArg : args) { <ide> if (thisArg.equals("-v")) { <ide> GlobalUtils.verbose = true; <ide> } else if (thisArg.equals("-h")) { <ide> includeHistory = true; <add> } else if (thisArg.equals("-u")) { <add> isUnzipLocation = true; <add> } else if (isUnzipLocation) { <add> unzipLocation = new File(thisArg); <add> if (!unzipLocation.isDirectory()) { <add> throw new RF1ConversionException(thisArg + " is an invalid location to unzip archive to!"); <add> } <add> isUnzipLocation = false; <ide> } else { <ide> File possibleArchive = new File(thisArg); <ide> if (possibleArchive.exists() && !possibleArchive.isDirectory() && possibleArchive.canRead()) {
Java
apache-2.0
9e9e13fbe0982f7ef8738a0114ee228e00993edf
0
PDXFinder/pdxfinder,PDXFinder/pdxfinder,PDXFinder/pdxfinder,PDXFinder/pdxfinder
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.pdxfinder.services; //import org.apache.commons.cli.Option; import org.pdxfinder.dao.*; import org.pdxfinder.repositories.*; import org.pdxfinder.services.ds.Standardizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import java.util.Collection; import java.util.List; import java.util.Set; /** * The hope was to put a lot of reused repository actions into one place ie find * or create a node or create a node with that requires a number of 'child' * nodes that are terms * * @author sbn */ @Component public class DataImportService { //public static Option loadAll = new Option("LoadAll", false, "Load all PDX Finder data"); private TumorTypeRepository tumorTypeRepository; private HostStrainRepository hostStrainRepository; private EngraftmentTypeRepository engraftmentTypeRepository; private EngraftmentSiteRepository engraftmentSiteRepository; private GroupRepository groupRepository; private PatientRepository patientRepository; private ModelCreationRepository modelCreationRepository; private TissueRepository tissueRepository; private PatientSnapshotRepository patientSnapshotRepository; private SampleRepository sampleRepository; private MarkerRepository markerRepository; private MarkerAssociationRepository markerAssociationRepository; private MolecularCharacterizationRepository molecularCharacterizationRepository; private QualityAssuranceRepository qualityAssuranceRepository; private OntologyTermRepository ontologyTermRepository; private SpecimenRepository specimenRepository; private PlatformRepository platformRepository; private PlatformAssociationRepository platformAssociationRepository; private DataProjectionRepository dataProjectionRepository; private TreatmentSummaryRepository treatmentSummaryRepository; private TreatmentProtocolRepository treatmentProtocolRepository; private CurrentTreatmentRepository currentTreatmentRepository; private ExternalUrlRepository externalUrlRepository; private final static Logger log = LoggerFactory.getLogger(DataImportService.class); public DataImportService(TumorTypeRepository tumorTypeRepository, HostStrainRepository hostStrainRepository, EngraftmentTypeRepository engraftmentTypeRepository, EngraftmentSiteRepository engraftmentSiteRepository, GroupRepository groupRepository, PatientRepository patientRepository, ModelCreationRepository modelCreationRepository, TissueRepository tissueRepository, PatientSnapshotRepository patientSnapshotRepository, SampleRepository sampleRepository, MarkerRepository markerRepository, MarkerAssociationRepository markerAssociationRepository, MolecularCharacterizationRepository molecularCharacterizationRepository, QualityAssuranceRepository qualityAssuranceRepository, OntologyTermRepository ontologyTermRepository, SpecimenRepository specimenRepository, PlatformRepository platformRepository, PlatformAssociationRepository platformAssociationRepository, DataProjectionRepository dataProjectionRepository, TreatmentSummaryRepository treatmentSummaryRepository, TreatmentProtocolRepository treatmentProtocolRepository, CurrentTreatmentRepository currentTreatmentRepository, ExternalUrlRepository externalUrlRepository) { Assert.notNull(tumorTypeRepository, "tumorTypeRepository cannot be null"); Assert.notNull(hostStrainRepository, "hostStrainRepository cannot be null"); Assert.notNull(engraftmentTypeRepository, "implantationTypeRepository cannot be null"); Assert.notNull(engraftmentSiteRepository, "implantationSiteRepository cannot be null"); Assert.notNull(groupRepository, "GroupRepository cannot be null"); Assert.notNull(patientRepository, "patientRepository cannot be null"); Assert.notNull(modelCreationRepository, "modelCreationRepository cannot be null"); Assert.notNull(tissueRepository, "tissueRepository cannot be null"); Assert.notNull(patientSnapshotRepository, "patientSnapshotRepository cannot be null"); Assert.notNull(sampleRepository, "sampleRepository cannot be null"); Assert.notNull(markerRepository, "markerRepository cannot be null"); Assert.notNull(markerAssociationRepository, "markerAssociationRepository cannot be null"); Assert.notNull(molecularCharacterizationRepository, "molecularCharacterizationRepository cannot be null"); Assert.notNull(externalUrlRepository, "externalUrlRepository cannot be null"); this.tumorTypeRepository = tumorTypeRepository; this.hostStrainRepository = hostStrainRepository; this.engraftmentTypeRepository = engraftmentTypeRepository; this.engraftmentSiteRepository = engraftmentSiteRepository; this.groupRepository = groupRepository; this.patientRepository = patientRepository; this.modelCreationRepository = modelCreationRepository; this.tissueRepository = tissueRepository; this.patientSnapshotRepository = patientSnapshotRepository; this.sampleRepository = sampleRepository; this.markerRepository = markerRepository; this.markerAssociationRepository = markerAssociationRepository; this.molecularCharacterizationRepository = molecularCharacterizationRepository; this.qualityAssuranceRepository = qualityAssuranceRepository; this.ontologyTermRepository = ontologyTermRepository; this.specimenRepository = specimenRepository; this.platformRepository = platformRepository; this.platformAssociationRepository = platformAssociationRepository; this.dataProjectionRepository = dataProjectionRepository; this.treatmentSummaryRepository = treatmentSummaryRepository; this.treatmentProtocolRepository = treatmentProtocolRepository; this.currentTreatmentRepository = currentTreatmentRepository; this.externalUrlRepository = externalUrlRepository; } public Group getGroup(String name, String abbrev, String type){ Group g = groupRepository.findByNameAndType(name, type); if(g == null){ log.info("Group not found. Creating", name); g = new Group(name, abbrev, type); groupRepository.save(g); } return g; } public Group getProviderGroup(String name, String abbrev, String description, String providerType, String accessibility, String accessModalities, String contact, String url){ Group g = groupRepository.findByNameAndType(name, "Provider"); if(g == null){ log.info("Provider group not found. Creating", name); g = new Group(name, abbrev, description, providerType, accessibility, accessModalities, contact, url); groupRepository.save(g); } return g; } public ExternalUrl getExternalUrl(ExternalUrl.Type type, String url) { ExternalUrl externalUrl = externalUrlRepository.findByTypeAndUrl(type.getValue(), url); if (externalUrl == null) { log.info("External URL '{}' not found. Creating", type); externalUrl = new ExternalUrl( type, url); externalUrlRepository.save(externalUrl); } return externalUrl; } public ModelCreation createModelCreation(String pdxId, String dataSource, Sample sample, QualityAssurance qa, List<ExternalUrl> externalUrls) { ModelCreation modelCreation = modelCreationRepository.findBySourcePdxIdAndDataSource(pdxId, dataSource); if (modelCreation != null) { log.info("Deleting existing ModelCreation " + pdxId); modelCreationRepository.delete(modelCreation); } modelCreation = new ModelCreation(pdxId, dataSource, sample, qa, externalUrls); modelCreationRepository.save(modelCreation); return modelCreation; } public ModelCreation createModelCreation(String pdxId, String dataSource, Sample sample, List<QualityAssurance> qa, List<ExternalUrl> externalUrls) { ModelCreation modelCreation = modelCreationRepository.findBySourcePdxIdAndDataSource(pdxId, dataSource); if (modelCreation != null) { log.info("Deleting existing ModelCreation " + pdxId); modelCreationRepository.delete(modelCreation); } modelCreation = new ModelCreation(pdxId, dataSource, sample, qa, externalUrls); modelCreationRepository.save(modelCreation); return modelCreation; } public Collection<ModelCreation> findAllModelsPlatforms(){ return modelCreationRepository.findAllModelsPlatforms(); } public int countMarkerAssociationBySourcePdxId(String modelId, String platformName){ return modelCreationRepository.countMarkerAssociationBySourcePdxId(modelId,platformName); } public Collection<ModelCreation> findModelsWithPatientData(){ return modelCreationRepository.findModelsWithPatientData(); } public Collection<ModelCreation> findAllModels(){ return this.modelCreationRepository.findAllModels(); } public ModelCreation findModelByIdAndDataSource(String modelId, String dataSource){ return modelCreationRepository.findBySourcePdxIdAndDataSource(modelId, dataSource); } public void saveModelCreation(ModelCreation modelCreation){ this.modelCreationRepository.save(modelCreation); } public ModelCreation findModelByMolChar(MolecularCharacterization mc){ return modelCreationRepository.findByMolChar(mc); } public Patient createPatient(String patientId, Group dataSource, String sex, String race, String ethnicity){ Patient patient = findPatient(patientId, dataSource); if(patient == null){ patient = this.getPatient(patientId, sex, race, ethnicity, dataSource); patientRepository.save(patient); } return patient; } public Patient findPatient(String patientId, Group dataSource){ return patientRepository.findByExternalIdAndGroup(patientId, dataSource); } public PatientSnapshot getPatientSnapshot(String externalId, String sex, String race, String ethnicity, String age, Group group) { Patient patient = patientRepository.findByExternalIdAndGroup(externalId, group); PatientSnapshot patientSnapshot; if (patient == null) { log.info("Patient '{}' not found. Creating", externalId); patient = this.getPatient(externalId, sex, race, ethnicity, group); patientSnapshot = new PatientSnapshot(patient, age); patientSnapshotRepository.save(patientSnapshot); } else { patientSnapshot = this.getPatientSnapshot(patient, age); } return patientSnapshot; } public PatientSnapshot getPatientSnapshot(Patient patient, String age) { PatientSnapshot patientSnapshot = null; Set<PatientSnapshot> pSnaps = patientSnapshotRepository.findByPatient(patient.getExternalId()); loop: for (PatientSnapshot ps : pSnaps) { if (ps.getAgeAtCollection().equals(age)) { patientSnapshot = ps; break loop; } } if (patientSnapshot == null) { log.info("PatientSnapshot for patient '{}' at age '{}' not found. Creating", patient.getExternalId(), age); patientSnapshot = new PatientSnapshot(patient, age); patientSnapshotRepository.save(patientSnapshot); } return patientSnapshot; } public PatientSnapshot findPatientSnapshot(Patient patient, String ageAtCollection, String collectionDate, String collectionEvent, String ellapsedTime){ PatientSnapshot ps = null; if(patient.getSnapshots() != null){ ps = patient.getSnapShotByCollection(ageAtCollection, collectionDate, collectionEvent, ellapsedTime); } return ps; } public PatientSnapshot getPatientSnapshot(String patientId, String age, String dataSource){ PatientSnapshot ps = patientSnapshotRepository.findByPatientIdAndDataSourceAndAge(patientId, dataSource, age); return ps; } public Patient getPatient(String externalId, String sex, String race, String ethnicity, Group group) { Patient patient = patientRepository.findByExternalIdAndGroup(externalId, group); if (patient == null) { log.info("Patient '{}' not found. Creating", externalId); patient = new Patient(externalId, sex, race, ethnicity, group); patientRepository.save(patient); } return patient; } public Sample getSample(String sourceSampleId, String typeStr, String diagnosis, String originStr, String sampleSiteStr, String extractionMethod, String classification, Boolean normalTissue, String dataSource) { TumorType type = this.getTumorType(typeStr); Tissue origin = this.getTissue(originStr); Tissue sampleSite = this.getTissue(sampleSiteStr); Sample sample = sampleRepository.findBySourceSampleIdAndDataSource(sourceSampleId, dataSource); String updatedDiagnosis = diagnosis; // Changes Malignant * Neoplasm to * Cancer String pattern = "(.*)Malignant(.*)Neoplasm(.*)"; if (diagnosis.matches(pattern)) { updatedDiagnosis = (diagnosis.replaceAll(pattern, "\t$1$2Cancer$3")).trim(); log.info("Replacing diagnosis '{}' with '{}'", diagnosis, updatedDiagnosis); } updatedDiagnosis = updatedDiagnosis.replaceAll(",", ""); if (sample == null) { sample = new Sample(sourceSampleId, type, updatedDiagnosis, origin, sampleSite, extractionMethod, classification, normalTissue, dataSource); sampleRepository.save(sample); } return sample; } public Sample getSample(String sourceSampleId, String dataSource, String typeStr, String diagnosis, String originStr, String sampleSiteStr, String extractionMethod, Boolean normalTissue, String stage, String stageClassification, String grade, String gradeClassification){ TumorType type = this.getTumorType(typeStr); Tissue origin = this.getTissue(originStr); Tissue sampleSite = this.getTissue(sampleSiteStr); Sample sample = sampleRepository.findBySourceSampleIdAndDataSource(sourceSampleId, dataSource); String updatedDiagnosis = diagnosis; // Changes Malignant * Neoplasm to * Cancer String pattern = "(.*)Malignant(.*)Neoplasm(.*)"; if (diagnosis.matches(pattern)) { updatedDiagnosis = (diagnosis.replaceAll(pattern, "\t$1$2Cancer$3")).trim(); log.info("Replacing diagnosis '{}' with '{}'", diagnosis, updatedDiagnosis); } updatedDiagnosis = updatedDiagnosis.replaceAll(",", ""); if (sample == null) { //String sourceSampleId, TumorType type, String diagnosis, Tissue originTissue, Tissue sampleSite, String extractionMethod, // String stage, String stageClassification, String grade, String gradeClassification, Boolean normalTissue, String dataSource sample = new Sample(sourceSampleId, type, updatedDiagnosis, origin, sampleSite, extractionMethod, stage, stage, grade, gradeClassification, normalTissue, dataSource); sampleRepository.save(sample); } return sample; } public Sample findSampleByDataSourceAndSourceSampleId(String dataSource, String sampleId){ return sampleRepository.findBySourceSampleIdAndDataSource(sampleId, dataSource); } public Collection<Sample> findSamplesWithoutOntologyMapping(){ return sampleRepository.findSamplesWithoutOntologyMapping(); } public Sample getMouseSample(ModelCreation model, String specimenId, String dataSource, String passage, String sampleId){ Specimen specimen = this.getSpecimen(model, specimenId, dataSource, passage); Sample sample = null; if(specimen.getSample() == null){ sample = new Sample(); sample.setSourceSampleId(sampleId); sampleRepository.save(sample); } else{ sample = specimen.getSample(); } return sample; } public Sample getHumanSample(String sampleId, String dataSource){ return sampleRepository.findHumanSampleBySampleIdAndDataSource(sampleId, dataSource); } public Sample findHumanSample(String modelId, String dsAbbrev){ return sampleRepository.findHumanSampleByModelIdAndDS(modelId, dsAbbrev); } public Sample findXenograftSample(String modelId, String dataSource, String specimenId){ return sampleRepository.findMouseSampleByModelIdAndDataSourceAndSpecimenId(modelId, dataSource, specimenId); } public int getHumanSamplesNumber(){ return sampleRepository.findHumanSamplesNumber(); } public Collection<Sample> findHumanSamplesFromTo(int from, int to){ return sampleRepository.findHumanSamplesFromTo(from, to); } public void saveSample(Sample sample){ sampleRepository.save(sample); } public EngraftmentSite getImplantationSite(String iSite) { EngraftmentSite site = engraftmentSiteRepository.findByName(iSite); if (site == null) { log.info("Implantation Site '{}' not found. Creating.", iSite); site = new EngraftmentSite(iSite); engraftmentSiteRepository.save(site); } return site; } public EngraftmentType getImplantationType(String iType) { EngraftmentType type = engraftmentTypeRepository.findByName(iType); if (type == null) { log.info("Implantation Site '{}' not found. Creating.", iType); type = new EngraftmentType(iType); engraftmentTypeRepository.save(type); } return type; } public Tissue getTissue(String t) { Tissue tissue = tissueRepository.findByName(t); if (tissue == null) { log.info("Tissue '{}' not found. Creating.", t); tissue = new Tissue(t); tissueRepository.save(tissue); } return tissue; } public TumorType getTumorType(String name) { TumorType tumorType = tumorTypeRepository.findByName(name); if (tumorType == null) { log.info("TumorType '{}' not found. Creating.", name); tumorType = new TumorType(name); tumorTypeRepository.save(tumorType); } return tumorType; } public HostStrain getHostStrain(String name, String symbol, String url, String description) { HostStrain hostStrain = hostStrainRepository.findBySymbol(symbol); if (hostStrain == null) { log.info("Background Strain '{}' not found. Creating", name); hostStrain = new HostStrain(name, symbol, description, url); hostStrainRepository.save(hostStrain); } return hostStrain; } // is this bad? ... probably.. public Marker getMarker(String symbol) { return this.getMarker(symbol, symbol); } public Marker getMarker(String symbol, String name) { Marker marker = markerRepository.findByName(name); if (marker == null && symbol != null) { marker = markerRepository.findBySymbol(symbol); } if (marker == null) { log.info("Marker '{}' not found. Creating", name); marker = new Marker(symbol, name); marker = markerRepository.save(marker); } return marker; } public MarkerAssociation getMarkerAssociation(String type, String markerSymbol, String markerName) { Marker m = this.getMarker(markerSymbol, markerName); MarkerAssociation ma = markerAssociationRepository.findByTypeAndMarkerName(type, m.getName()); if (ma == null && m.getSymbol() != null) { ma = markerAssociationRepository.findByTypeAndMarkerSymbol(type, m.getSymbol()); } if (ma == null) { ma = new MarkerAssociation(type, m); markerAssociationRepository.save(ma); } return ma; } public Set<MarkerAssociation> findMarkerAssocsByMolChar(MolecularCharacterization mc){ return markerAssociationRepository.findByMolChar(mc); } public void savePatientSnapshot(PatientSnapshot ps) { patientSnapshotRepository.save(ps); } public void saveMolecularCharacterization(MolecularCharacterization mc) { molecularCharacterizationRepository.save(mc); } public void saveQualityAssurance(QualityAssurance qa) { if (qa != null) { if (null == qualityAssuranceRepository.findFirstByTechnologyAndDescription(qa.getTechnology(), qa.getDescription())) { qualityAssuranceRepository.save(qa); } } } public Collection<MolecularCharacterization> findMolCharsByType(String type){ return molecularCharacterizationRepository.findAllByType(type); } public Specimen getSpecimen(ModelCreation model, String specimenId, String dataSource, String passage){ Specimen specimen = specimenRepository.findByModelIdAndDataSourceAndSpecimenIdAndPassage(model.getSourcePdxId(), dataSource, specimenId, passage); if(specimen == null){ specimen = new Specimen(); specimen.setExternalId(specimenId); specimen.setPassage(passage); specimenRepository.save(specimen); } return specimen; } public void saveSpecimen(Specimen specimen){ specimenRepository.save(specimen); } public OntologyTerm getOntologyTerm(String url, String label){ OntologyTerm ot = ontologyTermRepository.findByUrl(url); if(ot == null){ ot = new OntologyTerm(url, label); ontologyTermRepository.save(ot); } return ot; } public OntologyTerm getOntologyTerm(String url){ OntologyTerm ot = ontologyTermRepository.findByUrl(url); return ot; } public OntologyTerm findOntologyTermByLabel(String label){ OntologyTerm ot = ontologyTermRepository.findByLabel(label); return ot; } public Collection<OntologyTerm> getAllOntologyTerms() { return ontologyTermRepository.findAll(); } public Collection<OntologyTerm> getAllOntologyTermsWithNotZeroDirectMapping(){ return ontologyTermRepository.findAllWithNotZeroDirectMappingNumber(); } public Collection<OntologyTerm> getAllDirectParents(String termUrl){ return ontologyTermRepository.findAllDirectParents(termUrl); } public int getIndirectMappingNumber(String label) { return ontologyTermRepository.getIndirectMappingNumber(label); } public int findDirectMappingNumber(String label) { Set<OntologyTerm> otset = ontologyTermRepository.getDistinctSubTreeNodes(label); int mapNum = 0; for (OntologyTerm ot : otset) { mapNum += ot.getDirectMappedSamplesNumber(); } return mapNum; } public Collection<OntologyTerm> getAllOntologyTermsFromTo(int from, int to) { return ontologyTermRepository.findAllFromTo(from, to); } public void saveOntologyTerm(OntologyTerm ot){ ontologyTermRepository.save(ot); } public void deleteOntologyTermsWithoutMapping(){ ontologyTermRepository.deleteTermsWithZeroMappings(); } public void saveMarker(Marker marker) { markerRepository.save(marker); } public Collection<Marker> getAllMarkers() { return markerRepository.findAllMarkers(); } public Collection<Marker> getAllHumanMarkers() { return markerRepository.findAllHumanMarkers(); } public Platform getPlatform(String name, Group group) { //remove special characters from platform name name = name.replaceAll("[^A-Za-z0-9 _-]", ""); Platform p = platformRepository.findByNameAndDataSource(name, group.getName()); if (p == null) { p = new Platform(); p.setName(name); p.setGroup(group); // platformRepository.save(p); } return p; } public Platform getPlatform(String name, Group group, String platformUrl) { //remove special characters from platform name name = name.replaceAll("[^A-Za-z0-9 _-]", ""); Platform p = platformRepository.findByNameAndDataSourceAndUrl(name, group.getName(), platformUrl); if (p == null) { p = new Platform(); p.setName(name); p.setGroup(group); p.setUrl(platformUrl); } return p; } public void savePlatform(Platform p){ platformRepository.save(p); } public PlatformAssociation createPlatformAssociation(Platform p, Marker m) { if (platformAssociationRepository == null) { System.out.println("PAR is null"); } if (p == null) { System.out.println("Platform is null"); } if (p.getGroup() == null) { System.out.println("P.EDS is null"); } if (m == null) { System.out.println("Marker is null"); } PlatformAssociation pa = platformAssociationRepository.findByPlatformAndMarker(p.getName(), p.getGroup().getName(), m.getSymbol()); if (pa == null) { pa = new PlatformAssociation(); pa.setPlatform(p); pa.setMarker(m); //platformAssociationRepository.save(pa); } return pa; } public void savePlatformAssociation(PlatformAssociation pa){ platformAssociationRepository.save(pa); } public void saveDataProjection(DataProjection dp){ dataProjectionRepository.save(dp); } public DataProjection findDataProjectionByLabel(String label){ return dataProjectionRepository.findByLabel(label); } public boolean isTreatmentSummaryAvailable(String dataSource, String modelId){ TreatmentSummary ts = treatmentSummaryRepository.findByDataSourceAndModelId(dataSource, modelId); if(ts != null && ts.getTreatmentProtocols() != null){ return true; } return false; } public ModelCreation findModelByTreatmentSummary(TreatmentSummary ts){ return modelCreationRepository.findByTreatmentSummary(ts); } public Drug getStandardizedDrug(String drugString){ Drug d = new Drug(); d.setName(Standardizer.getDrugName(drugString)); return d; } public CurrentTreatment getCurrentTreatment(String name){ CurrentTreatment ct = currentTreatmentRepository.findByName(name); if(ct == null){ ct = new CurrentTreatment(name); currentTreatmentRepository.save(ct); } return ct; } /** * * @param drugString * @param doseString * @param response * @return * * Creates a (tp:TreatmentProtocol)--(tc:TreatmentComponent)--(d:Drug) * (tp)--(r:Response) node */ public TreatmentProtocol getTreatmentProtocol(String drugString, String doseString, String response){ TreatmentProtocol tp = new TreatmentProtocol(); //combination of drugs? if(drugString.contains("+") && doseString.contains(";")){ String[] drugArray = drugString.split("\\+"); String[] doseArray = doseString.split(";"); if(drugArray.length == doseArray.length){ for(int i=0;i<drugArray.length;i++){ Drug d = getStandardizedDrug(drugArray[i].trim()); TreatmentComponent tc = new TreatmentComponent(); tc.setType(Standardizer.getTreatmentComponentType(drugArray[i])); tc.setDose(doseArray[i].trim()); tc.setDrug(d); tp.addTreatmentComponent(tc); } } else{ //TODO: deal with the case when there are more drugs than doses or vice versa } } else if(drugString.contains("+") && !doseString.contains(";")){ String[] drugArray = drugString.split("\\+"); for(int i=0;i<drugArray.length;i++){ Drug d = getStandardizedDrug(drugArray[i].trim()); TreatmentComponent tc = new TreatmentComponent(); tc.setType(Standardizer.getTreatmentComponentType(drugArray[i])); tc.setDose(doseString.trim()); tc.setDrug(d); tp.addTreatmentComponent(tc); } } //one drug only else{ Drug d = getStandardizedDrug(drugString.trim()); TreatmentComponent tc = new TreatmentComponent(); tc.setType(Standardizer.getTreatmentComponentType(drugString)); tc.setDrug(d); tc.setDose(doseString.trim()); tp.addTreatmentComponent(tc); } Response r = new Response(); r.setDescription(Standardizer.getDrugResponse(response)); tp.setResponse(r); return tp; } public TreatmentProtocol getTreatmentProtocol(String drugString, String doseString, String response, boolean currentTreatment){ TreatmentProtocol tp = getTreatmentProtocol(drugString, doseString, response); if(currentTreatment && tp.getCurrentTreatment() == null){ CurrentTreatment ct = getCurrentTreatment("Current Treatment"); tp.setCurrentTreatment(ct); } return tp; } }
data-services/src/main/java/org/pdxfinder/services/DataImportService.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.pdxfinder.services; //import org.apache.commons.cli.Option; import org.pdxfinder.dao.*; import org.pdxfinder.repositories.*; import org.pdxfinder.services.ds.Standardizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import java.util.Collection; import java.util.List; import java.util.Set; /** * The hope was to put a lot of reused repository actions into one place ie find * or create a node or create a node with that requires a number of 'child' * nodes that are terms * * @author sbn */ @Component public class DataImportService { //public static Option loadAll = new Option("LoadAll", false, "Load all PDX Finder data"); private TumorTypeRepository tumorTypeRepository; private HostStrainRepository hostStrainRepository; private EngraftmentTypeRepository engraftmentTypeRepository; private EngraftmentSiteRepository engraftmentSiteRepository; private GroupRepository groupRepository; private PatientRepository patientRepository; private ModelCreationRepository modelCreationRepository; private TissueRepository tissueRepository; private PatientSnapshotRepository patientSnapshotRepository; private SampleRepository sampleRepository; private MarkerRepository markerRepository; private MarkerAssociationRepository markerAssociationRepository; private MolecularCharacterizationRepository molecularCharacterizationRepository; private QualityAssuranceRepository qualityAssuranceRepository; private OntologyTermRepository ontologyTermRepository; private SpecimenRepository specimenRepository; private PlatformRepository platformRepository; private PlatformAssociationRepository platformAssociationRepository; private DataProjectionRepository dataProjectionRepository; private TreatmentSummaryRepository treatmentSummaryRepository; private TreatmentProtocolRepository treatmentProtocolRepository; private CurrentTreatmentRepository currentTreatmentRepository; private ExternalUrlRepository externalUrlRepository; private final static Logger log = LoggerFactory.getLogger(DataImportService.class); public DataImportService(TumorTypeRepository tumorTypeRepository, HostStrainRepository hostStrainRepository, EngraftmentTypeRepository engraftmentTypeRepository, EngraftmentSiteRepository engraftmentSiteRepository, GroupRepository groupRepository, PatientRepository patientRepository, ModelCreationRepository modelCreationRepository, TissueRepository tissueRepository, PatientSnapshotRepository patientSnapshotRepository, SampleRepository sampleRepository, MarkerRepository markerRepository, MarkerAssociationRepository markerAssociationRepository, MolecularCharacterizationRepository molecularCharacterizationRepository, QualityAssuranceRepository qualityAssuranceRepository, OntologyTermRepository ontologyTermRepository, SpecimenRepository specimenRepository, PlatformRepository platformRepository, PlatformAssociationRepository platformAssociationRepository, DataProjectionRepository dataProjectionRepository, TreatmentSummaryRepository treatmentSummaryRepository, TreatmentProtocolRepository treatmentProtocolRepository, CurrentTreatmentRepository currentTreatmentRepository, ExternalUrlRepository externalUrlRepository) { Assert.notNull(tumorTypeRepository, "tumorTypeRepository cannot be null"); Assert.notNull(hostStrainRepository, "hostStrainRepository cannot be null"); Assert.notNull(engraftmentTypeRepository, "implantationTypeRepository cannot be null"); Assert.notNull(engraftmentSiteRepository, "implantationSiteRepository cannot be null"); Assert.notNull(groupRepository, "GroupRepository cannot be null"); Assert.notNull(patientRepository, "patientRepository cannot be null"); Assert.notNull(modelCreationRepository, "modelCreationRepository cannot be null"); Assert.notNull(tissueRepository, "tissueRepository cannot be null"); Assert.notNull(patientSnapshotRepository, "patientSnapshotRepository cannot be null"); Assert.notNull(sampleRepository, "sampleRepository cannot be null"); Assert.notNull(markerRepository, "markerRepository cannot be null"); Assert.notNull(markerAssociationRepository, "markerAssociationRepository cannot be null"); Assert.notNull(molecularCharacterizationRepository, "molecularCharacterizationRepository cannot be null"); Assert.notNull(externalUrlRepository, "externalUrlRepository cannot be null"); this.tumorTypeRepository = tumorTypeRepository; this.hostStrainRepository = hostStrainRepository; this.engraftmentTypeRepository = engraftmentTypeRepository; this.engraftmentSiteRepository = engraftmentSiteRepository; this.groupRepository = groupRepository; this.patientRepository = patientRepository; this.modelCreationRepository = modelCreationRepository; this.tissueRepository = tissueRepository; this.patientSnapshotRepository = patientSnapshotRepository; this.sampleRepository = sampleRepository; this.markerRepository = markerRepository; this.markerAssociationRepository = markerAssociationRepository; this.molecularCharacterizationRepository = molecularCharacterizationRepository; this.qualityAssuranceRepository = qualityAssuranceRepository; this.ontologyTermRepository = ontologyTermRepository; this.specimenRepository = specimenRepository; this.platformRepository = platformRepository; this.platformAssociationRepository = platformAssociationRepository; this.dataProjectionRepository = dataProjectionRepository; this.treatmentSummaryRepository = treatmentSummaryRepository; this.treatmentProtocolRepository = treatmentProtocolRepository; this.currentTreatmentRepository = currentTreatmentRepository; this.externalUrlRepository = externalUrlRepository; } public Group getGroup(String name, String abbrev, String type){ Group g = groupRepository.findByNameAndType(name, type); if(g == null){ log.info("Group not found. Creating", name); g = new Group(name, abbrev, type); groupRepository.save(g); } return g; } public Group getProviderGroup(String name, String abbrev, String description, String providerType, String accessibility, String accessModalities, String contact, String url){ Group g = groupRepository.findByNameAndType(name, "Provider"); if(g == null){ log.info("Provider group not found. Creating", name); g = new Group(name, abbrev, description, providerType, accessibility, accessModalities, contact, url); groupRepository.save(g); } return g; } public ExternalUrl getExternalUrl(ExternalUrl.Type type, String url) { ExternalUrl externalUrl = externalUrlRepository.findByTypeAndUrl(type.getValue(), url); if (externalUrl == null) { log.info("External URL '{}' not found. Creating", type); externalUrl = new ExternalUrl( type, url); externalUrlRepository.save(externalUrl); } return externalUrl; } public ModelCreation createModelCreation(String pdxId, String dataSource, Sample sample, QualityAssurance qa, List<ExternalUrl> externalUrls) { ModelCreation modelCreation = modelCreationRepository.findBySourcePdxIdAndDataSource(pdxId, dataSource); if (modelCreation != null) { log.info("Deleting existing ModelCreation " + pdxId); modelCreationRepository.delete(modelCreation); } modelCreation = new ModelCreation(pdxId, dataSource, sample, qa, externalUrls); modelCreationRepository.save(modelCreation); return modelCreation; } public ModelCreation createModelCreation(String pdxId, String dataSource, Sample sample, List<QualityAssurance> qa, List<ExternalUrl> externalUrls) { ModelCreation modelCreation = modelCreationRepository.findBySourcePdxIdAndDataSource(pdxId, dataSource); if (modelCreation != null) { log.info("Deleting existing ModelCreation " + pdxId); modelCreationRepository.delete(modelCreation); } modelCreation = new ModelCreation(pdxId, dataSource, sample, qa, externalUrls); modelCreationRepository.save(modelCreation); return modelCreation; } public Collection<ModelCreation> findAllModelsPlatforms(){ return modelCreationRepository.findAllModelsPlatforms(); } public int countMarkerAssociationBySourcePdxId(String modelId, String platformName){ return modelCreationRepository.countMarkerAssociationBySourcePdxId(modelId,platformName); } public Collection<ModelCreation> findModelsWithPatientData(){ return modelCreationRepository.findModelsWithPatientData(); } public Collection<ModelCreation> findAllModels(){ return this.modelCreationRepository.findAllModels(); } public ModelCreation findModelByIdAndDataSource(String modelId, String dataSource){ return modelCreationRepository.findBySourcePdxIdAndDataSource(modelId, dataSource); } public void saveModelCreation(ModelCreation modelCreation){ this.modelCreationRepository.save(modelCreation); } public ModelCreation findModelByMolChar(MolecularCharacterization mc){ return modelCreationRepository.findByMolChar(mc); } public PatientSnapshot getPatientSnapshot(String externalId, String sex, String race, String ethnicity, String age, Group group) { Patient patient = patientRepository.findByExternalIdAndGroup(externalId, group); PatientSnapshot patientSnapshot; if (patient == null) { log.info("Patient '{}' not found. Creating", externalId); patient = this.getPatient(externalId, sex, race, ethnicity, group); patientSnapshot = new PatientSnapshot(patient, age); patientSnapshotRepository.save(patientSnapshot); } else { patientSnapshot = this.getPatientSnapshot(patient, age); } return patientSnapshot; } public PatientSnapshot getPatientSnapshot(Patient patient, String age) { PatientSnapshot patientSnapshot = null; Set<PatientSnapshot> pSnaps = patientSnapshotRepository.findByPatient(patient.getExternalId()); loop: for (PatientSnapshot ps : pSnaps) { if (ps.getAgeAtCollection().equals(age)) { patientSnapshot = ps; break loop; } } if (patientSnapshot == null) { log.info("PatientSnapshot for patient '{}' at age '{}' not found. Creating", patient.getExternalId(), age); patientSnapshot = new PatientSnapshot(patient, age); patientSnapshotRepository.save(patientSnapshot); } return patientSnapshot; } public PatientSnapshot getPatientSnapshot(String patientId, String age, String dataSource){ PatientSnapshot ps = patientSnapshotRepository.findByPatientIdAndDataSourceAndAge(patientId, dataSource, age); return ps; } public Patient getPatient(String externalId, String sex, String race, String ethnicity, Group group) { Patient patient = patientRepository.findByExternalIdAndGroup(externalId, group); if (patient == null) { log.info("Patient '{}' not found. Creating", externalId); patient = new Patient(externalId, sex, race, ethnicity, group); patientRepository.save(patient); } return patient; } public Sample getSample(String sourceSampleId, String typeStr, String diagnosis, String originStr, String sampleSiteStr, String extractionMethod, String classification, Boolean normalTissue, String dataSource) { TumorType type = this.getTumorType(typeStr); Tissue origin = this.getTissue(originStr); Tissue sampleSite = this.getTissue(sampleSiteStr); Sample sample = sampleRepository.findBySourceSampleIdAndDataSource(sourceSampleId, dataSource); String updatedDiagnosis = diagnosis; // Changes Malignant * Neoplasm to * Cancer String pattern = "(.*)Malignant(.*)Neoplasm(.*)"; if (diagnosis.matches(pattern)) { updatedDiagnosis = (diagnosis.replaceAll(pattern, "\t$1$2Cancer$3")).trim(); log.info("Replacing diagnosis '{}' with '{}'", diagnosis, updatedDiagnosis); } updatedDiagnosis = updatedDiagnosis.replaceAll(",", ""); if (sample == null) { sample = new Sample(sourceSampleId, type, updatedDiagnosis, origin, sampleSite, extractionMethod, classification, normalTissue, dataSource); sampleRepository.save(sample); } return sample; } public Sample findSampleByDataSourceAndSourceSampleId(String dataSource, String sampleId){ return sampleRepository.findBySourceSampleIdAndDataSource(sampleId, dataSource); } public Collection<Sample> findSamplesWithoutOntologyMapping(){ return sampleRepository.findSamplesWithoutOntologyMapping(); } public Sample getMouseSample(ModelCreation model, String specimenId, String dataSource, String passage, String sampleId){ Specimen specimen = this.getSpecimen(model, specimenId, dataSource, passage); Sample sample = null; if(specimen.getSample() == null){ sample = new Sample(); sample.setSourceSampleId(sampleId); sampleRepository.save(sample); } else{ sample = specimen.getSample(); } return sample; } public Sample getHumanSample(String sampleId, String dataSource){ return sampleRepository.findHumanSampleBySampleIdAndDataSource(sampleId, dataSource); } public Sample findHumanSample(String modelId, String dsAbbrev){ return sampleRepository.findHumanSampleByModelIdAndDS(modelId, dsAbbrev); } public Sample findXenograftSample(String modelId, String dataSource, String specimenId){ return sampleRepository.findMouseSampleByModelIdAndDataSourceAndSpecimenId(modelId, dataSource, specimenId); } public int getHumanSamplesNumber(){ return sampleRepository.findHumanSamplesNumber(); } public Collection<Sample> findHumanSamplesFromTo(int from, int to){ return sampleRepository.findHumanSamplesFromTo(from, to); } public void saveSample(Sample sample){ sampleRepository.save(sample); } public EngraftmentSite getImplantationSite(String iSite) { EngraftmentSite site = engraftmentSiteRepository.findByName(iSite); if (site == null) { log.info("Implantation Site '{}' not found. Creating.", iSite); site = new EngraftmentSite(iSite); engraftmentSiteRepository.save(site); } return site; } public EngraftmentType getImplantationType(String iType) { EngraftmentType type = engraftmentTypeRepository.findByName(iType); if (type == null) { log.info("Implantation Site '{}' not found. Creating.", iType); type = new EngraftmentType(iType); engraftmentTypeRepository.save(type); } return type; } public Tissue getTissue(String t) { Tissue tissue = tissueRepository.findByName(t); if (tissue == null) { log.info("Tissue '{}' not found. Creating.", t); tissue = new Tissue(t); tissueRepository.save(tissue); } return tissue; } public TumorType getTumorType(String name) { TumorType tumorType = tumorTypeRepository.findByName(name); if (tumorType == null) { log.info("TumorType '{}' not found. Creating.", name); tumorType = new TumorType(name); tumorTypeRepository.save(tumorType); } return tumorType; } public HostStrain getHostStrain(String name, String symbol, String url, String description) { HostStrain hostStrain = hostStrainRepository.findBySymbol(symbol); if (hostStrain == null) { log.info("Background Strain '{}' not found. Creating", name); hostStrain = new HostStrain(name, symbol, description, url); hostStrainRepository.save(hostStrain); } return hostStrain; } // is this bad? ... probably.. public Marker getMarker(String symbol) { return this.getMarker(symbol, symbol); } public Marker getMarker(String symbol, String name) { Marker marker = markerRepository.findByName(name); if (marker == null && symbol != null) { marker = markerRepository.findBySymbol(symbol); } if (marker == null) { log.info("Marker '{}' not found. Creating", name); marker = new Marker(symbol, name); marker = markerRepository.save(marker); } return marker; } public MarkerAssociation getMarkerAssociation(String type, String markerSymbol, String markerName) { Marker m = this.getMarker(markerSymbol, markerName); MarkerAssociation ma = markerAssociationRepository.findByTypeAndMarkerName(type, m.getName()); if (ma == null && m.getSymbol() != null) { ma = markerAssociationRepository.findByTypeAndMarkerSymbol(type, m.getSymbol()); } if (ma == null) { ma = new MarkerAssociation(type, m); markerAssociationRepository.save(ma); } return ma; } public Set<MarkerAssociation> findMarkerAssocsByMolChar(MolecularCharacterization mc){ return markerAssociationRepository.findByMolChar(mc); } public void savePatientSnapshot(PatientSnapshot ps) { patientSnapshotRepository.save(ps); } public void saveMolecularCharacterization(MolecularCharacterization mc) { molecularCharacterizationRepository.save(mc); } public void saveQualityAssurance(QualityAssurance qa) { if (qa != null) { if (null == qualityAssuranceRepository.findFirstByTechnologyAndDescription(qa.getTechnology(), qa.getDescription())) { qualityAssuranceRepository.save(qa); } } } public Collection<MolecularCharacterization> findMolCharsByType(String type){ return molecularCharacterizationRepository.findAllByType(type); } public Specimen getSpecimen(ModelCreation model, String specimenId, String dataSource, String passage){ Specimen specimen = specimenRepository.findByModelIdAndDataSourceAndSpecimenIdAndPassage(model.getSourcePdxId(), dataSource, specimenId, passage); if(specimen == null){ specimen = new Specimen(); specimen.setExternalId(specimenId); specimen.setPassage(passage); specimenRepository.save(specimen); } return specimen; } public void saveSpecimen(Specimen specimen){ specimenRepository.save(specimen); } public OntologyTerm getOntologyTerm(String url, String label){ OntologyTerm ot = ontologyTermRepository.findByUrl(url); if(ot == null){ ot = new OntologyTerm(url, label); ontologyTermRepository.save(ot); } return ot; } public OntologyTerm getOntologyTerm(String url){ OntologyTerm ot = ontologyTermRepository.findByUrl(url); return ot; } public OntologyTerm findOntologyTermByLabel(String label){ OntologyTerm ot = ontologyTermRepository.findByLabel(label); return ot; } public Collection<OntologyTerm> getAllOntologyTerms() { return ontologyTermRepository.findAll(); } public Collection<OntologyTerm> getAllOntologyTermsWithNotZeroDirectMapping(){ return ontologyTermRepository.findAllWithNotZeroDirectMappingNumber(); } public Collection<OntologyTerm> getAllDirectParents(String termUrl){ return ontologyTermRepository.findAllDirectParents(termUrl); } public int getIndirectMappingNumber(String label) { return ontologyTermRepository.getIndirectMappingNumber(label); } public int findDirectMappingNumber(String label) { Set<OntologyTerm> otset = ontologyTermRepository.getDistinctSubTreeNodes(label); int mapNum = 0; for (OntologyTerm ot : otset) { mapNum += ot.getDirectMappedSamplesNumber(); } return mapNum; } public Collection<OntologyTerm> getAllOntologyTermsFromTo(int from, int to) { return ontologyTermRepository.findAllFromTo(from, to); } public void saveOntologyTerm(OntologyTerm ot){ ontologyTermRepository.save(ot); } public void deleteOntologyTermsWithoutMapping(){ ontologyTermRepository.deleteTermsWithZeroMappings(); } public void saveMarker(Marker marker) { markerRepository.save(marker); } public Collection<Marker> getAllMarkers() { return markerRepository.findAllMarkers(); } public Collection<Marker> getAllHumanMarkers() { return markerRepository.findAllHumanMarkers(); } public Platform getPlatform(String name, Group group) { //remove special characters from platform name name = name.replaceAll("[^A-Za-z0-9 _-]", ""); Platform p = platformRepository.findByNameAndDataSource(name, group.getName()); if (p == null) { p = new Platform(); p.setName(name); p.setGroup(group); // platformRepository.save(p); } return p; } public Platform getPlatform(String name, Group group, String platformUrl) { //remove special characters from platform name name = name.replaceAll("[^A-Za-z0-9 _-]", ""); Platform p = platformRepository.findByNameAndDataSourceAndUrl(name, group.getName(), platformUrl); if (p == null) { p = new Platform(); p.setName(name); p.setGroup(group); p.setUrl(platformUrl); } return p; } public void savePlatform(Platform p){ platformRepository.save(p); } public PlatformAssociation createPlatformAssociation(Platform p, Marker m) { if (platformAssociationRepository == null) { System.out.println("PAR is null"); } if (p == null) { System.out.println("Platform is null"); } if (p.getGroup() == null) { System.out.println("P.EDS is null"); } if (m == null) { System.out.println("Marker is null"); } PlatformAssociation pa = platformAssociationRepository.findByPlatformAndMarker(p.getName(), p.getGroup().getName(), m.getSymbol()); if (pa == null) { pa = new PlatformAssociation(); pa.setPlatform(p); pa.setMarker(m); //platformAssociationRepository.save(pa); } return pa; } public void savePlatformAssociation(PlatformAssociation pa){ platformAssociationRepository.save(pa); } public void saveDataProjection(DataProjection dp){ dataProjectionRepository.save(dp); } public DataProjection findDataProjectionByLabel(String label){ return dataProjectionRepository.findByLabel(label); } public boolean isTreatmentSummaryAvailable(String dataSource, String modelId){ TreatmentSummary ts = treatmentSummaryRepository.findByDataSourceAndModelId(dataSource, modelId); if(ts != null && ts.getTreatmentProtocols() != null){ return true; } return false; } public ModelCreation findModelByTreatmentSummary(TreatmentSummary ts){ return modelCreationRepository.findByTreatmentSummary(ts); } public Drug getStandardizedDrug(String drugString){ Drug d = new Drug(); d.setName(Standardizer.getDrugName(drugString)); return d; } public CurrentTreatment getCurrentTreatment(String name){ CurrentTreatment ct = currentTreatmentRepository.findByName(name); if(ct == null){ ct = new CurrentTreatment(name); currentTreatmentRepository.save(ct); } return ct; } /** * * @param drugString * @param doseString * @param response * @return * * Creates a (tp:TreatmentProtocol)--(tc:TreatmentComponent)--(d:Drug) * (tp)--(r:Response) node */ public TreatmentProtocol getTreatmentProtocol(String drugString, String doseString, String response){ TreatmentProtocol tp = new TreatmentProtocol(); //combination of drugs? if(drugString.contains("+") && doseString.contains(";")){ String[] drugArray = drugString.split("\\+"); String[] doseArray = doseString.split(";"); if(drugArray.length == doseArray.length){ for(int i=0;i<drugArray.length;i++){ Drug d = getStandardizedDrug(drugArray[i].trim()); TreatmentComponent tc = new TreatmentComponent(); tc.setType(Standardizer.getTreatmentComponentType(drugArray[i])); tc.setDose(doseArray[i].trim()); tc.setDrug(d); tp.addTreatmentComponent(tc); } } else{ //TODO: deal with the case when there are more drugs than doses or vice versa } } else if(drugString.contains("+") && !doseString.contains(";")){ String[] drugArray = drugString.split("\\+"); for(int i=0;i<drugArray.length;i++){ Drug d = getStandardizedDrug(drugArray[i].trim()); TreatmentComponent tc = new TreatmentComponent(); tc.setType(Standardizer.getTreatmentComponentType(drugArray[i])); tc.setDose(doseString.trim()); tc.setDrug(d); tp.addTreatmentComponent(tc); } } //one drug only else{ Drug d = getStandardizedDrug(drugString.trim()); TreatmentComponent tc = new TreatmentComponent(); tc.setType(Standardizer.getTreatmentComponentType(drugString)); tc.setDrug(d); tc.setDose(doseString.trim()); tp.addTreatmentComponent(tc); } Response r = new Response(); r.setDescription(Standardizer.getDrugResponse(response)); tp.setResponse(r); return tp; } public TreatmentProtocol getTreatmentProtocol(String drugString, String doseString, String response, boolean currentTreatment){ TreatmentProtocol tp = getTreatmentProtocol(drugString, doseString, response); if(currentTreatment && tp.getCurrentTreatment() == null){ CurrentTreatment ct = getCurrentTreatment("Current Treatment"); tp.setCurrentTreatment(ct); } return tp; } }
Add support methods for creating patients and samples
data-services/src/main/java/org/pdxfinder/services/DataImportService.java
Add support methods for creating patients and samples
<ide><path>ata-services/src/main/java/org/pdxfinder/services/DataImportService.java <ide> return modelCreationRepository.findByMolChar(mc); <ide> } <ide> <add> public Patient createPatient(String patientId, Group dataSource, String sex, String race, String ethnicity){ <add> <add> Patient patient = findPatient(patientId, dataSource); <add> <add> if(patient == null){ <add> <add> patient = this.getPatient(patientId, sex, race, ethnicity, dataSource); <add> patientRepository.save(patient); <add> } <add> <add> return patient; <add> } <add> <add> public Patient findPatient(String patientId, Group dataSource){ <add> <add> return patientRepository.findByExternalIdAndGroup(patientId, dataSource); <add> <add> } <add> <add> <add> <ide> public PatientSnapshot getPatientSnapshot(String externalId, String sex, String race, String ethnicity, String age, Group group) { <ide> <ide> Patient patient = patientRepository.findByExternalIdAndGroup(externalId, group); <ide> return patientSnapshot; <ide> } <ide> <add> public PatientSnapshot findPatientSnapshot(Patient patient, String ageAtCollection, String collectionDate, String collectionEvent, String ellapsedTime){ <add> <add> PatientSnapshot ps = null; <add> <add> if(patient.getSnapshots() != null){ <add> ps = patient.getSnapShotByCollection(ageAtCollection, collectionDate, collectionEvent, ellapsedTime); <add> } <add> <add> return ps; <add> } <add> <add> <ide> public PatientSnapshot getPatientSnapshot(String patientId, String age, String dataSource){ <ide> <ide> PatientSnapshot ps = patientSnapshotRepository.findByPatientIdAndDataSourceAndAge(patientId, dataSource, age); <ide> <ide> return sample; <ide> } <add> <add> public Sample getSample(String sourceSampleId, String dataSource, String typeStr, String diagnosis, String originStr, <add> String sampleSiteStr, String extractionMethod, Boolean normalTissue, String stage, String stageClassification, <add> String grade, String gradeClassification){ <add> <add> TumorType type = this.getTumorType(typeStr); <add> Tissue origin = this.getTissue(originStr); <add> Tissue sampleSite = this.getTissue(sampleSiteStr); <add> Sample sample = sampleRepository.findBySourceSampleIdAndDataSource(sourceSampleId, dataSource); <add> <add> String updatedDiagnosis = diagnosis; <add> <add> // Changes Malignant * Neoplasm to * Cancer <add> String pattern = "(.*)Malignant(.*)Neoplasm(.*)"; <add> <add> if (diagnosis.matches(pattern)) { <add> updatedDiagnosis = (diagnosis.replaceAll(pattern, "\t$1$2Cancer$3")).trim(); <add> log.info("Replacing diagnosis '{}' with '{}'", diagnosis, updatedDiagnosis); <add> } <add> <add> updatedDiagnosis = updatedDiagnosis.replaceAll(",", ""); <add> <add> if (sample == null) { <add> <add> //String sourceSampleId, TumorType type, String diagnosis, Tissue originTissue, Tissue sampleSite, String extractionMethod, <add> // String stage, String stageClassification, String grade, String gradeClassification, Boolean normalTissue, String dataSource <add> sample = new Sample(sourceSampleId, type, updatedDiagnosis, origin, sampleSite, extractionMethod, stage, stage, grade, gradeClassification, normalTissue, dataSource); <add> sampleRepository.save(sample); <add> } <add> <add> return sample; <add> <add> } <add> <ide> <ide> public Sample findSampleByDataSourceAndSourceSampleId(String dataSource, String sampleId){ <ide>
Java
apache-2.0
c298ca905cf964b9dc8917ddad325660425112a6
0
tmtron/Conductor,tmtron/Conductor,bluelinelabs/Conductor,bluelinelabs/Conductor
package com.bluelinelabs.conductor.internal; import android.annotation.TargetApi; import android.app.Activity; import android.app.Application.ActivityLifecycleCallbacks; import android.app.Fragment; import android.content.Context; import android.content.Intent; import android.content.IntentSender; import android.os.Build; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.SparseArray; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.ViewGroup; import com.bluelinelabs.conductor.ActivityHostedRouter; import com.bluelinelabs.conductor.Router; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class LifecycleHandler extends Fragment implements ActivityLifecycleCallbacks { private static final String FRAGMENT_TAG = "LifecycleHandler"; private static final String KEY_PENDING_PERMISSION_REQUESTS = "LifecycleHandler.pendingPermissionRequests"; private static final String KEY_PERMISSION_REQUEST_CODES = "LifecycleHandler.permissionRequests"; private static final String KEY_ACTIVITY_REQUEST_CODES = "LifecycleHandler.activityRequests"; private static final String KEY_ROUTER_STATE_PREFIX = "LifecycleHandler.routerState"; private Activity activity; private boolean hasRegisteredCallbacks; private boolean destroyed; private boolean attached; private static final Map<Activity, LifecycleHandler> activeLifecycleHandlers = new HashMap<>(); private SparseArray<String> permissionRequestMap = new SparseArray<>(); private SparseArray<String> activityRequestMap = new SparseArray<>(); private ArrayList<PendingPermissionRequest> pendingPermissionRequests = new ArrayList<>(); private final Map<Integer, ActivityHostedRouter> routerMap = new HashMap<>(); public LifecycleHandler() { setRetainInstance(true); setHasOptionsMenu(true); } @Nullable private static LifecycleHandler findInActivity(@NonNull Activity activity) { LifecycleHandler lifecycleHandler = activeLifecycleHandlers.get(activity); if (lifecycleHandler == null) { lifecycleHandler = (LifecycleHandler)activity.getFragmentManager().findFragmentByTag(FRAGMENT_TAG); } if (lifecycleHandler != null) { lifecycleHandler.registerActivityListener(activity); } return lifecycleHandler; } @NonNull public static LifecycleHandler install(@NonNull Activity activity) { LifecycleHandler lifecycleHandler = findInActivity(activity); if (lifecycleHandler == null) { lifecycleHandler = new LifecycleHandler(); activity.getFragmentManager().beginTransaction().add(lifecycleHandler, FRAGMENT_TAG).commit(); } lifecycleHandler.registerActivityListener(activity); return lifecycleHandler; } @NonNull public Router getRouter(@NonNull ViewGroup container, @Nullable Bundle savedInstanceState) { ActivityHostedRouter router = routerMap.get(getRouterHashKey(container)); if (router == null) { router = new ActivityHostedRouter(); router.setHost(this, container); if (savedInstanceState != null) { Bundle routerSavedState = savedInstanceState.getBundle(KEY_ROUTER_STATE_PREFIX + router.getContainerId()); if (routerSavedState != null) { router.restoreInstanceState(routerSavedState); } } routerMap.put(getRouterHashKey(container), router); } else { router.setHost(this, container); } return router; } @NonNull public List<Router> getRouters() { return new ArrayList<Router>(routerMap.values()); } @Nullable public Activity getLifecycleActivity() { return activity; } private static int getRouterHashKey(@NonNull ViewGroup viewGroup) { return viewGroup.getId(); } private void registerActivityListener(@NonNull Activity activity) { this.activity = activity; if (!hasRegisteredCallbacks) { hasRegisteredCallbacks = true; activity.getApplication().registerActivityLifecycleCallbacks(this); // Since Fragment transactions are async, we have to keep an <Activity, LifecycleHandler> map in addition // to trying to find the LifecycleHandler fragment in the Activity to handle the case of the developer // trying to immediately get > 1 router in the same Activity. See issue #299. activeLifecycleHandlers.put(activity, this); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { StringSparseArrayParceler permissionParcel = savedInstanceState.getParcelable(KEY_PERMISSION_REQUEST_CODES); permissionRequestMap = permissionParcel != null ? permissionParcel.getStringSparseArray() : new SparseArray<String>(); StringSparseArrayParceler activityParcel = savedInstanceState.getParcelable(KEY_ACTIVITY_REQUEST_CODES); activityRequestMap = activityParcel != null ? activityParcel.getStringSparseArray() : new SparseArray<String>(); ArrayList<PendingPermissionRequest> pendingRequests = savedInstanceState.getParcelableArrayList(KEY_PENDING_PERMISSION_REQUESTS); pendingPermissionRequests = pendingRequests != null ? pendingRequests : new ArrayList<PendingPermissionRequest>(); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(KEY_PERMISSION_REQUEST_CODES, new StringSparseArrayParceler(permissionRequestMap)); outState.putParcelable(KEY_ACTIVITY_REQUEST_CODES, new StringSparseArrayParceler(activityRequestMap)); outState.putParcelableArrayList(KEY_PENDING_PERMISSION_REQUESTS, pendingPermissionRequests); } @Override public void onDestroy() { super.onDestroy(); if (activity != null) { activity.getApplication().unregisterActivityLifecycleCallbacks(this); activeLifecycleHandlers.remove(activity); destroyRouters(); activity = null; } } @SuppressWarnings("deprecation") @Override public void onAttach(Activity activity) { super.onAttach(activity); destroyed = false; setAttached(); } @Override public void onAttach(Context context) { super.onAttach(context); destroyed = false; setAttached(); } @Override public void onDetach() { super.onDetach(); attached = false; destroyRouters(); } private void setAttached() { if (!attached) { attached = true; for (int i = pendingPermissionRequests.size() - 1; i >= 0; i--) { PendingPermissionRequest request = pendingPermissionRequests.remove(i); requestPermissions(request.instanceId, request.permissions, request.requestCode); } } } private void destroyRouters() { if (!destroyed) { destroyed = true; if (activity != null) { for (Router router : routerMap.values()) { router.onActivityDestroyed(activity); } } } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); String instanceId = activityRequestMap.get(requestCode); if (instanceId != null) { for (Router router : routerMap.values()) { router.onActivityResult(instanceId, requestCode, resultCode, data); } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); String instanceId = permissionRequestMap.get(requestCode); if (instanceId != null) { for (Router router : routerMap.values()) { router.onRequestPermissionsResult(instanceId, requestCode, permissions, grantResults); } } } @Override public boolean shouldShowRequestPermissionRationale(@NonNull String permission) { for (Router router : routerMap.values()) { Boolean handled = router.handleRequestedPermission(permission); if (handled != null) { return handled; } } return super.shouldShowRequestPermissionRationale(permission); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); for (Router router : routerMap.values()) { router.onCreateOptionsMenu(menu, inflater); } } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); for (Router router : routerMap.values()) { router.onPrepareOptionsMenu(menu); } } @Override public boolean onOptionsItemSelected(MenuItem item) { for (Router router : routerMap.values()) { if (router.onOptionsItemSelected(item)) { return true; } } return super.onOptionsItemSelected(item); } public void registerForActivityResult(@NonNull String instanceId, int requestCode) { activityRequestMap.put(requestCode, instanceId); } public void unregisterForActivityResults(@NonNull String instanceId) { for (int i = activityRequestMap.size() - 1; i >= 0; i--) { if (instanceId.equals(activityRequestMap.get(activityRequestMap.keyAt(i)))) { activityRequestMap.removeAt(i); } } } public void startActivityForResult(@NonNull String instanceId, @NonNull Intent intent, int requestCode) { registerForActivityResult(instanceId, requestCode); startActivityForResult(intent, requestCode); } public void startActivityForResult(@NonNull String instanceId, @NonNull Intent intent, int requestCode, @Nullable Bundle options) { registerForActivityResult(instanceId, requestCode); startActivityForResult(intent, requestCode, options); } @TargetApi(Build.VERSION_CODES.N) public void startIntentSenderForResult(@NonNull String instanceId, @NonNull IntentSender intent, int requestCode, @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, @Nullable Bundle options) throws IntentSender.SendIntentException { registerForActivityResult(instanceId, requestCode); startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask, flagsValues, extraFlags, options); } @TargetApi(Build.VERSION_CODES.M) public void requestPermissions(@NonNull String instanceId, @NonNull String[] permissions, int requestCode) { if (attached) { permissionRequestMap.put(requestCode, instanceId); requestPermissions(permissions, requestCode); } else { pendingPermissionRequests.add(new PendingPermissionRequest(instanceId, permissions, requestCode)); } } @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { if (this.activity == null && findInActivity(activity) == LifecycleHandler.this) { this.activity = activity; } } @Override public void onActivityStarted(Activity activity) { if (this.activity == activity) { for (Router router : routerMap.values()) { router.onActivityStarted(activity); } } } @Override public void onActivityResumed(Activity activity) { if (this.activity == activity) { for (Router router : routerMap.values()) { router.onActivityResumed(activity); } } } @Override public void onActivityPaused(Activity activity) { if (this.activity == activity) { for (Router router : routerMap.values()) { router.onActivityPaused(activity); } } } @Override public void onActivityStopped(Activity activity) { if (this.activity == activity) { for (Router router : routerMap.values()) { router.onActivityStopped(activity); } } } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { if (this.activity == activity) { for (Router router : routerMap.values()) { Bundle bundle = new Bundle(); router.saveInstanceState(bundle); outState.putBundle(KEY_ROUTER_STATE_PREFIX + router.getContainerId(), bundle); } } } @Override public void onActivityDestroyed(Activity activity) { activeLifecycleHandlers.remove(activity); } private static class PendingPermissionRequest implements Parcelable { final String instanceId; final String[] permissions; final int requestCode; PendingPermissionRequest(@NonNull String instanceId, @NonNull String[] permissions, int requestCode) { this.instanceId = instanceId; this.permissions = permissions; this.requestCode = requestCode; } private PendingPermissionRequest(Parcel in) { instanceId = in.readString(); permissions = in.createStringArray(); requestCode = in.readInt(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out, int flags) { out.writeString(instanceId); out.writeStringArray(permissions); out.writeInt(requestCode); } public static final Parcelable.Creator<PendingPermissionRequest> CREATOR = new Parcelable.Creator<PendingPermissionRequest>() { @Override public PendingPermissionRequest createFromParcel(Parcel in) { return new PendingPermissionRequest(in); } @Override public PendingPermissionRequest[] newArray(int size) { return new PendingPermissionRequest[size]; } }; } }
conductor/src/main/java/com/bluelinelabs/conductor/internal/LifecycleHandler.java
package com.bluelinelabs.conductor.internal; import android.annotation.TargetApi; import android.app.Activity; import android.app.Application.ActivityLifecycleCallbacks; import android.app.Fragment; import android.content.Context; import android.content.Intent; import android.content.IntentSender; import android.os.Build; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.SparseArray; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.ViewGroup; import com.bluelinelabs.conductor.ActivityHostedRouter; import com.bluelinelabs.conductor.Router; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class LifecycleHandler extends Fragment implements ActivityLifecycleCallbacks { private static final String FRAGMENT_TAG = "LifecycleHandler"; private static final String KEY_PENDING_PERMISSION_REQUESTS = "LifecycleHandler.pendingPermissionRequests"; private static final String KEY_PERMISSION_REQUEST_CODES = "LifecycleHandler.permissionRequests"; private static final String KEY_ACTIVITY_REQUEST_CODES = "LifecycleHandler.activityRequests"; private static final String KEY_ROUTER_STATE_PREFIX = "LifecycleHandler.routerState"; private Activity activity; private boolean hasRegisteredCallbacks; private boolean destroyed; private boolean attached; private static final Map<Activity, LifecycleHandler> activeLifecycleHandlers = new HashMap<>(); private SparseArray<String> permissionRequestMap = new SparseArray<>(); private SparseArray<String> activityRequestMap = new SparseArray<>(); private ArrayList<PendingPermissionRequest> pendingPermissionRequests = new ArrayList<>(); private final Map<Integer, ActivityHostedRouter> routerMap = new HashMap<>(); public LifecycleHandler() { setRetainInstance(true); setHasOptionsMenu(true); } @Nullable private static LifecycleHandler findInActivity(@NonNull Activity activity) { LifecycleHandler lifecycleHandler = activeLifecycleHandlers.get(activity); if (lifecycleHandler == null) { lifecycleHandler = (LifecycleHandler)activity.getFragmentManager().findFragmentByTag(FRAGMENT_TAG); } if (lifecycleHandler != null) { lifecycleHandler.registerActivityListener(activity); } return lifecycleHandler; } @NonNull public static LifecycleHandler install(@NonNull Activity activity) { LifecycleHandler lifecycleHandler = findInActivity(activity); if (lifecycleHandler == null) { lifecycleHandler = new LifecycleHandler(); activity.getFragmentManager().beginTransaction().add(lifecycleHandler, FRAGMENT_TAG).commit(); // Since Fragment transactions are async, we have to keep an <Activity, LifecycleHandler> map in addition // to trying to find the LifecycleHandler fragment in the Activity to handle the case of the developer // trying to immediately get > 1 router in the same Activity. See issue #299. activeLifecycleHandlers.put(activity, lifecycleHandler); } lifecycleHandler.registerActivityListener(activity); return lifecycleHandler; } @NonNull public Router getRouter(@NonNull ViewGroup container, @Nullable Bundle savedInstanceState) { ActivityHostedRouter router = routerMap.get(getRouterHashKey(container)); if (router == null) { router = new ActivityHostedRouter(); router.setHost(this, container); if (savedInstanceState != null) { Bundle routerSavedState = savedInstanceState.getBundle(KEY_ROUTER_STATE_PREFIX + router.getContainerId()); if (routerSavedState != null) { router.restoreInstanceState(routerSavedState); } } routerMap.put(getRouterHashKey(container), router); } else { router.setHost(this, container); } return router; } @NonNull public List<Router> getRouters() { return new ArrayList<Router>(routerMap.values()); } @Nullable public Activity getLifecycleActivity() { return activity; } private static int getRouterHashKey(@NonNull ViewGroup viewGroup) { return viewGroup.getId(); } private void registerActivityListener(@NonNull Activity activity) { this.activity = activity; if (!hasRegisteredCallbacks) { hasRegisteredCallbacks = true; activity.getApplication().registerActivityLifecycleCallbacks(this); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { StringSparseArrayParceler permissionParcel = savedInstanceState.getParcelable(KEY_PERMISSION_REQUEST_CODES); permissionRequestMap = permissionParcel != null ? permissionParcel.getStringSparseArray() : new SparseArray<String>(); StringSparseArrayParceler activityParcel = savedInstanceState.getParcelable(KEY_ACTIVITY_REQUEST_CODES); activityRequestMap = activityParcel != null ? activityParcel.getStringSparseArray() : new SparseArray<String>(); ArrayList<PendingPermissionRequest> pendingRequests = savedInstanceState.getParcelableArrayList(KEY_PENDING_PERMISSION_REQUESTS); pendingPermissionRequests = pendingRequests != null ? pendingRequests : new ArrayList<PendingPermissionRequest>(); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(KEY_PERMISSION_REQUEST_CODES, new StringSparseArrayParceler(permissionRequestMap)); outState.putParcelable(KEY_ACTIVITY_REQUEST_CODES, new StringSparseArrayParceler(activityRequestMap)); outState.putParcelableArrayList(KEY_PENDING_PERMISSION_REQUESTS, pendingPermissionRequests); } @Override public void onDestroy() { super.onDestroy(); if (activity != null) { activity.getApplication().unregisterActivityLifecycleCallbacks(this); destroyRouters(); activity = null; } } @SuppressWarnings("deprecation") @Override public void onAttach(Activity activity) { super.onAttach(activity); destroyed = false; setAttached(); } @Override public void onAttach(Context context) { super.onAttach(context); destroyed = false; setAttached(); } @Override public void onDetach() { super.onDetach(); attached = false; destroyRouters(); } private void setAttached() { if (!attached) { attached = true; for (int i = pendingPermissionRequests.size() - 1; i >= 0; i--) { PendingPermissionRequest request = pendingPermissionRequests.remove(i); requestPermissions(request.instanceId, request.permissions, request.requestCode); } } } private void destroyRouters() { if (!destroyed) { destroyed = true; if (activity != null) { for (Router router : routerMap.values()) { router.onActivityDestroyed(activity); } } } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); String instanceId = activityRequestMap.get(requestCode); if (instanceId != null) { for (Router router : routerMap.values()) { router.onActivityResult(instanceId, requestCode, resultCode, data); } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); String instanceId = permissionRequestMap.get(requestCode); if (instanceId != null) { for (Router router : routerMap.values()) { router.onRequestPermissionsResult(instanceId, requestCode, permissions, grantResults); } } } @Override public boolean shouldShowRequestPermissionRationale(@NonNull String permission) { for (Router router : routerMap.values()) { Boolean handled = router.handleRequestedPermission(permission); if (handled != null) { return handled; } } return super.shouldShowRequestPermissionRationale(permission); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); for (Router router : routerMap.values()) { router.onCreateOptionsMenu(menu, inflater); } } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); for (Router router : routerMap.values()) { router.onPrepareOptionsMenu(menu); } } @Override public boolean onOptionsItemSelected(MenuItem item) { for (Router router : routerMap.values()) { if (router.onOptionsItemSelected(item)) { return true; } } return super.onOptionsItemSelected(item); } public void registerForActivityResult(@NonNull String instanceId, int requestCode) { activityRequestMap.put(requestCode, instanceId); } public void unregisterForActivityResults(@NonNull String instanceId) { for (int i = activityRequestMap.size() - 1; i >= 0; i--) { if (instanceId.equals(activityRequestMap.get(activityRequestMap.keyAt(i)))) { activityRequestMap.removeAt(i); } } } public void startActivityForResult(@NonNull String instanceId, @NonNull Intent intent, int requestCode) { registerForActivityResult(instanceId, requestCode); startActivityForResult(intent, requestCode); } public void startActivityForResult(@NonNull String instanceId, @NonNull Intent intent, int requestCode, @Nullable Bundle options) { registerForActivityResult(instanceId, requestCode); startActivityForResult(intent, requestCode, options); } @TargetApi(Build.VERSION_CODES.N) public void startIntentSenderForResult(@NonNull String instanceId, @NonNull IntentSender intent, int requestCode, @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, @Nullable Bundle options) throws IntentSender.SendIntentException { registerForActivityResult(instanceId, requestCode); startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask, flagsValues, extraFlags, options); } @TargetApi(Build.VERSION_CODES.M) public void requestPermissions(@NonNull String instanceId, @NonNull String[] permissions, int requestCode) { if (attached) { permissionRequestMap.put(requestCode, instanceId); requestPermissions(permissions, requestCode); } else { pendingPermissionRequests.add(new PendingPermissionRequest(instanceId, permissions, requestCode)); } } @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { if (this.activity == null && findInActivity(activity) == LifecycleHandler.this) { this.activity = activity; } } @Override public void onActivityStarted(Activity activity) { if (this.activity == activity) { for (Router router : routerMap.values()) { router.onActivityStarted(activity); } } } @Override public void onActivityResumed(Activity activity) { if (this.activity == activity) { for (Router router : routerMap.values()) { router.onActivityResumed(activity); } } } @Override public void onActivityPaused(Activity activity) { if (this.activity == activity) { for (Router router : routerMap.values()) { router.onActivityPaused(activity); } } } @Override public void onActivityStopped(Activity activity) { if (this.activity == activity) { for (Router router : routerMap.values()) { router.onActivityStopped(activity); } } } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { if (this.activity == activity) { for (Router router : routerMap.values()) { Bundle bundle = new Bundle(); router.saveInstanceState(bundle); outState.putBundle(KEY_ROUTER_STATE_PREFIX + router.getContainerId(), bundle); } } } @Override public void onActivityDestroyed(Activity activity) { activeLifecycleHandlers.remove(activity); } private static class PendingPermissionRequest implements Parcelable { final String instanceId; final String[] permissions; final int requestCode; PendingPermissionRequest(@NonNull String instanceId, @NonNull String[] permissions, int requestCode) { this.instanceId = instanceId; this.permissions = permissions; this.requestCode = requestCode; } private PendingPermissionRequest(Parcel in) { instanceId = in.readString(); permissions = in.createStringArray(); requestCode = in.readInt(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out, int flags) { out.writeString(instanceId); out.writeStringArray(permissions); out.writeInt(requestCode); } public static final Parcelable.Creator<PendingPermissionRequest> CREATOR = new Parcelable.Creator<PendingPermissionRequest>() { @Override public PendingPermissionRequest createFromParcel(Parcel in) { return new PendingPermissionRequest(in); } @Override public PendingPermissionRequest[] newArray(int size) { return new PendingPermissionRequest[size]; } }; } }
Fixes leaked activity introduced in e64fe1c61027db77a788c7a9abeaecac166a11ff
conductor/src/main/java/com/bluelinelabs/conductor/internal/LifecycleHandler.java
Fixes leaked activity introduced in e64fe1c61027db77a788c7a9abeaecac166a11ff
<ide><path>onductor/src/main/java/com/bluelinelabs/conductor/internal/LifecycleHandler.java <ide> if (lifecycleHandler == null) { <ide> lifecycleHandler = new LifecycleHandler(); <ide> activity.getFragmentManager().beginTransaction().add(lifecycleHandler, FRAGMENT_TAG).commit(); <del> <del> // Since Fragment transactions are async, we have to keep an <Activity, LifecycleHandler> map in addition <del> // to trying to find the LifecycleHandler fragment in the Activity to handle the case of the developer <del> // trying to immediately get > 1 router in the same Activity. See issue #299. <del> activeLifecycleHandlers.put(activity, lifecycleHandler); <ide> } <ide> lifecycleHandler.registerActivityListener(activity); <ide> return lifecycleHandler; <ide> if (!hasRegisteredCallbacks) { <ide> hasRegisteredCallbacks = true; <ide> activity.getApplication().registerActivityLifecycleCallbacks(this); <add> <add> // Since Fragment transactions are async, we have to keep an <Activity, LifecycleHandler> map in addition <add> // to trying to find the LifecycleHandler fragment in the Activity to handle the case of the developer <add> // trying to immediately get > 1 router in the same Activity. See issue #299. <add> activeLifecycleHandlers.put(activity, this); <ide> } <ide> } <ide> <ide> <ide> if (activity != null) { <ide> activity.getApplication().unregisterActivityLifecycleCallbacks(this); <add> activeLifecycleHandlers.remove(activity); <ide> destroyRouters(); <ide> activity = null; <ide> }
Java
mit
c9378c676dd3875506f134b3d4b32057c6fab5f7
0
bschmeck/android_todo
package com.s10r.todolist; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; public class MainActivity extends AppCompatActivity { ArrayList<Item> items; ArrayAdapter<Item> itemsAdapter; ListView lvItems; ToDoListDbHelper mDbHelper; private final int EDIT_ITEM_REQUEST_CODE = 10; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lvItems = (ListView)findViewById(R.id.lvItems); mDbHelper = new ToDoListDbHelper(this.getApplicationContext()); readItems(); itemsAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items); lvItems.setAdapter(itemsAdapter); setupListViewListener(); } public void onAddItem(View v) { EditText etNewItem = (EditText)findViewById(R.id.etNewItem); String itemText = etNewItem.getText().toString(); Item item = new Item(mDbHelper, itemText); item.save(); itemsAdapter.add(item); etNewItem.setText(""); } private void setupListViewListener() { lvItems.setOnItemLongClickListener( new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapter, View item, int pos, long id) { Item itm = items.remove(pos); itm.complete(); items.add(itm); itemsAdapter.notifyDataSetChanged(); return true; } } ); lvItems.setOnItemClickListener( new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) { Item itm = items.get(pos); if (!itm.isCompleted()) { launchEditView(pos, itm); } } } ); } public void launchEditView(int pos, Item item) { Intent i = new Intent(MainActivity.this, EditItemActivity.class); i.putExtra("itemText", item.text); i.putExtra("pos", pos); i.putExtra("dueDate", formatDate(item.dueDate)); startActivityForResult(i, EDIT_ITEM_REQUEST_CODE); } private String formatDate(Date date) { if (date == null) { return null; } SimpleDateFormat formatter = new SimpleDateFormat("yyyy-M-dd HH:mm"); return formatter.format(date); } private Date parseDate(String dateStr) { if (dateStr == null) { return null; } ParsePosition pos = new ParsePosition(0); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-M-dd HH:mm"); Date date = formatter.parse(dateStr, pos); if (date != null) { return date; } formatter = new SimpleDateFormat("yyyy-M-dd"); return formatter.parse(dateStr, pos); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK && requestCode == EDIT_ITEM_REQUEST_CODE) { String itemText = data.getStringExtra("itemText"); String dueDate = data.getStringExtra("dueDate"); // TODO: Handle invalid pos int pos = data.getIntExtra("pos", -1); Item item = items.get(pos); item.text = itemText; item.dueDate = parseDate(dueDate); item.save(); itemsAdapter.notifyDataSetChanged(); } } private void readItems() { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor c = db.query( ToDoListContract.ItemEntry.TABLE_NAME, Item.COLUMN_PROJECTION, null, null, null, null, ToDoListContract.ItemEntry.COLUMN_NAME_COMPLETED_AT ); items = new ArrayList<Item>(); c.moveToFirst(); while (!c.isAfterLast()) { items.add(new Item(mDbHelper, c)); c.moveToNext(); } c.close(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
app/src/main/java/com/s10r/todolist/MainActivity.java
package com.s10r.todolist; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; public class MainActivity extends AppCompatActivity { ArrayList<Item> items; ArrayAdapter<Item> itemsAdapter; ListView lvItems; ToDoListDbHelper mDbHelper; private final int EDIT_ITEM_REQUEST_CODE = 10; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lvItems = (ListView)findViewById(R.id.lvItems); mDbHelper = new ToDoListDbHelper(this.getApplicationContext()); readItems(); itemsAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items); lvItems.setAdapter(itemsAdapter); setupListViewListener(); } public void onAddItem(View v) { EditText etNewItem = (EditText)findViewById(R.id.etNewItem); String itemText = etNewItem.getText().toString(); Item item = new Item(mDbHelper, itemText); item.save(); itemsAdapter.add(item); etNewItem.setText(""); } private void setupListViewListener() { lvItems.setOnItemLongClickListener( new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapter, View item, int pos, long id) { Item itm = items.get(pos); itm.complete(); itemsAdapter.notifyDataSetChanged(); return true; } } ); lvItems.setOnItemClickListener( new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) { Item itm = items.get(pos); if (!itm.isCompleted()) { launchEditView(pos, itm); } } } ); } public void launchEditView(int pos, Item item) { Intent i = new Intent(MainActivity.this, EditItemActivity.class); i.putExtra("itemText", item.text); i.putExtra("pos", pos); i.putExtra("dueDate", formatDate(item.dueDate)); startActivityForResult(i, EDIT_ITEM_REQUEST_CODE); } private String formatDate(Date date) { if (date == null) { return null; } SimpleDateFormat formatter = new SimpleDateFormat("yyyy-M-dd HH:mm"); return formatter.format(date); } private Date parseDate(String dateStr) { if (dateStr == null) { return null; } ParsePosition pos = new ParsePosition(0); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-M-dd HH:mm"); Date date = formatter.parse(dateStr, pos); if (date != null) { return date; } formatter = new SimpleDateFormat("yyyy-M-dd"); return formatter.parse(dateStr, pos); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK && requestCode == EDIT_ITEM_REQUEST_CODE) { String itemText = data.getStringExtra("itemText"); String dueDate = data.getStringExtra("dueDate"); // TODO: Handle invalid pos int pos = data.getIntExtra("pos", -1); Item item = items.get(pos); item.text = itemText; item.dueDate = parseDate(dueDate); item.save(); itemsAdapter.notifyDataSetChanged(); } } private void readItems() { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor c = db.query( ToDoListContract.ItemEntry.TABLE_NAME, Item.COLUMN_PROJECTION, null, null, null, null, null ); items = new ArrayList<Item>(); c.moveToFirst(); while (!c.isAfterLast()) { items.add(new Item(mDbHelper, c)); c.moveToNext(); } c.close(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
Put completed Items at the bottom of the list
app/src/main/java/com/s10r/todolist/MainActivity.java
Put completed Items at the bottom of the list
<ide><path>pp/src/main/java/com/s10r/todolist/MainActivity.java <ide> @Override <ide> public boolean onItemLongClick(AdapterView<?> adapter, <ide> View item, int pos, long id) { <del> Item itm = items.get(pos); <add> Item itm = items.remove(pos); <ide> itm.complete(); <add> items.add(itm); <ide> itemsAdapter.notifyDataSetChanged(); <ide> return true; <ide> } <ide> null, <ide> null, <ide> null, <del> null <add> ToDoListContract.ItemEntry.COLUMN_NAME_COMPLETED_AT <ide> ); <ide> items = new ArrayList<Item>(); <ide> c.moveToFirst();
Java
epl-1.0
a7c042eb89501ce095f583ec48548f79422e0125
0
blalusues/JSPProject_4team,blalusues/JSPProject_4team
package servlet; import java.io.File; //2017/10/23 import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.oreilly.servlet.MultipartRequest; import com.oreilly.servlet.multipart.DefaultFileRenamePolicy; import service.TravelContentService; import vo.CommentVO; import vo.ContentDetailVO; import vo.ContentPageVO; import vo.ContentVO; @WebServlet("/content") public class TravelContentServlet extends HttpServlet { private TravelContentService service = TravelContentService.getInstance(); ///////////////////////////////////////////////////////////////////////////////////////////// @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String task = request.getParameter("task"); String path = ""; if (task.equals("read")) { // ı б 10/24ۼ HttpSession session = request.getSession(); String email = (String) session.getAttribute("email"); String contentNumberStr = request.getParameter("contentNumber"); int contentNumber = Integer.parseInt(contentNumberStr); List<ContentDetailVO> contentDetailList = service.read(contentNumber); ContentVO content = service.read(email, contentNumber); List<CommentVO> comment = service.commentSelect(content.getContent_no()); if (contentDetailList != null) { request.setAttribute("contentDetailList", contentDetailList); request.setAttribute("content", content); request.setAttribute("comment", comment); path = "read.jsp"; } else { path = "article_not_found.jsp"; } } else if (task.equals("contentList")) { // int page = 1; ContentPageVO contentPage = null; String pageStr = request.getParameter("page"); if (pageStr != null && pageStr.length() > 0) { page = Integer.parseInt(pageStr); } request.setCharacterEncoding("EUC-KR"); String search = request.getParameter("search"); String category = request.getParameter("category"); if ((search.equals("") && category.equals(""))) { // null̸ ׳ main contentPage = service.makePage(1, page, search, category); path = "main_search.jsp"; } else if (category.equals("")) { // ŸƲ ˻ contentPage = service.makePage(2, page, search, category); path = "main_search.jsp"; } else if (search.equals("")) { // ˻ contentPage = service.makePage(3, page, search, category); path = "main_search.jsp"; } else { // ŸƲ + ˻ contentPage = service.makePage(4, page, search, category); path = "main_search.jsp"; } request.setAttribute("contentPage", contentPage); request.setAttribute("category", category); request.setAttribute("search", search); } else if (task.equals("wirteForm")) { // ȭ (α κ ��...) path = "write_form_newest.jsp"; } else if (task.equals("updateForm")) { HttpSession session = request.getSession(); String email = (String) session.getAttribute("email"); String contentNumStr = request.getParameter("contentNum"); int contentNum = Integer.parseInt(contentNumStr); ContentVO content = service.read(email, contentNum); List<ContentDetailVO> contentDetailList = service.read(contentNum); int dayNumber = service.caculateDLNum(contentNum); request.setAttribute("dayNum", dayNumber); request.setAttribute("contentDetailList", contentDetailList); request.setAttribute("content", content); path = "update_form.jsp"; } else if (task.equals("deleteForm")) { String contentNumStr = request.getParameter("contentNum"); int contentNum = Integer.parseInt(contentNumStr); if (service.deleteContent(contentNum) == true) { path = "delete_success.jsp"; } } RequestDispatcher dispatcher = request.getRequestDispatcher(path); dispatcher.forward(request, response); } //////////////////////////////////////////////////////////////////////////////////////////// @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("euc-kr"); if (request.getParameter("task") == null) { System.out.println("taskĶ" + request.getParameter("task")); String uploadFolder = "C:\\kjhsample"; MultipartRequest mReq = new MultipartRequest(request, uploadFolder, 1024 * 1024 * 40, "euc-kr", new DefaultFileRenamePolicy()); String task = mReq.getParameter("task"); String path = ""; if (task.equals("write")) { request.setCharacterEncoding("euc-kr"); HttpSession session = request.getSession(); String loginId = (String) session.getAttribute("name"); String email = (String) session.getAttribute("email"); ContentVO content = new ContentVO(); List<ContentDetailVO> detailList = new ArrayList<>(); content.setTitle(mReq.getParameter("title")); content.setWriter(loginId); content.setLocation(mReq.getParameter("locations")); File uploadFile = mReq.getFile("main_image"); // ε Ϸ content.setMain_img(mReq.getOriginalFileName("main_image")); content.setStart_date(mReq.getParameter("start_date")); content.setEmail(email); // day (Day02 day=2) String dayStr = mReq.getParameter("day"); int day = 0; if (dayStr != null && dayStr.length() > 0) { day = Integer.parseInt(dayStr); } int[] maxPath = new int[5]; for (int y = 1; y < day + 1; y++) { String pathStr = mReq.getParameter("maxPath" + y); maxPath[y] = Integer.parseInt(pathStr); } // day ŭ detailList // (Day02 content, path parameter̸ content2, path2) for (int i = 1; i < day + 1; i++) { String plusPath = ""; ContentDetailVO detail = new ContentDetailVO(); detail.setDay(i); detail.setContent(mReq.getParameter("content" + i)); for (int x = 1; x < maxPath[i] + 1; x++) { plusPath = plusPath + mReq.getParameter("loc" + i + "_" + x) + "%" + mReq.getParameterValues("sum" + i + "_" + x)[0] + "%"; } detail.setPath(plusPath); detailList.add(detail); } if (service.write(content, detailList) == 1) { path = "write_success.jsp"; } else { path = "write_fail.jsp"; } } else if(task.equals("updateRead")) { request.setCharacterEncoding("euc-kr"); ContentVO content = new ContentVO(); List<ContentDetailVO> detailList = new ArrayList<>(); List<ContentDetailVO> detailListOther = new ArrayList<>(); ContentDetailVO detail = new ContentDetailVO(); String contentNumStr = mReq.getParameter("contentNum"); int contentNum = Integer.parseInt(contentNumStr); // day String dayNumStr = mReq.getParameter("dayNum"); int dayNum = Integer.parseInt(dayNumStr); content.setContent_no(contentNum); content.setTitle(mReq.getParameter("title")); content.setLocation(mReq.getParameter("locations")); File uploadFile = mReq.getFile("main_image"); content.setMain_img(mReq.getOriginalFileName("main_image")); // day String dayStr = mReq.getParameter("day"); int day = 0; if (dayStr != null && dayStr.length() > 0) { day = Integer.parseInt(dayStr); } System.out.println(" day : " + dayNum); System.out.println(" day : " + day); int[] maxPath = new int[5]; for (int y = 1; y < day + 1; y++) { String pathStr = request.getParameter("maxPath" + y); maxPath[y] = Integer.parseInt(pathStr); } if (day > dayNum) {// day ߰ Ǿ for (int i = 1; i < dayNum + 1; i++) { String plusPath = ""; detail.setDay(i); detail.setContent(mReq.getParameter("content" + i)); for (int x = 1; x < maxPath[i] + 1; x++) { plusPath = plusPath + mReq.getParameter("loc" + i + "_" + x) + "%" + mReq.getParameterValues("sum" + i + "_" + x)[0] + "%"; } detail.setPath(plusPath); detailList.add(detail); } for (int i = dayNum + 1; i < detailList.size() + 1; i++) { String plusPath = ""; detail.setDay(i); detail.setContent(mReq.getParameter("content" + i)); for (int x = 1; x < maxPath[i] + 1; x++) { plusPath = plusPath + mReq.getParameter("loc" + i + "_" + x) + "%" + mReq.getParameterValues("sum" + i + "_" + x)[0] + "%"; } detail.setPath(plusPath); detailListOther.add(detail); } if (service.updateRead(content, detailList) && service.insertDay(contentNum, detailListOther)) { path = "update_success.jsp"; } else { path = "update_fail.jsp"; } } else if (day == dayNum) { // day for (int i = 1; i < detailList.size() + 1; i++) { String plusPath = ""; detail.setDay(i); detail.setContent(mReq.getParameter("content" + i)); for (int x = 1; x < maxPath[i] + 1; x++) { plusPath = plusPath + mReq.getParameter("loc" + i + "_" + x) + "%" + mReq.getParameterValues("sum" + i + "_" + x)[0] + "%"; } detail.setPath(plusPath); detailList.add(detail); } if (service.updateRead(content, detailList)) { path = "update_success.jsp"; } else { path = "update_fail.jsp"; } } else if (day < dayNum) { // day Ǿ for (int i = 1; i < detailList.size() + 1; i++) { String plusPath = ""; detail.setDay(i); detail.setContent(mReq.getParameter("content" + i)); for (int x = 1; x < maxPath[i] + 1; x++) { plusPath = plusPath + mReq.getParameter("loc" + i + "_" + x) + "%" + mReq.getParameterValues("sum" + i + "_" + x)[0] + "%"; } detail.setPath(plusPath); detailList.add(detail); } for (int i = detailList.size() + 1; i < dayNum + 1; i++) { String plusPath = ""; detail.setDay(i); detail.setContent(mReq.getParameter("content" + i)); for (int x = 1; x < maxPath[i] + 1; x++) { plusPath = plusPath + mReq.getParameter("loc" + i + "_" + x) + "%" + mReq.getParameterValues("sum" + i + "_" + x)[0] + "%"; } detail.setPath(plusPath); detailListOther.add(detail); } if (service.updateRead(content, detailList) && service.DeleteDay(contentNum, detailListOther)) { path = "update_success.jsp"; } else { path = "update_fail.jsp"; } } } RequestDispatcher dispatcher = request.getRequestDispatcher(path); dispatcher.forward(request, response); } else { String task = request.getParameter("task"); String path = ""; if (task.equals("commentCheck")) { HttpSession session = request.getSession(); String loginId = (String) session.getAttribute("name"); String email = (String) session.getAttribute("email"); String articleNumStr = request.getParameter("comment_board"); int articleNum = Integer.parseInt(articleNumStr); String comment_content = request.getParameter("comment_content"); comment_content = comment_content.replace("\r\n", "<br>"); CommentVO comment = new CommentVO(); comment.setBrdNo(articleNum); comment.setWriter(loginId); comment.setContent(comment_content); comment.setEmail(email); boolean result = service.commentSignUp(comment); if (result == true) { request.setAttribute("articleNum", articleNum); path = "comment_success.jsp"; } else { request.setAttribute("articleNum", articleNum); path = "comment_fail.jsp"; } } else if (task.equals("commentDelete")) { String articleNumStr = request.getParameter("comment_board"); int articleNum = Integer.parseInt(articleNumStr); CommentVO comment = new CommentVO(); String comment_numStr = request.getParameter("comment_num"); int comment_num = Integer.parseInt(comment_numStr); comment.setCommentNum(comment_num); boolean result = service.commentDelete(comment); if (result == true) { request.setAttribute("articleNum", articleNum); path = "commentDelete_success.jsp"; } else { request.setAttribute("articleNum", articleNum); path = "commentDelete_fail.jsp"; } } RequestDispatcher dispatcher = request.getRequestDispatcher(path); dispatcher.forward(request, response); } } }
src/servlet/TravelContentServlet.java
package servlet; import java.io.File; //2017/10/23 import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.oreilly.servlet.MultipartRequest; import com.oreilly.servlet.multipart.DefaultFileRenamePolicy; import service.TravelContentService; import vo.CommentVO; import vo.ContentDetailVO; import vo.ContentPageVO; import vo.ContentVO; @WebServlet("/content") public class TravelContentServlet extends HttpServlet { private TravelContentService service = TravelContentService.getInstance(); ///////////////////////////////////////////////////////////////////////////////////////////// @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String task = request.getParameter("task"); String path = ""; if (task.equals("read")) { // ı б 10/24ۼ HttpSession session = request.getSession(); String email = (String) session.getAttribute("email"); String contentNumberStr = request.getParameter("contentNumber"); int contentNumber = Integer.parseInt(contentNumberStr); List<ContentDetailVO> contentDetailList = service.read(contentNumber); ContentVO content = service.read(email, contentNumber); List<CommentVO> comment = service.commentSelect(content.getContent_no()); if (contentDetailList != null) { request.setAttribute("contentDetailList", contentDetailList); request.setAttribute("content", content); request.setAttribute("comment", comment); path = "read.jsp"; } else { path = "article_not_found.jsp"; } } else if (task.equals("contentList")) { // int page = 1; ContentPageVO contentPage = null; String pageStr = request.getParameter("page"); if (pageStr != null && pageStr.length() > 0) { page = Integer.parseInt(pageStr); } request.setCharacterEncoding("EUC-KR"); String search = request.getParameter("search"); String category = request.getParameter("category"); if ((search.equals("") && category.equals(""))) { // null̸ ׳ main contentPage = service.makePage(1, page, search, category); path = "main_search.jsp"; } else if (category.equals("")) { // ŸƲ ˻ contentPage = service.makePage(2, page, search, category); path = "main_search.jsp"; } else if (search.equals("")) { // ˻ contentPage = service.makePage(3, page, search, category); path = "main_search.jsp"; } else { // ŸƲ + ˻ contentPage = service.makePage(4, page, search, category); path = "main_search.jsp"; } request.setAttribute("contentPage", contentPage); request.setAttribute("category", category); request.setAttribute("search", search); } else if (task.equals("wirteForm")) { // ȭ (α κ ��...) path = "write_form_newest.jsp"; } else if (task.equals("updateForm")) { HttpSession session = request.getSession(); String email = (String) session.getAttribute("email"); String contentNumStr = request.getParameter("contentNum"); int contentNum = Integer.parseInt(contentNumStr); ContentVO content = service.read(email, contentNum); List<ContentDetailVO> contentDetailList = service.read(contentNum); int dayNumber = service.caculateDLNum(contentNum); request.setAttribute("dayNum", dayNumber); request.setAttribute("contentDetailList", contentDetailList); request.setAttribute("content", content); path = "update_form.jsp"; } else if (task.equals("deleteForm")) { String contentNumStr = request.getParameter("contentNum"); int contentNum = Integer.parseInt(contentNumStr); if (service.deleteContent(contentNum) == true) { path = "delete_success.jsp"; } } RequestDispatcher dispatcher = request.getRequestDispatcher(path); dispatcher.forward(request, response); } //////////////////////////////////////////////////////////////////////////////////////////// @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("euc-kr"); if (request.getParameter("task") == null) { System.out.println("taskĶ" + request.getParameter("task")); String uploadFolder = "C:\\kjhsample"; MultipartRequest mReq = new MultipartRequest(request, uploadFolder, 1024 * 1024 * 40, "euc-kr", new DefaultFileRenamePolicy()); String task = mReq.getParameter("task"); String path = ""; if (task.equals("write")) { request.setCharacterEncoding("euc-kr"); HttpSession session = request.getSession(); String loginId = (String) session.getAttribute("name"); String email = (String) session.getAttribute("email"); ContentVO content = new ContentVO(); List<ContentDetailVO> detailList = new ArrayList<>(); content.setTitle(mReq.getParameter("title")); content.setWriter(loginId); content.setLocation(mReq.getParameter("locations")); File uploadFile = mReq.getFile("main_image"); // ε Ϸ content.setMain_img(mReq.getOriginalFileName("main_image")); content.setStart_date(mReq.getParameter("start_date")); content.setEmail(email); // day (Day02 day=2) String dayStr = mReq.getParameter("day"); int day = 0; if (dayStr != null && dayStr.length() > 0) { day = Integer.parseInt(dayStr); } int[] maxPath = new int[5]; for (int y = 1; y < day + 1; y++) { String pathStr = mReq.getParameter("maxPath" + y); maxPath[y] = Integer.parseInt(pathStr); } // day ŭ detailList // (Day02 content, path parameter̸ content2, path2) for (int i = 1; i < day + 1; i++) { String plusPath = ""; ContentDetailVO detail = new ContentDetailVO(); detail.setDay(i); detail.setContent(mReq.getParameter("content" + i)); for (int x = 1; x < maxPath[i] + 1; x++) { plusPath = plusPath + mReq.getParameter("loc" + i + "_" + x) + "%" + mReq.getParameterValues("sum" + i + "_" + x)[0] + "%"; } detail.setPath(plusPath); detailList.add(detail); } if (service.write(content, detailList) == 1) { path = "write_success.jsp"; } else { path = "write_fail.jsp"; } } else if(task.equals("updateRead")) { request.setCharacterEncoding("euc-kr"); ContentVO content = new ContentVO(); List<ContentDetailVO> detailList = new ArrayList<>(); List<ContentDetailVO> detailListOther = new ArrayList<>(); ContentDetailVO detail = new ContentDetailVO(); String contentNumStr = mReq.getParameter("contentNum"); int contentNum = Integer.parseInt(contentNumStr); String dayNumStr = mReq.getParameter("dayNum"); int dayNum = Integer.parseInt(dayNumStr); content.setContent_no(contentNum); content.setTitle(mReq.getParameter("title")); content.setLocation(mReq.getParameter("locations")); File uploadFile = mReq.getFile("main_image"); content.setMain_img(mReq.getOriginalFileName("main_image")); String dayStr = request.getParameter("day"); int day = 0; if (dayStr != null && dayStr.length() > 0) { day = Integer.parseInt(dayStr); } int[] maxPath = new int[5]; for (int y = 1; y < day + 1; y++) { String pathStr = request.getParameter("maxPath" + y); maxPath[y] = Integer.parseInt(pathStr); } if (day > dayNum) {// day ߰ Ǿ for (int i = 1; i < dayNum + 1; i++) { String plusPath = ""; detail.setDay(i); detail.setContent(mReq.getParameter("content" + i)); for (int x = 1; x < maxPath[i] + 1; x++) { plusPath = plusPath + mReq.getParameter("loc" + i + "_" + x) + "%" + mReq.getParameterValues("sum" + i + "_" + x)[0] + "%"; } detail.setPath(plusPath); detailList.add(detail); } for (int i = dayNum + 1; i < detailList.size() + 1; i++) { String plusPath = ""; detail.setDay(i); detail.setContent(mReq.getParameter("content" + i)); for (int x = 1; x < maxPath[i] + 1; x++) { plusPath = plusPath + mReq.getParameter("loc" + i + "_" + x) + "%" + mReq.getParameterValues("sum" + i + "_" + x)[0] + "%"; } detail.setPath(plusPath); detailListOther.add(detail); } if (service.updateRead(content, detailList) && service.insertDay(contentNum, detailListOther)) { path = "update_success.jsp"; } else { path = "update_fail.jsp"; } } else if (day == dayNum) { // day for (int i = 1; i < detailList.size() + 1; i++) { String plusPath = ""; detail.setDay(i); detail.setContent(mReq.getParameter("content" + i)); for (int x = 1; x < maxPath[i] + 1; x++) { plusPath = plusPath + mReq.getParameter("loc" + i + "_" + x) + "%" + mReq.getParameterValues("sum" + i + "_" + x)[0] + "%"; } detail.setPath(plusPath); detailList.add(detail); } if (service.updateRead(content, detailList)) { path = "update_success.jsp"; } else { path = "update_fail.jsp"; } } else if (day < dayNum) { // day Ǿ for (int i = 1; i < detailList.size() + 1; i++) { String plusPath = ""; detail.setDay(i); detail.setContent(mReq.getParameter("content" + i)); for (int x = 1; x < maxPath[i] + 1; x++) { plusPath = plusPath + mReq.getParameter("loc" + i + "_" + x) + "%" + mReq.getParameterValues("sum" + i + "_" + x)[0] + "%"; } detail.setPath(plusPath); detailList.add(detail); } for (int i = detailList.size() + 1; i < dayNum + 1; i++) { String plusPath = ""; detail.setDay(i); detail.setContent(mReq.getParameter("content" + i)); for (int x = 1; x < maxPath[i] + 1; x++) { plusPath = plusPath + mReq.getParameter("loc" + i + "_" + x) + "%" + mReq.getParameterValues("sum" + i + "_" + x)[0] + "%"; } detail.setPath(plusPath); detailListOther.add(detail); } if (service.updateRead(content, detailList) && service.DeleteDay(contentNum, detailListOther)) { path = "update_success.jsp"; } else { path = "update_fail.jsp"; } } } RequestDispatcher dispatcher = request.getRequestDispatcher(path); dispatcher.forward(request, response); } else { String task = request.getParameter("task"); String path = ""; if (task.equals("commentCheck")) { HttpSession session = request.getSession(); String loginId = (String) session.getAttribute("name"); String email = (String) session.getAttribute("email"); String articleNumStr = request.getParameter("comment_board"); int articleNum = Integer.parseInt(articleNumStr); String comment_content = request.getParameter("comment_content"); comment_content = comment_content.replace("\r\n", "<br>"); CommentVO comment = new CommentVO(); comment.setBrdNo(articleNum); comment.setWriter(loginId); comment.setContent(comment_content); comment.setEmail(email); boolean result = service.commentSignUp(comment); if (result == true) { request.setAttribute("articleNum", articleNum); path = "comment_success.jsp"; } else { request.setAttribute("articleNum", articleNum); path = "comment_fail.jsp"; } } else if (task.equals("commentDelete")) { String articleNumStr = request.getParameter("comment_board"); int articleNum = Integer.parseInt(articleNumStr); CommentVO comment = new CommentVO(); String comment_numStr = request.getParameter("comment_num"); int comment_num = Integer.parseInt(comment_numStr); comment.setCommentNum(comment_num); boolean result = service.commentDelete(comment); if (result == true) { request.setAttribute("articleNum", articleNum); path = "commentDelete_success.jsp"; } else { request.setAttribute("articleNum", articleNum); path = "commentDelete_fail.jsp"; } } RequestDispatcher dispatcher = request.getRequestDispatcher(path); dispatcher.forward(request, response); } } }
--------------
src/servlet/TravelContentServlet.java
--------------
<ide><path>rc/servlet/TravelContentServlet.java <ide> String contentNumStr = mReq.getParameter("contentNum"); <ide> int contentNum = Integer.parseInt(contentNumStr); <ide> <add> // day <ide> String dayNumStr = mReq.getParameter("dayNum"); <ide> int dayNum = Integer.parseInt(dayNumStr); <del> <add> <ide> content.setContent_no(contentNum); <ide> content.setTitle(mReq.getParameter("title")); <ide> content.setLocation(mReq.getParameter("locations")); <ide> File uploadFile = mReq.getFile("main_image"); <ide> content.setMain_img(mReq.getOriginalFileName("main_image")); <del> <del> String dayStr = request.getParameter("day"); <add> <add> // day <add> String dayStr = mReq.getParameter("day"); <ide> int day = 0; <ide> if (dayStr != null && dayStr.length() > 0) { <ide> day = Integer.parseInt(dayStr); <ide> } <add> System.out.println(" day : " + dayNum); <add> System.out.println(" day : " + day); <ide> <ide> int[] maxPath = new int[5]; <ide> for (int y = 1; y < day + 1; y++) {
Java
apache-2.0
312cdd959aa01ea759219e223dfb3c7956979b82
0
mohanaraosv/commons-jcs,apache/commons-jcs,apache/commons-jcs,apache/commons-jcs,mohanaraosv/commons-jcs,mohanaraosv/commons-jcs
package org.apache.commons.jcs.engine; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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. */ import java.util.Properties; import junit.framework.TestCase; import org.apache.commons.jcs.JCS; import org.apache.commons.jcs.access.CacheAccess; import org.apache.commons.jcs.engine.control.CompositeCacheManager; import org.apache.commons.jcs.utils.props.PropertyLoader; /** * Verify that system properties can override. */ public class SystemPropertyUsageUnitTest extends TestCase { /** * Verify that the system properties are used. * @throws Exception * */ public void testSystemPropertyUsage() throws Exception { final int testValue = 6789; System.getProperties().setProperty( "jcs.default.cacheattributes.MaxObjects", String.valueOf(testValue) ); JCS.setConfigFilename( "/TestSystemPropertyUsage.ccf" ); CacheAccess<String, String> jcs = JCS.getInstance( "someCacheNotInFile" ); assertEquals( "System property value is not reflected", testValue, jcs.getCacheAttributes().getMaxObjects()); } /** * Verify that the system properties are not used is specified. * * @throws Exception * */ public void testSystemPropertyUsage_inactive() throws Exception { System.getProperties().setProperty( "jcs.default.cacheattributes.MaxObjects", "6789" ); CompositeCacheManager mgr = CompositeCacheManager.getUnconfiguredInstance(); Properties props = PropertyLoader.loadProperties( "TestSystemPropertyUsage.ccf" ); mgr.configure( props, false ); CacheAccess<String, String> jcs = JCS.getInstance( "someCacheNotInFile" ); assertFalse( "System property value should not be reflected", jcs.getCacheAttributes().getMaxObjects() == Integer.parseInt( props .getProperty( "jcs.default.cacheattributes.MaxObjects" ) ) ); } }
src/test/org/apache/commons/jcs/engine/SystemPropertyUsageUnitTest.java
package org.apache.commons.jcs.engine; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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. */ import java.util.Properties; import junit.framework.TestCase; import org.apache.commons.jcs.JCS; import org.apache.commons.jcs.access.CacheAccess; import org.apache.commons.jcs.engine.control.CompositeCacheManager; import org.apache.commons.jcs.utils.props.PropertyLoader; /** * Verify that system properties can override. */ public class SystemPropertyUsageUnitTest extends TestCase { /** * Verify that the system properties are used. * @throws Exception * */ public void testSystemPropertyUsage() throws Exception { System.getProperties().setProperty( "jcs.default.cacheattributes.MaxObjects", "6789" ); JCS.setConfigFilename( "/TestSystemPropertyUsage.ccf" ); CacheAccess<String, String> jcs = JCS.getInstance( "someCacheNotInFile" ); assertEquals( "System property value is not reflected", jcs.getCacheAttributes().getMaxObjects(), Integer .parseInt( "6789" ) ); } /** * Verify that the system properties are not used is specified. * * @throws Exception * */ public void testSystemPropertyUsage_inactive() throws Exception { System.getProperties().setProperty( "jcs.default.cacheattributes.MaxObjects", "6789" ); CompositeCacheManager mgr = CompositeCacheManager.getUnconfiguredInstance(); Properties props = PropertyLoader.loadProperties( "TestSystemPropertyUsage.ccf" ); mgr.configure( props, false ); CacheAccess<String, String> jcs = JCS.getInstance( "someCacheNotInFile" ); assertFalse( "System property value should not be reflected", jcs.getCacheAttributes().getMaxObjects() == Integer.parseInt( props .getProperty( "jcs.default.cacheattributes.MaxObjects" ) ) ); } }
Simplify; use shared common value git-svn-id: fd52ae19693b7be904def34076a5ebbd6e132215@1585672 13f79535-47bb-0310-9956-ffa450edef68
src/test/org/apache/commons/jcs/engine/SystemPropertyUsageUnitTest.java
Simplify; use shared common value
<ide><path>rc/test/org/apache/commons/jcs/engine/SystemPropertyUsageUnitTest.java <ide> public void testSystemPropertyUsage() <ide> throws Exception <ide> { <del> System.getProperties().setProperty( "jcs.default.cacheattributes.MaxObjects", "6789" ); <add> final int testValue = 6789; <add> <add> System.getProperties().setProperty( "jcs.default.cacheattributes.MaxObjects", String.valueOf(testValue) ); <ide> <ide> JCS.setConfigFilename( "/TestSystemPropertyUsage.ccf" ); <ide> <ide> CacheAccess<String, String> jcs = JCS.getInstance( "someCacheNotInFile" ); <ide> <del> assertEquals( "System property value is not reflected", jcs.getCacheAttributes().getMaxObjects(), Integer <del> .parseInt( "6789" ) ); <add> assertEquals( "System property value is not reflected", testValue, jcs.getCacheAttributes().getMaxObjects()); <ide> <ide> } <ide>
Java
mit
40af3cf8153646496cfbac6f236aedd27babd5c9
0
TakayukiHoshi1984/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,Onuzimoyr/dAndroid,TakayukiHoshi1984/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,ssdwa/android,DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,Onuzimoyr/dAndroid,TakayukiHoshi1984/DeviceConnect-Android
/* HueLightProfile Copyright (c) 2014 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ package org.deviceconnect.android.deviceplugin.hue.profile; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.deviceconnect.android.message.MessageUtils; import org.deviceconnect.android.original.profile.LightProfile; import org.deviceconnect.message.DConnectMessage; import android.content.Intent; import android.os.Bundle; import com.philips.lighting.hue.listener.PHGroupListener; import com.philips.lighting.hue.listener.PHLightListener; import com.philips.lighting.hue.sdk.PHHueSDK; import com.philips.lighting.hue.sdk.utilities.PHUtilities; import com.philips.lighting.model.PHBridge; import com.philips.lighting.model.PHBridgeResource; import com.philips.lighting.model.PHBridgeResourcesCache; import com.philips.lighting.model.PHGroup; import com.philips.lighting.model.PHHueError; import com.philips.lighting.model.PHLight; import com.philips.lighting.model.PHLight.PHLightColorMode; import com.philips.lighting.model.PHLightState; /** * 親クラスで振り分けられたメソッドに対して、Hueのlight attribute処理を呼び出す. * @author NTT DOCOMO, INC. */ public class HueLightProfile extends LightProfile { /** * エラーコード301. */ private static final int HUE_SDK_ERROR_301 = 301; /** RGBの文字列の長さ. */ private static final int RGB_LENGTH = 6; @Override protected boolean onGetLight(final Intent request, final Intent response) { String serviceId = getServiceID(request); PHBridge bridge = findBridge(serviceId); if (bridge == null) { MessageUtils.setNotFoundServiceError(response, "Not found bridge: " + serviceId); return true; } List<Bundle> lightsParam = new ArrayList<Bundle>(); for (PHLight light : bridge.getResourceCache().getAllLights()) { Bundle lightParam = new Bundle(); lightParam.putString(PARAM_LIGHT_ID, light.getIdentifier()); lightParam.putString(PARAM_NAME, light.getName()); lightParam.putString(PARAM_CONFIG, ""); PHLightState state = light.getLastKnownLightState(); lightParam.putBoolean(PARAM_ON, state.isOn()); lightsParam.add(lightParam); } response.putExtra(PARAM_LIGHTS, lightsParam.toArray(new Bundle[lightsParam.size()])); sendResultOK(response); return false; } @Override protected boolean onPostLight(final Intent request, final Intent response) { String serviceId = getServiceID(request); String lightId = getLightID(request); // 必須パラメータの存在チェック if (lightId == null || lightId.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "lightId is not specified."); return true; } PHBridge bridge = findBridge(serviceId); if (bridge == null) { MessageUtils.setNotFoundServiceError(response, "Not found bridge: " + serviceId); return true; } PHLight light = bridge.getResourceCache().getLights().get(lightId); if (light == null) { MessageUtils.setInvalidRequestParameterError(response, "Not found light: " + lightId + "@" + serviceId); return true; } if (getBrightness(request) != null) { try { float mBrightness = Float.valueOf(getBrightness(request)); if (mBrightness > 1.0 || mBrightness < 0) { MessageUtils.setInvalidRequestParameterError(response, "brightness should be a value between 0 and 1.0"); return true; } } catch (NumberFormatException e) { MessageUtils.setInvalidRequestParameterError(response, "brightness should be a value between 0 and 1.0"); return true; } } if (getColor(request) != null) { try { String mColor = getColor(request); String rr = mColor.substring(0, 2); String gg = mColor.substring(2, 4); String bb = mColor.substring(4, 6); int mColorParam; if (mColor.length() == RGB_LENGTH) { if (rr == null) { MessageUtils.setInvalidRequestParameterError(response); return true; } else { mColorParam = Integer.parseInt(rr, 16); } if (gg == null) { MessageUtils.setInvalidRequestParameterError(response); return true; } else { mColorParam = Integer.parseInt(gg, 16); } if (bb == null) { MessageUtils.setInvalidRequestParameterError(response); return true; } else { mColorParam = Integer.parseInt(bb, 16); } } else { MessageUtils.setInvalidRequestParameterError(response); return true; } } catch (NumberFormatException e) { MessageUtils.setInvalidRequestParameterError(response); return true; } catch (IllegalArgumentException e) { MessageUtils.setInvalidRequestParameterError(response); return true; } } PHLightState lightState = new PHLightState(); lightState.setOn(true); lightState.setColorMode(PHLightColorMode.COLORMODE_XY); String colorParam = getColor(request); if (colorParam == null) { colorParam = "FFFFFF"; } Color hueColor = new Color(colorParam); lightState.setX(hueColor.mX); lightState.setY(hueColor.mY); String brightnessParam = getBrightness(request); if (brightnessParam != null) { lightState.setBrightness(Integer.valueOf(new Brightness(brightnessParam).mValue)); } bridge.updateLightState(light, lightState, new PHLightAdapter() { @Override public void onStateUpdate(final Map<String, String> successAttribute, final List<PHHueError> errorAttribute) { sendResultOK(response); } @Override public void onError(final int code, final String message) { MessageUtils.setUnknownError(response, code + ": " + message); sendResultERR(response); } }); return false; } @Override protected boolean onDeleteLight(final Intent request, final Intent response) { String serviceId = getServiceID(request); String lightId = getLightID(request); // 必須パラメータの存在チェック if (lightId == null || lightId.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "lightId is not specified."); return true; } PHBridge bridge = findBridge(serviceId); if (bridge == null) { MessageUtils.setNotFoundServiceError(response, "Not found bridge: " + serviceId); return true; } PHLight light = bridge.getResourceCache().getLights().get(lightId); if (light == null) { MessageUtils.setInvalidRequestParameterError(response, "Not found light: " + lightId + "@" + serviceId); return true; } PHLightState lightState = new PHLightState(); lightState.setOn(false); bridge.updateLightState(light, lightState, new PHLightAdapter() { @Override public void onStateUpdate(final Map<String, String> successAttribute, final List<PHHueError> errorAttribute) { sendResultOK(response); } @Override public void onError(final int code, final String message) { String errMsg = "ライトの状態更新に失敗しました hue:code = " + Integer.toString(code) + " message = " + message; MessageUtils.setUnknownError(response, errMsg); sendResultERR(response); } }); return false; } @Override protected boolean onPutLight(final Intent request, final Intent response) { String serviceId = getServiceID(request); String lightId = getLightID(request); String name = getName(request); // 必須パラメータの存在チェック if (lightId == null || lightId.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "lightId is not specified."); return true; } if (name == null || name.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "name is not specified."); return true; } PHBridge bridge = findBridge(serviceId); if (bridge == null) { MessageUtils.setNotFoundServiceError(response, "Not found bridge: " + serviceId); return true; } PHLight light = getLight(bridge, lightId); if (light == null) { MessageUtils.setInvalidRequestParameterError(response, "Not found light: " + lightId + "@" + serviceId); return true; } PHLight newLight = new PHLight(light); newLight.setName(name); bridge.updateLight(newLight, new PHLightAdapter() { @Override public void onSuccess() { sendResultOK(response); } @Override public void onError(final int code, final String message) { String errMsg = "ライトの名称変更に失敗しました hue:code = " + Integer.toString(code) + " message = " + message; MessageUtils.setUnknownError(response, errMsg); sendResultERR(response); } }); return false; } @Override protected boolean onGetLightGroup(final Intent request, final Intent response) { String serviceId = getServiceID(request); PHBridge bridge = findBridge(serviceId); if (bridge == null) { MessageUtils.setNotFoundServiceError(response, "Not found bridge: " + serviceId); return true; } List<Bundle> groupsParam = new ArrayList<Bundle>(); Map<String, PHLight> allLights = bridge.getResourceCache().getLights(); for (PHGroup group : bridge.getResourceCache().getAllGroups()) { Bundle groupParam = new Bundle(); groupParam.putString(PARAM_GROUP_ID, group.getIdentifier()); groupParam.putString(PARAM_NAME, group.getName()); List<Bundle> lightsParam = new ArrayList<Bundle>(); for (String lightId : group.getLightIdentifiers()) { PHLight light = allLights.get(lightId); if (light != null) { Bundle lightParam = new Bundle(); lightParam.putString(PARAM_LIGHT_ID, lightId); lightParam.putString(PARAM_NAME, light.getName()); PHLightState state = light.getLastKnownLightState(); if (state != null) { lightParam.putBoolean(PARAM_ON, state.isOn().booleanValue()); } lightParam.putString(PARAM_CONFIG, ""); lightsParam.add(lightParam); } } groupParam.putParcelableArray(PARAM_LIGHTS, lightsParam.toArray(new Bundle[lightsParam.size()])); groupParam.putString(PARAM_CONFIG, ""); groupsParam.add(groupParam); } response.putExtra(PARAM_LIGHT_GROUPS, groupsParam.toArray(new Bundle[groupsParam.size()])); setResult(response, DConnectMessage.RESULT_OK); return true; } @Override protected boolean onPostLightGroup(final Intent request, final Intent response) { String serviceId = getServiceID(request); String groupId = getGroupId(request); // 必須パラメータの存在チェック if (groupId == null || groupId.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "groupId is not specified."); return true; } PHBridge bridge = findBridge(serviceId); if (bridge == null) { MessageUtils.setNotFoundServiceError(response, "Not found bridge: " + serviceId); return true; } PHLightState lightState = new PHLightState(); lightState.setOn(true); lightState.setColorMode(PHLightColorMode.COLORMODE_XY); String colorParam = getColor(request); if (colorParam == null) { colorParam = "FFFFFF"; } Color hueColor = new Color(colorParam); lightState.setX(hueColor.mX); lightState.setY(hueColor.mY); String brightnessParam = getBrightness(request); if (brightnessParam != null) { lightState.setBrightness(Integer.valueOf(new Brightness(brightnessParam).mValue)); } if ("0".equals(groupId)) { bridge.setLightStateForDefaultGroup(lightState); setResult(response, DConnectMessage.RESULT_OK); return true; } PHGroup group = getGroup(bridge, groupId); if (group == null) { MessageUtils.setUnknownError(response, "Not found group: " + groupId); return true; } bridge.setLightStateForGroup(group.getIdentifier(), lightState, new PHGroupAdapter() { @Override public void onError(final int code, final String message) { String msg = "ライトの状態更新に失敗しました hue:code = " + Integer.toString(code) + " message = " + message; MessageUtils.setUnknownError(response, msg); sendResultERR(response); } @Override public void onStateUpdate(final Map<String, String> successAttributes, final List<PHHueError> errorAttributes) { sendResultOK(response); } }); return false; } @Override protected boolean onDeleteLightGroup(final Intent request, final Intent response) { String serviceId = getServiceID(request); String groupId = getGroupId(request); // 必須パラメータの存在チェック if (groupId == null || groupId.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "groupId is not specified."); return true; } PHBridge bridge = findBridge(serviceId); if (bridge == null) { MessageUtils.setNotFoundServiceError(response, "Not found bridge: " + serviceId); return true; } PHLightState lightState = new PHLightState(); lightState.setOn(false); if ("0".equals(groupId)) { bridge.setLightStateForDefaultGroup(lightState); setResult(response, DConnectMessage.RESULT_OK); return true; } PHGroup group = getGroup(bridge, groupId); if (group == null) { MessageUtils.setUnknownError(response, "Not found group: " + groupId); return true; } bridge.setLightStateForGroup(group.getIdentifier(), lightState, new PHGroupAdapter() { @Override public void onError(final int code, final String message) { String msg = "ライトの状態更新に失敗しました hue:code = " + Integer.toString(code) + " message = " + message; MessageUtils.setUnknownError(response, msg); sendResultERR(response); } @Override public void onStateUpdate(final Map<String, String> successAttributes, final List<PHHueError> errorAttributes) { sendResultOK(response); } }); return false; } @Override protected boolean onPutLightGroup(final Intent request, final Intent response) { String serviceId = getServiceID(request); String groupId = getGroupId(request); // 必須パラメータの存在チェック if (groupId == null || groupId.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "groupId is not specified."); return true; } PHBridge bridge = findBridge(serviceId); if (bridge == null) { MessageUtils.setNotFoundServiceError(response, "Not found bridge: " + serviceId); return true; } String name = getName(request); if (name == null || name.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "name is not specified."); return true; } PHGroup group = getGroup(bridge, groupId); if (group == null) { MessageUtils.setUnknownError(response, "Not found group: " + groupId); return true; } PHGroup newGroup = new PHGroup(name, group.getIdentifier()); bridge.updateGroup(newGroup, new PHGroupAdapter() { @Override public void onSuccess() { sendResultOK(response); } @Override public void onError(final int code, final String message) { String errMsg = "グループの名称変更に失敗しました hue:code = " + Integer.toString(code) + " message = " + message; MessageUtils.setUnknownError(response, errMsg); sendResultERR(response); } }); return false; } @Override protected boolean onPostLightGroupCreate(final Intent request, final Intent response) { String serviceId = getServiceID(request); String groupName = getGroupName(request); String lightIds = getLightIds(request); // 必須パラメータの存在チェック if (groupName == null || groupName.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "groupName is not specified."); return true; } if (lightIds == null || lightIds.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "lightIds is not specified."); return true; } String[] lightIdsArray = getSelectedIdList(lightIds); if (lightIdsArray == null) { MessageUtils.setInvalidRequestParameterError(response, "lightIds is not specified."); return true; } else if (lightIdsArray.length < 1) { MessageUtils.setInvalidRequestParameterError(response, "lightIds is not specified."); return true; } PHBridge bridge = findBridge(serviceId); if (bridge == null) { MessageUtils.setNotFoundServiceError(response, "Not found bridge: " + serviceId); return true; } bridge.createGroup(groupName, Arrays.asList(lightIdsArray), new PHGroupAdapter() { @Override public void onCreated(final PHGroup group) { response.putExtra(PARAM_GROUP_ID, group.getIdentifier()); sendResultOK(response); } @Override public void onError(final int code, final String msg) { String errMsg = "グループ作成に失敗しました hue:code = " + Integer.toString(code) + " message = " + msg; if (code == HUE_SDK_ERROR_301) { MessageUtils.setUnknownError(response, "グループが作成できる上限に達しています"); } else { MessageUtils.setUnknownError(response, errMsg); } sendResultERR(response); } }); return false; } @Override protected boolean onDeleteLightGroupClear(final Intent request, final Intent response) { String serviceId = getServiceID(request); String groupId = getGroupId(request); // 必須パラメータの存在チェック if (groupId == null || groupId.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "groupId is not specified."); return true; } PHBridge bridge = findBridge(serviceId); if (bridge == null) { MessageUtils.setNotFoundServiceError(response, "Not found bridge: " + serviceId); return true; } bridge.deleteGroup(groupId, new PHGroupAdapter() { @Override public void onSuccess() { sendResultOK(response); } @Override public void onError(final int code, final String msg) { String errMsg = "グループ削除に失敗しました hue:code = " + Integer.toString(code) + " message = " + msg; MessageUtils.setUnknownError(response, errMsg); sendResultERR(response); } }); return false; } /** * Hueのブリッジを検索する. * @param serviceId Service ID * @return Hueのブリッジを管理するオブジェクト */ private PHBridge findBridge(final String serviceId) { PHBridge bridge = PHHueSDK.getInstance().getSelectedBridge(); if (bridge != null) { PHBridgeResourcesCache cache = bridge.getResourceCache(); String ipAddress = cache.getBridgeConfiguration().getIpAddress(); if (serviceId.equals(ipAddress)) { return bridge; } } return null; } /** * Hue Lightを管理するオブジェクトを取得する. * @param bridge Hueのブリッジ * @param lightId Light ID * @return Lightを管理するオブジェクト */ private PHLight getLight(final PHBridge bridge, final String lightId) { for (PHLight light : bridge.getResourceCache().getAllLights()) { if (light.getIdentifier().equals(lightId)) { return light; } } return null; } /** * Hue Lightのグループ情報を管理するオブジェクトを取得する. * @param bridge Hueのブリッジ * @param groupID Group ID * @return Lightのグループ情報を持つオブジェクト */ private PHGroup getGroup(final PHBridge bridge, final String groupID) { for (PHGroup group : bridge.getResourceCache().getAllGroups()) { if (groupID.equals(group.getIdentifier())) { return group; } } return null; } /** * 選択したLight IDのリストを取得する. * @param lightIdList Light IDをカンマ区切りした文字列 * @return Light IDのリスト */ private String[] getSelectedIdList(final String lightIdList) { String[] strAry = lightIdList.split(","); int i = 0; for (String string : strAry) { strAry[i] = string.trim(); i++; } return strAry; } /** * Error レスポンス設定. * @param response response */ private void setResultERR(final Intent response) { setResult(response, DConnectMessage.RESULT_ERROR); } /** * 成功レスポンス送信. * @param response response */ private void sendResultOK(final Intent response) { setResult(response, DConnectMessage.RESULT_OK); getContext().sendBroadcast(response); } /** * エラーレスポンスを送信する. * @param response エラーレスポンス */ private void sendResultERR(final Intent response) { setResultERR(response); getContext().sendBroadcast(response); } /** * ライトID取得. * * @param request request * @return lightid */ private static String getLightID(final Intent request) { return request.getStringExtra(PARAM_LIGHT_ID); } /** * 名前取得. * * @param request request * @return myName */ private static String getName(final Intent request) { return request.getStringExtra(PARAM_NAME); } /** * グループ名取得. * * @param request request * @return myName */ private static String getGroupName(final Intent request) { return request.getStringExtra(PARAM_GROUP_NAME); } /** * ライトID取得. * * @param request request * @return myName */ private static String getLightIds(final Intent request) { return request.getStringExtra(PARAM_LIGHT_IDS); } /** * グループID取得. * * @param request request * @return myName */ private static String getGroupId(final Intent request) { return request.getStringExtra(PARAM_GROUP_ID); } /** * 輝度取得. * * @param request request * @return PARAM_BRIGHTNESS */ private static String getBrightness(final Intent request) { return request.getStringExtra(PARAM_BRIGHTNESS); } /** * リクエストからcolorパラメータを取得する. * * @param request リクエスト * @return colorパラメータ */ private static String getColor(final Intent request) { return request.getStringExtra(PARAM_COLOR); } /** * Hueの色指定. * @author NTT DOCOMO, INC. */ private static class Color { /** * モデル. */ private static final String MODEL = "LST001"; /** R. */ final int mR; /** G. */ final int mG; /** B. */ final int mB; /** 色相のX座標. */ final float mX; /** 色相のY座標. */ final float mY; /** * コンストラクタ. * @param rgb RGBの文字列 */ Color(final String rgb) { if (rgb == null) { throw new IllegalArgumentException(); } if (rgb.length() != RGB_LENGTH) { throw new IllegalArgumentException(); } String rr = rgb.substring(0, 2); String gg = rgb.substring(2, 4); String bb = rgb.substring(4, 6); if (rr == null) { throw new IllegalArgumentException(); } if (gg == null) { throw new IllegalArgumentException(); } if (bb == null) { throw new IllegalArgumentException(); } this.mR = Integer.parseInt(rr, 16); this.mG = Integer.parseInt(gg, 16); this.mB = Integer.parseInt(bb, 16); float[] xy = PHUtilities.calculateXYFromRGB(this.mR, this.mG, this.mB, MODEL); mX = xy[0]; mY = xy[1]; } } /** * Hueの明るさ判定. * @author NTT DOCOMO, INC. * */ private static class Brightness { /** 明るさのMax値. */ static final int MAX_VALUE = 255; /** 明るさのチューニング用Max値. */ static final int TUNED_MAX_VALUE = 254; /** 明るさの値. */ final int mValue; /** * コンストラクタ. * @param param 明るさ */ Brightness(final String param) { int temp = (int) (MAX_VALUE * Float.parseFloat(param)); if (temp >= MAX_VALUE) { temp = TUNED_MAX_VALUE; // 255を指定するとHue上のエラーとなるため254に丸める. } mValue = temp; } } /** * ライトのアダプター. * @author NTT DOCOMO, INC. * */ private static class PHLightAdapter implements PHLightListener { @Override public void onError(final int code, final String message) { } @Override public void onStateUpdate(final Map<String, String> successAttribute, final List<PHHueError> errorAttribute) { } @Override public void onSuccess() { } @Override public void onReceivingLightDetails(final PHLight light) { } @Override public void onReceivingLights(final List<PHBridgeResource> lights) { } @Override public void onSearchComplete() { } } /** * ライトグループのアダプター. * @author NTT DOCOMO, INC. * */ private static class PHGroupAdapter implements PHGroupListener { @Override public void onError(final int code, final String msg) { } @Override public void onStateUpdate(final Map<String, String> arg0, final List<PHHueError> arg1) { } @Override public void onSuccess() { } @Override public void onCreated(final PHGroup group) { } @Override public void onReceivingAllGroups(final List<PHBridgeResource> arg0) { } @Override public void onReceivingGroupDetails(final PHGroup arg0) { } } }
dConnectDevicePlugin/dConnectDeviceHue/src/org/deviceconnect/android/deviceplugin/hue/profile/HueLightProfile.java
/* HueLightProfile Copyright (c) 2014 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ package org.deviceconnect.android.deviceplugin.hue.profile; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.deviceconnect.android.message.MessageUtils; import org.deviceconnect.android.original.profile.LightProfile; import org.deviceconnect.message.DConnectMessage; import android.content.Intent; import android.os.Bundle; import com.philips.lighting.hue.listener.PHGroupListener; import com.philips.lighting.hue.listener.PHLightListener; import com.philips.lighting.hue.sdk.PHHueSDK; import com.philips.lighting.hue.sdk.utilities.PHUtilities; import com.philips.lighting.model.PHBridge; import com.philips.lighting.model.PHBridgeResource; import com.philips.lighting.model.PHBridgeResourcesCache; import com.philips.lighting.model.PHGroup; import com.philips.lighting.model.PHHueError; import com.philips.lighting.model.PHLight; import com.philips.lighting.model.PHLight.PHLightColorMode; import com.philips.lighting.model.PHLightState; /** * 親クラスで振り分けられたメソッドに対して、Hueのlight attribute処理を呼び出す. * @author NTT DOCOMO, INC. */ public class HueLightProfile extends LightProfile { /** * エラーコード301. */ private static final int HUE_SDK_ERROR_301 = 301; @Override protected boolean onGetLight(final Intent request, final Intent response) { String serviceId = getServiceID(request); PHBridge bridge = findBridge(serviceId); if (bridge == null) { MessageUtils.setNotFoundServiceError(response, "Not found bridge: " + serviceId); return true; } List<Bundle> lightsParam = new ArrayList<Bundle>(); for (PHLight light : bridge.getResourceCache().getAllLights()) { Bundle lightParam = new Bundle(); lightParam.putString(PARAM_LIGHT_ID, light.getIdentifier()); lightParam.putString(PARAM_NAME, light.getName()); lightParam.putString(PARAM_CONFIG, ""); PHLightState state = light.getLastKnownLightState(); lightParam.putBoolean(PARAM_ON, state.isOn()); lightsParam.add(lightParam); } response.putExtra(PARAM_LIGHTS, lightsParam.toArray(new Bundle[lightsParam.size()])); sendResultOK(response); return false; } @Override protected boolean onPostLight(final Intent request, final Intent response) { String serviceId = getServiceID(request); String lightId = getLightID(request); // 必須パラメータの存在チェック if (lightId == null || lightId.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "lightId is not specified."); return true; } PHBridge bridge = findBridge(serviceId); if (bridge == null) { MessageUtils.setNotFoundServiceError(response, "Not found bridge: " + serviceId); return true; } PHLight light = bridge.getResourceCache().getLights().get(lightId); if (light == null) { MessageUtils.setNotFoundServiceError(response, "Not found light: " + lightId + "@" + serviceId); return true; } PHLightState lightState = new PHLightState(); lightState.setOn(true); lightState.setColorMode(PHLightColorMode.COLORMODE_XY); String colorParam = getColor(request); if (colorParam == null) { colorParam = "FFFFFF"; } Color hueColor = new Color(colorParam); lightState.setX(hueColor.mX); lightState.setY(hueColor.mY); String brightnessParam = getBrightness(request); if (brightnessParam != null) { lightState.setBrightness(Integer.valueOf(new Brightness(brightnessParam).mValue)); } bridge.updateLightState(light, lightState, new PHLightAdapter() { @Override public void onStateUpdate(final Map<String, String> successAttribute, final List<PHHueError> errorAttribute) { sendResultOK(response); } @Override public void onError(final int code, final String message) { MessageUtils.setUnknownError(response, code + ": " + message); sendResultERR(response); } }); return false; } @Override protected boolean onDeleteLight(final Intent request, final Intent response) { String serviceId = getServiceID(request); String lightId = getLightID(request); // 必須パラメータの存在チェック if (lightId == null || lightId.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "lightId is not specified."); return true; } PHBridge bridge = findBridge(serviceId); if (bridge == null) { MessageUtils.setNotFoundServiceError(response, "Not found bridge: " + serviceId); return true; } PHLight light = bridge.getResourceCache().getLights().get(lightId); if (light == null) { MessageUtils.setNotFoundServiceError(response, "Not found light: " + lightId + "@" + serviceId); return true; } PHLightState lightState = new PHLightState(); lightState.setOn(false); bridge.updateLightState(light, lightState, new PHLightAdapter() { @Override public void onStateUpdate(final Map<String, String> successAttribute, final List<PHHueError> errorAttribute) { sendResultOK(response); } @Override public void onError(final int code, final String message) { String errMsg = "ライトの状態更新に失敗しました hue:code = " + Integer.toString(code) + " message = " + message; MessageUtils.setUnknownError(response, errMsg); sendResultERR(response); } }); return false; } @Override protected boolean onPutLight(final Intent request, final Intent response) { String serviceId = getServiceID(request); String lightId = getLightID(request); String name = getName(request); // 必須パラメータの存在チェック if (lightId == null || lightId.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "lightId is not specified."); return true; } if (name == null || name.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "name is not specified."); return true; } PHBridge bridge = findBridge(serviceId); if (bridge == null) { MessageUtils.setNotFoundServiceError(response, "Not found bridge: " + serviceId); return true; } PHLight light = getLight(bridge, lightId); if (light == null) { MessageUtils.setNotFoundServiceError(response, "Not found light: " + lightId + "@" + serviceId); return true; } PHLight newLight = new PHLight(light); newLight.setName(name); bridge.updateLight(newLight, new PHLightAdapter() { @Override public void onSuccess() { sendResultOK(response); } @Override public void onError(final int code, final String message) { String errMsg = "ライトの名称変更に失敗しました hue:code = " + Integer.toString(code) + " message = " + message; MessageUtils.setUnknownError(response, errMsg); sendResultERR(response); } }); return false; } @Override protected boolean onGetLightGroup(final Intent request, final Intent response) { String serviceId = getServiceID(request); PHBridge bridge = findBridge(serviceId); if (bridge == null) { MessageUtils.setNotFoundServiceError(response, "Not found bridge: " + serviceId); return true; } List<Bundle> groupsParam = new ArrayList<Bundle>(); Map<String, PHLight> allLights = bridge.getResourceCache().getLights(); for (PHGroup group : bridge.getResourceCache().getAllGroups()) { Bundle groupParam = new Bundle(); groupParam.putString(PARAM_GROUP_ID, group.getIdentifier()); groupParam.putString(PARAM_NAME, group.getName()); List<Bundle> lightsParam = new ArrayList<Bundle>(); for (String lightId : group.getLightIdentifiers()) { PHLight light = allLights.get(lightId); if (light != null) { Bundle lightParam = new Bundle(); lightParam.putString(PARAM_LIGHT_ID, lightId); lightParam.putString(PARAM_NAME, light.getName()); PHLightState state = light.getLastKnownLightState(); if (state != null) { lightParam.putBoolean(PARAM_ON, state.isOn().booleanValue()); } lightParam.putString(PARAM_CONFIG, ""); lightsParam.add(lightParam); } } groupParam.putParcelableArray(PARAM_LIGHTS, lightsParam.toArray(new Bundle[lightsParam.size()])); groupParam.putString(PARAM_CONFIG, ""); groupsParam.add(groupParam); } response.putExtra(PARAM_LIGHT_GROUPS, groupsParam.toArray(new Bundle[groupsParam.size()])); setResult(response, DConnectMessage.RESULT_OK); return true; } @Override protected boolean onPostLightGroup(final Intent request, final Intent response) { String serviceId = getServiceID(request); String groupId = getGroupId(request); // 必須パラメータの存在チェック if (groupId == null || groupId.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "groupId is not specified."); return true; } PHBridge bridge = findBridge(serviceId); if (bridge == null) { MessageUtils.setNotFoundServiceError(response, "Not found bridge: " + serviceId); return true; } PHLightState lightState = new PHLightState(); lightState.setOn(true); lightState.setColorMode(PHLightColorMode.COLORMODE_XY); String colorParam = getColor(request); if (colorParam == null) { colorParam = "FFFFFF"; } Color hueColor = new Color(colorParam); lightState.setX(hueColor.mX); lightState.setY(hueColor.mY); String brightnessParam = getBrightness(request); if (brightnessParam != null) { lightState.setBrightness(Integer.valueOf(new Brightness(brightnessParam).mValue)); } if ("0".equals(groupId)) { bridge.setLightStateForDefaultGroup(lightState); setResult(response, DConnectMessage.RESULT_OK); return true; } PHGroup group = getGroup(bridge, groupId); if (group == null) { MessageUtils.setUnknownError(response, "Not found group: " + groupId); return true; } bridge.setLightStateForGroup(group.getIdentifier(), lightState, new PHGroupAdapter() { @Override public void onError(final int code, final String message) { String msg = "ライトの状態更新に失敗しました hue:code = " + Integer.toString(code) + " message = " + message; MessageUtils.setUnknownError(response, msg); sendResultERR(response); } @Override public void onStateUpdate(final Map<String, String> successAttributes, final List<PHHueError> errorAttributes) { sendResultOK(response); } }); return false; } @Override protected boolean onDeleteLightGroup(final Intent request, final Intent response) { String serviceId = getServiceID(request); String groupId = getGroupId(request); // 必須パラメータの存在チェック if (groupId == null || groupId.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "groupId is not specified."); return true; } PHBridge bridge = findBridge(serviceId); if (bridge == null) { MessageUtils.setNotFoundServiceError(response, "Not found bridge: " + serviceId); return true; } PHLightState lightState = new PHLightState(); lightState.setOn(false); if ("0".equals(groupId)) { bridge.setLightStateForDefaultGroup(lightState); setResult(response, DConnectMessage.RESULT_OK); return true; } PHGroup group = getGroup(bridge, groupId); if (group == null) { MessageUtils.setUnknownError(response, "Not found group: " + groupId); return true; } bridge.setLightStateForGroup(group.getIdentifier(), lightState, new PHGroupAdapter() { @Override public void onError(final int code, final String message) { String msg = "ライトの状態更新に失敗しました hue:code = " + Integer.toString(code) + " message = " + message; MessageUtils.setUnknownError(response, msg); sendResultERR(response); } @Override public void onStateUpdate(final Map<String, String> successAttributes, final List<PHHueError> errorAttributes) { sendResultOK(response); } }); return false; } @Override protected boolean onPutLightGroup(final Intent request, final Intent response) { String serviceId = getServiceID(request); String groupId = getGroupId(request); // 必須パラメータの存在チェック if (groupId == null || groupId.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "groupId is not specified."); return true; } PHBridge bridge = findBridge(serviceId); if (bridge == null) { MessageUtils.setNotFoundServiceError(response, "Not found bridge: " + serviceId); return true; } String name = getName(request); if (name == null || name.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "name is not specified."); return true; } PHGroup group = getGroup(bridge, groupId); if (group == null) { MessageUtils.setUnknownError(response, "Not found group: " + groupId); return true; } PHGroup newGroup = new PHGroup(name, group.getIdentifier()); bridge.updateGroup(newGroup, new PHGroupAdapter() { @Override public void onSuccess() { sendResultOK(response); } @Override public void onError(final int code, final String message) { String errMsg = "グループの名称変更に失敗しました hue:code = " + Integer.toString(code) + " message = " + message; MessageUtils.setUnknownError(response, errMsg); sendResultERR(response); } }); return false; } @Override protected boolean onPostLightGroupCreate(final Intent request, final Intent response) { String serviceId = getServiceID(request); String groupName = getGroupName(request); String lightIds = getLightIds(request); // 必須パラメータの存在チェック if (groupName == null || groupName.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "groupName is not specified."); return true; } if (lightIds == null || lightIds.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "lightIds is not specified."); return true; } String[] lightIdsArray = getSelectedIdList(lightIds); if (lightIdsArray == null) { MessageUtils.setInvalidRequestParameterError(response, "lightIds is not specified."); return true; } else if (lightIdsArray.length < 1) { MessageUtils.setInvalidRequestParameterError(response, "lightIds is not specified."); return true; } PHBridge bridge = findBridge(serviceId); if (bridge == null) { MessageUtils.setNotFoundServiceError(response, "Not found bridge: " + serviceId); return true; } bridge.createGroup(groupName, Arrays.asList(lightIdsArray), new PHGroupAdapter() { @Override public void onCreated(final PHGroup group) { response.putExtra(PARAM_GROUP_ID, group.getIdentifier()); sendResultOK(response); } @Override public void onError(final int code, final String msg) { String errMsg = "グループ作成に失敗しました hue:code = " + Integer.toString(code) + " message = " + msg; if (code == HUE_SDK_ERROR_301) { MessageUtils.setUnknownError(response, "グループが作成できる上限に達しています"); } else { MessageUtils.setUnknownError(response, errMsg); } sendResultERR(response); } }); return false; } @Override protected boolean onDeleteLightGroupClear(final Intent request, final Intent response) { String serviceId = getServiceID(request); String groupId = getGroupId(request); // 必須パラメータの存在チェック if (groupId == null || groupId.length() == 0) { MessageUtils.setInvalidRequestParameterError(response, "groupId is not specified."); return true; } PHBridge bridge = findBridge(serviceId); if (bridge == null) { MessageUtils.setNotFoundServiceError(response, "Not found bridge: " + serviceId); return true; } bridge.deleteGroup(groupId, new PHGroupAdapter() { @Override public void onSuccess() { sendResultOK(response); } @Override public void onError(final int code, final String msg) { String errMsg = "グループ削除に失敗しました hue:code = " + Integer.toString(code) + " message = " + msg; MessageUtils.setUnknownError(response, errMsg); sendResultERR(response); } }); return false; } /** * Hueのブリッジを検索する. * @param serviceId Service ID * @return Hueのブリッジを管理するオブジェクト */ private PHBridge findBridge(final String serviceId) { PHBridge bridge = PHHueSDK.getInstance().getSelectedBridge(); if (bridge != null) { PHBridgeResourcesCache cache = bridge.getResourceCache(); String ipAddress = cache.getBridgeConfiguration().getIpAddress(); if (serviceId.equals(ipAddress)) { return bridge; } } return null; } /** * Hue Lightを管理するオブジェクトを取得する. * @param bridge Hueのブリッジ * @param lightId Light ID * @return Lightを管理するオブジェクト */ private PHLight getLight(final PHBridge bridge, final String lightId) { for (PHLight light : bridge.getResourceCache().getAllLights()) { if (light.getIdentifier().equals(lightId)) { return light; } } return null; } /** * Hue Lightのグループ情報を管理するオブジェクトを取得する. * @param bridge Hueのブリッジ * @param groupID Group ID * @return Lightのグループ情報を持つオブジェクト */ private PHGroup getGroup(final PHBridge bridge, final String groupID) { for (PHGroup group : bridge.getResourceCache().getAllGroups()) { if (groupID.equals(group.getIdentifier())) { return group; } } return null; } /** * 選択したLight IDのリストを取得する. * @param lightIdList Light IDをカンマ区切りした文字列 * @return Light IDのリスト */ private String[] getSelectedIdList(final String lightIdList) { String[] strAry = lightIdList.split(","); int i = 0; for (String string : strAry) { strAry[i] = string.trim(); i++; } return strAry; } /** * Error レスポンス設定. * @param response response */ private void setResultERR(final Intent response) { setResult(response, DConnectMessage.RESULT_ERROR); } /** * 成功レスポンス送信. * @param response response */ private void sendResultOK(final Intent response) { setResult(response, DConnectMessage.RESULT_OK); getContext().sendBroadcast(response); } /** * エラーレスポンスを送信する. * @param response エラーレスポンス */ private void sendResultERR(final Intent response) { setResultERR(response); getContext().sendBroadcast(response); } /** * ライトID取得. * * @param request request * @return lightid */ private static String getLightID(final Intent request) { return request.getStringExtra(PARAM_LIGHT_ID); } /** * 名前取得. * * @param request request * @return myName */ private static String getName(final Intent request) { return request.getStringExtra(PARAM_NAME); } /** * グループ名取得. * * @param request request * @return myName */ private static String getGroupName(final Intent request) { return request.getStringExtra(PARAM_GROUP_NAME); } /** * ライトID取得. * * @param request request * @return myName */ private static String getLightIds(final Intent request) { return request.getStringExtra(PARAM_LIGHT_IDS); } /** * グループID取得. * * @param request request * @return myName */ private static String getGroupId(final Intent request) { return request.getStringExtra(PARAM_GROUP_ID); } /** * 輝度取得. * * @param request request * @return PARAM_BRIGHTNESS */ private static String getBrightness(final Intent request) { return request.getStringExtra(PARAM_BRIGHTNESS); } /** * リクエストからcolorパラメータを取得する. * * @param request リクエスト * @return colorパラメータ */ private static String getColor(final Intent request) { return request.getStringExtra(PARAM_COLOR); } /** * Hueの色指定. * @author NTT DOCOMO, INC. */ private static class Color { /** * モデル. */ private static final String MODEL = "LST001"; /** RGBの文字列の長さ. */ private static final int RGB_LENGTH = 6; /** R. */ final int mR; /** G. */ final int mG; /** B. */ final int mB; /** 色相のX座標. */ final float mX; /** 色相のY座標. */ final float mY; /** * コンストラクタ. * @param rgb RGBの文字列 */ Color(final String rgb) { if (rgb == null) { throw new IllegalArgumentException(); } if (rgb.length() != RGB_LENGTH) { throw new IllegalArgumentException(); } String rr = rgb.substring(0, 2); String gg = rgb.substring(2, 4); String bb = rgb.substring(4, 6); if (rr == null) { throw new IllegalArgumentException(); } if (gg == null) { throw new IllegalArgumentException(); } if (bb == null) { throw new IllegalArgumentException(); } this.mR = Integer.parseInt(rr, 16); this.mG = Integer.parseInt(gg, 16); this.mB = Integer.parseInt(bb, 16); float[] xy = PHUtilities.calculateXYFromRGB(this.mR, this.mG, this.mB, MODEL); mX = xy[0]; mY = xy[1]; } } /** * Hueの明るさ判定. * @author NTT DOCOMO, INC. * */ private static class Brightness { /** 明るさのMax値. */ static final int MAX_VALUE = 255; /** 明るさのチューニング用Max値. */ static final int TUNED_MAX_VALUE = 254; /** 明るさの値. */ final int mValue; /** * コンストラクタ. * @param param 明るさ */ Brightness(final String param) { int temp = (int) (MAX_VALUE * Float.parseFloat(param)); if (temp >= MAX_VALUE) { temp = TUNED_MAX_VALUE; // 255を指定するとHue上のエラーとなるため254に丸める. } mValue = temp; } } /** * ライトのアダプター. * @author NTT DOCOMO, INC. * */ private static class PHLightAdapter implements PHLightListener { @Override public void onError(final int code, final String message) { } @Override public void onStateUpdate(final Map<String, String> successAttribute, final List<PHHueError> errorAttribute) { } @Override public void onSuccess() { } @Override public void onReceivingLightDetails(final PHLight light) { } @Override public void onReceivingLights(final List<PHBridgeResource> lights) { } @Override public void onSearchComplete() { } } /** * ライトグループのアダプター. * @author NTT DOCOMO, INC. * */ private static class PHGroupAdapter implements PHGroupListener { @Override public void onError(final int code, final String msg) { } @Override public void onStateUpdate(final Map<String, String> arg0, final List<PHHueError> arg1) { } @Override public void onSuccess() { } @Override public void onCreated(final PHGroup group) { } @Override public void onReceivingAllGroups(final List<PHBridgeResource> arg0) { } @Override public void onReceivingGroupDetails(final PHGroup arg0) { } } }
Add request parameter check and modify returning error code.
dConnectDevicePlugin/dConnectDeviceHue/src/org/deviceconnect/android/deviceplugin/hue/profile/HueLightProfile.java
Add request parameter check and modify returning error code.
<ide><path>ConnectDevicePlugin/dConnectDeviceHue/src/org/deviceconnect/android/deviceplugin/hue/profile/HueLightProfile.java <ide> * エラーコード301. <ide> */ <ide> private static final int HUE_SDK_ERROR_301 = 301; <add> /** RGBの文字列の長さ. */ <add> private static final int RGB_LENGTH = 6; <ide> <ide> @Override <ide> protected boolean onGetLight(final Intent request, final Intent response) { <ide> } <ide> PHLight light = bridge.getResourceCache().getLights().get(lightId); <ide> if (light == null) { <del> MessageUtils.setNotFoundServiceError(response, "Not found light: " + lightId + "@" + serviceId); <del> return true; <del> } <del> <add> MessageUtils.setInvalidRequestParameterError(response, "Not found light: " + lightId + "@" + serviceId); <add> return true; <add> } <add> <add> if (getBrightness(request) != null) { <add> try { <add> float mBrightness = Float.valueOf(getBrightness(request)); <add> if (mBrightness > 1.0 <add> || mBrightness < 0) { <add> MessageUtils.setInvalidRequestParameterError(response, <add> "brightness should be a value between 0 and 1.0"); <add> return true; <add> } <add> } catch (NumberFormatException e) { <add> MessageUtils.setInvalidRequestParameterError(response, <add> "brightness should be a value between 0 and 1.0"); <add> return true; <add> } <add> } <add> <add> if (getColor(request) != null) { <add> try { <add> String mColor = getColor(request); <add> String rr = mColor.substring(0, 2); <add> String gg = mColor.substring(2, 4); <add> String bb = mColor.substring(4, 6); <add> int mColorParam; <add> if (mColor.length() == RGB_LENGTH) { <add> if (rr == null) { <add> MessageUtils.setInvalidRequestParameterError(response); <add> return true; <add> } else { <add> mColorParam = Integer.parseInt(rr, 16); <add> } <add> if (gg == null) { <add> MessageUtils.setInvalidRequestParameterError(response); <add> return true; <add> } else { <add> mColorParam = Integer.parseInt(gg, 16); <add> } <add> if (bb == null) { <add> MessageUtils.setInvalidRequestParameterError(response); <add> return true; <add> } else { <add> mColorParam = Integer.parseInt(bb, 16); <add> } <add> } else { <add> MessageUtils.setInvalidRequestParameterError(response); <add> return true; <add> } <add> } catch (NumberFormatException e) { <add> MessageUtils.setInvalidRequestParameterError(response); <add> return true; <add> } catch (IllegalArgumentException e) { <add> MessageUtils.setInvalidRequestParameterError(response); <add> return true; <add> } <add> } <add> <ide> PHLightState lightState = new PHLightState(); <ide> lightState.setOn(true); <ide> lightState.setColorMode(PHLightColorMode.COLORMODE_XY); <ide> } <ide> PHLight light = bridge.getResourceCache().getLights().get(lightId); <ide> if (light == null) { <del> MessageUtils.setNotFoundServiceError(response, "Not found light: " + lightId + "@" + serviceId); <add> MessageUtils.setInvalidRequestParameterError(response, "Not found light: " + lightId + "@" + serviceId); <ide> return true; <ide> } <ide> PHLightState lightState = new PHLightState(); <ide> } <ide> PHLight light = getLight(bridge, lightId); <ide> if (light == null) { <del> MessageUtils.setNotFoundServiceError(response, "Not found light: " + lightId + "@" + serviceId); <add> MessageUtils.setInvalidRequestParameterError(response, "Not found light: " + lightId + "@" + serviceId); <ide> return true; <ide> } <ide> <ide> * モデル. <ide> */ <ide> private static final String MODEL = "LST001"; <del> /** RGBの文字列の長さ. */ <del> private static final int RGB_LENGTH = 6; <ide> /** R. */ <ide> final int mR; <ide> /** G. */
Java
apache-2.0
d13b6cd60dad543ba21d1b040fbf86e377b71a44
0
ipros-team/presto,tellproject/presto,shubham166/presto,twitter-forks/presto,nileema/presto,vishalsan/presto,elonazoulay/presto,troels/nz-presto,martint/presto,DanielTing/presto,springning/presto,miquelruiz/presto,albertocsm/presto,ebyhr/presto,haozhun/presto,nvoron23/presto,xiangel/presto,cberner/presto,shubham166/presto,mattyb149/presto,fiedukow/presto,Praveen2112/presto,tomz/presto,smartpcr/presto,mcanthony/presto,jf367/presto,cawallin/presto,ajoabraham/presto,stewartpark/presto,EvilMcJerkface/presto,damiencarol/presto,shixuan-fan/presto,kingland/presto,sumitkgec/presto,xiangel/presto,raghavsethi/presto,joshk/presto,ipros-team/presto,mugglmenzel/presto,kaschaeffer/presto,nakajijiji/presto,joshk/presto,nileema/presto,TeradataCenterForHadoop/bootcamp,idemura/presto,sumanth232/presto,Yaliang/presto,kuzemchik/presto,Teradata/presto,shubham166/presto,bloomberg/presto,CHINA-JD/presto,jf367/presto,martint/presto,pwz3n0/presto,gh351135612/presto,bloomberg/presto,aleph-zero/presto,kingland/presto,Myrthan/presto,prateek1306/presto,EvilMcJerkface/presto,mcanthony/presto,wrmsr/presto,propene/presto,pwz3n0/presto,mode/presto,arhimondr/presto,geraint0923/presto,losipiuk/presto,cberner/presto,ArturGajowy/presto,joy-yao/presto,XiaominZhang/presto,martint/presto,zofuthan/presto,mandusm/presto,nileema/presto,springning/presto,mode/presto,miniway/presto,ocono-tech/presto,wrmsr/presto,HackShare/Presto,jf367/presto,Yaliang/presto,Jimexist/presto,zjshen/presto,aleph-zero/presto,avasilevskiy/presto,svstanev/presto,arhimondr/presto,jf367/presto,mugglmenzel/presto,damiencarol/presto,totticarter/presto,kaschaeffer/presto,losipiuk/presto,nileema/presto,pnowojski/presto,dabaitu/presto,smartpcr/presto,aglne/presto,hulu/presto,kined/presto,arhimondr/presto,chrisunder/presto,yu-yamada/presto,aramesh117/presto,pwz3n0/presto,Svjard/presto,aramesh117/presto,aleph-zero/presto,prateek1306/presto,y-lan/presto,yu-yamada/presto,mode/presto,kaschaeffer/presto,cosinequanon/presto,RobinUS2/presto,electrum/presto,wagnermarkd/presto,mattyb149/presto,DanielTing/presto,sopel39/presto,wyukawa/presto,zzhao0/presto,dongjoon-hyun/presto,shixuan-fan/presto,tellproject/presto,youngwookim/presto,ebd2/presto,mattyb149/presto,jiangyifangh/presto,xiangel/presto,treasure-data/presto,mono-plane/presto,miquelruiz/presto,facebook/presto,martint/presto,propene/presto,y-lan/presto,elonazoulay/presto,avasilevskiy/presto,cberner/presto,saidalaoui/presto,bloomberg/presto,mandusm/presto,mono-plane/presto,ebyhr/presto,yuananf/presto,mpilman/presto,sumitkgec/presto,wagnermarkd/presto,mvp/presto,sopel39/presto,deciament/presto,harunurhan/presto,facebook/presto,mono-plane/presto,nsabharwal/presto,kined/presto,zofuthan/presto,Yaliang/presto,raghavsethi/presto,nsabharwal/presto,zzhao0/presto,gcnonato/presto,pwz3n0/presto,ebd2/presto,saidalaoui/presto,twitter-forks/presto,sumanth232/presto,ipros-team/presto,nezihyigitbasi/presto,RobinUS2/presto,mandusm/presto,Svjard/presto,ebyhr/presto,dongjoon-hyun/presto,jacobgao/presto,Svjard/presto,kaschaeffer/presto,zhenyuy-fb/presto,mpilman/presto,ptkool/presto,ajoabraham/presto,sumanth232/presto,deciament/presto,troels/nz-presto,kietly/presto,zjshen/presto,ArturGajowy/presto,ocono-tech/presto,fengshao0907/presto,raghavsethi/presto,toxeh/presto,elonazoulay/presto,soz-fb/presto,Zoomdata/presto,Jimexist/presto,takari/presto,zhenxiao/presto,mvp/presto,Jimexist/presto,sunchao/presto,totticarter/presto,fiedukow/presto,mpilman/presto,mandusm/presto,yu-yamada/presto,fiedukow/presto,stagraqubole/presto,XiaominZhang/presto,dongjoon-hyun/presto,gh351135612/presto,jiangyifangh/presto,dain/presto,siddhartharay007/presto,springning/presto,Teradata/presto,CHINA-JD/presto,miniway/presto,jietang3/test,idemura/presto,damiencarol/presto,toyama0919/presto,dabaitu/presto,ebyhr/presto,jiekechoo/presto,lingochamp/presto,DanielTing/presto,jiekechoo/presto,ajoabraham/presto,Myrthan/presto,wrmsr/presto,jf367/presto,kingland/presto,prateek1306/presto,XiaominZhang/presto,svstanev/presto,aramesh117/presto,sumitkgec/presto,arhimondr/presto,cosinequanon/presto,mvp/presto,raghavsethi/presto,miquelruiz/presto,frsyuki/presto,ajoabraham/presto,shixuan-fan/presto,Nasdaq/presto,dain/presto,facebook/presto,dabaitu/presto,smartnews/presto,prateek1306/presto,RobinUS2/presto,shixuan-fan/presto,shubham166/presto,jiangyifangh/presto,nezihyigitbasi/presto,zzhao0/presto,mpilman/presto,nsabharwal/presto,wyukawa/presto,zzhao0/presto,haozhun/presto,jacobgao/presto,hgschmie/presto,sdgdsffdsfff/presto,mcanthony/presto,stewartpark/presto,ptkool/presto,wangcan2014/presto,hgschmie/presto,fipar/presto,smartnews/presto,jxiang/presto,sdgdsffdsfff/presto,pnowojski/presto,smartpcr/presto,sopel39/presto,dain/presto,dain/presto,haozhun/presto,kuzemchik/presto,sunchao/presto,miniway/presto,zhenyuy-fb/presto,cawallin/presto,chrisunder/presto,mvp/presto,elonazoulay/presto,bloomberg/presto,zjshen/presto,bd-dev-mobileum/presto,shixuan-fan/presto,wyukawa/presto,smartnews/presto,harunurhan/presto,saidalaoui/presto,siddhartharay007/presto,mode/presto,EvilMcJerkface/presto,totticarter/presto,avasilevskiy/presto,mugglmenzel/presto,Zoomdata/presto,tomz/presto,TeradataCenterForHadoop/bootcamp,pwz3n0/presto,nvoron23/presto,lingochamp/presto,deciament/presto,youngwookim/presto,y-lan/presto,toxeh/presto,denizdemir/presto,Jimexist/presto,sumanth232/presto,lingochamp/presto,smartpcr/presto,albertocsm/presto,yu-yamada/presto,idemura/presto,twitter-forks/presto,mattyb149/presto,rockerbox/presto,dabaitu/presto,ptkool/presto,miniway/presto,suyucs/presto,wagnermarkd/presto,vishalsan/presto,springning/presto,hulu/presto,avasilevskiy/presto,prestodb/presto,kined/presto,toxeh/presto,cawallin/presto,damiencarol/presto,avasilevskiy/presto,mpilman/presto,lingochamp/presto,Praveen2112/presto,chrisunder/presto,11xor6/presto,electrum/presto,deciament/presto,mbeitchman/presto,vishalsan/presto,twitter-forks/presto,nakajijiji/presto,zjshen/presto,zhenxiao/presto,Svjard/presto,joy-yao/presto,EvilMcJerkface/presto,hgschmie/presto,pnowojski/presto,siddhartharay007/presto,nileema/presto,xiangel/presto,denizdemir/presto,toyama0919/presto,jekey/presto,erichwang/presto,kuzemchik/presto,sumanth232/presto,sopel39/presto,Jimexist/presto,zofuthan/presto,cberner/presto,geraint0923/presto,zjshen/presto,gcnonato/presto,kined/presto,erichwang/presto,wangcan2014/presto,zhenyuy-fb/presto,denizdemir/presto,hulu/presto,kietly/presto,zhenyuy-fb/presto,tomz/presto,raghavsethi/presto,arhimondr/presto,aglne/presto,sdgdsffdsfff/presto,toxeh/presto,losipiuk/presto,siddhartharay007/presto,wyukawa/presto,hgschmie/presto,dongjoon-hyun/presto,damiencarol/presto,saidalaoui/presto,takari/presto,lingochamp/presto,kuzemchik/presto,kined/presto,nezihyigitbasi/presto,hgschmie/presto,mbeitchman/presto,svstanev/presto,zhenxiao/presto,takari/presto,tomz/presto,gh351135612/presto,joy-yao/presto,totticarter/presto,fipar/presto,martint/presto,mugglmenzel/presto,yuananf/presto,vermaravikant/presto,takari/presto,haozhun/presto,bd-dev-mobileum/presto,stewartpark/presto,ajoabraham/presto,nezihyigitbasi/presto,Zoomdata/presto,tellproject/presto,jxiang/presto,prestodb/presto,treasure-data/presto,XiaominZhang/presto,electrum/presto,joshk/presto,rockerbox/presto,mode/presto,kietly/presto,pnowojski/presto,wangcan2014/presto,joy-yao/presto,DanielTing/presto,erichwang/presto,elonazoulay/presto,chrisunder/presto,zofuthan/presto,ipros-team/presto,xiangel/presto,mandusm/presto,geraint0923/presto,Zoomdata/presto,harunurhan/presto,soz-fb/presto,CHINA-JD/presto,kietly/presto,Teradata/presto,toyama0919/presto,mvp/presto,haitaoyao/presto,propene/presto,nakajijiji/presto,twitter-forks/presto,soz-fb/presto,aglne/presto,jiekechoo/presto,kingland/presto,miniway/presto,sumitkgec/presto,saidalaoui/presto,yuananf/presto,nvoron23/presto,nsabharwal/presto,EvilMcJerkface/presto,aleph-zero/presto,XiaominZhang/presto,TeradataCenterForHadoop/bootcamp,Yaliang/presto,frsyuki/presto,suyucs/presto,ptkool/presto,nvoron23/presto,y-lan/presto,albertocsm/presto,jxiang/presto,wrmsr/presto,ptkool/presto,svstanev/presto,haitaoyao/presto,Myrthan/presto,jiangyifangh/presto,troels/nz-presto,troels/nz-presto,sunchao/presto,facebook/presto,ArturGajowy/presto,miquelruiz/presto,prestodb/presto,ebd2/presto,fengshao0907/presto,gh351135612/presto,stewartpark/presto,bd-dev-mobileum/presto,DanielTing/presto,haitaoyao/presto,takari/presto,wagnermarkd/presto,gh351135612/presto,soz-fb/presto,gcnonato/presto,bd-dev-mobileum/presto,bd-dev-mobileum/presto,treasure-data/presto,Praveen2112/presto,ebd2/presto,deciament/presto,HackShare/Presto,ArturGajowy/presto,vermaravikant/presto,jekey/presto,mbeitchman/presto,joshk/presto,cosinequanon/presto,RobinUS2/presto,jekey/presto,11xor6/presto,wangcan2014/presto,mpilman/presto,jacobgao/presto,rockerbox/presto,ocono-tech/presto,fengshao0907/presto,dongjoon-hyun/presto,cosinequanon/presto,cawallin/presto,jiangyifangh/presto,sopel39/presto,svstanev/presto,TeradataCenterForHadoop/bootcamp,prestodb/presto,Praveen2112/presto,vermaravikant/presto,rockerbox/presto,prestodb/presto,dabaitu/presto,geraint0923/presto,hulu/presto,yuananf/presto,treasure-data/presto,fipar/presto,propene/presto,joy-yao/presto,smartnews/presto,suyucs/presto,jxiang/presto,zofuthan/presto,albertocsm/presto,albertocsm/presto,jxiang/presto,aramesh117/presto,sunchao/presto,suyucs/presto,fiedukow/presto,treasure-data/presto,idemura/presto,haozhun/presto,nakajijiji/presto,miquelruiz/presto,jiekechoo/presto,Myrthan/presto,wrmsr/presto,11xor6/presto,Yaliang/presto,tellproject/presto,nezihyigitbasi/presto,mattyb149/presto,totticarter/presto,mono-plane/presto,wrmsr/presto,fipar/presto,nsabharwal/presto,11xor6/presto,vermaravikant/presto,losipiuk/presto,jacobgao/presto,ArturGajowy/presto,wyukawa/presto,aramesh117/presto,youngwookim/presto,soz-fb/presto,rockerbox/presto,harunurhan/presto,sunchao/presto,geraint0923/presto,jekey/presto,Nasdaq/presto,mcanthony/presto,wagnermarkd/presto,propene/presto,CHINA-JD/presto,Nasdaq/presto,ebyhr/presto,Zoomdata/presto,mugglmenzel/presto,zzhao0/presto,mcanthony/presto,electrum/presto,Praveen2112/presto,haitaoyao/presto,bloomberg/presto,fiedukow/presto,hulu/presto,stewartpark/presto,erichwang/presto,Myrthan/presto,zhenxiao/presto,chrisunder/presto,Teradata/presto,losipiuk/presto,zhenyuy-fb/presto,nakajijiji/presto,Svjard/presto,jietang3/test,y-lan/presto,prestodb/presto,harunurhan/presto,11xor6/presto,youngwookim/presto,jiekechoo/presto,Nasdaq/presto,denizdemir/presto,yuananf/presto,fipar/presto,ebd2/presto,facebook/presto,ocono-tech/presto,wangcan2014/presto,sumitkgec/presto,vermaravikant/presto,treasure-data/presto,Nasdaq/presto,cosinequanon/presto,yu-yamada/presto,aleph-zero/presto,gcnonato/presto,tellproject/presto,fengshao0907/presto,smartnews/presto,stagraqubole/presto,prateek1306/presto,troels/nz-presto,RobinUS2/presto,ocono-tech/presto,tellproject/presto,smartpcr/presto,dain/presto,mbeitchman/presto,electrum/presto,idemura/presto,youngwookim/presto,cawallin/presto,cberner/presto,aglne/presto,mbeitchman/presto,HackShare/Presto,kuzemchik/presto,TeradataCenterForHadoop/bootcamp,kaschaeffer/presto,toyama0919/presto,aglne/presto,ipros-team/presto,springning/presto,toyama0919/presto,siddhartharay007/presto,toxeh/presto,jekey/presto,erichwang/presto,Teradata/presto,tomz/presto,kingland/presto,CHINA-JD/presto,suyucs/presto,fengshao0907/presto,haitaoyao/presto,kietly/presto
package com.facebook.presto.sql.compiler; import com.facebook.presto.sql.tree.QualifiedName; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import javax.annotation.Nullable; import java.util.List; import static com.facebook.presto.sql.compiler.NamedSlot.optionalNameGetter; public class TupleDescriptor { private final List<NamedSlot> slots; public TupleDescriptor(List<NamedSlot> slots) { Preconditions.checkNotNull(slots, "slots is null"); this.slots = ImmutableList.copyOf(slots); } public TupleDescriptor(List<Optional<QualifiedName>> names, List<Slot> slots) { Preconditions.checkNotNull(names, "names is null"); Preconditions.checkNotNull(slots, "slots is null"); Preconditions.checkArgument(names.size() == slots.size(), "names and slots sizes do not match"); ImmutableList.Builder<NamedSlot> builder = ImmutableList.builder(); for (int i = 0; i < names.size(); i++) { builder.add(new NamedSlot(names.get(i), slots.get(i))); } this.slots = builder.build(); } public List<Optional<QualifiedName>> getNames() { return Lists.transform(slots, optionalNameGetter()); } public List<NamedSlot> getSlots() { return slots; } @Override public String toString() { return slots.toString(); } public List<NamedSlot> resolve(final QualifiedName name) { return ImmutableList.copyOf(Iterables.filter(slots, new Predicate<NamedSlot>() { @Override public boolean apply(NamedSlot input) { return input.getName().isPresent() && input.getName().get().hasSuffix(name); } })); } }
presto-main/src/main/java/com/facebook/presto/sql/compiler/TupleDescriptor.java
package com.facebook.presto.sql.compiler; import com.facebook.presto.sql.tree.QualifiedName; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import javax.annotation.Nullable; import java.util.List; import static com.facebook.presto.sql.compiler.NamedSlot.optionalNameGetter; public class TupleDescriptor { private final List<NamedSlot> slots; public TupleDescriptor(List<NamedSlot> slots) { Preconditions.checkNotNull(slots, "slots is null"); this.slots = ImmutableList.copyOf(slots); } public TupleDescriptor(List<Optional<QualifiedName>> names, List<Slot> slots) { Preconditions.checkNotNull(names, "names is null"); Preconditions.checkNotNull(slots, "slots is null"); Preconditions.checkArgument(names.size() == slots.size(), "names and slots sizes do not match"); ImmutableList.Builder<NamedSlot> builder = ImmutableList.builder(); for (int i = 0; i < names.size(); i++) { builder.add(new NamedSlot(names.get(i), slots.get(i))); } this.slots = builder.build(); } public List<Optional<QualifiedName>> getNames() { return Lists.transform(slots, optionalNameGetter()); } public List<NamedSlot> getSlots() { return slots; } @Override public String toString() { return Joiner.on(",").join(slots); } public List<NamedSlot> resolve(final QualifiedName name) { return ImmutableList.copyOf(Iterables.filter(slots, new Predicate<NamedSlot>() { @Override public boolean apply(NamedSlot input) { return input.getName().isPresent() && input.getName().get().hasSuffix(name); } })); } }
Fix toString
presto-main/src/main/java/com/facebook/presto/sql/compiler/TupleDescriptor.java
Fix toString
<ide><path>resto-main/src/main/java/com/facebook/presto/sql/compiler/TupleDescriptor.java <ide> @Override <ide> public String toString() <ide> { <del> return Joiner.on(",").join(slots); <add> return slots.toString(); <ide> } <ide> <ide> public List<NamedSlot> resolve(final QualifiedName name)
Java
apache-2.0
6e11b2d132dc793ac985c39b5ae59bbca2d37efc
0
cfg4j/cfg4j,fromanator/cfg4j
/* * Copyright 2015 Norbert Potocki ([email protected]) * * 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. */ package pl.nort.config.source; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class GitConfigurationSource implements ConfigurationSource, Closeable { private static final String LOCAL_REPOSITORY_PATH_IN_TEMP = "nort-config-git-config-repository"; private final Git clonedRepo; private final File clonedRepoPath; /** * Read configuration from the remote GIT repository residing at {@code repositoryURI}. Keeps a local * clone of the repository in the system tmp directory. * * @param repositoryURI URI to the remote git repository * @throws GitConfigurationSourceException when unable to clone repository */ public GitConfigurationSource(String repositoryURI) { this(repositoryURI, System.getProperty("java.io.tmpdir"), LOCAL_REPOSITORY_PATH_IN_TEMP); } /** * Read configuration from the remote GIT repository residing at {@code repositoryURI}. Keeps a local * clone of the repository in the {@code localRepositoryPathInTemp} directory under {@code tmpPath} path. * * @param repositoryURI URI to the remote git repository * @param tmpPath path to the tmp directory * @param localRepositoryPathInTemp name of the local directory keeping the repository clone * @throws GitConfigurationSourceException when unable to clone repository */ public GitConfigurationSource(String repositoryURI, String tmpPath, String localRepositoryPathInTemp) { try { clonedRepoPath = File.createTempFile(localRepositoryPathInTemp, "", new File(tmpPath)); // This folder can't exist or JGit will throw NPE on clone if (!clonedRepoPath.delete()) { throw new GitConfigurationSourceException("Unable to remove temp directory for local clone: " + localRepositoryPathInTemp); } } catch (IOException e) { throw new GitConfigurationSourceException("Unable to create local clone directory: " + localRepositoryPathInTemp, e); } try { clonedRepo = Git.cloneRepository() .setURI(repositoryURI) .setDirectory(clonedRepoPath) .call(); } catch (GitAPIException e) { throw new GitConfigurationSourceException("Unable to clone repository: " + repositoryURI, e); } } @Override public Properties getConfiguration() { Properties properties = new Properties(); InputStream input = null; try { input = new FileInputStream(clonedRepoPath + "/application.properties"); properties.load(input); } catch (IOException ex) { ex.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } return properties; } @Override public void refresh() { try { clonedRepo.pull().call(); } catch (GitAPIException e) { throw new IllegalStateException("Unable to pull from remote repository", e); } } @Override public void close() throws IOException { clonedRepo.close(); } }
src/main/java/pl/nort/config/source/GitConfigurationSource.java
/* * Copyright 2015 Norbert Potocki ([email protected]) * * 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. */ package pl.nort.config.source; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class GitConfigurationSource implements ConfigurationSource, Closeable { private static final String LOCAL_REPOSITORY_PATH_IN_TEMP = "nort-config-git-config-repository"; private final Git clonedRepo; private final File clonedRepoPath; /** * Read configuration from the remote GIT repository residing at {@code repositoryURI}. Keeps a local * clone of the repository in the system tmp directory. * * @param repositoryURI URI to the remote git repository * @throws GitConfigurationSourceException when unable to clone repository */ public GitConfigurationSource(String repositoryURI) { this(repositoryURI, System.getProperty("java.io.tmpdir"), LOCAL_REPOSITORY_PATH_IN_TEMP); } /** * Read configuration from the remote GIT repository residing at {@code repositoryURI}. Keeps a local * clone of the repository in the {@code localRepositoryPathInTemp} directory under {@code tmpPath} path. * * @param repositoryURI URI to the remote git repository * @param tmpPath path to the tmp directory * @param localRepositoryPathInTemp name of the local directory keeping the repository clone * @throws GitConfigurationSourceException when unable to clone repository */ public GitConfigurationSource(String repositoryURI, String tmpPath, String localRepositoryPathInTemp) { try { clonedRepoPath = File.createTempFile(localRepositoryPathInTemp, "", new File(tmpPath)); // This folder can't exist or JGit will throw NPE on clone if (!clonedRepoPath.delete()) { throw new GitConfigurationSourceException("Unable to remove temp directory for local clone: " + localRepositoryPathInTemp); } } catch (IOException e) { throw new GitConfigurationSourceException("Unable to create local clone directory: " + localRepositoryPathInTemp, e); } try { clonedRepo = Git.cloneRepository() .setURI(repositoryURI) .setDirectory(clonedRepoPath) .call(); } catch (GitAPIException e) { throw new GitConfigurationSourceException("Unable to clone repository: " + repositoryURI, e); } } @Override public Properties getConfiguration() { Properties properties = new Properties(); InputStream input = null; try { input = new FileInputStream(clonedRepoPath + "/application.properties"); properties.load(input); } catch (IOException ex) { ex.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } return properties; } @Override public void refresh() { } @Override public void close() throws IOException { clonedRepo.close(); } }
implement refresh()
src/main/java/pl/nort/config/source/GitConfigurationSource.java
implement refresh()
<ide><path>rc/main/java/pl/nort/config/source/GitConfigurationSource.java <ide> <ide> @Override <ide> public void refresh() { <del> <add> try { <add> clonedRepo.pull().call(); <add> } catch (GitAPIException e) { <add> throw new IllegalStateException("Unable to pull from remote repository", e); <add> } <ide> } <ide> <ide> @Override
Java
apache-2.0
284238532257a75f0648ed76a7fd26d80f474f50
0
edannenberg/maven-magento-plugin
/** * Copyright 2011-2012 BBe Consulting GmbH * * 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. */ package de.bbe_consulting.mavento; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.FileVisitOption; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.Locale; import java.util.Map; import javax.xml.transform.TransformerException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.codehaus.plexus.util.FileUtils; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import de.bbe_consulting.mavento.helper.FileUtil; import de.bbe_consulting.mavento.helper.MagentoSqlUtil; import de.bbe_consulting.mavento.helper.MagentoUtil; import de.bbe_consulting.mavento.helper.MagentoXmlUtil; import de.bbe_consulting.mavento.helper.MavenUtil; import de.bbe_consulting.mavento.helper.visitor.CopyFilesVisitor; import de.bbe_consulting.mavento.helper.visitor.ExtractZipVisitor; import de.bbe_consulting.mavento.type.MagentoVersion; /** * Abstract class for mojos that want to setup a Magento instance * @author Erik Dannenberg */ public abstract class AbstractMagentoSetupMojo extends AbstractMagentoSqlMojo { /** * Use a custom magento sqldump instead of generating the magento database.<br/> * Dump is expected in /sqldumps of your project root.<br/> * @parameter expression="${magento.db.dump.file}" */ protected String magentoDumpFileName; /** * GroupId of a custom magento artifact for integration tests.<br/> * @parameter expression="${magento.artifact.group.id}" default-value="com.varien" */ protected String magentoArtifactGroupId; /** * Id of a custom magento artifact for integration tests.<br/> * @parameter expression="${magento.artifact.id}" default-value="magento" */ protected String magentoArtifactId; /** * Version of a custom magento artifact for integration tests.<br/> * @parameter expression="${magento.artifact.version}" */ protected String magentoArtifactVersion; /** * Run full setup or just update db/baseurl.<br/> * @parameter expression="${magento.artifact.is.custom}" default-value="false" */ protected Boolean magentoArtifactIsCustom; /** * Use https for backend access? true|false<br/> * @parameter expression="${magento.use.https.backend}" default-value="true" */ protected Boolean magentoUseHttpsBackend; /** * Use https for frontend access? true|false<br/> * @parameter expression="${magento.use.https.frontend}" default-value="true" */ protected Boolean magentoUseHttpsFrontend; /** * Backend admin username. * @parameter expression="${magento.admin.username}" default-value="admin" */ protected String magentoAdminUsername; /** * Backend admin password. * @parameter expression="${magento.admin.passwd}" * @required */ protected String magentoAdminPasswd; /** * Want official sample data? true|false<br/> * @parameter expression="${magento.use.sample.data}" default-value="false" */ protected Boolean magentoUseSampleData; /** * Enable exception exposing? (only Magento >=1.4.0.0) true|false<br/> * @parameter expression="${magento.expose.exceptions}" default-value="true" */ protected Boolean magentoExposeExceptions; /** * Restrict access to specified ip(s), empty for public access. * @parameter expression="${magento.dev.restrict.ip}" default-value="" */ protected String magentoDevRestrictIp; /** * Enable the Magento profiler? true|false<br/> * @parameter expression="${magento.dev.profiler}" default-value="false" */ protected Boolean magentoDevProfiler; /** * Enable logging? true|false<br/> * @parameter expression="${magento.dev.log.active}" default-value="true" */ protected Boolean magentoDevLogActive; /** * Logfile name, saved to var/log or /tmp if the former is not accessible.<br/> * @parameter expression="${magento.dev.log.file}" default-value="system.log" */ protected String magentoDevLogFile; /** * Logfile name for exceptions, saved to var/log or /tmp if the former is not accessible.<br/> * @parameter expression="${magento.dev.log.file.exception}" default-value="exception.log" */ protected String magentoDevLogFileException; /** * Allow symlinked templates? (only Magento >=1.5.1.0) true|false<br/> * @parameter expression="${magento.dev.allow.symlinks}" default-value="true" */ protected Boolean magentoDevAllowSymlinks; /** * Setup pear after installation? true|false<br/> * @parameter expression="${magento.pear.enabled}" default-value="true" */ protected Boolean magentoPearEnabled; /** * Upgrade pear after installation? true|false<br/> * Will autorun for Magento 1.4.2.0<br/> * @parameter expression="${magento.pear.upgrade}" default-value="false" */ protected Boolean magentoPearUpgrade; /** * Set prefered extension stability. alpha|beta|stable<br/> * @parameter expression="${magento.extensions.prefered.stability}" default-value="beta" */ protected String magentoExtensionsPreferedStability; /** * List of core extension keys you want installed after setup.<br/> * <pre>Interface_Frontend_Default_Blank,etc</pre> * You can append the version string.<br/> * <pre>Interface_Frontend_Default_Blank-1.4.0.1</pre> * @parameter expression="${magento.extensions.core}" default-value="" */ protected String magentoExtensionsCore; /** * List of community extension keys you want installed after setup.<br/> * <pre>Locale_Mage_community_de_DE,market_ready_germany</pre> * You can append the version string.<br/> * <pre>Locale_Mage_community_de_DE-1.4.0.1</pre> * @parameter expression="${magento.extensions.community}" default-value="" */ protected String magentoExtensionsCommunity; /** * Other artifacts you want deployed on installation, list of .zip files.<br/> * Put the artifacts into /extensions of your project root.<br/> * If you have a bunch of them you can use * instead of typing them all out. * @parameter expression="${magento.extensions.other}" default-value="" */ protected String magentoExtensionsOther; /** * Reindex Magento database after setup? true|false<br/> * @parameter expression="${magento.db.reindex}" default-value="false" */ protected Boolean magentoDbReindex; /** * Default locale key.<br/> * @parameter expression="${magento.locale}" default-value="en_US" */ protected String magentoLocale; /** * Default Magento theme.<br/> * @parameter expression="${magento.theme}" default-value="default" */ protected String magentoTheme; /** * Admin user email address.<br/> * @parameter expression="${magento.admin.email}" default-value="[email protected]" */ protected String magentoAdminEmail; /** * Admin user first name.<br/> * @parameter expression="${magento.admin.name.first}" default-value="Heinzi" */ protected String magentoAdminNameFirst; /** * Admin user last name.<br/> * @parameter expression="${magento.admin.name.last}" default-value="Floppel" */ protected String magentoAdminNameLast; /** * Default time zone.<br/> * @parameter expression="${magento.timezone}" default-value="Europe/Berlin" */ protected String magentoTimezone; /** * Default currency.<br/> * @parameter expression="${magento.currency}" default-value="EUR" */ protected String magentoCurrency; /** * Frontend name for backend accesss.<br/> * @parameter expression="${magento.backend.frontend.name}" default-value="admin" */ protected String magentoBackendFrontendName; /** * Enable SEO rewriting? true|false<br/> * @parameter expression="${magento.seo.use.rewrites}" default-value="true" */ protected Boolean magentoSeoUseRewrites; /** * Enable API cache? true|false<br/> * @parameter expression="${magento.cache.api}" default-value="false" */ protected Boolean magentoCacheApi; /** * Enable block cache? true|false<br/> * @parameter expression="${magento.cache.block}" default-value="false" */ protected Boolean magentoCacheBlock; /** * Enable config cache? true|false<br/> * @parameter expression="${magento.cache.config}" default-value="false" */ protected Boolean magentoCacheConfig; /** * Enable collection cache? true|false<br/> * @parameter expression="${magento.cache.collections}" default-value="false" */ protected Boolean magentoCacheCollections; /** * Enable EAV cache? true|false<br/> * @parameter expression="${magento.cache.eav}" default-value="false" */ protected Boolean magentoCacheEav; /** * Enable layout cache? true|false<br/> * @parameter expression="${magento.cache.layout}" default-value="false" */ protected Boolean magentoCacheLayout; /** * Enable translate cache? true|false<br/> * @parameter expression="${magento.cache.translate}" default-value="false" */ protected Boolean magentoCacheTranslate; /** * Reverse proxy header1 (local.xml)<br/> * @parameter expression="${magento.remote.addr.header1}" default-value="HTTP_X_REAL_IP" */ protected String magentoRemoteAddrHeader1; /** * Reverse proxy header2 (local.xml)<br/> * @parameter expression="${magento.remote.addr.header2}" default-value="HTTP_X_FORWARDED_FOR" */ protected String magentoRemoteAddrHeader2; /** * Where to save sessions? files|db<br/> * @parameter expression="${magento.session.save}" default-value="files" */ protected String magentoSessionSave; /** * Sessiondata location? files|db|memcache<br/> * @parameter expression="${magento.sessiondata.location}" default-value="files" */ protected String magentoSessiondataLocation; /** * @parameter expression="${magento.sessiondata.savepath}" default-value="" */ protected String magentoSessiondataSavepath; /** * @parameter expression="${magento.session.cache.limiter}" default-value="" */ protected String magentoSessionCacheLimiter; /** * file|apc|memcached<br/> * @parameter expression="${magento.session.cache.backend}" default-value="files" */ protected String magentoSessionCacheBackend; /** * file|apc|memcached<br/> * @parameter expression="${magento.session.cache.slow.backend}" default-value="files" */ protected String magentoSessionCacheSlowBackend; /** * @parameter expression="${magento.session.cache.slow.backend.store.data}" default-value="false" */ protected Boolean magentoSessionCacheSlowBackendStoreData; /** * @parameter expression="${magento.session.cache.auto.refresh.fast.cache}" default-value="false" */ protected Boolean magentoSessionCacheAutoRefreshFastCache; /** * Memcached url.<br/> * @parameter expression="${magento.session.cache.memcached.host}" default-value="" */ protected String magentoSessionCacheMemcachedHost; /** * Memcached port.<br/> * @parameter expression="${magento.session.cache.memcached.port}" default-value="" */ protected String magentoSessionCacheMemcachedPort; /** * @parameter expression="${magento.session.cache.memcached.weight}" default-value="" */ protected String magentoSessionCacheMemcachedWeight; /** * @parameter expression="${magento.session.cache.memcached.timeout}" default-value="" */ protected String magentoSessionCacheMemcachedTimeout; /** * @parameter expression="${magento.session.cache.memcached.interval}" default-value="" */ protected String magentoSessionCacheMemcachedInterval; /** * @parameter expression="${magento.session.cache.memcached.status}" default-value="" */ protected String magentoSessionCacheMemcachedStatus; /** * @parameter expression="${magento.session.cache.memcached.persistent}" default-value="" */ protected String magentoSessionCacheMemcachedPersistent; /** * @parameter expression="${magento.session.cache.memcached.compression}" default-value="false" */ protected Boolean magentoSessionCacheMemcachedCompression; /** * @parameter expression="${magento.session.cache.memcached.cachedir}" default-value="" */ protected String magentoSessionCacheMemcachedCachedir; /** * @parameter expression="${magento.session.cache.memcached.hashed.dir.umask}" default-value="" */ protected String magentoSessionCacheMemcachedHashedDirUmask; /** * @parameter expression="${magento.session.cache.memcached.file.prefix}" default-value="" */ protected String magentoSessionCacheMemcachedFilePrefix; /** * Encryption key to use. If omitted a fresh one will be generated.<br/> * @parameter expression="${magento.encryptionkey}" */ protected String magentoEncryptionkey; /** * Omit for current date, format: Tue, 13 Apr 2010 21:40:52 +0000<br/> * @parameter expression="${magento.install.date}" */ protected String magentoInstallDate; /** * Omit for current date, format: 2010-04-13 21:40:52<br/> * @parameter expression="${magento.install.date.sql}" */ protected String magentoInstallDateSql; /** * Database table prefix, not implemented yet.<br/> * @parameter expression="${magento.db.table.prefix}" default-value="" */ protected String magentoDbTablePrefix; /** * @parameter expression="${magento.session.cache.memcached.hashed.dir.level}" default-value="" */ protected String magentoSessionCacheMemcachedHashedDirLevel; /** * Magento base url.<br/> * @parameter expression="${magento.url.base}" * @required */ protected String magentoUrlBase; /** * Magento secure base url.<br/> * @parameter expression="${magento.url.base.https}" */ protected String magentoUrlBaseHttps; protected MagentoVersion mVersion; protected String magentoAdminPasswdHashed = ""; protected String tempDir; protected String targetDir; protected Boolean isIntegrationTest = false; // kinda obsolete, may return if we want to support token mapping in sql dumps again protected void createFinalSqlDump() throws MojoExecutionException { // get params for regex replace in the sql dump Map<String, String> sqlTags = getSqlTagMap(); File sqlDumpFiltered = new File( tempDir+"/sql", "magento.sql.f" ); String sqlDumpFileName = "magento.sql"; if (magentoUseSampleData) { sqlDumpFileName = "magento_with_sample_data.sql"; } String sqlDumpOrg = null; try { sqlDumpOrg = FileUtils.fileRead(new File(tempDir+"/sql/"+sqlDumpFileName)); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(),e); } FileWriter w = null; try { w = new FileWriter( sqlDumpFiltered ); w.write( MagentoUtil.replaceTags(sqlDumpOrg, sqlTags) ); } catch (IOException e) { throw new MojoExecutionException( "Error creating file " + sqlDumpFiltered, e ); } finally { if ( w != null ) { try { w.close(); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } } } } protected void createLocalXml() throws MojoExecutionException { if (magentoEncryptionkey == null || magentoEncryptionkey.isEmpty()) { try { getLog().info("Generating fresh encryption key.."); magentoEncryptionkey = MagentoUtil.getMd5Hash(new Date().toString()); getLog().info("-> "+magentoEncryptionkey); } catch (UnsupportedEncodingException e) { throw new MojoExecutionException(e.getMessage(),e); } catch (NoSuchAlgorithmException e) { throw new MojoExecutionException(e.getMessage(),e); } } if (magentoInstallDate == null || magentoInstallDate.isEmpty()) { SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", new Locale("en", "EN")); magentoInstallDate = format.format(new Date()); } Path localXmlPath = Paths.get(tempDir+"/app/etc/local.xml"); if (Files.notExists(localXmlPath)) { Path localXmlPathTemp = Paths.get(tempDir+"/app/etc/local.xml.template"); if (Files.notExists(localXmlPathTemp)) { throw new MojoExecutionException("Could read neither local.xml or local.xml.template!"); } try { Files.move(localXmlPathTemp, localXmlPath); } catch (IOException e) { throw new MojoExecutionException("Error renaming local.xml.template! "+e.getMessage(), e); } } // get params for regex replace in local.xml Map<String, String> localTags = getLocalXmlTagMap(); Document localXml = MagentoXmlUtil.readXmlFile(tempDir+"/app/etc/local.xml"); Document localXmlAdditional = MagentoXmlUtil.readXmlFile(tempDir+"/app/etc/local.xml.additional"); if (magentoSessiondataSavepath != null && !magentoSessiondataSavepath.isEmpty()) { // find cache nodes in local.xml.additional NodeList cacheNodes = localXmlAdditional.getElementsByTagName("session_save_path"); // import them to a new node Node n = localXml.importNode(cacheNodes.item(0), true); // find global node of local.xml NodeList globalNodes = localXml.getElementsByTagName("global"); // append imported nodes to local.xml Node g = globalNodes.item(0); g.appendChild(n); } if (magentoSessionCacheLimiter != null && !magentoSessionCacheLimiter.isEmpty()) { // find cache nodes in local.xml.additional NodeList cacheNodes = localXmlAdditional.getElementsByTagName("session_cache_limiter"); // import them to a new node Node n = localXml.importNode(cacheNodes.item(0), true); // find global node of local.xml NodeList globalNodes = localXml.getElementsByTagName("global"); // append imported nodes to local.xml Node g = globalNodes.item(0); g.appendChild(n); } if (magentoSessionCacheBackend.equals("memcached") || magentoSessionCacheBackend.equals("apc") || magentoSessionCacheBackend.equals("xcache")) { // find cache nodes in local.xml.additional NodeList cacheNodes = localXmlAdditional.getElementsByTagName("cache"); // import them to a new node Node n = localXml.importNode(cacheNodes.item(0), true); // find global node of local.xml NodeList globalNodes = localXml.getElementsByTagName("global"); // append imported nodes to local.xml Node g = globalNodes.item(0); g.appendChild(n); } if (mVersion.getMajorVersion() <= 1 && mVersion.getMinorVersion() < 6) { if (magentoRemoteAddrHeader1 != null && !magentoRemoteAddrHeader1.isEmpty()) { // find cache nodes in local.xml.additional NodeList cacheNodes = localXmlAdditional.getElementsByTagName("remote_addr_headers"); // import them to a new node Node n = localXml.importNode(cacheNodes.item(0), true); // find global node of local.xml NodeList globalNodes = localXml.getElementsByTagName("global"); // append imported nodes to local.xml Node g = globalNodes.item(0); g.appendChild(n); } } MagentoXmlUtil.updateXmlValues(localTags, localXml); String finalLocalXml = null; try { finalLocalXml = MagentoUtil.replaceTags(MagentoXmlUtil.transformXmlToString(localXml), localTags); } catch (TransformerException e) { throw new MojoExecutionException("Error while creating local.xml", e); } MagentoXmlUtil.writeXmlFile(finalLocalXml, tempDir+"/app/etc/local.xml"); } protected void updateLocalXml() throws MojoExecutionException { String localXmlPath = tempDir+"/app/etc/local.xml"; Document localXml = MagentoXmlUtil.readXmlFile(localXmlPath); MagentoXmlUtil.updateDbValues(magentoDbHost, magentoDbUser, magentoDbPasswd, magentoDbName, localXml); try { MagentoXmlUtil.writeXmlFile(MagentoXmlUtil.transformXmlToString(localXml), localXmlPath); } catch (TransformerException e) { throw new MojoExecutionException(e.getMessage(), e); } } protected NodeList findXmlNode(Object obj, String xpathExpression) throws XPathExpressionException { XPath xPath = XPathFactory.newInstance().newXPath(); XPathExpression expression; expression = xPath.compile( xpathExpression ); return (NodeList) expression.evaluate( obj, XPathConstants.NODESET ); } protected void createOldCacheConfig() throws MojoExecutionException { // get params for regex replace in local.xml Map<String, String> cacheTags = getOldCacheTagMap(); String cacheConfigTemplate = "a:7:{s:6:\"config\";i:@CACHE_CONFIG@;s:6:\"layout\";i:@CACHE_LAYOUT@;s:10:\"block_html\";i:@CACHE_BLOCK@;s:9:\"translate\";i:@CACHE_TRANSLATE@;s:11:\"collections\";i:@CACHE_COLLECTIONS@;s:3:\"eav\";i:@CACHE_EAV@;s:10:\"config_api\";i:@CACHE_API@;}"; String finalCacheConfig = null; finalCacheConfig = MagentoUtil.replaceTags(cacheConfigTemplate, cacheTags); File cacheConfigFiltered = new File(tempDir+"/app/etc/use_cache.ser"); FileWriter cacheWriter = null; try { cacheWriter = new FileWriter( cacheConfigFiltered ); cacheWriter.write( finalCacheConfig ); } catch ( IOException e ) { throw new MojoExecutionException("Error writing use_cache.ser", e); } finally { if ( cacheWriter != null ) { try { cacheWriter.close(); } catch ( IOException e ) { throw new MojoExecutionException(e.getMessage(), e); } } } } // setup standard magento protected void setupMagento() throws MojoFailureException, MojoExecutionException { try { mVersion = new MagentoVersion(magentoVersion); } catch (Exception e) { throw new MojoExecutionException(e.getMessage(), e); } if (!magentoArtifactGroupId.equals("com.varien")) { magentoArtifactIsCustom = true; } magentoUrlBase = MagentoUtil.validateBaseUrl(magentoUrlBase, false); if (magentoUrlBaseHttps != null && !magentoUrlBaseHttps.isEmpty()) { magentoUrlBaseHttps = MagentoUtil.validateBaseUrl(magentoUrlBaseHttps, true); } else { magentoUrlBaseHttps = magentoUrlBase; } // extract magento artifact if (!isIntegrationTest) { try { getLog().info("Resolving dependencies.."); MavenUtil.extractCompileDependencies(tempDir, project, getLog()); getLog().info("..done."); } catch (IOException e) { throw new MojoExecutionException("Error extracting artifact: " + e.getMessage(), e); } } // drop db if existing MagentoSqlUtil.dropMagentoDb(magentoDbUser, magentoDbPasswd, magentoDbHost, magentoDbPort, magentoDbName, getLog()); // create db MagentoSqlUtil.createMagentoDb(magentoDbUser, magentoDbPasswd, magentoDbHost, magentoDbPort, magentoDbName, getLog()); String dumpFileName = tempDir+"/mavento_setup/sql/magento.sql"; if (magentoDumpFileName != null && !magentoDumpFileName.isEmpty()) { // use premade dump dumpFileName = project.getBasedir()+"/sqldumps/"+magentoDumpFileName; if (!new File(dumpFileName).exists()) { throw new MojoExecutionException("Could not find custom sql dump file. Make sure to place it in /sqldumps of your project root."); } getLog().info("Using custom dump: "+dumpFileName); } else if (magentoUseSampleData && !magentoArtifactIsCustom) { dumpFileName = tempDir+"/mavento_setup/sql/magento_with_sample_data.sql"; } // inject dump into database MagentoSqlUtil.importSqlDump(dumpFileName, magentoDbUser, magentoDbPasswd, magentoDbHost, magentoDbPort, magentoDbName, getLog()); String jdbcUrl = MagentoSqlUtil.getJdbcUrl(magentoDbHost, magentoDbPort, magentoDbName); Map<String, String> config = null; getLog().info("Generating admin pw hash.."); try { magentoAdminPasswdHashed = MagentoUtil.getSaltedMd5Hash(magentoAdminPasswd); } catch (UnsupportedEncodingException e) { throw new MojoExecutionException( "Error while creating admin password hash." + e.getMessage(), e); } catch (NoSuchAlgorithmException e) { throw new MojoExecutionException( "Error while creating admin password hash." + e.getMessage(), e); } getLog().info("-> "+magentoAdminPasswdHashed); // fix https url if not configured if (magentoUrlBaseHttps == null || magentoUrlBaseHttps.isEmpty()) { magentoUrlBaseHttps = magentoUrlBase; } // generate new install date if not configured if (magentoInstallDateSql == null || magentoInstallDateSql.isEmpty()) { SimpleDateFormat fo = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); magentoInstallDateSql = fo.format(new Date()); } // check if ip restrictions are not null if (magentoDevRestrictIp == null) { magentoDevRestrictIp = ""; } if (magentoArtifactIsCustom || (magentoDumpFileName != null && !magentoDumpFileName.isEmpty())) { config = getSqlAdminTagMap(); MagentoSqlUtil.updateAdminUser(config, magentoDbUser, magentoDbPasswd, jdbcUrl, getLog()); // only update baseurl and dev settings for custom magento artifacts getLog().info("Setting baseUrl to: "+magentoUrlBase); config = getSqlTagMapBasic(); } else { // update everything getLog().info("Updating database.."); config = getSqlAdminTagMap(); MagentoSqlUtil.updateAdminUser(config, magentoDbUser, magentoDbPasswd, jdbcUrl, getLog()); if (mVersion.getMajorVersion() == 1 && mVersion.getMinorVersion() > 3 ) { config = getSqlCacheTagMap(); MagentoSqlUtil.updateCacheConfig(config, magentoDbUser, magentoDbPasswd, jdbcUrl, getLog()); } config = getSqlTagMap(); } MagentoSqlUtil.setCoreConfigData(config, magentoDbUser, magentoDbPasswd, jdbcUrl, getLog()); getLog().info("..done."); // update db settings in local.xml for custom artifacts, else do a full setup if (magentoArtifactIsCustom) { getLog().info("Updating db settings in local.xml.."); updateLocalXml(); getLog().info("..done."); } else { // prepare local.xml createLocalXml(); updateLocalXml(); // create cache config file for magento <1.4.x if (mVersion.getMajorVersion() == 1 && mVersion.getMinorVersion() < 4) { getLog().info("Generating pre 1.4 Magento cache file.."); createOldCacheConfig(); getLog().info("..done."); } // handle exception exposing if (magentoExposeExceptions && (mVersion.getMajorVersion() == 1 && mVersion.getMinorVersion() > 3)) { getLog().info("Enabling exception printing.."); try { Files.move(Paths.get(tempDir+"/errors/local.xml.sample"), Paths.get(tempDir+"/errors/local.xml")); } catch (IOException e) { throw new MojoExecutionException("Error while enabling exception printing! " + e.getMessage(), e); } getLog().info("..done."); } // copy sample data product images if (magentoUseSampleData && !magentoArtifactIsCustom) { Path magentoSourcePath = Paths.get(tempDir+"/mavento_setup/sample_data"); Path magentoTargetPath = Paths.get(tempDir); try { getLog().info("Copying sample data.."); CopyFilesVisitor cv = new CopyFilesVisitor(magentoSourcePath, magentoTargetPath, false); Files.walkFileTree(magentoSourcePath, cv); getLog().info("..done."); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } } } // extract local extensions if ( magentoExtensionsOther != null && !magentoExtensionsOther.isEmpty() ) { if ( magentoExtensionsOther.equals("*") ) { Path eDir = Paths.get("extensions"); Path tDir = Paths.get(tempDir); try { Files.createDirectories(eDir); ExtractZipVisitor ev = new ExtractZipVisitor(tDir, getLog()); EnumSet<FileVisitOption> options = EnumSet.of(FileVisitOption.FOLLOW_LINKS); Files.walkFileTree(eDir, options, 1, ev); } catch (IOException e) { throw new MojoExecutionException("Error: "+e.getMessage(), e); } } else { String[] k = magentoExtensionsOther.split(","); for (String extensionKey : k) { String fPath = "extensions/"+extensionKey; Path sourceFile = Paths.get(fPath); if ( !Files.exists(sourceFile) ) { if (extensionKey.endsWith(".zip")) { sourceFile = Paths.get(fPath+".zip"); if ( !Files.exists(sourceFile) ) { throw new MojoExecutionException("Could not find "+extensionKey+" in extensions/"); } } else { throw new MojoExecutionException("Could not find "+extensionKey+" in extensions/"); } } else { try { getLog().info("Extracting "+sourceFile.getFileName()); FileUtil.unzipFile(sourceFile.toAbsolutePath().toString(), tempDir); } catch (IOException e) { throw new MojoExecutionException("Error: "+e.getMessage(), e); } } } } getLog().info("..done."); } try { FileUtil.deleteFile(tempDir+"/var/cache", getLog()); FileUtil.deleteFile(tempDir+"/mavento_setup", getLog()); FileUtil.deleteFile(tempDir+"/META-INF", getLog()); } catch (IOException e) { throw new MojoExecutionException("Error deleting directories. "+e.getMessage(), e); } if (!isIntegrationTest) { // copy prepared magento to final destination unless this an integration test Path magentoSourcePath = Paths.get(tempDir); Path magentoTargetPath = Paths.get(magentoRootLocal); getLog().info("Everything is prepared, copying to "+magentoRootLocal); try { FileUtil.deleteFile(magentoRootLocal, getLog()); Files.createDirectories(magentoTargetPath); CopyFilesVisitor cv = new CopyFilesVisitor(magentoSourcePath, magentoTargetPath, false); Files.walkFileTree(magentoSourcePath, cv); } catch (IOException e) { throw new MojoExecutionException("Error while copying to: "+magentoTargetPath.toAbsolutePath() + " " + e.getMessage(), e); } getLog().info("..done."); } setupPear(); // add any core_config_data properties after extension install, as the extension might overwrite them else getLog().info("Updating core_config_data.."); config = MavenUtil.addMagentoMiscProperties(project, new HashMap<String,String>(), getLog()); MagentoSqlUtil.setCoreConfigData(config, magentoDbUser, magentoDbPasswd, jdbcUrl, getLog()); getLog().info("..done."); // finally reindex the magento db indexDb(); } private void setupPear() throws MojoExecutionException { // handle pear setup and possible additional extensions if (magentoPearEnabled) { File magentoTargetPath = new File(targetDir); File pearExecutable = null; if (mVersion.getMajorVersion() >= 1 && mVersion.getMinorVersion() >= 5) { pearExecutable = new File(magentoTargetPath.getAbsolutePath()+"/mage"); } else { pearExecutable = new File(magentoTargetPath.getAbsolutePath()+"/pear"); } pearExecutable.setExecutable(true, true); getLog().info("Initializing pear.."); MagentoUtil.executePearCommand(pearExecutable.getAbsolutePath(), new String[] {"mage-setup"}, magentoTargetPath.getAbsolutePath(), mVersion, getLog()); getLog().info("..done."); if (magentoPearUpgrade || (mVersion.getMajorVersion() == 1 && mVersion.getMinorVersion() == 4 && mVersion.getRevisionVersion() == 2)) { getLog().info("Updating pear channel.."); MagentoUtil.executePearCommand(pearExecutable.getAbsolutePath(), new String[] {"channel-update", "pear.php.net"}, magentoTargetPath.getAbsolutePath(), mVersion, getLog()); if (mVersion.getMajorVersion() <= 1 && mVersion.getMinorVersion() < 6) { getLog().info("Upgrading pear.."); MagentoUtil.executePearCommand(pearExecutable.getAbsolutePath(), new String[] {"upgrade", "--force", "PEAR"}, magentoTargetPath.getAbsolutePath(), mVersion, getLog()); } getLog().info("..done."); } // set extension prefered stability if (magentoExtensionsPreferedStability != null && !magentoExtensionsPreferedStability.isEmpty()) { getLog().info("Setting preferred extension stability to "+magentoExtensionsPreferedStability+".."); MagentoUtil.executePearCommand(pearExecutable.getAbsolutePath(), new String[] {"config-set", "preferred_state", magentoExtensionsPreferedStability}, magentoTargetPath.getAbsolutePath(), mVersion, getLog()); getLog().info("..done."); } // install core extensions String[] extensionKeys = null; if (magentoExtensionsCore != null) { extensionKeys = magentoExtensionsCore.split(","); installPearModules("core", extensionKeys, pearExecutable); } // install community extensions if (magentoExtensionsCommunity != null) { extensionKeys = magentoExtensionsCommunity.split(","); installPearModules("community", extensionKeys, pearExecutable); } } } protected void installPearModules(String channel, String[] extensionKeys, File pearExecutable) throws MojoExecutionException { for (String extensionKey : extensionKeys) { if (!extensionKey.isEmpty()) { String[] params = null; if (mVersion.getMajorVersion() == 1 && mVersion.getMinorVersion() <= 4) { String realChannel = "magento-core/"; if (channel.equals("community")) { realChannel = "magento-community/"; } params = new String[] {"install", realChannel+extensionKey}; } else { String realChannel = "http://connect20.magentocommerce.com/core"; if (channel.equals("community")) { realChannel = "http://connect20.magentocommerce.com/community"; } if (extensionKey.contains("-")) { String[] s = extensionKey.split("-"); String extensionVersion = ""; if (s.length == 2) { extensionKey = s[0]; extensionVersion = s[1]; } getLog().info("Installing magento-"+channel+"/"+extensionKey+"-"+extensionVersion+".."); params = new String[] {"install", realChannel, extensionKey, extensionVersion}; } else { getLog().info("Installing magento-"+channel+"/"+extensionKey+".."); params = new String[] {"install", realChannel, extensionKey}; } } MagentoUtil.executePearCommand(pearExecutable.getAbsolutePath(), params, targetDir, mVersion, getLog()); getLog().info("..done."); } } } private void indexDb() throws MojoExecutionException { // reindex db if (magentoDbReindex && (mVersion.getMajorVersion() >= 1 && mVersion.getMinorVersion() >= 4)) { if (magentoDeployType.equals("local")) { MagentoSqlUtil.indexDb(targetDir, getLog()); } else { throw new MojoExecutionException("Oops, remote indexing not implemented yet. Skipping.."); } } } private Map<String, String> getSqlTagMap() { Map<String, String> tokenMap = getSqlTagMapBasic(); tokenMap.put("general/locale/timezone", magentoTimezone); tokenMap.put("currency/options/base", magentoCurrency); tokenMap.put("currency/options/default", magentoCurrency); tokenMap.put("currency/options/allow", magentoCurrency); tokenMap.put("general/locale/code", magentoLocale); tokenMap.put("design/theme/default", magentoTheme); tokenMap.put("web/seo/use_rewrites", magentoSeoUseRewrites ? "1" : "0"); return tokenMap; } private Map<String, String> getSqlTagMapBasic() { Map<String, String> tokenMap = new HashMap<String, String>(); tokenMap.put("web/unsecure/base_url", magentoUrlBase); tokenMap.put("web/secure/base_url", magentoUrlBaseHttps); tokenMap.put("web/secure/use_in_adminhtml", magentoUseHttpsBackend ? "1" : "0"); tokenMap.put("web/secure/use_in_frontend", magentoUseHttpsFrontend ? "1" : "0"); tokenMap.put("web/unsecure/base_skin_url", "{{unsecure_base_url}}skin/"); tokenMap.put("web/unsecure/base_media_url", "{{unsecure_base_url}}media/"); tokenMap.put("web/unsecure/base_link_url", "{{unsecure_base_url}}"); tokenMap.put("web/unsecure/base_js_url", "{{unsecure_base_url}}js/"); tokenMap.put("web/secure/base_skin_url", "{{secure_base_url}}skin/"); tokenMap.put("web/secure/base_media_url", "{{secure_base_url}}media/"); tokenMap.put("web/secure/base_link_url", "{{secure_base_url}}"); tokenMap.put("web/secure/base_js_url", "{{secure_base_url}}js/"); // dev stuff tokenMap.put("dev/restrict/allow_ips", magentoDevRestrictIp); tokenMap.put("dev/debug/profiler", magentoDevProfiler ? "1" : "0"); tokenMap.put("dev/log/active", magentoDevLogActive ? "1" : "0" ); tokenMap.put("dev/log/file", magentoDevLogFile); tokenMap.put("dev/log/exception_file", magentoDevLogFileException); tokenMap.put("dev/template/allow_symlink", magentoDevAllowSymlinks ? "1" : "0"); return tokenMap; } private Map<String, String> getSqlAdminTagMap() { Map<String, String> tokenMap = new HashMap<String, String>(); tokenMap.put("ADMIN_USERNAME", magentoAdminUsername); tokenMap.put("ADMIN_PASSWD", magentoAdminPasswdHashed); tokenMap.put("ADMIN_NAME_FIRST", magentoAdminNameFirst); tokenMap.put("ADMIN_NAME_LAST", magentoAdminNameLast); tokenMap.put("ADMIN_EMAIL", magentoAdminEmail); tokenMap.put("INSTALL_DATESQL", magentoInstallDateSql); return tokenMap; } private Map<String, String> getSqlCacheTagMap() { Map<String, String> tokenMap = new HashMap<String, String>(); // only magento >=1.4.x.x tokenMap.put("config", magentoCacheConfig ? "1" : "0"); tokenMap.put("layout", magentoCacheLayout ? "1" : "0"); tokenMap.put("block_html", magentoCacheBlock ? "1" : "0"); tokenMap.put("translate", magentoCacheTranslate ? "1" : "0"); tokenMap.put("collections", magentoCacheCollections ? "1" : "0"); tokenMap.put("eav", magentoCacheEav ? "1" : "0"); tokenMap.put("config_api", magentoCacheApi ? "1" : "0"); return tokenMap; } private Map<String, String> getOldCacheTagMap() { Map<String, String> tokenMap = new HashMap<String, String>(); // only magento <1.4.x tokenMap.put("CACHE_CONFIG", magentoCacheConfig ? "1" : "0"); tokenMap.put("CACHE_LAYOUT", magentoCacheLayout ? "1" : "0"); tokenMap.put("CACHE_BLOCK", magentoCacheBlock ? "1" : "0"); tokenMap.put("CACHE_TRANSLATE", magentoCacheTranslate ? "1" : "0"); tokenMap.put("CACHE_COLLECTIONS", magentoCacheCollections ? "1" : "0"); tokenMap.put("CACHE_EAV", magentoCacheEav ? "1" : "0"); tokenMap.put("CACHE_API", magentoCacheApi ? "1" : "0"); return tokenMap; } private Map<String, String> getLocalXmlTagMap() { Map<String, String> tokenMap = new HashMap<String, String>(); tokenMap.put("host", magentoDbHost); tokenMap.put("dbname", magentoDbName); tokenMap.put("username", magentoDbUser); tokenMap.put("password", magentoDbPasswd); if (magentoDbTablePrefix == null) { magentoDbTablePrefix=""; } tokenMap.put("table_prefix", magentoDbTablePrefix); tokenMap.put("session_save", magentoSessionSave); tokenMap.put("key", magentoEncryptionkey); tokenMap.put("frontName", magentoBackendFrontendName); tokenMap.put("date", magentoInstallDate); // local.xml.additional // TODO: handle local.xml.additional stuff via xml in createLocalXml() // tokenMap.put("session_save", magentoSessionSave); // tokenMap.put("session_save", magentoSessiondataLocation); // tokenMap.put("session_save_path", magentoSessiondataSavepath); // tokenMap.put("session_cache_limiter", magentoSessionCacheLimiter); // tokenMap.put("backend", magentoSessionCacheBackend); // tokenMap.put("slow_backend", magentoSessionCacheSlowBackend); // tokenMap.put("auto_refresh_fast_cache", magentoSessionCacheAutoRefreshFastCache ? "1" : "0"); // tokenMap.put("slow_backend_store_data", magentoSessionCacheSlowBackendStoreData ? "1" : "0"); // tokenMap.put("host", magentoSessionCacheMemcachedHost); // tokenMap.put("port", magentoSessionCacheMemcachedPort); // tokenMap.put("persistent", magentoSessionCacheMemcachedPersistent); // tokenMap.put("compression", magentoSessionCacheMemcachedCompression ? "1" : "0"); // tokenMap.put("cache_dir", magentoSessionCacheMemcachedCachedir); // tokenMap.put("hashed_directory_level", magentoSessionCacheMemcachedHashedDirLevel); // tokenMap.put("hashed_directory_umask", magentoSessionCacheMemcachedHashedDirUmask); // tokenMap.put("file_name_prefix", magentoSessionCacheMemcachedFilePrefix); // tokenMap.put("weight", magentoSessionCacheMemcachedWeight); // tokenMap.put("retry_interval", magentoSessionCacheMemcachedInterval); // tokenMap.put("status", magentoSessionCacheMemcachedStatus); // tokenMap.put("timeout", magentoSessionCacheMemcachedTimeout); // tokenMap.put("header1", magentoRemoteAddrHeader1); // tokenMap.put("header2", magentoRemoteAddrHeader2); return tokenMap; } }
src/main/java/de/bbe_consulting/mavento/AbstractMagentoSetupMojo.java
/** * Copyright 2011-2012 BBe Consulting GmbH * * 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. */ package de.bbe_consulting.mavento; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.FileVisitOption; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.Locale; import java.util.Map; import javax.xml.transform.TransformerException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.codehaus.plexus.util.FileUtils; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import de.bbe_consulting.mavento.helper.FileUtil; import de.bbe_consulting.mavento.helper.MagentoSqlUtil; import de.bbe_consulting.mavento.helper.MagentoUtil; import de.bbe_consulting.mavento.helper.MagentoXmlUtil; import de.bbe_consulting.mavento.helper.MavenUtil; import de.bbe_consulting.mavento.helper.visitor.CopyFilesVisitor; import de.bbe_consulting.mavento.helper.visitor.ExtractZipVisitor; import de.bbe_consulting.mavento.type.MagentoVersion; /** * Abstract class for mojos that want to setup a Magento instance * @author Erik Dannenberg */ public abstract class AbstractMagentoSetupMojo extends AbstractMagentoSqlMojo { /** * Use a custom magento sqldump instead of generating the magento database.<br/> * Dump is expected in /sqldumps of your project root.<br/> * @parameter expression="${magento.db.dump.file}" */ protected String magentoDumpFileName; /** * GroupId of a custom magento artifact for integration tests.<br/> * @parameter expression="${magento.artifact.group.id}" default-value="com.varien" */ protected String magentoArtifactGroupId; /** * Id of a custom magento artifact for integration tests.<br/> * @parameter expression="${magento.artifact.id}" default-value="magento" */ protected String magentoArtifactId; /** * Version of a custom magento artifact for integration tests.<br/> * @parameter expression="${magento.artifact.version}" */ protected String magentoArtifactVersion; /** * Run full setup or just update db/baseurl.<br/> * @parameter expression="${magento.artifact.is.custom}" default-value="false" */ protected Boolean magentoArtifactIsCustom; /** * Use https for backend access? true|false<br/> * @parameter expression="${magento.use.https.backend}" default-value="true" */ protected Boolean magentoUseHttpsBackend; /** * Use https for frontend access? true|false<br/> * @parameter expression="${magento.use.https.frontend}" default-value="true" */ protected Boolean magentoUseHttpsFrontend; /** * Backend admin username. * @parameter expression="${magento.admin.username}" default-value="admin" */ protected String magentoAdminUsername; /** * Backend admin password. * @parameter expression="${magento.admin.passwd}" * @required */ protected String magentoAdminPasswd; /** * Want official sample data? true|false<br/> * @parameter expression="${magento.use.sample.data}" default-value="false" */ protected Boolean magentoUseSampleData; /** * Enable exception exposing? (only Magento >=1.4.0.0) true|false<br/> * @parameter expression="${magento.expose.exceptions}" default-value="true" */ protected Boolean magentoExposeExceptions; /** * Restrict access to specified ip(s), empty for public access. * @parameter expression="${magento.dev.restrict.ip}" default-value="" */ protected String magentoDevRestrictIp; /** * Enable the Magento profiler? true|false<br/> * @parameter expression="${magento.dev.profiler}" default-value="false" */ protected Boolean magentoDevProfiler; /** * Enable logging? true|false<br/> * @parameter expression="${magento.dev.log.active}" default-value="true" */ protected Boolean magentoDevLogActive; /** * Logfile name, saved to var/log or /tmp if the former is not accessible.<br/> * @parameter expression="${magento.dev.log.file}" default-value="system.log" */ protected String magentoDevLogFile; /** * Logfile name for exceptions, saved to var/log or /tmp if the former is not accessible.<br/> * @parameter expression="${magento.dev.log.file.exception}" default-value="exception.log" */ protected String magentoDevLogFileException; /** * Allow symlinked templates? (only Magento >=1.5.1.0) true|false<br/> * @parameter expression="${magento.dev.allow.symlinks}" default-value="true" */ protected Boolean magentoDevAllowSymlinks; /** * Setup pear after installation? true|false<br/> * @parameter expression="${magento.pear.enabled}" default-value="true" */ protected Boolean magentoPearEnabled; /** * Upgrade pear after installation? true|false<br/> * Will autorun for Magento 1.4.2.0<br/> * @parameter expression="${magento.pear.upgrade}" default-value="false" */ protected Boolean magentoPearUpgrade; /** * Set prefered extension stability. alpha|beta|stable<br/> * @parameter expression="${magento.extensions.prefered.stability}" default-value="beta" */ protected String magentoExtensionsPreferedStability; /** * List of core extension keys you want installed after setup.<br/> * <pre>Interface_Frontend_Default_Blank,etc</pre> * You can append the version string.<br/> * <pre>Interface_Frontend_Default_Blank-1.4.0.1</pre> * @parameter expression="${magento.extensions.core}" default-value="" */ protected String magentoExtensionsCore; /** * List of community extension keys you want installed after setup.<br/> * <pre>Locale_Mage_community_de_DE,market_ready_germany</pre> * You can append the version string.<br/> * <pre>Locale_Mage_community_de_DE-1.4.0.1</pre> * @parameter expression="${magento.extensions.community}" default-value="" */ protected String magentoExtensionsCommunity; /** * Other artifacts you want deployed on installation, list of .zip files.<br/> * Put the artifacts into /extensions of your project root.<br/> * If you have a bunch of them you can use * instead of typing them all out. * @parameter expression="${magento.extensions.other}" default-value="" */ protected String magentoExtensionsOther; /** * Reindex Magento database after setup? true|false<br/> * @parameter expression="${magento.db.reindex}" default-value="false" */ protected Boolean magentoDbReindex; /** * Default locale key.<br/> * @parameter expression="${magento.locale}" default-value="en_US" */ protected String magentoLocale; /** * Default Magento theme.<br/> * @parameter expression="${magento.theme}" default-value="default" */ protected String magentoTheme; /** * Admin user email address.<br/> * @parameter expression="${magento.admin.email}" default-value="[email protected]" */ protected String magentoAdminEmail; /** * Admin user first name.<br/> * @parameter expression="${magento.admin.name.first}" default-value="Heinzi" */ protected String magentoAdminNameFirst; /** * Admin user last name.<br/> * @parameter expression="${magento.admin.name.last}" default-value="Floppel" */ protected String magentoAdminNameLast; /** * Default time zone.<br/> * @parameter expression="${magento.timezone}" default-value="Europe/Berlin" */ protected String magentoTimezone; /** * Default currency.<br/> * @parameter expression="${magento.currency}" default-value="EUR" */ protected String magentoCurrency; /** * Frontend name for backend accesss.<br/> * @parameter expression="${magento.backend.frontend.name}" default-value="admin" */ protected String magentoBackendFrontendName; /** * Enable SEO rewriting? true|false<br/> * @parameter expression="${magento.seo.use.rewrites}" default-value="true" */ protected Boolean magentoSeoUseRewrites; /** * Enable API cache? true|false<br/> * @parameter expression="${magento.cache.api}" default-value="false" */ protected Boolean magentoCacheApi; /** * Enable block cache? true|false<br/> * @parameter expression="${magento.cache.block}" default-value="false" */ protected Boolean magentoCacheBlock; /** * Enable config cache? true|false<br/> * @parameter expression="${magento.cache.config}" default-value="false" */ protected Boolean magentoCacheConfig; /** * Enable collection cache? true|false<br/> * @parameter expression="${magento.cache.collections}" default-value="false" */ protected Boolean magentoCacheCollections; /** * Enable EAV cache? true|false<br/> * @parameter expression="${magento.cache.eav}" default-value="false" */ protected Boolean magentoCacheEav; /** * Enable layout cache? true|false<br/> * @parameter expression="${magento.cache.layout}" default-value="false" */ protected Boolean magentoCacheLayout; /** * Enable translate cache? true|false<br/> * @parameter expression="${magento.cache.translate}" default-value="false" */ protected Boolean magentoCacheTranslate; /** * Reverse proxy header1 (local.xml)<br/> * @parameter expression="${magento.remote.addr.header1}" default-value="HTTP_X_REAL_IP" */ protected String magentoRemoteAddrHeader1; /** * Reverse proxy header2 (local.xml)<br/> * @parameter expression="${magento.remote.addr.header2}" default-value="HTTP_X_FORWARDED_FOR" */ protected String magentoRemoteAddrHeader2; /** * Where to save sessions? files|db<br/> * @parameter expression="${magento.session.save}" default-value="files" */ protected String magentoSessionSave; /** * Sessiondata location? files|db|memcache<br/> * @parameter expression="${magento.sessiondata.location}" default-value="files" */ protected String magentoSessiondataLocation; /** * @parameter expression="${magento.sessiondata.savepath}" default-value="" */ protected String magentoSessiondataSavepath; /** * @parameter expression="${magento.session.cache.limiter}" default-value="" */ protected String magentoSessionCacheLimiter; /** * file|apc|memcached<br/> * @parameter expression="${magento.session.cache.backend}" default-value="files" */ protected String magentoSessionCacheBackend; /** * file|apc|memcached<br/> * @parameter expression="${magento.session.cache.slow.backend}" default-value="files" */ protected String magentoSessionCacheSlowBackend; /** * @parameter expression="${magento.session.cache.slow.backend.store.data}" default-value="false" */ protected Boolean magentoSessionCacheSlowBackendStoreData; /** * @parameter expression="${magento.session.cache.auto.refresh.fast.cache}" default-value="false" */ protected Boolean magentoSessionCacheAutoRefreshFastCache; /** * Memcached url.<br/> * @parameter expression="${magento.session.cache.memcached.host}" default-value="" */ protected String magentoSessionCacheMemcachedHost; /** * Memcached port.<br/> * @parameter expression="${magento.session.cache.memcached.port}" default-value="" */ protected String magentoSessionCacheMemcachedPort; /** * @parameter expression="${magento.session.cache.memcached.weight}" default-value="" */ protected String magentoSessionCacheMemcachedWeight; /** * @parameter expression="${magento.session.cache.memcached.timeout}" default-value="" */ protected String magentoSessionCacheMemcachedTimeout; /** * @parameter expression="${magento.session.cache.memcached.interval}" default-value="" */ protected String magentoSessionCacheMemcachedInterval; /** * @parameter expression="${magento.session.cache.memcached.status}" default-value="" */ protected String magentoSessionCacheMemcachedStatus; /** * @parameter expression="${magento.session.cache.memcached.persistent}" default-value="" */ protected String magentoSessionCacheMemcachedPersistent; /** * @parameter expression="${magento.session.cache.memcached.compression}" default-value="false" */ protected Boolean magentoSessionCacheMemcachedCompression; /** * @parameter expression="${magento.session.cache.memcached.cachedir}" default-value="" */ protected String magentoSessionCacheMemcachedCachedir; /** * @parameter expression="${magento.session.cache.memcached.hashed.dir.umask}" default-value="" */ protected String magentoSessionCacheMemcachedHashedDirUmask; /** * @parameter expression="${magento.session.cache.memcached.file.prefix}" default-value="" */ protected String magentoSessionCacheMemcachedFilePrefix; /** * Encryption key to use. If omitted a fresh one will be generated.<br/> * @parameter expression="${magento.encryptionkey}" */ protected String magentoEncryptionkey; /** * Omit for current date, format: Tue, 13 Apr 2010 21:40:52 +0000<br/> * @parameter expression="${magento.install.date}" */ protected String magentoInstallDate; /** * Omit for current date, format: 2010-04-13 21:40:52<br/> * @parameter expression="${magento.install.date.sql}" */ protected String magentoInstallDateSql; /** * Database table prefix, not implemented yet.<br/> * @parameter expression="${magento.db.table.prefix}" default-value="" */ protected String magentoDbTablePrefix; /** * @parameter expression="${magento.session.cache.memcached.hashed.dir.level}" default-value="" */ protected String magentoSessionCacheMemcachedHashedDirLevel; /** * Magento base url.<br/> * @parameter expression="${magento.url.base}" * @required */ protected String magentoUrlBase; /** * Magento secure base url.<br/> * @parameter expression="${magento.url.base.https}" */ protected String magentoUrlBaseHttps; protected MagentoVersion mVersion; protected String magentoAdminPasswdHashed = ""; protected String tempDir; protected String targetDir; protected Boolean isIntegrationTest = false; // kinda obsolete, may return if we want to support token mapping in sql dumps again protected void createFinalSqlDump() throws MojoExecutionException { // get params for regex replace in the sql dump Map<String, String> sqlTags = getSqlTagMap(); File sqlDumpFiltered = new File( tempDir+"/sql", "magento.sql.f" ); String sqlDumpFileName = "magento.sql"; if (magentoUseSampleData) { sqlDumpFileName = "magento_with_sample_data.sql"; } String sqlDumpOrg = null; try { sqlDumpOrg = FileUtils.fileRead(new File(tempDir+"/sql/"+sqlDumpFileName)); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(),e); } FileWriter w = null; try { w = new FileWriter( sqlDumpFiltered ); w.write( MagentoUtil.replaceTags(sqlDumpOrg, sqlTags) ); } catch (IOException e) { throw new MojoExecutionException( "Error creating file " + sqlDumpFiltered, e ); } finally { if ( w != null ) { try { w.close(); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } } } } protected void createLocalXml() throws MojoExecutionException { if (magentoEncryptionkey == null || magentoEncryptionkey.isEmpty()) { try { getLog().info("Generating fresh encryption key.."); magentoEncryptionkey = MagentoUtil.getMd5Hash(new Date().toString()); getLog().info("-> "+magentoEncryptionkey); } catch (UnsupportedEncodingException e) { throw new MojoExecutionException(e.getMessage(),e); } catch (NoSuchAlgorithmException e) { throw new MojoExecutionException(e.getMessage(),e); } } if (magentoInstallDate == null || magentoInstallDate.isEmpty()) { SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", new Locale("en", "EN")); magentoInstallDate = format.format(new Date()); } Path localXmlPath = Paths.get(tempDir+"/app/etc/local.xml"); if (Files.notExists(localXmlPath)) { Path localXmlPathTemp = Paths.get(tempDir+"/app/etc/local.xml.template"); if (Files.notExists(localXmlPathTemp)) { throw new MojoExecutionException("Could read neither local.xml or local.xml.template!"); } try { Files.move(localXmlPathTemp, localXmlPath); } catch (IOException e) { throw new MojoExecutionException("Error renaming local.xml.template! "+e.getMessage(), e); } } // get params for regex replace in local.xml Map<String, String> localTags = getLocalXmlTagMap(); Document localXml = MagentoXmlUtil.readXmlFile(tempDir+"/app/etc/local.xml"); Document localXmlAdditional = MagentoXmlUtil.readXmlFile(tempDir+"/app/etc/local.xml.additional"); if (magentoSessiondataSavepath != null && !magentoSessiondataSavepath.isEmpty()) { // find cache nodes in local.xml.additional NodeList cacheNodes = localXmlAdditional.getElementsByTagName("session_save_path"); // import them to a new node Node n = localXml.importNode(cacheNodes.item(0), true); // find global node of local.xml NodeList globalNodes = localXml.getElementsByTagName("global"); // append imported nodes to local.xml Node g = globalNodes.item(0); g.appendChild(n); } if (magentoSessionCacheLimiter != null && !magentoSessionCacheLimiter.isEmpty()) { // find cache nodes in local.xml.additional NodeList cacheNodes = localXmlAdditional.getElementsByTagName("session_cache_limiter"); // import them to a new node Node n = localXml.importNode(cacheNodes.item(0), true); // find global node of local.xml NodeList globalNodes = localXml.getElementsByTagName("global"); // append imported nodes to local.xml Node g = globalNodes.item(0); g.appendChild(n); } if (magentoSessionCacheBackend.equals("memcached") || magentoSessionCacheBackend.equals("apc") || magentoSessionCacheBackend.equals("xcache")) { // find cache nodes in local.xml.additional NodeList cacheNodes = localXmlAdditional.getElementsByTagName("cache"); // import them to a new node Node n = localXml.importNode(cacheNodes.item(0), true); // find global node of local.xml NodeList globalNodes = localXml.getElementsByTagName("global"); // append imported nodes to local.xml Node g = globalNodes.item(0); g.appendChild(n); } if (mVersion.getMajorVersion() <= 1 && mVersion.getMinorVersion() < 6) { if (magentoRemoteAddrHeader1 != null && !magentoRemoteAddrHeader1.isEmpty()) { // find cache nodes in local.xml.additional NodeList cacheNodes = localXmlAdditional.getElementsByTagName("remote_addr_headers"); // import them to a new node Node n = localXml.importNode(cacheNodes.item(0), true); // find global node of local.xml NodeList globalNodes = localXml.getElementsByTagName("global"); // append imported nodes to local.xml Node g = globalNodes.item(0); g.appendChild(n); } } MagentoXmlUtil.updateXmlValues(localTags, localXml); String finalLocalXml = null; try { finalLocalXml = MagentoUtil.replaceTags(MagentoXmlUtil.transformXmlToString(localXml), localTags); } catch (TransformerException e) { throw new MojoExecutionException("Error while creating local.xml", e); } MagentoXmlUtil.writeXmlFile(finalLocalXml, tempDir+"/app/etc/local.xml"); } protected void updateLocalXml() throws MojoExecutionException { String localXmlPath = tempDir+"/app/etc/local.xml"; Document localXml = MagentoXmlUtil.readXmlFile(localXmlPath); MagentoXmlUtil.updateDbValues(magentoDbHost, magentoDbUser, magentoDbPasswd, magentoDbName, localXml); try { MagentoXmlUtil.writeXmlFile(MagentoXmlUtil.transformXmlToString(localXml), localXmlPath); } catch (TransformerException e) { throw new MojoExecutionException(e.getMessage(), e); } } protected NodeList findXmlNode(Object obj, String xpathExpression) throws XPathExpressionException { XPath xPath = XPathFactory.newInstance().newXPath(); XPathExpression expression; expression = xPath.compile( xpathExpression ); return (NodeList) expression.evaluate( obj, XPathConstants.NODESET ); } protected void createOldCacheConfig() throws MojoExecutionException { // get params for regex replace in local.xml Map<String, String> cacheTags = getOldCacheTagMap(); String cacheConfigTemplate = "a:7:{s:6:\"config\";i:@CACHE_CONFIG@;s:6:\"layout\";i:@CACHE_LAYOUT@;s:10:\"block_html\";i:@CACHE_BLOCK@;s:9:\"translate\";i:@CACHE_TRANSLATE@;s:11:\"collections\";i:@CACHE_COLLECTIONS@;s:3:\"eav\";i:@CACHE_EAV@;s:10:\"config_api\";i:@CACHE_API@;}"; String finalCacheConfig = null; finalCacheConfig = MagentoUtil.replaceTags(cacheConfigTemplate, cacheTags); File cacheConfigFiltered = new File(tempDir+"/app/etc/use_cache.ser"); FileWriter cacheWriter = null; try { cacheWriter = new FileWriter( cacheConfigFiltered ); cacheWriter.write( finalCacheConfig ); } catch ( IOException e ) { throw new MojoExecutionException("Error writing use_cache.ser", e); } finally { if ( cacheWriter != null ) { try { cacheWriter.close(); } catch ( IOException e ) { throw new MojoExecutionException(e.getMessage(), e); } } } } // setup standard magento protected void setupMagento() throws MojoFailureException, MojoExecutionException { try { mVersion = new MagentoVersion(magentoVersion); } catch (Exception e) { throw new MojoExecutionException(e.getMessage(), e); } if (!magentoArtifactGroupId.equals("com.varien")) { magentoArtifactIsCustom = true; } magentoUrlBase = MagentoUtil.validateBaseUrl(magentoUrlBase, false); if (magentoUrlBaseHttps != null && !magentoUrlBaseHttps.isEmpty()) { magentoUrlBaseHttps = MagentoUtil.validateBaseUrl(magentoUrlBaseHttps, true); } else { magentoUrlBaseHttps = magentoUrlBase; } // extract magento artifact try { getLog().info("Resolving dependencies.."); MavenUtil.extractCompileDependencies(tempDir, project, getLog()); getLog().info("..done."); } catch (IOException e) { throw new MojoExecutionException("Error extracting artifact: " + e.getMessage(), e); } // drop db if existing MagentoSqlUtil.dropMagentoDb(magentoDbUser, magentoDbPasswd, magentoDbHost, magentoDbPort, magentoDbName, getLog()); // create db MagentoSqlUtil.createMagentoDb(magentoDbUser, magentoDbPasswd, magentoDbHost, magentoDbPort, magentoDbName, getLog()); String dumpFileName = tempDir+"/mavento_setup/sql/magento.sql"; if (magentoDumpFileName != null && !magentoDumpFileName.isEmpty()) { // use premade dump dumpFileName = project.getBasedir()+"/sqldumps/"+magentoDumpFileName; if (!new File(dumpFileName).exists()) { throw new MojoExecutionException("Could not find custom sql dump file. Make sure to place it in /sqldumps of your project root."); } getLog().info("Using custom dump: "+dumpFileName); } else if (magentoUseSampleData && !magentoArtifactIsCustom) { dumpFileName = tempDir+"/mavento_setup/sql/magento_with_sample_data.sql"; } // inject dump into database MagentoSqlUtil.importSqlDump(dumpFileName, magentoDbUser, magentoDbPasswd, magentoDbHost, magentoDbPort, magentoDbName, getLog()); String jdbcUrl = MagentoSqlUtil.getJdbcUrl(magentoDbHost, magentoDbPort, magentoDbName); Map<String, String> config = null; getLog().info("Generating admin pw hash.."); try { magentoAdminPasswdHashed = MagentoUtil.getSaltedMd5Hash(magentoAdminPasswd); } catch (UnsupportedEncodingException e) { throw new MojoExecutionException( "Error while creating admin password hash." + e.getMessage(), e); } catch (NoSuchAlgorithmException e) { throw new MojoExecutionException( "Error while creating admin password hash." + e.getMessage(), e); } getLog().info("-> "+magentoAdminPasswdHashed); // fix https url if not configured if (magentoUrlBaseHttps == null || magentoUrlBaseHttps.isEmpty()) { magentoUrlBaseHttps = magentoUrlBase; } // generate new install date if not configured if (magentoInstallDateSql == null || magentoInstallDateSql.isEmpty()) { SimpleDateFormat fo = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); magentoInstallDateSql = fo.format(new Date()); } // check if ip restrictions are not null if (magentoDevRestrictIp == null) { magentoDevRestrictIp = ""; } if (magentoArtifactIsCustom || (magentoDumpFileName != null && !magentoDumpFileName.isEmpty())) { config = getSqlAdminTagMap(); MagentoSqlUtil.updateAdminUser(config, magentoDbUser, magentoDbPasswd, jdbcUrl, getLog()); // only update baseurl and dev settings for custom magento artifacts getLog().info("Setting baseUrl to: "+magentoUrlBase); config = getSqlTagMapBasic(); } else { // update everything getLog().info("Updating database.."); config = getSqlAdminTagMap(); MagentoSqlUtil.updateAdminUser(config, magentoDbUser, magentoDbPasswd, jdbcUrl, getLog()); if (mVersion.getMajorVersion() == 1 && mVersion.getMinorVersion() > 3 ) { config = getSqlCacheTagMap(); MagentoSqlUtil.updateCacheConfig(config, magentoDbUser, magentoDbPasswd, jdbcUrl, getLog()); } config = getSqlTagMap(); } MagentoSqlUtil.setCoreConfigData(config, magentoDbUser, magentoDbPasswd, jdbcUrl, getLog()); getLog().info("..done."); // update db settings in local.xml for custom artifacts, else do a full setup if (magentoArtifactIsCustom) { getLog().info("Updating db settings in local.xml.."); updateLocalXml(); getLog().info("..done."); } else { // prepare local.xml createLocalXml(); updateLocalXml(); // create cache config file for magento <1.4.x if (mVersion.getMajorVersion() == 1 && mVersion.getMinorVersion() < 4) { getLog().info("Generating pre 1.4 Magento cache file.."); createOldCacheConfig(); getLog().info("..done."); } // handle exception exposing if (magentoExposeExceptions && (mVersion.getMajorVersion() == 1 && mVersion.getMinorVersion() > 3)) { getLog().info("Enabling exception printing.."); try { Files.move(Paths.get(tempDir+"/errors/local.xml.sample"), Paths.get(tempDir+"/errors/local.xml")); } catch (IOException e) { throw new MojoExecutionException("Error while enabling exception printing! " + e.getMessage(), e); } getLog().info("..done."); } // copy sample data product images if (magentoUseSampleData && !magentoArtifactIsCustom) { Path magentoSourcePath = Paths.get(tempDir+"/mavento_setup/sample_data"); Path magentoTargetPath = Paths.get(tempDir); try { getLog().info("Copying sample data.."); CopyFilesVisitor cv = new CopyFilesVisitor(magentoSourcePath, magentoTargetPath, false); Files.walkFileTree(magentoSourcePath, cv); getLog().info("..done."); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } } } // extract local extensions if ( magentoExtensionsOther != null && !magentoExtensionsOther.isEmpty() ) { if ( magentoExtensionsOther.equals("*") ) { Path eDir = Paths.get("extensions"); Path tDir = Paths.get(tempDir); try { Files.createDirectories(eDir); ExtractZipVisitor ev = new ExtractZipVisitor(tDir, getLog()); EnumSet<FileVisitOption> options = EnumSet.of(FileVisitOption.FOLLOW_LINKS); Files.walkFileTree(eDir, options, 1, ev); } catch (IOException e) { throw new MojoExecutionException("Error: "+e.getMessage(), e); } } else { String[] k = magentoExtensionsOther.split(","); for (String extensionKey : k) { String fPath = "extensions/"+extensionKey; Path sourceFile = Paths.get(fPath); if ( !Files.exists(sourceFile) ) { if (extensionKey.endsWith(".zip")) { sourceFile = Paths.get(fPath+".zip"); if ( !Files.exists(sourceFile) ) { throw new MojoExecutionException("Could not find "+extensionKey+" in extensions/"); } } else { throw new MojoExecutionException("Could not find "+extensionKey+" in extensions/"); } } else { try { getLog().info("Extracting "+sourceFile.getFileName()); FileUtil.unzipFile(sourceFile.toAbsolutePath().toString(), tempDir); } catch (IOException e) { throw new MojoExecutionException("Error: "+e.getMessage(), e); } } } } getLog().info("..done."); } try { FileUtil.deleteFile(tempDir+"/var/cache", getLog()); FileUtil.deleteFile(tempDir+"/mavento_setup", getLog()); FileUtil.deleteFile(tempDir+"/META-INF", getLog()); } catch (IOException e) { throw new MojoExecutionException("Error deleting directories. "+e.getMessage(), e); } if (!isIntegrationTest) { // copy prepared magento to final destination unless this an integration test Path magentoSourcePath = Paths.get(tempDir); Path magentoTargetPath = Paths.get(magentoRootLocal); getLog().info("Everything is prepared, copying to "+magentoRootLocal); try { FileUtil.deleteFile(magentoRootLocal, getLog()); Files.createDirectories(magentoTargetPath); CopyFilesVisitor cv = new CopyFilesVisitor(magentoSourcePath, magentoTargetPath, false); Files.walkFileTree(magentoSourcePath, cv); } catch (IOException e) { throw new MojoExecutionException("Error while copying to: "+magentoTargetPath.toAbsolutePath() + " " + e.getMessage(), e); } getLog().info("..done."); } setupPear(); // add any core_config_data properties after extension install, as the extension might overwrite them else getLog().info("Updating core_config_data.."); config = MavenUtil.addMagentoMiscProperties(project, new HashMap<String,String>(), getLog()); MagentoSqlUtil.setCoreConfigData(config, magentoDbUser, magentoDbPasswd, jdbcUrl, getLog()); getLog().info("..done."); // finally reindex the magento db indexDb(); } private void setupPear() throws MojoExecutionException { // handle pear setup and possible additional extensions if (magentoPearEnabled) { File magentoTargetPath = new File(targetDir); File pearExecutable = null; if (mVersion.getMajorVersion() >= 1 && mVersion.getMinorVersion() >= 5) { pearExecutable = new File(magentoTargetPath.getAbsolutePath()+"/mage"); } else { pearExecutable = new File(magentoTargetPath.getAbsolutePath()+"/pear"); } pearExecutable.setExecutable(true, true); getLog().info("Initializing pear.."); MagentoUtil.executePearCommand(pearExecutable.getAbsolutePath(), new String[] {"mage-setup"}, magentoTargetPath.getAbsolutePath(), mVersion, getLog()); getLog().info("..done."); if (magentoPearUpgrade || (mVersion.getMajorVersion() == 1 && mVersion.getMinorVersion() == 4 && mVersion.getRevisionVersion() == 2)) { getLog().info("Updating pear channel.."); MagentoUtil.executePearCommand(pearExecutable.getAbsolutePath(), new String[] {"channel-update", "pear.php.net"}, magentoTargetPath.getAbsolutePath(), mVersion, getLog()); if (mVersion.getMajorVersion() <= 1 && mVersion.getMinorVersion() < 6) { getLog().info("Upgrading pear.."); MagentoUtil.executePearCommand(pearExecutable.getAbsolutePath(), new String[] {"upgrade", "--force", "PEAR"}, magentoTargetPath.getAbsolutePath(), mVersion, getLog()); } getLog().info("..done."); } // set extension prefered stability if (magentoExtensionsPreferedStability != null && !magentoExtensionsPreferedStability.isEmpty()) { getLog().info("Setting preferred extension stability to "+magentoExtensionsPreferedStability+".."); MagentoUtil.executePearCommand(pearExecutable.getAbsolutePath(), new String[] {"config-set", "preferred_state", magentoExtensionsPreferedStability}, magentoTargetPath.getAbsolutePath(), mVersion, getLog()); getLog().info("..done."); } // install core extensions String[] extensionKeys = null; if (magentoExtensionsCore != null) { extensionKeys = magentoExtensionsCore.split(","); installPearModules("core", extensionKeys, pearExecutable); } // install community extensions if (magentoExtensionsCommunity != null) { extensionKeys = magentoExtensionsCommunity.split(","); installPearModules("community", extensionKeys, pearExecutable); } } } protected void installPearModules(String channel, String[] extensionKeys, File pearExecutable) throws MojoExecutionException { for (String extensionKey : extensionKeys) { if (!extensionKey.isEmpty()) { String[] params = null; if (mVersion.getMajorVersion() == 1 && mVersion.getMinorVersion() <= 4) { String realChannel = "magento-core/"; if (channel.equals("community")) { realChannel = "magento-community/"; } params = new String[] {"install", realChannel+extensionKey}; } else { String realChannel = "http://connect20.magentocommerce.com/core"; if (channel.equals("community")) { realChannel = "http://connect20.magentocommerce.com/community"; } if (extensionKey.contains("-")) { String[] s = extensionKey.split("-"); String extensionVersion = ""; if (s.length == 2) { extensionKey = s[0]; extensionVersion = s[1]; } getLog().info("Installing magento-"+channel+"/"+extensionKey+"-"+extensionVersion+".."); params = new String[] {"install", realChannel, extensionKey, extensionVersion}; } else { getLog().info("Installing magento-"+channel+"/"+extensionKey+".."); params = new String[] {"install", realChannel, extensionKey}; } } MagentoUtil.executePearCommand(pearExecutable.getAbsolutePath(), params, targetDir, mVersion, getLog()); getLog().info("..done."); } } } private void indexDb() throws MojoExecutionException { // reindex db if (magentoDbReindex && (mVersion.getMajorVersion() >= 1 && mVersion.getMinorVersion() >= 4)) { if (magentoDeployType.equals("local")) { MagentoSqlUtil.indexDb(targetDir, getLog()); } else { throw new MojoExecutionException("Oops, remote indexing not implemented yet. Skipping.."); } } } private Map<String, String> getSqlTagMap() { Map<String, String> tokenMap = getSqlTagMapBasic(); tokenMap.put("general/locale/timezone", magentoTimezone); tokenMap.put("currency/options/base", magentoCurrency); tokenMap.put("currency/options/default", magentoCurrency); tokenMap.put("currency/options/allow", magentoCurrency); tokenMap.put("general/locale/code", magentoLocale); tokenMap.put("design/theme/default", magentoTheme); tokenMap.put("web/seo/use_rewrites", magentoSeoUseRewrites ? "1" : "0"); return tokenMap; } private Map<String, String> getSqlTagMapBasic() { Map<String, String> tokenMap = new HashMap<String, String>(); tokenMap.put("web/unsecure/base_url", magentoUrlBase); tokenMap.put("web/secure/base_url", magentoUrlBaseHttps); tokenMap.put("web/secure/use_in_adminhtml", magentoUseHttpsBackend ? "1" : "0"); tokenMap.put("web/secure/use_in_frontend", magentoUseHttpsFrontend ? "1" : "0"); tokenMap.put("web/unsecure/base_skin_url", "{{unsecure_base_url}}skin/"); tokenMap.put("web/unsecure/base_media_url", "{{unsecure_base_url}}media/"); tokenMap.put("web/unsecure/base_link_url", "{{unsecure_base_url}}"); tokenMap.put("web/unsecure/base_js_url", "{{unsecure_base_url}}js/"); tokenMap.put("web/secure/base_skin_url", "{{secure_base_url}}skin/"); tokenMap.put("web/secure/base_media_url", "{{secure_base_url}}media/"); tokenMap.put("web/secure/base_link_url", "{{secure_base_url}}"); tokenMap.put("web/secure/base_js_url", "{{secure_base_url}}js/"); // dev stuff tokenMap.put("dev/restrict/allow_ips", magentoDevRestrictIp); tokenMap.put("dev/debug/profiler", magentoDevProfiler ? "1" : "0"); tokenMap.put("dev/log/active", magentoDevLogActive ? "1" : "0" ); tokenMap.put("dev/log/file", magentoDevLogFile); tokenMap.put("dev/log/exception_file", magentoDevLogFileException); tokenMap.put("dev/template/allow_symlink", magentoDevAllowSymlinks ? "1" : "0"); return tokenMap; } private Map<String, String> getSqlAdminTagMap() { Map<String, String> tokenMap = new HashMap<String, String>(); tokenMap.put("ADMIN_USERNAME", magentoAdminUsername); tokenMap.put("ADMIN_PASSWD", magentoAdminPasswdHashed); tokenMap.put("ADMIN_NAME_FIRST", magentoAdminNameFirst); tokenMap.put("ADMIN_NAME_LAST", magentoAdminNameLast); tokenMap.put("ADMIN_EMAIL", magentoAdminEmail); tokenMap.put("INSTALL_DATESQL", magentoInstallDateSql); return tokenMap; } private Map<String, String> getSqlCacheTagMap() { Map<String, String> tokenMap = new HashMap<String, String>(); // only magento >=1.4.x.x tokenMap.put("config", magentoCacheConfig ? "1" : "0"); tokenMap.put("layout", magentoCacheLayout ? "1" : "0"); tokenMap.put("block_html", magentoCacheBlock ? "1" : "0"); tokenMap.put("translate", magentoCacheTranslate ? "1" : "0"); tokenMap.put("collections", magentoCacheCollections ? "1" : "0"); tokenMap.put("eav", magentoCacheEav ? "1" : "0"); tokenMap.put("config_api", magentoCacheApi ? "1" : "0"); return tokenMap; } private Map<String, String> getOldCacheTagMap() { Map<String, String> tokenMap = new HashMap<String, String>(); // only magento <1.4.x tokenMap.put("CACHE_CONFIG", magentoCacheConfig ? "1" : "0"); tokenMap.put("CACHE_LAYOUT", magentoCacheLayout ? "1" : "0"); tokenMap.put("CACHE_BLOCK", magentoCacheBlock ? "1" : "0"); tokenMap.put("CACHE_TRANSLATE", magentoCacheTranslate ? "1" : "0"); tokenMap.put("CACHE_COLLECTIONS", magentoCacheCollections ? "1" : "0"); tokenMap.put("CACHE_EAV", magentoCacheEav ? "1" : "0"); tokenMap.put("CACHE_API", magentoCacheApi ? "1" : "0"); return tokenMap; } private Map<String, String> getLocalXmlTagMap() { Map<String, String> tokenMap = new HashMap<String, String>(); tokenMap.put("host", magentoDbHost); tokenMap.put("dbname", magentoDbName); tokenMap.put("username", magentoDbUser); tokenMap.put("password", magentoDbPasswd); if (magentoDbTablePrefix == null) { magentoDbTablePrefix=""; } tokenMap.put("table_prefix", magentoDbTablePrefix); tokenMap.put("session_save", magentoSessionSave); tokenMap.put("key", magentoEncryptionkey); tokenMap.put("frontName", magentoBackendFrontendName); tokenMap.put("date", magentoInstallDate); // local.xml.additional // TODO: handle local.xml.additional stuff via xml in createLocalXml() // tokenMap.put("session_save", magentoSessionSave); // tokenMap.put("session_save", magentoSessiondataLocation); // tokenMap.put("session_save_path", magentoSessiondataSavepath); // tokenMap.put("session_cache_limiter", magentoSessionCacheLimiter); // tokenMap.put("backend", magentoSessionCacheBackend); // tokenMap.put("slow_backend", magentoSessionCacheSlowBackend); // tokenMap.put("auto_refresh_fast_cache", magentoSessionCacheAutoRefreshFastCache ? "1" : "0"); // tokenMap.put("slow_backend_store_data", magentoSessionCacheSlowBackendStoreData ? "1" : "0"); // tokenMap.put("host", magentoSessionCacheMemcachedHost); // tokenMap.put("port", magentoSessionCacheMemcachedPort); // tokenMap.put("persistent", magentoSessionCacheMemcachedPersistent); // tokenMap.put("compression", magentoSessionCacheMemcachedCompression ? "1" : "0"); // tokenMap.put("cache_dir", magentoSessionCacheMemcachedCachedir); // tokenMap.put("hashed_directory_level", magentoSessionCacheMemcachedHashedDirLevel); // tokenMap.put("hashed_directory_umask", magentoSessionCacheMemcachedHashedDirUmask); // tokenMap.put("file_name_prefix", magentoSessionCacheMemcachedFilePrefix); // tokenMap.put("weight", magentoSessionCacheMemcachedWeight); // tokenMap.put("retry_interval", magentoSessionCacheMemcachedInterval); // tokenMap.put("status", magentoSessionCacheMemcachedStatus); // tokenMap.put("timeout", magentoSessionCacheMemcachedTimeout); // tokenMap.put("header1", magentoRemoteAddrHeader1); // tokenMap.put("header2", magentoRemoteAddrHeader2); return tokenMap; } }
TestSetup will no longer extract dependencies.
src/main/java/de/bbe_consulting/mavento/AbstractMagentoSetupMojo.java
TestSetup will no longer extract dependencies.
<ide><path>rc/main/java/de/bbe_consulting/mavento/AbstractMagentoSetupMojo.java <ide> } <ide> <ide> // extract magento artifact <del> try { <del> getLog().info("Resolving dependencies.."); <del> MavenUtil.extractCompileDependencies(tempDir, project, getLog()); <del> getLog().info("..done."); <del> } catch (IOException e) { <del> throw new MojoExecutionException("Error extracting artifact: " + e.getMessage(), e); <del> } <add> if (!isIntegrationTest) { <add> try { <add> getLog().info("Resolving dependencies.."); <add> MavenUtil.extractCompileDependencies(tempDir, project, getLog()); <add> getLog().info("..done."); <add> } catch (IOException e) { <add> throw new MojoExecutionException("Error extracting artifact: " + e.getMessage(), e); <add> } <add> } <ide> <ide> // drop db if existing <ide> MagentoSqlUtil.dropMagentoDb(magentoDbUser, magentoDbPasswd, magentoDbHost, magentoDbPort, magentoDbName, getLog());
JavaScript
mit
ee283f922bcfec33316088f1991c4d928b7f8827
0
alanplotko/Dash,alanplotko/Dash
// --------- Dependencies --------- var User = require('../models/user'); var validator = require('validator'); require('../config/custom-validation.js')(validator); var xss = require('xss'); var debug = (process.env.NODE_ENV == 'dev'); module.exports = function(app, passport) { // --------- Front Page --------- app.get('/', function (req, res) { if (req.isAuthenticated()) return res.redirect('/dashboard'); res.render('index'); }); // --------- User Dashboard --------- app.get('/dashboard', isLoggedIn, function(req, res) { res.render('dashboard', { // Add other connection fields here connected: req.user.facebook.profileId !== undefined, facebookPosts: req.user.facebook.posts }); }); app.post('/refresh', isLoggedIn, function(req, res) { req.user.updateContent(function(err, posts) { if (err) { return res.status(500).send({ message: 'Encountered an error. Please try again in a few minutes.' }); } else if (posts) { return res.status(200).send({ message: 'New posts have come in!', refresh: true }); } else { return res.status(200).send({ message: 'No new posts.', refresh: false }); } }); }); app.post('/dismiss/facebook/:id', isLoggedIn, function(req, res) { User.findByIdAndUpdate(req.user._id, { $set: { 'facebook.posts': [] } }, function(err, user) { if (err) return res.sendStatus(500); return res.sendStatus(200); }); }); app.post('/dismiss/facebook/all', isLoggedIn, function(req, res) { User.findByIdAndUpdate(req.user._id, { $pull: { 'facebook.posts': { _id: req.params.id } } }, function(err, user) { if (err) return res.sendStatus(500); return res.sendStatus(200); }); }); // --------- User's Settings --------- app.get('/settings', isLoggedIn, function(req, res) { res.render('settings', { message: req.flash('settingsMessage') }); }); app.post('/settings', isLoggedIn, function(req, res) { var displayName = validator.trim(req.body.displayName); var settings = {}; // Validate changes if (validator.isValidDisplayName(displayName)) { settings.displayName = displayName; } // Update user settings User.updateUser(req.user._id, settings, function(err, updateSuccess) { // An error occurred if (err) { req.flash('settingsMessage', err.toString()); } // Update succeeded else if (updateSuccess) { req.flash('settingsMessage', 'Your changes have been saved.'); } // An unexpected error occurred else { req.flash('settingsMessage', 'An error occurred. Please try again in a few minutes.'); } return res.redirect('/settings'); }); }); // --------- User's Connected Sites --------- app.get('/connect', isLoggedIn, function(req, res) { res.render('connect', { message: req.flash('connectMessage'), facebook: req.user.facebook.profileId }); }); app.get('/setup/facebook/groups', isLoggedIn, function(req, res) { User.setUpFacebookGroups(req.user._id, function(err, data) { // An error occurred if (err) { req.flash('setupMessage', err.toString()); res.redirect('/setup/facebook/groups'); } // Found groups else if (Object.keys(data).length > 0) { res.render('setup', { message: req.flash('setupMessage'), content: data, contentName: 'groups' }); } // No groups found; proceed to pages else {; res.redirect('/setup/facebook/pages'); } }); }); app.post('/setup/facebook/groups', isLoggedIn, function(req, res) { User.saveFacebookGroups(req.user._id, Object.keys(req.body), function(err, data) { // An error occurred if (err) { req.flash('setupMessage', err.toString()); res.redirect('/setup/facebook/groups'); } // Saved groups else { res.redirect('/setup/facebook/pages'); } }); }); app.get('/setup/facebook/pages', isLoggedIn, function(req, res) { User.setUpFacebookPages(req.user._id, function(err, data) { // An error occurred if (err) { req.flash('setupMessage', err.toString()); res.redirect('/setup/facebook/groups'); } // Found groups else if (Object.keys(data).length > 0) { res.render('setup', { message: req.flash('setupMessage'), content: data, contentName: 'pages' }); } // No groups found; proceed to pages else { res.redirect('/connect'); } }); }); app.post('/setup/facebook/pages', isLoggedIn, function(req, res) { User.saveFacebookPages(req.user._id, Object.keys(req.body), function(err, data) { // An error occurred if (err) { req.flash('setupMessage', err.toString()); res.redirect('/setup/facebook/pages'); } // Saved pages; return to connect page else { res.redirect('/connect'); } }); }); app.get('/connect/auth/facebook', passport.authenticate('facebook', { scope: ['user_managed_groups', 'user_likes'] })); app.get('/connect/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/connect', successRedirect: '/setup/facebook/groups' })); app.get('/connect/remove/facebook', isLoggedIn, function(req, res) { User.removeFacebook(req.user.id, function(err) { if (err) { req.flash('connectMessage', err.toString()); } else { req.flash('connectMessage', 'Your Facebook connection has been removed.'); } res.redirect('/connect'); }); }); // --------- Dash Login/Logout --------- app.get('/login', function(req, res) { if (req.isAuthenticated()) { return res.redirect('/dashboard'); } else { res.render('login', { message: req.flash('loginMessage') }); } }); app.post('/login', passport.authenticate('local-login', { successRedirect : '/dashboard', failureRedirect : '/login', failureFlash : true })); // Clear credentials and destroy session upon logout app.get('/logout', function(req, res) { req.logout(); req.session.destroy(function (err) { res.redirect('/'); }); }); // --------- Dash Registration --------- app.get('/register', function(req, res) { res.render('register', { message: req.flash('registerMessage') }); }); app.post('/register', passport.authenticate('local-register', { successRedirect : '/dashboard', failureRedirect : '/register', failureFlash : true })); // --------- Miscellaneous Routes & Helper Functions --------- // Route middleware to ensure user is logged in function isLoggedIn(req, res, next) { // Proceed if user is authenticated if (req.isAuthenticated()) return next(); // Otherwise, redirect to front page res.redirect('/'); } /*================================================================ * If the route does not exist (error 404), go to the error * page. This route must remain as the last defined route, so * that other routes are not overridden! ==================================================================*/ app.all('*', function(req, res, next) { var err = new Error(); err.status = 404; err.message = 'Page Not Found'; err.description = 'That\'s strange... we couldn\'t find what you were looking for.<br /><br />If you\'re sure that you\'re in the right place, let the team know.<br /><br />Otherwise, if you\'re lost, you can find your way back to the front page using the button below.'; next(err); }); };
routes/pages.js
// --------- Dependencies --------- var User = require('../models/user'); var validator = require('validator'); require('../config/custom-validation.js')(validator); var xss = require('xss'); var debug = (process.env.NODE_ENV == 'dev'); module.exports = function(app, passport) { // --------- Front Page --------- app.get('/', function (req, res) { if (req.isAuthenticated()) return res.redirect('/dashboard'); res.render('index'); }); // --------- User Dashboard --------- app.get('/dashboard', isLoggedIn, function(req, res) { User.updateContent(req.user._id, function(err, posts) { if (err) return next(err); // An error occurred }); res.render('dashboard', { // Add other connection fields here connected: req.user.facebook.profileId !== undefined, facebook: req.user.facebook.posts }); }); app.post('/dismiss/facebook/:id', isLoggedIn, function(req, res) { User.findByIdAndUpdate(req.user._id, { $set: { 'facebook.posts': [] } }, function(err, user) { if (err) return res.sendStatus(500); return res.sendStatus(200); }); }); app.post('/dismiss/facebook/all', isLoggedIn, function(req, res) { User.findByIdAndUpdate(req.user._id, { $pull: { 'facebook.posts': { _id: req.params.id } } }, function(err, user) { if (err) return res.sendStatus(500); return res.sendStatus(200); }); }); // --------- User's Settings --------- app.get('/settings', isLoggedIn, function(req, res) { res.render('settings', { message: req.flash('settingsMessage') }); }); app.post('/settings', isLoggedIn, function(req, res) { var displayName = validator.trim(req.body.displayName); var settings = {}; // Validate changes if (validator.isValidDisplayName(displayName)) { settings.displayName = displayName; } // Update user settings User.updateUser(req.user._id, settings, function(err, updateSuccess) { // An error occurred if (err) { req.flash('settingsMessage', err.toString()); } // Update succeeded else if (updateSuccess) { req.flash('settingsMessage', 'Your changes have been saved.'); } // An unexpected error occurred else { req.flash('settingsMessage', 'An error occurred. Please try again in a few minutes.'); } return res.redirect('/settings'); }); }); // --------- User's Connected Sites --------- app.get('/connect', isLoggedIn, function(req, res) { res.render('connect', { message: req.flash('connectMessage'), facebook: req.user.facebook.profileId }); }); app.get('/setup/facebook/groups', isLoggedIn, function(req, res) { User.setUpFacebookGroups(req.user._id, function(err, data) { // An error occurred if (err) { req.flash('setupMessage', err.toString()); res.redirect('/setup/facebook/groups'); } // Found groups else if (Object.keys(data).length > 0) { res.render('setup', { message: req.flash('setupMessage'), content: data, contentName: 'groups' }); } // No groups found; proceed to pages else {; res.redirect('/setup/facebook/pages'); } }); }); app.post('/setup/facebook/groups', isLoggedIn, function(req, res) { User.saveFacebookGroups(req.user._id, Object.keys(req.body), function(err, data) { // An error occurred if (err) { req.flash('setupMessage', err.toString()); res.redirect('/setup/facebook/groups'); } // Saved groups else { res.redirect('/setup/facebook/pages'); } }); }); app.get('/setup/facebook/pages', isLoggedIn, function(req, res) { User.setUpFacebookPages(req.user._id, function(err, data) { // An error occurred if (err) { req.flash('setupMessage', err.toString()); res.redirect('/setup/facebook/groups'); } // Found groups else if (Object.keys(data).length > 0) { res.render('setup', { message: req.flash('setupMessage'), content: data, contentName: 'pages' }); } // No groups found; proceed to pages else { res.redirect('/connect'); } }); }); app.post('/setup/facebook/pages', isLoggedIn, function(req, res) { User.saveFacebookPages(req.user._id, Object.keys(req.body), function(err, data) { // An error occurred if (err) { req.flash('setupMessage', err.toString()); res.redirect('/setup/facebook/pages'); } // Saved pages; return to connect page else { res.redirect('/connect'); } }); }); app.get('/connect/auth/facebook', passport.authenticate('facebook', { scope: ['user_managed_groups', 'user_likes'] })); app.get('/connect/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/connect', successRedirect: '/setup/facebook/groups' })); app.get('/connect/remove/facebook', isLoggedIn, function(req, res) { User.removeFacebook(req.user.id, function(err) { if (err) { req.flash('connectMessage', err.toString()); } else { req.flash('connectMessage', 'Your Facebook connection has been removed.'); } res.redirect('/connect'); }); }); // --------- Dash Login/Logout --------- app.get('/login', function(req, res) { if (req.isAuthenticated()) { return res.redirect('/dashboard'); } else { res.render('login', { message: req.flash('loginMessage') }); } }); app.post('/login', passport.authenticate('local-login', { successRedirect : '/dashboard', failureRedirect : '/login', failureFlash : true })); // Clear credentials and destroy session upon logout app.get('/logout', function(req, res) { req.logout(); req.session.destroy(function (err) { res.redirect('/'); }); }); // --------- Dash Registration --------- app.get('/register', function(req, res) { res.render('register', { message: req.flash('registerMessage') }); }); app.post('/register', passport.authenticate('local-register', { successRedirect : '/dashboard', failureRedirect : '/register', failureFlash : true })); // --------- Miscellaneous Routes & Helper Functions --------- // Route middleware to ensure user is logged in function isLoggedIn(req, res, next) { // Proceed if user is authenticated if (req.isAuthenticated()) return next(); // Otherwise, redirect to front page res.redirect('/'); } /*================================================================ * If the route does not exist (error 404), go to the error * page. This route must remain as the last defined route, so * that other routes are not overridden! ==================================================================*/ app.all('*', function(req, res, next) { var err = new Error(); err.status = 404; err.message = 'Page Not Found'; err.description = 'That\'s strange... we couldn\'t find what you were looking for.<br /><br />If you\'re sure that you\'re in the right place, let the team know.<br /><br />Otherwise, if you\'re lost, you can find your way back to the front page using the button below.'; next(err); }); };
Add function for post requests to /refresh - A post request to refresh will trigger a manual update with the current logged in user (req.user.updateContent(callback))
routes/pages.js
Add function for post requests to /refresh
<ide><path>outes/pages.js <ide> }); <ide> <ide> // --------- User Dashboard --------- <del> app.get('/dashboard', isLoggedIn, function(req, res) { <del> User.updateContent(req.user._id, function(err, posts) { <del> if (err) return next(err); // An error occurred <del> }); <del> <add> app.get('/dashboard', isLoggedIn, function(req, res) { <ide> res.render('dashboard', { <ide> // Add other connection fields here <ide> connected: req.user.facebook.profileId !== undefined, <del> facebook: req.user.facebook.posts <add> facebookPosts: req.user.facebook.posts <add> }); <add> }); <add> <add> app.post('/refresh', isLoggedIn, function(req, res) { <add> req.user.updateContent(function(err, posts) { <add> if (err) <add> { <add> return res.status(500).send({ <add> message: 'Encountered an error. Please try again in a few minutes.' <add> }); <add> } <add> else if (posts) <add> { <add> return res.status(200).send({ <add> message: 'New posts have come in!', <add> refresh: true <add> }); <add> } <add> else <add> { <add> return res.status(200).send({ <add> message: 'No new posts.', <add> refresh: false <add> }); <add> } <ide> }); <ide> }); <ide>
Java
apache-2.0
fa4b63924bd63ee67e1114f7cfebb65bb93faf2e
0
mglukhikh/intellij-community,ibinti/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,xfournet/intellij-community,semonte/intellij-community,hurricup/intellij-community,ibinti/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,allotria/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,semonte/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,signed/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,asedunov/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,FHannes/intellij-community,da1z/intellij-community,da1z/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,xfournet/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,ibinti/intellij-community,ibinti/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,signed/intellij-community,FHannes/intellij-community,hurricup/intellij-community,allotria/intellij-community,signed/intellij-community,asedunov/intellij-community,asedunov/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,apixandru/intellij-community,fitermay/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,apixandru/intellij-community,retomerz/intellij-community,ibinti/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,retomerz/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,youdonghai/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,apixandru/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,ibinti/intellij-community,apixandru/intellij-community,fitermay/intellij-community,ibinti/intellij-community,asedunov/intellij-community,allotria/intellij-community,ibinti/intellij-community,semonte/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,ibinti/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,fitermay/intellij-community,signed/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,da1z/intellij-community,asedunov/intellij-community,retomerz/intellij-community,semonte/intellij-community,asedunov/intellij-community,xfournet/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,signed/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,da1z/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,semonte/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,FHannes/intellij-community,apixandru/intellij-community,semonte/intellij-community,apixandru/intellij-community,signed/intellij-community,retomerz/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,kdwink/intellij-community,allotria/intellij-community,xfournet/intellij-community,apixandru/intellij-community,signed/intellij-community,FHannes/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,hurricup/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,asedunov/intellij-community,FHannes/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,da1z/intellij-community,retomerz/intellij-community,allotria/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,da1z/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,FHannes/intellij-community,fitermay/intellij-community,xfournet/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,da1z/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,retomerz/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,xfournet/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,signed/intellij-community,allotria/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,kdwink/intellij-community,xfournet/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,hurricup/intellij-community
/* * Copyright 2000-2014 JetBrains s.r.o. * * 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. */ package com.jetbrains.python.refactoring; import com.google.common.collect.Sets; import com.intellij.codeInsight.controlflow.ControlFlow; import com.intellij.codeInsight.controlflow.ControlFlowUtil; import com.intellij.codeInsight.controlflow.Instruction; import com.intellij.openapi.util.Comparing; import com.intellij.psi.PsiElement; import com.intellij.util.Function; import com.jetbrains.python.codeInsight.controlflow.ControlFlowCache; import com.jetbrains.python.codeInsight.controlflow.ReadWriteInstruction; import com.jetbrains.python.codeInsight.controlflow.ScopeOwner; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyAugAssignmentStatementNavigator; import com.intellij.psi.util.QualifiedName; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * @author Dennis.Ushakov */ public class PyDefUseUtil { private PyDefUseUtil() { } @NotNull public static List<ReadWriteInstruction> getLatestDefs(ScopeOwner block, String varName, PsiElement anchor, boolean acceptTypeAssertions) { final ControlFlow controlFlow = ControlFlowCache.getControlFlow(block); final Instruction[] instructions = controlFlow.getInstructions(); final PyAugAssignmentStatement augAssignment = PyAugAssignmentStatementNavigator.getStatementByTarget(anchor); if (augAssignment != null) { anchor = augAssignment; } int instr = ControlFlowUtil.findInstructionNumberByElement(instructions, anchor); if (instr < 0) { return Collections.emptyList(); } if (anchor instanceof PyTargetExpression) { Collection<Instruction> pred = instructions[instr].allPred(); if (!pred.isEmpty()) { instr = pred.iterator().next().num(); } } final Collection<ReadWriteInstruction> result = getLatestDefs(varName, instructions, instr, acceptTypeAssertions); return new ArrayList<ReadWriteInstruction>(result); } private static Collection<ReadWriteInstruction> getLatestDefs(final String varName, final Instruction[] instructions, final int instr, final boolean acceptTypeAssertions) { final Collection<ReadWriteInstruction> result = new LinkedHashSet<ReadWriteInstruction>(); ControlFlowUtil.iteratePrev(instr, instructions, new Function<Instruction, ControlFlowUtil.Operation>() { @Override public ControlFlowUtil.Operation fun(Instruction instruction) { if (instruction instanceof ReadWriteInstruction) { final ReadWriteInstruction rwInstruction = (ReadWriteInstruction)instruction; final PsiElement element = instruction.getElement(); final ReadWriteInstruction.ACCESS access = rwInstruction.getAccess(); if (access.isWriteAccess() || acceptTypeAssertions && access.isAssertTypeAccess()) { final String name = elementName(element); if (Comparing.strEqual(name, varName)) { result.add(rwInstruction); return ControlFlowUtil.Operation.CONTINUE; } } } return ControlFlowUtil.Operation.NEXT; } }); return result; } @Nullable private static String elementName(PsiElement element) { if (element instanceof PyImportElement) { return ((PyImportElement) element).getVisibleName(); } if (element instanceof PyReferenceExpression) { final QualifiedName qname = ((PyReferenceExpression)element).asQualifiedName(); if (qname != null) { return qname.toString(); } } return element instanceof PyElement ? ((PyElement)element).getName() : null; } @NotNull public static PsiElement[] getPostRefs(ScopeOwner block, PyTargetExpression var, PyExpression anchor) { final ControlFlow controlFlow = ControlFlowCache.getControlFlow(block); final Instruction[] instructions = controlFlow.getInstructions(); final int instr = ControlFlowUtil.findInstructionNumberByElement(instructions, anchor); if (instr < 0) { return new PyElement[0]; } final boolean[] visited = new boolean[instructions.length]; final Collection<PyElement> result = Sets.newHashSet(); for (Instruction instruction : instructions[instr].allSucc()) { getPostRefs(var, instructions, instruction.num(), visited, result); } return result.toArray(new PyElement[result.size()]); } private static void getPostRefs(PyTargetExpression var, Instruction[] instructions, int instr, boolean[] visited, Collection<PyElement> result) { // TODO: Use ControlFlowUtil.process() for forwards CFG traversal if (visited[instr]) return; visited[instr] = true; if (instructions[instr] instanceof ReadWriteInstruction) { final ReadWriteInstruction instruction = (ReadWriteInstruction)instructions[instr]; final PsiElement element = instruction.getElement(); String name = elementName(element); if (Comparing.strEqual(name, var.getName())) { final ReadWriteInstruction.ACCESS access = instruction.getAccess(); if (access.isWriteAccess()) { return; } result.add((PyElement)instruction.getElement()); } } for (Instruction instruction : instructions[instr].allSucc()) { getPostRefs(var, instructions, instruction.num(), visited, result); } } public static class InstructionNotFoundException extends RuntimeException { } }
python/src/com/jetbrains/python/refactoring/PyDefUseUtil.java
/* * Copyright 2000-2014 JetBrains s.r.o. * * 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. */ package com.jetbrains.python.refactoring; import com.google.common.collect.Sets; import com.intellij.codeInsight.controlflow.ControlFlow; import com.intellij.codeInsight.controlflow.ControlFlowUtil; import com.intellij.codeInsight.controlflow.Instruction; import com.intellij.openapi.util.Comparing; import com.intellij.psi.PsiElement; import com.intellij.util.Function; import com.jetbrains.python.codeInsight.controlflow.ControlFlowCache; import com.jetbrains.python.codeInsight.controlflow.ReadWriteInstruction; import com.jetbrains.python.codeInsight.controlflow.ScopeOwner; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyAugAssignmentStatementNavigator; import com.intellij.psi.util.QualifiedName; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * @author Dennis.Ushakov */ public class PyDefUseUtil { private PyDefUseUtil() { } @NotNull public static List<ReadWriteInstruction> getLatestDefs(ScopeOwner block, String varName, PsiElement anchor, boolean acceptTypeAssertions) { final ControlFlow controlFlow = ControlFlowCache.getControlFlow(block); final Instruction[] instructions = controlFlow.getInstructions(); final PyAugAssignmentStatement augAssignment = PyAugAssignmentStatementNavigator.getStatementByTarget(anchor); if (augAssignment != null) { anchor = augAssignment; } int instr = ControlFlowUtil.findInstructionNumberByElement(instructions, anchor); if (instr < 0) { return Collections.emptyList(); } if (anchor instanceof PyTargetExpression) { Collection<Instruction> pred = instructions[instr].allPred(); if (!pred.isEmpty()) { instr = pred.iterator().next().num(); } } final Collection<ReadWriteInstruction> result = getLatestDefs(varName, instructions, instr, acceptTypeAssertions); return new ArrayList<ReadWriteInstruction>(result); } private static Collection<ReadWriteInstruction> getLatestDefs(final String varName, final Instruction[] instructions, final int instr, final boolean acceptTypeAssertions) { final Collection<ReadWriteInstruction> result = new LinkedHashSet<ReadWriteInstruction>(); ControlFlowUtil.iteratePrev(instr, instructions, new Function<Instruction, ControlFlowUtil.Operation>() { @Override public ControlFlowUtil.Operation fun(Instruction instruction) { if (instruction instanceof ReadWriteInstruction) { final ReadWriteInstruction rwInstruction = (ReadWriteInstruction)instruction; final PsiElement element = instruction.getElement(); final String name = elementName(element); final ReadWriteInstruction.ACCESS access = rwInstruction.getAccess(); if ((access.isWriteAccess() || (acceptTypeAssertions && access.isAssertTypeAccess())) && Comparing.strEqual(name, varName)) { result.add(rwInstruction); return ControlFlowUtil.Operation.CONTINUE; } } return ControlFlowUtil.Operation.NEXT; } }); return result; } @Nullable private static String elementName(PsiElement element) { if (element instanceof PyImportElement) { return ((PyImportElement) element).getVisibleName(); } if (element instanceof PyReferenceExpression) { final QualifiedName qname = ((PyReferenceExpression)element).asQualifiedName(); if (qname != null) { return qname.toString(); } } return element instanceof PyElement ? ((PyElement)element).getName() : null; } @NotNull public static PsiElement[] getPostRefs(ScopeOwner block, PyTargetExpression var, PyExpression anchor) { final ControlFlow controlFlow = ControlFlowCache.getControlFlow(block); final Instruction[] instructions = controlFlow.getInstructions(); final int instr = ControlFlowUtil.findInstructionNumberByElement(instructions, anchor); if (instr < 0) { return new PyElement[0]; } final boolean[] visited = new boolean[instructions.length]; final Collection<PyElement> result = Sets.newHashSet(); for (Instruction instruction : instructions[instr].allSucc()) { getPostRefs(var, instructions, instruction.num(), visited, result); } return result.toArray(new PyElement[result.size()]); } private static void getPostRefs(PyTargetExpression var, Instruction[] instructions, int instr, boolean[] visited, Collection<PyElement> result) { // TODO: Use ControlFlowUtil.process() for forwards CFG traversal if (visited[instr]) return; visited[instr] = true; if (instructions[instr] instanceof ReadWriteInstruction) { final ReadWriteInstruction instruction = (ReadWriteInstruction)instructions[instr]; final PsiElement element = instruction.getElement(); String name = elementName(element); if (Comparing.strEqual(name, var.getName())) { final ReadWriteInstruction.ACCESS access = instruction.getAccess(); if (access.isWriteAccess()) { return; } result.add((PyElement)instruction.getElement()); } } for (Instruction instruction : instructions[instr].allSucc()) { getPostRefs(var, instructions, instruction.num(), visited, result); } } public static class InstructionNotFoundException extends RuntimeException { } }
Get element name only when we need it for better performance (PY-17508)
python/src/com/jetbrains/python/refactoring/PyDefUseUtil.java
Get element name only when we need it for better performance (PY-17508)
<ide><path>ython/src/com/jetbrains/python/refactoring/PyDefUseUtil.java <ide> if (instruction instanceof ReadWriteInstruction) { <ide> final ReadWriteInstruction rwInstruction = (ReadWriteInstruction)instruction; <ide> final PsiElement element = instruction.getElement(); <del> final String name = elementName(element); <ide> final ReadWriteInstruction.ACCESS access = rwInstruction.getAccess(); <del> if ((access.isWriteAccess() || (acceptTypeAssertions && access.isAssertTypeAccess())) && <del> Comparing.strEqual(name, varName)) { <del> result.add(rwInstruction); <del> return ControlFlowUtil.Operation.CONTINUE; <add> if (access.isWriteAccess() || acceptTypeAssertions && access.isAssertTypeAccess()) { <add> final String name = elementName(element); <add> if (Comparing.strEqual(name, varName)) { <add> result.add(rwInstruction); <add> return ControlFlowUtil.Operation.CONTINUE; <add> } <ide> } <ide> } <ide> return ControlFlowUtil.Operation.NEXT;
Java
apache-2.0
008b791b7dc00b93aeb2872db8527b5abbf14d16
0
apixandru/intellij-community,allotria/intellij-community,suncycheng/intellij-community,da1z/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,asedunov/intellij-community,xfournet/intellij-community,apixandru/intellij-community,apixandru/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,semonte/intellij-community,semonte/intellij-community,signed/intellij-community,ibinti/intellij-community,fitermay/intellij-community,semonte/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,signed/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,semonte/intellij-community,da1z/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,asedunov/intellij-community,allotria/intellij-community,da1z/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,allotria/intellij-community,fitermay/intellij-community,xfournet/intellij-community,semonte/intellij-community,FHannes/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,asedunov/intellij-community,asedunov/intellij-community,semonte/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,ibinti/intellij-community,signed/intellij-community,signed/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,signed/intellij-community,fitermay/intellij-community,apixandru/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,da1z/intellij-community,xfournet/intellij-community,allotria/intellij-community,allotria/intellij-community,signed/intellij-community,ibinti/intellij-community,fitermay/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,da1z/intellij-community,FHannes/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,semonte/intellij-community,signed/intellij-community,ibinti/intellij-community,allotria/intellij-community,FHannes/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,ibinti/intellij-community,xfournet/intellij-community,asedunov/intellij-community,da1z/intellij-community,xfournet/intellij-community,asedunov/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,semonte/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,allotria/intellij-community,allotria/intellij-community,asedunov/intellij-community,xfournet/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,semonte/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,allotria/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,fitermay/intellij-community,apixandru/intellij-community,allotria/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community
package com.intellij.vcs.log.ui.render; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.ui.GraphicsConfig; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.vcs.changes.issueLinks.IssueLinkRenderer; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.ColoredTableCellRenderer; import com.intellij.ui.SimpleTextAttributes; import com.intellij.ui.TableCell; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.GraphicsUtil; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import com.intellij.vcs.log.VcsRef; import com.intellij.vcs.log.data.VcsLogData; import com.intellij.vcs.log.graph.PrintElement; import com.intellij.vcs.log.graph.VisibleGraph; import com.intellij.vcs.log.paint.GraphCellPainter; import com.intellij.vcs.log.paint.PaintParameters; import com.intellij.vcs.log.ui.frame.VcsLogGraphTable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.util.Collection; public class GraphCommitCellRenderer extends ColoredTableCellRenderer { private static final Logger LOG = Logger.getInstance(GraphCommitCellRenderer.class); private static final int MAX_GRAPH_WIDTH = 10; private static final int VERTICAL_PADDING = JBUI.scale(7); @NotNull private final VcsLogData myLogData; @NotNull private final GraphCellPainter myPainter; @NotNull private final VcsLogGraphTable myGraphTable; @NotNull private final IssueLinkRenderer myIssueLinkRenderer; @NotNull private final ReferencePainter myReferencePainter = isRedesignedLabels() ? new LabelPainter() : new RectangleReferencePainter(); @Nullable private final FadeOutPainter myFadeOutPainter = isRedesignedLabels() ? new FadeOutPainter() : null; @Nullable private PaintInfo myGraphImage; @NotNull private Font myFont; private int myHeight; private boolean myExpanded; public GraphCommitCellRenderer(@NotNull VcsLogData logData, @NotNull GraphCellPainter painter, @NotNull VcsLogGraphTable table) { myLogData = logData; myPainter = painter; myGraphTable = table; myIssueLinkRenderer = new IssueLinkRenderer(myLogData.getProject(), this); myFont = RectanglePainter.getFont(); myHeight = calculateHeight(); } @NotNull @Override public Dimension getPreferredSize() { Dimension preferredSize = super.getPreferredSize(); return new Dimension(preferredSize.width + (myReferencePainter.isLeftAligned() ? 0 : myReferencePainter.getSize().width - LabelPainter.GRADIENT_WIDTH), getPreferredHeight()); } public int getPreferredHeight() { Font font = RectanglePainter.getFont(); if (myFont != font) { myFont = font; myHeight = calculateHeight(); } return myHeight; } private int calculateHeight() { return Math.max(myReferencePainter.getSize().height, getFontMetrics(myFont).getHeight() + VERTICAL_PADDING); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); int graphImageWidth = (myGraphImage != null) ? myGraphImage.getWidth() : 0; if (!myReferencePainter.isLeftAligned()) { int start = Math.max(graphImageWidth, getWidth() - myReferencePainter.getSize().width); myReferencePainter.paint((Graphics2D)g, start, 0, getHeight()); } else { myReferencePainter.paint((Graphics2D)g, graphImageWidth, 0, getHeight()); } if (myFadeOutPainter != null) { if (!myExpanded) { int start = Math.max(graphImageWidth, getWidth() - myFadeOutPainter.getWidth()); myFadeOutPainter.paint((Graphics2D)g, start, 0, getHeight()); } } if (myGraphImage != null) { UIUtil.drawImage(g, myGraphImage.getImage(), 0, 0, null); } else { // TODO temporary diagnostics: why does graph sometimes disappear LOG.error("Image is null"); } } @Override protected void customizeCellRenderer(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (value == null) { return; } GraphCommitCell cell = getAssertCommitCell(value); myGraphImage = getGraphImage(row); int graphPadding; if (myGraphImage != null) { graphPadding = myGraphImage.getWidth(); if (graphPadding < 2) { // TODO temporary diagnostics: why does graph sometimes disappear LOG.error("Too small image width: " + graphPadding); } } else { graphPadding = 0; } SimpleTextAttributes style = myGraphTable.applyHighlighters(this, row, column, "", hasFocus, isSelected); Collection<VcsRef> refs = cell.getRefsToThisCommit(); Color foreground = ObjectUtils.assertNotNull(myGraphTable.getBaseStyle(row, column, "", hasFocus, isSelected).getForeground()); myExpanded = myGraphTable.getExpandableItemsHandler().getExpandedItems().contains(new TableCell(row, column)); if (myFadeOutPainter != null) { myFadeOutPainter.customize(refs, row, column, table, foreground); } customizeRefsPainter(myReferencePainter, refs, foreground); setBorder(null); append(""); appendTextPadding(graphPadding + (myReferencePainter.isLeftAligned() ? myReferencePainter.getSize().width : 0)); myIssueLinkRenderer.appendTextWithLinks(cell.getText(), style); } private void customizeRefsPainter(@NotNull ReferencePainter painter, @NotNull Collection<VcsRef> refs, @NotNull Color foreground) { if (!refs.isEmpty()) { VirtualFile root = ObjectUtils.assertNotNull(ContainerUtil.getFirstItem(refs)).getRoot(); painter.customizePainter(this, refs, myLogData.getLogProvider(root).getReferenceManager(), getBackground(), foreground); } else { painter.customizePainter(this, refs, null, getBackground(), foreground); } } @Nullable private PaintInfo getGraphImage(int row) { VisibleGraph<Integer> graph = myGraphTable.getVisibleGraph(); Collection<? extends PrintElement> printElements = graph.getRowInfo(row).getPrintElements(); int maxIndex = 0; for (PrintElement printElement : printElements) { maxIndex = Math.max(maxIndex, printElement.getPositionInCurrentRow()); } maxIndex++; maxIndex = Math.max(maxIndex, Math.min(MAX_GRAPH_WIDTH, graph.getRecommendedWidth())); final BufferedImage image = UIUtil .createImage(PaintParameters.getNodeWidth(myGraphTable.getRowHeight()) * (maxIndex + 4), myGraphTable.getRowHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); myPainter.draw(g2, printElements); int width = maxIndex * PaintParameters.getNodeWidth(myGraphTable.getRowHeight()); return new PaintInfo(image, width); } private static GraphCommitCell getAssertCommitCell(Object value) { assert value instanceof GraphCommitCell : "Value of incorrect class was supplied: " + value; return (GraphCommitCell)value; } public static boolean isRedesignedLabels() { return Registry.is("vcs.log.labels.redesign"); } private static class PaintInfo { private int myWidth; @NotNull private Image myImage; PaintInfo(@NotNull Image image, int width) { myImage = image; myWidth = width; } @NotNull Image getImage() { return myImage; } /** * Returns the "interesting" width of the painted image, i.e. the width which the text in the table should be offset by. <br/> * It can be smaller than the width of {@link #getImage() the image}, because we allow the text to cover part of the graph * (some diagonal edges, etc.) */ int getWidth() { return myWidth; } } private class FadeOutPainter { @NotNull private final LabelPainter myEmptyPainter = new LabelPainter(); private int myWidth = LabelPainter.GRADIENT_WIDTH; public void customize(@NotNull Collection<VcsRef> currentRefs, int row, int column, @NotNull JTable table, @NotNull Color foreground) { myWidth = 0; if (currentRefs.isEmpty()) { int prevWidth = 0; if (row > 0) { GraphCommitCell commitCell = getAssertCommitCell(table.getValueAt(row - 1, column)); customizeRefsPainter(myEmptyPainter, commitCell.getRefsToThisCommit(), foreground); prevWidth = myEmptyPainter.getSize().width; } int nextWidth = 0; if (row < table.getRowCount() - 1) { GraphCommitCell commitCell = getAssertCommitCell(table.getValueAt(row + 1, column)); customizeRefsPainter(myEmptyPainter, commitCell.getRefsToThisCommit(), foreground); nextWidth = myEmptyPainter.getSize().width; } myWidth = Math.max(Math.max(prevWidth, nextWidth), LabelPainter.GRADIENT_WIDTH); } } public void paint(@NotNull Graphics2D g2, int x, int y, int height) { GraphicsConfig config = GraphicsUtil.setupAAPainting(g2); myEmptyPainter.paintFadeOut(g2, x, y, myWidth, height); config.restore(); } public int getWidth() { return myWidth; } } }
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/GraphCommitCellRenderer.java
package com.intellij.vcs.log.ui.render; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.ui.GraphicsConfig; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.vcs.changes.issueLinks.IssueLinkRenderer; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.ColoredTableCellRenderer; import com.intellij.ui.SimpleTextAttributes; import com.intellij.ui.TableCell; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.GraphicsUtil; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import com.intellij.vcs.log.VcsRef; import com.intellij.vcs.log.data.VcsLogData; import com.intellij.vcs.log.graph.PrintElement; import com.intellij.vcs.log.graph.VisibleGraph; import com.intellij.vcs.log.paint.GraphCellPainter; import com.intellij.vcs.log.paint.PaintParameters; import com.intellij.vcs.log.ui.frame.VcsLogGraphTable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.util.Collection; public class GraphCommitCellRenderer extends ColoredTableCellRenderer { private static final Logger LOG = Logger.getInstance(GraphCommitCellRenderer.class); private static final int MAX_GRAPH_WIDTH = 10; private static final int VERTICAL_PADDING = JBUI.scale(7); @NotNull private final VcsLogData myLogData; @NotNull private final GraphCellPainter myPainter; @NotNull private final VcsLogGraphTable myGraphTable; @NotNull private final IssueLinkRenderer myIssueLinkRenderer; @NotNull private final ReferencePainter myReferencePainter = isRedesignedLabels() ? new LabelPainter() : new RectangleReferencePainter(); @Nullable private final FadeOutPainter myFadeOutPainter = isRedesignedLabels() ? new FadeOutPainter() : null; @Nullable private PaintInfo myGraphImage; @NotNull private Font myFont; private int myHeight; private boolean myExpanded; public GraphCommitCellRenderer(@NotNull VcsLogData logData, @NotNull GraphCellPainter painter, @NotNull VcsLogGraphTable table) { myLogData = logData; myPainter = painter; myGraphTable = table; myIssueLinkRenderer = new IssueLinkRenderer(myLogData.getProject(), this); myFont = RectanglePainter.getFont(); myHeight = calculateHeight(); } @NotNull @Override public Dimension getPreferredSize() { Dimension preferredSize = super.getPreferredSize(); return new Dimension(preferredSize.width + (myReferencePainter.isLeftAligned() ? 0 : myReferencePainter.getSize().width), getPreferredHeight()); } public int getPreferredHeight() { Font font = RectanglePainter.getFont(); if (myFont != font) { myFont = font; myHeight = calculateHeight(); } return myHeight; } private int calculateHeight() { return Math.max(myReferencePainter.getSize().height, getFontMetrics(myFont).getHeight() + VERTICAL_PADDING); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); int graphImageWidth = (myGraphImage != null) ? myGraphImage.getWidth() : 0; if (!myReferencePainter.isLeftAligned()) { int start = Math.max(graphImageWidth, getWidth() - myReferencePainter.getSize().width); myReferencePainter.paint((Graphics2D)g, start, 0, getHeight()); } else { myReferencePainter.paint((Graphics2D)g, graphImageWidth, 0, getHeight()); } if (myFadeOutPainter != null) { if (!myExpanded) { int start = Math.max(graphImageWidth, getWidth() - myFadeOutPainter.getWidth()); myFadeOutPainter.paint((Graphics2D)g, start, 0, getHeight()); } } if (myGraphImage != null) { UIUtil.drawImage(g, myGraphImage.getImage(), 0, 0, null); } else { // TODO temporary diagnostics: why does graph sometimes disappear LOG.error("Image is null"); } } @Override protected void customizeCellRenderer(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (value == null) { return; } GraphCommitCell cell = getAssertCommitCell(value); myGraphImage = getGraphImage(row); int graphPadding; if (myGraphImage != null) { graphPadding = myGraphImage.getWidth(); if (graphPadding < 2) { // TODO temporary diagnostics: why does graph sometimes disappear LOG.error("Too small image width: " + graphPadding); } } else { graphPadding = 0; } SimpleTextAttributes style = myGraphTable.applyHighlighters(this, row, column, "", hasFocus, isSelected); Collection<VcsRef> refs = cell.getRefsToThisCommit(); Color foreground = ObjectUtils.assertNotNull(myGraphTable.getBaseStyle(row, column, "", hasFocus, isSelected).getForeground()); myExpanded = myGraphTable.getExpandableItemsHandler().getExpandedItems().contains(new TableCell(row, column)); if (myFadeOutPainter != null) { myFadeOutPainter.customize(refs, row, column, table, foreground); } customizeRefsPainter(myReferencePainter, refs, foreground); setBorder(null); append(""); appendTextPadding(graphPadding + (myReferencePainter.isLeftAligned() ? myReferencePainter.getSize().width : 0)); myIssueLinkRenderer.appendTextWithLinks(cell.getText(), style); } private void customizeRefsPainter(@NotNull ReferencePainter painter, @NotNull Collection<VcsRef> refs, @NotNull Color foreground) { if (!refs.isEmpty()) { VirtualFile root = ObjectUtils.assertNotNull(ContainerUtil.getFirstItem(refs)).getRoot(); painter.customizePainter(this, refs, myLogData.getLogProvider(root).getReferenceManager(), getBackground(), foreground); } else { painter.customizePainter(this, refs, null, getBackground(), foreground); } } @Nullable private PaintInfo getGraphImage(int row) { VisibleGraph<Integer> graph = myGraphTable.getVisibleGraph(); Collection<? extends PrintElement> printElements = graph.getRowInfo(row).getPrintElements(); int maxIndex = 0; for (PrintElement printElement : printElements) { maxIndex = Math.max(maxIndex, printElement.getPositionInCurrentRow()); } maxIndex++; maxIndex = Math.max(maxIndex, Math.min(MAX_GRAPH_WIDTH, graph.getRecommendedWidth())); final BufferedImage image = UIUtil .createImage(PaintParameters.getNodeWidth(myGraphTable.getRowHeight()) * (maxIndex + 4), myGraphTable.getRowHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); myPainter.draw(g2, printElements); int width = maxIndex * PaintParameters.getNodeWidth(myGraphTable.getRowHeight()); return new PaintInfo(image, width); } private static GraphCommitCell getAssertCommitCell(Object value) { assert value instanceof GraphCommitCell : "Value of incorrect class was supplied: " + value; return (GraphCommitCell)value; } public static boolean isRedesignedLabels() { return Registry.is("vcs.log.labels.redesign"); } private static class PaintInfo { private int myWidth; @NotNull private Image myImage; PaintInfo(@NotNull Image image, int width) { myImage = image; myWidth = width; } @NotNull Image getImage() { return myImage; } /** * Returns the "interesting" width of the painted image, i.e. the width which the text in the table should be offset by. <br/> * It can be smaller than the width of {@link #getImage() the image}, because we allow the text to cover part of the graph * (some diagonal edges, etc.) */ int getWidth() { return myWidth; } } private class FadeOutPainter { @NotNull private final LabelPainter myEmptyPainter = new LabelPainter(); private int myWidth = LabelPainter.GRADIENT_WIDTH; public void customize(@NotNull Collection<VcsRef> currentRefs, int row, int column, @NotNull JTable table, @NotNull Color foreground) { myWidth = 0; if (currentRefs.isEmpty()) { int prevWidth = 0; if (row > 0) { GraphCommitCell commitCell = getAssertCommitCell(table.getValueAt(row - 1, column)); customizeRefsPainter(myEmptyPainter, commitCell.getRefsToThisCommit(), foreground); prevWidth = myEmptyPainter.getSize().width; } int nextWidth = 0; if (row < table.getRowCount() - 1) { GraphCommitCell commitCell = getAssertCommitCell(table.getValueAt(row + 1, column)); customizeRefsPainter(myEmptyPainter, commitCell.getRefsToThisCommit(), foreground); nextWidth = myEmptyPainter.getSize().width; } myWidth = Math.max(Math.max(prevWidth, nextWidth), LabelPainter.GRADIENT_WIDTH); } } public void paint(@NotNull Graphics2D g2, int x, int y, int height) { GraphicsConfig config = GraphicsUtil.setupAAPainting(g2); myEmptyPainter.paintFadeOut(g2, x, y, myWidth, height); config.restore(); } public int getWidth() { return myWidth; } } }
[vcs-log] fix commit cell width in expanded mode
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/GraphCommitCellRenderer.java
[vcs-log] fix commit cell width in expanded mode
<ide><path>latform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/GraphCommitCellRenderer.java <ide> @Override <ide> public Dimension getPreferredSize() { <ide> Dimension preferredSize = super.getPreferredSize(); <del> return new Dimension(preferredSize.width + (myReferencePainter.isLeftAligned() ? 0 : myReferencePainter.getSize().width), <add> return new Dimension(preferredSize.width + (myReferencePainter.isLeftAligned() ? 0 : <add> myReferencePainter.getSize().width - LabelPainter.GRADIENT_WIDTH), <ide> getPreferredHeight()); <ide> } <ide>
Java
mit
5e968a51c85e8d71df676d6d3232ce74c30aaa1c
0
srbhuyan/mmdb
package com.lukti.android.mmdb.mobilemoviedatabase; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.lukti.android.mmdb.mobilemoviedatabase.data.Movie; import com.lukti.android.mmdb.mobilemoviedatabase.data.MovieRecyclerAdapter; import com.lukti.android.mmdb.mobilemoviedatabase.data.RecyclerItemClickListener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; /** * MainActivity fragment. */ public class MainActivityFragment extends Fragment { private final String LOG_TAG = MainActivityFragment.class.getSimpleName(); private ArrayList<Movie> mMovieBuffer; private RecyclerView mRecyclerView; private MovieRecyclerAdapter mMovieAdapter; private RecyclerView.LayoutManager mLayoutManager; private SharedPreferences mSharedPref; private String mSortPref; private boolean mPrefChanged; private static final int VERTICAL_SPAN_COUNT = 2; private static final int HORIZONTAL_SPAN_COUNT = 4; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if( savedInstanceState != null ){ mMovieBuffer = savedInstanceState.getParcelableArrayList(getString(R.string.movie_object_key)); }else{ mMovieBuffer = new ArrayList<Movie>(); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelableArrayList(getString(R.string.movie_object_key), mMovieBuffer); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRecyclerView = (RecyclerView)inflater.inflate(R.layout.fragment_main, container, false); mRecyclerView.setHasFixedSize(true); int spanCount = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ? VERTICAL_SPAN_COUNT : HORIZONTAL_SPAN_COUNT; mLayoutManager = new GridLayoutManager(getActivity(), spanCount, GridLayoutManager.VERTICAL, false); mRecyclerView.setLayoutManager(mLayoutManager); mMovieAdapter = new MovieRecyclerAdapter(getActivity(), mMovieBuffer); mRecyclerView.setAdapter(mMovieAdapter); mRecyclerView.addOnItemTouchListener( new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Movie movie = mMovieAdapter.getItem(position); Intent intent = new Intent(getActivity(), DetailActivity.class).putExtra(getString(R.string.movie_object_key), movie); startActivity(intent); } } )); mSharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity()); return mRecyclerView; } @Override public void onStart() { super.onStart(); String sortPref = mSharedPref.getString(getString(R.string.pref_movie_sort_order_key), getString(R.string.sort_order_value_most_popular)); mPrefChanged = sortPref.equals(mSortPref) ? false : true; if( mMovieBuffer.size() == 0 || mPrefChanged ) fetchMovieData(); } @Override public void onPause() { super.onPause(); mSortPref = mSharedPref.getString(getString(R.string.pref_movie_sort_order_key), getString(R.string.sort_order_value_most_popular)); } private void fetchMovieData(){ new FetchMovieTask().execute(mSharedPref.getString(getString(R.string.pref_movie_sort_order_key), getString(R.string.sort_order_value_most_popular))); } /** * FetchMovieTask AsyncTask to fetch the movie data */ public class FetchMovieTask extends AsyncTask<String, Void, ArrayList<Movie>> { private final String LOG_TAG = FetchMovieTask.class.getSimpleName(); private String buildFullPosterPath(String partialPath){ Uri builtUri = Uri.parse(getString(R.string.TMD_POSTER_BASE_URL)).buildUpon() .appendPath(getString(R.string.TMD_POSTER_SIZE)) .appendEncodedPath(partialPath) .build(); return builtUri.toString(); } private ArrayList<Movie> getMoviesFromJson(String movieJsonStr) throws JSONException { JSONObject movieJson = new JSONObject(movieJsonStr); JSONArray movieArray = movieJson.getJSONArray(getString(R.string.TMD_RESULT)); ArrayList<Movie> movies = new ArrayList<Movie>(); for(int i = 0; i < movieArray.length(); i++) { JSONObject movie = movieArray.getJSONObject(i); movies.add(new Movie( movie.getString(getString(R.string.TMD_TITLE)), buildFullPosterPath(movie.getString(getString(R.string.TMD_POSTER))), movie.getString(getString(R.string.TMD_PLOT)), movie.getString(getString(R.string.TMD_RELEASE_DATE)), movie.getDouble(getString(R.string.TMD_RATING)), movie.getDouble(getString(R.string.TMD_POPULARITY)) )); } return movies; } protected ArrayList<Movie> doInBackground(String... params){ HttpURLConnection urlConnection = null; BufferedReader reader = null; String movieJsonStr = null; try { Uri builtUri = Uri.parse(getString(R.string.TMD_BASE_URL)).buildUpon() .appendQueryParameter(getString(R.string.TMD_SORT), params[0]) .appendQueryParameter(getString(R.string.TMD_API_KEY), BuildConfig.THE_MOVIE_DB_API_KEY) .build(); URL url = new URL(builtUri.toString()); //Log.v(LOG_TAG, "Built URI " + builtUri.toString()); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); if (inputStream == null) { return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuffer buffer = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { buffer.append(line + "\n"); } if (buffer.length() == 0) { return null; } movieJsonStr = buffer.toString(); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); return null; } finally{ if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } try { return getMoviesFromJson(movieJsonStr); }catch(JSONException e){ Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } return null; } @Override protected void onPostExecute(ArrayList<Movie> movies) { super.onPostExecute(movies); if( movies != null ) { if( mPrefChanged ) mMovieBuffer.clear(); mMovieBuffer.addAll(movies); mMovieAdapter.notifyDataSetChanged(); } } } }
app/src/main/java/com/lukti/android/mmdb/mobilemoviedatabase/MainActivityFragment.java
package com.lukti.android.mmdb.mobilemoviedatabase; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.lukti.android.mmdb.mobilemoviedatabase.data.Movie; import com.lukti.android.mmdb.mobilemoviedatabase.data.MovieRecyclerAdapter; import com.lukti.android.mmdb.mobilemoviedatabase.data.RecyclerItemClickListener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; /** * MainActivity fragment. */ public class MainActivityFragment extends Fragment { private final String LOG_TAG = MainActivityFragment.class.getSimpleName(); private ArrayList<Movie> mMovieBuffer; private RecyclerView mRecyclerView; private MovieRecyclerAdapter mMovieAdapter; private RecyclerView.LayoutManager mLayoutManager; private static final int VERTICAL_SPAN_COUNT = 2; private static final int HORIZONTAL_SPAN_COUNT = 4; public MainActivityFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if( savedInstanceState != null ){ mMovieBuffer = savedInstanceState.getParcelableArrayList(getString(R.string.movie_object_key)); }else{ mMovieBuffer = new ArrayList<Movie>(); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelableArrayList(getString(R.string.movie_object_key), mMovieBuffer); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRecyclerView = (RecyclerView)inflater.inflate(R.layout.fragment_main, container, false); mRecyclerView.setHasFixedSize(true); int spanCount = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ? VERTICAL_SPAN_COUNT : HORIZONTAL_SPAN_COUNT; mLayoutManager = new GridLayoutManager(getActivity(), spanCount, GridLayoutManager.VERTICAL, false); mRecyclerView.setLayoutManager(mLayoutManager); mMovieAdapter = new MovieRecyclerAdapter(getActivity(), mMovieBuffer); mRecyclerView.setAdapter(mMovieAdapter); mRecyclerView.addOnItemTouchListener( new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Movie movie = mMovieAdapter.getItem(position); Intent intent = new Intent(getActivity(), DetailActivity.class).putExtra(getString(R.string.movie_object_key), movie); startActivity(intent); } } )); return mRecyclerView; } private void fetchMovieData(){ if( mMovieBuffer.size() == 0 ) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); String sortPref = prefs.getString(getString(R.string.pref_movie_sort_order_key), getString(R.string.sort_order_value_most_popular)); new FetchMovieTask().execute(sortPref); } } @Override public void onStart() { super.onStart(); fetchMovieData(); } /** * FetchMovieTask AsyncTask to fetch the movie data */ public class FetchMovieTask extends AsyncTask<String, Void, ArrayList<Movie>> { private final String LOG_TAG = FetchMovieTask.class.getSimpleName(); private String buildFullPosterPath(String partialPath){ Uri builtUri = Uri.parse(getString(R.string.TMD_POSTER_BASE_URL)).buildUpon() .appendPath(getString(R.string.TMD_POSTER_SIZE)) .appendEncodedPath(partialPath) .build(); return builtUri.toString(); } private ArrayList<Movie> getMoviesFromJson(String movieJsonStr) throws JSONException { JSONObject movieJson = new JSONObject(movieJsonStr); JSONArray movieArray = movieJson.getJSONArray(getString(R.string.TMD_RESULT)); ArrayList<Movie> movies = new ArrayList<Movie>(); for(int i = 0; i < movieArray.length(); i++) { JSONObject movie = movieArray.getJSONObject(i); movies.add(new Movie( movie.getString(getString(R.string.TMD_TITLE)), buildFullPosterPath(movie.getString(getString(R.string.TMD_POSTER))), movie.getString(getString(R.string.TMD_PLOT)), movie.getString(getString(R.string.TMD_RELEASE_DATE)), movie.getDouble(getString(R.string.TMD_RATING)), movie.getDouble(getString(R.string.TMD_POPULARITY)) )); } return movies; } protected ArrayList<Movie> doInBackground(String... params){ HttpURLConnection urlConnection = null; BufferedReader reader = null; String movieJsonStr = null; try { Uri builtUri = Uri.parse(getString(R.string.TMD_BASE_URL)).buildUpon() .appendQueryParameter(getString(R.string.TMD_SORT), params[0]) .appendQueryParameter(getString(R.string.TMD_API_KEY), BuildConfig.THE_MOVIE_DB_API_KEY) .build(); URL url = new URL(builtUri.toString()); //Log.v(LOG_TAG, "Built URI " + builtUri.toString()); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); if (inputStream == null) { return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuffer buffer = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { buffer.append(line + "\n"); } if (buffer.length() == 0) { return null; } movieJsonStr = buffer.toString(); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); return null; } finally{ if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } try { return getMoviesFromJson(movieJsonStr); }catch(JSONException e){ Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } return null; } @Override protected void onPostExecute(ArrayList<Movie> movies) { super.onPostExecute(movies); if( movies != null ) { mMovieBuffer.addAll(movies); mMovieAdapter.notifyDataSetChanged(); } } } }
Sort preference working
app/src/main/java/com/lukti/android/mmdb/mobilemoviedatabase/MainActivityFragment.java
Sort preference working
<ide><path>pp/src/main/java/com/lukti/android/mmdb/mobilemoviedatabase/MainActivityFragment.java <ide> private MovieRecyclerAdapter mMovieAdapter; <ide> private RecyclerView.LayoutManager mLayoutManager; <ide> <add> private SharedPreferences mSharedPref; <add> private String mSortPref; <add> private boolean mPrefChanged; <add> <ide> private static final int VERTICAL_SPAN_COUNT = 2; <ide> private static final int HORIZONTAL_SPAN_COUNT = 4; <del> <del> public MainActivityFragment() { <del> } <ide> <ide> @Override <ide> public void onCreate(Bundle savedInstanceState) { <ide> } <ide> )); <ide> <add> mSharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity()); <ide> return mRecyclerView; <del> } <del> <del> private void fetchMovieData(){ <del> <del> if( mMovieBuffer.size() == 0 ) { <del> SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); <del> String sortPref = prefs.getString(getString(R.string.pref_movie_sort_order_key), <del> getString(R.string.sort_order_value_most_popular)); <del> <del> new FetchMovieTask().execute(sortPref); <del> } <ide> } <ide> <ide> @Override <ide> public void onStart() { <ide> super.onStart(); <del> fetchMovieData(); <add> String sortPref = mSharedPref.getString(getString(R.string.pref_movie_sort_order_key), <add> getString(R.string.sort_order_value_most_popular)); <add> <add> mPrefChanged = sortPref.equals(mSortPref) ? false : true; <add> <add> if( mMovieBuffer.size() == 0 || mPrefChanged ) <add> fetchMovieData(); <add> } <add> <add> @Override <add> public void onPause() { <add> super.onPause(); <add> mSortPref = mSharedPref.getString(getString(R.string.pref_movie_sort_order_key), <add> getString(R.string.sort_order_value_most_popular)); <add> } <add> <add> private void fetchMovieData(){ <add> new FetchMovieTask().execute(mSharedPref.getString(getString(R.string.pref_movie_sort_order_key), <add> getString(R.string.sort_order_value_most_popular))); <ide> } <ide> <ide> /** <ide> protected void onPostExecute(ArrayList<Movie> movies) { <ide> super.onPostExecute(movies); <ide> if( movies != null ) { <add> if( mPrefChanged ) <add> mMovieBuffer.clear(); <add> <ide> mMovieBuffer.addAll(movies); <ide> mMovieAdapter.notifyDataSetChanged(); <ide> }
Java
apache-2.0
91733275e7ee02c19c286fa0f6ebe89b5f6f1bdd
0
apache/accumulo,apache/accumulo,ctubbsii/accumulo,milleruntime/accumulo,apache/accumulo,milleruntime/accumulo,apache/accumulo,apache/accumulo,milleruntime/accumulo,mjwall/accumulo,milleruntime/accumulo,mjwall/accumulo,ctubbsii/accumulo,apache/accumulo,milleruntime/accumulo,ctubbsii/accumulo,ctubbsii/accumulo,milleruntime/accumulo,mjwall/accumulo,ctubbsii/accumulo,ctubbsii/accumulo,mjwall/accumulo,milleruntime/accumulo,mjwall/accumulo,ctubbsii/accumulo,apache/accumulo,mjwall/accumulo,mjwall/accumulo
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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.apache.accumulo.miniclusterImpl; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Objects.requireNonNull; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static org.apache.accumulo.fate.util.UtilWaitThread.sleepUninterruptibly; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.URI; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Stream; import org.apache.accumulo.cluster.AccumuloCluster; import org.apache.accumulo.core.Constants; import org.apache.accumulo.core.client.Accumulo; import org.apache.accumulo.core.client.AccumuloClient; import org.apache.accumulo.core.client.AccumuloException; import org.apache.accumulo.core.client.AccumuloSecurityException; import org.apache.accumulo.core.client.security.tokens.AuthenticationToken; import org.apache.accumulo.core.clientImpl.ClientContext; import org.apache.accumulo.core.clientImpl.ManagerClient; import org.apache.accumulo.core.clientImpl.thrift.ThriftNotActiveServiceException; import org.apache.accumulo.core.clientImpl.thrift.ThriftSecurityException; import org.apache.accumulo.core.conf.AccumuloConfiguration; import org.apache.accumulo.core.conf.ClientProperty; import org.apache.accumulo.core.conf.ConfigurationCopy; import org.apache.accumulo.core.conf.DefaultConfiguration; import org.apache.accumulo.core.conf.Property; import org.apache.accumulo.core.conf.SiteConfiguration; import org.apache.accumulo.core.manager.thrift.ManagerClientService; import org.apache.accumulo.core.manager.thrift.ManagerGoalState; import org.apache.accumulo.core.manager.thrift.ManagerMonitorInfo; import org.apache.accumulo.core.trace.TraceUtil; import org.apache.accumulo.core.util.Pair; import org.apache.accumulo.fate.zookeeper.ZooReaderWriter; import org.apache.accumulo.fate.zookeeper.ZooUtil; import org.apache.accumulo.manager.state.SetGoalState; import org.apache.accumulo.minicluster.MiniAccumuloCluster; import org.apache.accumulo.minicluster.ServerType; import org.apache.accumulo.server.ServerContext; import org.apache.accumulo.server.ServerDirs; import org.apache.accumulo.server.fs.VolumeManager; import org.apache.accumulo.server.init.Initialize; import org.apache.accumulo.server.util.AccumuloStatus; import org.apache.accumulo.server.util.PortUtils; import org.apache.accumulo.start.Main; import org.apache.accumulo.start.classloader.vfs.MiniDFSUtil; import org.apache.accumulo.start.spi.KeywordExecutable; import org.apache.commons.io.IOUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeys; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.thrift.TException; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.ZooKeeper.States; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * This class provides the backing implementation for {@link MiniAccumuloCluster}, and may contain * features for internal testing which have not yet been promoted to the public API. It's best to * use {@link MiniAccumuloCluster} whenever possible. Use of this class risks API breakage between * versions. * * @since 1.6.0 */ public class MiniAccumuloClusterImpl implements AccumuloCluster { private static final Logger log = LoggerFactory.getLogger(MiniAccumuloClusterImpl.class); private boolean initialized = false; private Set<Pair<ServerType,Integer>> debugPorts = new HashSet<>(); private File zooCfgFile; private String dfsUri; private SiteConfiguration siteConfig; private ServerContext context; private Properties clientProperties; private MiniAccumuloConfigImpl config; private MiniDFSCluster miniDFS = null; private List<Process> cleanup = new ArrayList<>(); private ExecutorService executor; private MiniAccumuloClusterControl clusterControl; File getZooCfgFile() { return zooCfgFile; } public ProcessInfo exec(Class<?> clazz, String... args) throws IOException { return exec(clazz, null, args); } public ProcessInfo exec(Class<?> clazz, List<String> jvmArgs, String... args) throws IOException { ArrayList<String> jvmArgs2 = new ArrayList<>(1 + (jvmArgs == null ? 0 : jvmArgs.size())); jvmArgs2.add("-Xmx" + config.getDefaultMemory()); if (jvmArgs != null) { jvmArgs2.addAll(jvmArgs); } return _exec(clazz, jvmArgs2, args); } private String getClasspath() { StringBuilder classpathBuilder = new StringBuilder(); classpathBuilder.append(config.getConfDir().getAbsolutePath()); if (config.getHadoopConfDir() != null) { classpathBuilder.append(File.pathSeparator) .append(config.getHadoopConfDir().getAbsolutePath()); } if (config.getClasspathItems() == null) { String javaClassPath = System.getProperty("java.class.path"); if (javaClassPath == null) { throw new IllegalStateException("java.class.path is not set"); } classpathBuilder.append(File.pathSeparator).append(javaClassPath); } else { for (String s : config.getClasspathItems()) { classpathBuilder.append(File.pathSeparator).append(s); } } return classpathBuilder.toString(); } public static class ProcessInfo { private final Process process; private final File stdOut; public ProcessInfo(Process process, File stdOut) { this.process = process; this.stdOut = stdOut; } public Process getProcess() { return process; } public String readStdOut() { try (InputStream in = new FileInputStream(stdOut)) { return IOUtils.toString(in, UTF_8); } catch (IOException e) { throw new UncheckedIOException(e); } } } @SuppressFBWarnings(value = {"COMMAND_INJECTION", "PATH_TRAVERSAL_IN"}, justification = "mini runs in the same security context as user providing the args") private ProcessInfo _exec(Class<?> clazz, List<String> extraJvmOpts, String... args) throws IOException { String javaHome = System.getProperty("java.home"); String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; String classpath = getClasspath(); String className = clazz.getName(); ArrayList<String> argList = new ArrayList<>(); argList.addAll(Arrays.asList(javaBin, "-Dproc=" + clazz.getSimpleName(), "-cp", classpath)); argList.addAll(extraJvmOpts); for (Entry<String,String> sysProp : config.getSystemProperties().entrySet()) { argList.add(String.format("-D%s=%s", sysProp.getKey(), sysProp.getValue())); } // @formatter:off argList.addAll(Arrays.asList( "-Dapple.awt.UIElement=true", "-Djava.net.preferIPv4Stack=true", "-XX:+PerfDisableSharedMem", "-XX:+AlwaysPreTouch", Main.class.getName(), className)); // @formatter:on argList.addAll(Arrays.asList(args)); ProcessBuilder builder = new ProcessBuilder(argList); builder.environment().put("ACCUMULO_HOME", config.getDir().getAbsolutePath()); builder.environment().put("ACCUMULO_LOG_DIR", config.getLogDir().getAbsolutePath()); builder.environment().put("ACCUMULO_CLIENT_CONF_PATH", config.getClientConfFile().getAbsolutePath()); String ldLibraryPath = Joiner.on(File.pathSeparator).join(config.getNativeLibPaths()); builder.environment().put("LD_LIBRARY_PATH", ldLibraryPath); builder.environment().put("DYLD_LIBRARY_PATH", ldLibraryPath); // if we're running under accumulo.start, we forward these env vars String env = System.getenv("HADOOP_HOME"); if (env != null) { builder.environment().put("HADOOP_HOME", env); } env = System.getenv("ZOOKEEPER_HOME"); if (env != null) { builder.environment().put("ZOOKEEPER_HOME", env); } builder.environment().put("ACCUMULO_CONF_DIR", config.getConfDir().getAbsolutePath()); if (config.getHadoopConfDir() != null) { builder.environment().put("HADOOP_CONF_DIR", config.getHadoopConfDir().getAbsolutePath()); } log.debug("Starting MiniAccumuloCluster process with class: " + clazz.getSimpleName() + "\n, jvmOpts: " + extraJvmOpts + "\n, classpath: " + classpath + "\n, args: " + argList + "\n, environment: " + builder.environment()); int hashcode = builder.hashCode(); File stdOut = new File(config.getLogDir(), clazz.getSimpleName() + "_" + hashcode + ".out"); File stdErr = new File(config.getLogDir(), clazz.getSimpleName() + "_" + hashcode + ".err"); Process process = builder.redirectError(stdErr).redirectOutput(stdOut).start(); cleanup.add(process); return new ProcessInfo(process, stdOut); } public ProcessInfo _exec(KeywordExecutable server, ServerType serverType, Map<String,String> configOverrides, String... args) throws IOException { String[] modifiedArgs; if (args == null || args.length == 0) { modifiedArgs = new String[] {server.keyword()}; } else { modifiedArgs = Stream.concat(Stream.of(server.keyword()), Stream.of(args)).toArray(String[]::new); } return _exec(Main.class, serverType, configOverrides, modifiedArgs); } public ProcessInfo _exec(Class<?> clazz, ServerType serverType, Map<String,String> configOverrides, String... args) throws IOException { List<String> jvmOpts = new ArrayList<>(); if (serverType == ServerType.ZOOKEEPER) { // disable zookeeper's log4j 1.2 jmx support, which depends on log4j 1.2 on the class path, // which we don't need or expect to be there jvmOpts.add("-Dzookeeper.jmx.log4j.disable=true"); } jvmOpts.add("-Xmx" + config.getMemory(serverType)); if (configOverrides != null && !configOverrides.isEmpty()) { File siteFile = Files.createTempFile(config.getConfDir().toPath(), "accumulo", ".properties").toFile(); Map<String,String> confMap = new HashMap<>(); confMap.putAll(config.getSiteConfig()); confMap.putAll(configOverrides); writeConfigProperties(siteFile, confMap); jvmOpts.add("-Daccumulo.properties=" + siteFile.getName()); } if (config.isJDWPEnabled()) { int port = PortUtils.getRandomFreePort(); jvmOpts.addAll(buildRemoteDebugParams(port)); debugPorts.add(new Pair<>(serverType, port)); } return _exec(clazz, jvmOpts, args); } /** * * @param dir * An empty or nonexistent temp directory that Accumulo and Zookeeper can store data in. * Creating the directory is left to the user. Java 7, Guava, and Junit provide methods * for creating temporary directories. * @param rootPassword * Initial root password for instance. */ public MiniAccumuloClusterImpl(File dir, String rootPassword) throws IOException { this(new MiniAccumuloConfigImpl(dir, rootPassword)); } /** * @param config * initial configuration */ @SuppressWarnings("deprecation") public MiniAccumuloClusterImpl(MiniAccumuloConfigImpl config) throws IOException { this.config = config.initialize(); if (Boolean.valueOf(config.getSiteConfig().get(Property.TSERV_NATIVEMAP_ENABLED.getKey())) && config.getNativeLibPaths().length == 0 && !config.getSystemProperties().containsKey("accumulo.native.lib.path")) { throw new RuntimeException( "MAC configured to use native maps, but native library path was not provided."); } mkdirs(config.getConfDir()); mkdirs(config.getLogDir()); mkdirs(config.getLibDir()); mkdirs(config.getLibExtDir()); if (!config.useExistingInstance()) { if (!config.useExistingZooKeepers()) { mkdirs(config.getZooKeeperDir()); } mkdirs(config.getAccumuloDir()); } if (config.useMiniDFS()) { File nn = new File(config.getAccumuloDir(), "nn"); mkdirs(nn); File dn = new File(config.getAccumuloDir(), "dn"); mkdirs(dn); File dfs = new File(config.getAccumuloDir(), "dfs"); mkdirs(dfs); Configuration conf = new Configuration(); conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY, nn.getAbsolutePath()); conf.set(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY, dn.getAbsolutePath()); conf.set(DFSConfigKeys.DFS_REPLICATION_KEY, "1"); conf.set(DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY, "1"); conf.set("dfs.support.append", "true"); conf.set("dfs.datanode.synconclose", "true"); conf.set("dfs.datanode.data.dir.perm", MiniDFSUtil.computeDatanodeDirectoryPermission()); String oldTestBuildData = System.setProperty("test.build.data", dfs.getAbsolutePath()); miniDFS = new MiniDFSCluster.Builder(conf).build(); if (oldTestBuildData == null) { System.clearProperty("test.build.data"); } else { System.setProperty("test.build.data", oldTestBuildData); } miniDFS.waitClusterUp(); InetSocketAddress dfsAddress = miniDFS.getNameNode().getNameNodeAddress(); dfsUri = "hdfs://" + dfsAddress.getHostName() + ":" + dfsAddress.getPort(); File coreFile = new File(config.getConfDir(), "core-site.xml"); writeConfig(coreFile, Collections.singletonMap("fs.default.name", dfsUri).entrySet()); File hdfsFile = new File(config.getConfDir(), "hdfs-site.xml"); writeConfig(hdfsFile, conf); Map<String,String> siteConfig = config.getSiteConfig(); siteConfig.put(Property.INSTANCE_VOLUMES.getKey(), dfsUri + "/accumulo"); config.setSiteConfig(siteConfig); } else if (config.useExistingInstance()) { dfsUri = config.getHadoopConfiguration().get(CommonConfigurationKeys.FS_DEFAULT_NAME_KEY); } else { dfsUri = "file:///"; } File clientConfFile = config.getClientConfFile(); // Write only the properties that correspond to ClientConfiguration properties writeConfigProperties(clientConfFile, Maps.filterEntries(config.getSiteConfig(), v -> org.apache.accumulo.core.client.ClientConfiguration.ClientProperty .getPropertyByKey(v.getKey()) != null)); Map<String,String> clientProps = config.getClientProps(); clientProps.put(ClientProperty.INSTANCE_ZOOKEEPERS.getKey(), config.getZooKeepers()); clientProps.put(ClientProperty.INSTANCE_NAME.getKey(), config.getInstanceName()); if (!clientProps.containsKey(ClientProperty.AUTH_TYPE.getKey())) { clientProps.put(ClientProperty.AUTH_TYPE.getKey(), "password"); clientProps.put(ClientProperty.AUTH_PRINCIPAL.getKey(), config.getRootUserName()); clientProps.put(ClientProperty.AUTH_TOKEN.getKey(), config.getRootPassword()); } File clientPropsFile = config.getClientPropsFile(); writeConfigProperties(clientPropsFile, clientProps); File siteFile = new File(config.getConfDir(), "accumulo.properties"); writeConfigProperties(siteFile, config.getSiteConfig()); siteConfig = SiteConfiguration.fromFile(siteFile).build(); if (!config.useExistingInstance() && !config.useExistingZooKeepers()) { zooCfgFile = new File(config.getConfDir(), "zoo.cfg"); FileWriter fileWriter = new FileWriter(zooCfgFile, UTF_8); // zookeeper uses Properties to read its config, so use that to write in order to properly // escape things like Windows paths Properties zooCfg = new Properties(); zooCfg.setProperty("tickTime", "2000"); zooCfg.setProperty("initLimit", "10"); zooCfg.setProperty("syncLimit", "5"); zooCfg.setProperty("clientPortAddress", "127.0.0.1"); zooCfg.setProperty("clientPort", config.getZooKeeperPort() + ""); zooCfg.setProperty("maxClientCnxns", "1000"); zooCfg.setProperty("dataDir", config.getZooKeeperDir().getAbsolutePath()); zooCfg.setProperty("4lw.commands.whitelist", "ruok,wchs"); zooCfg.setProperty("admin.enableServer", "false"); zooCfg.store(fileWriter, null); fileWriter.close(); } clusterControl = new MiniAccumuloClusterControl(this); } private static void mkdirs(File dir) { if (!dir.mkdirs()) { log.warn("Unable to create {}", dir); } } private void writeConfig(File file, Iterable<Map.Entry<String,String>> settings) throws IOException { FileWriter fileWriter = new FileWriter(file, UTF_8); fileWriter.append("<configuration>\n"); for (Entry<String,String> entry : settings) { String value = entry.getValue().replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"); fileWriter.append( "<property><name>" + entry.getKey() + "</name><value>" + value + "</value></property>\n"); } fileWriter.append("</configuration>\n"); fileWriter.close(); } private void writeConfigProperties(File file, Map<String,String> settings) throws IOException { FileWriter fileWriter = new FileWriter(file, UTF_8); for (Entry<String,String> entry : settings.entrySet()) { fileWriter.append(entry.getKey() + "=" + entry.getValue() + "\n"); } fileWriter.close(); } /** * Starts Accumulo and Zookeeper processes. Can only be called once. */ @SuppressFBWarnings(value = "UNENCRYPTED_SOCKET", justification = "insecure socket used for reservation") @Override public synchronized void start() throws IOException, InterruptedException { if (config.useMiniDFS() && miniDFS == null) { throw new IllegalStateException("Cannot restart mini when using miniDFS"); } MiniAccumuloClusterControl control = getClusterControl(); if (config.useExistingInstance()) { AccumuloConfiguration acuConf = config.getAccumuloConfiguration(); Configuration hadoopConf = config.getHadoopConfiguration(); ServerDirs serverDirs = new ServerDirs(acuConf, hadoopConf); ConfigurationCopy cc = new ConfigurationCopy(acuConf); Path instanceIdPath; try (var fs = getServerContext().getVolumeManager()) { instanceIdPath = serverDirs.getInstanceIdLocation(fs.getFirst()); } catch (IOException e) { throw new RuntimeException(e); } String instanceIdFromFile = VolumeManager.getInstanceIDFromHdfs(instanceIdPath, hadoopConf); ZooReaderWriter zrw = new ZooReaderWriter(cc.get(Property.INSTANCE_ZK_HOST), (int) cc.getTimeInMillis(Property.INSTANCE_ZK_TIMEOUT), cc.get(Property.INSTANCE_SECRET)); String rootPath = ZooUtil.getRoot(instanceIdFromFile); String instanceName = null; try { for (String name : zrw.getChildren(Constants.ZROOT + Constants.ZINSTANCES)) { String instanceNamePath = Constants.ZROOT + Constants.ZINSTANCES + "/" + name; byte[] bytes = zrw.getData(instanceNamePath); String iid = new String(bytes, UTF_8); if (iid.equals(instanceIdFromFile)) { instanceName = name; } } } catch (KeeperException e) { throw new RuntimeException("Unable to read instance name from zookeeper.", e); } if (instanceName == null) { throw new RuntimeException("Unable to read instance name from zookeeper."); } config.setInstanceName(instanceName); if (!AccumuloStatus.isAccumuloOffline(zrw, rootPath)) { throw new RuntimeException( "The Accumulo instance being used is already running. Aborting."); } } else { if (!initialized) { Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { MiniAccumuloClusterImpl.this.stop(); } catch (IOException e) { log.error("IOException while attempting to stop the MiniAccumuloCluster.", e); } catch (InterruptedException e) { log.error("The stopping of MiniAccumuloCluster was interrupted.", e); } })); } if (!config.useExistingZooKeepers()) { control.start(ServerType.ZOOKEEPER); } if (!initialized) { if (!config.useExistingZooKeepers()) { // sleep a little bit to let zookeeper come up before calling init, seems to work better long startTime = System.currentTimeMillis(); while (true) { try (Socket s = new Socket("localhost", config.getZooKeeperPort())) { s.setReuseAddress(true); s.getOutputStream().write("ruok\n".getBytes()); s.getOutputStream().flush(); byte[] buffer = new byte[100]; int n = s.getInputStream().read(buffer); if (n >= 4 && new String(buffer, 0, 4).equals("imok")) { break; } } catch (Exception e) { if (System.currentTimeMillis() - startTime >= config.getZooKeeperStartupTime()) { throw new ZooKeeperBindException("Zookeeper did not start within " + (config.getZooKeeperStartupTime() / 1000) + " seconds. Check the logs in " + config.getLogDir() + " for errors. Last exception: " + e); } // Don't spin absurdly fast sleepUninterruptibly(250, TimeUnit.MILLISECONDS); } } } LinkedList<String> args = new LinkedList<>(); args.add("--instance-name"); args.add(config.getInstanceName()); args.add("--user"); args.add(config.getRootUserName()); args.add("--clear-instance-name"); // If we aren't using SASL, add in the root password final String saslEnabled = config.getSiteConfig().get(Property.INSTANCE_RPC_SASL_ENABLED.getKey()); if (saslEnabled == null || !Boolean.parseBoolean(saslEnabled)) { args.add("--password"); args.add(config.getRootPassword()); } Process initProcess = exec(Initialize.class, args.toArray(new String[0])).getProcess(); int ret = initProcess.waitFor(); if (ret != 0) { throw new RuntimeException("Initialize process returned " + ret + ". Check the logs in " + config.getLogDir() + " for errors."); } initialized = true; } } log.info("Starting MAC against instance {} and zookeeper(s) {}.", config.getInstanceName(), config.getZooKeepers()); control.start(ServerType.TABLET_SERVER); int ret = 0; for (int i = 0; i < 5; i++) { ret = exec(Main.class, SetGoalState.class.getName(), ManagerGoalState.NORMAL.toString()) .getProcess().waitFor(); if (ret == 0) { break; } sleepUninterruptibly(1, TimeUnit.SECONDS); } if (ret != 0) { throw new RuntimeException("Could not set manager goal state, process returned " + ret + ". Check the logs in " + config.getLogDir() + " for errors."); } control.start(ServerType.MANAGER); control.start(ServerType.GARBAGE_COLLECTOR); if (executor == null) { executor = Executors.newSingleThreadExecutor(); } verifyUp(); } // wait up to 10 seconds for the process to start private static void waitForProcessStart(Process p, String name) throws InterruptedException { long start = System.nanoTime(); while (p.info().startInstant().isEmpty()) { if (NANOSECONDS.toSeconds(System.nanoTime() - start) > 10) { throw new IllegalStateException( "Error starting " + name + " - instance not started within 10 seconds"); } Thread.sleep(50); } } private void verifyUp() throws InterruptedException, IOException { int numTries = 10; requireNonNull(getClusterControl().managerProcess, "Error starting Manager - no process"); waitForProcessStart(getClusterControl().managerProcess, "Manager"); requireNonNull(getClusterControl().gcProcess, "Error starting GC - no process"); waitForProcessStart(getClusterControl().gcProcess, "GC"); int tsExpectedCount = 0; for (Process tsp : getClusterControl().tabletServerProcesses) { tsExpectedCount++; requireNonNull(tsp, "Error starting TabletServer " + tsExpectedCount + " - no process"); waitForProcessStart(tsp, "TabletServer" + tsExpectedCount); } try (ZooKeeper zk = new ZooKeeper(getZooKeepers(), 60000, event -> log.info("{}", event))) { String secret = getSiteConfiguration().get(Property.INSTANCE_SECRET); for (int i = 0; i < numTries; i++) { if (zk.getState().equals(States.CONNECTED)) { ZooUtil.digestAuth(zk, secret); break; } else { Thread.sleep(1000); } } String instanceId = null; try { for (String name : zk.getChildren(Constants.ZROOT + Constants.ZINSTANCES, null)) { if (name.equals(config.getInstanceName())) { String instanceNamePath = Constants.ZROOT + Constants.ZINSTANCES + "/" + name; byte[] bytes = zk.getData(instanceNamePath, null, null); instanceId = new String(bytes, UTF_8); break; } } } catch (KeeperException e) { throw new RuntimeException("Unable to read instance id from zookeeper.", e); } if (instanceId == null) { throw new RuntimeException("Unable to find instance id from zookeeper."); } String rootPath = Constants.ZROOT + "/" + instanceId; int tsActualCount = 0; try { while (tsActualCount < tsExpectedCount) { tsActualCount = 0; for (String child : zk.getChildren(rootPath + Constants.ZTSERVERS, null)) { if (zk.getChildren(rootPath + Constants.ZTSERVERS + "/" + child, null).isEmpty()) { log.info("TServer " + tsActualCount + " not yet present in ZooKeeper"); } else { tsActualCount++; log.info("TServer " + tsActualCount + " present in ZooKeeper"); } } Thread.sleep(500); } } catch (KeeperException e) { throw new RuntimeException("Unable to read TServer information from zookeeper.", e); } try { while (zk.getChildren(rootPath + Constants.ZMANAGER_LOCK, null).isEmpty()) { log.info("Manager not yet present in ZooKeeper"); Thread.sleep(500); } } catch (KeeperException e) { throw new RuntimeException("Unable to read Manager information from zookeeper.", e); } try { while (zk.getChildren(rootPath + Constants.ZGC_LOCK, null).isEmpty()) { log.info("GC not yet present in ZooKeeper"); Thread.sleep(500); } } catch (KeeperException e) { throw new RuntimeException("Unable to read GC information from zookeeper.", e); } } } private List<String> buildRemoteDebugParams(int port) { return Collections.singletonList( String.format("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=%d", port)); } /** * @return generated remote debug ports if in debug mode. * @since 1.6.0 */ public Set<Pair<ServerType,Integer>> getDebugPorts() { return debugPorts; } List<ProcessReference> references(Process... procs) { List<ProcessReference> result = new ArrayList<>(); for (Process proc : procs) { result.add(new ProcessReference(proc)); } return result; } public Map<ServerType,Collection<ProcessReference>> getProcesses() { Map<ServerType,Collection<ProcessReference>> result = new HashMap<>(); MiniAccumuloClusterControl control = getClusterControl(); result.put(ServerType.MANAGER, references(control.managerProcess)); result.put(ServerType.TABLET_SERVER, references(control.tabletServerProcesses.toArray(new Process[0]))); if (control.zooKeeperProcess != null) { result.put(ServerType.ZOOKEEPER, references(control.zooKeeperProcess)); } if (control.gcProcess != null) { result.put(ServerType.GARBAGE_COLLECTOR, references(control.gcProcess)); } return result; } public void killProcess(ServerType type, ProcessReference proc) throws ProcessNotFoundException, InterruptedException { getClusterControl().killProcess(type, proc); } @Override public String getInstanceName() { return config.getInstanceName(); } @Override public String getZooKeepers() { return config.getZooKeepers(); } @Override public synchronized ServerContext getServerContext() { if (context == null) { context = new ServerContext(siteConfig); } return context; } /** * Stops Accumulo and Zookeeper processes. If stop is not called, there is a shutdown hook that is * setup to kill the processes. However it's probably best to call stop in a finally block as soon * as possible. */ @Override public synchronized void stop() throws IOException, InterruptedException { if (executor == null) { // keep repeated calls to stop() from failing return; } MiniAccumuloClusterControl control = getClusterControl(); control.stop(ServerType.GARBAGE_COLLECTOR, null); control.stop(ServerType.MANAGER, null); control.stop(ServerType.TABLET_SERVER, null); control.stop(ServerType.ZOOKEEPER, null); // ACCUMULO-2985 stop the ExecutorService after we finished using it to stop accumulo procs if (executor != null) { List<Runnable> tasksRemaining = executor.shutdownNow(); // the single thread executor shouldn't have any pending tasks, but check anyways if (!tasksRemaining.isEmpty()) { log.warn( "Unexpectedly had {} task(s) remaining in threadpool for execution when being stopped", tasksRemaining.size()); } executor = null; } if (config.useMiniDFS() && miniDFS != null) { miniDFS.shutdown(); } for (Process p : cleanup) { p.destroy(); p.waitFor(); } miniDFS = null; } /** * @since 1.6.0 */ public MiniAccumuloConfigImpl getConfig() { return config; } @Override public AccumuloClient createAccumuloClient(String user, AuthenticationToken token) { return Accumulo.newClient().from(getClientProperties()).as(user, token).build(); } @SuppressWarnings("deprecation") @Override public org.apache.accumulo.core.client.ClientConfiguration getClientConfig() { return org.apache.accumulo.core.client.ClientConfiguration.fromMap(config.getSiteConfig()) .withInstance(this.getInstanceName()).withZkHosts(this.getZooKeepers()); } @Override public synchronized Properties getClientProperties() { if (clientProperties == null) { clientProperties = Accumulo.newClientProperties().from(config.getClientPropsFile().toPath()).build(); } return clientProperties; } @Override public FileSystem getFileSystem() { try { return FileSystem.get(new URI(dfsUri), new Configuration()); } catch (Exception e) { throw new RuntimeException(e); } } @VisibleForTesting protected void setShutdownExecutor(ExecutorService svc) { this.executor = svc; } @VisibleForTesting protected ExecutorService getShutdownExecutor() { return executor; } public int stopProcessWithTimeout(final Process proc, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { FutureTask<Integer> future = new FutureTask<>(() -> { proc.destroy(); return proc.waitFor(); }); executor.execute(future); return future.get(timeout, unit); } /** * Get programmatic interface to information available in a normal monitor. XXX the returned * structure won't contain information about the metadata table until there is data in it. e.g. if * you want to see the metadata table you should create a table. * * @since 1.6.1 */ public ManagerMonitorInfo getManagerMonitorInfo() throws AccumuloException, AccumuloSecurityException { try (AccumuloClient c = Accumulo.newClient().from(getClientProperties()).build()) { while (true) { ManagerClientService.Iface client = null; try { client = ManagerClient.getConnectionWithRetry((ClientContext) c); return client.getManagerStats(TraceUtil.traceInfo(), ((ClientContext) c).rpcCreds()); } catch (ThriftSecurityException exception) { throw new AccumuloSecurityException(exception); } catch (ThriftNotActiveServiceException e) { // Let it loop, fetching a new location log.debug("Contacted a Manager which is no longer active, retrying"); sleepUninterruptibly(100, TimeUnit.MILLISECONDS); } catch (TException exception) { throw new AccumuloException(exception); } finally { if (client != null) { ManagerClient.close(client, (ClientContext) c); } } } } } public synchronized MiniDFSCluster getMiniDfs() { return this.miniDFS; } @Override public MiniAccumuloClusterControl getClusterControl() { return clusterControl; } @Override public Path getTemporaryPath() { String p; if (config.useMiniDFS()) { p = "/tmp/"; } else { File tmp = new File(config.getDir(), "tmp"); mkdirs(tmp); p = tmp.toString(); } return getFileSystem().makeQualified(new Path(p)); } @Override public AccumuloConfiguration getSiteConfiguration() { return new ConfigurationCopy( Iterables.concat(DefaultConfiguration.getInstance(), config.getSiteConfig().entrySet())); } @Override public String getAccumuloPropertiesPath() { return new File(config.getConfDir(), "accumulo.properties").toString(); } @Override public String getClientPropsPath() { return config.getClientPropsFile().getAbsolutePath(); } }
minicluster/src/main/java/org/apache/accumulo/miniclusterImpl/MiniAccumuloClusterImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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.apache.accumulo.miniclusterImpl; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Objects.requireNonNull; import static org.apache.accumulo.fate.util.UtilWaitThread.sleepUninterruptibly; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.URI; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Stream; import org.apache.accumulo.cluster.AccumuloCluster; import org.apache.accumulo.core.Constants; import org.apache.accumulo.core.client.Accumulo; import org.apache.accumulo.core.client.AccumuloClient; import org.apache.accumulo.core.client.AccumuloException; import org.apache.accumulo.core.client.AccumuloSecurityException; import org.apache.accumulo.core.client.security.tokens.AuthenticationToken; import org.apache.accumulo.core.clientImpl.ClientContext; import org.apache.accumulo.core.clientImpl.ManagerClient; import org.apache.accumulo.core.clientImpl.thrift.ThriftNotActiveServiceException; import org.apache.accumulo.core.clientImpl.thrift.ThriftSecurityException; import org.apache.accumulo.core.conf.AccumuloConfiguration; import org.apache.accumulo.core.conf.ClientProperty; import org.apache.accumulo.core.conf.ConfigurationCopy; import org.apache.accumulo.core.conf.DefaultConfiguration; import org.apache.accumulo.core.conf.Property; import org.apache.accumulo.core.conf.SiteConfiguration; import org.apache.accumulo.core.manager.thrift.ManagerClientService; import org.apache.accumulo.core.manager.thrift.ManagerGoalState; import org.apache.accumulo.core.manager.thrift.ManagerMonitorInfo; import org.apache.accumulo.core.trace.TraceUtil; import org.apache.accumulo.core.util.Pair; import org.apache.accumulo.fate.util.UtilWaitThread; import org.apache.accumulo.fate.zookeeper.ZooReaderWriter; import org.apache.accumulo.fate.zookeeper.ZooUtil; import org.apache.accumulo.manager.state.SetGoalState; import org.apache.accumulo.minicluster.MiniAccumuloCluster; import org.apache.accumulo.minicluster.ServerType; import org.apache.accumulo.server.ServerContext; import org.apache.accumulo.server.ServerDirs; import org.apache.accumulo.server.fs.VolumeManager; import org.apache.accumulo.server.init.Initialize; import org.apache.accumulo.server.util.AccumuloStatus; import org.apache.accumulo.server.util.PortUtils; import org.apache.accumulo.start.Main; import org.apache.accumulo.start.classloader.vfs.MiniDFSUtil; import org.apache.accumulo.start.spi.KeywordExecutable; import org.apache.commons.io.IOUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeys; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.thrift.TException; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.ZooKeeper.States; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * This class provides the backing implementation for {@link MiniAccumuloCluster}, and may contain * features for internal testing which have not yet been promoted to the public API. It's best to * use {@link MiniAccumuloCluster} whenever possible. Use of this class risks API breakage between * versions. * * @since 1.6.0 */ public class MiniAccumuloClusterImpl implements AccumuloCluster { private static final Logger log = LoggerFactory.getLogger(MiniAccumuloClusterImpl.class); private boolean initialized = false; private Set<Pair<ServerType,Integer>> debugPorts = new HashSet<>(); private File zooCfgFile; private String dfsUri; private SiteConfiguration siteConfig; private ServerContext context; private Properties clientProperties; private MiniAccumuloConfigImpl config; private MiniDFSCluster miniDFS = null; private List<Process> cleanup = new ArrayList<>(); private ExecutorService executor; private MiniAccumuloClusterControl clusterControl; File getZooCfgFile() { return zooCfgFile; } public ProcessInfo exec(Class<?> clazz, String... args) throws IOException { return exec(clazz, null, args); } public ProcessInfo exec(Class<?> clazz, List<String> jvmArgs, String... args) throws IOException { ArrayList<String> jvmArgs2 = new ArrayList<>(1 + (jvmArgs == null ? 0 : jvmArgs.size())); jvmArgs2.add("-Xmx" + config.getDefaultMemory()); if (jvmArgs != null) { jvmArgs2.addAll(jvmArgs); } return _exec(clazz, jvmArgs2, args); } private String getClasspath() { StringBuilder classpathBuilder = new StringBuilder(); classpathBuilder.append(config.getConfDir().getAbsolutePath()); if (config.getHadoopConfDir() != null) { classpathBuilder.append(File.pathSeparator) .append(config.getHadoopConfDir().getAbsolutePath()); } if (config.getClasspathItems() == null) { String javaClassPath = System.getProperty("java.class.path"); if (javaClassPath == null) { throw new IllegalStateException("java.class.path is not set"); } classpathBuilder.append(File.pathSeparator).append(javaClassPath); } else { for (String s : config.getClasspathItems()) { classpathBuilder.append(File.pathSeparator).append(s); } } return classpathBuilder.toString(); } public static class ProcessInfo { private final Process process; private final File stdOut; public ProcessInfo(Process process, File stdOut) { this.process = process; this.stdOut = stdOut; } public Process getProcess() { return process; } public String readStdOut() { try (InputStream in = new FileInputStream(stdOut)) { return IOUtils.toString(in, UTF_8); } catch (IOException e) { throw new UncheckedIOException(e); } } } @SuppressFBWarnings(value = {"COMMAND_INJECTION", "PATH_TRAVERSAL_IN"}, justification = "mini runs in the same security context as user providing the args") private ProcessInfo _exec(Class<?> clazz, List<String> extraJvmOpts, String... args) throws IOException { String javaHome = System.getProperty("java.home"); String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; String classpath = getClasspath(); String className = clazz.getName(); ArrayList<String> argList = new ArrayList<>(); argList.addAll(Arrays.asList(javaBin, "-Dproc=" + clazz.getSimpleName(), "-cp", classpath)); argList.addAll(extraJvmOpts); for (Entry<String,String> sysProp : config.getSystemProperties().entrySet()) { argList.add(String.format("-D%s=%s", sysProp.getKey(), sysProp.getValue())); } // @formatter:off argList.addAll(Arrays.asList( "-Dapple.awt.UIElement=true", "-Djava.net.preferIPv4Stack=true", "-XX:+PerfDisableSharedMem", "-XX:+AlwaysPreTouch", Main.class.getName(), className)); // @formatter:on argList.addAll(Arrays.asList(args)); ProcessBuilder builder = new ProcessBuilder(argList); builder.environment().put("ACCUMULO_HOME", config.getDir().getAbsolutePath()); builder.environment().put("ACCUMULO_LOG_DIR", config.getLogDir().getAbsolutePath()); builder.environment().put("ACCUMULO_CLIENT_CONF_PATH", config.getClientConfFile().getAbsolutePath()); String ldLibraryPath = Joiner.on(File.pathSeparator).join(config.getNativeLibPaths()); builder.environment().put("LD_LIBRARY_PATH", ldLibraryPath); builder.environment().put("DYLD_LIBRARY_PATH", ldLibraryPath); // if we're running under accumulo.start, we forward these env vars String env = System.getenv("HADOOP_HOME"); if (env != null) { builder.environment().put("HADOOP_HOME", env); } env = System.getenv("ZOOKEEPER_HOME"); if (env != null) { builder.environment().put("ZOOKEEPER_HOME", env); } builder.environment().put("ACCUMULO_CONF_DIR", config.getConfDir().getAbsolutePath()); if (config.getHadoopConfDir() != null) { builder.environment().put("HADOOP_CONF_DIR", config.getHadoopConfDir().getAbsolutePath()); } log.debug("Starting MiniAccumuloCluster process with class: " + clazz.getSimpleName() + "\n, jvmOpts: " + extraJvmOpts + "\n, classpath: " + classpath + "\n, args: " + argList + "\n, environment: " + builder.environment()); int hashcode = builder.hashCode(); File stdOut = new File(config.getLogDir(), clazz.getSimpleName() + "_" + hashcode + ".out"); File stdErr = new File(config.getLogDir(), clazz.getSimpleName() + "_" + hashcode + ".err"); Process process = builder.redirectError(stdErr).redirectOutput(stdOut).start(); cleanup.add(process); return new ProcessInfo(process, stdOut); } public ProcessInfo _exec(KeywordExecutable server, ServerType serverType, Map<String,String> configOverrides, String... args) throws IOException { String[] modifiedArgs; if (args == null || args.length == 0) { modifiedArgs = new String[] {server.keyword()}; } else { modifiedArgs = Stream.concat(Stream.of(server.keyword()), Stream.of(args)).toArray(String[]::new); } return _exec(Main.class, serverType, configOverrides, modifiedArgs); } public ProcessInfo _exec(Class<?> clazz, ServerType serverType, Map<String,String> configOverrides, String... args) throws IOException { List<String> jvmOpts = new ArrayList<>(); if (serverType == ServerType.ZOOKEEPER) { // disable zookeeper's log4j 1.2 jmx support, which depends on log4j 1.2 on the class path, // which we don't need or expect to be there jvmOpts.add("-Dzookeeper.jmx.log4j.disable=true"); } jvmOpts.add("-Xmx" + config.getMemory(serverType)); if (configOverrides != null && !configOverrides.isEmpty()) { File siteFile = Files.createTempFile(config.getConfDir().toPath(), "accumulo", ".properties").toFile(); Map<String,String> confMap = new HashMap<>(); confMap.putAll(config.getSiteConfig()); confMap.putAll(configOverrides); writeConfigProperties(siteFile, confMap); jvmOpts.add("-Daccumulo.properties=" + siteFile.getName()); } if (config.isJDWPEnabled()) { int port = PortUtils.getRandomFreePort(); jvmOpts.addAll(buildRemoteDebugParams(port)); debugPorts.add(new Pair<>(serverType, port)); } return _exec(clazz, jvmOpts, args); } /** * * @param dir * An empty or nonexistent temp directory that Accumulo and Zookeeper can store data in. * Creating the directory is left to the user. Java 7, Guava, and Junit provide methods * for creating temporary directories. * @param rootPassword * Initial root password for instance. */ public MiniAccumuloClusterImpl(File dir, String rootPassword) throws IOException { this(new MiniAccumuloConfigImpl(dir, rootPassword)); } /** * @param config * initial configuration */ @SuppressWarnings("deprecation") public MiniAccumuloClusterImpl(MiniAccumuloConfigImpl config) throws IOException { this.config = config.initialize(); if (Boolean.valueOf(config.getSiteConfig().get(Property.TSERV_NATIVEMAP_ENABLED.getKey())) && config.getNativeLibPaths().length == 0 && !config.getSystemProperties().containsKey("accumulo.native.lib.path")) { throw new RuntimeException( "MAC configured to use native maps, but native library path was not provided."); } mkdirs(config.getConfDir()); mkdirs(config.getLogDir()); mkdirs(config.getLibDir()); mkdirs(config.getLibExtDir()); if (!config.useExistingInstance()) { if (!config.useExistingZooKeepers()) { mkdirs(config.getZooKeeperDir()); } mkdirs(config.getAccumuloDir()); } if (config.useMiniDFS()) { File nn = new File(config.getAccumuloDir(), "nn"); mkdirs(nn); File dn = new File(config.getAccumuloDir(), "dn"); mkdirs(dn); File dfs = new File(config.getAccumuloDir(), "dfs"); mkdirs(dfs); Configuration conf = new Configuration(); conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY, nn.getAbsolutePath()); conf.set(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY, dn.getAbsolutePath()); conf.set(DFSConfigKeys.DFS_REPLICATION_KEY, "1"); conf.set(DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY, "1"); conf.set("dfs.support.append", "true"); conf.set("dfs.datanode.synconclose", "true"); conf.set("dfs.datanode.data.dir.perm", MiniDFSUtil.computeDatanodeDirectoryPermission()); String oldTestBuildData = System.setProperty("test.build.data", dfs.getAbsolutePath()); miniDFS = new MiniDFSCluster.Builder(conf).build(); if (oldTestBuildData == null) { System.clearProperty("test.build.data"); } else { System.setProperty("test.build.data", oldTestBuildData); } miniDFS.waitClusterUp(); InetSocketAddress dfsAddress = miniDFS.getNameNode().getNameNodeAddress(); dfsUri = "hdfs://" + dfsAddress.getHostName() + ":" + dfsAddress.getPort(); File coreFile = new File(config.getConfDir(), "core-site.xml"); writeConfig(coreFile, Collections.singletonMap("fs.default.name", dfsUri).entrySet()); File hdfsFile = new File(config.getConfDir(), "hdfs-site.xml"); writeConfig(hdfsFile, conf); Map<String,String> siteConfig = config.getSiteConfig(); siteConfig.put(Property.INSTANCE_VOLUMES.getKey(), dfsUri + "/accumulo"); config.setSiteConfig(siteConfig); } else if (config.useExistingInstance()) { dfsUri = config.getHadoopConfiguration().get(CommonConfigurationKeys.FS_DEFAULT_NAME_KEY); } else { dfsUri = "file:///"; } File clientConfFile = config.getClientConfFile(); // Write only the properties that correspond to ClientConfiguration properties writeConfigProperties(clientConfFile, Maps.filterEntries(config.getSiteConfig(), v -> org.apache.accumulo.core.client.ClientConfiguration.ClientProperty .getPropertyByKey(v.getKey()) != null)); Map<String,String> clientProps = config.getClientProps(); clientProps.put(ClientProperty.INSTANCE_ZOOKEEPERS.getKey(), config.getZooKeepers()); clientProps.put(ClientProperty.INSTANCE_NAME.getKey(), config.getInstanceName()); if (!clientProps.containsKey(ClientProperty.AUTH_TYPE.getKey())) { clientProps.put(ClientProperty.AUTH_TYPE.getKey(), "password"); clientProps.put(ClientProperty.AUTH_PRINCIPAL.getKey(), config.getRootUserName()); clientProps.put(ClientProperty.AUTH_TOKEN.getKey(), config.getRootPassword()); } File clientPropsFile = config.getClientPropsFile(); writeConfigProperties(clientPropsFile, clientProps); File siteFile = new File(config.getConfDir(), "accumulo.properties"); writeConfigProperties(siteFile, config.getSiteConfig()); siteConfig = SiteConfiguration.fromFile(siteFile).build(); if (!config.useExistingInstance() && !config.useExistingZooKeepers()) { zooCfgFile = new File(config.getConfDir(), "zoo.cfg"); FileWriter fileWriter = new FileWriter(zooCfgFile, UTF_8); // zookeeper uses Properties to read its config, so use that to write in order to properly // escape things like Windows paths Properties zooCfg = new Properties(); zooCfg.setProperty("tickTime", "2000"); zooCfg.setProperty("initLimit", "10"); zooCfg.setProperty("syncLimit", "5"); zooCfg.setProperty("clientPortAddress", "127.0.0.1"); zooCfg.setProperty("clientPort", config.getZooKeeperPort() + ""); zooCfg.setProperty("maxClientCnxns", "1000"); zooCfg.setProperty("dataDir", config.getZooKeeperDir().getAbsolutePath()); zooCfg.setProperty("4lw.commands.whitelist", "ruok,wchs"); zooCfg.setProperty("admin.enableServer", "false"); zooCfg.store(fileWriter, null); fileWriter.close(); } clusterControl = new MiniAccumuloClusterControl(this); } private static void mkdirs(File dir) { if (!dir.mkdirs()) { log.warn("Unable to create {}", dir); } } private void writeConfig(File file, Iterable<Map.Entry<String,String>> settings) throws IOException { FileWriter fileWriter = new FileWriter(file, UTF_8); fileWriter.append("<configuration>\n"); for (Entry<String,String> entry : settings) { String value = entry.getValue().replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"); fileWriter.append( "<property><name>" + entry.getKey() + "</name><value>" + value + "</value></property>\n"); } fileWriter.append("</configuration>\n"); fileWriter.close(); } private void writeConfigProperties(File file, Map<String,String> settings) throws IOException { FileWriter fileWriter = new FileWriter(file, UTF_8); for (Entry<String,String> entry : settings.entrySet()) { fileWriter.append(entry.getKey() + "=" + entry.getValue() + "\n"); } fileWriter.close(); } /** * Starts Accumulo and Zookeeper processes. Can only be called once. */ @SuppressFBWarnings(value = "UNENCRYPTED_SOCKET", justification = "insecure socket used for reservation") @Override public synchronized void start() throws IOException, InterruptedException { if (config.useMiniDFS() && miniDFS == null) { throw new IllegalStateException("Cannot restart mini when using miniDFS"); } MiniAccumuloClusterControl control = getClusterControl(); if (config.useExistingInstance()) { AccumuloConfiguration acuConf = config.getAccumuloConfiguration(); Configuration hadoopConf = config.getHadoopConfiguration(); ServerDirs serverDirs = new ServerDirs(acuConf, hadoopConf); ConfigurationCopy cc = new ConfigurationCopy(acuConf); Path instanceIdPath; try (var fs = getServerContext().getVolumeManager()) { instanceIdPath = serverDirs.getInstanceIdLocation(fs.getFirst()); } catch (IOException e) { throw new RuntimeException(e); } String instanceIdFromFile = VolumeManager.getInstanceIDFromHdfs(instanceIdPath, hadoopConf); ZooReaderWriter zrw = new ZooReaderWriter(cc.get(Property.INSTANCE_ZK_HOST), (int) cc.getTimeInMillis(Property.INSTANCE_ZK_TIMEOUT), cc.get(Property.INSTANCE_SECRET)); String rootPath = ZooUtil.getRoot(instanceIdFromFile); String instanceName = null; try { for (String name : zrw.getChildren(Constants.ZROOT + Constants.ZINSTANCES)) { String instanceNamePath = Constants.ZROOT + Constants.ZINSTANCES + "/" + name; byte[] bytes = zrw.getData(instanceNamePath); String iid = new String(bytes, UTF_8); if (iid.equals(instanceIdFromFile)) { instanceName = name; } } } catch (KeeperException e) { throw new RuntimeException("Unable to read instance name from zookeeper.", e); } if (instanceName == null) { throw new RuntimeException("Unable to read instance name from zookeeper."); } config.setInstanceName(instanceName); if (!AccumuloStatus.isAccumuloOffline(zrw, rootPath)) { throw new RuntimeException( "The Accumulo instance being used is already running. Aborting."); } } else { if (!initialized) { Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { MiniAccumuloClusterImpl.this.stop(); } catch (IOException e) { log.error("IOException while attempting to stop the MiniAccumuloCluster.", e); } catch (InterruptedException e) { log.error("The stopping of MiniAccumuloCluster was interrupted.", e); } })); } if (!config.useExistingZooKeepers()) { control.start(ServerType.ZOOKEEPER); } if (!initialized) { if (!config.useExistingZooKeepers()) { // sleep a little bit to let zookeeper come up before calling init, seems to work better long startTime = System.currentTimeMillis(); while (true) { try (Socket s = new Socket("localhost", config.getZooKeeperPort())) { s.setReuseAddress(true); s.getOutputStream().write("ruok\n".getBytes()); s.getOutputStream().flush(); byte[] buffer = new byte[100]; int n = s.getInputStream().read(buffer); if (n >= 4 && new String(buffer, 0, 4).equals("imok")) { break; } } catch (Exception e) { if (System.currentTimeMillis() - startTime >= config.getZooKeeperStartupTime()) { throw new ZooKeeperBindException("Zookeeper did not start within " + (config.getZooKeeperStartupTime() / 1000) + " seconds. Check the logs in " + config.getLogDir() + " for errors. Last exception: " + e); } // Don't spin absurdly fast sleepUninterruptibly(250, TimeUnit.MILLISECONDS); } } } LinkedList<String> args = new LinkedList<>(); args.add("--instance-name"); args.add(config.getInstanceName()); args.add("--user"); args.add(config.getRootUserName()); args.add("--clear-instance-name"); // If we aren't using SASL, add in the root password final String saslEnabled = config.getSiteConfig().get(Property.INSTANCE_RPC_SASL_ENABLED.getKey()); if (saslEnabled == null || !Boolean.parseBoolean(saslEnabled)) { args.add("--password"); args.add(config.getRootPassword()); } Process initProcess = exec(Initialize.class, args.toArray(new String[0])).getProcess(); int ret = initProcess.waitFor(); if (ret != 0) { throw new RuntimeException("Initialize process returned " + ret + ". Check the logs in " + config.getLogDir() + " for errors."); } initialized = true; } } log.info("Starting MAC against instance {} and zookeeper(s) {}.", config.getInstanceName(), config.getZooKeepers()); control.start(ServerType.TABLET_SERVER); int ret = 0; for (int i = 0; i < 5; i++) { ret = exec(Main.class, SetGoalState.class.getName(), ManagerGoalState.NORMAL.toString()) .getProcess().waitFor(); if (ret == 0) { break; } sleepUninterruptibly(1, TimeUnit.SECONDS); } if (ret != 0) { throw new RuntimeException("Could not set manager goal state, process returned " + ret + ". Check the logs in " + config.getLogDir() + " for errors."); } control.start(ServerType.MANAGER); control.start(ServerType.GARBAGE_COLLECTOR); if (executor == null) { executor = Executors.newSingleThreadExecutor(); } verifyUp(); } private void verifyUp() throws InterruptedException, IOException { int numTries = 10; requireNonNull(getClusterControl().managerProcess, "Error starting Manager - no process"); requireNonNull(getClusterControl().managerProcess.info().startInstant().get(), "Error starting Manager - instance not started"); requireNonNull(getClusterControl().gcProcess, "Error starting GC - no process"); requireNonNull(getClusterControl().gcProcess.info().startInstant().get(), "Error starting GC - instance not started"); int tsExpectedCount = 0; for (Process tsp : getClusterControl().tabletServerProcesses) { tsExpectedCount++; requireNonNull(tsp, "Error starting TabletServer " + tsExpectedCount + " - no process"); requireNonNull(tsp.info().startInstant().get(), "Error starting TabletServer " + tsExpectedCount + "- instance not started"); } try (ZooKeeper zk = new ZooKeeper(getZooKeepers(), 60000, null)) { String secret = getSiteConfiguration().get(Property.INSTANCE_SECRET); for (int i = 0; i < numTries; i++) { if (zk.getState().equals(States.CONNECTED)) { ZooUtil.digestAuth(zk, secret); break; } else UtilWaitThread.sleep(1000); } String instanceId = null; try { for (String name : zk.getChildren(Constants.ZROOT + Constants.ZINSTANCES, null)) { if (name.equals(config.getInstanceName())) { String instanceNamePath = Constants.ZROOT + Constants.ZINSTANCES + "/" + name; byte[] bytes = zk.getData(instanceNamePath, null, null); instanceId = new String(bytes, UTF_8); break; } } } catch (KeeperException e) { throw new RuntimeException("Unable to read instance id from zookeeper.", e); } if (instanceId == null) { throw new RuntimeException("Unable to find instance id from zookeeper."); } String rootPath = Constants.ZROOT + "/" + instanceId; int tsActualCount = 0; try { while (tsActualCount < tsExpectedCount) { tsActualCount = 0; for (String child : zk.getChildren(rootPath + Constants.ZTSERVERS, null)) { if (zk.getChildren(rootPath + Constants.ZTSERVERS + "/" + child, null).isEmpty()) { log.info("TServer " + tsActualCount + " not yet present in ZooKeeper"); } else { tsActualCount++; log.info("TServer " + tsActualCount + " present in ZooKeeper"); } } Thread.sleep(500); } } catch (KeeperException e) { throw new RuntimeException("Unable to read TServer information from zookeeper.", e); } try { while (zk.getChildren(rootPath + Constants.ZMANAGER_LOCK, null).isEmpty()) { log.info("Manager not yet present in ZooKeeper"); Thread.sleep(500); } } catch (KeeperException e) { throw new RuntimeException("Unable to read Manager information from zookeeper.", e); } try { while (zk.getChildren(rootPath + Constants.ZGC_LOCK, null).isEmpty()) { log.info("GC not yet present in ZooKeeper"); Thread.sleep(500); } } catch (KeeperException e) { throw new RuntimeException("Unable to read GC information from zookeeper.", e); } } } private List<String> buildRemoteDebugParams(int port) { return Collections.singletonList( String.format("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=%d", port)); } /** * @return generated remote debug ports if in debug mode. * @since 1.6.0 */ public Set<Pair<ServerType,Integer>> getDebugPorts() { return debugPorts; } List<ProcessReference> references(Process... procs) { List<ProcessReference> result = new ArrayList<>(); for (Process proc : procs) { result.add(new ProcessReference(proc)); } return result; } public Map<ServerType,Collection<ProcessReference>> getProcesses() { Map<ServerType,Collection<ProcessReference>> result = new HashMap<>(); MiniAccumuloClusterControl control = getClusterControl(); result.put(ServerType.MANAGER, references(control.managerProcess)); result.put(ServerType.TABLET_SERVER, references(control.tabletServerProcesses.toArray(new Process[0]))); if (control.zooKeeperProcess != null) { result.put(ServerType.ZOOKEEPER, references(control.zooKeeperProcess)); } if (control.gcProcess != null) { result.put(ServerType.GARBAGE_COLLECTOR, references(control.gcProcess)); } return result; } public void killProcess(ServerType type, ProcessReference proc) throws ProcessNotFoundException, InterruptedException { getClusterControl().killProcess(type, proc); } @Override public String getInstanceName() { return config.getInstanceName(); } @Override public String getZooKeepers() { return config.getZooKeepers(); } @Override public synchronized ServerContext getServerContext() { if (context == null) { context = new ServerContext(siteConfig); } return context; } /** * Stops Accumulo and Zookeeper processes. If stop is not called, there is a shutdown hook that is * setup to kill the processes. However it's probably best to call stop in a finally block as soon * as possible. */ @Override public synchronized void stop() throws IOException, InterruptedException { if (executor == null) { // keep repeated calls to stop() from failing return; } MiniAccumuloClusterControl control = getClusterControl(); control.stop(ServerType.GARBAGE_COLLECTOR, null); control.stop(ServerType.MANAGER, null); control.stop(ServerType.TABLET_SERVER, null); control.stop(ServerType.ZOOKEEPER, null); // ACCUMULO-2985 stop the ExecutorService after we finished using it to stop accumulo procs if (executor != null) { List<Runnable> tasksRemaining = executor.shutdownNow(); // the single thread executor shouldn't have any pending tasks, but check anyways if (!tasksRemaining.isEmpty()) { log.warn( "Unexpectedly had {} task(s) remaining in threadpool for execution when being stopped", tasksRemaining.size()); } executor = null; } if (config.useMiniDFS() && miniDFS != null) { miniDFS.shutdown(); } for (Process p : cleanup) { p.destroy(); p.waitFor(); } miniDFS = null; } /** * @since 1.6.0 */ public MiniAccumuloConfigImpl getConfig() { return config; } @Override public AccumuloClient createAccumuloClient(String user, AuthenticationToken token) { return Accumulo.newClient().from(getClientProperties()).as(user, token).build(); } @SuppressWarnings("deprecation") @Override public org.apache.accumulo.core.client.ClientConfiguration getClientConfig() { return org.apache.accumulo.core.client.ClientConfiguration.fromMap(config.getSiteConfig()) .withInstance(this.getInstanceName()).withZkHosts(this.getZooKeepers()); } @Override public synchronized Properties getClientProperties() { if (clientProperties == null) { clientProperties = Accumulo.newClientProperties().from(config.getClientPropsFile().toPath()).build(); } return clientProperties; } @Override public FileSystem getFileSystem() { try { return FileSystem.get(new URI(dfsUri), new Configuration()); } catch (Exception e) { throw new RuntimeException(e); } } @VisibleForTesting protected void setShutdownExecutor(ExecutorService svc) { this.executor = svc; } @VisibleForTesting protected ExecutorService getShutdownExecutor() { return executor; } public int stopProcessWithTimeout(final Process proc, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { FutureTask<Integer> future = new FutureTask<>(() -> { proc.destroy(); return proc.waitFor(); }); executor.execute(future); return future.get(timeout, unit); } /** * Get programmatic interface to information available in a normal monitor. XXX the returned * structure won't contain information about the metadata table until there is data in it. e.g. if * you want to see the metadata table you should create a table. * * @since 1.6.1 */ public ManagerMonitorInfo getManagerMonitorInfo() throws AccumuloException, AccumuloSecurityException { try (AccumuloClient c = Accumulo.newClient().from(getClientProperties()).build()) { while (true) { ManagerClientService.Iface client = null; try { client = ManagerClient.getConnectionWithRetry((ClientContext) c); return client.getManagerStats(TraceUtil.traceInfo(), ((ClientContext) c).rpcCreds()); } catch (ThriftSecurityException exception) { throw new AccumuloSecurityException(exception); } catch (ThriftNotActiveServiceException e) { // Let it loop, fetching a new location log.debug("Contacted a Manager which is no longer active, retrying"); sleepUninterruptibly(100, TimeUnit.MILLISECONDS); } catch (TException exception) { throw new AccumuloException(exception); } finally { if (client != null) { ManagerClient.close(client, (ClientContext) c); } } } } } public synchronized MiniDFSCluster getMiniDfs() { return this.miniDFS; } @Override public MiniAccumuloClusterControl getClusterControl() { return clusterControl; } @Override public Path getTemporaryPath() { String p; if (config.useMiniDFS()) { p = "/tmp/"; } else { File tmp = new File(config.getDir(), "tmp"); mkdirs(tmp); p = tmp.toString(); } return getFileSystem().makeQualified(new Path(p)); } @Override public AccumuloConfiguration getSiteConfiguration() { return new ConfigurationCopy( Iterables.concat(DefaultConfiguration.getInstance(), config.getSiteConfig().entrySet())); } @Override public String getAccumuloPropertiesPath() { return new File(config.getConfDir(), "accumulo.properties").toString(); } @Override public String getClientPropsPath() { return config.getClientPropsFile().getAbsolutePath(); } }
Add trivial ZK Watcher to MiniAccumuloClusterImpl (#2434) Add a trivial watcher to MiniAccumuloClusterImpl.verifyUp to avoid an annoying ERROR coming from ZooKeeper that is logged when a ZooKeeper client is constructed with a null Watcher. Also address comments on #2414 to remove the redundant use of requireNonNull for calls to Optional.get(). Instead, use a private helper method to wait for the Process to be recorded as having a start time, up to 10 seconds. So, instead of expecting the start time to be non-null, it is now expected to be non-null within 10 seconds, and it does so using Optional.isEmpty() instead of requireNonNull. This fixes #2431
minicluster/src/main/java/org/apache/accumulo/miniclusterImpl/MiniAccumuloClusterImpl.java
Add trivial ZK Watcher to MiniAccumuloClusterImpl (#2434)
<ide><path>inicluster/src/main/java/org/apache/accumulo/miniclusterImpl/MiniAccumuloClusterImpl.java <ide> <ide> import static java.nio.charset.StandardCharsets.UTF_8; <ide> import static java.util.Objects.requireNonNull; <add>import static java.util.concurrent.TimeUnit.NANOSECONDS; <ide> import static org.apache.accumulo.fate.util.UtilWaitThread.sleepUninterruptibly; <ide> <ide> import java.io.File; <ide> import org.apache.accumulo.core.manager.thrift.ManagerMonitorInfo; <ide> import org.apache.accumulo.core.trace.TraceUtil; <ide> import org.apache.accumulo.core.util.Pair; <del>import org.apache.accumulo.fate.util.UtilWaitThread; <ide> import org.apache.accumulo.fate.zookeeper.ZooReaderWriter; <ide> import org.apache.accumulo.fate.zookeeper.ZooUtil; <ide> import org.apache.accumulo.manager.state.SetGoalState; <ide> <ide> } <ide> <add> // wait up to 10 seconds for the process to start <add> private static void waitForProcessStart(Process p, String name) throws InterruptedException { <add> long start = System.nanoTime(); <add> while (p.info().startInstant().isEmpty()) { <add> if (NANOSECONDS.toSeconds(System.nanoTime() - start) > 10) { <add> throw new IllegalStateException( <add> "Error starting " + name + " - instance not started within 10 seconds"); <add> } <add> Thread.sleep(50); <add> } <add> } <add> <ide> private void verifyUp() throws InterruptedException, IOException { <ide> <ide> int numTries = 10; <ide> <ide> requireNonNull(getClusterControl().managerProcess, "Error starting Manager - no process"); <del> requireNonNull(getClusterControl().managerProcess.info().startInstant().get(), <del> "Error starting Manager - instance not started"); <add> waitForProcessStart(getClusterControl().managerProcess, "Manager"); <ide> <ide> requireNonNull(getClusterControl().gcProcess, "Error starting GC - no process"); <del> requireNonNull(getClusterControl().gcProcess.info().startInstant().get(), <del> "Error starting GC - instance not started"); <add> waitForProcessStart(getClusterControl().gcProcess, "GC"); <ide> <ide> int tsExpectedCount = 0; <ide> for (Process tsp : getClusterControl().tabletServerProcesses) { <ide> tsExpectedCount++; <ide> requireNonNull(tsp, "Error starting TabletServer " + tsExpectedCount + " - no process"); <del> requireNonNull(tsp.info().startInstant().get(), <del> "Error starting TabletServer " + tsExpectedCount + "- instance not started"); <del> } <del> <del> try (ZooKeeper zk = new ZooKeeper(getZooKeepers(), 60000, null)) { <add> waitForProcessStart(tsp, "TabletServer" + tsExpectedCount); <add> } <add> <add> try (ZooKeeper zk = new ZooKeeper(getZooKeepers(), 60000, event -> log.info("{}", event))) { <ide> <ide> String secret = getSiteConfiguration().get(Property.INSTANCE_SECRET); <ide> <ide> if (zk.getState().equals(States.CONNECTED)) { <ide> ZooUtil.digestAuth(zk, secret); <ide> break; <del> } else <del> UtilWaitThread.sleep(1000); <add> } else { <add> Thread.sleep(1000); <add> } <ide> } <ide> <ide> String instanceId = null;
Java
apache-2.0
41d34406b82661cb7fd52c98847478190ce98872
0
phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida
package ca.corefacility.bioinformatics.irida.service.impl.integration; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Set; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.junit.Assume; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.security.test.context.support.WithSecurityContextTestExcecutionListener; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import ca.corefacility.bioinformatics.irida.config.IridaApiGalaxyTestConfig; import ca.corefacility.bioinformatics.irida.config.conditions.WindowsPlatformCondition; import ca.corefacility.bioinformatics.irida.exceptions.IridaWorkflowNotFoundException; import ca.corefacility.bioinformatics.irida.model.enums.AnalysisState; import ca.corefacility.bioinformatics.irida.model.user.User; import ca.corefacility.bioinformatics.irida.model.workflow.submission.AnalysisSubmission; import ca.corefacility.bioinformatics.irida.repositories.analysis.submission.AnalysisSubmissionRepository; import ca.corefacility.bioinformatics.irida.repositories.user.UserRepository; import ca.corefacility.bioinformatics.irida.service.AnalysisExecutionScheduledTask; import ca.corefacility.bioinformatics.irida.service.DatabaseSetupGalaxyITService; import ca.corefacility.bioinformatics.irida.service.analysis.execution.AnalysisExecutionService; import ca.corefacility.bioinformatics.irida.service.impl.AnalysisExecutionScheduledTaskImpl; import com.github.springtestdbunit.DbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.google.common.collect.Sets; /** * Integration tests for analysis schedulers. * * @author Aaron Petkau <[email protected]> * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { IridaApiGalaxyTestConfig.class }) @ActiveProfiles("test") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class, WithSecurityContextTestExcecutionListener.class }) @DatabaseSetup("/ca/corefacility/bioinformatics/irida/repositories/analysis/AnalysisRepositoryIT.xml") @DatabaseTearDown("/ca/corefacility/bioinformatics/irida/test/integration/TableReset.xml") public class AnalysisExecutionScheduledTaskImplIT { @Autowired private DatabaseSetupGalaxyITService analysisExecutionGalaxyITService; @Autowired private AnalysisSubmissionRepository analysisSubmissionRepository; @Autowired private AnalysisExecutionService analysisExecutionService; @Autowired private UserRepository userRepository; private AnalysisExecutionScheduledTask analysisExecutionScheduledTask; private Path sequenceFilePath; private Path sequenceFilePath2; private Path referenceFilePath; private Path referenceFilePath2; private UUID validIridaWorkflowId = UUID.fromString("1f9ea289-5053-4e4a-bc76-1f0c60b179f8"); private UUID invalidIridaWorkflowId = UUID.fromString("8ec369e8-1b39-4b9a-97a1-70ac1f6cc9e6"); private User analysisSubmitter; /** * Sets up variables for testing. * * @throws URISyntaxException * @throws IOException */ @Before public void setup() throws URISyntaxException, IOException { Assume.assumeFalse(WindowsPlatformCondition.isWindows()); analysisExecutionScheduledTask = new AnalysisExecutionScheduledTaskImpl(analysisSubmissionRepository, analysisExecutionService); Path sequenceFilePathReal = Paths .get(DatabaseSetupGalaxyITService.class.getResource("testData1.fastq").toURI()); Path referenceFilePathReal = Paths.get(DatabaseSetupGalaxyITService.class.getResource("testReference.fasta") .toURI()); sequenceFilePath = Files.createTempFile("testData1", ".fastq"); Files.delete(sequenceFilePath); Files.copy(sequenceFilePathReal, sequenceFilePath); sequenceFilePath2 = Files.createTempFile("testData1", ".fastq"); Files.delete(sequenceFilePath2); Files.copy(sequenceFilePathReal, sequenceFilePath2); referenceFilePath = Files.createTempFile("testReference", ".fasta"); Files.delete(referenceFilePath); Files.copy(referenceFilePathReal, referenceFilePath); referenceFilePath2 = Files.createTempFile("testReference", ".fasta"); Files.delete(referenceFilePath2); Files.copy(referenceFilePathReal, referenceFilePath2); analysisSubmitter = userRepository.findOne(1L); } /** * Tests out successfully executing an analysis submission, from newly * created to downloading results. * * @throws Exception */ @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void testFullAnalysisRunSuccess() throws Exception { AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L, sequenceFilePath, referenceFilePath, validIridaWorkflowId); validateFullAnalysis(Sets.newHashSet(analysisSubmission), 1); } /** * Tests out successfully executing two analyses submissions, from newly * created to downloading results. * * @throws Exception */ @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void testFullAnalysisRunSuccessTwoSubmissions() throws Exception { AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L, sequenceFilePath, referenceFilePath, validIridaWorkflowId); AnalysisSubmission analysisSubmission2 = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L, sequenceFilePath2, referenceFilePath2, validIridaWorkflowId); validateFullAnalysis(Sets.newHashSet(analysisSubmission, analysisSubmission2), 2); } /** * Tests out successfully executing analysis scheduled tasks with no submissions. * * @throws Exception */ @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void testFullAnalysisRunSuccessNoSubmissions() throws Exception { validateFullAnalysis(Sets.newHashSet(), 0); } /** * Tests out successfully executing only one analysis when another analysis * is already in an error state. * * @throws Exception */ @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void testFullAnalysisRunSuccessOneSubmissionOneError() throws Exception { AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L, sequenceFilePath, referenceFilePath, validIridaWorkflowId); AnalysisSubmission analysisSubmission2 = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L, sequenceFilePath2, referenceFilePath2, validIridaWorkflowId); analysisSubmission2.setAnalysisState(AnalysisState.ERROR); analysisSubmissionRepository.save(analysisSubmission2); validateFullAnalysis(Sets.newHashSet(analysisSubmission, analysisSubmission2), 1); AnalysisSubmission loadedSubmission2 = analysisSubmissionRepository.findOne(analysisSubmission2.getId()); assertEquals(AnalysisState.ERROR, loadedSubmission2.getAnalysisState()); } /** * Tests out failing to prepare an analysis due to an invalid workflow. * * @throws Throwable */ @Test(expected = IridaWorkflowNotFoundException.class) @WithMockUser(username = "aaron", roles = "ADMIN") public void testFullAnalysisRunFailInvalidWorkflow() throws Throwable { AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L, sequenceFilePath, referenceFilePath, invalidIridaWorkflowId); try { validateFullAnalysis(Sets.newHashSet(analysisSubmission), 1); } catch (ExecutionException e) { AnalysisSubmission loadedSubmission = analysisSubmissionRepository.findOne(analysisSubmission.getId()); assertEquals(AnalysisState.ERROR, loadedSubmission.getAnalysisState()); throw e.getCause(); } } /** * Tests out failing to complete execution of a workflow due to an error * with the status. * * @throws Throwable */ @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void testFullAnalysisRunFailInvalidWorkflowStatus() throws Throwable { analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L, sequenceFilePath, referenceFilePath, validIridaWorkflowId); // PREPARE SUBMISSION Set<Future<AnalysisSubmission>> submissionsFutureSet = analysisExecutionScheduledTask.prepareAnalyses(); assertEquals(1, submissionsFutureSet.size()); // wait until finished for (Future<AnalysisSubmission> submissionFuture : submissionsFutureSet) { AnalysisSubmission returnedSubmission = submissionFuture.get(); assertEquals(AnalysisState.PREPARED, returnedSubmission.getAnalysisState()); } // EXECUTE SUBMISSION submissionsFutureSet = analysisExecutionScheduledTask.executeAnalyses(); assertEquals(1, submissionsFutureSet.size()); // wait until finished AnalysisSubmission returnedSubmission = submissionsFutureSet.iterator().next().get(); assertEquals(AnalysisState.RUNNING, returnedSubmission.getAnalysisState()); // Modify remoteAnalysisId so getting the status fails returnedSubmission.setRemoteAnalysisId("invalid"); analysisSubmissionRepository.save(returnedSubmission); // CHECK GALAXY STATUS submissionsFutureSet = analysisExecutionScheduledTask.monitorRunningAnalyses(); // Should be in error state assertEquals(1, submissionsFutureSet.size()); returnedSubmission = submissionsFutureSet.iterator().next().get(); assertEquals(AnalysisState.ERROR, returnedSubmission.getAnalysisState()); } /** * Tests out failure to run analysis due to authentication error. * * @throws Exception */ @Test(expected = AuthenticationCredentialsNotFoundException.class) @WithMockUser(username = "aaron", roles = "ADMIN") public void testFullAnalysisRunFailAuthentication() throws Exception { AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L, sequenceFilePath, referenceFilePath, validIridaWorkflowId); SecurityContextHolder.clearContext(); validateFullAnalysis(Sets.newHashSet(analysisSubmission), 1); } /** * Performs a full analysis to completion on the passed submissions. * * @param submissions * The submission to attempt to perform and validate a full * analysis on. * @param expectedSubmissionsToProcess * The expected number of submissions to pick up and process. * @throws Exception * On any exception. */ private void validateFullAnalysis(Set<AnalysisSubmission> submissions, int expectedSubmissionsToProcess) throws Exception { // PREPARE SUBMISSION Set<Future<AnalysisSubmission>> submissionsFutureSet = analysisExecutionScheduledTask.prepareAnalyses(); assertEquals(expectedSubmissionsToProcess, submissionsFutureSet.size()); // wait until finished for (Future<AnalysisSubmission> submissionFuture : submissionsFutureSet) { AnalysisSubmission returnedSubmission = submissionFuture.get(); assertEquals(AnalysisState.PREPARED, returnedSubmission.getAnalysisState()); } // EXECUTE SUBMISSION submissionsFutureSet = analysisExecutionScheduledTask.executeAnalyses(); assertEquals(expectedSubmissionsToProcess, submissionsFutureSet.size()); // wait until finished for (Future<AnalysisSubmission> submissionFuture : submissionsFutureSet) { AnalysisSubmission returnedSubmission = submissionFuture.get(); assertEquals(AnalysisState.RUNNING, returnedSubmission.getAnalysisState()); // wait until Galaxy finished analysisExecutionGalaxyITService.waitUntilSubmissionComplete(returnedSubmission); } // CHECK GALAXY STATUS submissionsFutureSet = analysisExecutionScheduledTask.monitorRunningAnalyses(); assertEquals(expectedSubmissionsToProcess, submissionsFutureSet.size()); // wait until finished for (Future<AnalysisSubmission> submissionFuture : submissionsFutureSet) { AnalysisSubmission returnedSubmission = submissionFuture.get(); assertEquals(AnalysisState.FINISHED_RUNNING, returnedSubmission.getAnalysisState()); } // TRANSFER SUBMISSION RESULTS submissionsFutureSet = analysisExecutionScheduledTask.transferAnalysesResults(); assertEquals(expectedSubmissionsToProcess, submissionsFutureSet.size()); // wait until finished for (Future<AnalysisSubmission> submissionFuture : submissionsFutureSet) { AnalysisSubmission returnedSubmission = submissionFuture.get(); assertEquals(AnalysisState.COMPLETED, returnedSubmission.getAnalysisState()); assertEquals(analysisSubmitter, returnedSubmission.getSubmitter()); } } }
src/test/java/ca/corefacility/bioinformatics/irida/service/impl/integration/AnalysisExecutionScheduledTaskImplIT.java
package ca.corefacility.bioinformatics.irida.service.impl.integration; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Set; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.junit.Assume; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.security.test.context.support.WithSecurityContextTestExcecutionListener; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import ca.corefacility.bioinformatics.irida.config.IridaApiGalaxyTestConfig; import ca.corefacility.bioinformatics.irida.config.conditions.WindowsPlatformCondition; import ca.corefacility.bioinformatics.irida.exceptions.IridaWorkflowNotFoundException; import ca.corefacility.bioinformatics.irida.model.enums.AnalysisState; import ca.corefacility.bioinformatics.irida.model.workflow.submission.AnalysisSubmission; import ca.corefacility.bioinformatics.irida.repositories.analysis.submission.AnalysisSubmissionRepository; import ca.corefacility.bioinformatics.irida.service.AnalysisExecutionScheduledTask; import ca.corefacility.bioinformatics.irida.service.DatabaseSetupGalaxyITService; import ca.corefacility.bioinformatics.irida.service.analysis.execution.AnalysisExecutionService; import ca.corefacility.bioinformatics.irida.service.impl.AnalysisExecutionScheduledTaskImpl; import com.github.springtestdbunit.DbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.google.common.collect.Sets; /** * Integration tests for analysis schedulers. * * @author Aaron Petkau <[email protected]> * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { IridaApiGalaxyTestConfig.class }) @ActiveProfiles("test") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class, WithSecurityContextTestExcecutionListener.class }) @DatabaseSetup("/ca/corefacility/bioinformatics/irida/repositories/analysis/AnalysisRepositoryIT.xml") @DatabaseTearDown("/ca/corefacility/bioinformatics/irida/test/integration/TableReset.xml") public class AnalysisExecutionScheduledTaskImplIT { @Autowired private DatabaseSetupGalaxyITService analysisExecutionGalaxyITService; @Autowired private AnalysisSubmissionRepository analysisSubmissionRepository; @Autowired private AnalysisExecutionService analysisExecutionService; private AnalysisExecutionScheduledTask analysisExecutionScheduledTask; private Path sequenceFilePath; private Path sequenceFilePath2; private Path referenceFilePath; private Path referenceFilePath2; private UUID validIridaWorkflowId = UUID.fromString("1f9ea289-5053-4e4a-bc76-1f0c60b179f8"); private UUID invalidIridaWorkflowId = UUID.fromString("8ec369e8-1b39-4b9a-97a1-70ac1f6cc9e6"); /** * Sets up variables for testing. * * @throws URISyntaxException * @throws IOException */ @Before public void setup() throws URISyntaxException, IOException { Assume.assumeFalse(WindowsPlatformCondition.isWindows()); analysisExecutionScheduledTask = new AnalysisExecutionScheduledTaskImpl(analysisSubmissionRepository, analysisExecutionService); Path sequenceFilePathReal = Paths .get(DatabaseSetupGalaxyITService.class.getResource("testData1.fastq").toURI()); Path referenceFilePathReal = Paths.get(DatabaseSetupGalaxyITService.class.getResource("testReference.fasta") .toURI()); sequenceFilePath = Files.createTempFile("testData1", ".fastq"); Files.delete(sequenceFilePath); Files.copy(sequenceFilePathReal, sequenceFilePath); sequenceFilePath2 = Files.createTempFile("testData1", ".fastq"); Files.delete(sequenceFilePath2); Files.copy(sequenceFilePathReal, sequenceFilePath2); referenceFilePath = Files.createTempFile("testReference", ".fasta"); Files.delete(referenceFilePath); Files.copy(referenceFilePathReal, referenceFilePath); referenceFilePath2 = Files.createTempFile("testReference", ".fasta"); Files.delete(referenceFilePath2); Files.copy(referenceFilePathReal, referenceFilePath2); } /** * Tests out successfully executing an analysis submission, from newly * created to downloading results. * * @throws Exception */ @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void testFullAnalysisRunSuccess() throws Exception { AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L, sequenceFilePath, referenceFilePath, validIridaWorkflowId); validateFullAnalysis(Sets.newHashSet(analysisSubmission), 1); } /** * Tests out successfully executing two analyses submissions, from newly * created to downloading results. * * @throws Exception */ @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void testFullAnalysisRunSuccessTwoSubmissions() throws Exception { AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L, sequenceFilePath, referenceFilePath, validIridaWorkflowId); AnalysisSubmission analysisSubmission2 = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L, sequenceFilePath2, referenceFilePath2, validIridaWorkflowId); validateFullAnalysis(Sets.newHashSet(analysisSubmission, analysisSubmission2), 2); } /** * Tests out successfully executing analysis scheduled tasks with no submissions. * * @throws Exception */ @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void testFullAnalysisRunSuccessNoSubmissions() throws Exception { validateFullAnalysis(Sets.newHashSet(), 0); } /** * Tests out successfully executing only one analysis when another analysis * is already in an error state. * * @throws Exception */ @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void testFullAnalysisRunSuccessOneSubmissionOneError() throws Exception { AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L, sequenceFilePath, referenceFilePath, validIridaWorkflowId); AnalysisSubmission analysisSubmission2 = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L, sequenceFilePath2, referenceFilePath2, validIridaWorkflowId); analysisSubmission2.setAnalysisState(AnalysisState.ERROR); analysisSubmissionRepository.save(analysisSubmission2); validateFullAnalysis(Sets.newHashSet(analysisSubmission, analysisSubmission2), 1); AnalysisSubmission loadedSubmission2 = analysisSubmissionRepository.findOne(analysisSubmission2.getId()); assertEquals(AnalysisState.ERROR, loadedSubmission2.getAnalysisState()); } /** * Tests out failing to prepare an analysis due to an invalid workflow. * * @throws Throwable */ @Test(expected = IridaWorkflowNotFoundException.class) @WithMockUser(username = "aaron", roles = "ADMIN") public void testFullAnalysisRunFailInvalidWorkflow() throws Throwable { AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L, sequenceFilePath, referenceFilePath, invalidIridaWorkflowId); try { validateFullAnalysis(Sets.newHashSet(analysisSubmission), 1); } catch (ExecutionException e) { AnalysisSubmission loadedSubmission = analysisSubmissionRepository.findOne(analysisSubmission.getId()); assertEquals(AnalysisState.ERROR, loadedSubmission.getAnalysisState()); throw e.getCause(); } } /** * Tests out failing to complete execution of a workflow due to an error * with the status. * * @throws Throwable */ @Test @WithMockUser(username = "aaron", roles = "ADMIN") public void testFullAnalysisRunFailInvalidWorkflowStatus() throws Throwable { analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L, sequenceFilePath, referenceFilePath, validIridaWorkflowId); // PREPARE SUBMISSION Set<Future<AnalysisSubmission>> submissionsFutureSet = analysisExecutionScheduledTask.prepareAnalyses(); assertEquals(1, submissionsFutureSet.size()); // wait until finished for (Future<AnalysisSubmission> submissionFuture : submissionsFutureSet) { AnalysisSubmission returnedSubmission = submissionFuture.get(); assertEquals(AnalysisState.PREPARED, returnedSubmission.getAnalysisState()); } // EXECUTE SUBMISSION submissionsFutureSet = analysisExecutionScheduledTask.executeAnalyses(); assertEquals(1, submissionsFutureSet.size()); // wait until finished AnalysisSubmission returnedSubmission = submissionsFutureSet.iterator().next().get(); assertEquals(AnalysisState.RUNNING, returnedSubmission.getAnalysisState()); // Modify remoteAnalysisId so getting the status fails returnedSubmission.setRemoteAnalysisId("invalid"); analysisSubmissionRepository.save(returnedSubmission); // CHECK GALAXY STATUS submissionsFutureSet = analysisExecutionScheduledTask.monitorRunningAnalyses(); // Should be in error state assertEquals(1, submissionsFutureSet.size()); returnedSubmission = submissionsFutureSet.iterator().next().get(); assertEquals(AnalysisState.ERROR, returnedSubmission.getAnalysisState()); } /** * Tests out failure to run analysis due to authentication error. * * @throws Exception */ @Test(expected = AuthenticationCredentialsNotFoundException.class) @WithMockUser(username = "aaron", roles = "ADMIN") public void testFullAnalysisRunFailAuthentication() throws Exception { AnalysisSubmission analysisSubmission = analysisExecutionGalaxyITService.setupSubmissionInDatabase(1L, sequenceFilePath, referenceFilePath, validIridaWorkflowId); SecurityContextHolder.clearContext(); validateFullAnalysis(Sets.newHashSet(analysisSubmission), 1); } /** * Performs a full analysis to completion on the passed submissions. * * @param submissions * The submission to attempt to perform and validate a full * analysis on. * @param expectedSubmissionsToProcess * The expected number of submissions to pick up and process. * @throws Exception * On any exception. */ private void validateFullAnalysis(Set<AnalysisSubmission> submissions, int expectedSubmissionsToProcess) throws Exception { // PREPARE SUBMISSION Set<Future<AnalysisSubmission>> submissionsFutureSet = analysisExecutionScheduledTask.prepareAnalyses(); assertEquals(expectedSubmissionsToProcess, submissionsFutureSet.size()); // wait until finished for (Future<AnalysisSubmission> submissionFuture : submissionsFutureSet) { AnalysisSubmission returnedSubmission = submissionFuture.get(); assertEquals(AnalysisState.PREPARED, returnedSubmission.getAnalysisState()); } // EXECUTE SUBMISSION submissionsFutureSet = analysisExecutionScheduledTask.executeAnalyses(); assertEquals(expectedSubmissionsToProcess, submissionsFutureSet.size()); // wait until finished for (Future<AnalysisSubmission> submissionFuture : submissionsFutureSet) { AnalysisSubmission returnedSubmission = submissionFuture.get(); assertEquals(AnalysisState.RUNNING, returnedSubmission.getAnalysisState()); // wait until Galaxy finished analysisExecutionGalaxyITService.waitUntilSubmissionComplete(returnedSubmission); } // CHECK GALAXY STATUS submissionsFutureSet = analysisExecutionScheduledTask.monitorRunningAnalyses(); assertEquals(expectedSubmissionsToProcess, submissionsFutureSet.size()); // wait until finished for (Future<AnalysisSubmission> submissionFuture : submissionsFutureSet) { AnalysisSubmission returnedSubmission = submissionFuture.get(); assertEquals(AnalysisState.FINISHED_RUNNING, returnedSubmission.getAnalysisState()); } // TRANSFER SUBMISSION RESULTS submissionsFutureSet = analysisExecutionScheduledTask.transferAnalysesResults(); assertEquals(expectedSubmissionsToProcess, submissionsFutureSet.size()); // wait until finished for (Future<AnalysisSubmission> submissionFuture : submissionsFutureSet) { AnalysisSubmission returnedSubmission = submissionFuture.get(); assertEquals(AnalysisState.COMPLETED, returnedSubmission.getAnalysisState()); } } }
Added test to make sure the user who submitted the analysis is the same when the analysis is complete
src/test/java/ca/corefacility/bioinformatics/irida/service/impl/integration/AnalysisExecutionScheduledTaskImplIT.java
Added test to make sure the user who submitted the analysis is the same when the analysis is complete
<ide><path>rc/test/java/ca/corefacility/bioinformatics/irida/service/impl/integration/AnalysisExecutionScheduledTaskImplIT.java <ide> import ca.corefacility.bioinformatics.irida.config.conditions.WindowsPlatformCondition; <ide> import ca.corefacility.bioinformatics.irida.exceptions.IridaWorkflowNotFoundException; <ide> import ca.corefacility.bioinformatics.irida.model.enums.AnalysisState; <add>import ca.corefacility.bioinformatics.irida.model.user.User; <ide> import ca.corefacility.bioinformatics.irida.model.workflow.submission.AnalysisSubmission; <ide> import ca.corefacility.bioinformatics.irida.repositories.analysis.submission.AnalysisSubmissionRepository; <add>import ca.corefacility.bioinformatics.irida.repositories.user.UserRepository; <ide> import ca.corefacility.bioinformatics.irida.service.AnalysisExecutionScheduledTask; <ide> import ca.corefacility.bioinformatics.irida.service.DatabaseSetupGalaxyITService; <ide> import ca.corefacility.bioinformatics.irida.service.analysis.execution.AnalysisExecutionService; <ide> <ide> @Autowired <ide> private AnalysisExecutionService analysisExecutionService; <add> <add> @Autowired <add> private UserRepository userRepository; <ide> <ide> private AnalysisExecutionScheduledTask analysisExecutionScheduledTask; <ide> <ide> <ide> private UUID validIridaWorkflowId = UUID.fromString("1f9ea289-5053-4e4a-bc76-1f0c60b179f8"); <ide> private UUID invalidIridaWorkflowId = UUID.fromString("8ec369e8-1b39-4b9a-97a1-70ac1f6cc9e6"); <add> <add> private User analysisSubmitter; <ide> <ide> /** <ide> * Sets up variables for testing. <ide> referenceFilePath2 = Files.createTempFile("testReference", ".fasta"); <ide> Files.delete(referenceFilePath2); <ide> Files.copy(referenceFilePathReal, referenceFilePath2); <add> <add> analysisSubmitter = userRepository.findOne(1L); <ide> } <ide> <ide> /** <ide> for (Future<AnalysisSubmission> submissionFuture : submissionsFutureSet) { <ide> AnalysisSubmission returnedSubmission = submissionFuture.get(); <ide> assertEquals(AnalysisState.COMPLETED, returnedSubmission.getAnalysisState()); <add> assertEquals(analysisSubmitter, returnedSubmission.getSubmitter()); <ide> } <ide> } <ide> }
Java
apache-2.0
d16e79a1d42f1ad92c144f80ce429c3479d280a7
0
merlimat/pulsar,yahoo/pulsar,yahoo/pulsar,merlimat/pulsar,massakam/pulsar,merlimat/pulsar,merlimat/pulsar,massakam/pulsar,yahoo/pulsar,yahoo/pulsar,merlimat/pulsar,massakam/pulsar,massakam/pulsar,massakam/pulsar,merlimat/pulsar,yahoo/pulsar,massakam/pulsar,yahoo/pulsar
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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.apache.pulsar.admin.cli; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import org.apache.pulsar.client.admin.PulsarAdmin; import org.apache.pulsar.client.admin.PulsarAdminException; import org.apache.pulsar.client.admin.PulsarAdminException.ConnectException; public abstract class CmdBase { protected final JCommander jcommander; protected final PulsarAdmin admin; @Parameter(names = { "-h", "--help" }, help = true, hidden = true) private boolean help; public CmdBase(String cmdName, PulsarAdmin admin) { this.admin = admin; jcommander = new JCommander(); jcommander.setProgramName("pulsar-admin " + cmdName); } private void tryShowCommandUsage() { try { String chosenCommand = jcommander.getParsedCommand(); jcommander.usage(chosenCommand); } catch (Exception e) { // it is caused by an invalid command, the invalid command can not be parsed System.err.println("Invalid command, please use `pulsar-admin --help` to check out how to use"); } } public boolean run(String[] args) { try { jcommander.parse(args); } catch (Exception e) { System.err.println(e.getMessage()); System.err.println(); tryShowCommandUsage(); return false; } String cmd = jcommander.getParsedCommand(); if (cmd == null) { jcommander.usage(); return false; } else { JCommander obj = jcommander.getCommands().get(cmd); CliCommand cmdObj = (CliCommand) obj.getObjects().get(0); try { cmdObj.run(); return true; } catch (ParameterException e) { System.err.println(e.getMessage()); System.err.println(); return false; } catch (ConnectException e) { System.err.println(e.getMessage()); System.err.println(); System.err.println("Error connecting to: " + admin.getServiceUrl()); return false; } catch (PulsarAdminException e) { System.err.println(e.getHttpError()); System.err.println(); System.err.println("Reason: " + e.getMessage()); return false; } catch (Exception e) { e.printStackTrace(); return false; } } } }
pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdBase.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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.apache.pulsar.admin.cli; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import org.apache.pulsar.client.admin.PulsarAdmin; import org.apache.pulsar.client.admin.PulsarAdminException; import org.apache.pulsar.client.admin.PulsarAdminException.ConnectException; public abstract class CmdBase { protected final JCommander jcommander; protected final PulsarAdmin admin; @Parameter(names = { "-h", "--help" }, help = true, hidden = true) private boolean help; public CmdBase(String cmdName, PulsarAdmin admin) { this.admin = admin; jcommander = new JCommander(); jcommander.setProgramName("pulsar-admin " + cmdName); } public boolean run(String[] args) { try { jcommander.parse(args); } catch (Exception e) { System.err.println(e.getMessage()); System.err.println(); String chosenCommand = jcommander.getParsedCommand(); jcommander.usage(chosenCommand); return false; } String cmd = jcommander.getParsedCommand(); if (cmd == null) { jcommander.usage(); return false; } else { JCommander obj = jcommander.getCommands().get(cmd); CliCommand cmdObj = (CliCommand) obj.getObjects().get(0); try { cmdObj.run(); return true; } catch (ParameterException e) { System.err.println(e.getMessage()); System.err.println(); return false; } catch (ConnectException e) { System.err.println(e.getMessage()); System.err.println(); System.err.println("Error connecting to: " + admin.getServiceUrl()); return false; } catch (PulsarAdminException e) { System.err.println(e.getHttpError()); System.err.println(); System.err.println("Reason: " + e.getMessage()); return false; } catch (Exception e) { e.printStackTrace(); return false; } } } }
Fix hangs when type invalid args at command-line (#5615) Fixes #5533 *Motivation* When we using command-line tools, it hangs after type an invalid args. *Modifications* We don't need to parse the command, just show the command usage.
pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdBase.java
Fix hangs when type invalid args at command-line (#5615)
<ide><path>ulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdBase.java <ide> jcommander.setProgramName("pulsar-admin " + cmdName); <ide> } <ide> <add> private void tryShowCommandUsage() { <add> try { <add> String chosenCommand = jcommander.getParsedCommand(); <add> jcommander.usage(chosenCommand); <add> } catch (Exception e) { <add> // it is caused by an invalid command, the invalid command can not be parsed <add> System.err.println("Invalid command, please use `pulsar-admin --help` to check out how to use"); <add> } <add> } <add> <ide> public boolean run(String[] args) { <ide> try { <ide> jcommander.parse(args); <ide> } catch (Exception e) { <ide> System.err.println(e.getMessage()); <ide> System.err.println(); <del> String chosenCommand = jcommander.getParsedCommand(); <del> jcommander.usage(chosenCommand); <add> tryShowCommandUsage(); <ide> return false; <ide> } <ide>
Java
lgpl-2.1
596af994f8ece302472848fbdbd7fabdae1e36f5
0
deegree/deegree3,deegree/deegree3,deegree/deegree3,deegree/deegree3,deegree/deegree3
//$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2009 by: Department of Geography, University of Bonn and lat/lon GmbH This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.commons.modules; import static org.apache.commons.io.IOUtils.closeQuietly; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.Collection; import java.util.Properties; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.regex.Pattern; import org.reflections.Reflections; import org.reflections.scanners.ResourcesScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provides access to deegree module metadata (e.g. Maven artifact identifier and build information). * <p> * The information is extracted from the following resources on the classpath: * <ul> * <li><code>META-INF/deegree/buildinfo.properties</code></li> * <li><code>META-INF/maven/$groupId/$artifactId/pom.properties</code></li> * </ul> * </p> * * @author <a href="mailto:[email protected]">Rutger Bezema</a> * @author <a href="mailto:[email protected]">Markus Schneider</a> * @author last edited by: $Author$ * * @version $Revision$, $Date$ */ public final class ModuleInfo implements Comparable<ModuleInfo> { private static final Logger LOG = LoggerFactory.getLogger( ModuleInfo.class ); private static Collection<ModuleInfo> modulesInfo; static { try { modulesInfo = extractModulesInfo( ClasspathHelper.getUrlsForCurrentClasspath() ); } catch ( IOException e ) { LOG.error( "Error extracting module info: " + e.getMessage(), e ); } } private final URL classpath; private final String groupId; private final String artifactId; private final String version; private final String scmRevision; private final String buildDate; private final String buildBy; private ModuleInfo( URL classpath, String groupId, String artifactId, String version, String scmRevision, String buildDate, String buildBy ) { this.classpath = classpath; this.groupId = groupId; this.artifactId = artifactId; this.version = version; this.scmRevision = scmRevision; this.buildDate = buildDate; this.buildBy = buildBy; } /** * Returns the URL of the module's classpath. * * @return url, never <code>null</code> */ public URL getClasspath() { return classpath; } public String getGroupId() { return groupId; } public String getArtifactId() { return artifactId; } /** * Returns the module's version. * * @return the version number */ public String getVersion() { return version; } /** * Returns the date string when the current build was created. * * @return the date as String */ public String getBuildDate() { return buildDate; } /** * Returns the name of the builder. * * @return the name of the builder */ public String getBuildBy() { return buildBy; } /** * @return the svn revision number */ public String getSvnRevision() { return scmRevision; } /** * Returns the {@link ModuleInfo}s for the deegree modules accessible by the default classloader. * * @return module infos, never <code>null</code>, but can be empty */ public static Collection<ModuleInfo> getModulesInfo() { return modulesInfo; } /** * Returns the {@link ModuleInfo}s for the deegree modules on the given classpathes. * * @param classpathURLs * classpath urls, must not be <code>null</code> * @return module infos, never <code>null</code>, but can be empty (if no deegree module information is present on * the given classpathes) * @throws IOException * if accessing <code>META-INF/deegree/buildinfo.properties</code> or * <code>META-INF/maven/[..]/pom.properties</code> fails */ public static Collection<ModuleInfo> extractModulesInfo( Set<URL> classpathURLs ) throws IOException { SortedSet<ModuleInfo> modules = new TreeSet<ModuleInfo>(); for ( URL classpathURL : classpathURLs ) { if ( classpathURL.getFile().toLowerCase().endsWith( ".zip" ) ) { continue; } try { ModuleInfo moduleInfo = extractModuleInfo( classpathURL ); if ( moduleInfo != null ) { modules.add( moduleInfo ); } } catch ( Throwable e ) { LOG.warn( "Could not extract module info from {}.", classpathURL ); } } return modules; } /** * Returns the {@link ModuleInfo} for the deegree module on the given classpath. * * @param classpathURL * classpath url, must not be <code>null</code> * @return module info or <code>null</code> (if the module does not have file META-INF/deegree/buildinfo.properties) * @throws IOException * if accessing <code>META-INF/deegree/buildinfo.properties</code> or * <code>META-INF/maven/[..]/pom.properties</code> fails */ public static ModuleInfo extractModuleInfo( URL classpathURL ) throws IOException { ModuleInfo moduleInfo = null; ConfigurationBuilder builder = new ConfigurationBuilder(); builder = builder.setUrls( classpathURL ); builder = builder.setScanners( new ResourcesScanner() ); Reflections r = new Reflections( builder ); Set<String> resources = r.getResources( Pattern.compile( "buildinfo\\.properties" ) ); if ( !resources.isEmpty() ) { URLClassLoader classLoader = new URLClassLoader( new URL[] { classpathURL }, null ); String resourcePath = resources.iterator().next(); InputStream buildInfoStream = null; try { Properties props = new Properties(); buildInfoStream = classLoader.getResourceAsStream( resourcePath ); props.load( buildInfoStream ); String buildBy = props.getProperty( "build.by" ); String buildArtifactId = props.getProperty( "build.artifactId" ); String buildDate = props.getProperty( "build.date" ); String buildRev = props.getProperty( "build.svnrev" ); String pomGroupId = null; String pomVersion = null; resources = r.getResources( Pattern.compile( "pom\\.properties" ) ); InputStream pomInputStream = null; if ( !resources.isEmpty() ) { resourcePath = resources.iterator().next(); try { props = new Properties(); pomInputStream = classLoader.findResource( resourcePath ).openStream(); props.load( pomInputStream ); String pomArtifactId = props.getProperty( "artifactId" ); if ( !pomArtifactId.equals( buildArtifactId ) ) { LOG.warn( "ArtifactId mismatch for module on path: " + classpathURL + " (buildinfo.properties vs. pom.properties)." ); } pomGroupId = props.getProperty( "groupId" ); pomVersion = props.getProperty( "version" ); } finally { closeQuietly( pomInputStream ); } } moduleInfo = new ModuleInfo( classpathURL, pomGroupId, buildArtifactId, pomVersion, buildRev, buildDate, buildBy ); } finally { closeQuietly( buildInfoStream ); } } return moduleInfo; } @Override public int compareTo( ModuleInfo that ) { return toString().compareTo( that.toString() ); } @Override public boolean equals( Object o ) { if ( o instanceof ModuleInfo ) { return this.toString().equals( o.toString() ); } return false; } @Override public String toString() { StringBuilder sb = new StringBuilder(); // if ( groupId != null ) { // sb.append( groupId ); // sb.append( "." ); // } sb.append( artifactId ); if ( version != null ) { sb.append( "-" ); sb.append( version ); } sb.append( " (svn revision " ); sb.append( scmRevision ); sb.append( " build@" ); sb.append( buildDate ); sb.append( " by " ); sb.append( buildBy ); sb.append( ")" ); return sb.toString(); } }
deegree-core/deegree-core-commons/src/main/java/org/deegree/commons/modules/ModuleInfo.java
//$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2009 by: Department of Geography, University of Bonn and lat/lon GmbH This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.commons.modules; import static org.apache.commons.io.IOUtils.closeQuietly; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.Collection; import java.util.Properties; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.regex.Pattern; import org.reflections.Reflections; import org.reflections.scanners.ResourcesScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provides access to deegree module metadata (e.g. Maven artifact identifier and build information). * <p> * The information is extracted from the following resources on the classpath: * <ul> * <li><code>META-INF/deegree/buildinfo.properties</code></li> * <li><code>META-INF/maven/$groupId/$artifactId/pom.properties</code></li> * </ul> * </p> * * @author <a href="mailto:[email protected]">Rutger Bezema</a> * @author <a href="mailto:[email protected]">Markus Schneider</a> * @author last edited by: $Author$ * * @version $Revision$, $Date$ */ public final class ModuleInfo implements Comparable<ModuleInfo> { private static final Logger LOG = LoggerFactory.getLogger( ModuleInfo.class ); private static Collection<ModuleInfo> modulesInfo; static { try { modulesInfo = extractModulesInfo( ClasspathHelper.getUrlsForCurrentClasspath() ); } catch ( IOException e ) { LOG.error( "Error extracting module info: " + e.getMessage(), e ); } } private final URL classpath; private final String groupId; private final String artifactId; private final String version; private final String scmRevision; private final String buildDate; private final String buildBy; private ModuleInfo( URL classpath, String groupId, String artifactId, String version, String scmRevision, String buildDate, String buildBy ) { this.classpath = classpath; this.groupId = groupId; this.artifactId = artifactId; this.version = version; this.scmRevision = scmRevision; this.buildDate = buildDate; this.buildBy = buildBy; } /** * Returns the URL of the module's classpath. * * @return url, never <code>null</code> */ public URL getClasspath() { return classpath; } public String getGroupId() { return groupId; } public String getArtifactId() { return artifactId; } /** * Returns the module's version. * * @return the version number */ public String getVersion() { return version; } /** * Returns the date string when the current build was created. * * @return the date as String */ public String getBuildDate() { return buildDate; } /** * Returns the name of the builder. * * @return the name of the builder */ public String getBuildBy() { return buildBy; } /** * @return the svn revision number */ public String getSvnRevision() { return scmRevision; } /** * Returns the {@link ModuleInfo}s for the deegree modules accessible by the default classloader. * * @return module infos, never <code>null</code>, but can be empty */ public static Collection<ModuleInfo> getModulesInfo() { return modulesInfo; } /** * Returns the {@link ModuleInfo}s for the deegree modules on the given classpathes. * * @param classpathURLs * classpath urls, must not be <code>null</code> * @return module infos, never <code>null</code>, but can be empty (if no deegree module information is present on * the given classpathes) * @throws IOException * if accessing <code>META-INF/deegree/buildinfo.properties</code> or * <code>META-INF/maven/[..]/pom.properties</code> fails */ public static Collection<ModuleInfo> extractModulesInfo( Set<URL> classpathURLs ) throws IOException { SortedSet<ModuleInfo> modules = new TreeSet<ModuleInfo>(); for ( URL classpathURL : classpathURLs ) { ModuleInfo moduleInfo = extractModuleInfo( classpathURL ); if ( moduleInfo != null ) { modules.add( moduleInfo ); } } return modules; } /** * Returns the {@link ModuleInfo} for the deegree module on the given classpath. * * @param classpathURL * classpath url, must not be <code>null</code> * @return module info or <code>null</code> (if the module does not have file META-INF/deegree/buildinfo.properties) * @throws IOException * if accessing <code>META-INF/deegree/buildinfo.properties</code> or * <code>META-INF/maven/[..]/pom.properties</code> fails */ public static ModuleInfo extractModuleInfo( URL classpathURL ) throws IOException { ModuleInfo moduleInfo = null; ConfigurationBuilder builder = new ConfigurationBuilder(); builder = builder.setUrls( classpathURL ); builder = builder.setScanners( new ResourcesScanner() ); Reflections r = new Reflections( builder ); Set<String> resources = r.getResources( Pattern.compile( "buildinfo\\.properties" ) ); if ( !resources.isEmpty() ) { URLClassLoader classLoader = new URLClassLoader( new URL[] { classpathURL }, null ); String resourcePath = resources.iterator().next(); InputStream buildInfoStream = null; try { Properties props = new Properties(); buildInfoStream = classLoader.getResourceAsStream( resourcePath ); props.load( buildInfoStream ); String buildBy = props.getProperty( "build.by" ); String buildArtifactId = props.getProperty( "build.artifactId" ); String buildDate = props.getProperty( "build.date" ); String buildRev = props.getProperty( "build.svnrev" ); String pomGroupId = null; String pomVersion = null; resources = r.getResources( Pattern.compile( "pom\\.properties" ) ); InputStream pomInputStream = null; if ( !resources.isEmpty() ) { resourcePath = resources.iterator().next(); try { props = new Properties(); pomInputStream = classLoader.findResource( resourcePath ).openStream(); props.load( pomInputStream ); String pomArtifactId = props.getProperty( "artifactId" ); if ( !pomArtifactId.equals( buildArtifactId ) ) { LOG.warn( "ArtifactId mismatch for module on path: " + classpathURL + " (buildinfo.properties vs. pom.properties)." ); } pomGroupId = props.getProperty( "groupId" ); pomVersion = props.getProperty( "version" ); } finally { closeQuietly( pomInputStream ); } } moduleInfo = new ModuleInfo( classpathURL, pomGroupId, buildArtifactId, pomVersion, buildRev, buildDate, buildBy ); } finally { closeQuietly( buildInfoStream ); } } return moduleInfo; } @Override public int compareTo( ModuleInfo that ) { return toString().compareTo( that.toString() ); } @Override public boolean equals( Object o ) { if ( o instanceof ModuleInfo ) { return this.toString().equals( o.toString() ); } return false; } @Override public String toString() { StringBuilder sb = new StringBuilder(); // if ( groupId != null ) { // sb.append( groupId ); // sb.append( "." ); // } sb.append( artifactId ); if ( version != null ) { sb.append( "-" ); sb.append( version ); } sb.append( " (svn revision " ); sb.append( scmRevision ); sb.append( " build@" ); sb.append( buildDate ); sb.append( " by " ); sb.append( buildBy ); sb.append( ")" ); return sb.toString(); } }
fixed exception when zip classpath entries are found
deegree-core/deegree-core-commons/src/main/java/org/deegree/commons/modules/ModuleInfo.java
fixed exception when zip classpath entries are found
<ide><path>eegree-core/deegree-core-commons/src/main/java/org/deegree/commons/modules/ModuleInfo.java <ide> throws IOException { <ide> SortedSet<ModuleInfo> modules = new TreeSet<ModuleInfo>(); <ide> for ( URL classpathURL : classpathURLs ) { <del> ModuleInfo moduleInfo = extractModuleInfo( classpathURL ); <del> if ( moduleInfo != null ) { <del> modules.add( moduleInfo ); <add> if ( classpathURL.getFile().toLowerCase().endsWith( ".zip" ) ) { <add> continue; <add> } <add> try { <add> ModuleInfo moduleInfo = extractModuleInfo( classpathURL ); <add> if ( moduleInfo != null ) { <add> modules.add( moduleInfo ); <add> } <add> } catch ( Throwable e ) { <add> LOG.warn( "Could not extract module info from {}.", classpathURL ); <ide> } <ide> } <ide> return modules;
JavaScript
lgpl-2.1
df5735f0d87c272c644d1e4b6c95676849109ce1
0
UWCS/choob,UWCS/choob,UWCS/choob,UWCS/choob,UWCS/choob,UWCS/choob
// JavaScript plugin for RSS and Atom feeds. // // Copyright 2005 - 2006, James G. Ross // var BufferedReader = Packages.java.io.BufferedReader; var File = Packages.java.io.File; var FileInputStream = Packages.java.io.FileInputStream; var InputStreamReader = Packages.java.io.InputStreamReader; var System = Packages.java.lang.System; var URL = Packages.java.net.URL; var ChoobPermission = Packages.uk.co.uwcs.choob.support.ChoobPermission; var GetContentsCached = Packages.uk.co.uwcs.choob.support.GetContentsCached; function log(msg) { dumpln("FEEDS [" + (new Date()) + "] " + msg); } String.prototype.trim = function _trim() { return this.replace(/^\s+/, "").replace(/\s+$/, ""); } // Constructor: Feeds function Feeds(mods, irc) { profile.start(); this._mods = mods; this._irc = irc; this._debugStatus = ""; this._debugChannel = "#testing42"; this._announceChannel = "#testing42"; this._debug_profile = false; this._debug_interval = false; this._debug_store = false; this._debug_xml = false; this._debug_trace = false; this._feedList = new Array(); this._feedCheckLock = false; var feeds = mods.odb.retrieve(Feed, ""); for (var i = 0; i < feeds.size(); i++) { var feed = feeds.get(i); // Allow the feed to save itself when it makes changes. feed.__mods = mods; feed.save = function _feed_save() { this.__mods.odb.update(this) }; feed.init(this, ""); this._feedList.push(feed); } mods.interval.callBack("feed-check", 10000, 1); profile.stop("init"); this._setStatus("Waiting for first feed check."); } Feeds.prototype.info = [ "Generic feed reader with notification.", "James Ross", "[email protected]", "1.6.4" ]; // Callback for all intervals from this plugin. Feeds.prototype.interval = function(param, mods, irc) { function mapCase(s, a, b) { return a.toUpperCase() + b.toLowerCase(); }; if (param) { var name = "_" + param.replace(/-(\w)(\w+)/g, mapCase) + "Interval"; if (name in this) { try { this[name](param, mods, irc); } catch(ex) { log("Exception in " + name + ": " + ex + (ex.fileName ? " at <" + ex.fileName + ":" + ex.lineNumber + ">":"")); irc.sendMessage(this._debugChannel, "Exception in " + name + ": " + ex + (ex.fileName ? " at <" + ex.fileName + ":" + ex.lineNumber + ">":"")); } } else { irc.sendMessage(this._debugChannel, "Interval code missing: " + name); } } else { irc.sendMessage(this._debugChannel, "Unnamed interval attempted!"); } } // Command: Add Feeds.prototype.commandAdd = function(mes, mods, irc) { var params = mods.util.getParams(mes, 2); if (params.size() <= 2) { irc.sendContextReply(mes, "Syntax: Feeds.Add <feedname> <url>"); return; } var feedName = String(params.get(1)).trim(); var feedURL = String(params.get(2)).trim(); // Remove existing feed, if possible. var feed = this._getFeed(feedName); if (feed) { if (!this._canAdminFeed(feed, mes)) { irc.sendContextReply(mes, "You don't have permission to replace feed '" + feedName + "'!"); } this._removeFeed(feed); } // Load new feed. irc.sendContextReply(mes, "Loading feed '" + feedName + "'..."); var feed = new Feed(this, feedName, feedURL, mes.getContext()); mods.odb.save(feed); // Allow the feed to save itself when it makes changes. feed.__mods = mods; feed.save = function _feed_save() { this.__mods.odb.update(this) }; feed.owner = this._getOwnerFrom(mes.getNick()); this._feedList.push(feed); feed.addOutputTo(mes.getContext()); // Check feed now. mods.interval.callBack("feed-check", 1000, 1); } Feeds.prototype.commandAdd.help = [ "Adds a new feed.", "<feedname> <url>", "<feedname> is the name for the new feed", "<url> is the URL of the new feed" ]; // Command: Remove Feeds.prototype.commandRemove = function(mes, mods, irc) { var params = mods.util.getParams(mes, 1); if (params.size() <= 1) { irc.sendContextReply(mes, "Syntax: Feeds.Remove <feedname>"); return; } var feedName = String(params.get(1)).trim(); var feed = this._getFeed(feedName); if (!feed) { irc.sendContextReply(mes, "Feed '" + feedName + "' not found."); return; } if (!this._canAdminFeed(feed, mes)) { irc.sendContextReply(mes, "You don't have permission to remove feed '" + feedName + "'!"); return; } this._removeFeed(feed); irc.sendContextReply(mes, "Feed " + feed.getDisplayName() + " removed."); } Feeds.prototype.commandRemove.help = [ "Removes an feed entirely.", "<feedname>", "<feedname> is the name of the feed to remove" ]; // Command: List Feeds.prototype.commandList = function(mes, mods, irc) { if (this._feedList.length == 0) { irc.sendContextReply(mes, "No feeds set up."); return; } function displayFeedItemLine(i, feed) { var dests = feed._outputTo.join(", "); var error = feed.getError(); irc.sendContextReply(mes, "Feed " + feed.getDisplayName() + " owned by " + (feed.owner ? feed.owner : "<unknown>") + (feed.isPrivate ? " (\x02private\x02)" : "") + ", " + (error ? (error) : (feed._lastItemCount + " items (" + feed.getLastLoaded() + ")") ) + ", " + "TTL of " + feed.ttl + "s, source <" + feed.url + ">." + (dests ? " Notifications to: " + dests + "." : "")); }; function getFeedItemString(feed) { return feed.getDisplayName() + " (" + feed._lastItemCount + (feed.isPrivate ? ", \x02private\x02" : "") + ")"; }; function getFeedErrorLine(feed) { return "Feed " + feed.getDisplayName() + ": " + feed.getError() + "."; }; var params = mods.util.getParams(mes, 1); if (params.size() > 1) { var findName = String(params.get(1)).trim(); var findIO = "," + findName.toLowerCase() + ","; var foundIO = false; for (var i = 0; i < this._feedList.length; i++) { // Skip private feeds that user can't control. if (this._feedList[i].isPrivate && !this._canAdminFeed(this._feedList[i], mes)) { continue; } if (this._feedList[i].name.toLowerCase() == findName.toLowerCase()) { displayFeedItemLine(i, this._feedList[i]); return; } else if (("," + this._feedList[i]._outputTo.join(",") + ",").toLowerCase().indexOf(findIO) != -1) { displayFeedItemLine(i, this._feedList[i]); foundIO = true; } else if (findName == "*") { displayFeedItemLine(i, this._feedList[i]); } } if ((findName != "*") && !foundIO) { irc.sendContextReply(mes, "Feed or target '" + findName + "' not found."); } return; } var outputs = new Object(); var errs = new Array(); for (var i = 0; i < this._feedList.length; i++) { // Skip private feeds that user can't control. if (this._feedList[i].isPrivate && !this._canAdminFeed(this._feedList[i], mes)) { continue; } var st = this._feedList[i].getSendTo(); for (var j = 0; j < st.length; j++) { if (!(st[j] in outputs)) { outputs[st[j]] = new Array(); } outputs[st[j]].push(this._feedList[i]); } if (st.length == 0) { if (!("nowhere" in outputs)) { outputs["nowhere"] = new Array(); } outputs["nowhere"].push(this._feedList[i]); } if (this._feedList[i].getError()) { errs.push(this._feedList[i]); } } var outputList = new Array(); for (var o in outputs) { outputList.push(o); } outputList.sort(); for (o = 0; o < outputList.length; o++) { var str = "For " + outputList[o] + ": "; for (var i = 0; i < outputs[outputList[o]].length; i++) { if (i > 0) { str += ", "; } str += getFeedItemString(outputs[outputList[o]][i]); } str += "."; irc.sendContextReply(mes, str); } for (var i = 0; i < errs.length; i++) { irc.sendContextReply(mes, getFeedErrorLine(errs[i])); } } Feeds.prototype.commandList.help = [ "Lists all feeds and where they are displayed, or information about a single feed.", "[<name>]", "<name> is the (optional) name of a feed or target (e.g. channel) to get details on" ]; // Command: AddOutput Feeds.prototype.commandAddOutput = function(mes, mods, irc) { var params = mods.util.getParams(mes, 2); if (params.size() <= 2) { irc.sendContextReply(mes, "Syntax: Feeds.AddOutput <feedname> <dest>"); return; } var feedName = String(params.get(1)).trim(); var feed = this._getFeed(feedName); if (!feed) { irc.sendContextReply(mes, "Feed '" + feedName + "' not found."); return; } if (!this._canAdminFeed(feed, mes)) { irc.sendContextReply(mes, "You don't have permission to edit feed '" + feedName + "'!"); return; } var feedDest = String(params.get(2)).trim(); if (feed.addOutputTo(feedDest)) { irc.sendContextReply(mes, "Feed " + feed.getDisplayName() + " will now output to '" + feedDest + "'."); } else { irc.sendContextReply(mes, "Feed " + feed.getDisplayName() + " already outputs to '" + feedDest + "'."); } } Feeds.prototype.commandAddOutput.help = [ "Adds a new output destination for an feed.", "<feedname> <dest>", "<feedname> is the name of the feed to modify", "<dest> is the channel name to send notifications to" ]; // Command: RemoveOutput Feeds.prototype.commandRemoveOutput = function(mes, mods, irc) { var params = mods.util.getParams(mes, 2); if (params.size() <= 2) { irc.sendContextReply(mes, "Syntax: Feeds.RemoveOutput <feedname> <dest>"); return; } var feedName = String(params.get(1)).trim(); var feed = this._getFeed(feedName); if (!feed) { irc.sendContextReply(mes, "Feed '" + feedName + "' not found."); return; } if (!this._canAdminFeed(feed, mes)) { irc.sendContextReply(mes, "You don't have permission to edit feed '" + feedName + "'!"); return; } var feedDest = String(params.get(2)).trim(); if (feed.removeOutputTo(feedDest)) { irc.sendContextReply(mes, "Feed " + feed.getDisplayName() + " will no longer output to '" + feedDest + "'."); } else { irc.sendContextReply(mes, "Feed " + feed.getDisplayName() + " doesn't output to '" + feedDest + "'."); } } Feeds.prototype.commandRemoveOutput.help = [ "Removes an output destination for an feed.", "<feedname> <dest>", "<feedname> is the name of the feed to modify", "<dest> is the channel name to stop sending notifications to" ]; // Command: Recent Feeds.prototype.commandRecent = function(mes, mods, irc) { var params = mods.util.getParams(mes, 2); if (params.size() <= 1) { irc.sendContextReply(mes, "Syntax: Feeds.Recent <feedname> [[<offset>] <count>]"); return; } var feedName = String(params.get(1)).trim(); var feed = this._getFeed(feedName); if (!feed) { irc.sendContextReply(mes, "Feed '" + feedName + "' not found."); return; } // Allow anyone to get recent items for public feeds, and only someone // who can admin a feed to do it for private feeds. if (feed.isPrivate && !this._canAdminFeed(feed, mes)) { irc.sendContextReply(mes, "You don't have permission to view feed '" + feedName + "'!"); return; } var offset = 0; var count = 5; if (params.size() > 3) { offset = params.get(2); count = params.get(3); } else if (params.size() > 2) { count = params.get(2); } if ((String(offset).trim() != String(Number(offset))) || (offset < 0)) { irc.sendContextReply(mes, "<offset> must be numeric and non-negative"); return; } if ((String(count).trim() != String(Number(count))) || (count <= 0)) { irc.sendContextReply(mes, "<count> must be numeric and positive"); return; } if (offset + count > feed._lastItemCount) { count = feed._lastItemCount - offset; } feed.showRecent(mes.getContext(), offset, count); } Feeds.prototype.commandRecent.help = [ "Displays a number of recent items from a feed.", "<feedname> [[<offset>] <count>]", "<feedname> is the name of the feed to modify", "<offset> is now many entires back in time to go (default is 0)", "<count> is the number of recent items to show (default is 5)" ]; // Command: SetOwner Feeds.prototype.commandSetOwner = function(mes, mods, irc) { var params = mods.util.getParams(mes, 2); if (params.size() <= 2) { irc.sendContextReply(mes, "Syntax: Feeds.SetOwner <feedname> <owner>"); return; } var feedName = String(params.get(1)).trim(); var feed = this._getFeed(feedName); if (!feed) { irc.sendContextReply(mes, "Feed '" + feedName + "' not found."); return; } if (!this._canAdminFeed(feed, mes)) { irc.sendContextReply(mes, "You don't have permission to edit feed '" + feedName + "'!"); return; } var owner = this._getOwnerFrom(String(params.get(2)).trim()); feed.owner = owner; irc.sendContextReply(mes, "Feed " + feed.getDisplayName() + " now has an owner of " + owner + "."); mods.odb.update(feed); } Feeds.prototype.commandSetOwner.help = [ "Sets the owner of the feed, who has full control over it.", "<feedname> <ttl>", "<feedname> is the name of the feed to modify", "<owner> is the new owner", ]; // Command: SetPrivate Feeds.prototype.commandSetPrivate = function(mes, mods, irc) { var params = mods.util.getParams(mes, 2); if (params.size() <= 2) { irc.sendContextReply(mes, "Syntax: Feeds.SetPrivate <feedname> <value>"); return; } var feedName = String(params.get(1)).trim(); var feed = this._getFeed(feedName); if (!feed) { irc.sendContextReply(mes, "Feed '" + feedName + "' not found."); return; } if (!this._canAdminFeed(feed, mes)) { irc.sendContextReply(mes, "You don't have permission to edit feed '" + feedName + "'!"); return; } var isPrivate = String(params.get(2)).trim(); isPrivate = ((isPrivate == "1") || (isPrivate == "on") || (isPrivate == "true") || (isPrivate == "yes")); feed.isPrivate = isPrivate; if (isPrivate) { irc.sendContextReply(mes, "Feed " + feed.getDisplayName() + " is now private."); } else { irc.sendContextReply(mes, "Feed " + feed.getDisplayName() + " is no longer private."); } mods.odb.update(feed); } Feeds.prototype.commandSetOwner.help = [ "Sets whether the feed shows up to users who can't administrate it.", "<feedname> <value>", "<feedname> is the name of the feed to modify", "<value> is either 'true' or 'false'", ]; // Command: SetTTL Feeds.prototype.commandSetTTL = function(mes, mods, irc) { var params = mods.util.getParams(mes, 2); if (params.size() <= 2) { irc.sendContextReply(mes, "Syntax: Feeds.SetTTL <feedname> <ttl>"); return; } var feedName = String(params.get(1)).trim(); var feed = this._getFeed(feedName); if (!feed) { irc.sendContextReply(mes, "Feed '" + feedName + "' not found."); return; } if (!this._canAdminFeed(feed, mes)) { irc.sendContextReply(mes, "You don't have permission to edit feed '" + feedName + "'!"); return; } var feedTTL = 1 * params.get(2); if (feedTTL < 60) { irc.sendContextReply(mes, "Sorry, but a TTL of less than 60 is not allowed."); return; } feed.ttl = feedTTL; irc.sendContextReply(mes, "Feed " + feed.getDisplayName() + " now has a TTL of " + feedTTL + "."); mods.odb.update(feed); } Feeds.prototype.commandSetTTL.help = [ "Sets the TTL (time between updates) of a feed.", "<feedname> <ttl>", "<feedname> is the name of the feed to modify", "<ttl> is the new TTL for the feed", ]; // Command: SetDebug Feeds.prototype.commandSetDebug = function(mes, mods, irc) { if (!mods.security.hasPerm(new ChoobPermission("feeds.debug"), mes)) { irc.sendContextReply(mes, "You don't have permission to debug Feeds!"); return; } var params = mods.util.getParams(mes, 2); if (params.size() <= 2) { irc.sendContextReply(mes, "Syntax: Feeds.SetDebug <flag> <enabled>"); return; } var flag = String(params.get(1)).trim(); var enabled = String(params.get(2)).trim(); enabled = ((enabled == "1") || (enabled == "on") || (enabled == "true") || (enabled == "yes")); if (flag == "profile") { if (enabled) { irc.sendContextReply(mes, "Debug profiling enabled."); } else { irc.sendContextReply(mes, "Debug profiling disabled."); } } else if (flag == "interval") { if (enabled) { irc.sendContextReply(mes, "Debug interval timing enabled."); } else { irc.sendContextReply(mes, "Debug interval timing disabled."); } } else if (flag == "store") { if (enabled) { irc.sendContextReply(mes, "Debug feed store enabled."); } else { irc.sendContextReply(mes, "Debug feed store disabled."); } } else if (flag == "xml") { if (enabled) { irc.sendContextReply(mes, "Debug XML parser enabled."); } else { irc.sendContextReply(mes, "Debug XML parser disabled."); } } else if (flag == "trace") { if (enabled) { profile.showRunningTrace = true; irc.sendContextReply(mes, "Debug execution trace enabled."); } else { profile.showRunningTrace = false; irc.sendContextReply(mes, "Debug execution trace disabled."); } } else { irc.sendContextReply(msg, "Unknown flag specified. Must be one of 'profile', 'interval', 'store', 'xml' or 'trace'."); return; } this["_debug_" + flag] = enabled; } Feeds.prototype.commandSetDebug.help = [ "Sets debug mode on or off.", "<flag> <enabled>", "<flag> is one of 'profile', 'interval', 'store', 'xml' or 'trace', so specify what to debug", "<enabled> is either 'true' or 'false' to set" ]; // Command: Status Feeds.prototype.commandStatus = function(mes, mods, irc) { irc.sendContextReply(mes, "Feeds Status: " + this._debugStatus); } Feeds.prototype.commandStatus.help = [ "Shows the current debugging status of the Feeds plugin.", "" ]; // Command: Info //Feeds.prototype.commandInfo = function(mes, mods, irc) { // // //irc.sendContextReply(mes, "Error getting SVN info: " + ex); //} //Feeds.prototype.commandInfo.help = [ // "Stuff." // ]; Feeds.prototype._getOwnerFrom = function(nick) { var primary = this._mods.nick.getBestPrimaryNick(nick); var root = this._mods.security.getRootUser(primary); if (root) { return String(root); } return String(primary); } Feeds.prototype._getFeed = function(name) { for (var i = 0; i < this._feedList.length; i++) { var feed = this._feedList[i]; if (feed.name.toLowerCase() == name.toLowerCase()) { return feed; } } return null; } Feeds.prototype._canAdminFeed = function(feed, mes) { if (this._mods.security.hasPerm(new ChoobPermission("feeds.edit"), mes)) { return true; // plugin admin } if (feed.owner == this._getOwnerFrom(mes.getNick())) { return true; // feed owner } return false; } Feeds.prototype._removeFeed = function(feed) { for (var i = 0; i < this._feedList.length; i++) { if (this._feedList[i] == feed) { this._mods.odb["delete"](this._feedList[i]); this._feedList.splice(i, 1); return; } } } Feeds.prototype._setStatus = function(msg) { this._debugStatus = "[" + (new Date()) + "] " + msg; } Feeds.prototype._ = function() { } // Interval: feed-check Feeds.prototype._feedCheckInterval = function(param, mods, irc) { if (this._feedCheckLock) return; this._feedCheckLock = true; if (this._debug_interval) { log("Interval: start"); } this._setStatus("Checking feeds..."); for (var i = 0; i < this._feedList.length; i++) { var feed = this._feedList[i]; if (!feed.safeToCheck()) { continue; } if (this._debug_interval) { log("Interval: checking " + feed.name + " (" + -this._feedList[i].getNextCheck() + "ms late)"); } this._setStatus("Checking feed " + feed.getDisplayName() + "..."); if (this._debug_profile) { profile.start(); } feed.checkForNewItems(); if (this._debug_profile) { profile.stop(feed.name); } this._setStatus("Last checked feed " + feed.getDisplayName() + "."); } var nextCheck = 60 * 60 * 1000; // 1 hour for (var i = 0; i < this._feedList.length; i++) { var feedNextCheck = this._feedList[i].getNextCheck(); if (feedNextCheck < 0) { feedNextCheck = 0; } if (nextCheck > feedNextCheck) { nextCheck = feedNextCheck; } } // Helps to group the calls. var extra = 0; if (nextCheck > 10000) { extra = 5000; } if (this._debug_interval) { log("Interval: next check due in " + nextCheck + "ms" + (extra ? " + " + extra + "ms" : "")); log("Interval: end"); } this._feedCheckLock = false; // Don't return in anything less than 1s. mods.interval.callBack("feed-check", nextCheck + extra, 1); } function Feed() { this.id = 0; this.name = ""; this.displayName = ""; this.outputTo = ""; this.url = ""; this.ttl = 300; // Default TTL this.owner = ""; this.isPrivate = false; this.save = function(){}; this._items = new Array(); this._error = ""; this._errorExpires = 0; if (arguments.length > 0) { this._ctor(arguments[0], arguments[1], arguments[2], arguments[3]); } } Feed.prototype._ctor = function(parent, name, url, loadContext) { this.name = name; this.displayName = name; this.url = url; this.init(parent, loadContext) } Feed.prototype.getDisplayName = function() { if (this.displayName) return "'" + this.displayName + "' (" + this.name + ")"; return this.name; } Feed.prototype.init = function(parent, loadContext) { profile.enterFn("Feed(" + this.name + ")", "init"); this._parent = parent; this._loadContext = loadContext; this._outputTo = new Array(); if (this.outputTo) { this._outputTo = this.outputTo.split(" "); this._outputTo.sort(); } this._cachedContents = null; this._lastSeen = new Object(); this._lastSeenPub = new Object(); this._lastItemCount = 0; this._lastCheck = 0; this._lastLoaded = 0; if (this._parent._debug_store) { log("Feed Store: " + this.name + ": " + this._items.length); } profile.leaveFn("init"); } Feed.prototype.addOutputTo = function(destination) { for (var i = 0; i < this._outputTo.length; i++) { if (this._outputTo[i].toLowerCase() == destination.toLowerCase()) { return false; } } this._outputTo.push(destination); this._outputTo.sort(); this.outputTo = this._outputTo.join(" "); this.save(); return true; } Feed.prototype.removeOutputTo = function(destination) { for (var i = 0; i < this._outputTo.length; i++) { if (this._outputTo[i].toLowerCase() == destination.toLowerCase()) { this._outputTo.splice(i, 1); this.outputTo = this._outputTo.join(" "); this.save(); return true; } } return false; } Feed.prototype.getError = function() { if (this._error) { return this._error + " [expires " + (new Date(this._errorExpires)) + "]"; } return ""; } Feed.prototype.setError = function(msg) { this._error = msg; this._errorExpires = Number(new Date()) + 60 * 60 * 1000; // 1 hour } Feed.prototype.getSendTo = function() { var st = new Array(); for (var i = 0; i < this._outputTo.length; i++) { st.push(this._outputTo[i]); } return st; } Feed.prototype.getLastLoaded = function() { if (this._lastLoaded == 0) return "never loaded"; return ("loaded " + this._lastLoaded); } // Return boolean indicating if it is ok to reload the contents of the feed. Feed.prototype.safeToCheck = function() { // If the error has expired, clear it. if (this._error && (this._errorExpires < Number(new Date()))) { this._error = ""; this._errorExpires = 0; } if (this._error) { return false; } // <ttl> min delay. Default is 1m. var checkTime = Number(new Date()) - (this.ttl * 1000); return (Number(this._lastCheck) < checkTime); } // Return the number of milliseconds until the next checkpoint. Feed.prototype.getNextCheck = function() { var delay = (this._lastCheck ? Number(this._lastCheck) - Number(new Date()) + (this.ttl * 1000) : 0); if (this._error) { delay = this._errorExpires - Number(new Date()); } return delay; } Feed.prototype.showRecent = function(target, offset, count) { if (this.getError()) { this._sendTo(target, this.getDisplayName() + ": \x02ERROR\x02: " + this.getError()); return; } var items = this._items; if (items.length == 0) { if (this._lastCheck == 0) { this._sendTo(target, this.getDisplayName() + " has not loaded yet."); } else { this._sendTo(target, this.getDisplayName() + " has no recent items."); } return; } var start = items.length - 1; // Default to the last item. if (start > offset + count) { start = offset + count - 1; } if (start > items.length - 1) { // Make sure not to start before the oldest item we have. start = items.length - 1; } for (var i = start; i >= offset; i--) { this._sendTo(target, "[" + items[i].date + "] \x1F" + items[i].title + "\x1F " + items[i].desc, (items[i].link ? " <" + items[i].link + ">" : "")); } } Feed.prototype.checkForNewItems = function() { profile.enterFn("Feed(" + this.name + ")", "checkForNewItems"); if (this.getError()) { profile.leaveFn("checkForNewItems"); return; } var firstRun = (this._lastCheck == 0); var newItems = this.getNewItems(); if (this.getError()) { if (firstRun && this._loadContext) { // We're trying to load the feed, and it failed. Oh the humanity. this._parent._irc.sendMessage(this._loadContext, this.getDisplayName() + " failed to load, incurring the error: " + this.getError()); } //this._sendToAll(this.getDisplayName() + ": \x02ERROR\x02: " + this.getError()); profile.leaveFn("checkForNewItems"); return; } this._lastLoaded = new Date(); if (firstRun && this._loadContext) { this._parent._irc.sendMessage(this._loadContext, this.getDisplayName() + " loaded with " + this._lastItemCount + " items."); } // If there are more than 3 items, and it's more than 20% of the feed's // length, don't display the items. This allows feeds with more items (e.g. // news feeds) to flood a little bit more, but still prevents a feed from // showing all it's items if it just added them all. // Never bother with more than 10 items, whatever. if ((newItems.length > 10) || ((newItems.length > 3) && (newItems.length > 0.20 * this._lastItemCount))) { this._sendToAll(this.getDisplayName() + " has too many (" + newItems.length + ") new items to display."); } else { for (var i = newItems.length - 1; i >= 0; i--) { if (newItems[i].updated) { this._sendToAll("\x1F" + newItems[i].title + "\x1F " + newItems[i].desc, (newItems[i].link ? " <" + newItems[i].link + ">" : "")); } else { this._sendToAll("\x1F\x02" + newItems[i].title + "\x02\x1F " + newItems[i].desc, (newItems[i].link ? " <" + newItems[i].link + ">" : "")); } } } profile.leaveFn("checkForNewItems"); } Feed.prototype.ensureCachedContents = function() { profile.enterFn("Feed(" + this.name + ")", "ensureCachedContents"); try { if (!this._cachedContents) { var urlObj = new URL(this.url); profile.enterFn("Feed(" + this.name + ")", "ensureCachedContents.getContentsCached"); this._cachedContents = new GetContentsCached(urlObj, 60000); profile.leaveFn("ensureCachedContents.getContentsCached"); } } catch(ex) { // Error = no items. this.setError("Exception getting data: " + ex + (ex.fileName ? " at <" + ex.fileName + ":" + ex.lineNumber + ">":"")); profile.leaveFn("ensureCachedContents"); return false; } profile.leaveFn("ensureCachedContents"); return true; } Feed.prototype.getNewItems = function() { profile.enterFn("Feed(" + this.name + ")", "getNewItems"); if (!this.ensureCachedContents()) { profile.leaveFn("getNewItems"); return []; } var feedData = ""; profile.enterFn("Feed(" + this.name + ")", "getNewItems.getCachedContents"); try { feedData = String(this._cachedContents.getContents()); } catch(ex) { profile.leaveFn("getNewItems.getCachedContents"); // Error = no items. this.setError("Exception getting data: " + ex + (ex.fileName ? " at <" + ex.fileName + ":" + ex.lineNumber + ">":"")); profile.leaveFn("getNewItems"); return []; } profile.leaveFn("getNewItems.getCachedContents"); if (feedData == "") { this.setError("Unable to fetch data"); profile.leaveFn("getNewItems"); return []; } try { profile.enterFn("FeedParser(" + this.name + ")", "new"); var feedParser = new FeedParser(this._parent, feedData); profile.leaveFn("new"); } catch(ex) { this.setError("Exception in parser: " + ex + (ex.fileName ? " at <" + ex.fileName + ":" + ex.lineNumber + ">":"")); profile.leaveFn("getNewItems"); return []; } var firstTime = true; var curItems = new Object(); for (var d in this._lastSeen) { firstTime = false; this._lastSeen[d] = false; } for (var d in this._lastSeenPub) { this._lastSeenPub[d] = false; } // Force TTL to be >= that in the feed itself. if (feedParser.ttl && (this.ttl < feedParser.ttl)) { this.ttl = feedParser.ttl; this.save(); } // Update title if it's different. if (feedParser.title) { var feedTitle = feedParser.title.replace(/^\s+/, "").replace(/\s+$/, ""); if (this.displayName != feedTitle) { this.displayName = feedTitle; this.save(); } } var newItems = new Array(); var newUniques = new Object(); // Only keep new or updated items in the list. for (var i = 0; i < feedParser.items.length; i++) { var item = feedParser.items[i]; // Prefer, in order: GUID, link, date, title. var unique = (item.guid ? item.guid : (item.link ? item.link : (item.date != "?" ? item.date : item.title))); var date = unique + ":" + item.date; if (unique in newUniques) { // Skip repeated unique items. Broken feed! continue; } newUniques[unique] = true; if (unique in this._lastSeen) { // Seen this item before. Has it changed? if (date in this._lastSeenPub) { // No change. this._lastSeen[unique] = true; this._lastSeenPub[date] = true; continue; } // Items changed. item.updated = true; } // New item. item.uniqueKey = unique; newItems.push(item); this._lastSeen[unique] = true; this._lastSeenPub[date] = true; // Remove and re-add from store if it's updated. Just add for new. if (item.updated) { for (var i = 0; i < this._items.length; i++) { if (this._items[i].uniqueKey == item.uniqueKey) { if (this._parent._debug_store) { log("Feed Store: " + this.name + ": DEL <" + this._items[i].uniqueKey + "><" + this._items[i].date + ">"); } this._items.splice(i, 1); break; } } } if (this._parent._debug_store) { log("Feed Store: " + this.name + ": ADD <" + item.uniqueKey + "><" + item.date + ">"); } this._items.push(item); } for (var d in this._lastSeen) { if (!this._lastSeen[d]) { delete this._lastSeen[d]; for (var i = 0; i < this._items.length; i++) { if (this._items[i].uniqueKey == d) { if (this._parent._debug_store) { log("Feed Store: " + this.name + ": DEL <" + this._items[i].uniqueKey + "><" + this._items[i].date + ">"); } this._items.splice(i, 1); break; } } } } for (var d in this._lastSeenPub) { if (!this._lastSeenPub[d]) { delete this._lastSeenPub[d]; } } if (this._parent._debug_store) { log("Feed Store: " + this.name + ": " + this._items.length); } var count = 0; for (var d in this._lastSeenPub) { count++; } this._lastItemCount = count; if (firstTime) { newItems = new Array(); } this._lastCheck = new Date(); profile.leaveFn("getNewItems"); return newItems; } Feed.prototype._sendToAll = function(message, suffix) { for (var i = 0; i < this._outputTo.length; i++) { this._sendTo(this._outputTo[i], message, suffix); } } Feed.prototype._sendTo = function(target, message, suffix) { if (typeof suffix != "string") { suffix = ""; } if (message.length + suffix.length > 390) { message = message.substr(0, 390 - suffix.length) + "..."; } this._parent._irc.sendMessage(target, message + suffix); } var entityMap = { "lt": "<", "#60": "<", "gt": ">", "#62": ">", "quot": '"', "#34": '"', "ldquo": '"', "#8220": '"', "rdquo": '"', "#8221": '"', "apos": "'", "#39": "'", "lsquo": "'", "#8216": "'", "rsquo": "'", "#8217": "'", "nbsp": " ", "#160": " ", "ndash": "-", "#8211": "-", "mdash": "-", "#8212": "-", "lsaquo": "<<", "#8249": "<<", "rsaquo": ">>", "#8250": ">>", "times": "x", "#163": "", "#8230": "...", "dummy": "" }; function _decodeEntities(data) { profile.enterFn("", "_decodeEntities"); // Decode XML into HTML... data = data.replace(/&(?:(\w+)|#(\d+)|#x([0-9a-f]{2}));/gi, function _decodeEntity(match, name, decnum, hexnum) { if (name && (name in entityMap)) { return entityMap[name]; } if (decnum && (String("#" + parseInt(decnum, 10)) in entityMap)) { return entityMap[String("#" + parseInt(decnum, 10))]; } if (hexnum && (String("#" + parseInt(hexnum, 16)) in entityMap)) { return entityMap[String("#" + parseInt(hexnum, 16))]; } return match; //"[unknown entity '" + (name || decnum || hexnum) + "']"; }); // Done as a special-case, last, so that it doesn't bugger up // doubly-escaped things. data = data.replace(/&(amp|#0*38|#x0*26);/g, "&"); profile.leaveFn("_decodeEntities"); return data; } var htmlInlineTags = { "A": true, "ABBR": true, "ACRONYM": true, "AREA": true, "B": true, "BASE": true, "BASEFONT": true, "BDO": true, "BIG": true, "BUTTON": true, "CITE": true, "CODE": true, "DEL": true, "DFN": true, "EM": true, "FONT": true, "I": true, "INS": true, "ISINDEX": true, "KBD": true, "LABEL": true, "LEGEND": true, "LINK": true, "MAP": true, "META": true, "NOSCRIPT": true, "OPTGROUP": true, "OPTION": true, "PARAM": true, "Q": true, "S": true, "SAMP": true, "SCRIPT": true, "SELECT": true, "SMALL": true, "SPAN": true, "STRIKE": true, "STRONG": true, "STYLE": true, "SUB": true, "SUP": true, "TEXTAREA": true, "TT": true, "U": true, "VAR": true, }; function _decodeRSSHTML(data) { profile.enterFn("", "_decodeRSSHTML"); // Decode XML into HTML... data = _decodeEntities(data); // Remove all tags. data = data.replace(/<\/?(\w+)[^>]*>/g, function (text, tag) { return tag.toUpperCase() in htmlInlineTags ? "" : " " }); // Decode HTML into text... data = _decodeEntities(data); // Remove all entities. //data = data.replace(/&[^;]+;/g, ""); data = data.replace(/\s+/g, " "); profile.leaveFn("_decodeRSSHTML"); return data; } function _decodeAtomText(element) { if (!element) return ""; var content = element.contents(); var type = element.attribute("type"); if (type && (type.value == "html")) { return _decodeRSSHTML(content); } return _decodeEntities(content); } function _decodeAtomDate(element) { var ary = element.contents().match(/^(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+)(?:.(\d+))?(Z|([+-])(\d+):(\d+))$/); if (ary) { var d = new Date(ary[1], ary[2] - 1, ary[3], ary[4], ary[5], ary[6]); // 8 = Z/zone // 9 = +/- // 10/11 = zone offset if (d.getTimezoneOffset() != 0) { d = new Date(Number(d) - d.getTimezoneOffset() * 60 * 1000); } if (ary[9] == "+") { d = new Date(Number(d) + ((ary[10] * 60) + ary[11]) * 60 * 1000); } if (ary[9] == "-") { d = new Date(Number(d) - ((ary[10] * 60) + ary[11]) * 60 * 1000); } return String(d); } return "?"; } // Generic feed parser. function FeedParser(feedsOwner, data) { profile.enterFn("FeedParser", "init.replace"); data = data.replace(/[\r\n\s]+/, " "); profile.leaveFn("init.replace"); profile.enterFn("XMLParser", "new"); try { this._xmlData = new XMLParser(data); } finally { profile.leaveFn("new"); } this._parse(feedsOwner); } FeedParser.prototype.toString = function() { return "FeedParser<" + this.title + ">"; } FeedParser.prototype._parse = function(feedsOwner) { profile.enterFn("FeedParser", "_parse"); this.title = ""; this.link = ""; this.description = ""; this.language = ""; this.ttl = 0; this.items = new Array(); this.error = ""; var ATOM_1_0_NS = "http://www.w3.org/2005/Atom"; function getChildContents(elt, name, namespace) { profile.enterFn("FeedParser", "getChildContents"); var child = elt.childByName(name, namespace); if (child) { profile.leaveFn("getChildContents"); return child.contents(); } profile.leaveFn("getChildContents"); return ""; }; // Check what kind of feed we have! if (this._xmlData.rootElement.localName == "rss") { var rssVersion = this._xmlData.rootElement.attribute("version"); if (rssVersion && ((rssVersion.value == 0.91) || (rssVersion.value == 2.0))) { // RSS 0.91 or 2.0 code. var channel = this._xmlData.rootElement.childByName("channel"); this.title = getChildContents(channel, "title").trim(); this.link = getChildContents(channel, "link").trim(); this.description = getChildContents(channel, "description").trim(); this.language = getChildContents(channel, "language").trim(); this.ttl = getChildContents(channel, "ttl").trim(); var items = channel.childrenByName("item"); for (var i = 0; i < items.length; i++) { var item = items[i]; var pubDate = item.childByName("pubDate"); if (pubDate) { pubDate = pubDate.contents(); } else { pubDate = "?"; } var guid = item.childByName("guid") || ""; if (guid) { guid = guid.contents(); } var title = item.childByName("title") || ""; if (title) { title = title.contents(); } var link = item.childByName("link") || ""; if (link) { link = link.contents(); } var desc = item.childByName("description") || ""; if (desc) { desc = desc.contents(); } this.items.push({ date: pubDate.trim(), guid: guid.trim(), title: _decodeRSSHTML(title).trim(), link: _decodeEntities(link).trim(), desc: _decodeRSSHTML(desc).trim(), updated: false }); } } else { if (rssVersion) { profile.leaveFn("_parse"); throw new Error("Unsuported RSS version: " + rssVersion.value); } profile.leaveFn("_parse"); throw new Error("Unsuported RSS version: <unknown>"); } } else if (this._xmlData.rootElement.localName == "RDF") { // RSS 1.0 probably. if (this._xmlData.rootElement.namespace == "http://www.w3.org/1999/02/22-rdf-syntax-ns#") { var channel = this._xmlData.rootElement.childByName("channel", "http://purl.org/rss/1.0/"); this.title = getChildContents(channel, "title", "http://purl.org/rss/1.0/").trim(); this.link = getChildContents(channel, "link", "http://purl.org/rss/1.0/").trim(); this.description = getChildContents(channel, "description", "http://purl.org/rss/1.0/").trim(); this.language = getChildContents(channel, "language", "http://purl.org/rss/1.0/").trim(); this.ttl = getChildContents(channel, "ttl", "http://purl.org/rss/1.0/").trim(); var items = this._xmlData.rootElement.childrenByName("item", "http://purl.org/rss/1.0/"); for (var i = 0; i < items.length; i++) { var item = items[i]; var pubDate = item.childByName("pubDate", "http://purl.org/rss/1.0/"); if (pubDate) { pubDate = pubDate.contents(); } else { pubDate = "?"; } var title = item.childByName("title", "http://purl.org/rss/1.0/") || ""; if (title) { title = title.contents(); } var link = item.childByName("link", "http://purl.org/rss/1.0/") || ""; if (link) { link = link.contents(); } var desc = item.childByName("description", "http://purl.org/rss/1.0/") || ""; if (desc) { desc = desc.contents(); } this.items.push({ date: pubDate.trim(), title: _decodeRSSHTML(title).trim(), link: _decodeEntities(link).trim(), desc: _decodeRSSHTML(desc).trim(), updated: false }); } } else { profile.leaveFn("_parse"); throw new Error("Unsuported namespace: " + this._xmlData.rootElement.namespace); } } else if (this._xmlData.rootElement.is("feed", ATOM_1_0_NS)) { // Atom 1.0. // Text decoder: _decodeAtomText(element) // Date decoder: _decodeAtomDate(element); var feed = this._xmlData.rootElement; this.title = _decodeAtomText(feed.childByName("title", ATOM_1_0_NS)).trim(); var items = feed.childrenByName("entry", ATOM_1_0_NS); for (var i = 0; i < items.length; i++) { var item = items[i]; var date = _decodeAtomDate(item.childByName("updated", ATOM_1_0_NS)); var title = _decodeAtomText(item.childByName("title", ATOM_1_0_NS)); var link = item.childByName("link", ATOM_1_0_NS); if (link) { link = link.attribute("href"); if (link) { link = link.value; } else { link = ""; } } else { link = ""; } var desc = _decodeAtomText(item.childByName("content", ATOM_1_0_NS)); this.items.push({ date: date.trim(), title: title.trim(), link: link.trim(), desc: desc.trim(), updated: false }); } } else { profile.leaveFn("_parse"); throw new Error("Unsupported feed type: " + this._xmlData.rootElement); } if (feedsOwner && feedsOwner._debug_xml) { var limit = { value: 25 }; log("# URL : " + this.link); log("# TITLE : " + this.title); log("# DESCRIPTION: " + this.description); this._xmlData._dump(this._xmlData.root, "", limit); } profile.leaveFn("_parse"); } // #include JavaScriptXML.jsi // General XML parser, win! function XMLParser(data) { this.data = data; this.root = []; this._state = []; this._parse(); } XMLParser.prototype._dumpln = function(line, limit) { limit.value--; if (limit.value == 0) { dumpln("*** TRUNCATED ***"); } if (limit.value <= 0) { return; } dumpln(line); } XMLParser.prototype._dump = function(list, indent, limit) { profile.enterFn("XMLParser", "_dumpElement"); for (var i = 0; i < list.length; i++) { this._dumpElement(list[i], indent, limit); } profile.leaveFn("_dumpElement"); } XMLParser.prototype._dumpElement = function(elt, indent, limit) { profile.enterFn("XMLParser", "_dumpElement"); if (elt._content) { this._dumpln(indent + elt + elt._content + "</" + elt.name + ">", limit); } else if (elt._children && (elt._children.length > 0)) { this._dumpln(indent + elt, limit); this._dump(elt._children, indent + " ", limit); this._dumpln(indent + "</" + elt.name + ">", limit); } else { this._dumpln(indent + elt, limit); } profile.leaveFn("_dumpElement"); } XMLParser.prototype._parse = function() { profile.enterFn("XMLParser", "_parse"); // Hack off the Unicode DOM if it exists. if (this.data.substr(0, 3) == "\xEF\xBB\xBF") { this.data = this.data.substr(3); } // Process all entities here. this._processEntities(); // Head off for the <?xml PI. while (this.data.length > 0) { this._eatWhitespace(); if (this.data.substr(0, 4) == "<!--") { // Comment. this.root.push(this._eatComment()); } else if (this.data.substr(0, 2) == "<!") { // SGML element. this.root.push(this._eatSGMLElement()); } else if (this.data.substr(0, 2) == "<?") { var e = this._eatElement(null); if (e.name != "xml") { profile.leaveFn("_parse"); throw new Error("Expected <?xml?>, found <?" + e.name + "?>"); } this.xmlPI = e; this.root.push(e); break; } else { break; //profile.leaveFn("_parse"); //throw new Error("Expected <?xml?>, found " + this.data.substr(0, 10) + "..."); } } // OK, onto the root element... while (this.data.length > 0) { this._eatWhitespace(); if (this.data.substr(0, 4) == "<!--") { // Comment. this.root.push(this._eatComment()); } else if (this.data.substr(0, 2) == "<!") { // SGML element. this.root.push(this._eatSGMLElement()); } else if (this.data.substr(0, 2) == "<?") { var e = this._eatElement(null); this.root.push(e); } else if (this.data.substr(0, 1) == "<") { var e = this._eatElement(null); if (e.start == false) { profile.leaveFn("_parse"); throw new Error("Expected start element, found end element"); } this.rootElement = e; this.root.push(e); this._state.unshift(e); break; } else { profile.leaveFn("_parse"); throw new Error("Expected root element, found " + this.data.substr(0, 10) + "..."); } } // Now the contents. while (this.data.length > 0) { this._eatWhitespace(); if (this.data.substr(0, 4) == "<!--") { // Comment. this._state[0]._children.push(this._eatComment()); } else if (this.data.substr(0, 2) == "<!") { // SGML element. this._state[0]._children.push(this._eatSGMLElement()); } else if (this.data[0] == "<") { var e = this._eatElement(this._state[0]); if (e.empty) { this._state[0]._children.push(e); } else if (e.start) { this._state[0]._children.push(e); this._state.unshift(e); } else { if (e.name != this._state[0].name) { profile.leaveFn("_parse"); throw new Error("Expected </" + this._state[0].name + ">, found </" + e.name + ">"); } this._state.shift(); if (this._state.length == 0) { // We've ended the root element, that's it folks! break; } } } else { var pos = this.data.indexOf("<"); if (pos < 0) { this._state[0]._content = this.data; this.data = ""; } else { this._state[0]._content = this.data.substr(0, pos); this.data = this.data.substr(pos); } } } this._eatWhitespace(); if (this._state.length > 0) { profile.leaveFn("_parse"); throw new Error("Expected </" + this._state[0].name + ">, found EOF."); } if (this.data.length > 0) { profile.leaveFn("_parse"); throw new Error("Expected EOF, found " + this.data.substr(0, 10) + "..."); } profile.leaveFn("_parse"); } XMLParser.prototype._processEntities = function() {} XMLParser.prototype._processEntities_TODO = function(string) { profile.enterFn("XMLParser", "_processEntities"); var i = 0; while (i < string.length) { // Find next &... i = string.indexOf("&", i); //if (string.substr(i, 4) == "&lt;") { // this.data = string.substr(0, i - 1) + "<" + // Make sure we skip over the character we just inserted. i++; } profile.leaveFn("_processEntities"); return string; } XMLParser.prototype._eatWhitespace = function() { profile.enterFn("XMLParser", "_eatWhitespace"); var len = this._countWhitespace(); if (len > 0) { this.data = this.data.substr(len); } profile.leaveFn("_eatWhitespace"); } XMLParser.prototype._countWhitespace = function() { profile.enterFn("XMLParser", "_countWhitespace"); // Optimise by checking only first character first. if (this.data.length <= 0) { profile.leaveFn("_countWhitespace"); return 0; } var ws = this.data[0].match(/^\s+/); if (ws) { // Now check first 256 characters. ws = this.data.substr(0, 256).match(/^\s+/); if (ws[0].length == 256) { // Ok, check it all. ws = this.data.match(/^\s+/); profile.leaveFn("_countWhitespace"); return ws[0].length; } profile.leaveFn("_countWhitespace"); return ws[0].length; } profile.leaveFn("_countWhitespace"); return 0; } XMLParser.prototype._eatComment = function() { profile.enterFn("XMLParser", "_eatComment"); if (this.data.substr(0, 4) != "<!--") { profile.leaveFn("_eatComment"); throw new Error("Expected <!--, found " + this.data.substr(0, 10) + "..."); } var i = 4; while (i < this.data.length) { if (this.data.substr(i, 3) == "-->") { // Done. var c = new XMLComment(this.data.substr(4, i - 4)); this.data = this.data.substr(i + 3); profile.leaveFn("_eatComment"); return c; } i++; } profile.leaveFn("_eatComment"); throw new Error("Expected -->, found EOF."); } XMLParser.prototype._eatSGMLElement = function() { profile.enterFn("XMLParser", "_eatSGMLElement"); if (this.data.substr(0, 2) != "<!") { profile.leaveFn("_eatSGMLElement"); throw new Error("Expected <!, found " + this.data.substr(0, 10) + "..."); } // CDATA chunk? if (this.data.substr(0, 9) == "<![CDATA[") { profile.leaveFn("_eatSGMLElement"); return this._eatCDATAElement(); } var i = 2; var inQuote = ""; while (i < this.data.length) { if (inQuote == this.data[i]) { inQuote = ""; } else if ((this.data[i] == "'") || (this.data[i] == '"')) { inQuote = this.data[i]; } else if (this.data[i] == ">") { // Done. var c = new XMLComment(this.data.substr(2, i - 1)); this.data = this.data.substr(i + 1); profile.leaveFn("_eatSGMLElement"); return c; } i++; } profile.leaveFn("_eatSGMLElement"); throw new Error("Expected >, found EOF."); } XMLParser.prototype._eatCDATAElement = function() { profile.enterFn("XMLParser", "_eatCDATAElement"); if (this.data.substr(0, 9) != "<![CDATA[") { profile.leaveFn("_eatCDATAElement"); throw new Error("Expected <![CDATA[, found " + this.data.substr(0, 20) + "..."); } var i = 9; while (i < this.data.length) { if ((this.data[i] == "]") && (this.data.substr(i, 3) == "]]>")) { // Done. var e = new XMLCData(this.data.substr(9, i - 9)); this.data = this.data.substr(i + 3); profile.leaveFn("_eatCDATAElement"); return e; } i++; } profile.leaveFn("_eatCDATAElement"); throw new Error("Expected ]]>, found EOF."); } XMLParser.prototype._eatElement = function(parent) { profile.enterFn("XMLParser", "_eatElement"); if (this.data[0] != "<") { profile.leaveFn("_eatElement"); throw new Error("Expected <, found " + this.data.substr(0, 10) + "..."); } var whitespace = /\s/i; var e; var name = ""; var start = true; var pi = false; var i = 1; if (this.data[i] == "?") { pi = true; i++; } if (!pi && (this.data[i] == "/")) { start = false; i++; } while (i < this.data.length) { if (!pi && (this.data[i] == ">")) { e = new XMLElement(parent, name, start, pi, false); this.data = this.data.substr(i + 1); e.resolveNamespaces(); profile.leaveFn("_eatElement"); return e; } else if (start && (this.data.substr(i, 2) == "/>")) { e = new XMLElement(parent, name, start, pi, true); this.data = this.data.substr(i + 2); e.resolveNamespaces(); profile.leaveFn("_eatElement"); return e; } else if (pi && (this.data.substr(i, 2) == "?>")) { e = new XMLElement(parent, name, start, pi, false); this.data = this.data.substr(i + 2); e.resolveNamespaces(); profile.leaveFn("_eatElement"); return e; } else if (whitespace.test(this.data[i])) { // End of name. e = new XMLElement(parent, name, start, pi, false); i++; break; } else { name += this.data[i]; } i++; } // On to attributes. name = ""; var a = ""; var inName = false; var inEQ = false; var inVal = false; var inQuote = ""; while (i < this.data.length) { if (!pi && !inName && !inEQ && !inVal && (this.data[i] == ">")) { this.data = this.data.substr(i + 1); e.resolveNamespaces(); profile.leaveFn("_eatElement"); return e; } else if (!pi && !inName && !inEQ && !inVal && (this.data.substr(i, 2) == "/>")) { if (!e.start) { profile.leaveFn("_eatElement"); throw new Error("Invalid end tag, found " + this.data.substr(0, i + 10) + "..."); } e.empty = true; this.data = this.data.substr(i + 2); e.resolveNamespaces(); profile.leaveFn("_eatElement"); return e; } else if (pi && !inName && !inEQ && !inVal && (this.data.substr(i, 2) == "?>")) { this.data = this.data.substr(i + 2); e.resolveNamespaces(); profile.leaveFn("_eatElement"); return e; } else if (inName && (this.data[i] == "=")) { inName = false; inEQ = true; } else if (inEQ && ((this.data[i] == '"') || (this.data[i] == "'"))) { inEQ = false; inVal = true; inQuote = this.data[i]; } else if (inQuote && ((this.data[i] == '"') || (this.data[i] == "'"))) { if (inQuote == this.data[i]) { inQuote = ""; inVal = false; e._attributes.push(new XMLAttribute(e, name, a)); name = ""; a = ""; } } else if (whitespace.test(this.data[i])) { if (inVal && !inQuote) { inVal = false; e._attributes.push(new XMLAttribute(e, name, a)); name = ""; a = ""; } } else if (inEQ || inVal) { if (inEQ) { inEQ = false; inVal = true; a = ""; } a += this.data[i]; } else { if (!inName) { inName = true; } name += this.data[i]; } i++; } //this.data = this.data.substr(i); //e.resolveNamespaces(); profile.leaveFn("_eatElement"); //return e; throw new Error("Expected >, found EOF."); } function XMLElement(parent, name, start, pi, empty) { this.type = "XMLElement"; this.parent = parent; this.name = name; this.start = start; this.pi = pi; this.empty = empty; this.namespace = ""; var ary = this.name.match(/^(.*?):(.*)$/); if (ary) { this.prefix = ary[1]; this.localName = ary[2]; } else { this.prefix = null; this.localName = this.name; } this._attributes = []; this._content = ""; this._children = []; } XMLElement.prototype.toString = function() { profile.enterFn("XMLElement", "toString"); var str = "<"; if (this.pi) { str += "?"; } else if (!this.start) { str += "/"; } if (this.prefix != null) { str += this.prefix + ":"; } str += this.localName; if (this.namespace) { str += "[[" + this.namespace + "]]"; } for (var a in this._attributes) { str += " " + this._attributes[a]; } if (this.pi) { str += "?"; } if (this.empty || ((this._content == "") && (this._children.length == 0))) { str += "/"; } str += ">"; profile.leaveFn("toString"); return str; } XMLElement.prototype.resolveNamespaces = function() { profile.enterFn("XMLElement", "resolveNamespaces"); function getNameSpaceFromPrefix(base, pfx) { profile.enterFn("XMLElement", "resolveNamespaces.getNameSpaceFromPrefix"); var attrName = "xmlns"; if (pfx) { attrName = "xmlns:" + pfx; } var element = base; while (element) { var attr = element.attribute(attrName); if (attr) { profile.leaveFn("resolveNamespaces.getNameSpaceFromPrefix"); return attr.value; } element = element.parent; } profile.leaveFn("resolveNamespaces.getNameSpaceFromPrefix"); return ""; }; this.namespace = getNameSpaceFromPrefix(this, this.prefix); for (var i = 0; i < this._attributes.length; i++) { if (/^xmlns(?:$|:)/.test(this._attributes[i].name)) { continue; } this._attributes[i].namespace = getNameSpaceFromPrefix(this, this._attributes[i].prefix); } profile.leaveFn("resolveNamespaces"); } XMLElement.prototype.is = function(localName, namespace) { return (this.localName == localName) && (this.namespace == namespace); } XMLElement.prototype.contents = function() { profile.enterFn("XMLElement", "contents"); var str = this._content; if ((this._content == "") && (this._children.length > 0)) { str = ""; for (var i = 0; i < this._children.length; i++) { str += this._children[i].contents(); } } profile.leaveFn("contents"); return str; } XMLElement.prototype.attribute = function(name, namespace) { profile.enterFn("XMLElement", "attribute"); for (var i = 0; i < this._attributes.length; i++) { if ((typeof namespace != "undefined") && (this._attributes[i].namespace != namespace)) { continue; } if (this._attributes[i].name == name) { profile.leaveFn("attribute"); return this._attributes[i]; } } profile.leaveFn("attribute"); return null; } XMLElement.prototype.childrenByName = function(name, namespace) { profile.enterFn("XMLElement", "childrenByName"); var rv = []; for (var i = 0; i < this._children.length; i++) { if ((typeof namespace != "undefined") && (this._children[i].namespace != namespace)) { continue; } if (this._children[i].name == name) { rv.push(this._children[i]); } } profile.leaveFn("childrenByName"); return rv; } XMLElement.prototype.childByName = function(name, namespace) { profile.enterFn("XMLElement", "childByName"); var l = this.childrenByName(name); if (l.length != 1) { profile.leaveFn("childByName"); return null; } profile.leaveFn("childByName"); return l[0]; } function XMLAttribute(parent, name, value) { this.type = "XMLAttribute"; this.parent = parent; this.name = name; this.value = value; this.namespace = ""; var ary = this.name.match(/^(.*?):(.*)$/); if (ary) { this.prefix = ary[1]; this.localName = ary[2]; } else { this.prefix = null; this.localName = this.name; } } XMLAttribute.prototype.toString = function() { profile.enterFn("XMLAttribute", "toString"); var str = ""; if (this.prefix != null) { str += this.prefix + ":"; } str += this.localName; if (this.namespace) { str += "[[" + this.namespace + "]]"; } str += "='" + this.value + "'"; profile.leaveFn("toString"); return str; } function XMLCData(value) { this.type = "XMLCData"; this.value = value; } XMLCData.prototype.toString = function() { profile.enterFn("XMLCData", "toString"); var str = "<![CDATA[" + this.value + "]]>"; profile.leaveFn("toString"); return str; } XMLCData.prototype.contents = function() { return this.value; } function XMLComment(value) { this.type = "XMLComment"; this.value = value; } XMLComment.prototype.toString = function() { profile.enterFn("XMLComment", "toString"); var str = "<!" + this.value + ">"; profile.leaveFn("toString"); return str; } XMLComment.prototype.contents = function() { return this.toString(); } // #includeend function JSProfiler() { this.running = false; this.showRunningTrace = false; this._calls = 0; } JSProfiler.prototype.start = function() { if (this.running) { throw new Error("Can't start profiler when it is already running."); } this.running = true; this._calls = 0; this._functions = new Object(); this._stack = new Array(); this._lastJumpTime = Number(new Date()); if (this.showRunningTrace) { log("PROFILER: START"); } } JSProfiler.prototype.stop = function(title) { if (!this.running) { throw new Error("Can't stop profiler when it is not running."); } if (this.showRunningTrace) { log("PROFILER: STOP"); } this.running = false; if (this._calls == 0) { //log("No JSPRofiler profiled functions."); return; } function makeCol(val, width) { val = String(val); while (val.length < width) { val = " " + val; } return val; }; var keys = new Array(); for (var key in this._functions) { keys.push(key); } var self = this; keys.sort(function(a, b) { if (self._functions[a].totalTime < self._functions[b].totalTime) return 1; if (self._functions[a].totalTime > self._functions[b].totalTime) return -1; if (self._functions[a].callCount < self._functions[b].callCount) return 1; if (self._functions[a].callCount > self._functions[b].callCount) return -1; return 0; }); if (keys.length == 0) { return; } var shownHeaders = false; for (var i = 0; i < keys.length; i++) { var fn = this._functions[keys[i]]; // Always print if runTime >= 1000 or in top 3, but drop out for < 100ms anyway. //if (((fn.totalTime < 1000) && (i >= 3)) || (fn.totalTime < 100)) { if (fn.totalTime < 100) { break; } if (!shownHeaders) { log("JSProfiler Dump" + (title ? " for " + title : "") + ":"); log(" Calls Actual (ms) Nested (ms) Class/Name"); shownHeaders = true; } log(" " + makeCol(fn.callCount, 6) + makeCol(fn.runTime, 13) + makeCol(fn.totalTime, 13) + " " + keys[i]); } } JSProfiler.prototype.enterFn = function(cls, name) { var key = (cls ? cls + "." : "") + name; if (!(key in this._functions)) { this._functions[key] = { cls: cls, name: name, callCount: 0, totalTime: 0, runTime: 0 }; } if (this.showRunningTrace) { var nest = ""; for (var i = 0; i < this._stack.length; i++) { nest += " "; } log("PROFILER: " + nest + (cls ? "<" + cls + ">" : "") + name + " {"); } var now = Number(new Date()); if (this._stack.length > 0) { this._functions[this._stack[this._stack.length - 1].key].runTime += now - this._lastJumpTime; } this._calls++; this._functions[key].callCount++; this._stack.push({ key: key, name: name, start: now }); this._lastJumpTime = now; } JSProfiler.prototype.leaveFn = function(name) { if (this.showRunningTrace) { var nest = ""; for (var i = 1; i < this._stack.length; i++) { nest += " "; } log("PROFILER: " + nest + "} // " + name); } var now = Number(new Date()); var items = new Array(); for (var i = this._stack.length - 1; i >= 0; i--) { if (this._stack[i].name == name) { this._functions[this._stack[i].key].runTime += now - this._lastJumpTime; this._functions[this._stack[i].key].totalTime += now - this._stack[i].start; if (i != this._stack.length - 1) { log("WARNING: leaving function '" + name + "' skipping " + (this._stack.length - 1 - i) + " stack items (" + items.join(", ") + ")!"); } this._stack.splice(i); this._lastJumpTime = now; return; } items.push(this._stack[i].key); } log("WARNING: leaving function '" + name + "' we never entered!"); this._lastJumpTime = now; } var profile = new JSProfiler();
contrib/Feeds.js
// JavaScript plugin for RSS and Atom feeds. // // Copyright 2005 - 2006, James G. Ross // var BufferedReader = Packages.java.io.BufferedReader; var File = Packages.java.io.File; var FileInputStream = Packages.java.io.FileInputStream; var InputStreamReader = Packages.java.io.InputStreamReader; var System = Packages.java.lang.System; var URL = Packages.java.net.URL; var ChoobPermission = Packages.uk.co.uwcs.choob.support.ChoobPermission; var GetContentsCached = Packages.uk.co.uwcs.choob.support.GetContentsCached; function log(msg) { dumpln("FEEDS [" + (new Date()) + "] " + msg); } String.prototype.trim = function _trim() { return this.replace(/^\s+/, "").replace(/\s+$/, ""); } // Constructor: Feeds function Feeds(mods, irc) { profile.start(); this._mods = mods; this._irc = irc; this._debugStatus = ""; this._debugChannel = "#testing42"; this._announceChannel = "#testing42"; this._debug_profile = false; this._debug_interval = false; this._debug_store = false; this._debug_xml = false; this._debug_trace = false; this._feedList = new Array(); this._feedCheckLock = false; var feeds = mods.odb.retrieve(Feed, ""); for (var i = 0; i < feeds.size(); i++) { var feed = feeds.get(i); // Allow the feed to save itself when it makes changes. feed.__mods = mods; feed.save = function _feed_save() { this.__mods.odb.update(this) }; feed.init(this, ""); this._feedList.push(feed); } mods.interval.callBack("feed-check", 10000, 1); profile.stop("init"); this._setStatus("Waiting for first feed check."); } Feeds.prototype.info = [ "Generic feed reader with notification.", "James Ross", "[email protected]", "1.6.3" ]; // Callback for all intervals from this plugin. Feeds.prototype.interval = function(param, mods, irc) { function mapCase(s, a, b) { return a.toUpperCase() + b.toLowerCase(); }; if (param) { var name = "_" + param.replace(/-(\w)(\w+)/g, mapCase) + "Interval"; if (name in this) { try { this[name](param, mods, irc); } catch(ex) { log("Exception in " + name + ": " + ex + (ex.fileName ? " at <" + ex.fileName + ":" + ex.lineNumber + ">":"")); irc.sendMessage(this._debugChannel, "Exception in " + name + ": " + ex + (ex.fileName ? " at <" + ex.fileName + ":" + ex.lineNumber + ">":"")); } } else { irc.sendMessage(this._debugChannel, "Interval code missing: " + name); } } else { irc.sendMessage(this._debugChannel, "Unnamed interval attempted!"); } } // Command: Add Feeds.prototype.commandAdd = function(mes, mods, irc) { var params = mods.util.getParams(mes, 2); if (params.size() <= 2) { irc.sendContextReply(mes, "Syntax: Feeds.Add <feedname> <url>"); return; } var feedName = String(params.get(1)).trim(); var feedURL = String(params.get(2)).trim(); // Remove existing feed, if possible. var feed = this._getFeed(feedName); if (feed) { if (!this._canAdminFeed(feed, mes)) { irc.sendContextReply(mes, "You don't have permission to replace feed '" + feedName + "'!"); } this._removeFeed(feed); } // Load new feed. irc.sendContextReply(mes, "Loading feed '" + feedName + "'..."); var feed = new Feed(this, feedName, feedURL, mes.getContext()); mods.odb.save(feed); // Allow the feed to save itself when it makes changes. feed.__mods = mods; feed.save = function _feed_save() { this.__mods.odb.update(this) }; feed.owner = this._getOwnerFrom(mes.getNick()); this._feedList.push(feed); feed.addOutputTo(mes.getContext()); // Check feed now. mods.interval.callBack("feed-check", 1000, 1); } Feeds.prototype.commandAdd.help = [ "Adds a new feed.", "<feedname> <url>", "<feedname> is the name for the new feed", "<url> is the URL of the new feed" ]; // Command: Remove Feeds.prototype.commandRemove = function(mes, mods, irc) { var params = mods.util.getParams(mes, 1); if (params.size() <= 1) { irc.sendContextReply(mes, "Syntax: Feeds.Remove <feedname>"); return; } var feedName = String(params.get(1)).trim(); var feed = this._getFeed(feedName); if (!feed) { irc.sendContextReply(mes, "Feed '" + feedName + "' not found."); return; } if (!this._canAdminFeed(feed, mes)) { irc.sendContextReply(mes, "You don't have permission to remove feed '" + feedName + "'!"); return; } this._removeFeed(feed); irc.sendContextReply(mes, "Feed " + feed.getDisplayName() + " removed."); } Feeds.prototype.commandRemove.help = [ "Removes an feed entirely.", "<feedname>", "<feedname> is the name of the feed to remove" ]; // Command: List Feeds.prototype.commandList = function(mes, mods, irc) { if (this._feedList.length == 0) { irc.sendContextReply(mes, "No feeds set up."); return; } function displayFeedItemLine(i, feed) { var dests = feed._outputTo.join(", "); var error = feed.getError(); irc.sendContextReply(mes, "Feed " + feed.getDisplayName() + " owned by " + (feed.owner ? feed.owner : "<unknown>") + (feed.isPrivate ? " (\x02private\x02)" : "") + ", " + (error ? (error) : (feed._lastItemCount + " items (" + feed.getLastLoaded() + ")") ) + ", " + "TTL of " + feed.ttl + "s, source <" + feed.url + ">." + (dests ? " Notifications to: " + dests + "." : "")); }; function getFeedItemString(feed) { return feed.getDisplayName() + " (" + feed._lastItemCount + (feed.isPrivate ? ", \x02private\x02" : "") + ")"; }; function getFeedErrorLine(feed) { return "Feed " + feed.getDisplayName() + ": " + feed.getError() + "."; }; var params = mods.util.getParams(mes, 1); if (params.size() > 1) { var findName = String(params.get(1)).trim(); var findIO = "," + findName.toLowerCase() + ","; var foundIO = false; for (var i = 0; i < this._feedList.length; i++) { // Skip private feeds that user can't control. if (this._feedList[i].isPrivate && !this._canAdminFeed(this._feedList[i], mes)) { continue; } if (this._feedList[i].name.toLowerCase() == findName.toLowerCase()) { displayFeedItemLine(i, this._feedList[i]); return; } else if (("," + this._feedList[i]._outputTo.join(",") + ",").toLowerCase().indexOf(findIO) != -1) { displayFeedItemLine(i, this._feedList[i]); foundIO = true; } else if (findName == "*") { displayFeedItemLine(i, this._feedList[i]); } } if ((findName != "*") && !foundIO) { irc.sendContextReply(mes, "Feed or target '" + findName + "' not found."); } return; } var outputs = new Object(); var errs = new Array(); for (var i = 0; i < this._feedList.length; i++) { // Skip private feeds that user can't control. if (this._feedList[i].isPrivate && !this._canAdminFeed(this._feedList[i], mes)) { continue; } var st = this._feedList[i].getSendTo(); for (var j = 0; j < st.length; j++) { if (!(st[j] in outputs)) { outputs[st[j]] = new Array(); } outputs[st[j]].push(this._feedList[i]); } if (st.length == 0) { if (!("nowhere" in outputs)) { outputs["nowhere"] = new Array(); } outputs["nowhere"].push(this._feedList[i]); } if (this._feedList[i].getError()) { errs.push(this._feedList[i]); } } var outputList = new Array(); for (var o in outputs) { outputList.push(o); } outputList.sort(); for (o = 0; o < outputList.length; o++) { var str = "For " + outputList[o] + ": "; for (var i = 0; i < outputs[outputList[o]].length; i++) { if (i > 0) { str += ", "; } str += getFeedItemString(outputs[outputList[o]][i]); } str += "."; irc.sendContextReply(mes, str); } for (var i = 0; i < errs.length; i++) { irc.sendContextReply(mes, getFeedErrorLine(errs[i])); } } Feeds.prototype.commandList.help = [ "Lists all feeds and where they are displayed, or information about a single feed.", "[<name>]", "<name> is the (optional) name of a feed or target (e.g. channel) to get details on" ]; // Command: AddOutput Feeds.prototype.commandAddOutput = function(mes, mods, irc) { var params = mods.util.getParams(mes, 2); if (params.size() <= 2) { irc.sendContextReply(mes, "Syntax: Feeds.AddOutput <feedname> <dest>"); return; } var feedName = String(params.get(1)).trim(); var feed = this._getFeed(feedName); if (!feed) { irc.sendContextReply(mes, "Feed '" + feedName + "' not found."); return; } if (!this._canAdminFeed(feed, mes)) { irc.sendContextReply(mes, "You don't have permission to edit feed '" + feedName + "'!"); return; } var feedDest = String(params.get(2)).trim(); if (feed.addOutputTo(feedDest)) { irc.sendContextReply(mes, "Feed " + feed.getDisplayName() + " will now output to '" + feedDest + "'."); } else { irc.sendContextReply(mes, "Feed " + feed.getDisplayName() + " already outputs to '" + feedDest + "'."); } } Feeds.prototype.commandAddOutput.help = [ "Adds a new output destination for an feed.", "<feedname> <dest>", "<feedname> is the name of the feed to modify", "<dest> is the channel name to send notifications to" ]; // Command: RemoveOutput Feeds.prototype.commandRemoveOutput = function(mes, mods, irc) { var params = mods.util.getParams(mes, 2); if (params.size() <= 2) { irc.sendContextReply(mes, "Syntax: Feeds.RemoveOutput <feedname> <dest>"); return; } var feedName = String(params.get(1)).trim(); var feed = this._getFeed(feedName); if (!feed) { irc.sendContextReply(mes, "Feed '" + feedName + "' not found."); return; } if (!this._canAdminFeed(feed, mes)) { irc.sendContextReply(mes, "You don't have permission to edit feed '" + feedName + "'!"); return; } var feedDest = String(params.get(2)).trim(); if (feed.removeOutputTo(feedDest)) { irc.sendContextReply(mes, "Feed " + feed.getDisplayName() + " will no longer output to '" + feedDest + "'."); } else { irc.sendContextReply(mes, "Feed " + feed.getDisplayName() + " doesn't output to '" + feedDest + "'."); } } Feeds.prototype.commandRemoveOutput.help = [ "Removes an output destination for an feed.", "<feedname> <dest>", "<feedname> is the name of the feed to modify", "<dest> is the channel name to stop sending notifications to" ]; // Command: Recent Feeds.prototype.commandRecent = function(mes, mods, irc) { var params = mods.util.getParams(mes, 2); if (params.size() <= 1) { irc.sendContextReply(mes, "Syntax: Feeds.Recent <feedname> [[<offset>] <count>]"); return; } var feedName = String(params.get(1)).trim(); var feed = this._getFeed(feedName); if (!feed) { irc.sendContextReply(mes, "Feed '" + feedName + "' not found."); return; } // Allow anyone to get recent items for public feeds, and only someone // who can admin a feed to do it for private feeds. if (feed.isPrivate && !this._canAdminFeed(feed, mes)) { irc.sendContextReply(mes, "You don't have permission to view feed '" + feedName + "'!"); return; } var offset = 0; var count = 5; if (params.size() > 3) { offset = params.get(2); count = params.get(3); } else if (params.size() > 2) { count = params.get(2); } if ((String(offset).trim() != String(Number(offset))) || (offset < 0)) { irc.sendContextReply(mes, "<offset> must be numeric and non-negative"); return; } if ((String(count).trim() != String(Number(count))) || (count <= 0)) { irc.sendContextReply(mes, "<count> must be numeric and positive"); return; } if (offset + count > feed._lastItemCount) { count = feed._lastItemCount - offset; } feed.showRecent(mes.getContext(), offset, count); } Feeds.prototype.commandRecent.help = [ "Displays a number of recent items from a feed.", "<feedname> [[<offset>] <count>]", "<feedname> is the name of the feed to modify", "<offset> is now many entires back in time to go (default is 0)", "<count> is the number of recent items to show (default is 5)" ]; // Command: SetOwner Feeds.prototype.commandSetOwner = function(mes, mods, irc) { var params = mods.util.getParams(mes, 2); if (params.size() <= 2) { irc.sendContextReply(mes, "Syntax: Feeds.SetOwner <feedname> <owner>"); return; } var feedName = String(params.get(1)).trim(); var feed = this._getFeed(feedName); if (!feed) { irc.sendContextReply(mes, "Feed '" + feedName + "' not found."); return; } if (!this._canAdminFeed(feed, mes)) { irc.sendContextReply(mes, "You don't have permission to edit feed '" + feedName + "'!"); return; } var owner = this._getOwnerFrom(String(params.get(2)).trim()); feed.owner = owner; irc.sendContextReply(mes, "Feed " + feed.getDisplayName() + " now has an owner of " + owner + "."); mods.odb.update(feed); } Feeds.prototype.commandSetOwner.help = [ "Sets the owner of the feed, who has full control over it.", "<feedname> <ttl>", "<feedname> is the name of the feed to modify", "<owner> is the new owner", ]; // Command: SetPrivate Feeds.prototype.commandSetPrivate = function(mes, mods, irc) { var params = mods.util.getParams(mes, 2); if (params.size() <= 2) { irc.sendContextReply(mes, "Syntax: Feeds.SetPrivate <feedname> <value>"); return; } var feedName = String(params.get(1)).trim(); var feed = this._getFeed(feedName); if (!feed) { irc.sendContextReply(mes, "Feed '" + feedName + "' not found."); return; } if (!this._canAdminFeed(feed, mes)) { irc.sendContextReply(mes, "You don't have permission to edit feed '" + feedName + "'!"); return; } var isPrivate = String(params.get(2)).trim(); isPrivate = ((isPrivate == "1") || (isPrivate == "on") || (isPrivate == "true") || (isPrivate == "yes")); feed.isPrivate = isPrivate; if (isPrivate) { irc.sendContextReply(mes, "Feed " + feed.getDisplayName() + " is now private."); } else { irc.sendContextReply(mes, "Feed " + feed.getDisplayName() + " is no longer private."); } mods.odb.update(feed); } Feeds.prototype.commandSetOwner.help = [ "Sets whether the feed shows up to users who can't administrate it.", "<feedname> <value>", "<feedname> is the name of the feed to modify", "<value> is either 'true' or 'false'", ]; // Command: SetTTL Feeds.prototype.commandSetTTL = function(mes, mods, irc) { var params = mods.util.getParams(mes, 2); if (params.size() <= 2) { irc.sendContextReply(mes, "Syntax: Feeds.SetTTL <feedname> <ttl>"); return; } var feedName = String(params.get(1)).trim(); var feed = this._getFeed(feedName); if (!feed) { irc.sendContextReply(mes, "Feed '" + feedName + "' not found."); return; } if (!this._canAdminFeed(feed, mes)) { irc.sendContextReply(mes, "You don't have permission to edit feed '" + feedName + "'!"); return; } var feedTTL = 1 * params.get(2); if (feedTTL < 60) { irc.sendContextReply(mes, "Sorry, but a TTL of less than 60 is not allowed."); return; } feed.ttl = feedTTL; irc.sendContextReply(mes, "Feed " + feed.getDisplayName() + " now has a TTL of " + feedTTL + "."); mods.odb.update(feed); } Feeds.prototype.commandSetTTL.help = [ "Sets the TTL (time between updates) of a feed.", "<feedname> <ttl>", "<feedname> is the name of the feed to modify", "<ttl> is the new TTL for the feed", ]; // Command: SetDebug Feeds.prototype.commandSetDebug = function(mes, mods, irc) { if (!mods.security.hasPerm(new ChoobPermission("feeds.debug"), mes)) { irc.sendContextReply(mes, "You don't have permission to debug Feeds!"); return; } var params = mods.util.getParams(mes, 2); if (params.size() <= 2) { irc.sendContextReply(mes, "Syntax: Feeds.SetDebug <flag> <enabled>"); return; } var flag = String(params.get(1)).trim(); var enabled = String(params.get(2)).trim(); enabled = ((enabled == "1") || (enabled == "on") || (enabled == "true") || (enabled == "yes")); if (flag == "profile") { if (enabled) { irc.sendContextReply(mes, "Debug profiling enabled."); } else { irc.sendContextReply(mes, "Debug profiling disabled."); } } else if (flag == "interval") { if (enabled) { irc.sendContextReply(mes, "Debug interval timing enabled."); } else { irc.sendContextReply(mes, "Debug interval timing disabled."); } } else if (flag == "store") { if (enabled) { irc.sendContextReply(mes, "Debug feed store enabled."); } else { irc.sendContextReply(mes, "Debug feed store disabled."); } } else if (flag == "xml") { if (enabled) { irc.sendContextReply(mes, "Debug XML parser enabled."); } else { irc.sendContextReply(mes, "Debug XML parser disabled."); } } else if (flag == "trace") { if (enabled) { profile.showRunningTrace = true; irc.sendContextReply(mes, "Debug execution trace enabled."); } else { profile.showRunningTrace = false; irc.sendContextReply(mes, "Debug execution trace disabled."); } } else { irc.sendContextReply(msg, "Unknown flag specified. Must be one of 'profile', 'interval', 'store', 'xml' or 'trace'."); return; } this["_debug_" + flag] = enabled; } Feeds.prototype.commandSetDebug.help = [ "Sets debug mode on or off.", "<flag> <enabled>", "<flag> is one of 'profile', 'interval', 'store', 'xml' or 'trace', so specify what to debug", "<enabled> is either 'true' or 'false' to set" ]; // Command: Status Feeds.prototype.commandStatus = function(mes, mods, irc) { irc.sendContextReply(mes, "Feeds Status: " + this._debugStatus); } Feeds.prototype.commandStatus.help = [ "Shows the current debugging status of the Feeds plugin.", "" ]; // Command: Info //Feeds.prototype.commandInfo = function(mes, mods, irc) { // // //irc.sendContextReply(mes, "Error getting SVN info: " + ex); //} //Feeds.prototype.commandInfo.help = [ // "Stuff." // ]; Feeds.prototype._getOwnerFrom = function(nick) { var primary = this._mods.nick.getBestPrimaryNick(nick); var root = this._mods.security.getRootUser(primary); if (root) { return String(root); } return String(primary); } Feeds.prototype._getFeed = function(name) { for (var i = 0; i < this._feedList.length; i++) { var feed = this._feedList[i]; if (feed.name.toLowerCase() == name.toLowerCase()) { return feed; } } return null; } Feeds.prototype._canAdminFeed = function(feed, mes) { if (this._mods.security.hasPerm(new ChoobPermission("feeds.edit"), mes)) { return true; // plugin admin } if (feed.owner == this._getOwnerFrom(mes.getNick())) { return true; // feed owner } return false; } Feeds.prototype._removeFeed = function(feed) { for (var i = 0; i < this._feedList.length; i++) { if (this._feedList[i] == feed) { this._mods.odb["delete"](this._feedList[i]); this._feedList.splice(i, 1); return; } } } Feeds.prototype._setStatus = function(msg) { this._debugStatus = "[" + (new Date()) + "] " + msg; } Feeds.prototype._ = function() { } // Interval: feed-check Feeds.prototype._feedCheckInterval = function(param, mods, irc) { if (this._feedCheckLock) return; this._feedCheckLock = true; if (this._debug_interval) { log("Interval: start"); } this._setStatus("Checking feeds..."); for (var i = 0; i < this._feedList.length; i++) { var feed = this._feedList[i]; if (!feed.safeToCheck()) { continue; } if (this._debug_interval) { log("Interval: checking " + feed.name + " (" + -this._feedList[i].getNextCheck() + "ms late)"); } this._setStatus("Checking feed " + feed.getDisplayName() + "..."); if (this._debug_profile) { profile.start(); } feed.checkForNewItems(); if (this._debug_profile) { profile.stop(feed.name); } this._setStatus("Last checked feed " + feed.getDisplayName() + "."); } var nextCheck = 60 * 60 * 1000; // 1 hour for (var i = 0; i < this._feedList.length; i++) { var feedNextCheck = this._feedList[i].getNextCheck(); if (feedNextCheck < 0) { feedNextCheck = 0; } if (nextCheck > feedNextCheck) { nextCheck = feedNextCheck; } } // Helps to group the calls. var extra = 0; if (nextCheck > 10000) { extra = 5000; } if (this._debug_interval) { log("Interval: next check due in " + nextCheck + "ms" + (extra ? " + " + extra + "ms" : "")); log("Interval: end"); } this._feedCheckLock = false; // Don't return in anything less than 1s. mods.interval.callBack("feed-check", nextCheck + extra, 1); } function Feed() { this.id = 0; this.name = ""; this.displayName = ""; this.outputTo = ""; this.url = ""; this.ttl = 300; // Default TTL this.owner = ""; this.isPrivate = false; this.save = function(){}; this._items = new Array(); this._error = ""; this._errorExpires = 0; if (arguments.length > 0) { this._ctor(arguments[0], arguments[1], arguments[2], arguments[3]); } } Feed.prototype._ctor = function(parent, name, url, loadContext) { this.name = name; this.displayName = name; this.url = url; this.init(parent, loadContext) } Feed.prototype.getDisplayName = function() { if (this.displayName) return "'" + this.displayName + "' (" + this.name + ")"; return this.name; } Feed.prototype.init = function(parent, loadContext) { profile.enterFn("Feed(" + this.name + ")", "init"); this._parent = parent; this._loadContext = loadContext; this._outputTo = new Array(); if (this.outputTo) { this._outputTo = this.outputTo.split(" "); this._outputTo.sort(); } this._cachedContents = null; this._lastSeen = new Object(); this._lastSeenPub = new Object(); this._lastItemCount = 0; this._lastCheck = 0; this._lastLoaded = 0; if (this._parent._debug_store) { log("Feed Store: " + this.name + ": " + this._items.length); } profile.leaveFn("init"); } Feed.prototype.addOutputTo = function(destination) { for (var i = 0; i < this._outputTo.length; i++) { if (this._outputTo[i].toLowerCase() == destination.toLowerCase()) { return false; } } this._outputTo.push(destination); this._outputTo.sort(); this.outputTo = this._outputTo.join(" "); this.save(); return true; } Feed.prototype.removeOutputTo = function(destination) { for (var i = 0; i < this._outputTo.length; i++) { if (this._outputTo[i].toLowerCase() == destination.toLowerCase()) { this._outputTo.splice(i, 1); this.outputTo = this._outputTo.join(" "); this.save(); return true; } } return false; } Feed.prototype.getError = function() { if (this._error) { return this._error + " [expires " + (new Date(this._errorExpires)) + "]"; } return ""; } Feed.prototype.setError = function(msg) { this._error = msg; this._errorExpires = Number(new Date()) + 60 * 60 * 1000; // 1 hour } Feed.prototype.getSendTo = function() { var st = new Array(); for (var i = 0; i < this._outputTo.length; i++) { st.push(this._outputTo[i]); } return st; } Feed.prototype.getLastLoaded = function() { if (this._lastLoaded == 0) return "never loaded"; return ("loaded " + this._lastLoaded); } // Return boolean indicating if it is ok to reload the contents of the feed. Feed.prototype.safeToCheck = function() { // If the error has expired, clear it. if (this._error && (this._errorExpires < Number(new Date()))) { this._error = ""; this._errorExpires = 0; } if (this._error) { return false; } // <ttl> min delay. Default is 1m. var checkTime = Number(new Date()) - (this.ttl * 1000); return (Number(this._lastCheck) < checkTime); } // Return the number of milliseconds until the next checkpoint. Feed.prototype.getNextCheck = function() { var delay = (this._lastCheck ? Number(this._lastCheck) - Number(new Date()) + (this.ttl * 1000) : 0); if (this._error) { delay = this._errorExpires - Number(new Date()); } return delay; } Feed.prototype.showRecent = function(target, offset, count) { if (this.getError()) { this._sendTo(target, this.getDisplayName() + ": \x02ERROR\x02: " + this.getError()); return; } var items = this._items; if (items.length == 0) { if (this._lastCheck == 0) { this._sendTo(target, this.getDisplayName() + " has not loaded yet."); } else { this._sendTo(target, this.getDisplayName() + " has no recent items."); } return; } var start = items.length - 1; // Default to the last item. if (start > offset + count) { start = offset + count - 1; } if (start > items.length - 1) { // Make sure not to start before the oldest item we have. start = items.length - 1; } for (var i = start; i >= offset; i--) { this._sendTo(target, "[" + items[i].date + "] \x1F" + items[i].title + "\x1F " + items[i].desc, (items[i].link ? " <" + items[i].link + ">" : "")); } } Feed.prototype.checkForNewItems = function() { profile.enterFn("Feed(" + this.name + ")", "checkForNewItems"); if (this.getError()) { profile.leaveFn("checkForNewItems"); return; } var firstRun = (this._lastCheck == 0); var newItems = this.getNewItems(); if (this.getError()) { if (firstRun && this._loadContext) { // We're trying to load the feed, and it failed. Oh the humanity. this._parent._irc.sendMessage(this._loadContext, this.getDisplayName() + " failed to load, incurring the error: " + this.getError()); } //this._sendToAll(this.getDisplayName() + ": \x02ERROR\x02: " + this.getError()); profile.leaveFn("checkForNewItems"); return; } this._lastLoaded = new Date(); if (firstRun && this._loadContext) { this._parent._irc.sendMessage(this._loadContext, this.getDisplayName() + " loaded with " + this._lastItemCount + " items."); } // If there are more than 3 items, and it's more than 20% of the feed's // length, don't display the items. This allows feeds with more items (e.g. // news feeds) to flood a little bit more, but still prevents a feed from // showing all it's items if it just added them all. // Never bother with more than 10 items, whatever. if ((newItems.length > 10) || ((newItems.length > 3) && (newItems.length > 0.20 * this._lastItemCount))) { this._sendToAll(this.getDisplayName() + " has too many (" + newItems.length + ") new items to display."); } else { for (var i = newItems.length - 1; i >= 0; i--) { if (newItems[i].updated) { this._sendToAll("\x1F" + newItems[i].title + "\x1F " + newItems[i].desc, (newItems[i].link ? " <" + newItems[i].link + ">" : "")); } else { this._sendToAll("\x1F\x02" + newItems[i].title + "\x02\x1F " + newItems[i].desc, (newItems[i].link ? " <" + newItems[i].link + ">" : "")); } } } profile.leaveFn("checkForNewItems"); } Feed.prototype.ensureCachedContents = function() { profile.enterFn("Feed(" + this.name + ")", "ensureCachedContents"); try { if (!this._cachedContents) { var urlObj = new URL(this.url); profile.enterFn("Feed(" + this.name + ")", "ensureCachedContents.getContentsCached"); this._cachedContents = new GetContentsCached(urlObj, 60000); profile.leaveFn("ensureCachedContents.getContentsCached"); } } catch(ex) { // Error = no items. this.setError("Exception getting data: " + ex + (ex.fileName ? " at <" + ex.fileName + ":" + ex.lineNumber + ">":"")); profile.leaveFn("ensureCachedContents"); return false; } profile.leaveFn("ensureCachedContents"); return true; } Feed.prototype.getNewItems = function() { profile.enterFn("Feed(" + this.name + ")", "getNewItems"); if (!this.ensureCachedContents()) { profile.leaveFn("getNewItems"); return []; } var feedData = ""; profile.enterFn("Feed(" + this.name + ")", "getNewItems.getCachedContents"); try { feedData = String(this._cachedContents.getContents()); } catch(ex) { profile.leaveFn("getNewItems.getCachedContents"); // Error = no items. this.setError("Exception getting data: " + ex + (ex.fileName ? " at <" + ex.fileName + ":" + ex.lineNumber + ">":"")); profile.leaveFn("getNewItems"); return []; } profile.leaveFn("getNewItems.getCachedContents"); if (feedData == "") { this.setError("Unable to fetch data"); profile.leaveFn("getNewItems"); return []; } try { profile.enterFn("FeedParser(" + this.name + ")", "new"); var feedParser = new FeedParser(this._parent, feedData); profile.leaveFn("new"); } catch(ex) { this.setError("Exception in parser: " + ex + (ex.fileName ? " at <" + ex.fileName + ":" + ex.lineNumber + ">":"")); profile.leaveFn("getNewItems"); return []; } var firstTime = true; var curItems = new Object(); for (var d in this._lastSeen) { firstTime = false; this._lastSeen[d] = false; } for (var d in this._lastSeenPub) { this._lastSeenPub[d] = false; } // Force TTL to be >= that in the feed itself. if (feedParser.ttl && (this.ttl < feedParser.ttl)) { this.ttl = feedParser.ttl; this.save(); } // Update title if it's different. if (feedParser.title) { var feedTitle = feedParser.title.replace(/^\s+/, "").replace(/\s+$/, ""); if (this.displayName != feedTitle) { this.displayName = feedTitle; this.save(); } } var newItems = new Array(); var newUniques = new Object(); // Only keep new or updated items in the list. for (var i = 0; i < feedParser.items.length; i++) { var item = feedParser.items[i]; // Prefer, in order: GUID, link, date, title. var unique = (item.guid ? item.guid : (item.link ? item.link : (item.date != "?" ? item.date : item.title))); var date = unique + ":" + item.date; if (unique in newUniques) { // Skip repeated unique items. Broken feed! continue; } newUniques[unique] = true; if (unique in this._lastSeen) { // Seen this item before. Has it changed? if (date in this._lastSeenPub) { // No change. this._lastSeen[unique] = true; this._lastSeenPub[date] = true; continue; } // Items changed. item.updated = true; } // New item. item.uniqueKey = unique; newItems.push(item); this._lastSeen[unique] = true; this._lastSeenPub[date] = true; // Remove and re-add from store if it's updated. Just add for new. if (item.updated) { for (var i = 0; i < this._items.length; i++) { if (this._items[i].uniqueKey == item.uniqueKey) { if (this._parent._debug_store) { log("Feed Store: " + this.name + ": DEL <" + this._items[i].uniqueKey + "><" + this._items[i].date + ">"); } this._items.splice(i, 1); break; } } } if (this._parent._debug_store) { log("Feed Store: " + this.name + ": ADD <" + item.uniqueKey + "><" + item.date + ">"); } this._items.push(item); } for (var d in this._lastSeen) { if (!this._lastSeen[d]) { delete this._lastSeen[d]; for (var i = 0; i < this._items.length; i++) { if (this._items[i].uniqueKey == d) { if (this._parent._debug_store) { log("Feed Store: " + this.name + ": DEL <" + this._items[i].uniqueKey + "><" + this._items[i].date + ">"); } this._items.splice(i, 1); break; } } } } for (var d in this._lastSeenPub) { if (!this._lastSeenPub[d]) { delete this._lastSeenPub[d]; } } if (this._parent._debug_store) { log("Feed Store: " + this.name + ": " + this._items.length); } var count = 0; for (var d in this._lastSeenPub) { count++; } this._lastItemCount = count; if (firstTime) { newItems = new Array(); } this._lastCheck = new Date(); profile.leaveFn("getNewItems"); return newItems; } Feed.prototype._sendToAll = function(message, suffix) { for (var i = 0; i < this._outputTo.length; i++) { this._sendTo(this._outputTo[i], message, suffix); } } Feed.prototype._sendTo = function(target, message, suffix) { if (typeof suffix != "string") { suffix = ""; } if (message.length + suffix.length > 390) { message = message.substr(0, 390 - suffix.length) + "..."; } this._parent._irc.sendMessage(target, message + suffix); } var entityMap = { "lt": "<", "#60": "<", "gt": ">", "#62": ">", "quot": '"', "#34": '"', "ldquo": '"', "#8220": '"', "rdquo": '"', "#8221": '"', "apos": "'", "#39": "'", "lsquo": "'", "#8216": "'", "rsquo": "'", "#8217": "'", "nbsp": " ", "#160": " ", "ndash": "-", "#8211": "-", "mdash": "-", "#8212": "-", "lsaquo": "<<", "#8249": "<<", "rsaquo": ">>", "#8250": ">>", "times": "x", "#163": "", "#8230": "...", "dummy": "" }; function _decodeEntities(data) { profile.enterFn("", "_decodeEntities"); // Decode XML into HTML... data = data.replace(/&(?:(\w+)|#(\d+)|#x([0-9a-f]{2}));/gi, function _decodeEntity(match, name, decnum, hexnum) { if (name && (name in entityMap)) { return entityMap[name]; } if (decnum && (String("#" + parseInt(decnum, 10)) in entityMap)) { return entityMap[String("#" + parseInt(decnum, 10))]; } if (hexnum && (String("#" + parseInt(hexnum, 16)) in entityMap)) { return entityMap[String("#" + parseInt(hexnum, 16))]; } return match; //"[unknown entity '" + (name || decnum || hexnum) + "']"; }); // Done as a special-case, last, so that it doesn't bugger up // doubly-escaped things. data = data.replace(/&(amp|#0*38|#x0*26);/g, "&"); profile.leaveFn("_decodeEntities"); return data; } var htmlInlineTags = { "A": true, "ABBR": true, "ACRONYM": true, "AREA": true, "B": true, "BASE": true, "BASEFONT": true, "BDO": true, "BIG": true, "BUTTON": true, "CITE": true, "CODE": true, "DEL": true, "DFN": true, "EM": true, "FONT": true, "I": true, "INS": true, "ISINDEX": true, "KBD": true, "LABEL": true, "LEGEND": true, "LINK": true, "MAP": true, "META": true, "NOSCRIPT": true, "OPTGROUP": true, "OPTION": true, "PARAM": true, "Q": true, "S": true, "SAMP": true, "SCRIPT": true, "SELECT": true, "SMALL": true, "SPAN": true, "STRIKE": true, "STRONG": true, "STYLE": true, "SUB": true, "SUP": true, "TEXTAREA": true, "TT": true, "U": true, "VAR": true, }; function _decodeRSSHTML(data) { profile.enterFn("", "_decodeRSSHTML"); // Decode XML into HTML... data = _decodeEntities(data); // Remove all tags. data = data.replace(/<\/?(\w+)[^>]*>/g, function (text, tag) { return tag.toUpperCase() in htmlInlineTags ? "" : " " }); // Decode HTML into text... data = _decodeEntities(data); // Remove all entities. //data = data.replace(/&[^;]+;/g, ""); data = data.replace(/\s+/g, " "); profile.leaveFn("_decodeRSSHTML"); return data; } function _decodeAtomText(element) { if (!element) return ""; var content = element.contents(); var type = element.attribute("type"); if (type && (type.value == "html")) { return _decodeRSSHTML(content); } return _decodeEntities(content); } function _decodeAtomDate(element) { var ary = element.contents().match(/^(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+)(?:.(\d+))?(Z|([+-])(\d+):(\d+))$/); if (ary) { var d = new Date(ary[1], ary[2] - 1, ary[3], ary[4], ary[5], ary[6]); // 8 = Z/zone // 9 = +/- // 10/11 = zone offset if (d.getTimezoneOffset() != 0) { d = new Date(Number(d) - d.getTimezoneOffset() * 60 * 1000); } if (ary[9] == "+") { d = new Date(Number(d) + ((ary[10] * 60) + ary[11]) * 60 * 1000); } if (ary[9] == "-") { d = new Date(Number(d) - ((ary[10] * 60) + ary[11]) * 60 * 1000); } return d; } return 0; } // Generic feed parser. function FeedParser(feedsOwner, data) { profile.enterFn("FeedParser", "init.replace"); data = data.replace(/[\r\n\s]+/, " "); profile.leaveFn("init.replace"); profile.enterFn("XMLParser", "new"); try { this._xmlData = new XMLParser(data); } finally { profile.leaveFn("new"); } this._parse(feedsOwner); } FeedParser.prototype.toString = function() { return "FeedParser<" + this.title + ">"; } FeedParser.prototype._parse = function(feedsOwner) { profile.enterFn("FeedParser", "_parse"); this.title = ""; this.link = ""; this.description = ""; this.language = ""; this.ttl = 0; this.items = new Array(); this.error = ""; var ATOM_1_0_NS = "http://www.w3.org/2005/Atom"; function getChildContents(elt, name, namespace) { profile.enterFn("FeedParser", "getChildContents"); var child = elt.childByName(name, namespace); if (child) { profile.leaveFn("getChildContents"); return child.contents(); } profile.leaveFn("getChildContents"); return ""; }; // Check what kind of feed we have! if (this._xmlData.rootElement.localName == "rss") { var rssVersion = this._xmlData.rootElement.attribute("version"); if (rssVersion && ((rssVersion.value == 0.91) || (rssVersion.value == 2.0))) { // RSS 0.91 or 2.0 code. var channel = this._xmlData.rootElement.childByName("channel"); this.title = getChildContents(channel, "title").trim(); this.link = getChildContents(channel, "link").trim(); this.description = getChildContents(channel, "description").trim(); this.language = getChildContents(channel, "language").trim(); this.ttl = getChildContents(channel, "ttl").trim(); var items = channel.childrenByName("item"); for (var i = 0; i < items.length; i++) { var item = items[i]; var pubDate = item.childByName("pubDate"); if (pubDate) { pubDate = pubDate.contents(); } else { pubDate = "?"; } var guid = item.childByName("guid") || ""; if (guid) { guid = guid.contents(); } var title = item.childByName("title") || ""; if (title) { title = title.contents(); } var link = item.childByName("link") || ""; if (link) { link = link.contents(); } var desc = item.childByName("description") || ""; if (desc) { desc = desc.contents(); } this.items.push({ date: pubDate.trim(), guid: guid.trim(), title: _decodeRSSHTML(title).trim(), link: _decodeEntities(link).trim(), desc: _decodeRSSHTML(desc).trim(), updated: false }); } } else { if (rssVersion) { profile.leaveFn("_parse"); throw new Error("Unsuported RSS version: " + rssVersion.value); } profile.leaveFn("_parse"); throw new Error("Unsuported RSS version: <unknown>"); } } else if (this._xmlData.rootElement.localName == "RDF") { // RSS 1.0 probably. if (this._xmlData.rootElement.namespace == "http://www.w3.org/1999/02/22-rdf-syntax-ns#") { var channel = this._xmlData.rootElement.childByName("channel", "http://purl.org/rss/1.0/"); this.title = getChildContents(channel, "title", "http://purl.org/rss/1.0/").trim(); this.link = getChildContents(channel, "link", "http://purl.org/rss/1.0/").trim(); this.description = getChildContents(channel, "description", "http://purl.org/rss/1.0/").trim(); this.language = getChildContents(channel, "language", "http://purl.org/rss/1.0/").trim(); this.ttl = getChildContents(channel, "ttl", "http://purl.org/rss/1.0/").trim(); var items = this._xmlData.rootElement.childrenByName("item", "http://purl.org/rss/1.0/"); for (var i = 0; i < items.length; i++) { var item = items[i]; var pubDate = item.childByName("pubDate", "http://purl.org/rss/1.0/"); if (pubDate) { pubDate = pubDate.contents(); } else { pubDate = "?"; } var title = item.childByName("title", "http://purl.org/rss/1.0/") || ""; if (title) { title = title.contents(); } var link = item.childByName("link", "http://purl.org/rss/1.0/") || ""; if (link) { link = link.contents(); } var desc = item.childByName("description", "http://purl.org/rss/1.0/") || ""; if (desc) { desc = desc.contents(); } this.items.push({ date: pubDate.trim(), title: _decodeRSSHTML(title).trim(), link: _decodeEntities(link).trim(), desc: _decodeRSSHTML(desc).trim(), updated: false }); } } else { profile.leaveFn("_parse"); throw new Error("Unsuported namespace: " + this._xmlData.rootElement.namespace); } } else if (this._xmlData.rootElement.is("feed", ATOM_1_0_NS)) { // Atom 1.0. // Text decoder: _decodeAtomText(element) // Date decoder: _decodeAtomDate(element); var feed = this._xmlData.rootElement; this.title = _decodeAtomText(feed.childByName("title", ATOM_1_0_NS)).trim(); var items = feed.childrenByName("entry", ATOM_1_0_NS); for (var i = 0; i < items.length; i++) { var item = items[i]; var date = _decodeAtomDate(item.childByName("updated", ATOM_1_0_NS)); var title = _decodeAtomText(item.childByName("title", ATOM_1_0_NS)); var link = item.childByName("link", ATOM_1_0_NS); if (link) { link = link.attribute("href"); if (link) { link = link.value; } } var desc = _decodeAtomText(item.childByName("content", ATOM_1_0_NS)); this.items.push({ date: date.trim(), title: title.trim(), link: link.trim(), desc: desc.trim(), updated: false }); } } else { profile.leaveFn("_parse"); throw new Error("Unsupported feed type: " + this._xmlData.rootElement); } if (feedsOwner && feedsOwner._debug_xml) { var limit = { value: 25 }; log("# URL : " + this.link); log("# TITLE : " + this.title); log("# DESCRIPTION: " + this.description); this._xmlData._dump(this._xmlData.root, "", limit); } profile.leaveFn("_parse"); } // #include JavaScriptXML.jsi // General XML parser, win! function XMLParser(data) { this.data = data; this.root = []; this._state = []; this._parse(); } XMLParser.prototype._dumpln = function(line, limit) { limit.value--; if (limit.value == 0) { dumpln("*** TRUNCATED ***"); } if (limit.value <= 0) { return; } dumpln(line); } XMLParser.prototype._dump = function(list, indent, limit) { profile.enterFn("XMLParser", "_dumpElement"); for (var i = 0; i < list.length; i++) { this._dumpElement(list[i], indent, limit); } profile.leaveFn("_dumpElement"); } XMLParser.prototype._dumpElement = function(elt, indent, limit) { profile.enterFn("XMLParser", "_dumpElement"); if (elt._content) { this._dumpln(indent + elt + elt._content + "</" + elt.name + ">", limit); } else if (elt._children && (elt._children.length > 0)) { this._dumpln(indent + elt, limit); this._dump(elt._children, indent + " ", limit); this._dumpln(indent + "</" + elt.name + ">", limit); } else { this._dumpln(indent + elt, limit); } profile.leaveFn("_dumpElement"); } XMLParser.prototype._parse = function() { profile.enterFn("XMLParser", "_parse"); // Hack off the Unicode DOM if it exists. if (this.data.substr(0, 3) == "\xEF\xBB\xBF") { this.data = this.data.substr(3); } // Process all entities here. this._processEntities(); // Head off for the <?xml PI. while (this.data.length > 0) { this._eatWhitespace(); if (this.data.substr(0, 4) == "<!--") { // Comment. this.root.push(this._eatComment()); } else if (this.data.substr(0, 2) == "<!") { // SGML element. this.root.push(this._eatSGMLElement()); } else if (this.data.substr(0, 2) == "<?") { var e = this._eatElement(null); if (e.name != "xml") { profile.leaveFn("_parse"); throw new Error("Expected <?xml?>, found <?" + e.name + "?>"); } this.xmlPI = e; this.root.push(e); break; } else { break; //profile.leaveFn("_parse"); //throw new Error("Expected <?xml?>, found " + this.data.substr(0, 10) + "..."); } } // OK, onto the root element... while (this.data.length > 0) { this._eatWhitespace(); if (this.data.substr(0, 4) == "<!--") { // Comment. this.root.push(this._eatComment()); } else if (this.data.substr(0, 2) == "<!") { // SGML element. this.root.push(this._eatSGMLElement()); } else if (this.data.substr(0, 2) == "<?") { var e = this._eatElement(null); this.root.push(e); } else if (this.data.substr(0, 1) == "<") { var e = this._eatElement(null); if (e.start == false) { profile.leaveFn("_parse"); throw new Error("Expected start element, found end element"); } this.rootElement = e; this.root.push(e); this._state.unshift(e); break; } else { profile.leaveFn("_parse"); throw new Error("Expected root element, found " + this.data.substr(0, 10) + "..."); } } // Now the contents. while (this.data.length > 0) { this._eatWhitespace(); if (this.data.substr(0, 4) == "<!--") { // Comment. this._state[0]._children.push(this._eatComment()); } else if (this.data.substr(0, 2) == "<!") { // SGML element. this._state[0]._children.push(this._eatSGMLElement()); } else if (this.data[0] == "<") { var e = this._eatElement(this._state[0]); if (e.empty) { this._state[0]._children.push(e); } else if (e.start) { this._state[0]._children.push(e); this._state.unshift(e); } else { if (e.name != this._state[0].name) { profile.leaveFn("_parse"); throw new Error("Expected </" + this._state[0].name + ">, found </" + e.name + ">"); } this._state.shift(); if (this._state.length == 0) { // We've ended the root element, that's it folks! break; } } } else { var pos = this.data.indexOf("<"); if (pos < 0) { this._state[0]._content = this.data; this.data = ""; } else { this._state[0]._content = this.data.substr(0, pos); this.data = this.data.substr(pos); } } } this._eatWhitespace(); if (this._state.length > 0) { profile.leaveFn("_parse"); throw new Error("Expected </" + this._state[0].name + ">, found EOF."); } if (this.data.length > 0) { profile.leaveFn("_parse"); throw new Error("Expected EOF, found " + this.data.substr(0, 10) + "..."); } profile.leaveFn("_parse"); } XMLParser.prototype._processEntities = function() {} XMLParser.prototype._processEntities_TODO = function(string) { profile.enterFn("XMLParser", "_processEntities"); var i = 0; while (i < string.length) { // Find next &... i = string.indexOf("&", i); //if (string.substr(i, 4) == "&lt;") { // this.data = string.substr(0, i - 1) + "<" + // Make sure we skip over the character we just inserted. i++; } profile.leaveFn("_processEntities"); return string; } XMLParser.prototype._eatWhitespace = function() { profile.enterFn("XMLParser", "_eatWhitespace"); var len = this._countWhitespace(); if (len > 0) { this.data = this.data.substr(len); } profile.leaveFn("_eatWhitespace"); } XMLParser.prototype._countWhitespace = function() { profile.enterFn("XMLParser", "_countWhitespace"); // Optimise by checking only first character first. if (this.data.length <= 0) { profile.leaveFn("_countWhitespace"); return 0; } var ws = this.data[0].match(/^\s+/); if (ws) { // Now check first 256 characters. ws = this.data.substr(0, 256).match(/^\s+/); if (ws[0].length == 256) { // Ok, check it all. ws = this.data.match(/^\s+/); profile.leaveFn("_countWhitespace"); return ws[0].length; } profile.leaveFn("_countWhitespace"); return ws[0].length; } profile.leaveFn("_countWhitespace"); return 0; } XMLParser.prototype._eatComment = function() { profile.enterFn("XMLParser", "_eatComment"); if (this.data.substr(0, 4) != "<!--") { profile.leaveFn("_eatComment"); throw new Error("Expected <!--, found " + this.data.substr(0, 10) + "..."); } var i = 4; while (i < this.data.length) { if (this.data.substr(i, 3) == "-->") { // Done. var c = new XMLComment(this.data.substr(4, i - 4)); this.data = this.data.substr(i + 3); profile.leaveFn("_eatComment"); return c; } i++; } profile.leaveFn("_eatComment"); throw new Error("Expected -->, found EOF."); } XMLParser.prototype._eatSGMLElement = function() { profile.enterFn("XMLParser", "_eatSGMLElement"); if (this.data.substr(0, 2) != "<!") { profile.leaveFn("_eatSGMLElement"); throw new Error("Expected <!, found " + this.data.substr(0, 10) + "..."); } // CDATA chunk? if (this.data.substr(0, 9) == "<![CDATA[") { profile.leaveFn("_eatSGMLElement"); return this._eatCDATAElement(); } var i = 2; var inQuote = ""; while (i < this.data.length) { if (inQuote == this.data[i]) { inQuote = ""; } else if ((this.data[i] == "'") || (this.data[i] == '"')) { inQuote = this.data[i]; } else if (this.data[i] == ">") { // Done. var c = new XMLComment(this.data.substr(2, i - 1)); this.data = this.data.substr(i + 1); profile.leaveFn("_eatSGMLElement"); return c; } i++; } profile.leaveFn("_eatSGMLElement"); throw new Error("Expected >, found EOF."); } XMLParser.prototype._eatCDATAElement = function() { profile.enterFn("XMLParser", "_eatCDATAElement"); if (this.data.substr(0, 9) != "<![CDATA[") { profile.leaveFn("_eatCDATAElement"); throw new Error("Expected <![CDATA[, found " + this.data.substr(0, 20) + "..."); } var i = 9; while (i < this.data.length) { if ((this.data[i] == "]") && (this.data.substr(i, 3) == "]]>")) { // Done. var e = new XMLCData(this.data.substr(9, i - 9)); this.data = this.data.substr(i + 3); profile.leaveFn("_eatCDATAElement"); return e; } i++; } profile.leaveFn("_eatCDATAElement"); throw new Error("Expected ]]>, found EOF."); } XMLParser.prototype._eatElement = function(parent) { profile.enterFn("XMLParser", "_eatElement"); if (this.data[0] != "<") { profile.leaveFn("_eatElement"); throw new Error("Expected <, found " + this.data.substr(0, 10) + "..."); } var whitespace = /\s/i; var e; var name = ""; var start = true; var pi = false; var i = 1; if (this.data[i] == "?") { pi = true; i++; } if (!pi && (this.data[i] == "/")) { start = false; i++; } while (i < this.data.length) { if (!pi && (this.data[i] == ">")) { e = new XMLElement(parent, name, start, pi, false); this.data = this.data.substr(i + 1); e.resolveNamespaces(); profile.leaveFn("_eatElement"); return e; } else if (start && (this.data.substr(i, 2) == "/>")) { e = new XMLElement(parent, name, start, pi, true); this.data = this.data.substr(i + 2); e.resolveNamespaces(); profile.leaveFn("_eatElement"); return e; } else if (pi && (this.data.substr(i, 2) == "?>")) { e = new XMLElement(parent, name, start, pi, false); this.data = this.data.substr(i + 2); e.resolveNamespaces(); profile.leaveFn("_eatElement"); return e; } else if (whitespace.test(this.data[i])) { // End of name. e = new XMLElement(parent, name, start, pi, false); i++; break; } else { name += this.data[i]; } i++; } // On to attributes. name = ""; var a = ""; var inName = false; var inEQ = false; var inVal = false; var inQuote = ""; while (i < this.data.length) { if (!pi && !inName && !inEQ && !inVal && (this.data[i] == ">")) { this.data = this.data.substr(i + 1); e.resolveNamespaces(); profile.leaveFn("_eatElement"); return e; } else if (!pi && !inName && !inEQ && !inVal && (this.data.substr(i, 2) == "/>")) { if (!e.start) { profile.leaveFn("_eatElement"); throw new Error("Invalid end tag, found " + this.data.substr(0, i + 10) + "..."); } e.empty = true; this.data = this.data.substr(i + 2); e.resolveNamespaces(); profile.leaveFn("_eatElement"); return e; } else if (pi && !inName && !inEQ && !inVal && (this.data.substr(i, 2) == "?>")) { this.data = this.data.substr(i + 2); e.resolveNamespaces(); profile.leaveFn("_eatElement"); return e; } else if (inName && (this.data[i] == "=")) { inName = false; inEQ = true; } else if (inEQ && ((this.data[i] == '"') || (this.data[i] == "'"))) { inEQ = false; inVal = true; inQuote = this.data[i]; } else if (inQuote && ((this.data[i] == '"') || (this.data[i] == "'"))) { if (inQuote == this.data[i]) { inQuote = ""; inVal = false; e._attributes.push(new XMLAttribute(e, name, a)); name = ""; a = ""; } } else if (whitespace.test(this.data[i])) { if (inVal && !inQuote) { inVal = false; e._attributes.push(new XMLAttribute(e, name, a)); name = ""; a = ""; } } else if (inEQ || inVal) { if (inEQ) { inEQ = false; inVal = true; a = ""; } a += this.data[i]; } else { if (!inName) { inName = true; } name += this.data[i]; } i++; } //this.data = this.data.substr(i); //e.resolveNamespaces(); profile.leaveFn("_eatElement"); //return e; throw new Error("Expected >, found EOF."); } function XMLElement(parent, name, start, pi, empty) { this.type = "XMLElement"; this.parent = parent; this.name = name; this.start = start; this.pi = pi; this.empty = empty; this.namespace = ""; var ary = this.name.match(/^(.*?):(.*)$/); if (ary) { this.prefix = ary[1]; this.localName = ary[2]; } else { this.prefix = null; this.localName = this.name; } this._attributes = []; this._content = ""; this._children = []; } XMLElement.prototype.toString = function() { profile.enterFn("XMLElement", "toString"); var str = "<"; if (this.pi) { str += "?"; } else if (!this.start) { str += "/"; } if (this.prefix != null) { str += this.prefix + ":"; } str += this.localName; if (this.namespace) { str += "[[" + this.namespace + "]]"; } for (var a in this._attributes) { str += " " + this._attributes[a]; } if (this.pi) { str += "?"; } if (this.empty || ((this._content == "") && (this._children.length == 0))) { str += "/"; } str += ">"; profile.leaveFn("toString"); return str; } XMLElement.prototype.resolveNamespaces = function() { profile.enterFn("XMLElement", "resolveNamespaces"); function getNameSpaceFromPrefix(base, pfx) { profile.enterFn("XMLElement", "resolveNamespaces.getNameSpaceFromPrefix"); var attrName = "xmlns"; if (pfx) { attrName = "xmlns:" + pfx; } var element = base; while (element) { var attr = element.attribute(attrName); if (attr) { profile.leaveFn("resolveNamespaces.getNameSpaceFromPrefix"); return attr.value; } element = element.parent; } profile.leaveFn("resolveNamespaces.getNameSpaceFromPrefix"); return ""; }; this.namespace = getNameSpaceFromPrefix(this, this.prefix); for (var i = 0; i < this._attributes.length; i++) { if (/^xmlns(?:$|:)/.test(this._attributes[i].name)) { continue; } this._attributes[i].namespace = getNameSpaceFromPrefix(this, this._attributes[i].prefix); } profile.leaveFn("resolveNamespaces"); } XMLElement.prototype.is = function(localName, namespace) { return (this.localName == localName) && (this.namespace == namespace); } XMLElement.prototype.contents = function() { profile.enterFn("XMLElement", "contents"); var str = this._content; if ((this._content == "") && (this._children.length > 0)) { str = ""; for (var i = 0; i < this._children.length; i++) { str += this._children[i].contents(); } } profile.leaveFn("contents"); return str; } XMLElement.prototype.attribute = function(name, namespace) { profile.enterFn("XMLElement", "attribute"); for (var i = 0; i < this._attributes.length; i++) { if ((typeof namespace != "undefined") && (this._attributes[i].namespace != namespace)) { continue; } if (this._attributes[i].name == name) { profile.leaveFn("attribute"); return this._attributes[i]; } } profile.leaveFn("attribute"); return null; } XMLElement.prototype.childrenByName = function(name, namespace) { profile.enterFn("XMLElement", "childrenByName"); var rv = []; for (var i = 0; i < this._children.length; i++) { if ((typeof namespace != "undefined") && (this._children[i].namespace != namespace)) { continue; } if (this._children[i].name == name) { rv.push(this._children[i]); } } profile.leaveFn("childrenByName"); return rv; } XMLElement.prototype.childByName = function(name, namespace) { profile.enterFn("XMLElement", "childByName"); var l = this.childrenByName(name); if (l.length != 1) { profile.leaveFn("childByName"); return null; } profile.leaveFn("childByName"); return l[0]; } function XMLAttribute(parent, name, value) { this.type = "XMLAttribute"; this.parent = parent; this.name = name; this.value = value; this.namespace = ""; var ary = this.name.match(/^(.*?):(.*)$/); if (ary) { this.prefix = ary[1]; this.localName = ary[2]; } else { this.prefix = null; this.localName = this.name; } } XMLAttribute.prototype.toString = function() { profile.enterFn("XMLAttribute", "toString"); var str = ""; if (this.prefix != null) { str += this.prefix + ":"; } str += this.localName; if (this.namespace) { str += "[[" + this.namespace + "]]"; } str += "='" + this.value + "'"; profile.leaveFn("toString"); return str; } function XMLCData(value) { this.type = "XMLCData"; this.value = value; } XMLCData.prototype.toString = function() { profile.enterFn("XMLCData", "toString"); var str = "<![CDATA[" + this.value + "]]>"; profile.leaveFn("toString"); return str; } XMLCData.prototype.contents = function() { return this.value; } function XMLComment(value) { this.type = "XMLComment"; this.value = value; } XMLComment.prototype.toString = function() { profile.enterFn("XMLComment", "toString"); var str = "<!" + this.value + ">"; profile.leaveFn("toString"); return str; } XMLComment.prototype.contents = function() { return this.toString(); } // #includeend function JSProfiler() { this.running = false; this.showRunningTrace = false; this._calls = 0; } JSProfiler.prototype.start = function() { if (this.running) { throw new Error("Can't start profiler when it is already running."); } this.running = true; this._calls = 0; this._functions = new Object(); this._stack = new Array(); this._lastJumpTime = Number(new Date()); if (this.showRunningTrace) { log("PROFILER: START"); } } JSProfiler.prototype.stop = function(title) { if (!this.running) { throw new Error("Can't stop profiler when it is not running."); } if (this.showRunningTrace) { log("PROFILER: STOP"); } this.running = false; if (this._calls == 0) { //log("No JSPRofiler profiled functions."); return; } function makeCol(val, width) { val = String(val); while (val.length < width) { val = " " + val; } return val; }; var keys = new Array(); for (var key in this._functions) { keys.push(key); } var self = this; keys.sort(function(a, b) { if (self._functions[a].totalTime < self._functions[b].totalTime) return 1; if (self._functions[a].totalTime > self._functions[b].totalTime) return -1; if (self._functions[a].callCount < self._functions[b].callCount) return 1; if (self._functions[a].callCount > self._functions[b].callCount) return -1; return 0; }); if (keys.length == 0) { return; } var shownHeaders = false; for (var i = 0; i < keys.length; i++) { var fn = this._functions[keys[i]]; // Always print if runTime >= 1000 or in top 3, but drop out for < 100ms anyway. //if (((fn.totalTime < 1000) && (i >= 3)) || (fn.totalTime < 100)) { if (fn.totalTime < 100) { break; } if (!shownHeaders) { log("JSProfiler Dump" + (title ? " for " + title : "") + ":"); log(" Calls Actual (ms) Nested (ms) Class/Name"); shownHeaders = true; } log(" " + makeCol(fn.callCount, 6) + makeCol(fn.runTime, 13) + makeCol(fn.totalTime, 13) + " " + keys[i]); } } JSProfiler.prototype.enterFn = function(cls, name) { var key = (cls ? cls + "." : "") + name; if (!(key in this._functions)) { this._functions[key] = { cls: cls, name: name, callCount: 0, totalTime: 0, runTime: 0 }; } if (this.showRunningTrace) { var nest = ""; for (var i = 0; i < this._stack.length; i++) { nest += " "; } log("PROFILER: " + nest + (cls ? "<" + cls + ">" : "") + name + " {"); } var now = Number(new Date()); if (this._stack.length > 0) { this._functions[this._stack[this._stack.length - 1].key].runTime += now - this._lastJumpTime; } this._calls++; this._functions[key].callCount++; this._stack.push({ key: key, name: name, start: now }); this._lastJumpTime = now; } JSProfiler.prototype.leaveFn = function(name) { if (this.showRunningTrace) { var nest = ""; for (var i = 1; i < this._stack.length; i++) { nest += " "; } log("PROFILER: " + nest + "} // " + name); } var now = Number(new Date()); var items = new Array(); for (var i = this._stack.length - 1; i >= 0; i--) { if (this._stack[i].name == name) { this._functions[this._stack[i].key].runTime += now - this._lastJumpTime; this._functions[this._stack[i].key].totalTime += now - this._stack[i].start; if (i != this._stack.length - 1) { log("WARNING: leaving function '" + name + "' skipping " + (this._stack.length - 1 - i) + " stack items (" + items.join(", ") + ")!"); } this._stack.splice(i); this._lastJumpTime = now; return; } items.push(this._stack[i].key); } log("WARNING: leaving function '" + name + "' we never entered!"); this._lastJumpTime = now; } var profile = new JSProfiler();
Bug fix for Atom feeds without a link and date trim.
contrib/Feeds.js
Bug fix for Atom feeds without a link and date trim.
<ide><path>ontrib/Feeds.js <ide> "Generic feed reader with notification.", <ide> "James Ross", <ide> "[email protected]", <del> "1.6.3" <add> "1.6.4" <ide> ]; <ide> <ide> <ide> if (ary[9] == "-") { <ide> d = new Date(Number(d) - ((ary[10] * 60) + ary[11]) * 60 * 1000); <ide> } <del> return d; <del> } <del> return 0; <add> return String(d); <add> } <add> return "?"; <ide> } <ide> <ide> <ide> link = link.attribute("href"); <ide> if (link) { <ide> link = link.value; <add> } else { <add> link = ""; <ide> } <add> } else { <add> link = ""; <ide> } <ide> <ide> var desc = _decodeAtomText(item.childByName("content", ATOM_1_0_NS));
Java
mit
b3150501e418b2005f1661141a235a8ad5fd8e7e
0
aibax/cryptography-samples
package jp.aibax.rsa; import static javax.crypto.Cipher.DECRYPT_MODE; import static javax.crypto.Cipher.ENCRYPT_MODE; import java.io.File; import java.io.IOException; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import org.apache.commons.io.FileUtils; public class RSA { public KeyPair generateKeyPair(int keysize) { try { KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); SecureRandom random = SecureRandom.getInstanceStrong(); // 利用可能な最も安全な乱数生成のアルゴリズムを使用 generator.initialize(keysize, random); return generator.generateKeyPair(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public PublicKey loadPublicKeyFromFile(File publicKeyFile) throws IOException { PublicKey publicKey = null; try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); byte[] publicKeyBytes = FileUtils.readFileToByteArray(publicKeyFile); KeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes); publicKey = keyFactory.generatePublic(publicKeySpec); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw new RuntimeException(e); } return publicKey; } public PrivateKey loadPrivateKeyFromFile(File privateKeyFile) throws IOException { PrivateKey privateKey = null; try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); byte[] privateKeyBytes = FileUtils.readFileToByteArray(privateKeyFile); KeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes); privateKey = keyFactory.generatePrivate(privateKeySpec); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw new RuntimeException(e); } return privateKey; } public KeyPair loadKeyPairFromFile(File publicKeyFile, File privateKeyFile) throws IOException { PublicKey publicKey = loadPublicKeyFromFile(publicKeyFile); PrivateKey privateKey = loadPrivateKeyFromFile(privateKeyFile); return new KeyPair(publicKey, privateKey); } public byte[] encrypt(byte[] cleartext, PublicKey publicKey) { byte[] encrypted = null; try { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(ENCRYPT_MODE, publicKey); encrypted = cipher.doFinal(cleartext); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { throw new RuntimeException(e); } return encrypted; } public byte[] encrypt(byte[] cleartext, PrivateKey privateKey) { byte[] encrypted = null; try { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(ENCRYPT_MODE, privateKey); encrypted = cipher.doFinal(cleartext); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { throw new RuntimeException(e); } return encrypted; } public byte[] decrypt(byte[] encrypted, PrivateKey privateKey) { byte[] decrypted = null; try { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(DECRYPT_MODE, privateKey); decrypted = cipher.doFinal(encrypted); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { throw new RuntimeException(e); } return decrypted; } public byte[] decrypt(byte[] encrypted, PublicKey publicKey) { byte[] decrypted = null; try { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(DECRYPT_MODE, publicKey); decrypted = cipher.doFinal(encrypted); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { throw new RuntimeException(e); } return decrypted; } }
src/main/java/jp/aibax/rsa/RSA.java
package jp.aibax.rsa; import static javax.crypto.Cipher.DECRYPT_MODE; import static javax.crypto.Cipher.ENCRYPT_MODE; import java.io.File; import java.io.IOException; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import org.apache.commons.io.FileUtils; public class RSA { public KeyPair generateKeyPair(int keysize) { try { KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); SecureRandom random = SecureRandom.getInstanceStrong(); // 利用可能な最も安全な乱数生成のアルゴリズムを使用 generator.initialize(keysize, random); return generator.generateKeyPair(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public KeyPair loadKeyPairFromFile(File publicKeyFile, File privateKeyFile) throws IOException { KeyPair keyPair = null; try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); byte[] publicKeyBytes = FileUtils.readFileToByteArray(publicKeyFile); KeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes); PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); byte[] privateKeyBytes = FileUtils.readFileToByteArray(privateKeyFile); KeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes); PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); keyPair = new KeyPair(publicKey, privateKey); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw new RuntimeException(e); } return keyPair; } public byte[] encrypt(byte[] cleartext, PublicKey publicKey) { byte[] encrypted = null; try { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(ENCRYPT_MODE, publicKey); encrypted = cipher.doFinal(cleartext); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { throw new RuntimeException(e); } return encrypted; } public byte[] encrypt(byte[] cleartext, PrivateKey privateKey) { byte[] encrypted = null; try { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(ENCRYPT_MODE, privateKey); encrypted = cipher.doFinal(cleartext); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { throw new RuntimeException(e); } return encrypted; } public byte[] decrypt(byte[] encrypted, PrivateKey privateKey) { byte[] decrypted = null; try { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(DECRYPT_MODE, privateKey); decrypted = cipher.doFinal(encrypted); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { throw new RuntimeException(e); } return decrypted; } public byte[] decrypt(byte[] encrypted, PublicKey publicKey) { byte[] decrypted = null; try { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(DECRYPT_MODE, publicKey); decrypted = cipher.doFinal(encrypted); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { throw new RuntimeException(e); } return decrypted; } }
公開鍵と秘密鍵をそれぞれ個別で読み込めるように変更
src/main/java/jp/aibax/rsa/RSA.java
公開鍵と秘密鍵をそれぞれ個別で読み込めるように変更
<ide><path>rc/main/java/jp/aibax/rsa/RSA.java <ide> } <ide> } <ide> <del> public KeyPair loadKeyPairFromFile(File publicKeyFile, File privateKeyFile) throws IOException <add> public PublicKey loadPublicKeyFromFile(File publicKeyFile) throws IOException <ide> { <del> KeyPair keyPair = null; <add> PublicKey publicKey = null; <ide> <ide> try <ide> { <ide> <ide> byte[] publicKeyBytes = FileUtils.readFileToByteArray(publicKeyFile); <ide> KeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes); <del> PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); <del> <del> byte[] privateKeyBytes = FileUtils.readFileToByteArray(privateKeyFile); <del> KeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes); <del> PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); <del> <del> keyPair = new KeyPair(publicKey, privateKey); <add> publicKey = keyFactory.generatePublic(publicKeySpec); <ide> } <ide> catch (NoSuchAlgorithmException | InvalidKeySpecException e) <ide> { <ide> throw new RuntimeException(e); <ide> } <ide> <del> return keyPair; <add> return publicKey; <add> } <add> <add> public PrivateKey loadPrivateKeyFromFile(File privateKeyFile) throws IOException <add> { <add> PrivateKey privateKey = null; <add> <add> try <add> { <add> KeyFactory keyFactory = KeyFactory.getInstance("RSA"); <add> <add> byte[] privateKeyBytes = FileUtils.readFileToByteArray(privateKeyFile); <add> KeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes); <add> privateKey = keyFactory.generatePrivate(privateKeySpec); <add> } <add> catch (NoSuchAlgorithmException | InvalidKeySpecException e) <add> { <add> throw new RuntimeException(e); <add> } <add> <add> return privateKey; <add> } <add> <add> public KeyPair loadKeyPairFromFile(File publicKeyFile, File privateKeyFile) throws IOException <add> { <add> PublicKey publicKey = loadPublicKeyFromFile(publicKeyFile); <add> PrivateKey privateKey = loadPrivateKeyFromFile(privateKeyFile); <add> return new KeyPair(publicKey, privateKey); <ide> } <ide> <ide> public byte[] encrypt(byte[] cleartext, PublicKey publicKey)
Java
bsd-3-clause
03c27a18d2f262a28b24264995f3330e12a33e12
0
asamgir/openspecimen,asamgir/openspecimen,krishagni/openspecimen,asamgir/openspecimen,krishagni/openspecimen,krishagni/openspecimen
/** * */ package edu.wustl.catissuecore.util; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import edu.wustl.catissuecore.TaskTimeCalculater; import edu.wustl.catissuecore.bizlogic.CollectionProtocolBizLogic; import edu.wustl.catissuecore.domain.CollectionProtocol; import edu.wustl.catissuecore.domain.Site; import edu.wustl.catissuecore.domain.User; import edu.wustl.catissuecore.multiRepository.bean.SiteUserRolePrivilegeBean; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.catissuecore.util.global.Utility; import edu.wustl.common.beans.NameValueBean; import edu.wustl.common.beans.SecurityDataBean; import edu.wustl.common.dao.DAO; import edu.wustl.common.domain.AbstractDomainObject; import edu.wustl.common.security.PrivilegeManager; import edu.wustl.common.security.SecurityManager; import edu.wustl.common.security.exceptions.SMException; import edu.wustl.common.util.Roles; import edu.wustl.common.util.dbManager.DAOException; import edu.wustl.common.util.logger.Logger; import gov.nih.nci.security.exceptions.CSException; /** * @author supriya_dankh * */ public class CollectionProtocolAuthorization implements edu.wustl.catissuecore.util.Roles { public void authenticate(CollectionProtocol collectionProtocol, HashSet protectionObjects, Map<String,SiteUserRolePrivilegeBean> rowIdMap) throws DAOException { TaskTimeCalculater cpAuth = TaskTimeCalculater.startTask("CP insert Authenticatge", CollectionProtocolBizLogic.class); try { PrivilegeManager privilegeManager = PrivilegeManager.getInstance(); privilegeManager.insertAuthorizationData( getAuthorizationData(collectionProtocol, rowIdMap), protectionObjects, getDynamicGroups(collectionProtocol), collectionProtocol.getObjectId()); } catch (SMException e) { throw new DAOException(e); } catch (CSException e) { throw new DAOException(e); } finally { TaskTimeCalculater.endTask(cpAuth); } } /** * This method returns collection of UserGroupRoleProtectionGroup objects that speciefies the * user group protection group linkage through a role. It also specifies the groups the protection * elements returned by this class should be added to. * @return * @throws CSException */ protected Vector<SecurityDataBean> getAuthorizationData(AbstractDomainObject obj, Map<String,SiteUserRolePrivilegeBean> rowIdMap) throws SMException, CSException { Vector<SecurityDataBean> authorizationData = new Vector<SecurityDataBean>(); CollectionProtocol collectionProtocol = (CollectionProtocol) obj; inserPIPrivileges(collectionProtocol, authorizationData); insertCoordinatorPrivileges(collectionProtocol, authorizationData); if(rowIdMap !=null) { insertCpUserPrivilegs(collectionProtocol, authorizationData, rowIdMap); } return authorizationData; } public void insertCpUserPrivilegs(CollectionProtocol collectionProtocol, Vector<SecurityDataBean> authorizationData, Map<String,SiteUserRolePrivilegeBean> rowIdMap) throws SMException, CSException { int noOfUsers = rowIdMap.size(); Set<Site> siteCollection = new HashSet<Site>(); Set<User> userCollection = new HashSet<User>(); String roleName = ""; for (Iterator<String> mapItr = rowIdMap.keySet().iterator(); mapItr.hasNext(); ) { String key = mapItr.next(); SiteUserRolePrivilegeBean siteUserRolePrivilegeBean = rowIdMap.get(key); User user = siteUserRolePrivilegeBean.getUser(); if(siteUserRolePrivilegeBean.isRowDeleted()) { Utility.processDeletedPrivilegesOnCPPage(siteUserRolePrivilegeBean, collectionProtocol.getId()); } else if(siteUserRolePrivilegeBean.isRowEdited()) { // siteCollection.addAll(siteList); // user = siteUserRolePrivilegeBean.getUser(); // userCollection.add(user); String defaultRole = siteUserRolePrivilegeBean.getRole().getValue(); if (defaultRole != null && (defaultRole.equalsIgnoreCase("-1") || defaultRole.equalsIgnoreCase("0")) ) { roleName = Constants.getCPRoleName(collectionProtocol.getId(), user.getCsmUserId(), defaultRole); } else { roleName = siteUserRolePrivilegeBean.getRole().getName(); } Set<String> privileges = new HashSet<String>(); List<NameValueBean> privilegeList = siteUserRolePrivilegeBean.getPrivileges(); for(NameValueBean privilege : privilegeList) { privileges.add(privilege.getValue()); } PrivilegeManager.getInstance().createRole(roleName, privileges); String userId = String.valueOf(user.getCsmUserId()); gov.nih.nci.security.authorization.domainobjects.User csmUser = getUserByID(userId); HashSet<gov.nih.nci.security.authorization.domainobjects.User> group = new HashSet<gov.nih.nci.security.authorization.domainobjects.User>(); group.add(csmUser); String protectionGroupName = new String(Constants .getCollectionProtocolPGName(collectionProtocol.getId())); SecurityDataBean userGroupRoleProtectionGroupBean = new SecurityDataBean(); userGroupRoleProtectionGroupBean.setUser(""); userGroupRoleProtectionGroupBean.setRoleName(roleName); userGroupRoleProtectionGroupBean.setGroupName(Constants.getCPUserGroupName(collectionProtocol.getId(), user.getCsmUserId())); userGroupRoleProtectionGroupBean.setProtectionGroupName(protectionGroupName); userGroupRoleProtectionGroupBean.setGroup(group); authorizationData.add(userGroupRoleProtectionGroupBean); } if(!siteUserRolePrivilegeBean.isRowDeleted()) { userCollection.add(user); List<Site> siteList = siteUserRolePrivilegeBean.getSiteList(); for (Site site : siteList) { boolean isPresent = false; for (Site setSite : siteCollection) { if (setSite.getId().equals(site.getId())) { isPresent = true; } } if (!isPresent) { siteCollection.add(site); } } } } collectionProtocol.getSiteCollection().clear(); collectionProtocol.getSiteCollection().addAll(siteCollection); for (User user : userCollection) { boolean isPresent = false; for (User setUser : collectionProtocol.getAssignedProtocolUserCollection()) { if (user.getId().equals(setUser.getId())) { isPresent = true; } } if (!isPresent) { collectionProtocol.getAssignedProtocolUserCollection().add(user); } } } /** * @param siteCollection * @param siteList */ private Set<Site> getSiteCollection(List<Long> siteList) { Set<Site> siteCollection = new HashSet<Site>(); for (Long siteId : siteList) { Site site = new Site(); site.setId(siteId); siteCollection.add(site); } return siteCollection; } protected void insertCoordinatorPrivileges(CollectionProtocol collectionProtocol, Vector<SecurityDataBean> authorizationData) throws SMException { Collection<User> coordinators = collectionProtocol.getCoordinatorCollection(); HashSet<gov.nih.nci.security.authorization.domainobjects.User> group = new HashSet<gov.nih.nci.security.authorization.domainobjects.User>(); String userId = ""; for (Iterator<User> it = coordinators.iterator(); it.hasNext();) { User aUser = it.next(); userId = String.valueOf(aUser.getCsmUserId()); gov.nih.nci.security.authorization.domainobjects.User user = getUserByID(userId); group.add(user); } String protectionGroupName = new String(Constants .getCollectionProtocolPGName(collectionProtocol.getId())); SecurityDataBean userGroupRoleProtectionGroupBean = new SecurityDataBean(); userGroupRoleProtectionGroupBean.setUser(userId); userGroupRoleProtectionGroupBean.setRoleName(COORDINATOR); userGroupRoleProtectionGroupBean.setGroupName(Constants .getCollectionProtocolCoordinatorGroupName(collectionProtocol.getId())); userGroupRoleProtectionGroupBean.setProtectionGroupName(protectionGroupName); userGroupRoleProtectionGroupBean.setGroup(group); authorizationData.add(userGroupRoleProtectionGroupBean); } private void inserPIPrivileges(CollectionProtocol collectionProtocol, Vector<SecurityDataBean> authorizationData) throws SMException { HashSet<gov.nih.nci.security.authorization.domainobjects.User> group = new HashSet<gov.nih.nci.security.authorization.domainobjects.User>(); String userId = String .valueOf(collectionProtocol.getPrincipalInvestigator().getCsmUserId()); gov.nih.nci.security.authorization.domainobjects.User user = getUserByID(userId); group.add(user); String protectionGroupName = new String(Constants .getCollectionProtocolPGName(collectionProtocol.getId())); SecurityDataBean userGroupRoleProtectionGroupBean = new SecurityDataBean(); userGroupRoleProtectionGroupBean.setUser(userId); userGroupRoleProtectionGroupBean.setRoleName(PI); userGroupRoleProtectionGroupBean.setGroupName(Constants .getCollectionProtocolPIGroupName(collectionProtocol.getId())); userGroupRoleProtectionGroupBean.setProtectionGroupName(protectionGroupName); userGroupRoleProtectionGroupBean.setGroup(group); authorizationData.add(userGroupRoleProtectionGroupBean); } private String[] getDynamicGroups(AbstractDomainObject obj) { String[] dynamicGroups = null; return dynamicGroups; } /** * @param userId * @return * @throws SMException */ private gov.nih.nci.security.authorization.domainobjects.User getUserByID(String userId) throws SMException { gov.nih.nci.security.authorization.domainobjects.User user = SecurityManager.getInstance( this.getClass()).getUserById(userId); return user; } //not required /** * @param collectionProtocol * @return * @throws DAOException */ public Long getCSMUserId(DAO dao, User user) throws DAOException { String[] selectColumnNames = {Constants.CSM_USER_ID}; String[] whereColumnNames = {Constants.SYSTEM_IDENTIFIER}; String[] whereColumnCondition = {"="}; Long[] whereColumnValues = {user.getId()}; List csmUserIdList = dao.retrieve(User.class.getName(), selectColumnNames, whereColumnNames, whereColumnCondition, whereColumnValues, Constants.AND_JOIN_CONDITION); if (csmUserIdList.isEmpty() == false) { Long csmUserId = (Long) csmUserIdList.get(0); return csmUserId; } return null; } public boolean hasCoordinator(User coordinator, CollectionProtocol collectionProtocol) { Iterator<User> it = collectionProtocol.getCoordinatorCollection().iterator(); while (it.hasNext()) { User coordinatorOld = it.next(); if (coordinator.getId().equals(coordinatorOld.getId())) { return true; } } return false; } public void updatePIAndCoordinatorGroup(DAO dao, CollectionProtocol collectionProtocol, boolean operation) throws SMException, DAOException { Long principalInvestigatorId = collectionProtocol.getPrincipalInvestigator().getCsmUserId(); String userGroupName = Constants.getCollectionProtocolPIGroupName(collectionProtocol .getId()); if (operation) { SecurityManager.getInstance(CollectionProtocolBizLogic.class).removeUserFromGroup( userGroupName, principalInvestigatorId.toString()); } else { SecurityManager.getInstance(CollectionProtocolBizLogic.class).assignUserToGroup( userGroupName, principalInvestigatorId.toString()); } userGroupName = Constants.getCollectionProtocolCoordinatorGroupName(collectionProtocol .getId()); Iterator<User> iterator = collectionProtocol.getCoordinatorCollection().iterator(); while (iterator.hasNext()) { User user = iterator.next(); if (operation) { SecurityManager.getInstance(CollectionProtocolBizLogic.class).removeUserFromGroup( userGroupName, user.getCsmUserId().toString()); } else { Long csmUserId = getCSMUserId(dao, user); if (csmUserId != null) { SecurityManager.getInstance(CollectionProtocolBizLogic.class) .assignUserToGroup(userGroupName, csmUserId.toString()); } } } } }
WEB-INF/src/edu/wustl/catissuecore/util/CollectionProtocolAuthorization.java
/** * */ package edu.wustl.catissuecore.util; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import edu.wustl.catissuecore.TaskTimeCalculater; import edu.wustl.catissuecore.bizlogic.CollectionProtocolBizLogic; import edu.wustl.catissuecore.domain.CollectionProtocol; import edu.wustl.catissuecore.domain.Site; import edu.wustl.catissuecore.domain.User; import edu.wustl.catissuecore.multiRepository.bean.SiteUserRolePrivilegeBean; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.catissuecore.util.global.Utility; import edu.wustl.common.beans.NameValueBean; import edu.wustl.common.beans.SecurityDataBean; import edu.wustl.common.dao.DAO; import edu.wustl.common.domain.AbstractDomainObject; import edu.wustl.common.security.PrivilegeManager; import edu.wustl.common.security.SecurityManager; import edu.wustl.common.security.exceptions.SMException; import edu.wustl.common.util.Roles; import edu.wustl.common.util.dbManager.DAOException; import edu.wustl.common.util.logger.Logger; import gov.nih.nci.security.exceptions.CSException; /** * @author supriya_dankh * */ public class CollectionProtocolAuthorization implements edu.wustl.catissuecore.util.Roles { public void authenticate(CollectionProtocol collectionProtocol, HashSet protectionObjects, Map<String,SiteUserRolePrivilegeBean> rowIdMap) throws DAOException { TaskTimeCalculater cpAuth = TaskTimeCalculater.startTask("CP insert Authenticatge", CollectionProtocolBizLogic.class); try { PrivilegeManager privilegeManager = PrivilegeManager.getInstance(); privilegeManager.insertAuthorizationData( getAuthorizationData(collectionProtocol, rowIdMap), protectionObjects, getDynamicGroups(collectionProtocol), collectionProtocol.getObjectId()); } catch (SMException e) { throw new DAOException(e); } catch (CSException e) { throw new DAOException(e); } finally { TaskTimeCalculater.endTask(cpAuth); } } /** * This method returns collection of UserGroupRoleProtectionGroup objects that speciefies the * user group protection group linkage through a role. It also specifies the groups the protection * elements returned by this class should be added to. * @return * @throws CSException */ protected Vector<SecurityDataBean> getAuthorizationData(AbstractDomainObject obj, Map<String,SiteUserRolePrivilegeBean> rowIdMap) throws SMException, CSException { Vector<SecurityDataBean> authorizationData = new Vector<SecurityDataBean>(); CollectionProtocol collectionProtocol = (CollectionProtocol) obj; inserPIPrivileges(collectionProtocol, authorizationData); insertCoordinatorPrivileges(collectionProtocol, authorizationData); if(rowIdMap !=null) { insertCpUserPrivilegs(collectionProtocol, authorizationData, rowIdMap); } return authorizationData; } public void insertCpUserPrivilegs(CollectionProtocol collectionProtocol, Vector<SecurityDataBean> authorizationData, Map<String,SiteUserRolePrivilegeBean> rowIdMap) throws SMException, CSException { int noOfUsers = rowIdMap.size(); Set<Site> siteCollection = new HashSet<Site>(); Set<User> userCollection = new HashSet<User>(); String roleName = ""; for (Iterator<String> mapItr = rowIdMap.keySet().iterator(); mapItr.hasNext(); ) { String key = mapItr.next(); SiteUserRolePrivilegeBean siteUserRolePrivilegeBean = rowIdMap.get(key); User user = null; if(siteUserRolePrivilegeBean.isRowDeleted()) { Utility.processDeletedPrivilegesOnCPPage(siteUserRolePrivilegeBean, collectionProtocol.getId()); } else if(siteUserRolePrivilegeBean.isRowEdited()) { //siteCollection.addAll(siteList); user = siteUserRolePrivilegeBean.getUser(); // userCollection.add(user); String defaultRole = siteUserRolePrivilegeBean.getRole().getValue(); if (defaultRole != null && (defaultRole.equalsIgnoreCase("-1") || defaultRole.equalsIgnoreCase("0")) ) { roleName = Constants.getCPRoleName(collectionProtocol.getId(), user.getCsmUserId(), defaultRole); } else { roleName = siteUserRolePrivilegeBean.getRole().getName(); } Set<String> privileges = new HashSet<String>(); List<NameValueBean> privilegeList = siteUserRolePrivilegeBean.getPrivileges(); for(NameValueBean privilege : privilegeList) { privileges.add(privilege.getValue()); } PrivilegeManager.getInstance().createRole(roleName, privileges); String userId = String.valueOf(user.getCsmUserId()); gov.nih.nci.security.authorization.domainobjects.User csmUser = getUserByID(userId); HashSet<gov.nih.nci.security.authorization.domainobjects.User> group = new HashSet<gov.nih.nci.security.authorization.domainobjects.User>(); group.add(csmUser); String protectionGroupName = new String(Constants .getCollectionProtocolPGName(collectionProtocol.getId())); SecurityDataBean userGroupRoleProtectionGroupBean = new SecurityDataBean(); userGroupRoleProtectionGroupBean.setUser(""); userGroupRoleProtectionGroupBean.setRoleName(roleName); userGroupRoleProtectionGroupBean.setGroupName(Constants.getCPUserGroupName(collectionProtocol.getId(), user.getCsmUserId())); userGroupRoleProtectionGroupBean.setProtectionGroupName(protectionGroupName); userGroupRoleProtectionGroupBean.setGroup(group); authorizationData.add(userGroupRoleProtectionGroupBean); } if(!siteUserRolePrivilegeBean.isRowDeleted()) { userCollection.add(user); List<Site> siteList = siteUserRolePrivilegeBean.getSiteList(); for (Site site : siteList) { boolean isPresent = false; for (Site setSite : siteCollection) { if (setSite.getId().equals(site.getId())) { isPresent = true; } } if (!isPresent) { siteCollection.add(site); } } } } collectionProtocol.getSiteCollection().clear(); collectionProtocol.getSiteCollection().addAll(siteCollection); for (User user : userCollection) { boolean isPresent = false; for (User setUser : collectionProtocol.getAssignedProtocolUserCollection()) { if (user.getId().equals(setUser.getId())) { isPresent = true; } } if (!isPresent) { collectionProtocol.getAssignedProtocolUserCollection().add(user); } } } /** * @param siteCollection * @param siteList */ private Set<Site> getSiteCollection(List<Long> siteList) { Set<Site> siteCollection = new HashSet<Site>(); for (Long siteId : siteList) { Site site = new Site(); site.setId(siteId); siteCollection.add(site); } return siteCollection; } protected void insertCoordinatorPrivileges(CollectionProtocol collectionProtocol, Vector<SecurityDataBean> authorizationData) throws SMException { Collection<User> coordinators = collectionProtocol.getCoordinatorCollection(); HashSet<gov.nih.nci.security.authorization.domainobjects.User> group = new HashSet<gov.nih.nci.security.authorization.domainobjects.User>(); String userId = ""; for (Iterator<User> it = coordinators.iterator(); it.hasNext();) { User aUser = it.next(); userId = String.valueOf(aUser.getCsmUserId()); gov.nih.nci.security.authorization.domainobjects.User user = getUserByID(userId); group.add(user); } String protectionGroupName = new String(Constants .getCollectionProtocolPGName(collectionProtocol.getId())); SecurityDataBean userGroupRoleProtectionGroupBean = new SecurityDataBean(); userGroupRoleProtectionGroupBean.setUser(userId); userGroupRoleProtectionGroupBean.setRoleName(COORDINATOR); userGroupRoleProtectionGroupBean.setGroupName(Constants .getCollectionProtocolCoordinatorGroupName(collectionProtocol.getId())); userGroupRoleProtectionGroupBean.setProtectionGroupName(protectionGroupName); userGroupRoleProtectionGroupBean.setGroup(group); authorizationData.add(userGroupRoleProtectionGroupBean); } private void inserPIPrivileges(CollectionProtocol collectionProtocol, Vector<SecurityDataBean> authorizationData) throws SMException { HashSet<gov.nih.nci.security.authorization.domainobjects.User> group = new HashSet<gov.nih.nci.security.authorization.domainobjects.User>(); String userId = String .valueOf(collectionProtocol.getPrincipalInvestigator().getCsmUserId()); gov.nih.nci.security.authorization.domainobjects.User user = getUserByID(userId); group.add(user); String protectionGroupName = new String(Constants .getCollectionProtocolPGName(collectionProtocol.getId())); SecurityDataBean userGroupRoleProtectionGroupBean = new SecurityDataBean(); userGroupRoleProtectionGroupBean.setUser(userId); userGroupRoleProtectionGroupBean.setRoleName(PI); userGroupRoleProtectionGroupBean.setGroupName(Constants .getCollectionProtocolPIGroupName(collectionProtocol.getId())); userGroupRoleProtectionGroupBean.setProtectionGroupName(protectionGroupName); userGroupRoleProtectionGroupBean.setGroup(group); authorizationData.add(userGroupRoleProtectionGroupBean); } private String[] getDynamicGroups(AbstractDomainObject obj) { String[] dynamicGroups = null; return dynamicGroups; } /** * @param userId * @return * @throws SMException */ private gov.nih.nci.security.authorization.domainobjects.User getUserByID(String userId) throws SMException { gov.nih.nci.security.authorization.domainobjects.User user = SecurityManager.getInstance( this.getClass()).getUserById(userId); return user; } //not required /** * @param collectionProtocol * @return * @throws DAOException */ public Long getCSMUserId(DAO dao, User user) throws DAOException { String[] selectColumnNames = {Constants.CSM_USER_ID}; String[] whereColumnNames = {Constants.SYSTEM_IDENTIFIER}; String[] whereColumnCondition = {"="}; Long[] whereColumnValues = {user.getId()}; List csmUserIdList = dao.retrieve(User.class.getName(), selectColumnNames, whereColumnNames, whereColumnCondition, whereColumnValues, Constants.AND_JOIN_CONDITION); if (csmUserIdList.isEmpty() == false) { Long csmUserId = (Long) csmUserIdList.get(0); return csmUserId; } return null; } public boolean hasCoordinator(User coordinator, CollectionProtocol collectionProtocol) { Iterator<User> it = collectionProtocol.getCoordinatorCollection().iterator(); while (it.hasNext()) { User coordinatorOld = it.next(); if (coordinator.getId().equals(coordinatorOld.getId())) { return true; } } return false; } public void updatePIAndCoordinatorGroup(DAO dao, CollectionProtocol collectionProtocol, boolean operation) throws SMException, DAOException { Long principalInvestigatorId = collectionProtocol.getPrincipalInvestigator().getCsmUserId(); String userGroupName = Constants.getCollectionProtocolPIGroupName(collectionProtocol .getId()); if (operation) { SecurityManager.getInstance(CollectionProtocolBizLogic.class).removeUserFromGroup( userGroupName, principalInvestigatorId.toString()); } else { SecurityManager.getInstance(CollectionProtocolBizLogic.class).assignUserToGroup( userGroupName, principalInvestigatorId.toString()); } userGroupName = Constants.getCollectionProtocolCoordinatorGroupName(collectionProtocol .getId()); Iterator<User> iterator = collectionProtocol.getCoordinatorCollection().iterator(); while (iterator.hasNext()) { User user = iterator.next(); if (operation) { SecurityManager.getInstance(CollectionProtocolBizLogic.class).removeUserFromGroup( userGroupName, user.getCsmUserId().toString()); } else { Long csmUserId = getCSMUserId(dao, user); if (csmUserId != null) { SecurityManager.getInstance(CollectionProtocolBizLogic.class) .assignUserToGroup(userGroupName, csmUserId.toString()); } } } } }
MSR changes for S6 SVN-Revision: 14807
WEB-INF/src/edu/wustl/catissuecore/util/CollectionProtocolAuthorization.java
MSR changes for S6
<ide><path>EB-INF/src/edu/wustl/catissuecore/util/CollectionProtocolAuthorization.java <ide> { <ide> String key = mapItr.next(); <ide> SiteUserRolePrivilegeBean siteUserRolePrivilegeBean = rowIdMap.get(key); <del> User user = null; <add> User user = siteUserRolePrivilegeBean.getUser(); <ide> <ide> if(siteUserRolePrivilegeBean.isRowDeleted()) <ide> { <ide> } <ide> else if(siteUserRolePrivilegeBean.isRowEdited()) <ide> { <del> //siteCollection.addAll(siteList); <del> user = siteUserRolePrivilegeBean.getUser(); <add> // siteCollection.addAll(siteList); <add> // user = siteUserRolePrivilegeBean.getUser(); <ide> // userCollection.add(user); <ide> String defaultRole = siteUserRolePrivilegeBean.getRole().getValue(); <ide> if (defaultRole != null && (defaultRole.equalsIgnoreCase("-1") || defaultRole.equalsIgnoreCase("0")) )
Java
lgpl-2.1
a922795971df48ee110a8c0d3c5ee472106f319c
0
Mineshopper/carpentersblocks,Techern/carpentersblocks,burpingdog1/carpentersblocks
package com.carpentersblocks.block; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.BlockDirectional; import net.minecraft.block.BlockRedstoneWire; import net.minecraft.block.material.Material; import net.minecraft.client.particle.EffectRenderer; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.boss.EntityDragon; import net.minecraft.entity.boss.EntityWither; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Direction; import net.minecraft.util.IIcon; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.client.ForgeHooksClient; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.common.IPlantable; import net.minecraftforge.common.util.ForgeDirection; import com.carpentersblocks.api.ICarpentersChisel; import com.carpentersblocks.api.ICarpentersHammer; import com.carpentersblocks.api.IWrappableBlock; import com.carpentersblocks.renderer.helper.FancyFluidsHelper; import com.carpentersblocks.renderer.helper.ParticleHelper; import com.carpentersblocks.tileentity.TEBase; import com.carpentersblocks.util.BlockProperties; import com.carpentersblocks.util.EntityLivingUtil; import com.carpentersblocks.util.handler.DesignHandler; import com.carpentersblocks.util.handler.EventHandler; import com.carpentersblocks.util.handler.OverlayHandler; import com.carpentersblocks.util.handler.OverlayHandler.Overlay; import com.carpentersblocks.util.protection.PlayerPermissions; import com.carpentersblocks.util.registry.FeatureRegistry; import com.carpentersblocks.util.registry.IconRegistry; import com.carpentersblocks.util.registry.ItemRegistry; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class BlockCoverable extends BlockContainer { /** Block drop event for dropping attribute. */ public static int EVENT_ID_DROP_ATTR = 0; /** Indicates during getDrops that block instance should not be dropped. */ protected final int METADATA_DROP_ATTR_ONLY = 16; /** Caches light values. */ public static Map<Integer,Integer> cache = new HashMap<Integer,Integer>(); /** * Stores actions taken on a block in order to properly play sounds, * decrement player inventory, and to determine if a block was altered. */ protected class ActionResult { public ItemStack itemStack; public boolean playSound = true; public boolean altered = false; public boolean decInv = false; public ActionResult setSoundSource(ItemStack itemStack) { this.itemStack = itemStack; return this; } public ActionResult setNoSound() { playSound = false; return this; } public ActionResult setAltered() { altered = true; return this; } public ActionResult decInventory() { decInv = true; return this; } } /** * Class constructor. * * @param material */ public BlockCoverable(Material material) { super(material); setLightLevel(1.0F); // Make mob spawns check block light value } @SideOnly(Side.CLIENT) @Override /** * When this method is called, your block should register all the icons it needs with the given IconRegister. This * is the only chance you get to register icons. */ public void registerBlockIcons(IIconRegister iconRegister) { } @SideOnly(Side.CLIENT) /** * Returns a base icon that doesn't rely on blockIcon, which * is set prior to texture stitch events. * * @return default icon */ public IIcon getIcon() { return IconRegistry.icon_uncovered_solid; } @SideOnly(Side.CLIENT) @Override /** * Returns the icon on the side given the block metadata. * <p> * Due to the amount of control needed over this, vanilla calls will always return an invisible icon. */ public IIcon getIcon(int side, int metadata) { if (BlockProperties.isMetadataDefaultIcon(metadata)) { return getIcon(); } /* * This icon is a mask (or something) for redstone wire. * We use it here because it renders an invisible icon. * * Using an invisible icon is important because sprint particles are * hard-coded and will always grab particle icons using this method. * We'll throw our own sprint particles in EventHandler.class. */ return BlockRedstoneWire.getRedstoneWireIcon("cross_overlay"); } @SideOnly(Side.CLIENT) @Override /** * Retrieves the block texture to use based on the display side. Args: iBlockAccess, x, y, z, side */ public IIcon getIcon(IBlockAccess blockAccess, int x, int y, int z, int side) { TEBase TE = getTileEntity(blockAccess, x, y, z); ItemStack itemStack = BlockProperties.getCover(TE, 6); Block block = BlockProperties.toBlock(itemStack); return block instanceof BlockCoverable ? getIcon() : getWrappedIcon(block, blockAccess, x, y, z, side, itemStack.getItemDamage()); } private static IIcon getWrappedIcon(Block b, IBlockAccess iba, int x, int y, int z, int side, int meta) { return b instanceof IWrappableBlock ? ((IWrappableBlock)b).getIcon(iba, x, y, z, side, b, meta) : b.getIcon(side, meta); } /** * For South-sided blocks, rotates and sets the block bounds using * the provided ForgeDirection. * * @param dir the rotated {@link ForgeDirection} */ protected void setBlockBounds(float minX, float minY, float minZ, float maxX, float maxY, float maxZ, ForgeDirection dir) { switch (dir) { case DOWN: setBlockBounds(minX, 1.0F - maxZ, minY, maxX, 1.0F - minZ, maxY); break; case UP: setBlockBounds(minX, minZ, minY, maxX, maxZ, maxY); break; case NORTH: setBlockBounds(1.0F - maxX, minY, 1.0F - maxZ, 1.0F - minX, maxY, 1.0F - minZ); break; case EAST: setBlockBounds(minZ, minY, 1.0F - maxX, maxZ, maxY, 1.0F - minX); break; case WEST: setBlockBounds(1.0F - maxZ, minY, minX, 1.0F - minZ, maxY, maxX); break; default: setBlockBounds(minX, minY, minZ, maxX, maxY, maxZ); break; } } /** * Called when block event is received. *<p> * For the context of this mod, this is used for dropping block attributes * like covers, overlays, dyes, or any other ItemStack. *<p> * In order for external classes to call the protected method * {@link Block#dropBlockAsItem(World,int,int,int,ItemStack) dropBlockAsItem}, * they create a block event with parameters itemId and metadata, allowing * the {@link ItemStack} to be recreated and dropped. * * @param world the {@link World} * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate * @param itemId the eventId, repurposed * @param metadata the event parameter, repurposed * @return true if event was handled */ @Override public boolean onBlockEventReceived(World world, int x, int y, int z, int eventId, int param /*attrId*/) { if (!world.isRemote && eventId == EVENT_ID_DROP_ATTR) { TEBase TE = getSimpleTileEntity(world, x, y, z); if (TE != null && TE.hasAttribute((byte) param)) { ItemStack itemStack = TE.getAttributeForDrop((byte) param); dropBlockAsItem(world, x, y, z, itemStack); TE.onAttrDropped((byte) param); return true; } } return super.onBlockEventReceived(world, x, y, z, eventId, param); } /** * Returns an item stack containing a single instance of the current block type. 'i' is the block's subtype/damage * and is ignored for blocks which do not support subtypes. Blocks which cannot be harvested should return null. */ protected ItemStack getItemDrop(World world, int metadata) { int fortune = 1; return new ItemStack(getItemDropped(metadata, world.rand, fortune), 1, metadata); } /** * Returns adjacent, similar tile entities that can be used for duplicating * block properties like dye color, pattern, style, etc. * * @param world the world reference * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate * @return an array of adjacent, similar tile entities * @see {@link TEBase} */ protected TEBase[] getAdjacentTileEntities(World world, int x, int y, int z) { return new TEBase[] { getSimpleTileEntity(world, x, y - 1, z), getSimpleTileEntity(world, x, y + 1, z), getSimpleTileEntity(world, x, y, z - 1), getSimpleTileEntity(world, x, y, z + 1), getSimpleTileEntity(world, x - 1, y, z), getSimpleTileEntity(world, x + 1, y, z) }; } /** * Returns tile entity if block tile entity is instanceof TEBase. * * Used for generic purposes such as getting pattern, dye color, or * cover of another Carpenter's block. Is also used if block * no longer exists, such as when breaking a block and ejecting * attributes. */ protected TEBase getSimpleTileEntity(IBlockAccess blockAccess, int x, int y, int z) { TileEntity TE = blockAccess.getTileEntity(x, y, z); return (TE instanceof TEBase) ? (TEBase) TE : null; } /** * Returns tile entity if block tile entity is instanceof TEBase and * also belongs to this block type. */ protected TEBase getTileEntity(IBlockAccess blockAccess, int x, int y, int z) { TEBase TE = getSimpleTileEntity(blockAccess, x, y, z); return TE != null && blockAccess.getBlock(x, y, z).equals(this) ? TE : null; } /** * Returns whether player is allowed to activate this block. */ protected boolean canPlayerActivate(TEBase TE, EntityPlayer entityPlayer) { return true; } @Override /** * Called when the block is clicked by a player. Args: x, y, z, entityPlayer */ public void onBlockClicked(World world, int x, int y, int z, EntityPlayer entityPlayer) { if (world.isRemote) { return; } TEBase TE = getTileEntity(world, x, y, z); if (TE == null) { return; } else if (!PlayerPermissions.canPlayerEdit(TE, TE.xCoord, TE.yCoord, TE.zCoord, entityPlayer)) { return; } ItemStack itemStack = entityPlayer.getCurrentEquippedItem(); if (itemStack == null) { return; } int effectiveSide = TE.hasAttribute(TE.ATTR_COVER[EventHandler.eventFace]) ? EventHandler.eventFace : 6; Item item = itemStack.getItem(); if (item instanceof ICarpentersHammer && ((ICarpentersHammer)item).canUseHammer(world, entityPlayer)) { ActionResult actionResult = new ActionResult(); preOnBlockClicked(TE, world, x, y, z, entityPlayer, actionResult); if (!actionResult.altered) { if (entityPlayer.isSneaking()) { popAttribute(TE, effectiveSide); } else { onHammerLeftClick(TE, entityPlayer); } actionResult.setAltered(); } else { onNeighborBlockChange(world, x, y, z, this); world.notifyBlocksOfNeighborChange(x, y, z, this); } } else if (item instanceof ICarpentersChisel && ((ICarpentersChisel)item).canUseChisel(world, entityPlayer)) { if (entityPlayer.isSneaking() && TE.hasChiselDesign(effectiveSide)) { TE.removeChiselDesign(effectiveSide); } else if (TE.hasAttribute(TE.ATTR_COVER[effectiveSide])) { onChiselClick(TE, effectiveSide, true); } } } /** * Pops attribute in hard-coded order. * * @param TE * @param side */ private void popAttribute(TEBase TE, int side) { if (TE.hasAttribute(TE.ATTR_ILLUMINATOR)) { TE.createBlockDropEvent(TE.ATTR_ILLUMINATOR); } else if (TE.hasAttribute(TE.ATTR_OVERLAY[side])) { TE.createBlockDropEvent(TE.ATTR_OVERLAY[side]); } else if (TE.hasAttribute(TE.ATTR_DYE[side])) { TE.createBlockDropEvent(TE.ATTR_DYE[side]); } else if (TE.hasAttribute(TE.ATTR_COVER[side])) { TE.createBlockDropEvent(TE.ATTR_COVER[side]); TE.removeChiselDesign(side); } } @Override /** * Called upon block activation (right click on the block.) */ public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityPlayer, int side, float hitX, float hitY, float hitZ) { if (world.isRemote) { return true; } else { TEBase TE = getTileEntity(world, x, y, z); if (TE == null) { return false; } if (!canPlayerActivate(TE, entityPlayer)) { return false; } // Allow block to change TE if needed before altering attributes TE = getTileEntityForBlockActivation(TE); ActionResult actionResult = new ActionResult(); preOnBlockActivated(TE, entityPlayer, side, hitX, hitY, hitZ, actionResult); // If no prior event occurred, try regular activation if (!actionResult.altered) { if (PlayerPermissions.canPlayerEdit(TE, TE.xCoord, TE.yCoord, TE.zCoord, entityPlayer)) { ItemStack itemStack = entityPlayer.getCurrentEquippedItem(); if (itemStack != null) { /* Sides 0-5 are side covers, and 6 is the base block. */ int effectiveSide = TE.hasAttribute(TE.ATTR_COVER[side]) ? side : 6; if (itemStack.getItem() instanceof ICarpentersHammer && ((ICarpentersHammer)itemStack.getItem()).canUseHammer(world, entityPlayer)) { if (onHammerRightClick(TE, entityPlayer)) { actionResult.setAltered(); } } else if (ItemRegistry.enableChisel && itemStack.getItem() instanceof ICarpentersChisel && ((ICarpentersChisel)itemStack.getItem()).canUseChisel(world, entityPlayer)) { if (TE.hasAttribute(TE.ATTR_COVER[effectiveSide])) { if (onChiselClick(TE, effectiveSide, false)) { actionResult.setAltered(); } } } else if (FeatureRegistry.enableCovers && BlockProperties.isCover(itemStack)) { Block block = BlockProperties.toBlock(itemStack); /* Will handle blocks that save directions using only y axis (pumpkin) */ int metadata = block instanceof BlockDirectional ? MathHelper.floor_double(entityPlayer.rotationYaw * 4.0F / 360.0F + 2.5D) & 3 : itemStack.getItemDamage(); /* Will handle blocks that save directions using all axes (logs, quartz) */ if (BlockProperties.blockRotates(itemStack)) { int rot = Direction.rotateOpposite[EntityLivingUtil.getRotationValue(entityPlayer)]; int side_interpolated = entityPlayer.rotationPitch < -45.0F ? 0 : entityPlayer.rotationPitch > 45 ? 1 : rot == 0 ? 3 : rot == 1 ? 4 : rot == 2 ? 2 : 5; metadata = block.onBlockPlaced(world, TE.xCoord, TE.yCoord, TE.zCoord, side_interpolated, hitX, hitY, hitZ, metadata); } ItemStack tempStack = itemStack.copy(); tempStack.setItemDamage(metadata); /* Base cover should always be checked. */ if (effectiveSide == 6 && (!canCoverSide(TE, world, TE.xCoord, TE.yCoord, TE.zCoord, 6) || TE.hasAttribute(TE.ATTR_COVER[6]))) { effectiveSide = side; } if (canCoverSide(TE, world, TE.xCoord, TE.yCoord, TE.zCoord, effectiveSide) && !TE.hasAttribute(TE.ATTR_COVER[effectiveSide])) { TE.addAttribute(TE.ATTR_COVER[effectiveSide], tempStack); actionResult.setAltered().decInventory().setSoundSource(itemStack); } } else if (entityPlayer.isSneaking()) { if (FeatureRegistry.enableIllumination && BlockProperties.isIlluminator(itemStack)) { if (!TE.hasAttribute(TE.ATTR_ILLUMINATOR)) { TE.addAttribute(TE.ATTR_ILLUMINATOR, itemStack); actionResult.setAltered().decInventory().setSoundSource(itemStack); } } else if (FeatureRegistry.enableOverlays && BlockProperties.isOverlay(itemStack)) { if (!TE.hasAttribute(TE.ATTR_OVERLAY[effectiveSide]) && (effectiveSide < 6 && TE.hasAttribute(TE.ATTR_COVER[effectiveSide]) || effectiveSide == 6)) { TE.addAttribute(TE.ATTR_OVERLAY[effectiveSide], itemStack); actionResult.setAltered().decInventory().setSoundSource(itemStack); } } else if (FeatureRegistry.enableDyeColors && BlockProperties.isDye(itemStack, false)) { if (!TE.hasAttribute(TE.ATTR_DYE[effectiveSide])) { TE.addAttribute(TE.ATTR_DYE[effectiveSide], itemStack); actionResult.setAltered().decInventory().setSoundSource(itemStack); } } } } } } if (!actionResult.altered) { // If no prior or regular event occurred, try a post event postOnBlockActivated(TE, entityPlayer, side, hitX, hitY, hitZ, actionResult); } else { if (actionResult.itemStack == null) { actionResult.setSoundSource(BlockProperties.getCover(TE, 6)); } damageItemWithChance(world, entityPlayer); onNeighborBlockChange(world, TE.xCoord, TE.yCoord, TE.zCoord, this); world.notifyBlocksOfNeighborChange(TE.xCoord, TE.yCoord, TE.zCoord, this); } if (actionResult.playSound) { BlockProperties.playBlockSound(TE.getWorldObj(), actionResult.itemStack, TE.xCoord, TE.yCoord, TE.zCoord, false); } if (actionResult.decInv) { EntityLivingUtil.decrementCurrentSlot(entityPlayer); } return actionResult.altered; } } /** * Cycles through chisel patterns. */ public boolean onChiselClick(TEBase TE, int side, boolean leftClick) { String design = TE.getChiselDesign(side); String designAdj = ""; if (design.equals("")) { World world = TE.getWorldObj(); /* Match pattern with adjacent pattern if possible. */ TEBase[] TE_list = getAdjacentTileEntities(world, TE.xCoord, TE.yCoord, TE.zCoord); for (TEBase TE_current : TE_list) { if (TE_current != null) { TE_current.getBlockType(); if (TE_current.hasChiselDesign(side)) { design = TE_current.getChiselDesign(side); designAdj = design; } } } } if (designAdj.equals("")) { design = leftClick ? DesignHandler.getPrev("chisel", design) : DesignHandler.getNext("chisel", design); } if (!design.equals("")) { TE.setChiselDesign(side, design); } return true; } @Override /** * Lets the block know when one of its neighbor changes. Doesn't know which neighbor changed (coordinates passed are * their own) Args: x, y, z, neighbor blockID */ public void onNeighborBlockChange(World world, int x, int y, int z, Block block) { /* This will check for and eject side covers that are obstructed. */ if (!world.isRemote) { TEBase TE = getTileEntity(world, x, y, z); if (TE != null) { for (int side = 0; side < 6; ++side) { if (TE.hasAttribute(TE.ATTR_COVER[side])) { if (!canCoverSide(TE, world, x, y, z, side)) { TE.removeAttributes(side); continue; } ForgeDirection dir = ForgeDirection.getOrientation(side); if (world.isSideSolid(x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ, dir.getOpposite()) && isSideSolid(world, x, y, z, dir)) { TE.removeAttributes(side); } } } } } } @Override /** * Returns true if the block is emitting indirect/weak redstone power on the specified side. If isBlockNormalCube * returns true, standard redstone propagation rules will apply instead and this will not be called. Args: World, X, * Y, Z, side. Note that the side is reversed - eg it is 1 (up) when checking the bottom of the block. */ public int isProvidingWeakPower(IBlockAccess blockAccess, int x, int y, int z, int side) { TEBase TE = getTileEntity(blockAccess, x, y, z); int power = 0; /* Indirect power is provided by any cover. */ if (TE != null) { for (int idx = 0; idx < 7; ++idx) { if (TE.hasAttribute(TE.ATTR_COVER[idx])) { Block block = BlockProperties.toBlock(BlockProperties.getCover(TE, idx)); int tempPower = block.isProvidingWeakPower(blockAccess, x, y, z, side); if (tempPower > power) { power = tempPower; } } } } return power; } @Override /** * Returns true if the block is emitting direct/strong redstone power on the specified side. Args: World, X, Y, Z, * side. Note that the side is reversed - eg it is 1 (up) when checking the bottom of the block. */ public int isProvidingStrongPower(IBlockAccess blockAccess, int x, int y, int z, int side) { TEBase TE = getTileEntity(blockAccess, x, y, z); int power = 0; /* Strong power is provided by the base cover, or a side cover if one exists. */ int effectiveSide = ForgeDirection.OPPOSITES[side]; if (BlockProperties.hasAttribute(TE, TE.ATTR_COVER[effectiveSide])) { Block block = BlockProperties.toBlock(BlockProperties.getCover(TE, effectiveSide)); int tempPower = block.isProvidingWeakPower(blockAccess, x, y, z, side); if (tempPower > power) { power = tempPower; } } else if (BlockProperties.hasAttribute(TE, TE.ATTR_COVER[6])) { Block block = BlockProperties.toBlock(BlockProperties.getCover(TE, 6)); int tempPower = block.isProvidingWeakPower(blockAccess, x, y, z, side); if (tempPower > power) { power = tempPower; } } return power; } @Override @SideOnly(Side.CLIENT) /** * Spawn a digging particle effect in the world, this is a wrapper * around EffectRenderer.addBlockHitEffects to allow the block more * control over the particles. Useful when you have entirely different * texture sheets for different sides/locations in the world. * * @param world The current world * @param target The target the player is looking at {x/y/z/side/sub} * @param effectRenderer A reference to the current effect renderer. * @return True to prevent vanilla digging particles form spawning. */ public boolean addHitEffects(World world, MovingObjectPosition target, EffectRenderer effectRenderer) { TEBase TE = getTileEntity(world, target.blockX, target.blockY, target.blockZ); if (TE != null) { int effectiveSide = TE.hasAttribute(TE.ATTR_COVER[target.sideHit]) ? target.sideHit : 6; ItemStack itemStack = BlockProperties.getCover(TE, effectiveSide); if (BlockProperties.hasAttribute(TE, TE.ATTR_OVERLAY[effectiveSide])) { Overlay overlay = OverlayHandler.getOverlayType(TE.getAttribute(TE.ATTR_OVERLAY[effectiveSide])); if (OverlayHandler.coversFullSide(overlay, target.sideHit)) { itemStack = overlay.getItemStack(); } } Block block = BlockProperties.toBlock(itemStack); double xOffset = target.blockX + world.rand.nextDouble() * (block.getBlockBoundsMaxX() - block.getBlockBoundsMinX() - 0.1F * 2.0F) + 0.1F + block.getBlockBoundsMinX(); double yOffset = target.blockY + world.rand.nextDouble() * (block.getBlockBoundsMaxY() - block.getBlockBoundsMinY() - 0.1F * 2.0F) + 0.1F + block.getBlockBoundsMinY(); double zOffset = target.blockZ + world.rand.nextDouble() * (block.getBlockBoundsMaxZ() - block.getBlockBoundsMinZ() - 0.1F * 2.0F) + 0.1F + block.getBlockBoundsMinZ(); switch (target.sideHit) { case 0: yOffset = target.blockY + block.getBlockBoundsMinY() - 0.1D; break; case 1: yOffset = target.blockY + block.getBlockBoundsMaxY() + 0.1D; break; case 2: zOffset = target.blockZ + block.getBlockBoundsMinZ() - 0.1D; break; case 3: zOffset = target.blockZ + block.getBlockBoundsMaxZ() + 0.1D; break; case 4: xOffset = target.blockX + block.getBlockBoundsMinX() - 0.1D; break; case 5: xOffset = target.blockX + block.getBlockBoundsMaxX() + 0.1D; break; } ParticleHelper.addHitEffect(TE, target, xOffset, yOffset, zOffset, itemStack, effectRenderer); return true; } return super.addHitEffects(world, target, effectRenderer); } @Override @SideOnly(Side.CLIENT) /** * Renders block destruction effects. * This is controlled to prevent block destroy effects if left-clicked with a Carpenter's Hammer while player is in creative mode. * * Returns false to display effects. True suppresses them (backwards). */ public boolean addDestroyEffects(World world, int x, int y, int z, int metadata, EffectRenderer effectRenderer) { /* * We don't have the ability to accurately determine the entity that is * hitting the block. So, instead we're guessing based on who is * closest. This should be adequate most of the time. */ TEBase TE = getTileEntity(world, x, y, z); if (TE != null) { EntityPlayer entityPlayer = world.getClosestPlayer(x, y, z, 6.5F); if (entityPlayer != null) { if (!suppressDestroyBlock(entityPlayer)) { ParticleHelper.addDestroyEffect(world, x, y, z, BlockProperties.getCover(TE, 6), effectRenderer); } else { return true; } } } return false; } /** * Gets the current light value based on covers and illumination. * * @param blockAccess the {@link IBlockAccess} object * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate * @return a light value from 0 to 15 */ protected int getCurrentLightValue(IBlockAccess blockAccess, int x, int y, int z) { int lightValue = 0; TEBase TE = getTileEntity(blockAccess, x, y, z); if (TE != null) { if (FeatureRegistry.enableIllumination && TE.hasAttribute(TE.ATTR_ILLUMINATOR)) { lightValue = 15; } else { for (int side = 0; side < 7; ++side) { if (TE.hasAttribute(TE.ATTR_COVER[side])) { ItemStack itemStack = BlockProperties.getCover(TE, side); int tempLight = getLightValue(TE, BlockProperties.toBlock(itemStack), itemStack.getItemDamage()); lightValue = Math.max(tempLight, lightValue); } } } } return lightValue; } /** * Updates cached light value for block. * <b> * Several blocks may call for light values at once, and * grabbing the tile entity each time eats into performance. * * @param blockAccess the {@link IBlockAccess} object * @param x * @param y * @param z */ public void updateLightValue(IBlockAccess blockAccess, int x, int y, int z) { int lightValue = getCurrentLightValue(blockAccess, x, y, z); cache.put(BlockProperties.hashCoords(x, y, z), lightValue); } /** * Returns light value for block using two methods. First, it * checks if the static light value is not zero. If zero, it checks * using the block metadata. * * @param TE the {@link TEBase} * @param block the {@link Block} * @param metadata the block metadata * @return a light value from 0 to 15 */ protected int getLightValue(TEBase TE, Block block, int metadata) { /* Grab static light value */ int lightValue = block.getLightValue(); /* Try grabbing more accurate lighting using metadata */ if (lightValue == 0) { TE.setMetadata(metadata); lightValue = block.getLightValue(TE.getWorldObj(), TE.xCoord, TE.yCoord, TE.zCoord); TE.restoreMetadata(); } return lightValue; } @Override /** * Returns light value based on cover or side covers. */ public final int getLightValue(IBlockAccess blockAccess, int x, int y, int z) { int hash = BlockProperties.hashCoords(x, y, z); if (cache.containsKey(hash)) { return cache.get(hash); } return 0; } @Override /** * Returns the block hardness at a location. Args: world, x, y, z */ public float getBlockHardness(World world, int x, int y, int z) { TEBase TE = getTileEntity(world, x, y, z); if (BlockProperties.hasAttribute(TE, TE.ATTR_COVER[6])) { ItemStack is = BlockProperties.getCover(TE, 6); Block b = BlockProperties.toBlock(is); return b instanceof IWrappableBlock ? ((IWrappableBlock)b).getHardness(world, x, y, z, b, is.getItemDamage()) : b.getBlockHardness(world, x, y, z); } return blockHardness; } @Override /** * Chance that fire will spread and consume this block. */ public int getFlammability(IBlockAccess blockAccess, int x, int y, int z, ForgeDirection face) { TEBase TE = getTileEntity(blockAccess, x, y, z); if (TE != null) { ItemStack is = BlockProperties.getCover(TE, 6); Block b = BlockProperties.toBlock(is); return b instanceof IWrappableBlock ? ((IWrappableBlock)b).getFlammability(blockAccess, x, y, z, face, b, is.getItemDamage()) : Blocks.fire.getFlammability(b); } return super.getFlammability(blockAccess, x, y, z, face); } @Override /** * Called when fire is updating on a neighbor block. */ public int getFireSpreadSpeed(IBlockAccess blockAccess, int x, int y, int z, ForgeDirection side) { TEBase TE = getTileEntity(blockAccess, x, y, z); if (TE != null) { ItemStack is = BlockProperties.getCover(TE, 6); Block b = BlockProperties.toBlock(is); return b instanceof IWrappableBlock ? ((IWrappableBlock)b).getFireSpread(blockAccess, x, y, z, side, b, is.getItemDamage()) : Blocks.fire.getEncouragement(b); } return super.getFireSpreadSpeed(blockAccess, x, y, z, side); } @Override /** * Currently only called by fire when it is on top of this block. * Returning true will prevent the fire from naturally dying during updating. * Also prevents fire from dying from rain. */ public boolean isFireSource(World world, int x, int y, int z, ForgeDirection side) { TEBase TE = getTileEntity(world, x, y, z); if (BlockProperties.hasAttribute(TE, TE.ATTR_COVER[6])) { ItemStack is = BlockProperties.getCover(TE, 6); Block b = BlockProperties.toBlock(is); return b instanceof IWrappableBlock ? ((IWrappableBlock)b).sustainsFire(world, x, y, z, side, b, is.getItemDamage()) : b.isFireSource(world, x, y, z, side); } return false; } @Override /** * Location sensitive version of getExplosionRestance */ public float getExplosionResistance(Entity entity, World world, int x, int y, int z, double explosionX, double explosionY, double explosionZ) { TEBase TE = getTileEntity(world, x, y, z); if (BlockProperties.hasAttribute(TE, TE.ATTR_COVER[6])) { ItemStack is = BlockProperties.getCover(TE, 6); Block b = BlockProperties.toBlock(is); return b instanceof IWrappableBlock ? ((IWrappableBlock)b).getBlastResistance(entity, world, x, y, z, explosionX, explosionY, explosionZ, b, is.getItemDamage()) : b.getExplosionResistance(entity, world, x, y, z, explosionX, explosionY, explosionZ); } return this.getExplosionResistance(entity); } @Override /** * Returns whether block is wood */ public boolean isWood(IBlockAccess blockAccess, int x, int y, int z) { TEBase TE = getTileEntity(blockAccess, x, y, z); if (BlockProperties.hasAttribute(TE, TE.ATTR_COVER[6])) { ItemStack is = BlockProperties.getCover(TE, 6); Block b = BlockProperties.toBlock(is); return b instanceof IWrappableBlock ? ((IWrappableBlock)b).isLog(blockAccess, x, y, z, b, is.getItemDamage()) : b.isWood(blockAccess, x, y, z); } return super.isWood(blockAccess, x, y, z); } /** * Determines if this block is can be destroyed by the specified entities normal behavior. */ @Override public boolean canEntityDestroy(IBlockAccess blockAccess, int x, int y, int z, Entity entity) { TEBase TE = getTileEntity(blockAccess, x, y, z); if (BlockProperties.hasAttribute(TE, TE.ATTR_COVER[6])) { Block block = BlockProperties.toBlock(BlockProperties.getCover(TE, 6)); if (entity instanceof EntityWither) { return !block.equals(Blocks.bedrock) && !block.equals(Blocks.end_portal) && !block.equals(Blocks.end_portal_frame) && !block.equals(Blocks.command_block); } else if (entity instanceof EntityDragon) { return !block.equals(Blocks.obsidian) && !block.equals(Blocks.end_stone) && !block.equals(Blocks.bedrock); } } return super.canEntityDestroy(blockAccess, x, y, z, entity); } @Override /** * Triggered whenever an entity collides with this block (enters into the block). Args: world, x, y, z, entity */ public void onEntityCollidedWithBlock(World world, int x, int y, int z, Entity entity) { TEBase TE = getTileEntity(world, x, y, z); if (BlockProperties.hasAttribute(TE, TE.ATTR_COVER[6])) { BlockProperties.toBlock(BlockProperties.getCover(TE, 6)).onEntityCollidedWithBlock(world, x, y, z, entity); } } @Override /** * Spawns EntityItem in the world for the given ItemStack if the world is not remote. */ protected void dropBlockAsItem(World world, int x, int y, int z, ItemStack itemStack) { // Clear metadata for Carpenter's blocks Block block = BlockProperties.toBlock(itemStack); if (block instanceof BlockCoverable) { itemStack.setItemDamage(0); } super.dropBlockAsItem(world, x, y, z, itemStack); } @Override /** * Called when the player destroys a block with an item that can harvest it. (i, j, k) are the coordinates of the * block and l is the block's subtype/damage. */ public void harvestBlock(World p_149636_1_, EntityPlayer p_149636_2_, int p_149636_3_, int p_149636_4_, int p_149636_5_, int p_149636_6_) {} /** * Indicates whether block destruction should be suppressed when block is clicked. * Will return true if player is holding a Carpenter's tool in creative mode. */ protected boolean suppressDestroyBlock(EntityPlayer entityPlayer) { if (entityPlayer == null) { return false; } ItemStack itemStack = entityPlayer.getHeldItem(); if (itemStack != null) { Item item = itemStack.getItem(); return entityPlayer.capabilities.isCreativeMode && item != null && (item instanceof ICarpentersHammer || item instanceof ICarpentersChisel); } return false; } /** * Drops block as {@link ItemStack} and notifies relevant systems of * block removal. Block attributes will drop later in destruction. * <p> * This is usually called when a {@link #onNeighborBlockChange(World, int, int, int, Block) neighbor changes}. * * @param world the {@link World} * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate * @param dropBlock whether block {@link ItemStack} is dropped */ protected void destroyBlock(World world, int x, int y, int z, boolean dropBlock) { // Drop attributes int metadata = dropBlock ? 0 : METADATA_DROP_ATTR_ONLY; ArrayList<ItemStack> items = getDrops(world, x, y, z, metadata, 0); for (ItemStack item : items) { dropBlockAsItem(world, x, y, z, item); } world.setBlockToAir(x, y, z); } @Override /** * Called when a player removes a block. This is responsible for * actually destroying the block, and the block is intact at time of call. * This is called regardless of whether the player can harvest the block or * not. * * Return true if the block is actually destroyed. * * Note: When used in multiplayer, this is called on both client and * server sides! * * @param world The current world * @param player The player damaging the block, may be null * @param x X Position * @param y Y position * @param z Z position * @param willHarvest True if Block.harvestBlock will be called after this, if the return in true. * Can be useful to delay the destruction of tile entities till after harvestBlock * @return True if the block is actually destroyed. */ public boolean removedByPlayer(World world, EntityPlayer entityPlayer, int x, int y, int z, boolean willHarvest) { if (world.isRemote) { return super.removedByPlayer(world, entityPlayer, x, y, z, willHarvest); } // Grab drops while tile entity exists (before calling super) int metadata = entityPlayer != null && entityPlayer.capabilities.isCreativeMode ? METADATA_DROP_ATTR_ONLY : 0; ArrayList<ItemStack> items = getDrops(world, x, y, z, metadata, 0); // Drop attributes if block destroyed, and no Carpenter's Tool is held by entity if (!suppressDestroyBlock(entityPlayer) && super.removedByPlayer(world, entityPlayer, x, y, z, willHarvest)) { for (ItemStack item : items) { dropBlockAsItem(world, x, y, z, item); } return true; } return false; } @Override /** * Ejects contained items into the world, and notifies neighbors of an update, as appropriate */ public void breakBlock(World world, int x, int y, int z, Block block, int metadata) { // Remove cached light value cache.remove(BlockProperties.hashCoords(x, y, z)); super.breakBlock(world, x, y, z, block, metadata); } /** * This returns a complete list of items dropped from this block. * * @param world The current world * @param x X Position * @param y Y Position * @param z Z Position * @param metadata Current metadata * @param fortune Breakers fortune level * @return A ArrayList containing all items this block drops */ @Override public ArrayList<ItemStack> getDrops(World world, int x, int y, int z, int metadata, int fortune) { ArrayList<ItemStack> ret = super.getDrops(world, x, y, z, metadata, fortune); // Add block item drop TEBase TE = getSimpleTileEntity(world, x, y, z); if (metadata == METADATA_DROP_ATTR_ONLY) { ret.clear(); // Remove block instance from drop list } if (TE != null) { for (int idx = 0; idx < 7; ++idx) { if (TE.hasAttribute(TE.ATTR_COVER[idx])) { ret.add(TE.getAttributeForDrop(TE.ATTR_COVER[idx])); } if (TE.hasAttribute(TE.ATTR_OVERLAY[idx])) { ret.add(TE.getAttributeForDrop(TE.ATTR_OVERLAY[idx])); } if (TE.hasAttribute(TE.ATTR_DYE[idx])) { ret.add(TE.getAttributeForDrop(TE.ATTR_DYE[idx])); } } if (TE.hasAttribute(TE.ATTR_ILLUMINATOR)) { ret.add(TE.getAttributeForDrop(TE.ATTR_ILLUMINATOR)); } } return ret; } @Override @SideOnly(Side.CLIENT) /** * A randomly called display update to be able to add particles or other items for display */ public void randomDisplayTick(World world, int x, int y, int z, Random random) { TEBase TE = getTileEntity(world, x, y, z); if (TE != null) { if (TE.hasAttribute(TE.ATTR_COVER[6])) { BlockProperties.toBlock(BlockProperties.getCover(TE, 6)).randomDisplayTick(world, x, y, z, random); } if (TE.hasAttribute(TE.ATTR_OVERLAY[6])) { if (OverlayHandler.getOverlayType(TE.getAttribute(TE.ATTR_OVERLAY[6])).equals(Overlay.MYCELIUM)) { Blocks.mycelium.randomDisplayTick(world, x, y, z, random); } } } } /** * Determines if this block can support the passed in plant, allowing it to be planted and grow. * Some examples: * Reeds check if its a reed, or if its sand/dirt/grass and adjacent to water * Cacti checks if its a cacti, or if its sand * Nether types check for soul sand * Crops check for tilled soil * Caves check if it's a solid surface * Plains check if its grass or dirt * Water check if its still water * * @param blockAccess The current world * @param x X Position * @param y Y Position * @param z Z position * @param side The direction relative to the given position the plant wants to be, typically its UP * @param plantable The plant that wants to check * @return True to allow the plant to be planted/stay. */ @Override public boolean canSustainPlant(IBlockAccess blockAccess, int x, int y, int z, ForgeDirection side, IPlantable plantable) { TEBase TE = getTileEntity(blockAccess, x, y, z); if (TE != null) { /* If side is not solid, it can't sustain a plant. */ if (!isSideSolid(blockAccess, x, y, z, side)) { return false; } /* * Add base block, top block, and both of their associated * overlays to judge whether plants can be supported on block. */ List<Block> blocks = new ArrayList<Block>(); for (int side1 = 1; side1 < 7; side1 += 5) { if (TE.hasAttribute(TE.ATTR_COVER[side1])) { blocks.add(BlockProperties.toBlock(BlockProperties.getCover(TE, side1))); } if (TE.hasAttribute(TE.ATTR_OVERLAY[side1])) { blocks.add(BlockProperties.toBlock(OverlayHandler.getOverlayType(TE.getAttribute(TE.ATTR_OVERLAY[side1])).getItemStack())); } } /* Add types using cover material */ Material material = BlockProperties.toBlock(BlockProperties.getCover(TE, 6)).getMaterial(); if (material.equals(Material.grass)) { blocks.add(Blocks.grass); } else if (material.equals(Material.ground)) { blocks.add(Blocks.dirt); } else if (material.equals(Material.sand)) { blocks.add(Blocks.sand); } switch (plantable.getPlantType(blockAccess, x, y + 1, z)) { case Desert: return blocks.contains(Blocks.sand); case Nether: return blocks.contains(Blocks.soul_sand); case Plains: return blocks.contains(Blocks.grass) || blocks.contains(Blocks.dirt); case Beach: boolean isBeach = blocks.contains(Blocks.grass) || blocks.contains(Blocks.dirt) || blocks.contains(Blocks.sand); boolean hasWater = blockAccess.getBlock(x - 1, y, z ).getMaterial() == Material.water || blockAccess.getBlock(x + 1, y, z ).getMaterial() == Material.water || blockAccess.getBlock(x, y, z - 1).getMaterial() == Material.water || blockAccess.getBlock(x, y, z + 1).getMaterial() == Material.water; return isBeach && hasWater; default: break; } } return super.canSustainPlant(blockAccess, x, y, z, side, plantable); } /** * Returns whether this block is considered solid. */ protected boolean isBlockSolid(IBlockAccess blockAccess, int x, int y, int z) { TEBase TE = getTileEntity(blockAccess, x, y, z); if (TE != null) { return !TE.hasAttribute(TE.ATTR_COVER[6]) || BlockProperties.toBlock(BlockProperties.getCover(TE, 6)).isOpaqueCube(); } else { return false; } } @Override /** * Called when the block is placed in the world. */ public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entityLiving, ItemStack itemStack) { if (!world.isRemote) { TEBase TE = getTileEntity(world, x, y, z); if (TE != null) { TE.setOwner(entityLiving.getUniqueID()); } } } @Override /** * Gets the hardness of block at the given coordinates in the given world, relative to the ability of the given * EntityPlayer. */ public float getPlayerRelativeBlockHardness(EntityPlayer entityPlayer, World world, int x, int y, int z) { /* Don't damage block if holding Carpenter's tool. */ ItemStack itemStack = entityPlayer.getHeldItem(); if (itemStack != null) { Item item = itemStack.getItem(); if (item instanceof ICarpentersHammer || item instanceof ICarpentersChisel) { return -1; } } /* Return block hardness of cover. */ TEBase TE = getTileEntity(world, x, y, z); if (TE != null) { return ForgeHooks.blockStrength(BlockProperties.toBlock(BlockProperties.getCover(TE, 6)), entityPlayer, world, x, y, z); } else { return super.getPlayerRelativeBlockHardness(entityPlayer, world, x, y, z); } } @SideOnly(Side.CLIENT) @Override public int colorMultiplier(IBlockAccess blockAccess, int x, int y, int z) { TEBase TE = getTileEntity(blockAccess, x, y, z); if (TE != null) { ItemStack itemStack = BlockProperties.getCover(TE, 6); Block block = BlockProperties.toBlock(itemStack); if (!(block instanceof BlockCoverable)) { return block instanceof IWrappableBlock ? ((IWrappableBlock)block).getColorMultiplier(blockAccess, x, y, z, block, itemStack.getItemDamage()) : block.colorMultiplier(blockAccess, x, y, z); } } return super.colorMultiplier(blockAccess, x, y, z); } @Override @SideOnly(Side.CLIENT) /** * Returns true if the given side of this block type should be rendered, if the adjacent block is at the given * coordinates. Args: world, x, y, z, side */ public boolean shouldSideBeRendered(IBlockAccess blockAccess, int x, int y, int z, int side) { // Side checks in out-of-range areas will crash if (y > 0 && y < blockAccess.getHeight()) { TEBase TE = getTileEntity(blockAccess, x, y, z); if (TE != null) { ForgeDirection side_src = ForgeDirection.getOrientation(side); ForgeDirection side_adj = side_src.getOpposite(); TEBase TE_adj = (TEBase) blockAccess.getTileEntity(x, y, z); TEBase TE_src = (TEBase) blockAccess.getTileEntity(x + side_adj.offsetX, y + side_adj.offsetY, z + side_adj.offsetZ); if (TE_adj.getBlockType().isSideSolid(blockAccess, x, y, z, side_adj) == TE_src.getBlockType().isSideSolid(blockAccess, x + side_adj.offsetX, y + side_adj.offsetY, z + side_adj.offsetZ, ForgeDirection.getOrientation(side))) { if (shareFaces(TE_adj, TE_src, side_adj, side_src)) { Block block_adj = BlockProperties.toBlock(BlockProperties.getCover(TE_adj, 6)); Block block_src = BlockProperties.toBlock(BlockProperties.getCover(TE_src, 6)); if (!TE_adj.hasAttribute(TE.ATTR_COVER[6])) { return TE_src.hasAttribute(TE.ATTR_COVER[6]); } else { if (!TE_src.hasAttribute(TE.ATTR_COVER[6]) && block_adj.getRenderBlockPass() == 0) { return !block_adj.isOpaqueCube(); } else if (TE_src.hasAttribute(TE.ATTR_COVER[6]) && block_src.isOpaqueCube() == block_adj.isOpaqueCube() && block_src.getRenderBlockPass() == block_adj.getRenderBlockPass()) { return false; } else { return true; } } } } } } return super.shouldSideBeRendered(blockAccess, x, y, z, side); } @Override /** * Determines if this block should render in this pass. */ public boolean canRenderInPass(int pass) { ForgeHooksClient.setRenderPass(pass); return true; } @Override @SideOnly(Side.CLIENT) /** * Returns which pass this block be rendered on. 0 for solids and 1 for alpha. */ public int getRenderBlockPass() { /* * Alpha properties of block or cover depend on this returning a value * of 1, so it's the default value. However, when rendering in player * hand we'll encounter sorting artifacts, and thus need to enforce * opaque rendering, or 0. */ if (ForgeHooksClient.getWorldRenderPass() < 0) { return 0; } else { return 1; } } /** * Returns whether two blocks share faces. * Primarily for slopes, stairs and slabs. */ protected boolean shareFaces(TEBase TE_adj, TEBase TE_src, ForgeDirection side_adj, ForgeDirection side_src) { return TE_adj.getBlockType().isSideSolid(TE_adj.getWorldObj(), TE_adj.xCoord, TE_adj.yCoord, TE_adj.zCoord, side_adj) && TE_src.getBlockType().isSideSolid(TE_src.getWorldObj(), TE_src.xCoord, TE_src.yCoord, TE_src.zCoord, side_src); } @Override /** * Is this block (a) opaque and (b) a full 1m cube? This determines whether or not to render the shared face of two * adjacent blocks and also whether the player can attach torches, redstone wire, etc to this block. */ public boolean isOpaqueCube() { if (FMLCommonHandler.instance().getEffectiveSide().isServer()) { return false; } if (FeatureRegistry.enableRoutableFluids) { Class<?> clazz = FancyFluidsHelper.getCallerClass(); if (clazz != null) { for (Class clazz1 : FancyFluidsHelper.liquidClasses) { if (clazz.isAssignableFrom(clazz1)) { return true; } } } } return false; } @Override /** * If this block doesn't render as an ordinary block it will return False (examples: signs, buttons, stairs, etc) */ public boolean renderAsNormalBlock() { return false; } /** * Should block use the brightest neighbor light value as its own */ @Override public boolean getUseNeighborBrightness() { return true; } @Override /** * Called whenever the block is added into the world. Args: world, x, y, z */ public void onBlockAdded(World world, int x, int y, int z) { world.setTileEntity(x, y, z, createNewTileEntity(world, 0)); updateLightValue(world, x, y, z); } @Override public TileEntity createNewTileEntity(World world, int metadata) { return new TEBase(); } @Override public boolean hasTileEntity(int metadata) { return true; } /** * This method is configured on as as-needed basis. * It's calling order is not guaranteed. */ protected void preOnBlockClicked(TEBase TE, World world, int x, int y, int z, EntityPlayer entityPlayer, ActionResult actionResult) {} /** * Called before cover or decoration checks are performed. */ protected void preOnBlockActivated(TEBase TE, EntityPlayer entityPlayer, int side, float hitX, float hitY, float hitZ, ActionResult actionResult) {} /** * Called if cover and decoration checks have been performed but * returned no changes. */ protected void postOnBlockActivated(TEBase TE, EntityPlayer entityPlayer, int side, float hitX, float hitY, float hitZ, ActionResult actionResult) {} protected boolean onHammerLeftClick(TEBase TE, EntityPlayer entityPlayer) { return false; } protected boolean onHammerRightClick(TEBase TE, EntityPlayer entityPlayer) { return false; } protected void damageItemWithChance(World world, EntityPlayer entityPlayer) { Item item = entityPlayer.getCurrentEquippedItem().getItem(); if (item instanceof ICarpentersHammer) { ((ICarpentersHammer) item).onHammerUse(world, entityPlayer); } else if (item instanceof ICarpentersChisel) { ((ICarpentersChisel) item).onChiselUse(world, entityPlayer); } } /** * Returns whether side of block supports a cover. */ protected boolean canCoverSide(TEBase TE, World world, int x, int y, int z, int side) { return side == 6; } /** * Allows a tile entity called during block activation to be changed before * altering attributes like cover, dye, overlay, etc. * <p> * Primarily offered for the garage door, when open, to swap the top piece * with the bottom piece for consistency. * * @param TE the originating {@link TEBase} * @return a swapped in {@link TEBase}, or the passed in {@link TEBase} */ protected TEBase getTileEntityForBlockActivation(TEBase TE) { return TE; } }
src/main/java/com/carpentersblocks/block/BlockCoverable.java
package com.carpentersblocks.block; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.BlockDirectional; import net.minecraft.block.BlockRedstoneWire; import net.minecraft.block.material.Material; import net.minecraft.client.particle.EffectRenderer; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.boss.EntityDragon; import net.minecraft.entity.boss.EntityWither; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Direction; import net.minecraft.util.IIcon; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.client.ForgeHooksClient; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.common.IPlantable; import net.minecraftforge.common.util.ForgeDirection; import com.carpentersblocks.api.ICarpentersChisel; import com.carpentersblocks.api.ICarpentersHammer; import com.carpentersblocks.api.IWrappableBlock; import com.carpentersblocks.renderer.helper.FancyFluidsHelper; import com.carpentersblocks.renderer.helper.ParticleHelper; import com.carpentersblocks.tileentity.TEBase; import com.carpentersblocks.util.BlockProperties; import com.carpentersblocks.util.EntityLivingUtil; import com.carpentersblocks.util.handler.DesignHandler; import com.carpentersblocks.util.handler.EventHandler; import com.carpentersblocks.util.handler.OverlayHandler; import com.carpentersblocks.util.handler.OverlayHandler.Overlay; import com.carpentersblocks.util.protection.PlayerPermissions; import com.carpentersblocks.util.registry.FeatureRegistry; import com.carpentersblocks.util.registry.IconRegistry; import com.carpentersblocks.util.registry.ItemRegistry; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class BlockCoverable extends BlockContainer { /** Block drop event for dropping attribute. */ public static int EVENT_ID_DROP_ATTR = 0; /** Indicates during getDrops that block instance should not be dropped. */ protected final int METADATA_DROP_ATTR_ONLY = 16; /** Caches light values. */ public static Map<Integer,Integer> cache = new HashMap<Integer,Integer>(); /** * Stores actions taken on a block in order to properly play sounds, * decrement player inventory, and to determine if a block was altered. */ protected class ActionResult { public ItemStack itemStack; public boolean playSound = true; public boolean altered = false; public boolean decInv = false; public ActionResult setSoundSource(ItemStack itemStack) { this.itemStack = itemStack; return this; } public ActionResult setNoSound() { playSound = false; return this; } public ActionResult setAltered() { altered = true; return this; } public ActionResult decInventory() { decInv = true; return this; } } /** * Class constructor. * * @param material */ public BlockCoverable(Material material) { super(material); } @SideOnly(Side.CLIENT) @Override /** * When this method is called, your block should register all the icons it needs with the given IconRegister. This * is the only chance you get to register icons. */ public void registerBlockIcons(IIconRegister iconRegister) { } @SideOnly(Side.CLIENT) /** * Returns a base icon that doesn't rely on blockIcon, which * is set prior to texture stitch events. * * @return default icon */ public IIcon getIcon() { return IconRegistry.icon_uncovered_solid; } @SideOnly(Side.CLIENT) @Override /** * Returns the icon on the side given the block metadata. * <p> * Due to the amount of control needed over this, vanilla calls will always return an invisible icon. */ public IIcon getIcon(int side, int metadata) { if (BlockProperties.isMetadataDefaultIcon(metadata)) { return getIcon(); } /* * This icon is a mask (or something) for redstone wire. * We use it here because it renders an invisible icon. * * Using an invisible icon is important because sprint particles are * hard-coded and will always grab particle icons using this method. * We'll throw our own sprint particles in EventHandler.class. */ return BlockRedstoneWire.getRedstoneWireIcon("cross_overlay"); } @SideOnly(Side.CLIENT) @Override /** * Retrieves the block texture to use based on the display side. Args: iBlockAccess, x, y, z, side */ public IIcon getIcon(IBlockAccess blockAccess, int x, int y, int z, int side) { TEBase TE = getTileEntity(blockAccess, x, y, z); ItemStack itemStack = BlockProperties.getCover(TE, 6); Block block = BlockProperties.toBlock(itemStack); return block instanceof BlockCoverable ? getIcon() : getWrappedIcon(block, blockAccess, x, y, z, side, itemStack.getItemDamage()); } private static IIcon getWrappedIcon(Block b, IBlockAccess iba, int x, int y, int z, int side, int meta) { return b instanceof IWrappableBlock ? ((IWrappableBlock)b).getIcon(iba, x, y, z, side, b, meta) : b.getIcon(side, meta); } /** * For South-sided blocks, rotates and sets the block bounds using * the provided ForgeDirection. * * @param dir the rotated {@link ForgeDirection} */ protected void setBlockBounds(float minX, float minY, float minZ, float maxX, float maxY, float maxZ, ForgeDirection dir) { switch (dir) { case DOWN: setBlockBounds(minX, 1.0F - maxZ, minY, maxX, 1.0F - minZ, maxY); break; case UP: setBlockBounds(minX, minZ, minY, maxX, maxZ, maxY); break; case NORTH: setBlockBounds(1.0F - maxX, minY, 1.0F - maxZ, 1.0F - minX, maxY, 1.0F - minZ); break; case EAST: setBlockBounds(minZ, minY, 1.0F - maxX, maxZ, maxY, 1.0F - minX); break; case WEST: setBlockBounds(1.0F - maxZ, minY, minX, 1.0F - minZ, maxY, maxX); break; default: setBlockBounds(minX, minY, minZ, maxX, maxY, maxZ); break; } } /** * Called when block event is received. *<p> * For the context of this mod, this is used for dropping block attributes * like covers, overlays, dyes, or any other ItemStack. *<p> * In order for external classes to call the protected method * {@link Block#dropBlockAsItem(World,int,int,int,ItemStack) dropBlockAsItem}, * they create a block event with parameters itemId and metadata, allowing * the {@link ItemStack} to be recreated and dropped. * * @param world the {@link World} * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate * @param itemId the eventId, repurposed * @param metadata the event parameter, repurposed * @return true if event was handled */ @Override public boolean onBlockEventReceived(World world, int x, int y, int z, int eventId, int param /*attrId*/) { if (!world.isRemote && eventId == EVENT_ID_DROP_ATTR) { TEBase TE = getSimpleTileEntity(world, x, y, z); if (TE != null && TE.hasAttribute((byte) param)) { ItemStack itemStack = TE.getAttributeForDrop((byte) param); dropBlockAsItem(world, x, y, z, itemStack); TE.onAttrDropped((byte) param); return true; } } return super.onBlockEventReceived(world, x, y, z, eventId, param); } /** * Drops block as {@link ItemStack} and notifies relevant systems of * block removal. Block attributes will drop later in destruction. * <p> * This is usually called when a {@link #onNeighborBlockChange(World, int, int, int, Block) neighbor changes}. * * @param world the {@link World} * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate * @param dropBlock whether block {@link ItemStack} is dropped */ protected void destroyBlock(World world, int x, int y, int z, boolean dropBlock) { if (dropBlock) { dropBlockAsItem(world, x, y, z, new ItemStack(getItemDropped(0, world.rand, 0))); } world.setBlockToAir(x, y, z); } /** * Returns an item stack containing a single instance of the current block type. 'i' is the block's subtype/damage * and is ignored for blocks which do not support subtypes. Blocks which cannot be harvested should return null. */ protected ItemStack getItemDrop(World world, int metadata) { int fortune = 1; return new ItemStack(getItemDropped(metadata, world.rand, fortune), 1, metadata); } /** * Returns adjacent, similar tile entities that can be used for duplicating * block properties like dye color, pattern, style, etc. * * @param world the world reference * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate * @return an array of adjacent, similar tile entities * @see {@link TEBase} */ protected TEBase[] getAdjacentTileEntities(World world, int x, int y, int z) { return new TEBase[] { getSimpleTileEntity(world, x, y - 1, z), getSimpleTileEntity(world, x, y + 1, z), getSimpleTileEntity(world, x, y, z - 1), getSimpleTileEntity(world, x, y, z + 1), getSimpleTileEntity(world, x - 1, y, z), getSimpleTileEntity(world, x + 1, y, z) }; } /** * Returns tile entity if block tile entity is instanceof TEBase. * * Used for generic purposes such as getting pattern, dye color, or * cover of another Carpenter's block. Is also used if block * no longer exists, such as when breaking a block and ejecting * attributes. */ protected TEBase getSimpleTileEntity(IBlockAccess blockAccess, int x, int y, int z) { TileEntity TE = blockAccess.getTileEntity(x, y, z); return (TE instanceof TEBase) ? (TEBase) TE : null; } /** * Returns tile entity if block tile entity is instanceof TEBase and * also belongs to this block type. */ protected TEBase getTileEntity(IBlockAccess blockAccess, int x, int y, int z) { TEBase TE = getSimpleTileEntity(blockAccess, x, y, z); return TE != null && blockAccess.getBlock(x, y, z).equals(this) ? TE : null; } /** * Returns whether player is allowed to activate this block. */ protected boolean canPlayerActivate(TEBase TE, EntityPlayer entityPlayer) { return true; } @Override /** * Called when the block is clicked by a player. Args: x, y, z, entityPlayer */ public void onBlockClicked(World world, int x, int y, int z, EntityPlayer entityPlayer) { if (world.isRemote) { return; } TEBase TE = getTileEntity(world, x, y, z); if (TE == null) { return; } else if (!PlayerPermissions.canPlayerEdit(TE, TE.xCoord, TE.yCoord, TE.zCoord, entityPlayer)) { return; } ItemStack itemStack = entityPlayer.getCurrentEquippedItem(); if (itemStack == null) { return; } int effectiveSide = TE.hasAttribute(TE.ATTR_COVER[EventHandler.eventFace]) ? EventHandler.eventFace : 6; Item item = itemStack.getItem(); if (item instanceof ICarpentersHammer && ((ICarpentersHammer)item).canUseHammer(world, entityPlayer)) { ActionResult actionResult = new ActionResult(); preOnBlockClicked(TE, world, x, y, z, entityPlayer, actionResult); if (!actionResult.altered) { if (entityPlayer.isSneaking()) { popAttribute(TE, effectiveSide); } else { onHammerLeftClick(TE, entityPlayer); } actionResult.setAltered(); } else { onNeighborBlockChange(world, x, y, z, this); world.notifyBlocksOfNeighborChange(x, y, z, this); } } else if (item instanceof ICarpentersChisel && ((ICarpentersChisel)item).canUseChisel(world, entityPlayer)) { if (entityPlayer.isSneaking() && TE.hasChiselDesign(effectiveSide)) { TE.removeChiselDesign(effectiveSide); } else if (TE.hasAttribute(TE.ATTR_COVER[effectiveSide])) { onChiselClick(TE, effectiveSide, true); } } } /** * Pops attribute in hard-coded order. * * @param TE * @param side */ private void popAttribute(TEBase TE, int side) { if (TE.hasAttribute(TE.ATTR_ILLUMINATOR)) { TE.createBlockDropEvent(TE.ATTR_ILLUMINATOR); } else if (TE.hasAttribute(TE.ATTR_OVERLAY[side])) { TE.createBlockDropEvent(TE.ATTR_OVERLAY[side]); } else if (TE.hasAttribute(TE.ATTR_DYE[side])) { TE.createBlockDropEvent(TE.ATTR_DYE[side]); } else if (TE.hasAttribute(TE.ATTR_COVER[side])) { TE.createBlockDropEvent(TE.ATTR_COVER[side]); TE.removeChiselDesign(side); } } @Override /** * Called upon block activation (right click on the block.) */ public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityPlayer, int side, float hitX, float hitY, float hitZ) { if (world.isRemote) { return true; } else { TEBase TE = getTileEntity(world, x, y, z); if (TE == null) { return false; } if (!canPlayerActivate(TE, entityPlayer)) { return false; } // Allow block to change TE if needed before altering attributes TE = getTileEntityForBlockActivation(TE); ActionResult actionResult = new ActionResult(); preOnBlockActivated(TE, entityPlayer, side, hitX, hitY, hitZ, actionResult); // If no prior event occurred, try regular activation if (!actionResult.altered) { if (PlayerPermissions.canPlayerEdit(TE, TE.xCoord, TE.yCoord, TE.zCoord, entityPlayer)) { ItemStack itemStack = entityPlayer.getCurrentEquippedItem(); if (itemStack != null) { /* Sides 0-5 are side covers, and 6 is the base block. */ int effectiveSide = TE.hasAttribute(TE.ATTR_COVER[side]) ? side : 6; if (itemStack.getItem() instanceof ICarpentersHammer && ((ICarpentersHammer)itemStack.getItem()).canUseHammer(world, entityPlayer)) { if (onHammerRightClick(TE, entityPlayer)) { actionResult.setAltered(); } } else if (ItemRegistry.enableChisel && itemStack.getItem() instanceof ICarpentersChisel && ((ICarpentersChisel)itemStack.getItem()).canUseChisel(world, entityPlayer)) { if (TE.hasAttribute(TE.ATTR_COVER[effectiveSide])) { if (onChiselClick(TE, effectiveSide, false)) { actionResult.setAltered(); } } } else if (FeatureRegistry.enableCovers && BlockProperties.isCover(itemStack)) { Block block = BlockProperties.toBlock(itemStack); /* Will handle blocks that save directions using only y axis (pumpkin) */ int metadata = block instanceof BlockDirectional ? MathHelper.floor_double(entityPlayer.rotationYaw * 4.0F / 360.0F + 2.5D) & 3 : itemStack.getItemDamage(); /* Will handle blocks that save directions using all axes (logs, quartz) */ if (BlockProperties.blockRotates(itemStack)) { int rot = Direction.rotateOpposite[EntityLivingUtil.getRotationValue(entityPlayer)]; int side_interpolated = entityPlayer.rotationPitch < -45.0F ? 0 : entityPlayer.rotationPitch > 45 ? 1 : rot == 0 ? 3 : rot == 1 ? 4 : rot == 2 ? 2 : 5; metadata = block.onBlockPlaced(world, TE.xCoord, TE.yCoord, TE.zCoord, side_interpolated, hitX, hitY, hitZ, metadata); } ItemStack tempStack = itemStack.copy(); tempStack.setItemDamage(metadata); /* Base cover should always be checked. */ if (effectiveSide == 6 && (!canCoverSide(TE, world, TE.xCoord, TE.yCoord, TE.zCoord, 6) || TE.hasAttribute(TE.ATTR_COVER[6]))) { effectiveSide = side; } if (canCoverSide(TE, world, TE.xCoord, TE.yCoord, TE.zCoord, effectiveSide) && !TE.hasAttribute(TE.ATTR_COVER[effectiveSide])) { TE.addAttribute(TE.ATTR_COVER[effectiveSide], tempStack); actionResult.setAltered().decInventory().setSoundSource(itemStack); } } else if (entityPlayer.isSneaking()) { if (FeatureRegistry.enableIllumination && BlockProperties.isIlluminator(itemStack)) { if (!TE.hasAttribute(TE.ATTR_ILLUMINATOR)) { TE.addAttribute(TE.ATTR_ILLUMINATOR, itemStack); actionResult.setAltered().decInventory().setSoundSource(itemStack); } } else if (FeatureRegistry.enableOverlays && BlockProperties.isOverlay(itemStack)) { if (!TE.hasAttribute(TE.ATTR_OVERLAY[effectiveSide]) && (effectiveSide < 6 && TE.hasAttribute(TE.ATTR_COVER[effectiveSide]) || effectiveSide == 6)) { TE.addAttribute(TE.ATTR_OVERLAY[effectiveSide], itemStack); actionResult.setAltered().decInventory().setSoundSource(itemStack); } } else if (FeatureRegistry.enableDyeColors && BlockProperties.isDye(itemStack, false)) { if (!TE.hasAttribute(TE.ATTR_DYE[effectiveSide])) { TE.addAttribute(TE.ATTR_DYE[effectiveSide], itemStack); actionResult.setAltered().decInventory().setSoundSource(itemStack); } } } } } } if (!actionResult.altered) { // If no prior or regular event occurred, try a post event postOnBlockActivated(TE, entityPlayer, side, hitX, hitY, hitZ, actionResult); } else { if (actionResult.itemStack == null) { actionResult.setSoundSource(BlockProperties.getCover(TE, 6)); } damageItemWithChance(world, entityPlayer); onNeighborBlockChange(world, TE.xCoord, TE.yCoord, TE.zCoord, this); world.notifyBlocksOfNeighborChange(TE.xCoord, TE.yCoord, TE.zCoord, this); } if (actionResult.playSound) { BlockProperties.playBlockSound(TE.getWorldObj(), actionResult.itemStack, TE.xCoord, TE.yCoord, TE.zCoord, false); } if (actionResult.decInv) { EntityLivingUtil.decrementCurrentSlot(entityPlayer); } return actionResult.altered; } } /** * Cycles through chisel patterns. */ public boolean onChiselClick(TEBase TE, int side, boolean leftClick) { String design = TE.getChiselDesign(side); String designAdj = ""; if (design.equals("")) { World world = TE.getWorldObj(); /* Match pattern with adjacent pattern if possible. */ TEBase[] TE_list = getAdjacentTileEntities(world, TE.xCoord, TE.yCoord, TE.zCoord); for (TEBase TE_current : TE_list) { if (TE_current != null) { TE_current.getBlockType(); if (TE_current.hasChiselDesign(side)) { design = TE_current.getChiselDesign(side); designAdj = design; } } } } if (designAdj.equals("")) { design = leftClick ? DesignHandler.getPrev("chisel", design) : DesignHandler.getNext("chisel", design); } if (!design.equals("")) { TE.setChiselDesign(side, design); } return true; } @Override /** * Lets the block know when one of its neighbor changes. Doesn't know which neighbor changed (coordinates passed are * their own) Args: x, y, z, neighbor blockID */ public void onNeighborBlockChange(World world, int x, int y, int z, Block block) { /* This will check for and eject side covers that are obstructed. */ if (!world.isRemote) { TEBase TE = getTileEntity(world, x, y, z); if (TE != null) { for (int side = 0; side < 6; ++side) { if (TE.hasAttribute(TE.ATTR_COVER[side])) { if (!canCoverSide(TE, world, x, y, z, side)) { TE.removeAttributes(side); continue; } ForgeDirection dir = ForgeDirection.getOrientation(side); if (world.isSideSolid(x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ, dir.getOpposite()) && isSideSolid(world, x, y, z, dir)) { TE.removeAttributes(side); } } } } } } @Override /** * Returns true if the block is emitting indirect/weak redstone power on the specified side. If isBlockNormalCube * returns true, standard redstone propagation rules will apply instead and this will not be called. Args: World, X, * Y, Z, side. Note that the side is reversed - eg it is 1 (up) when checking the bottom of the block. */ public int isProvidingWeakPower(IBlockAccess blockAccess, int x, int y, int z, int side) { TEBase TE = getTileEntity(blockAccess, x, y, z); int power = 0; /* Indirect power is provided by any cover. */ if (TE != null) { for (int idx = 0; idx < 7; ++idx) { if (TE.hasAttribute(TE.ATTR_COVER[idx])) { Block block = BlockProperties.toBlock(BlockProperties.getCover(TE, idx)); int tempPower = block.isProvidingWeakPower(blockAccess, x, y, z, side); if (tempPower > power) { power = tempPower; } } } } return power; } @Override /** * Returns true if the block is emitting direct/strong redstone power on the specified side. Args: World, X, Y, Z, * side. Note that the side is reversed - eg it is 1 (up) when checking the bottom of the block. */ public int isProvidingStrongPower(IBlockAccess blockAccess, int x, int y, int z, int side) { TEBase TE = getTileEntity(blockAccess, x, y, z); int power = 0; /* Strong power is provided by the base cover, or a side cover if one exists. */ int effectiveSide = ForgeDirection.OPPOSITES[side]; if (BlockProperties.hasAttribute(TE, TE.ATTR_COVER[effectiveSide])) { Block block = BlockProperties.toBlock(BlockProperties.getCover(TE, effectiveSide)); int tempPower = block.isProvidingWeakPower(blockAccess, x, y, z, side); if (tempPower > power) { power = tempPower; } } else if (BlockProperties.hasAttribute(TE, TE.ATTR_COVER[6])) { Block block = BlockProperties.toBlock(BlockProperties.getCover(TE, 6)); int tempPower = block.isProvidingWeakPower(blockAccess, x, y, z, side); if (tempPower > power) { power = tempPower; } } return power; } /** * Indicates whether block destruction should be suppressed when block is clicked. * Will return true if player is holding a Carpenter's tool in creative mode. */ protected boolean suppressDestroyBlock(EntityPlayer entityPlayer) { ItemStack itemStack = entityPlayer.getHeldItem(); if (itemStack != null) { Item item = itemStack.getItem(); return entityPlayer.capabilities.isCreativeMode && item != null && (item instanceof ICarpentersHammer || item instanceof ICarpentersChisel); } return false; } @Override /** * Called when a player removes a block. * This controls block break behavior when a player in creative mode left-clicks on block while holding a Carpenter's Hammer */ public boolean removedByPlayer(World world, EntityPlayer entityPlayer, int x, int y, int z) { if (!suppressDestroyBlock(entityPlayer)) { return super.removedByPlayer(world, entityPlayer, x, y, z); } return false; } @Override @SideOnly(Side.CLIENT) /** * Spawn a digging particle effect in the world, this is a wrapper * around EffectRenderer.addBlockHitEffects to allow the block more * control over the particles. Useful when you have entirely different * texture sheets for different sides/locations in the world. * * @param world The current world * @param target The target the player is looking at {x/y/z/side/sub} * @param effectRenderer A reference to the current effect renderer. * @return True to prevent vanilla digging particles form spawning. */ public boolean addHitEffects(World world, MovingObjectPosition target, EffectRenderer effectRenderer) { TEBase TE = getTileEntity(world, target.blockX, target.blockY, target.blockZ); if (TE != null) { int effectiveSide = TE.hasAttribute(TE.ATTR_COVER[target.sideHit]) ? target.sideHit : 6; ItemStack itemStack = BlockProperties.getCover(TE, effectiveSide); if (BlockProperties.hasAttribute(TE, TE.ATTR_OVERLAY[effectiveSide])) { Overlay overlay = OverlayHandler.getOverlayType(TE.getAttribute(TE.ATTR_OVERLAY[effectiveSide])); if (OverlayHandler.coversFullSide(overlay, target.sideHit)) { itemStack = overlay.getItemStack(); } } Block block = BlockProperties.toBlock(itemStack); double xOffset = target.blockX + world.rand.nextDouble() * (block.getBlockBoundsMaxX() - block.getBlockBoundsMinX() - 0.1F * 2.0F) + 0.1F + block.getBlockBoundsMinX(); double yOffset = target.blockY + world.rand.nextDouble() * (block.getBlockBoundsMaxY() - block.getBlockBoundsMinY() - 0.1F * 2.0F) + 0.1F + block.getBlockBoundsMinY(); double zOffset = target.blockZ + world.rand.nextDouble() * (block.getBlockBoundsMaxZ() - block.getBlockBoundsMinZ() - 0.1F * 2.0F) + 0.1F + block.getBlockBoundsMinZ(); switch (target.sideHit) { case 0: yOffset = target.blockY + block.getBlockBoundsMinY() - 0.1D; break; case 1: yOffset = target.blockY + block.getBlockBoundsMaxY() + 0.1D; break; case 2: zOffset = target.blockZ + block.getBlockBoundsMinZ() - 0.1D; break; case 3: zOffset = target.blockZ + block.getBlockBoundsMaxZ() + 0.1D; break; case 4: xOffset = target.blockX + block.getBlockBoundsMinX() - 0.1D; break; case 5: xOffset = target.blockX + block.getBlockBoundsMaxX() + 0.1D; break; } ParticleHelper.addHitEffect(TE, target, xOffset, yOffset, zOffset, itemStack, effectRenderer); return true; } return super.addHitEffects(world, target, effectRenderer); } @Override @SideOnly(Side.CLIENT) /** * Renders block destruction effects. * This is controlled to prevent block destroy effects if left-clicked with a Carpenter's Hammer while player is in creative mode. * * Returns false to display effects. True suppresses them (backwards). */ public boolean addDestroyEffects(World world, int x, int y, int z, int metadata, EffectRenderer effectRenderer) { /* * We don't have the ability to accurately determine the entity that is * hitting the block. So, instead we're guessing based on who is * closest. This should be adequate most of the time. */ TEBase TE = getTileEntity(world, x, y, z); if (TE != null) { EntityPlayer entityPlayer = world.getClosestPlayer(x, y, z, 6.5F); if (entityPlayer != null) { if (!suppressDestroyBlock(entityPlayer)) { ParticleHelper.addDestroyEffect(world, x, y, z, BlockProperties.getCover(TE, 6), effectRenderer); } else { return true; } } } return false; } /** * Gets the current light value based on covers and illumination. * * @param blockAccess the {@link IBlockAccess} object * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate * @return a light value from 0 to 15 */ protected int getCurrentLightValue(IBlockAccess blockAccess, int x, int y, int z) { int lightValue = 0; TEBase TE = getTileEntity(blockAccess, x, y, z); if (TE != null) { if (FeatureRegistry.enableIllumination && TE.hasAttribute(TE.ATTR_ILLUMINATOR)) { lightValue = 15; } else { for (int side = 0; side < 7; ++side) { if (TE.hasAttribute(TE.ATTR_COVER[side])) { ItemStack itemStack = BlockProperties.getCover(TE, side); int tempLight = getLightValue(TE, BlockProperties.toBlock(itemStack), itemStack.getItemDamage()); lightValue = Math.max(tempLight, lightValue); } } } } return lightValue; } /** * Updates cached light value for block. * <b> * Several blocks may call for light values at once, and * grabbing the tile entity each time eats into performance. * * @param blockAccess the {@link IBlockAccess} object * @param x * @param y * @param z */ public void updateLightValue(IBlockAccess blockAccess, int x, int y, int z) { int lightValue = getCurrentLightValue(blockAccess, x, y, z); cache.put(BlockProperties.hashCoords(x, y, z), lightValue); } /** * Returns light value for block using two methods. First, it * checks if the static light value is not zero. If zero, it checks * using the block metadata. * * @param TE the {@link TEBase} * @param block the {@link Block} * @param metadata the block metadata * @return a light value from 0 to 15 */ protected int getLightValue(TEBase TE, Block block, int metadata) { /* Grab static light value */ int lightValue = block.getLightValue(); /* Try grabbing more accurate lighting using metadata */ if (lightValue == 0) { TE.setMetadata(metadata); lightValue = block.getLightValue(TE.getWorldObj(), TE.xCoord, TE.yCoord, TE.zCoord); TE.restoreMetadata(); } return lightValue; } @Override /** * Returns light value based on cover or side covers. */ public final int getLightValue(IBlockAccess blockAccess, int x, int y, int z) { int hash = BlockProperties.hashCoords(x, y, z); if (cache.containsKey(hash)) { return cache.get(hash); } return 0; } @Override /** * Returns the block hardness at a location. Args: world, x, y, z */ public float getBlockHardness(World world, int x, int y, int z) { TEBase TE = getTileEntity(world, x, y, z); if (BlockProperties.hasAttribute(TE, TE.ATTR_COVER[6])) { ItemStack is = BlockProperties.getCover(TE, 6); Block b = BlockProperties.toBlock(is); return b instanceof IWrappableBlock ? ((IWrappableBlock)b).getHardness(world, x, y, z, b, is.getItemDamage()) : b.getBlockHardness(world, x, y, z); } return blockHardness; } @Override /** * Chance that fire will spread and consume this block. */ public int getFlammability(IBlockAccess blockAccess, int x, int y, int z, ForgeDirection face) { TEBase TE = getTileEntity(blockAccess, x, y, z); if (TE != null) { ItemStack is = BlockProperties.getCover(TE, 6); Block b = BlockProperties.toBlock(is); return b instanceof IWrappableBlock ? ((IWrappableBlock)b).getFlammability(blockAccess, x, y, z, face, b, is.getItemDamage()) : Blocks.fire.getFlammability(b); } return super.getFlammability(blockAccess, x, y, z, face); } @Override /** * Called when fire is updating on a neighbor block. */ public int getFireSpreadSpeed(IBlockAccess blockAccess, int x, int y, int z, ForgeDirection side) { TEBase TE = getTileEntity(blockAccess, x, y, z); if (TE != null) { ItemStack is = BlockProperties.getCover(TE, 6); Block b = BlockProperties.toBlock(is); return b instanceof IWrappableBlock ? ((IWrappableBlock)b).getFireSpread(blockAccess, x, y, z, side, b, is.getItemDamage()) : Blocks.fire.getEncouragement(b); } return super.getFireSpreadSpeed(blockAccess, x, y, z, side); } @Override /** * Currently only called by fire when it is on top of this block. * Returning true will prevent the fire from naturally dying during updating. * Also prevents fire from dying from rain. */ public boolean isFireSource(World world, int x, int y, int z, ForgeDirection side) { TEBase TE = getTileEntity(world, x, y, z); if (BlockProperties.hasAttribute(TE, TE.ATTR_COVER[6])) { ItemStack is = BlockProperties.getCover(TE, 6); Block b = BlockProperties.toBlock(is); return b instanceof IWrappableBlock ? ((IWrappableBlock)b).sustainsFire(world, x, y, z, side, b, is.getItemDamage()) : b.isFireSource(world, x, y, z, side); } return false; } @Override /** * Location sensitive version of getExplosionRestance */ public float getExplosionResistance(Entity entity, World world, int x, int y, int z, double explosionX, double explosionY, double explosionZ) { TEBase TE = getTileEntity(world, x, y, z); if (BlockProperties.hasAttribute(TE, TE.ATTR_COVER[6])) { ItemStack is = BlockProperties.getCover(TE, 6); Block b = BlockProperties.toBlock(is); return b instanceof IWrappableBlock ? ((IWrappableBlock)b).getBlastResistance(entity, world, x, y, z, explosionX, explosionY, explosionZ, b, is.getItemDamage()) : b.getExplosionResistance(entity, world, x, y, z, explosionX, explosionY, explosionZ); } return this.getExplosionResistance(entity); } @Override /** * Returns whether block is wood */ public boolean isWood(IBlockAccess blockAccess, int x, int y, int z) { TEBase TE = getTileEntity(blockAccess, x, y, z); if (BlockProperties.hasAttribute(TE, TE.ATTR_COVER[6])) { ItemStack is = BlockProperties.getCover(TE, 6); Block b = BlockProperties.toBlock(is); return b instanceof IWrappableBlock ? ((IWrappableBlock)b).isLog(blockAccess, x, y, z, b, is.getItemDamage()) : b.isWood(blockAccess, x, y, z); } return super.isWood(blockAccess, x, y, z); } /** * Determines if this block is can be destroyed by the specified entities normal behavior. */ @Override public boolean canEntityDestroy(IBlockAccess blockAccess, int x, int y, int z, Entity entity) { TEBase TE = getTileEntity(blockAccess, x, y, z); if (BlockProperties.hasAttribute(TE, TE.ATTR_COVER[6])) { Block block = BlockProperties.toBlock(BlockProperties.getCover(TE, 6)); if (entity instanceof EntityWither) { return !block.equals(Blocks.bedrock) && !block.equals(Blocks.end_portal) && !block.equals(Blocks.end_portal_frame) && !block.equals(Blocks.command_block); } else if (entity instanceof EntityDragon) { return !block.equals(Blocks.obsidian) && !block.equals(Blocks.end_stone) && !block.equals(Blocks.bedrock); } } return super.canEntityDestroy(blockAccess, x, y, z, entity); } @Override /** * Triggered whenever an entity collides with this block (enters into the block). Args: world, x, y, z, entity */ public void onEntityCollidedWithBlock(World world, int x, int y, int z, Entity entity) { TEBase TE = getTileEntity(world, x, y, z); if (BlockProperties.hasAttribute(TE, TE.ATTR_COVER[6])) { BlockProperties.toBlock(BlockProperties.getCover(TE, 6)).onEntityCollidedWithBlock(world, x, y, z, entity); } } @Override /** * Spawns EntityItem in the world for the given ItemStack if the world is not remote. */ protected void dropBlockAsItem(World world, int x, int y, int z, ItemStack itemStack) { // Clear metadata for Carpenter's blocks Block block = BlockProperties.toBlock(itemStack); if (block instanceof BlockCoverable) { itemStack.setItemDamage(0); } super.dropBlockAsItem(world, x, y, z, itemStack); } @Override /** * Ejects contained items into the world, and notifies neighbors of an update, as appropriate */ public void breakBlock(World world, int x, int y, int z, Block block, int metadata) { // Remove cached light value cache.remove(BlockProperties.hashCoords(x, y,z )); super.breakBlock(world, x, y, z, block, metadata); } /** * This returns a complete list of items dropped from this block. * * @param world The current world * @param x X Position * @param y Y Position * @param z Z Position * @param metadata Current metadata * @param fortune Breakers fortune level * @return A ArrayList containing all items this block drops */ @Override public ArrayList<ItemStack> getDrops(World world, int x, int y, int z, int metadata, int fortune) { ArrayList<ItemStack> ret = super.getDrops(world, x, y, z, metadata, fortune); TEBase TE = getSimpleTileEntity(world, x, y, z); if (metadata == METADATA_DROP_ATTR_ONLY) { ret.clear(); // Remove block instance from drop list } if (TE != null) { for (int idx = 0; idx < 7; ++idx) { if (TE.hasAttribute(TE.ATTR_COVER[idx])) { ret.add(TE.getAttributeForDrop(TE.ATTR_COVER[idx])); } if (TE.hasAttribute(TE.ATTR_OVERLAY[idx])) { ret.add(TE.getAttributeForDrop(TE.ATTR_OVERLAY[idx])); } if (TE.hasAttribute(TE.ATTR_DYE[idx])) { ret.add(TE.getAttributeForDrop(TE.ATTR_DYE[idx])); } } if (TE.hasAttribute(TE.ATTR_ILLUMINATOR)) { ret.add(TE.getAttributeForDrop(TE.ATTR_ILLUMINATOR)); } } return ret; } @Override @SideOnly(Side.CLIENT) /** * A randomly called display update to be able to add particles or other items for display */ public void randomDisplayTick(World world, int x, int y, int z, Random random) { TEBase TE = getTileEntity(world, x, y, z); if (TE != null) { if (TE.hasAttribute(TE.ATTR_COVER[6])) { BlockProperties.toBlock(BlockProperties.getCover(TE, 6)).randomDisplayTick(world, x, y, z, random); } if (TE.hasAttribute(TE.ATTR_OVERLAY[6])) { if (OverlayHandler.getOverlayType(TE.getAttribute(TE.ATTR_OVERLAY[6])).equals(Overlay.MYCELIUM)) { Blocks.mycelium.randomDisplayTick(world, x, y, z, random); } } } } /** * Determines if this block can support the passed in plant, allowing it to be planted and grow. * Some examples: * Reeds check if its a reed, or if its sand/dirt/grass and adjacent to water * Cacti checks if its a cacti, or if its sand * Nether types check for soul sand * Crops check for tilled soil * Caves check if it's a solid surface * Plains check if its grass or dirt * Water check if its still water * * @param blockAccess The current world * @param x X Position * @param y Y Position * @param z Z position * @param side The direction relative to the given position the plant wants to be, typically its UP * @param plantable The plant that wants to check * @return True to allow the plant to be planted/stay. */ @Override public boolean canSustainPlant(IBlockAccess blockAccess, int x, int y, int z, ForgeDirection side, IPlantable plantable) { TEBase TE = getTileEntity(blockAccess, x, y, z); if (TE != null) { /* If side is not solid, it can't sustain a plant. */ if (!isSideSolid(blockAccess, x, y, z, side)) { return false; } /* * Add base block, top block, and both of their associated * overlays to judge whether plants can be supported on block. */ List<Block> blocks = new ArrayList<Block>(); for (int side1 = 1; side1 < 7; side1 += 5) { if (TE.hasAttribute(TE.ATTR_COVER[side1])) { blocks.add(BlockProperties.toBlock(BlockProperties.getCover(TE, side1))); } if (TE.hasAttribute(TE.ATTR_OVERLAY[side1])) { blocks.add(BlockProperties.toBlock(OverlayHandler.getOverlayType(TE.getAttribute(TE.ATTR_OVERLAY[side1])).getItemStack())); } } /* Add types using cover material */ Material material = BlockProperties.toBlock(BlockProperties.getCover(TE, 6)).getMaterial(); if (material.equals(Material.grass)) { blocks.add(Blocks.grass); } else if (material.equals(Material.ground)) { blocks.add(Blocks.dirt); } else if (material.equals(Material.sand)) { blocks.add(Blocks.sand); } switch (plantable.getPlantType(blockAccess, x, y + 1, z)) { case Desert: return blocks.contains(Blocks.sand); case Nether: return blocks.contains(Blocks.soul_sand); case Plains: return blocks.contains(Blocks.grass) || blocks.contains(Blocks.dirt); case Beach: boolean isBeach = blocks.contains(Blocks.grass) || blocks.contains(Blocks.dirt) || blocks.contains(Blocks.sand); boolean hasWater = blockAccess.getBlock(x - 1, y, z ).getMaterial() == Material.water || blockAccess.getBlock(x + 1, y, z ).getMaterial() == Material.water || blockAccess.getBlock(x, y, z - 1).getMaterial() == Material.water || blockAccess.getBlock(x, y, z + 1).getMaterial() == Material.water; return isBeach && hasWater; default: break; } } return super.canSustainPlant(blockAccess, x, y, z, side, plantable); } /** * Returns whether this block is considered solid. */ protected boolean isBlockSolid(IBlockAccess blockAccess, int x, int y, int z) { TEBase TE = getTileEntity(blockAccess, x, y, z); if (TE != null) { return !TE.hasAttribute(TE.ATTR_COVER[6]) || BlockProperties.toBlock(BlockProperties.getCover(TE, 6)).isOpaqueCube(); } else { return false; } } @Override /** * Called when the block is placed in the world. */ public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entityLiving, ItemStack itemStack) { if (!world.isRemote) { TEBase TE = getTileEntity(world, x, y, z); if (TE != null) { TE.setOwner(entityLiving.getUniqueID()); } } } @Override /** * Gets the hardness of block at the given coordinates in the given world, relative to the ability of the given * EntityPlayer. */ public float getPlayerRelativeBlockHardness(EntityPlayer entityPlayer, World world, int x, int y, int z) { /* Don't damage block if holding Carpenter's tool. */ ItemStack itemStack = entityPlayer.getHeldItem(); if (itemStack != null) { Item item = itemStack.getItem(); if (item instanceof ICarpentersHammer || item instanceof ICarpentersChisel) { return -1; } } /* Return block hardness of cover. */ TEBase TE = getTileEntity(world, x, y, z); if (TE != null) { return ForgeHooks.blockStrength(BlockProperties.toBlock(BlockProperties.getCover(TE, 6)), entityPlayer, world, x, y, z); } else { return super.getPlayerRelativeBlockHardness(entityPlayer, world, x, y, z); } } @SideOnly(Side.CLIENT) @Override public int colorMultiplier(IBlockAccess blockAccess, int x, int y, int z) { TEBase TE = getTileEntity(blockAccess, x, y, z); if (TE != null) { ItemStack itemStack = BlockProperties.getCover(TE, 6); Block block = BlockProperties.toBlock(itemStack); if (!(block instanceof BlockCoverable)) { return block instanceof IWrappableBlock ? ((IWrappableBlock)block).getColorMultiplier(blockAccess, x, y, z, block, itemStack.getItemDamage()) : block.colorMultiplier(blockAccess, x, y, z); } } return super.colorMultiplier(blockAccess, x, y, z); } @Override @SideOnly(Side.CLIENT) /** * Returns true if the given side of this block type should be rendered, if the adjacent block is at the given * coordinates. Args: world, x, y, z, side */ public boolean shouldSideBeRendered(IBlockAccess blockAccess, int x, int y, int z, int side) { // Side checks in out-of-range areas will crash if (y > 0 && y < blockAccess.getHeight()) { TEBase TE = getTileEntity(blockAccess, x, y, z); if (TE != null) { ForgeDirection side_src = ForgeDirection.getOrientation(side); ForgeDirection side_adj = side_src.getOpposite(); TEBase TE_adj = (TEBase) blockAccess.getTileEntity(x, y, z); TEBase TE_src = (TEBase) blockAccess.getTileEntity(x + side_adj.offsetX, y + side_adj.offsetY, z + side_adj.offsetZ); if (TE_adj.getBlockType().isSideSolid(blockAccess, x, y, z, side_adj) == TE_src.getBlockType().isSideSolid(blockAccess, x + side_adj.offsetX, y + side_adj.offsetY, z + side_adj.offsetZ, ForgeDirection.getOrientation(side))) { if (shareFaces(TE_adj, TE_src, side_adj, side_src)) { Block block_adj = BlockProperties.toBlock(BlockProperties.getCover(TE_adj, 6)); Block block_src = BlockProperties.toBlock(BlockProperties.getCover(TE_src, 6)); if (!TE_adj.hasAttribute(TE.ATTR_COVER[6])) { return TE_src.hasAttribute(TE.ATTR_COVER[6]); } else { if (!TE_src.hasAttribute(TE.ATTR_COVER[6]) && block_adj.getRenderBlockPass() == 0) { return !block_adj.isOpaqueCube(); } else if (TE_src.hasAttribute(TE.ATTR_COVER[6]) && block_src.isOpaqueCube() == block_adj.isOpaqueCube() && block_src.getRenderBlockPass() == block_adj.getRenderBlockPass()) { return false; } else { return true; } } } } } } return super.shouldSideBeRendered(blockAccess, x, y, z, side); } @Override /** * Determines if this block should render in this pass. */ public boolean canRenderInPass(int pass) { ForgeHooksClient.setRenderPass(pass); return true; } @Override @SideOnly(Side.CLIENT) /** * Returns which pass this block be rendered on. 0 for solids and 1 for alpha. */ public int getRenderBlockPass() { /* * Alpha properties of block or cover depend on this returning a value * of 1, so it's the default value. However, when rendering in player * hand we'll encounter sorting artifacts, and thus need to enforce * opaque rendering, or 0. */ if (ForgeHooksClient.getWorldRenderPass() < 0) { return 0; } else { return 1; } } /** * Returns whether two blocks share faces. * Primarily for slopes, stairs and slabs. */ protected boolean shareFaces(TEBase TE_adj, TEBase TE_src, ForgeDirection side_adj, ForgeDirection side_src) { return TE_adj.getBlockType().isSideSolid(TE_adj.getWorldObj(), TE_adj.xCoord, TE_adj.yCoord, TE_adj.zCoord, side_adj) && TE_src.getBlockType().isSideSolid(TE_src.getWorldObj(), TE_src.xCoord, TE_src.yCoord, TE_src.zCoord, side_src); } @Override /** * Is this block (a) opaque and (b) a full 1m cube? This determines whether or not to render the shared face of two * adjacent blocks and also whether the player can attach torches, redstone wire, etc to this block. */ public boolean isOpaqueCube() { if (FMLCommonHandler.instance().getEffectiveSide().isServer()) { return false; } if (FeatureRegistry.enableRoutableFluids) { Class<?> clazz = FancyFluidsHelper.getCallerClass(); if (clazz != null) { for (Class clazz1 : FancyFluidsHelper.liquidClasses) { if (clazz.isAssignableFrom(clazz1)) { return true; } } } } return false; } @Override /** * If this block doesn't render as an ordinary block it will return False (examples: signs, buttons, stairs, etc) */ public boolean renderAsNormalBlock() { return false; } /** * Should block use the brightest neighbor light value as its own */ @Override public boolean getUseNeighborBrightness() { return true; } @Override /** * Called whenever the block is added into the world. Args: world, x, y, z */ public void onBlockAdded(World world, int x, int y, int z) { world.setTileEntity(x, y, z, createNewTileEntity(world, 0)); updateLightValue(world, x, y, z); } @Override public TileEntity createNewTileEntity(World world, int metadata) { return new TEBase(); } @Override public boolean hasTileEntity(int metadata) { return true; } /** * This method is configured on as as-needed basis. * It's calling order is not guaranteed. */ protected void preOnBlockClicked(TEBase TE, World world, int x, int y, int z, EntityPlayer entityPlayer, ActionResult actionResult) {} /** * Called before cover or decoration checks are performed. */ protected void preOnBlockActivated(TEBase TE, EntityPlayer entityPlayer, int side, float hitX, float hitY, float hitZ, ActionResult actionResult) {} /** * Called if cover and decoration checks have been performed but * returned no changes. */ protected void postOnBlockActivated(TEBase TE, EntityPlayer entityPlayer, int side, float hitX, float hitY, float hitZ, ActionResult actionResult) {} protected boolean onHammerLeftClick(TEBase TE, EntityPlayer entityPlayer) { return false; } protected boolean onHammerRightClick(TEBase TE, EntityPlayer entityPlayer) { return false; } protected void damageItemWithChance(World world, EntityPlayer entityPlayer) { Item item = entityPlayer.getCurrentEquippedItem().getItem(); if (item instanceof ICarpentersHammer) { ((ICarpentersHammer) item).onHammerUse(world, entityPlayer); } else if (item instanceof ICarpentersChisel) { ((ICarpentersChisel) item).onChiselUse(world, entityPlayer); } } /** * Returns whether side of block supports a cover. */ protected boolean canCoverSide(TEBase TE, World world, int x, int y, int z, int side) { return side == 6; } /** * Allows a tile entity called during block activation to be changed before * altering attributes like cover, dye, overlay, etc. * <p> * Primarily offered for the garage door, when open, to swap the top piece * with the bottom piece for consistency. * * @param TE the originating {@link TEBase} * @return a swapped in {@link TEBase}, or the passed in {@link TEBase} */ protected TEBase getTileEntityForBlockActivation(TEBase TE) { return TE; } }
Set non-zero light level to hopefully address mob spawns. Block drops refactored to address bugs.
src/main/java/com/carpentersblocks/block/BlockCoverable.java
Set non-zero light level to hopefully address mob spawns. Block drops refactored to address bugs.
<ide><path>rc/main/java/com/carpentersblocks/block/BlockCoverable.java <ide> public BlockCoverable(Material material) <ide> { <ide> super(material); <add> setLightLevel(1.0F); // Make mob spawns check block light value <ide> } <ide> <ide> @SideOnly(Side.CLIENT) <ide> } <ide> <ide> /** <del> * Drops block as {@link ItemStack} and notifies relevant systems of <del> * block removal. Block attributes will drop later in destruction. <del> * <p> <del> * This is usually called when a {@link #onNeighborBlockChange(World, int, int, int, Block) neighbor changes}. <del> * <del> * @param world the {@link World} <del> * @param x the x coordinate <del> * @param y the y coordinate <del> * @param z the z coordinate <del> * @param dropBlock whether block {@link ItemStack} is dropped <del> */ <del> protected void destroyBlock(World world, int x, int y, int z, boolean dropBlock) <del> { <del> if (dropBlock) { <del> dropBlockAsItem(world, x, y, z, new ItemStack(getItemDropped(0, world.rand, 0))); <del> } <del> world.setBlockToAir(x, y, z); <del> } <del> <del> /** <ide> * Returns an item stack containing a single instance of the current block type. 'i' is the block's subtype/damage <ide> * and is ignored for blocks which do not support subtypes. Blocks which cannot be harvested should return null. <ide> */ <ide> <ide> <ide> return power; <del> } <del> <del> /** <del> * Indicates whether block destruction should be suppressed when block is clicked. <del> * Will return true if player is holding a Carpenter's tool in creative mode. <del> */ <del> protected boolean suppressDestroyBlock(EntityPlayer entityPlayer) <del> { <del> ItemStack itemStack = entityPlayer.getHeldItem(); <del> <del> if (itemStack != null) { <del> Item item = itemStack.getItem(); <del> return entityPlayer.capabilities.isCreativeMode && item != null && (item instanceof ICarpentersHammer || item instanceof ICarpentersChisel); <del> } <del> <del> return false; <del> } <del> <del> @Override <del> /** <del> * Called when a player removes a block. <del> * This controls block break behavior when a player in creative mode left-clicks on block while holding a Carpenter's Hammer <del> */ <del> public boolean removedByPlayer(World world, EntityPlayer entityPlayer, int x, int y, int z) <del> { <del> if (!suppressDestroyBlock(entityPlayer)) { <del> return super.removedByPlayer(world, entityPlayer, x, y, z); <del> } <del> <del> return false; <ide> } <ide> <ide> @Override <ide> <ide> @Override <ide> /** <add> * Called when the player destroys a block with an item that can harvest it. (i, j, k) are the coordinates of the <add> * block and l is the block's subtype/damage. <add> */ <add> public void harvestBlock(World p_149636_1_, EntityPlayer p_149636_2_, int p_149636_3_, int p_149636_4_, int p_149636_5_, int p_149636_6_) {} <add> <add> /** <add> * Indicates whether block destruction should be suppressed when block is clicked. <add> * Will return true if player is holding a Carpenter's tool in creative mode. <add> */ <add> protected boolean suppressDestroyBlock(EntityPlayer entityPlayer) <add> { <add> if (entityPlayer == null) { <add> return false; <add> } <add> <add> ItemStack itemStack = entityPlayer.getHeldItem(); <add> <add> if (itemStack != null) { <add> Item item = itemStack.getItem(); <add> return entityPlayer.capabilities.isCreativeMode && item != null && (item instanceof ICarpentersHammer || item instanceof ICarpentersChisel); <add> } <add> <add> return false; <add> } <add> <add> /** <add> * Drops block as {@link ItemStack} and notifies relevant systems of <add> * block removal. Block attributes will drop later in destruction. <add> * <p> <add> * This is usually called when a {@link #onNeighborBlockChange(World, int, int, int, Block) neighbor changes}. <add> * <add> * @param world the {@link World} <add> * @param x the x coordinate <add> * @param y the y coordinate <add> * @param z the z coordinate <add> * @param dropBlock whether block {@link ItemStack} is dropped <add> */ <add> protected void destroyBlock(World world, int x, int y, int z, boolean dropBlock) <add> { <add> // Drop attributes <add> int metadata = dropBlock ? 0 : METADATA_DROP_ATTR_ONLY; <add> ArrayList<ItemStack> items = getDrops(world, x, y, z, metadata, 0); <add> for (ItemStack item : items) { <add> dropBlockAsItem(world, x, y, z, item); <add> } <add> <add> world.setBlockToAir(x, y, z); <add> } <add> <add> @Override <add> /** <add> * Called when a player removes a block. This is responsible for <add> * actually destroying the block, and the block is intact at time of call. <add> * This is called regardless of whether the player can harvest the block or <add> * not. <add> * <add> * Return true if the block is actually destroyed. <add> * <add> * Note: When used in multiplayer, this is called on both client and <add> * server sides! <add> * <add> * @param world The current world <add> * @param player The player damaging the block, may be null <add> * @param x X Position <add> * @param y Y position <add> * @param z Z position <add> * @param willHarvest True if Block.harvestBlock will be called after this, if the return in true. <add> * Can be useful to delay the destruction of tile entities till after harvestBlock <add> * @return True if the block is actually destroyed. <add> */ <add> public boolean removedByPlayer(World world, EntityPlayer entityPlayer, int x, int y, int z, boolean willHarvest) <add> { <add> if (world.isRemote) { <add> return super.removedByPlayer(world, entityPlayer, x, y, z, willHarvest); <add> } <add> <add> // Grab drops while tile entity exists (before calling super) <add> int metadata = entityPlayer != null && entityPlayer.capabilities.isCreativeMode ? METADATA_DROP_ATTR_ONLY : 0; <add> ArrayList<ItemStack> items = getDrops(world, x, y, z, metadata, 0); <add> <add> // Drop attributes if block destroyed, and no Carpenter's Tool is held by entity <add> if (!suppressDestroyBlock(entityPlayer) && super.removedByPlayer(world, entityPlayer, x, y, z, willHarvest)) { <add> for (ItemStack item : items) { <add> dropBlockAsItem(world, x, y, z, item); <add> } <add> return true; <add> } <add> <add> return false; <add> } <add> <add> @Override <add> /** <ide> * Ejects contained items into the world, and notifies neighbors of an update, as appropriate <ide> */ <ide> public void breakBlock(World world, int x, int y, int z, Block block, int metadata) <ide> { <ide> // Remove cached light value <del> cache.remove(BlockProperties.hashCoords(x, y,z )); <add> cache.remove(BlockProperties.hashCoords(x, y, z)); <ide> <ide> super.breakBlock(world, x, y, z, block, metadata); <ide> } <ide> @Override <ide> public ArrayList<ItemStack> getDrops(World world, int x, int y, int z, int metadata, int fortune) <ide> { <del> ArrayList<ItemStack> ret = super.getDrops(world, x, y, z, metadata, fortune); <add> ArrayList<ItemStack> ret = super.getDrops(world, x, y, z, metadata, fortune); // Add block item drop <ide> TEBase TE = getSimpleTileEntity(world, x, y, z); <ide> <ide> if (metadata == METADATA_DROP_ATTR_ONLY) { <ide> ret.clear(); // Remove block instance from drop list <ide> } <ide> <del> if (TE != null) { <add> if (TE != null) <add> { <ide> for (int idx = 0; idx < 7; ++idx) { <ide> if (TE.hasAttribute(TE.ATTR_COVER[idx])) { <ide> ret.add(TE.getAttributeForDrop(TE.ATTR_COVER[idx]));
Java
apache-2.0
c58ecdafbeeed5b240f1a67e7935e765c0523510
0
jeorme/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,nssales/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,codeaudit/OG-Platform,ChinaQuants/OG-Platform,ChinaQuants/OG-Platform,jerome79/OG-Platform,jeorme/OG-Platform,nssales/OG-Platform,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,codeaudit/OG-Platform,codeaudit/OG-Platform,jerome79/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,jerome79/OG-Platform,McLeodMoores/starling,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,codeaudit/OG-Platform,jeorme/OG-Platform,jerome79/OG-Platform,McLeodMoores/starling,nssales/OG-Platform
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.masterdb.batch; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Maps.newHashMap; import static java.util.Collections.emptyList; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.time.Instant; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Factory; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.opengamma.DataNotFoundException; import com.opengamma.batch.RunCreationMode; import com.opengamma.batch.SnapshotMode; import com.opengamma.batch.domain.FunctionUniqueId; import com.opengamma.batch.domain.HbComputationTargetSpecification; import com.opengamma.batch.domain.MarketData; import com.opengamma.batch.domain.MarketDataValue; import com.opengamma.batch.domain.RiskRun; import com.opengamma.batch.domain.RiskValueSpecification; import com.opengamma.core.security.Security; import com.opengamma.core.security.impl.SimpleSecurity; import com.opengamma.engine.ComputationTargetSpecification; import com.opengamma.engine.ComputationTargetType; import com.opengamma.engine.value.ComputedValueResult; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.engine.view.InMemoryViewComputationResultModel; import com.opengamma.engine.view.ViewComputationResultModel; import com.opengamma.engine.view.calc.ViewCycleMetadata; import com.opengamma.engine.view.calcnode.ExecutionLog; import com.opengamma.engine.view.calcnode.InvocationResult; import com.opengamma.id.ExternalId; import com.opengamma.id.ExternalIdBundle; import com.opengamma.id.ObjectId; import com.opengamma.id.UniqueId; import com.opengamma.id.VersionCorrection; import com.opengamma.masterdb.DbMasterTestUtils; import com.opengamma.util.paging.PagingRequest; import com.opengamma.util.test.DbTest; /** * Test DbBatchWriter. */ public class DbBatchWriterTest extends DbTest { private DbBatchMaster _batchMaster; private DbBatchWriter _batchWriter; private ViewCycleMetadata _cycleMetadataStub; private ComputationTargetSpecification _compTargetSpec; private ValueRequirement _requirement; private ValueSpecification _specification; @Factory(dataProvider = "databases", dataProviderClass = DbTest.class) public DbBatchWriterTest(String databaseType, String databaseVersion) { super(databaseType, databaseVersion, databaseVersion); } @BeforeMethod public void setUp() throws Exception { super.setUp(); ConfigurableApplicationContext context = DbMasterTestUtils.getContext(getDatabaseType()); _batchMaster = (DbBatchMaster) context.getBean(getDatabaseType() + "DbBatchMaster"); _batchWriter = new DbBatchWriter(_batchMaster.getDbConnector()); final String calculationConfigName = "config_1"; _compTargetSpec = new ComputationTargetSpecification(ComputationTargetType.SECURITY, UniqueId.of("Sec", "APPL")); final Security security = new SimpleSecurity(_compTargetSpec.getUniqueId(), ExternalIdBundle.of("Sec", "APPL"), "equity", "APPL"); _requirement = new ValueRequirement("FAIR_VALUE", security); _specification = new ValueSpecification(_requirement, "IDENTITY_FUNCTION"); final Instant _valuationTime = Instant.parse("2011-12-14T14:20:17.143Z"); _cycleMetadataStub = new ViewCycleMetadata() { @Override public UniqueId getViewCycleId() { return UniqueId.of("viewcycle", "viewcycle", "viewcycle"); } @Override public Collection<String> getAllCalculationConfigurationNames() { return newArrayList(calculationConfigName); } @Override public Collection<com.opengamma.engine.ComputationTargetSpecification> getComputationTargets(String calcConfName) { if (calcConfName.equals(calculationConfigName)) { return Arrays.asList(new ComputationTargetSpecification(UniqueId.of("Primitive", "Value")), _compTargetSpec); } else { return emptyList(); } } @Override public Map<ValueSpecification, Set<ValueRequirement>> getTerminalOutputs(String calcConfName) { return ImmutableMap.<ValueSpecification, Set<ValueRequirement>>of(_specification, ImmutableSet.of(_requirement)); } @Override public UniqueId getMarketDataSnapshotId() { return UniqueId.of("snapshot", "snapshot", "snapshot"); } @Override public Instant getValuationTime() { return _valuationTime; } @Override public VersionCorrection getVersionCorrection() { return VersionCorrection.LATEST; } @Override public UniqueId getViewDefinitionId() { return UniqueId.of("viewdef", "viewdef", "viewdef"); } }; } //------------------------------------------------------------------------- @Test(expectedExceptions = IllegalArgumentException.class) public void addValuesToNonexistentSnapshot() { _batchMaster.addValuesToMarketData(ObjectId.of("nonexistent", "nonexistent"), Collections.<MarketDataValue>emptySet()); } @Test public void addValuesToIncompleteSnapshot() { MarketData marketData = _batchWriter.createOrGetMarketDataInTransaction(_cycleMetadataStub.getMarketDataSnapshotId()); _batchMaster.addValuesToMarketData(marketData.getObjectId(), Collections.<MarketDataValue>emptySet()); List<MarketDataValue> marketDataValues = _batchMaster.getMarketDataValues(marketData.getObjectId(), PagingRequest.ALL).getFirst(); assertNotNull(marketDataValues); assertEquals(0, marketDataValues.size()); final Set<ComputationTargetSpecification> specs = Sets.newHashSet(); specs.add(new ComputationTargetSpecification(UniqueId.of("BUID", "EQ12345", null))); specs.add(new ComputationTargetSpecification(UniqueId.of("BUID", "EQ12346", "1"))); specs.add(new ComputationTargetSpecification(UniqueId.of("BUID", "EQ12347", "2"))); final Map<ComputationTargetSpecification, Long> compTargetSpecIdx = new HashMap<ComputationTargetSpecification, Long>(); final Map<Long, ComputationTargetSpecification> reversedCompTargetSpecIdx = new HashMap<Long, ComputationTargetSpecification>(); _batchMaster.getDbConnector().getTransactionTemplate().execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { // manually populationg db with computation targets for (ComputationTargetSpecification spec : specs) { HbComputationTargetSpecification hbComputationTargetSpecification = _batchWriter.getOrCreateComputationTargetInTransaction(spec); compTargetSpecIdx.put(spec, hbComputationTargetSpecification.getId()); reversedCompTargetSpecIdx.put(hbComputationTargetSpecification.getId(), spec); } return null; } }); Set<MarketDataValue> values = new HashSet<MarketDataValue>(); for (ComputationTargetSpecification spec : specs) { values.add(new MarketDataValue(spec, 123.45, "value_name")); } _batchMaster.addValuesToMarketData(marketData.getObjectId(), values); marketDataValues = _batchMaster.getMarketDataValues(marketData.getObjectId(), PagingRequest.ALL).getFirst(); assertEquals(specs.size(), marketDataValues.size()); Map<Long, MarketDataValue> marketDataValuesMap = newHashMap(); for (MarketDataValue value : marketDataValues) { marketDataValuesMap.put(value.getComputationTargetSpecificationId(), value); } for (ComputationTargetSpecification spec : specs) { Long targetSpecificationId = compTargetSpecIdx.get(spec); MarketDataValue marketDataValue = marketDataValuesMap.get(targetSpecificationId); assertNotNull(marketDataValue); assertEquals(spec, reversedCompTargetSpecIdx.get(marketDataValue.getComputationTargetSpecificationId())); assertEquals("value_name", marketDataValue.getName()); assertEquals(123.45, marketDataValue.getValue(), 0.000001); } // should not add anything extra _batchMaster.addValuesToMarketData(marketData.getObjectId(), values); marketDataValues = _batchMaster.getMarketDataValues(marketData.getObjectId(), PagingRequest.ALL).getFirst(); assertEquals(3, marketDataValues.size()); // should update 2, add 1 values = new HashSet<MarketDataValue>(); values.add(new MarketDataValue(new ComputationTargetSpecification(UniqueId.of("BUID", "EQ12345", null)), 123.46, "value_name")); values.add(new MarketDataValue(new ComputationTargetSpecification(UniqueId.of("BUID", "EQ12347", "2")), 123.47, "value_name")); values.add(new MarketDataValue(new ComputationTargetSpecification(ExternalId.of("BUID", "EQ12348")), 123.45, "value_name")); _batchMaster.addValuesToMarketData(marketData.getObjectId(), values); marketDataValues = _batchMaster.getMarketDataValues(marketData.getObjectId(), PagingRequest.ALL).getFirst(); assertEquals(4, marketDataValues.size()); } /*@Test public void fixLiveDataSnapshotTime() { _batchMaster.createLiveDataSnapshot(_batch.getBatchId().getBatchSnapshotId()); _batchMaster.fixLiveDataSnapshotTime(_batch.getBatchId().getBatchSnapshotId(), OffsetTime.now()); }*/ /*@Test(expectedExceptions = IllegalArgumentException.class) public void tryToFixNonexistentLiveDataSnapshotTime() { _batchMaster.fixLiveDataSnapshotTime(_batch.getBatchId().getBatchSnapshotId(), OffsetTime.now()); }*/ @Test public void createLiveDataSnapshotMultipleTimes() { final UniqueId marketDataUid = _cycleMetadataStub.getMarketDataSnapshotId(); _batchMaster.createMarketData(marketDataUid); _batchMaster.createMarketData(marketDataUid); _batchMaster.getDbConnector().getTransactionTemplate().execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { assertNotNull(_batchWriter.createOrGetMarketDataInTransaction(marketDataUid)); return null; } }); } @Test public void createThenGetRiskRun() { final UniqueId marketDataUid = _cycleMetadataStub.getMarketDataSnapshotId(); _batchMaster.createMarketData(marketDataUid); RiskRun run = _batchMaster.startRiskRun(_cycleMetadataStub, Maps.<String, String>newHashMap(), RunCreationMode.AUTO, SnapshotMode.PREPARED); RiskRun run2 = _batchWriter.getRiskRun(run.getObjectId()); assertNotNull(run2); assertNotNull(run2.getCreateInstant()); assertNotNull(run2.getStartInstant()); assertNull(run2.getEndInstant()); assertNotNull(run2.getMarketData()); // Map<String, String> props = run2.getPropertiesMap(); //assertEquals(10, props.size()); //assertEquals("AD_HOC_RUN", props.getId("observationTime")); //assertEquals(ZonedDateTime.ofInstant(run2.getCreateInstant(), TimeZone.UTC).toString(), props.getId("valuationTime")); //assertEquals("test_view", props.getId("view")); //assertEquals(ZonedDateTime.ofInstant(run2.getCreateInstant(), TimeZone.UTC).getZone().toString(), props.getId("timeZone")); //assertEquals(ZonedDateTime.ofInstant(run2.getCreateInstant(), TimeZone.UTC).toLocalTime().toString(), props.getId("staticDataTime")); //assertEquals(ZonedDateTime.ofInstant(run2.getCreateInstant(), TimeZone.UTC).toLocalTime().toString(), props.getId("configDbTime")); // assertEquals("Manual run2 started on " // + run2.getCreateInstant().toString() // + " by " // + System.getProperty("user.name"), // props.getId("reason")); // assertEquals(run2.getCreateInstant().toString(), props.getId("valuationInstant")); // assertEquals(run2.getCreateInstant().toInstant().toString(), props.getId("configDbInstant")); // assertEquals(run2.getCreateInstant().toString(), props.getId("staticDataInstant")); //assertEquals(run2.getCreateInstant().toInstant(), _riskRun.getOriginalCreationTime()); // getId RiskRun run3 = _batchWriter.getRiskRun(run.getObjectId()); assertEquals(run2.getId(), run3.getId()); } @Test public void startAndEndBatch() { final UniqueId marketDataUid = _cycleMetadataStub.getMarketDataSnapshotId(); _batchMaster.createMarketData(marketDataUid); RiskRun run = _batchMaster.startRiskRun(_cycleMetadataStub, Maps.<String, String>newHashMap(), RunCreationMode.AUTO, SnapshotMode.PREPARED); RiskRun run1 = _batchWriter.getRiskRun(run.getObjectId()); assertNotNull(run1); assertNotNull(run1.getStartInstant()); assertNull(run1.getEndInstant()); RiskRun run2 = _batchWriter.getRiskRun(run.getObjectId()); assertEquals(run1.getId(), run2.getId()); _batchMaster.endRiskRun(run.getObjectId()); run1 = _batchWriter.getRiskRun(run.getObjectId()); assertNotNull(run1); assertNotNull(run1.getStartInstant()); assertNotNull(run1.getEndInstant()); } @Test public void startBatchTwice() { final UniqueId marketDataUid = _cycleMetadataStub.getMarketDataSnapshotId(); _batchMaster.createMarketData(marketDataUid); RiskRun run1 = _batchMaster.startRiskRun(_cycleMetadataStub, Maps.<String, String>newHashMap(), RunCreationMode.AUTO, SnapshotMode.PREPARED); RiskRun run2 = _batchWriter.getRiskRun(run1.getObjectId()); assertNotNull(run2.getCreateInstant()); assertEquals(0, run2.getNumRestarts()); RiskRun run10 = _batchMaster.startRiskRun(_cycleMetadataStub, Maps.<String, String>newHashMap(), RunCreationMode.AUTO, SnapshotMode.PREPARED); RiskRun run20 = _batchWriter.getRiskRun(run10.getObjectId()); assertEquals(1, run20.getNumRestarts()); RiskRun run3 = _batchWriter.getRiskRun(run10.getObjectId()); assertEquals(run20.getId(), run3.getId()); } @Test public void getComputationTargetBySpec() { final UniqueId uniqueId = UniqueId.of("foo", "bar"); _batchMaster.getDbConnector().getTransactionTemplate().execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { HbComputationTargetSpecification portfolio = _batchWriter.getOrCreateComputationTargetInTransaction( new ComputationTargetSpecification(ComputationTargetType.PORTFOLIO_NODE, uniqueId)); assertNotNull(portfolio); assertEquals(ComputationTargetType.PORTFOLIO_NODE, portfolio.getType()); assertEquals(uniqueId, portfolio.getUniqueId()); HbComputationTargetSpecification position = _batchWriter.getComputationTargetIntransaction( new ComputationTargetSpecification(ComputationTargetType.POSITION, uniqueId)); assertNull(position); HbComputationTargetSpecification security = _batchWriter.getComputationTargetIntransaction( new ComputationTargetSpecification(ComputationTargetType.SECURITY, uniqueId)); assertNull(security); HbComputationTargetSpecification primitive = _batchWriter.getComputationTargetIntransaction( new ComputationTargetSpecification(ComputationTargetType.PRIMITIVE, uniqueId)); assertNull(primitive); return null; } }); } @Test public void getComputationTarget() { final UniqueId uniqueId = UniqueId.of("foo", "bar", "1"); final SimpleSecurity mockSecurity = new SimpleSecurity("option"); mockSecurity.setUniqueId(uniqueId); mockSecurity.setName("myOption"); //Batch batch = new Batch(_batchId, _cycleInfo); _batchMaster.getDbConnector().getTransactionTemplate().execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { HbComputationTargetSpecification security = _batchWriter.getOrCreateComputationTargetInTransaction( new ComputationTargetSpecification(ComputationTargetType.SECURITY, uniqueId)); assertEquals(ComputationTargetType.SECURITY, security.getType()); HbComputationTargetSpecification primitive = _batchWriter.getOrCreateComputationTargetInTransaction( new ComputationTargetSpecification(ComputationTargetType.PRIMITIVE, uniqueId)); assertEquals(ComputationTargetType.PRIMITIVE, primitive.getType()); return null; } }); } @Test public void updateComputationTarget() { final UniqueId uniqueId = UniqueId.of("foo", "bar"); final SimpleSecurity mockSecurity = new SimpleSecurity("option"); mockSecurity.setUniqueId(uniqueId); mockSecurity.setName("myOption"); _batchMaster.getDbConnector().getTransactionTemplate().execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { HbComputationTargetSpecification security = _batchWriter.getOrCreateComputationTargetInTransaction( new ComputationTargetSpecification(ComputationTargetType.SECURITY, uniqueId)); assertEquals(ComputationTargetType.SECURITY, security.getType()); com.opengamma.engine.ComputationTarget target = new com.opengamma.engine.ComputationTarget(mockSecurity); security = _batchWriter.getOrCreateComputationTargetInTransaction(target.toSpecification()); assertEquals(ComputationTargetType.SECURITY, security.getType()); return null; } }); } @Test public void getValueConstraint() { _batchMaster.getDbConnector().getTransactionTemplate().execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { // create RiskValueSpecification valueSpecification1 = _batchWriter.getRiskValueSpecification(ValueProperties.parse("currency=USD")); assertNotNull(valueSpecification1); assertEquals("{\"properties\":[{\"values\":[\"USD\"],\"name\":\"currency\"}]}", valueSpecification1.getSyntheticForm()); // getId RiskValueSpecification valueSpecification2 = _batchWriter.getRiskValueSpecification(ValueProperties.parse("currency=USD")); assertEquals(valueSpecification1, valueSpecification2); assertEquals(valueSpecification1.getId(), valueSpecification2.getId()); return null; } }); } @Test public void getFunctionUniqueId() { _batchMaster.getDbConnector().getTransactionTemplate().execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { // create FunctionUniqueId id1 = _batchWriter.getFunctionUniqueIdInTransaction("test_id"); assertNotNull(id1); assertEquals("test_id", id1.getUniqueId()); // getId FunctionUniqueId id2 = _batchWriter.getFunctionUniqueIdInTransaction("test_id"); assertEquals(id1, id2); return null; } }); } @Test(expectedExceptions = DataNotFoundException.class) public void deleteNonExisting() { final ObjectId runId = ObjectId.of("---", "000"); _batchMaster.getDbConnector().getTransactionTemplate().execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { assertNull(_batchWriter.getRiskRun(runId)); _batchMaster.deleteRiskRun(runId); return null; } }); } @Test(expectedExceptions = IllegalArgumentException.class) public void getRiskWithoutUniqueId() { assertNull(_batchWriter.getRiskRun(null)); } @Test(expectedExceptions = DataNotFoundException.class) public void delete() { final UniqueId marketDataUid = _cycleMetadataStub.getMarketDataSnapshotId(); _batchMaster.createMarketData(marketDataUid); RiskRun run = _batchMaster.startRiskRun(_cycleMetadataStub, Maps.<String, String>newHashMap(), RunCreationMode.AUTO, SnapshotMode.PREPARED); assertNotNull(_batchWriter.getRiskRun(run.getObjectId())); _batchMaster.deleteRiskRun(run.getObjectId()); assertNull(_batchWriter.getRiskRun(run.getObjectId())); } @Test(expectedExceptions = IllegalArgumentException.class) public void addJobResultsToUnstartedBatch() { ViewComputationResultModel result = new InMemoryViewComputationResultModel(); _batchMaster.addJobResults(null, result); } @Test(expectedExceptions = IllegalArgumentException.class) public void addJobResultsWithoutExistingComputeNodeId() { final UniqueId marketDataUid = _cycleMetadataStub.getMarketDataSnapshotId(); _batchMaster.createMarketData(marketDataUid); RiskRun run = _batchMaster.startRiskRun(_cycleMetadataStub, Maps.<String, String>newHashMap(), RunCreationMode.AUTO, SnapshotMode.PREPARED); InMemoryViewComputationResultModel result = new InMemoryViewComputationResultModel(); ComputationTargetSpecification computationTargetSpec = new ComputationTargetSpecification(ComputationTargetType.SECURITY, UniqueId.of("Sec", "APPL")); ValueProperties properties = ValueProperties.with(ValuePropertyNames.FUNCTION, "asd").get(); ValueSpecification valueSpec = new ValueSpecification("value", computationTargetSpec, properties); ComputedValueResult cvr = new ComputedValueResult(valueSpec, 1000.0, ExecutionLog.EMPTY, null, null, InvocationResult.SUCCESS); //cvr.setRequirements(newHashSet(_requirement)); result.addValue("config_1", cvr); _batchMaster.addJobResults(run.getObjectId(), result); } @Test public void addJobResults() { final UniqueId marketDataUid = _cycleMetadataStub.getMarketDataSnapshotId(); _batchMaster.createMarketData(marketDataUid); RiskRun run = _batchMaster.startRiskRun(_cycleMetadataStub, Maps.<String, String>newHashMap(), RunCreationMode.AUTO, SnapshotMode.PREPARED); InMemoryViewComputationResultModel result = new InMemoryViewComputationResultModel(); ComputedValueResult cvr = new ComputedValueResult(_specification, 1000.0, ExecutionLog.EMPTY, "someComputeNode", null, InvocationResult.SUCCESS); //cvr.setRequirements(newHashSet(_requirement)); result.addValue("config_1", cvr); _batchMaster.addJobResults(run.getObjectId(), result); } }
projects/OG-MasterDB/src/test/java/com/opengamma/masterdb/batch/DbBatchWriterTest.java
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.masterdb.batch; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Maps.newHashMap; import static com.google.common.collect.Sets.newHashSet; import static java.util.Collections.emptyList; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.time.Instant; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Factory; import org.testng.annotations.Test; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.opengamma.DataNotFoundException; import com.opengamma.batch.RunCreationMode; import com.opengamma.batch.SnapshotMode; import com.opengamma.batch.domain.FunctionUniqueId; import com.opengamma.batch.domain.HbComputationTargetSpecification; import com.opengamma.batch.domain.MarketData; import com.opengamma.batch.domain.MarketDataValue; import com.opengamma.batch.domain.RiskRun; import com.opengamma.batch.domain.RiskValueSpecification; import com.opengamma.core.security.Security; import com.opengamma.core.security.impl.SimpleSecurity; import com.opengamma.engine.ComputationTargetSpecification; import com.opengamma.engine.ComputationTargetType; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.engine.view.InMemoryViewComputationResultModel; import com.opengamma.engine.view.ViewComputationResultModel; import com.opengamma.engine.view.calc.ViewCycleMetadata; import com.opengamma.engine.view.calcnode.InvocationResult; import com.opengamma.id.ExternalId; import com.opengamma.id.ExternalIdBundle; import com.opengamma.id.ObjectId; import com.opengamma.id.UniqueId; import com.opengamma.id.VersionCorrection; import com.opengamma.masterdb.DbMasterTestUtils; import com.opengamma.util.paging.PagingRequest; import com.opengamma.util.test.DbTest; /** * Test DbBatchWriter. */ public class DbBatchWriterTest extends DbTest { private DbBatchMaster _batchMaster; private DbBatchWriter _batchWriter; private ViewCycleMetadata _cycleMetadataStub; private ComputationTargetSpecification _compTargetSpec; private ValueRequirement _requirement; private ValueSpecification _specification; @Factory(dataProvider = "databases", dataProviderClass = DbTest.class) public DbBatchWriterTest(String databaseType, String databaseVersion) { super(databaseType, databaseVersion, databaseVersion); } @BeforeMethod public void setUp() throws Exception { super.setUp(); ConfigurableApplicationContext context = DbMasterTestUtils.getContext(getDatabaseType()); _batchMaster = (DbBatchMaster) context.getBean(getDatabaseType() + "DbBatchMaster"); _batchWriter = new DbBatchWriter(_batchMaster.getDbConnector()); final String calculationConfigName = "config_1"; _compTargetSpec = new ComputationTargetSpecification(ComputationTargetType.SECURITY, UniqueId.of("Sec", "APPL")); final Security security = new SimpleSecurity(_compTargetSpec.getUniqueId(), ExternalIdBundle.of("Sec", "APPL"), "equity", "APPL"); _requirement = new ValueRequirement("FAIR_VALUE", security); _specification = new ValueSpecification(_requirement, "IDENTITY_FUNCTION"); final Instant _valuationTime = Instant.parse("2011-12-14T14:20:17.143Z"); _cycleMetadataStub = new ViewCycleMetadata() { @Override public UniqueId getViewCycleId() { return UniqueId.of("viewcycle", "viewcycle", "viewcycle"); } @Override public Collection<String> getAllCalculationConfigurationNames() { return newArrayList(calculationConfigName); } @Override public Collection<com.opengamma.engine.ComputationTargetSpecification> getComputationTargets(String calcConfName) { if (calcConfName.equals(calculationConfigName)) { return Arrays.asList(new ComputationTargetSpecification(UniqueId.of("Primitive", "Value")), _compTargetSpec); } else { return emptyList(); } } @Override public Map<ValueSpecification, Set<ValueRequirement>> getTerminalOutputs(String calcConfName) { return new HashMap<ValueSpecification, Set<ValueRequirement>>() {{ put(_specification, new HashSet<ValueRequirement>() {{ add(_requirement); }}); }}; } @Override public UniqueId getMarketDataSnapshotId() { return UniqueId.of("snapshot", "snapshot", "snapshot"); } @Override public Instant getValuationTime() { return _valuationTime; } @Override public VersionCorrection getVersionCorrection() { return VersionCorrection.LATEST; } @Override public UniqueId getViewDefinitionId() { return UniqueId.of("viewdef", "viewdef", "viewdef"); } }; } //------------------------------------------------------------------------- @Test(expectedExceptions = IllegalArgumentException.class) public void addValuesToNonexistentSnapshot() { _batchMaster.addValuesToMarketData(ObjectId.of("nonexistent", "nonexistent"), Collections.<MarketDataValue>emptySet()); } @Test public void addValuesToIncompleteSnapshot() { MarketData marketData = _batchWriter.createOrGetMarketDataInTransaction(_cycleMetadataStub.getMarketDataSnapshotId()); _batchMaster.addValuesToMarketData(marketData.getObjectId(), Collections.<MarketDataValue>emptySet()); List<MarketDataValue> marketDataValues = _batchMaster.getMarketDataValues(marketData.getObjectId(), PagingRequest.ALL).getFirst(); assertNotNull(marketDataValues); assertEquals(0, marketDataValues.size()); final Set<ComputationTargetSpecification> specs = Sets.newHashSet(); specs.add(new ComputationTargetSpecification(UniqueId.of("BUID", "EQ12345", null))); specs.add(new ComputationTargetSpecification(UniqueId.of("BUID", "EQ12346", "1"))); specs.add(new ComputationTargetSpecification(UniqueId.of("BUID", "EQ12347", "2"))); final Map<ComputationTargetSpecification, Long> compTargetSpecIdx = new HashMap<ComputationTargetSpecification, Long>(); final Map<Long, ComputationTargetSpecification> reversedCompTargetSpecIdx = new HashMap<Long, ComputationTargetSpecification>(); _batchMaster.getDbConnector().getTransactionTemplate().execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { // manually populationg db with computation targets for (ComputationTargetSpecification spec : specs) { HbComputationTargetSpecification hbComputationTargetSpecification = _batchWriter.getOrCreateComputationTargetInTransaction(spec); compTargetSpecIdx.put(spec, hbComputationTargetSpecification.getId()); reversedCompTargetSpecIdx.put(hbComputationTargetSpecification.getId(), spec); } return null; } }); Set<MarketDataValue> values = new HashSet<MarketDataValue>(); for (ComputationTargetSpecification spec : specs) { values.add(new MarketDataValue(spec, 123.45, "value_name")); } _batchMaster.addValuesToMarketData(marketData.getObjectId(), values); marketDataValues = _batchMaster.getMarketDataValues(marketData.getObjectId(), PagingRequest.ALL).getFirst(); assertEquals(specs.size(), marketDataValues.size()); Map<Long, MarketDataValue> marketDataValuesMap = newHashMap(); for (MarketDataValue value : marketDataValues) { marketDataValuesMap.put(value.getComputationTargetSpecificationId(), value); } for (ComputationTargetSpecification spec : specs) { Long targetSpecificationId = compTargetSpecIdx.get(spec); MarketDataValue marketDataValue = marketDataValuesMap.get(targetSpecificationId); assertNotNull(marketDataValue); assertEquals(spec, reversedCompTargetSpecIdx.get(marketDataValue.getComputationTargetSpecificationId())); assertEquals("value_name", marketDataValue.getName()); assertEquals(123.45, marketDataValue.getValue(), 0.000001); } // should not add anything extra _batchMaster.addValuesToMarketData(marketData.getObjectId(), values); marketDataValues = _batchMaster.getMarketDataValues(marketData.getObjectId(), PagingRequest.ALL).getFirst(); assertEquals(3, marketDataValues.size()); // should update 2, add 1 values = new HashSet<MarketDataValue>(); values.add(new MarketDataValue(new ComputationTargetSpecification(UniqueId.of("BUID", "EQ12345", null)), 123.46, "value_name")); values.add(new MarketDataValue(new ComputationTargetSpecification(UniqueId.of("BUID", "EQ12347", "2")), 123.47, "value_name")); values.add(new MarketDataValue(new ComputationTargetSpecification(ExternalId.of("BUID", "EQ12348")), 123.45, "value_name")); _batchMaster.addValuesToMarketData(marketData.getObjectId(), values); marketDataValues = _batchMaster.getMarketDataValues(marketData.getObjectId(), PagingRequest.ALL).getFirst(); assertEquals(4, marketDataValues.size()); } /*@Test public void fixLiveDataSnapshotTime() { _batchMaster.createLiveDataSnapshot(_batch.getBatchId().getBatchSnapshotId()); _batchMaster.fixLiveDataSnapshotTime(_batch.getBatchId().getBatchSnapshotId(), OffsetTime.now()); }*/ /*@Test(expectedExceptions = IllegalArgumentException.class) public void tryToFixNonexistentLiveDataSnapshotTime() { _batchMaster.fixLiveDataSnapshotTime(_batch.getBatchId().getBatchSnapshotId(), OffsetTime.now()); }*/ @Test public void createLiveDataSnapshotMultipleTimes() { final UniqueId marketDataUid = _cycleMetadataStub.getMarketDataSnapshotId(); _batchMaster.createMarketData(marketDataUid); _batchMaster.createMarketData(marketDataUid); _batchMaster.getDbConnector().getTransactionTemplate().execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { assertNotNull(_batchWriter.createOrGetMarketDataInTransaction(marketDataUid)); return null; } }); } @Test public void createThenGetRiskRun() { final UniqueId marketDataUid = _cycleMetadataStub.getMarketDataSnapshotId(); _batchMaster.createMarketData(marketDataUid); RiskRun run = _batchMaster.startRiskRun(_cycleMetadataStub, Maps.<String, String>newHashMap(), RunCreationMode.AUTO, SnapshotMode.PREPARED); RiskRun run2 = _batchWriter.getRiskRun(run.getObjectId()); assertNotNull(run2); assertNotNull(run2.getCreateInstant()); assertNotNull(run2.getStartInstant()); assertNull(run2.getEndInstant()); assertNotNull(run2.getMarketData()); // Map<String, String> props = run2.getPropertiesMap(); //assertEquals(10, props.size()); //assertEquals("AD_HOC_RUN", props.getId("observationTime")); //assertEquals(ZonedDateTime.ofInstant(run2.getCreateInstant(), TimeZone.UTC).toString(), props.getId("valuationTime")); //assertEquals("test_view", props.getId("view")); //assertEquals(ZonedDateTime.ofInstant(run2.getCreateInstant(), TimeZone.UTC).getZone().toString(), props.getId("timeZone")); //assertEquals(ZonedDateTime.ofInstant(run2.getCreateInstant(), TimeZone.UTC).toLocalTime().toString(), props.getId("staticDataTime")); //assertEquals(ZonedDateTime.ofInstant(run2.getCreateInstant(), TimeZone.UTC).toLocalTime().toString(), props.getId("configDbTime")); // assertEquals("Manual run2 started on " // + run2.getCreateInstant().toString() // + " by " // + System.getProperty("user.name"), // props.getId("reason")); // assertEquals(run2.getCreateInstant().toString(), props.getId("valuationInstant")); // assertEquals(run2.getCreateInstant().toInstant().toString(), props.getId("configDbInstant")); // assertEquals(run2.getCreateInstant().toString(), props.getId("staticDataInstant")); //assertEquals(run2.getCreateInstant().toInstant(), _riskRun.getOriginalCreationTime()); // getId RiskRun run3 = _batchWriter.getRiskRun(run.getObjectId()); assertEquals(run2.getId(), run3.getId()); } @Test public void startAndEndBatch() { final UniqueId marketDataUid = _cycleMetadataStub.getMarketDataSnapshotId(); _batchMaster.createMarketData(marketDataUid); RiskRun run = _batchMaster.startRiskRun(_cycleMetadataStub, Maps.<String, String>newHashMap(), RunCreationMode.AUTO, SnapshotMode.PREPARED); RiskRun run1 = _batchWriter.getRiskRun(run.getObjectId()); assertNotNull(run1); assertNotNull(run1.getStartInstant()); assertNull(run1.getEndInstant()); RiskRun run2 = _batchWriter.getRiskRun(run.getObjectId()); assertEquals(run1.getId(), run2.getId()); _batchMaster.endRiskRun(run.getObjectId()); run1 = _batchWriter.getRiskRun(run.getObjectId()); assertNotNull(run1); assertNotNull(run1.getStartInstant()); assertNotNull(run1.getEndInstant()); } @Test public void startBatchTwice() { final UniqueId marketDataUid = _cycleMetadataStub.getMarketDataSnapshotId(); _batchMaster.createMarketData(marketDataUid); RiskRun run1 = _batchMaster.startRiskRun(_cycleMetadataStub, Maps.<String, String>newHashMap(), RunCreationMode.AUTO, SnapshotMode.PREPARED); RiskRun run2 = _batchWriter.getRiskRun(run1.getObjectId()); assertNotNull(run2.getCreateInstant()); assertEquals(0, run2.getNumRestarts()); RiskRun run10 = _batchMaster.startRiskRun(_cycleMetadataStub, Maps.<String, String>newHashMap(), RunCreationMode.AUTO, SnapshotMode.PREPARED); RiskRun run20 = _batchWriter.getRiskRun(run10.getObjectId()); assertEquals(1, run20.getNumRestarts()); RiskRun run3 = _batchWriter.getRiskRun(run10.getObjectId()); assertEquals(run20.getId(), run3.getId()); } @Test public void getComputationTargetBySpec() { final UniqueId uniqueId = UniqueId.of("foo", "bar"); _batchMaster.getDbConnector().getTransactionTemplate().execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { HbComputationTargetSpecification portfolio = _batchWriter.getOrCreateComputationTargetInTransaction( new ComputationTargetSpecification(ComputationTargetType.PORTFOLIO_NODE, uniqueId)); assertNotNull(portfolio); assertEquals(ComputationTargetType.PORTFOLIO_NODE, portfolio.getType()); assertEquals(uniqueId, portfolio.getUniqueId()); HbComputationTargetSpecification position = _batchWriter.getComputationTargetIntransaction( new ComputationTargetSpecification(ComputationTargetType.POSITION, uniqueId)); assertNull(position); HbComputationTargetSpecification security = _batchWriter.getComputationTargetIntransaction( new ComputationTargetSpecification(ComputationTargetType.SECURITY, uniqueId)); assertNull(security); HbComputationTargetSpecification primitive = _batchWriter.getComputationTargetIntransaction( new ComputationTargetSpecification(ComputationTargetType.PRIMITIVE, uniqueId)); assertNull(primitive); return null; } }); } @Test public void getComputationTarget() { final UniqueId uniqueId = UniqueId.of("foo", "bar", "1"); final SimpleSecurity mockSecurity = new SimpleSecurity("option"); mockSecurity.setUniqueId(uniqueId); mockSecurity.setName("myOption"); //Batch batch = new Batch(_batchId, _cycleInfo); _batchMaster.getDbConnector().getTransactionTemplate().execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { HbComputationTargetSpecification security = _batchWriter.getOrCreateComputationTargetInTransaction( new ComputationTargetSpecification(ComputationTargetType.SECURITY, uniqueId)); assertEquals(ComputationTargetType.SECURITY, security.getType()); HbComputationTargetSpecification primitive = _batchWriter.getOrCreateComputationTargetInTransaction( new ComputationTargetSpecification(ComputationTargetType.PRIMITIVE, uniqueId)); assertEquals(ComputationTargetType.PRIMITIVE, primitive.getType()); return null; } }); } @Test public void updateComputationTarget() { final UniqueId uniqueId = UniqueId.of("foo", "bar"); final SimpleSecurity mockSecurity = new SimpleSecurity("option"); mockSecurity.setUniqueId(uniqueId); mockSecurity.setName("myOption"); _batchMaster.getDbConnector().getTransactionTemplate().execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { HbComputationTargetSpecification security = _batchWriter.getOrCreateComputationTargetInTransaction( new ComputationTargetSpecification(ComputationTargetType.SECURITY, uniqueId)); assertEquals(ComputationTargetType.SECURITY, security.getType()); com.opengamma.engine.ComputationTarget target = new com.opengamma.engine.ComputationTarget(mockSecurity); security = _batchWriter.getOrCreateComputationTargetInTransaction(target.toSpecification()); assertEquals(ComputationTargetType.SECURITY, security.getType()); return null; } }); } @Test public void getValueConstraint() { _batchMaster.getDbConnector().getTransactionTemplate().execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { // create RiskValueSpecification valueSpecification1 = _batchWriter.getRiskValueSpecification(ValueProperties.parse("currency=USD")); assertNotNull(valueSpecification1); assertEquals("{\"properties\":[{\"values\":[\"USD\"],\"name\":\"currency\"}]}", valueSpecification1.getSyntheticForm()); // getId RiskValueSpecification valueSpecification2 = _batchWriter.getRiskValueSpecification(ValueProperties.parse("currency=USD")); assertEquals(valueSpecification1, valueSpecification2); assertEquals(valueSpecification1.getId(), valueSpecification2.getId()); return null; } }); } @Test public void getFunctionUniqueId() { _batchMaster.getDbConnector().getTransactionTemplate().execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { // create FunctionUniqueId id1 = _batchWriter.getFunctionUniqueIdInTransaction("test_id"); assertNotNull(id1); assertEquals("test_id", id1.getUniqueId()); // getId FunctionUniqueId id2 = _batchWriter.getFunctionUniqueIdInTransaction("test_id"); assertEquals(id1, id2); return null; } }); } @Test(expectedExceptions = DataNotFoundException.class) public void deleteNonExisting() { final ObjectId runId = ObjectId.of("---", "000"); _batchMaster.getDbConnector().getTransactionTemplate().execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { assertNull(_batchWriter.getRiskRun(runId)); _batchMaster.deleteRiskRun(runId); return null; } }); } @Test(expectedExceptions = IllegalArgumentException.class) public void getRiskWithoutUniqueId() { assertNull(_batchWriter.getRiskRun(null)); } @Test(expectedExceptions = DataNotFoundException.class) public void delete() { final UniqueId marketDataUid = _cycleMetadataStub.getMarketDataSnapshotId(); _batchMaster.createMarketData(marketDataUid); RiskRun run = _batchMaster.startRiskRun(_cycleMetadataStub, Maps.<String, String>newHashMap(), RunCreationMode.AUTO, SnapshotMode.PREPARED); assertNotNull(_batchWriter.getRiskRun(run.getObjectId())); _batchMaster.deleteRiskRun(run.getObjectId()); assertNull(_batchWriter.getRiskRun(run.getObjectId())); } @Test(expectedExceptions = IllegalArgumentException.class) public void addJobResultsToUnstartedBatch() { ViewComputationResultModel result = new InMemoryViewComputationResultModel(); _batchMaster.addJobResults(null, result); } @Test(expectedExceptions = IllegalArgumentException.class) public void addJobResultsWithoutExistingComputeNodeId() { final UniqueId marketDataUid = _cycleMetadataStub.getMarketDataSnapshotId(); _batchMaster.createMarketData(marketDataUid); RiskRun run = _batchMaster.startRiskRun(_cycleMetadataStub, Maps.<String, String>newHashMap(), RunCreationMode.AUTO, SnapshotMode.PREPARED); InMemoryViewComputationResultModel result = new InMemoryViewComputationResultModel(); result.addValue("config_1", new ComputedValue( new ValueSpecification( "value", new ComputationTargetSpecification(ComputationTargetType.SECURITY, UniqueId.of("Sec", "APPL")), ValueProperties.with(ValuePropertyNames.FUNCTION, "asd").get()), 1000.0) {{ this.setInvocationResult(InvocationResult.SUCCESS); this.setRequirements(newHashSet(_requirement)); }}); _batchMaster.addJobResults(run.getObjectId(), result); } @Test public void addJobResults() { final UniqueId marketDataUid = _cycleMetadataStub.getMarketDataSnapshotId(); _batchMaster.createMarketData(marketDataUid); RiskRun run = _batchMaster.startRiskRun(_cycleMetadataStub, Maps.<String, String>newHashMap(), RunCreationMode.AUTO, SnapshotMode.PREPARED); InMemoryViewComputationResultModel result = new InMemoryViewComputationResultModel(); result.addValue("config_1", new ComputedValue( _specification, 1000.0) {{ this.setInvocationResult(InvocationResult.SUCCESS); this.setRequirements(newHashSet(_requirement)); this.setComputeNodeId("someComputeNode"); }}); _batchMaster.addJobResults(run.getObjectId(), result); } }
[PLAT-2779] Checkstyle; use of ComputedValueResult and new API
projects/OG-MasterDB/src/test/java/com/opengamma/masterdb/batch/DbBatchWriterTest.java
[PLAT-2779] Checkstyle; use of ComputedValueResult and new API
<ide><path>rojects/OG-MasterDB/src/test/java/com/opengamma/masterdb/batch/DbBatchWriterTest.java <ide> <ide> import static com.google.common.collect.Lists.newArrayList; <ide> import static com.google.common.collect.Maps.newHashMap; <del>import static com.google.common.collect.Sets.newHashSet; <ide> import static java.util.Collections.emptyList; <ide> import static org.testng.AssertJUnit.assertEquals; <ide> import static org.testng.AssertJUnit.assertNotNull; <ide> import org.testng.annotations.Factory; <ide> import org.testng.annotations.Test; <ide> <add>import com.google.common.collect.ImmutableMap; <add>import com.google.common.collect.ImmutableSet; <ide> import com.google.common.collect.Maps; <ide> import com.google.common.collect.Sets; <ide> import com.opengamma.DataNotFoundException; <ide> import com.opengamma.core.security.impl.SimpleSecurity; <ide> import com.opengamma.engine.ComputationTargetSpecification; <ide> import com.opengamma.engine.ComputationTargetType; <del>import com.opengamma.engine.value.ComputedValue; <add>import com.opengamma.engine.value.ComputedValueResult; <ide> import com.opengamma.engine.value.ValueProperties; <ide> import com.opengamma.engine.value.ValuePropertyNames; <ide> import com.opengamma.engine.value.ValueRequirement; <ide> import com.opengamma.engine.view.InMemoryViewComputationResultModel; <ide> import com.opengamma.engine.view.ViewComputationResultModel; <ide> import com.opengamma.engine.view.calc.ViewCycleMetadata; <add>import com.opengamma.engine.view.calcnode.ExecutionLog; <ide> import com.opengamma.engine.view.calcnode.InvocationResult; <ide> import com.opengamma.id.ExternalId; <ide> import com.opengamma.id.ExternalIdBundle; <ide> <ide> @Override <ide> public Map<ValueSpecification, Set<ValueRequirement>> getTerminalOutputs(String calcConfName) { <del> return new HashMap<ValueSpecification, Set<ValueRequirement>>() {{ <del> put(_specification, new HashSet<ValueRequirement>() {{ <del> add(_requirement); <del> }}); <del> }}; <add> return ImmutableMap.<ValueSpecification, Set<ValueRequirement>>of(_specification, ImmutableSet.of(_requirement)); <ide> } <ide> <ide> @Override <ide> RiskRun run = _batchMaster.startRiskRun(_cycleMetadataStub, Maps.<String, String>newHashMap(), RunCreationMode.AUTO, SnapshotMode.PREPARED); <ide> <ide> InMemoryViewComputationResultModel result = new InMemoryViewComputationResultModel(); <del> result.addValue("config_1", <del> new ComputedValue( <del> new ValueSpecification( <del> "value", <del> new ComputationTargetSpecification(ComputationTargetType.SECURITY, UniqueId.of("Sec", "APPL")), ValueProperties.with(ValuePropertyNames.FUNCTION, "asd").get()), <del> 1000.0) {{ <del> this.setInvocationResult(InvocationResult.SUCCESS); <del> this.setRequirements(newHashSet(_requirement)); <del> }}); <add> ComputationTargetSpecification computationTargetSpec = new ComputationTargetSpecification(ComputationTargetType.SECURITY, UniqueId.of("Sec", "APPL")); <add> ValueProperties properties = ValueProperties.with(ValuePropertyNames.FUNCTION, "asd").get(); <add> ValueSpecification valueSpec = new ValueSpecification("value", computationTargetSpec, properties); <add> ComputedValueResult cvr = new ComputedValueResult(valueSpec, 1000.0, ExecutionLog.EMPTY, null, null, InvocationResult.SUCCESS); <add> //cvr.setRequirements(newHashSet(_requirement)); <add> result.addValue("config_1", cvr); <ide> _batchMaster.addJobResults(run.getObjectId(), result); <ide> } <ide> <ide> _batchMaster.createMarketData(marketDataUid); <ide> RiskRun run = _batchMaster.startRiskRun(_cycleMetadataStub, Maps.<String, String>newHashMap(), RunCreationMode.AUTO, SnapshotMode.PREPARED); <ide> InMemoryViewComputationResultModel result = new InMemoryViewComputationResultModel(); <del> result.addValue("config_1", <del> new ComputedValue( <del> _specification, <del> 1000.0) {{ <del> this.setInvocationResult(InvocationResult.SUCCESS); <del> this.setRequirements(newHashSet(_requirement)); <del> this.setComputeNodeId("someComputeNode"); <del> }}); <add> ComputedValueResult cvr = new ComputedValueResult(_specification, 1000.0, ExecutionLog.EMPTY, "someComputeNode", null, InvocationResult.SUCCESS); <add> //cvr.setRequirements(newHashSet(_requirement)); <add> result.addValue("config_1", cvr); <ide> _batchMaster.addJobResults(run.getObjectId(), result); <ide> } <ide> }
Java
mit
02bb1564716c528bb52947dacce80ebaaf79baac
0
open-keychain/spongycastle,savichris/spongycastle,lesstif/spongycastle,onessimofalconi/bc-java,isghe/bc-java,Skywalker-11/spongycastle,isghe/bc-java,lesstif/spongycastle,savichris/spongycastle,sergeypayu/bc-java,Skywalker-11/spongycastle,open-keychain/spongycastle,lesstif/spongycastle,bcgit/bc-java,Skywalker-11/spongycastle,sergeypayu/bc-java,open-keychain/spongycastle,bcgit/bc-java,isghe/bc-java,sonork/spongycastle,sonork/spongycastle,onessimofalconi/bc-java,FAU-Inf2/spongycastle,FAU-Inf2/spongycastle,sergeypayu/bc-java,onessimofalconi/bc-java,sonork/spongycastle,FAU-Inf2/spongycastle,bcgit/bc-java,savichris/spongycastle
package org.bouncycastle.crypto.tls; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Hashtable; import java.util.Vector; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.Extensions; import org.bouncycastle.asn1.x509.KeyUsage; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.digests.MD5Digest; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.digests.SHA224Digest; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.digests.SHA384Digest; import org.bouncycastle.crypto.digests.SHA512Digest; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.DSAPublicKeyParameters; import org.bouncycastle.crypto.params.ECPublicKeyParameters; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.RSAKeyParameters; import org.bouncycastle.crypto.util.PublicKeyFactory; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Integers; import org.bouncycastle.util.Strings; import org.bouncycastle.util.io.Streams; /** * Some helper functions for MicroTLS. */ public class TlsUtils { public static final byte[] EMPTY_BYTES = new byte[0]; public static final Integer EXT_signature_algorithms = Integers.valueOf(ExtensionType.signature_algorithms); public static void checkUint8(short i) throws IOException { if (!isValidUint8(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint8(int i) throws IOException { if (!isValidUint8(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint8(long i) throws IOException { if (!isValidUint8(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint16(int i) throws IOException { if (!isValidUint16(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint16(long i) throws IOException { if (!isValidUint16(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint24(int i) throws IOException { if (!isValidUint24(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint24(long i) throws IOException { if (!isValidUint24(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint32(long i) throws IOException { if (!isValidUint32(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint48(long i) throws IOException { if (!isValidUint48(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint64(long i) throws IOException { if (!isValidUint64(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static boolean isValidUint8(short i) { return (i & 0xFF) == i; } public static boolean isValidUint8(int i) { return (i & 0xFF) == i; } public static boolean isValidUint8(long i) { return (i & 0xFFL) == i; } public static boolean isValidUint16(int i) { return (i & 0xFFFF) == i; } public static boolean isValidUint16(long i) { return (i & 0xFFFFL) == i; } public static boolean isValidUint24(int i) { return (i & 0xFFFFFF) == i; } public static boolean isValidUint24(long i) { return (i & 0xFFFFFFL) == i; } public static boolean isValidUint32(long i) { return (i & 0xFFFFFFFFL) == i; } public static boolean isValidUint48(long i) { return (i & 0xFFFFFFFFFFFFL) == i; } public static boolean isValidUint64(long i) { return true; } public static boolean isSSL(TlsContext context) { return context.getServerVersion().isSSL(); } public static boolean isTLSv11(TlsContext context) { return ProtocolVersion.TLSv11.isEqualOrEarlierVersionOf(context.getServerVersion().getEquivalentTLSVersion()); } public static boolean isTLSv12(TlsContext context) { return ProtocolVersion.TLSv12.isEqualOrEarlierVersionOf(context.getServerVersion().getEquivalentTLSVersion()); } public static void writeUint8(short i, OutputStream output) throws IOException { output.write(i); } public static void writeUint8(int i, OutputStream output) throws IOException { output.write(i); } public static void writeUint8(short i, byte[] buf, int offset) { buf[offset] = (byte)i; } public static void writeUint8(int i, byte[] buf, int offset) { buf[offset] = (byte)i; } public static void writeUint16(int i, OutputStream output) throws IOException { output.write(i >>> 8); output.write(i); } public static void writeUint16(int i, byte[] buf, int offset) { buf[offset] = (byte)(i >>> 8); buf[offset + 1] = (byte)i; } public static void writeUint24(int i, OutputStream output) throws IOException { output.write((byte)(i >>> 16)); output.write((byte)(i >>> 8)); output.write((byte)i); } public static void writeUint24(int i, byte[] buf, int offset) { buf[offset] = (byte)(i >>> 16); buf[offset + 1] = (byte)(i >>> 8); buf[offset + 2] = (byte)i; } public static void writeUint32(long i, OutputStream output) throws IOException { output.write((byte)(i >>> 24)); output.write((byte)(i >>> 16)); output.write((byte)(i >>> 8)); output.write((byte)i); } public static void writeUint32(long i, byte[] buf, int offset) { buf[offset] = (byte)(i >>> 24); buf[offset + 1] = (byte)(i >>> 16); buf[offset + 2] = (byte)(i >>> 8); buf[offset + 3] = (byte)i; } public static void writeUint48(long i, OutputStream output) throws IOException { output.write((byte)(i >>> 40)); output.write((byte)(i >>> 32)); output.write((byte)(i >>> 24)); output.write((byte)(i >>> 16)); output.write((byte)(i >>> 8)); output.write((byte)i); } public static void writeUint48(long i, byte[] buf, int offset) { buf[offset] = (byte)(i >>> 40); buf[offset + 1] = (byte)(i >>> 32); buf[offset + 2] = (byte)(i >>> 24); buf[offset + 3] = (byte)(i >>> 16); buf[offset + 4] = (byte)(i >>> 8); buf[offset + 5] = (byte)i; } public static void writeUint64(long i, OutputStream output) throws IOException { output.write((byte)(i >>> 56)); output.write((byte)(i >>> 48)); output.write((byte)(i >>> 40)); output.write((byte)(i >>> 32)); output.write((byte)(i >>> 24)); output.write((byte)(i >>> 16)); output.write((byte)(i >>> 8)); output.write((byte)i); } public static void writeUint64(long i, byte[] buf, int offset) { buf[offset] = (byte)(i >>> 56); buf[offset + 1] = (byte)(i >>> 48); buf[offset + 2] = (byte)(i >>> 40); buf[offset + 3] = (byte)(i >>> 32); buf[offset + 4] = (byte)(i >>> 24); buf[offset + 5] = (byte)(i >>> 16); buf[offset + 6] = (byte)(i >>> 8); buf[offset + 7] = (byte)i; } public static void writeOpaque8(byte[] buf, OutputStream output) throws IOException { checkUint8(buf.length); writeUint8(buf.length, output); output.write(buf); } public static void writeOpaque16(byte[] buf, OutputStream output) throws IOException { checkUint16(buf.length); writeUint16(buf.length, output); output.write(buf); } public static void writeOpaque24(byte[] buf, OutputStream output) throws IOException { checkUint24(buf.length); writeUint24(buf.length, output); output.write(buf); } public static void writeUint8Array(short[] uints, OutputStream output) throws IOException { for (int i = 0; i < uints.length; ++i) { writeUint8(uints[i], output); } } public static void writeUint8Array(short[] uints, byte[] buf, int offset) throws IOException { for (int i = 0; i < uints.length; ++i) { writeUint8(uints[i], buf, offset); ++offset; } } public static void writeUint8ArrayWithUint8Length(short[] uints, OutputStream output) throws IOException { checkUint8(uints.length); writeUint8(uints.length, output); writeUint8Array(uints, output); } public static void writeUint8ArrayWithUint8Length(short[] uints, byte[] buf, int offset) throws IOException { checkUint8(uints.length); writeUint8(uints.length, buf, offset); writeUint8Array(uints, buf, offset + 1); } public static void writeUint16Array(int[] uints, OutputStream output) throws IOException { for (int i = 0; i < uints.length; ++i) { writeUint16(uints[i], output); } } public static void writeUint16Array(int[] uints, byte[] buf, int offset) throws IOException { for (int i = 0; i < uints.length; ++i) { writeUint16(uints[i], buf, offset); offset += 2; } } public static void writeUint16ArrayWithUint16Length(int[] uints, OutputStream output) throws IOException { int length = 2 * uints.length; checkUint16(length); writeUint16(length, output); writeUint16Array(uints, output); } public static void writeUint16ArrayWithUint16Length(int[] uints, byte[] buf, int offset) throws IOException { int length = 2 * uints.length; checkUint16(length); writeUint16(length, buf, offset); writeUint16Array(uints, buf, offset + 2); } public static byte[] encodeOpaque8(byte[] buf) throws IOException { checkUint8(buf.length); return Arrays.prepend(buf, (byte)buf.length); } public static byte[] encodeUint8ArrayWithUint8Length(short[] uints) throws IOException { byte[] result = new byte[1 + uints.length]; writeUint8ArrayWithUint8Length(uints, result, 0); return result; } public static byte[] encodeUint16ArrayWithUint16Length(int[] uints) throws IOException { int length = 2 * uints.length; byte[] result = new byte[2 + length]; writeUint16ArrayWithUint16Length(uints, result, 0); return result; } public static short readUint8(InputStream input) throws IOException { int i = input.read(); if (i < 0) { throw new EOFException(); } return (short)i; } public static short readUint8(byte[] buf, int offset) { return (short)buf[offset]; } public static int readUint16(InputStream input) throws IOException { int i1 = input.read(); int i2 = input.read(); if (i2 < 0) { throw new EOFException(); } return i1 << 8 | i2; } public static int readUint16(byte[] buf, int offset) { int n = (buf[offset] & 0xff) << 8; n |= (buf[++offset] & 0xff); return n; } public static int readUint24(InputStream input) throws IOException { int i1 = input.read(); int i2 = input.read(); int i3 = input.read(); if (i3 < 0) { throw new EOFException(); } return (i1 << 16) | (i2 << 8) | i3; } public static int readUint24(byte[] buf, int offset) { int n = (buf[offset] & 0xff) << 16; n |= (buf[++offset] & 0xff) << 8; n |= (buf[++offset] & 0xff); return n; } public static long readUint32(InputStream input) throws IOException { int i1 = input.read(); int i2 = input.read(); int i3 = input.read(); int i4 = input.read(); if (i4 < 0) { throw new EOFException(); } return ((i1 << 2) | (i2 << 16) | (i3 << 8) | i4) & 0xFFFFFFFFL; } public static long readUint32(byte[] buf, int offset) { int n = (buf[offset] & 0xff) << 24; n |= (buf[++offset] & 0xff) << 16; n |= (buf[++offset] & 0xff) << 8; n |= (buf[++offset] & 0xff); return n & 0xFFFFFFFFL; } public static long readUint48(InputStream input) throws IOException { int hi = readUint24(input); int lo = readUint24(input); return ((long)(hi & 0xffffffffL) << 24) | (long)(lo & 0xffffffffL); } public static long readUint48(byte[] buf, int offset) { int hi = readUint24(buf, offset); int lo = readUint24(buf, offset + 3); return ((long)(hi & 0xffffffffL) << 24) | (long)(lo & 0xffffffffL); } public static byte[] readAllOrNothing(int length, InputStream input) throws IOException { if (length < 1) { return EMPTY_BYTES; } byte[] buf = new byte[length]; int read = Streams.readFully(input, buf); if (read == 0) { return null; } if (read != length) { throw new EOFException(); } return buf; } public static byte[] readFully(int length, InputStream input) throws IOException { if (length < 1) { return EMPTY_BYTES; } byte[] buf = new byte[length]; if (length != Streams.readFully(input, buf)) { throw new EOFException(); } return buf; } public static void readFully(byte[] buf, InputStream input) throws IOException { int length = buf.length; if (length > 0 && length != Streams.readFully(input, buf)) { throw new EOFException(); } } public static byte[] readOpaque8(InputStream input) throws IOException { short length = readUint8(input); return readFully(length, input); } public static byte[] readOpaque16(InputStream input) throws IOException { int length = readUint16(input); return readFully(length, input); } public static byte[] readOpaque24(InputStream input) throws IOException { int length = readUint24(input); return readFully(length, input); } public static short[] readUint8Array(int count, InputStream input) throws IOException { short[] uints = new short[count]; for (int i = 0; i < count; ++i) { uints[i] = readUint8(input); } return uints; } public static int[] readUint16Array(int count, InputStream input) throws IOException { int[] uints = new int[count]; for (int i = 0; i < count; ++i) { uints[i] = readUint16(input); } return uints; } public static ProtocolVersion readVersion(byte[] buf, int offset) throws IOException { return ProtocolVersion.get(buf[offset] & 0xFF, buf[offset + 1] & 0xFF); } public static ProtocolVersion readVersion(InputStream input) throws IOException { int i1 = input.read(); int i2 = input.read(); if (i2 < 0) { throw new EOFException(); } return ProtocolVersion.get(i1, i2); } public static int readVersionRaw(byte[] buf, int offset) throws IOException { return (buf[offset] << 8) | buf[offset + 1]; } public static int readVersionRaw(InputStream input) throws IOException { int i1 = input.read(); int i2 = input.read(); if (i2 < 0) { throw new EOFException(); } return (i1 << 8) | i2; } public static ASN1Primitive readASN1Object(byte[] encoding) throws IOException { ASN1InputStream asn1 = new ASN1InputStream(encoding); ASN1Primitive result = asn1.readObject(); if (null == result) { throw new TlsFatalAlert(AlertDescription.decode_error); } if (null != asn1.readObject()) { throw new TlsFatalAlert(AlertDescription.decode_error); } return result; } public static ASN1Primitive readDERObject(byte[] encoding) throws IOException { /* * NOTE: The current ASN.1 parsing code can't enforce DER-only parsing, but since DER is * canonical, we can check it by re-encoding the result and comparing to the original. */ ASN1Primitive result = readASN1Object(encoding); byte[] check = result.getEncoded(ASN1Encoding.DER); if (!Arrays.areEqual(check, encoding)) { throw new TlsFatalAlert(AlertDescription.decode_error); } return result; } public static void writeGMTUnixTime(byte[] buf, int offset) { int t = (int)(System.currentTimeMillis() / 1000L); buf[offset] = (byte)(t >>> 24); buf[offset + 1] = (byte)(t >>> 16); buf[offset + 2] = (byte)(t >>> 8); buf[offset + 3] = (byte)t; } public static void writeVersion(ProtocolVersion version, OutputStream output) throws IOException { output.write(version.getMajorVersion()); output.write(version.getMinorVersion()); } public static void writeVersion(ProtocolVersion version, byte[] buf, int offset) { buf[offset] = (byte)version.getMajorVersion(); buf[offset + 1] = (byte)version.getMinorVersion(); } public static Vector getDefaultDSSSignatureAlgorithms() { return vectorOfOne(new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.dsa)); } public static Vector getDefaultECDSASignatureAlgorithms() { return vectorOfOne(new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.ecdsa)); } public static Vector getDefaultRSASignatureAlgorithms() { return vectorOfOne(new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.rsa)); } public static byte[] getExtensionData(Hashtable extensions, Integer extensionType) { return extensions == null ? null : (byte[])extensions.get(extensionType); } public static boolean hasExpectedEmptyExtensionData(Hashtable extensions, Integer extensionType, short alertDescription) throws IOException { byte[] extension_data = getExtensionData(extensions, extensionType); if (extension_data == null) { return false; } if (extension_data.length != 0) { throw new TlsFatalAlert(alertDescription); } return true; } public static TlsSession importSession(byte[] sessionID, SessionParameters sessionParameters) { return new TlsSessionImpl(sessionID, sessionParameters); } public static boolean isSignatureAlgorithmsExtensionAllowed(ProtocolVersion clientVersion) { return ProtocolVersion.TLSv12.isEqualOrEarlierVersionOf(clientVersion.getEquivalentTLSVersion()); } /** * Add a 'signature_algorithms' extension to existing extensions. * * @param extensions A {@link Hashtable} to add the extension to. * @param supportedSignatureAlgorithms {@link Vector} containing at least 1 {@link SignatureAndHashAlgorithm}. * @throws IOException */ public static void addSignatureAlgorithmsExtension(Hashtable extensions, Vector supportedSignatureAlgorithms) throws IOException { extensions.put(EXT_signature_algorithms, createSignatureAlgorithmsExtension(supportedSignatureAlgorithms)); } /** * Get a 'signature_algorithms' extension from extensions. * * @param extensions A {@link Hashtable} to get the extension from, if it is present. * @return A {@link Vector} containing at least 1 {@link SignatureAndHashAlgorithm}, or null. * @throws IOException */ public static Vector getSignatureAlgorithmsExtension(Hashtable extensions) throws IOException { byte[] extensionData = getExtensionData(extensions, EXT_signature_algorithms); return extensionData == null ? null : readSignatureAlgorithmsExtension(extensionData); } /** * Create a 'signature_algorithms' extension value. * * @param supportedSignatureAlgorithms A {@link Vector} containing at least 1 {@link SignatureAndHashAlgorithm}. * @return A byte array suitable for use as an extension value. * @throws IOException */ public static byte[] createSignatureAlgorithmsExtension(Vector supportedSignatureAlgorithms) throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); // supported_signature_algorithms encodeSupportedSignatureAlgorithms(supportedSignatureAlgorithms, false, buf); return buf.toByteArray(); } /** * Read 'signature_algorithms' extension data. * * @param extensionData The extension data. * @return A {@link Vector} containing at least 1 {@link SignatureAndHashAlgorithm}. * @throws IOException */ public static Vector readSignatureAlgorithmsExtension(byte[] extensionData) throws IOException { if (extensionData == null) { throw new IllegalArgumentException("'extensionData' cannot be null"); } ByteArrayInputStream buf = new ByteArrayInputStream(extensionData); // supported_signature_algorithms Vector supported_signature_algorithms = parseSupportedSignatureAlgorithms(false, buf); TlsProtocol.assertEmpty(buf); return supported_signature_algorithms; } public static void encodeSupportedSignatureAlgorithms(Vector supportedSignatureAlgorithms, boolean allowAnonymous, OutputStream output) throws IOException { if (supportedSignatureAlgorithms == null || supportedSignatureAlgorithms.size() < 1 || supportedSignatureAlgorithms.size() >= (1 << 15)) { throw new IllegalArgumentException( "'supportedSignatureAlgorithms' must have length from 1 to (2^15 - 1)"); } // supported_signature_algorithms int length = 2 * supportedSignatureAlgorithms.size(); checkUint16(length); writeUint16(length, output); for (int i = 0; i < supportedSignatureAlgorithms.size(); ++i) { SignatureAndHashAlgorithm entry = (SignatureAndHashAlgorithm)supportedSignatureAlgorithms.elementAt(i); if (!allowAnonymous && entry.getSignature() == SignatureAlgorithm.anonymous) { /* * RFC 5246 7.4.1.4.1 The "anonymous" value is meaningless in this context but used * in Section 7.4.3. It MUST NOT appear in this extension. */ throw new IllegalArgumentException( "SignatureAlgorithm.anonymous MUST NOT appear in the signature_algorithms extension"); } entry.encode(output); } } public static Vector parseSupportedSignatureAlgorithms(boolean allowAnonymous, InputStream input) throws IOException { // supported_signature_algorithms int length = readUint16(input); if (length < 2 || (length & 1) != 0) { throw new TlsFatalAlert(AlertDescription.decode_error); } int count = length / 2; Vector supportedSignatureAlgorithms = new Vector(count); for (int i = 0; i < count; ++i) { SignatureAndHashAlgorithm entry = SignatureAndHashAlgorithm.parse(input); if (!allowAnonymous && entry.getSignature() == SignatureAlgorithm.anonymous) { /* * RFC 5246 7.4.1.4.1 The "anonymous" value is meaningless in this context but used * in Section 7.4.3. It MUST NOT appear in this extension. */ throw new TlsFatalAlert(AlertDescription.illegal_parameter); } supportedSignatureAlgorithms.addElement(entry); } return supportedSignatureAlgorithms; } public static byte[] PRF(TlsContext context, byte[] secret, String asciiLabel, byte[] seed, int size) { ProtocolVersion version = context.getServerVersion(); if (version.isSSL()) { throw new IllegalStateException("No PRF available for SSLv3 session"); } byte[] label = Strings.toByteArray(asciiLabel); byte[] labelSeed = concat(label, seed); int prfAlgorithm = context.getSecurityParameters().getPrfAlgorithm(); if (prfAlgorithm == PRFAlgorithm.tls_prf_legacy) { return PRF_legacy(secret, label, labelSeed, size); } Digest prfDigest = createPRFHash(prfAlgorithm); byte[] buf = new byte[size]; hmac_hash(prfDigest, secret, labelSeed, buf); return buf; } public static byte[] PRF_legacy(byte[] secret, String asciiLabel, byte[] seed, int size) { byte[] label = Strings.toByteArray(asciiLabel); byte[] labelSeed = concat(label, seed); return PRF_legacy(secret, label, labelSeed, size); } static byte[] PRF_legacy(byte[] secret, byte[] label, byte[] labelSeed, int size) { int s_half = (secret.length + 1) / 2; byte[] s1 = new byte[s_half]; byte[] s2 = new byte[s_half]; System.arraycopy(secret, 0, s1, 0, s_half); System.arraycopy(secret, secret.length - s_half, s2, 0, s_half); byte[] b1 = new byte[size]; byte[] b2 = new byte[size]; hmac_hash(createHash(HashAlgorithm.md5), s1, labelSeed, b1); hmac_hash(createHash(HashAlgorithm.sha1), s2, labelSeed, b2); for (int i = 0; i < size; i++) { b1[i] ^= b2[i]; } return b1; } static byte[] concat(byte[] a, byte[] b) { byte[] c = new byte[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static void hmac_hash(Digest digest, byte[] secret, byte[] seed, byte[] out) { HMac mac = new HMac(digest); mac.init(new KeyParameter(secret)); byte[] a = seed; int size = digest.getDigestSize(); int iterations = (out.length + size - 1) / size; byte[] buf = new byte[mac.getMacSize()]; byte[] buf2 = new byte[mac.getMacSize()]; for (int i = 0; i < iterations; i++) { mac.update(a, 0, a.length); mac.doFinal(buf, 0); a = buf; mac.update(a, 0, a.length); mac.update(seed, 0, seed.length); mac.doFinal(buf2, 0); System.arraycopy(buf2, 0, out, (size * i), Math.min(size, out.length - (size * i))); } } static void validateKeyUsage(org.bouncycastle.asn1.x509.Certificate c, int keyUsageBits) throws IOException { Extensions exts = c.getTBSCertificate().getExtensions(); if (exts != null) { KeyUsage ku = KeyUsage.fromExtensions(exts); if (ku != null) { int bits = ku.getBytes()[0] & 0xff; if ((bits & keyUsageBits) != keyUsageBits) { throw new TlsFatalAlert(AlertDescription.certificate_unknown); } } } } static byte[] calculateKeyBlock(TlsContext context, int size) { SecurityParameters securityParameters = context.getSecurityParameters(); byte[] master_secret = securityParameters.getMasterSecret(); byte[] seed = concat(securityParameters.getServerRandom(), securityParameters.getClientRandom()); if (isSSL(context)) { return calculateKeyBlock_SSL(master_secret, seed, size); } return PRF(context, master_secret, ExporterLabel.key_expansion, seed, size); } static byte[] calculateKeyBlock_SSL(byte[] master_secret, byte[] random, int size) { Digest md5 = createHash(HashAlgorithm.md5); Digest sha1 = createHash(HashAlgorithm.sha1); int md5Size = md5.getDigestSize(); byte[] shatmp = new byte[sha1.getDigestSize()]; byte[] tmp = new byte[size + md5Size]; int i = 0, pos = 0; while (pos < size) { byte[] ssl3Const = SSL3_CONST[i]; sha1.update(ssl3Const, 0, ssl3Const.length); sha1.update(master_secret, 0, master_secret.length); sha1.update(random, 0, random.length); sha1.doFinal(shatmp, 0); md5.update(master_secret, 0, master_secret.length); md5.update(shatmp, 0, shatmp.length); md5.doFinal(tmp, pos); pos += md5Size; ++i; } return Arrays.copyOfRange(tmp, 0, size); } static byte[] calculateMasterSecret(TlsContext context, byte[] pre_master_secret) { SecurityParameters securityParameters = context.getSecurityParameters(); byte[] seed; if (securityParameters.extendedMasterSecret) { seed = securityParameters.getSessionHash(); } else { seed = concat(securityParameters.getClientRandom(), securityParameters.getServerRandom()); } if (isSSL(context)) { return calculateMasterSecret_SSL(pre_master_secret, seed); } String asciiLabel = securityParameters.extendedMasterSecret ? ExporterLabel.extended_master_secret : ExporterLabel.master_secret; return PRF(context, pre_master_secret, asciiLabel, seed, 48); } static byte[] calculateMasterSecret_SSL(byte[] pre_master_secret, byte[] random) { Digest md5 = createHash(HashAlgorithm.md5); Digest sha1 = createHash(HashAlgorithm.sha1); int md5Size = md5.getDigestSize(); byte[] shatmp = new byte[sha1.getDigestSize()]; byte[] rval = new byte[md5Size * 3]; int pos = 0; for (int i = 0; i < 3; ++i) { byte[] ssl3Const = SSL3_CONST[i]; sha1.update(ssl3Const, 0, ssl3Const.length); sha1.update(pre_master_secret, 0, pre_master_secret.length); sha1.update(random, 0, random.length); sha1.doFinal(shatmp, 0); md5.update(pre_master_secret, 0, pre_master_secret.length); md5.update(shatmp, 0, shatmp.length); md5.doFinal(rval, pos); pos += md5Size; } return rval; } static byte[] calculateVerifyData(TlsContext context, String asciiLabel, byte[] handshakeHash) { if (isSSL(context)) { return handshakeHash; } SecurityParameters securityParameters = context.getSecurityParameters(); byte[] master_secret = securityParameters.getMasterSecret(); int verify_data_length = securityParameters.getVerifyDataLength(); return PRF(context, master_secret, asciiLabel, handshakeHash, verify_data_length); } public static Digest createHash(short hashAlgorithm) { switch (hashAlgorithm) { case HashAlgorithm.md5: return new MD5Digest(); case HashAlgorithm.sha1: return new SHA1Digest(); case HashAlgorithm.sha224: return new SHA224Digest(); case HashAlgorithm.sha256: return new SHA256Digest(); case HashAlgorithm.sha384: return new SHA384Digest(); case HashAlgorithm.sha512: return new SHA512Digest(); default: throw new IllegalArgumentException("unknown HashAlgorithm"); } } public static Digest cloneHash(short hashAlgorithm, Digest hash) { switch (hashAlgorithm) { case HashAlgorithm.md5: return new MD5Digest((MD5Digest)hash); case HashAlgorithm.sha1: return new SHA1Digest((SHA1Digest)hash); case HashAlgorithm.sha224: return new SHA224Digest((SHA224Digest)hash); case HashAlgorithm.sha256: return new SHA256Digest((SHA256Digest)hash); case HashAlgorithm.sha384: return new SHA384Digest((SHA384Digest)hash); case HashAlgorithm.sha512: return new SHA512Digest((SHA512Digest)hash); default: throw new IllegalArgumentException("unknown HashAlgorithm"); } } public static Digest createPRFHash(int prfAlgorithm) { switch (prfAlgorithm) { case PRFAlgorithm.tls_prf_legacy: return new CombinedHash(); default: return createHash(getHashAlgorithmForPRFAlgorithm(prfAlgorithm)); } } public static Digest clonePRFHash(int prfAlgorithm, Digest hash) { switch (prfAlgorithm) { case PRFAlgorithm.tls_prf_legacy: return new CombinedHash((CombinedHash)hash); default: return cloneHash(getHashAlgorithmForPRFAlgorithm(prfAlgorithm), hash); } } public static short getHashAlgorithmForPRFAlgorithm(int prfAlgorithm) { switch (prfAlgorithm) { case PRFAlgorithm.tls_prf_legacy: throw new IllegalArgumentException("legacy PRF not a valid algorithm"); case PRFAlgorithm.tls_prf_sha256: return HashAlgorithm.sha256; case PRFAlgorithm.tls_prf_sha384: return HashAlgorithm.sha384; default: throw new IllegalArgumentException("unknown PRFAlgorithm"); } } public static ASN1ObjectIdentifier getOIDForHashAlgorithm(short hashAlgorithm) { switch (hashAlgorithm) { case HashAlgorithm.md5: return PKCSObjectIdentifiers.md5; case HashAlgorithm.sha1: return X509ObjectIdentifiers.id_SHA1; case HashAlgorithm.sha224: return NISTObjectIdentifiers.id_sha224; case HashAlgorithm.sha256: return NISTObjectIdentifiers.id_sha256; case HashAlgorithm.sha384: return NISTObjectIdentifiers.id_sha384; case HashAlgorithm.sha512: return NISTObjectIdentifiers.id_sha512; default: throw new IllegalArgumentException("unknown HashAlgorithm"); } } static short getClientCertificateType(Certificate clientCertificate, Certificate serverCertificate) throws IOException { if (clientCertificate.isEmpty()) { return -1; } org.bouncycastle.asn1.x509.Certificate x509Cert = clientCertificate.getCertificateAt(0); SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo(); try { AsymmetricKeyParameter publicKey = PublicKeyFactory.createKey(keyInfo); if (publicKey.isPrivate()) { throw new TlsFatalAlert(AlertDescription.internal_error); } /* * TODO RFC 5246 7.4.6. The certificates MUST be signed using an acceptable hash/ * signature algorithm pair, as described in Section 7.4.4. Note that this relaxes the * constraints on certificate-signing algorithms found in prior versions of TLS. */ /* * RFC 5246 7.4.6. Client Certificate */ /* * RSA public key; the certificate MUST allow the key to be used for signing with the * signature scheme and hash algorithm that will be employed in the certificate verify * message. */ if (publicKey instanceof RSAKeyParameters) { validateKeyUsage(x509Cert, KeyUsage.digitalSignature); return ClientCertificateType.rsa_sign; } /* * DSA public key; the certificate MUST allow the key to be used for signing with the * hash algorithm that will be employed in the certificate verify message. */ if (publicKey instanceof DSAPublicKeyParameters) { validateKeyUsage(x509Cert, KeyUsage.digitalSignature); return ClientCertificateType.dss_sign; } /* * ECDSA-capable public key; the certificate MUST allow the key to be used for signing * with the hash algorithm that will be employed in the certificate verify message; the * public key MUST use a curve and point format supported by the server. */ if (publicKey instanceof ECPublicKeyParameters) { validateKeyUsage(x509Cert, KeyUsage.digitalSignature); // TODO Check the curve and point format return ClientCertificateType.ecdsa_sign; } // TODO Add support for ClientCertificateType.*_fixed_* throw new TlsFatalAlert(AlertDescription.unsupported_certificate); } catch (Exception e) { throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e); } } static void trackHashAlgorithms(TlsHandshakeHash handshakeHash, Vector supportedSignatureAlgorithms) { if (supportedSignatureAlgorithms != null) { for (int i = 0; i < supportedSignatureAlgorithms.size(); ++i) { SignatureAndHashAlgorithm signatureAndHashAlgorithm = (SignatureAndHashAlgorithm) supportedSignatureAlgorithms.elementAt(i); short hashAlgorithm = signatureAndHashAlgorithm.getHash(); handshakeHash.trackHashAlgorithm(hashAlgorithm); } } } public static boolean hasSigningCapability(short clientCertificateType) { switch (clientCertificateType) { case ClientCertificateType.dss_sign: case ClientCertificateType.ecdsa_sign: case ClientCertificateType.rsa_sign: return true; default: return false; } } public static TlsSigner createTlsSigner(short clientCertificateType) { switch (clientCertificateType) { case ClientCertificateType.dss_sign: return new TlsDSSSigner(); case ClientCertificateType.ecdsa_sign: return new TlsECDSASigner(); case ClientCertificateType.rsa_sign: return new TlsRSASigner(); default: throw new IllegalArgumentException("'clientCertificateType' is not a type with signing capability"); } } static final byte[] SSL_CLIENT = {0x43, 0x4C, 0x4E, 0x54}; static final byte[] SSL_SERVER = {0x53, 0x52, 0x56, 0x52}; // SSL3 magic mix constants ("A", "BB", "CCC", ...) static final byte[][] SSL3_CONST = genSSL3Const(); private static byte[][] genSSL3Const() { int n = 10; byte[][] arr = new byte[n][]; for (int i = 0; i < n; i++) { byte[] b = new byte[i + 1]; Arrays.fill(b, (byte)('A' + i)); arr[i] = b; } return arr; } private static Vector vectorOfOne(Object obj) { Vector v = new Vector(1); v.addElement(obj); return v; } public static int getCipherType(int ciphersuite) throws IOException { switch (getEncryptionAlgorithm(ciphersuite)) { case EncryptionAlgorithm.AES_128_GCM: case EncryptionAlgorithm.AES_256_GCM: case EncryptionAlgorithm.AES_128_CCM: case EncryptionAlgorithm.AES_128_CCM_8: case EncryptionAlgorithm.AES_256_CCM: case EncryptionAlgorithm.AES_256_CCM_8: case EncryptionAlgorithm.CAMELLIA_128_GCM: case EncryptionAlgorithm.CAMELLIA_256_GCM: case EncryptionAlgorithm.AEAD_CHACHA20_POLY1305: return CipherType.aead; case EncryptionAlgorithm.RC2_CBC_40: case EncryptionAlgorithm.IDEA_CBC: case EncryptionAlgorithm.DES40_CBC: case EncryptionAlgorithm.DES_CBC: case EncryptionAlgorithm._3DES_EDE_CBC: case EncryptionAlgorithm.AES_128_CBC: case EncryptionAlgorithm.AES_256_CBC: case EncryptionAlgorithm.CAMELLIA_128_CBC: case EncryptionAlgorithm.CAMELLIA_256_CBC: case EncryptionAlgorithm.SEED_CBC: return CipherType.block; case EncryptionAlgorithm.RC4_40: case EncryptionAlgorithm.RC4_128: case EncryptionAlgorithm.ESTREAM_SALSA20: case EncryptionAlgorithm.SALSA20: return CipherType.stream; default: throw new TlsFatalAlert(AlertDescription.internal_error); } } public static int getEncryptionAlgorithm(int ciphersuite) throws IOException { switch (ciphersuite) { case CipherSuite.TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA: return EncryptionAlgorithm._3DES_EDE_CBC; case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: return EncryptionAlgorithm.AEAD_CHACHA20_POLY1305; case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_SRP_SHA_WITH_AES_128_CBC_SHA: return EncryptionAlgorithm.AES_128_CBC; case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256: return EncryptionAlgorithm.AES_128_CBC; case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM: case CipherSuite.TLS_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_RSA_WITH_AES_128_CCM: return EncryptionAlgorithm.AES_128_CCM; case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8: case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8: return EncryptionAlgorithm.AES_128_CCM_8; case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256: return EncryptionAlgorithm.AES_128_GCM; case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_SRP_SHA_WITH_AES_256_CBC_SHA: return EncryptionAlgorithm.AES_256_CBC; case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256: return EncryptionAlgorithm.AES_256_CBC; case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA384: return EncryptionAlgorithm.AES_256_CBC; case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM: case CipherSuite.TLS_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_RSA_WITH_AES_256_CCM: return EncryptionAlgorithm.AES_256_CCM; case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8: case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8: return EncryptionAlgorithm.AES_256_CCM_8; case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384: return EncryptionAlgorithm.AES_256_GCM; case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA: return EncryptionAlgorithm.CAMELLIA_128_CBC; case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256: return EncryptionAlgorithm.CAMELLIA_128_CBC; case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256: return EncryptionAlgorithm.CAMELLIA_128_GCM; case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA: return EncryptionAlgorithm.CAMELLIA_256_CBC; case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256: return EncryptionAlgorithm.CAMELLIA_256_CBC; case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384: return EncryptionAlgorithm.CAMELLIA_256_CBC; case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384: return EncryptionAlgorithm.CAMELLIA_256_GCM; case CipherSuite.TLS_DHE_PSK_WITH_ESTREAM_SALSA20_SHA1: case CipherSuite.TLS_DHE_RSA_WITH_ESTREAM_SALSA20_SHA1: case CipherSuite.TLS_ECDHE_ECDSA_WITH_ESTREAM_SALSA20_SHA1: case CipherSuite.TLS_ECDHE_PSK_WITH_ESTREAM_SALSA20_SHA1: case CipherSuite.TLS_ECDHE_RSA_WITH_ESTREAM_SALSA20_SHA1: case CipherSuite.TLS_PSK_WITH_ESTREAM_SALSA20_SHA1: case CipherSuite.TLS_RSA_PSK_WITH_ESTREAM_SALSA20_SHA1: case CipherSuite.TLS_RSA_WITH_ESTREAM_SALSA20_SHA1: return EncryptionAlgorithm.ESTREAM_SALSA20; case CipherSuite.TLS_RSA_WITH_NULL_MD5: return EncryptionAlgorithm.NULL; case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_NULL_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_NULL_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_NULL_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_NULL_SHA: case CipherSuite.TLS_PSK_WITH_NULL_SHA: case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA: case CipherSuite.TLS_RSA_WITH_NULL_SHA: return EncryptionAlgorithm.NULL; case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_RSA_WITH_NULL_SHA256: return EncryptionAlgorithm.NULL; case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA384: return EncryptionAlgorithm.NULL; case CipherSuite.TLS_DH_anon_WITH_RC4_128_MD5: case CipherSuite.TLS_RSA_WITH_RC4_128_MD5: return EncryptionAlgorithm.RC4_128; case CipherSuite.TLS_DHE_PSK_WITH_RC4_128_SHA: case CipherSuite.TLS_ECDH_anon_WITH_RC4_128_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_RC4_128_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_RC4_128_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_RC4_128_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_RC4_128_SHA: case CipherSuite.TLS_PSK_WITH_RC4_128_SHA: case CipherSuite.TLS_RSA_WITH_RC4_128_SHA: case CipherSuite.TLS_RSA_PSK_WITH_RC4_128_SHA: return EncryptionAlgorithm.RC4_128; case CipherSuite.TLS_DHE_PSK_WITH_SALSA20_SHA1: case CipherSuite.TLS_DHE_RSA_WITH_SALSA20_SHA1: case CipherSuite.TLS_ECDHE_ECDSA_WITH_SALSA20_SHA1: case CipherSuite.TLS_ECDHE_PSK_WITH_SALSA20_SHA1: case CipherSuite.TLS_ECDHE_RSA_WITH_SALSA20_SHA1: case CipherSuite.TLS_PSK_WITH_SALSA20_SHA1: case CipherSuite.TLS_RSA_PSK_WITH_SALSA20_SHA1: case CipherSuite.TLS_RSA_WITH_SALSA20_SHA1: return EncryptionAlgorithm.SALSA20; case CipherSuite.TLS_DH_DSS_WITH_SEED_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_SEED_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_SEED_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_SEED_CBC_SHA: case CipherSuite.TLS_RSA_WITH_SEED_CBC_SHA: return EncryptionAlgorithm.SEED_CBC; default: throw new TlsFatalAlert(AlertDescription.internal_error); } } public static ProtocolVersion getMinimumVersion(int ciphersuite) { switch (ciphersuite) { case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_AES_256_CCM: case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_NULL_SHA256: return ProtocolVersion.TLSv12; default: return ProtocolVersion.SSLv3; } } public static boolean isAEADCipherSuite(int ciphersuite) throws IOException { return CipherType.aead == getCipherType(ciphersuite); } public static boolean isBlockCipherSuite(int ciphersuite) throws IOException { return CipherType.block == getCipherType(ciphersuite); } public static boolean isStreamCipherSuite(int ciphersuite) throws IOException { return CipherType.stream == getCipherType(ciphersuite); } public static boolean isValidCipherSuiteForVersion(int cipherSuite, ProtocolVersion serverVersion) { return getMinimumVersion(cipherSuite).isEqualOrEarlierVersionOf(serverVersion.getEquivalentTLSVersion()); } }
core/src/main/java/org/bouncycastle/crypto/tls/TlsUtils.java
package org.bouncycastle.crypto.tls; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Hashtable; import java.util.Vector; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.Extensions; import org.bouncycastle.asn1.x509.KeyUsage; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.digests.MD5Digest; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.digests.SHA224Digest; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.digests.SHA384Digest; import org.bouncycastle.crypto.digests.SHA512Digest; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.DSAPublicKeyParameters; import org.bouncycastle.crypto.params.ECPublicKeyParameters; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.RSAKeyParameters; import org.bouncycastle.crypto.util.PublicKeyFactory; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Integers; import org.bouncycastle.util.Strings; import org.bouncycastle.util.io.Streams; /** * Some helper functions for MicroTLS. */ public class TlsUtils { public static final byte[] EMPTY_BYTES = new byte[0]; public static final Integer EXT_signature_algorithms = Integers.valueOf(ExtensionType.signature_algorithms); public static void checkUint8(short i) throws IOException { if (!isValidUint8(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint8(int i) throws IOException { if (!isValidUint8(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint8(long i) throws IOException { if (!isValidUint8(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint16(int i) throws IOException { if (!isValidUint16(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint16(long i) throws IOException { if (!isValidUint16(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint24(int i) throws IOException { if (!isValidUint24(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint24(long i) throws IOException { if (!isValidUint24(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint32(long i) throws IOException { if (!isValidUint32(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint48(long i) throws IOException { if (!isValidUint48(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint64(long i) throws IOException { if (!isValidUint64(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static boolean isValidUint8(short i) { return (i & 0xFF) == i; } public static boolean isValidUint8(int i) { return (i & 0xFF) == i; } public static boolean isValidUint8(long i) { return (i & 0xFFL) == i; } public static boolean isValidUint16(int i) { return (i & 0xFFFF) == i; } public static boolean isValidUint16(long i) { return (i & 0xFFFFL) == i; } public static boolean isValidUint24(int i) { return (i & 0xFFFFFF) == i; } public static boolean isValidUint24(long i) { return (i & 0xFFFFFFL) == i; } public static boolean isValidUint32(long i) { return (i & 0xFFFFFFFFL) == i; } public static boolean isValidUint48(long i) { return (i & 0xFFFFFFFFFFFFL) == i; } public static boolean isValidUint64(long i) { return true; } public static boolean isSSL(TlsContext context) { return context.getServerVersion().isSSL(); } public static boolean isTLSv11(TlsContext context) { return ProtocolVersion.TLSv11.isEqualOrEarlierVersionOf(context.getServerVersion().getEquivalentTLSVersion()); } public static boolean isTLSv12(TlsContext context) { return ProtocolVersion.TLSv12.isEqualOrEarlierVersionOf(context.getServerVersion().getEquivalentTLSVersion()); } public static void writeUint8(short i, OutputStream output) throws IOException { output.write(i); } public static void writeUint8(int i, OutputStream output) throws IOException { output.write(i); } public static void writeUint8(short i, byte[] buf, int offset) { buf[offset] = (byte)i; } public static void writeUint8(int i, byte[] buf, int offset) { buf[offset] = (byte)i; } public static void writeUint16(int i, OutputStream output) throws IOException { output.write(i >>> 8); output.write(i); } public static void writeUint16(int i, byte[] buf, int offset) { buf[offset] = (byte)(i >>> 8); buf[offset + 1] = (byte)i; } public static void writeUint24(int i, OutputStream output) throws IOException { output.write((byte)(i >>> 16)); output.write((byte)(i >>> 8)); output.write((byte)i); } public static void writeUint24(int i, byte[] buf, int offset) { buf[offset] = (byte)(i >>> 16); buf[offset + 1] = (byte)(i >>> 8); buf[offset + 2] = (byte)i; } public static void writeUint32(long i, OutputStream output) throws IOException { output.write((byte)(i >>> 24)); output.write((byte)(i >>> 16)); output.write((byte)(i >>> 8)); output.write((byte)i); } public static void writeUint32(long i, byte[] buf, int offset) { buf[offset] = (byte)(i >>> 24); buf[offset + 1] = (byte)(i >>> 16); buf[offset + 2] = (byte)(i >>> 8); buf[offset + 3] = (byte)i; } public static void writeUint48(long i, OutputStream output) throws IOException { output.write((byte)(i >>> 40)); output.write((byte)(i >>> 32)); output.write((byte)(i >>> 24)); output.write((byte)(i >>> 16)); output.write((byte)(i >>> 8)); output.write((byte)i); } public static void writeUint48(long i, byte[] buf, int offset) { buf[offset] = (byte)(i >>> 40); buf[offset + 1] = (byte)(i >>> 32); buf[offset + 2] = (byte)(i >>> 24); buf[offset + 3] = (byte)(i >>> 16); buf[offset + 4] = (byte)(i >>> 8); buf[offset + 5] = (byte)i; } public static void writeUint64(long i, OutputStream output) throws IOException { output.write((byte)(i >>> 56)); output.write((byte)(i >>> 48)); output.write((byte)(i >>> 40)); output.write((byte)(i >>> 32)); output.write((byte)(i >>> 24)); output.write((byte)(i >>> 16)); output.write((byte)(i >>> 8)); output.write((byte)i); } public static void writeUint64(long i, byte[] buf, int offset) { buf[offset] = (byte)(i >>> 56); buf[offset + 1] = (byte)(i >>> 48); buf[offset + 2] = (byte)(i >>> 40); buf[offset + 3] = (byte)(i >>> 32); buf[offset + 4] = (byte)(i >>> 24); buf[offset + 5] = (byte)(i >>> 16); buf[offset + 6] = (byte)(i >>> 8); buf[offset + 7] = (byte)i; } public static void writeOpaque8(byte[] buf, OutputStream output) throws IOException { checkUint8(buf.length); writeUint8(buf.length, output); output.write(buf); } public static void writeOpaque16(byte[] buf, OutputStream output) throws IOException { checkUint16(buf.length); writeUint16(buf.length, output); output.write(buf); } public static void writeOpaque24(byte[] buf, OutputStream output) throws IOException { checkUint24(buf.length); writeUint24(buf.length, output); output.write(buf); } public static void writeUint8Array(short[] uints, OutputStream output) throws IOException { for (int i = 0; i < uints.length; ++i) { writeUint8(uints[i], output); } } public static void writeUint8Array(short[] uints, byte[] buf, int offset) throws IOException { for (int i = 0; i < uints.length; ++i) { writeUint8(uints[i], buf, offset); ++offset; } } public static void writeUint8ArrayWithUint8Length(short[] uints, OutputStream output) throws IOException { checkUint8(uints.length); writeUint8(uints.length, output); writeUint8Array(uints, output); } public static void writeUint8ArrayWithUint8Length(short[] uints, byte[] buf, int offset) throws IOException { checkUint8(uints.length); writeUint8(uints.length, buf, offset); writeUint8Array(uints, buf, offset + 1); } public static void writeUint16Array(int[] uints, OutputStream output) throws IOException { for (int i = 0; i < uints.length; ++i) { writeUint16(uints[i], output); } } public static void writeUint16Array(int[] uints, byte[] buf, int offset) throws IOException { for (int i = 0; i < uints.length; ++i) { writeUint16(uints[i], buf, offset); offset += 2; } } public static void writeUint16ArrayWithUint16Length(int[] uints, OutputStream output) throws IOException { int length = 2 * uints.length; checkUint16(length); writeUint16(length, output); writeUint16Array(uints, output); } public static void writeUint16ArrayWithUint16Length(int[] uints, byte[] buf, int offset) throws IOException { int length = 2 * uints.length; checkUint16(length); writeUint16(length, buf, offset); writeUint16Array(uints, buf, offset + 2); } public static byte[] encodeOpaque8(byte[] buf) throws IOException { checkUint8(buf.length); return Arrays.prepend(buf, (byte)buf.length); } public static byte[] encodeUint8ArrayWithUint8Length(short[] uints) throws IOException { byte[] result = new byte[1 + uints.length]; writeUint8ArrayWithUint8Length(uints, result, 0); return result; } public static byte[] encodeUint16ArrayWithUint16Length(int[] uints) throws IOException { int length = 2 * uints.length; byte[] result = new byte[2 + length]; writeUint16ArrayWithUint16Length(uints, result, 0); return result; } public static short readUint8(InputStream input) throws IOException { int i = input.read(); if (i < 0) { throw new EOFException(); } return (short)i; } public static short readUint8(byte[] buf, int offset) { return (short)buf[offset]; } public static int readUint16(InputStream input) throws IOException { int i1 = input.read(); int i2 = input.read(); if (i2 < 0) { throw new EOFException(); } return i1 << 8 | i2; } public static int readUint16(byte[] buf, int offset) { int n = (buf[offset] & 0xff) << 8; n |= (buf[++offset] & 0xff); return n; } public static int readUint24(InputStream input) throws IOException { int i1 = input.read(); int i2 = input.read(); int i3 = input.read(); if (i3 < 0) { throw new EOFException(); } return (i1 << 16) | (i2 << 8) | i3; } public static int readUint24(byte[] buf, int offset) { int n = (buf[offset] & 0xff) << 16; n |= (buf[++offset] & 0xff) << 8; n |= (buf[++offset] & 0xff); return n; } public static long readUint32(InputStream input) throws IOException { int i1 = input.read(); int i2 = input.read(); int i3 = input.read(); int i4 = input.read(); if (i4 < 0) { throw new EOFException(); } return ((i1 << 2) | (i2 << 16) | (i3 << 8) | i4) & 0xFFFFFFFFL; } public static long readUint32(byte[] buf, int offset) { int n = (buf[offset] & 0xff) << 24; n |= (buf[++offset] & 0xff) << 16; n |= (buf[++offset] & 0xff) << 8; n |= (buf[++offset] & 0xff); return n & 0xFFFFFFFFL; } public static long readUint48(InputStream input) throws IOException { int hi = readUint24(input); int lo = readUint24(input); return ((long)(hi & 0xffffffffL) << 24) | (long)(lo & 0xffffffffL); } public static long readUint48(byte[] buf, int offset) { int hi = readUint24(buf, offset); int lo = readUint24(buf, offset + 3); return ((long)(hi & 0xffffffffL) << 24) | (long)(lo & 0xffffffffL); } public static byte[] readAllOrNothing(int length, InputStream input) throws IOException { if (length < 1) { return EMPTY_BYTES; } byte[] buf = new byte[length]; int read = Streams.readFully(input, buf); if (read == 0) { return null; } if (read != length) { throw new EOFException(); } return buf; } public static byte[] readFully(int length, InputStream input) throws IOException { if (length < 1) { return EMPTY_BYTES; } byte[] buf = new byte[length]; if (length != Streams.readFully(input, buf)) { throw new EOFException(); } return buf; } public static void readFully(byte[] buf, InputStream input) throws IOException { int length = buf.length; if (length > 0 && length != Streams.readFully(input, buf)) { throw new EOFException(); } } public static byte[] readOpaque8(InputStream input) throws IOException { short length = readUint8(input); return readFully(length, input); } public static byte[] readOpaque16(InputStream input) throws IOException { int length = readUint16(input); return readFully(length, input); } public static byte[] readOpaque24(InputStream input) throws IOException { int length = readUint24(input); return readFully(length, input); } public static short[] readUint8Array(int count, InputStream input) throws IOException { short[] uints = new short[count]; for (int i = 0; i < count; ++i) { uints[i] = readUint8(input); } return uints; } public static int[] readUint16Array(int count, InputStream input) throws IOException { int[] uints = new int[count]; for (int i = 0; i < count; ++i) { uints[i] = readUint16(input); } return uints; } public static ProtocolVersion readVersion(byte[] buf, int offset) throws IOException { return ProtocolVersion.get(buf[offset] & 0xFF, buf[offset + 1] & 0xFF); } public static ProtocolVersion readVersion(InputStream input) throws IOException { int i1 = input.read(); int i2 = input.read(); if (i2 < 0) { throw new EOFException(); } return ProtocolVersion.get(i1, i2); } public static int readVersionRaw(byte[] buf, int offset) throws IOException { return (buf[offset] << 8) | buf[offset + 1]; } public static int readVersionRaw(InputStream input) throws IOException { int i1 = input.read(); int i2 = input.read(); if (i2 < 0) { throw new EOFException(); } return (i1 << 8) | i2; } public static ASN1Primitive readASN1Object(byte[] encoding) throws IOException { ASN1InputStream asn1 = new ASN1InputStream(encoding); ASN1Primitive result = asn1.readObject(); if (null == result) { throw new TlsFatalAlert(AlertDescription.decode_error); } if (null != asn1.readObject()) { throw new TlsFatalAlert(AlertDescription.decode_error); } return result; } public static ASN1Primitive readDERObject(byte[] encoding) throws IOException { /* * NOTE: The current ASN.1 parsing code can't enforce DER-only parsing, but since DER is * canonical, we can check it by re-encoding the result and comparing to the original. */ ASN1Primitive result = readASN1Object(encoding); byte[] check = result.getEncoded(ASN1Encoding.DER); if (!Arrays.areEqual(check, encoding)) { throw new TlsFatalAlert(AlertDescription.decode_error); } return result; } public static void writeGMTUnixTime(byte[] buf, int offset) { int t = (int)(System.currentTimeMillis() / 1000L); buf[offset] = (byte)(t >>> 24); buf[offset + 1] = (byte)(t >>> 16); buf[offset + 2] = (byte)(t >>> 8); buf[offset + 3] = (byte)t; } public static void writeVersion(ProtocolVersion version, OutputStream output) throws IOException { output.write(version.getMajorVersion()); output.write(version.getMinorVersion()); } public static void writeVersion(ProtocolVersion version, byte[] buf, int offset) { buf[offset] = (byte)version.getMajorVersion(); buf[offset + 1] = (byte)version.getMinorVersion(); } public static Vector getDefaultDSSSignatureAlgorithms() { return vectorOfOne(new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.dsa)); } public static Vector getDefaultECDSASignatureAlgorithms() { return vectorOfOne(new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.ecdsa)); } public static Vector getDefaultRSASignatureAlgorithms() { return vectorOfOne(new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.rsa)); } public static byte[] getExtensionData(Hashtable extensions, Integer extensionType) { return extensions == null ? null : (byte[])extensions.get(extensionType); } public static boolean hasExpectedEmptyExtensionData(Hashtable extensions, Integer extensionType, short alertDescription) throws IOException { byte[] extension_data = getExtensionData(extensions, extensionType); if (extension_data == null) { return false; } if (extension_data.length != 0) { throw new TlsFatalAlert(alertDescription); } return true; } public static TlsSession importSession(byte[] sessionID, SessionParameters sessionParameters) { return new TlsSessionImpl(sessionID, sessionParameters); } public static boolean isSignatureAlgorithmsExtensionAllowed(ProtocolVersion clientVersion) { return ProtocolVersion.TLSv12.isEqualOrEarlierVersionOf(clientVersion.getEquivalentTLSVersion()); } /** * Add a 'signature_algorithms' extension to existing extensions. * * @param extensions A {@link Hashtable} to add the extension to. * @param supportedSignatureAlgorithms {@link Vector} containing at least 1 {@link SignatureAndHashAlgorithm}. * @throws IOException */ public static void addSignatureAlgorithmsExtension(Hashtable extensions, Vector supportedSignatureAlgorithms) throws IOException { extensions.put(EXT_signature_algorithms, createSignatureAlgorithmsExtension(supportedSignatureAlgorithms)); } /** * Get a 'signature_algorithms' extension from extensions. * * @param extensions A {@link Hashtable} to get the extension from, if it is present. * @return A {@link Vector} containing at least 1 {@link SignatureAndHashAlgorithm}, or null. * @throws IOException */ public static Vector getSignatureAlgorithmsExtension(Hashtable extensions) throws IOException { byte[] extensionData = getExtensionData(extensions, EXT_signature_algorithms); return extensionData == null ? null : readSignatureAlgorithmsExtension(extensionData); } /** * Create a 'signature_algorithms' extension value. * * @param supportedSignatureAlgorithms A {@link Vector} containing at least 1 {@link SignatureAndHashAlgorithm}. * @return A byte array suitable for use as an extension value. * @throws IOException */ public static byte[] createSignatureAlgorithmsExtension(Vector supportedSignatureAlgorithms) throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); // supported_signature_algorithms encodeSupportedSignatureAlgorithms(supportedSignatureAlgorithms, false, buf); return buf.toByteArray(); } /** * Read 'signature_algorithms' extension data. * * @param extensionData The extension data. * @return A {@link Vector} containing at least 1 {@link SignatureAndHashAlgorithm}. * @throws IOException */ public static Vector readSignatureAlgorithmsExtension(byte[] extensionData) throws IOException { if (extensionData == null) { throw new IllegalArgumentException("'extensionData' cannot be null"); } ByteArrayInputStream buf = new ByteArrayInputStream(extensionData); // supported_signature_algorithms Vector supported_signature_algorithms = parseSupportedSignatureAlgorithms(false, buf); TlsProtocol.assertEmpty(buf); return supported_signature_algorithms; } public static void encodeSupportedSignatureAlgorithms(Vector supportedSignatureAlgorithms, boolean allowAnonymous, OutputStream output) throws IOException { if (supportedSignatureAlgorithms == null || supportedSignatureAlgorithms.size() < 1 || supportedSignatureAlgorithms.size() >= (1 << 15)) { throw new IllegalArgumentException( "'supportedSignatureAlgorithms' must have length from 1 to (2^15 - 1)"); } // supported_signature_algorithms int length = 2 * supportedSignatureAlgorithms.size(); checkUint16(length); writeUint16(length, output); for (int i = 0; i < supportedSignatureAlgorithms.size(); ++i) { SignatureAndHashAlgorithm entry = (SignatureAndHashAlgorithm)supportedSignatureAlgorithms.elementAt(i); if (!allowAnonymous && entry.getSignature() == SignatureAlgorithm.anonymous) { /* * RFC 5246 7.4.1.4.1 The "anonymous" value is meaningless in this context but used * in Section 7.4.3. It MUST NOT appear in this extension. */ throw new IllegalArgumentException( "SignatureAlgorithm.anonymous MUST NOT appear in the signature_algorithms extension"); } entry.encode(output); } } public static Vector parseSupportedSignatureAlgorithms(boolean allowAnonymous, InputStream input) throws IOException { // supported_signature_algorithms int length = readUint16(input); if (length < 2 || (length & 1) != 0) { throw new TlsFatalAlert(AlertDescription.decode_error); } int count = length / 2; Vector supportedSignatureAlgorithms = new Vector(count); for (int i = 0; i < count; ++i) { SignatureAndHashAlgorithm entry = SignatureAndHashAlgorithm.parse(input); if (!allowAnonymous && entry.getSignature() == SignatureAlgorithm.anonymous) { /* * RFC 5246 7.4.1.4.1 The "anonymous" value is meaningless in this context but used * in Section 7.4.3. It MUST NOT appear in this extension. */ throw new TlsFatalAlert(AlertDescription.illegal_parameter); } supportedSignatureAlgorithms.addElement(entry); } return supportedSignatureAlgorithms; } public static byte[] PRF(TlsContext context, byte[] secret, String asciiLabel, byte[] seed, int size) { ProtocolVersion version = context.getServerVersion(); if (version.isSSL()) { throw new IllegalStateException("No PRF available for SSLv3 session"); } byte[] label = Strings.toByteArray(asciiLabel); byte[] labelSeed = concat(label, seed); int prfAlgorithm = context.getSecurityParameters().getPrfAlgorithm(); if (prfAlgorithm == PRFAlgorithm.tls_prf_legacy) { return PRF_legacy(secret, label, labelSeed, size); } Digest prfDigest = createPRFHash(prfAlgorithm); byte[] buf = new byte[size]; hmac_hash(prfDigest, secret, labelSeed, buf); return buf; } public static byte[] PRF_legacy(byte[] secret, String asciiLabel, byte[] seed, int size) { byte[] label = Strings.toByteArray(asciiLabel); byte[] labelSeed = concat(label, seed); return PRF_legacy(secret, label, labelSeed, size); } static byte[] PRF_legacy(byte[] secret, byte[] label, byte[] labelSeed, int size) { int s_half = (secret.length + 1) / 2; byte[] s1 = new byte[s_half]; byte[] s2 = new byte[s_half]; System.arraycopy(secret, 0, s1, 0, s_half); System.arraycopy(secret, secret.length - s_half, s2, 0, s_half); byte[] b1 = new byte[size]; byte[] b2 = new byte[size]; hmac_hash(createHash(HashAlgorithm.md5), s1, labelSeed, b1); hmac_hash(createHash(HashAlgorithm.sha1), s2, labelSeed, b2); for (int i = 0; i < size; i++) { b1[i] ^= b2[i]; } return b1; } static byte[] concat(byte[] a, byte[] b) { byte[] c = new byte[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static void hmac_hash(Digest digest, byte[] secret, byte[] seed, byte[] out) { HMac mac = new HMac(digest); mac.init(new KeyParameter(secret)); byte[] a = seed; int size = digest.getDigestSize(); int iterations = (out.length + size - 1) / size; byte[] buf = new byte[mac.getMacSize()]; byte[] buf2 = new byte[mac.getMacSize()]; for (int i = 0; i < iterations; i++) { mac.update(a, 0, a.length); mac.doFinal(buf, 0); a = buf; mac.update(a, 0, a.length); mac.update(seed, 0, seed.length); mac.doFinal(buf2, 0); System.arraycopy(buf2, 0, out, (size * i), Math.min(size, out.length - (size * i))); } } static void validateKeyUsage(org.bouncycastle.asn1.x509.Certificate c, int keyUsageBits) throws IOException { Extensions exts = c.getTBSCertificate().getExtensions(); if (exts != null) { KeyUsage ku = KeyUsage.fromExtensions(exts); if (ku != null) { int bits = ku.getBytes()[0] & 0xff; if ((bits & keyUsageBits) != keyUsageBits) { throw new TlsFatalAlert(AlertDescription.certificate_unknown); } } } } static byte[] calculateKeyBlock(TlsContext context, int size) { SecurityParameters securityParameters = context.getSecurityParameters(); byte[] master_secret = securityParameters.getMasterSecret(); byte[] seed = concat(securityParameters.getServerRandom(), securityParameters.getClientRandom()); if (isSSL(context)) { return calculateKeyBlock_SSL(master_secret, seed, size); } return PRF(context, master_secret, ExporterLabel.key_expansion, seed, size); } static byte[] calculateKeyBlock_SSL(byte[] master_secret, byte[] random, int size) { Digest md5 = createHash(HashAlgorithm.md5); Digest sha1 = createHash(HashAlgorithm.sha1); int md5Size = md5.getDigestSize(); byte[] shatmp = new byte[sha1.getDigestSize()]; byte[] tmp = new byte[size + md5Size]; int i = 0, pos = 0; while (pos < size) { byte[] ssl3Const = SSL3_CONST[i]; sha1.update(ssl3Const, 0, ssl3Const.length); sha1.update(master_secret, 0, master_secret.length); sha1.update(random, 0, random.length); sha1.doFinal(shatmp, 0); md5.update(master_secret, 0, master_secret.length); md5.update(shatmp, 0, shatmp.length); md5.doFinal(tmp, pos); pos += md5Size; ++i; } return Arrays.copyOfRange(tmp, 0, size); } static byte[] calculateMasterSecret(TlsContext context, byte[] pre_master_secret) { SecurityParameters securityParameters = context.getSecurityParameters(); byte[] seed; if (securityParameters.extendedMasterSecret) { seed = securityParameters.getSessionHash(); } else { seed = concat(securityParameters.getClientRandom(), securityParameters.getServerRandom()); } if (isSSL(context)) { return calculateMasterSecret_SSL(pre_master_secret, seed); } String asciiLabel = securityParameters.extendedMasterSecret ? ExporterLabel.extended_master_secret : ExporterLabel.master_secret; return PRF(context, pre_master_secret, asciiLabel, seed, 48); } static byte[] calculateMasterSecret_SSL(byte[] pre_master_secret, byte[] random) { Digest md5 = createHash(HashAlgorithm.md5); Digest sha1 = createHash(HashAlgorithm.sha1); int md5Size = md5.getDigestSize(); byte[] shatmp = new byte[sha1.getDigestSize()]; byte[] rval = new byte[md5Size * 3]; int pos = 0; for (int i = 0; i < 3; ++i) { byte[] ssl3Const = SSL3_CONST[i]; sha1.update(ssl3Const, 0, ssl3Const.length); sha1.update(pre_master_secret, 0, pre_master_secret.length); sha1.update(random, 0, random.length); sha1.doFinal(shatmp, 0); md5.update(pre_master_secret, 0, pre_master_secret.length); md5.update(shatmp, 0, shatmp.length); md5.doFinal(rval, pos); pos += md5Size; } return rval; } static byte[] calculateVerifyData(TlsContext context, String asciiLabel, byte[] handshakeHash) { if (isSSL(context)) { return handshakeHash; } SecurityParameters securityParameters = context.getSecurityParameters(); byte[] master_secret = securityParameters.getMasterSecret(); int verify_data_length = securityParameters.getVerifyDataLength(); return PRF(context, master_secret, asciiLabel, handshakeHash, verify_data_length); } public static Digest createHash(short hashAlgorithm) { switch (hashAlgorithm) { case HashAlgorithm.md5: return new MD5Digest(); case HashAlgorithm.sha1: return new SHA1Digest(); case HashAlgorithm.sha224: return new SHA224Digest(); case HashAlgorithm.sha256: return new SHA256Digest(); case HashAlgorithm.sha384: return new SHA384Digest(); case HashAlgorithm.sha512: return new SHA512Digest(); default: throw new IllegalArgumentException("unknown HashAlgorithm"); } } public static Digest cloneHash(short hashAlgorithm, Digest hash) { switch (hashAlgorithm) { case HashAlgorithm.md5: return new MD5Digest((MD5Digest)hash); case HashAlgorithm.sha1: return new SHA1Digest((SHA1Digest)hash); case HashAlgorithm.sha224: return new SHA224Digest((SHA224Digest)hash); case HashAlgorithm.sha256: return new SHA256Digest((SHA256Digest)hash); case HashAlgorithm.sha384: return new SHA384Digest((SHA384Digest)hash); case HashAlgorithm.sha512: return new SHA512Digest((SHA512Digest)hash); default: throw new IllegalArgumentException("unknown HashAlgorithm"); } } public static Digest createPRFHash(int prfAlgorithm) { switch (prfAlgorithm) { case PRFAlgorithm.tls_prf_legacy: return new CombinedHash(); default: return createHash(getHashAlgorithmForPRFAlgorithm(prfAlgorithm)); } } public static Digest clonePRFHash(int prfAlgorithm, Digest hash) { switch (prfAlgorithm) { case PRFAlgorithm.tls_prf_legacy: return new CombinedHash((CombinedHash)hash); default: return cloneHash(getHashAlgorithmForPRFAlgorithm(prfAlgorithm), hash); } } public static short getHashAlgorithmForPRFAlgorithm(int prfAlgorithm) { switch (prfAlgorithm) { case PRFAlgorithm.tls_prf_legacy: throw new IllegalArgumentException("legacy PRF not a valid algorithm"); case PRFAlgorithm.tls_prf_sha256: return HashAlgorithm.sha256; case PRFAlgorithm.tls_prf_sha384: return HashAlgorithm.sha384; default: throw new IllegalArgumentException("unknown PRFAlgorithm"); } } public static ASN1ObjectIdentifier getOIDForHashAlgorithm(short hashAlgorithm) { switch (hashAlgorithm) { case HashAlgorithm.md5: return PKCSObjectIdentifiers.md5; case HashAlgorithm.sha1: return X509ObjectIdentifiers.id_SHA1; case HashAlgorithm.sha224: return NISTObjectIdentifiers.id_sha224; case HashAlgorithm.sha256: return NISTObjectIdentifiers.id_sha256; case HashAlgorithm.sha384: return NISTObjectIdentifiers.id_sha384; case HashAlgorithm.sha512: return NISTObjectIdentifiers.id_sha512; default: throw new IllegalArgumentException("unknown HashAlgorithm"); } } static short getClientCertificateType(Certificate clientCertificate, Certificate serverCertificate) throws IOException { if (clientCertificate.isEmpty()) { return -1; } org.bouncycastle.asn1.x509.Certificate x509Cert = clientCertificate.getCertificateAt(0); SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo(); try { AsymmetricKeyParameter publicKey = PublicKeyFactory.createKey(keyInfo); if (publicKey.isPrivate()) { throw new TlsFatalAlert(AlertDescription.internal_error); } /* * TODO RFC 5246 7.4.6. The certificates MUST be signed using an acceptable hash/ * signature algorithm pair, as described in Section 7.4.4. Note that this relaxes the * constraints on certificate-signing algorithms found in prior versions of TLS. */ /* * RFC 5246 7.4.6. Client Certificate */ /* * RSA public key; the certificate MUST allow the key to be used for signing with the * signature scheme and hash algorithm that will be employed in the certificate verify * message. */ if (publicKey instanceof RSAKeyParameters) { validateKeyUsage(x509Cert, KeyUsage.digitalSignature); return ClientCertificateType.rsa_sign; } /* * DSA public key; the certificate MUST allow the key to be used for signing with the * hash algorithm that will be employed in the certificate verify message. */ if (publicKey instanceof DSAPublicKeyParameters) { validateKeyUsage(x509Cert, KeyUsage.digitalSignature); return ClientCertificateType.dss_sign; } /* * ECDSA-capable public key; the certificate MUST allow the key to be used for signing * with the hash algorithm that will be employed in the certificate verify message; the * public key MUST use a curve and point format supported by the server. */ if (publicKey instanceof ECPublicKeyParameters) { validateKeyUsage(x509Cert, KeyUsage.digitalSignature); // TODO Check the curve and point format return ClientCertificateType.ecdsa_sign; } // TODO Add support for ClientCertificateType.*_fixed_* throw new TlsFatalAlert(AlertDescription.unsupported_certificate); } catch (Exception e) { throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e); } } static void trackHashAlgorithms(TlsHandshakeHash handshakeHash, Vector supportedSignatureAlgorithms) { if (supportedSignatureAlgorithms != null) { for (int i = 0; i < supportedSignatureAlgorithms.size(); ++i) { SignatureAndHashAlgorithm signatureAndHashAlgorithm = (SignatureAndHashAlgorithm) supportedSignatureAlgorithms.elementAt(i); short hashAlgorithm = signatureAndHashAlgorithm.getHash(); handshakeHash.trackHashAlgorithm(hashAlgorithm); } } } public static boolean hasSigningCapability(short clientCertificateType) { switch (clientCertificateType) { case ClientCertificateType.dss_sign: case ClientCertificateType.ecdsa_sign: case ClientCertificateType.rsa_sign: return true; default: return false; } } public static TlsSigner createTlsSigner(short clientCertificateType) { switch (clientCertificateType) { case ClientCertificateType.dss_sign: return new TlsDSSSigner(); case ClientCertificateType.ecdsa_sign: return new TlsECDSASigner(); case ClientCertificateType.rsa_sign: return new TlsRSASigner(); default: throw new IllegalArgumentException("'clientCertificateType' is not a type with signing capability"); } } static final byte[] SSL_CLIENT = {0x43, 0x4C, 0x4E, 0x54}; static final byte[] SSL_SERVER = {0x53, 0x52, 0x56, 0x52}; // SSL3 magic mix constants ("A", "BB", "CCC", ...) static final byte[][] SSL3_CONST = genSSL3Const(); private static byte[][] genSSL3Const() { int n = 10; byte[][] arr = new byte[n][]; for (int i = 0; i < n; i++) { byte[] b = new byte[i + 1]; Arrays.fill(b, (byte)('A' + i)); arr[i] = b; } return arr; } private static Vector vectorOfOne(Object obj) { Vector v = new Vector(1); v.addElement(obj); return v; } public static int getCipherType(int ciphersuite) throws IOException { switch (getEncryptionAlgorithm(ciphersuite)) { case EncryptionAlgorithm.AES_128_GCM: case EncryptionAlgorithm.AES_256_GCM: case EncryptionAlgorithm.AES_128_CCM: case EncryptionAlgorithm.AES_128_CCM_8: case EncryptionAlgorithm.AES_256_CCM: case EncryptionAlgorithm.AES_256_CCM_8: case EncryptionAlgorithm.CAMELLIA_128_GCM: case EncryptionAlgorithm.CAMELLIA_256_GCM: case EncryptionAlgorithm.AEAD_CHACHA20_POLY1305: return CipherType.aead; case EncryptionAlgorithm.RC2_CBC_40: case EncryptionAlgorithm.IDEA_CBC: case EncryptionAlgorithm.DES40_CBC: case EncryptionAlgorithm.DES_CBC: case EncryptionAlgorithm._3DES_EDE_CBC: case EncryptionAlgorithm.AES_128_CBC: case EncryptionAlgorithm.AES_256_CBC: case EncryptionAlgorithm.CAMELLIA_128_CBC: case EncryptionAlgorithm.CAMELLIA_256_CBC: case EncryptionAlgorithm.SEED_CBC: return CipherType.block; case EncryptionAlgorithm.RC4_40: case EncryptionAlgorithm.RC4_128: case EncryptionAlgorithm.ESTREAM_SALSA20: case EncryptionAlgorithm.SALSA20: return CipherType.stream; default: throw new TlsFatalAlert(AlertDescription.internal_error); } } public static int getEncryptionAlgorithm(int ciphersuite) throws IOException { switch (ciphersuite) { case CipherSuite.TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA: return EncryptionAlgorithm._3DES_EDE_CBC; case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: return EncryptionAlgorithm.AEAD_CHACHA20_POLY1305; case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_SRP_SHA_WITH_AES_128_CBC_SHA: return EncryptionAlgorithm.AES_128_CBC; case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256: return EncryptionAlgorithm.AES_128_CBC; case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM: return EncryptionAlgorithm.AES_128_CCM; case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8: case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8: return EncryptionAlgorithm.AES_128_CCM_8; case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256: return EncryptionAlgorithm.AES_128_GCM; case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_SRP_SHA_WITH_AES_256_CBC_SHA: return EncryptionAlgorithm.AES_256_CBC; case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256: return EncryptionAlgorithm.AES_256_CBC; case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA384: return EncryptionAlgorithm.AES_256_CBC; case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM: case CipherSuite.TLS_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_RSA_WITH_AES_256_CCM: return EncryptionAlgorithm.AES_256_CCM; case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8: case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8: return EncryptionAlgorithm.AES_256_CCM_8; case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384: return EncryptionAlgorithm.AES_256_GCM; case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA: return EncryptionAlgorithm.CAMELLIA_128_CBC; case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256: return EncryptionAlgorithm.CAMELLIA_128_CBC; case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256: return EncryptionAlgorithm.CAMELLIA_128_GCM; case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA: return EncryptionAlgorithm.CAMELLIA_256_CBC; case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256: return EncryptionAlgorithm.CAMELLIA_256_CBC; case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384: return EncryptionAlgorithm.CAMELLIA_256_CBC; case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384: return EncryptionAlgorithm.CAMELLIA_256_GCM; case CipherSuite.TLS_DHE_PSK_WITH_ESTREAM_SALSA20_SHA1: case CipherSuite.TLS_DHE_RSA_WITH_ESTREAM_SALSA20_SHA1: case CipherSuite.TLS_ECDHE_ECDSA_WITH_ESTREAM_SALSA20_SHA1: case CipherSuite.TLS_ECDHE_PSK_WITH_ESTREAM_SALSA20_SHA1: case CipherSuite.TLS_ECDHE_RSA_WITH_ESTREAM_SALSA20_SHA1: case CipherSuite.TLS_PSK_WITH_ESTREAM_SALSA20_SHA1: case CipherSuite.TLS_RSA_PSK_WITH_ESTREAM_SALSA20_SHA1: case CipherSuite.TLS_RSA_WITH_ESTREAM_SALSA20_SHA1: return EncryptionAlgorithm.ESTREAM_SALSA20; case CipherSuite.TLS_RSA_WITH_NULL_MD5: return EncryptionAlgorithm.NULL; case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_NULL_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_NULL_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_NULL_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_NULL_SHA: case CipherSuite.TLS_PSK_WITH_NULL_SHA: case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA: case CipherSuite.TLS_RSA_WITH_NULL_SHA: return EncryptionAlgorithm.NULL; case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_RSA_WITH_NULL_SHA256: return EncryptionAlgorithm.NULL; case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA384: return EncryptionAlgorithm.NULL; case CipherSuite.TLS_DH_anon_WITH_RC4_128_MD5: case CipherSuite.TLS_RSA_WITH_RC4_128_MD5: return EncryptionAlgorithm.RC4_128; case CipherSuite.TLS_DHE_PSK_WITH_RC4_128_SHA: case CipherSuite.TLS_ECDH_anon_WITH_RC4_128_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_RC4_128_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_RC4_128_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_RC4_128_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_RC4_128_SHA: case CipherSuite.TLS_PSK_WITH_RC4_128_SHA: case CipherSuite.TLS_RSA_WITH_RC4_128_SHA: case CipherSuite.TLS_RSA_PSK_WITH_RC4_128_SHA: return EncryptionAlgorithm.RC4_128; case CipherSuite.TLS_DHE_PSK_WITH_SALSA20_SHA1: case CipherSuite.TLS_DHE_RSA_WITH_SALSA20_SHA1: case CipherSuite.TLS_ECDHE_ECDSA_WITH_SALSA20_SHA1: case CipherSuite.TLS_ECDHE_PSK_WITH_SALSA20_SHA1: case CipherSuite.TLS_ECDHE_RSA_WITH_SALSA20_SHA1: case CipherSuite.TLS_PSK_WITH_SALSA20_SHA1: case CipherSuite.TLS_RSA_PSK_WITH_SALSA20_SHA1: case CipherSuite.TLS_RSA_WITH_SALSA20_SHA1: return EncryptionAlgorithm.SALSA20; case CipherSuite.TLS_DH_DSS_WITH_SEED_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_SEED_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_SEED_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_SEED_CBC_SHA: case CipherSuite.TLS_RSA_WITH_SEED_CBC_SHA: return EncryptionAlgorithm.SEED_CBC; default: throw new TlsFatalAlert(AlertDescription.internal_error); } } public static ProtocolVersion getMinimumVersion(int ciphersuite) { switch (ciphersuite) { case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_AES_256_CCM: case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_NULL_SHA256: return ProtocolVersion.TLSv12; default: return ProtocolVersion.SSLv3; } } public static boolean isAEADCipherSuite(int ciphersuite) throws IOException { return CipherType.aead == getCipherType(ciphersuite); } public static boolean isBlockCipherSuite(int ciphersuite) throws IOException { return CipherType.block == getCipherType(ciphersuite); } public static boolean isStreamCipherSuite(int ciphersuite) throws IOException { return CipherType.stream == getCipherType(ciphersuite); } public static boolean isValidCipherSuiteForVersion(int cipherSuite, ProtocolVersion serverVersion) { return getMinimumVersion(cipherSuite).isEqualOrEarlierVersionOf(serverVersion.getEquivalentTLSVersion()); } }
Minor reformat
core/src/main/java/org/bouncycastle/crypto/tls/TlsUtils.java
Minor reformat
<ide><path>ore/src/main/java/org/bouncycastle/crypto/tls/TlsUtils.java <ide> <ide> case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM: <ide> case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM: <add> case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM: <ide> case CipherSuite.TLS_PSK_WITH_AES_128_CCM: <ide> case CipherSuite.TLS_RSA_WITH_AES_128_CCM: <del> case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM: <ide> return EncryptionAlgorithm.AES_128_CCM; <ide> <ide> case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8:
JavaScript
mit
b5d9a00fd1ccb6acfcc43546c71501ba9c789e90
0
sdeveloper/Telescope,msavin/Telescope,guillaumj/Telescope,TelescopeJS/Screenings,youprofit/Telescope,bharatjilledumudi/india-shop,SachaG/bjjbot,azukiapp/Telescope,covernal/Telescope,STANAPO/Telescope,adhikariaman01/Telescope,codebuddiesdotorg/cb-v2,aykutyaman/Telescope,parkeasz/Telescope,nhlennox/gbjobs,ahmadassaf/Telescope,nathanmelenbrink/theRecord,aykutyaman/Telescope,bshenk/projectIterate,yourcelf/Telescope,automenta/sernyl,Discordius/Telescope,geoclicks/Telescope,TodoTemplates/Telescope,Code-for-Miami/miami-graph-telescope,wangleihd/Telescope,aykutyaman/Telescope,Discordius/Telescope,adhikariaman01/Telescope,acidsound/Telescope,SachaG/Gamba,mr1azl/Telescope,sing1ee/Telescope,aozora/Telescope,msavin/Telescope,geverit4/Telescope,johndpark/Telescope,automenta/sernyl,VulcanJS/Vulcan,nathanmelenbrink/theRecord,wduntak/tibetalk,covernal/Telescope,bengott/Telescope,nhlennox/gbjobs,bengott/Telescope,geoclicks/Telescope,em0ney/Telescope,youprofit/Telescope,evilhei/itForum,SachaG/Gamba,sdeveloper/Telescope,bengott/Telescope,acidsound/Telescope,JstnEdr/Telescope,jonmc12/heypsycho,Code-for-Miami/miami-graph-telescope,em0ney/Telescope,parkeasz/Telescope,ahmadassaf/Telescope,tupeloTS/grittynashville,JstnEdr/Telescope,wangleihd/Telescope,jonmc12/heypsycho,aozora/Telescope,metstrike/Telescope,Daz2345/dhPulse,nathanmelenbrink/theRecord,hoihei/Telescope,JstnEdr/Telescope,automenta/sernyl,Daz2345/dhPulse,edjv711/presto,HelloMeets/HelloMakers,evilhei/itForum,hoihei/Telescope,HelloMeets/HelloMakers,jonmc12/heypsycho,Discordius/Lesswrong2,StEight/Telescope,Daz2345/dhPulse,basemm911/questionsociety,aichane/digigov,Air2air/Telescope,tupeloTS/telescopety,aichane/digigov,TodoTemplates/Telescope,youprofit/Telescope,TribeMedia/Telescope,SachaG/Zensroom,queso/Telescope,nishanbose/Telescope,Daz2345/Telescope,TribeMedia/Telescope,sdeveloper/Telescope,eruwinu/presto,bshenk/projectIterate,TribeMedia/Telescope,IQ2022/Telescope,manriquef/Vulcan,queso/Telescope,TelescopeJS/Screenings,queso/Telescope,capensisma/Asteroid,tupeloTS/telescopety,Discordius/Telescope,geoclicks/Telescope,kakedis/Telescope,dominictracey/Telescope,metstrike/Telescope,wunderkraut/WunderShare,basemm911/questionsociety,mr1azl/Telescope,Daz2345/Telescope,capensisma/Asteroid,metstrike/Telescope,guillaumj/Telescope,gzingraf/GreenLight-Pix,TodoTemplates/Telescope,kakedis/Telescope,SachaG/swpsub,tupeloTS/telescopety,Discordius/Lesswrong2,johndpark/Telescope,msavin/Telescope,kakedis/Telescope,StEight/Telescope,manriquef/Vulcan,Discordius/Lesswrong2,ryeskelton/Telescope,sing1ee/Telescope,huaiyudavid/rentech,geverit4/Telescope,bharatjilledumudi/india-shop,guillaumj/Telescope,nishanbose/Telescope,edjv711/presto,veerjainATgmail/Telescope,tupeloTS/grittynashville,wunderkraut/WunderShare,HelloMeets/HelloMakers,eruwinu/presto,SachaG/bjjbot,acidsound/Telescope,delgermurun/Telescope,geverit4/Telescope,adhikariaman01/Telescope,azukiapp/Telescope,ryeskelton/Telescope,ryeskelton/Telescope,gzingraf/GreenLight-Pix,ahmadassaf/Telescope,yourcelf/Telescope,bharatjilledumudi/india-shop,gzingraf/GreenLight-Pix,wduntak/tibetalk,tupeloTS/grittynashville,delgermurun/Telescope,StEight/Telescope,julienlapointe/telescope-nova-social-news,STANAPO/Telescope,Air2air/Telescope,veerjainATgmail/Telescope,yourcelf/Telescope,edjv711/presto,rtluu/immersive,SachaG/swpsub,nishanbose/Telescope,SachaG/Gamba,wangleihd/Telescope,VulcanJS/Vulcan,Discordius/Telescope,dominictracey/Telescope,dominictracey/Telescope,sing1ee/Telescope,rtluu/immersive,SachaG/swpsub,SachaG/Zensroom,julienlapointe/telescope-nova-social-news,wunderkraut/WunderShare,IQ2022/Telescope,codebuddiesdotorg/cb-v2,johndpark/Telescope,evilhei/itForum,hoihei/Telescope,SachaG/bjjbot,manriquef/Vulcan,aichane/digigov,aozora/Telescope,azukiapp/Telescope,Code-for-Miami/miami-graph-telescope,eruwinu/presto,mr1azl/Telescope,nhlennox/gbjobs,bshenk/projectIterate,parkeasz/Telescope,IQ2022/Telescope,veerjainATgmail/Telescope,huaiyudavid/rentech,codebuddiesdotorg/cb-v2,STANAPO/Telescope,rtluu/immersive,TelescopeJS/Screenings,SachaG/Zensroom,basemm911/questionsociety,Discordius/Lesswrong2,Air2air/Telescope,covernal/Telescope,Daz2345/Telescope,wduntak/tibetalk,em0ney/Telescope,delgermurun/Telescope,capensisma/Asteroid,julienlapointe/telescope-nova-social-news,huaiyudavid/rentech
Package.describe({ name: "telescope:releases", summary: "Show Telescope release notes and phone home with some stats.", version: "0.24.0", git: "https://github.com/TelescopeJS/telescope-releases.git" }); Package.onUse(function (api) { api.versionsFrom(['[email protected]']); // --------------------------- 1. Meteor packages dependencies --------------------------- api.use(['telescope:[email protected]']); // ---------------------------------- 2. Files to include ---------------------------------- // i18n config (must come first) api.addFiles([ 'package-tap.i18n' ], ['client', 'server']); // both api.addFiles([ 'lib/releases.js', ], ['client', 'server']); // client api.addFiles([ 'lib/client/templates/current_release.html', 'lib/client/templates/current_release.js', 'lib/client/scss/releases.scss' ], ['client']); // server api.addFiles([ 'lib/server/publications.js', 'lib/server/import_releases.js' ], ['server']); api.addFiles('releases/0.11.0.md', 'server', { isAsset: true }); api.addFiles('releases/0.11.1.md', 'server', { isAsset: true }); api.addFiles('releases/0.12.0.md', 'server', { isAsset: true }); api.addFiles('releases/0.13.0.md', 'server', { isAsset: true }); api.addFiles('releases/0.14.0.md', 'server', { isAsset: true }); api.addFiles('releases/0.14.1.md', 'server', { isAsset: true }); api.addFiles('releases/0.14.2.md', 'server', { isAsset: true }); api.addFiles('releases/0.14.3.md', 'server', { isAsset: true }); api.addFiles('releases/0.15.0.md', 'server', { isAsset: true }); api.addFiles('releases/0.20.4.md', 'server', { isAsset: true }); api.addFiles('releases/0.20.5.md', 'server', { isAsset: true }); api.addFiles('releases/0.20.6.md', 'server', { isAsset: true }); api.addFiles('releases/0.21.1.md', 'server', { isAsset: true }); api.addFiles('releases/0.22.1.md', 'server', { isAsset: true }); api.addFiles('releases/0.22.2.md', 'server', { isAsset: true }); api.addFiles('releases/0.23.0.md', 'server', { isAsset: true }); api.addFiles('releases/0.24.0.md', 'server', { isAsset: true }); // i18n languages (must come last) var languages = ["ar", "bg", "cs", "da", "de", "el", "en", "es", "et", "fr", "hu", "it", "ja", "ko", "nl", "pl", "pt-BR", "ro", "ru", "sv", "th", "tr", "vi", "zh-CN"]; var languagesPaths = languages.map(function (language) { return "i18n/"+language+".i18n.json"; }); api.addFiles(languagesPaths, ["client", "server"]); // -------------------------------- 3. Variables to export -------------------------------- api.export([ 'Releases' ]); });
packages/telescope-releases/package.js
Package.describe({ name: "telescope:releases", summary: "Show Telescope release notes and phone home with some stats.", version: "0.24.0", git: "https://github.com/TelescopeJS/telescope-releases.git" }); Package.onUse(function (api) { api.versionsFrom(['[email protected]']); // --------------------------- 1. Meteor packages dependencies --------------------------- api.use(['telescope:[email protected]']); // ---------------------------------- 2. Files to include ---------------------------------- // i18n config (must come first) api.addFiles([ 'package-tap.i18n' ], ['client', 'server']); // both api.addFiles([ 'lib/releases.js', ], ['client', 'server']); // client api.addFiles([ 'lib/client/templates/current_release.html', 'lib/client/templates/current_release.js', 'lib/client/scss/releases.scss' ], ['client']); // server api.addFiles([ 'lib/server/publications.js', 'lib/server/import_releases.js' ], ['server']); api.addFiles('releases/0.11.0.md', 'server', { isAsset: true }); api.addFiles('releases/0.11.1.md', 'server', { isAsset: true }); api.addFiles('releases/0.12.0.md', 'server', { isAsset: true }); api.addFiles('releases/0.13.0.md', 'server', { isAsset: true }); api.addFiles('releases/0.14.0.md', 'server', { isAsset: true }); api.addFiles('releases/0.14.1.md', 'server', { isAsset: true }); api.addFiles('releases/0.14.2.md', 'server', { isAsset: true }); api.addFiles('releases/0.14.3.md', 'server', { isAsset: true }); api.addFiles('releases/0.15.0.md', 'server', { isAsset: true }); api.addFiles('releases/0.20.4.md', 'server', { isAsset: true }); api.addFiles('releases/0.20.5.md', 'server', { isAsset: true }); api.addFiles('releases/0.20.6.md', 'server', { isAsset: true }); api.addFiles('releases/0.21.1.md', 'server', { isAsset: true }); api.addFiles('releases/0.22.1.md', 'server', { isAsset: true }); api.addFiles('releases/0.22.2.md', 'server', { isAsset: true }); api.addFiles('releases/0.24.0.md', 'server', { isAsset: true }); api.addFiles('releases/0.24.0.md', 'server', { isAsset: true }); // i18n languages (must come last) var languages = ["ar", "bg", "cs", "da", "de", "el", "en", "es", "et", "fr", "hu", "it", "ja", "ko", "nl", "pl", "pt-BR", "ro", "ru", "sv", "th", "tr", "vi", "zh-CN"]; var languagesPaths = languages.map(function (language) { return "i18n/"+language+".i18n.json"; }); api.addFiles(languagesPaths, ["client", "server"]); // -------------------------------- 3. Variables to export -------------------------------- api.export([ 'Releases' ]); });
fix file name
packages/telescope-releases/package.js
fix file name
<ide><path>ackages/telescope-releases/package.js <ide> api.addFiles('releases/0.21.1.md', 'server', { isAsset: true }); <ide> api.addFiles('releases/0.22.1.md', 'server', { isAsset: true }); <ide> api.addFiles('releases/0.22.2.md', 'server', { isAsset: true }); <del> api.addFiles('releases/0.24.0.md', 'server', { isAsset: true }); <add> api.addFiles('releases/0.23.0.md', 'server', { isAsset: true }); <ide> api.addFiles('releases/0.24.0.md', 'server', { isAsset: true }); <ide> <ide> // i18n languages (must come last)
Java
apache-2.0
dc817a3b84fe9909275f2549ce37616c3adb6d7a
0
droolsjbpm/droolsjbpm-integration,jesuino/droolsjbpm-integration,jesuino/droolsjbpm-integration,droolsjbpm/droolsjbpm-integration,winklerm/droolsjbpm-integration,droolsjbpm/droolsjbpm-integration,jesuino/droolsjbpm-integration,droolsjbpm/droolsjbpm-integration,jesuino/droolsjbpm-integration,winklerm/droolsjbpm-integration,winklerm/droolsjbpm-integration,winklerm/droolsjbpm-integration
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.kie.server.controller.impl.storage; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.kie.server.api.model.KieContainerStatus; import org.kie.server.api.model.KieScannerStatus; import org.kie.server.api.model.ReleaseId; import org.kie.server.controller.api.model.runtime.Container; import org.kie.server.controller.api.model.spec.Capability; import org.kie.server.controller.api.model.spec.ContainerConfig; import org.kie.server.controller.api.model.spec.ContainerSpec; import org.kie.server.controller.api.model.spec.ProcessConfig; import org.kie.server.controller.api.model.spec.RuleConfig; import org.kie.server.controller.api.model.spec.ServerTemplate; import org.kie.server.controller.api.model.spec.ServerTemplateKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class FileBasedKieServerTemplateStorageTest { private static final Logger logger = LoggerFactory.getLogger(FileBasedKieServerTemplateStorageTest.class); private static final File TEST_SERVER_TEMPLATE_DIRECTORY = new File(System.getProperty("java.io.tmpdir")); private static Map<ServerTemplateKey, ServerTemplate> templateMap; private File tmpTemplateStore; private FileBasedKieServerTemplateStorage storage; /** * Method that creates a server template instance and saves it in the specManageService * @param templateName The name of the template being created * @param templateCount The expected number of templates saved in the specManageService, including the one being created * @return A new server template instance */ private static ServerTemplate createServerTemplateWithContainer(String templateName, int templateCount) { ServerTemplate template = new ServerTemplate(); template.setName(templateName); template.setId(UUID.randomUUID().toString()); Map<Capability, ContainerConfig> configs = new HashMap<Capability, ContainerConfig>(); // Add a rule configuration to the server template's configuration RuleConfig ruleConfig = new RuleConfig(); ruleConfig.setPollInterval(1000l); ruleConfig.setScannerStatus(KieScannerStatus.STARTED); configs.put(Capability.RULE, ruleConfig); // Add a process configuration to the server template's configuration ProcessConfig processConfig = new ProcessConfig(); processConfig.setKBase("defaultKieBase"); processConfig.setKSession("defaultKieSession"); processConfig.setMergeMode("MERGE_COLLECTION"); processConfig.setRuntimeStrategy("PER_PROCESS_INSTANCE"); configs.put(Capability.PROCESS, processConfig); // Add a container specification to the specManageService, // associating it with the new server template instance ContainerSpec containerSpec = new ContainerSpec(); containerSpec.setId("test container"); containerSpec.setServerTemplateKey(new ServerTemplateKey(template.getId(), template.getName())); containerSpec.setReleasedId(new ReleaseId("org.kie", "kie-server-kjar", "1.0")); containerSpec.setStatus(KieContainerStatus.STOPPED); containerSpec.setConfigs(configs); containerSpec.setServerTemplateKey(new ServerTemplateKey(template.getId(), template.getName())); template.addContainerSpec(containerSpec); // Create a container with the server template Container container = new Container(); container.setServerInstanceId(template.getId()); container.setServerTemplateId(template.getId()); container.setResolvedReleasedId(containerSpec.getReleasedId()); container.setContainerName(containerSpec.getContainerName()); container.setContainerSpecId(containerSpec.getId()); container.setUrl("http://fake.server.net/kie-server"); container.setStatus(containerSpec.getStatus()); return template; } /** * Retrieves the first template from our static map of server templates, * using an Iterator over the value in the map. Asserts that we did, * in fact, retrieve a template. * @return The first server template */ private ServerTemplate getFirstTemplateFromMap() { Iterator<ServerTemplate> iter = templateMap.values().iterator(); ServerTemplate testTemplate = iter.hasNext() ? iter.next() : null; assertNotNull("Unable to find a test server template!",testTemplate); return testTemplate; } /** * Retrieves a template from the static instance of FileBasedKieServerTemplateStorage, * based on the id found in the passed in ServerTemplate. Asserts that we * did retrieve a template, and that the retrieved template is equal to * the one that was used as a source for the id. * @param template The source instance of a ServerTemplate * @return The retrieved ServerTemplate instance */ private ServerTemplate loadTemplateWithAssertEquals(ServerTemplate template) { ServerTemplate loadedTemplate = storage.load(template.getId()); assertNotNull("Unable to load template from storage",loadedTemplate); assertEquals("Loaded template is not the one asked for",template,loadedTemplate); return loadedTemplate; } @BeforeClass public static void beforeClass() { templateMap = new ConcurrentHashMap<>(); for (int x = 0; x < 3; x++) { StringBuilder templateName = new StringBuilder("test server : ").append(x); ServerTemplate template = createServerTemplateWithContainer(templateName.toString(),x+1); ServerTemplateKey key = new ServerTemplateKey(template.getId(), template.getName()); templateMap.put(key, template); } } @Before public void setup() throws IOException { tmpTemplateStore = File.createTempFile("templates_", ".xml", TEST_SERVER_TEMPLATE_DIRECTORY); storage = new FileBasedKieServerTemplateStorage(tmpTemplateStore.getAbsolutePath()); templateMap.keySet().forEach(key -> { storage.store(templateMap.get(key)); }); assertEquals("Mismatched number of server templates stored",templateMap.keySet().size(),storage.loadKeys().size()); } @After public void clean() { System.clearProperty(FileBasedKieServerTemplateStorage.STORAGE_FILE_WATCHER_ENABLED); try { Files.deleteIfExists(tmpTemplateStore.toPath()); } catch (IOException e) { logger.warn("Exception while deleting test server template storage",e); e.printStackTrace(); } } @Test public void testStore() { /* * Just need to make sure that if we load the keys * back in from the file, we get the same size set * More in depth testing of the actual elements retrieve * happens in later tests */ storage.loadTemplateMapsFromFile(); assertEquals("Mismatched number of server templates",templateMap.keySet().size(),storage.loadKeys().size()); } @Test public void testLoadKeys() { /* * Using the clearTemplateMaps method insures * that the code that checks for loading from * files is called */ storage.loadTemplateMapsFromFile(); List<ServerTemplateKey> keys = storage.loadKeys(); /* * Now we check that both the number of keys retrieved is correct * and that for each key we think we should have, it is in our * reloaded keys */ assertEquals("Mismatched number of server template keys",templateMap.keySet().size(),keys.size()); templateMap.keySet().forEach(key -> { assertTrue("Key for server template not found",keys.contains(key)); }); } @Test public void testLoadList() { storage.loadTemplateMapsFromFile(); List<ServerTemplate> templates = storage.load(); assertEquals("Mismatched number of server templates",templateMap.values().size(),templates.size()); templateMap.values().forEach(value -> { assertTrue("Server template not found",templates.contains(value)); }); } @Test public void testLoadSingle() { storage.loadTemplateMapsFromFile(); ServerTemplate toSearchFor = getFirstTemplateFromMap(); loadTemplateWithAssertEquals(toSearchFor); } @Test public void testLoadNotExisting() { storage.loadTemplateMapsFromFile(); String notExists = "not-exists"; ServerTemplate loadedTemplate = storage.load(notExists); assertNull(loadedTemplate); } @Test public void testExists() { storage.loadTemplateMapsFromFile(); ServerTemplate toSearchFor = getFirstTemplateFromMap(); assertTrue("Exists fails",storage.exists(toSearchFor.getId())); } @Test public void testNotExists() { storage.loadTemplateMapsFromFile(); String notExists = "not-exists"; assertFalse("Exists return true for not existing id: " + notExists, storage.exists(notExists)); } @Test public void testUpdate() { final String testName = "Updated template Name"; storage.loadTemplateMapsFromFile(); ServerTemplate toUpdateTemplate = getFirstTemplateFromMap(); toUpdateTemplate.setName(testName); storage.update(toUpdateTemplate); storage.loadTemplateMapsFromFile(); loadTemplateWithAssertEquals(toUpdateTemplate); } @Test public void testDelete() { storage.clearTemplateMaps(); ServerTemplate toDeleteTemplate = getFirstTemplateFromMap(); storage.delete(toDeleteTemplate.getId()); storage.clearTemplateMaps(); assertTrue("Delete template failed",!storage.exists(toDeleteTemplate.getId())); } @Test public void testDeleteNotExistingTemplate() { storage.loadTemplateMapsFromFile(); List<ServerTemplate> templates = storage.load(); assertEquals("Mismatched number of server templates", templateMap.values().size(), templates.size()); storage.delete("not-exists"); storage.loadTemplateMapsFromFile(); templates = storage.load(); assertEquals("Mismatched number of server templates", templateMap.values().size(), templates.size()); } @Test public void testLoadNotExistingTemplate() { List<ServerTemplate> templates = storage.load(); assertEquals(3, templates.size()); // Delete template file tmpTemplateStore.delete(); storage.loadTemplateMapsFromFile(); // Storage should still contain previously loaded templates templates = storage.load(); assertEquals(3, templates.size()); } @Test public void testGetStorageLocation() { String location = storage.getTemplatesLocation(); assertEquals(tmpTemplateStore.getAbsolutePath(), location); } @Test(timeout=30000) public void testUpdatedStorageFromWatcher() throws Exception { FileBasedKieServerTemplateStorage secondStorage = new FileBasedKieServerTemplateStorage(tmpTemplateStore.getAbsolutePath()); System.setProperty(FileBasedKieServerTemplateStorage.STORAGE_FILE_WATCHER_ENABLED, "true"); System.setProperty(ControllerStorageFileWatcher.STORAGE_FILE_WATCHER_INTERVAL, "1000"); CountDownLatch waitForReload = new CountDownLatch(2); storage = new FileBasedKieServerTemplateStorage(tmpTemplateStore.getAbsolutePath()) { @Override public void loadTemplateMapsFromFile() { super.loadTemplateMapsFromFile(); waitForReload.countDown(); } }; List<ServerTemplate> templates = storage.load(); assertEquals(3, templates.size()); // delay it a bit from the creation of the file Thread.sleep(3000); ServerTemplate serverTemplate = new ServerTemplate(); serverTemplate.setName("UpdateFromOtherController"); serverTemplate.setId(UUID.randomUUID().toString()); secondStorage.store(serverTemplate); waitForReload.await(); templates = storage.load(); assertEquals(4, templates.size()); } }
kie-server-parent/kie-server-controller/kie-server-controller-impl/src/test/java/org/kie/server/controller/impl/storage/FileBasedKieServerTemplateStorageTest.java
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.kie.server.controller.impl.storage; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.CountDownLatch; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.kie.server.api.model.KieContainerStatus; import org.kie.server.api.model.KieScannerStatus; import org.kie.server.api.model.ReleaseId; import org.kie.server.controller.api.model.runtime.Container; import org.kie.server.controller.api.model.spec.Capability; import org.kie.server.controller.api.model.spec.ContainerConfig; import org.kie.server.controller.api.model.spec.ContainerSpec; import org.kie.server.controller.api.model.spec.ProcessConfig; import org.kie.server.controller.api.model.spec.RuleConfig; import org.kie.server.controller.api.model.spec.ServerTemplate; import org.kie.server.controller.api.model.spec.ServerTemplateKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Maps; public class FileBasedKieServerTemplateStorageTest { private static final Logger logger = LoggerFactory.getLogger(FileBasedKieServerTemplateStorageTest.class); private static final File TEST_SERVER_TEMPLATE_DIRECTORY = new File(System.getProperty("java.io.tmpdir")); private static Map<ServerTemplateKey, ServerTemplate> templateMap; private File tmpTemplateStore; private FileBasedKieServerTemplateStorage storage; /** * Method that creates a server template instance and saves it in the specManageService * @param templateName The name of the template being created * @param templateCount The expected number of templates saved in the specManageService, including the one being created * @return A new server template instance */ private static ServerTemplate createServerTemplateWithContainer(String templateName, int templateCount) { ServerTemplate template = new ServerTemplate(); template.setName(templateName); template.setId(UUID.randomUUID().toString()); Map<Capability, ContainerConfig> configs = new HashMap<Capability, ContainerConfig>(); // Add a rule configuration to the server template's configuration RuleConfig ruleConfig = new RuleConfig(); ruleConfig.setPollInterval(1000l); ruleConfig.setScannerStatus(KieScannerStatus.STARTED); configs.put(Capability.RULE, ruleConfig); // Add a process configuration to the server template's configuration ProcessConfig processConfig = new ProcessConfig(); processConfig.setKBase("defaultKieBase"); processConfig.setKSession("defaultKieSession"); processConfig.setMergeMode("MERGE_COLLECTION"); processConfig.setRuntimeStrategy("PER_PROCESS_INSTANCE"); configs.put(Capability.PROCESS, processConfig); // Add a container specification to the specManageService, // associating it with the new server template instance ContainerSpec containerSpec = new ContainerSpec(); containerSpec.setId("test container"); containerSpec.setServerTemplateKey(new ServerTemplateKey(template.getId(), template.getName())); containerSpec.setReleasedId(new ReleaseId("org.kie", "kie-server-kjar", "1.0")); containerSpec.setStatus(KieContainerStatus.STOPPED); containerSpec.setConfigs(configs); containerSpec.setServerTemplateKey(new ServerTemplateKey(template.getId(), template.getName())); template.addContainerSpec(containerSpec); // Create a container with the server template Container container = new Container(); container.setServerInstanceId(template.getId()); container.setServerTemplateId(template.getId()); container.setResolvedReleasedId(containerSpec.getReleasedId()); container.setContainerName(containerSpec.getContainerName()); container.setContainerSpecId(containerSpec.getId()); container.setUrl("http://fake.server.net/kie-server"); container.setStatus(containerSpec.getStatus()); return template; } /** * Retrieves the first template from our static map of server templates, * using an Iterator over the value in the map. Asserts that we did, * in fact, retrieve a template. * @return The first server template */ private ServerTemplate getFirstTemplateFromMap() { Iterator<ServerTemplate> iter = templateMap.values().iterator(); ServerTemplate testTemplate = iter.hasNext() ? iter.next() : null; assertNotNull("Unable to find a test server template!",testTemplate); return testTemplate; } /** * Retrieves a template from the static instance of FileBasedKieServerTemplateStorage, * based on the id found in the passed in ServerTemplate. Asserts that we * did retrieve a template, and that the retrieved template is equal to * the one that was used as a source for the id. * @param template The source instance of a ServerTemplate * @return The retrieved ServerTemplate instance */ private ServerTemplate loadTemplateWithAssertEquals(ServerTemplate template) { ServerTemplate loadedTemplate = storage.load(template.getId()); assertNotNull("Unable to load template from storage",loadedTemplate); assertEquals("Loaded template is not the one asked for",template,loadedTemplate); return loadedTemplate; } @BeforeClass public static void beforeClass() { templateMap = Maps.newConcurrentMap(); for (int x = 0; x < 3; x++) { StringBuilder templateName = new StringBuilder("test server : ").append(x); ServerTemplate template = createServerTemplateWithContainer(templateName.toString(),x+1); ServerTemplateKey key = new ServerTemplateKey(template.getId(), template.getName()); templateMap.put(key, template); } } @Before public void setup() throws IOException { tmpTemplateStore = File.createTempFile("templates_", ".xml", TEST_SERVER_TEMPLATE_DIRECTORY); storage = new FileBasedKieServerTemplateStorage(tmpTemplateStore.getAbsolutePath()); templateMap.keySet().forEach(key -> { storage.store(templateMap.get(key)); }); assertEquals("Mismatched number of server templates stored",templateMap.keySet().size(),storage.loadKeys().size()); } @After public void clean() { System.clearProperty(FileBasedKieServerTemplateStorage.STORAGE_FILE_WATCHER_ENABLED); try { Files.deleteIfExists(tmpTemplateStore.toPath()); } catch (IOException e) { logger.warn("Exception while deleting test server template storage",e); e.printStackTrace(); } } @Test public void testStore() { /* * Just need to make sure that if we load the keys * back in from the file, we get the same size set * More in depth testing of the actual elements retrieve * happens in later tests */ storage.loadTemplateMapsFromFile(); assertEquals("Mismatched number of server templates",templateMap.keySet().size(),storage.loadKeys().size()); } @Test public void testLoadKeys() { /* * Using the clearTemplateMaps method insures * that the code that checks for loading from * files is called */ storage.loadTemplateMapsFromFile(); List<ServerTemplateKey> keys = storage.loadKeys(); /* * Now we check that both the number of keys retrieved is correct * and that for each key we think we should have, it is in our * reloaded keys */ assertEquals("Mismatched number of server template keys",templateMap.keySet().size(),keys.size()); templateMap.keySet().forEach(key -> { assertTrue("Key for server template not found",keys.contains(key)); }); } @Test public void testLoadList() { storage.loadTemplateMapsFromFile(); List<ServerTemplate> templates = storage.load(); assertEquals("Mismatched number of server templates",templateMap.values().size(),templates.size()); templateMap.values().forEach(value -> { assertTrue("Server template not found",templates.contains(value)); }); } @Test public void testLoadSingle() { storage.loadTemplateMapsFromFile(); ServerTemplate toSearchFor = getFirstTemplateFromMap(); loadTemplateWithAssertEquals(toSearchFor); } @Test public void testLoadNotExisting() { storage.loadTemplateMapsFromFile(); String notExists = "not-exists"; ServerTemplate loadedTemplate = storage.load(notExists); assertNull(loadedTemplate); } @Test public void testExists() { storage.loadTemplateMapsFromFile(); ServerTemplate toSearchFor = getFirstTemplateFromMap(); assertTrue("Exists fails",storage.exists(toSearchFor.getId())); } @Test public void testNotExists() { storage.loadTemplateMapsFromFile(); String notExists = "not-exists"; assertFalse("Exists return true for not existing id: " + notExists, storage.exists(notExists)); } @Test public void testUpdate() { final String testName = "Updated template Name"; storage.loadTemplateMapsFromFile(); ServerTemplate toUpdateTemplate = getFirstTemplateFromMap(); toUpdateTemplate.setName(testName); storage.update(toUpdateTemplate); storage.loadTemplateMapsFromFile(); loadTemplateWithAssertEquals(toUpdateTemplate); } @Test public void testDelete() { storage.clearTemplateMaps(); ServerTemplate toDeleteTemplate = getFirstTemplateFromMap(); storage.delete(toDeleteTemplate.getId()); storage.clearTemplateMaps(); assertTrue("Delete template failed",!storage.exists(toDeleteTemplate.getId())); } @Test public void testDeleteNotExistingTemplate() { storage.loadTemplateMapsFromFile(); List<ServerTemplate> templates = storage.load(); assertEquals("Mismatched number of server templates", templateMap.values().size(), templates.size()); storage.delete("not-exists"); storage.loadTemplateMapsFromFile(); templates = storage.load(); assertEquals("Mismatched number of server templates", templateMap.values().size(), templates.size()); } @Test public void testLoadNotExistingTemplate() { List<ServerTemplate> templates = storage.load(); assertEquals(3, templates.size()); // Delete template file tmpTemplateStore.delete(); storage.loadTemplateMapsFromFile(); // Storage should still contain previously loaded templates templates = storage.load(); assertEquals(3, templates.size()); } @Test public void testGetStorageLocation() { String location = storage.getTemplatesLocation(); assertEquals(tmpTemplateStore.getAbsolutePath(), location); } @Test(timeout=30000) public void testUpdatedStorageFromWatcher() throws Exception { FileBasedKieServerTemplateStorage secondStorage = new FileBasedKieServerTemplateStorage(tmpTemplateStore.getAbsolutePath()); System.setProperty(FileBasedKieServerTemplateStorage.STORAGE_FILE_WATCHER_ENABLED, "true"); System.setProperty(ControllerStorageFileWatcher.STORAGE_FILE_WATCHER_INTERVAL, "1000"); CountDownLatch waitForReload = new CountDownLatch(2); storage = new FileBasedKieServerTemplateStorage(tmpTemplateStore.getAbsolutePath()) { @Override public void loadTemplateMapsFromFile() { super.loadTemplateMapsFromFile(); waitForReload.countDown(); } }; List<ServerTemplate> templates = storage.load(); assertEquals(3, templates.size()); // delay it a bit from the creation of the file Thread.sleep(3000); ServerTemplate serverTemplate = new ServerTemplate(); serverTemplate.setName("UpdateFromOtherController"); serverTemplate.setId(UUID.randomUUID().toString()); secondStorage.store(serverTemplate); waitForReload.await(); templates = storage.load(); assertEquals(4, templates.size()); } }
remove needless use of guava map in test
kie-server-parent/kie-server-controller/kie-server-controller-impl/src/test/java/org/kie/server/controller/impl/storage/FileBasedKieServerTemplateStorageTest.java
remove needless use of guava map in test
<ide><path>ie-server-parent/kie-server-controller/kie-server-controller-impl/src/test/java/org/kie/server/controller/impl/storage/FileBasedKieServerTemplateStorageTest.java <ide> */ <ide> package org.kie.server.controller.impl.storage; <ide> <del>import static org.junit.Assert.assertEquals; <del>import static org.junit.Assert.assertNotNull; <del>import static org.junit.Assert.assertTrue; <del>import static org.junit.Assert.assertFalse; <del>import static org.junit.Assert.assertNull; <del> <ide> import java.io.File; <ide> import java.io.IOException; <ide> import java.nio.file.Files; <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.UUID; <add>import java.util.concurrent.ConcurrentHashMap; <ide> import java.util.concurrent.CountDownLatch; <ide> <ide> import org.junit.After; <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> <del>import com.google.common.collect.Maps; <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertFalse; <add>import static org.junit.Assert.assertNotNull; <add>import static org.junit.Assert.assertNull; <add>import static org.junit.Assert.assertTrue; <ide> <ide> public class FileBasedKieServerTemplateStorageTest { <ide> private static final Logger logger = LoggerFactory.getLogger(FileBasedKieServerTemplateStorageTest.class); <ide> <ide> @BeforeClass <ide> public static void beforeClass() { <del> templateMap = Maps.newConcurrentMap(); <add> templateMap = new ConcurrentHashMap<>(); <ide> for (int x = 0; x < 3; x++) { <ide> StringBuilder templateName = new StringBuilder("test server : ").append(x); <ide> ServerTemplate template = createServerTemplateWithContainer(templateName.toString(),x+1);
Java
apache-2.0
e1c0133ac517fd87415d38f0d1bd54884a28e089
0
consulo/consulo-dotnet
/* * Copyright 2013-2014 must-be.org * * 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. */ package org.mustbe.consulo.dotnet.debugger; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Queue; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentLinkedDeque; import org.consulo.lombok.annotations.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mustbe.consulo.dotnet.debugger.linebreakType.DotNetAbstractBreakpointType; import org.mustbe.consulo.dotnet.debugger.linebreakType.DotNetLineBreakpointType; import org.mustbe.consulo.dotnet.execution.DebugConnectionInfo; import org.mustbe.consulo.dotnet.psi.DotNetTypeDeclaration; import com.intellij.execution.configurations.RunProfile; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.application.Result; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Key; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.util.ArrayUtil; import com.intellij.util.Processor; import com.intellij.xdebugger.XDebugSession; import com.intellij.xdebugger.XDebuggerManager; import com.intellij.xdebugger.breakpoints.XBreakpointProperties; import com.intellij.xdebugger.breakpoints.XLineBreakpoint; import lombok.val; import mono.debugger.EventKind; import mono.debugger.Location; import mono.debugger.SocketListeningConnector; import mono.debugger.SuspendPolicy; import mono.debugger.TypeMirror; import mono.debugger.VirtualMachine; import mono.debugger.connect.Connector; import mono.debugger.event.Event; import mono.debugger.event.EventQueue; import mono.debugger.event.EventSet; import mono.debugger.event.TypeLoadEvent; import mono.debugger.event.VMDeathEvent; import mono.debugger.request.BreakpointRequest; import mono.debugger.request.EventRequest; import mono.debugger.request.StepRequest; import mono.debugger.request.TypeLoadRequest; /** * @author VISTALL * @since 10.04.14 */ @Logger public class DotNetDebugThread extends Thread { public static Key<EventRequest> EVENT_REQUEST = Key.create("event-request-for-line-breakpoint"); private final XDebugSession mySession; private final XDebuggerManager myDebuggerManager; private final DotNetDebugProcess myDebugProcess; private final DebugConnectionInfo myDebugConnectionInfo; private final RunProfile myRunProfile; private boolean myStop; private Queue<Processor<VirtualMachine>> myQueue = new ConcurrentLinkedDeque<Processor<VirtualMachine>>(); private VirtualMachine myVirtualMachine; public DotNetDebugThread(XDebugSession session, DotNetDebugProcess debugProcess, DebugConnectionInfo debugConnectionInfo, RunProfile runProfile) { super("DotNetDebugThread: " + new Random().nextInt()); mySession = session; myDebugProcess = debugProcess; myDebugConnectionInfo = debugConnectionInfo; myRunProfile = runProfile; myDebuggerManager = XDebuggerManager.getInstance(session.getProject()); } public void setStop() { myStop = true; myVirtualMachine = null; } @Override public void run() { VirtualMachine virtualMachine = null; if(!myDebugConnectionInfo.isServer()) { SocketListeningConnector l = new SocketListeningConnector(); Map<String, Connector.Argument> argumentMap = l.defaultArguments(); argumentMap.get(SocketListeningConnector.ARG_LOCALADDR).setValue(myDebugConnectionInfo.getHost()); argumentMap.get(SocketListeningConnector.ARG_PORT).setValue(String.valueOf(myDebugConnectionInfo.getPort())); argumentMap.get("timeout").setValue("10000"); try { virtualMachine = l.accept(argumentMap); myVirtualMachine = virtualMachine; } catch(Exception e) { e.printStackTrace(); // } if(virtualMachine == null) { return; } virtualMachine.enableEvents(EventKind.ASSEMBLY_LOAD, EventKind.THREAD_START, EventKind.THREAD_DEATH, EventKind.ASSEMBLY_UNLOAD, EventKind.USER_BREAK, EventKind.USER_LOG); TypeLoadRequest typeLoad = virtualMachine.eventRequestManager().createTypeLoad(); if(virtualMachine.isAtLeastVersion(2, 9)) { Set<String> files = new HashSet<String>(); Collection<? extends XLineBreakpoint<XBreakpointProperties>> ourBreakpoints = getOurBreakpoints(); for(final XLineBreakpoint<XBreakpointProperties> ourBreakpoint : ourBreakpoints) { files.add(ourBreakpoint.getPresentableFilePath()); } typeLoad.addSourceFileFilter(ArrayUtil.toStringArray(files)); } typeLoad.enable(); try { virtualMachine.eventQueue().remove(); //Wait VMStart virtualMachine.resume(); } catch(InterruptedException e) { e.printStackTrace(); return; } } else { } if(virtualMachine == null) { return; } while(!myStop) { processCommands(virtualMachine); boolean stoppedAlready = false; EventQueue eventQueue = virtualMachine.eventQueue(); EventSet eventSet; try { l: while((eventSet = eventQueue.remove(50)) != null) { Location location = null; for(final Event event : eventSet) { EventRequest request = event.request(); if(request instanceof BreakpointRequest) { location = ((BreakpointRequest) request).location(); } if(request instanceof StepRequest) { request.disable(); } if(event instanceof TypeLoadEvent) { insertBreakpoints(virtualMachine, ((TypeLoadEvent) event).typeMirror()); continue l; } if(event instanceof VMDeathEvent) { myStop = true; return; } } if(!stoppedAlready && eventSet.suspendPolicy() == SuspendPolicy.ALL) { stoppedAlready = true; myDebugProcess.setPausedEventSet(eventSet); XLineBreakpoint<?> xLineBreakpoint = resolveToBreakpoint(location); DotNetDebugContext debugContext = createDebugContext(); if(xLineBreakpoint != null) { mySession.breakpointReached(xLineBreakpoint, null, new DotNetSuspendContext(debugContext, eventSet.eventThread())); } else { mySession.positionReached(new DotNetSuspendContext(debugContext, eventSet.eventThread())); } } } } catch(Exception e) { // } try { Thread.sleep(50); } catch(InterruptedException e) { // } } } private void insertBreakpoints(final VirtualMachine virtualMachine, final TypeMirror typeMirror) { new ReadAction<Object>() { @Override protected void run(Result<Object> objectResult) throws Throwable { DotNetDebugContext debugContext = createDebugContext(); DotNetTypeDeclaration[] qualifiedNameImpl = DotNetVirtualMachineUtil.findTypesByQualifiedName(typeMirror, debugContext); if(qualifiedNameImpl.length == 0) { return; } Collection<? extends XLineBreakpoint<XBreakpointProperties>> breakpoints = getOurBreakpoints(); for(DotNetTypeDeclaration dotNetTypeDeclaration : qualifiedNameImpl) { VirtualFile typeVirtualFile = dotNetTypeDeclaration.getContainingFile().getVirtualFile(); for(final XLineBreakpoint<XBreakpointProperties> breakpoint : breakpoints) { VirtualFile lineBreakpoint = VirtualFileManager.getInstance().findFileByUrl(breakpoint.getFileUrl()); if(!Comparing.equal(typeVirtualFile, lineBreakpoint)) { continue; } val type = (DotNetLineBreakpointType) breakpoint.getType(); type.createRequest(mySession.getProject(), virtualMachine, breakpoint, typeMirror); } } virtualMachine.resume(); } }.execute(); } private void processCommands(VirtualMachine virtualMachine) { Processor<VirtualMachine> processor; while((processor = myQueue.poll()) != null) { if(processor.process(virtualMachine)) { virtualMachine.resume(); } } } @NotNull public DotNetDebugContext createDebugContext() { assert myVirtualMachine != null; return new DotNetDebugContext(mySession.getProject(), myVirtualMachine, myRunProfile); } @Nullable private XLineBreakpoint<?> resolveToBreakpoint(@Nullable Location location) { if(location == null) { return null; } String sourcePath = location.sourcePath(); if(sourcePath == null) { return null; } VirtualFile fileByPath = LocalFileSystem.getInstance().findFileByPath(sourcePath); if(fileByPath == null) { return null; } XLineBreakpoint<XBreakpointProperties> breakpointAtLine = myDebuggerManager.getBreakpointManager().findBreakpointAtLine (DotNetLineBreakpointType.getInstance(), fileByPath, location.lineNumber() - 1); // .net asm - 1 index based, consulo - 0 based if(breakpointAtLine == null) { return null; } return breakpointAtLine; } public void normalizeBreakpoints() { for(XLineBreakpoint<XBreakpointProperties> lineBreakpoint : getOurBreakpoints()) { lineBreakpoint.putUserData(EVENT_REQUEST, null); myDebuggerManager.getBreakpointManager().updateBreakpointPresentation(lineBreakpoint, null, null); } } @NotNull public Collection<? extends XLineBreakpoint<XBreakpointProperties>> getOurBreakpoints() { return ApplicationManager.getApplication().runReadAction(new Computable<Collection<? extends XLineBreakpoint<XBreakpointProperties>>>() { @Override public Collection<? extends XLineBreakpoint<XBreakpointProperties>> compute() { return myDebuggerManager.getBreakpointManager().getBreakpoints(DotNetAbstractBreakpointType.class); } }); } public void processAnyway(Processor<VirtualMachine> processor) { if(myVirtualMachine == null) { return; } processor.process(myVirtualMachine); } public void addCommand(Processor<VirtualMachine> processor) { myQueue.add(processor); } public boolean isConnected() { return myVirtualMachine != null; } }
dotnet-debugger-impl/src/org/mustbe/consulo/dotnet/debugger/DotNetDebugThread.java
/* * Copyright 2013-2014 must-be.org * * 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. */ package org.mustbe.consulo.dotnet.debugger; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Queue; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentLinkedDeque; import org.consulo.lombok.annotations.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mustbe.consulo.dotnet.debugger.linebreakType.DotNetAbstractBreakpointType; import org.mustbe.consulo.dotnet.debugger.linebreakType.DotNetLineBreakpointType; import org.mustbe.consulo.dotnet.execution.DebugConnectionInfo; import org.mustbe.consulo.dotnet.psi.DotNetTypeDeclaration; import com.intellij.execution.configurations.RunProfile; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.application.Result; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Key; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.util.ArrayUtil; import com.intellij.util.Processor; import com.intellij.xdebugger.XDebugSession; import com.intellij.xdebugger.XDebuggerManager; import com.intellij.xdebugger.breakpoints.XBreakpointProperties; import com.intellij.xdebugger.breakpoints.XLineBreakpoint; import lombok.val; import mono.debugger.EventKind; import mono.debugger.Location; import mono.debugger.SocketListeningConnector; import mono.debugger.SuspendPolicy; import mono.debugger.TypeMirror; import mono.debugger.VirtualMachine; import mono.debugger.connect.Connector; import mono.debugger.event.Event; import mono.debugger.event.EventQueue; import mono.debugger.event.EventSet; import mono.debugger.event.TypeLoadEvent; import mono.debugger.event.VMDeathEvent; import mono.debugger.request.BreakpointRequest; import mono.debugger.request.EventRequest; import mono.debugger.request.StepRequest; import mono.debugger.request.TypeLoadRequest; /** * @author VISTALL * @since 10.04.14 */ @Logger public class DotNetDebugThread extends Thread { public static Key<EventRequest> EVENT_REQUEST = Key.create("event-request-for-line-breakpoint"); private final XDebugSession mySession; private final XDebuggerManager myDebuggerManager; private final DotNetDebugProcess myDebugProcess; private final DebugConnectionInfo myDebugConnectionInfo; private final RunProfile myRunProfile; private boolean myStop; private Queue<Processor<VirtualMachine>> myQueue = new ConcurrentLinkedDeque<Processor<VirtualMachine>>(); private VirtualMachine myVirtualMachine; public DotNetDebugThread(XDebugSession session, DotNetDebugProcess debugProcess, DebugConnectionInfo debugConnectionInfo, RunProfile runProfile) { super("DotNetDebugThread: " + new Random().nextInt()); mySession = session; myDebugProcess = debugProcess; myDebugConnectionInfo = debugConnectionInfo; myRunProfile = runProfile; myDebuggerManager = XDebuggerManager.getInstance(session.getProject()); } public void setStop() { myStop = true; myVirtualMachine = null; } @Override public void run() { VirtualMachine virtualMachine = null; if(!myDebugConnectionInfo.isServer()) { SocketListeningConnector l = new SocketListeningConnector(); Map<String, Connector.Argument> argumentMap = l.defaultArguments(); argumentMap.get(SocketListeningConnector.ARG_LOCALADDR).setValue(myDebugConnectionInfo.getHost()); argumentMap.get(SocketListeningConnector.ARG_PORT).setValue(String.valueOf(myDebugConnectionInfo.getPort())); argumentMap.get("timeout").setValue("10000"); try { virtualMachine = l.accept(argumentMap); myVirtualMachine = virtualMachine; } catch(Exception e) { e.printStackTrace(); // } if(virtualMachine == null) { return; } virtualMachine.enableEvents(EventKind.ASSEMBLY_LOAD, EventKind.THREAD_START, EventKind.THREAD_DEATH, EventKind.ASSEMBLY_UNLOAD, EventKind.USER_BREAK, EventKind.USER_LOG); TypeLoadRequest typeLoad = virtualMachine.eventRequestManager().createTypeLoad(); if(virtualMachine.isAtLeastVersion(2, 9)) { Set<String> files = new HashSet<String>(); Collection<? extends XLineBreakpoint<XBreakpointProperties>> ourBreakpoints = getOurBreakpoints(); for(final XLineBreakpoint<XBreakpointProperties> ourBreakpoint : ourBreakpoints) { files.add(ourBreakpoint.getPresentableFilePath()); } typeLoad.addSourceFileFilter(ArrayUtil.toStringArray(files)); } typeLoad.enable(); try { virtualMachine.eventQueue().remove(); //Wait VMStart virtualMachine.resume(); } catch(InterruptedException e) { e.printStackTrace(); return; } } else { } if(virtualMachine == null) { return; } while(!myStop) { processCommands(virtualMachine); boolean stoppedAlready = false; EventQueue eventQueue = virtualMachine.eventQueue(); EventSet eventSet; try { l: while((eventSet = eventQueue.remove(50)) != null) { Location location = null; for(final Event event : eventSet) { EventRequest request = event.request(); if(request instanceof BreakpointRequest) { location = ((BreakpointRequest) request).location(); } if(request instanceof StepRequest) { request.disable(); } if(event instanceof TypeLoadEvent) { insertBreakpoints(virtualMachine, ((TypeLoadEvent) event).typeMirror()); continue l; } if(event instanceof VMDeathEvent) { myStop = true; return; } } if(!stoppedAlready && eventSet.suspendPolicy() == SuspendPolicy.ALL) { stoppedAlready = true; myDebugProcess.setPausedEventSet(eventSet); XLineBreakpoint<?> xLineBreakpoint = resolveToBreakpoint(location); DotNetDebugContext debugContext = createDebugContext(); if(xLineBreakpoint != null) { mySession.breakpointReached(xLineBreakpoint, null, new DotNetSuspendContext(debugContext, eventSet.eventThread())); } else { mySession.positionReached(new DotNetSuspendContext(debugContext, eventSet.eventThread())); } } } } catch(Exception e) { // } try { Thread.sleep(50); } catch(InterruptedException e) { // } } } private void insertBreakpoints(final VirtualMachine virtualMachine, final TypeMirror typeMirror) { new ReadAction<Object>() { @Override protected void run(Result<Object> objectResult) throws Throwable { DotNetDebugContext debugContext = createDebugContext(); DotNetTypeDeclaration[] qualifiedNameImpl = DotNetVirtualMachineUtil.findTypesByQualifiedName(typeMirror, debugContext); if(qualifiedNameImpl.length == 0) { return; } Collection<? extends XLineBreakpoint<XBreakpointProperties>> breakpoints = getOurBreakpoints(); for(DotNetTypeDeclaration dotNetTypeDeclaration : qualifiedNameImpl) { VirtualFile typeVirtualFile = dotNetTypeDeclaration.getContainingFile().getVirtualFile(); for(final XLineBreakpoint<XBreakpointProperties> breakpoint : breakpoints) { VirtualFile lineBreakpoint = VirtualFileManager.getInstance().findFileByUrl(breakpoint.getFileUrl()); if(!Comparing.equal(typeVirtualFile, lineBreakpoint)) { continue; } val type = (DotNetLineBreakpointType) breakpoint.getType(); type.createRequest(mySession.getProject(), virtualMachine, breakpoint, null); } } virtualMachine.resume(); } }.execute(); } private void processCommands(VirtualMachine virtualMachine) { Processor<VirtualMachine> processor; while((processor = myQueue.poll()) != null) { if(processor.process(virtualMachine)) { virtualMachine.resume(); } } } @NotNull public DotNetDebugContext createDebugContext() { assert myVirtualMachine != null; return new DotNetDebugContext(mySession.getProject(), myVirtualMachine, myRunProfile); } @Nullable private XLineBreakpoint<?> resolveToBreakpoint(@Nullable Location location) { if(location == null) { return null; } String sourcePath = location.sourcePath(); if(sourcePath == null) { return null; } VirtualFile fileByPath = LocalFileSystem.getInstance().findFileByPath(sourcePath); if(fileByPath == null) { return null; } XLineBreakpoint<XBreakpointProperties> breakpointAtLine = myDebuggerManager.getBreakpointManager().findBreakpointAtLine (DotNetLineBreakpointType.getInstance(), fileByPath, location.lineNumber() - 1); // .net asm - 1 index based, consulo - 0 based if(breakpointAtLine == null) { return null; } return breakpointAtLine; } public void normalizeBreakpoints() { for(XLineBreakpoint<XBreakpointProperties> lineBreakpoint : getOurBreakpoints()) { lineBreakpoint.putUserData(EVENT_REQUEST, null); myDebuggerManager.getBreakpointManager().updateBreakpointPresentation(lineBreakpoint, null, null); } } @NotNull public Collection<? extends XLineBreakpoint<XBreakpointProperties>> getOurBreakpoints() { return ApplicationManager.getApplication().runReadAction(new Computable<Collection<? extends XLineBreakpoint<XBreakpointProperties>>>() { @Override public Collection<? extends XLineBreakpoint<XBreakpointProperties>> compute() { return myDebuggerManager.getBreakpointManager().getBreakpoints(DotNetAbstractBreakpointType.class); } }); } public void processAnyway(Processor<VirtualMachine> processor) { if(myVirtualMachine == null) { return; } processor.process(myVirtualMachine); } public void addCommand(Processor<VirtualMachine> processor) { myQueue.add(processor); } public boolean isConnected() { return myVirtualMachine != null; } }
use existed typemirror
dotnet-debugger-impl/src/org/mustbe/consulo/dotnet/debugger/DotNetDebugThread.java
use existed typemirror
<ide><path>otnet-debugger-impl/src/org/mustbe/consulo/dotnet/debugger/DotNetDebugThread.java <ide> <ide> val type = (DotNetLineBreakpointType) breakpoint.getType(); <ide> <del> type.createRequest(mySession.getProject(), virtualMachine, breakpoint, null); <add> type.createRequest(mySession.getProject(), virtualMachine, breakpoint, typeMirror); <ide> <ide> } <ide> }
Java
agpl-3.0
19d27cc5412c912f81d3616650f780dc4d5ea09d
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
afc0120c-2e61-11e5-9284-b827eb9e62be
hello.java
afba6c58-2e61-11e5-9284-b827eb9e62be
afc0120c-2e61-11e5-9284-b827eb9e62be
hello.java
afc0120c-2e61-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>afba6c58-2e61-11e5-9284-b827eb9e62be <add>afc0120c-2e61-11e5-9284-b827eb9e62be
Java
apache-2.0
9b08bedd7ca6883f3b0d8ad561fb0d4486cf4118
0
jeluard/stone,jeluard/stone
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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. */ package com.github.jeluard.stone.spi; import com.google.common.base.Optional; import com.google.common.collect.Iterables; import java.io.IOException; import org.joda.time.DateTime; import org.junit.Assert; import org.junit.Test; public abstract class BaseStorageTest<T extends Storage> { protected abstract T createStorage() throws IOException; @Test public void shouldEndBeAfterBeginningWhenDefined() throws IOException { final T storage = createStorage(); final Optional<DateTime> beginning = storage.beginning(); final Optional<DateTime> end = storage.end(); if (beginning.isPresent() && end.isPresent()) { Assert.assertTrue(end.get().isAfter(beginning.get())); } } @Test public void shouldBeginningAndEndBeUndefinedWhenAllIsEmpty() throws IOException { final T storage = createStorage(); final Iterable<?> iterable = storage.all(); if (Iterables.isEmpty(iterable)) { Assert.assertFalse(storage.beginning().isPresent()); Assert.assertFalse(storage.end().isPresent()); } } @Test public void shouldBeginningAndEndReflectAll() throws IOException { final T storage = createStorage(); final Optional<DateTime> beginning = storage.beginning(); final Optional<DateTime> end = storage.end(); if (beginning.isPresent() && end.isPresent()) { Assert.assertTrue(end.get().isAfter(beginning.get())); } } @Test public void shouldNewConsolidatesBeLatestFromAll() throws Exception { final T storage = createStorage(); final long timestamp = 12345L; storage.onConsolidation(timestamp, new int[]{1, 2}); Assert.assertEquals(timestamp, storage.end().get().getMillis()); Assert.assertEquals(timestamp, (long) Iterables.getLast(storage.all()).first); } }
core/src/test/java/com/github/jeluard/stone/spi/BaseStorageTest.java
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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. */ package com.github.jeluard.stone.spi; import com.google.common.base.Optional; import com.google.common.collect.Iterables; import java.io.IOException; import org.joda.time.DateTime; import org.junit.Assert; import org.junit.Test; public abstract class BaseStorageTest<T extends Storage> { protected abstract T createStorage() throws IOException; @Test public void shouldEndBeAfterBeginningWhenDefined() throws IOException { final T storage = createStorage(); final Optional<DateTime> beginning = storage.beginning(); final Optional<DateTime> end = storage.end(); if (beginning.isPresent() && end.isPresent()) { Assert.assertTrue(end.get().isAfter(beginning.get())); } } @Test public void shouldBeginningAndEndBeUndefinedWhenAllIsEmpty() throws IOException { final T storage = createStorage(); final Iterable<?> iterable = storage.all(); if (Iterables.isEmpty(iterable)) { Assert.assertFalse(storage.beginning().isPresent()); Assert.assertFalse(storage.end().isPresent()); } } @Test public void shouldBeginningAndEndReflectAll() throws IOException { final T storage = createStorage(); final Optional<DateTime> beginning = storage.beginning(); final Optional<DateTime> end = storage.end(); if (beginning.isPresent() && end.isPresent()) { Assert.assertTrue(end.get().isAfter(beginning.get())); } } @Test public void shouldNewConsolidatesBeLatestFromAll() throws Exception { final T storage = createStorage(); final long timestamp = 12345L; storage.onConsolidation(timestamp, new int[]{1, 2}); Assert.assertEquals(timestamp, storage.end().get()); Assert.assertEquals(timestamp, Iterables.getLast(storage.all())); } }
Fixed test.
core/src/test/java/com/github/jeluard/stone/spi/BaseStorageTest.java
Fixed test.
<ide><path>ore/src/test/java/com/github/jeluard/stone/spi/BaseStorageTest.java <ide> final long timestamp = 12345L; <ide> storage.onConsolidation(timestamp, new int[]{1, 2}); <ide> <del> Assert.assertEquals(timestamp, storage.end().get()); <del> Assert.assertEquals(timestamp, Iterables.getLast(storage.all())); <add> Assert.assertEquals(timestamp, storage.end().get().getMillis()); <add> Assert.assertEquals(timestamp, (long) Iterables.getLast(storage.all()).first); <ide> } <ide> <ide> }
Java
bsd-3-clause
5e92c620bca33a05574e0d052cc0082f315f49b4
0
kevinko/mahttp,kevinko/mahttp
// Copyright 2014, Kevin Ko <[email protected]> package com.faveset.khttp; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.text.SimpleDateFormat; import java.util.Date; import java.util.EnumMap; import java.util.Map; import com.faveset.log.Log; import com.faveset.log.NullLog; // Handles an HTTP request in non-blocking fashion. class HttpConnection { /** * Called when the HttpConnection is closed. The caller should call * close() to clean up. */ public interface OnCloseCallback { void onClose(HttpConnection conn); } private enum State { // Request start line. REQUEST_START, REQUEST_HEADERS, MESSAGE_BODY, // Sending response. Receives will be blocked until // this state is complete. RESPONSE_SEND, SERVER_ERROR, // The state will be manually assigned by a callback. If the callback // does not assign a state, the state will remain unchanged. // The receive handler will exit once this is encountered during // a transition. (A selector can then call the receive handler again // if so configured.) MANUAL, } private static class StateEntry { private State mNextState; private StateHandler mHandler; /** * @param nextState the state to transition to on success. */ public StateEntry(State nextState, StateHandler handler) { mNextState = nextState; mHandler = handler; } public StateHandler getHandler() { return mHandler; } public State getNextState() { return mNextState; } } private static final String sTag = HttpConnection.class.toString(); /* Size for the internal buffers. */ public static final int BUFFER_SIZE = 4096; private static final EnumMap<State, StateEntry> mStateHandlerMap; private Log mLog = new NullLog(); // Formats Date strings in common log format. private ThreadLocal<SimpleDateFormat> mLogDateFormatter = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { // See getLogTime() for time format. return new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z"); } }; private Map<String, HttpHandler> mHttpHandlerMap; private NonBlockingConnection mConn; private HandlerState mHandlerState; private State mState; private OnCloseCallback mOnCloseCallback; private NonBlockingConnection.OnCloseCallback mNbcCloseCallback = new NonBlockingConnection.OnCloseCallback() { public void onClose(NonBlockingConnection conn) { handleClose(conn); } }; private NonBlockingConnection.OnErrorCallback mNbcErrorCallback = new NonBlockingConnection.OnErrorCallback() { public void onError(NonBlockingConnection conn, String reason) { handleError(conn, reason); } }; private NonBlockingConnection.OnRecvCallback mNbcRecvCallback = new NonBlockingConnection.OnRecvCallback() { public void onRecv(NonBlockingConnection conn, ByteBuffer buf) { handleRecv(conn, buf); } }; private HandlerState.OnRequestCallback mRequestCallback = new HandlerState.OnRequestCallback() { public boolean onRequest(HttpRequest req, ByteBuffer data, ResponseWriter w) { return handleRequest(req, data, w); } }; private ResponseWriter.OnSendCallback mSendResponseCallback = new ResponseWriter.OnSendCallback() { public void onSend() { handleSendResponse(); } }; /** * The HttpConnection will manage registration of selector keys. * A SelectorHandler will be attached to selector keys for handling * by callers. */ public HttpConnection(Selector selector, SocketChannel chan) throws IOException { mConn = new NonBlockingConnection(selector, chan, BUFFER_SIZE); mHandlerState = new HandlerState().setOnRequestCallback(mRequestCallback); mState = State.REQUEST_START; } /** * Closes the connection and releases all resources. */ public void close() throws IOException { mConn.close(); } /** * @return the current time in common log format * * [day/month/year:hour:minute:second zone] * day = 2*digit * month = 3*letter * year = 4*digit * hour = 2*digit * minute = 2*digit * second = 2*digit * zone = (`+' | `-') 4*digit */ private String getLogTime() { Date now = new Date(); return mLogDateFormatter.get().format(now); } /** * @return the underlying NonBlockingConnection. */ public NonBlockingConnection getNonBlockingConnection() { return mConn; } /** * Handle read closes. */ private void handleClose(NonBlockingConnection conn) { try { conn.close(); } catch (IOException e) { // Just warn and continue clean-up. mLog.e(sTag, "failed to close connection during shutdown", e); } if (mOnCloseCallback != null) { mOnCloseCallback.onClose(this); } } private void handleError(NonBlockingConnection conn, String reason) { mLog.e(sTag, "error with connection, closing: " + reason); handleClose(conn); } private void handleRecv(NonBlockingConnection conn, ByteBuffer buf) { boolean done = false; do { done = handleStateStep(conn, buf); } while (!done); } private boolean handleRequest(HttpRequest req, ByteBuffer data, ResponseWriter w) { // Prepare the writer. w.setHttpMinorVersion(req.getMinorVersion()); String uri = req.getUri(); HttpHandler handler = mHttpHandlerMap.get(uri); if (handler == null) { sendErrorResponse(HttpStatus.NOT_FOUND); // Transition to a new state to handle the send. return true; } handler.onRequest(req, w); switch (req.getBodyType()) { case READ: // We need to read the body in its entirety. // TODO case IGNORE: default: // It's safe to send the response right now. sendResponse(mConn, w); return true; } } /** * Called after the HTTP response has been sent to the client. This * reconfigures the HttpConnection to listen for another request. */ private void handleSendResponse() { // We're done sending the response; log the result. String remoteAddrStr = mConn.socketChannel().socket().getInetAddress().toString(); ResponseWriter w = mHandlerState.getResponseWriter(); logRequest(mHandlerState.getRequestBuilder(), remoteAddrStr, w.getStatus(), w.getSentCount()); mState = State.REQUEST_START; // Restart the receive, now that we're at the start state. mConn.recvPersistent(mNbcRecvCallback); } /** * Performs one step for the state machine. * * @return true if more data needs to be read into buf. The receive * handler will finish as a result. */ private boolean handleStateStep(NonBlockingConnection conn, ByteBuffer buf) { StateEntry entry = mStateHandlerMap.get(mState); if (entry == null) { mLog.e(sTag, "invalid HTTP state: " + mState); sendErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR); // Unknown state. Stop state steps until we send the response. return true; } try { if (!entry.getHandler().handleState(conn, buf, mHandlerState)) { // Continue reading new data from the connection. The recv() // is already persistent. return true; } State nextState = entry.getNextState(); if (nextState == State.MANUAL) { // Hold back on advancing steps automatically so that the // receive handler can be called again (if configured). // // This gives an opportunity to pause receive handling when, // for example, sending a response. return true; } mState = nextState; } catch (InvalidRequestException e) { sendErrorResponse(e.getErrorCode()); // Stop stepping states until we send the response. return true; } return false; } /** * Logs the request using the response code httpStatus. * * @param req may be null if undetermined (due to error) * @param httpStatus * @param remoteAddrStr remote address * @param responseLen number of bytes for the response. */ private void logRequest(HttpRequest req, String remoteAddrStr, int httpStatus, long responseLen) { String reqStr; if (req != null) { reqStr = req.toString(); } else { reqStr = ""; } String s = String.format("%s - - [%s] \"%s\" %d %d", remoteAddrStr, getLogTime(), reqStr, httpStatus, responseLen); mLog.i(sTag, s); } /** * Convenience method for sending error responses. The state will * change to RESPONSE_SEND. Thus, this should be called in a transition * to a MANUAL state or outside a state machine callback. */ private void sendErrorResponse(int errorCode) { ResponseWriter writer = mHandlerState.getResponseWriter(); writer.writeHeader(errorCode); sendResponse(mConn, writer); } /** * Sends w over conn and configures handleSendResponse to handle the * send completion callback. * * The state will change to RESPONSE_SEND. Thus, this should be called * in a transition to a MANUAL state or outside a state machine callback. * * Receive callbacks will be blocked until send completion. */ private void sendResponse(NonBlockingConnection conn, ResponseWriter w) { mState = State.RESPONSE_SEND; // Turn off receive callbacks, since the state machine is in a send // state. conn.cancelRecv(); w.send(conn, mSendResponseCallback); } /** * Configures the HttpConnection to log output to log. */ public void setLog(Log log) { mLog = log; } /** * Assigns the callback that will be called when the connection is closed. * * Use this for cleaning up any external dependencies on the * HttpConnection. * * The recipient should close the HttpConnection to clean up. */ public void setOnCloseCallback(OnCloseCallback cb) { mOnCloseCallback = cb; } /** * Start HttpConnection processing. * * @param handlers maps uris to HttpHandlers for handling requests. */ public void start(Map<String, HttpHandler> handlers) { mHttpHandlerMap = handlers; // Configure all callbacks. mConn.setOnCloseCallback(mNbcCloseCallback); mConn.setOnErrorCallback(mNbcErrorCallback); mConn.recvPersistent(mNbcRecvCallback); } static { mStateHandlerMap = new EnumMap<State, StateEntry>(State.class); mStateHandlerMap.put(State.REQUEST_START, new StateEntry(State.REQUEST_HEADERS, new RequestStartHandler())); mStateHandlerMap.put(State.REQUEST_HEADERS, new StateEntry(State.MESSAGE_BODY, new RequestHeaderHandler())); // The handleRequest handler will configure the state. mStateHandlerMap.put(State.MESSAGE_BODY, new StateEntry(State.MANUAL, new MessageBodyHandler())); } };
src/main/com/faveset/khttp/HttpConnection.java
// Copyright 2014, Kevin Ko <[email protected]> package com.faveset.khttp; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.EnumMap; import java.util.Map; import com.faveset.log.Log; import com.faveset.log.NullLog; // Handles an HTTP request in non-blocking fashion. class HttpConnection { private static final String sTag = HttpConnection.class.toString(); private Log mLog = new NullLog(); /** * Called when the HttpConnection is closed. The caller should call * close() to clean up. */ public interface OnCloseCallback { void onClose(HttpConnection conn); } private enum State { // Request start line. REQUEST_START, REQUEST_HEADERS, MESSAGE_BODY, // Sending response. Receives will be blocked until // this state is complete. RESPONSE_SEND, SERVER_ERROR, // The state will be manually assigned by a callback. If the callback // does not assign a state, the state will remain unchanged. // The receive handler will exit once this is encountered during // a transition. (A selector can then call the receive handler again // if so configured.) MANUAL, } private static class StateEntry { private State mNextState; private StateHandler mHandler; /** * @param nextState the state to transition to on success. */ public StateEntry(State nextState, StateHandler handler) { mNextState = nextState; mHandler = handler; } public StateHandler getHandler() { return mHandler; } public State getNextState() { return mNextState; } } /* Size for the internal buffers. */ public static final int BUFFER_SIZE = 4096; private static final EnumMap<State, StateEntry> mStateHandlerMap; private Map<String, HttpHandler> mHttpHandlerMap; private NonBlockingConnection mConn; private HandlerState mHandlerState; private State mState; private OnCloseCallback mOnCloseCallback; private NonBlockingConnection.OnCloseCallback mNbcCloseCallback = new NonBlockingConnection.OnCloseCallback() { public void onClose(NonBlockingConnection conn) { handleClose(conn); } }; private NonBlockingConnection.OnErrorCallback mNbcErrorCallback = new NonBlockingConnection.OnErrorCallback() { public void onError(NonBlockingConnection conn, String reason) { handleError(conn, reason); } }; private NonBlockingConnection.OnRecvCallback mNbcRecvCallback = new NonBlockingConnection.OnRecvCallback() { public void onRecv(NonBlockingConnection conn, ByteBuffer buf) { handleRecv(conn, buf); } }; private HandlerState.OnRequestCallback mRequestCallback = new HandlerState.OnRequestCallback() { public boolean onRequest(HttpRequest req, ByteBuffer data, ResponseWriter w) { return handleRequest(req, data, w); } }; private ResponseWriter.OnSendCallback mSendResponseCallback = new ResponseWriter.OnSendCallback() { public void onSend() { handleSendResponse(); } }; /** * The HttpConnection will manage registration of selector keys. * A SelectorHandler will be attached to selector keys for handling * by callers. */ public HttpConnection(Selector selector, SocketChannel chan) throws IOException { mConn = new NonBlockingConnection(selector, chan, BUFFER_SIZE); mHandlerState = new HandlerState().setOnRequestCallback(mRequestCallback); mState = State.REQUEST_START; } /** * Closes the connection and releases all resources. */ public void close() throws IOException { mConn.close(); } /** * @return the underlying NonBlockingConnection. */ public NonBlockingConnection getNonBlockingConnection() { return mConn; } /** * Handle read closes. */ private void handleClose(NonBlockingConnection conn) { try { conn.close(); } catch (IOException e) { // Just warn and continue clean-up. mLog.e(sTag, "failed to close connection during shutdown", e); } if (mOnCloseCallback != null) { mOnCloseCallback.onClose(this); } } private void handleError(NonBlockingConnection conn, String reason) { mLog.e(sTag, "error with connection, closing: " + reason); handleClose(conn); } private void handleRecv(NonBlockingConnection conn, ByteBuffer buf) { boolean done = false; do { done = handleStateStep(conn, buf); } while (!done); } private boolean handleRequest(HttpRequest req, ByteBuffer data, ResponseWriter w) { // Prepare the writer. w.setHttpMinorVersion(req.getMinorVersion()); String uri = req.getUri(); HttpHandler handler = mHttpHandlerMap.get(uri); if (handler == null) { sendErrorResponse(HttpStatus.NOT_FOUND); // Transition to a new state to handle the send. return true; } handler.onRequest(req, w); switch (req.getBodyType()) { case READ: // We need to read the body in its entirety. // TODO case IGNORE: default: // It's safe to send the response right now. sendResponse(mConn, w); return true; } } /** * Called after the HTTP response has been sent to the client. This * reconfigures the HttpConnection to listen for another request. */ private void handleSendResponse() { mState = State.REQUEST_START; // Restart the receive, now that we're at the start state. mConn.recvPersistent(mNbcRecvCallback); } /** * Performs one step for the state machine. * * @return true if more data needs to be read into buf. The receive * handler will finish as a result. */ private boolean handleStateStep(NonBlockingConnection conn, ByteBuffer buf) { StateEntry entry = mStateHandlerMap.get(mState); if (entry == null) { sendErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR); // Unknown state. Stop state steps until we send the response. return true; } try { if (!entry.getHandler().handleState(conn, buf, mHandlerState)) { // Continue reading new data from the connection. The recv() // is already persistent. return true; } State nextState = entry.getNextState(); if (nextState == State.MANUAL) { // Hold back on advancing steps automatically so that the // receive handler can be called again (if configured). // // This gives an opportunity to pause receive handling when, // for example, sending a response. return true; } mState = nextState; } catch (InvalidRequestException e) { sendErrorResponse(e.getErrorCode()); // Stop stepping states until we send the response. return true; } return false; } /** * Resets the connection state for a new request. */ private void reset() { mState = State.REQUEST_START; mHandlerState.clear(); } /** * Convenience method for sending error responses. The state will * change to RESPONSE_SEND. Thus, this should be called in a transition * to a MANUAL state or outside a state machine callback. */ private void sendErrorResponse(int errorCode) { ResponseWriter writer = mHandlerState.getResponseWriter(); writer.writeHeader(errorCode); sendResponse(mConn, writer); } /** * Sends w over conn and configures handleSendResponse to handle the * send completion callback. * * The state will change to RESPONSE_SEND. Thus, this should be called * in a transition to a MANUAL state or outside a state machine callback. * * Receive callbacks will be blocked until send completion. */ private void sendResponse(NonBlockingConnection conn, ResponseWriter w) { mState = State.RESPONSE_SEND; // Turn off receive callbacks, since the state machine is in a send // state. conn.cancelRecv(); w.send(conn, mSendResponseCallback); } /** * Configures the HttpConnection to log output to log. */ public void setLog(Log log) { mLog = log; } /** * Assigns the callback that will be called when the connection is closed. * * Use this for cleaning up any external dependencies on the * HttpConnection. * * The recipient should close the HttpConnection to clean up. */ public void setOnCloseCallback(OnCloseCallback cb) { mOnCloseCallback = cb; } /** * Start HttpConnection processing. * * @param handlers maps uris to HttpHandlers for handling requests. */ public void start(Map<String, HttpHandler> handlers) { mHttpHandlerMap = handlers; // Configure all callbacks. mConn.setOnCloseCallback(mNbcCloseCallback); mConn.setOnErrorCallback(mNbcErrorCallback); mConn.recvPersistent(mNbcRecvCallback); } static { mStateHandlerMap = new EnumMap<State, StateEntry>(State.class); mStateHandlerMap.put(State.REQUEST_START, new StateEntry(State.REQUEST_HEADERS, new RequestStartHandler())); mStateHandlerMap.put(State.REQUEST_HEADERS, new StateEntry(State.MESSAGE_BODY, new RequestHeaderHandler())); // The handleRequest handler will configure the state. mStateHandlerMap.put(State.MESSAGE_BODY, new StateEntry(State.MANUAL, new MessageBodyHandler())); } };
Add request logging. Add error logging when an invalid handler state is encountered.
src/main/com/faveset/khttp/HttpConnection.java
Add request logging. Add error logging when an invalid handler state is encountered.
<ide><path>rc/main/com/faveset/khttp/HttpConnection.java <ide> import java.nio.channels.Selector; <ide> import java.nio.channels.SocketChannel; <ide> <add>import java.text.SimpleDateFormat; <add>import java.util.Date; <ide> import java.util.EnumMap; <ide> import java.util.Map; <ide> <ide> <ide> // Handles an HTTP request in non-blocking fashion. <ide> class HttpConnection { <del> private static final String sTag = HttpConnection.class.toString(); <del> <del> private Log mLog = new NullLog(); <del> <ide> /** <ide> * Called when the HttpConnection is closed. The caller should call <ide> * close() to clean up. <ide> } <ide> } <ide> <add> private static final String sTag = HttpConnection.class.toString(); <add> <ide> /* Size for the internal buffers. */ <ide> public static final int BUFFER_SIZE = 4096; <ide> <ide> private static final EnumMap<State, StateEntry> mStateHandlerMap; <add> <add> private Log mLog = new NullLog(); <add> <add> // Formats Date strings in common log format. <add> private ThreadLocal<SimpleDateFormat> mLogDateFormatter = <add> new ThreadLocal<SimpleDateFormat>() { <add> @Override <add> protected SimpleDateFormat initialValue() { <add> // See getLogTime() for time format. <add> return new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z"); <add> } <add> }; <ide> <ide> private Map<String, HttpHandler> mHttpHandlerMap; <ide> <ide> */ <ide> public void close() throws IOException { <ide> mConn.close(); <add> } <add> <add> /** <add> * @return the current time in common log format <add> * <add> * [day/month/year:hour:minute:second zone] <add> * day = 2*digit <add> * month = 3*letter <add> * year = 4*digit <add> * hour = 2*digit <add> * minute = 2*digit <add> * second = 2*digit <add> * zone = (`+' | `-') 4*digit <add> */ <add> private String getLogTime() { <add> Date now = new Date(); <add> return mLogDateFormatter.get().format(now); <ide> } <ide> <ide> /** <ide> * reconfigures the HttpConnection to listen for another request. <ide> */ <ide> private void handleSendResponse() { <add> // We're done sending the response; log the result. <add> String remoteAddrStr = mConn.socketChannel().socket().getInetAddress().toString(); <add> ResponseWriter w = mHandlerState.getResponseWriter(); <add> logRequest(mHandlerState.getRequestBuilder(), remoteAddrStr, <add> w.getStatus(), w.getSentCount()); <add> <ide> mState = State.REQUEST_START; <ide> <ide> // Restart the receive, now that we're at the start state. <ide> private boolean handleStateStep(NonBlockingConnection conn, ByteBuffer buf) { <ide> StateEntry entry = mStateHandlerMap.get(mState); <ide> if (entry == null) { <add> mLog.e(sTag, "invalid HTTP state: " + mState); <add> <ide> sendErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR); <ide> // Unknown state. Stop state steps until we send the response. <ide> return true; <ide> } <ide> <ide> /** <del> * Resets the connection state for a new request. <del> */ <del> private void reset() { <del> mState = State.REQUEST_START; <del> mHandlerState.clear(); <add> * Logs the request using the response code httpStatus. <add> * <add> * @param req may be null if undetermined (due to error) <add> * @param httpStatus <add> * @param remoteAddrStr remote address <add> * @param responseLen number of bytes for the response. <add> */ <add> private void logRequest(HttpRequest req, <add> String remoteAddrStr, int httpStatus, long responseLen) { <add> String reqStr; <add> if (req != null) { <add> reqStr = req.toString(); <add> } else { <add> reqStr = ""; <add> } <add> <add> String s = String.format("%s - - [%s] \"%s\" %d %d", <add> remoteAddrStr, getLogTime(), reqStr, httpStatus, responseLen); <add> <add> mLog.i(sTag, s); <ide> } <ide> <ide> /**
Java
mit
ea4be4a3bbd4d4c86e4464e09119394a7ddbd9db
0
jpolodna01/Drury-Explorer
package edu.drury.mcs.icarus.druryexplorer; import android.app.ActionBar; import android.app.Activity; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class about_drury extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about_drury); ActionBar bar =getActionBar(); bar.setTitle("About Drury"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.navigation, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_about) { Intent about = new Intent(this, About_Page.class); startActivity(about); return true; } if (id == R.id.about_drury) { Intent drury = new Intent(this, about_drury.class); startActivity(drury); return true; } return super.onOptionsItemSelected(item); } }
DruryExplorer/app/src/main/java/edu/drury/mcs/icarus/druryexplorer/about_drury.java
package edu.drury.mcs.icarus.druryexplorer; import android.app.Activity; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class about_drury extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about_drury); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.navigation, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_about) { Intent about = new Intent(this, About_Page.class); startActivity(about); return true; } if (id == R.id.about_drury) { Intent drury = new Intent(this, about_drury.class); startActivity(drury); return true; } return super.onOptionsItemSelected(item); } }
made the background image more transparent
DruryExplorer/app/src/main/java/edu/drury/mcs/icarus/druryexplorer/about_drury.java
made the background image more transparent
<ide><path>ruryExplorer/app/src/main/java/edu/drury/mcs/icarus/druryexplorer/about_drury.java <ide> package edu.drury.mcs.icarus.druryexplorer; <ide> <add>import android.app.ActionBar; <ide> import android.app.Activity; <ide> import android.content.Intent; <ide> import android.support.v7.app.ActionBarActivity; <ide> protected void onCreate(Bundle savedInstanceState) { <ide> super.onCreate(savedInstanceState); <ide> setContentView(R.layout.activity_about_drury); <add> <add> ActionBar bar =getActionBar(); <add> bar.setTitle("About Drury"); <ide> } <ide> <ide>
Java
apache-2.0
12bf445f4bb13797edb42d7c438365876815dc11
0
eladnava/redalert-android
package com.red.alert.logic.notifications; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.BitmapFactory; import android.graphics.Color; import androidx.annotation.RequiresApi; import androidx.core.app.NotificationCompat; import me.pushy.sdk.Pushy; import android.media.AudioAttributes; import android.net.Uri; import android.os.Build; import android.util.Log; import android.widget.Toast; import com.red.alert.R; import com.red.alert.activities.AlertPopup; import com.red.alert.activities.Main; import com.red.alert.config.Logging; import com.red.alert.config.Sound; import com.red.alert.logic.communication.intents.MainActivityParameters; import com.red.alert.logic.communication.intents.RocketNotificationParameters; import com.red.alert.logic.feedback.sound.SoundLogic; import com.red.alert.logic.integration.BluetoothIntegration; import com.red.alert.receivers.NotificationDeletedReceiver; import com.red.alert.utils.communication.Broadcasts; import com.red.alert.utils.formatting.StringUtils; public class RocketNotifications { // Silent notification channel config for no-sound alerts public static final String SILENT_NOTIFICATION_CHANNEL_ID = "redalert_silent"; public static final String SILENT_NOTIFICATION_CHANNEL_NAME = "Silent Notifications"; public static void notify(Context context, String city, String notificationTitle, String notificationContent, String alertType, String overrideSound) { // Get notification manager NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE); // In case there is no content if (StringUtils.stringIsNullOrEmpty(notificationContent)) { // Move title to content notificationContent = notificationTitle; // Set title as app name notificationTitle = context.getString(R.string.appName); } // Create a new notification and style it NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setTicker(notificationContent) .setAutoCancel(true) .setContentTitle(notificationTitle) .setContentText(notificationContent) .setLights(Color.RED, 1000, 1000) .setSmallIcon(R.drawable.ic_notify) .setColor(Color.parseColor("#ff4032")) .setCategory(NotificationCompat.CATEGORY_ALARM) .setPriority(NotificationCompat.PRIORITY_MAX) .setStyle(new NotificationCompat.BigTextStyle().bigText(notificationContent)) .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher)); // Handle notification delete builder.setDeleteIntent(getNotificationDeletedReceiverIntent(context)); // No click event for test notifications if (!alertType.contains("test")) { // Handle notification click builder.setContentIntent(getNotificationIntent(context)); } // Generate a notification ID based on the unique hash-code of the alert zone int notificationID = notificationTitle.hashCode(); // Cancel previous notification for same alert zone notificationManager.cancel(notificationID); // Automatically configure notification channel (if required) setNotificationChannel(alertType, builder, context); try { // Issue the notification notificationManager.notify(notificationID, builder.build()); } catch (Exception exc) { // Log it Log.e(Logging.TAG, "Rocket notification failed", exc); // Show it as a toast message Toast.makeText(context, notificationTitle + " - " + notificationContent, Toast.LENGTH_LONG).show(); } // Play alert sound (if applicable) SoundLogic.playSound(alertType, overrideSound, context); // Show alert popup (if applicable) AlertPopup.showAlertPopup(alertType, city, context); // Notify BLE devices (if applicable) BluetoothIntegration.notifyDevices(alertType, context); // Reload recent alerts (if main activity is open) Broadcasts.publish(context, MainActivityParameters.RELOAD_RECENT_ALERTS); } private static PendingIntent getNotificationDeletedReceiverIntent(Context context) { // Prepare delete intent Intent deleteIntent = new Intent(context, NotificationDeletedReceiver.class); // Set action deleteIntent.setAction(RocketNotificationParameters.NOTIFICATION_DELETED_ACTION); // Get broadcast receiver return PendingIntent.getBroadcast(context, 0, deleteIntent, 0); } public static PendingIntent getNotificationIntent(Context context) { // Prepare notification intent Intent notificationIntent = new Intent(context, Main.class); // Prepare pending intent PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); // Return it return pendingIntent; } private static void setNotificationChannel(String alertType, NotificationCompat.Builder builder, Context context) { // Android O and up (no channels before then) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { return; } // Get path to alert sound resource for current alert type Uri alarmSoundURI = SoundLogic.getAlertSound(alertType, null, context); // "Silent" sound selected for this alert type? if (SoundLogic.shouldPlayAlertSound(alertType, context) && alarmSoundURI == null) { // Use silent alert notification channel setSilentNotificationChannel(builder, context); } else { // Use standard high-importance channel with sound + vibrate Pushy.setNotificationChannel(builder, context); } } @RequiresApi(api = Build.VERSION_CODES.O) private static void setSilentNotificationChannel(NotificationCompat.Builder builder, Context context) { // Get notification manager instance NotificationManager manager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE); // Initialize channel (low importance so Android does not force sound and vibration) NotificationChannel channel = new NotificationChannel(SILENT_NOTIFICATION_CHANNEL_ID, SILENT_NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW); // Create channel (does nothing if already exists) manager.createNotificationChannel(channel); // Set notification channel on builder builder.setChannelId(SILENT_NOTIFICATION_CHANNEL_ID); } }
app/src/main/java/com/red/alert/logic/notifications/RocketNotifications.java
package com.red.alert.logic.notifications; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.BitmapFactory; import android.graphics.Color; import androidx.core.app.NotificationCompat; import android.util.Log; import android.widget.Toast; import com.red.alert.R; import com.red.alert.activities.AlertPopup; import com.red.alert.activities.Main; import com.red.alert.config.Logging; import com.red.alert.logic.communication.intents.MainActivityParameters; import com.red.alert.logic.communication.intents.RocketNotificationParameters; import com.red.alert.logic.feedback.sound.SoundLogic; import com.red.alert.logic.integration.BluetoothIntegration; import com.red.alert.receivers.NotificationDeletedReceiver; import com.red.alert.utils.communication.Broadcasts; import com.red.alert.utils.formatting.StringUtils; import me.pushy.sdk.Pushy; public class RocketNotifications { public static void notify(Context context, String city, String notificationTitle, String notificationContent, String alertType, String overrideSound) { // Get notification manager NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE); // In case there is no content if (StringUtils.stringIsNullOrEmpty(notificationContent)) { // Move title to content notificationContent = notificationTitle; // Set title as app name notificationTitle = context.getString(R.string.appName); } // Create a new notification and style it NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setTicker(notificationContent) .setAutoCancel(true) .setContentTitle(notificationTitle) .setContentText(notificationContent) .setLights(Color.RED, 1000, 1000) .setSmallIcon(R.drawable.ic_notify) .setColor(Color.parseColor("#ff4032")) .setCategory(NotificationCompat.CATEGORY_ALARM) .setPriority(NotificationCompat.PRIORITY_MAX) .setStyle(new NotificationCompat.BigTextStyle().bigText(notificationContent)) .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher)); // Handle notification delete builder.setDeleteIntent(getNotificationDeletedReceiverIntent(context)); // No click event for test notifications if (!alertType.contains("test")) { // Handle notification click builder.setContentIntent(getNotificationIntent(context)); } // Generate a notification ID based on the unique hash-code of the alert zone int notificationID = notificationTitle.hashCode(); // Cancel previous notification for same alert zone notificationManager.cancel(notificationID); // Automatically configure notification channel (if required) Pushy.setNotificationChannel(builder, context); try { // Issue the notification notificationManager.notify(notificationID, builder.build()); } catch (Exception exc) { // Log it Log.e(Logging.TAG, "Rocket notification failed", exc); // Show it as a toast message Toast.makeText(context, notificationTitle + " - " + notificationContent, Toast.LENGTH_LONG).show(); } // Play alert sound (if applicable) SoundLogic.playSound(alertType, overrideSound, context); // Show alert popup (if applicable) AlertPopup.showAlertPopup(alertType, city, context); // Notify BLE devices (if applicable) BluetoothIntegration.notifyDevices(alertType, context); // Reload recent alerts (if main activity is open) Broadcasts.publish(context, MainActivityParameters.RELOAD_RECENT_ALERTS); } private static PendingIntent getNotificationDeletedReceiverIntent(Context context) { // Prepare delete intent Intent deleteIntent = new Intent(context, NotificationDeletedReceiver.class); // Set action deleteIntent.setAction(RocketNotificationParameters.NOTIFICATION_DELETED_ACTION); // Get broadcast receiver return PendingIntent.getBroadcast(context, 0, deleteIntent, 0); } public static PendingIntent getNotificationIntent(Context context) { // Prepare notification intent Intent notificationIntent = new Intent(context, Main.class); // Prepare pending intent PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); // Return it return pendingIntent; } }
Fix #26: Alert Sound even when set to silent
app/src/main/java/com/red/alert/logic/notifications/RocketNotifications.java
Fix #26: Alert Sound even when set to silent
<ide><path>pp/src/main/java/com/red/alert/logic/notifications/RocketNotifications.java <ide> package com.red.alert.logic.notifications; <ide> <add>import android.app.NotificationChannel; <ide> import android.app.NotificationManager; <ide> import android.app.PendingIntent; <ide> import android.content.Context; <ide> import android.content.Intent; <ide> import android.graphics.BitmapFactory; <ide> import android.graphics.Color; <add> <add>import androidx.annotation.RequiresApi; <ide> import androidx.core.app.NotificationCompat; <add>import me.pushy.sdk.Pushy; <add> <add>import android.media.AudioAttributes; <add>import android.net.Uri; <add>import android.os.Build; <ide> import android.util.Log; <ide> import android.widget.Toast; <ide> <ide> import com.red.alert.activities.AlertPopup; <ide> import com.red.alert.activities.Main; <ide> import com.red.alert.config.Logging; <add>import com.red.alert.config.Sound; <ide> import com.red.alert.logic.communication.intents.MainActivityParameters; <ide> import com.red.alert.logic.communication.intents.RocketNotificationParameters; <ide> import com.red.alert.logic.feedback.sound.SoundLogic; <ide> import com.red.alert.utils.communication.Broadcasts; <ide> import com.red.alert.utils.formatting.StringUtils; <ide> <del>import me.pushy.sdk.Pushy; <add>public class RocketNotifications { <add> // Silent notification channel config for no-sound alerts <add> public static final String SILENT_NOTIFICATION_CHANNEL_ID = "redalert_silent"; <add> public static final String SILENT_NOTIFICATION_CHANNEL_NAME = "Silent Notifications"; <ide> <del>public class RocketNotifications { <ide> public static void notify(Context context, String city, String notificationTitle, String notificationContent, String alertType, String overrideSound) { <ide> // Get notification manager <ide> NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE); <ide> notificationManager.cancel(notificationID); <ide> <ide> // Automatically configure notification channel (if required) <del> Pushy.setNotificationChannel(builder, context); <add> setNotificationChannel(alertType, builder, context); <ide> <ide> try { <ide> // Issue the notification <ide> // Return it <ide> return pendingIntent; <ide> } <add> <add> private static void setNotificationChannel(String alertType, NotificationCompat.Builder builder, Context context) { <add> // Android O and up (no channels before then) <add> if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { <add> return; <add> } <add> <add> // Get path to alert sound resource for current alert type <add> Uri alarmSoundURI = SoundLogic.getAlertSound(alertType, null, context); <add> <add> // "Silent" sound selected for this alert type? <add> if (SoundLogic.shouldPlayAlertSound(alertType, context) && alarmSoundURI == null) { <add> // Use silent alert notification channel <add> setSilentNotificationChannel(builder, context); <add> } <add> else { <add> // Use standard high-importance channel with sound + vibrate <add> Pushy.setNotificationChannel(builder, context); <add> } <add> } <add> <add> @RequiresApi(api = Build.VERSION_CODES.O) <add> private static void setSilentNotificationChannel(NotificationCompat.Builder builder, Context context) { <add> // Get notification manager instance <add> NotificationManager manager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE); <add> <add> // Initialize channel (low importance so Android does not force sound and vibration) <add> NotificationChannel channel = new NotificationChannel(SILENT_NOTIFICATION_CHANNEL_ID, SILENT_NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW); <add> <add> // Create channel (does nothing if already exists) <add> manager.createNotificationChannel(channel); <add> <add> // Set notification channel on builder <add> builder.setChannelId(SILENT_NOTIFICATION_CHANNEL_ID); <add> } <ide> }
Java
apache-2.0
0fc491da82be697d0dbff2627a3c37cc729d5e07
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.sh.rename; import com.intellij.codeInsight.template.impl.TemplateManagerImpl; import com.intellij.codeInsight.template.impl.TemplateState; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.application.PluginPathManager; import com.intellij.openapi.util.Disposer; import com.intellij.testFramework.LightPlatformCodeInsightTestCase; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class ShRenameAllOccurrencesTest extends LightPlatformCodeInsightTestCase { @NotNull @Override protected String getTestDataPath() { return PluginPathManager.getPluginHomePath("sh") + "/testData/rename/"; } public void testBasic1() { doTest("MY_NAME"); } public void testBasic2() { doTest(null); } public void testBasic3() { doTest("command -v"); } public void testSelection1() { doTest("Bye"); } public void testSelection2() { doTest("zsh"); } public void testSelection3() { doTest("m"); } public void testSelection4() { doTest("4]]"); } public void testNotFunction() { doTest("bash"); } public void testKeyword1() { doTest(null); } public void testKeyword2() { doTest(null); } private void doTest(@Nullable String newName) { configureByFile(getTestName(true) + "-before.sh"); TemplateManagerImpl.setTemplateTesting(getTestRootDisposable()); executeRenameAction(newName != null); TemplateState templateState = TemplateManagerImpl.getTemplateState(getEditor()); if (newName != null) { assertNotNull(templateState); } else { assertNull(templateState); return; } assertFalse(templateState.isFinished()); type(newName); templateState.gotoEnd(); checkResultByFile(getTestName(true) + "-after.sh"); doTestWithPlainTextRenamer(newName); } private void executeRenameAction(boolean expectEnabled) { try { executeAction(IdeActions.ACTION_RENAME); } catch (AssertionError e) { if (expectEnabled) { throw e; } } } private void doTestWithPlainTextRenamer(@NotNull String newName) { configureByFile(getTestName(true) + "-before.sh"); runWithoutInplaceRename(() -> { executeAction(IdeActions.ACTION_RENAME); getEditor().getUserData(ShRenameAllOccurrencesHandler.RENAMER_KEY).renameTo(newName); }); checkResultByFile(getTestName(true) + "-after.sh"); } static void runWithoutInplaceRename(@NotNull Runnable runnable) { Disposable parentDisposable = Disposer.newDisposable(); ShRenameAllOccurrencesHandler.getMaxInplaceRenameSegmentsRegistryValue().setValue(-1, parentDisposable); try { runnable.run(); } finally { Disposer.dispose(parentDisposable); } } }
plugins/sh/tests/com/intellij/sh/rename/ShRenameAllOccurrencesTest.java
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.sh.rename; import com.intellij.codeInsight.template.impl.TemplateManagerImpl; import com.intellij.codeInsight.template.impl.TemplateState; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.application.PluginPathManager; import com.intellij.openapi.util.Disposer; import com.intellij.testFramework.LightPlatformCodeInsightTestCase; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class ShRenameAllOccurrencesTest extends LightPlatformCodeInsightTestCase { @NotNull @Override protected String getTestDataPath() { return PluginPathManager.getPluginHomePath("sh") + "/testData/rename/"; } public void testBasic1() { doTest("MY_NAME"); } public void testBasic2() { doTest(null); } public void testBasic3() { doTest("command -v"); } public void testSelection1() { doTest("Bye"); } public void testSelection2() { doTest("zsh"); } public void testSelection3() { doTest("m"); } public void testSelection4() { doTest("4]]"); } public void testNotFunction() { doTest("bash"); } public void testKeyword1() { doTest(null); } public void testKeyword2() { doTest(null); } private void doTest(@Nullable String newName) { configureByFile(getTestName(true) + "-before.sh"); TemplateManagerImpl.setTemplateTesting(getTestRootDisposable()); executeAction(IdeActions.ACTION_RENAME); TemplateState templateState = TemplateManagerImpl.getTemplateState(getEditor()); if (newName != null) { assertNotNull(templateState); } else { assertNull(templateState); return; } assertFalse(templateState.isFinished()); type(newName); templateState.gotoEnd(); checkResultByFile(getTestName(true) + "-after.sh"); doTestWithPlainTextRenamer(newName); } private void doTestWithPlainTextRenamer(@NotNull String newName) { configureByFile(getTestName(true) + "-before.sh"); runWithoutInplaceRename(() -> { executeAction(IdeActions.ACTION_RENAME); getEditor().getUserData(ShRenameAllOccurrencesHandler.RENAMER_KEY).renameTo(newName); }); checkResultByFile(getTestName(true) + "-after.sh"); } static void runWithoutInplaceRename(@NotNull Runnable runnable) { Disposable parentDisposable = Disposer.newDisposable(); ShRenameAllOccurrencesHandler.getMaxInplaceRenameSegmentsRegistryValue().setValue(-1, parentDisposable); try { runnable.run(); } finally { Disposer.dispose(parentDisposable); } } }
sh: fix test when rename action is disabled, e.g. when renaming keywords GitOrigin-RevId: 334fbc36a9696ae7ab6cd39c52563e1c91555442
plugins/sh/tests/com/intellij/sh/rename/ShRenameAllOccurrencesTest.java
sh: fix test when rename action is disabled, e.g. when renaming keywords
<ide><path>lugins/sh/tests/com/intellij/sh/rename/ShRenameAllOccurrencesTest.java <ide> private void doTest(@Nullable String newName) { <ide> configureByFile(getTestName(true) + "-before.sh"); <ide> TemplateManagerImpl.setTemplateTesting(getTestRootDisposable()); <del> executeAction(IdeActions.ACTION_RENAME); <add> executeRenameAction(newName != null); <ide> TemplateState templateState = TemplateManagerImpl.getTemplateState(getEditor()); <ide> if (newName != null) { <ide> assertNotNull(templateState); <ide> templateState.gotoEnd(); <ide> checkResultByFile(getTestName(true) + "-after.sh"); <ide> doTestWithPlainTextRenamer(newName); <add> } <add> <add> private void executeRenameAction(boolean expectEnabled) { <add> try { <add> executeAction(IdeActions.ACTION_RENAME); <add> } <add> catch (AssertionError e) { <add> if (expectEnabled) { <add> throw e; <add> } <add> } <ide> } <ide> <ide> private void doTestWithPlainTextRenamer(@NotNull String newName) {
JavaScript
mit
7b8435174142cb793d4efc42045b9c9d3f00b2d0
0
17/seals,17/seals
import helpers from './helpers' function normalizeMessage (chatHistory, me, friend) { // let messageList // let mediaList let result = { message: [] , media: [] } for (let i = 0; i < chatHistory.length; i++) { const _message = chatHistory[i] const _content = _message.c const message = { time: _message.time , from: _message.fromuin , to: _message.fromuin === friend ? me : friend , content: [] , media: {} } const content = [] for (let j = 0; j < _content.length; j++) { const _slice = _content[j] // 0 文字 // 1 表情 // 2 URL 图片 // 3 UUID 图片 // content.push({ // type: _slice.t // , content: _slice.uuid || _slice.v // }) switch (_slice.t) { case 0: case 1: content.push({ type: _slice.t , value: _slice.v }) break case 2: case 3: const uuid = helpers.uuid() result.media.push({ uuid , type: _slice.t , value: _slice.uuid || _slice.v }) message.media[uuid] = { type: _slice.t , value: _slice.uuid || _slice.v } content.push({ type: _slice.t , value: uuid }) break default: break } } message.content = content result.message.push(message) } return result } function normalizeFriendList (grp, remarks) { // const { grp, remarks } = data const groupList = [] const nicenameList = {} for (let i = 0; i < remarks.length; i++) { nicenameList[remarks[i].u] = remarks[i].n } for (let i = 0; i < grp.length; i++) { const group = grp[i] const friendList = { index: group.gid // group.gsd , name: group.gn , friend: [] } if (group.frd == null) { continue } for (let j = 0; j < group.frd.length; j++) { let friend = group.frd[j] friendList.friend.push({ number: friend.u , name: friend.n , nicename: nicenameList[friend.u] || '' }) } groupList.push(friendList) } return groupList } export default { normalizeMessage , normalizeFriendList }
src/utils/qq.js
import helpers from './helpers' function normalizeMessage (chatHistory, me, friend) { // let messageList // let mediaList let result = { message: [] , media: [] } for (let i = 0; i < chatHistory.length; i++) { const _message = chatHistory[i] const _content = _message.c const message = { time: _message.time , from: _message.fromuin , to: _message.fromuin === friend ? me : friend , content: [] , media: {} } const content = [] for (let j = 0; j < _content.length; j++) { const _slice = _content[j] // 0 文字 // 1 表情 // 2 URL 图片 // 3 UUID 图片 // content.push({ // type: _slice.t // , content: _slice.uuid || _slice.v // }) switch (_slice.t) { case 0: case 1: content.push({ type: _slice.t , value: _slice.v }) break case 2: case 3: const uuid = helpers.uuid() result.media.push({ uuid , type: _slice.t , value: _slice.uuid || _slice.v }) message.media[uuid] = { type: _slice.t , value: _slice.uuid || _slice.v } content.push({ type: _slice.t , value: uuid }) break default: break } } message.content = content result.message.push(message) } return result } function normalizeFriendList (grp, remarks) { // const { grp, remarks } = data const groupList = [] const nicenameList = {} for (let i = 0; i < remarks.length; i++) { nicenameList[remarks[i].u] = remarks[i].n } for (let i = 0; i < grp.length; i++) { const group = grp[i] const friendList = { index: group.gid // group.gsd , name: group.gn , friend: [] } for (let j = 0; j < group.frd.length; j++) { let friend = group.frd[j] friendList.friend.push({ number: friend.u , name: friend.n , nicename: nicenameList[friend.u] || '' }) } groupList.push(friendList) } return groupList } export default { normalizeMessage , normalizeFriendList }
修复解析空好友表列时出现的错误
src/utils/qq.js
修复解析空好友表列时出现的错误
<ide><path>rc/utils/qq.js <ide> , name: group.gn <ide> , friend: [] <ide> } <add> if (group.frd == null) { <add> continue <add> } <ide> for (let j = 0; j < group.frd.length; j++) { <ide> let friend = group.frd[j] <ide> friendList.friend.push({
Java
apache-2.0
8b66a4f8e46b2c7d58a281247f7a08c8605b6c8d
0
max3163/jmeter,ra0077/jmeter,max3163/jmeter,max3163/jmeter,kschroeder/jmeter,ra0077/jmeter,d0k1/jmeter,kschroeder/jmeter,hizhangqi/jmeter-1,ubikfsabbe/jmeter,thomsonreuters/jmeter,vherilier/jmeter,liwangbest/jmeter,ThiagoGarciaAlves/jmeter,tuanhq/jmeter,ubikloadpack/jmeter,kschroeder/jmeter,hemikak/jmeter,hemikak/jmeter,ThiagoGarciaAlves/jmeter,fj11/jmeter,hemikak/jmeter,ubikloadpack/jmeter,DoctorQ/jmeter,hizhangqi/jmeter-1,etnetera/jmeter,ubikfsabbe/jmeter,thomsonreuters/jmeter,ThiagoGarciaAlves/jmeter,vherilier/jmeter,hemikak/jmeter,kyroskoh/jmeter,DoctorQ/jmeter,max3163/jmeter,kyroskoh/jmeter,etnetera/jmeter,etnetera/jmeter,vherilier/jmeter,fj11/jmeter,kyroskoh/jmeter,tuanhq/jmeter,tuanhq/jmeter,thomsonreuters/jmeter,irfanah/jmeter,fj11/jmeter,etnetera/jmeter,irfanah/jmeter,ubikfsabbe/jmeter,d0k1/jmeter,ra0077/jmeter,irfanah/jmeter,d0k1/jmeter,etnetera/jmeter,ubikfsabbe/jmeter,ubikloadpack/jmeter,DoctorQ/jmeter,liwangbest/jmeter,ra0077/jmeter,ubikloadpack/jmeter,liwangbest/jmeter,vherilier/jmeter,hizhangqi/jmeter-1,d0k1/jmeter
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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.apache.jmeter.testelement; import java.io.IOException; import java.io.Serializable; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.jmeter.config.Arguments; import org.apache.jmeter.config.ConfigElement; import org.apache.jmeter.services.FileServer; import org.apache.jmeter.testelement.property.CollectionProperty; import org.apache.jmeter.testelement.property.TestElementProperty; import org.apache.jmeter.threads.AbstractThreadGroup; import org.apache.jmeter.util.JMeterUtils; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; public class ReportPlan extends AbstractTestElement implements Serializable, TestStateListener { private static final long serialVersionUID = 233L; private static final Logger log = LoggingManager.getLoggerForClass(); public static final String REPORT_PAGE = "ReportPlan.report_page"; public static final String USER_DEFINED_VARIABLES = "ReportPlan.user_defined_variables"; public static final String REPORT_COMMENTS = "ReportPlan.comments"; public static final String BASEDIR = "ReportPlan.basedir"; private transient List<AbstractThreadGroup> reportPages = new LinkedList<AbstractThreadGroup>(); private transient List<ConfigElement> configs = new LinkedList<ConfigElement>(); private static final List<String> itemsCanAdd = new LinkedList<String>(); //private static ReportPlan plan; // There's only 1 test plan, so can cache the mode here private static volatile boolean functionalMode = false; static { itemsCanAdd.add(JMeterUtils.getResString("report_page")); // $NON-NLS-1$ } public ReportPlan() { this(JMeterUtils.getResString("report_plan")); // $NON-NLS-1$ } public ReportPlan(String name) { setName(name); setProperty(new CollectionProperty(REPORT_PAGE, reportPages)); } public void setUserDefinedVariables(Arguments vars) { setProperty(new TestElementProperty(USER_DEFINED_VARIABLES, vars)); } public String getBasedir() { return getPropertyAsString(BASEDIR); } public void setBasedir(String b) { setProperty(BASEDIR, b); } public Map<String, String> getUserDefinedVariables() { Arguments args = getVariables(); return args.getArgumentsAsMap(); } private Arguments getVariables() { Arguments args = (Arguments) getProperty(USER_DEFINED_VARIABLES).getObjectValue(); if (args == null) { args = new Arguments(); setUserDefinedVariables(args); } return args; } /** * Gets the static copy of the functional mode * * @return mode */ public static boolean getFunctionalMode() { return functionalMode; } public void addParameter(String name, String value) { getVariables().addArgument(name, value); } // FIXME Wrong code that create different constructor for static field depending on caller // public static ReportPlan createReportPlan(String name) { // if (plan == null) { // if (name == null) { // plan = new ReportPlan(); // } else { // plan = new ReportPlan(name); // } // plan.setProperty(new StringProperty(TestElement.GUI_CLASS, "org.apache.jmeter.control.gui.ReportGui")); // } // return plan; // } @Override public void addTestElement(TestElement tg) { super.addTestElement(tg); if (tg instanceof AbstractThreadGroup && !isRunningVersion()) { addReportPage((AbstractThreadGroup) tg); } } public void addJMeterComponent(TestElement child) { if (child instanceof AbstractThreadGroup) { addReportPage((AbstractThreadGroup) child); } } /** * Gets the ThreadGroups attribute of the TestPlan object. * * @return the ThreadGroups value */ public Collection<AbstractThreadGroup> getReportPages() { return reportPages; } /** * Adds a feature to the ConfigElement attribute of the TestPlan object. * * @param c * the feature to be added to the ConfigElement attribute */ public void addConfigElement(ConfigElement c) { configs.add(c); } /** * Adds a feature to the AbstractThreadGroup attribute of the TestPlan object. * * @param group * the feature to be added to the AbstractThreadGroup attribute */ public void addReportPage(AbstractThreadGroup group) { reportPages.add(group); } /* * (non-Javadoc) * * @see org.apache.jmeter.testelement.TestStateListener#testEnded() */ @Override public void testEnded() { try { FileServer.getFileServer().closeFiles(); } catch (IOException e) { log.error("Problem closing files at end of test", e); } } /* * (non-Javadoc) * * @see org.apache.jmeter.testelement.TestStateListener#testEnded(java.lang.String) */ @Override public void testEnded(String host) { testEnded(); } /* * (non-Javadoc) * * @see org.apache.jmeter.testelement.TestStateListener#testStarted() */ @Override public void testStarted() { if (getBasedir() != null && getBasedir().length() > 0) { try { FileServer.getFileServer().setBasedir(FileServer.getFileServer().getBaseDir() + getBasedir()); } catch (IllegalStateException e) { log.error("Failed to set file server base dir with " + getBasedir(), e); } } } /* * (non-Javadoc) * * @see org.apache.jmeter.testelement.TestStateListener#testStarted(java.lang.String) */ @Override public void testStarted(String host) { testStarted(); } protected Object readResolve(){ reportPages = new LinkedList<AbstractThreadGroup>(); configs = new LinkedList<ConfigElement>(); return this; } }
src/reports/org/apache/jmeter/testelement/ReportPlan.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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.apache.jmeter.testelement; import java.io.IOException; import java.io.Serializable; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.jmeter.config.Arguments; import org.apache.jmeter.config.ConfigElement; import org.apache.jmeter.services.FileServer; import org.apache.jmeter.testelement.property.CollectionProperty; import org.apache.jmeter.testelement.property.TestElementProperty; import org.apache.jmeter.threads.AbstractThreadGroup; import org.apache.jmeter.util.JMeterUtils; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; public class ReportPlan extends AbstractTestElement implements Serializable, TestStateListener { private static final long serialVersionUID = 233L; private static final Logger log = LoggingManager.getLoggerForClass(); public static final String REPORT_PAGE = "ReportPlan.report_page"; public static final String USER_DEFINED_VARIABLES = "ReportPlan.user_defined_variables"; public static final String REPORT_COMMENTS = "ReportPlan.comments"; public static final String BASEDIR = "ReportPlan.basedir"; private transient List<AbstractThreadGroup> reportPages = new LinkedList<AbstractThreadGroup>(); private transient List<ConfigElement> configs = new LinkedList<ConfigElement>(); private static final List<String> itemsCanAdd = new LinkedList<String>(); //private static ReportPlan plan; // There's only 1 test plan, so can cache the mode here private static volatile boolean functionalMode = false; static { itemsCanAdd.add(JMeterUtils.getResString("report_page")); // $NON-NLS-1$ } public ReportPlan() { this(JMeterUtils.getResString("report_plan")); // $NON-NLS-1$ } public ReportPlan(String name) { setName(name); setProperty(new CollectionProperty(REPORT_PAGE, reportPages)); } public void setUserDefinedVariables(Arguments vars) { setProperty(new TestElementProperty(USER_DEFINED_VARIABLES, vars)); } public String getBasedir() { return getPropertyAsString(BASEDIR); } public void setBasedir(String b) { setProperty(BASEDIR, b); } public Map<String, String> getUserDefinedVariables() { Arguments args = getVariables(); return args.getArgumentsAsMap(); } private Arguments getVariables() { Arguments args = (Arguments) getProperty(USER_DEFINED_VARIABLES).getObjectValue(); if (args == null) { args = new Arguments(); setUserDefinedVariables(args); } return args; } /** * Gets the static copy of the functional mode * * @return mode */ public static boolean getFunctionalMode() { return functionalMode; } public void addParameter(String name, String value) { getVariables().addArgument(name, value); } // FIXME Wrong code that create different constructor for static field depending on caller // public static ReportPlan createReportPlan(String name) { // if (plan == null) { // if (name == null) { // plan = new ReportPlan(); // } else { // plan = new ReportPlan(name); // } // plan.setProperty(new StringProperty(TestElement.GUI_CLASS, "org.apache.jmeter.control.gui.ReportGui")); // } // return plan; // } @Override public void addTestElement(TestElement tg) { super.addTestElement(tg); if (tg instanceof AbstractThreadGroup && !isRunningVersion()) { addReportPage((AbstractThreadGroup) tg); } } public void addJMeterComponent(TestElement child) { if (child instanceof AbstractThreadGroup) { addReportPage((AbstractThreadGroup) child); } } /** * Gets the ThreadGroups attribute of the TestPlan object. * * @return the ThreadGroups value */ public Collection<AbstractThreadGroup> getReportPages() { return reportPages; } /** * Adds a feature to the ConfigElement attribute of the TestPlan object. * * @param c * the feature to be added to the ConfigElement attribute */ public void addConfigElement(ConfigElement c) { configs.add(c); } /** * Adds a feature to the AbstractThreadGroup attribute of the TestPlan object. * * @param group * the feature to be added to the AbstractThreadGroup attribute */ public void addReportPage(AbstractThreadGroup group) { reportPages.add(group); } /* * (non-Javadoc) * * @see org.apache.jmeter.testelement.TestStateListener#testEnded() */ @Override public void testEnded() { try { FileServer.getFileServer().closeFiles(); } catch (IOException e) { log.error("Problem closing files at end of test", e); } } /* * (non-Javadoc) * * @see org.apache.jmeter.testelement.TestStateListener#testEnded(java.lang.String) */ @Override public void testEnded(String host) { testEnded(); } /* * (non-Javadoc) * * @see org.apache.jmeter.testelement.TestStateListener#testStarted() */ @Override public void testStarted() { if (getBasedir() != null && getBasedir().length() > 0) { try { FileServer.getFileServer().setBasedir(FileServer.getFileServer().getBaseDir() + getBasedir()); } catch (IllegalStateException e) { log.error("Failed to set file server base dir with " + getBasedir(), e); } } } /* * (non-Javadoc) * * @see org.apache.jmeter.testelement.TestStateListener#testStarted(java.lang.String) */ @Override public void testStarted(String host) { testStarted(); } }
Bug 52265 - Code:Transient fields not set by deserialization Bugzilla Id: 52265 git-svn-id: 5ccfe34f605a6c2f9041ff2965ab60012c62539a@1442357 13f79535-47bb-0310-9956-ffa450edef68
src/reports/org/apache/jmeter/testelement/ReportPlan.java
Bug 52265 - Code:Transient fields not set by deserialization Bugzilla Id: 52265
<ide><path>rc/reports/org/apache/jmeter/testelement/ReportPlan.java <ide> public void testStarted(String host) { <ide> testStarted(); <ide> } <add> <add> protected Object readResolve(){ <add> reportPages = new LinkedList<AbstractThreadGroup>(); <add> configs = new LinkedList<ConfigElement>(); <add> return this; <add> } <ide> }
JavaScript
mit
c39d06f9834f5d4de5ccf0d498062754d1646b97
0
phetsims/chipper,phetsims/chipper,phetsims/chipper
// Copyright 2019, University of Colorado Boulder /** * Launch an instance of the simulation using puppeteer, gather the phet-io api of the simulation, see phetioEngine.getPhetioElementsBaseline * @author Michael Kauzmann (PhET Interactive Simulations) * @author Chris Klusendorf (PhET Interactive Simulations) * @author Sam Reid (PhET Interactive Simulations) */ 'use strict'; const puppeteer = require( 'puppeteer' ); const fs = require( 'fs' ); /** * @param {string} repo * @param {string} localTestingURL - the browser url to access the root of phet repos */ module.exports = async ( repo, localTestingURL ) => { return new Promise( async ( resolve, reject ) => { const phetioDirectory = 'js/phet-io'; const baselineFileName = `${phetioDirectory}/${repo}-phet-io-elements-baseline.js`; const overridesFileName = `${phetioDirectory}/${repo}-phet-io-elements-overrides.js`; const typesFileName = `${phetioDirectory}/${repo}-phet-io-types.js`; if ( !fs.existsSync( phetioDirectory ) ) { fs.mkdirSync( phetioDirectory ); } // empty the current baseline file so we know that a stale version is not left behind fs.writeFileSync( baselineFileName, '' ); // if there is already an overrides file, don't overwrite it with an empty one if ( !fs.existsSync( overridesFileName ) ) { fs.writeFileSync( overridesFileName, '/* eslint-disable */\nwindow.phet.phetio.phetioElementsOverrides = {};' ); } let receivedBaseline = false; let receivedTypes = false; const browser = await puppeteer.launch(); const page = await browser.newPage(); page.on( 'console', async msg => { if ( msg.text().indexOf( 'window.phet.phetio.phetioElementsBaseline' ) >= 0 ) { fs.writeFileSync( baselineFileName, msg.text() ); receivedBaseline = true; await resolved(); } else if ( msg.text().indexOf( 'window.phet.phetio.phetioTypes' ) >= 0 ) { fs.writeFileSync( typesFileName, msg.text() ); receivedTypes = true; await resolved(); } else if ( msg.type() === 'error' ) { console.error( msg.text() ); } } ); const resolved = async () => { if ( receivedBaseline && receivedTypes ) { await browser.close(); resolve(); } }; page.on( 'error', msg => reject( msg ) ); page.on( 'pageerror', msg => reject( msg ) ); try { await page.goto( `${localTestingURL}${repo}/${repo}_en.html?brand=phet-io&phetioStandalone&phetioPrintPhetioFiles` ); } catch( e ) { reject( e ); } } ); };
js/grunt/phet-io/generatePhetioAPIFiles.js
// Copyright 2019, University of Colorado Boulder /** * Launch an instance of the simulation using puppeteer, gather the phet-io api of the simulation, see phetioEngine.getPhetioElementsBaseline * @author Michael Kauzmann (PhET Interactive Simulations) * @author Chris Klusendorf (PhET Interactive Simulations) * @author Sam Reid (PhET Interactive Simulations) */ 'use strict'; const puppeteer = require( 'puppeteer' ); const fs = require( 'fs' ); /** * @param {string} repo * @param {string} localTestingURL - the browser url to access the root of phet repos */ module.exports = async ( repo, localTestingURL ) => { return new Promise( async ( resolve, reject ) => { const phetioDirectory = 'js/phet-io'; const baselineFileName = `${phetioDirectory}/${repo}-phet-io-elements-baseline.js`; const overridesFileName = `${phetioDirectory}/${repo}-phet-io-elements-overrides.js`; const typesFileName = `${phetioDirectory}/${repo}-phet-io-types.js`; if ( !fs.existsSync( phetioDirectory ) ) { fs.mkdirSync( phetioDirectory ); } // empty the current baseline file so we know that a stale version is not left behind fs.writeFileSync( baselineFileName, '' ); // if there is already an overrides file, don't overwrite it with an empty one if ( !fs.existsSync( overridesFileName ) ) { fs.writeFileSync( overridesFileName, '/* eslint-disable */\nwindow.phet.phetio.phetioElementsOverrides = {};' ); } let receivedBaseline = false; let receivedTypes = false; const browser = await puppeteer.launch(); const page = await browser.newPage(); page.on( 'console', async msg => { if ( msg.text().indexOf( 'window.phet.phetio.phetioElementsBaseline' ) >= 0 ) { fs.writeFileSync( baselineFileName, msg.text() ); receivedBaseline = true; await resolved(); } else if ( msg.text().indexOf( 'window.phet.phetio.phetioTypes' ) >= 0 ) { fs.writeFileSync( typesFileName, msg.text() ); receivedTypes = true; await resolved(); } else if ( msg.type() === 'error' ) { console.error( msg.text() ); } } ); const resolved = async () => { if ( receivedBaseline && receivedTypes ) { await browser.close(); resolve(); } }; page.on( 'error', msg => reject( msg ) ); page.on( 'pageerror', msg => reject( msg ) ); try { await page.goto( `${localTestingURL}${repo}/${repo}_en.html?brand=phet-io&phetioStandalone&ea&phetioPrintPhetioFiles` ); } catch( e ) { reject( e ); } } ); };
remove 'ea' for generating API files, phetsims/phet-io#1589
js/grunt/phet-io/generatePhetioAPIFiles.js
remove 'ea' for generating API files, phetsims/phet-io#1589
<ide><path>s/grunt/phet-io/generatePhetioAPIFiles.js <ide> page.on( 'pageerror', msg => reject( msg ) ); <ide> <ide> try { <del> await page.goto( `${localTestingURL}${repo}/${repo}_en.html?brand=phet-io&phetioStandalone&ea&phetioPrintPhetioFiles` ); <add> await page.goto( `${localTestingURL}${repo}/${repo}_en.html?brand=phet-io&phetioStandalone&phetioPrintPhetioFiles` ); <ide> } <ide> catch( e ) { <ide> reject( e );
Java
apache-2.0
f30ac86aa4b73be1d580f6a9396e0722a3eadc5e
0
BlakeDickie/java-template-launcher
/* * Copyright 2015 QHR Technologies. * * 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. */ package com.qhrtech.emr.launcher.docker; import com.qhrtech.emr.launcher.TemplateLauncherManager; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.async.ResultCallback; import com.github.dockerjava.api.command.EventsCmd; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.model.Container; import com.github.dockerjava.api.model.Event; import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.InternetProtocol; import com.github.dockerjava.api.model.Ports; import com.github.dockerjava.core.DockerClientBuilder; import com.github.dockerjava.core.DockerClientConfig; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * @author Blake Dickie */ public class DockerInstance { private final String hostname; private final int portNumber; private DockerClient client; public DockerInstance( String hostname, int portNumber, File dockerCerts ) { this.hostname = hostname; this.portNumber = portNumber; DockerClientConfig.DockerClientConfigBuilder confBuilder = DockerClientConfig.createDefaultConfigBuilder() .withUri( String.format( "https://%s:%d", hostname, portNumber ) ); if ( dockerCerts != null ) { confBuilder.withDockerCertPath( dockerCerts.getPath() ); } DockerClientConfig config = confBuilder.build(); client = DockerClientBuilder.getInstance( config ).build(); } public DockerInstance( String hostname, File dockerCerts ) { this( hostname, 2376, dockerCerts ); } public void startMonitoring() { EventsCmd eventsCmd = client.eventsCmd(); EventMonitor exec = eventsCmd.exec( new EventMonitor() ); TemplateLauncherManager.getInstance().reportDockerEvent(); } public void appendToState( DockerState state ) { List<Container> containers = client.listContainersCmd().exec(); for ( Container c : containers ) { InspectContainerResponse response = client.inspectContainerCmd( c.getId() ).exec(); DockerContainer container = new DockerContainer(); container.setContainerId( response.getId() ); container.setMachineHostname( hostname ); Map<String, String> environment = new HashMap<String, String>(); for ( String envString : response.getConfig().getEnv() ) { String[] parts = envString.split( "=", 2 ); environment.put( parts[0], parts[1] ); } container.setEnvironment( environment ); InspectContainerResponse.NetworkSettings networkSettings = response.getNetworkSettings(); container.setContainerIpAddress( networkSettings.getIpAddress() ); for ( Map.Entry<ExposedPort, Ports.Binding[]> entry : networkSettings.getPorts().getBindings().entrySet() ) { ExposedPort key = entry.getKey(); Ports.Binding[] value = entry.getValue(); if ( value == null || value.length == 0 ) { DockerPort p = new DockerPort(); p.setContainerPort( key.getPort() ); p.setUdp( key.getProtocol() == InternetProtocol.UDP ); container.addPort( p ); } else { for ( Ports.Binding binding : value ) { DockerPort p = new DockerPort(); p.setContainerPort( key.getPort() ); p.setUdp( key.getProtocol() == InternetProtocol.UDP ); p.setMachinePort( binding.getHostPort() ); container.addPort( p ); } } } state.addContainer( container ); } } private class EventMonitor implements ResultCallback<Event> { @Override public void onStart( Closeable closeable ) { } @Override public void onNext( Event object ) { TemplateLauncherManager.getInstance().reportDockerEvent(); } @Override public void onError( Throwable throwable ) { LoggerFactory.getLogger( getClass() ).warn( "Error monitoring for docker events.", throwable ); startMonitoring(); } @Override public void onComplete() { } @Override public void close() throws IOException { } } }
src/main/java/com/qhrtech/emr/launcher/docker/DockerInstance.java
/* * Copyright 2015 QHR Technologies. * * 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. */ package com.qhrtech.emr.launcher.docker; import com.qhrtech.emr.launcher.TemplateLauncherManager; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.async.ResultCallback; import com.github.dockerjava.api.command.EventsCmd; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.model.Container; import com.github.dockerjava.api.model.Event; import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.InternetProtocol; import com.github.dockerjava.api.model.Ports; import com.github.dockerjava.core.DockerClientBuilder; import com.github.dockerjava.core.DockerClientConfig; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * @author Blake Dickie */ public class DockerInstance { private final String hostname; private final int portNumber; private DockerClient client; public DockerInstance( String hostname, int portNumber, File dockerCerts ) { this.hostname = hostname; this.portNumber = portNumber; DockerClientConfig.DockerClientConfigBuilder confBuilder = DockerClientConfig.createDefaultConfigBuilder() .withUri( String.format( "https://%s:%d", hostname, portNumber ) ); if ( dockerCerts != null ) { confBuilder.withDockerCertPath( dockerCerts.getPath() ); } DockerClientConfig config = confBuilder.build(); client = DockerClientBuilder.getInstance( config ).build(); } public DockerInstance( String hostname, File dockerCerts ) { this( hostname, 2376, dockerCerts ); } public void startMonitoring() { EventsCmd eventsCmd = client.eventsCmd(); eventsCmd.exec( new EventMonitor() ); } public void appendToState( DockerState state ) { List<Container> containers = client.listContainersCmd().exec(); for ( Container c : containers ) { InspectContainerResponse response = client.inspectContainerCmd( c.getId() ).exec(); DockerContainer container = new DockerContainer(); container.setContainerId( response.getId() ); container.setMachineHostname( hostname ); Map<String, String> environment = new HashMap<String, String>(); for ( String envString : response.getConfig().getEnv() ) { String[] parts = envString.split( "=", 2 ); environment.put( parts[0], parts[1] ); } container.setEnvironment( environment ); InspectContainerResponse.NetworkSettings networkSettings = response.getNetworkSettings(); container.setContainerIpAddress( networkSettings.getIpAddress() ); for ( Map.Entry<ExposedPort, Ports.Binding[]> entry : networkSettings.getPorts().getBindings().entrySet() ) { ExposedPort key = entry.getKey(); Ports.Binding[] value = entry.getValue(); if ( value == null || value.length == 0 ) { DockerPort p = new DockerPort(); p.setContainerPort( key.getPort() ); p.setUdp( key.getProtocol() == InternetProtocol.UDP ); container.addPort( p ); } else { for ( Ports.Binding binding : value ) { DockerPort p = new DockerPort(); p.setContainerPort( key.getPort() ); p.setUdp( key.getProtocol() == InternetProtocol.UDP ); p.setMachinePort( binding.getHostPort() ); container.addPort( p ); } } } state.addContainer( container ); } } private class EventMonitor implements ResultCallback<Event> { @Override public void onStart( Closeable closeable ) { } @Override public void onNext( Event object ) { TemplateLauncherManager.getInstance().reportDockerEvent(); } @Override public void onError( Throwable throwable ) { LoggerFactory.getLogger( getClass() ).warn( "Error monitoring for docker events.", throwable ); } @Override public void onComplete() { } @Override public void close() throws IOException { } } }
EMRDI-10: Fixing monitoring after network errors.
src/main/java/com/qhrtech/emr/launcher/docker/DockerInstance.java
EMRDI-10: Fixing monitoring after network errors.
<ide><path>rc/main/java/com/qhrtech/emr/launcher/docker/DockerInstance.java <ide> <ide> public void startMonitoring() { <ide> EventsCmd eventsCmd = client.eventsCmd(); <del> eventsCmd.exec( new EventMonitor() ); <add> EventMonitor exec = eventsCmd.exec( new EventMonitor() ); <add> TemplateLauncherManager.getInstance().reportDockerEvent(); <ide> } <ide> <ide> public void appendToState( DockerState state ) { <ide> @Override <ide> public void onError( Throwable throwable ) { <ide> LoggerFactory.getLogger( getClass() ).warn( "Error monitoring for docker events.", throwable ); <add> <add> startMonitoring(); <ide> } <ide> <ide> @Override <ide> <ide> @Override <ide> public void close() throws IOException { <del> <ide> } <ide> <ide> }
Java
apache-2.0
3959fb183435e56c1167334031da8849a37f6896
0
enternoescape/opendct,enternoescape/opendct,enternoescape/opendct
/* * Copyright 2015 The OpenDCT Authors. 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. */ package opendct.tuning.upnp.config; import opendct.config.Config; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.fourthline.cling.DefaultUpnpServiceConfiguration; import org.fourthline.cling.transport.impl.CDATAGENAEventProcessorImpl; import org.fourthline.cling.transport.impl.NetworkAddressFactoryImpl; import org.fourthline.cling.transport.impl.SOAPActionProcessorImpl; import org.fourthline.cling.transport.spi.GENAEventProcessor; import org.fourthline.cling.transport.spi.NetworkAddressFactory; import org.fourthline.cling.transport.spi.SOAPActionProcessor; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Iterator; public class DCTDefaultUpnpServiceConfiguration { private static final Logger logger = LogManager.getLogger(DCTDefaultUpnpServiceConfiguration.class); // Extending this class will add a dependency for javax.enterprise.inject.Alternative // so this is the easier alternative. public static DefaultUpnpServiceConfiguration getDCTDefault() { final int listenPort = Config.getInteger("upnp.service.configuration.http_listen_port", 8501); final String excludeInterfaces[] = Config.getStringArray("upnp.service.configuration.ignore_interfaces_csv"); final InetAddress excludeLocalAddresses[] = Config.getInetAddressArray("upnp.service.configuration.ignore_local_ip_csv"); return new DefaultUpnpServiceConfiguration() { @Override public SOAPActionProcessor getSoapActionProcessor() { // Default. return new SOAPActionProcessorImpl(); } @Override public GENAEventProcessor getGenaEventProcessor() { // Modified to return the CDATA returned in the XML of DCT subscription events. return new CDATAGENAEventProcessorImpl(); } @Override public NetworkAddressFactory createNetworkAddressFactory() { return new NetworkAddressFactoryImpl(listenPort) { @Override public Iterator<NetworkInterface> getNetworkInterfaces() { Iterator<NetworkInterface> interfaces = super.getNetworkInterfaces(); return interfaces; } @Override protected boolean isUsableAddress(NetworkInterface networkInterface, InetAddress address) { if (!super.isUsableAddress(networkInterface, address)) { return false; } for (String excludeInterface : excludeInterfaces) { if (networkInterface.getName().toLowerCase().equals(excludeInterface.toLowerCase())) { logger.info("Excluding the interface '{}' with IP address {} from UPnP discovery because it matched {}.", networkInterface.getName(), address.getHostAddress(), excludeInterface); return false; } } for (InetAddress excludeLocalAddress : excludeLocalAddresses) { if (address.equals(excludeLocalAddress)) { logger.info("Excluding interface '{}' with IP address {} from UPnP discovery because it matched {}.", networkInterface.getName(), address.getHostAddress(), excludeLocalAddress); return false; } } logger.info("Using the interface '{}' with IP address {} for UPnP discovery.", networkInterface.getName(), address.getHostAddress()); return true; } }; } }; } }
src/main/java/opendct/tuning/upnp/config/DCTDefaultUpnpServiceConfiguration.java
/* * Copyright 2015 The OpenDCT Authors. 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. */ package opendct.tuning.upnp.config; import opendct.config.Config; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.fourthline.cling.DefaultUpnpServiceConfiguration; import org.fourthline.cling.transport.impl.CDATAGENAEventProcessorImpl; import org.fourthline.cling.transport.impl.NetworkAddressFactoryImpl; import org.fourthline.cling.transport.impl.SOAPActionProcessorImpl; import org.fourthline.cling.transport.spi.GENAEventProcessor; import org.fourthline.cling.transport.spi.NetworkAddressFactory; import org.fourthline.cling.transport.spi.SOAPActionProcessor; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Iterator; public class DCTDefaultUpnpServiceConfiguration { private static final Logger logger = LogManager.getLogger(DCTDefaultUpnpServiceConfiguration.class); // Extending this class will add a dependency for javax.enterprise.inject.Alternative // so this is the easier alternative. public static DefaultUpnpServiceConfiguration getDCTDefault() { final int listenPort = Config.getInteger("upnp.service.configuration.http_listen_port", 8501); final String excludeInterfaces[] = Config.getStringArray("upnp.service.configuration.ignore_interfaces_csv"); final InetAddress excludeLocalAddresses[] = Config.getInetAddressArray("upnp.service.configuration.ignore_local_ip_csv"); return new DefaultUpnpServiceConfiguration() { @Override public SOAPActionProcessor getSoapActionProcessor() { // Default. return new SOAPActionProcessorImpl(); } @Override public GENAEventProcessor getGenaEventProcessor() { // Modified to return the CDATA returned in the XML of DCT subscription events. return new CDATAGENAEventProcessorImpl(); } @Override public NetworkAddressFactory createNetworkAddressFactory() { return new NetworkAddressFactoryImpl(listenPort) { @Override public Iterator<NetworkInterface> getNetworkInterfaces() { Iterator<NetworkInterface> interfaces = super.getNetworkInterfaces(); return interfaces; } @Override protected boolean isUsableAddress(NetworkInterface networkInterface, InetAddress address) { if (!super.isUsableAddress(networkInterface, address)) { return false; } for (String excludeInterface : excludeInterfaces) { if (networkInterface.getName().toLowerCase().equals(excludeInterface.toLowerCase())) { logger.info("Excluding the interface '{}' with IP address {} from UPnP discovery because it matched {}.", networkInterface.getName(), address.getHostAddress(), excludeInterface); return false; } } for (InetAddress excludeLocalAddress : excludeLocalAddresses) { if (address.equals(excludeLocalAddress)) { logger.info("Excluding interface '{}' with IP address {} from UPnP discovery because it matched {}.", networkInterface.getName(), address.getHostAddress(), excludeLocalAddress); return false; } } logger.info("Using the interface '{}' with IP address {} for UPnP discovery.", networkInterface.getName(), address); return true; } }; } }; } }
Logging cleanup.
src/main/java/opendct/tuning/upnp/config/DCTDefaultUpnpServiceConfiguration.java
Logging cleanup.
<ide><path>rc/main/java/opendct/tuning/upnp/config/DCTDefaultUpnpServiceConfiguration.java <ide> } <ide> } <ide> <del> logger.info("Using the interface '{}' with IP address {} for UPnP discovery.", networkInterface.getName(), address); <add> logger.info("Using the interface '{}' with IP address {} for UPnP discovery.", networkInterface.getName(), address.getHostAddress()); <ide> <ide> return true; <ide> }
Java
bsd-3-clause
d7e6a4b1e7ea0eeceb2be6aa431e505642e41168
0
dednal/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,anirudhSK/chromium,littlstar/chromium.src,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,ltilve/chromium,ltilve/chromium,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,patrickm/chromium.src,M4sse/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,Chilledheart/chromium,jaruba/chromium.src,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,M4sse/chromium.src,M4sse/chromium.src,patrickm/chromium.src,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,Just-D/chromium-1,fujunwei/chromium-crosswalk,markYoungH/chromium.src,patrickm/chromium.src,littlstar/chromium.src,Just-D/chromium-1,anirudhSK/chromium,dushu1203/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,mogoweb/chromium-crosswalk,ltilve/chromium,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,anirudhSK/chromium,ltilve/chromium,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,ChromiumWebApps/chromium,markYoungH/chromium.src,dednal/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,jaruba/chromium.src,Chilledheart/chromium,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,markYoungH/chromium.src,ondra-novak/chromium.src,axinging/chromium-crosswalk,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,ltilve/chromium,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,dednal/chromium.src,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,Jonekee/chromium.src,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,anirudhSK/chromium,hujiajie/pa-chromium,M4sse/chromium.src,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,littlstar/chromium.src,jaruba/chromium.src,jaruba/chromium.src,hujiajie/pa-chromium,hujiajie/pa-chromium,ondra-novak/chromium.src,markYoungH/chromium.src,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,littlstar/chromium.src,fujunwei/chromium-crosswalk,Just-D/chromium-1,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,ChromiumWebApps/chromium,axinging/chromium-crosswalk,M4sse/chromium.src,Jonekee/chromium.src,littlstar/chromium.src,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,patrickm/chromium.src,jaruba/chromium.src,dushu1203/chromium.src,dednal/chromium.src,Fireblend/chromium-crosswalk,dushu1203/chromium.src,patrickm/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,anirudhSK/chromium,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,patrickm/chromium.src,jaruba/chromium.src,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,Jonekee/chromium.src,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,Just-D/chromium-1,hujiajie/pa-chromium,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk,ltilve/chromium,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,hujiajie/pa-chromium,Just-D/chromium-1,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,anirudhSK/chromium,dushu1203/chromium.src,chuan9/chromium-crosswalk,hujiajie/pa-chromium,hujiajie/pa-chromium,patrickm/chromium.src,M4sse/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,dednal/chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,chuan9/chromium-crosswalk,dednal/chromium.src,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,M4sse/chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,ltilve/chromium
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.content.browser; import android.test.FlakyTest; import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.MediumTest; import org.chromium.base.test.util.Feature; import org.chromium.content.common.CommandLine; /** * Test suite for phone number detection. */ public class PhoneNumberDetectionTest extends ContentDetectionTestBase { private static final String TELEPHONE_INTENT_PREFIX = "tel:"; private boolean isExpectedTelephoneIntent(String intentUrl, String expectedContent) { if (intentUrl == null) return false; final String expectedUrl = TELEPHONE_INTENT_PREFIX + urlForContent(expectedContent); return intentUrl.equals(expectedUrl); } /** * Starts the content shell activity with the provided test URL and setting the local country * to the one provided by its 2-letter ISO code. * @param testUrl Test url to load. * @param countryIso 2-letter ISO country code. If set to null only international numbers * can be assumed to be supported. */ private void startActivityWithTestUrlAndCountryIso(String testUrl, String countryIso) throws Throwable { final String[] cmdlineArgs = countryIso == null ? null : new String[] { "--" + CommandLine.NETWORK_COUNTRY_ISO + "=" + countryIso }; startActivityWithTestUrlAndCommandLineArgs(testUrl, cmdlineArgs); } /* @LargeTest */ @FlakyTest @Feature({"ContentDetection", "TabContents"}) public void testInternationalNumberIntents() throws Throwable { startActivityWithTestUrl("content/content_detection/phone_international.html"); assertWaitForPageScaleFactorMatch(1.0f); // US: +1 650-253-0000. String intentUrl = scrollAndTapExpectingIntent("US"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+16502530000")); // Australia: +61 2 9374 4000. intentUrl = scrollAndTapExpectingIntent("Australia"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+61293744000")); // China: +86-10-62503000. intentUrl = scrollAndTapExpectingIntent("China"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+861062503000")); // Hong Kong: +852-3923-5400. intentUrl = scrollAndTapExpectingIntent("Hong Kong"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+85239235400")); // India: +91-80-67218000. intentUrl = scrollAndTapExpectingIntent("India"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+918067218000")); // Japan: +81-3-6384-9000. intentUrl = scrollAndTapExpectingIntent("Japan"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+81363849000")); // Korea: +82-2-531-9000. intentUrl = scrollAndTapExpectingIntent("Korea"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+8225319000")); // Singapore: +65 6521-8000. intentUrl = scrollAndTapExpectingIntent("Singapore"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+6565218000")); // Taiwan: +886 2 8729 6000. intentUrl = scrollAndTapExpectingIntent("Taiwan"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+886287296000")); // Kenya: +254 20 360 1000. intentUrl = scrollAndTapExpectingIntent("Kenya"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+254203601000")); // France: +33 (0)1 42 68 53 00. intentUrl = scrollAndTapExpectingIntent("France"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+33142685300")); // Germany: +49 40-80-81-79-000. intentUrl = scrollAndTapExpectingIntent("Germany"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+4940808179000")); // Ireland: +353 (1) 436 1001. intentUrl = scrollAndTapExpectingIntent("Ireland"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+35314361001")); // Italy: +39 02-36618 300. intentUrl = scrollAndTapExpectingIntent("Italy"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+390236618300")); // Netherlands: +31 (0)20-5045-100. intentUrl = scrollAndTapExpectingIntent("Netherlands"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+31205045100")); // Norway: +47 22996288. intentUrl = scrollAndTapExpectingIntent("Norway"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+4722996288")); // Poland: +48 (12) 68 15 300. intentUrl = scrollAndTapExpectingIntent("Poland"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+48126815300")); // Russia: +7-495-644-1400. intentUrl = scrollAndTapExpectingIntent("Russia"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+74956441400")); // Spain: +34 91-748-6400. intentUrl = scrollAndTapExpectingIntent("Spain"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+34917486400")); // Switzerland: +41 44-668-1800. intentUrl = scrollAndTapExpectingIntent("Switzerland"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+41446681800")); // UK: +44 (0)20-7031-3000. intentUrl = scrollAndTapExpectingIntent("UK"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+442070313000")); // Canada: +1 514-670-8700. intentUrl = scrollAndTapExpectingIntent("Canada"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+15146708700")); // Argentina: +54-11-5530-3000. intentUrl = scrollAndTapExpectingIntent("Argentina"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+541155303000")); // Brazil: +55-31-2128-6800. intentUrl = scrollAndTapExpectingIntent("Brazil"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+553121286800")); // Mexico: +52 55-5342-8400. intentUrl = scrollAndTapExpectingIntent("Mexico"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+525553428400")); // Israel: +972-74-746-6245. intentUrl = scrollAndTapExpectingIntent("Israel"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+972747466245")); // UAE: +971 4 4509500. intentUrl = scrollAndTapExpectingIntent("UAE"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+97144509500")); } /* @MediumTest */ @FlakyTest @Feature({"ContentDetection", "TabContents"}) public void testLocalUSNumbers() throws Throwable { startActivityWithTestUrlAndCountryIso("content/content_detection/phone_local.html", "US"); assertWaitForPageScaleFactorMatch(1.0f); // US_1: 1-888-433-5788. String intentUrl = scrollAndTapExpectingIntent("US_1"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+18884335788")); // US_2: 703-293-6299. intentUrl = scrollAndTapExpectingIntent("US_2"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+17032936299")); // US_3: (202) 456-2121. intentUrl = scrollAndTapExpectingIntent("US_3"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+12024562121")); // International numbers should still work. intentUrl = scrollAndTapExpectingIntent("International"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+31205045100")); } /* @MediumTest */ @FlakyTest @Feature({"ContentDetection", "TabContents"}) public void testLocalUKNumbers() throws Throwable { startActivityWithTestUrlAndCountryIso("content/content_detection/phone_local.html", "GB"); assertWaitForPageScaleFactorMatch(1.0f); // GB_1: (0) 20 7323 8299. String intentUrl = scrollAndTapExpectingIntent("GB_1"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+442073238299")); // GB_2: 01227865330. intentUrl = scrollAndTapExpectingIntent("GB_2"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+441227865330")); // GB_3: 01963 824686. intentUrl = scrollAndTapExpectingIntent("GB_3"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+441963824686")); // International numbers should still work. intentUrl = scrollAndTapExpectingIntent("International"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+31205045100")); } /* @MediumTest */ @FlakyTest @Feature({"ContentDetection", "TabContents"}) public void testLocalFRNumbers() throws Throwable { startActivityWithTestUrlAndCountryIso("content/content_detection/phone_local.html", "FR"); assertWaitForPageScaleFactorMatch(1.0f); // FR_1: 01 40 20 50 50. String intentUrl = scrollAndTapExpectingIntent("FR_1"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+33140205050")); // FR_2: 0326475534. intentUrl = scrollAndTapExpectingIntent("FR_2"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+33326475534")); // FR_3: (0) 237 211 992. intentUrl = scrollAndTapExpectingIntent("FR_3"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+33237211992")); // International numbers should still work. intentUrl = scrollAndTapExpectingIntent("International"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+31205045100")); } }
content/public/android/javatests/src/org/chromium/content/browser/PhoneNumberDetectionTest.java
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.content.browser; import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.MediumTest; import org.chromium.base.test.util.Feature; import org.chromium.content.common.CommandLine; /** * Test suite for phone number detection. */ public class PhoneNumberDetectionTest extends ContentDetectionTestBase { private static final String TELEPHONE_INTENT_PREFIX = "tel:"; private boolean isExpectedTelephoneIntent(String intentUrl, String expectedContent) { if (intentUrl == null) return false; final String expectedUrl = TELEPHONE_INTENT_PREFIX + urlForContent(expectedContent); return intentUrl.equals(expectedUrl); } /** * Starts the content shell activity with the provided test URL and setting the local country * to the one provided by its 2-letter ISO code. * @param testUrl Test url to load. * @param countryIso 2-letter ISO country code. If set to null only international numbers * can be assumed to be supported. */ private void startActivityWithTestUrlAndCountryIso(String testUrl, String countryIso) throws Throwable { final String[] cmdlineArgs = countryIso == null ? null : new String[] { "--" + CommandLine.NETWORK_COUNTRY_ISO + "=" + countryIso }; startActivityWithTestUrlAndCommandLineArgs(testUrl, cmdlineArgs); } @LargeTest @Feature({"ContentDetection", "TabContents"}) public void testInternationalNumberIntents() throws Throwable { startActivityWithTestUrl("content/content_detection/phone_international.html"); assertWaitForPageScaleFactorMatch(1.0f); // US: +1 650-253-0000. String intentUrl = scrollAndTapExpectingIntent("US"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+16502530000")); // Australia: +61 2 9374 4000. intentUrl = scrollAndTapExpectingIntent("Australia"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+61293744000")); // China: +86-10-62503000. intentUrl = scrollAndTapExpectingIntent("China"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+861062503000")); // Hong Kong: +852-3923-5400. intentUrl = scrollAndTapExpectingIntent("Hong Kong"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+85239235400")); // India: +91-80-67218000. intentUrl = scrollAndTapExpectingIntent("India"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+918067218000")); // Japan: +81-3-6384-9000. intentUrl = scrollAndTapExpectingIntent("Japan"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+81363849000")); // Korea: +82-2-531-9000. intentUrl = scrollAndTapExpectingIntent("Korea"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+8225319000")); // Singapore: +65 6521-8000. intentUrl = scrollAndTapExpectingIntent("Singapore"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+6565218000")); // Taiwan: +886 2 8729 6000. intentUrl = scrollAndTapExpectingIntent("Taiwan"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+886287296000")); // Kenya: +254 20 360 1000. intentUrl = scrollAndTapExpectingIntent("Kenya"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+254203601000")); // France: +33 (0)1 42 68 53 00. intentUrl = scrollAndTapExpectingIntent("France"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+33142685300")); // Germany: +49 40-80-81-79-000. intentUrl = scrollAndTapExpectingIntent("Germany"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+4940808179000")); // Ireland: +353 (1) 436 1001. intentUrl = scrollAndTapExpectingIntent("Ireland"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+35314361001")); // Italy: +39 02-36618 300. intentUrl = scrollAndTapExpectingIntent("Italy"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+390236618300")); // Netherlands: +31 (0)20-5045-100. intentUrl = scrollAndTapExpectingIntent("Netherlands"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+31205045100")); // Norway: +47 22996288. intentUrl = scrollAndTapExpectingIntent("Norway"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+4722996288")); // Poland: +48 (12) 68 15 300. intentUrl = scrollAndTapExpectingIntent("Poland"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+48126815300")); // Russia: +7-495-644-1400. intentUrl = scrollAndTapExpectingIntent("Russia"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+74956441400")); // Spain: +34 91-748-6400. intentUrl = scrollAndTapExpectingIntent("Spain"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+34917486400")); // Switzerland: +41 44-668-1800. intentUrl = scrollAndTapExpectingIntent("Switzerland"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+41446681800")); // UK: +44 (0)20-7031-3000. intentUrl = scrollAndTapExpectingIntent("UK"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+442070313000")); // Canada: +1 514-670-8700. intentUrl = scrollAndTapExpectingIntent("Canada"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+15146708700")); // Argentina: +54-11-5530-3000. intentUrl = scrollAndTapExpectingIntent("Argentina"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+541155303000")); // Brazil: +55-31-2128-6800. intentUrl = scrollAndTapExpectingIntent("Brazil"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+553121286800")); // Mexico: +52 55-5342-8400. intentUrl = scrollAndTapExpectingIntent("Mexico"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+525553428400")); // Israel: +972-74-746-6245. intentUrl = scrollAndTapExpectingIntent("Israel"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+972747466245")); // UAE: +971 4 4509500. intentUrl = scrollAndTapExpectingIntent("UAE"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+97144509500")); } @MediumTest @Feature({"ContentDetection", "TabContents"}) public void testLocalUSNumbers() throws Throwable { startActivityWithTestUrlAndCountryIso("content/content_detection/phone_local.html", "US"); assertWaitForPageScaleFactorMatch(1.0f); // US_1: 1-888-433-5788. String intentUrl = scrollAndTapExpectingIntent("US_1"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+18884335788")); // US_2: 703-293-6299. intentUrl = scrollAndTapExpectingIntent("US_2"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+17032936299")); // US_3: (202) 456-2121. intentUrl = scrollAndTapExpectingIntent("US_3"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+12024562121")); // International numbers should still work. intentUrl = scrollAndTapExpectingIntent("International"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+31205045100")); } @MediumTest @Feature({"ContentDetection", "TabContents"}) public void testLocalUKNumbers() throws Throwable { startActivityWithTestUrlAndCountryIso("content/content_detection/phone_local.html", "GB"); assertWaitForPageScaleFactorMatch(1.0f); // GB_1: (0) 20 7323 8299. String intentUrl = scrollAndTapExpectingIntent("GB_1"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+442073238299")); // GB_2: 01227865330. intentUrl = scrollAndTapExpectingIntent("GB_2"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+441227865330")); // GB_3: 01963 824686. intentUrl = scrollAndTapExpectingIntent("GB_3"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+441963824686")); // International numbers should still work. intentUrl = scrollAndTapExpectingIntent("International"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+31205045100")); } @MediumTest @Feature({"ContentDetection", "TabContents"}) public void testLocalFRNumbers() throws Throwable { startActivityWithTestUrlAndCountryIso("content/content_detection/phone_local.html", "FR"); assertWaitForPageScaleFactorMatch(1.0f); // FR_1: 01 40 20 50 50. String intentUrl = scrollAndTapExpectingIntent("FR_1"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+33140205050")); // FR_2: 0326475534. intentUrl = scrollAndTapExpectingIntent("FR_2"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+33326475534")); // FR_3: (0) 237 211 992. intentUrl = scrollAndTapExpectingIntent("FR_3"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+33237211992")); // International numbers should still work. intentUrl = scrollAndTapExpectingIntent("International"); assertTrue(isExpectedTelephoneIntent(intentUrl, "+31205045100")); } }
Mark PhoneNumberDetectionTest as flaky BUG=231484 Review URL: https://codereview.chromium.org/14265011 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@194241 0039d316-1c4b-4281-b951-d872f2087c98
content/public/android/javatests/src/org/chromium/content/browser/PhoneNumberDetectionTest.java
Mark PhoneNumberDetectionTest as flaky
<ide><path>ontent/public/android/javatests/src/org/chromium/content/browser/PhoneNumberDetectionTest.java <ide> <ide> package org.chromium.content.browser; <ide> <add>import android.test.FlakyTest; <ide> import android.test.suitebuilder.annotation.LargeTest; <ide> import android.test.suitebuilder.annotation.MediumTest; <ide> <ide> startActivityWithTestUrlAndCommandLineArgs(testUrl, cmdlineArgs); <ide> } <ide> <del> @LargeTest <add> /* @LargeTest */ <add> @FlakyTest <ide> @Feature({"ContentDetection", "TabContents"}) <ide> public void testInternationalNumberIntents() throws Throwable { <ide> startActivityWithTestUrl("content/content_detection/phone_international.html"); <ide> assertTrue(isExpectedTelephoneIntent(intentUrl, "+97144509500")); <ide> } <ide> <del> @MediumTest <add> /* @MediumTest */ <add> @FlakyTest <ide> @Feature({"ContentDetection", "TabContents"}) <ide> public void testLocalUSNumbers() throws Throwable { <ide> startActivityWithTestUrlAndCountryIso("content/content_detection/phone_local.html", "US"); <ide> assertTrue(isExpectedTelephoneIntent(intentUrl, "+31205045100")); <ide> } <ide> <del> @MediumTest <add> /* @MediumTest */ <add> @FlakyTest <ide> @Feature({"ContentDetection", "TabContents"}) <ide> public void testLocalUKNumbers() throws Throwable { <ide> startActivityWithTestUrlAndCountryIso("content/content_detection/phone_local.html", "GB"); <ide> assertTrue(isExpectedTelephoneIntent(intentUrl, "+31205045100")); <ide> } <ide> <del> @MediumTest <add> /* @MediumTest */ <add> @FlakyTest <ide> @Feature({"ContentDetection", "TabContents"}) <ide> public void testLocalFRNumbers() throws Throwable { <ide> startActivityWithTestUrlAndCountryIso("content/content_detection/phone_local.html", "FR");
JavaScript
mit
5a755319f95a520fdf9e603451db16822f806416
0
sama2/Viridian-Pokemon-Showdown,Flareninja/Sora,Flareninja/Sora,Sora-Server/Sora,Raina4uberz/Light-server,Raina4uberz/Light-server,sama2/Viridian-Pokemon-Showdown,Sora-Server/Sora,Flareninja/Sora,Sora-Server/Sora
/** * Commands * Pokemon Showdown - https://pokemonshowdown.com/ * * These are commands. For instance, you can define the command 'whois' * here, then use it by typing /whois into Pokemon Showdown. * * A command can be in the form: * ip: 'whois', * This is called an alias: it makes it so /ip does the same thing as * /whois. * * But to actually define a command, it's a function: * * allowchallenges: function (target, room, user) { * user.blockChallenges = false; * this.sendReply("You are available for challenges from now on."); * } * * Commands are actually passed five parameters: * function (target, room, user, connection, cmd, message) * Most of the time, you only need the first three, though. * * target = the part of the message after the command * room = the room object the message was sent to * The room name is room.id * user = the user object that sent the message * The user's name is user.name * connection = the connection that the message was sent from * cmd = the name of the command * message = the entire message sent by the user * * If a user types in "/msg zarel, hello" * target = "zarel, hello" * cmd = "msg" * message = "/msg zarel, hello" * * Commands return the message the user should say. If they don't * return anything or return something falsy, the user won't say * anything. * * Commands have access to the following functions: * * this.sendReply(message) * Sends a message back to the room the user typed the command into. * * this.sendReplyBox(html) * Same as sendReply, but shows it in a box, and you can put HTML in * it. * * this.popupReply(message) * Shows a popup in the window the user typed the command into. * * this.add(message) * Adds a message to the room so that everyone can see it. * This is like this.sendReply, except everyone in the room gets it, * instead of just the user that typed the command. * * this.send(message) * Sends a message to the room so that everyone can see it. * This is like this.add, except it's not logged, and users who join * the room later won't see it in the log, and if it's a battle, it * won't show up in saved replays. * You USUALLY want to use this.add instead. * * this.logEntry(message) * Log a message to the room's log without sending it to anyone. This * is like this.add, except no one will see it. * * this.addModCommand(message) * Like this.add, but also logs the message to the moderator log * which can be seen with /modlog. * * this.logModCommand(message) * Like this.addModCommand, except users in the room won't see it. * * this.can(permission) * this.can(permission, targetUser) * Checks if the user has the permission to do something, or if a * targetUser is passed, check if the user has permission to do * it to that user. Will automatically give the user an "Access * denied" message if the user doesn't have permission: use * user.can() if you don't want that message. * * Should usually be near the top of the command, like: * if (!this.can('potd')) return false; * * this.canBroadcast() * Signifies that a message can be broadcast, as long as the user * has permission to. This will check to see if the user used * "!command" instead of "/command". If so, it will check to see * if the user has permission to broadcast (by default, voice+ can), * and return false if not. Otherwise, it will add the message to * the room, and turn on the flag this.broadcasting, so that * this.sendReply and this.sendReplyBox will broadcast to the room * instead of just the user that used the command. * * Should usually be near the top of the command, like: * if (!this.canBroadcast()) return false; * * this.canBroadcast(suppressMessage) * Functionally the same as this.canBroadcast(). However, it * will look as if the user had written the text suppressMessage. * * this.canTalk() * Checks to see if the user can speak in the room. Returns false * if the user can't speak (is muted, the room has modchat on, etc), * or true otherwise. * * Should usually be near the top of the command, like: * if (!this.canTalk()) return false; * * this.canTalk(message, room) * Checks to see if the user can say the message in the room. * If a room is not specified, it will default to the current one. * If it has a falsy value, the check won't be attached to any room. * In addition to running the checks from this.canTalk(), it also * checks to see if the message has any banned words, is too long, * or was just sent by the user. Returns the filtered message, or a * falsy value if the user can't speak. * * Should usually be near the top of the command, like: * target = this.canTalk(target); * if (!target) return false; * * this.parse(message) * Runs the message as if the user had typed it in. * * Mostly useful for giving help messages, like for commands that * require a target: * if (!target) return this.parse('/help msg'); * * After 10 levels of recursion (calling this.parse from a command * called by this.parse from a command called by this.parse etc) * we will assume it's a bug in your command and error out. * * this.targetUserOrSelf(target, exactName) * If target is blank, returns the user that sent the message. * Otherwise, returns the user with the username in target, or * a falsy value if no user with that username exists. * By default, this will track users across name changes. However, * if exactName is true, it will enforce exact matches. * * this.getLastIdOf(user) * Returns the last userid of an specified user. * * this.splitTarget(target, exactName) * Splits a target in the form "user, message" into its * constituent parts. Returns message, and sets this.targetUser to * the user, and this.targetUsername to the username. * By default, this will track users across name changes. However, * if exactName is true, it will enforce exact matches. * * Remember to check if this.targetUser exists before going further. * * Unless otherwise specified, these functions will return undefined, * so you can return this.sendReply or something to send a reply and * stop the command there. * * @license MIT license */ var commands = exports.commands = { ip: 'whois', rooms: 'whois', alt: 'whois', alts: 'whois', whois: function (target, room, user) { var targetUser = this.targetUserOrSelf(target, user.group === Config.groups.default.global); if (!targetUser) { return this.sendReply("User " + this.targetUsername + " not found."); } this.sendReply("User: " + targetUser.name); if (user.can('alts', targetUser)) { var alts = targetUser.getAlts(); var output = Object.keys(targetUser.prevNames).join(", "); if (output) this.sendReply("Previous names: " + output); for (var j = 0; j < alts.length; ++j) { var targetAlt = Users.get(alts[j]); if (!targetAlt.named && !targetAlt.connected) continue; if (Config.groups.bySymbol[targetAlt.group] && Config.groups.bySymbol[user.group] && Config.groups.bySymbol[targetAlt.group].rank > Config.groups.bySymbol[user.group].rank) continue; this.sendReply("Alt: " + targetAlt.name); output = Object.keys(targetAlt.prevNames).join(", "); if (output) this.sendReply("Previous names: " + output); } } if (Config.groups.bySymbol[targetUser.group] && Config.groups.bySymbol[targetUser.group].name) { this.sendReply("Group: " + Config.groups.bySymbol[targetUser.group].name + " (" + targetUser.group + ")"); } if (targetUser.isSysop) { this.sendReply("(Pok\xE9mon Showdown System Operator)"); } if (!targetUser.authenticated) { this.sendReply("(Unregistered)"); } if (!this.broadcasting && (user.can('ip', targetUser) || user === targetUser)) { var ips = Object.keys(targetUser.ips); this.sendReply("IP" + ((ips.length > 1) ? "s" : "") + ": " + ips.join(", ")); this.sendReply("Host: " + targetUser.latestHost); } var output = "In rooms: "; var first = true; for (var i in targetUser.roomCount) { if (i === 'global' || Rooms.get(i).isPrivate) continue; if (!first) output += " | "; first = false; output += '<a href="/' + i + '" room="' + i + '">' + i + '</a>'; } this.sendReply('|raw|' + output); }, ipsearch: function (target, room, user) { if (!this.can('rangeban')) return; var atLeastOne = false; this.sendReply("Users with IP " + target + ":"); for (var userid in Users.users) { var curUser = Users.users[userid]; if (curUser.latestIp === target) { this.sendReply((curUser.connected ? " + " : "-") + " " + curUser.name); atLeastOne = true; } } if (!atLeastOne) this.sendReply("No results found."); }, /********************************************************* * Shortcuts *********************************************************/ invite: function (target, room, user) { target = this.splitTarget(target); if (!this.targetUser) { return this.sendReply("User " + this.targetUsername + " not found."); } var roomid = (target || room.id); if (!Rooms.get(roomid)) { return this.sendReply("Room " + roomid + " not found."); } return this.parse('/msg ' + this.targetUsername + ', /invite ' + roomid); }, /********************************************************* * Informational commands *********************************************************/ pstats: 'data', stats: 'data', dex: 'data', pokedex: 'data', details: 'data', dt: 'data', data: function (target, room, user, connection, cmd) { if (!this.canBroadcast()) return; var buffer = ''; var targetId = toId(target); var newTargets = Tools.dataSearch(target); var showDetails = (cmd === 'dt' || cmd === 'details'); if (newTargets && newTargets.length) { for (var i = 0; i < newTargets.length; ++i) { if (newTargets[i].id !== targetId && !Tools.data.Aliases[targetId] && !i) { buffer = "No Pokemon, item, move, ability or nature named '" + target + "' was found. Showing the data of '" + newTargets[0].name + "' instead.\n"; } if (newTargets[i].searchType === 'nature') { buffer += "" + newTargets[i].name + " nature: "; if (newTargets[i].plus) { var statNames = {'atk': "Attack", 'def': "Defense", 'spa': "Special Attack", 'spd': "Special Defense", 'spe': "Speed"}; buffer += "+10% " + statNames[newTargets[i].plus] + ", -10% " + statNames[newTargets[i].minus] + "."; } else { buffer += "No effect."; } return this.sendReply(buffer); } else { buffer += '|c|~|/data-' + newTargets[i].searchType + ' ' + newTargets[i].name + '\n'; } } } else { return this.sendReply("No Pokemon, item, move, ability or nature named '" + target + "' was found. (Check your spelling?)"); } if (showDetails) { var details; if (newTargets[0].searchType === 'pokemon') { var pokemon = Tools.getTemplate(newTargets[0].name); var weighthit = 20; if (pokemon.weightkg >= 200) { weighthit = 120; } else if (pokemon.weightkg >= 100) { weighthit = 100; } else if (pokemon.weightkg >= 50) { weighthit = 80; } else if (pokemon.weightkg >= 25) { weighthit = 60; } else if (pokemon.weightkg >= 10) { weighthit = 40; } details = { "Dex#": pokemon.num, "Height": pokemon.heightm + " m", "Weight": pokemon.weightkg + " kg <em>(" + weighthit + " BP)</em>", "Dex Colour": pokemon.color, "Egg Group(s)": pokemon.eggGroups.join(", ") }; if (!pokemon.evos.length) { details["<font color=#585858>Does Not Evolve</font>"] = ""; } else { details["Evolution"] = pokemon.evos.map(function (evo) { evo = Tools.getTemplate(evo); return evo.name + " (" + evo.evoLevel + ")"; }).join(", "); } } else if (newTargets[0].searchType === 'move') { var move = Tools.getMove(newTargets[0].name); details = { "Priority": move.priority, }; if (move.secondary || move.secondaries) details["<font color=black>&#10003; Secondary Effect</font>"] = ""; if (move.isContact) details["<font color=black>&#10003; Contact</font>"] = ""; if (move.isSoundBased) details["<font color=black>&#10003; Sound</font>"] = ""; if (move.isBullet) details["<font color=black>&#10003; Bullet</font>"] = ""; if (move.isPulseMove) details["<font color=black>&#10003; Pulse</font>"] = ""; details["Target"] = { 'normal': "Adjacent Pokemon", 'self': "Self", 'adjacentAlly': "Single Ally", 'allAdjacentFoes': "Adjacent Foes", 'foeSide': "All Foes", 'allySide': "All Allies", 'allAdjacent': "All Adjacent Pokemon", 'any': "Any Pokemon", 'all': "All Pokemon" }[move.target] || "Unknown"; } else if (newTargets[0].searchType === 'item') { var item = Tools.getItem(newTargets[0].name); details = {}; if (item.fling) { details["Fling Base Power"] = item.fling.basePower; if (item.fling.status) details["Fling Effect"] = item.fling.status; if (item.fling.volatileStatus) details["Fling Effect"] = item.fling.volatileStatus; if (item.isBerry) details["Fling Effect"] = "Activates effect of berry on target."; if (item.id === 'whiteherb') details["Fling Effect"] = "Removes all negative stat levels on the target."; if (item.id === 'mentalherb') details["Fling Effect"] = "Removes the effects of infatuation, Taunt, Encore, Torment, Disable, and Cursed Body on the target."; } if (!item.fling) details["Fling"] = "This item cannot be used with Fling"; if (item.naturalGift) { details["Natural Gift Type"] = item.naturalGift.type; details["Natural Gift BP"] = item.naturalGift.basePower; } } else { details = {}; } buffer += '|raw|<font size="1">' + Object.keys(details).map(function (detail) { return '<font color=#585858>' + detail + (details[detail] !== '' ? ':</font> ' + details[detail] : '</font>'); }).join("&nbsp;|&ThickSpace;") + '</font>'; } this.sendReply(buffer); }, ds: 'dexsearch', dsearch: 'dexsearch', dexsearch: function (target, room, user) { if (!this.canBroadcast()) return; if (!target) return this.parse('/help dexsearch'); var targets = target.split(','); var searches = {}; var allTiers = {'uber':1, 'ou':1, 'uu':1, 'lc':1, 'cap':1, 'bl':1, 'bl2':1, 'ru':1, 'bl3':1, 'nu':1}; var allColours = {'green':1, 'red':1, 'blue':1, 'white':1, 'brown':1, 'yellow':1, 'purple':1, 'pink':1, 'gray':1, 'black':1}; var showAll = false; var megaSearch = null; var feSearch = null; // search for fully evolved pokemon only var output = 10; for (var i in targets) { var isNotSearch = false; target = targets[i].trim().toLowerCase(); if (target.slice(0, 1) === '!') { isNotSearch = true; target = target.slice(1); } var targetAbility = Tools.getAbility(targets[i]); if (targetAbility.exists) { if (!searches['ability']) searches['ability'] = {}; if (Object.count(searches['ability'], true) === 1 && !isNotSearch) return this.sendReplyBox("Specify only one ability."); if ((searches['ability'][targetAbility.name] && isNotSearch) || (searches['ability'][targetAbility.name] === false && !isNotSearch)) return this.sendReplyBox("A search cannot both exclude and include an ability."); searches['ability'][targetAbility.name] = !isNotSearch; continue; } if (target in allTiers) { if (!searches['tier']) searches['tier'] = {}; if ((searches['tier'][target] && isNotSearch) || (searches['tier'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a tier.'); searches['tier'][target] = !isNotSearch; continue; } if (target in allColours) { if (!searches['color']) searches['color'] = {}; if ((searches['color'][target] && isNotSearch) || (searches['color'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a color.'); searches['color'][target] = !isNotSearch; continue; } var targetInt = parseInt(target); if (0 < targetInt && targetInt < 7) { if (!searches['gen']) searches['gen'] = {}; if ((searches['gen'][target] && isNotSearch) || (searches['gen'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a generation.'); searches['gen'][target] = !isNotSearch; continue; } if (target === 'all') { if (this.broadcasting) { return this.sendReplyBox("A search with the parameter 'all' cannot be broadcast."); } showAll = true; continue; } if (target === 'megas' || target === 'mega') { if ((megaSearch && isNotSearch) || (megaSearch === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include Mega Evolutions.'); megaSearch = !isNotSearch; continue; } if (target === 'fe' || target === 'fullyevolved' || target === 'nfe' || target === 'notfullyevolved') { if (target === 'nfe' || target === 'notfullyevolved') isNotSearch = !isNotSearch; if ((feSearch && isNotSearch) || (feSearch === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include fully evolved Pokémon.'); feSearch = !isNotSearch; continue; } var targetMove = Tools.getMove(target); if (targetMove.exists) { if (!searches['moves']) searches['moves'] = {}; if (Object.count(searches['moves'], true) === 4 && !isNotSearch) return this.sendReplyBox("Specify a maximum of 4 moves."); if ((searches['moves'][targetMove.name] && isNotSearch) || (searches['moves'][targetMove.name] === false && !isNotSearch)) return this.sendReplyBox("A search cannot both exclude and include a move."); searches['moves'][targetMove.name] = !isNotSearch; continue; } if (target.indexOf(' type') > -1) { target = target.charAt(0).toUpperCase() + target.slice(1, target.indexOf(' type')); if (target in Tools.data.TypeChart) { if (!searches['types']) searches['types'] = {}; if (Object.count(searches['types'], true) === 2 && !isNotSearch) return this.sendReplyBox("Specify a maximum of two types."); if ((searches['types'][target] && isNotSearch) || (searches['types'][target] === false && !isNotSearch)) return this.sendReplyBox("A search cannot both exclude and include a type."); searches['types'][target] = !isNotSearch; continue; } } return this.sendReplyBox("'" + Tools.escapeHTML(target) + "' could not be found in any of the search categories."); } if (showAll && Object.size(searches) === 0 && megaSearch === null && feSearch === null) return this.sendReplyBox("No search parameters other than 'all' were found. Try '/help dexsearch' for more information on this command."); var dex = {}; for (var pokemon in Tools.data.Pokedex) { var template = Tools.getTemplate(pokemon); var megaSearchResult = (megaSearch === null || (megaSearch === true && template.isMega) || (megaSearch === false && !template.isMega)); var feSearchResult = (feSearch === null || (feSearch === true && !template.evos.length) || (feSearch === false && template.evos.length)); if (template.tier !== 'Unreleased' && template.tier !== 'Illegal' && (template.tier !== 'CAP' || (searches['tier'] && searches['tier']['cap'])) && megaSearchResult && feSearchResult) { dex[pokemon] = template; } } for (var search in {'moves':1, 'types':1, 'ability':1, 'tier':1, 'gen':1, 'color':1}) { if (!searches[search]) continue; switch (search) { case 'types': for (var mon in dex) { if (Object.count(searches[search], true) === 2) { if (!(searches[search][dex[mon].types[0]]) || !(searches[search][dex[mon].types[1]])) delete dex[mon]; } else { if (searches[search][dex[mon].types[0]] === false || searches[search][dex[mon].types[1]] === false || (Object.count(searches[search], true) > 0 && (!(searches[search][dex[mon].types[0]]) && !(searches[search][dex[mon].types[1]])))) delete dex[mon]; } } break; case 'tier': for (var mon in dex) { if ('lc' in searches[search]) { // some LC legal Pokemon are stored in other tiers (Ferroseed/Murkrow etc) // this checks for LC legality using the going criteria, instead of dex[mon].tier var isLC = (dex[mon].evos && dex[mon].evos.length > 0) && !dex[mon].prevo && Tools.data.Formats['lc'].banlist.indexOf(dex[mon].species) === -1; if ((searches[search]['lc'] && !isLC) || (!searches[search]['lc'] && isLC)) { delete dex[mon]; continue; } } if (searches[search][String(dex[mon][search]).toLowerCase()] === false) { delete dex[mon]; } else if (Object.count(searches[search], true) > 0 && !searches[search][String(dex[mon][search]).toLowerCase()]) delete dex[mon]; } break; case 'gen': case 'color': for (var mon in dex) { if (searches[search][String(dex[mon][search]).toLowerCase()] === false) { delete dex[mon]; } else if (Object.count(searches[search], true) > 0 && !searches[search][String(dex[mon][search]).toLowerCase()]) delete dex[mon]; } break; case 'ability': for (var mon in dex) { for (var ability in searches[search]) { var needsAbility = searches[search][ability]; var hasAbility = Object.count(dex[mon].abilities, ability) > 0; if (hasAbility !== needsAbility) { delete dex[mon]; break; } } } break; case 'moves': for (var mon in dex) { var template = Tools.getTemplate(dex[mon].id); if (!template.learnset) template = Tools.getTemplate(template.baseSpecies); if (!template.learnset) continue; for (var i in searches[search]) { var move = Tools.getMove(i); if (!move.exists) return this.sendReplyBox("'" + move + "' is not a known move."); var prevoTemp = Tools.getTemplate(template.id); while (prevoTemp.prevo && prevoTemp.learnset && !(prevoTemp.learnset[move.id])) { prevoTemp = Tools.getTemplate(prevoTemp.prevo); } var canLearn = (prevoTemp.learnset.sketch && !(move.id in {'chatter':1, 'struggle':1, 'magikarpsrevenge':1})) || prevoTemp.learnset[move.id]; if ((!canLearn && searches[search][i]) || (searches[search][i] === false && canLearn)) delete dex[mon]; } } break; default: return this.sendReplyBox("Something broke! PM TalkTakesTime here or on the Smogon forums with the command you tried."); } } var results = Object.keys(dex).map(function (speciesid) {return dex[speciesid].species;}); results = results.filter(function (species) { var template = Tools.getTemplate(species); return !(species !== template.baseSpecies && results.indexOf(template.baseSpecies) > -1); }); var resultsStr = ""; if (results.length > 0) { if (showAll || results.length <= output) { results.sort(); resultsStr = results.join(", "); } else { results.randomize(); resultsStr = results.slice(0, 10).join(", ") + ", and " + string(results.length - output) + " more. Redo the search with 'all' as a search parameter to show all results."; } } else { resultsStr = "No Pokémon found."; } return this.sendReplyBox(resultsStr); }, learnset: 'learn', learnall: 'learn', learn5: 'learn', g6learn: 'learn', learn: function (target, room, user, connection, cmd) { if (!target) return this.parse('/help learn'); if (!this.canBroadcast()) return; var lsetData = {set:{}}; var targets = target.split(','); var template = Tools.getTemplate(targets[0]); var move = {}; var problem; var all = (cmd === 'learnall'); if (cmd === 'learn5') lsetData.set.level = 5; if (cmd === 'g6learn') lsetData.format = {noPokebank: true}; if (!template.exists) { return this.sendReply("Pokemon '" + template.id + "' not found."); } if (targets.length < 2) { return this.sendReply("You must specify at least one move."); } for (var i = 1, len = targets.length; i < len; ++i) { move = Tools.getMove(targets[i]); if (!move.exists) { return this.sendReply("Move '" + move.id + "' not found."); } problem = TeamValidator.checkLearnsetSync(null, move, template, lsetData); if (problem) break; } var buffer = template.name + (problem ? " <span class=\"message-learn-cannotlearn\">can't</span> learn " : " <span class=\"message-learn-canlearn\">can</span> learn ") + (targets.length > 2 ? "these moves" : move.name); if (!problem) { var sourceNames = {E:"egg", S:"event", D:"dream world"}; if (lsetData.sources || lsetData.sourcesBefore) buffer += " only when obtained from:<ul class=\"message-learn-list\">"; if (lsetData.sources) { var sources = lsetData.sources.sort(); var prevSource; var prevSourceType; var prevSourceCount = 0; for (var i = 0, len = sources.length; i < len; ++i) { var source = sources[i]; if (source.substr(0, 2) === prevSourceType) { if (prevSourceCount < 0) { buffer += ": " + source.substr(2); } else if (all || prevSourceCount < 3) { buffer += ", " + source.substr(2); } else if (prevSourceCount === 3) { buffer += ", ..."; } ++prevSourceCount; continue; } prevSourceType = source.substr(0, 2); prevSourceCount = source.substr(2) ? 0 : -1; buffer += "<li>gen " + source.substr(0, 1) + " " + sourceNames[source.substr(1, 1)]; if (prevSourceType === '5E' && template.maleOnlyHidden) buffer += " (cannot have hidden ability)"; if (source.substr(2)) buffer += ": " + source.substr(2); } } if (lsetData.sourcesBefore) buffer += "<li>any generation before " + (lsetData.sourcesBefore + 1); buffer += "</ul>"; } this.sendReplyBox(buffer); }, weak: 'weakness', resist: 'weakness', weakness: function (target, room, user){ if (!this.canBroadcast()) return; var targets = target.split(/[ ,\/]/); var pokemon = Tools.getTemplate(target); var type1 = Tools.getType(targets[0]); var type2 = Tools.getType(targets[1]); if (pokemon.exists) { target = pokemon.species; } else if (type1.exists && type2.exists) { pokemon = {types: [type1.id, type2.id]}; target = type1.id + "/" + type2.id; } else if (type1.exists) { pokemon = {types: [type1.id]}; target = type1.id; } else { return this.sendReplyBox("" + Tools.escapeHTML(target) + " isn't a recognized type or pokemon."); } var weaknesses = []; var resistances = []; var immunities = []; Object.keys(Tools.data.TypeChart).forEach(function (type) { var notImmune = Tools.getImmunity(type, pokemon); if (notImmune) { var typeMod = Tools.getEffectiveness(type, pokemon); switch (typeMod) { case 1: weaknesses.push(type); break; case 2: weaknesses.push("<b>" + type + "</b>"); break; case -1: resistances.push(type); break; case -2: resistances.push("<b>" + type + "</b>"); break; } } else { immunities.push(type); } }); var buffer = []; buffer.push(pokemon.exists ? "" + target + ' (ignoring abilities):' : '' + target + ':'); buffer.push('<span class=\"message-effect-weak\">Weaknesses</span>: ' + (weaknesses.join(', ') || 'None')); buffer.push('<span class=\"message-effect-resist\">Resistances</span>: ' + (resistances.join(', ') || 'None')); buffer.push('<span class=\"message-effect-immune\">Immunities</span>: ' + (immunities.join(', ') || 'None')); this.sendReplyBox(buffer.join('<br>')); }, eff: 'effectiveness', type: 'effectiveness', matchup: 'effectiveness', effectiveness: function (target, room, user) { var targets = target.split(/[,/]/).slice(0, 2); if (targets.length !== 2) return this.sendReply("Attacker and defender must be separated with a comma."); var searchMethods = {'getType':1, 'getMove':1, 'getTemplate':1}; var sourceMethods = {'getType':1, 'getMove':1}; var targetMethods = {'getType':1, 'getTemplate':1}; var source; var defender; var foundData; var atkName; var defName; for (var i = 0; i < 2; ++i) { var method; for (method in searchMethods) { foundData = Tools[method](targets[i]); if (foundData.exists) break; } if (!foundData.exists) return this.parse('/help effectiveness'); if (!source && method in sourceMethods) { if (foundData.type) { source = foundData; atkName = foundData.name; } else { source = foundData.id; atkName = foundData.id; } searchMethods = targetMethods; } else if (!defender && method in targetMethods) { if (foundData.types) { defender = foundData; defName = foundData.species + " (not counting abilities)"; } else { defender = {types: [foundData.id]}; defName = foundData.id; } searchMethods = sourceMethods; } } if (!this.canBroadcast()) return; var factor = 0; if (Tools.getImmunity(source.type || source, defender)) { if (source.effectType !== 'Move' || source.basePower || source.basePowerCallback) { factor = Math.pow(2, Tools.getEffectiveness(source, defender)); } else { factor = 1; } } this.sendReplyBox("" + atkName + " is " + factor + "x effective against " + defName + "."); }, uptime: function (target, room, user) { if (!this.canBroadcast()) return; var uptime = process.uptime(); var uptimeText; if (uptime > 24 * 60 * 60) { var uptimeDays = Math.floor(uptime / (24 * 60 * 60)); uptimeText = uptimeDays + " " + (uptimeDays === 1 ? "day" : "days"); var uptimeHours = Math.floor(uptime / (60 * 60)) - uptimeDays * 24; if (uptimeHours) uptimeText += ", " + uptimeHours + " " + (uptimeHours === 1 ? "hour" : "hours"); } else { uptimeText = uptime.seconds().duration(); } this.sendReplyBox("Uptime: <b>" + uptimeText + "</b>"); }, groups: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox(Config.groups.byRank.reduce(function (info, group) { if (!Config.groups.bySymbol[group].name || !Config.groups.bySymbol[group].description) return info; return info + (info ? "<br />" : "") + Tools.escapeHTML(group) + " <strong>" + Tools.escapeHTML(Config.groups.bySymbol[group].name) + "</strong> - " + Tools.escapeHTML(Config.groups.bySymbol[group].description); }, "")); }, git: 'opensource', opensource: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "Pokemon Showdown is open source:<br />" + "- Language: JavaScript (Node.js)<br />" + "- <a href=\"https://github.com/Zarel/Pokemon-Showdown/commits/master\">What's new?</a><br />" + "- <a href=\"https://github.com/Zarel/Pokemon-Showdown\">Server source code</a><br />" + "- <a href=\"https://github.com/Zarel/Pokemon-Showdown-Client\">Client source code</a>" ); }, staff: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox("<a href=\"https://www.smogon.com/sim/staff_list\">Pokemon Showdown Staff List</a>"); }, avatars: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('You can <button name="avatars">change your avatar</button> by clicking on it in the <button name="openOptions"><i class="icon-cog"></i> Options</button> menu in the upper right. Custom avatars are only obtainable by staff.'); }, showtan: function (target, room, user) { if (room.id !== 'showderp') return this.sendReply("The command '/showtan' was unrecognized. To send a message starting with '/showtan', type '//showtan'."); if (!this.can('showtan', room)) return; target = this.splitTarget(target); if (!this.targetUser) return this.sendReply('user not found'); if (!room.users[this.targetUser.userid]) return this.sendReply('not a showderper'); this.targetUser.avatar = '#showtan'; room.add(user.name+' applied showtan to affected area of '+this.targetUser.name); }, introduction: 'intro', intro: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "New to competitive pokemon?<br />" + "- <a href=\"https://www.smogon.com/sim/ps_guide\">Beginner's Guide to Pokémon Showdown</a><br />" + "- <a href=\"https://www.smogon.com/dp/articles/intro_comp_pokemon\">An introduction to competitive Pokémon</a><br />" + "- <a href=\"https://www.smogon.com/bw/articles/bw_tiers\">What do 'OU', 'UU', etc mean?</a><br />" + "- <a href=\"https://www.smogon.com/xyhub/tiers\">What are the rules for each format? What is 'Sleep Clause'?</a>" ); }, mentoring: 'smogintro', smogonintro: 'smogintro', smogintro: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "Welcome to Smogon's official simulator! Here are some useful links to <a href=\"https://www.smogon.com/mentorship/\">Smogon\'s Mentorship Program</a> to help you get integrated into the community:<br />" + "- <a href=\"https://www.smogon.com/mentorship/primer\">Smogon Primer: A brief introduction to Smogon's subcommunities</a><br />" + "- <a href=\"https://www.smogon.com/mentorship/introductions\">Introduce yourself to Smogon!</a><br />" + "- <a href=\"https://www.smogon.com/mentorship/profiles\">Profiles of current Smogon Mentors</a><br />" + "- <a href=\"http://mibbit.com/#[email protected]\">#mentor: the Smogon Mentorship IRC channel</a>" ); }, calculator: 'calc', calc: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "Pokemon Showdown! damage calculator. (Courtesy of Honko)<br />" + "- <a href=\"https://pokemonshowdown.com/damagecalc/\">Damage Calculator</a>" ); }, cap: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "An introduction to the Create-A-Pokemon project:<br />" + "- <a href=\"https://www.smogon.com/cap/\">CAP project website and description</a><br />" + "- <a href=\"https://www.smogon.com/forums/showthread.php?t=48782\">What Pokemon have been made?</a><br />" + "- <a href=\"https://www.smogon.com/forums/showthread.php?t=3464513\">Talk about the metagame here</a><br />" + "- <a href=\"https://www.smogon.com/forums/showthread.php?t=3466826\">Practice BW CAP teams</a>" ); }, gennext: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "NEXT (also called Gen-NEXT) is a mod that makes changes to the game:<br />" + "- <a href=\"https://github.com/Zarel/Pokemon-Showdown/blob/master/mods/gennext/README.md\">README: overview of NEXT</a><br />" + "Example replays:<br />" + "- <a href=\"https://replay.pokemonshowdown.com/gennextou-120689854\">Zergo vs Mr Weegle Snarf</a><br />" + "- <a href=\"https://replay.pokemonshowdown.com/gennextou-130756055\">NickMP vs Khalogie</a>" ); }, om: 'othermetas', othermetas: function (target, room, user) { if (!this.canBroadcast()) return; target = toId(target); var buffer = ""; var matched = false; if (!target || target === 'all') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/forums/206/\">Other Metagames Forum</a><br />"; if (target !== 'all') { buffer += "- <a href=\"https://www.smogon.com/forums/threads/3505031/\">Other Metagames Index</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3507466/\">Sample teams for entering Other Metagames</a><br />"; } } if (target === 'all' || target === 'omofthemonth' || target === 'omotm' || target === 'month') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3481155/\">OM of the Month</a><br />"; } if (target === 'all' || target === 'pokemonthrowback' || target === 'throwback') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3510401/\">Pokémon Throwback</a><br />"; } if (target === 'all' || target === 'balancedhackmons' || target === 'bh') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3489849/\">Balanced Hackmons</a><br />"; if (target !== 'all') { buffer += "- <a href=\"https://www.smogon.com/forums/threads/3499973/\">Balanced Hackmons Mentoring Program</a><br />"; } } if (target === 'all' || target === '1v1') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3496773/\">1v1</a><br />"; } if (target === 'all' || target === 'oumonotype' || target === 'monotype') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3493087/\">OU Monotype</a><br />"; if (target !== 'all') { buffer += "- <a href=\"https://www.smogon.com/forums/threads/3507565/\">OU Monotype Viability Rankings</a><br />"; } } if (target === 'all' || target === 'tiershift' || target === 'ts') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3508369/\">Tier Shift</a><br />"; } if (target === 'all' || target === 'almostanyability' || target === 'aaa') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3495737/\">Almost Any Ability</a><br />"; if (target !== 'all') { buffer += "- <a href=\"https://www.smogon.com/forums/threads/3508794/\">Almost Any Ability Viability Rankings</a><br />"; } } if (target === 'all' || target === 'stabmons') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3493081/\">STABmons</a><br />"; if (target !== 'all') { buffer += "- <a href=\"https://www.smogon.com/forums/threads/3512215/\">STABmons Viability Rankings</a><br />"; } } if (target === 'all' || target === 'skybattles' || target === 'skybattle') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3493601/\">Sky Battles</a><br />"; } if (target === 'all' || target === 'inversebattle' || target === 'inverse') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3492433/\">Inverse Battle</a><br />"; } if (target === 'all' || target === 'hackmons' || target === 'ph') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3500418/\">Hackmons</a><br />"; } if (target === 'all' || target === 'smogontriples' || target === 'triples') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3511522/\">Smogon Triples</a><br />"; } if (target === 'all' || target === 'alphabetcup') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3498167/\">Alphabet Cup</a><br />"; } if (target === 'all' || target === 'averagemons') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3495527/\">Averagemons</a><br />"; } if (target === 'all' || target === 'middlecup' || target === 'mc') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3494887/\">Middle Cup</a><br />"; } if (target === 'all' || target === 'glitchmons') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3467120/\">Glitchmons</a><br />"; } if (!matched) { return this.sendReply("The Other Metas entry '" + target + "' was not found. Try /othermetas or /om for general help."); } this.sendReplyBox(buffer); }, /*formats: 'formathelp', formatshelp: 'formathelp', formathelp: function (target, room, user) { if (!this.canBroadcast()) return; if (this.broadcasting && (room.id === 'lobby' || room.battle)) return this.sendReply("This command is too spammy to broadcast in lobby/battles"); var buf = []; var showAll = (target === 'all'); for (var id in Tools.data.Formats) { var format = Tools.data.Formats[id]; if (!format) continue; if (format.effectType !== 'Format') continue; if (!format.challengeShow) continue; if (!showAll && !format.searchShow) continue; buf.push({ name: format.name, gameType: format.gameType || 'singles', mod: format.mod, searchShow: format.searchShow, desc: format.desc || 'No description.' }); } this.sendReplyBox( "Available Formats: (<strong>Bold</strong> formats are on ladder.)<br />" + buf.map(function (data) { var str = ""; // Bold = Ladderable. str += (data.searchShow ? "<strong>" + data.name + "</strong>" : data.name) + ": "; str += "(" + (!data.mod || data.mod === 'base' ? "" : data.mod + " ") + data.gameType + " format) "; str += data.desc; return str; }).join("<br />") ); },*/ roomhelp: function (target, room, user) { if (room.id === 'lobby' || room.battle) return this.sendReply("This command is too spammy for lobby/battles."); if (!this.canBroadcast()) return; this.sendReplyBox( "Room drivers (%) can use:<br />" + "- /warn OR /k <em>username</em>: warn a user and show the Pokemon Showdown rules<br />" + "- /mute OR /m <em>username</em>: 7 minute mute<br />" + "- /hourmute OR /hm <em>username</em>: 60 minute mute<br />" + "- /unmute <em>username</em>: unmute<br />" + "- /announce OR /wall <em>message</em>: make an announcement<br />" + "- /modlog <em>username</em>: search the moderator log of the room<br />" + "- /modnote <em>note</em>: adds a moderator note that can be read through modlog<br />" + "<br />" + "Room moderators (@) can also use:<br />" + "- /roomban OR /rb <em>username</em>: bans user from the room<br />" + "- /roomunban <em>username</em>: unbans user from the room<br />" + "- /roomvoice <em>username</em>: appoint a room voice<br />" + "- /roomdevoice <em>username</em>: remove a room voice<br />" + "- /modchat <em>[off/autoconfirmed/+]</em>: set modchat level<br />" + "<br />" + "Room owners (#) can also use:<br />" + "- /roomintro <em>intro</em>: sets the room introduction that will be displayed for all users joining the room<br />" + "- /rules <em>rules link</em>: set the room rules link seen when using /rules<br />" + "- /roommod, /roomdriver <em>username</em>: appoint a room moderator/driver<br />" + "- /roomdemod, /roomdedriver <em>username</em>: remove a room moderator/driver<br />" + "- /modchat <em>[%/@/#]</em>: set modchat level<br />" + "- /declare <em>message</em>: make a large blue declaration to the room<br />" + "- !htmlbox <em>HTML code</em>: broadcasts a box of HTML code to the room<br />" + "- !showimage <em>[url], [width], [height]</em>: shows an image to the room<br />" + "</div>" ); }, restarthelp: function (target, room, user) { if (room.id === 'lobby' && !this.can('lockdown')) return false; if (!this.canBroadcast()) return; this.sendReplyBox( "The server is restarting. Things to know:<br />" + "- We wait a few minutes before restarting so people can finish up their battles<br />" + "- The restart itself will take around 0.6 seconds<br />" + "- Your ladder ranking and teams will not change<br />" + "- We are restarting to update Pokémon Showdown to a newer version" ); }, rule: 'rules', rules: function (target, room, user) { if (!target) { if (!this.canBroadcast()) return; this.sendReplyBox("Please follow the rules:<br />" + (room.rulesLink ? "- <a href=\"" + Tools.escapeHTML(room.rulesLink) + "\">" + Tools.escapeHTML(room.title) + " room rules</a><br />" : "") + "- <a href=\"https://pokemonshowdown.com/rules\">" + (room.rulesLink ? "Global rules" : "Rules") + "</a>"); return; } if (!this.can('declare', room)) return; if (target.length > 80) { return this.sendReply("Error: Room rules link is too long (must be under 80 characters). You can use a URL shortener to shorten the link."); } room.rulesLink = target.trim(); this.sendReply("(The room rules link is now: " + target + ")"); if (room.chatRoomData) { room.chatRoomData.rulesLink = room.rulesLink; Rooms.global.writeChatRoomData(); } }, faq: function (target, room, user) { if (!this.canBroadcast()) return; target = target.toLowerCase(); var buffer = ""; var matched = false; if (!target || target === 'all') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq\">Frequently Asked Questions</a><br />"; } if (target === 'all' || target === 'deviation') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#deviation\">Why did this user gain or lose so many points?</a><br />"; } if (target === 'all' || target === 'doubles' || target === 'triples' || target === 'rotation') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#doubles\">Can I play doubles/triples/rotation battles here?</a><br />"; } if (target === 'all' || target === 'randomcap') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#randomcap\">What is this fakemon and what is it doing in my random battle?</a><br />"; } if (target === 'all' || target === 'restarts') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#restarts\">Why is the server restarting?</a><br />"; } if (target === 'all' || target === 'staff') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/staff_faq\">Staff FAQ</a><br />"; } if (target === 'all' || target === 'autoconfirmed' || target === 'ac') { matched = true; buffer += "A user is autoconfirmed when they have won at least one rated battle and have been registered for a week or longer.<br />"; } if (!matched) { return this.sendReply("The FAQ entry '" + target + "' was not found. Try /faq for general help."); } this.sendReplyBox(buffer); }, banlists: 'tiers', tier: 'tiers', tiers: function (target, room, user) { if (!this.canBroadcast()) return; target = toId(target); var buffer = ""; var matched = false; if (!target || target === 'all') { matched = true; buffer += "- <a href=\"https://www.smogon.com/tiers/\">Smogon Tiers</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/tiering-faq.3498332/\">Tiering FAQ</a><br />"; buffer += "- <a href=\"https://www.smogon.com/xyhub/tiers\">The banlists for each tier</a><br />"; } if (target === 'all' || target === 'ubers' || target === 'uber') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3496305/\">Ubers Viability Rankings</a><br />"; } if (target === 'all' || target === 'overused' || target === 'ou') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3511596/\">np: OU Stage 5</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3491371/\">OU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3502428/\">OU Viability Rankings</a><br />"; } if (target === 'all' || target === 'underused' || target === 'uu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3508311/\">np: UU Stage 2</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3502698/#post-5323505\">UU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3500340/\">UU Viability Rankings</a><br />"; } if (target === 'all' || target === 'rarelyused' || target === 'ru') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3513684/\">np: RU Stage 3</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3506500/\">RU Viability Rankings</a><br />"; } if (target === 'all' || target === 'neverused' || target === 'nu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3506287/\">np: NU (beta)</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3509494/\">NU Viability Rankings</a><br />"; } if (target === 'all' || target === 'littlecup' || target === 'lc') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3496013/\">LC Viability Rankings</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3490462/\">Official LC Banlist</a><br />"; } if (target === 'all' || target === 'doubles') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3509279/\">np: Doubles Stage 3.5</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3498688/\">Doubles Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3496306/\">Doubles Viability Rankings</a><br />"; } if (!matched) { return this.sendReply("The Tiers entry '" + target + "' was not found. Try /tiers for general help."); } this.sendReplyBox(buffer); }, analysis: 'smogdex', strategy: 'smogdex', smogdex: function (target, room, user) { if (!this.canBroadcast()) return; var targets = target.split(','); if (toId(targets[0]) === 'previews') return this.sendReplyBox("<a href=\"https://www.smogon.com/forums/threads/sixth-generation-pokemon-analyses-index.3494918/\">Generation 6 Analyses Index</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); var pokemon = Tools.getTemplate(targets[0]); var item = Tools.getItem(targets[0]); var move = Tools.getMove(targets[0]); var ability = Tools.getAbility(targets[0]); var atLeastOne = false; var generation = (targets[1] || 'xy').trim().toLowerCase(); var genNumber = 6; // var doublesFormats = {'vgc2012':1, 'vgc2013':1, 'vgc2014':1, 'doubles':1}; var doublesFormats = {}; var doublesFormat = (!targets[2] && generation in doublesFormats)? generation : (targets[2] || '').trim().toLowerCase(); var doublesText = ''; if (generation === 'xy' || generation === 'xy' || generation === '6' || generation === 'six') { generation = 'xy'; } else if (generation === 'bw' || generation === 'bw2' || generation === '5' || generation === 'five') { generation = 'bw'; genNumber = 5; } else if (generation === 'dp' || generation === 'dpp' || generation === '4' || generation === 'four') { generation = 'dp'; genNumber = 4; } else if (generation === 'adv' || generation === 'rse' || generation === 'rs' || generation === '3' || generation === 'three') { generation = 'rs'; genNumber = 3; } else if (generation === 'gsc' || generation === 'gs' || generation === '2' || generation === 'two') { generation = 'gs'; genNumber = 2; } else if(generation === 'rby' || generation === 'rb' || generation === '1' || generation === 'one') { generation = 'rb'; genNumber = 1; } else { generation = 'xy'; } if (doublesFormat !== '') { // Smogon only has doubles formats analysis from gen 5 onwards. if (!(generation in {'bw':1, 'xy':1}) || !(doublesFormat in doublesFormats)) { doublesFormat = ''; } else { doublesText = {'vgc2012':"VGC 2012", 'vgc2013':"VGC 2013", 'vgc2014':"VGC 2014", 'doubles':"Doubles"}[doublesFormat]; doublesFormat = '/' + doublesFormat; } } // Pokemon if (pokemon.exists) { atLeastOne = true; if (genNumber < pokemon.gen) { return this.sendReplyBox("" + pokemon.name + " did not exist in " + generation.toUpperCase() + "!"); } // if (pokemon.tier === 'CAP') generation = 'cap'; if (pokemon.tier === 'CAP') return this.sendReply("CAP is not currently supported by Smogon Strategic Pokedex."); var illegalStartNums = {'351':1, '421':1, '487':1, '493':1, '555':1, '647':1, '648':1, '649':1, '681':1}; if (pokemon.isMega || pokemon.num in illegalStartNums) pokemon = Tools.getTemplate(pokemon.baseSpecies); var poke = pokemon.name.toLowerCase().replace(/\ /g, '_').replace(/[^a-z0-9\-\_]+/g, ''); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/pokemon/" + poke + doublesFormat + "\">" + generation.toUpperCase() + " " + doublesText + " " + pokemon.name + " analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } // Item if (item.exists && genNumber > 1 && item.gen <= genNumber) { atLeastOne = true; var itemName = item.name.toLowerCase().replace(' ', '_'); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/items/" + itemName + "\">" + generation.toUpperCase() + " " + item.name + " item analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } // Ability if (ability.exists && genNumber > 2 && ability.gen <= genNumber) { atLeastOne = true; var abilityName = ability.name.toLowerCase().replace(' ', '_'); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/abilities/" + abilityName + "\">" + generation.toUpperCase() + " " + ability.name + " ability analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } // Move if (move.exists && move.gen <= genNumber) { atLeastOne = true; var moveName = move.name.toLowerCase().replace(' ', '_'); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/moves/" + moveName + "\">" + generation.toUpperCase() + " " + move.name + " move analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } if (!atLeastOne) { return this.sendReplyBox("Pokemon, item, move, or ability not found for generation " + generation.toUpperCase() + "."); } }, /********************************************************* * Miscellaneous commands *********************************************************/ potd: function (target, room, user) { if (!this.can('potd')) return false; Config.potd = target; Simulator.SimulatorProcess.eval('Config.potd = \'' + toId(target) + '\''); if (target) { if (Rooms.lobby) Rooms.lobby.addRaw("<div class=\"broadcast-blue\"><b>The Pokemon of the Day is now " + target + "!</b><br />This Pokemon will be guaranteed to show up in random battles.</div>"); this.logModCommand("The Pokemon of the Day was changed to " + target + " by " + user.name + "."); } else { if (Rooms.lobby) Rooms.lobby.addRaw("<div class=\"broadcast-blue\"><b>The Pokemon of the Day was removed!</b><br />No pokemon will be guaranteed in random battles.</div>"); this.logModCommand("The Pokemon of the Day was removed by " + user.name + "."); } }, roll: 'dice', dice: function (target, room, user) { if (!target) return this.parse('/help dice'); if (!this.canBroadcast()) return; var d = target.indexOf("d"); if (d != -1) { var num = parseInt(target.substring(0, d)); var faces; if (target.length > d) faces = parseInt(target.substring(d + 1)); if (isNaN(num)) num = 1; if (isNaN(faces)) return this.sendReply("The number of faces must be a valid integer."); if (faces < 1 || faces > 1000) return this.sendReply("The number of faces must be between 1 and 1000"); if (num < 1 || num > 20) return this.sendReply("The number of dice must be between 1 and 20"); var rolls = []; var total = 0; for (var i = 0; i < num; ++i) { rolls[i] = (Math.floor(faces * Math.random()) + 1); total += rolls[i]; } return this.sendReplyBox("Random number " + num + "x(1 - " + faces + "): " + rolls.join(", ") + "<br />Total: " + total); } if (target && isNaN(target) || target.length > 21) return this.sendReply("The max roll must be a number under 21 digits."); var maxRoll = (target)? target : 6; var rand = Math.floor(maxRoll * Math.random()) + 1; return this.sendReplyBox("Random number (1 - " + maxRoll + "): " + rand); }, pr: 'pickrandom', pick: 'pickrandom', pickrandom: function (target, room, user) { var options = target.split(','); if (options.length < 2) return this.parse('/help pick'); if (!this.canBroadcast()) return false; return this.sendReplyBox('<em>We randomly picked:</em> ' + Tools.escapeHTML(options.sample().trim())); }, register: function () { if (!this.canBroadcast()) return; this.sendReplyBox('You will be prompted to register upon winning a rated battle. Alternatively, there is a register button in the <button name="openOptions"><i class="icon-cog"></i> Options</button> menu in the upper right.'); }, lobbychat: function (target, room, user, connection) { if (!Rooms.lobby) return this.popupReply("This server doesn't have a lobby."); target = toId(target); if (target === 'off') { user.leaveRoom(Rooms.lobby, connection.socket); connection.send('|users|'); this.sendReply("You are now blocking lobby chat."); } else { user.joinRoom(Rooms.lobby, connection); this.sendReply("You are now receiving lobby chat."); } }, showimage: function (target, room, user) { if (!target) return this.parse('/help showimage'); if (!this.can('declare', room)) return false; if (!this.canBroadcast()) return; var targets = target.split(','); if (targets.length != 3) { return this.parse('/help showimage'); } this.sendReply('|raw|<img src="' + Tools.escapeHTML(targets[0]) + '" alt="" width="' + toId(targets[1]) + '" height="' + toId(targets[2]) + '" />'); }, postimage: 'image', image: function (target, room, user) { if (!target) return this.sendReply('Usage: /image link, size'); if (!this.can('ban', room)) return false; if (!this.canBroadcast()) return; var targets = target.split(','); if (targets.length != 2) { return this.sendReply('|raw|<center><img src="' + Tools.escapeHTML(targets[0]) + '" alt="" width="50%"/></center>'); } if (parseInt(targets[1]) <= 0 || parseInt(targets[1]) > 100) return this.parse('Usage: /image link, size (1-100)'); this.sendReply('|raw|<center><img src="' + Tools.escapeHTML(targets[0]) + '" alt="" width="' + toId(targets[1]) + '%"/></center>'); }, htmlbox: function (target, room, user) { if (!target) return this.parse('/help htmlbox'); if (!this.can('gdeclare', room)) return; if (!this.canHTML(target)) return; if (!this.canBroadcast('!htmlbox')) return; this.sendReplyBox(target); }, a: function (target, room, user) { if (!this.can('rawpacket')) return false; // secret sysop command room.add(target); }, /********************************************************* * Custom commands *********************************************************/ customavatars: 'customavatar', customavatar: (function () { const script = function () {/* FILENAME=`mktemp` function cleanup { rm -f $FILENAME } trap cleanup EXIT set -xe timeout 10 wget "$1" -nv -O $FILENAME FRAMES=`identify $FILENAME | wc -l` if [ $FRAMES -gt 1 ]; then EXT=".gif" else EXT=".png" fi timeout 10 convert $FILENAME -layers TrimBounds -coalesce -adaptive-resize 80x80\> -background transparent -gravity center -extent 80x80 "$2$EXT" */}.toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1]; var pendingAdds = {}; return function (target) { var parts = target.split(','); var cmd = parts[0].trim().toLowerCase(); if (cmd in {'':1, show:1, view:1, display:1}) { var message = ""; for (var a in Config.customAvatars) message += "<strong>" + Tools.escapeHTML(a) + ":</strong> " + Tools.escapeHTML(Config.customAvatars[a]) + "<br />"; return this.sendReplyBox(message); } if (!this.can('customavatar')) return false; switch (cmd) { case 'set': var userid = toId(parts[1]); var user = Users.getExact(userid); var avatar = parts.slice(2).join(',').trim(); if (!userid) return this.sendReply("You didn't specify a user."); if (Config.customAvatars[userid]) return this.sendReply(userid + " already has a custom avatar."); var hash = require('crypto').createHash('sha512').update(userid + '\u0000' + avatar).digest('hex').slice(0, 8); pendingAdds[hash] = {userid: userid, avatar: avatar}; parts[1] = hash; if (!user) { this.sendReply("Warning: " + userid + " is not online."); this.sendReply("If you want to continue, use: /customavatar forceset, " + hash); return; } /* falls through */ case 'forceset': var hash = parts[1].trim(); if (!pendingAdds[hash]) return this.sendReply("Invalid hash."); var userid = pendingAdds[hash].userid; var avatar = pendingAdds[hash].avatar; delete pendingAdds[hash]; require('child_process').execFile('bash', ['-c', script, '-', avatar, './config/avatars/' + userid], function (e, out, err) { if (e) { this.sendReply(userid + "'s custom avatar failed to be set. Script output:"); (out + err).split('\n').forEach(this.sendReply.bind(this)); return; } reloadCustomAvatars(); this.sendReply(userid + "'s custom avatar has been set."); }.bind(this)); break; case 'delete': var userid = toId(parts[1]); if (!Config.customAvatars[userid]) return this.sendReply(userid + " does not have a custom avatar."); if (Config.customAvatars[userid].toString().split('.').slice(0, -1).join('.') !== userid) return this.sendReply(userid + "'s custom avatar (" + Config.customAvatars[userid] + ") cannot be removed with this script."); require('fs').unlink('./config/avatars/' + Config.customAvatars[userid], function (e) { if (e) return this.sendReply(userid + "'s custom avatar (" + Config.customAvatars[userid] + ") could not be removed: " + e.toString()); delete Config.customAvatars[userid]; this.sendReply(userid + "'s custom avatar removed successfully"); }.bind(this)); break; default: return this.sendReply("Invalid command. Valid commands are `/customavatar set, user, avatar` and `/customavatar delete, user`."); } }; })(), /********************************************************* * Clan commands *********************************************************/ ayudaclan: 'clanshelp', clanhelp: 'clanshelp', clanshelp: function () { if (!this.canBroadcast()) return false; this.sendReplyBox( "<big><b>Comandos Básicos:</b></big><br /><br />" + "/clanes - Lista los clanes.<br />" + "/clan (clan/miembro) - Muestra la ficha/perfil de un clan.<br />" + "/miembrosclan (clan/miembro) - muestra los miembros con los que cuenta un clan.<br />" + "/clanauth (clan/miembro) - muestra la jerarquía de miembros de un clan.<br />" + "/warlog (clan/miembro) - muestra las 10 últimas wars de un clan.<br />" + "/invitarclan - Invita a un usuario a unirse al clan. Requiere ser Oficial o Líder del clan.<br />" + "/expulsarclan (miembro) - Expulsa a un miembro del clan. Requiere ser Líder del clan.<br />" + "/aceptarclan (clan) - Acepta una invitación al clan.<br />" + "/invitacionesclan (clan/miembro) - Lista a los usuarios invitados a un clan.<br />" + "/borrarinvitaciones - Borra las invitaciones pendientes al Clan. Requiere ser líder del clan.<br />" + "/abandonarclan - Abandona el clan.<br />" + "<br />" + "<big><b>Comandos de Clan-Auth:</b></big><br /><br />" + "/liderclan (miembro) - Nombra a un miembro líder del clan. Requiere ~<br />" + "/oficialclan (miembro) - Nombra a un miembro oficial del clan. Requiere ser Líder del clan.<br />" + "/demoteclan (miembro) - Borra a un miembro del staff del clan. Requiere ser Líder del clan y ~ para demotear a un Líder.<br />" + "/lemaclan (lema) - Establece el Lema del clan. Requiere ser líder del clan.<br />" + "/logoclan (logo) - Establece el Logotipo del clan. Requiere ser líder del clan.<br />" + "/closeclanroom - Bloquea una sala de clan a todos los que no sean miembros de dicho clan, salvo administradores.<br />" + "/openclanroom - Elimina el bloqueo del comando /closeclanroom.<br />" + "/rk o /roomkick - Expulsa a un usuario de una sala. Requiere @ o superior.<br />" + "<br />" + "<big><b>Comandos de Administración:</b></big><br /><br />" + "/createclan &lt;name> - Crea un clan.<br />" + "/deleteclan &lt;name> - Elimina un clan.<br />" + "/addclanmember &lt;clan>, &lt;user> - Fuerza a un usuario a unirse a un clan.<br />" + "/removeclanmember &lt;clan>, &lt;user> - Expulsa a un usuario del clan.<br />" + "/setlemaclan &lt;clan>,&lt;lema> - Establece un lema para un clan.<br />" + "/setlogoclan &lt;clan>,&lt;logo> - Establece un logotipo para un clan.<br />" + "/setsalaclan &lt;clan>,&lt;sala> - Establece una sala para un clan.<br />" + "/setgxeclan &lt;clan>,&lt;wins>,&lt;losses>,&lt;draws> - Establece la puntuación de un clan.<br />" + "/serankclan &lt;clan>,&lt;puntos> - Establece la puntuación de un clan.<br />" + "/settitleclan &lt;clan>&lt;puntos> - Estable un título para el clan.<br />" + "<br />" + "<big><b>Comandos de Wars:</b></big><br /><br />" + "/war &lt;formato>, &lt;tamano>, &lt;clan 1>, &lt;clan 2> - Incia una war entre 2 clanes. Requiere +<br />" + "/totalwar &lt;formato>, &lt;tamano>, &lt;clan 1>, &lt;clan 2> - Incia una war total entre 2 clanes. Requiere +<br />" + "/endwar - Finaliza una war. Requiere +<br />" + "/vw - Muestra el estado de la war.<br />" + "/jw o /joinwar - Comando para unirse a una war.<br />" + "/lw o /leavewar - Comando para salir de una war.<br />" + "/warkick - Fuerza a un usuario a abandonar una war. Requiere %<br />" + "/wardq - Descalifica a un usuario. Requiere % o autoridad en el clan.<br />" + "/warreplace &lt;usuario 1>, &lt;usuario 2> - Comando para reemplazar. Requiere % o autoridad en el clan.<br />" + "/warinvalidate &lt;participante> - Deniega la validez de una batalla o un resultado. Requiere @<br />" ); }, createclan: function (target) { if (!this.can('clans')) return false; if (target.length < 2) this.sendReply("El nombre del clan es demasiado corto"); else if (!Clans.createClan(target)) this.sendReply("No se pudo crear el clan. Es posible que ya exista otro con el mismo nombre."); else this.sendReply("Clan: " + target + " creado con éxito."); }, deleteclan: function (target) { if (!this.can('clans')) return false; if (!Clans.deleteClan(target)) this.sendReply("No se pudo eliminar el clan. Es posble que no exista o que se encuentre en war."); else this.sendReply("Clan: " + target + " eliminado con éxito."); }, getclans: 'clans', clanes: 'clans', clans: function (target, room, user) { if (!this.canBroadcast()) return false; var clansTableTitle = "Lista de Clanes"; if (toId(target) === 'rank' || toId(target) === 'puntos') clansTableTitle = "Lista de Clanes por Puntuaci&oacute;n"; if (toId(target) === 'miembros' || toId(target) === 'members') clansTableTitle = "Lista de Clanes por Miembros"; var clansTable = '<br /><center><big><big><strong>' + clansTableTitle + '</strong></big></big><center><br /><table class="clanstable" width="100%" border="1"><tr><td><center><strong>Clan</strong></center></td><td><center><strong>Miembros</strong></center></td><td><center><strong>Sala</strong></center></td><td><center><strong>GXE</strong></center></td><td><center><strong>Puntuaci&oacute;n</strong></center></td></tr>'; var clansList = Clans.getClansList(toId(target)); var auxRating = {}; var nMembers = 0; var membersClan = {}; var auxGxe = 0; for (var m in clansList) { auxRating = Clans.getElementalData(m); auxGxe = Math.floor(auxRating.gxe * 100) / 100; membersClan = Clans.getMembers(m); if (!membersClan) { nMembers = 0; } else { nMembers = membersClan.length; } clansTable += '<tr><td><center>' + Tools.escapeHTML(Clans.getClanName(m)) + '</center></td><td><center>' + nMembers + '</center></td><td><center>' + '<button name="send" value="/join ' + Tools.escapeHTML(auxRating.sala) + '" target="_blank">' + Tools.escapeHTML(auxRating.sala) + '</button>' + '</center></td><td><center>' + auxGxe + '</center></td><td><center>' + auxRating.rating + '</center></td></tr>'; } clansTable += '</table>'; this.sendReplyBox(clansTable); }, clanauth: function (target, room, user) { var autoclan = false; if (!target) autoclan = true; if (!this.canBroadcast()) return false; var clan = Clans.getRating(target); if (!clan) { target = Clans.findClanFromMember(target); if (target) clan = Clans.getRating(target); } if (!clan && autoclan) { target = Clans.findClanFromMember(user.name); if (target) clan = Clans.getRating(target); } if (!clan) { this.sendReply("El clan especificado no existe o no está disponible."); return; } //html codes for clan ranks var leaderClanSource = Clans.getAuthMembers(target, 2); if (leaderClanSource !== "") { leaderClanSource = "<big><b>Líderes</b></big><br /><br />" + leaderClanSource + "</b></big></big><br /><br />"; } var oficialClanSource = Clans.getAuthMembers(target, 1); if (oficialClanSource !== "") { oficialClanSource = "<big><b>Oficiales</b></big><br /><br />" + oficialClanSource + "</b></big></big><br /><br />"; } var memberClanSource = Clans.getAuthMembers(target, false); if (memberClanSource !== "") { memberClanSource = "<big><b>Resto de Miembros</b></big><br /><br />" + memberClanSource + "</b></big></big><br /><br />"; } this.sendReplyBox( "<center><big><big><b>Jerarquía del clan " + Tools.escapeHTML(Clans.getClanName(target)) + "</b></big></big> <br /><br />" + leaderClanSource + oficialClanSource + memberClanSource + '</center>' ); }, clanmembers: 'miembrosclan', miembrosclan: function (target, room, user) { var autoclan = false; if (!target) autoclan = true; if (!this.canBroadcast()) return false; var clan = Clans.getRating(target); if (!clan) { target = Clans.findClanFromMember(target); if (target) clan = Clans.getRating(target); } if (!clan && autoclan) { target = Clans.findClanFromMember(user.name); if (target) clan = Clans.getRating(target); } if (!clan) { this.sendReply("El clan especificado no existe o no está disponible."); return; } var nMembers = 0; var membersClan = Clans.getMembers(target); if (!membersClan) { nMembers = 0; } else { nMembers = membersClan.length; } this.sendReplyBox( "<strong>Miembros del clan " + Tools.escapeHTML(Clans.getClanName(target)) + ":</strong> " + Clans.getAuthMembers(target, "all") + '<br /><br /><strong>Número de miembros: ' + nMembers + '</strong>' ); }, invitacionesclan: function (target, room, user) { var autoclan = false; if (!target) autoclan = true; if (!this.canBroadcast()) return false; var clan = Clans.getRating(target); if (!clan) { target = Clans.findClanFromMember(target); if (target) clan = Clans.getRating(target); } if (!clan && autoclan) { target = Clans.findClanFromMember(user.name); if (target) clan = Clans.getRating(target); } if (!clan) { this.sendReply("El clan especificado no existe o no está disponible."); return; } this.sendReplyBox( "<strong>Invitaciones pendientes del clan " + Tools.escapeHTML(Clans.getClanName(target)) + ":</strong> " + Tools.escapeHTML(Clans.getInvitations(target).sort().join(", ")) ); }, clan: 'getclan', getclan: function (target, room, user) { var autoClan = false; var memberClanProfile = false; var clanMember = ""; if (!target) autoClan = true; if (!this.canBroadcast()) return false; var clan = Clans.getProfile(target); if (!clan) { clanMember = target; target = Clans.findClanFromMember(target); memberClanProfile = true; if (target) clan = Clans.getProfile(target); } if (!clan && autoClan) { target = Clans.findClanFromMember(user.name); if (target) clan = Clans.getProfile(target); memberClanProfile = true; clanMember = user.name; } if (!clan) { this.sendReply("El clan especificado no existe o no está disponible."); return; } var salaClanSource = ""; if (clan.sala === "none") { salaClanSource = 'Aún no establecida.'; } else { salaClanSource = '<button name="send" value="/join ' + Tools.escapeHTML(clan.sala) + '" target="_blank">' + Tools.escapeHTML(clan.sala) + '</button>'; } var clanTitle = ""; if (memberClanProfile) { var authValue = Clans.authMember(target, clanMember); if (authValue === 2) { clanTitle = clanMember + " - Líder del clan " + clan.compname; } else if (authValue === 1) { clanTitle = clanMember + " - Oficial del clan " + clan.compname; } else { clanTitle = clanMember + " - Miembro del clan " + clan.compname; } } else { clanTitle = clan.compname; } var medalsClan = ''; if (clan.medals) { for (var u in clan.medals) { medalsClan += '<img id="' + u + '" src="' + encodeURI(clan.medals[u].logo) + '" width="32" title="' + Tools.escapeHTML(clan.medals[u].desc) + '" />&nbsp;&nbsp;'; } } this.sendReplyBox( '<div id="fichaclan">' + '<h4><center><p> <br />' + Tools.escapeHTML(clanTitle) + '</center></h4><hr width="90%" />' + '<table width="90%" border="0" align="center"><tr><td width="180" rowspan="2"><div align="center"><img src="' + encodeURI(clan.logo) + '" width="160" height="160" /></div></td><td height="64" align="left" valign="middle"><span class="lemaclan">'+ Tools.escapeHTML(clan.lema) + '</span></td> </tr> <tr> <td align="left" valign="middle"><strong>Sala Propia</strong>: ' + salaClanSource + ' <p style="font-style: normal;font-size: 16px;"><strong>Puntuación</strong>:&nbsp;' + clan.rating + ' (' + clan.wins + ' Victorias, ' + clan.losses + ' Derrotas, ' + clan.draws + ' Empates)<br />' + ' </p> <p style="font-style: normal;font-size: 16px;">&nbsp;' + medalsClan + '</p></td> </tr></table></div>' ); }, setlemaclan: function (target) { if (!this.can('clans')) return false; var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /setlemaclan clan, lema"); if (!Clans.setLema(params[0], params[1])) this.sendReply("El clan no existe o el lema es mayor de 80 caracteres."); else { this.sendReply("El nuevo lema del clan " + params[0] + " ha sido establecido con éxito."); } }, setlogoclan: function (target) { if (!this.can('clans')) return false; var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /setlogoclan clan, logo"); if (!Clans.setLogo(params[0], params[1])) this.sendReply("El clan no existe o el link del logo es mayor de 80 caracteres."); else { this.sendReply("El nuevo logo del clan " + params[0] + " ha sido establecido con éxito."); } }, settitleclan: function (target) { if (!this.can('clans')) return false; var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /settitleclan clan, titulo"); if (!Clans.setCompname(params[0], params[1])) this.sendReply("El clan no existe o el título es mayor de 80 caracteres."); else { this.sendReply("El nuevo titulo del clan " + params[0] + " ha sido establecido con éxito."); } }, setrankclan: function (target) { if (!this.can('clans')) return false; var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /setrankclan clan, valor"); if (!Clans.setRanking(params[0], params[1])) this.sendReply("El clan no existe o el valor no es válido."); else { this.sendReply("El nuevo rank para el clan " + params[0] + " ha sido establecido con éxito."); } }, setgxeclan: function (target) { if (!this.can('clans')) return false; var params = target.split(','); if (!params || params.length !== 4) return this.sendReply("Usage: /setgxeclan clan, wins, losses, ties"); if (!Clans.setGxe(params[0], params[1], params[2], params[3])) this.sendReply("El clan no existe o el valor no es válido."); else { this.sendReply("El nuevo GXE para el clan " + params[0] + " ha sido establecido con éxito."); } }, setsalaclan: function (target) { if (!this.can('clans')) return false; var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /setsalaclan clan, sala"); if (!Clans.setSala(params[0], params[1])) this.sendReply("El clan no existe o el nombre de la sala es mayor de 80 caracteres."); else { this.sendReply("La nueva sala del clan " + params[0] + " ha sido establecida con éxito."); } }, giveclanmedal: function (target) { if (!this.can('clans')) return false; var params = target.split(','); if (!params || params.length !== 4) return this.sendReply("Usage: /giveclanmedal clan, medallaId, imagen, desc"); if (!Clans.addMedal(params[0], params[1], params[2], params[3])) this.sendReply("El clan no existe o alguno de los datos no es correcto"); else { this.sendReply("Has entegado una medalla al clan " + params[0]); } }, removeclanmedal: function (target) { if (!this.can('clans')) return false; var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /removeclanmedal clan, medallaId"); if (!Clans.deleteMedal(params[0], params[1])) this.sendReply("El clan no existe o no podeía dicha medalla"); else { this.sendReply("Has quitado una medalla al clan " + params[0]); } }, lemaclan: function (target, room, user) { var permisionClan = false; if (!target) return this.sendReply("Debe especificar un lema."); var clanUser = Clans.findClanFromMember(user.name); if (clanUser) { var clanUserid = toId(clanUser); var iduserwrit = toId(user.name); var perminsionvalue = Clans.authMember(clanUserid, iduserwrit); if (perminsionvalue === 2) permisionClan = true; if (!permisionClan && !this.can('clans')) return false; } else { return false; } var claninfo = Clans.getElementalData (clanUser); if (room && room.id === toId(claninfo.sala)) { if (!Clans.setLema(clanUser, target)) this.sendReply("El lema es mayor de 80 caracteres."); else { this.addModCommand("Un nuevo lema para el clan " + clanUser + " ha sido establecido por " + user.name); } } else { this.sendReply("Este comando solo puede ser usado en la sala del clan."); } }, logoclan: function (target, room, user) { var permisionClan = false; if (!target) return this.sendReply("Debe especificar un logo."); var clanUser = Clans.findClanFromMember(user.name); if (clanUser) { var clanUserid = toId(clanUser); var iduserwrit = toId(user.name); var perminsionvalue = Clans.authMember(clanUserid, iduserwrit); if (perminsionvalue === 2) permisionClan = true; if (!permisionClan && !this.can('clans')) return false; } else { return false; } var claninfo = Clans.getElementalData (clanUser); if (room && room.id === toId(claninfo.sala)) { if (!Clans.setLogo(clanUser, target)) this.sendReply("El logo es mayor de 80 caracteres."); else { this.addModCommand("Un nuevo logotipo para el clan " + clanUser + " ha sido establecido por " + user.name); } } else { this.sendReply("Este comando solo puede ser usado en la sala del clan."); } }, addclanmember: function (target) { if (!this.can('clans')) return false; var params = target.split(','); if (params.length !== 2) return this.sendReply("Usage: /addclanmember clan, member"); var user = Users.getExact(params[1]); if (!user || !user.connected) return this.sendReply("User: " + params[1] + " is not online."); if (!Clans.addMember(params[0], params[1])) this.sendReply("Could not add the user to the clan. Does the clan exist or is the user already in another clan?"); else { this.sendReply("User: " + user.name + " successfully added to the clan."); Rooms.rooms.lobby.add('|raw|<div class="clans-user-join">' + Tools.escapeHTML(user.name) + " se ha unido al clan: " + Tools.escapeHTML(Clans.getClanName(params[0])) + '</div>'); } }, clanleader: 'liderclan', liderclan: function (target, room, user) { if (!this.can('clans')) return false; var params = target.split(','); if (!params) return this.sendReply("Usage: /liderclan member"); var userk = Users.getExact(params[0]); if (!userk || !userk.connected) return this.sendReply("Usuario: " + params[0] + " no existe o no está disponible."); if (!Clans.addLeader(params[0])) this.sendReply("El usuario no existe, no pertenece a ningún clan o ya era líder de su clan."); else { var clanUser = Clans.findClanFromMember(params[0]); this.sendReply("Usuario: " + userk.name + " nombrado correctamente líder del clan " + clanUser + "."); userk.popup(user.name + " te ha nombrado Líder del clan " + clanUser + ".\nUtiliza el comando /clanhelp para más información."); } }, clanoficial: 'oficialclan', oficialclan: function (target, room, user) { var permisionClan = false; var params = target.split(','); if (!params) { return this.sendReply("Usage: /demoteclan member"); } var clanUser = Clans.findClanFromMember(user.name); var clanTarget = Clans.findClanFromMember(params[0]); if (clanUser) { var clanUserid = toId(clanUser); var userb = toId(params[0]); var iduserwrit = toId(user.name); var perminsionvalue = Clans.authMember(clanUserid, iduserwrit); if (perminsionvalue === 2 && clanTarget === clanUser) permisionClan = true; } if (!permisionClan && !this.can('clans')) return; var userk = Users.getExact(params[0]); if (!userk || !userk.connected) return this.sendReply("Usuario: " + params[0] + " no existe o no está disponible."); if (clanTarget) { var clanId = toId(clanTarget); var userId = toId(params[0]); if (Clans.authMember(clanId, userId) === 2 && !this.can('clans')) return false; } if (!Clans.addOficial(params[0])) this.sendReply("El usuario no existe, no pertenece a ningún clan o ya era oficial de su clan."); else { this.sendReply("Usuario: " + userk.name + " nombrado correctamente oficial del clan " + clanTarget + "."); userk.popup(user.name + " te ha nombrado Oficial del clan " + clanTarget + ".\nUtiliza el comando /clanhelp para más información."); } }, degradarclan: 'declanauth', demoteclan: 'declanauth', declanauth: function (target, room, user) { var permisionClan = false; var params = target.split(','); if (!params) { return this.sendReply("Usage: /demoteclan member"); } var clanUser = Clans.findClanFromMember(user.name); var clanTarget = Clans.findClanFromMember(params[0]); if (clanUser) { var clanUserid = toId(clanUser); var userb = toId(params[0]); var iduserwrit = toId(user.name); var perminsionValue = Clans.authMember(clanUserid, iduserwrit); if (perminsionValue === 2 && clanTarget === clanUser) permisionClan = true; } if (!permisionClan && !this.can('clans')) return; var userk = Users.getExact(params[0]); if (!clanTarget) { return this.sendReply("El usuario no existe o no pertenece a ningún clan."); } else { var clanId = toId(clanTarget); var userId = toId(params[0]); if (Clans.authMember(clanId, userId) === 2 && !this.can('clans')) return false; } if (!Clans.deleteLeader(params[0])) { if (!Clans.deleteOficial(params[0])) { this.sendReply("El usuario no poseía ninguna autoridad dentro del clan."); } else { if (!userk || !userk.connected) { this.addModCommand(params[0] + " ha sido degradado de rango en " + clanTarget + " por " + user.name); } else { this.addModCommand(userk.name + " ha sido degradado de rango en " + clanTarget + " por " + user.name); } } } else { var oficialDemote = Clans.deleteOficial(params[0]); if (!userk || !userk.connected) { this.addModCommand(params[0] + " ha sido degradado de rango en " + clanTarget + " por " + user.name); } else { this.addModCommand(userk.name + " ha sido degradado de rango en " + clanTarget + " por " + user.name); } } }, invitarclan: function (target, room, user) { var permisionClan = false; var clanUser = Clans.findClanFromMember(user.name); if (clanUser) { var clanUserid = toId(clanUser); var iduserwrit = toId(user.name); var permisionValue = Clans.authMember(clanUserid, iduserwrit); if (permisionValue === 1) permisionClan = true; if (permisionValue === 2) permisionClan = true; } if (!permisionClan) return false; var params = target.split(','); if (!params) return this.sendReply("Usage: /invitarclan user"); var userk = Users.getExact(params[0]); if (!userk || !userk.connected) return this.sendReply("Usuario: " + params[0] + " no existe o no está disponible."); if (!Clans.addInvite(clanUser, params[0])) this.sendReply("No se pudo invitar al usuario. ¿No existe, ya está invitado o está en otro clan?"); else { clanUser = Clans.findClanFromMember(user.name); userk.popup(user.name + " te ha invitado a unirte al clan " + clanUser + ".\nPara unirte al clan escribe en el chat /aceptarclan " + clanUser); this.addModCommand(userk.name + " ha sido invitado a unirse al clan " + clanUser + " por " + user.name); } }, aceptarclan: function (target, room, user) { var clanUser = Clans.findClanFromMember(user.name); if (clanUser) { return this.sendReply("Ya perteneces a un clan. No te puedes unir a otro."); } var params = target.split(','); if (!params) return this.sendReply("Usage: /aceptarclan clan"); var clanpropio = Clans.getClanName(params[0]); if (!clanpropio) return this.sendReply("El clan no existe o no está disponible."); if (!Clans.aceptInvite(params[0], user.name)) this.sendReply("El clan no existe o no has sido invitado a este."); else { this.sendReply("Te has unido correctamente al clan" + clanpropio); Rooms.rooms.lobby.add('|raw|<div class="clans-user-join">' + Tools.escapeHTML(user.name) + " se ha unido al clan: " + Tools.escapeHTML(Clans.getClanName(params[0])) + '</div>'); } }, inviteclear: 'borrarinvitaciones', borrarinvitaciones: function (target, room, user) { var permisionClan = false; var clanUser = Clans.findClanFromMember(user.name); if (!target) { if (clanUser) { var clanUserid = toId(clanUser); var iduserwrit = toId(user.name); var perminsionvalue = Clans.authMember(clanUserid, iduserwrit); if (perminsionvalue === 2) permisionClan = true; } if (!permisionClan) return false; } else { if (!this.can('clans')) return; clanUser = target; } if (!Clans.clearInvitations(clanUser)) this.sendReply("El clan no existe o no está disponible."); else { this.sendReply("Lista de Invitaciones pendientes del clan " + clanUser + " borrada correctamente."); } }, removeclanmember: function (target) { if (!this.can('clans')) return false; var params = target.split(','); if (params.length !== 2) return this.sendReply("Usage: /removeclanmember clan, member"); if (!Clans.removeMember(params[0], params[1])) this.sendReply("Could not remove the user from the clan. Does the clan exist or has the user already been removed from it?"); else { this.sendReply("User: " + params[1] + " successfully removed from the clan."); Rooms.rooms.lobby.add('|raw|<div class="clans-user-join">' + Tools.escapeHTML(params[1]) + " ha abandonado el clan: " + Tools.escapeHTML(Clans.getClanName(params[0])) + '</div>'); } }, expulsarclan: function (target, room, user) { var permisionClan = false; var params = target.split(','); if (!params) { return this.sendReply("Usage: /demoteclan member"); } var clanUser = Clans.findClanFromMember(user.name); var clanTarget = Clans.findClanFromMember(params[0]); if (clanUser) { var clanUserid = toId(clanUser); var userb = toId(params[0]); var iduserwrit = toId(user.name); var perminsionValue = Clans.authMember(clanUserid, iduserwrit); if (perminsionValue === 2 && clanTarget === clanUser) permisionClan = true; } if (!permisionClan && !this.can('clans')) return; var currentWar = Clans.findWarFromClan(clanTarget); if (currentWar) { var currentWarParticipants = Clans.getWarParticipants(currentWar); if (currentWarParticipants.clanAMembers[toId(params[0])] || currentWarParticipants.clanBMembers[toId(params[0])]) return this.sendReply("No puedes expulsar del clan si el miembro estaba participando en una war."); } var userk = Users.getExact(params[0]); if (!clanTarget) { return this.sendReply("El usuario no existe o no pertenece a ningún clan."); } else { var clanId = toId(clanTarget); var userId = toId(params[0]); if (Clans.authMember(clanId, userId) === 2 && !this.can('clans')) return false; } if (!Clans.removeMember(clanTarget, params[0])) { this.sendReply("El usuario no pudo ser expulsado del clan."); } else { if (!userk || !userk.connected) { this.addModCommand(params[0] + " ha sido expulsado del clan " + clanTarget + " por " + user.name); } else { this.addModCommand(userk.name + " ha sido expulsado del clan " + clanTarget + " por " + user.name); } } }, salirdelclan: 'abandonarclan', clanleave: 'abandonarclan', abandonarclan: function (target, room, user) { var clanUser = Clans.findClanFromMember(user.name); if (!clanUser) { return this.sendReply("No perteneces a ningún clan."); } var currentWar = Clans.findWarFromClan(clanUser); if (currentWar) { var currentWarParticipants = Clans.getWarParticipants(currentWar); if (currentWarParticipants.clanAMembers[toId(user.name)] || currentWarParticipants.clanBMembers[toId(user.name)]) return this.sendReply("No puedes salir del clan si estabas participando en una war."); } if (!Clans.removeMember(clanUser, user.name)) { this.sendReply("Error al intentar salir del clan."); } else { this.sendReply("Has salido del clan" + clanUser); Rooms.rooms.lobby.add('|raw|<div class="clans-user-join">' + Tools.escapeHTML(user.name) + " ha abandonado el clan: " + Tools.escapeHTML(Clans.getClanName(clanUser)) + '</div>'); } }, //new war system pendingwars: 'wars', wars: function (target, room, user) { if (!this.canBroadcast()) return false; this.sendReplyBox(Clans.getPendingWars()); }, viewwar: 'vw', warstatus: 'vw', vw: function (target, room, user) { if (!this.canBroadcast()) return false; if (!room.isOfficial) return this.sendReply("Este comando solo puede ser usado en salas Oficiales."); var currentWar = Clans.findWarFromRoom(room.id); if (!currentWar) return this.sendReply("No había ninguna war en curso en esta sala."); var currentWarData = Clans.getWarData(currentWar); var currentWarParticipants = Clans.getWarParticipants(currentWar); if (currentWarData.warRound === 0) { this.sendReply('|raw| <hr /><h2><font color="green">' + ' Inscríbanse a la war en formato ' + Clans.getWarFormatName(currentWarData.format) + ' entre los clanes ' + Clans.getClanName(currentWar) + " y " + Clans.getClanName(currentWarData.against) + '. Para unirte escribe </font> <font color="red">/joinwar</font> <font color="green">.</font></h2><b><font color="blueviolet">Jugadores por clan:</font></b> ' + currentWarData.warSize + '<br /><font color="blue"><b>FORMATO:</b></font> ' + Clans.getWarFormatName(currentWarData.format) + '<hr /><br /><font color="red"><b>Recuerda que debes mantener tu nombre durante toda la duración de la war.</b></font>'); } else { var warType = ""; if (currentWarData.warStyle === 2) warType = " total"; var htmlSource = '<hr /><h3><center><font color=green><big>War' + warType + ' entre ' + Clans.getClanName(currentWar) + " y " + Clans.getClanName(currentWarData.against) + '</big></font></center></h3><center><b>FORMATO:</b> ' + Clans.getWarFormatName(currentWarData.format) + "</center><hr /><center><small><font color=red>Red</font> = descalificado, <font color=green>Green</font> = paso a la siguiente ronda, <a class='ilink'><b>URL</b></a> = combatiendo</small></center><br />"; for (var t in currentWarParticipants.byes) { var userFreeBye = Users.getExact(t); if (!userFreeBye) {userFreeBye = t;} else {userFreeBye = userFreeBye.name;} htmlSource += '<center><small><font color=green>' + userFreeBye + ' ha pasado a la siguiente ronda.</font></small></center><br />'; } var clanDataA = Clans.getProfile(currentWar); var clanDataB = Clans.getProfile(currentWarData.against); var matchupsTable = '<table align="center" border="0" cellpadding="0" cellspacing="0"><tr><td align="right"><img width="100" height="100" src="' + encodeURI(clanDataA.logo) + '" />&nbsp;&nbsp;&nbsp;&nbsp;</td><td align="center"><table align="center" border="0" cellpadding="0" cellspacing="0">'; for (var i in currentWarParticipants.matchups) { var userk = Users.getExact(currentWarParticipants.matchups[i].from); if (!userk) {userk = currentWarParticipants.matchups[i].from;} else {userk = userk.name;} var userf = Users.getExact(currentWarParticipants.matchups[i].to); if (!userf) {userf = currentWarParticipants.matchups[i].to;} else {userf = userf.name;} switch (currentWarParticipants.matchups[i].result) { case 0: matchupsTable += '<tr><td align="right"><big>' + userk + '</big></td><td>&nbsp;vs&nbsp;</td><td><big align="left">' + userf + "</big></td></tr>"; break; case 1: matchupsTable += '<tr><td align="right"><a href="/' + currentWarParticipants.matchups[i].battleLink +'" room ="' + currentWarParticipants.matchups[i].battleLink + '" class="ilink"><b><big>' + userk + '</big></b></a></td><td>&nbsp;<a href="/' + currentWarParticipants.matchups[i].battleLink + '" room ="' + currentWarParticipants.matchups[i].battleLink + '" class="ilink">vs</a>&nbsp;</td><td><a href="/' + currentWarParticipants.matchups[i].battleLink + '" room ="' + currentWarParticipants.matchups[i].battleLink + '" class="ilink"><b><big align="left">' + userf + "</big></b></a></td></tr>"; break; case 2: matchupsTable += '<tr><td align="right"><font color="green"><b><big>' + userk + '</big></b></font></td><td>&nbsp;vs&nbsp;</td><td><font color="red"><b><big align="left">' + userf + "</big></b></font></td></tr>"; break; case 3: matchupsTable += '<tr><td align="right"><font color="red"><b><big>' + userk + '</big></b></font></td><td>&nbsp;vs&nbsp;</td><td><font color="green"><b><big align="left">' + userf + "</big></b></font></td></tr>"; break; } } matchupsTable += '</table></td><td>&nbsp;&nbsp;&nbsp;&nbsp;<img width="100" height="100" src="' + encodeURI(clanDataB.logo) + '" /></td></tr></table><hr />'; htmlSource += matchupsTable; this.sendReply('|raw| ' + htmlSource); } }, standardwar: 'war', war: function (target, room, user) { var permisionCreateWar = false; if (user.group === '+' || user.group === '%' || user.group === '@' || user.group === '&' || user.group === '~') permisionCreateWar = true; //if (room.auth && room.auth[user.userid]) permisionCreateWar = true; if (!permisionCreateWar && !this.can('wars')) return false; if (!room.isOfficial) return this.sendReply("Este comando solo puede ser usado en salas Oficiales."); if (Clans.findWarFromRoom(room.id)) return this.sendReply("Ya había una war en curso en esta sala."); var params = target.split(','); if (params.length !== 4) return this.sendReply("Usage: /war formato, tamaño, clanA, clanB"); if (!Clans.getWarFormatName(params[0])) return this.sendReply("El formato especificado para la war no es válido."); params[1] = parseInt(params[1]); if (params[1] < 3 || params[1] > 100) return this.sendReply("El tamaño de la war no es válido."); if (!Clans.createWar(params[2], params[3], room.id, params[0], params[1], 1)) { this.sendReply("Alguno de los clanes especificados no existía o ya estaba en war."); } else { this.logModCommand(user.name + " ha iniciado una war standard entre los clanes " + Clans.getClanName(params[2]) + " y " + Clans.getClanName(params[3]) + " en formato " + Clans.getWarFormatName(params[0]) + "."); Rooms.rooms[room.id].addRaw('<hr /><h2><font color="green">' + user.name + ' ha iniciado una War en formato ' + Clans.getWarFormatName(params[0]) + ' entre los clanes ' + Clans.getClanName(params[2]) + " y " + Clans.getClanName(params[3]) + '. Si deseas unirte escribe </font> <font color="red">/joinwar</font> <font color="green">.</font></h2><b><font color="blueviolet">Jugadores por clan:</font></b> ' + params[1] + '<br /><font color="blue"><b>FORMATO:</b></font> ' + Clans.getWarFormatName(params[0]) + '<hr /><br /><font color="red"><b>Recuerda que debes mantener tu nombre durante toda la duración de la war.</b></font>'); } }, totalwar: 'wartotal', wartotal: function (target, room, user) { var permisionCreateWar = false; if (user.group === '+' || user.group === '%' || user.group === '@' || user.group === '&' || user.group === '~') permisionCreateWar = true; if (!permisionCreateWar && !this.can('wars')) return false; if (!room.isOfficial) return this.sendReply("Este comando solo puede ser usado en salas Oficiales."); if (Clans.findWarFromRoom(room.id)) return this.sendReply("Ya había una war en curso en esta sala."); var params = target.split(','); if (params.length !== 4) return this.sendReply("Usage: /totalwar formato, tamaño, clanA, clanB"); if (!Clans.getWarFormatName(params[0])) return this.sendReply("El formato especificado para la war no es válido."); params[1] = parseInt(params[1]); if (params[1] < 3 || params[1] > 100) return this.sendReply("El tamaño de la war no es válido."); if (!Clans.createWar(params[2], params[3], room.id, params[0], params[1], 2)) { this.sendReply("Alguno de los clanes especificados no existía o ya estaba en war."); } else { this.logModCommand(user.name + " ha iniciado una war total entre los clanes " + Clans.getClanName(params[2]) + " y " + Clans.getClanName(params[3]) + " en formato " + Clans.getWarFormatName(params[0]) + "."); Rooms.rooms[room.id].addRaw('<hr /><h2><font color="green">' + user.name + ' ha iniciado una War Total en formato ' + Clans.getWarFormatName(params[0]) + ' entre los clanes ' + Clans.getClanName(params[2]) + " y " + Clans.getClanName(params[3]) + '. Si deseas unirte escribe </font> <font color="red">/joinwar</font> <font color="green">.</font></h2><b><font color="blueviolet">Jugadores por clan:</font></b> ' + params[1] + '<br /><font color="blue"><b>FORMATO:</b></font> ' + Clans.getWarFormatName(params[0]) + '<hr /><br /><font color="red"><b>Recuerda que debes mantener tu nombre durante toda la duración de la war.</b></font>'); } }, joinwar: 'jw', jw: function (target, room, user) { var clanUser = Clans.findClanFromMember(user.name); if (!clanUser) { return this.sendReply("No perteneces a ningún clan."); } var currentWar = Clans.findWarFromRoom(room.id); if (!currentWar) return this.sendReply("No había ninguna war en curso en esta sala."); var currentWarData = Clans.getWarData(currentWar); if (toId(clanUser) !== toId(currentWar) && toId(clanUser) !== toId(currentWarData.against)) return this.sendReply("No perteneces a ninguno de los clanes que se están enfrentando en war."); var currentWarParticipants = Clans.getWarParticipants(currentWar); if (currentWarParticipants.clanAMembers[toId(user.name)] || currentWarParticipants.clanBMembers[toId(user.name)]) return this.sendReply("Ya estabas inscrito en esta war."); if (currentWarData.warRound > 0) return this.sendReply("La War ya ha empezado. No te puedes unir."); var registeredA = Object.keys(currentWarParticipants.clanAMembers); var registeredB = Object.keys(currentWarParticipants.clanBMembers); if (toId(clanUser) === toId(currentWar) && registeredA.length === currentWarData.warSize) return this.sendReply("No quedan plazas para tu clan en esta war."); if (toId(clanUser) === toId(currentWarData.against) && registeredB.length === currentWarData.warSize) return this.sendReply("No quedan plazas para tu clan en esta war."); //join war var clanBJoin = false; if (toId(clanUser) === toId(currentWarData.against)) clanBJoin = true; if (!Clans.addWarParticipant(currentWar, user.name, clanBJoin)) { this.sendReply("Error al intentar unirse a la war."); } else { var freePlaces = Clans.getFreePlaces(currentWar); if (freePlaces > 0) { Rooms.rooms[room.id].addRaw('<b>' + user.name + '</b> se ha unido a la War. Quedan ' + freePlaces + ' plazas.'); } else{ Rooms.rooms[room.id].addRaw('<b>' + user.name + '</b> se ha unido a la War. Comienza la War!'); Clans.startWar(currentWar); //view war status var warType = ""; if (currentWarData.warStyle === 2) warType = " total"; currentWarParticipants = Clans.getWarParticipants(currentWar); var htmlSource = '<hr /><h3><center><font color=green><big>War' + warType + ' entre ' + Clans.getClanName(currentWar) + " y " + Clans.getClanName(currentWarData.against) + '</big></font></center></h3><center><b>FORMATO:</b> ' + Clans.getWarFormatName(currentWarData.format) + "</center><hr /><center><small><font color=red>Red</font> = descalificado, <font color=green>Green</font> = paso a la siguiente ronda, <a class='ilink'><b>URL</b></a> = combatiendo</small><center><br />"; var clanDataA = Clans.getProfile(currentWar); var clanDataB = Clans.getProfile(currentWarData.against); var matchupsTable = '<table align="center" border="0" cellpadding="0" cellspacing="0"><tr><td align="right"><img width="100" height="100" src="' + encodeURI(clanDataA.logo) + '" />&nbsp;&nbsp;&nbsp;&nbsp;</td><td align="center"><table align="center" border="0" cellpadding="0" cellspacing="0">'; for (var i in currentWarParticipants.matchups) { var userk = Users.getExact(currentWarParticipants.matchups[i].from); if (!userk) {userk = currentWarParticipants.matchups[i].from;} else {userk = userk.name;} var userf = Users.getExact(currentWarParticipants.matchups[i].to); if (!userf) {userf = currentWarParticipants.matchups[i].to;} else {userf = userf.name;} switch (currentWarParticipants.matchups[i].result) { case 0: matchupsTable += '<tr><td align="right"><big>' + userk + '</big></td><td>&nbsp;vs&nbsp;</td><td><big align="left">' + userf + "</big></td></tr>"; break; case 1: matchupsTable += '<tr><td align="right"><a href="' + currentWarParticipants.matchups[i].battleLink + '" room ="' + currentWarParticipants.matchups[i].battleLink + '"class="ilink"><big>' + userk + '</big></a></td><td>&nbsp;<a href="' + currentWarParticipants.matchups[i].battleLink + '" room ="' + currentWarParticipants.matchups[i].battleLink + '"class="ilink">vs</a>&nbsp;</td><td><a href="' + currentWarParticipants.matchups[i].battleLink + '" room ="' + currentWarParticipants.matchups[i].battleLink + '"class="ilink"><big align="left">' + userf + "</big></a></td></tr>"; break; case 2: matchupsTable += '<tr><td align="right"><font color="green"><big>' + userk + '</big></font></td><td>&nbsp;vs&nbsp;</td><td><font color="red"><big align="left">' + userf + "</big></font></td></tr>"; break; case 3: matchupsTable += '<tr><td align="right"><font color="red"><big>' + userk + '</big></font></td><td>&nbsp;vs&nbsp;</td><td><font color="green"><big align="left">' + userf + "</big></font></td></tr>"; break; } } matchupsTable += '</table></td><td>&nbsp;&nbsp;&nbsp;&nbsp;<img width="100" height="100" src="' + encodeURI(clanDataB.logo) + '" /></td></tr></table><hr />'; htmlSource += matchupsTable; Rooms.rooms[room.id].addRaw(htmlSource); } } }, leavewar: 'lw', lw: function (target, room, user) { var clanUser = Clans.findClanFromMember(user.name); if (!clanUser) { return this.sendReply("No perteneces a ningún clan."); } var currentWar = Clans.findWarFromRoom(room.id); if (!currentWar) return this.sendReply("No había ninguna war en curso en esta sala."); var currentWarData = Clans.getWarData(currentWar); if (toId(clanUser) !== toId(currentWar) && toId(clanUser) !== toId(currentWarData.against)) return this.sendReply("No perteneces a ninguno de los clanes que se están enfrentando en war."); var currentWarParticipants = Clans.getWarParticipants(currentWar); if (!currentWarParticipants.clanAMembers[toId(user.name)] && !currentWarParticipants.clanBMembers[toId(user.name)]) return this.sendReply("No estabas inscrito en esta war."); if (currentWarData.warRound > 0) return this.sendReply("La War ya ha empezado. No puedes salir de ella."); //leave war var clanBJoin = false; if (toId(clanUser) === toId(currentWarData.against)) clanBJoin = true; if (!Clans.removeWarParticipant(currentWar, user.name, clanBJoin)) { this.sendReply("Error al intentar salir de la war."); } else { var freePlaces = Clans.getFreePlaces(currentWar); Rooms.rooms[room.id].addRaw('<b>' + user.name + '</b> ha salido de la War. Quedan ' + freePlaces + ' plazas.'); } }, warkick: function (target, room, user) { var permisionModWar = false; if (user.group === '%' || user.group === '@' || user.group === '&' || user.group === '~') permisionModWar = true; if (!permisionModWar && !this.can('wars')) return false; if (!target) return this.sendReply("No has especificado ningún usuario"); var clanUser = Clans.findClanFromMember(target); if (!clanUser) { return this.sendReply("El usuario no pertene a ningún clan."); } var currentWar = Clans.findWarFromRoom(room.id); if (!currentWar) return this.sendReply("No había ninguna war en curso en esta sala."); var currentWarData = Clans.getWarData(currentWar); if (toId(clanUser) !== toId(currentWar) && toId(clanUser) !== toId(currentWarData.against)) return this.sendReply("El usuario no pertenece a ninguno de los clanes que se están enfrentando en war."); var currentWarParticipants = Clans.getWarParticipants(currentWar); if (!currentWarParticipants.clanAMembers[toId(target)] && !currentWarParticipants.clanBMembers[toId(target)]) return this.sendReply("El Usuario no estaba inscrito en esta war."); if (currentWarData.warRound > 0) return this.sendReply("La War ya ha empezado. No puedes usar este comando."); //leave war var clanBJoin = false; if (toId(clanUser) === toId(currentWarData.against)) clanBJoin = true; if (!Clans.removeWarParticipant(currentWar, target, clanBJoin)) { this.sendReply("Error al intentar expulsar de la war."); } else { var freePlaces = Clans.getFreePlaces(currentWar); var userk = Users.getExact(target); if (!userk) { Rooms.rooms[room.id].addRaw('<b>' + user.name + '</b> ha expulsado a <b>' + userk.name + '</b> de la War. Quedan ' + freePlaces + ' plazas.'); } else { Rooms.rooms[room.id].addRaw('<b>' + user.name + '</b> ha expulsado a <b>' + toId(target) + '</b> de la War. Quedan ' + freePlaces + ' plazas.'); } } }, wdq: 'wardq', wardq: function (target, room, user) { var permisionModWar = false; if (!target) return this.sendReply("No has especificado ningún usuario"); var clanUser = Clans.findClanFromMember(target); if (user.group === '%' || user.group === '@' || user.group === '&' || user.group === '~') permisionModWar = true; if (!clanUser) { return this.sendReply("El usuario no pertene a ningún clan."); } if (Clans.authMember(clanUser, user.name) === 1 || Clans.authMember(clanUser, user.name) === 2) permisionModWar = true; if (!permisionModWar && !this.can('wars')) return false; var currentWar = Clans.findWarFromRoom(room.id); if (!currentWar) return this.sendReply("No había ninguna war en curso en esta sala."); var currentWarData = Clans.getWarData(currentWar); if (toId(clanUser) !== toId(currentWar) && toId(clanUser) !== toId(currentWarData.against)) return this.sendReply("El usuario no pertenece a ninguno de los clanes que se están enfrentando en war."); var currentWarParticipants = Clans.getWarParticipants(currentWar); if (!currentWarParticipants.clanAMembers[toId(target)] && !currentWarParticipants.clanBMembers[toId(target)]) return this.sendReply("El Usuario no estaba inscrito en esta war."); if (currentWarData.warRound === 0) return this.sendReply("La War no ha empezado aún. No puedes usar este comando."); var clanBJoin = false; if (toId(clanUser) === toId(currentWarData.against)) clanBJoin = true; var matchupId = toId(target); if (!clanBJoin) { if (!currentWarParticipants.matchups[toId(target)] || currentWarParticipants.matchups[toId(target)].result > 1) return this.sendReply("El usuario no participaba en la war o ya había pasado a la siguiete ronda."); } else { var isParticipant = false; for (var g in currentWarParticipants.matchups) { if (toId(currentWarParticipants.matchups[g].to) === toId(target) && currentWarParticipants.matchups[g].result < 2) { isParticipant = true; matchupId = g; } } if (!isParticipant) return this.sendReply("El usuario no participaba en la war o ya había pasado a la siguiete ronda."); } if (!Clans.dqWarParticipant(currentWar, matchupId, clanBJoin)) { this.sendReply("El usuario no participaba en la war o ya había pasado a la siguiete ronda."); } else { var userk = Users.getExact(target); if (!userk) { this.addModCommand(target + " ha sido descalificado de la war por " + user.name + "."); } else { this.addModCommand(userk.name + " ha sido descalificado de la war por " + user.name + "."); } if (Clans.isWarEnded(currentWar)) { Clans.autoEndWar(currentWar); } } }, warinvalidate: function (target, room, user) { var permisionModWar = false; if (!target) return this.sendReply("No has especificado ningún usuario"); var clanUser = Clans.findClanFromMember(target); if (user.group === '@' || user.group === '&' || user.group === '~') permisionModWar = true; if (!clanUser) { return this.sendReply("El usuario no pertene a ningún clan."); } if (!permisionModWar && !this.can('wars')) return false; var currentWar = Clans.findWarFromRoom(room.id); if (!currentWar) return this.sendReply("No había ninguna war en curso en esta sala."); var currentWarData = Clans.getWarData(currentWar); if (toId(clanUser) !== toId(currentWar) && toId(clanUser) !== toId(currentWarData.against)) return this.sendReply("El usuario no pertenece a ninguno de los clanes que se están enfrentando en war."); var currentWarParticipants = Clans.getWarParticipants(currentWar); if (!currentWarParticipants.clanAMembers[toId(target)] && !currentWarParticipants.clanBMembers[toId(target)]) return this.sendReply("El Usuario no estaba inscrito en esta war."); if (currentWarData.warRound === 0) return this.sendReply("La War no ha empezado aún. No puedes usar este comando."); var clanBJoin = false; if (toId(clanUser) === toId(currentWarData.against)) clanBJoin = true; var matchupId = toId(target); if (!clanBJoin) { if (!currentWarParticipants.matchups[toId(target)] || currentWarParticipants.matchups[toId(target)].result === 0) return this.sendReply("El usuario no participaba o no había ningún resultado fijado para esta batalla de war."); } else { var isParticipant = false; for (var g in currentWarParticipants.matchups) { if (toId(currentWarParticipants.matchups[g].to) === toId(target) && currentWarParticipants.matchups[g].result > 0) { isParticipant = true; matchupId = g; } } if (!isParticipant) return this.sendReply("El usuario no participaba o no había ningún resultado fijado para esta batalla de war."); } if (!Clans.invalidateWarMatchup(currentWar, matchupId)) { this.sendReply("El usuario no participaba o no había ningún resultado fijado para esta batalla de war."); } else { var userk = Users.getExact(currentWarParticipants.matchups[matchupId].from); if (!userk) {userk = currentWarParticipants.matchups[matchupId].from;} else {userk = userk.name;} var userf = Users.getExact(currentWarParticipants.matchups[matchupId].to); if (!userf) {userf = currentWarParticipants.matchups[matchupId].to;} else {userf = userf.name;} this.addModCommand("La batalla entre " + userk + " y " + userf + " ha sido invalidada por " + user.name + "."); } }, wreplace: 'warreplace', warreplace: function (target, room, user) { var permisionModWar = false; var params = target.split(','); if (params.length !== 2) return this.sendReply("Usage: /wreplace usuario1, usuario2"); var clanUser = Clans.findClanFromMember(params[0]); if (user.group === '%' || user.group === '@' || user.group === '&' || user.group === '~') permisionModWar = true; if (!clanUser) { return this.sendReply("El usuario no pertene a ningún clan."); } if (Clans.authMember(clanUser, user.name) === 1 || Clans.authMember(clanUser, user.name) === 2) permisionModWar = true; if (!permisionModWar && !this.can('wars')) return false; var userh = Users.getExact(params[1]); if (!userh || !userh.connected) return this.sendReply("Usuario: " + params[1] + " no existe o no está disponible."); var clanTarget = Clans.findClanFromMember(params[1]); if (toId(clanTarget) !== toId(clanUser)) return this.sendReply("No puedes reemplazar por alguien de distinto clan."); var currentWar = Clans.findWarFromRoom(room.id); if (!currentWar) return this.sendReply("No había ninguna war en curso en esta sala."); var currentWarData = Clans.getWarData(currentWar); if (toId(clanUser) !== toId(currentWar) && toId(clanUser) !== toId(currentWarData.against)) return this.sendReply("El usuario no pertenece a ninguno de los clanes que se están enfrentando en war."); var currentWarParticipants = Clans.getWarParticipants(currentWar); if (!currentWarParticipants.clanAMembers[toId(params[0])] && !currentWarParticipants.clanBMembers[toId(params[0])]) return this.sendReply("El Usuario no estaba inscrito en esta war."); if (currentWarParticipants.clanAMembers[toId(params[1])] || currentWarParticipants.clanBMembers[toId(params[1])]) return this.sendReply("No puedes reemplazar por alguien que ya participaba en la war."); if (currentWarData.warRound === 0) return this.sendReply("La War no ha empezado aún. No puedes usar este comando."); var clanBJoin = false; if (toId(clanUser) === toId(currentWarData.against)) clanBJoin = true; var matchupId = toId(params[0]); if (!clanBJoin) { if (!currentWarParticipants.matchups[toId(params[0])] || currentWarParticipants.matchups[toId(params[0])].result !== 0) return this.sendReply("El usuario no participaba o ya había empezado su batalla."); } else { var isParticipant = false; for (var g in currentWarParticipants.matchups) { if (toId(currentWarParticipants.matchups[g].to) === toId(params[0]) && currentWarParticipants.matchups[g].result === 0) { isParticipant = true; matchupId = g; } } if (!isParticipant) return this.sendReply("El usuario no participaba o ya había empezado su batalla."); } if (!Clans.replaceWarParticipant(currentWar, matchupId, params[1], clanBJoin)) { this.sendReply("El usuario no participaba o ya había empezado su batalla."); } else { var userk = Users.getExact(params[0]); if (!userk) {userk = params[0];} else {userk = userk.name;} var userf = Users.getExact(params[1]); if (!userf) {userf = params[1];} else {userf = userf.name;} this.addModCommand(user.name + ": " + userk + " es reemplazado por " + userf + "."); } }, finalizarwar: 'endwar', endwar: function (target, room, user) { var permisionCreateWar = false; if (user.group === '+' || user.group === '%' || user.group === '@' || user.group === '&' || user.group === '~') permisionCreateWar = true; //if (room.auth && room.auth[user.userid]) permisionCreateWar = true; if (!permisionCreateWar && !this.can('wars')) return false; var currentWar = Clans.findWarFromRoom(room.id); if (!currentWar) return this.sendReply("No había ninguna war en curso en esta sala."); var currentWarData = Clans.getWarData(currentWar); if (!Clans.endWar(currentWar)) { this.sendReply("No se pudo terminar la war de esta sala debido a un error."); } else { this.logModCommand(user.name + " ha cancelado la war entre los clanes " + Clans.getClanName(currentWar) + " y " + Clans.getClanName(currentWarData.against) + "."); Rooms.rooms[room.id].addRaw('<hr /><h2><font color="green">' + user.name + ' ha cancelado la War entre los clanes ' + Clans.getClanName(currentWar) + " y " + Clans.getClanName(currentWarData.against) + '. <br /><hr />'); } }, warlog: function (target, room, user) { var autoclan = false; if (!target) autoclan = true; if (!this.canBroadcast()) return false; var clan = Clans.getRating(target); if (!clan) { target = Clans.findClanFromMember(target); if (target) clan = Clans.getRating(target); } if (!clan && autoclan) { target = Clans.findClanFromMember(user.name); if (target) clan = Clans.getRating(target); } if (!clan) { this.sendReply("El clan especificado no existe o no está disponible."); return; } var f = new Date(); var dateWar = f.getDate() + '-' + f.getMonth() + ' ' + f.getHours() + 'h'; this.sendReply( "|raw| <center><big><big><b>Ultimas Wars del clan " + Tools.escapeHTML(Clans.getClanName(target)) + "</b></big></big> <br /><br />" + Clans.getWarLogTable(target) + '<br /> Fecha del servidor: ' + dateWar + '</center>' ); }, closeclanroom: function (target, room, user) { var permisionClan = false; var clanRoom = Clans.findClanFromRoom(room.id); if (!clanRoom) return this.sendReply("Esta no es una sala de Clan."); var clanUser = Clans.findClanFromMember(user.name); if (clanUser && toId(clanRoom) === toId(clanUser)) { var clanUserid = toId(clanUser); var iduserwrit = toId(user.name); var perminsionvalue = Clans.authMember(clanUserid, iduserwrit); if (perminsionvalue === 2) permisionClan = true; } if (!permisionClan && !this.can('clans')) return false; if (!Clans.closeRoom(room.id, clanRoom)) this.sendReply("Error al intentar cerrar la sala. Es posible que ya esté cerrada."); else { this.addModCommand("Esta sala ha sido cerrada a quienes no sean miembros de " + clanRoom + " por " + user.name); } }, openclanroom: function (target, room, user) { var permisionClan = false; var clanRoom = Clans.findClanFromRoom(room.id); if (!clanRoom) return this.sendReply("Esta no es una sala de Clan."); var clanUser = Clans.findClanFromMember(user.name); if (clanUser && toId(clanRoom) === toId(clanUser)) { var clanUserid = toId(clanUser); var iduserwrit = toId(user.name); var perminsionvalue = Clans.authMember(clanUserid, iduserwrit); if (perminsionvalue === 2) permisionClan = true; } if (!permisionClan && !this.can('clans')) return false; if (!Clans.openRoom(room.id, clanRoom)) this.sendReply("Error al intentar abrir la sala. Es posible que ya esté abierta."); else { this.addModCommand("Esta sala ha sido abierta a todos los usuarios por " + user.name); } }, rk: 'roomkick', roomkick: function (target, room, user, connection) { if (!target) return this.sendReply("Usage: /roomkick user"); if (user.locked || user.mutedRooms[room.id]) return this.sendReply("You cannot do this while unable to talk."); target = this.splitTarget(target, true); var targetUser = this.targetUser; var name = this.targetUsername; var userid = toId(name); if (!userid || !targetUser) return this.sendReply("User '" + name + "' does not exist."); if (!this.can('ban', targetUser, room)) return false; if (!Rooms.rooms[room.id].users[targetUser.userid]) { return this.sendReply("User " + this.targetUsername + " is not in the room " + room.id + "."); } this.addModCommand("" + targetUser.name + " was kicked from room " + room.id + " by " + user.name + "." + (target ? " (" + target + ")" : "")); this.add('|unlink|' + this.getLastIdOf(targetUser)); targetUser.leaveRoom(room.id); }, kickall: function (target, room, user, connection) { if (user.locked || user.mutedRooms[room.id]) return this.sendReply("You cannot do this while unable to talk."); if (!this.can('makeroom')) return false; var targetUser; for (var f in Rooms.rooms[room.id].users) { targetUser = Users.getExact(Rooms.rooms[room.id].users[f]); if (toId(targetUser.name) !== toId(user.name)) targetUser.leaveRoom(room.id); } this.addModCommand("" + user.name + " has kicked all users from room " + room.id + '.'); }, /********************************************************* * Shop commands *********************************************************/ tienda: 'shop', shop: function (target, room, user) { if (!this.canBroadcast()) return false; this.sendReplyBox( '<center><h3><b><u>Tienda de Viridian</u></b></h3><table border="1" cellspacing="0" cellpadding="3" target="_blank"><tbody>' + '<tr><th>Art&iacute;culo</th><th>Descripci&oacute;n</th><th>Coste</th></tr>' + '<tr><td>CustomTC</td><td>Compra una Tarjeta de Entrenador personalizada (a partir de código html). Contactar con un administrador si el código es muy largo para un solo mensaje.</td><td>10000</td></tr>' + '<tr><td>Chatroom</td><td>Compra una Sala de chat. Será pública o privada en función del motivo de su compra. Si se detecta spam de comandos / saturación del modlog será borrada.</td><td>8000</td></tr>' + '<tr><td>CustomAvatar</td><td>Compra un avatar personalizado. Preferiblemente debe ser una imagen de pequeñas dimensiones y acorde a las reglas del servidor. Contactar con un Admin para obtener este art&iacute;culo.</td><td>6000</td></tr>' + '<tr><td>TC</td><td>Compra una Tarjeta de entrenador básica. Con una Imagen modificable con /tcimage y una frase de entrenador modificable con /tcphrase</td><td>3000</td></tr>' + '<tr><td>Symbol</td><td>Compra el acceso al comado /customsymbol que permite elegir un símbolo (excepto staff) para aparecer en lo alto de la lista de usuarios.</td><td>3000</td></tr>' + '<tr><td>Avatar</td><td>Si ya tienes un avatar personaliado. Puedes cambiarlo por otro diferente. Contactar con un administrador para obtener este art&iacute;culo.</td><td>1000</td></tr>' + '<tr><td>Sprite</td><td>Añade la imagen de un Pokemon a tu TC Básica. Máximo 6. Se pueden cambiar los pokemon con el comando /tcpokemon</td><td>100</td></tr>' + '</tbody></table><br /> Para comprar un artículo usa el comando /buy (artículo)' + '<br /> Algunos artículos solo se pueden comprar contactando con un Administrador. Para más información usa /shophelp' + '</center>' ); }, ayudatienda: 'shophelp', shophelp: function () { if (!this.canBroadcast()) return false; this.sendReplyBox( "<center><h3><b><u>Tienda de Viridian</u></b></h3></center>" + "<b>Comandos Básicos:</b><br /><br />" + "/shop - Muestra los artículos de la tienda.<br />" + "/buy (artículo) - Compra un artículo de la tienda.<br />" + "/pd (user) - muestra los ahorros de un usuario.<br />" + "/donate (user), (money) - Dona una cantidad determinada a otro usuario.<br />" + "<br />" + "<b>Comandos Específicos:</b><br /><br />" + "/tc (user) - Muestra la tarjeta de entrenador de un usuario.<br />" + "/tcimage (link) - Cambia la imagen de la Tc.<br />" + "/tcphrase (text) - Cambia la frase de la Tc.<br />" + "/tcpokemon (pokemon1),(pokemon2)... - Cambia Los sprites de los pokemon de la Tc.<br />" + "/tchtml (html) - Modifica la Tarjeta de entrenador personalizada.<br />" + "/customsymbol (symbol) - Cambia el símbolo a uno personalizado, pero sin cambiar por ello el rango.<br />" + "/resetsymbol - Reestablece el símbolo por omisión.<br />" + "<br />" + "<b>Comandos Administrativos:</b><br /><br />" + "/givemoney (user), (pds) - Da una cantidad de Pds a un usuario.<br />" + "/removemoney (user), (pds) - Quita una cantidad de Pds a un usuario.<br />" + "/symbolpermision (user), (on/off) - Da o Quita el permiso para usar Custom Symbols.<br />" + "/removetc (user) - Elimina una tarjeta de entrenador.<br />" + "/setcustomtc (user), (on/off) - Establece el permiso para usar una Tc personalizada.<br />" + "/sethtmltc (user), (html) - Modifica la Tc personalizada de un usuario.<br />" ); }, comprar: 'buy', buy: function (target, room, user) { var params = target.split(','); var prize = 0; if (!params) return this.sendReply("Usage: /buy object"); var article = toId(params[0]); switch (article) { case 'customtc': prize = 10000; if (Shop.getUserMoney(user.name) < prize) return this.sendReply("No tienes suficiente dinero."); var tcUser = Shop.getTrainerCard(user.name); if (!tcUser) { Shop.giveTrainerCard(user.name); tcUser = Shop.getTrainerCard(user.name); } if (tcUser.customTC) return this.sendReply("Ya poseías este artículo."); Shop.setCustomTrainerCard(user.name, true); Shop.removeMoney(user.name, prize); return this.sendReply("Has comprado una Tarjeta de entreador personalizada. Consulta /shophelp para más información."); break; case 'tc': prize = 3000; if (Shop.getUserMoney(user.name) < prize) return this.sendReply("No tienes suficiente dinero."); var tcUser = Shop.getTrainerCard(user.name); if (tcUser) return this.sendReply("Ya poseías este artículo."); Shop.giveTrainerCard(user.name); Shop.removeMoney(user.name, prize); return this.sendReply("Has comprado una Tarjeta de Entrenador. Revisa /shophelp para saber como editarla."); break; case 'sprite': prize = 100; if (Shop.getUserMoney(user.name) < prize) return this.sendReply("No tienes suficiente dinero."); var tcUser = Shop.getTrainerCard(user.name); if (!tcUser) return this.sendReply("Necesitas comprar primero una Tarjeta de entrenador."); if (tcUser.nPokemon > 5) return this.sendReply("Ya tienes 6 Pokemon para tu tarjeta de entrenador."); if (tcUser.customTC) return this.sendReply("Tu tarjeta es Personalizada. Usa /tchtml pata modificarla."); Shop.nPokemonTrainerCard(user.name, tcUser.nPokemon + 1); Shop.removeMoney(user.name, prize); return this.sendReply("Has comprado un Sprite de un pokemon para tu TC. Revisa /shophelp para más información."); break; case 'chatroom': prize = 8000; if (Shop.getUserMoney(user.name) < prize) return this.sendReply("No tienes suficiente dinero."); if (params.length !== 2) return this.sendReply("Usa el comando así: /buy chatroom,[nombre]"); var id = toId(params[1]); if (Rooms.rooms[id]) return this.sendReply("La sala '" + params[1] + "' ya exsiste. Usa otro nombre."); if (Rooms.global.addChatRoom(params[1])) { if (!Rooms.rooms[id].auth) Rooms.rooms[id].auth = Rooms.rooms[id].chatRoomData.auth = {}; Rooms.rooms[id].auth[toId(user.name)] = '#'; if (Rooms.rooms[id].chatRoomData) Rooms.global.writeChatRoomData(); Shop.removeMoney(user.name, prize); return this.sendReply("La sala '" + params[1] + "' fue creada con éxito. Únete usando /join " + id); } return this.sendReply("No se pudo realizar la compra debido a un error al crear la sala '" + params[1] + "'."); break; case 'symbol': prize = 3000; if (Shop.getUserMoney(user.name) < prize) return this.sendReply("No tienes suficiente dinero."); if (Shop.symbolPermision(user.name)) return this.sendReply("Ya posees este artículo."); Shop.setSymbolPermision(user.name, true); Shop.removeMoney(user.name, prize); return this.sendReply("Has comprado el permiso para usar los comandos /customsymbol y /resetsymbol. Para más información consulta /shophelp."); break; case 'avatar': case 'customavatar': return this.sendReply("Para comprar este artículo dirígete a un administrador."); break; default: return this.sendReply("No has especificado ningún artículo válido."); } }, money: 'pd', pd: function (target, room, user) { var autoData = false; if (!target) autoData = true; if (!this.canBroadcast()) return false; var pds = 0; var userName = user.name; if (autoData) { pds = Shop.getUserMoney(user.name); } else { pds = Shop.getUserMoney(target); userName = toId(target); var userh = Users.getExact(target); if (userh) userName = userh.name; } this.sendReplyBox('Ahorros de <b>' + userName + '</b>: ' + pds + ' pd'); }, trainercard: 'tc', tc: function (target, room, user) { var autoData = false; if (!target) autoData = true; if (!this.canBroadcast()) return false; var pds = 0; var userName = user.name; var tcData = {}; if (autoData) { tcData = Shop.getTrainerCard(user.name); } else { tcData = Shop.getTrainerCard(target); userName = toId(target); var userh = Users.getExact(target); if (userh) userName = userh.name; } if (!tcData) return this.sendReply(userName + " no tenía ninguna tarjeta de entrenador."); if (tcData.customTC) return this.sendReplyBox(tcData.customHtml); var pokeData = '<hr />'; for (var t in tcData.pokemon) { pokeData += '<img src="http://play.pokemonshowdown.com/sprites/xyani/' + Tools.escapeHTML(Shop.getPokemonId(tcData.pokemon[t])) + '.gif" width="auto" /> &nbsp;'; } if (tcData.nPokemon === 0) pokeData = ''; this.sendReplyBox('<center><h2>' + userName + '</h2><img src="' + encodeURI(tcData.image) + '" width="80" height="80" title="' + userName + '" /><br /><br /><b>"' + Tools.escapeHTML(tcData.phrase) + '"</b>' + pokeData + '</center>'); }, givemoney: function (target, room, user) { var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /givemoney usuario, pds"); if (!this.can('givemoney')) return false; var pds = parseInt(params[1]); if (pds <= 0) return this.sendReply("La cantidad no es valida."); var userh = Users.getExact(params[0]); if (!userh || !userh.connected) return this.sendReply("El usuario no existe o no está disponible"); var userName = userh.name; if (!Shop.giveMoney(params[0], pds)) { this.sendReply("Error desconocido."); } else { this.sendReply(userName + ' ha recibido ' + pds + ' pd'); } }, removemoney: function (target, room, user) { var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /removemoney usuario, pds"); if (!this.can('givemoney')) return false; var pds = parseInt(params[1]); if (pds <= 0) return this.sendReply("La cantidad no es valida."); var userh = Users.getExact(params[0]); var userName = toId(params[0]); if (userh) userName = userh.name; if (!Shop.removeMoney(params[0], pds)) { this.sendReply("El usuario no tenía suficientes Pds."); } else { this.sendReply(userName + ' ha perdido ' + pds + ' pd'); } }, donar: 'donate', donate: function (target, room, user) { var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /donate usuario, pds"); var pds = parseInt(params[1]); if (pds <= 0) return this.sendReply("La cantidad no es valida."); var userh = Users.getExact(params[0]); if (!userh || !userh.connected) return this.sendReply("El usuario no existe o no está disponible"); var userName = userh.name; if (!Shop.transferMoney(user.name, params[0], pds)) { this.sendReply("No tienes suficientes pds."); } else { this.sendReply('Has donado ' + pds + ' pd al usuario ' + userName + '.'); } }, symbolpermision: function (target, room, user) { if (!this.can('givemoney')) return false; var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /symbolpermision usuario, [on/off]"); var permision = false; if (toId(params[1]) !== 'on' && toId(params[1]) !== 'off') return this.sendReply("Usage: /symbolpermision usuario, [on/off]"); if (toId(params[1]) === 'on') permision = true; if (permision) { var userh = Users.getExact(params[0]); if (!userh || !userh.connected) return this.sendReply("El usuario no existe o no está disponible"); if (Shop.setSymbolPermision(params[0], permision)) return this.sendReply("Permiso para customsymbols concedido a " + userh.name); return this.sendReply("El usuario ya poseía permiso para usar los customsymbols."); } else { if (Shop.setSymbolPermision(params[0], permision)) return this.sendReply("Permiso para customsymbols retirado a " + params[0]); return this.sendReply("El usuario no tenía ningún permiso que quitar."); } }, simbolo: 'customsymbol', customsymbol: function (target, room, user) { if (!Shop.symbolPermision(user.name)) return this.sendReply('Debes comprar este comando en la tienda para usarlo.'); if (!target || target.length > 1) return this.parse('/help customsymbol'); if (target.match(/[A-Za-z\d]+/g) || '‽!+%@\u2605&~#'.indexOf(target) >= 0) return this.sendReply('Lo sentimos, pero no puedes cambiar el símbolo al que has escogido por razones de seguridad/estabilidad.'); user.getIdentity = function (roomid) { if (!roomid) roomid = 'lobby'; var name = this.name; if (this.locked) { return '‽' + name; } if (this.mutedRooms[roomid]) { return '!' + name; } var room = Rooms.rooms[roomid]; if (room.auth) { if (room.auth[this.userid]) { return room.auth[this.userid] + name; } if (room.isPrivate) return ' ' + name; } return target + name; }; user.updateIdentity(); user.hasCustomSymbol = true; }, resetsymbol: function (target, room, user) { if (!user.hasCustomSymbol) return this.sendReply('No tienes nigún simbolo personalizado.'); user.getIdentity = function (roomid) { if (!roomid) roomid = 'lobby'; var name = this.name; if (this.locked) { return '‽' + name; } if (this.mutedRooms[roomid]) { return '!' + name; } var room = Rooms.rooms[roomid]; if (room.auth) { if (room.auth[this.userid]) { return room.auth[this.userid] + name; } if (room.isPrivate) return ' ' + name; } return this.group + name; }; user.hasCustomSymbol = false; user.updateIdentity(); this.sendReply('Tu simbolo se ha restablecido.'); }, removetc: function (target, room, user) { if (!this.can('givemoney')) return false; if (!target) return this.sendReply("Usage: /removetc usuario"); if (Shop.removeTrainerCard(target)) { return this.sendReply("Tarjeta de entrenador del usuario " + toId(target) + ' eliminada.'); } else { return this.sendReply("El usuario no poseía Tc."); } }, setcustomtc: function (target, room, user) { if (!this.can('givemoney')) return false; var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /setcustomtc usuario, [on/off]"); var permision = false; if (toId(params[1]) !== 'on' && toId(params[1]) !== 'off') return this.sendReply("Usage: /setcustomtc usuario, [on/off]"); if (toId(params[1]) === 'on') permision = true; if (permision) { var userh = Users.getExact(params[0]); if (!userh || !userh.connected) return this.sendReply("El usuario no existe o no está disponible"); if (Shop.setCustomTrainerCard(params[0], permision)) return this.sendReply("Permiso para customtrainercards concedido a " + userh.name); return this.sendReply("El usuario no poseía Tc o ya tenía el permiso para customtrainercards."); } else { if (Shop.setCustomTrainerCard(params[0], permision)) return this.sendReply("Permiso para customtrainercards retirado a " + params[0]); return this.sendReply("El usuario no poseía Tc o no tenía el permiso para customtrainercards."); } }, tcimage: function (target, room, user) { if (!target) return this.sendReply("Usage: /tcimage link"); var tcData = Shop.getTrainerCard(user.name); if (!tcData) return this.sendReply("No posees ninguna tarjeta de entrenador."); if (tcData.customTC) return this.sendReply("Tu tarjeta es personalizada. usa /tchtml para cambiarla."); if (target.length > 120) return this.sendReply("El enlace es demasiado largo."); if (Shop.imageTrainerCard(user.name, target)) { return this.sendReply("Imagen de la TC cambiada con éxito."); } else { return this.sendReply("Error al cambiar la imagen de la TC."); } }, tcphrase: function (target, room, user) { if (!target) return this.sendReply("Usage: /tcphrase text"); var tcData = Shop.getTrainerCard(user.name); if (!tcData) return this.sendReply("No posees ninguna tarjeta de entrenador."); if (tcData.customTC) return this.sendReply("Tu tarjeta es personalizada. usa /tchtml para cambiarla."); if (target.length > 120) return this.sendReply("La frase es muy larga."); if (Shop.phraseTrainerCard(user.name, target)) { return this.sendReply("Frase de la TC cambiada con éxito."); } else { return this.sendReply("Error al cambiar la frase de la TC."); } }, tcpokemon: function (target, room, user) { if (!target) return this.sendReply("Usage: /tcpokemon [Pokemon1], [Pokemon2]..."); var params = target.split(','); var tcData = Shop.getTrainerCard(user.name); if (!tcData) return this.sendReply("No posees ninguna tarjeta de entrenador."); if (tcData.customTC) return this.sendReply("Tu tarjeta es personalizada. usa /tchtml para cambiarla."); if (params.length > tcData.nPokemon) return this.sendReply("Has especificado más Pokemon de los que has comprado."); var pokemonList = {}; var pokemonId = ''; for (var h in params) { pokemonId = Tools.escapeHTML(params[h]); if (pokemonId.length > 20) return this.sendReply("Alguno de los nombres de los Pokemon era muy largo."); pokemonList[h] = pokemonId; } if (Shop.pokemonTrainerCard(user.name, pokemonList)) { return this.sendReply("Los pokemon de la Tc han sido modificados."); } else { return this.sendReply("Error al cambiar los pokemon de la TC."); } }, tchtml: 'tccustom', tccustom: function (target, room, user) { if (!target) return this.sendReply("Usage: /tccustom html"); var tcData = Shop.getTrainerCard(user.name); if (!tcData) return this.sendReply("No posees ninguna tarjeta de entrenador."); if (!tcData.customTC) return this.sendReply("Tu tarjeta no es personalizada."); if (target.length > 1000) return this.sendReply("Tu código es demasiado largo. Contacta con un administrador para modificar la TC custom."); var targetABS = Shop.deleteValues(target); if (Shop.htmlTrainerCard(user.name, targetABS)) { return this.sendReply("La tarjeta de entrenador personalizada ha sido modificada."); } else { return this.sendReply("Error al cambiar los datos."); } }, sethtmltc: function (target, room, user) { if (!this.can('givemoney')) return false; var params = target.split(','); if (!params || params.length < 2) return this.sendReply("Usage: /sethtmltc usuario, html"); var tcData = Shop.getTrainerCard(params[0]); if (!tcData) return this.sendReply("El usuario no posee ninguna tarjeta de entrenador."); if (!tcData.customTC) return this.sendReply("La tarjeta no es personalizada."); var targetABS = Shop.deleteValues(target.substr(params[0].length + 1)); if (Shop.htmlTrainerCard(params[0], targetABS)) { return this.sendReply("La tarjeta de entrenador personalizada ha sido modificada."); } else { return this.sendReply("Error al cambiar los datos."); } }, /********************************************************* * Help commands *********************************************************/ commands: 'help', h: 'help', '?': 'help', help: function (target, room, user) { target = target.toLowerCase(); var roomType = room.auth ? room.type + 'Room' : 'global'; var matched = false; if (target === 'all' || target === 'msg' || target === 'pm' || target === 'whisper' || target === 'w') { matched = true; this.sendReply("/msg OR /whisper OR /w [username], [message] - Send a private message."); } if (target === 'all' || target === 'r' || target === 'reply') { matched = true; this.sendReply("/reply OR /r [message] - Send a private message to the last person you received a message from, or sent a message to."); } if (target === 'all' || target === 'rating' || target === 'ranking' || target === 'rank' || target === 'ladder') { matched = true; this.sendReply("/rating - Get your own rating."); this.sendReply("/rating [username] - Get user's rating."); } if (target === 'all' || target === 'nick') { matched = true; this.sendReply("/nick [new username] - Change your username."); } if (target === 'all' || target === 'avatar') { matched = true; this.sendReply("/avatar [new avatar number] - Change your trainer sprite."); } if (target === 'all' || target === 'whois' || target === 'alts' || target === 'ip' || target === 'rooms') { matched = true; this.sendReply("/whois - Get details on yourself: alts, group, IP address, and rooms."); this.sendReply("/whois [username] - Get details on a username: alts (Requires: % @ & ~), group, IP address (Requires: @ & ~), and rooms."); } if (target === 'all' || target === 'data') { matched = true; this.sendReply("/data [pokemon/item/move/ability] - Get details on this pokemon/item/move/ability/nature."); this.sendReply("!data [pokemon/item/move/ability] - Show everyone these details. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'details' || target === 'dt') { matched = true; this.sendReply("/details [pokemon] - Get additional details on this pokemon/item/move/ability/nature."); this.sendReply("!details [pokemon] - Show everyone these details. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'analysis') { matched = true; this.sendReply("/analysis [pokemon], [generation] - Links to the Smogon University analysis for this Pokemon in the given generation."); this.sendReply("!analysis [pokemon], [generation] - Shows everyone this link. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'groups') { matched = true; this.sendReply("/groups - Explains what the " + Config.groups[roomType + 'ByRank'].filter(function (g) { return g.trim(); }).join(" ") + " next to people's names mean."); this.sendReply("!groups - Show everyone that information. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'opensource') { matched = true; this.sendReply("/opensource - Links to PS's source code repository."); this.sendReply("!opensource - Show everyone that information. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'avatars') { matched = true; this.sendReply("/avatars - Explains how to change avatars."); this.sendReply("!avatars - Show everyone that information. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'intro') { matched = true; this.sendReply("/intro - Provides an introduction to competitive pokemon."); this.sendReply("!intro - Show everyone that information. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'cap') { matched = true; this.sendReply("/cap - Provides an introduction to the Create-A-Pokemon project."); this.sendReply("!cap - Show everyone that information. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'om') { matched = true; this.sendReply("/om - Provides links to information on the Other Metagames."); this.sendReply("!om - Show everyone that information. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'learn' || target === 'learnset' || target === 'learnall') { matched = true; this.sendReply("/learn [pokemon], [move, move, ...] - Displays how a Pokemon can learn the given moves, if it can at all."); this.sendReply("!learn [pokemon], [move, move, ...] - Show everyone that information. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'calc' || target === 'calculator') { matched = true; this.sendReply("/calc - Provides a link to a damage calculator"); this.sendReply("!calc - Shows everyone a link to a damage calculator. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'blockchallenges' || target === 'away' || target === 'idle') { matched = true; this.sendReply("/away - Blocks challenges so no one can challenge you. Deactivate it with /back."); } if (target === 'all' || target === 'allowchallenges' || target === 'back') { matched = true; this.sendReply("/back - Unlocks challenges so you can be challenged again. Deactivate it with /away."); } if (target === 'all' || target === 'faq') { matched = true; this.sendReply("/faq [theme] - Provides a link to the FAQ. Add deviation, doubles, randomcap, restart, or staff for a link to these questions. Add all for all of them."); this.sendReply("!faq [theme] - Shows everyone a link to the FAQ. Add deviation, doubles, randomcap, restart, or staff for a link to these questions. Add all for all of them. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'highlight') { matched = true; this.sendReply("Set up highlights:"); this.sendReply("/highlight add, word - add a new word to the highlight list."); this.sendReply("/highlight list - list all words that currently highlight you."); this.sendReply("/highlight delete, word - delete a word from the highlight list."); this.sendReply("/highlight delete - clear the highlight list"); } if (target === 'all' || target === 'timestamps') { matched = true; this.sendReply("Set your timestamps preference:"); this.sendReply("/timestamps [all|lobby|pms], [minutes|seconds|off]"); this.sendReply("all - change all timestamps preferences, lobby - change only lobby chat preferences, pms - change only PM preferences"); this.sendReply("off - set timestamps off, minutes - show timestamps of the form [hh:mm], seconds - show timestamps of the form [hh:mm:ss]"); } if (target === 'all' || target === 'effectiveness' || target === 'matchup' || target === 'eff' || target === 'type') { matched = true; this.sendReply("/effectiveness OR /matchup OR /eff OR /type [attack], [defender] - Provides the effectiveness of a move or type on another type or a Pokémon."); this.sendReply("!effectiveness OR !matchup OR !eff OR !type [attack], [defender] - Shows everyone the effectiveness of a move or type on another type or a Pokémon."); } if (target === 'all' || target === 'dexsearch' || target === 'dsearch' || target === 'ds') { matched = true; this.sendReply("/dexsearch [type], [move], [move], ... - Searches for Pokemon that fulfill the selected criteria."); this.sendReply("Search categories are: type, tier, color, moves, ability, gen."); this.sendReply("Valid colors are: green, red, blue, white, brown, yellow, purple, pink, gray and black."); this.sendReply("Valid tiers are: Uber/OU/BL/UU/BL2/RU/BL3/NU/LC/CAP."); this.sendReply("Types must be followed by ' type', e.g., 'dragon type'."); this.sendReply("Parameters can be excluded through the use of '!', e.g., '!water type' excludes all water types."); this.sendReply("The parameter 'mega' can be added to search for Mega Evolutions only, and the parameters 'FE' or 'NFE' can be added to search fully or not-fully evolved Pokemon only."); this.sendReply("The order of the parameters does not matter."); } if (target === 'all' || target === 'dice' || target === 'roll') { matched = true; this.sendReply("/dice [optional max number] - Randomly picks a number between 1 and 6, or between 1 and the number you choose."); this.sendReply("/dice [number of dice]d[number of sides] - Simulates rolling a number of dice, e.g., /dice 2d4 simulates rolling two 4-sided dice."); } if (target === 'all' || target === 'pick' || target === 'pickrandom') { matched = true; this.sendReply("/pick [option], [option], ... - Randomly selects an item from a list containing 2 or more elements."); } if (target === 'all' || target === 'join') { matched = true; this.sendReply("/join [roomname] - Attempts to join the room [roomname]."); } if (target === 'all' || target === 'ignore') { matched = true; this.sendReply("/ignore [user] - Ignores all messages from the user [user]."); this.sendReply("Note that staff messages cannot be ignored."); } if (target === 'all' || target === 'invite') { matched = true; this.sendReply("/invite [username], [roomname] - Invites the player [username] to join the room [roomname]."); } if (Users.can(target, 'lock') || target === 'lock' || target === 'l') { matched = true; this.sendReply("/lock OR /l [username], [reason] - Locks the user from talking in all chats. Requires: " + Users.getGroupsThatCan('lock', room).join(" ")); } if (Users.can(target, 'lock') || target === 'unlock') { matched = true; this.sendReply("/unlock [username] - Unlocks the user. Requires: " + Users.getGroupsThatCan('lock', room).join(" ")); } if (Users.can(target, 'redirect') || target === 'redirect' || target === 'redir') { matched = true; this.sendReply("/redirect or /redir [username], [roomname] - Attempts to redirect the user [username] to the room [roomname]. Requires: " + Users.getGroupsThatCan('redirect', room).join(" ")); } if (Users.can(target, 'staff') || target === 'modnote') { matched = true; this.sendReply("/modnote [note] - Adds a moderator note that can be read through modlog. Requires: " + Users.getGroupsThatCan('staff', room).join(" ")); } if (Users.can(target, 'forcerename') || target === 'forcerename' || target === 'fr') { matched = true; this.sendReply("/forcerename OR /fr [username], [reason] - Forcibly change a user's name and shows them the [reason]. Requires: " + Users.getGroupsThatCan('forcerename').join(" ")); } if (Users.can(target, 'ban') || target === 'roomban') { matched = true; this.sendReply("/roomban [username] - Bans the user from the room you are in. Requires: " + Users.getGroupsThatCan('ban', room).join(" ")); } if (Users.can(target, 'ban') || target === 'roomunban') { matched = true; this.sendReply("/roomunban [username] - Unbans the user from the room you are in. Requires: " + Users.getGroupsThatCan('ban', room).join(" ")); } if (Users.can(target, 'ban') || target === 'ban') { matched = true; this.sendReply("/ban OR /b [username], [reason] - Kick user from all rooms and ban user's IP address with reason. Requires: " + Users.getGroupsThatCan('ban').join(" ")); } if (Users.can(target, 'roompromote') || target === 'roompromote') { matched = true; this.sendReply("/roompromote [username], [group] - Promotes the user to the specified group or next ranked group. Requires: " + Users.getGroupsThatCan('roompromote', room).join(" ")); } if (Users.can(target, 'roompromote') || target === 'roomdemote') { matched = true; this.sendReply("/roomdemote [username], [group] - Demotes the user to the specified group or previous ranked group. Requires: " + Users.getGroupsThatCan('roompromote', room).join(" ")); } if (Users.can(target, 'rangeban') || target === 'banip') { matched = true; this.sendReply("/banip [ip] - Kick users on this IP or IP range from all rooms and bans it. Accepts wildcards to ban ranges. Requires: " + Users.getGroupsThatCan('rangeban').join(" ")); } if (Users.can(target, 'rangeban') || target === 'unbanip') { matched = true; this.sendReply("/unbanip [ip] - Kick users on this IP or IP range from all rooms and bans it. Accepts wildcards to ban ranges. Requires: " + Users.getGroupsThatCan('rangeban').join(" ")); } if (Users.can(target, 'ban') || target === 'unban') { matched = true; this.sendReply("/unban [username] - Unban a user. Requires: " + Users.getGroupsThatCan('ban').join(" ")); } if (Users.can(target, 'ban') || target === 'unbanall') { matched = true; this.sendReply("/unbanall - Unban all IP addresses. Requires: " + Users.getGroupsThatCan('ban').join(" ")); } if (Users.can(target, 'staff') || target === 'modlog') { matched = true; this.sendReply("/modlog [roomid|all], [n] - Roomid defaults to current room. If n is a number or omitted, display the last n lines of the moderator log. Defaults to 15. If n is not a number, search the moderator log for 'n' on room's log [roomid]. If you set [all] as [roomid], searches for 'n' on all rooms's logs. Requires: " + Users.getGroupsThatCan('staff', room).join(" ")); } if (Users.can(target, 'kick') || target === 'kickbattle ') { matched = true; this.sendReply("/kickbattle [username], [reason] - Kicks a user from a battle with reason. Requires: " + Users.getGroupsThatCan('kick').join(" ")); } if (Users.can(target, 'warn') || target === 'warn' || target === 'k') { matched = true; this.sendReply("/warn OR /k [username], [reason] - Warns a user showing them the Pokemon Showdown Rules and [reason] in an overlay. Requires: " + Users.getGroupsThatCan('warn', room).join(" ")); } if (Users.can(target, 'mute') || target === 'mute' || target === 'm') { matched = true; this.sendReply("/mute OR /m [username], [reason] - Mutes a user with reason for 7 minutes. Requires: " + Users.getGroupsThatCan('mute', room).join(" ")); } if (Users.can(target, 'mute') || target === 'hourmute' || target === 'hm') { matched = true; this.sendReply("/hourmute OR /hm [username], [reason] - Mutes a user with reason for an hour. Requires: " + Users.getGroupsThatCan('mute', room).join(" ")); } if (Users.can(target, 'mute') || target === 'unmute' || target === 'um') { matched = true; this.sendReply("/unmute [username] - Removes mute from user. Requires: " + Users.getGroupsThatCan('mute', room).join(" ")); } if (Users.can(target, 'promote') || target === 'promote') { matched = true; this.sendReply("/promote [username], [group] - Promotes the user to the specified group or next ranked group. Requires: " + Users.getGroupsThatCan('promote').join(" ")); } if (Users.can(target, 'promote') || target === 'demote') { matched = true; this.sendReply("/demote [username], [group] - Demotes the user to the specified group or previous ranked group. Requires: " + Users.getGroupsThatCan('promote').join(" ")); } if (Users.can(target, 'forcewin') || target === 'forcetie') { matched = true; this.sendReply("/forcetie - Forces the current match to tie. Requires: " + Users.getGroupsThatCan('forcewin').join(" ")); } if (Users.can(target, 'declare') || target === 'showimage') { matched = true; this.sendReply("/showimage [url], [width], [height] - Show an image. Requires: " + Users.getGroupsThatCan('declare', room).join(" ")); } if (Users.can(target, 'declare') || target === 'declare') { matched = true; this.sendReply("/declare [message] - Anonymously announces a message. Requires: " + Users.getGroupsThatCan('declare', room).join(" ")); } if (Users.can(target, 'gdeclare') || target === 'chatdeclare' || target === 'cdeclare') { matched = true; this.sendReply("/cdeclare [message] - Anonymously announces a message to all chatrooms on the server. Requires: " + Users.getGroupsThatCan('gdeclare').join(" ")); } if (Users.can(target, 'gdeclare') || target === 'globaldeclare' || target === 'gdeclare') { matched = true; this.sendReply("/globaldeclare [message] - Anonymously announces a message to every room on the server. Requires: " + Users.getGroupsThatCan('gdeclare').join(" ")); } if (target === '~' || target === 'htmlbox') { matched = true; this.sendReply("/htmlbox [message] - Displays a message, parsing HTML code contained. Requires: ~ # with global authority"); } if (Users.can(target, 'announce') || target === 'announce' || target === 'wall') { matched = true; this.sendReply("/announce OR /wall [message] - Makes an announcement. Requires: " + Users.getGroupsThatCan('announce', room).join(" ")); } if (Users.can(target, 'modchat') || target === 'modchat') { matched = true; this.sendReply("/modchat [off/autoconfirmed/" + Config.groups[roomType + 'ByRank'].filter(function (g) { return g.trim(); }).join("/") + "] - Set the level of moderated chat. Requires: " + Users.getGroupsThatCan('modchat', room).join(" ") + " for off/autoconfirmed/" + Config.groups[roomType + 'ByRank'].slice(0, 2).filter(function (g) { return g.trim(); }).join("/") + " options, " + Users.getGroupsThatCan('modchatall', room).join(" ") + " for all the options"); } if (Users.can(target, 'hotpatch') || target === 'hotpatch') { matched = true; this.sendReply("Hot-patching the game engine allows you to update parts of Showdown without interrupting currently-running battles. Requires: " + Users.getGroupsThatCan('hotpatch').join(" ")); this.sendReply("Hot-patching has greater memory requirements than restarting."); this.sendReply("/hotpatch chat - reload chat-commands.js"); this.sendReply("/hotpatch battles - spawn new simulator processes"); this.sendReply("/hotpatch formats - reload the tools.js tree, rebuild and rebroad the formats list, and also spawn new simulator processes"); } if (Users.can(target, 'lockdown') || target === 'lockdown') { matched = true; this.sendReply("/lockdown - locks down the server, which prevents new battles from starting so that the server can eventually be restarted. Requires: " + Users.getGroupsThatCan('lockdown').join(" ")); } if (Users.can(target, 'lockdown') || target === 'kill') { matched = true; this.sendReply("/kill - kills the server. Can't be done unless the server is in lockdown state. Requires: " + Users.getGroupsThatCan('lockdown').join(" ")); } if (Users.can(target, 'hotpatch') || target === 'loadbanlist') { matched = true; this.sendReply("/loadbanlist - Loads the bans located at ipbans.txt. The command is executed automatically at startup. Requires: " + Users.getGroupsThatCan('hotpatch').join(" ")); } if (Users.can(target, 'makeroom') || target === 'makechatroom') { matched = true; this.sendReply("/makechatroom [roomname] - Creates a new room named [roomname]. Requires: " + Users.getGroupsThatCan('makeroom').join(" ")); } if (Users.can(target, 'makeroom') || target === 'deregisterchatroom') { matched = true; this.sendReply("/deregisterchatroom [roomname] - Deletes room [roomname] after the next server restart. Requires: " + Users.getGroupsThatCan('makeroom').join(" ")); } if (Users.can(target, 'roompromote', Config.groups[roomType + 'ByRank'].slice(-1)[0]) || target === 'roomowner') { matched = true; this.sendReply("/roomowner [username] - Appoints [username] as a room owner. Removes official status. Requires: " + Users.getGroupsThatCan('roompromote', Config.groups[roomType + 'ByRank'].slice(-1)[0]).join(" ")); } if (Users.can(target, 'roompromote', Config.groups[roomType + 'ByRank'].slice(-1)[0]) || target === 'roomdeowner') { matched = true; this.sendReply("/roomdeowner [username] - Removes [username]'s status as a room owner. Requires: " + Users.getGroupsThatCan('roompromote', Config.groups[roomType + 'ByRank'].slice(-1)[0]).join(" ")); } if (Users.can(target, 'privateroom') || target === 'privateroom') { matched = true; this.sendReply("/privateroom [on/off] - Makes or unmakes a room private. Requires: " + Users.getGroupsThatCan('privateroom', room).join(" ")); } if (target === 'all' || target === 'help' || target === 'h' || target === '?' || target === 'commands') { matched = true; this.sendReply("/help OR /h OR /? - Gives you help."); } if (!target) { this.sendReply("COMMANDS: /nick, /avatar, /rating, /whois, /msg, /reply, /ignore, /away, /back, /timestamps, /highlight"); this.sendReply("INFORMATIONAL COMMANDS: /data, /dexsearch, /groups, /opensource, /avatars, /faq, /rules, /intro, /tiers, /othermetas, /learn, /analysis, /calc (replace / with ! to broadcast. (Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ") + "))"); this.sendReply("For details on all room commands, use /roomhelp"); this.sendReply("For details on all commands, use /help all"); if (user.group !== Config.groups.default[roomType]) { this.sendReply("DRIVER COMMANDS: /warn, /mute, /unmute, /alts, /forcerename, /modlog, /lock, /unlock, /announce, /redirect"); this.sendReply("MODERATOR COMMANDS: /ban, /unban, /ip"); this.sendReply("LEADER COMMANDS: /declare, /forcetie, /forcewin, /promote, /demote, /banip, /unbanall"); this.sendReply("For details on all moderator commands, use /help " + Users.getGroupsThatCan('staff', room)[0]); } this.sendReply("For details of a specific command, use something like: /help data"); } else if (!matched) { this.sendReply("The command '" + target + "' was not found. Try /help for general help"); } }, };
config/commands.js
/** * Commands * Pokemon Showdown - https://pokemonshowdown.com/ * * These are commands. For instance, you can define the command 'whois' * here, then use it by typing /whois into Pokemon Showdown. * * A command can be in the form: * ip: 'whois', * This is called an alias: it makes it so /ip does the same thing as * /whois. * * But to actually define a command, it's a function: * * allowchallenges: function (target, room, user) { * user.blockChallenges = false; * this.sendReply("You are available for challenges from now on."); * } * * Commands are actually passed five parameters: * function (target, room, user, connection, cmd, message) * Most of the time, you only need the first three, though. * * target = the part of the message after the command * room = the room object the message was sent to * The room name is room.id * user = the user object that sent the message * The user's name is user.name * connection = the connection that the message was sent from * cmd = the name of the command * message = the entire message sent by the user * * If a user types in "/msg zarel, hello" * target = "zarel, hello" * cmd = "msg" * message = "/msg zarel, hello" * * Commands return the message the user should say. If they don't * return anything or return something falsy, the user won't say * anything. * * Commands have access to the following functions: * * this.sendReply(message) * Sends a message back to the room the user typed the command into. * * this.sendReplyBox(html) * Same as sendReply, but shows it in a box, and you can put HTML in * it. * * this.popupReply(message) * Shows a popup in the window the user typed the command into. * * this.add(message) * Adds a message to the room so that everyone can see it. * This is like this.sendReply, except everyone in the room gets it, * instead of just the user that typed the command. * * this.send(message) * Sends a message to the room so that everyone can see it. * This is like this.add, except it's not logged, and users who join * the room later won't see it in the log, and if it's a battle, it * won't show up in saved replays. * You USUALLY want to use this.add instead. * * this.logEntry(message) * Log a message to the room's log without sending it to anyone. This * is like this.add, except no one will see it. * * this.addModCommand(message) * Like this.add, but also logs the message to the moderator log * which can be seen with /modlog. * * this.logModCommand(message) * Like this.addModCommand, except users in the room won't see it. * * this.can(permission) * this.can(permission, targetUser) * Checks if the user has the permission to do something, or if a * targetUser is passed, check if the user has permission to do * it to that user. Will automatically give the user an "Access * denied" message if the user doesn't have permission: use * user.can() if you don't want that message. * * Should usually be near the top of the command, like: * if (!this.can('potd')) return false; * * this.canBroadcast() * Signifies that a message can be broadcast, as long as the user * has permission to. This will check to see if the user used * "!command" instead of "/command". If so, it will check to see * if the user has permission to broadcast (by default, voice+ can), * and return false if not. Otherwise, it will add the message to * the room, and turn on the flag this.broadcasting, so that * this.sendReply and this.sendReplyBox will broadcast to the room * instead of just the user that used the command. * * Should usually be near the top of the command, like: * if (!this.canBroadcast()) return false; * * this.canBroadcast(suppressMessage) * Functionally the same as this.canBroadcast(). However, it * will look as if the user had written the text suppressMessage. * * this.canTalk() * Checks to see if the user can speak in the room. Returns false * if the user can't speak (is muted, the room has modchat on, etc), * or true otherwise. * * Should usually be near the top of the command, like: * if (!this.canTalk()) return false; * * this.canTalk(message, room) * Checks to see if the user can say the message in the room. * If a room is not specified, it will default to the current one. * If it has a falsy value, the check won't be attached to any room. * In addition to running the checks from this.canTalk(), it also * checks to see if the message has any banned words, is too long, * or was just sent by the user. Returns the filtered message, or a * falsy value if the user can't speak. * * Should usually be near the top of the command, like: * target = this.canTalk(target); * if (!target) return false; * * this.parse(message) * Runs the message as if the user had typed it in. * * Mostly useful for giving help messages, like for commands that * require a target: * if (!target) return this.parse('/help msg'); * * After 10 levels of recursion (calling this.parse from a command * called by this.parse from a command called by this.parse etc) * we will assume it's a bug in your command and error out. * * this.targetUserOrSelf(target, exactName) * If target is blank, returns the user that sent the message. * Otherwise, returns the user with the username in target, or * a falsy value if no user with that username exists. * By default, this will track users across name changes. However, * if exactName is true, it will enforce exact matches. * * this.getLastIdOf(user) * Returns the last userid of an specified user. * * this.splitTarget(target, exactName) * Splits a target in the form "user, message" into its * constituent parts. Returns message, and sets this.targetUser to * the user, and this.targetUsername to the username. * By default, this will track users across name changes. However, * if exactName is true, it will enforce exact matches. * * Remember to check if this.targetUser exists before going further. * * Unless otherwise specified, these functions will return undefined, * so you can return this.sendReply or something to send a reply and * stop the command there. * * @license MIT license */ var commands = exports.commands = { ip: 'whois', rooms: 'whois', alt: 'whois', alts: 'whois', whois: function (target, room, user) { var targetUser = this.targetUserOrSelf(target, user.group === Config.groups.default.global); if (!targetUser) { return this.sendReply("User " + this.targetUsername + " not found."); } this.sendReply("User: " + targetUser.name); if (user.can('alts', targetUser)) { var alts = targetUser.getAlts(); var output = Object.keys(targetUser.prevNames).join(", "); if (output) this.sendReply("Previous names: " + output); for (var j = 0; j < alts.length; ++j) { var targetAlt = Users.get(alts[j]); if (!targetAlt.named && !targetAlt.connected) continue; if (Config.groups.bySymbol[targetAlt.group] && Config.groups.bySymbol[user.group] && Config.groups.bySymbol[targetAlt.group].rank > Config.groups.bySymbol[user.group].rank) continue; this.sendReply("Alt: " + targetAlt.name); output = Object.keys(targetAlt.prevNames).join(", "); if (output) this.sendReply("Previous names: " + output); } } if (Config.groups.bySymbol[targetUser.group] && Config.groups.bySymbol[targetUser.group].name) { this.sendReply("Group: " + Config.groups.bySymbol[targetUser.group].name + " (" + targetUser.group + ")"); } if (targetUser.isSysop) { this.sendReply("(Pok\xE9mon Showdown System Operator)"); } if (!targetUser.authenticated) { this.sendReply("(Unregistered)"); } if (!this.broadcasting && (user.can('ip', targetUser) || user === targetUser)) { var ips = Object.keys(targetUser.ips); this.sendReply("IP" + ((ips.length > 1) ? "s" : "") + ": " + ips.join(", ")); this.sendReply("Host: " + targetUser.latestHost); } var output = "In rooms: "; var first = true; for (var i in targetUser.roomCount) { if (i === 'global' || Rooms.get(i).isPrivate) continue; if (!first) output += " | "; first = false; output += '<a href="/' + i + '" room="' + i + '">' + i + '</a>'; } this.sendReply('|raw|' + output); }, ipsearch: function (target, room, user) { if (!this.can('rangeban')) return; var atLeastOne = false; this.sendReply("Users with IP " + target + ":"); for (var userid in Users.users) { var curUser = Users.users[userid]; if (curUser.latestIp === target) { this.sendReply((curUser.connected ? " + " : "-") + " " + curUser.name); atLeastOne = true; } } if (!atLeastOne) this.sendReply("No results found."); }, /********************************************************* * Shortcuts *********************************************************/ invite: function (target, room, user) { target = this.splitTarget(target); if (!this.targetUser) { return this.sendReply("User " + this.targetUsername + " not found."); } var roomid = (target || room.id); if (!Rooms.get(roomid)) { return this.sendReply("Room " + roomid + " not found."); } return this.parse('/msg ' + this.targetUsername + ', /invite ' + roomid); }, /********************************************************* * Informational commands *********************************************************/ pstats: 'data', stats: 'data', dex: 'data', pokedex: 'data', details: 'data', dt: 'data', data: function (target, room, user, connection, cmd) { if (!this.canBroadcast()) return; var buffer = ''; var targetId = toId(target); var newTargets = Tools.dataSearch(target); var showDetails = (cmd === 'dt' || cmd === 'details'); if (newTargets && newTargets.length) { for (var i = 0; i < newTargets.length; ++i) { if (newTargets[i].id !== targetId && !Tools.data.Aliases[targetId] && !i) { buffer = "No Pokemon, item, move, ability or nature named '" + target + "' was found. Showing the data of '" + newTargets[0].name + "' instead.\n"; } if (newTargets[i].searchType === 'nature') { buffer += "" + newTargets[i].name + " nature: "; if (newTargets[i].plus) { var statNames = {'atk': "Attack", 'def': "Defense", 'spa': "Special Attack", 'spd': "Special Defense", 'spe': "Speed"}; buffer += "+10% " + statNames[newTargets[i].plus] + ", -10% " + statNames[newTargets[i].minus] + "."; } else { buffer += "No effect."; } return this.sendReply(buffer); } else { buffer += '|c|~|/data-' + newTargets[i].searchType + ' ' + newTargets[i].name + '\n'; } } } else { return this.sendReply("No Pokemon, item, move, ability or nature named '" + target + "' was found. (Check your spelling?)"); } if (showDetails) { var details; if (newTargets[0].searchType === 'pokemon') { var pokemon = Tools.getTemplate(newTargets[0].name); var weighthit = 20; if (pokemon.weightkg >= 200) { weighthit = 120; } else if (pokemon.weightkg >= 100) { weighthit = 100; } else if (pokemon.weightkg >= 50) { weighthit = 80; } else if (pokemon.weightkg >= 25) { weighthit = 60; } else if (pokemon.weightkg >= 10) { weighthit = 40; } details = { "Dex#": pokemon.num, "Height": pokemon.heightm + " m", "Weight": pokemon.weightkg + " kg <em>(" + weighthit + " BP)</em>", "Dex Colour": pokemon.color, "Egg Group(s)": pokemon.eggGroups.join(", ") }; if (!pokemon.evos.length) { details["<font color=#585858>Does Not Evolve</font>"] = ""; } else { details["Evolution"] = pokemon.evos.map(function (evo) { evo = Tools.getTemplate(evo); return evo.name + " (" + evo.evoLevel + ")"; }).join(", "); } } else if (newTargets[0].searchType === 'move') { var move = Tools.getMove(newTargets[0].name); details = { "Priority": move.priority, }; if (move.secondary || move.secondaries) details["<font color=black>&#10003; Secondary Effect</font>"] = ""; if (move.isContact) details["<font color=black>&#10003; Contact</font>"] = ""; if (move.isSoundBased) details["<font color=black>&#10003; Sound</font>"] = ""; if (move.isBullet) details["<font color=black>&#10003; Bullet</font>"] = ""; if (move.isPulseMove) details["<font color=black>&#10003; Pulse</font>"] = ""; details["Target"] = { 'normal': "Adjacent Pokemon", 'self': "Self", 'adjacentAlly': "Single Ally", 'allAdjacentFoes': "Adjacent Foes", 'foeSide': "All Foes", 'allySide': "All Allies", 'allAdjacent': "All Adjacent Pokemon", 'any': "Any Pokemon", 'all': "All Pokemon" }[move.target] || "Unknown"; } else if (newTargets[0].searchType === 'item') { var item = Tools.getItem(newTargets[0].name); details = {}; if (item.fling) { details["Fling Base Power"] = item.fling.basePower; if (item.fling.status) details["Fling Effect"] = item.fling.status; if (item.fling.volatileStatus) details["Fling Effect"] = item.fling.volatileStatus; if (item.isBerry) details["Fling Effect"] = "Activates effect of berry on target."; if (item.id === 'whiteherb') details["Fling Effect"] = "Removes all negative stat levels on the target."; if (item.id === 'mentalherb') details["Fling Effect"] = "Removes the effects of infatuation, Taunt, Encore, Torment, Disable, and Cursed Body on the target."; } if (!item.fling) details["Fling"] = "This item cannot be used with Fling"; if (item.naturalGift) { details["Natural Gift Type"] = item.naturalGift.type; details["Natural Gift BP"] = item.naturalGift.basePower; } } else { details = {}; } buffer += '|raw|<font size="1">' + Object.keys(details).map(function (detail) { return '<font color=#585858>' + detail + (details[detail] !== '' ? ':</font> ' + details[detail] : '</font>'); }).join("&nbsp;|&ThickSpace;") + '</font>'; } this.sendReply(buffer); }, ds: 'dexsearch', dsearch: 'dexsearch', dexsearch: function (target, room, user) { if (!this.canBroadcast()) return; if (!target) return this.parse('/help dexsearch'); var targets = target.split(','); var searches = {}; var allTiers = {'uber':1, 'ou':1, 'uu':1, 'lc':1, 'cap':1, 'bl':1, 'bl2':1, 'ru':1, 'bl3':1, 'nu':1}; var allColours = {'green':1, 'red':1, 'blue':1, 'white':1, 'brown':1, 'yellow':1, 'purple':1, 'pink':1, 'gray':1, 'black':1}; var showAll = false; var megaSearch = null; var feSearch = null; // search for fully evolved pokemon only var output = 10; for (var i in targets) { var isNotSearch = false; target = targets[i].trim().toLowerCase(); if (target.slice(0, 1) === '!') { isNotSearch = true; target = target.slice(1); } var targetAbility = Tools.getAbility(targets[i]); if (targetAbility.exists) { if (!searches['ability']) searches['ability'] = {}; if (Object.count(searches['ability'], true) === 1 && !isNotSearch) return this.sendReplyBox("Specify only one ability."); if ((searches['ability'][targetAbility.name] && isNotSearch) || (searches['ability'][targetAbility.name] === false && !isNotSearch)) return this.sendReplyBox("A search cannot both exclude and include an ability."); searches['ability'][targetAbility.name] = !isNotSearch; continue; } if (target in allTiers) { if (!searches['tier']) searches['tier'] = {}; if ((searches['tier'][target] && isNotSearch) || (searches['tier'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a tier.'); searches['tier'][target] = !isNotSearch; continue; } if (target in allColours) { if (!searches['color']) searches['color'] = {}; if ((searches['color'][target] && isNotSearch) || (searches['color'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a color.'); searches['color'][target] = !isNotSearch; continue; } var targetInt = parseInt(target); if (0 < targetInt && targetInt < 7) { if (!searches['gen']) searches['gen'] = {}; if ((searches['gen'][target] && isNotSearch) || (searches['gen'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a generation.'); searches['gen'][target] = !isNotSearch; continue; } if (target === 'all') { if (this.broadcasting) { return this.sendReplyBox("A search with the parameter 'all' cannot be broadcast."); } showAll = true; continue; } if (target === 'megas' || target === 'mega') { if ((megaSearch && isNotSearch) || (megaSearch === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include Mega Evolutions.'); megaSearch = !isNotSearch; continue; } if (target === 'fe' || target === 'fullyevolved' || target === 'nfe' || target === 'notfullyevolved') { if (target === 'nfe' || target === 'notfullyevolved') isNotSearch = !isNotSearch; if ((feSearch && isNotSearch) || (feSearch === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include fully evolved Pokémon.'); feSearch = !isNotSearch; continue; } var targetMove = Tools.getMove(target); if (targetMove.exists) { if (!searches['moves']) searches['moves'] = {}; if (Object.count(searches['moves'], true) === 4 && !isNotSearch) return this.sendReplyBox("Specify a maximum of 4 moves."); if ((searches['moves'][targetMove.name] && isNotSearch) || (searches['moves'][targetMove.name] === false && !isNotSearch)) return this.sendReplyBox("A search cannot both exclude and include a move."); searches['moves'][targetMove.name] = !isNotSearch; continue; } if (target.indexOf(' type') > -1) { target = target.charAt(0).toUpperCase() + target.slice(1, target.indexOf(' type')); if (target in Tools.data.TypeChart) { if (!searches['types']) searches['types'] = {}; if (Object.count(searches['types'], true) === 2 && !isNotSearch) return this.sendReplyBox("Specify a maximum of two types."); if ((searches['types'][target] && isNotSearch) || (searches['types'][target] === false && !isNotSearch)) return this.sendReplyBox("A search cannot both exclude and include a type."); searches['types'][target] = !isNotSearch; continue; } } return this.sendReplyBox("'" + Tools.escapeHTML(target) + "' could not be found in any of the search categories."); } if (showAll && Object.size(searches) === 0 && megaSearch === null && feSearch === null) return this.sendReplyBox("No search parameters other than 'all' were found. Try '/help dexsearch' for more information on this command."); var dex = {}; for (var pokemon in Tools.data.Pokedex) { var template = Tools.getTemplate(pokemon); var megaSearchResult = (megaSearch === null || (megaSearch === true && template.isMega) || (megaSearch === false && !template.isMega)); var feSearchResult = (feSearch === null || (feSearch === true && !template.evos.length) || (feSearch === false && template.evos.length)); if (template.tier !== 'Unreleased' && template.tier !== 'Illegal' && (template.tier !== 'CAP' || (searches['tier'] && searches['tier']['cap'])) && megaSearchResult && feSearchResult) { dex[pokemon] = template; } } for (var search in {'moves':1, 'types':1, 'ability':1, 'tier':1, 'gen':1, 'color':1}) { if (!searches[search]) continue; switch (search) { case 'types': for (var mon in dex) { if (Object.count(searches[search], true) === 2) { if (!(searches[search][dex[mon].types[0]]) || !(searches[search][dex[mon].types[1]])) delete dex[mon]; } else { if (searches[search][dex[mon].types[0]] === false || searches[search][dex[mon].types[1]] === false || (Object.count(searches[search], true) > 0 && (!(searches[search][dex[mon].types[0]]) && !(searches[search][dex[mon].types[1]])))) delete dex[mon]; } } break; case 'tier': for (var mon in dex) { if ('lc' in searches[search]) { // some LC legal Pokemon are stored in other tiers (Ferroseed/Murkrow etc) // this checks for LC legality using the going criteria, instead of dex[mon].tier var isLC = (dex[mon].evos && dex[mon].evos.length > 0) && !dex[mon].prevo && Tools.data.Formats['lc'].banlist.indexOf(dex[mon].species) === -1; if ((searches[search]['lc'] && !isLC) || (!searches[search]['lc'] && isLC)) { delete dex[mon]; continue; } } if (searches[search][String(dex[mon][search]).toLowerCase()] === false) { delete dex[mon]; } else if (Object.count(searches[search], true) > 0 && !searches[search][String(dex[mon][search]).toLowerCase()]) delete dex[mon]; } break; case 'gen': case 'color': for (var mon in dex) { if (searches[search][String(dex[mon][search]).toLowerCase()] === false) { delete dex[mon]; } else if (Object.count(searches[search], true) > 0 && !searches[search][String(dex[mon][search]).toLowerCase()]) delete dex[mon]; } break; case 'ability': for (var mon in dex) { for (var ability in searches[search]) { var needsAbility = searches[search][ability]; var hasAbility = Object.count(dex[mon].abilities, ability) > 0; if (hasAbility !== needsAbility) { delete dex[mon]; break; } } } break; case 'moves': for (var mon in dex) { var template = Tools.getTemplate(dex[mon].id); if (!template.learnset) template = Tools.getTemplate(template.baseSpecies); if (!template.learnset) continue; for (var i in searches[search]) { var move = Tools.getMove(i); if (!move.exists) return this.sendReplyBox("'" + move + "' is not a known move."); var prevoTemp = Tools.getTemplate(template.id); while (prevoTemp.prevo && prevoTemp.learnset && !(prevoTemp.learnset[move.id])) { prevoTemp = Tools.getTemplate(prevoTemp.prevo); } var canLearn = (prevoTemp.learnset.sketch && !(move.id in {'chatter':1, 'struggle':1, 'magikarpsrevenge':1})) || prevoTemp.learnset[move.id]; if ((!canLearn && searches[search][i]) || (searches[search][i] === false && canLearn)) delete dex[mon]; } } break; default: return this.sendReplyBox("Something broke! PM TalkTakesTime here or on the Smogon forums with the command you tried."); } } var results = Object.keys(dex).map(function (speciesid) {return dex[speciesid].species;}); results = results.filter(function (species) { var template = Tools.getTemplate(species); return !(species !== template.baseSpecies && results.indexOf(template.baseSpecies) > -1); }); var resultsStr = ""; if (results.length > 0) { if (showAll || results.length <= output) { results.sort(); resultsStr = results.join(", "); } else { results.randomize(); resultsStr = results.slice(0, 10).join(", ") + ", and " + string(results.length - output) + " more. Redo the search with 'all' as a search parameter to show all results."; } } else { resultsStr = "No Pokémon found."; } return this.sendReplyBox(resultsStr); }, learnset: 'learn', learnall: 'learn', learn5: 'learn', g6learn: 'learn', learn: function (target, room, user, connection, cmd) { if (!target) return this.parse('/help learn'); if (!this.canBroadcast()) return; var lsetData = {set:{}}; var targets = target.split(','); var template = Tools.getTemplate(targets[0]); var move = {}; var problem; var all = (cmd === 'learnall'); if (cmd === 'learn5') lsetData.set.level = 5; if (cmd === 'g6learn') lsetData.format = {noPokebank: true}; if (!template.exists) { return this.sendReply("Pokemon '" + template.id + "' not found."); } if (targets.length < 2) { return this.sendReply("You must specify at least one move."); } for (var i = 1, len = targets.length; i < len; ++i) { move = Tools.getMove(targets[i]); if (!move.exists) { return this.sendReply("Move '" + move.id + "' not found."); } problem = TeamValidator.checkLearnsetSync(null, move, template, lsetData); if (problem) break; } var buffer = template.name + (problem ? " <span class=\"message-learn-cannotlearn\">can't</span> learn " : " <span class=\"message-learn-canlearn\">can</span> learn ") + (targets.length > 2 ? "these moves" : move.name); if (!problem) { var sourceNames = {E:"egg", S:"event", D:"dream world"}; if (lsetData.sources || lsetData.sourcesBefore) buffer += " only when obtained from:<ul class=\"message-learn-list\">"; if (lsetData.sources) { var sources = lsetData.sources.sort(); var prevSource; var prevSourceType; var prevSourceCount = 0; for (var i = 0, len = sources.length; i < len; ++i) { var source = sources[i]; if (source.substr(0, 2) === prevSourceType) { if (prevSourceCount < 0) { buffer += ": " + source.substr(2); } else if (all || prevSourceCount < 3) { buffer += ", " + source.substr(2); } else if (prevSourceCount === 3) { buffer += ", ..."; } ++prevSourceCount; continue; } prevSourceType = source.substr(0, 2); prevSourceCount = source.substr(2) ? 0 : -1; buffer += "<li>gen " + source.substr(0, 1) + " " + sourceNames[source.substr(1, 1)]; if (prevSourceType === '5E' && template.maleOnlyHidden) buffer += " (cannot have hidden ability)"; if (source.substr(2)) buffer += ": " + source.substr(2); } } if (lsetData.sourcesBefore) buffer += "<li>any generation before " + (lsetData.sourcesBefore + 1); buffer += "</ul>"; } this.sendReplyBox(buffer); }, weak: 'weakness', resist: 'weakness', weakness: function (target, room, user){ if (!this.canBroadcast()) return; var targets = target.split(/[ ,\/]/); var pokemon = Tools.getTemplate(target); var type1 = Tools.getType(targets[0]); var type2 = Tools.getType(targets[1]); if (pokemon.exists) { target = pokemon.species; } else if (type1.exists && type2.exists) { pokemon = {types: [type1.id, type2.id]}; target = type1.id + "/" + type2.id; } else if (type1.exists) { pokemon = {types: [type1.id]}; target = type1.id; } else { return this.sendReplyBox("" + Tools.escapeHTML(target) + " isn't a recognized type or pokemon."); } var weaknesses = []; var resistances = []; var immunities = []; Object.keys(Tools.data.TypeChart).forEach(function (type) { var notImmune = Tools.getImmunity(type, pokemon); if (notImmune) { var typeMod = Tools.getEffectiveness(type, pokemon); switch (typeMod) { case 1: weaknesses.push(type); break; case 2: weaknesses.push("<b>" + type + "</b>"); break; case -1: resistances.push(type); break; case -2: resistances.push("<b>" + type + "</b>"); break; } } else { immunities.push(type); } }); var buffer = []; buffer.push(pokemon.exists ? "" + target + ' (ignoring abilities):' : '' + target + ':'); buffer.push('<span class=\"message-effect-weak\">Weaknesses</span>: ' + (weaknesses.join(', ') || 'None')); buffer.push('<span class=\"message-effect-resist\">Resistances</span>: ' + (resistances.join(', ') || 'None')); buffer.push('<span class=\"message-effect-immune\">Immunities</span>: ' + (immunities.join(', ') || 'None')); this.sendReplyBox(buffer.join('<br>')); }, eff: 'effectiveness', type: 'effectiveness', matchup: 'effectiveness', effectiveness: function (target, room, user) { var targets = target.split(/[,/]/).slice(0, 2); if (targets.length !== 2) return this.sendReply("Attacker and defender must be separated with a comma."); var searchMethods = {'getType':1, 'getMove':1, 'getTemplate':1}; var sourceMethods = {'getType':1, 'getMove':1}; var targetMethods = {'getType':1, 'getTemplate':1}; var source; var defender; var foundData; var atkName; var defName; for (var i = 0; i < 2; ++i) { var method; for (method in searchMethods) { foundData = Tools[method](targets[i]); if (foundData.exists) break; } if (!foundData.exists) return this.parse('/help effectiveness'); if (!source && method in sourceMethods) { if (foundData.type) { source = foundData; atkName = foundData.name; } else { source = foundData.id; atkName = foundData.id; } searchMethods = targetMethods; } else if (!defender && method in targetMethods) { if (foundData.types) { defender = foundData; defName = foundData.species + " (not counting abilities)"; } else { defender = {types: [foundData.id]}; defName = foundData.id; } searchMethods = sourceMethods; } } if (!this.canBroadcast()) return; var factor = 0; if (Tools.getImmunity(source.type || source, defender)) { if (source.effectType !== 'Move' || source.basePower || source.basePowerCallback) { factor = Math.pow(2, Tools.getEffectiveness(source, defender)); } else { factor = 1; } } this.sendReplyBox("" + atkName + " is " + factor + "x effective against " + defName + "."); }, uptime: function (target, room, user) { if (!this.canBroadcast()) return; var uptime = process.uptime(); var uptimeText; if (uptime > 24 * 60 * 60) { var uptimeDays = Math.floor(uptime / (24 * 60 * 60)); uptimeText = uptimeDays + " " + (uptimeDays === 1 ? "day" : "days"); var uptimeHours = Math.floor(uptime / (60 * 60)) - uptimeDays * 24; if (uptimeHours) uptimeText += ", " + uptimeHours + " " + (uptimeHours === 1 ? "hour" : "hours"); } else { uptimeText = uptime.seconds().duration(); } this.sendReplyBox("Uptime: <b>" + uptimeText + "</b>"); }, groups: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox(Config.groups.byRank.reduce(function (info, group) { if (!Config.groups.bySymbol[group].name || !Config.groups.bySymbol[group].description) return info; return info + (info ? "<br />" : "") + Tools.escapeHTML(group) + " <strong>" + Tools.escapeHTML(Config.groups.bySymbol[group].name) + "</strong> - " + Tools.escapeHTML(Config.groups.bySymbol[group].description); }, "")); }, git: 'opensource', opensource: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "Pokemon Showdown is open source:<br />" + "- Language: JavaScript (Node.js)<br />" + "- <a href=\"https://github.com/Zarel/Pokemon-Showdown/commits/master\">What's new?</a><br />" + "- <a href=\"https://github.com/Zarel/Pokemon-Showdown\">Server source code</a><br />" + "- <a href=\"https://github.com/Zarel/Pokemon-Showdown-Client\">Client source code</a>" ); }, staff: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox("<a href=\"https://www.smogon.com/sim/staff_list\">Pokemon Showdown Staff List</a>"); }, avatars: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('You can <button name="avatars">change your avatar</button> by clicking on it in the <button name="openOptions"><i class="icon-cog"></i> Options</button> menu in the upper right. Custom avatars are only obtainable by staff.'); }, showtan: function (target, room, user) { if (room.id !== 'showderp') return this.sendReply("The command '/showtan' was unrecognized. To send a message starting with '/showtan', type '//showtan'."); if (!this.can('showtan', room)) return; target = this.splitTarget(target); if (!this.targetUser) return this.sendReply('user not found'); if (!room.users[this.targetUser.userid]) return this.sendReply('not a showderper'); this.targetUser.avatar = '#showtan'; room.add(user.name+' applied showtan to affected area of '+this.targetUser.name); }, introduction: 'intro', intro: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "New to competitive pokemon?<br />" + "- <a href=\"https://www.smogon.com/sim/ps_guide\">Beginner's Guide to Pokémon Showdown</a><br />" + "- <a href=\"https://www.smogon.com/dp/articles/intro_comp_pokemon\">An introduction to competitive Pokémon</a><br />" + "- <a href=\"https://www.smogon.com/bw/articles/bw_tiers\">What do 'OU', 'UU', etc mean?</a><br />" + "- <a href=\"https://www.smogon.com/xyhub/tiers\">What are the rules for each format? What is 'Sleep Clause'?</a>" ); }, mentoring: 'smogintro', smogonintro: 'smogintro', smogintro: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "Welcome to Smogon's official simulator! Here are some useful links to <a href=\"https://www.smogon.com/mentorship/\">Smogon\'s Mentorship Program</a> to help you get integrated into the community:<br />" + "- <a href=\"https://www.smogon.com/mentorship/primer\">Smogon Primer: A brief introduction to Smogon's subcommunities</a><br />" + "- <a href=\"https://www.smogon.com/mentorship/introductions\">Introduce yourself to Smogon!</a><br />" + "- <a href=\"https://www.smogon.com/mentorship/profiles\">Profiles of current Smogon Mentors</a><br />" + "- <a href=\"http://mibbit.com/#[email protected]\">#mentor: the Smogon Mentorship IRC channel</a>" ); }, calculator: 'calc', calc: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "Pokemon Showdown! damage calculator. (Courtesy of Honko)<br />" + "- <a href=\"https://pokemonshowdown.com/damagecalc/\">Damage Calculator</a>" ); }, cap: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "An introduction to the Create-A-Pokemon project:<br />" + "- <a href=\"https://www.smogon.com/cap/\">CAP project website and description</a><br />" + "- <a href=\"https://www.smogon.com/forums/showthread.php?t=48782\">What Pokemon have been made?</a><br />" + "- <a href=\"https://www.smogon.com/forums/showthread.php?t=3464513\">Talk about the metagame here</a><br />" + "- <a href=\"https://www.smogon.com/forums/showthread.php?t=3466826\">Practice BW CAP teams</a>" ); }, gennext: function (target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox( "NEXT (also called Gen-NEXT) is a mod that makes changes to the game:<br />" + "- <a href=\"https://github.com/Zarel/Pokemon-Showdown/blob/master/mods/gennext/README.md\">README: overview of NEXT</a><br />" + "Example replays:<br />" + "- <a href=\"https://replay.pokemonshowdown.com/gennextou-120689854\">Zergo vs Mr Weegle Snarf</a><br />" + "- <a href=\"https://replay.pokemonshowdown.com/gennextou-130756055\">NickMP vs Khalogie</a>" ); }, om: 'othermetas', othermetas: function (target, room, user) { if (!this.canBroadcast()) return; target = toId(target); var buffer = ""; var matched = false; if (!target || target === 'all') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/forums/206/\">Other Metagames Forum</a><br />"; if (target !== 'all') { buffer += "- <a href=\"https://www.smogon.com/forums/threads/3505031/\">Other Metagames Index</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3507466/\">Sample teams for entering Other Metagames</a><br />"; } } if (target === 'all' || target === 'omofthemonth' || target === 'omotm' || target === 'month') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3481155/\">OM of the Month</a><br />"; } if (target === 'all' || target === 'pokemonthrowback' || target === 'throwback') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3510401/\">Pokémon Throwback</a><br />"; } if (target === 'all' || target === 'balancedhackmons' || target === 'bh') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3489849/\">Balanced Hackmons</a><br />"; if (target !== 'all') { buffer += "- <a href=\"https://www.smogon.com/forums/threads/3499973/\">Balanced Hackmons Mentoring Program</a><br />"; } } if (target === 'all' || target === '1v1') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3496773/\">1v1</a><br />"; } if (target === 'all' || target === 'oumonotype' || target === 'monotype') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3493087/\">OU Monotype</a><br />"; if (target !== 'all') { buffer += "- <a href=\"https://www.smogon.com/forums/threads/3507565/\">OU Monotype Viability Rankings</a><br />"; } } if (target === 'all' || target === 'tiershift' || target === 'ts') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3508369/\">Tier Shift</a><br />"; } if (target === 'all' || target === 'almostanyability' || target === 'aaa') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3495737/\">Almost Any Ability</a><br />"; if (target !== 'all') { buffer += "- <a href=\"https://www.smogon.com/forums/threads/3508794/\">Almost Any Ability Viability Rankings</a><br />"; } } if (target === 'all' || target === 'stabmons') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3493081/\">STABmons</a><br />"; if (target !== 'all') { buffer += "- <a href=\"https://www.smogon.com/forums/threads/3512215/\">STABmons Viability Rankings</a><br />"; } } if (target === 'all' || target === 'skybattles' || target === 'skybattle') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3493601/\">Sky Battles</a><br />"; } if (target === 'all' || target === 'inversebattle' || target === 'inverse') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3492433/\">Inverse Battle</a><br />"; } if (target === 'all' || target === 'hackmons' || target === 'ph') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3500418/\">Hackmons</a><br />"; } if (target === 'all' || target === 'smogontriples' || target === 'triples') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3511522/\">Smogon Triples</a><br />"; } if (target === 'all' || target === 'alphabetcup') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3498167/\">Alphabet Cup</a><br />"; } if (target === 'all' || target === 'averagemons') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3495527/\">Averagemons</a><br />"; } if (target === 'all' || target === 'middlecup' || target === 'mc') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3494887/\">Middle Cup</a><br />"; } if (target === 'all' || target === 'glitchmons') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3467120/\">Glitchmons</a><br />"; } if (!matched) { return this.sendReply("The Other Metas entry '" + target + "' was not found. Try /othermetas or /om for general help."); } this.sendReplyBox(buffer); }, /*formats: 'formathelp', formatshelp: 'formathelp', formathelp: function (target, room, user) { if (!this.canBroadcast()) return; if (this.broadcasting && (room.id === 'lobby' || room.battle)) return this.sendReply("This command is too spammy to broadcast in lobby/battles"); var buf = []; var showAll = (target === 'all'); for (var id in Tools.data.Formats) { var format = Tools.data.Formats[id]; if (!format) continue; if (format.effectType !== 'Format') continue; if (!format.challengeShow) continue; if (!showAll && !format.searchShow) continue; buf.push({ name: format.name, gameType: format.gameType || 'singles', mod: format.mod, searchShow: format.searchShow, desc: format.desc || 'No description.' }); } this.sendReplyBox( "Available Formats: (<strong>Bold</strong> formats are on ladder.)<br />" + buf.map(function (data) { var str = ""; // Bold = Ladderable. str += (data.searchShow ? "<strong>" + data.name + "</strong>" : data.name) + ": "; str += "(" + (!data.mod || data.mod === 'base' ? "" : data.mod + " ") + data.gameType + " format) "; str += data.desc; return str; }).join("<br />") ); },*/ roomhelp: function (target, room, user) { if (room.id === 'lobby' || room.battle) return this.sendReply("This command is too spammy for lobby/battles."); if (!this.canBroadcast()) return; this.sendReplyBox( "Room drivers (%) can use:<br />" + "- /warn OR /k <em>username</em>: warn a user and show the Pokemon Showdown rules<br />" + "- /mute OR /m <em>username</em>: 7 minute mute<br />" + "- /hourmute OR /hm <em>username</em>: 60 minute mute<br />" + "- /unmute <em>username</em>: unmute<br />" + "- /announce OR /wall <em>message</em>: make an announcement<br />" + "- /modlog <em>username</em>: search the moderator log of the room<br />" + "- /modnote <em>note</em>: adds a moderator note that can be read through modlog<br />" + "<br />" + "Room moderators (@) can also use:<br />" + "- /roomban OR /rb <em>username</em>: bans user from the room<br />" + "- /roomunban <em>username</em>: unbans user from the room<br />" + "- /roomvoice <em>username</em>: appoint a room voice<br />" + "- /roomdevoice <em>username</em>: remove a room voice<br />" + "- /modchat <em>[off/autoconfirmed/+]</em>: set modchat level<br />" + "<br />" + "Room owners (#) can also use:<br />" + "- /roomintro <em>intro</em>: sets the room introduction that will be displayed for all users joining the room<br />" + "- /rules <em>rules link</em>: set the room rules link seen when using /rules<br />" + "- /roommod, /roomdriver <em>username</em>: appoint a room moderator/driver<br />" + "- /roomdemod, /roomdedriver <em>username</em>: remove a room moderator/driver<br />" + "- /modchat <em>[%/@/#]</em>: set modchat level<br />" + "- /declare <em>message</em>: make a large blue declaration to the room<br />" + "- !htmlbox <em>HTML code</em>: broadcasts a box of HTML code to the room<br />" + "- !showimage <em>[url], [width], [height]</em>: shows an image to the room<br />" + "</div>" ); }, restarthelp: function (target, room, user) { if (room.id === 'lobby' && !this.can('lockdown')) return false; if (!this.canBroadcast()) return; this.sendReplyBox( "The server is restarting. Things to know:<br />" + "- We wait a few minutes before restarting so people can finish up their battles<br />" + "- The restart itself will take around 0.6 seconds<br />" + "- Your ladder ranking and teams will not change<br />" + "- We are restarting to update Pokémon Showdown to a newer version" ); }, rule: 'rules', rules: function (target, room, user) { if (!target) { if (!this.canBroadcast()) return; this.sendReplyBox("Please follow the rules:<br />" + (room.rulesLink ? "- <a href=\"" + Tools.escapeHTML(room.rulesLink) + "\">" + Tools.escapeHTML(room.title) + " room rules</a><br />" : "") + "- <a href=\"https://pokemonshowdown.com/rules\">" + (room.rulesLink ? "Global rules" : "Rules") + "</a>"); return; } if (!this.can('declare', room)) return; if (target.length > 80) { return this.sendReply("Error: Room rules link is too long (must be under 80 characters). You can use a URL shortener to shorten the link."); } room.rulesLink = target.trim(); this.sendReply("(The room rules link is now: " + target + ")"); if (room.chatRoomData) { room.chatRoomData.rulesLink = room.rulesLink; Rooms.global.writeChatRoomData(); } }, faq: function (target, room, user) { if (!this.canBroadcast()) return; target = target.toLowerCase(); var buffer = ""; var matched = false; if (!target || target === 'all') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq\">Frequently Asked Questions</a><br />"; } if (target === 'all' || target === 'deviation') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#deviation\">Why did this user gain or lose so many points?</a><br />"; } if (target === 'all' || target === 'doubles' || target === 'triples' || target === 'rotation') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#doubles\">Can I play doubles/triples/rotation battles here?</a><br />"; } if (target === 'all' || target === 'randomcap') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#randomcap\">What is this fakemon and what is it doing in my random battle?</a><br />"; } if (target === 'all' || target === 'restarts') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/faq#restarts\">Why is the server restarting?</a><br />"; } if (target === 'all' || target === 'staff') { matched = true; buffer += "<a href=\"https://www.smogon.com/sim/staff_faq\">Staff FAQ</a><br />"; } if (target === 'all' || target === 'autoconfirmed' || target === 'ac') { matched = true; buffer += "A user is autoconfirmed when they have won at least one rated battle and have been registered for a week or longer.<br />"; } if (!matched) { return this.sendReply("The FAQ entry '" + target + "' was not found. Try /faq for general help."); } this.sendReplyBox(buffer); }, banlists: 'tiers', tier: 'tiers', tiers: function (target, room, user) { if (!this.canBroadcast()) return; target = toId(target); var buffer = ""; var matched = false; if (!target || target === 'all') { matched = true; buffer += "- <a href=\"https://www.smogon.com/tiers/\">Smogon Tiers</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/tiering-faq.3498332/\">Tiering FAQ</a><br />"; buffer += "- <a href=\"https://www.smogon.com/xyhub/tiers\">The banlists for each tier</a><br />"; } if (target === 'all' || target === 'ubers' || target === 'uber') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3496305/\">Ubers Viability Rankings</a><br />"; } if (target === 'all' || target === 'overused' || target === 'ou') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3511596/\">np: OU Stage 5</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3491371/\">OU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3502428/\">OU Viability Rankings</a><br />"; } if (target === 'all' || target === 'underused' || target === 'uu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3508311/\">np: UU Stage 2</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3502698/#post-5323505\">UU Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3500340/\">UU Viability Rankings</a><br />"; } if (target === 'all' || target === 'rarelyused' || target === 'ru') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3513684/\">np: RU Stage 3</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3506500/\">RU Viability Rankings</a><br />"; } if (target === 'all' || target === 'neverused' || target === 'nu') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3506287/\">np: NU (beta)</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3509494/\">NU Viability Rankings</a><br />"; } if (target === 'all' || target === 'littlecup' || target === 'lc') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3496013/\">LC Viability Rankings</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3490462/\">Official LC Banlist</a><br />"; } if (target === 'all' || target === 'doubles') { matched = true; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3509279/\">np: Doubles Stage 3.5</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3498688/\">Doubles Banlist</a><br />"; buffer += "- <a href=\"https://www.smogon.com/forums/threads/3496306/\">Doubles Viability Rankings</a><br />"; } if (!matched) { return this.sendReply("The Tiers entry '" + target + "' was not found. Try /tiers for general help."); } this.sendReplyBox(buffer); }, analysis: 'smogdex', strategy: 'smogdex', smogdex: function (target, room, user) { if (!this.canBroadcast()) return; var targets = target.split(','); if (toId(targets[0]) === 'previews') return this.sendReplyBox("<a href=\"https://www.smogon.com/forums/threads/sixth-generation-pokemon-analyses-index.3494918/\">Generation 6 Analyses Index</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); var pokemon = Tools.getTemplate(targets[0]); var item = Tools.getItem(targets[0]); var move = Tools.getMove(targets[0]); var ability = Tools.getAbility(targets[0]); var atLeastOne = false; var generation = (targets[1] || 'xy').trim().toLowerCase(); var genNumber = 6; // var doublesFormats = {'vgc2012':1, 'vgc2013':1, 'vgc2014':1, 'doubles':1}; var doublesFormats = {}; var doublesFormat = (!targets[2] && generation in doublesFormats)? generation : (targets[2] || '').trim().toLowerCase(); var doublesText = ''; if (generation === 'xy' || generation === 'xy' || generation === '6' || generation === 'six') { generation = 'xy'; } else if (generation === 'bw' || generation === 'bw2' || generation === '5' || generation === 'five') { generation = 'bw'; genNumber = 5; } else if (generation === 'dp' || generation === 'dpp' || generation === '4' || generation === 'four') { generation = 'dp'; genNumber = 4; } else if (generation === 'adv' || generation === 'rse' || generation === 'rs' || generation === '3' || generation === 'three') { generation = 'rs'; genNumber = 3; } else if (generation === 'gsc' || generation === 'gs' || generation === '2' || generation === 'two') { generation = 'gs'; genNumber = 2; } else if(generation === 'rby' || generation === 'rb' || generation === '1' || generation === 'one') { generation = 'rb'; genNumber = 1; } else { generation = 'xy'; } if (doublesFormat !== '') { // Smogon only has doubles formats analysis from gen 5 onwards. if (!(generation in {'bw':1, 'xy':1}) || !(doublesFormat in doublesFormats)) { doublesFormat = ''; } else { doublesText = {'vgc2012':"VGC 2012", 'vgc2013':"VGC 2013", 'vgc2014':"VGC 2014", 'doubles':"Doubles"}[doublesFormat]; doublesFormat = '/' + doublesFormat; } } // Pokemon if (pokemon.exists) { atLeastOne = true; if (genNumber < pokemon.gen) { return this.sendReplyBox("" + pokemon.name + " did not exist in " + generation.toUpperCase() + "!"); } // if (pokemon.tier === 'CAP') generation = 'cap'; if (pokemon.tier === 'CAP') return this.sendReply("CAP is not currently supported by Smogon Strategic Pokedex."); var illegalStartNums = {'351':1, '421':1, '487':1, '493':1, '555':1, '647':1, '648':1, '649':1, '681':1}; if (pokemon.isMega || pokemon.num in illegalStartNums) pokemon = Tools.getTemplate(pokemon.baseSpecies); var poke = pokemon.name.toLowerCase().replace(/\ /g, '_').replace(/[^a-z0-9\-\_]+/g, ''); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/pokemon/" + poke + doublesFormat + "\">" + generation.toUpperCase() + " " + doublesText + " " + pokemon.name + " analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } // Item if (item.exists && genNumber > 1 && item.gen <= genNumber) { atLeastOne = true; var itemName = item.name.toLowerCase().replace(' ', '_'); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/items/" + itemName + "\">" + generation.toUpperCase() + " " + item.name + " item analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } // Ability if (ability.exists && genNumber > 2 && ability.gen <= genNumber) { atLeastOne = true; var abilityName = ability.name.toLowerCase().replace(' ', '_'); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/abilities/" + abilityName + "\">" + generation.toUpperCase() + " " + ability.name + " ability analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } // Move if (move.exists && move.gen <= genNumber) { atLeastOne = true; var moveName = move.name.toLowerCase().replace(' ', '_'); this.sendReplyBox("<a href=\"https://www.smogon.com/dex/" + generation + "/moves/" + moveName + "\">" + generation.toUpperCase() + " " + move.name + " move analysis</a>, brought to you by <a href=\"https://www.smogon.com\">Smogon University</a>"); } if (!atLeastOne) { return this.sendReplyBox("Pokemon, item, move, or ability not found for generation " + generation.toUpperCase() + "."); } }, /********************************************************* * Miscellaneous commands *********************************************************/ potd: function (target, room, user) { if (!this.can('potd')) return false; Config.potd = target; Simulator.SimulatorProcess.eval('Config.potd = \'' + toId(target) + '\''); if (target) { if (Rooms.lobby) Rooms.lobby.addRaw("<div class=\"broadcast-blue\"><b>The Pokemon of the Day is now " + target + "!</b><br />This Pokemon will be guaranteed to show up in random battles.</div>"); this.logModCommand("The Pokemon of the Day was changed to " + target + " by " + user.name + "."); } else { if (Rooms.lobby) Rooms.lobby.addRaw("<div class=\"broadcast-blue\"><b>The Pokemon of the Day was removed!</b><br />No pokemon will be guaranteed in random battles.</div>"); this.logModCommand("The Pokemon of the Day was removed by " + user.name + "."); } }, roll: 'dice', dice: function (target, room, user) { if (!target) return this.parse('/help dice'); if (!this.canBroadcast()) return; var d = target.indexOf("d"); if (d != -1) { var num = parseInt(target.substring(0, d)); var faces; if (target.length > d) faces = parseInt(target.substring(d + 1)); if (isNaN(num)) num = 1; if (isNaN(faces)) return this.sendReply("The number of faces must be a valid integer."); if (faces < 1 || faces > 1000) return this.sendReply("The number of faces must be between 1 and 1000"); if (num < 1 || num > 20) return this.sendReply("The number of dice must be between 1 and 20"); var rolls = []; var total = 0; for (var i = 0; i < num; ++i) { rolls[i] = (Math.floor(faces * Math.random()) + 1); total += rolls[i]; } return this.sendReplyBox("Random number " + num + "x(1 - " + faces + "): " + rolls.join(", ") + "<br />Total: " + total); } if (target && isNaN(target) || target.length > 21) return this.sendReply("The max roll must be a number under 21 digits."); var maxRoll = (target)? target : 6; var rand = Math.floor(maxRoll * Math.random()) + 1; return this.sendReplyBox("Random number (1 - " + maxRoll + "): " + rand); }, pr: 'pickrandom', pick: 'pickrandom', pickrandom: function (target, room, user) { var options = target.split(','); if (options.length < 2) return this.parse('/help pick'); if (!this.canBroadcast()) return false; return this.sendReplyBox('<em>We randomly picked:</em> ' + Tools.escapeHTML(options.sample().trim())); }, register: function () { if (!this.canBroadcast()) return; this.sendReplyBox('You will be prompted to register upon winning a rated battle. Alternatively, there is a register button in the <button name="openOptions"><i class="icon-cog"></i> Options</button> menu in the upper right.'); }, lobbychat: function (target, room, user, connection) { if (!Rooms.lobby) return this.popupReply("This server doesn't have a lobby."); target = toId(target); if (target === 'off') { user.leaveRoom(Rooms.lobby, connection.socket); connection.send('|users|'); this.sendReply("You are now blocking lobby chat."); } else { user.joinRoom(Rooms.lobby, connection); this.sendReply("You are now receiving lobby chat."); } }, showimage: function (target, room, user) { if (!target) return this.parse('/help showimage'); if (!this.can('declare', room)) return false; if (!this.canBroadcast()) return; var targets = target.split(','); if (targets.length != 3) { return this.parse('/help showimage'); } this.sendReply('|raw|<img src="' + Tools.escapeHTML(targets[0]) + '" alt="" width="' + toId(targets[1]) + '" height="' + toId(targets[2]) + '" />'); }, postimage: 'image', image: function (target, room, user) { if (!target) return this.sendReply('Usage: /image link, size'); if (!this.can('ban', room)) return false; if (!this.canBroadcast()) return; var targets = target.split(','); if (targets.length != 2) { return this.sendReply('|raw|<center><img src="' + Tools.escapeHTML(targets[0]) + '" alt="" width="50%"/></center>'); } if (parseInt(targets[1]) <= 0 || parseInt(targets[1]) > 100) return this.parse('Usage: /image link, size (1-100)'); this.sendReply('|raw|<center><img src="' + Tools.escapeHTML(targets[0]) + '" alt="" width="' + toId(targets[1]) + '%"/></center>'); }, htmlbox: function (target, room, user) { if (!target) return this.parse('/help htmlbox'); if (!this.can('gdeclare', room)) return; if (!this.canHTML(target)) return; if (!this.canBroadcast('!htmlbox')) return; this.sendReplyBox(target); }, a: function (target, room, user) { if (!this.can('rawpacket')) return false; // secret sysop command room.add(target); }, /********************************************************* * Custom commands *********************************************************/ customavatars: 'customavatar', customavatar: (function () { const script = function () {/* FILENAME=`mktemp` function cleanup { rm -f $FILENAME } trap cleanup EXIT set -xe timeout 10 wget "$1" -nv -O $FILENAME FRAMES=`identify $FILENAME | wc -l` if [ $FRAMES -gt 1 ]; then EXT=".gif" else EXT=".png" fi timeout 10 convert $FILENAME -layers TrimBounds -coalesce -adaptive-resize 80x80\> -background transparent -gravity center -extent 80x80 "$2$EXT" */}.toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1]; var pendingAdds = {}; return function (target) { var parts = target.split(','); var cmd = parts[0].trim().toLowerCase(); if (cmd in {'':1, show:1, view:1, display:1}) { var message = ""; for (var a in Config.customAvatars) message += "<strong>" + Tools.escapeHTML(a) + ":</strong> " + Tools.escapeHTML(Config.customAvatars[a]) + "<br />"; return this.sendReplyBox(message); } if (!this.can('customavatar')) return false; switch (cmd) { case 'set': var userid = toId(parts[1]); var user = Users.getExact(userid); var avatar = parts.slice(2).join(',').trim(); if (!userid) return this.sendReply("You didn't specify a user."); if (Config.customAvatars[userid]) return this.sendReply(userid + " already has a custom avatar."); var hash = require('crypto').createHash('sha512').update(userid + '\u0000' + avatar).digest('hex').slice(0, 8); pendingAdds[hash] = {userid: userid, avatar: avatar}; parts[1] = hash; if (!user) { this.sendReply("Warning: " + userid + " is not online."); this.sendReply("If you want to continue, use: /customavatar forceset, " + hash); return; } /* falls through */ case 'forceset': var hash = parts[1].trim(); if (!pendingAdds[hash]) return this.sendReply("Invalid hash."); var userid = pendingAdds[hash].userid; var avatar = pendingAdds[hash].avatar; delete pendingAdds[hash]; require('child_process').execFile('bash', ['-c', script, '-', avatar, './config/avatars/' + userid], function (e, out, err) { if (e) { this.sendReply(userid + "'s custom avatar failed to be set. Script output:"); (out + err).split('\n').forEach(this.sendReply.bind(this)); return; } reloadCustomAvatars(); this.sendReply(userid + "'s custom avatar has been set."); }.bind(this)); break; case 'delete': var userid = toId(parts[1]); if (!Config.customAvatars[userid]) return this.sendReply(userid + " does not have a custom avatar."); if (Config.customAvatars[userid].toString().split('.').slice(0, -1).join('.') !== userid) return this.sendReply(userid + "'s custom avatar (" + Config.customAvatars[userid] + ") cannot be removed with this script."); require('fs').unlink('./config/avatars/' + Config.customAvatars[userid], function (e) { if (e) return this.sendReply(userid + "'s custom avatar (" + Config.customAvatars[userid] + ") could not be removed: " + e.toString()); delete Config.customAvatars[userid]; this.sendReply(userid + "'s custom avatar removed successfully"); }.bind(this)); break; default: return this.sendReply("Invalid command. Valid commands are `/customavatar set, user, avatar` and `/customavatar delete, user`."); } }; })(), /********************************************************* * Clan commands *********************************************************/ ayudaclan: 'clanshelp', clanhelp: 'clanshelp', clanshelp: function () { if (!this.canBroadcast()) return false; this.sendReplyBox( "<big><b>Comandos Básicos:</b></big><br /><br />" + "/clanes - Lista los clanes.<br />" + "/clan (clan/miembro) - Muestra la ficha/perfil de un clan.<br />" + "/miembrosclan (clan/miembro) - muestra los miembros con los que cuenta un clan.<br />" + "/clanauth (clan/miembro) - muestra la jerarquía de miembros de un clan.<br />" + "/warlog (clan/miembro) - muestra las 10 últimas wars de un clan.<br />" + "/invitarclan - Invita a un usuario a unirse al clan. Requiere ser Oficial o Líder del clan.<br />" + "/expulsarclan (miembro) - Expulsa a un miembro del clan. Requiere ser Líder del clan.<br />" + "/aceptarclan (clan) - Acepta una invitación al clan.<br />" + "/invitacionesclan (clan/miembro) - Lista a los usuarios invitados a un clan.<br />" + "/borrarinvitaciones - Borra las invitaciones pendientes al Clan. Requiere ser líder del clan.<br />" + "/abandonarclan - Abandona el clan.<br />" + "<br />" + "<big><b>Comandos de Clan-Auth:</b></big><br /><br />" + "/liderclan (miembro) - Nombra a un miembro líder del clan. Requiere ~<br />" + "/oficialclan (miembro) - Nombra a un miembro oficial del clan. Requiere ser Líder del clan.<br />" + "/demoteclan (miembro) - Borra a un miembro del staff del clan. Requiere ser Líder del clan y ~ para demotear a un Líder.<br />" + "/lemaclan (lema) - Establece el Lema del clan. Requiere ser líder del clan.<br />" + "/logoclan (logo) - Establece el Logotipo del clan. Requiere ser líder del clan.<br />" + "/closeclanroom - Bloquea una sala de clan a todos los que no sean miembros de dicho clan, salvo administradores.<br />" + "/openclanroom - Elimina el bloqueo del comando /closeclanroom.<br />" + "/rk o /roomkick - Expulsa a un usuario de una sala. Requiere @ o superior.<br />" + "<br />" + "<big><b>Comandos de Administración:</b></big><br /><br />" + "/createclan &lt;name> - Crea un clan.<br />" + "/deleteclan &lt;name> - Elimina un clan.<br />" + "/addclanmember &lt;clan>, &lt;user> - Fuerza a un usuario a unirse a un clan.<br />" + "/removeclanmember &lt;clan>, &lt;user> - Expulsa a un usuario del clan.<br />" + "/setlemaclan &lt;clan>,&lt;lema> - Establece un lema para un clan.<br />" + "/setlogoclan &lt;clan>,&lt;logo> - Establece un logotipo para un clan.<br />" + "/setsalaclan &lt;clan>,&lt;sala> - Establece una sala para un clan.<br />" + "/setgxeclan &lt;clan>,&lt;wins>,&lt;losses>,&lt;draws> - Establece la puntuación de un clan.<br />" + "/serankclan &lt;clan>,&lt;puntos> - Establece la puntuación de un clan.<br />" + "/settitleclan &lt;clan>&lt;puntos> - Estable un título para el clan.<br />" + "<br />" + "<big><b>Comandos de Wars:</b></big><br /><br />" + "/war &lt;formato>, &lt;tamano>, &lt;clan 1>, &lt;clan 2> - Incia una war entre 2 clanes. Requiere +<br />" + "/totalwar &lt;formato>, &lt;tamano>, &lt;clan 1>, &lt;clan 2> - Incia una war total entre 2 clanes. Requiere +<br />" + "/endwar - Finaliza una war. Requiere +<br />" + "/vw - Muestra el estado de la war.<br />" + "/jw o /joinwar - Comando para unirse a una war.<br />" + "/lw o /leavewar - Comando para salir de una war.<br />" + "/warkick - Fuerza a un usuario a abandonar una war. Requiere %<br />" + "/wardq - Descalifica a un usuario. Requiere % o autoridad en el clan.<br />" + "/warreplace &lt;usuario 1>, &lt;usuario 2> - Comando para reemplazar. Requiere % o autoridad en el clan.<br />" + "/warinvalidate &lt;participante> - Deniega la validez de una batalla o un resultado. Requiere @<br />" ); }, createclan: function (target) { if (!this.can('clans')) return false; if (target.length < 2) this.sendReply("El nombre del clan es demasiado corto"); else if (!Clans.createClan(target)) this.sendReply("No se pudo crear el clan. Es posible que ya exista otro con el mismo nombre."); else this.sendReply("Clan: " + target + " creado con éxito."); }, deleteclan: function (target) { if (!this.can('clans')) return false; if (!Clans.deleteClan(target)) this.sendReply("No se pudo eliminar el clan. Es posble que no exista o que se encuentre en war."); else this.sendReply("Clan: " + target + " eliminado con éxito."); }, getclans: 'clans', clanes: 'clans', clans: function (target, room, user) { if (!this.canBroadcast()) return false; var clansTableTitle = "Lista de Clanes"; if (toId(target) === 'rank' || toId(target) === 'puntos') clansTableTitle = "Lista de Clanes por Puntuaci&oacute;n"; if (toId(target) === 'miembros' || toId(target) === 'members') clansTableTitle = "Lista de Clanes por Miembros"; var clansTable = '<br /><center><big><big><strong>' + clansTableTitle + '</strong></big></big><center><br /><table class="clanstable" width="100%" border="1"><tr><td><center><strong>Clan</strong></center></td><td><center><strong>Miembros</strong></center></td><td><center><strong>Sala</strong></center></td><td><center><strong>GXE</strong></center></td><td><center><strong>Puntuaci&oacute;n</strong></center></td></tr>'; var clansList = Clans.getClansList(toId(target)); var auxRating = {}; var nMembers = 0; var membersClan = {}; var auxGxe = 0; for (var m in clansList) { auxRating = Clans.getElementalData(m); auxGxe = Math.floor(auxRating.gxe * 100) / 100; membersClan = Clans.getMembers(m); if (!membersClan) { nMembers = 0; } else { nMembers = membersClan.length; } clansTable += '<tr><td><center>' + Tools.escapeHTML(Clans.getClanName(m)) + '</center></td><td><center>' + nMembers + '</center></td><td><center>' + '<button name="send" value="/join ' + Tools.escapeHTML(auxRating.sala) + '" target="_blank">' + Tools.escapeHTML(auxRating.sala) + '</button>' + '</center></td><td><center>' + auxGxe + '</center></td><td><center>' + auxRating.rating + '</center></td></tr>'; } clansTable += '</table>'; this.sendReplyBox(clansTable); }, clanauth: function (target, room, user) { var autoclan = false; if (!target) autoclan = true; if (!this.canBroadcast()) return false; var clan = Clans.getRating(target); if (!clan) { target = Clans.findClanFromMember(target); if (target) clan = Clans.getRating(target); } if (!clan && autoclan) { target = Clans.findClanFromMember(user.name); if (target) clan = Clans.getRating(target); } if (!clan) { this.sendReply("El clan especificado no existe o no está disponible."); return; } //html codes for clan ranks var leaderClanSource = Clans.getAuthMembers(target, 2); if (leaderClanSource !== "") { leaderClanSource = "<big><b>Líderes</b></big><br /><br />" + leaderClanSource + "</b></big></big><br /><br />"; } var oficialClanSource = Clans.getAuthMembers(target, 1); if (oficialClanSource !== "") { oficialClanSource = "<big><b>Oficiales</b></big><br /><br />" + oficialClanSource + "</b></big></big><br /><br />"; } var memberClanSource = Clans.getAuthMembers(target, false); if (memberClanSource !== "") { memberClanSource = "<big><b>Resto de Miembros</b></big><br /><br />" + memberClanSource + "</b></big></big><br /><br />"; } this.sendReplyBox( "<center><big><big><b>Jerarquía del clan " + Tools.escapeHTML(Clans.getClanName(target)) + "</b></big></big> <br /><br />" + leaderClanSource + oficialClanSource + memberClanSource + '</center>' ); }, clanmembers: 'miembrosclan', miembrosclan: function (target, room, user) { var autoclan = false; if (!target) autoclan = true; if (!this.canBroadcast()) return false; var clan = Clans.getRating(target); if (!clan) { target = Clans.findClanFromMember(target); if (target) clan = Clans.getRating(target); } if (!clan && autoclan) { target = Clans.findClanFromMember(user.name); if (target) clan = Clans.getRating(target); } if (!clan) { this.sendReply("El clan especificado no existe o no está disponible."); return; } var nMembers = 0; var membersClan = Clans.getMembers(target); if (!membersClan) { nMembers = 0; } else { nMembers = membersClan.length; } this.sendReplyBox( "<strong>Miembros del clan " + Tools.escapeHTML(Clans.getClanName(target)) + ":</strong> " + Clans.getAuthMembers(target, "all") + '<br /><br /><strong>Número de miembros: ' + nMembers + '</strong>' ); }, invitacionesclan: function (target, room, user) { var autoclan = false; if (!target) autoclan = true; if (!this.canBroadcast()) return false; var clan = Clans.getRating(target); if (!clan) { target = Clans.findClanFromMember(target); if (target) clan = Clans.getRating(target); } if (!clan && autoclan) { target = Clans.findClanFromMember(user.name); if (target) clan = Clans.getRating(target); } if (!clan) { this.sendReply("El clan especificado no existe o no está disponible."); return; } this.sendReplyBox( "<strong>Invitaciones pendientes del clan " + Tools.escapeHTML(Clans.getClanName(target)) + ":</strong> " + Tools.escapeHTML(Clans.getInvitations(target).sort().join(", ")) ); }, clan: 'getclan', getclan: function (target, room, user) { var autoClan = false; var memberClanProfile = false; var clanMember = ""; if (!target) autoClan = true; if (!this.canBroadcast()) return false; var clan = Clans.getProfile(target); if (!clan) { clanMember = target; target = Clans.findClanFromMember(target); memberClanProfile = true; if (target) clan = Clans.getProfile(target); } if (!clan && autoClan) { target = Clans.findClanFromMember(user.name); if (target) clan = Clans.getProfile(target); memberClanProfile = true; clanMember = user.name; } if (!clan) { this.sendReply("El clan especificado no existe o no está disponible."); return; } var salaClanSource = ""; if (clan.sala === "none") { salaClanSource = 'Aún no establecida.'; } else { salaClanSource = '<button name="send" value="/join ' + Tools.escapeHTML(clan.sala) + '" target="_blank">' + Tools.escapeHTML(clan.sala) + '</button>'; } var clanTitle = ""; if (memberClanProfile) { var authValue = Clans.authMember(target, clanMember); if (authValue === 2) { clanTitle = clanMember + " - Líder del clan " + clan.compname; } else if (authValue === 1) { clanTitle = clanMember + " - Oficial del clan " + clan.compname; } else { clanTitle = clanMember + " - Miembro del clan " + clan.compname; } } else { clanTitle = clan.compname; } var medalsClan = ''; if (clan.medals) { for (var u in clan.medals) { medalsClan += '<img id="' + u + '" src="' + encodeURI(clan.medals[u].logo) + '" width="32" title="' + Tools.escapeHTML(clan.medals[u].desc) + '" />&nbsp;&nbsp;'; } } this.sendReplyBox( '<div id="fichaclan">' + '<h4><center><p> <br />' + Tools.escapeHTML(clanTitle) + '</center></h4><hr width="90%" />' + '<table width="90%" border="0" align="center"><tr><td width="180" rowspan="2"><div align="center"><img src="' + encodeURI(clan.logo) + '" width="160" height="160" /></div></td><td height="64" align="left" valign="middle"><span class="lemaclan">'+ Tools.escapeHTML(clan.lema) + '</span></td> </tr> <tr> <td align="left" valign="middle"><strong>Sala Propia</strong>: ' + salaClanSource + ' <p style="font-style: normal;font-size: 16px;"><strong>Puntuación</strong>:&nbsp;' + clan.rating + ' (' + clan.wins + ' Victorias, ' + clan.losses + ' Derrotas, ' + clan.draws + ' Empates)<br />' + ' </p> <p style="font-style: normal;font-size: 16px;">&nbsp;' + medalsClan + '</p></td> </tr></table></div>' ); }, setlemaclan: function (target) { if (!this.can('clans')) return false; var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /setlemaclan clan, lema"); if (!Clans.setLema(params[0], params[1])) this.sendReply("El clan no existe o el lema es mayor de 80 caracteres."); else { this.sendReply("El nuevo lema del clan " + params[0] + " ha sido establecido con éxito."); } }, setlogoclan: function (target) { if (!this.can('clans')) return false; var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /setlogoclan clan, logo"); if (!Clans.setLogo(params[0], params[1])) this.sendReply("El clan no existe o el link del logo es mayor de 80 caracteres."); else { this.sendReply("El nuevo logo del clan " + params[0] + " ha sido establecido con éxito."); } }, settitleclan: function (target) { if (!this.can('clans')) return false; var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /settitleclan clan, titulo"); if (!Clans.setCompname(params[0], params[1])) this.sendReply("El clan no existe o el título es mayor de 80 caracteres."); else { this.sendReply("El nuevo titulo del clan " + params[0] + " ha sido establecido con éxito."); } }, setrankclan: function (target) { if (!this.can('clans')) return false; var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /setrankclan clan, valor"); if (!Clans.setRanking(params[0], params[1])) this.sendReply("El clan no existe o el valor no es válido."); else { this.sendReply("El nuevo rank para el clan " + params[0] + " ha sido establecido con éxito."); } }, setgxeclan: function (target) { if (!this.can('clans')) return false; var params = target.split(','); if (!params || params.length !== 4) return this.sendReply("Usage: /setgxeclan clan, wins, losses, ties"); if (!Clans.setGxe(params[0], params[1], params[2], params[3])) this.sendReply("El clan no existe o el valor no es válido."); else { this.sendReply("El nuevo GXE para el clan " + params[0] + " ha sido establecido con éxito."); } }, setsalaclan: function (target) { if (!this.can('clans')) return false; var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /setsalaclan clan, sala"); if (!Clans.setSala(params[0], params[1])) this.sendReply("El clan no existe o el nombre de la sala es mayor de 80 caracteres."); else { this.sendReply("La nueva sala del clan " + params[0] + " ha sido establecida con éxito."); } }, giveclanmedal: function (target) { if (!this.can('clans')) return false; var params = target.split(','); if (!params || params.length !== 4) return this.sendReply("Usage: /giveclanmedal clan, medallaId, imagen, desc"); if (!Clans.addMedal(params[0], params[1], params[2], params[3])) this.sendReply("El clan no existe o alguno de los datos no es correcto"); else { this.sendReply("Has entegado una medalla al clan " + params[0]); } }, removeclanmedal: function (target) { if (!this.can('clans')) return false; var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /removeclanmedal clan, medallaId"); if (!Clans.deleteMedal(params[0], params[1])) this.sendReply("El clan no existe o no podeía dicha medalla"); else { this.sendReply("Has quitado una medalla al clan " + params[0]); } }, lemaclan: function (target, room, user) { var permisionClan = false; if (!target) return this.sendReply("Debe especificar un lema."); var clanUser = Clans.findClanFromMember(user.name); if (clanUser) { var clanUserid = toId(clanUser); var iduserwrit = toId(user.name); var perminsionvalue = Clans.authMember(clanUserid, iduserwrit); if (perminsionvalue === 2) permisionClan = true; if (!permisionClan && !this.can('clans')) return false; } else { return false; } var claninfo = Clans.getElementalData (clanUser); if (room && room.id === toId(claninfo.sala)) { if (!Clans.setLema(clanUser, target)) this.sendReply("El lema es mayor de 80 caracteres."); else { this.addModCommand("Un nuevo lema para el clan " + clanUser + " ha sido establecido por " + user.name); } } else { this.sendReply("Este comando solo puede ser usado en la sala del clan."); } }, logoclan: function (target, room, user) { var permisionClan = false; if (!target) return this.sendReply("Debe especificar un logo."); var clanUser = Clans.findClanFromMember(user.name); if (clanUser) { var clanUserid = toId(clanUser); var iduserwrit = toId(user.name); var perminsionvalue = Clans.authMember(clanUserid, iduserwrit); if (perminsionvalue === 2) permisionClan = true; if (!permisionClan && !this.can('clans')) return false; } else { return false; } var claninfo = Clans.getElementalData (clanUser); if (room && room.id === toId(claninfo.sala)) { if (!Clans.setLogo(clanUser, target)) this.sendReply("El logo es mayor de 80 caracteres."); else { this.addModCommand("Un nuevo logotipo para el clan " + clanUser + " ha sido establecido por " + user.name); } } else { this.sendReply("Este comando solo puede ser usado en la sala del clan."); } }, addclanmember: function (target) { if (!this.can('clans')) return false; var params = target.split(','); if (params.length !== 2) return this.sendReply("Usage: /addclanmember clan, member"); var user = Users.getExact(params[1]); if (!user || !user.connected) return this.sendReply("User: " + params[1] + " is not online."); if (!Clans.addMember(params[0], params[1])) this.sendReply("Could not add the user to the clan. Does the clan exist or is the user already in another clan?"); else { this.sendReply("User: " + user.name + " successfully added to the clan."); Rooms.rooms.lobby.add('|raw|<div class="clans-user-join">' + Tools.escapeHTML(user.name) + " se ha unido al clan: " + Tools.escapeHTML(Clans.getClanName(params[0])) + '</div>'); } }, clanleader: 'liderclan', liderclan: function (target, room, user) { if (!this.can('clans')) return false; var params = target.split(','); if (!params) return this.sendReply("Usage: /liderclan member"); var userk = Users.getExact(params[0]); if (!userk || !userk.connected) return this.sendReply("Usuario: " + params[0] + " no existe o no está disponible."); if (!Clans.addLeader(params[0])) this.sendReply("El usuario no existe, no pertenece a ningún clan o ya era líder de su clan."); else { var clanUser = Clans.findClanFromMember(params[0]); this.sendReply("Usuario: " + userk.name + " nombrado correctamente líder del clan " + clanUser + "."); userk.popup(user.name + " te ha nombrado Líder del clan " + clanUser + ".\nUtiliza el comando /clanhelp para más información."); } }, clanoficial: 'oficialclan', oficialclan: function (target, room, user) { var permisionClan = false; var params = target.split(','); if (!params) { return this.sendReply("Usage: /demoteclan member"); } var clanUser = Clans.findClanFromMember(user.name); var clanTarget = Clans.findClanFromMember(params[0]); if (clanUser) { var clanUserid = toId(clanUser); var userb = toId(params[0]); var iduserwrit = toId(user.name); var perminsionvalue = Clans.authMember(clanUserid, iduserwrit); if (perminsionvalue === 2 && clanTarget === clanUser) permisionClan = true; } if (!permisionClan && !this.can('clans')) return; var userk = Users.getExact(params[0]); if (!userk || !userk.connected) return this.sendReply("Usuario: " + params[0] + " no existe o no está disponible."); if (clanTarget) { var clanId = toId(clanTarget); var userId = toId(params[0]); if (Clans.authMember(clanId, userId) === 2 && !this.can('clans')) return false; } if (!Clans.addOficial(params[0])) this.sendReply("El usuario no existe, no pertenece a ningún clan o ya era oficial de su clan."); else { this.sendReply("Usuario: " + userk.name + " nombrado correctamente oficial del clan " + clanTarget + "."); userk.popup(user.name + " te ha nombrado Oficial del clan " + clanTarget + ".\nUtiliza el comando /clanhelp para más información."); } }, degradarclan: 'declanauth', demoteclan: 'declanauth', declanauth: function (target, room, user) { var permisionClan = false; var params = target.split(','); if (!params) { return this.sendReply("Usage: /demoteclan member"); } var clanUser = Clans.findClanFromMember(user.name); var clanTarget = Clans.findClanFromMember(params[0]); if (clanUser) { var clanUserid = toId(clanUser); var userb = toId(params[0]); var iduserwrit = toId(user.name); var perminsionValue = Clans.authMember(clanUserid, iduserwrit); if (perminsionValue === 2 && clanTarget === clanUser) permisionClan = true; } if (!permisionClan && !this.can('clans')) return; var userk = Users.getExact(params[0]); if (!clanTarget) { return this.sendReply("El usuario no existe o no pertenece a ningún clan."); } else { var clanId = toId(clanTarget); var userId = toId(params[0]); if (Clans.authMember(clanId, userId) === 2 && !this.can('clans')) return false; } if (!Clans.deleteLeader(params[0])) { if (!Clans.deleteOficial(params[0])) { this.sendReply("El usuario no poseía ninguna autoridad dentro del clan."); } else { if (!userk || !userk.connected) { this.addModCommand(params[0] + " ha sido degradado de rango en " + clanTarget + " por " + user.name); } else { this.addModCommand(userk.name + " ha sido degradado de rango en " + clanTarget + " por " + user.name); } } } else { var oficialDemote = Clans.deleteOficial(params[0]); if (!userk || !userk.connected) { this.addModCommand(params[0] + " ha sido degradado de rango en " + clanTarget + " por " + user.name); } else { this.addModCommand(userk.name + " ha sido degradado de rango en " + clanTarget + " por " + user.name); } } }, invitarclan: function (target, room, user) { var permisionClan = false; var clanUser = Clans.findClanFromMember(user.name); if (clanUser) { var clanUserid = toId(clanUser); var iduserwrit = toId(user.name); var permisionValue = Clans.authMember(clanUserid, iduserwrit); if (permisionValue === 1) permisionClan = true; if (permisionValue === 2) permisionClan = true; } if (!permisionClan) return false; var params = target.split(','); if (!params) return this.sendReply("Usage: /invitarclan user"); var userk = Users.getExact(params[0]); if (!userk || !userk.connected) return this.sendReply("Usuario: " + params[0] + " no existe o no está disponible."); if (!Clans.addInvite(clanUser, params[0])) this.sendReply("No se pudo invitar al usuario. ¿No existe, ya está invitado o está en otro clan?"); else { clanUser = Clans.findClanFromMember(user.name); userk.popup(user.name + " te ha invitado a unirte al clan " + clanUser + ".\nPara unirte al clan escribe en el chat /aceptarclan " + clanUser); this.addModCommand(userk.name + " ha sido invitado a unirse al clan " + clanUser + " por " + user.name); } }, aceptarclan: function (target, room, user) { var clanUser = Clans.findClanFromMember(user.name); if (clanUser) { return this.sendReply("Ya perteneces a un clan. No te puedes unir a otro."); } var params = target.split(','); if (!params) return this.sendReply("Usage: /aceptarclan clan"); var clanpropio = Clans.getClanName(params[0]); if (!clanpropio) return this.sendReply("El clan no existe o no está disponible."); if (!Clans.aceptInvite(params[0], user.name)) this.sendReply("El clan no existe o no has sido invitado a este."); else { this.sendReply("Te has unido correctamente al clan" + clanpropio); Rooms.rooms.lobby.add('|raw|<div class="clans-user-join">' + Tools.escapeHTML(user.name) + " se ha unido al clan: " + Tools.escapeHTML(Clans.getClanName(params[0])) + '</div>'); } }, inviteclear: 'borrarinvitaciones', borrarinvitaciones: function (target, room, user) { var permisionClan = false; var clanUser = Clans.findClanFromMember(user.name); if (!target) { if (clanUser) { var clanUserid = toId(clanUser); var iduserwrit = toId(user.name); var perminsionvalue = Clans.authMember(clanUserid, iduserwrit); if (perminsionvalue === 2) permisionClan = true; } if (!permisionClan) return false; } else { if (!this.can('clans')) return; clanUser = target; } if (!Clans.clearInvitations(clanUser)) this.sendReply("El clan no existe o no está disponible."); else { this.sendReply("Lista de Invitaciones pendientes del clan " + clanUser + " borrada correctamente."); } }, removeclanmember: function (target) { if (!this.can('clans')) return false; var params = target.split(','); if (params.length !== 2) return this.sendReply("Usage: /removeclanmember clan, member"); if (!Clans.removeMember(params[0], params[1])) this.sendReply("Could not remove the user from the clan. Does the clan exist or has the user already been removed from it?"); else { this.sendReply("User: " + params[1] + " successfully removed from the clan."); Rooms.rooms.lobby.add('|raw|<div class="clans-user-join">' + Tools.escapeHTML(params[1]) + " ha abandonado el clan: " + Tools.escapeHTML(Clans.getClanName(params[0])) + '</div>'); } }, expulsarclan: function (target, room, user) { var permisionClan = false; var params = target.split(','); if (!params) { return this.sendReply("Usage: /demoteclan member"); } var clanUser = Clans.findClanFromMember(user.name); var clanTarget = Clans.findClanFromMember(params[0]); if (clanUser) { var clanUserid = toId(clanUser); var userb = toId(params[0]); var iduserwrit = toId(user.name); var perminsionValue = Clans.authMember(clanUserid, iduserwrit); if (perminsionValue === 2 && clanTarget === clanUser) permisionClan = true; } if (!permisionClan && !this.can('clans')) return; var currentWar = Clans.findWarFromClan(clanTarget); if (currentWar) { var currentWarParticipants = Clans.getWarParticipants(currentWar); if (currentWarParticipants.clanAMembers[toId(params[0])] || currentWarParticipants.clanBMembers[toId(params[0])]) return this.sendReply("No puedes expulsar del clan si el miembro estaba participando en una war."); } var userk = Users.getExact(params[0]); if (!clanTarget) { return this.sendReply("El usuario no existe o no pertenece a ningún clan."); } else { var clanId = toId(clanTarget); var userId = toId(params[0]); if (Clans.authMember(clanId, userId) === 2 && !this.can('clans')) return false; } if (!Clans.removeMember(clanTarget, params[0])) { this.sendReply("El usuario no pudo ser expulsado del clan."); } else { if (!userk || !userk.connected) { this.addModCommand(params[0] + " ha sido expulsado del clan " + clanTarget + " por " + user.name); } else { this.addModCommand(userk.name + " ha sido expulsado del clan " + clanTarget + " por " + user.name); } } }, salirdelclan: 'abandonarclan', clanleave: 'abandonarclan', abandonarclan: function (target, room, user) { var clanUser = Clans.findClanFromMember(user.name); if (!clanUser) { return this.sendReply("No perteneces a ningún clan."); } var currentWar = Clans.findWarFromClan(clanUser); if (currentWar) { var currentWarParticipants = Clans.getWarParticipants(currentWar); if (currentWarParticipants.clanAMembers[toId(user.name)] || currentWarParticipants.clanBMembers[toId(user.name)]) return this.sendReply("No puedes salir del clan si estabas participando en una war."); } if (!Clans.removeMember(clanUser, user.name)) { this.sendReply("Error al intentar salir del clan."); } else { this.sendReply("Has salido del clan" + clanUser); Rooms.rooms.lobby.add('|raw|<div class="clans-user-join">' + Tools.escapeHTML(user.name) + " ha abandonado el clan: " + Tools.escapeHTML(Clans.getClanName(clanUser)) + '</div>'); } }, //new war system pendingwars: 'wars', wars: function (target, room, user) { if (!this.canBroadcast()) return false; this.sendReplyBox(Clans.getPendingWars()); }, viewwar: 'vw', warstatus: 'vw', vw: function (target, room, user) { if (!this.canBroadcast()) return false; if (!room.isOfficial) return this.sendReply("Este comando solo puede ser usado en salas Oficiales."); var currentWar = Clans.findWarFromRoom(room.id); if (!currentWar) return this.sendReply("No había ninguna war en curso en esta sala."); var currentWarData = Clans.getWarData(currentWar); var currentWarParticipants = Clans.getWarParticipants(currentWar); if (currentWarData.warRound === 0) { this.sendReply('|raw| <hr /><h2><font color="green">' + ' Inscríbanse a la war en formato ' + Clans.getWarFormatName(currentWarData.format) + ' entre los clanes ' + Clans.getClanName(currentWar) + " y " + Clans.getClanName(currentWarData.against) + '. Para unirte escribe </font> <font color="red">/joinwar</font> <font color="green">.</font></h2><b><font color="blueviolet">Jugadores por clan:</font></b> ' + currentWarData.warSize + '<br /><font color="blue"><b>FORMATO:</b></font> ' + Clans.getWarFormatName(currentWarData.format) + '<hr /><br /><font color="red"><b>Recuerda que debes mantener tu nombre durante toda la duración de la war.</b></font>'); } else { var warType = ""; if (currentWarData.warStyle === 2) warType = " total"; var htmlSource = '<hr /><h3><center><font color=green><big>War' + warType + ' entre ' + Clans.getClanName(currentWar) + " y " + Clans.getClanName(currentWarData.against) + '</big></font></center></h3><center><b>FORMATO:</b> ' + Clans.getWarFormatName(currentWarData.format) + "</center><hr /><center><small><font color=red>Red</font> = descalificado, <font color=green>Green</font> = paso a la siguiente ronda, <a class='ilink'><b>URL</b></a> = combatiendo</small></center><br />"; for (var t in currentWarParticipants.byes) { var userFreeBye = Users.getExact(t); if (!userFreeBye) {userFreeBye = t;} else {userFreeBye = userFreeBye.name;} htmlSource += '<center><small><font color=green>' + userFreeBye + ' ha pasado a la siguiente ronda.</font></small></center><br />'; } var clanDataA = Clans.getProfile(currentWar); var clanDataB = Clans.getProfile(currentWarData.against); var matchupsTable = '<table align="center" border="0" cellpadding="0" cellspacing="0"><tr><td align="right"><img width="100" height="100" src="' + encodeURI(clanDataA.logo) + '" />&nbsp;&nbsp;&nbsp;&nbsp;</td><td align="center"><table align="center" border="0" cellpadding="0" cellspacing="0">'; for (var i in currentWarParticipants.matchups) { var userk = Users.getExact(currentWarParticipants.matchups[i].from); if (!userk) {userk = currentWarParticipants.matchups[i].from;} else {userk = userk.name;} var userf = Users.getExact(currentWarParticipants.matchups[i].to); if (!userf) {userf = currentWarParticipants.matchups[i].to;} else {userf = userf.name;} switch (currentWarParticipants.matchups[i].result) { case 0: matchupsTable += '<tr><td align="right"><big>' + userk + '</big></td><td>&nbsp;vs&nbsp;</td><td><big align="left">' + userf + "</big></td></tr>"; break; case 1: matchupsTable += '<tr><td align="right"><a href="/' + currentWarParticipants.matchups[i].battleLink +'" room ="' + currentWarParticipants.matchups[i].battleLink + '" class="ilink"><b><big>' + userk + '</big></b></a></td><td>&nbsp;<a href="/' + currentWarParticipants.matchups[i].battleLink + '" room ="' + currentWarParticipants.matchups[i].battleLink + '" class="ilink">vs</a>&nbsp;</td><td><a href="/' + currentWarParticipants.matchups[i].battleLink + '" room ="' + currentWarParticipants.matchups[i].battleLink + '" class="ilink"><b><big align="left">' + userf + "</big></b></a></td></tr>"; break; case 2: matchupsTable += '<tr><td align="right"><font color="green"><b><big>' + userk + '</big></b></font></td><td>&nbsp;vs&nbsp;</td><td><font color="red"><b><big align="left">' + userf + "</big></b></font></td></tr>"; break; case 3: matchupsTable += '<tr><td align="right"><font color="red"><b><big>' + userk + '</big></b></font></td><td>&nbsp;vs&nbsp;</td><td><font color="green"><b><big align="left">' + userf + "</big></b></font></td></tr>"; break; } } matchupsTable += '</table></td><td>&nbsp;&nbsp;&nbsp;&nbsp;<img width="100" height="100" src="' + encodeURI(clanDataB.logo) + '" /></td></tr></table><hr />'; htmlSource += matchupsTable; this.sendReply('|raw| ' + htmlSource); } }, standardwar: 'war', war: function (target, room, user) { var permisionCreateWar = false; if (user.group === '+' || user.group === '%' || user.group === '@' || user.group === '&' || user.group === '~') permisionCreateWar = true; //if (room.auth && room.auth[user.userid]) permisionCreateWar = true; if (!permisionCreateWar && !this.can('wars')) return false; if (!room.isOfficial) return this.sendReply("Este comando solo puede ser usado en salas Oficiales."); if (Clans.findWarFromRoom(room.id)) return this.sendReply("Ya había una war en curso en esta sala."); var params = target.split(','); if (params.length !== 4) return this.sendReply("Usage: /war formato, tamaño, clanA, clanB"); if (!Clans.getWarFormatName(params[0])) return this.sendReply("El formato especificado para la war no es válido."); params[1] = parseInt(params[1]); if (params[1] < 3 || params[1] > 100) return this.sendReply("El tamaño de la war no es válido."); if (!Clans.createWar(params[2], params[3], room.id, params[0], params[1], 1)) { this.sendReply("Alguno de los clanes especificados no existía o ya estaba en war."); } else { this.logModCommand(user.name + " ha iniciado una war standard entre los clanes " + Clans.getClanName(params[2]) + " y " + Clans.getClanName(params[3]) + " en formato " + Clans.getWarFormatName(params[0]) + "."); Rooms.rooms[room.id].addRaw('<hr /><h2><font color="green">' + user.name + ' ha iniciado una War en formato ' + Clans.getWarFormatName(params[0]) + ' entre los clanes ' + Clans.getClanName(params[2]) + " y " + Clans.getClanName(params[3]) + '. Si deseas unirte escribe </font> <font color="red">/joinwar</font> <font color="green">.</font></h2><b><font color="blueviolet">Jugadores por clan:</font></b> ' + params[1] + '<br /><font color="blue"><b>FORMATO:</b></font> ' + Clans.getWarFormatName(params[0]) + '<hr /><br /><font color="red"><b>Recuerda que debes mantener tu nombre durante toda la duración de la war.</b></font>'); } }, totalwar: 'wartotal', wartotal: function (target, room, user) { var permisionCreateWar = false; if (user.group === '+' || user.group === '%' || user.group === '@' || user.group === '&' || user.group === '~') permisionCreateWar = true; if (!permisionCreateWar && !this.can('wars')) return false; if (!room.isOfficial) return this.sendReply("Este comando solo puede ser usado en salas Oficiales."); if (Clans.findWarFromRoom(room.id)) return this.sendReply("Ya había una war en curso en esta sala."); var params = target.split(','); if (params.length !== 4) return this.sendReply("Usage: /totalwar formato, tamaño, clanA, clanB"); if (!Clans.getWarFormatName(params[0])) return this.sendReply("El formato especificado para la war no es válido."); params[1] = parseInt(params[1]); if (params[1] < 3 || params[1] > 100) return this.sendReply("El tamaño de la war no es válido."); if (!Clans.createWar(params[2], params[3], room.id, params[0], params[1], 2)) { this.sendReply("Alguno de los clanes especificados no existía o ya estaba en war."); } else { this.logModCommand(user.name + " ha iniciado una war total entre los clanes " + Clans.getClanName(params[2]) + " y " + Clans.getClanName(params[3]) + " en formato " + Clans.getWarFormatName(params[0]) + "."); Rooms.rooms[room.id].addRaw('<hr /><h2><font color="green">' + user.name + ' ha iniciado una War Total en formato ' + Clans.getWarFormatName(params[0]) + ' entre los clanes ' + Clans.getClanName(params[2]) + " y " + Clans.getClanName(params[3]) + '. Si deseas unirte escribe </font> <font color="red">/joinwar</font> <font color="green">.</font></h2><b><font color="blueviolet">Jugadores por clan:</font></b> ' + params[1] + '<br /><font color="blue"><b>FORMATO:</b></font> ' + Clans.getWarFormatName(params[0]) + '<hr /><br /><font color="red"><b>Recuerda que debes mantener tu nombre durante toda la duración de la war.</b></font>'); } }, joinwar: 'jw', jw: function (target, room, user) { var clanUser = Clans.findClanFromMember(user.name); if (!clanUser) { return this.sendReply("No perteneces a ningún clan."); } var currentWar = Clans.findWarFromRoom(room.id); if (!currentWar) return this.sendReply("No había ninguna war en curso en esta sala."); var currentWarData = Clans.getWarData(currentWar); if (toId(clanUser) !== toId(currentWar) && toId(clanUser) !== toId(currentWarData.against)) return this.sendReply("No perteneces a ninguno de los clanes que se están enfrentando en war."); var currentWarParticipants = Clans.getWarParticipants(currentWar); if (currentWarParticipants.clanAMembers[toId(user.name)] || currentWarParticipants.clanBMembers[toId(user.name)]) return this.sendReply("Ya estabas inscrito en esta war."); if (currentWarData.warRound > 0) return this.sendReply("La War ya ha empezado. No te puedes unir."); var registeredA = Object.keys(currentWarParticipants.clanAMembers); var registeredB = Object.keys(currentWarParticipants.clanBMembers); if (toId(clanUser) === toId(currentWar) && registeredA.length === currentWarData.warSize) return this.sendReply("No quedan plazas para tu clan en esta war."); if (toId(clanUser) === toId(currentWarData.against) && registeredB.length === currentWarData.warSize) return this.sendReply("No quedan plazas para tu clan en esta war."); //join war var clanBJoin = false; if (toId(clanUser) === toId(currentWarData.against)) clanBJoin = true; if (!Clans.addWarParticipant(currentWar, user.name, clanBJoin)) { this.sendReply("Error al intentar unirse a la war."); } else { var freePlaces = Clans.getFreePlaces(currentWar); if (freePlaces > 0) { Rooms.rooms[room.id].addRaw('<b>' + user.name + '</b> se ha unido a la War. Quedan ' + freePlaces + ' plazas.'); } else{ Rooms.rooms[room.id].addRaw('<b>' + user.name + '</b> se ha unido a la War. Comienza la War!'); Clans.startWar(currentWar); //view war status var warType = ""; if (currentWarData.warStyle === 2) warType = " total"; currentWarParticipants = Clans.getWarParticipants(currentWar); var htmlSource = '<hr /><h3><center><font color=green><big>War' + warType + ' entre ' + Clans.getClanName(currentWar) + " y " + Clans.getClanName(currentWarData.against) + '</big></font></center></h3><center><b>FORMATO:</b> ' + Clans.getWarFormatName(currentWarData.format) + "</center><hr /><center><small><font color=red>Red</font> = descalificado, <font color=green>Green</font> = paso a la siguiente ronda, <a class='ilink'><b>URL</b></a> = combatiendo</small><center><br />"; var clanDataA = Clans.getProfile(currentWar); var clanDataB = Clans.getProfile(currentWarData.against); var matchupsTable = '<table align="center" border="0" cellpadding="0" cellspacing="0"><tr><td align="right"><img width="100" height="100" src="' + encodeURI(clanDataA.logo) + '" />&nbsp;&nbsp;&nbsp;&nbsp;</td><td align="center"><table align="center" border="0" cellpadding="0" cellspacing="0">'; for (var i in currentWarParticipants.matchups) { var userk = Users.getExact(currentWarParticipants.matchups[i].from); if (!userk) {userk = currentWarParticipants.matchups[i].from;} else {userk = userk.name;} var userf = Users.getExact(currentWarParticipants.matchups[i].to); if (!userf) {userf = currentWarParticipants.matchups[i].to;} else {userf = userf.name;} switch (currentWarParticipants.matchups[i].result) { case 0: matchupsTable += '<tr><td align="right"><big>' + userk + '</big></td><td>&nbsp;vs&nbsp;</td><td><big align="left">' + userf + "</big></td></tr>"; break; case 1: matchupsTable += '<tr><td align="right"><a href="' + currentWarParticipants.matchups[i].battleLink + '" room ="' + currentWarParticipants.matchups[i].battleLink + '"class="ilink"><big>' + userk + '</big></a></td><td>&nbsp;<a href="' + currentWarParticipants.matchups[i].battleLink + '" room ="' + currentWarParticipants.matchups[i].battleLink + '"class="ilink">vs</a>&nbsp;</td><td><a href="' + currentWarParticipants.matchups[i].battleLink + '" room ="' + currentWarParticipants.matchups[i].battleLink + '"class="ilink"><big align="left">' + userf + "</big></a></td></tr>"; break; case 2: matchupsTable += '<tr><td align="right"><font color="green"><big>' + userk + '</big></font></td><td>&nbsp;vs&nbsp;</td><td><font color="red"><big align="left">' + userf + "</big></font></td></tr>"; break; case 3: matchupsTable += '<tr><td align="right"><font color="red"><big>' + userk + '</big></font></td><td>&nbsp;vs&nbsp;</td><td><font color="green"><big align="left">' + userf + "</big></font></td></tr>"; break; } } matchupsTable += '</table></td><td>&nbsp;&nbsp;&nbsp;&nbsp;<img width="100" height="100" src="' + encodeURI(clanDataB.logo) + '" /></td></tr></table><hr />'; htmlSource += matchupsTable; Rooms.rooms[room.id].addRaw(htmlSource); } } }, leavewar: 'lw', lw: function (target, room, user) { var clanUser = Clans.findClanFromMember(user.name); if (!clanUser) { return this.sendReply("No perteneces a ningún clan."); } var currentWar = Clans.findWarFromRoom(room.id); if (!currentWar) return this.sendReply("No había ninguna war en curso en esta sala."); var currentWarData = Clans.getWarData(currentWar); if (toId(clanUser) !== toId(currentWar) && toId(clanUser) !== toId(currentWarData.against)) return this.sendReply("No perteneces a ninguno de los clanes que se están enfrentando en war."); var currentWarParticipants = Clans.getWarParticipants(currentWar); if (!currentWarParticipants.clanAMembers[toId(user.name)] && !currentWarParticipants.clanBMembers[toId(user.name)]) return this.sendReply("No estabas inscrito en esta war."); if (currentWarData.warRound > 0) return this.sendReply("La War ya ha empezado. No puedes salir de ella."); //leave war var clanBJoin = false; if (toId(clanUser) === toId(currentWarData.against)) clanBJoin = true; if (!Clans.removeWarParticipant(currentWar, user.name, clanBJoin)) { this.sendReply("Error al intentar salir de la war."); } else { var freePlaces = Clans.getFreePlaces(currentWar); Rooms.rooms[room.id].addRaw('<b>' + user.name + '</b> ha salido de la War. Quedan ' + freePlaces + ' plazas.'); } }, warkick: function (target, room, user) { var permisionModWar = false; if (user.group === '%' || user.group === '@' || user.group === '&' || user.group === '~') permisionModWar = true; if (!permisionModWar && !this.can('wars')) return false; if (!target) return this.sendReply("No has especificado ningún usuario"); var clanUser = Clans.findClanFromMember(target); if (!clanUser) { return this.sendReply("El usuario no pertene a ningún clan."); } var currentWar = Clans.findWarFromRoom(room.id); if (!currentWar) return this.sendReply("No había ninguna war en curso en esta sala."); var currentWarData = Clans.getWarData(currentWar); if (toId(clanUser) !== toId(currentWar) && toId(clanUser) !== toId(currentWarData.against)) return this.sendReply("El usuario no pertenece a ninguno de los clanes que se están enfrentando en war."); var currentWarParticipants = Clans.getWarParticipants(currentWar); if (!currentWarParticipants.clanAMembers[toId(target)] && !currentWarParticipants.clanBMembers[toId(target)]) return this.sendReply("El Usuario no estaba inscrito en esta war."); if (currentWarData.warRound > 0) return this.sendReply("La War ya ha empezado. No puedes usar este comando."); //leave war var clanBJoin = false; if (toId(clanUser) === toId(currentWarData.against)) clanBJoin = true; if (!Clans.removeWarParticipant(currentWar, target, clanBJoin)) { this.sendReply("Error al intentar expulsar de la war."); } else { var freePlaces = Clans.getFreePlaces(currentWar); var userk = Users.getExact(target); if (!userk) { Rooms.rooms[room.id].addRaw('<b>' + user.name + '</b> ha expulsado a <b>' + userk.name + '</b> de la War. Quedan ' + freePlaces + ' plazas.'); } else { Rooms.rooms[room.id].addRaw('<b>' + user.name + '</b> ha expulsado a <b>' + toId(target) + '</b> de la War. Quedan ' + freePlaces + ' plazas.'); } } }, wdq: 'wardq', wardq: function (target, room, user) { var permisionModWar = false; if (!target) return this.sendReply("No has especificado ningún usuario"); var clanUser = Clans.findClanFromMember(target); if (user.group === '%' || user.group === '@' || user.group === '&' || user.group === '~') permisionModWar = true; if (!clanUser) { return this.sendReply("El usuario no pertene a ningún clan."); } if (Clans.authMember(clanUser, user.name) === 1 || Clans.authMember(clanUser, user.name) === 2) permisionModWar = true; if (!permisionModWar && !this.can('wars')) return false; var currentWar = Clans.findWarFromRoom(room.id); if (!currentWar) return this.sendReply("No había ninguna war en curso en esta sala."); var currentWarData = Clans.getWarData(currentWar); if (toId(clanUser) !== toId(currentWar) && toId(clanUser) !== toId(currentWarData.against)) return this.sendReply("El usuario no pertenece a ninguno de los clanes que se están enfrentando en war."); var currentWarParticipants = Clans.getWarParticipants(currentWar); if (!currentWarParticipants.clanAMembers[toId(target)] && !currentWarParticipants.clanBMembers[toId(target)]) return this.sendReply("El Usuario no estaba inscrito en esta war."); if (currentWarData.warRound === 0) return this.sendReply("La War no ha empezado aún. No puedes usar este comando."); var clanBJoin = false; if (toId(clanUser) === toId(currentWarData.against)) clanBJoin = true; var matchupId = toId(target); if (!clanBJoin) { if (!currentWarParticipants.matchups[toId(target)] || currentWarParticipants.matchups[toId(target)].result > 1) return this.sendReply("El usuario no participaba en la war o ya había pasado a la siguiete ronda."); } else { var isParticipant = false; for (var g in currentWarParticipants.matchups) { if (toId(currentWarParticipants.matchups[g].to) === toId(target) && currentWarParticipants.matchups[g].result < 2) { isParticipant = true; matchupId = g; } } if (!isParticipant) return this.sendReply("El usuario no participaba en la war o ya había pasado a la siguiete ronda."); } if (!Clans.dqWarParticipant(currentWar, matchupId, clanBJoin)) { this.sendReply("El usuario no participaba en la war o ya había pasado a la siguiete ronda."); } else { var userk = Users.getExact(target); if (!userk) { this.addModCommand(target + " ha sido descalificado de la war por " + user.name + "."); } else { this.addModCommand(userk.name + " ha sido descalificado de la war por " + user.name + "."); } if (Clans.isWarEnded(currentWar)) { Clans.autoEndWar(currentWar); } } }, warinvalidate: function (target, room, user) { var permisionModWar = false; if (!target) return this.sendReply("No has especificado ningún usuario"); var clanUser = Clans.findClanFromMember(target); if (user.group === '@' || user.group === '&' || user.group === '~') permisionModWar = true; if (!clanUser) { return this.sendReply("El usuario no pertene a ningún clan."); } if (!permisionModWar && !this.can('wars')) return false; var currentWar = Clans.findWarFromRoom(room.id); if (!currentWar) return this.sendReply("No había ninguna war en curso en esta sala."); var currentWarData = Clans.getWarData(currentWar); if (toId(clanUser) !== toId(currentWar) && toId(clanUser) !== toId(currentWarData.against)) return this.sendReply("El usuario no pertenece a ninguno de los clanes que se están enfrentando en war."); var currentWarParticipants = Clans.getWarParticipants(currentWar); if (!currentWarParticipants.clanAMembers[toId(target)] && !currentWarParticipants.clanBMembers[toId(target)]) return this.sendReply("El Usuario no estaba inscrito en esta war."); if (currentWarData.warRound === 0) return this.sendReply("La War no ha empezado aún. No puedes usar este comando."); var clanBJoin = false; if (toId(clanUser) === toId(currentWarData.against)) clanBJoin = true; var matchupId = toId(target); if (!clanBJoin) { if (!currentWarParticipants.matchups[toId(target)] || currentWarParticipants.matchups[toId(target)].result === 0) return this.sendReply("El usuario no participaba o no había ningún resultado fijado para esta batalla de war."); } else { var isParticipant = false; for (var g in currentWarParticipants.matchups) { if (toId(currentWarParticipants.matchups[g].to) === toId(target) && currentWarParticipants.matchups[g].result > 0) { isParticipant = true; matchupId = g; } } if (!isParticipant) return this.sendReply("El usuario no participaba o no había ningún resultado fijado para esta batalla de war."); } if (!Clans.invalidateWarMatchup(currentWar, matchupId)) { this.sendReply("El usuario no participaba o no había ningún resultado fijado para esta batalla de war."); } else { var userk = Users.getExact(currentWarParticipants.matchups[matchupId].from); if (!userk) {userk = currentWarParticipants.matchups[matchupId].from;} else {userk = userk.name;} var userf = Users.getExact(currentWarParticipants.matchups[matchupId].to); if (!userf) {userf = currentWarParticipants.matchups[matchupId].to;} else {userf = userf.name;} this.addModCommand("La batalla entre " + userk + " y " + userf + " ha sido invalidada por " + user.name + "."); } }, wreplace: 'warreplace', warreplace: function (target, room, user) { var permisionModWar = false; var params = target.split(','); if (params.length !== 2) return this.sendReply("Usage: /wreplace usuario1, usuario2"); var clanUser = Clans.findClanFromMember(params[0]); if (user.group === '%' || user.group === '@' || user.group === '&' || user.group === '~') permisionModWar = true; if (!clanUser) { return this.sendReply("El usuario no pertene a ningún clan."); } if (Clans.authMember(clanUser, user.name) === 1 || Clans.authMember(clanUser, user.name) === 2) permisionModWar = true; if (!permisionModWar && !this.can('wars')) return false; var userh = Users.getExact(params[1]); if (!userh || !userh.connected) return this.sendReply("Usuario: " + params[1] + " no existe o no está disponible."); var clanTarget = Clans.findClanFromMember(params[1]); if (toId(clanTarget) !== toId(clanUser)) return this.sendReply("No puedes reemplazar por alguien de distinto clan."); var currentWar = Clans.findWarFromRoom(room.id); if (!currentWar) return this.sendReply("No había ninguna war en curso en esta sala."); var currentWarData = Clans.getWarData(currentWar); if (toId(clanUser) !== toId(currentWar) && toId(clanUser) !== toId(currentWarData.against)) return this.sendReply("El usuario no pertenece a ninguno de los clanes que se están enfrentando en war."); var currentWarParticipants = Clans.getWarParticipants(currentWar); if (!currentWarParticipants.clanAMembers[toId(params[0])] && !currentWarParticipants.clanBMembers[toId(params[0])]) return this.sendReply("El Usuario no estaba inscrito en esta war."); if (currentWarParticipants.clanAMembers[toId(params[1])] || currentWarParticipants.clanBMembers[toId(params[1])]) return this.sendReply("No puedes reemplazar por alguien que ya participaba en la war."); if (currentWarData.warRound === 0) return this.sendReply("La War no ha empezado aún. No puedes usar este comando."); var clanBJoin = false; if (toId(clanUser) === toId(currentWarData.against)) clanBJoin = true; var matchupId = toId(params[0]); if (!clanBJoin) { if (!currentWarParticipants.matchups[toId(params[0])] || currentWarParticipants.matchups[toId(params[0])].result !== 0) return this.sendReply("El usuario no participaba o ya había empezado su batalla."); } else { var isParticipant = false; for (var g in currentWarParticipants.matchups) { if (toId(currentWarParticipants.matchups[g].to) === toId(params[0]) && currentWarParticipants.matchups[g].result === 0) { isParticipant = true; matchupId = g; } } if (!isParticipant) return this.sendReply("El usuario no participaba o ya había empezado su batalla."); } if (!Clans.replaceWarParticipant(currentWar, matchupId, params[1], clanBJoin)) { this.sendReply("El usuario no participaba o ya había empezado su batalla."); } else { var userk = Users.getExact(params[0]); if (!userk) {userk = params[0];} else {userk = userk.name;} var userf = Users.getExact(params[1]); if (!userf) {userf = params[1];} else {userf = userf.name;} this.addModCommand(user.name + ": " + userk + " es reemplazado por " + userf + "."); } }, finalizarwar: 'endwar', endwar: function (target, room, user) { var permisionCreateWar = false; if (user.group === '+' || user.group === '%' || user.group === '@' || user.group === '&' || user.group === '~') permisionCreateWar = true; //if (room.auth && room.auth[user.userid]) permisionCreateWar = true; if (!permisionCreateWar && !this.can('wars')) return false; var currentWar = Clans.findWarFromRoom(room.id); if (!currentWar) return this.sendReply("No había ninguna war en curso en esta sala."); var currentWarData = Clans.getWarData(currentWar); if (!Clans.endWar(currentWar)) { this.sendReply("No se pudo terminar la war de esta sala debido a un error."); } else { this.logModCommand(user.name + " ha cancelado la war entre los clanes " + Clans.getClanName(currentWar) + " y " + Clans.getClanName(currentWarData.against) + "."); Rooms.rooms[room.id].addRaw('<hr /><h2><font color="green">' + user.name + ' ha cancelado la War entre los clanes ' + Clans.getClanName(currentWar) + " y " + Clans.getClanName(currentWarData.against) + '. <br /><hr />'); } }, warlog: function (target, room, user) { var autoclan = false; if (!target) autoclan = true; if (!this.canBroadcast()) return false; var clan = Clans.getRating(target); if (!clan) { target = Clans.findClanFromMember(target); if (target) clan = Clans.getRating(target); } if (!clan && autoclan) { target = Clans.findClanFromMember(user.name); if (target) clan = Clans.getRating(target); } if (!clan) { this.sendReply("El clan especificado no existe o no está disponible."); return; } var f = new Date(); var dateWar = f.getDate() + '-' + f.getMonth() + ' ' + f.getHours() + 'h'; this.sendReply( "|raw| <center><big><big><b>Ultimas Wars del clan " + Tools.escapeHTML(Clans.getClanName(target)) + "</b></big></big> <br /><br />" + Clans.getWarLogTable(target) + '<br /> Fecha del servidor: ' + dateWar + '</center>' ); }, closeclanroom: function (target, room, user) { var permisionClan = false; var clanRoom = Clans.findClanFromRoom(room.id); if (!clanRoom) return this.sendReply("Esta no es una sala de Clan."); var clanUser = Clans.findClanFromMember(user.name); if (clanUser && toId(clanRoom) === toId(clanUser)) { var clanUserid = toId(clanUser); var iduserwrit = toId(user.name); var perminsionvalue = Clans.authMember(clanUserid, iduserwrit); if (perminsionvalue === 2) permisionClan = true; } if (!permisionClan && !this.can('clans')) return false; if (!Clans.closeRoom(room.id, clanRoom)) this.sendReply("Error al intentar cerrar la sala. Es posible que ya esté cerrada."); else { this.addModCommand("Esta sala ha sido cerrada a quienes no sean miembros de " + clanRoom + " por " + user.name); } }, openclanroom: function (target, room, user) { var permisionClan = false; var clanRoom = Clans.findClanFromRoom(room.id); if (!clanRoom) return this.sendReply("Esta no es una sala de Clan."); var clanUser = Clans.findClanFromMember(user.name); if (clanUser && toId(clanRoom) === toId(clanUser)) { var clanUserid = toId(clanUser); var iduserwrit = toId(user.name); var perminsionvalue = Clans.authMember(clanUserid, iduserwrit); if (perminsionvalue === 2) permisionClan = true; } if (!permisionClan && !this.can('clans')) return false; if (!Clans.openRoom(room.id, clanRoom)) this.sendReply("Error al intentar abrir la sala. Es posible que ya esté abierta."); else { this.addModCommand("Esta sala ha sido abierta a todos los usuarios por " + user.name); } }, rk: 'roomkick', roomkick: function (target, room, user, connection) { if (!target) return this.sendReply("Usage: /roomkick user"); if (user.locked || user.mutedRooms[room.id]) return this.sendReply("You cannot do this while unable to talk."); target = this.splitTarget(target, true); var targetUser = this.targetUser; var name = this.targetUsername; var userid = toId(name); if (!userid || !targetUser) return this.sendReply("User '" + name + "' does not exist."); if (!this.can('ban', targetUser, room)) return false; if (!Rooms.rooms[room.id].users[targetUser.userid]) { return this.sendReply("User " + this.targetUsername + " is not in the room " + room.id + "."); } this.addModCommand("" + targetUser.name + " was kicked from room " + room.id + " by " + user.name + "." + (target ? " (" + target + ")" : "")); this.add('|unlink|' + this.getLastIdOf(targetUser)); targetUser.leaveRoom(room.id); }, kickall: function (target, room, user, connection) { if (user.locked || user.mutedRooms[room.id]) return this.sendReply("You cannot do this while unable to talk."); if (!this.can('makeroom')) return false; var targetUser; for (var f in Rooms.rooms[room.id].users) { targetUser = Users.getExact(Rooms.rooms[room.id].users[f]); if (toId(targetUser.name) !== toId(user.name)) targetUser.leaveRoom(room.id); } this.addModCommand("" + user.name + " has kicked all users from room " + room.id + '.'); }, /********************************************************* * Shop commands *********************************************************/ tienda: 'shop', shop: function (target, room, user) { if (!this.canBroadcast()) return false; this.sendReplyBox('<center><h3><b><u>Tienda de Viridian</u></b></h3><table border="1" cellspacing="0" cellpadding="3" target="_blank"><tbody>' + '<tr><th>Art&iacute;culo</th><th>Descripci&oacute;n</th><th>Coste</th></tr>' + '<tr><td>CustomTC</td><td>Compra una Tarjeta de Entrenador personalizada (a partir de código html). Contactar con un administrador si el código es muy largo para un solo mensaje.</td><td>10000</td></tr>' + '<tr><td>Chatroom</td><td>Compra una Sala de chat. Será pública o privada en función del motivo de su compra. Si se detecta spam de comandos / saturación del modlog será borrada.</td><td>8000</td></tr>' + '<tr><td>CustomAvatar</td><td>Compra un avatar personalizado. Preferiblemente debe ser una imagen de pequeñas dimensiones y acorde a las reglas del servidor. Contactar con un Admin para obtener este art&iacute;culo.</td><td>6000</td></tr>' + '<tr><td>TC</td><td>Compra una Tarjeta de entrenador básica. Con una Imagen modificable con /tcimage y una frase de entrenador modificable con /tcphrase</td><td>3000</td></tr>' + '<tr><td>Symbol</td><td>Compra el acceso al comado /customsymbol que permite elegir un símbolo (excepto staff) para aparecer en lo alto de la lista de usuarios.</td><td>3000</td></tr>' + '<tr><td>Avatar</td><td>Si ya tienes un avatar personaliado. Puedes cambiarlo por otro diferente. Contactar con un administrador para obtener este art&iacute;culo.</td><td>1000</td></tr>' + '<tr><td>Sprite</td><td>Añade la imagen de un Pokemon a tu TC Básica. Máximo 6. Se pueden cambiar los pokemon con el comando /tcpokemon</td><td>100</td></tr>' + '</tbody></table><br /> Para comprar un artículo usa el comando /buy (artículo)' + '<br /> Algunos artículos solo se pueden comprar contactando con un Administrador. Para más información usa /shophelp' + '</center>'); }, ayudatienda: 'shophelp', shophelp: function () { if (!this.canBroadcast()) return false; this.sendReplyBox( "<center><h3><b><u>Tienda de Viridian</u></b></h3></center>" + "<b>Comandos Básicos:</b><br /><br />" + "/shop - Muestra los artículos de la tienda.<br />" + "/buy (artículo) - Compra un artículo de la tienda.<br />" + "/pd (user) - muestra los ahorros de un usuario.<br />" + "/donate (user), (money) - Dona una cantidad determinada a otro usuario.<br />" + "<br />" + "<b>Comandos Específicos:</b><br /><br />" + "/tc (user) - Muestra la tarjeta de entrenador de un usuario.<br />" + "/tcimage (link) - Cambia la imagen de la Tc.<br />" + "/tcphrase (text) - Cambia la frase de la Tc.<br />" + "/tcpokemon (pokemon1),(pokemon2)... - Cambia Los sprites de los pokemon de la Tc.<br />" + "/tchtml (html) - Modifica la Tarjeta de entrenador personalizada.<br />" + "/customsymbol (symbol) - Cambia el símbolo a uno personalizado, pero sin cambiar por ello el rango.<br />" + "/resetsymbol - Reestablece el símbolo por omisión.<br />" + "<br />" + "<b>Comandos Administrativos:</b><br /><br />" + "/givemoney (user), (pds) - Da una cantidad de Pds a un usuario.<br />" + "/removemoney (user), (pds) - Quita una cantidad de Pds a un usuario.<br />" + "/symbolpermision (user), (on/off) - Da o Quita el permiso para usar Custom Symbols.<br />" + "/removetc (user) - Elimina una tarjeta de entrenador.<br />" + "/setcustomtc (user), (on/off) - Establece el permiso para usar una Tc personalizada.<br />" + "/sethtmltc (user), (html) - Modifica la Tc personalizada de un usuario.<br />" ); }, comprar: 'buy', buy: function (target, room, user) { var params = target.split(','); var prize = 0; if (!params) return this.sendReply("Usage: /buy object"); var article = toId(params[0]); switch (article) { case 'customtc': prize = 10000; if (Shop.getUserMoney(user.name) < prize) return this.sendReply("No tienes suficiente dinero."); var tcUser = Shop.getTrainerCard(user.name); if (!tcUser) { Shop.giveTrainerCard(user.name); tcUser = Shop.getTrainerCard(user.name); } if (tcUser.customTC) return this.sendReply("Ya poseías este artículo."); Shop.setCustomTrainerCard(user.name, true); Shop.removeMoney(user.name, prize); return this.sendReply("Has comprado una Tarjeta de entreador personalizada. Consulta /shophelp para más información."); break; case 'tc': prize = 3000; if (Shop.getUserMoney(user.name) < prize) return this.sendReply("No tienes suficiente dinero."); var tcUser = Shop.getTrainerCard(user.name); if (tcUser) return this.sendReply("Ya poseías este artículo."); Shop.giveTrainerCard(user.name); Shop.removeMoney(user.name, prize); return this.sendReply("Has comprado una Tarjeta de Entrenador. Revisa /shophelp para saber como editarla."); break; case 'sprite': prize = 100; if (Shop.getUserMoney(user.name) < prize) return this.sendReply("No tienes suficiente dinero."); var tcUser = Shop.getTrainerCard(user.name); if (!tcUser) return this.sendReply("Necesitas comprar primero una Tarjeta de entrenador."); if (tcUser.nPokemon > 5) return this.sendReply("Ya tienes 6 Pokemon para tu tarjeta de entrenador."); if (tcUser.customTC) return this.sendReply("Tu tarjeta es Personalizada. Usa /tchtml pata modificarla."); Shop.nPokemonTrainerCard(user.name, tcUser.nPokemon + 1); Shop.removeMoney(user.name, prize); return this.sendReply("Has comprado un Sprite de un pokemon para tu TC. Revisa /shophelp para más información."); break; case 'chatroom': prize = 8000; if (Shop.getUserMoney(user.name) < prize) return this.sendReply("No tienes suficiente dinero."); if (params.length !== 2) return this.sendReply("Usa el comando así: /buy chatroom,[nombre]"); var id = toId(params[1]); if (Rooms.rooms[id]) return this.sendReply("La sala '" + params[1] + "' ya exsiste. Usa otro nombre."); if (Rooms.global.addChatRoom(params[1])) { if (!Rooms.rooms[id].auth) Rooms.rooms[id].auth = Rooms.rooms[id].chatRoomData.auth = {}; Rooms.rooms[id].auth[toId(user.name)] = '#'; if (Rooms.rooms[id].chatRoomData) Rooms.global.writeChatRoomData(); Shop.removeMoney(user.name, prize); return this.sendReply("La sala '" + params[1] + "' fue creada con éxito. Únete usando /join " + id); } return this.sendReply("No se pudo realizar la compra debido a un error al crear la sala '" + params[1] + "'."); break; case 'symbol': prize = 3000; if (Shop.getUserMoney(user.name) < prize) return this.sendReply("No tienes suficiente dinero."); if (Shop.symbolPermision(user.name)) return this.sendReply("Ya posees este artículo."); Shop.setSymbolPermision(user.name, true); Shop.removeMoney(user.name, prize); return this.sendReply("Has comprado el permiso para usar los comandos /customsymbol y /resetsymbol. Para más información consulta /shophelp."); break; case 'avatar': case 'customavatar': return this.sendReply("Para comprar este artículo dirígete a un administrador."); break; default: return this.sendReply("No has especificado ningún artículo válido."); } }, money: 'pd', pd: function (target, room, user) { var autoData = false; if (!target) autoData = true; if (!this.canBroadcast()) return false; var pds = 0; var userName = user.name; if (autoData) { pds = Shop.getUserMoney(user.name); } else { pds = Shop.getUserMoney(target); userName = toId(target); var userh = Users.getExact(target); if (userh) userName = userh.name; } this.sendReplyBox('Ahorros de <b>' + userName + '</b>: ' + pds + ' pd'); }, trainercard: 'tc', tc: function (target, room, user) { var autoData = false; if (!target) autoData = true; if (!this.canBroadcast()) return false; var pds = 0; var userName = user.name; var tcData = {}; if (autoData) { tcData = Shop.getTrainerCard(user.name); } else { tcData = Shop.getTrainerCard(target); userName = toId(target); var userh = Users.getExact(target); if (userh) userName = userh.name; } if (!tcData) return this.sendReply(userName + " no tenía ninguna tarjeta de entrenador."); if (tcData.customTC) return this.sendReplyBox(tcData.customHtml); var pokeData = '<hr />'; for (var t in tcData.pokemon) { pokeData += '<img src="http://play.pokemonshowdown.com/sprites/xyani/' + Tools.escapeHTML(Shop.getPokemonId(tcData.pokemon[t])) + '.gif" width="auto" /> &nbsp;'; } if (tcData.nPokemon === 0) pokeData = ''; this.sendReplyBox('<center><h2>' + userName + '</h2><img src="' + encodeURI(tcData.image) + '" width="80" height="80" title="' + userName + '" /><br /><br /><b>"' + Tools.escapeHTML(tcData.phrase) + '"</b>' + pokeData + '</center>'); }, givemoney: function (target, room, user) { var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /givemoney usuario, pds"); if (!this.can('givemoney')) return false; var pds = parseInt(params[1]); if (pds <= 0) return this.sendReply("La cantidad no es valida."); var userh = Users.getExact(params[0]); if (!userh || !userh.connected) return this.sendReply("El usuario no existe o no está disponible"); var userName = userh.name; if (!Shop.giveMoney(params[0], pds)) { this.sendReply("Error desconocido."); } else { this.sendReply(userName + ' ha recibido ' + pds + ' pd'); } }, removemoney: function (target, room, user) { var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /removemoney usuario, pds"); if (!this.can('givemoney')) return false; var pds = parseInt(params[1]); if (pds <= 0) return this.sendReply("La cantidad no es valida."); var userh = Users.getExact(params[0]); var userName = toId(params[0]); if (userh) userName = userh.name; if (!Shop.removeMoney(params[0], pds)) { this.sendReply("El usuario no tenía suficientes Pds."); } else { this.sendReply(userName + ' ha perdido ' + pds + ' pd'); } }, donar: 'donate', donate: function (target, room, user) { var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /donate usuario, pds"); var pds = parseInt(params[1]); if (pds <= 0) return this.sendReply("La cantidad no es valida."); var userh = Users.getExact(params[0]); if (!userh || !userh.connected) return this.sendReply("El usuario no existe o no está disponible"); var userName = userh.name; if (!Shop.transferMoney(user.name, params[0], pds)) { this.sendReply("No tienes suficientes pds."); } else { this.sendReply('Has donado ' + pds + ' pd al usuario ' + userName + '.'); } }, symbolpermision: function (target, room, user) { if (!this.can('givemoney')) return false; var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /symbolpermision usuario, [on/off]"); var permision = false; if (toId(params[1]) !== 'on' && toId(params[1]) !== 'off') return this.sendReply("Usage: /symbolpermision usuario, [on/off]"); if (toId(params[1]) === 'on') permision = true; if (permision) { var userh = Users.getExact(params[0]); if (!userh || !userh.connected) return this.sendReply("El usuario no existe o no está disponible"); if (Shop.setSymbolPermision(params[0], permision)) return this.sendReply("Permiso para customsymbols concedido a " + userh.name); return this.sendReply("El usuario ya poseía permiso para usar los customsymbols."); } else { if (Shop.setSymbolPermision(params[0], permision)) return this.sendReply("Permiso para customsymbols retirado a " + params[0]); return this.sendReply("El usuario no tenía ningún permiso que quitar."); } }, simbolo: 'customsymbol', customsymbol: function (target, room, user) { if (!Shop.symbolPermision(user.name)) return this.sendReply('Debes comprar este comando en la tienda para usarlo.'); if (!target || target.length > 1) return this.parse('/help customsymbol'); if (target.match(/[A-Za-z\d]+/g) || '‽!+%@\u2605&~#'.indexOf(target) >= 0) return this.sendReply('Lo sentimos, pero no puedes cambiar el símbolo al que has escogido por razones de seguridad/estabilidad.'); user.getIdentity = function (roomid) { if (!roomid) roomid = 'lobby'; var name = this.name; if (this.locked) { return '‽' + name; } if (this.mutedRooms[roomid]) { return '!' + name; } var room = Rooms.rooms[roomid]; if (room.auth) { if (room.auth[this.userid]) { return room.auth[this.userid] + name; } if (room.isPrivate) return ' ' + name; } return target + name; }; user.updateIdentity(); user.hasCustomSymbol = true; }, resetsymbol: function (target, room, user) { if (!user.hasCustomSymbol) return this.sendReply('No tienes nigún simbolo personalizado.'); user.getIdentity = function (roomid) { if (!roomid) roomid = 'lobby'; var name = this.name; if (this.locked) { return '‽' + name; } if (this.mutedRooms[roomid]) { return '!' + name; } var room = Rooms.rooms[roomid]; if (room.auth) { if (room.auth[this.userid]) { return room.auth[this.userid] + name; } if (room.isPrivate) return ' ' + name; } return this.group + name; }; user.hasCustomSymbol = false; user.updateIdentity(); this.sendReply('Tu simbolo se ha restablecido.'); }, removetc: function (target, room, user) { if (!this.can('givemoney')) return false; if (!target) return this.sendReply("Usage: /removetc usuario"); if (Shop.removeTrainerCard(target)) { return this.sendReply("Tarjeta de entrenador del usuario " + toId(target) + ' eliminada.'); } else { return this.sendReply("El usuario no poseía Tc."); } }, setcustomtc: function (target, room, user) { if (!this.can('givemoney')) return false; var params = target.split(','); if (!params || params.length !== 2) return this.sendReply("Usage: /setcustomtc usuario, [on/off]"); var permision = false; if (toId(params[1]) !== 'on' && toId(params[1]) !== 'off') return this.sendReply("Usage: /setcustomtc usuario, [on/off]"); if (toId(params[1]) === 'on') permision = true; if (permision) { var userh = Users.getExact(params[0]); if (!userh || !userh.connected) return this.sendReply("El usuario no existe o no está disponible"); if (Shop.setCustomTrainerCard(params[0], permision)) return this.sendReply("Permiso para customtrainercards concedido a " + userh.name); return this.sendReply("El usuario no poseía Tc o ya tenía el permiso para customtrainercards."); } else { if (Shop.setCustomTrainerCard(params[0], permision)) return this.sendReply("Permiso para customtrainercards retirado a " + params[0]); return this.sendReply("El usuario no poseía Tc o no tenía el permiso para customtrainercards."); } }, tcimage: function (target, room, user) { if (!target) return this.sendReply("Usage: /tcimage link"); var tcData = Shop.getTrainerCard(user.name); if (!tcData) return this.sendReply("No posees ninguna tarjeta de entrenador."); if (tcData.customTC) return this.sendReply("Tu tarjeta es personalizada. usa /tchtml para cambiarla."); if (target.length > 120) return this.sendReply("El enlace es demasiado largo."); if (Shop.imageTrainerCard(user.name, target)) { return this.sendReply("Imagen de la TC cambiada con éxito."); } else { return this.sendReply("Error al cambiar la imagen de la TC."); } }, tcphrase: function (target, room, user) { if (!target) return this.sendReply("Usage: /tcphrase text"); var tcData = Shop.getTrainerCard(user.name); if (!tcData) return this.sendReply("No posees ninguna tarjeta de entrenador."); if (tcData.customTC) return this.sendReply("Tu tarjeta es personalizada. usa /tchtml para cambiarla."); if (target.length > 120) return this.sendReply("La frase es muy larga."); if (Shop.phraseTrainerCard(user.name, target)) { return this.sendReply("Frase de la TC cambiada con éxito."); } else { return this.sendReply("Error al cambiar la frase de la TC."); } }, tcpokemon: function (target, room, user) { if (!target) return this.sendReply("Usage: /tcpokemon [Pokemon1], [Pokemon2]..."); var params = target.split(','); var tcData = Shop.getTrainerCard(user.name); if (!tcData) return this.sendReply("No posees ninguna tarjeta de entrenador."); if (tcData.customTC) return this.sendReply("Tu tarjeta es personalizada. usa /tchtml para cambiarla."); if (params.length > tcData.nPokemon) return this.sendReply("Has especificado más Pokemon de los que has comprado."); var pokemonList = {}; var pokemonId = ''; for (var h in params) { pokemonId = Tools.escapeHTML(params[h]); if (pokemonId.length > 20) return this.sendReply("Alguno de los nombres de los Pokemon era muy largo."); pokemonList[h] = pokemonId; } if (Shop.pokemonTrainerCard(user.name, pokemonList)) { return this.sendReply("Los pokemon de la Tc han sido modificados."); } else { return this.sendReply("Error al cambiar los pokemon de la TC."); } }, tchtml: 'tccustom', tccustom: function (target, room, user) { if (!target) return this.sendReply("Usage: /tccustom html"); var tcData = Shop.getTrainerCard(user.name); if (!tcData) return this.sendReply("No posees ninguna tarjeta de entrenador."); if (!tcData.customTC) return this.sendReply("Tu tarjeta no es personalizada."); if (target.length > 1000) return this.sendReply("Tu código es demasiado largo. Contacta con un administrador para modificar la TC custom."); var targetABS = Shop.deleteValues(target); if (Shop.htmlTrainerCard(user.name, targetABS)) { return this.sendReply("La tarjeta de entrenador personalizada ha sido modificada."); } else { return this.sendReply("Error al cambiar los datos."); } }, sethtmltc: function (target, room, user) { if (!this.can('givemoney')) return false; var params = target.split(','); if (!params || params.length < 2) return this.sendReply("Usage: /sethtmltc usuario, html"); var tcData = Shop.getTrainerCard(params[0]); if (!tcData) return this.sendReply("El usuario no posee ninguna tarjeta de entrenador."); if (!tcData.customTC) return this.sendReply("La tarjeta no es personalizada."); var targetABS = Shop.deleteValues(target.substr(params[0].length + 1)); if (Shop.htmlTrainerCard(params[0], targetABS)) { return this.sendReply("La tarjeta de entrenador personalizada ha sido modificada."); } else { return this.sendReply("Error al cambiar los datos."); } }, /********************************************************* * Help commands *********************************************************/ commands: 'help', h: 'help', '?': 'help', help: function (target, room, user) { target = target.toLowerCase(); var roomType = room.auth ? room.type + 'Room' : 'global'; var matched = false; if (target === 'all' || target === 'msg' || target === 'pm' || target === 'whisper' || target === 'w') { matched = true; this.sendReply("/msg OR /whisper OR /w [username], [message] - Send a private message."); } if (target === 'all' || target === 'r' || target === 'reply') { matched = true; this.sendReply("/reply OR /r [message] - Send a private message to the last person you received a message from, or sent a message to."); } if (target === 'all' || target === 'rating' || target === 'ranking' || target === 'rank' || target === 'ladder') { matched = true; this.sendReply("/rating - Get your own rating."); this.sendReply("/rating [username] - Get user's rating."); } if (target === 'all' || target === 'nick') { matched = true; this.sendReply("/nick [new username] - Change your username."); } if (target === 'all' || target === 'avatar') { matched = true; this.sendReply("/avatar [new avatar number] - Change your trainer sprite."); } if (target === 'all' || target === 'whois' || target === 'alts' || target === 'ip' || target === 'rooms') { matched = true; this.sendReply("/whois - Get details on yourself: alts, group, IP address, and rooms."); this.sendReply("/whois [username] - Get details on a username: alts (Requires: % @ & ~), group, IP address (Requires: @ & ~), and rooms."); } if (target === 'all' || target === 'data') { matched = true; this.sendReply("/data [pokemon/item/move/ability] - Get details on this pokemon/item/move/ability/nature."); this.sendReply("!data [pokemon/item/move/ability] - Show everyone these details. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'details' || target === 'dt') { matched = true; this.sendReply("/details [pokemon] - Get additional details on this pokemon/item/move/ability/nature."); this.sendReply("!details [pokemon] - Show everyone these details. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'analysis') { matched = true; this.sendReply("/analysis [pokemon], [generation] - Links to the Smogon University analysis for this Pokemon in the given generation."); this.sendReply("!analysis [pokemon], [generation] - Shows everyone this link. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'groups') { matched = true; this.sendReply("/groups - Explains what the " + Config.groups[roomType + 'ByRank'].filter(function (g) { return g.trim(); }).join(" ") + " next to people's names mean."); this.sendReply("!groups - Show everyone that information. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'opensource') { matched = true; this.sendReply("/opensource - Links to PS's source code repository."); this.sendReply("!opensource - Show everyone that information. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'avatars') { matched = true; this.sendReply("/avatars - Explains how to change avatars."); this.sendReply("!avatars - Show everyone that information. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'intro') { matched = true; this.sendReply("/intro - Provides an introduction to competitive pokemon."); this.sendReply("!intro - Show everyone that information. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'cap') { matched = true; this.sendReply("/cap - Provides an introduction to the Create-A-Pokemon project."); this.sendReply("!cap - Show everyone that information. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'om') { matched = true; this.sendReply("/om - Provides links to information on the Other Metagames."); this.sendReply("!om - Show everyone that information. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'learn' || target === 'learnset' || target === 'learnall') { matched = true; this.sendReply("/learn [pokemon], [move, move, ...] - Displays how a Pokemon can learn the given moves, if it can at all."); this.sendReply("!learn [pokemon], [move, move, ...] - Show everyone that information. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'calc' || target === 'calculator') { matched = true; this.sendReply("/calc - Provides a link to a damage calculator"); this.sendReply("!calc - Shows everyone a link to a damage calculator. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'blockchallenges' || target === 'away' || target === 'idle') { matched = true; this.sendReply("/away - Blocks challenges so no one can challenge you. Deactivate it with /back."); } if (target === 'all' || target === 'allowchallenges' || target === 'back') { matched = true; this.sendReply("/back - Unlocks challenges so you can be challenged again. Deactivate it with /away."); } if (target === 'all' || target === 'faq') { matched = true; this.sendReply("/faq [theme] - Provides a link to the FAQ. Add deviation, doubles, randomcap, restart, or staff for a link to these questions. Add all for all of them."); this.sendReply("!faq [theme] - Shows everyone a link to the FAQ. Add deviation, doubles, randomcap, restart, or staff for a link to these questions. Add all for all of them. Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ")); } if (target === 'all' || target === 'highlight') { matched = true; this.sendReply("Set up highlights:"); this.sendReply("/highlight add, word - add a new word to the highlight list."); this.sendReply("/highlight list - list all words that currently highlight you."); this.sendReply("/highlight delete, word - delete a word from the highlight list."); this.sendReply("/highlight delete - clear the highlight list"); } if (target === 'all' || target === 'timestamps') { matched = true; this.sendReply("Set your timestamps preference:"); this.sendReply("/timestamps [all|lobby|pms], [minutes|seconds|off]"); this.sendReply("all - change all timestamps preferences, lobby - change only lobby chat preferences, pms - change only PM preferences"); this.sendReply("off - set timestamps off, minutes - show timestamps of the form [hh:mm], seconds - show timestamps of the form [hh:mm:ss]"); } if (target === 'all' || target === 'effectiveness' || target === 'matchup' || target === 'eff' || target === 'type') { matched = true; this.sendReply("/effectiveness OR /matchup OR /eff OR /type [attack], [defender] - Provides the effectiveness of a move or type on another type or a Pokémon."); this.sendReply("!effectiveness OR !matchup OR !eff OR !type [attack], [defender] - Shows everyone the effectiveness of a move or type on another type or a Pokémon."); } if (target === 'all' || target === 'dexsearch' || target === 'dsearch' || target === 'ds') { matched = true; this.sendReply("/dexsearch [type], [move], [move], ... - Searches for Pokemon that fulfill the selected criteria."); this.sendReply("Search categories are: type, tier, color, moves, ability, gen."); this.sendReply("Valid colors are: green, red, blue, white, brown, yellow, purple, pink, gray and black."); this.sendReply("Valid tiers are: Uber/OU/BL/UU/BL2/RU/BL3/NU/LC/CAP."); this.sendReply("Types must be followed by ' type', e.g., 'dragon type'."); this.sendReply("Parameters can be excluded through the use of '!', e.g., '!water type' excludes all water types."); this.sendReply("The parameter 'mega' can be added to search for Mega Evolutions only, and the parameters 'FE' or 'NFE' can be added to search fully or not-fully evolved Pokemon only."); this.sendReply("The order of the parameters does not matter."); } if (target === 'all' || target === 'dice' || target === 'roll') { matched = true; this.sendReply("/dice [optional max number] - Randomly picks a number between 1 and 6, or between 1 and the number you choose."); this.sendReply("/dice [number of dice]d[number of sides] - Simulates rolling a number of dice, e.g., /dice 2d4 simulates rolling two 4-sided dice."); } if (target === 'all' || target === 'pick' || target === 'pickrandom') { matched = true; this.sendReply("/pick [option], [option], ... - Randomly selects an item from a list containing 2 or more elements."); } if (target === 'all' || target === 'join') { matched = true; this.sendReply("/join [roomname] - Attempts to join the room [roomname]."); } if (target === 'all' || target === 'ignore') { matched = true; this.sendReply("/ignore [user] - Ignores all messages from the user [user]."); this.sendReply("Note that staff messages cannot be ignored."); } if (target === 'all' || target === 'invite') { matched = true; this.sendReply("/invite [username], [roomname] - Invites the player [username] to join the room [roomname]."); } if (Users.can(target, 'lock') || target === 'lock' || target === 'l') { matched = true; this.sendReply("/lock OR /l [username], [reason] - Locks the user from talking in all chats. Requires: " + Users.getGroupsThatCan('lock', room).join(" ")); } if (Users.can(target, 'lock') || target === 'unlock') { matched = true; this.sendReply("/unlock [username] - Unlocks the user. Requires: " + Users.getGroupsThatCan('lock', room).join(" ")); } if (Users.can(target, 'redirect') || target === 'redirect' || target === 'redir') { matched = true; this.sendReply("/redirect or /redir [username], [roomname] - Attempts to redirect the user [username] to the room [roomname]. Requires: " + Users.getGroupsThatCan('redirect', room).join(" ")); } if (Users.can(target, 'staff') || target === 'modnote') { matched = true; this.sendReply("/modnote [note] - Adds a moderator note that can be read through modlog. Requires: " + Users.getGroupsThatCan('staff', room).join(" ")); } if (Users.can(target, 'forcerename') || target === 'forcerename' || target === 'fr') { matched = true; this.sendReply("/forcerename OR /fr [username], [reason] - Forcibly change a user's name and shows them the [reason]. Requires: " + Users.getGroupsThatCan('forcerename').join(" ")); } if (Users.can(target, 'ban') || target === 'roomban') { matched = true; this.sendReply("/roomban [username] - Bans the user from the room you are in. Requires: " + Users.getGroupsThatCan('ban', room).join(" ")); } if (Users.can(target, 'ban') || target === 'roomunban') { matched = true; this.sendReply("/roomunban [username] - Unbans the user from the room you are in. Requires: " + Users.getGroupsThatCan('ban', room).join(" ")); } if (Users.can(target, 'ban') || target === 'ban') { matched = true; this.sendReply("/ban OR /b [username], [reason] - Kick user from all rooms and ban user's IP address with reason. Requires: " + Users.getGroupsThatCan('ban').join(" ")); } if (Users.can(target, 'roompromote') || target === 'roompromote') { matched = true; this.sendReply("/roompromote [username], [group] - Promotes the user to the specified group or next ranked group. Requires: " + Users.getGroupsThatCan('roompromote', room).join(" ")); } if (Users.can(target, 'roompromote') || target === 'roomdemote') { matched = true; this.sendReply("/roomdemote [username], [group] - Demotes the user to the specified group or previous ranked group. Requires: " + Users.getGroupsThatCan('roompromote', room).join(" ")); } if (Users.can(target, 'rangeban') || target === 'banip') { matched = true; this.sendReply("/banip [ip] - Kick users on this IP or IP range from all rooms and bans it. Accepts wildcards to ban ranges. Requires: " + Users.getGroupsThatCan('rangeban').join(" ")); } if (Users.can(target, 'rangeban') || target === 'unbanip') { matched = true; this.sendReply("/unbanip [ip] - Kick users on this IP or IP range from all rooms and bans it. Accepts wildcards to ban ranges. Requires: " + Users.getGroupsThatCan('rangeban').join(" ")); } if (Users.can(target, 'ban') || target === 'unban') { matched = true; this.sendReply("/unban [username] - Unban a user. Requires: " + Users.getGroupsThatCan('ban').join(" ")); } if (Users.can(target, 'ban') || target === 'unbanall') { matched = true; this.sendReply("/unbanall - Unban all IP addresses. Requires: " + Users.getGroupsThatCan('ban').join(" ")); } if (Users.can(target, 'staff') || target === 'modlog') { matched = true; this.sendReply("/modlog [roomid|all], [n] - Roomid defaults to current room. If n is a number or omitted, display the last n lines of the moderator log. Defaults to 15. If n is not a number, search the moderator log for 'n' on room's log [roomid]. If you set [all] as [roomid], searches for 'n' on all rooms's logs. Requires: " + Users.getGroupsThatCan('staff', room).join(" ")); } if (Users.can(target, 'kick') || target === 'kickbattle ') { matched = true; this.sendReply("/kickbattle [username], [reason] - Kicks a user from a battle with reason. Requires: " + Users.getGroupsThatCan('kick').join(" ")); } if (Users.can(target, 'warn') || target === 'warn' || target === 'k') { matched = true; this.sendReply("/warn OR /k [username], [reason] - Warns a user showing them the Pokemon Showdown Rules and [reason] in an overlay. Requires: " + Users.getGroupsThatCan('warn', room).join(" ")); } if (Users.can(target, 'mute') || target === 'mute' || target === 'm') { matched = true; this.sendReply("/mute OR /m [username], [reason] - Mutes a user with reason for 7 minutes. Requires: " + Users.getGroupsThatCan('mute', room).join(" ")); } if (Users.can(target, 'mute') || target === 'hourmute' || target === 'hm') { matched = true; this.sendReply("/hourmute OR /hm [username], [reason] - Mutes a user with reason for an hour. Requires: " + Users.getGroupsThatCan('mute', room).join(" ")); } if (Users.can(target, 'mute') || target === 'unmute' || target === 'um') { matched = true; this.sendReply("/unmute [username] - Removes mute from user. Requires: " + Users.getGroupsThatCan('mute', room).join(" ")); } if (Users.can(target, 'promote') || target === 'promote') { matched = true; this.sendReply("/promote [username], [group] - Promotes the user to the specified group or next ranked group. Requires: " + Users.getGroupsThatCan('promote').join(" ")); } if (Users.can(target, 'promote') || target === 'demote') { matched = true; this.sendReply("/demote [username], [group] - Demotes the user to the specified group or previous ranked group. Requires: " + Users.getGroupsThatCan('promote').join(" ")); } if (Users.can(target, 'forcewin') || target === 'forcetie') { matched = true; this.sendReply("/forcetie - Forces the current match to tie. Requires: " + Users.getGroupsThatCan('forcewin').join(" ")); } if (Users.can(target, 'declare') || target === 'showimage') { matched = true; this.sendReply("/showimage [url], [width], [height] - Show an image. Requires: " + Users.getGroupsThatCan('declare', room).join(" ")); } if (Users.can(target, 'declare') || target === 'declare') { matched = true; this.sendReply("/declare [message] - Anonymously announces a message. Requires: " + Users.getGroupsThatCan('declare', room).join(" ")); } if (Users.can(target, 'gdeclare') || target === 'chatdeclare' || target === 'cdeclare') { matched = true; this.sendReply("/cdeclare [message] - Anonymously announces a message to all chatrooms on the server. Requires: " + Users.getGroupsThatCan('gdeclare').join(" ")); } if (Users.can(target, 'gdeclare') || target === 'globaldeclare' || target === 'gdeclare') { matched = true; this.sendReply("/globaldeclare [message] - Anonymously announces a message to every room on the server. Requires: " + Users.getGroupsThatCan('gdeclare').join(" ")); } if (target === '~' || target === 'htmlbox') { matched = true; this.sendReply("/htmlbox [message] - Displays a message, parsing HTML code contained. Requires: ~ # with global authority"); } if (Users.can(target, 'announce') || target === 'announce' || target === 'wall') { matched = true; this.sendReply("/announce OR /wall [message] - Makes an announcement. Requires: " + Users.getGroupsThatCan('announce', room).join(" ")); } if (Users.can(target, 'modchat') || target === 'modchat') { matched = true; this.sendReply("/modchat [off/autoconfirmed/" + Config.groups[roomType + 'ByRank'].filter(function (g) { return g.trim(); }).join("/") + "] - Set the level of moderated chat. Requires: " + Users.getGroupsThatCan('modchat', room).join(" ") + " for off/autoconfirmed/" + Config.groups[roomType + 'ByRank'].slice(0, 2).filter(function (g) { return g.trim(); }).join("/") + " options, " + Users.getGroupsThatCan('modchatall', room).join(" ") + " for all the options"); } if (Users.can(target, 'hotpatch') || target === 'hotpatch') { matched = true; this.sendReply("Hot-patching the game engine allows you to update parts of Showdown without interrupting currently-running battles. Requires: " + Users.getGroupsThatCan('hotpatch').join(" ")); this.sendReply("Hot-patching has greater memory requirements than restarting."); this.sendReply("/hotpatch chat - reload chat-commands.js"); this.sendReply("/hotpatch battles - spawn new simulator processes"); this.sendReply("/hotpatch formats - reload the tools.js tree, rebuild and rebroad the formats list, and also spawn new simulator processes"); } if (Users.can(target, 'lockdown') || target === 'lockdown') { matched = true; this.sendReply("/lockdown - locks down the server, which prevents new battles from starting so that the server can eventually be restarted. Requires: " + Users.getGroupsThatCan('lockdown').join(" ")); } if (Users.can(target, 'lockdown') || target === 'kill') { matched = true; this.sendReply("/kill - kills the server. Can't be done unless the server is in lockdown state. Requires: " + Users.getGroupsThatCan('lockdown').join(" ")); } if (Users.can(target, 'hotpatch') || target === 'loadbanlist') { matched = true; this.sendReply("/loadbanlist - Loads the bans located at ipbans.txt. The command is executed automatically at startup. Requires: " + Users.getGroupsThatCan('hotpatch').join(" ")); } if (Users.can(target, 'makeroom') || target === 'makechatroom') { matched = true; this.sendReply("/makechatroom [roomname] - Creates a new room named [roomname]. Requires: " + Users.getGroupsThatCan('makeroom').join(" ")); } if (Users.can(target, 'makeroom') || target === 'deregisterchatroom') { matched = true; this.sendReply("/deregisterchatroom [roomname] - Deletes room [roomname] after the next server restart. Requires: " + Users.getGroupsThatCan('makeroom').join(" ")); } if (Users.can(target, 'roompromote', Config.groups[roomType + 'ByRank'].slice(-1)[0]) || target === 'roomowner') { matched = true; this.sendReply("/roomowner [username] - Appoints [username] as a room owner. Removes official status. Requires: " + Users.getGroupsThatCan('roompromote', Config.groups[roomType + 'ByRank'].slice(-1)[0]).join(" ")); } if (Users.can(target, 'roompromote', Config.groups[roomType + 'ByRank'].slice(-1)[0]) || target === 'roomdeowner') { matched = true; this.sendReply("/roomdeowner [username] - Removes [username]'s status as a room owner. Requires: " + Users.getGroupsThatCan('roompromote', Config.groups[roomType + 'ByRank'].slice(-1)[0]).join(" ")); } if (Users.can(target, 'privateroom') || target === 'privateroom') { matched = true; this.sendReply("/privateroom [on/off] - Makes or unmakes a room private. Requires: " + Users.getGroupsThatCan('privateroom', room).join(" ")); } if (target === 'all' || target === 'help' || target === 'h' || target === '?' || target === 'commands') { matched = true; this.sendReply("/help OR /h OR /? - Gives you help."); } if (!target) { this.sendReply("COMMANDS: /nick, /avatar, /rating, /whois, /msg, /reply, /ignore, /away, /back, /timestamps, /highlight"); this.sendReply("INFORMATIONAL COMMANDS: /data, /dexsearch, /groups, /opensource, /avatars, /faq, /rules, /intro, /tiers, /othermetas, /learn, /analysis, /calc (replace / with ! to broadcast. (Requires: " + Users.getGroupsThatCan('broadcast', room).join(" ") + "))"); this.sendReply("For details on all room commands, use /roomhelp"); this.sendReply("For details on all commands, use /help all"); if (user.group !== Config.groups.default[roomType]) { this.sendReply("DRIVER COMMANDS: /warn, /mute, /unmute, /alts, /forcerename, /modlog, /lock, /unlock, /announce, /redirect"); this.sendReply("MODERATOR COMMANDS: /ban, /unban, /ip"); this.sendReply("LEADER COMMANDS: /declare, /forcetie, /forcewin, /promote, /demote, /banip, /unbanall"); this.sendReply("For details on all moderator commands, use /help " + Users.getGroupsThatCan('staff', room)[0]); } this.sendReply("For details of a specific command, use something like: /help data"); } else if (!matched) { this.sendReply("The command '" + target + "' was not found. Try /help for general help"); } }, };
Fix indenting
config/commands.js
Fix indenting
<ide><path>onfig/commands.js <ide> tienda: 'shop', <ide> shop: function (target, room, user) { <ide> if (!this.canBroadcast()) return false; <del> this.sendReplyBox('<center><h3><b><u>Tienda de Viridian</u></b></h3><table border="1" cellspacing="0" cellpadding="3" target="_blank"><tbody>' + <del> '<tr><th>Art&iacute;culo</th><th>Descripci&oacute;n</th><th>Coste</th></tr>' + <del> '<tr><td>CustomTC</td><td>Compra una Tarjeta de Entrenador personalizada (a partir de código html). Contactar con un administrador si el código es muy largo para un solo mensaje.</td><td>10000</td></tr>' + <del> '<tr><td>Chatroom</td><td>Compra una Sala de chat. Será pública o privada en función del motivo de su compra. Si se detecta spam de comandos / saturación del modlog será borrada.</td><td>8000</td></tr>' + <del> '<tr><td>CustomAvatar</td><td>Compra un avatar personalizado. Preferiblemente debe ser una imagen de pequeñas dimensiones y acorde a las reglas del servidor. Contactar con un Admin para obtener este art&iacute;culo.</td><td>6000</td></tr>' + <del> '<tr><td>TC</td><td>Compra una Tarjeta de entrenador básica. Con una Imagen modificable con /tcimage y una frase de entrenador modificable con /tcphrase</td><td>3000</td></tr>' + <del> '<tr><td>Symbol</td><td>Compra el acceso al comado /customsymbol que permite elegir un símbolo (excepto staff) para aparecer en lo alto de la lista de usuarios.</td><td>3000</td></tr>' + <del> '<tr><td>Avatar</td><td>Si ya tienes un avatar personaliado. Puedes cambiarlo por otro diferente. Contactar con un administrador para obtener este art&iacute;culo.</td><td>1000</td></tr>' + <del> '<tr><td>Sprite</td><td>Añade la imagen de un Pokemon a tu TC Básica. Máximo 6. Se pueden cambiar los pokemon con el comando /tcpokemon</td><td>100</td></tr>' + <del> '</tbody></table><br /> Para comprar un artículo usa el comando /buy (artículo)' + <del> '<br /> Algunos artículos solo se pueden comprar contactando con un Administrador. Para más información usa /shophelp' + <del> '</center>'); <add> this.sendReplyBox( <add> '<center><h3><b><u>Tienda de Viridian</u></b></h3><table border="1" cellspacing="0" cellpadding="3" target="_blank"><tbody>' + <add> '<tr><th>Art&iacute;culo</th><th>Descripci&oacute;n</th><th>Coste</th></tr>' + <add> '<tr><td>CustomTC</td><td>Compra una Tarjeta de Entrenador personalizada (a partir de código html). Contactar con un administrador si el código es muy largo para un solo mensaje.</td><td>10000</td></tr>' + <add> '<tr><td>Chatroom</td><td>Compra una Sala de chat. Será pública o privada en función del motivo de su compra. Si se detecta spam de comandos / saturación del modlog será borrada.</td><td>8000</td></tr>' + <add> '<tr><td>CustomAvatar</td><td>Compra un avatar personalizado. Preferiblemente debe ser una imagen de pequeñas dimensiones y acorde a las reglas del servidor. Contactar con un Admin para obtener este art&iacute;culo.</td><td>6000</td></tr>' + <add> '<tr><td>TC</td><td>Compra una Tarjeta de entrenador básica. Con una Imagen modificable con /tcimage y una frase de entrenador modificable con /tcphrase</td><td>3000</td></tr>' + <add> '<tr><td>Symbol</td><td>Compra el acceso al comado /customsymbol que permite elegir un símbolo (excepto staff) para aparecer en lo alto de la lista de usuarios.</td><td>3000</td></tr>' + <add> '<tr><td>Avatar</td><td>Si ya tienes un avatar personaliado. Puedes cambiarlo por otro diferente. Contactar con un administrador para obtener este art&iacute;culo.</td><td>1000</td></tr>' + <add> '<tr><td>Sprite</td><td>Añade la imagen de un Pokemon a tu TC Básica. Máximo 6. Se pueden cambiar los pokemon con el comando /tcpokemon</td><td>100</td></tr>' + <add> '</tbody></table><br /> Para comprar un artículo usa el comando /buy (artículo)' + <add> '<br /> Algunos artículos solo se pueden comprar contactando con un Administrador. Para más información usa /shophelp' + <add> '</center>' <add> ); <ide> }, <ide> <ide> ayudatienda: 'shophelp', <ide> return this.sendReply("La sala '" + params[1] + "' fue creada con éxito. Únete usando /join " + id); <ide> } <ide> return this.sendReply("No se pudo realizar la compra debido a un error al crear la sala '" + params[1] + "'."); <del> break; <add> break; <ide> case 'symbol': <ide> prize = 3000; <ide> if (Shop.getUserMoney(user.name) < prize) return this.sendReply("No tienes suficiente dinero."); <ide> Shop.setSymbolPermision(user.name, true); <ide> Shop.removeMoney(user.name, prize); <ide> return this.sendReply("Has comprado el permiso para usar los comandos /customsymbol y /resetsymbol. Para más información consulta /shophelp."); <del> break; <add> break; <ide> case 'avatar': <ide> case 'customavatar': <ide> return this.sendReply("Para comprar este artículo dirígete a un administrador.");
Java
apache-2.0
717d5ccc65b3ae17ee78b3884a223821a2f7432b
0
PDXFinder/pdxfinder,PDXFinder/pdxfinder,PDXFinder/pdxfinder,PDXFinder/pdxfinder
package org.pdxfinder.graph.dao; import org.neo4j.ogm.annotation.Index; import org.neo4j.ogm.annotation.NodeEntity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import java.util.HashSet; import java.util.Set; /** * Created by jmason on 17/03/2017. */ @NodeEntity public class Marker { @Id @GeneratedValue Long id; @Index String hgncSymbol; // This is the approved Symbol in HGNC - KRAS String hgncName; // This is the approved name in HGNC KRAS proto-oncogene, GTPase String hgncId; // This is the hugo unique ID - e.g HGNC:6407 String ucscGeneId; String ensemblGeneId; String ncbiGeneId; String uniprotId; @Index Set<String> prevSymbols; @Index Set<String> aliasSymbols; // This was formerly called synonymns public Marker() { } public Marker(String hgncSymbol, String hgncName) { this.hgncSymbol = hgncSymbol; this.hgncName = hgncName; } public String getHgncSymbol() { return hgncSymbol; } public void setHgncSymbol(String hgncSymbol) { this.hgncSymbol = hgncSymbol; } public String getHgncName() { return hgncName; } public void setHgncName(String hgncName) { this.hgncName = hgncName; } public String getHgncId() { return hgncId; } public void setHgncId(String hgncId) { this.hgncId = hgncId; } public String getUcscGeneId() { return ucscGeneId; } public void setUcscGeneId(String ucscGeneId) { this.ucscGeneId = ucscGeneId; } public String getUniprotId() { return uniprotId; } public void setUniprotId(String uniprotId) { this.uniprotId = uniprotId; } public String getEnsemblGeneId() { return ensemblGeneId; } public void setEnsemblGeneId(String ensemblGeneId) { this.ensemblGeneId = ensemblGeneId; } public String getNcbiGeneId() { return ncbiGeneId; } public void setNcbiGeneId(String ncbiGeneId) { this.ncbiGeneId = ncbiGeneId; } public Set<String> getPrevSymbols() { return prevSymbols; } public Set<String> getAliasSymbols() { return aliasSymbols; } public void setAliasSymbols(Set<String> aliasSymbols) { this.aliasSymbols = aliasSymbols; } public void addPrevSymbol(String s){ if(this.prevSymbols == null){ this.prevSymbols = new HashSet<>(); } this.prevSymbols.add(s); } public void addAliasSymbols(String s){ if(this.aliasSymbols == null){ this.aliasSymbols = new HashSet<>(); } this.aliasSymbols.add(s); } public void setPrevSymbols(Set<String> prevSymbols) { this.prevSymbols = prevSymbols; } }
data-model/src/main/java/org/pdxfinder/graph/dao/Marker.java
package org.pdxfinder.graph.dao; import org.neo4j.ogm.annotation.Index; import org.neo4j.ogm.annotation.NodeEntity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import java.util.HashSet; import java.util.Set; /** * Created by jmason on 17/03/2017. */ @NodeEntity public class Marker { @Id @GeneratedValue Long id; @Index String hgncSymbol; // This is the approved Symbol in HGNC - KRAS String hgncName; // This is the approved name in HGNC KRAS proto-oncogene, GTPase String hgncId; // This is the hugo unique ID - e.g HGNC:6407 String ucscGeneId; String ensemblGeneId; String ncbiGeneId; String uniprotId;// e.g For human KRAS : P01116 @Index Set<String> prevSymbols; @Index Set<String> aliasSymbols; // This was formerly called synonymns public Marker() { } public Marker(String hgncSymbol, String hgncName) { this.hgncSymbol = hgncSymbol; this.hgncName = hgncName; } public String getHgncSymbol() { return hgncSymbol; } public void setHgncSymbol(String hgncSymbol) { this.hgncSymbol = hgncSymbol; } public String getHgncName() { return hgncName; } public void setHgncName(String hgncName) { this.hgncName = hgncName; } public String getHgncId() { return hgncId; } public void setHgncId(String hgncId) { this.hgncId = hgncId; } public String getUcscGeneId() { return ucscGeneId; } public void setUcscGeneId(String ucscGeneId) { this.ucscGeneId = ucscGeneId; } public String getUniprotId() { return uniprotId; } public void setUniprotId(String uniprotId) { this.uniprotId = uniprotId; } public String getEnsemblGeneId() { return ensemblGeneId; } public void setEnsemblGeneId(String ensemblGeneId) { this.ensemblGeneId = ensemblGeneId; } public String getNcbiGeneId() { return ncbiGeneId; } public void setNcbiGeneId(String ncbiGeneId) { this.ncbiGeneId = ncbiGeneId; } public Set<String> getPrevSymbols() { return prevSymbols; } public Set<String> getAliasSymbols() { return aliasSymbols; } public void setAliasSymbols(Set<String> aliasSymbols) { this.aliasSymbols = aliasSymbols; } public void addPrevSymbol(String s){ if(this.prevSymbols == null){ this.prevSymbols = new HashSet<>(); } this.prevSymbols.add(s); } public void addAliasSymbols(String s){ if(this.aliasSymbols == null){ this.aliasSymbols = new HashSet<>(); } this.aliasSymbols.add(s); } public void setPrevSymbols(Set<String> prevSymbols) { this.prevSymbols = prevSymbols; } }
Update Marker.java
data-model/src/main/java/org/pdxfinder/graph/dao/Marker.java
Update Marker.java
<ide><path>ata-model/src/main/java/org/pdxfinder/graph/dao/Marker.java <ide> <ide> String ensemblGeneId; <ide> String ncbiGeneId; <del> String uniprotId;// e.g For human KRAS : P01116 <del> <add> String uniprotId; <add> <ide> @Index <ide> Set<String> prevSymbols; <ide> @Index
Java
apache-2.0
ce8924c275998315ac105646d36037079d746b78
0
windofthesky/AutoConfigServer
package configmanageserver; import java.util.Timer; import java.util.TimerTask; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPubSub; /** * @ClassName: ScheduledTimerTask. * @Description: this class extends from TimerTask and override the run() function which will be called when time's up. */ class ScheduledTimerTask extends TimerTask { /** * @FieldName: ipaddr. * @Description: the ip address of the redis server which is used to store the parameter. */ private String ipaddr; /** * @FieldName: channel. * @Description: the channel which is used to publish message of application. */ private String channel; /** * @Title: setIPAddr. * @Description: the function which is used to assign ip to private ipaddr. * @param ip: the redis server ip address. * @return none. */ public void setIPAddr(String ip) { this.ipaddr = ip; } /** * @Title: setChannel. * @Description: the function which is used to assign channel. * @param chnl: the channel on the redis server. * @return none. */ public void setChannel(String chnl) { this.channel = chnl; } @Override public void run() { System.out.println("Time's up!!"); Jedis jedis = new Jedis(ipaddr, 6379, 0); /* * if user application has some monitor parameters,they should be got here * and then publish them to specific monitor channels. * the code shoule be as below: * * if(channel.equals("OnLine_UserNum")) * { * String current_online_user_num = app.getOnlineUserNum(); * jedis.publish(channel, current_online_user_num); //publish the online user num. * jedis.quit(); * } * * if user application store the history data of the parameter,the redis command should * like these below: * if(channel.equals("OnLine_UserNum")) * { * String current_online_user_num = app.getOnlineUserNum(); * String current_time = app.getCurrentTime(); * jedis.hset("ONLINE_USERNUM", current_time, current_online_user_num); * jedis.quit(); * } * */ jedis.publish(channel, "this is a test!!!"); jedis.quit(); } } /** * @ClassName: ScheduleTimer. * @Description: this class which is used to submit specific info according to the timer value. */ class ScheduleTimer { /** * @FieldName: timer. * @Description: the private java.util.Timer object of this class. */ private Timer timer; /** * @Title: ScheduleTimer. * @Description: the construct function which is used to initialize the object. * @param ip:the ip address of the redis server. * @param channle: the pub/sub channel on the redis server. * @param time: the interval value of the timer. * @return none. */ public ScheduleTimer(String ip, String channel, int time) { timer = new Timer(); ScheduledTimerTask timerTask = new ScheduledTimerTask(); timerTask.setIPAddr(ip); timerTask.setChannel(channel); System.out.println("Timer Start!!!"); //timer.schedule(new ScheduledTimerTask(), time*1000, time*3000); timer.schedule(timerTask, time*1000, time*1000); } } /** * @ClassName: ConfigClient. * @Description: this class which is client of the config server,the shell of user application. */ public class ConfigClient { /** * @Title: user_def_func. * @Description: the user defined function which is used to re-initialize the user application. * @return none. */ private static void user_def_func() { //this function is defined by Client user,when get the latest config info //and then this function will be called to re-initialize the application config. } /** * @Title: Subscriber. * @Description: the function which is used to subscribe one channel from redis server. * @param ip: the redis server ip address. * @param channel: the specific channel which was subscribed by the application. * @return none. */ private static void Subscriber(final String ip, final String channel) { final JedisPubSub jedisPubSub = new JedisPubSub() { @Override public void onMessage(String channel, String message) { //System.out.println("Input channel =="+channel + "----input message ==" + message); if(channel.equals("USER_SUBSCRIBE_CHANNEL")) { user_def_func(); } //if user's application subscribe more than one channel and more user define functions //could be called here. /* if(channel.equals("USER_SUBSCRIBE_CHANNEL_another") { user_def_func_another(); } */ } }; new Thread(new Runnable() { @Override public void run() { //System.out.println("Start!!!"); try { Jedis jedis = new Jedis(ip, 6379, 0); //0 means no timeout. jedis.subscribe(jedisPubSub, channel); jedis.quit(); jedis.close(); } catch (Exception e) { //e.printStackTrace(); } } }, "subscriberThread").start(); } /** * @Title: Publisher. * @Description: the function which is used to publish message to one channel on redis server. * @param ip: the redis server ip address. * @param channel: the specific channel which the message will be published by the application. * @param message: the message which will be published to specific channel. * @return none. */ private static void Publisher(String ip,String channel, String message) { Jedis jedis = new Jedis(ip, 6379, 0); jedis.publish(channel, message); jedis.quit(); } /** * @Title: main. * @Description: main function of the user application. * @param args: input arguments of the main function. * @return none. */ public static void main(String[] args) { Subscriber("10.1.1.178", "TEST"); //application subscribe one channel(named "TEST"). Publisher("10.1.1.178", "TEST", "this is a test message!"); //application publish message to channel. ScheduleTimer pubTimer =new ScheduleTimer("10.1.1.178", "TEST", 5); } }
src/ConfigClient.java
package configmanageserver; import java.util.Timer; import java.util.TimerTask; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPubSub; /** * @ClassName: ScheduledTimerTask. * @Description: this class extends from TimerTask and override the run() function which will be called when time's up. */ class ScheduledTimerTask extends TimerTask { /** * @FieldName: ipaddr. * @Description: the ip address of the redis server which is used to store the parameter. */ private String ipaddr; /** * @FieldName: channel. * @Description: the channel which is used to publish message of application. */ private String channel; /** * @Title: setIPAddr. * @Description: the function which is used to assign ip to private ipaddr. * @param ip: the redis server ip address. * @return none. */ public void setIPAddr(String ip) { this.ipaddr = ip; } /** * @Title: setChannel. * @Description: the function which is used to assign channel. * @param chnl: the channel on the redis server. * @return none. */ public void setChannel(String chnl) { this.channel = chnl; } @Override public void run() { System.out.println("Time's up!!"); Jedis jedis = new Jedis(ipaddr, 6379, 0); /* * if user application has some monitor parameters,they should be got here * and then publish them to specific monitor channels. * the code shoule be as below: * * if(channel.equals("OnLine_UserNum")) * { * String current_online_user_num = app.getOnlineUserNum(); * jedis.publish(channel, current_online_user_num); //publish the online user num. * jedis.quit(); * } * * if user application store the history data of the parameter,the redis command should * like these below: * if(channel.equals("OnLine_UserNum")) * { * String current_online_user_num = app.getOnlineUserNum(); * String current_time = app.getCurrentTime(); * jedis.hset("ONLINE_USERNUM", current_time, current_online_user_num); * jedis.quit(); * } * */ jedis.publish(channel, "this is a test!!!"); jedis.quit(); } } /** * @ClassName: ScheduleTimer. * @Description: this class which is used to submit specific info according to the timer value. */ class ScheduleTimer { /** * @FieldName: timer. * @Description: the private java.util.Timer object of this class. */ private Timer timer; /** * @Title: ScheduleTimer. * @Description: the construct function which is used to initialize the object. * @param ip:the ip address of the redis server. * @param channle: the pub/sub channel on the redis server. * @param time: the interval value of the timer. * @return none. */ public ScheduleTimer(String ip, String channel, int time) { timer = new Timer(); ScheduledTimerTask timerTask = new ScheduledTimerTask(); timerTask.setIPAddr(ip); timerTask.setChannel(channel); System.out.println("Timer Start!!!"); //timer.schedule(new ScheduledTimerTask(), time*1000, time*3000); timer.schedule(timerTask, time*1000, time*1000); } } /** * @ClassName: ConfigClient. * @Description: this class which is client of the config server,the shell of user application. */ public class ConfigClient { /** * @Title: user_def_func. * @Description: the user defined function which is used to re-initialize the user application. * @return none. */ private static void user_def_func() { //this function is defined by Client user,when get the latest config info //and then this function will be called to re-initialize the application config. } /** * @Title: Subscriber. * @Description: the function which is used to subscribe one channel from redis server. * @param ip: the redis server ip address. * @param channel: the specific channel which was subscribed by the application. * @return none. */ private static void Subscriber(final String ip, final String channel) { final JedisPubSub jedisPubSub = new JedisPubSub() { @Override public void onMessage(String channel, String message) { //System.out.println("Input channel =="+channel + "----input message ==" + message); if(channel.equals("USER_SUBSCRIBE_CHANNEL")) { user_def_func(); } //if user's application subscribe more than one channel and more user define functions //could be called here. /* if(channel.equals("USER_SUBSCRIBE_CHANNEL_another") { user_def_func_another(); } */ } }; new Thread(new Runnable() { @Override public void run() { //System.out.println("Start!!!"); try { Jedis jedis = new Jedis(ip, 6379, 0); //0 means no timeout. jedis.subscribe(jedisPubSub, channel); jedis.quit(); jedis.close(); } catch (Exception e) { //e.printStackTrace(); } } }, "subscriberThread").start(); } /** * @Title: Publisher. * @Description: the function which is used to publish message to one channel on redis server. * @param ip: the redis server ip address. * @param channel: the specific channel which the message will be published by the application. * @param message: the message which will be published to specific channel. * @return none. */ private static void Publisher(String ip,String channel, String message) { Jedis jedis = new Jedis(ip, 6379, 0); jedis.publish(channel, message); jedis.quit(); } /** * @Title: main. * @Description: main function of the user application. * @param args: input arguments of the main function. * @return none. */ public static void main(String[] args) { Subscriber("10.1.1.178", "TEST"); //application subscribe one channel(named "TEST"). Publisher("10.1.1.178", "TEST", "this is a test message!"); //application publish message to channel. ScheduleTimer pubTimer =new ScheduleTimer("10.1.1.178", "TEST", 5); } }
Update ConfigClient.java Modify the code style.
src/ConfigClient.java
Update ConfigClient.java
<ide><path>rc/ConfigClient.java <ide> */ <ide> class ScheduledTimerTask extends TimerTask <ide> { <del> /** <add> /** <ide> * @FieldName: ipaddr. <ide> * @Description: the ip address of the redis server which is used to store the parameter. <ide> */ <del> private String ipaddr; <del> <del> /** <add> private String ipaddr; <add> <add> /** <ide> * @FieldName: channel. <ide> * @Description: the channel which is used to publish message of application. <ide> */ <del> private String channel; <add> private String channel; <ide> <ide> /** <ide> * @Title: setIPAddr. <ide> * @param ip: the redis server ip address. <ide> * @return none. <ide> */ <del> public void setIPAddr(String ip) <del> { <del> this.ipaddr = ip; <del> } <add> public void setIPAddr(String ip) <add> { <add> this.ipaddr = ip; <add> } <ide> <ide> /** <ide> * @Title: setChannel. <ide> * @param chnl: the channel on the redis server. <ide> * @return none. <ide> */ <del> public void setChannel(String chnl) <del> { <del> this.channel = chnl; <del> } <del> <del> @Override <add> public void setChannel(String chnl) <add> { <add> this.channel = chnl; <add> } <add> <add> @Override <ide> public void run() <ide> { <ide> System.out.println("Time's up!!"); <ide> */ <ide> class ScheduleTimer <ide> { <del> /** <add> /** <ide> * @FieldName: timer. <ide> * @Description: the private java.util.Timer object of this class. <ide> */ <ide> private Timer timer; <ide> <del> /** <add> /** <ide> * @Title: ScheduleTimer. <ide> * @Description: the construct function which is used to initialize the object. <del> * @param ip:the ip address of the redis server. <del> * @param channle: the pub/sub channel on the redis server. <add> * @param ip:the ip address of the redis server. <add> * @param channle: the pub/sub channel on the redis server. <ide> * @param time: the interval value of the timer. <ide> * @return none. <ide> */ <ide> * @Description: the user defined function which is used to re-initialize the user application. <ide> * @return none. <ide> */ <del> private static void user_def_func() <del> { <del> //this function is defined by Client user,when get the latest config info <del> //and then this function will be called to re-initialize the application config. <del> } <del> <del> /** <add> private static void user_def_func() <add> { <add> //this function is defined by Client user,when get the latest config info <add> //and then this function will be called to re-initialize the application config. <add> } <add> <add> /** <ide> * @Title: Subscriber. <ide> * @Description: the function which is used to subscribe one channel from redis server. <ide> * @param ip: the redis server ip address. <del> * @param channel: the specific channel which was subscribed by the application. <add> * @param channel: the specific channel which was subscribed by the application. <ide> * @return none. <ide> */ <ide> private static void Subscriber(final String ip, final String channel) <ide> * @Title: Publisher. <ide> * @Description: the function which is used to publish message to one channel on redis server. <ide> * @param ip: the redis server ip address. <del> * @param channel: the specific channel which the message will be published by the application. <del> * @param message: the message which will be published to specific channel. <del> * @return none. <del> */ <del> private static void Publisher(String ip,String channel, String message) <del> { <del> Jedis jedis = new Jedis(ip, 6379, 0); <del> jedis.publish(channel, message); <del> jedis.quit(); <del> } <add> * @param channel: the specific channel which the message will be published by the application. <add> * @param message: the message which will be published to specific channel. <add> * @return none. <add> */ <add> private static void Publisher(String ip,String channel, String message) <add> { <add> Jedis jedis = new Jedis(ip, 6379, 0); <add> jedis.publish(channel, message); <add> jedis.quit(); <add> } <ide> <ide> /** <ide> * @Title: main. <ide> * @param args: input arguments of the main function. <ide> * @return none. <ide> */ <del> public static void main(String[] args) <del> { <del> Subscriber("10.1.1.178", "TEST"); //application subscribe one channel(named "TEST"). <del> Publisher("10.1.1.178", "TEST", "this is a test message!"); //application publish message to channel. <del> ScheduleTimer pubTimer =new ScheduleTimer("10.1.1.178", "TEST", 5); <del> } <add> public static void main(String[] args) <add> { <add> Subscriber("10.1.1.178", "TEST"); //application subscribe one channel(named "TEST"). <add> Publisher("10.1.1.178", "TEST", "this is a test message!"); //application publish message to channel. <add> ScheduleTimer pubTimer =new ScheduleTimer("10.1.1.178", "TEST", 5); <add> } <ide> }
Java
mit
88769a876dfbf8def01a0443d7c7266587b9b5b4
0
SpongePowered/Sponge,SpongePowered/Sponge,SpongePowered/SpongeCommon,SpongePowered/Sponge,SpongePowered/SpongeCommon
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.mixin.core.util; import com.google.common.base.MoreObjects; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EntityDamageSourceIndirect; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentTranslation; import net.minecraft.world.Explosion; import org.spongepowered.api.Sponge; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.event.cause.entity.damage.DamageType; import org.spongepowered.api.event.cause.entity.damage.DamageTypes; import org.spongepowered.api.event.cause.entity.damage.source.DamageSource; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.common.registry.provider.DamageSourceToTypeProvider; import java.util.Optional; import java.util.UUID; @Mixin(value = net.minecraft.util.DamageSource.class, priority = 990) public abstract class MixinDamageSource implements DamageSource { @Shadow public String damageType; @Shadow public abstract boolean isProjectile(); @Shadow public abstract boolean isUnblockable(); @Shadow public abstract boolean canHarmInCreative(); @Shadow public abstract boolean isDamageAbsolute(); @Shadow public abstract boolean isMagicDamage(); @Shadow public abstract float getHungerDamage(); @Shadow public abstract boolean isDifficultyScaled(); @Shadow public abstract boolean isExplosion(); private DamageType apiDamageType; @Inject(method = "<init>", at = @At("RETURN")) private void spongeSetDamageTypeFromConstructor(String damageTypeIn, CallbackInfo ci) { if (!damageTypeIn.contains(":")) { this.apiDamageType = DamageSourceToTypeProvider.getInstance().getOrCustom(damageTypeIn); } else { this.apiDamageType = Sponge.getRegistry().getType(DamageType.class, damageTypeIn).orElse(DamageTypes.CUSTOM); } } @Inject(method = "getDeathMessage(Lnet/minecraft/entity/EntityLivingBase;)Lnet/minecraft/util/text/ITextComponent;", cancellable = true, at = @At(value = "RETURN")) private void beforeGetDeathMessageReturn(EntityLivingBase entityLivingBaseIn, CallbackInfoReturnable<ITextComponent> cir) { // This prevents untranslated keys from appearing in death messages, switching out those that are untranslated with the generic message. if (cir.getReturnValue().getUnformattedText().equals("death.attack." + this.damageType)) { cir.setReturnValue(new TextComponentTranslation("death.attack.generic", entityLivingBaseIn.getDisplayName())); } } @Inject(method = "causeExplosionDamage(Lnet/minecraft/world/Explosion;)Lnet/minecraft/util/DamageSource;", at = @At("HEAD"), cancellable = true) private static void onSetExplosionSource(Explosion explosionIn, CallbackInfoReturnable<net.minecraft.util.DamageSource> cir) { if (explosionIn != null && explosionIn.exploder != null && explosionIn.world != null) { if (explosionIn.getExplosivePlacedBy() == null) { // check creator Entity spongeEntity = (Entity) explosionIn.exploder; Optional<UUID> creatorUuid = spongeEntity.getCreator(); if (creatorUuid.isPresent()) { EntityPlayer player = explosionIn.world.getPlayerEntityByUUID(creatorUuid.get()); if (player != null) { EntityDamageSourceIndirect damageSource = new EntityDamageSourceIndirect("explosion.player", explosionIn.exploder, player); damageSource.setDifficultyScaled().setExplosion(); cir.setReturnValue(damageSource); } } } } } @Override public boolean isExplosive() { return isExplosion(); } @Override public boolean isMagic() { return isMagicDamage(); } @Override public boolean doesAffectCreative() { return canHarmInCreative(); } @Override public boolean isAbsolute() { return isDamageAbsolute(); } @Override public boolean isBypassingArmor() { return isUnblockable(); } @Override public boolean isScaledByDifficulty() { return isDifficultyScaled(); } @Override public double getExhaustion() { return getHungerDamage(); } @Override public DamageType getType() { return this.apiDamageType; } @Override public String toString() { return MoreObjects.toStringHelper("DamageSource") .add("Name", this.damageType) .add("Type", this.apiDamageType.getId()) .toString(); } }
src/main/java/org/spongepowered/common/mixin/core/util/MixinDamageSource.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.mixin.core.util; import com.google.common.base.MoreObjects; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EntityDamageSourceIndirect; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentTranslation; import net.minecraft.world.Explosion; import org.spongepowered.api.Sponge; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.event.cause.entity.damage.DamageType; import org.spongepowered.api.event.cause.entity.damage.DamageTypes; import org.spongepowered.api.event.cause.entity.damage.source.DamageSource; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.common.registry.provider.DamageSourceToTypeProvider; import java.util.Optional; import java.util.UUID; @Mixin(value = net.minecraft.util.DamageSource.class, priority = 990) public abstract class MixinDamageSource implements DamageSource { @Shadow public String damageType; @Shadow public abstract boolean isProjectile(); @Shadow public abstract boolean isUnblockable(); @Shadow public abstract boolean canHarmInCreative(); @Shadow public abstract boolean isDamageAbsolute(); @Shadow public abstract boolean isMagicDamage(); @Shadow public abstract float getHungerDamage(); @Shadow public abstract boolean isDifficultyScaled(); @Shadow public abstract boolean isExplosion(); private DamageType apiDamageType; @Inject(method = "<init>", at = @At("RETURN")) private void spongeSetDamageTypeFromConstructor(String damageTypeIn, CallbackInfo ci) { if (damageTypeIn.contains(":")) { this.apiDamageType = DamageSourceToTypeProvider.getInstance().getOrCustom(damageTypeIn); } else { this.apiDamageType = Sponge.getRegistry().getType(DamageType.class, damageTypeIn).orElse(DamageTypes.CUSTOM); } } @Inject(method = "getDeathMessage(Lnet/minecraft/entity/EntityLivingBase;)Lnet/minecraft/util/text/ITextComponent;", cancellable = true, at = @At(value = "RETURN")) private void beforeGetDeathMessageReturn(EntityLivingBase entityLivingBaseIn, CallbackInfoReturnable<ITextComponent> cir) { // This prevents untranslated keys from appearing in death messages, switching out those that are untranslated with the generic message. if (cir.getReturnValue().getUnformattedText().equals("death.attack." + this.damageType)) { cir.setReturnValue(new TextComponentTranslation("death.attack.generic", entityLivingBaseIn.getDisplayName())); } } @Inject(method = "causeExplosionDamage(Lnet/minecraft/world/Explosion;)Lnet/minecraft/util/DamageSource;", at = @At("HEAD"), cancellable = true) private static void onSetExplosionSource(Explosion explosionIn, CallbackInfoReturnable<net.minecraft.util.DamageSource> cir) { if (explosionIn != null && explosionIn.exploder != null && explosionIn.world != null) { if (explosionIn.getExplosivePlacedBy() == null) { // check creator Entity spongeEntity = (Entity) explosionIn.exploder; Optional<UUID> creatorUuid = spongeEntity.getCreator(); if (creatorUuid.isPresent()) { EntityPlayer player = explosionIn.world.getPlayerEntityByUUID(creatorUuid.get()); if (player != null) { EntityDamageSourceIndirect damageSource = new EntityDamageSourceIndirect("explosion.player", explosionIn.exploder, player); damageSource.setDifficultyScaled().setExplosion(); cir.setReturnValue(damageSource); } } } } } @Override public boolean isExplosive() { return isExplosion(); } @Override public boolean isMagic() { return isMagicDamage(); } @Override public boolean doesAffectCreative() { return canHarmInCreative(); } @Override public boolean isAbsolute() { return isDamageAbsolute(); } @Override public boolean isBypassingArmor() { return isUnblockable(); } @Override public boolean isScaledByDifficulty() { return isDifficultyScaled(); } @Override public double getExhaustion() { return getHungerDamage(); } @Override public DamageType getType() { return this.apiDamageType; } @Override public String toString() { return MoreObjects.toStringHelper("DamageSource") .add("Name", this.damageType) .add("Type", this.apiDamageType.getId()) .toString(); } }
Correctly detect the damage type in for registry matching versus vanilla type matching. Signed-off-by: Gabriel Harris-Rouquette <[email protected]>
src/main/java/org/spongepowered/common/mixin/core/util/MixinDamageSource.java
Correctly detect the damage type in for registry matching versus vanilla type matching.
<ide><path>rc/main/java/org/spongepowered/common/mixin/core/util/MixinDamageSource.java <ide> <ide> @Inject(method = "<init>", at = @At("RETURN")) <ide> private void spongeSetDamageTypeFromConstructor(String damageTypeIn, CallbackInfo ci) { <del> if (damageTypeIn.contains(":")) { <add> if (!damageTypeIn.contains(":")) { <ide> this.apiDamageType = DamageSourceToTypeProvider.getInstance().getOrCustom(damageTypeIn); <ide> } else { <ide> this.apiDamageType = Sponge.getRegistry().getType(DamageType.class, damageTypeIn).orElse(DamageTypes.CUSTOM);
Java
apache-2.0
e4f4283c76dd3a13d0bf3a6dc680bd37e8ae5cd4
0
lirui-apache/hive,b-slim/hive,lirui-apache/hive,anishek/hive,sankarh/hive,alanfgates/hive,nishantmonu51/hive,jcamachor/hive,b-slim/hive,b-slim/hive,lirui-apache/hive,anishek/hive,alanfgates/hive,sankarh/hive,vineetgarg02/hive,vineetgarg02/hive,sankarh/hive,b-slim/hive,vineetgarg02/hive,jcamachor/hive,alanfgates/hive,vineetgarg02/hive,nishantmonu51/hive,alanfgates/hive,lirui-apache/hive,anishek/hive,anishek/hive,jcamachor/hive,vineetgarg02/hive,sankarh/hive,vineetgarg02/hive,alanfgates/hive,lirui-apache/hive,nishantmonu51/hive,sankarh/hive,sankarh/hive,lirui-apache/hive,b-slim/hive,jcamachor/hive,vineetgarg02/hive,b-slim/hive,nishantmonu51/hive,sankarh/hive,alanfgates/hive,sankarh/hive,nishantmonu51/hive,alanfgates/hive,vineetgarg02/hive,lirui-apache/hive,lirui-apache/hive,anishek/hive,lirui-apache/hive,b-slim/hive,alanfgates/hive,vineetgarg02/hive,anishek/hive,sankarh/hive,b-slim/hive,anishek/hive,b-slim/hive,anishek/hive,jcamachor/hive,nishantmonu51/hive,jcamachor/hive,jcamachor/hive,nishantmonu51/hive,alanfgates/hive,nishantmonu51/hive,anishek/hive,nishantmonu51/hive,jcamachor/hive,jcamachor/hive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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.apache.hadoop.hive.ql.udf.generic; import java.util.List; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.metastore.conf.MetastoreConf; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.hive.ql.exec.UDFArgumentException; import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.metadata.HiveUtils; import org.apache.hadoop.hive.ql.security.authorization.HiveMetastoreAuthorizationProvider; import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthorizer; import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzPluginException; import org.apache.hadoop.hive.ql.session.SessionState; import org.apache.hadoop.hive.ql.udf.UDFType; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.apache.hadoop.io.BooleanWritable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * UDF to determine whether to enforce restriction of information schema. * This is intended for internal usage only. This function is not a deterministic function, * but a runtime constant. The return value is constant within a query but can be different between queries */ @UDFType(deterministic = false, runtimeConstant = true) @Description(name = "restrict_information_schema", value = "_FUNC_() - Returns whether or not to enable information schema restriction. " + "Currently it is enabled if either HS2 authorizer or metastore authorizer implements policy provider " + "interface.") @NDV(maxNdv = 1) public class GenericUDFRestrictInformationSchema extends GenericUDF { private static final Logger LOG = LoggerFactory.getLogger(GenericUDFRestrictInformationSchema.class.getName()); protected BooleanWritable enabled; @Override public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { if (arguments.length != 0) { throw new UDFArgumentLengthException( "The function RestrictInformationSchema does not take any arguments, but found " + arguments.length); } if (enabled == null) { HiveConf hiveConf = SessionState.getSessionConf(); boolean enableHS2PolicyProvider = false; boolean enableMetastorePolicyProvider = false; HiveAuthorizer authorizer = SessionState.get().getAuthorizerV2(); try { if (hiveConf.getBoolVar(HiveConf.ConfVars.HIVE_AUTHORIZATION_ENABLED) && authorizer.getHivePolicyProvider() != null) { enableHS2PolicyProvider = true; } } catch (HiveAuthzPluginException e) { LOG.warn("Error getting HivePolicyProvider", e); } if (!enableHS2PolicyProvider) { if (MetastoreConf.getVar(hiveConf, MetastoreConf.ConfVars.PRE_EVENT_LISTENERS) != null && !MetastoreConf.getVar(hiveConf, MetastoreConf.ConfVars.PRE_EVENT_LISTENERS).isEmpty() && HiveConf.getVar(hiveConf, HiveConf.ConfVars.HIVE_METASTORE_AUTHORIZATION_MANAGER) != null) { List<HiveMetastoreAuthorizationProvider> authorizerProviders; try { authorizerProviders = HiveUtils.getMetaStoreAuthorizeProviderManagers( hiveConf, HiveConf.ConfVars.HIVE_METASTORE_AUTHORIZATION_MANAGER, SessionState.get().getAuthenticator()); for (HiveMetastoreAuthorizationProvider authProvider : authorizerProviders) { if (authProvider.getHivePolicyProvider() != null) { enableMetastorePolicyProvider = true; break; } } } catch (HiveAuthzPluginException e) { LOG.warn("Error getting HivePolicyProvider", e); } catch (HiveException e) { LOG.warn("Error instantiating hive.security.metastore.authorization.manager", e); } } } if (enableHS2PolicyProvider || enableMetastorePolicyProvider) { enabled = new BooleanWritable(true); } else { enabled = new BooleanWritable(false); } } return PrimitiveObjectInspectorFactory.writableBooleanObjectInspector; } @Override public Object evaluate(DeferredObject[] arguments) throws HiveException { return enabled; } @Override public String getDisplayString(String[] children) { return "RESTRICT_INFORMATION_SCHEMA()"; } @Override public void copyToNewInstance(Object newInstance) throws UDFArgumentException { super.copyToNewInstance(newInstance); // Need to preserve enabled flag GenericUDFRestrictInformationSchema other = (GenericUDFRestrictInformationSchema) newInstance; if (this.enabled != null) { other.enabled = new BooleanWritable(this.enabled.get()); } } }
ql/src/java/org/apache/hadoop/hive/ql/udf/generic/GenericUDFRestrictInformationSchema.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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.apache.hadoop.hive.ql.udf.generic; import java.util.List; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.metastore.conf.MetastoreConf; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.hive.ql.exec.UDFArgumentException; import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.metadata.HiveUtils; import org.apache.hadoop.hive.ql.security.authorization.HiveMetastoreAuthorizationProvider; import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthorizer; import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzPluginException; import org.apache.hadoop.hive.ql.session.SessionState; import org.apache.hadoop.hive.ql.udf.UDFType; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.apache.hadoop.io.BooleanWritable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * UDF to determine whether to enforce restriction of information schema. * This is intended for internal usage only. This function is not a deterministic function, * but a runtime constant. The return value is constant within a query but can be different between queries */ @UDFType(deterministic = false, runtimeConstant = true) @Description(name = "restrict_information_schema", value = "_FUNC_() - Returns whether or not to enable information schema restriction. " + "Currently it is enabled if either HS2 authorizer or metastore authorizer implements policy provider " + "interface.") @NDV(maxNdv = 1) public class GenericUDFRestrictInformationSchema extends GenericUDF { private static final Logger LOG = LoggerFactory.getLogger(GenericUDFRestrictInformationSchema.class.getName()); protected BooleanWritable enabled; @Override public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { if (arguments.length != 0) { throw new UDFArgumentLengthException( "The function RestrictInformationSchema does not take any arguments, but found " + arguments.length); } if (enabled == null) { HiveConf hiveConf = SessionState.getSessionConf(); boolean enableHS2PolicyProvider = false; boolean enableMetastorePolicyProvider = false; HiveAuthorizer authorizer = SessionState.get().getAuthorizerV2(); try { if (hiveConf.getBoolVar(HiveConf.ConfVars.HIVE_AUTHORIZATION_ENABLED) && authorizer.getHivePolicyProvider() != null) { enableHS2PolicyProvider = true; } } catch (HiveAuthzPluginException e) { LOG.warn("Error getting HivePolicyProvider", e); } if (!enableHS2PolicyProvider) { if (MetastoreConf.getVar(hiveConf, MetastoreConf.ConfVars.PRE_EVENT_LISTENERS) != null && !MetastoreConf.getVar(hiveConf, MetastoreConf.ConfVars.PRE_EVENT_LISTENERS).isEmpty() && HiveConf.getVar(hiveConf, HiveConf.ConfVars.HIVE_METASTORE_AUTHORIZATION_MANAGER) != null) { List<HiveMetastoreAuthorizationProvider> authorizerProviders; try { authorizerProviders = HiveUtils.getMetaStoreAuthorizeProviderManagers( hiveConf, HiveConf.ConfVars.HIVE_METASTORE_AUTHORIZATION_MANAGER, SessionState.get().getAuthenticator()); for (HiveMetastoreAuthorizationProvider authProvider : authorizerProviders) { if (authProvider.getHivePolicyProvider() != null) { enableMetastorePolicyProvider = true; break; } } } catch (HiveAuthzPluginException e) { LOG.warn("Error getting HivePolicyProvider", e); } catch (HiveException e) { LOG.warn("Error instantiating hive.security.metastore.authorization.manager", e); } } if (enableHS2PolicyProvider || enableMetastorePolicyProvider) { enabled = new BooleanWritable(true); } else { enabled = new BooleanWritable(false); } } } return PrimitiveObjectInspectorFactory.writableBooleanObjectInspector; } @Override public Object evaluate(DeferredObject[] arguments) throws HiveException { return enabled; } @Override public String getDisplayString(String[] children) { return "RESTRICT_INFORMATION_SCHEMA()"; } @Override public void copyToNewInstance(Object newInstance) throws UDFArgumentException { super.copyToNewInstance(newInstance); // Need to preserve enabled flag GenericUDFRestrictInformationSchema other = (GenericUDFRestrictInformationSchema) newInstance; if (this.enabled != null) { other.enabled = new BooleanWritable(this.enabled.get()); } } }
HIVE-20494: GenericUDFRestrictInformationSchema is broken after HIVE-19440 (Daniel Dai, reviewed by Vaibhav Gumashta)
ql/src/java/org/apache/hadoop/hive/ql/udf/generic/GenericUDFRestrictInformationSchema.java
HIVE-20494: GenericUDFRestrictInformationSchema is broken after HIVE-19440 (Daniel Dai, reviewed by Vaibhav Gumashta)
<ide><path>l/src/java/org/apache/hadoop/hive/ql/udf/generic/GenericUDFRestrictInformationSchema.java <ide> LOG.warn("Error instantiating hive.security.metastore.authorization.manager", e); <ide> } <ide> } <del> <del> if (enableHS2PolicyProvider || enableMetastorePolicyProvider) { <del> enabled = new BooleanWritable(true); <del> } else { <del> enabled = new BooleanWritable(false); <del> } <add> } <add> if (enableHS2PolicyProvider || enableMetastorePolicyProvider) { <add> enabled = new BooleanWritable(true); <add> } else { <add> enabled = new BooleanWritable(false); <ide> } <ide> } <ide>
Java
apache-2.0
44bad8a10ebf99a00d4d759e09008e80db033f36
0
artemnikitin/SeriesGuide,UweTrottmann/SeriesGuide,hoanganhx86/SeriesGuide,r00t-user/SeriesGuide,0359xiaodong/SeriesGuide,epiphany27/SeriesGuide,UweTrottmann/SeriesGuide
package com.battlelancer.seriesguide.ui; import com.battlelancer.seriesguide.R; import com.battlelancer.seriesguide.items.SearchResult; import com.battlelancer.seriesguide.provider.SeriesContract.Episodes; import com.battlelancer.seriesguide.util.ImageDownloader; import com.battlelancer.seriesguide.util.ShareUtils; import com.battlelancer.seriesguide.util.Utils; import com.jakewharton.apibuilder.ApiException; import com.jakewharton.trakt.ServiceManager; import com.jakewharton.trakt.TraktException; import com.jakewharton.trakt.entities.ActivityItem; import com.jakewharton.trakt.entities.ActivityItemBase; import com.jakewharton.trakt.entities.TvShow; import com.jakewharton.trakt.entities.TvShowEpisode; import com.jakewharton.trakt.entities.UserProfile; import com.jakewharton.trakt.enumerations.ActivityType; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.AsyncTaskLoader; import android.support.v4.content.Loader; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class TraktFriendsFragment extends ListFragment implements LoaderManager.LoaderCallbacks<List<UserProfile>> { private TraktFriendsAdapter mAdapter; private boolean mDualPane; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Check to see if we have a frame in which to embed the details // fragment directly in the containing UI. View detailsFragment = getActivity().findViewById(R.id.fragment_details); mDualPane = detailsFragment != null && detailsFragment.getVisibility() == View.VISIBLE; setEmptyText(getString(R.string.friends_empty)); mAdapter = new TraktFriendsAdapter(getActivity()); setListAdapter(mAdapter); getListView().setDivider(null); getListView().setSelector(R.drawable.list_selector_holo_dark); setListShown(false); getLoaderManager().initLoader(0, null, this); } @Override public void onListItemClick(ListView l, View v, int position, long id) { UserProfile friend = (UserProfile) getListView().getItemAtPosition(position); TvShow show = null; TvShowEpisode episode = null; if (friend.watching != null) { show = friend.watching.show; episode = friend.watching.episode; } else if (!friend.watched.isEmpty()) { ActivityItem activity = friend.watched.get(0); show = activity.show; episode = activity.episode; } if (episode != null && show != null) { Cursor episodeidquery = getActivity().getContentResolver().query( Episodes.buildEpisodesOfShowUri(show.tvdbId), new String[] { Episodes._ID }, Episodes.NUMBER + "=? AND " + Episodes.SEASON + "=?", new String[] { String.valueOf(episode.number), String.valueOf(episode.season) }, null); if (episodeidquery.getCount() != 0) { // display the episode details if we have a match episodeidquery.moveToFirst(); String episodeId; episodeId = episodeidquery.getString(0); showDetails(episodeId); } else { // offer to add the show if it's not in the show database yet SearchResult newshow = new SearchResult(); newshow.tvdbid = show.tvdbId; newshow.title = show.title; newshow.overview = show.overview; AddDialogFragment.showAddDialog(newshow, getFragmentManager()); } episodeidquery.close(); } } private void showDetails(String episodeId) { if (mDualPane) { // Check if fragment is shown, create new if needed. EpisodeDetailsFragment detailsFragment = (EpisodeDetailsFragment) getFragmentManager() .findFragmentById(R.id.fragment_details); if (detailsFragment == null || !detailsFragment.getEpisodeId().equalsIgnoreCase(episodeId)) { // Make new fragment to show this selection. detailsFragment = EpisodeDetailsFragment.newInstance(episodeId, true); // Execute a transaction, replacing any existing // fragment with this one inside the frame. FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.fragment_details, detailsFragment, "fragmentDetails"); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); } } else { Intent intent = new Intent(); intent.setClass(getActivity(), EpisodeDetailsActivity.class); intent.putExtra(EpisodeDetailsActivity.InitBundle.EPISODE_ID, episodeId); startActivity(intent); } } private static class TraktFriendsLoader extends AsyncTaskLoader<List<UserProfile>> { private List<UserProfile> mFriends; public TraktFriendsLoader(Context context) { super(context); } @Override public List<UserProfile> loadInBackground() { if (ShareUtils.isTraktCredentialsValid(getContext())) { ServiceManager manager = null; try { manager = Utils.getServiceManagerWithAuth(getContext(), false); } catch (Exception e) { // TODO return null; } try { List<UserProfile> friends = manager.userService() .friends(Utils.getTraktUsername(getContext())).fire(); // list watching now separately and first List<UserProfile> friendsActivity = new ArrayList<UserProfile>(); for (UserProfile friend : friends) { if (friend.watching != null && friend.watching.type == ActivityType.Episode) { friendsActivity.add(friend); } } // then include friends which have a watched episode no // longer than 4 weeks in the past // so a friend can appear as watching something right now // and further down with the episode he watched before that for (UserProfile friend : friends) { for (ActivityItem activity : friend.watched) { // is this an episode? if (activity != null && activity.type == ActivityType.Episode) { // is this activity no longer than 4 weeks old? if (activity.watched.getTime() > System.currentTimeMillis() - DateUtils.WEEK_IN_MILLIS * 4) { UserProfile clonedfriend = new UserProfile(); clonedfriend.username = friend.username; clonedfriend.avatar = friend.avatar; List<ActivityItem> watchedclone = new ArrayList<ActivityItem>(); watchedclone.add(activity); clonedfriend.watched = watchedclone; friendsActivity.add(clonedfriend); break; } } } } return friendsActivity; } catch (TraktException te) { // TODO return null; } catch (ApiException ae) { // TODO return null; } } else { // TODO return null; } } /** * Called when there is new data to deliver to the client. The super * class will take care of delivering it; the implementation here just * adds a little more logic. */ @Override public void deliverResult(List<UserProfile> friends) { if (isReset()) { // An async query came in while the loader is stopped. We // don't need the result. if (friends != null) { onReleaseResources(friends); } } List<UserProfile> oldFriends = friends; mFriends = friends; if (isStarted()) { // If the Loader is currently started, we can immediately // deliver its results. super.deliverResult(friends); } if (oldFriends != null) { onReleaseResources(oldFriends); } } @Override protected void onStartLoading() { if (mFriends != null) { deliverResult(mFriends); } else { forceLoad(); } } /** * Handles a request to stop the Loader. */ @Override protected void onStopLoading() { // Attempt to cancel the current load task if possible. cancelLoad(); } /** * Handles a request to cancel a load. */ @Override public void onCanceled(List<UserProfile> friends) { super.onCanceled(friends); onReleaseResources(friends); } /** * Handles a request to completely reset the Loader. */ @Override protected void onReset() { super.onReset(); // Ensure the loader is stopped onStopLoading(); // At this point we can release resources if (mFriends != null) { onReleaseResources(mFriends); mFriends = null; } } /** * Helper function to take care of releasing resources associated with * an actively loaded data set. */ protected void onReleaseResources(List<UserProfile> apps) { // For a simple List<> there is nothing to do. For something // like a Cursor, we would close it here. } } private static class TraktFriendsAdapter extends ArrayAdapter<UserProfile> { private final ImageDownloader mImageDownloader; private final LayoutInflater mInflater; private final SharedPreferences mPrefs; public TraktFriendsAdapter(Context context) { super(context, R.layout.friend); mImageDownloader = ImageDownloader.getInstance(context); mPrefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext()); mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void setData(List<UserProfile> data) { clear(); if (data != null) { for (UserProfile userProfile : data) { add(userProfile); } } } @Override public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid // unneccessary calls to findViewById() on each row. ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.friend, null); holder = new ViewHolder(); holder.name = (TextView) convertView.findViewById(R.id.name); holder.show = (TextView) convertView.findViewById(R.id.show); holder.episode = (TextView) convertView.findViewById(R.id.episode); holder.timestamp = (TextView) convertView.findViewById(R.id.timestamp); holder.avatar = (ImageView) convertView.findViewById(R.id.avatar); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } // TODO refactor! // Bind the data efficiently with the holder. UserProfile friend = getItem(position); holder.name.setText(friend.username); mImageDownloader.download(friend.avatar, holder.avatar); String show = ""; String episode = ""; String timestamp = ""; if (friend.watching != null) { // look if this friend is watching something right now ActivityItemBase watching = friend.watching; switch (watching.type) { case Episode: show = watching.show.title; String episodenumber = Utils.getEpisodeNumber(mPrefs, String.valueOf(watching.episode.season), String.valueOf(watching.episode.number)); episode = episodenumber + " " + watching.episode.title; timestamp = getContext().getString(R.string.now); break; } } else if (friend.watched != null) { // if not display the latest episode he watched List<ActivityItem> watched = friend.watched; ActivityItem latestShow = null; for (ActivityItem mediaEntity : watched) { if (mediaEntity.type == ActivityType.Episode) { latestShow = mediaEntity; break; } } if (latestShow != null) { show = latestShow.show.title; String episodenumber = Utils.getEpisodeNumber(mPrefs, String.valueOf(latestShow.episode.season), String.valueOf(latestShow.episode.number)); episode = episodenumber + " " + latestShow.episode.title; timestamp = (String) DateUtils.getRelativeTimeSpanString( latestShow.watched.getTime(), System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL); } } holder.show.setText(show); holder.episode.setText(episode); holder.timestamp.setText(timestamp); return convertView; } static class ViewHolder { TextView name; TextView show; TextView episode; TextView timestamp; ImageView avatar; } } @Override public Loader<List<UserProfile>> onCreateLoader(int id, Bundle args) { return new TraktFriendsLoader(getActivity()); } @Override public void onLoadFinished(Loader<List<UserProfile>> loader, List<UserProfile> data) { mAdapter.setData(data); if (isResumed()) { setListShown(true); } else { setListShownNoAnimation(true); } } @Override public void onLoaderReset(Loader<List<UserProfile>> loader) { mAdapter.setData(null); } }
SeriesGuide/src/com/battlelancer/seriesguide/ui/TraktFriendsFragment.java
package com.battlelancer.seriesguide.ui; import com.battlelancer.seriesguide.R; import com.battlelancer.seriesguide.items.SearchResult; import com.battlelancer.seriesguide.provider.SeriesContract.Episodes; import com.battlelancer.seriesguide.util.ImageDownloader; import com.battlelancer.seriesguide.util.ShareUtils; import com.battlelancer.seriesguide.util.Utils; import com.jakewharton.apibuilder.ApiException; import com.jakewharton.trakt.ServiceManager; import com.jakewharton.trakt.TraktException; import com.jakewharton.trakt.entities.ActivityItem; import com.jakewharton.trakt.entities.ActivityItemBase; import com.jakewharton.trakt.entities.TvShow; import com.jakewharton.trakt.entities.TvShowEpisode; import com.jakewharton.trakt.entities.UserProfile; import com.jakewharton.trakt.enumerations.ActivityType; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.AsyncTaskLoader; import android.support.v4.content.Loader; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class TraktFriendsFragment extends ListFragment implements LoaderManager.LoaderCallbacks<List<UserProfile>> { private TraktFriendsAdapter mAdapter; private boolean mDualPane; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Check to see if we have a frame in which to embed the details // fragment directly in the containing UI. View detailsFragment = getActivity().findViewById(R.id.fragment_details); mDualPane = detailsFragment != null && detailsFragment.getVisibility() == View.VISIBLE; setEmptyText(getString(R.string.friends_empty)); mAdapter = new TraktFriendsAdapter(getActivity()); setListAdapter(mAdapter); getListView().setDivider(null); getListView().setSelector(R.drawable.list_selector_holo_dark); setListShown(false); getLoaderManager().initLoader(0, null, this); } @Override public void onListItemClick(ListView l, View v, int position, long id) { UserProfile friend = (UserProfile) getListView().getItemAtPosition(position); TvShow show = null; TvShowEpisode episode = null; if (friend.watching != null) { show = friend.watching.show; episode = friend.watching.episode; } else if (!friend.watched.isEmpty()) { ActivityItem activity = friend.watched.get(0); show = activity.show; episode = activity.episode; } if (episode != null && show != null) { Cursor episodeidquery = getActivity().getContentResolver().query( Episodes.buildEpisodesOfShowUri(show.tvdbId), new String[] { Episodes._ID }, Episodes.NUMBER + "=? AND " + Episodes.SEASON + "=?", new String[] { String.valueOf(episode.number), String.valueOf(episode.season) }, null); if (episodeidquery.getCount() != 0) { // display the episode details if we have a match episodeidquery.moveToFirst(); String episodeId; episodeId = episodeidquery.getString(0); showDetails(episodeId); } else { // offer to add the show if it's not in the show database yet SearchResult newshow = new SearchResult(); newshow.tvdbid = show.tvdbId; newshow.title = show.title; newshow.overview = show.overview; AddDialogFragment.showAddDialog(newshow, getFragmentManager()); } episodeidquery.close(); } } private void showDetails(String episodeId) { if (mDualPane) { // Check if fragment is shown, create new if needed. EpisodeDetailsFragment detailsFragment = (EpisodeDetailsFragment) getFragmentManager() .findFragmentById(R.id.fragment_details); if (detailsFragment == null || !detailsFragment.getEpisodeId().equalsIgnoreCase(episodeId)) { // Make new fragment to show this selection. detailsFragment = EpisodeDetailsFragment.newInstance(episodeId, true); // Execute a transaction, replacing any existing // fragment with this one inside the frame. FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.fragment_details, detailsFragment, "fragmentDetails"); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); } } else { Intent intent = new Intent(); intent.setClass(getActivity(), EpisodeDetailsActivity.class); intent.putExtra(EpisodeDetailsActivity.InitBundle.EPISODE_ID, episodeId); startActivity(intent); } } private static class TraktFriendsLoader extends AsyncTaskLoader<List<UserProfile>> { private List<UserProfile> mFriends; public TraktFriendsLoader(Context context) { super(context); } @Override public List<UserProfile> loadInBackground() { if (ShareUtils.isTraktCredentialsValid(getContext())) { ServiceManager manager = null; try { manager = Utils.getServiceManagerWithAuth(getContext(), false); } catch (Exception e) { // TODO return null; } try { List<UserProfile> friends = manager.userService() .friends(Utils.getTraktUsername(getContext())).fire(); // list watching now separately and first List<UserProfile> friendsActivity = new ArrayList<UserProfile>(); for (UserProfile friend : friends) { if (friend.watching != null && friend.watching.type == ActivityType.Episode) { friendsActivity.add(friend); } } // then include friends which have a watched episode no // longer than 4 weeks in the past // so a friend can appear as watching something right now // and further down with the episode he watched before that for (UserProfile friend : friends) { for (ActivityItem activity : friend.watched) { // is this an episode? if (activity.type == ActivityType.Episode) { // is this activity no longer than 4 weeks old? if (activity.watched.getTime() > System.currentTimeMillis() - DateUtils.WEEK_IN_MILLIS * 4) { UserProfile clonedfriend = new UserProfile(); clonedfriend.username = friend.username; clonedfriend.avatar = friend.avatar; List<ActivityItem> watchedclone = new ArrayList<ActivityItem>(); watchedclone.add(activity); clonedfriend.watched = watchedclone; friendsActivity.add(clonedfriend); break; } } } } return friendsActivity; } catch (TraktException te) { // TODO return null; } catch (ApiException ae) { // TODO return null; } } else { // TODO return null; } } /** * Called when there is new data to deliver to the client. The super * class will take care of delivering it; the implementation here just * adds a little more logic. */ @Override public void deliverResult(List<UserProfile> friends) { if (isReset()) { // An async query came in while the loader is stopped. We // don't need the result. if (friends != null) { onReleaseResources(friends); } } List<UserProfile> oldFriends = friends; mFriends = friends; if (isStarted()) { // If the Loader is currently started, we can immediately // deliver its results. super.deliverResult(friends); } if (oldFriends != null) { onReleaseResources(oldFriends); } } @Override protected void onStartLoading() { if (mFriends != null) { deliverResult(mFriends); } else { forceLoad(); } } /** * Handles a request to stop the Loader. */ @Override protected void onStopLoading() { // Attempt to cancel the current load task if possible. cancelLoad(); } /** * Handles a request to cancel a load. */ @Override public void onCanceled(List<UserProfile> friends) { super.onCanceled(friends); onReleaseResources(friends); } /** * Handles a request to completely reset the Loader. */ @Override protected void onReset() { super.onReset(); // Ensure the loader is stopped onStopLoading(); // At this point we can release resources if (mFriends != null) { onReleaseResources(mFriends); mFriends = null; } } /** * Helper function to take care of releasing resources associated with * an actively loaded data set. */ protected void onReleaseResources(List<UserProfile> apps) { // For a simple List<> there is nothing to do. For something // like a Cursor, we would close it here. } } private static class TraktFriendsAdapter extends ArrayAdapter<UserProfile> { private final ImageDownloader mImageDownloader; private final LayoutInflater mInflater; private final SharedPreferences mPrefs; public TraktFriendsAdapter(Context context) { super(context, R.layout.friend); mImageDownloader = ImageDownloader.getInstance(context); mPrefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext()); mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void setData(List<UserProfile> data) { clear(); if (data != null) { for (UserProfile userProfile : data) { add(userProfile); } } } @Override public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid // unneccessary calls to findViewById() on each row. ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.friend, null); holder = new ViewHolder(); holder.name = (TextView) convertView.findViewById(R.id.name); holder.show = (TextView) convertView.findViewById(R.id.show); holder.episode = (TextView) convertView.findViewById(R.id.episode); holder.timestamp = (TextView) convertView.findViewById(R.id.timestamp); holder.avatar = (ImageView) convertView.findViewById(R.id.avatar); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } // TODO refactor! // Bind the data efficiently with the holder. UserProfile friend = getItem(position); holder.name.setText(friend.username); mImageDownloader.download(friend.avatar, holder.avatar); String show = ""; String episode = ""; String timestamp = ""; if (friend.watching != null) { // look if this friend is watching something right now ActivityItemBase watching = friend.watching; switch (watching.type) { case Episode: show = watching.show.title; String episodenumber = Utils.getEpisodeNumber(mPrefs, String.valueOf(watching.episode.season), String.valueOf(watching.episode.number)); episode = episodenumber + " " + watching.episode.title; timestamp = getContext().getString(R.string.now); break; } } else if (friend.watched != null) { // if not display the latest episode he watched List<ActivityItem> watched = friend.watched; ActivityItem latestShow = null; for (ActivityItem mediaEntity : watched) { if (mediaEntity.type == ActivityType.Episode) { latestShow = mediaEntity; break; } } if (latestShow != null) { show = latestShow.show.title; String episodenumber = Utils.getEpisodeNumber(mPrefs, String.valueOf(latestShow.episode.season), String.valueOf(latestShow.episode.number)); episode = episodenumber + " " + latestShow.episode.title; timestamp = (String) DateUtils.getRelativeTimeSpanString( latestShow.watched.getTime(), System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL); } } holder.show.setText(show); holder.episode.setText(episode); holder.timestamp.setText(timestamp); return convertView; } static class ViewHolder { TextView name; TextView show; TextView episode; TextView timestamp; ImageView avatar; } } @Override public Loader<List<UserProfile>> onCreateLoader(int id, Bundle args) { return new TraktFriendsLoader(getActivity()); } @Override public void onLoadFinished(Loader<List<UserProfile>> loader, List<UserProfile> data) { mAdapter.setData(data); if (isResumed()) { setListShown(true); } else { setListShownNoAnimation(true); } } @Override public void onLoaderReset(Loader<List<UserProfile>> loader) { mAdapter.setData(null); } }
Check for null activity.
SeriesGuide/src/com/battlelancer/seriesguide/ui/TraktFriendsFragment.java
Check for null activity.
<ide><path>eriesGuide/src/com/battlelancer/seriesguide/ui/TraktFriendsFragment.java <ide> for (ActivityItem activity : friend.watched) { <ide> <ide> // is this an episode? <del> if (activity.type == ActivityType.Episode) { <add> if (activity != null && activity.type == ActivityType.Episode) { <ide> <ide> // is this activity no longer than 4 weeks old? <ide> if (activity.watched.getTime() > System.currentTimeMillis()
Java
apache-2.0
1cf571b073e73c5243c1b4ca666621f213c1f0c0
0
apache/juddi,apache/juddi,apache/juddi,apache/juddi,apache/juddi
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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. */ package org.apache.juddi.datastore.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.juddi.datatype.CategoryBag; import org.apache.juddi.datatype.KeyedReference; import org.apache.juddi.datatype.request.FindQualifiers; import org.apache.juddi.datatype.tmodel.TModel; import org.apache.juddi.util.Config; import org.apache.juddi.util.jdbc.ConnectionManager; import org.apache.juddi.util.jdbc.Transaction; /** * @author Steve Viens ([email protected]) */ class FindTModelByCategoryQuery { // private reference to the jUDDI logger private static Log log = LogFactory.getLog(FindTModelByCategoryQuery.class); static String selectSQL; static { // build selectSQL StringBuffer sql = new StringBuffer(200); sql.append("SELECT M.TMODEL_KEY,M.LAST_UPDATE "); sql.append("FROM TMODEL M,TMODEL_CATEGORY C "); selectSQL = sql.toString(); } /** * Select ... * * @param connection JDBC connection * @throws java.sql.SQLException */ public static Vector select(CategoryBag categoryBag,Vector keysIn,FindQualifiers qualifiers,Connection connection) throws java.sql.SQLException { // if there is a keysIn vector but it doesn't contain // any keys then the previous query has exhausted // all possibilities of a match so skip this call. if ((keysIn != null) && (keysIn.size() == 0)) return keysIn; Vector keysOut = new Vector(); PreparedStatement statement = null; ResultSet resultSet = null; // construct the SQL statement StringBuffer sql = new StringBuffer(selectSQL); appendWhere(sql,categoryBag,qualifiers); appendIn(sql,keysIn); appendOrderBy(sql,qualifiers); try { log.debug("select from TMODEL & TMODEL_CATEGORY tables:\n\n\t" + sql.toString() + "\n"); statement = connection.prepareStatement(sql.toString()); resultSet = statement.executeQuery(); while (resultSet.next()) keysOut.addElement(resultSet.getString(1));//("TMODEL_KEY")); return keysOut; } finally { try { resultSet.close(); } catch (Exception e) { log.warn("An Exception was encountered while attempting to close " + "the Find TModel ResultSet: "+e.getMessage(),e); } try { statement.close(); } catch (Exception e) { log.warn("An Exception was encountered while attempting to close " + "the Find TModel Statement: "+e.getMessage(),e); } } } /** * */ private static void appendWhere(StringBuffer sql,CategoryBag categoryBag,FindQualifiers qualifiers) { sql.append("WHERE M.TMODEL_KEY = C.TMODEL_KEY "); if(categoryBag != null) { Vector keyedRefVector = categoryBag.getKeyedReferenceVector(); if(keyedRefVector != null) { int vectorSize = keyedRefVector.size(); if (vectorSize > 0) { sql.append("AND ("); for (int i=0; i<vectorSize; i++) { KeyedReference keyedRef = (KeyedReference)keyedRefVector.elementAt(i); String name = keyedRef.getKeyName(); String value = keyedRef.getKeyValue(); String tModelKey = keyedRef.getTModelKey(); if (tModelKey.equals(TModel.GENERAL_KEYWORDS_TMODEL_KEY)) { // DO NOT ignore the name .. if ((name != null) && (value != null)) { sql.append("(C.KEY_NAME = '").append(name).append("' AND C.KEY_VALUE = '").append(value).append("')"); if (i+1 < vectorSize) sql.append(" OR "); } } else { if (value != null) { sql.append("(C.KEY_VALUE = '").append(value).append("')"); if (i+1 < vectorSize) sql.append(" OR "); } } } sql.append(") "); } } } } /** * Utility method used to construct SQL "IN" statements such as * the following SQL example: * * SELECT * FROM TABLE WHERE MONTH IN ('jan','feb','mar') * * @param sql StringBuffer to append the final results to * @param keysIn Vector of Strings used to construct the "IN" clause */ private static void appendIn(StringBuffer sql,Vector keysIn) { if (keysIn == null) return; sql.append("AND M.TMODEL_KEY IN ("); int keyCount = keysIn.size(); for (int i=0; i<keyCount; i++) { String key = (String)keysIn.elementAt(i); sql.append("'").append(key).append("'"); if ((i+1) < keyCount) sql.append(","); } sql.append(") "); } /** * */ private static void appendOrderBy(StringBuffer sql,FindQualifiers qualifiers) { sql.append("ORDER BY "); if (qualifiers == null) sql.append("M.LAST_UPDATE DESC"); else if (qualifiers.sortByDateAsc) sql.append("M.LAST_UPDATE ASC"); else sql.append("M.LAST_UPDATE DESC"); } /***************************************************************************/ /***************************** TEST DRIVER *********************************/ /***************************************************************************/ public static void main(String[] args) throws Exception { // make sure we're using a DBCP DataSource and // not trying to use JNDI to aquire one. Config.setStringProperty("juddi.useConnectionPool","true"); Connection conn = null; try { conn = ConnectionManager.aquireConnection(); test(conn); } finally { if (conn != null) conn.close(); } } public static void test(Connection connection) throws Exception { CategoryBag categoryBag = new CategoryBag(); Vector keyedRefVector = new Vector(); keyedRefVector.addElement(new KeyedReference("ntis-gov:NAICS:1997","51121")); keyedRefVector.addElement(new KeyedReference("Mining","21")); keyedRefVector.addElement(new KeyedReference("cff049d0-c460-40c2-91c7-aa2261123dc7","Yadda, Yadda, Yadda")); keyedRefVector.addElement(new KeyedReference("1775f0f8-cd47-451d-88da-73ce508836f3","blah, blah, blah")); categoryBag.setKeyedReferenceVector(keyedRefVector); Vector keysIn = new Vector(); keysIn.add("740d75b1-3cde-4547-85dd-9578cd3ea1cd"); keysIn.add("c311085b-3277-470d-8ce9-07b81c484e4b"); keysIn.add("6b368a5a-6a62-4f23-a002-f11e22780a91"); keysIn.add("45994713-d3c3-40d6-87b5-6ce51f36001c"); keysIn.add("901b15c5-799c-4387-8337-a1a35fceb791"); keysIn.add("80fdae14-0e5d-4ea6-8eb8-50fde422056d"); keysIn.add("e1996c33-c436-4004-9e3e-14de191bcc6b"); keysIn.add("3ef4772f-e04b-46ed-8065-c5a4e167b5ba"); Transaction txn = new Transaction(); if (connection != null) { try { // begin a new transaction txn.begin(connection); select(categoryBag,keysIn,null,connection); select(categoryBag,null,null,connection); // commit the transaction txn.commit(); } catch(Exception ex) { try { txn.rollback(); } catch(java.sql.SQLException sqlex) { sqlex.printStackTrace(); } throw ex; } } } }
src/java/org/apache/juddi/datastore/jdbc/FindTModelByCategoryQuery.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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. */ package org.apache.juddi.datastore.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.juddi.datatype.CategoryBag; import org.apache.juddi.datatype.KeyedReference; import org.apache.juddi.datatype.request.FindQualifiers; import org.apache.juddi.datatype.tmodel.TModel; import org.apache.juddi.util.Config; import org.apache.juddi.util.jdbc.ConnectionManager; import org.apache.juddi.util.jdbc.Transaction; /** * @author Steve Viens ([email protected]) */ class FindTModelByCategoryQuery { // private reference to the jUDDI logger private static Log log = LogFactory.getLog(FindTModelByCategoryQuery.class); static String selectSQL; static { // build selectSQL StringBuffer sql = new StringBuffer(200); sql.append("SELECT M.TMODEL_KEY,M.LAST_UPDATE "); sql.append("FROM TMODEL M,TMODEL_CATEGORY C "); selectSQL = sql.toString(); } /** * Select ... * * @param connection JDBC connection * @throws java.sql.SQLException */ public static Vector select(CategoryBag categoryBag,Vector keysIn,FindQualifiers qualifiers,Connection connection) throws java.sql.SQLException { // if there is a keysIn vector but it doesn't contain // any keys then the previous query has exhausted // all possibilities of a match so skip this call. if ((keysIn != null) && (keysIn.size() == 0)) return keysIn; Vector keysOut = new Vector(); PreparedStatement statement = null; ResultSet resultSet = null; // construct the SQL statement StringBuffer sql = new StringBuffer(selectSQL); appendWhere(sql,categoryBag,qualifiers); appendIn(sql,keysIn); appendOrderBy(sql,qualifiers); try { log.debug("select from TMODEL & TMODEL_CATEGORY tables:\n\n\t" + sql.toString() + "\n"); statement = connection.prepareStatement(sql.toString()); resultSet = statement.executeQuery(); while (resultSet.next()) keysOut.addElement(resultSet.getString(1));//("TMODEL_KEY")); return keysOut; } finally { try { resultSet.close(); } catch (Exception e) { log.warn("An Exception was encountered while attempting to close " + "the Find TModel ResultSet: "+e.getMessage(),e); } try { statement.close(); } catch (Exception e) { log.warn("An Exception was encountered while attempting to close " + "the Find TModel Statement: "+e.getMessage(),e); } } } /** * */ private static void appendWhere(StringBuffer sql,CategoryBag categoryBag,FindQualifiers qualifiers) { sql.append("WHERE M.TMODEL_KEY = C.TMODEL_KEY "); if(categoryBag != null) { Vector keyedRefVector = categoryBag.getKeyedReferenceVector(); if(keyedRefVector != null) { int vectorSize = keyedRefVector.size(); if (vectorSize > 0) { sql.append("AND ("); for (int i=0; i<vectorSize; i++) { KeyedReference keyedRef = (KeyedReference)keyedRefVector.elementAt(i); String name = keyedRef.getKeyName(); String value = keyedRef.getKeyValue(); String tModelKey = keyedRef.getTModelKey(); if (tModelKey.equals(TModel.GENERAL_KEYWORDS_TMODEL_KEY)) { // DO NOT ignore the name .. if ((name != null) && (value != null)) { sql.append("(C.KEY_NAME = '").append(name).append("' AND C.KEY_VALUE = '").append(value).append("')"); if (i+1 < vectorSize) sql.append(" OR "); } } else { if (value != null) { sql.append("(C.KEY_VALUE = '").append(value).append("')"); if (i+1 < vectorSize) sql.append(" OR "); } } } sql.append(") "); } } } } /** * Utility method used to construct SQL "IN" statements such as * the following SQL example: * * SELECT * FROM TABLE WHERE MONTH IN ('jan','feb','mar') * * @param sql StringBuffer to append the final results to * @param keysIn Vector of Strings used to construct the "IN" clause */ private static void appendIn(StringBuffer sql,Vector keysIn) { if (keysIn == null) return; sql.append("AND M.TMODEL_KEY IN ("); int keyCount = keysIn.size(); for (int i=0; i<keyCount; i++) { String key = (String)keysIn.elementAt(i); sql.append("'").append(key).append("'"); if ((i+1) < keyCount) sql.append(","); } sql.append(") "); } /** * */ private static void appendOrderBy(StringBuffer sql,FindQualifiers qualifiers) { sql.append("ORDER BY "); if (qualifiers == null) sql.append("M.LAST_UPDATE DESC"); else if (qualifiers.sortByDateAsc) sql.append("M.LAST_UPDATE ASC"); else sql.append("M.LAST_UPDATE DESC"); } /***************************************************************************/ /***************************** TEST DRIVER *********************************/ /***************************************************************************/ public static void main(String[] args) throws Exception { // make sure we're using a DBCP DataSource and // not trying to use JNDI to aquire one. Config.setStringProperty("juddi.useConnectionPool","true"); Connection conn = null; try { conn = ConnectionManager.aquireConnection(); test(conn); } finally { if (conn != null) conn.close(); } } public static void test(Connection connection) throws Exception { CategoryBag categoryBag = new CategoryBag(); Vector keyedRefVector = new Vector(); keyedRefVector.addElement(new KeyedReference("ntis-gov:NAICS:1997","51121")); keyedRefVector.addElement(new KeyedReference("Mining","21")); keyedRefVector.addElement(new KeyedReference("cff049d0-c460-40c2-91c7-aa2261123dc7","Yadda, Yadda, Yadda")); keyedRefVector.addElement(new KeyedReference("1775f0f8-cd47-451d-88da-73ce508836f3","blah, blah, blah")); categoryBag.setKeyedReferenceVector(keyedRefVector); Vector keysIn = new Vector(); keysIn.add("740d75b1-3cde-4547-85dd-9578cd3ea1cd"); keysIn.add("c311085b-3277-470d-8ce9-07b81c484e4b"); keysIn.add("6b368a5a-6a62-4f23-a002-f11e22780a91"); keysIn.add("45994713-d3c3-40d6-87b5-6ce51f36001c"); keysIn.add("901b15c5-799c-4387-8337-a1a35fceb791"); keysIn.add("80fdae14-0e5d-4ea6-8eb8-50fde422056d"); keysIn.add("e1996c33-c436-4004-9e3e-14de191bcc6b"); keysIn.add("3ef4772f-e04b-46ed-8065-c5a4e167b5ba"); Transaction txn = new Transaction(); if (connection != null) { try { // begin a new transaction txn.begin(connection); select(categoryBag,keysIn,null,connection); select(categoryBag,null,null,connection); // commit the transaction txn.commit(); } catch(Exception ex) { try { txn.rollback(); } catch(java.sql.SQLException sqlex) { sqlex.printStackTrace(); } throw ex; } } } }
Replaced tab character with spaces to satisfy Checkstyle. git-svn-id: 9afb1f5cc321249b413187f68ffea1707b8f9361@262677 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/juddi/datastore/jdbc/FindTModelByCategoryQuery.java
Replaced tab character with spaces to satisfy Checkstyle.
<ide><path>rc/java/org/apache/juddi/datastore/jdbc/FindTModelByCategoryQuery.java <ide> String name = keyedRef.getKeyName(); <ide> String value = keyedRef.getKeyValue(); <ide> <del> String tModelKey = keyedRef.getTModelKey(); <add> String tModelKey = keyedRef.getTModelKey(); <ide> if (tModelKey.equals(TModel.GENERAL_KEYWORDS_TMODEL_KEY)) <ide> { <ide> // DO NOT ignore the name ..
Java
mit
error: pathspec 'data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java' did not match any file(s) known to git
f495a88e915a1cc894d231b3911ae619f4536a54
1
StefanHeimberg/java-design-patterns,mookkiah/java-design-patterns,zik43/java-design-patterns,zik43/java-design-patterns,radkrish/java-design-patterns,kingland/java-design-patterns,inbreak/java-design-patterns,kingland/java-design-patterns,fluxw42/java-design-patterns,radkrish/java-design-patterns,radkrish/java-design-patterns,SerhatSurguvec/java-design-patterns,javaseeds/java-design-patterns,kingland/java-design-patterns,SerhatSurguvec/java-design-patterns,radkrish/java-design-patterns,StefanHeimberg/java-design-patterns,SerhatSurguvec/java-design-patterns,inbreak/java-design-patterns,inbreak/java-design-patterns,javaseeds/java-design-patterns,StefanHeimberg/java-design-patterns,SerhatSurguvec/java-design-patterns,mookkiah/java-design-patterns,radkrish/java-design-patterns,fluxw42/java-design-patterns,javaseeds/java-design-patterns,zik43/java-design-patterns,fluxw42/java-design-patterns,mookkiah/java-design-patterns,zik43/java-design-patterns,inbreak/java-design-patterns,zik43/java-design-patterns,javaseeds/java-design-patterns,fluxw42/java-design-patterns,mookkiah/java-design-patterns,inbreak/java-design-patterns,StefanHeimberg/java-design-patterns,kingland/java-design-patterns
package com.iluwatar.databus.members; import com.iluwatar.databus.data.MessageData; import com.iluwatar.databus.data.StartingData; import org.junit.Assert; import org.junit.Test; import java.time.LocalDateTime; /** * Tests for {@link MessageCollectorMember}. * * @author Paul Campbell ([email protected]) */ public class MessageCollectorMemberTest { @Test public void collectMessageFromMessageData() { //given final String message = "message"; final MessageData messageData = new MessageData(message); final MessageCollectorMember collector = new MessageCollectorMember("collector"); //when collector.accept(messageData); //then Assert.assertTrue(collector.getMessages().contains(message)); } @Test public void collectIgnoresMessageFromOtherDataTypes() { //given final StartingData startingData = new StartingData(LocalDateTime.now()); final MessageCollectorMember collector = new MessageCollectorMember("collector"); //when collector.accept(startingData); //then Assert.assertEquals(0, collector.getMessages().size()); } }
data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java
#467 data-bus: members: MessageCollectorMemberTest: added
data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java
#467 data-bus: members: MessageCollectorMemberTest: added
<ide><path>ata-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java <add>package com.iluwatar.databus.members; <add> <add>import com.iluwatar.databus.data.MessageData; <add>import com.iluwatar.databus.data.StartingData; <add>import org.junit.Assert; <add>import org.junit.Test; <add> <add>import java.time.LocalDateTime; <add> <add>/** <add> * Tests for {@link MessageCollectorMember}. <add> * <add> * @author Paul Campbell ([email protected]) <add> */ <add>public class MessageCollectorMemberTest { <add> <add> @Test <add> public void collectMessageFromMessageData() { <add> //given <add> final String message = "message"; <add> final MessageData messageData = new MessageData(message); <add> final MessageCollectorMember collector = new MessageCollectorMember("collector"); <add> //when <add> collector.accept(messageData); <add> //then <add> Assert.assertTrue(collector.getMessages().contains(message)); <add> } <add> <add> @Test <add> public void collectIgnoresMessageFromOtherDataTypes() { <add> //given <add> final StartingData startingData = new StartingData(LocalDateTime.now()); <add> final MessageCollectorMember collector = new MessageCollectorMember("collector"); <add> //when <add> collector.accept(startingData); <add> //then <add> Assert.assertEquals(0, collector.getMessages().size()); <add> } <add> <add>}
Java
agpl-3.0
443ae36418ce1f0d859c777997adef7101b8f082
0
geothomasp/kcmit,geothomasp/kcmit,geothomasp/kcmit,geothomasp/kcmit,geothomasp/kcmit
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php * * 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.kuali.kra.award.home; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.kuali.coeus.common.framework.keyword.KeywordsManager; import org.kuali.coeus.common.framework.keyword.ScienceKeyword; import org.kuali.coeus.common.framework.person.KcPerson; import org.kuali.coeus.common.framework.person.KcPersonService; import org.kuali.coeus.common.framework.version.sequence.owner.SequenceOwner; import org.kuali.coeus.common.framework.sponsor.Sponsor; import org.kuali.coeus.common.framework.sponsor.Sponsorable; import org.kuali.coeus.common.framework.type.ActivityType; import org.kuali.coeus.common.framework.type.ProposalType; import org.kuali.coeus.common.framework.unit.Unit; import org.kuali.coeus.common.framework.unit.UnitService; import org.kuali.coeus.common.framework.unit.admin.UnitAdministrator; import org.kuali.coeus.common.framework.version.VersionStatus; import org.kuali.coeus.common.framework.version.history.VersionHistorySearchBo; import org.kuali.coeus.common.permissions.impl.PermissionableKeys; import org.kuali.coeus.common.framework.auth.SystemAuthorizationService; import org.kuali.coeus.common.framework.auth.perm.Permissionable; import org.kuali.coeus.sys.framework.gv.GlobalVariableService; import org.kuali.coeus.sys.framework.model.KcPersistableBusinessObjectBase; import org.kuali.coeus.sys.framework.service.KcServiceLocator; import org.kuali.kra.award.AwardAmountInfoService; import org.kuali.kra.award.AwardTemplateSyncScope; import org.kuali.kra.award.awardhierarchy.AwardHierarchyService; import org.kuali.kra.award.awardhierarchy.AwardHierarchyTempObject; import org.kuali.kra.award.awardhierarchy.sync.AwardSyncChange; import org.kuali.kra.award.awardhierarchy.sync.AwardSyncStatus; import org.kuali.kra.award.awardhierarchy.sync.AwardSyncableProperty; import org.kuali.kra.award.budget.AwardBudgetExt; import org.kuali.kra.award.budget.AwardBudgetLimit; import org.kuali.kra.award.commitments.AwardCostShare; import org.kuali.kra.award.commitments.AwardFandaRate; import org.kuali.kra.award.contacts.AwardPerson; import org.kuali.kra.award.contacts.AwardSponsorContact; import org.kuali.kra.award.contacts.AwardUnitContact; import org.kuali.kra.award.customdata.AwardCustomData; import org.kuali.kra.award.document.AwardDocument; import org.kuali.kra.award.home.approvedsubawards.AwardApprovedSubaward; import org.kuali.kra.award.home.fundingproposal.AwardFundingProposal; import org.kuali.kra.award.home.keywords.AwardScienceKeyword; import org.kuali.kra.award.notesandattachments.attachments.AwardAttachment; import org.kuali.kra.award.notesandattachments.notes.AwardNotepad; import org.kuali.kra.award.paymentreports.awardreports.AwardReportTerm; import org.kuali.kra.award.paymentreports.closeout.AwardCloseout; import org.kuali.kra.award.paymentreports.paymentschedule.AwardPaymentSchedule; import org.kuali.kra.award.paymentreports.specialapproval.approvedequipment.AwardApprovedEquipment; import org.kuali.kra.award.paymentreports.specialapproval.foreigntravel.AwardApprovedForeignTravel; import org.kuali.kra.award.specialreview.AwardSpecialReview; import org.kuali.kra.award.timeandmoney.AwardDirectFandADistribution; import org.kuali.kra.bo.*; import org.kuali.coeus.common.budget.framework.core.Budget; import org.kuali.coeus.common.budget.framework.core.BudgetParent; import org.kuali.coeus.common.budget.framework.core.BudgetParentDocument; import org.kuali.coeus.common.framework.rolodex.PersonRolodex; import org.kuali.kra.coi.Disclosurable; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.infrastructure.KeyConstants; import org.kuali.kra.infrastructure.RoleConstants; import org.kuali.kra.institutionalproposal.home.InstitutionalProposal; import org.kuali.kra.institutionalproposal.service.InstitutionalProposalService; import org.kuali.kra.negotiations.bo.Negotiable; import org.kuali.kra.negotiations.bo.NegotiationPersonDTO; import org.kuali.kra.subaward.bo.SubAward; import org.kuali.kra.timeandmoney.TimeAndMoneyDocumentHistory; import org.kuali.kra.timeandmoney.document.TimeAndMoneyDocument; import org.kuali.kra.timeandmoney.service.TimeAndMoneyHistoryService; import org.kuali.kra.timeandmoney.transactions.AwardTransactionType; import org.kuali.rice.core.api.CoreApiServiceLocator; import org.kuali.rice.core.api.util.type.KualiDecimal; import org.kuali.coeus.sys.api.model.ScaleTwoDecimal; import org.kuali.rice.kew.api.exception.WorkflowException; import org.kuali.rice.kim.api.role.Role; import org.kuali.rice.krad.service.BusinessObjectService; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.util.AutoPopulatingList; import edu.mit.kc.coi.KcCoiLinkService; import java.sql.Date; import java.sql.SQLException; import java.sql.Timestamp; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * * This class is Award Business Object. * It implements ProcessKeywords to process all operations related to AwardScenceKeywords. */ public class Award extends KcPersistableBusinessObjectBase implements KeywordsManager<AwardScienceKeyword>, Permissionable, SequenceOwner<Award>, BudgetParent, Sponsorable, Negotiable, Disclosurable { public static final String DEFAULT_AWARD_NUMBER = "000000-00000"; public static final String BLANK_COMMENT = ""; public static final String ICR_RATE_CODE_NONE = "ICRNONE"; private static final String NO_FLAG = "N"; private static final int TOTAL_STATIC_REPORTS = 5; public static final String CLOSE_OUT_REPORT_TYPE_FINANCIAL_REPORT = "1"; public static final String CLOSE_OUT_REPORT_TYPE_TECHNICAL = "4"; public static final String CLOSE_OUT_REPORT_TYPE_PATENT = "3"; public static final String CLOSE_OUT_REPORT_TYPE_PROPERTY = "2"; public static final String CLOSE_OUT_REPORT_TYPE_INVOICE = "6"; private static final String DEFAULT_GROUP_CODE_FOR_CENTRAL_ADMIN_CONTACTS = "C"; public static final String NOTIFICATION_IRB_SPECIAL_REVIEW_LINK_ADDED = "552"; public static final String NOTIFICATION_IRB_SPECIAL_REVIEW_LINK_DELETED = "553"; public static final String NOTIFICATION_IACUC_SPECIAL_REVIEW_LINK_ADDED = "554"; public static final String NOTIFICATION_IACUC_SPECIAL_REVIEW_LINK_DELETED = "555"; private static final long serialVersionUID = 3797220122448310165L; private Long awardId; private AwardDocument awardDocument; private String awardNumber; private Integer sequenceNumber; @AwardSyncableProperty private String sponsorCode; @AwardSyncableProperty private Integer statusCode; private AwardStatus awardStatus; private String accountNumber; private String approvedEquipmentIndicator; private String approvedForeignTripIndicator; private String subContractIndicator; private Date awardEffectiveDate; private Date awardExecutionDate; private Date beginDate; private String costSharingIndicator; private String indirectCostIndicator; private String modificationNumber; private String nsfCode; private String paymentScheduleIndicator; private String scienceCodeIndicator; private String specialReviewIndicator; private String sponsorAwardNumber; private String transferSponsorIndicator; private Integer accountTypeCode; private String activityTypeCode; private Integer awardTypeCode; private AwardType awardType; private String cfdaNumber; private String documentFundingId; private ScaleTwoDecimal preAwardAuthorizedAmount; private Date preAwardEffectiveDate; private ScaleTwoDecimal preAwardInstitutionalAuthorizedAmount; private Date preAwardInstitutionalEffectiveDate; private String procurementPriorityCode; private String proposalNumber; private ScaleTwoDecimal specialEbRateOffCampus; private ScaleTwoDecimal specialEbRateOnCampus; private String subPlanFlag; private String title; private String archiveLocation; private Date closeoutDate; private Integer awardTransactionTypeCode; private Date noticeDate; private String currentActionComments; private String financialAccountDocumentNumber; private Date financialAccountCreationDate; private String financialChartOfAccountsCode; private String awardSequenceStatus; // private String sequenceOwnerVersionNameValue; // private Integer sequenceOwnerSequenceNumber; private boolean newVersion; private Integer templateCode; @AwardSyncable(scopes = { AwardTemplateSyncScope.AWARD_PAGE }) private String primeSponsorCode; @AwardSyncable(impactSourceScopeEmpty = false, scopes = { AwardTemplateSyncScope.PAYMENTS_AND_INVOICES_TAB }) private String basisOfPaymentCode; @AwardSyncable(impactSourceScopeEmpty = false, scopes = { AwardTemplateSyncScope.PAYMENTS_AND_INVOICES_TAB }) private String methodOfPaymentCode; private AwardTemplate awardTemplate; private AwardBasisOfPayment awardBasisOfPayment; private AwardMethodOfPayment awardMethodOfPayment; private AwardTransactionType awardTransactionType; private ActivityType activityType; private Sponsor sponsor; private Sponsor primeSponsor; @AwardSyncableList(syncClass = AwardComment.class, syncSourceClass = AwardTemplateComment.class, scopes={AwardTemplateSyncScope.COST_SHARE,AwardTemplateSyncScope.PAYMENTS_AND_INVOICES_TAB,AwardTemplateSyncScope.COMMENTS_TAB}, removeMissingListElementsFromTarget=false) private List<AwardComment> awardComments; @AwardSyncableList(syncClass = AwardReportTerm.class, syncSourceClass = AwardTemplateReportTerm.class, scopes = {AwardTemplateSyncScope.PAYMENTS_AND_INVOICES_TAB,AwardTemplateSyncScope.REPORTS_TAB}) private List<AwardReportTerm> awardReportTermItems; @AwardSyncableList(syncClass = AwardSponsorTerm.class, syncSourceClass = AwardTemplateTerm.class, scopes = { AwardTemplateSyncScope.TERMS_TAB }) private List<AwardSponsorTerm> awardSponsorTerms; @AwardSyncableList(syncClass = AwardSponsorContact.class, syncSourceClass = AwardTemplateContact.class, scopes = { AwardTemplateSyncScope.SPONSOR_CONTACTS_TAB }) private List<AwardSponsorContact> sponsorContacts; private List<AwardCustomData> awardCustomDataList; private List<Boolean> awardCommentHistoryFlags; private Map<String, AwardComment> commentMap; private List<AwardCostShare> awardCostShares; private List<AwardFandaRate> awardFandaRate; private List<AwardDirectFandADistribution> awardDirectFandADistributions; private List<AwardApprovedSubaward> awardApprovedSubawards; private List<AwardScienceKeyword> keywords; private List<AwardPerson> projectPersons; private List<AwardUnitContact> awardUnitContacts; private List<AwardSpecialReview> specialReviews; private List<AwardApprovedEquipment> approvedEquipmentItems; private List<AwardApprovedForeignTravel> approvedForeignTravelTrips; private List<AwardPaymentSchedule> paymentScheduleItems; private List<AwardTransferringSponsor> awardTransferringSponsors; private List<AwardAmountInfo> awardAmountInfos; private List<AwardCloseout> awardCloseoutItems; private List<AwardCloseout> awardCloseoutNewItems; private List<AwardNotepad> awardNotepads; private List<AwardAttachment> awardAttachments; private List<AwardSyncChange> syncChanges; private List<AwardSyncStatus> syncStatuses; private boolean syncChild; private List<AwardFundingProposal> fundingProposals; private List<AwardBudgetLimit> awardBudgetLimits; // Additional fields for lookup private Unit leadUnit; private String unitNumber; private KcPerson ospAdministrator; private String ospAdministratorName; private String principalInvestigatorName; private String statusDescription; private String sponsorName; // For award-account integration private String icrRateCode; private transient boolean awardInMultipleNodeHierarchy; private transient boolean awardHasAssociatedTandMOrIsVersioned; private transient boolean sponsorNihMultiplePi; private transient List<AwardHierarchyTempObject> awardHierarchyTempObjects; // transient for award header label private transient String docIdStatus; private transient String awardIdAccount; private transient String lookupOspAdministratorName; transient AwardAmountInfoService awardAmountInfoService; transient TimeAndMoneyHistoryService timeAndMoneyHistoryService; private transient AwardHierarchyService awardHierarchyService; private transient List<AwardUnitContact> centralAdminContacts; private List<SubAward> subAwardList; private transient boolean allowUpdateTimestampToBeReset = true; private VersionHistorySearchBo versionHistory; private transient KcPersonService kcPersonService; private transient boolean editAward = false; protected final Log LOG = LogFactory.getLog(Award.class); Logger LOGGER; @Qualifier("globalVariableService") private transient GlobalVariableService globalVariableService; public GlobalVariableService getGlobalVariableService() { if (globalVariableService == null) { globalVariableService = KcServiceLocator.getService(GlobalVariableService.class); } return globalVariableService; } public void setGlobalVariableService(GlobalVariableService globalVariableService) { this.globalVariableService = globalVariableService; } private transient KcCoiLinkService kcCoiLinkService; public KcCoiLinkService getKcCoiLinkService() { if (kcCoiLinkService == null) { kcCoiLinkService = KcServiceLocator.getService(KcCoiLinkService.class); } return kcCoiLinkService; } public void setKcCoiLinkService(KcCoiLinkService kcCoiLinkService) { this.kcCoiLinkService = kcCoiLinkService; } /** * * Constructs an Award BO. */ public Award() { super(); initializeAwardWithDefaultValues(); initializeCollections(); } /** * * This method sets the default values for initial persistence as part of skeleton. * As various panels are developed; corresponding field initializations should be removed from * this method. */ private void initializeAwardWithDefaultValues() { setAwardNumber(DEFAULT_AWARD_NUMBER); setSequenceNumber(1); setApprovedEquipmentIndicator(NO_FLAG); setApprovedForeignTripIndicator(NO_FLAG); setSubContractIndicator(NO_FLAG); setCostSharingIndicator(NO_FLAG); setIdcIndicator(NO_FLAG); setPaymentScheduleIndicator(NO_FLAG); setScienceCodeIndicator(NO_FLAG); setSpecialReviewIndicator(NO_FLAG); setTransferSponsorIndicator(NO_FLAG); awardComments = new AutoPopulatingList<AwardComment>(AwardComment.class); setCurrentActionComments(""); setNewVersion(false); awardSequenceStatus = VersionStatus.PENDING.name(); } private Map<String, AwardComment> getCommentMap() { if (commentMap == null || getNewVersion()) { commentMap = new HashMap<String, AwardComment>(); for (AwardComment ac : awardComments) { if (getNewVersion() && ac.getCommentType().getCommentTypeCode().equals(Constants.CURRENT_ACTION_COMMENT_TYPE_CODE)) { ac.setComments(BLANK_COMMENT); } commentMap.put(ac.getCommentType().getCommentTypeCode(), ac); } } return commentMap; } /** * Gets the templateCode attribute. * @return Returns the templateCode. */ public Integer getTemplateCode() { return templateCode; } public String getFinancialChartOfAccountsCode() { return financialChartOfAccountsCode; } public void setFinancialChartOfAccountsCode(String financialChartOfAccountsCode) { this.financialChartOfAccountsCode = financialChartOfAccountsCode; } public Long getAwardId() { return awardId; } /** * * @param awardId */ public void setAwardId(Long awardId) { this.awardId = awardId; } public String getAwardNumber() { return awardNumber; } /** * * @param awardNumber */ public void setAwardNumber(String awardNumber) { this.awardNumber = awardNumber; } @Override public Integer getSequenceNumber() { return sequenceNumber; } /** * * @param sequenceNumber */ public void setSequenceNumber(Integer sequenceNumber) { this.sequenceNumber = sequenceNumber; } public int getIndexOfLastAwardAmountInfo() { return awardAmountInfos.size() - 1; } public AwardAmountInfo getLastAwardAmountInfo() { return awardAmountInfos.get(getIndexOfLastAwardAmountInfo()); } public int getIndexOfAwardAmountInfoForDisplay() throws WorkflowException { AwardAmountInfo aai = getAwardAmountInfoService().fetchLastAwardAmountInfoForAwardVersionAndFinalizedTandMDocumentNumber(this); int returnVal = 0; int index = 0; if (aai.getAwardAmountInfoId() != null && this.isAwardInMultipleNodeHierarchy()) { this.refreshReferenceObject("awardAmountInfos"); } if (isAwardInitialCopy()) { // if it's copied, on initialization we want to return index of last AwardAmountInfo in collection. returnVal = getAwardAmountInfos().size() - 1; }else { for (AwardAmountInfo awardAmountInfo : getAwardAmountInfos()) { if (awardAmountInfo.getAwardAmountInfoId() == null && aai.getAwardAmountInfoId() == null) { returnVal = index; }else if(awardAmountInfo.getAwardAmountInfoId().equals(aai.getAwardAmountInfoId())) { returnVal = index; }else { index++; } } } return returnVal; } public int getIndexOfAwardAmountInfoForDisplayFromTimeAndMoneyDocNumber(String docNum) throws WorkflowException { AwardAmountInfo aai = getAwardAmountInfoService().fetchLastAwardAmountInfoForDocNum(this, docNum); int returnVal = 0; int index = 0; if (aai.getAwardAmountInfoId() != null && this.isAwardInMultipleNodeHierarchy()) { this.refreshReferenceObject("awardAmountInfos"); } if (isAwardInitialCopy()) { // if it's copied, on initialization we want to return index of last AwardAmountInfo in collection. returnVal = getAwardAmountInfos().size() - 1; }else { for (AwardAmountInfo awardAmountInfo : getAwardAmountInfos()) { if (awardAmountInfo.getAwardAmountInfoId() == null && aai.getAwardAmountInfoId() == null) { returnVal = index; }else if(awardAmountInfo.getAwardAmountInfoId().equals(aai.getAwardAmountInfoId())) { returnVal = index; }else { index++; } } } return returnVal; } /** * If the Award is copied then initially the AwardAmountInfos will have two entries without AwardAmountInfoId's. We need to recognize this * so we can display the correct data on initialization. * @return */ public boolean isAwardInitialCopy() { boolean returnValue = true; if (this.getAwardAmountInfos().size() > 1) { for (AwardAmountInfo aai : getAwardAmountInfos()) { if (aai.getAwardAmountInfoId() != null) { returnValue = false; break; } } } return returnValue; } /** * Gets the awardAmountInfoService attribute. * @return Returns the awardAmountInfoService. */ public AwardAmountInfoService getAwardAmountInfoService() { awardAmountInfoService = KcServiceLocator.getService(AwardAmountInfoService.class); return awardAmountInfoService; } public AwardHierarchyService getAwardHierarchyService() { if (awardHierarchyService == null) { awardHierarchyService = KcServiceLocator.getService(AwardHierarchyService.class); } return awardHierarchyService; } public TimeAndMoneyHistoryService getTimeAndMoneyHistoryService() { if (timeAndMoneyHistoryService == null) { timeAndMoneyHistoryService = KcServiceLocator.getService(TimeAndMoneyHistoryService.class); } return timeAndMoneyHistoryService; } /** * Sets the awardAmountInfoService attribute value. * @param awardAmountInfoService The awardAmountInfoService to set. */ public void setAwardAmountInfoService(AwardAmountInfoService awardAmountInfoService) { this.awardAmountInfoService = awardAmountInfoService; } public String getSponsorCode() { return sponsorCode; } /** * * @param sponsorCode */ public void setSponsorCode(String sponsorCode) { this.sponsorCode = sponsorCode; } public String getAccountTypeDescription() { AccountType accountType = (AccountType) getBusinessObjectService().findByPrimaryKey (AccountType.class, Collections.singletonMap("accountTypeCode", getAccountTypeCode())); if (accountType == null) { return "None Selected"; }else { return accountType.getDescription(); } } public Integer getStatusCode() { return statusCode; } /** * * @param statusCode */ public void setStatusCode(Integer statusCode) { this.statusCode = statusCode; } public String getAccountNumber() { return accountNumber; } /** * * @param accountNumber */ public void setAccountNumber(String accountNumber) { this.accountNumber = accountNumber; } public List<AwardApprovedEquipment> getApprovedEquipmentItems() { return approvedEquipmentItems; } public List<AwardUnitContact> getAwardUnitContacts() { return awardUnitContacts; } /** * @param index * @return */ public AwardPerson getProjectPerson(int index) { return projectPersons.get(index); } /** * Retrieve the AwardPerson for the given personId, if it exists. * * @param personId String * @return AwardPerson */ public AwardPerson getProjectPerson(String personId) { if (!StringUtils.isBlank(personId)) { for (AwardPerson awardPerson : this.getProjectPersons()) { if (personId.equals(awardPerson.getPersonId())) { return awardPerson; } } } return null; } /** * Retrieve the AwardPerson for the given rolodexId, if it exists. * * @param rolodexId Integer * @return AwardPerson */ public AwardPerson getProjectPerson(Integer rolodexId) { if (rolodexId != null) { for (AwardPerson awardPerson : this.getProjectPersons()) { if (rolodexId.equals(awardPerson.getRolodexId())) { return awardPerson; } } } return null; } public List<AwardPerson> getProjectPersons() { return projectPersons; } public List<AwardPerson> getProjectPersonsSorted() { List<AwardPerson> aList = new ArrayList<AwardPerson>(); if (this.getPrincipalInvestigator() != null) { aList.add(this.getPrincipalInvestigator()); } aList.addAll(this.getMultiplePis()); aList.addAll(this.getCoInvestigators()); aList.addAll(this.getKeyPersons()); return aList; } /** * This method returns all PIs and co-PIs. * @return */ public List<AwardPerson> getInvestigators() { List<AwardPerson> investigators = new ArrayList<AwardPerson>(); for (AwardPerson person : projectPersons) { if (person.isPrincipalInvestigator() || person.isCoInvestigator()) { investigators.add(person); } } Collections.sort(investigators); return investigators; } /** * This method returns all co-PIs. * @return */ public List<AwardPerson> getCoInvestigators() { List<AwardPerson> coInvestigators = new ArrayList<AwardPerson>(); for (AwardPerson person : projectPersons) { if (person.isCoInvestigator()) { coInvestigators.add(person); } } Collections.sort(coInvestigators); return coInvestigators; } /** * When the sponsor is in the NIH multiple PI hierarchy this will return any multiple pis, otherwise, empty list. * @return */ public List<AwardPerson> getMultiplePis() { List<AwardPerson> multiplePis = new ArrayList<AwardPerson>(); if (isSponsorNihMultiplePi()) { for (AwardPerson person : projectPersons) { if (person.isMultiplePi()) { multiplePis.add(person); } } Collections.sort(multiplePis); } return multiplePis; } /** * This method returns all key persons * @return */ public List<AwardPerson> getKeyPersons() { List<AwardPerson> keyPersons = new ArrayList<AwardPerson>(); for (AwardPerson person : projectPersons) { if (person.isKeyPerson()) { keyPersons.add(person); } } Collections.sort(keyPersons); return keyPersons; } /** * This method returns the combined number of units for all project personnel. * @return */ public int getTotalUnitCount() { int count = 0; for (AwardPerson person : projectPersons) count += person.getUnits().size(); return count; } public int getAwardContactsCount() { return awardUnitContacts.size(); } public int getApprovedEquipmentItemCount() { return approvedEquipmentItems.size(); } public int getApprovedForeignTravelTripCount() { return approvedForeignTravelTrips.size(); } public List<AwardApprovedForeignTravel> getApprovedForeignTravelTrips() { return approvedForeignTravelTrips; } /** * @param awardUnitContacts */ public void setAwardUnitContacts(List<AwardUnitContact> awardUnitContacts) { this.awardUnitContacts = awardUnitContacts; } /** * */ public void setApprovedEquipmentItems(List<AwardApprovedEquipment> awardApprovedEquipmentItems) { this.approvedEquipmentItems = awardApprovedEquipmentItems; } /** * */ public void setApprovedForeignTravelTrips(List<AwardApprovedForeignTravel> approvedForeignTravelTrips) { this.approvedForeignTravelTrips = approvedForeignTravelTrips; } public String getApprovedEquipmentIndicator() { return approvedEquipmentIndicator; } /** * * @param approvedEquipmentIndicator */ public void setApprovedEquipmentIndicator(String approvedEquipmentIndicator) { this.approvedEquipmentIndicator = approvedEquipmentIndicator; } public String getApprovedForeignTripIndicator() { return approvedForeignTripIndicator; } /** * * @param approvedForeignTripIndicator */ public void setApprovedForeignTripIndicator(String approvedForeignTripIndicator) { this.approvedForeignTripIndicator = approvedForeignTripIndicator; } public String getSubContractIndicator() { return subContractIndicator; } /** * * @param subContractIndicator */ public void setSubContractIndicator(String subContractIndicator) { this.subContractIndicator = subContractIndicator; } public Date getAwardEffectiveDate() { return awardEffectiveDate; } /** * * @param awardEffectiveDate */ public void setAwardEffectiveDate(Date awardEffectiveDate) { this.awardEffectiveDate = awardEffectiveDate; } public Date getAwardExecutionDate() { return awardExecutionDate; } /** * * @param awardExecutionDate */ public void setAwardExecutionDate(Date awardExecutionDate) { this.awardExecutionDate = awardExecutionDate; } public Date getBeginDate() { return beginDate; } /** * This method returns the project end date which is housed in the Amount Info list index[0] on the award. * @return */ public Date getProjectEndDate() { return awardAmountInfos.get(0).getFinalExpirationDate(); } /** * This method sets the project end date which is housed in the Amount Info list index[0] on the award. * @return */ public void setProjectEndDate(Date date) { this.awardAmountInfos.get(0).setFinalExpirationDate(date); } public Date getObligationExpirationDate() { // return awardAmountInfos.get(0).getObligationExpirationDate(); return getLastAwardAmountInfo().getObligationExpirationDate(); } public void setObligationExpirationDate(Date date) { this.awardAmountInfos.get(0).setObligationExpirationDate(date); } /** * * @param beginDate */ public void setBeginDate(Date beginDate) { this.beginDate = beginDate; } public String getCostSharingIndicator() { return costSharingIndicator; } /** * * @param costSharingIndicator */ public void setCostSharingIndicator(String costSharingIndicator) { this.costSharingIndicator = costSharingIndicator; } public List<AwardFundingProposal> getFundingProposals() { return fundingProposals; } /** * * For ease of use in JSP and tag files; the getter method uses acronym instead of full meaning. * idcIndicator is an acronym. Its full meaning is Indirect Cost Indicator * @return */ public String getIdcIndicator() { return indirectCostIndicator; } /** * * For ease of use in JSP and tag files; the setter method uses acronym instead of full meaning. * idcIndicator is an acronym. Its full meaning is Indirect Cost Indicator * @param indirectCostIndicator */ public void setIdcIndicator(String indirectCostIndicator) { this.indirectCostIndicator = indirectCostIndicator; } public String getModificationNumber() { return modificationNumber; } /** * * @param modificationNumber */ public void setModificationNumber(String modificationNumber) { this.modificationNumber = modificationNumber; } /** * NSFCode is an acronym. Its full meaning is National Science Foundation. * @return */ public String getNsfCode() { return nsfCode; } /** * NSFCode is an acronym. Its full meaning is National Science Foundation. * @param nsfCode */ public void setNsfCode(String nsfCode) { this.nsfCode = nsfCode; } public String getPaymentScheduleIndicator() { return paymentScheduleIndicator; } /** * * @param paymentScheduleIndicator */ public void setPaymentScheduleIndicator(String paymentScheduleIndicator) { this.paymentScheduleIndicator = paymentScheduleIndicator; } public String getScienceCodeIndicator() { return scienceCodeIndicator; } /** * * @param scienceCodeIndicator */ public void setScienceCodeIndicator(String scienceCodeIndicator) { this.scienceCodeIndicator = scienceCodeIndicator; } public String getSpecialReviewIndicator() { return specialReviewIndicator; } /** * * @param specialReviewIndicator */ public void setSpecialReviewIndicator(String specialReviewIndicator) { this.specialReviewIndicator = specialReviewIndicator; } /**\ * * @return */ public String getSponsorAwardNumber() { return sponsorAwardNumber; } /** * * @param sponsorAwardNumber */ public void setSponsorAwardNumber(String sponsorAwardNumber) { this.sponsorAwardNumber = sponsorAwardNumber; } public String getTransferSponsorIndicator() { return transferSponsorIndicator; } /** * This method finds the lead unit name, if any * @return */ public String getUnitName() { Unit leadUnit = getLeadUnit(); return leadUnit != null ? leadUnit.getUnitName() : null; } /** * This method finds the lead unit number, if any * @return */ public String getUnitNumber() { return unitNumber; } public String getLeadUnitNumber() { return getUnitNumber(); } /** * * @param transferSponsorIndicator */ public void setTransferSponsorIndicator(String transferSponsorIndicator) { this.transferSponsorIndicator = transferSponsorIndicator; } public Integer getAccountTypeCode() { return accountTypeCode; } /** * * @param accountTypeCode */ public void setAccountTypeCode(Integer accountTypeCode) { this.accountTypeCode = accountTypeCode; } public String getActivityTypeCode() { return activityTypeCode; } /** * * @param activityTypeCode */ public void setActivityTypeCode(String activityTypeCode) { this.activityTypeCode = activityTypeCode; } public Integer getAwardTypeCode() { return awardTypeCode; } /** * * @param awardTypeCode */ public void setAwardTypeCode(Integer awardTypeCode) { this.awardTypeCode = awardTypeCode; } /** * * cfdaNumber is an acronym. Its full meaning is Catalog of Federal Domestic Assistance * @return */ public String getCfdaNumber() { return cfdaNumber; } /** * * cfdaNumber is an acronym. Its full meaning is Catalog of Federal Domestic Assistance * @param cfdaNumber */ public void setCfdaNumber(String cfdaNumber) { this.cfdaNumber = cfdaNumber; } public String getDocumentFundingId() { return documentFundingId; } public void setDocumentFundingId(String documentFundingId) { this.documentFundingId = documentFundingId; } public KcPerson getOspAdministrator() { for (AwardUnitContact contact : getCentralAdminContacts()) { if (contact.isOspAdministrator()) { ospAdministrator = contact.getPerson(); break; } } return ospAdministrator; } public String getOspAdministratorName() { KcPerson ospAdministrator = getOspAdministrator(); ospAdministratorName = ospAdministrator != null ? ospAdministrator.getFullName() : null; return ospAdministratorName; } public ScaleTwoDecimal getPreAwardAuthorizedAmount() { return preAwardAuthorizedAmount; } /** * For negative values, this method makes the number positive by dropping the negative sign. * @param preAwardAuthorizedAmount */ public void setPreAwardAuthorizedAmount(ScaleTwoDecimal preAwardAuthorizedAmount) { // if preAwardAuthorizedAmount is negative, make it positive if (preAwardAuthorizedAmount != null && preAwardAuthorizedAmount.isNegative()) { this.preAwardAuthorizedAmount = ScaleTwoDecimal.ZERO.subtract(preAwardAuthorizedAmount); } else { this.preAwardAuthorizedAmount = preAwardAuthorizedAmount; } } public Date getPreAwardEffectiveDate() { return preAwardEffectiveDate; } /** * * @param preAwardEffectiveDate */ public void setPreAwardEffectiveDate(Date preAwardEffectiveDate) { this.preAwardEffectiveDate = preAwardEffectiveDate; } public String getProcurementPriorityCode() { return procurementPriorityCode; } /** * * @param procurementPriorityCode */ public void setProcurementPriorityCode(String procurementPriorityCode) { this.procurementPriorityCode = procurementPriorityCode; } public String getProposalNumber() { return proposalNumber; } /** * * @param proposalNumber */ public void setProposalNumber(String proposalNumber) { this.proposalNumber = proposalNumber; } public ScaleTwoDecimal getSpecialEbRateOffCampus() { return specialEbRateOffCampus; } /** * * @param specialEbRateOffCampus */ public void setSpecialEbRateOffCampus(ScaleTwoDecimal specialEbRateOffCampus) { this.specialEbRateOffCampus = specialEbRateOffCampus; } public ScaleTwoDecimal getSpecialEbRateOnCampus() { return specialEbRateOnCampus; } /** * * @param specialEbRateOnCampus */ public void setSpecialEbRateOnCampus(ScaleTwoDecimal specialEbRateOnCampus) { this.specialEbRateOnCampus = specialEbRateOnCampus; } public String getSubPlanFlag() { return subPlanFlag; } /** * * @param subPlanFlag */ public void setSubPlanFlag(String subPlanFlag) { this.subPlanFlag = subPlanFlag; } public String getTitle() { return title; } /** * * @param title */ public void setTitle(String title) { this.title = title; } public String getArchiveLocation() { return archiveLocation; } public void setArchiveLocation(String archiveLocation) { this.archiveLocation = archiveLocation; } public Date getCloseoutDate() { return closeoutDate; } public void setCloseoutDate(Date closeoutDate) { this.closeoutDate = closeoutDate; } /** * Gets the awardTransactionTypeCode attribute. * @return Returns the awardTransactionTypeCode. */ public Integer getAwardTransactionTypeCode() { return awardTransactionTypeCode; } /** * Sets the awardTransactionTypeCode attribute value. * @param awardTransactionTypeCode The awardTransactionTypeCode to set. */ public void setAwardTransactionTypeCode(Integer awardTransactionTypeCode) { this.awardTransactionTypeCode = awardTransactionTypeCode; } /** * Gets the noticeDate attribute. * @return Returns the noticeDate. */ public Date getNoticeDate() { return noticeDate; } /** * Sets the noticeDate attribute value. * @param noticeDate The noticeDate to set. */ public void setNoticeDate(Date noticeDate) { if (getNewVersion()) { this.noticeDate = null; } else { this.noticeDate = noticeDate; } } /** * Gets the currentActionComments attribute. * @return Returns the currentActionComments. */ public String getCurrentActionComments() { return currentActionComments; } /** * Sets the currentActionComments attribute value. * @param currentActionComments The currentActionComments to set. */ public void setCurrentActionComments(String currentActionComments) { if (getNewVersion()) { this.currentActionComments = BLANK_COMMENT; } else { this.currentActionComments = currentActionComments; } } /** * sets newVersion to specified value * @param newVersion the newVersion to be set */ public void setNewVersion (boolean newVersion) { this.newVersion = newVersion; if (this.newVersion) { commentMap = getCommentMap(); setCurrentActionComments(BLANK_COMMENT); setNoticeDate(null); } } /** * Gets the newVersion attribute * @return Returns the newVersion attribute */ public boolean getNewVersion () { return this.newVersion; } /** * Gets the awardTransactionType attribute. * @return Returns the awardTransactionType. */ public AwardTransactionType getAwardTransactionType() { return awardTransactionType; } /** * Sets the awardTransactionType attribute value. * @param awardTransactionType The awardTransactionType to set. */ public void setAwardTransactionType(AwardTransactionType awardTransactionType) { this.awardTransactionType = awardTransactionType; } public String getFinancialAccountDocumentNumber() { return financialAccountDocumentNumber; } public void setFinancialAccountDocumentNumber(String financialAccountDocumentNumber) { this.financialAccountDocumentNumber = financialAccountDocumentNumber; } public Date getFinancialAccountCreationDate() { return financialAccountCreationDate; } public void setFinancialAccountCreationDate(Date financialAccountCreationDate) { this.financialAccountCreationDate = financialAccountCreationDate; } public AwardDocument getAwardDocument() { if (awardDocument == null) { this.refreshReferenceObject("awardDocument"); } return awardDocument; } public String getAwardDocumentUrl() { return getAwardDocument().buildForwardUrl(); } public void setAwardDocument(AwardDocument awardDocument) { this.awardDocument = awardDocument; } public List<AwardComment> getAwardComments() { return awardComments; } public void setAwardComments(List<AwardComment> awardComments) { this.awardComments = awardComments; } public List<AwardCostShare> getAwardCostShares() { return awardCostShares; } public void setAwardCostShares(List<AwardCostShare> awardCostShares) { this.awardCostShares = awardCostShares; } public List<AwardApprovedSubaward> getAwardApprovedSubawards() { return awardApprovedSubawards; } public void setAwardApprovedSubawards(List<AwardApprovedSubaward> awardApprovedSubawards) { this.awardApprovedSubawards = awardApprovedSubawards; } /** * * Get the award Cost Share Comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardCostShareComment() { return getAwardCommentByType(Constants.COST_SHARE_COMMENT_TYPE_CODE, Constants.AWARD_COMMENT_INCLUDE_IN_CHECKLIST, true); } /** * * Get the award PreAward Sponsor Authorizations comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getawardPreAwardSponsorAuthorizationComment() { return getAwardCommentByType( Constants.PREAWARD_SPONSOR_AUTHORIZATION_COMMENT_TYPE_CODE,Constants.AWARD_COMMENT_EXCLUDE_FROM_CHECKLIST, true ); } /** * * Get the award PreAward Institutional Authorizations comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getawardPreAwardInstitutionalAuthorizationComment() { return getAwardCommentByType( Constants.PREAWARD_INSTITUTIONAL_AUTHORIZATION_COMMENT_TYPE_CODE,Constants.AWARD_COMMENT_EXCLUDE_FROM_CHECKLIST, true ); } /** * * Get the award F & A Rates Comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardFandaRateComment() { return getAwardCommentByType(Constants.FANDA_RATE_COMMENT_TYPE_CODE, Constants.AWARD_COMMENT_INCLUDE_IN_CHECKLIST, true); } /** * * Get the award AwardPaymentAndInvoiceRequirementsComments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardPaymentAndInvoiceRequirementsComments() { return getAwardCommentByType( Constants.PAYMENT_AND_INVOICES_COMMENT_TYPE_CODE,Constants.AWARD_COMMENT_INCLUDE_IN_CHECKLIST, true ); } /** * * Get the award Benefits Rate comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardBenefitsRateComment() { return getAwardCommentByType(Constants.BENEFITS_RATES_COMMENT_TYPE_CODE, Constants.AWARD_COMMENT_INCLUDE_IN_CHECKLIST, true); } /** * * Get the award General Comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardGeneralComments() { return getAwardCommentByType(Constants.GENERAL_COMMENT_TYPE_CODE, Constants.AWARD_COMMENT_INCLUDE_IN_CHECKLIST, true); } /** * * Get the award fiscal report comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardFiscalReportComments() { return getAwardCommentByType(Constants.FISCAL_REPORT_COMMENT_TYPE_CODE, Constants.AWARD_COMMENT_INCLUDE_IN_CHECKLIST, true); } /** * * Get the award current action comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardCurrentActionComments() { return getAwardCommentByType( Constants.CURRENT_ACTION_COMMENT_TYPE_CODE,Constants.AWARD_COMMENT_EXCLUDE_FROM_CHECKLIST, true ); } /** * * Get the award Intellectual Property comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardIntellectualPropertyComments() { return getAwardCommentByType( Constants.INTELLECTUAL_PROPERTY_COMMENT_TYPE_CODE,Constants.AWARD_COMMENT_EXCLUDE_FROM_CHECKLIST, true ); } /** * * Get the award Procurement Comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardProcurementComments() { return getAwardCommentByType(Constants.PROCUREMENT_COMMENT_TYPE_CODE, Constants.AWARD_COMMENT_INCLUDE_IN_CHECKLIST, true); } /** * * Get the award Award Property Comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardPropertyComments() { return getAwardCommentByType(Constants.PROPERTY_COMMENT_TYPE_CODE, Constants.AWARD_COMMENT_INCLUDE_IN_CHECKLIST, true); } /** * * Get the award Special Rate comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardSpecialRate() { return getAwardCommentByType(Constants.SPECIAL_RATE_COMMENT_TYPE_CODE, Constants.AWARD_COMMENT_EXCLUDE_FROM_CHECKLIST, true); } /** * * Get the award Special Review Comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardSpecialReviewComments() { return getAwardCommentByType( Constants.SPECIAL_REVIEW_COMMENT_TYPE_CODE,Constants.AWARD_COMMENT_EXCLUDE_FROM_CHECKLIST, true ); } /** * * Get the award Proposal Summary comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getawardProposalSummary() { return getAwardCommentByType( Constants.PROPOSAL_SUMMARY_COMMENT_TYPE_CODE,Constants.AWARD_COMMENT_EXCLUDE_FROM_CHECKLIST, true ); } /** * * Get the award Proposal comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getawardProposalComments() { return getAwardCommentByType(Constants.PROPOSAL_COMMENT_TYPE_CODE, Constants.AWARD_COMMENT_EXCLUDE_FROM_CHECKLIST, true); } /** * * Get the award Proposal IP Review Comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardProposalIPReviewComment() { return getAwardCommentByType( Constants.PROPOSAL_IP_REVIEW_COMMENT_TYPE_CODE,Constants.AWARD_COMMENT_EXCLUDE_FROM_CHECKLIST, true ); } /* * Get a comment by type. If it does not exist, then create it. */ public AwardComment getAwardCommentByType(String awardTypeCode, Boolean checklistPrintFlag, boolean createNew) { AwardCommentFactory awardCommentFactory = new AwardCommentFactory(); AwardComment awardComment = getCommentMap().get(awardTypeCode); if ((awardComment == null && createNew)) { awardComment = awardCommentFactory.createAwardComment(awardTypeCode, (checklistPrintFlag == null ? false : checklistPrintFlag.booleanValue())); add(awardComment); commentMap.put(awardComment.getCommentType().getCommentTypeCode(), awardComment); } return awardComment; } /* * Get a sponsor term by sponsor term id. */ public AwardSponsorTerm getAwardSponsorTermByTemplateTerm(AwardTemplateTerm templateTerm, boolean createNew) { AwardSponsorTerm result = null; for (AwardSponsorTerm term : this.getAwardSponsorTerms()) { if (term.getSponsorTermId().equals(templateTerm.getSponsorTermId())) { result = term; break; } } if (result == null && createNew) { result = new AwardSponsorTerm(); result.setSponsorTermId(templateTerm.getSponsorTermId()); result.setSponsorTerm(templateTerm.getSponsorTerm()); } return result; } /** * This method calls getTotalAmount to calculate the total of all Commitment Amounts. * @return */ public ScaleTwoDecimal getTotalCostShareCommitmentAmount() { return getTotalAmount(awardCostShares); } /** * This method calculates the total Cost Share Met amount for all Award Cost Shares. * @param valuableItems * @return The total value */ public ScaleTwoDecimal getTotalCostShareMetAmount() { ScaleTwoDecimal returnVal = new ScaleTwoDecimal(0.00); for (AwardCostShare awardCostShare : awardCostShares) { ScaleTwoDecimal amount = awardCostShare.getCostShareMet() != null ? awardCostShare.getCostShareMet() : new ScaleTwoDecimal(0.00); returnVal = returnVal.add(amount); } return returnVal; } /** * This method calculates the total Direct Cost Amount for all Direct F and A Distributions. * @return The total value */ public ScaleTwoDecimal getTotalDirectFandADistributionDirectCostAmount() { ScaleTwoDecimal returnVal = new ScaleTwoDecimal(0.00); for (AwardDirectFandADistribution awardDirectFandADistribution : awardDirectFandADistributions) { ScaleTwoDecimal amount; if (awardDirectFandADistribution.getDirectCost() != null) { amount = awardDirectFandADistribution.getDirectCost(); }else { amount = new ScaleTwoDecimal(0.00); } returnVal = returnVal.add(amount); } return returnVal; } /** * This method calculates the total Direct Cost Amount for all Direct F and A Distributions. * @return The total value */ public ScaleTwoDecimal getTotalDirectFandADistributionIndirectCostAmount() { ScaleTwoDecimal returnVal = new ScaleTwoDecimal(0.00); for (AwardDirectFandADistribution awardDirectFandADistribution : awardDirectFandADistributions) { ScaleTwoDecimal amount; if (awardDirectFandADistribution.getIndirectCost() != null) { amount = awardDirectFandADistribution.getIndirectCost(); }else { amount = new ScaleTwoDecimal(0.00); } returnVal = returnVal.add(amount); } return returnVal; } /** * This method calculates the total Direct Cost Amount for all Direct F and A Distributions. * @return The total value */ public ScaleTwoDecimal getTotalDirectFandADistributionAnticipatedCostAmount() { ScaleTwoDecimal returnVal = new ScaleTwoDecimal(0.00); returnVal = returnVal.add(getTotalDirectFandADistributionDirectCostAmount()); returnVal = returnVal.add(getTotalDirectFandADistributionIndirectCostAmount()); return returnVal; } /** * This method totals Approved SubAward amounts * @return */ public ScaleTwoDecimal getTotalApprovedSubawardAmount() { return getTotalAmount(awardApprovedSubawards); } /** * This method totals Approved Equipment amounts * @return */ public ScaleTwoDecimal getTotalApprovedEquipmentAmount() { return getTotalAmount(approvedEquipmentItems); } /** * This method Approved Foreign Travel trip amounts * @return */ public ScaleTwoDecimal getTotalApprovedApprovedForeignTravelAmount() { return getTotalAmount(approvedForeignTravelTrips); } public List<AwardFandaRate> getAwardFandaRate() { return awardFandaRate; } public void setAwardFandaRate(List<AwardFandaRate> awardFandaRate) { this.awardFandaRate = awardFandaRate; } /** * Gets the keywords attribute. * @return Returns the keywords. */ @Override public List<AwardScienceKeyword> getKeywords() { return keywords; } /** * Sets the keywords attribute value. * @param keywords The keywords to set. */ public void setKeywords(List<AwardScienceKeyword> keywords) { this.keywords = keywords; } /** * @param leadUnit */ public void setLeadUnit(Unit leadUnit) { this.leadUnit = leadUnit; this.unitNumber = leadUnit != null ? leadUnit.getUnitNumber() : null; } public void setUnitNumber(String unitNumber) { this.unitNumber = unitNumber; } /** * Add selected science keyword to award science keywords list. * @see org.kuali.coeus.common.framework.keyword.KeywordsManager#addKeyword(org.kuali.coeus.common.framework.keyword.ScienceKeyword) */ public void addKeyword(ScienceKeyword scienceKeyword) { AwardScienceKeyword awardScienceKeyword = new AwardScienceKeyword(getAwardId(), scienceKeyword); getKeywords().add(awardScienceKeyword); } /** * It returns the ScienceKeyword object from keywords list * @see org.kuali.coeus.common.framework.keyword.KeywordsManager#getKeyword(int) */ public AwardScienceKeyword getKeyword(int index) { return getKeywords().get(index); } /** * Sets the awardSpecialReviews attribute value. * @param awardSpecialReviews The awardSpecialReviews to set. */ public void setSpecialReviews(List<AwardSpecialReview> awardSpecialReviews) { this.specialReviews = awardSpecialReviews; } /** * Add AwardSpecialReview to the AwardSpecialReview list * @see org.kuali.kra.document.SpecialReviewHandler#addSpecialReview(java.lang.Object) */ public void addSpecialReview(AwardSpecialReview specialReview) { specialReview.setSequenceOwner(this); getSpecialReviews().add(specialReview); } /** * Get AwardSpecialReview from special review list * @see org.kuali.kra.document.SpecialReviewHandler#getSpecialReview(int) */ public AwardSpecialReview getSpecialReview(int index) { return getSpecialReviews().get(index); } /** * Get special review list * @see org.kuali.kra.document.SpecialReviewHandler#getSpecialReviews() */ public List<AwardSpecialReview> getSpecialReviews() { return specialReviews; } /** * Add an ApprovedEquipment item * @param newAwardApprovedEquipment */ public void add(AwardApprovedEquipment approvedEquipmentItem) { approvedEquipmentItems.add(0, approvedEquipmentItem); approvedEquipmentItem.setAward(this); } /** * Add an AwardFandaRate * @param fandaRate */ public void add(AwardFandaRate fandaRate) { awardFandaRate.add(fandaRate); fandaRate.setAward(this); } /** * @param awardSpecialReview */ public void add(AwardSpecialReview awardSpecialReview) { specialReviews.add(awardSpecialReview); awardSpecialReview.setSequenceOwner(this); } public void add(AwardSponsorContact awardSponsorContact) { sponsorContacts.add(awardSponsorContact); awardSponsorContact.setAward(this); } public void add(AwardReportTerm awardReportTerm) { awardReportTermItems.add(awardReportTerm); awardReportTerm.setAward(this); } public void add(AwardCloseout awardCloseoutItem) { awardCloseoutNewItems.clear(); if(awardCloseoutItems != null && awardCloseoutItems.size() > TOTAL_STATIC_REPORTS){ for(int i = TOTAL_STATIC_REPORTS ;i < awardCloseoutItems.size() ; i++){ awardCloseoutNewItems.add(awardCloseoutItems.get(i)); } } awardCloseoutItems.removeAll(awardCloseoutNewItems); awardCloseoutNewItems.add(awardCloseoutItem); Collections.sort(awardCloseoutNewItems, new Comparator(){ public int compare(Object o1, Object o2) { if(o1 instanceof AwardCloseout && o2 instanceof AwardCloseout) { AwardCloseout awardCloseout1 = (AwardCloseout)o1; AwardCloseout awardCloseout2 = (AwardCloseout)o2; return awardCloseout1.getCloseoutReportName().compareTo(awardCloseout2.getCloseoutReportName()); } return 0; }}); awardCloseoutItems.addAll(TOTAL_STATIC_REPORTS, awardCloseoutNewItems); awardCloseoutItem.setAward(this); } public void addStaticCloseout(AwardCloseout awardCloseoutItem) { awardCloseoutItems.add(awardCloseoutItem); awardCloseoutItem.setAward(this); } /** * Add an Award Unit or Central Administration contact * @param newAwardApprovedEquipment */ public void add(AwardUnitContact awardUnitContact) { awardUnitContacts.add(awardUnitContact); awardUnitContact.setAward(this); } /** * Creates an AwardFundingProposal and adds it to the collection * * It also adds the AwardFundingProposal to the InstitutionalProposal * * @param institutionalProposal */ public void add(InstitutionalProposal institutionalProposal) { if (institutionalProposal != null) { AwardFundingProposal afp = new AwardFundingProposal(this, institutionalProposal); fundingProposals.add(afp); institutionalProposal.add(afp); //IP is Linked with award COI integration point MITKC-611 case 2 try { getKcCoiLinkService().updateCOIOnLinkIPToAward(afp.getAward().getAwardNumber(),institutionalProposal.getInstProposalNumber(),getGlobalVariableService().getUserSession().getPrincipalName()); } catch(NullPointerException e){ LOGGER.log(Level.ALL,"Input parameters return null"); }catch (SQLException e) { LOGGER.log(Level.ALL, e.getMessage(), e); LOGGER.log(Level.ALL,"DBLINK is not accessible or the parameter value returning null"); } } } /** * @param awardSponsorContact */ public void addSponsorContact(AwardSponsorContact awardSponsorContact) { sponsorContacts.add(awardSponsorContact); awardSponsorContact.setAward(this); } /** * This method adds a Project Person to the award * @param projectPerson */ public void add(AwardPerson projectPerson) { projectPersons.add(projectPerson); projectPerson.setAward(this); } /** * Add an * @param newAwardPaymentSchedule */ public void add(AwardPaymentSchedule paymentScheduleItem) { paymentScheduleItems.add(paymentScheduleItem); paymentScheduleItem.setAward(this); } public void addAwardTransferringSponsor(Sponsor sponsor) { AwardTransferringSponsor awardTransferringSponsor = new AwardTransferringSponsor(this, sponsor); awardTransferringSponsors.add(0, awardTransferringSponsor); } protected void initializeCollections() { setAwardCostShares(new ArrayList<AwardCostShare>()); setAwardComments(new ArrayList<AwardComment>()); awardApprovedSubawards = new ArrayList<AwardApprovedSubaward>(); setAwardFandaRate(new ArrayList<AwardFandaRate>()); setAwardReportTermItems(new ArrayList<AwardReportTerm>()); keywords = new ArrayList<AwardScienceKeyword>(); specialReviews = new ArrayList<AwardSpecialReview>(); approvedEquipmentItems = new ArrayList<AwardApprovedEquipment>(); approvedForeignTravelTrips = new ArrayList<AwardApprovedForeignTravel>(); setAwardSponsorTerms(new ArrayList<AwardSponsorTerm>()); paymentScheduleItems = new ArrayList<AwardPaymentSchedule>(); awardTransferringSponsors = new ArrayList<AwardTransferringSponsor>(); awardDirectFandADistributions = new ArrayList<AwardDirectFandADistribution>(); awardCustomDataList = new ArrayList<AwardCustomData>(); awardCloseoutItems = new ArrayList<AwardCloseout>(); awardCloseoutNewItems = new ArrayList<AwardCloseout>(); awardNotepads = new ArrayList<AwardNotepad>(); initializeAwardAmountInfoObjects(); projectPersons = new ArrayList<AwardPerson>(); awardUnitContacts = new ArrayList<AwardUnitContact>(); sponsorContacts = new ArrayList<AwardSponsorContact>(); awardBudgetLimits = new ArrayList<AwardBudgetLimit>(); fundingProposals = new ArrayList<AwardFundingProposal>(); initializeAwardHierarchyTempObjects(); syncChanges = new ArrayList<AwardSyncChange>(); syncStatuses = new ArrayList<AwardSyncStatus>(); subAwardList = new ArrayList<SubAward>(); budgets = new ArrayList<AwardBudgetExt>(); } public void initializeAwardAmountInfoObjects() { awardAmountInfos = new ArrayList<AwardAmountInfo>(); AwardAmountInfo awardAmountInfo = new AwardAmountInfo(); awardAmountInfo.setAward(this); awardAmountInfo.setOriginatingAwardVersion(1); awardAmountInfos.add(awardAmountInfo); } public void initializeAwardHierarchyTempObjects() { awardHierarchyTempObjects = new AutoPopulatingList<AwardHierarchyTempObject>(AwardHierarchyTempObject.class); } public ScaleTwoDecimal getPreAwardInstitutionalAuthorizedAmount() { return preAwardInstitutionalAuthorizedAmount; } /** * For negative values, this method makes the number positive by dropping the negative sign. * @param preAwardInstitutionalAuthorizedAmount */ public void setPreAwardInstitutionalAuthorizedAmount(ScaleTwoDecimal preAwardInstitutionalAuthorizedAmount) { // if preAwardInstitutionalAuthorizedAmount is negative, make it positive if (preAwardInstitutionalAuthorizedAmount != null && preAwardInstitutionalAuthorizedAmount.isNegative()) { this.preAwardInstitutionalAuthorizedAmount = ScaleTwoDecimal.ZERO.subtract(preAwardInstitutionalAuthorizedAmount); } else { this.preAwardInstitutionalAuthorizedAmount = preAwardInstitutionalAuthorizedAmount; } } public Date getPreAwardInstitutionalEffectiveDate() { return preAwardInstitutionalEffectiveDate; } public void setPreAwardInstitutionalEffectiveDate(Date preAwardInstitutionalEffectiveDate) { this.preAwardInstitutionalEffectiveDate = preAwardInstitutionalEffectiveDate; } public void add(AwardCostShare awardCostShare) { awardCostShares.add(awardCostShare); awardCostShare.setAward(this); } public void add(AwardApprovedSubaward awardApprovedSubaward) { awardApprovedSubawards.add(awardApprovedSubaward); awardApprovedSubaward.setAward(this); } public void add(AwardComment awardComment) { awardComments.add(awardComment); awardComment.setAward(this); } /** * This method adds template comments to award when sync to template is being applied. * @param awardComment */ public void addTemplateComments(List<AwardTemplateComment> awardTemplateComments) { AwardCommentFactory awardCommentFactory = new AwardCommentFactory(); for (AwardTemplateComment awardTemplateComment : awardTemplateComments) { AwardComment testAwardComment = getCommentMap().get(awardTemplateComment.getCommentTypeCode()); if (testAwardComment == null) { AwardComment awardComment = awardCommentFactory.createAwardComment(awardTemplateComment.getCommentTypeCode(), awardTemplateComment.getChecklistPrintFlag()); awardComment.setComments(awardTemplateComment.getComments()); add(awardComment); commentMap.put(awardComment.getCommentType().getCommentTypeCode(), awardComment); }else { testAwardComment.setComments(awardTemplateComment.getComments()); } } } public void add(AwardSponsorTerm awardSponsorTerm) { awardSponsorTerms.add(awardSponsorTerm); awardSponsorTerm.setAward(this); } /** * This method adds template sponsor terms to award when sync to template is being applied. * @param awardTemplateTerms */ public void addTemplateTerms(List<AwardTemplateTerm> awardTemplateTerms) { List<AwardSponsorTerm> tempAwardSponsorTerms = new ArrayList<AwardSponsorTerm>(); for (AwardTemplateTerm awardTemplateTerm : awardTemplateTerms) { tempAwardSponsorTerms.add(new AwardSponsorTerm(awardTemplateTerm.getSponsorTermId(), awardTemplateTerm.getSponsorTerm())); } setAwardSponsorTerms(tempAwardSponsorTerms); } /** * This method adds AwardDirectFandADistribution to end of list. * @param awardDirectFandADistribution */ public void add(AwardDirectFandADistribution awardDirectFandADistribution) { awardDirectFandADistributions.add(awardDirectFandADistribution); awardDirectFandADistribution.setAward(this); awardDirectFandADistribution.setBudgetPeriod(awardDirectFandADistributions.size()); } /** * This method adds AwardDirectFandADistribution to the given index in the list. * @param awardDirectFandADistribution */ public void add(int index, AwardDirectFandADistribution awardDirectFandADistribution) { awardDirectFandADistributions.add(index, awardDirectFandADistribution); awardDirectFandADistribution.setAward(this); awardDirectFandADistribution.setBudgetPeriod(index + 1); updateDirectFandADistributionBudgetPeriods(index + 1); } public void add(AwardNotepad awardNotepad) { awardNotepad.setEntryNumber(awardNotepads.size() + 1); awardNotepad.setAwardNumber(this.getAwardNumber()); awardNotepads.add(awardNotepad); awardNotepad.setAward(this); } /** * This method updates the budget periods in the Award after insertion of new Award Direct F and A Distribution into list. * @param index */ public void updateDirectFandADistributionBudgetPeriods(int index) { for (int newIndex = index; newIndex < awardDirectFandADistributions.size(); newIndex++) { awardDirectFandADistributions.get(newIndex).setBudgetPeriod(newIndex + 1); } } /** * This method calculates the total value of a list of ValuableItems * @param valuableItems * @return The total value */ ScaleTwoDecimal getTotalAmount(List<? extends ValuableItem> valuableItems) { ScaleTwoDecimal returnVal = new ScaleTwoDecimal(0.00); for (ValuableItem item : valuableItems) { ScaleTwoDecimal amount = item.getAmount() != null ? item.getAmount() : new ScaleTwoDecimal(0.00); returnVal = returnVal.add(amount); } return returnVal; } /** * Gets the awardSponsorTerms attribute. * @return Returns the awardSponsorTerms. */ public List<AwardSponsorTerm> getAwardSponsorTerms() { return awardSponsorTerms; } public AwardStatus getAwardStatus() { if (awardStatus == null && statusCode != null) { refreshReferenceObject("awardStatus"); } return awardStatus; } /** * Sets the awardSponsorTerms attribute value. * @param awardSponsorTerms The awardSponsorTerms to set. */ public void setAwardSponsorTerms(List<AwardSponsorTerm> awardSponsorTerms) { this.awardSponsorTerms = awardSponsorTerms; } /** * This method violates our policy of not calling a service in a getter. * This will only call the service once to set a sponsor when a sponsor code exists, * but no sponsor was fetched * * Seems like a persistence design issue to me. Why wouldn't Sponsor:Award be a 1:M * relationship handled automagically by the persistence framework? * * @return */ public Sponsor getSponsor() { if (!StringUtils.isEmpty(sponsorCode)) { this.refreshReferenceObject("sponsor"); } return sponsor; } public List<AwardSponsorContact> getSponsorContacts() { return sponsorContacts; } public void setSponsorContacts(List<AwardSponsorContact> awardSponsorContacts) { this.sponsorContacts = awardSponsorContacts; } public void setSponsor(Sponsor sponsor) { this.sponsor = sponsor; this.sponsorCode = sponsor != null ? sponsor.getSponsorCode() : null; } public String getSponsorName() { Sponsor sponsor = getSponsor(); sponsorName = sponsor != null ? sponsor.getSponsorName() : null; return sponsorName; } public String getIcrRateCode() { return icrRateCode; } public void setIcrRateCode(String icrRateCode) { this.icrRateCode = icrRateCode; } /** * This method adds an approved foreign travel trip * @param approvedForeignTravelTrip */ public void add(AwardApprovedForeignTravel approvedForeignTravelTrip) { approvedForeignTravelTrips.add(approvedForeignTravelTrip); approvedForeignTravelTrip.setAward(this); } /** * Gets the paymentScheduleItems attribute. * @return Returns the paymentScheduleItems. */ public List<AwardPaymentSchedule> getPaymentScheduleItems() { return paymentScheduleItems; } /** * Sets the paymentScheduleItems attribute value. * @param paymentScheduleItems The paymentScheduleItems to set. */ public void setPaymentScheduleItems(List<AwardPaymentSchedule> paymentScheduleItems) { this.paymentScheduleItems = paymentScheduleItems; } public ScaleTwoDecimal getTotalPaymentScheduleAmount() { ScaleTwoDecimal amount = ScaleTwoDecimal.ZERO; for (AwardPaymentSchedule schedule : paymentScheduleItems) { if (schedule.getAmount() != null) { amount = amount.add(schedule.getAmount()); } } return amount; } // Note: following the pattern of Sponsor, this getter indirectly calls a service. // Is there a better way? public Sponsor getPrimeSponsor() { if (!StringUtils.isEmpty(getPrimeSponsorCode())) { this.refreshReferenceObject("primeSponsor"); } return primeSponsor; } public void setPrimeSponsor(Sponsor primeSponsor) { this.primeSponsor = primeSponsor; } public List<AwardTransferringSponsor> getAwardTransferringSponsors() { return awardTransferringSponsors; } /** * @param awardStatus */ public void setAwardStatus(AwardStatus awardStatus) { this.awardStatus = awardStatus; } public void setAwardTransferringSponsors(List<AwardTransferringSponsor> awardTransferringSponsors) { this.awardTransferringSponsors = awardTransferringSponsors; } /** * Gets the awardDirectFandADistribution attribute. * @return Returns the awardDirectFandADistribution. */ public List<AwardDirectFandADistribution> getAwardDirectFandADistributions() { return awardDirectFandADistributions; } /** * Sets the awardDirectFandADistribution attribute value. * @param awardDirectFandADistribution The awardDirectFandADistribution to set. */ public void setAwardDirectFandADistributions(List<AwardDirectFandADistribution> awardDirectFandADistributions) { for (AwardDirectFandADistribution awardDirectFandADistribution : awardDirectFandADistributions) { awardDirectFandADistribution.setAward(this); } this.awardDirectFandADistributions = awardDirectFandADistributions; } /** * Gets the awardNotepads attribute. * @return Returns the awardNotepads. */ public List<AwardNotepad> getAwardNotepads() { return awardNotepads; } /** * Sets the awardNotepads attribute value. * @param awardNotepads The awardNotepads to set. */ public void setAwardNotepads(List<AwardNotepad> awardNotepads) { this.awardNotepads = awardNotepads; } /** * Gets the indirectCostIndicator attribute. * @return Returns the indirectCostIndicator. */ public String getIndirectCostIndicator() { return indirectCostIndicator; } /** * Sets the indirectCostIndicator attribute value. * @param indirectCostIndicator The indirectCostIndicator to set. */ public void setIndirectCostIndicator(String indirectCostIndicator) { this.indirectCostIndicator = indirectCostIndicator; } /** * Gets the obligatedTotal attribute. * @return Returns the obligatedTotal. */ public ScaleTwoDecimal getObligatedTotal() { ScaleTwoDecimal returnValue = new ScaleTwoDecimal(0.00); // if(awardAmountInfos.get(0).getAmountObligatedToDate()!=null){ // returnValue = returnValue.add(awardAmountInfos.get(0).getAmountObligatedToDate()); // } if (getLastAwardAmountInfo().getAmountObligatedToDate() != null) { returnValue = returnValue.add(getLastAwardAmountInfo().getAmountObligatedToDate()); } return returnValue; } public ScaleTwoDecimal getObligatedDistributableTotal() { ScaleTwoDecimal returnValue = ScaleTwoDecimal.ZERO; if (getLastAwardAmountInfo().getObliDistributableAmount() != null) { returnValue = getLastAwardAmountInfo().getObliDistributableAmount(); } return returnValue; } /** * Returns the obligated distributable total or the total cost limit * whichever is less. * @return */ public ScaleTwoDecimal getBudgetTotalCostLimit() { ScaleTwoDecimal limit = getTotalCostBudgetLimit(); ScaleTwoDecimal obliTotal = getObligatedDistributableTotal(); if (limit != null && limit.isLessEqual(obliTotal)) { return limit; } else { return obliTotal; } } /** * Gets the obligatedTotal attribute. * @return Returns the obligatedTotal. */ public ScaleTwoDecimal getObligatedTotalDirect() { ScaleTwoDecimal returnValue = new ScaleTwoDecimal(0.00); // if(awardAmountInfos.get(0).getAmountObligatedToDate()!=null){ // returnValue = returnValue.add(awardAmountInfos.get(0).getAmountObligatedToDate()); // } if (getLastAwardAmountInfo().getObligatedTotalDirect() != null) { returnValue = returnValue.add(getLastAwardAmountInfo().getObligatedTotalDirect()); } return returnValue; } /** * Gets the obligatedTotal attribute. * @return Returns the obligatedTotal. */ public ScaleTwoDecimal getObligatedTotalIndirect() { ScaleTwoDecimal returnValue = new ScaleTwoDecimal(0.00); // if(awardAmountInfos.get(0).getAmountObligatedToDate()!=null){ // returnValue = returnValue.add(awardAmountInfos.get(0).getAmountObligatedToDate()); // } if (getLastAwardAmountInfo().getObligatedTotalIndirect() != null) { returnValue = returnValue.add(getLastAwardAmountInfo().getObligatedTotalIndirect()); } return returnValue; } /** * Gets the anticipatedTotal attribute. * @return Returns the anticipatedTotal. */ public ScaleTwoDecimal getAnticipatedTotal() { ScaleTwoDecimal returnValue = new ScaleTwoDecimal(0.00); // if(awardAmountInfos.get(0).getAnticipatedTotalAmount()!=null){ // returnValue = returnValue.add(awardAmountInfos.get(0).getAnticipatedTotalAmount()); // } if (getLastAwardAmountInfo().getAnticipatedTotalAmount() != null) { returnValue = returnValue.add(getLastAwardAmountInfo().getAnticipatedTotalAmount()); } return returnValue; } /** * Gets the anticipatedTotal attribute. * @return Returns the anticipatedTotal. */ public ScaleTwoDecimal getAnticipatedTotalDirect() { ScaleTwoDecimal returnValue = new ScaleTwoDecimal(0.00); // if(awardAmountInfos.get(0).getAnticipatedTotalAmount()!=null){ // returnValue = returnValue.add(awardAmountInfos.get(0).getAnticipatedTotalAmount()); // } if (getLastAwardAmountInfo().getAnticipatedTotalDirect() != null) { returnValue = returnValue.add(getLastAwardAmountInfo().getAnticipatedTotalDirect()); } return returnValue; } /** * Gets the anticipatedTotal attribute. * @return Returns the anticipatedTotal. */ public ScaleTwoDecimal getAnticipatedTotalIndirect() { ScaleTwoDecimal returnValue = new ScaleTwoDecimal(0.00); // if(awardAmountInfos.get(0).getAnticipatedTotalAmount()!=null){ // returnValue = returnValue.add(awardAmountInfos.get(0).getAnticipatedTotalAmount()); // } if (getLastAwardAmountInfo().getAnticipatedTotalIndirect() != null) { returnValue = returnValue.add(getLastAwardAmountInfo().getAnticipatedTotalIndirect()); } return returnValue; } @Override public String getDocumentNumberForPermission() { return awardId != null ? awardId.toString() : ""; } @Override public String getDocumentKey() { return PermissionableKeys.AWARD_KEY; } @Override public List<String> getRoleNames() { List<String> roles = new ArrayList<String>(); SystemAuthorizationService systemAuthorizationService = KcServiceLocator.getService("systemAuthorizationService"); List<Role> roleBOs = systemAuthorizationService.getRoles(Constants.MODULE_NAMESPACE_AWARD); for(Role role : roleBOs) { roles.add(role.getName()); } return roles; } public List<AwardAmountInfo> getAwardAmountInfos() { return awardAmountInfos; } public void setAwardAmountInfos(List<AwardAmountInfo> awardAmountInfos) { this.awardAmountInfos = awardAmountInfos; } public AwardAmountInfo getAwardAmountInfo() { return awardAmountInfos.get(0); } /** * Find the lead unit for the award * @return */ public Unit getLeadUnit() { if (leadUnit == null && unitNumber != null) { loadLeadUnit(); } return leadUnit; } public boolean isNew() { return awardId == null; } class ARTComparator implements Comparator { public int compare(Object art1, Object art2) { try { String art1Desc = ((AwardReportTerm) art1).getReport().getDescription(); String art2Desc = ((AwardReportTerm) art2).getReport().getDescription(); if (art1Desc == null) { art1Desc = ""; } if (art2Desc == null) { art2Desc = ""; } return art1Desc.compareTo(art2Desc); } catch (Exception e) { return 0; } } } /** * Gets the awardReportTermItems attribute. * @return Returns the awardReportTermItems. */ public List<AwardReportTerm> getAwardReportTermItems() { Collections.sort(awardReportTermItems, new ARTComparator()); return awardReportTermItems; } /** * Sets the awardReportTermItems attribute value. * @param awardReportTermItems The awardReportTermItems to set. */ public void setAwardReportTermItems(List<AwardReportTerm> awardReportTermItems) { this.awardReportTermItems = awardReportTermItems; } /** * Find principle investigator, if any * @return Principle investigator. May return null */ public AwardPerson getPrincipalInvestigator() { AwardPerson principleInvestigator = null; for (AwardPerson person : projectPersons) { if (person.isPrincipalInvestigator()) { principleInvestigator = person; break; } } return principleInvestigator; } /** * This method find PI name * @return PI name; may return null */ public String getPrincipalInvestigatorName() { AwardPerson pi = getPrincipalInvestigator(); if (pi != null) { if (pi.getIsRolodexPerson()) { principalInvestigatorName = pi.getRolodex().getOrganization(); } else { principalInvestigatorName = pi.getFullName(); } } return principalInvestigatorName; } /** * @param principalInvestigatorName */ public void setPrincipalInvestigatorName(String principalInvestigatorName) { this.principalInvestigatorName = principalInvestigatorName; } /** * This method returns the status description * @return */ public String getStatusDescription() { AwardStatus status = getAwardStatus(); statusDescription = status != null ? status.getDescription() : null; return statusDescription; } /** * Gets the awardCustomDataList attribute. * @return Returns the awardCustomDataList. */ public List<AwardCustomData> getAwardCustomDataList() { return awardCustomDataList; } /** * Sets the awardCustomDataList attribute value. * @param awardCustomDataList The awardCustomDataList to set. */ public void setAwardCustomDataList(List<AwardCustomData> awardCustomDataList) { this.awardCustomDataList = awardCustomDataList; } /** * Gets the awardCloseoutItems attribute. * @return Returns the awardCloseoutItems. */ public List<AwardCloseout> getAwardCloseoutItems() { return awardCloseoutItems; } /** * Sets the awardCloseoutItems attribute value. * @param awardCloseoutItems The awardCloseoutItems to set. */ public void setAwardCloseoutItems(List<AwardCloseout> awardCloseoutItems) { if(awardCloseoutItems != null && awardCloseoutItems.size() > TOTAL_STATIC_REPORTS){ awardCloseoutNewItems.clear(); for(int i = TOTAL_STATIC_REPORTS ;i < awardCloseoutItems.size() ; i++){ awardCloseoutNewItems.add(awardCloseoutItems.get(i)); } for (int i = awardCloseoutItems.size();i > TOTAL_STATIC_REPORTS; i--) { awardCloseoutItems.remove(i - 1); } Collections.sort(awardCloseoutNewItems, new Comparator(){ public int compare(Object o1, Object o2) { if(o1 instanceof AwardCloseout && o2 instanceof AwardCloseout) { AwardCloseout awardCloseout1 = (AwardCloseout)o1; AwardCloseout awardCloseout2 = (AwardCloseout)o2; return awardCloseout1.getCloseoutReportName().compareTo(awardCloseout2.getCloseoutReportName()); } return 0; }}); awardCloseoutItems.addAll(TOTAL_STATIC_REPORTS, awardCloseoutNewItems); } this.awardCloseoutItems = awardCloseoutItems; } /** * Gets the awardCloseoutNewItems attribute. * @return Returns the awardCloseoutNewItems. */ public List<AwardCloseout> getAwardCloseoutNewItems() { return awardCloseoutNewItems; } /** * Sets the awardCloseoutNewItems attribute value. * @param awardCloseoutNewItems The awardCloseoutNewItems to set. */ public void setAwardCloseoutNewItems(List<AwardCloseout> awardCloseoutNewItems) { this.awardCloseoutNewItems = awardCloseoutNewItems; } /** * Sets the templateCode attribute value. * @param templateCode The templateCode to set. */ public void setTemplateCode(Integer templateCode) { this.templateCode = templateCode; } /** * Gets the primeSponsorCode attribute. * @return Returns the primeSponsorCode. */ public String getPrimeSponsorCode() { return primeSponsorCode; } /** * Sets the primeSponsorCode attribute value. * @param primeSponsorCode The primeSponsorCode to set. */ public void setPrimeSponsorCode(String primeSponsorCode) { this.primeSponsorCode = primeSponsorCode; } /** * Gets the basisOfPaymentCode attribute. * @return Returns the basisOfPaymentCode. */ public String getBasisOfPaymentCode() { return basisOfPaymentCode; } /** * Sets the basisOfPaymentCode attribute value. * @param basisOfPaymentCode The basisOfPaymentCode to set. */ public void setBasisOfPaymentCode(String basisOfPaymentCode) { this.basisOfPaymentCode = basisOfPaymentCode; } /** * Gets the methodOfPaymentCode attribute. * @return Returns the methodOfPaymentCode. */ public String getMethodOfPaymentCode() { return methodOfPaymentCode; } /** * Sets the methodOfPaymentCode attribute value. * @param methodOfPaymentCode The methodOfPaymentCode to set. */ public void setMethodOfPaymentCode(String methodOfPaymentCode) { this.methodOfPaymentCode = methodOfPaymentCode; } /** * Gets the awardTemplate attribute. * @return Returns the awardTemplate. */ public AwardTemplate getAwardTemplate() { return awardTemplate; } /** * Sets the awardTemplate attribute value. * @param awardTemplate The awardTemplate to set. */ public void setAwardTemplate(AwardTemplate awardTemplate) { this.awardTemplate = awardTemplate; } /** * Gets the awardBasisOfPayment attribute. * @return Returns the awardBasisOfPayment. */ public AwardBasisOfPayment getAwardBasisOfPayment() { return awardBasisOfPayment; } /** * Sets the awardBasisOfPayment attribute value. * @param awardBasisOfPayment The awardBasisOfPayment to set. */ public void setAwardBasisOfPayment(AwardBasisOfPayment awardBasisOfPayment) { this.awardBasisOfPayment = awardBasisOfPayment; } /** * Gets the awardMethodOfPayment attribute. * @return Returns the awardMethodOfPayment. */ public AwardMethodOfPayment getAwardMethodOfPayment() { return awardMethodOfPayment; } /** * Sets the awardMethodOfPayment attribute value. * @param awardMethodOfPayment The awardMethodOfPayment to set. */ public void setAwardMethodOfPayment(AwardMethodOfPayment awardMethodOfPayment) { this.awardMethodOfPayment = awardMethodOfPayment; } @Override public Integer getOwnerSequenceNumber() { return null; } @Override public void incrementSequenceNumber() { this.sequenceNumber++; } @Override public Award getSequenceOwner() { return this; } @Override public void setSequenceOwner(Award newOwner) { // no-op } @Override public void resetPersistenceState() { this.awardId = null; } @Override public String getVersionNameField() { return "awardNumber"; } /** * Gets the activityType attribute. * @return Returns the activityType. */ public ActivityType getActivityType() { return activityType; } /** * Sets the activityType attribute value. * @param activityType The activityType to set. */ public void setActivityType(ActivityType activityType) { this.activityType = activityType; } /** * This method removes Funding Proposal for specified index from list * * It also removes the AwardFundingProposal from the InstitutionalProposal * * @param index */ public AwardFundingProposal removeFundingProposal(int index) { AwardFundingProposal afp = (index >= 0) ? fundingProposals.remove(index) : null; afp.getProposalId(); InstitutionalProposal proposal = getInstitutionalProposalService().getInstitutionalProposal(afp.getProposalId().toString()); if (proposal != null) { proposal.remove(afp); } return afp; } private InstitutionalProposalService getInstitutionalProposalService() { return KcServiceLocator.getService(InstitutionalProposalService.class); } /** * Given an AwardComment as a template, try to find an existing AwardComment of that type * @param template * @return The found awardComment of a specific type. If an existing comment is not found, return null */ public AwardComment findCommentOfSpecifiedType(AwardComment template) { return findCommentOfSpecifiedType(template.getCommentTypeCode()); } /** * For a given type code, this method returns the award comment, or null if none exists. * @param commentTypeCode One of the ..._COMMENT_TYPE_CODE values in org.kuali.kra.infrastructure.Constants * @return */ public AwardComment findCommentOfSpecifiedType(String commentTypeCode) { AwardComment comment = null; for (AwardComment ac : getAwardComments()) { if (ac.getCommentTypeCode().equals(commentTypeCode)) { comment = ac; break; } } return comment; } public String getBudgetStatus() { // hard coded as completed return "2"; } public List getPersonRolodexList() { return getProjectPersons(); } public PersonRolodex getProposalEmployee(String personId) { return getPerson(personId, true); } private PersonRolodex getPerson(String personId, boolean personFindFlag) { List<AwardPerson> awardPersons = getProjectPersons(); for (AwardPerson awardPerson : awardPersons) { // rearranged order of condition to handle null personId if ((personId != null) && personId.equals(awardPerson.getPersonId())) { if (personFindFlag && awardPerson.isEmployee()) { return awardPerson; }else{ return awardPerson; } } } return null; } public ContactRole getProposalEmployeeRole(String personId) { if (getProposalEmployee(personId) != null) { return ((AwardPerson) getProposalEmployee(personId)).getContactRole(); } else { return null; } } public PersonRolodex getProposalNonEmployee(Integer rolodexId) { List<AwardPerson> awardPersons = getProjectPersons(); for (AwardPerson awardPerson : awardPersons) { if (rolodexId.equals(awardPerson.getRolodexId())) { return awardPerson; } } return null; } public ContactRole getProposalNonEmployeeRole(Integer rolodexId) { if (getProposalNonEmployee(rolodexId) != null) { return ((AwardPerson) getProposalNonEmployee(rolodexId)).getContactRole(); } else { return null; } } public Date getRequestedEndDateInitial() { return getObligationExpirationDate(); } public Date getRequestedStartDateInitial() { AwardAmountInfo awardAmountInfo = getLastAwardAmountInfo(); return awardAmountInfo == null ? null : awardAmountInfo.getCurrentFundEffectiveDate(); } public Unit getUnit() { return getLeadUnit(); } public boolean isSponsorNihMultiplePi() { return sponsorNihMultiplePi; } public void setBudgetStatus(String budgetStatus) { } /** * Gets the attachmentsw. Cannot return {@code null}. * @return the attachments */ public List<AwardAttachment> getAwardAttachments() { if (this.awardAttachments == null) { this.awardAttachments = new ArrayList<AwardAttachment>(); } return this.awardAttachments; } public void setAttachments(List<AwardAttachment> attachments) { this.awardAttachments = attachments; } /** * Gets an attachment. * @param index the index * @return an attachment personnel */ public AwardAttachment getAwardAttachment(int index) { return this.awardAttachments.get(index); } /** * add an attachment. * @param attachment the attachment * @throws IllegalArgumentException if attachment is null */ public void addAttachment(AwardAttachment attachment) { this.getAwardAttachments().add(attachment); attachment.setAward(this); } /** * This method indicates if the Awrd has been persisted * @return True if persisted */ public boolean isPersisted() { return awardId != null; } public AwardApprovedSubaward getAwardApprovedSubawards(int index) { return getAwardApprovedSubawards().get(index); } public String getNamespace() { return Constants.MODULE_NAMESPACE_AWARD; } public String getDocumentRoleTypeCode() { return RoleConstants.AWARD_ROLE_TYPE; } protected void loadLeadUnit() { leadUnit = (Unit) getBusinessObjectService().findByPrimaryKey(Unit.class, Collections.singletonMap("unitNumber", getUnitNumber())); } public void populateAdditionalQualifiedRoleAttributes(Map<String, String> qualifiedRoleAttributes) { /** * when we check to see if the logged in user can create an award account, this function is called, but awardDocument is null at that time. */ String documentNumber = getAwardDocument() != null ? getAwardDocument().getDocumentNumber() : ""; qualifiedRoleAttributes.put("documentNumber", documentNumber); } protected BusinessObjectService getBusinessObjectService() { return KcServiceLocator.getService(BusinessObjectService.class); } public String getHierarchyStatus() { return "N"; } /** * This method gets the obligated, distributable amount for the Award. This may be replacable with the Award TimeAndMoney obligatedAmount value, but * at the time of its creation, TimeAndMoney wasn't complete * @return */ public ScaleTwoDecimal calculateObligatedDistributedAmountTotal() { ScaleTwoDecimal sum = ScaleTwoDecimal.ZERO; for (AwardAmountInfo amountInfo : getAwardAmountInfos()) { ScaleTwoDecimal obligatedDistributableAmount = amountInfo.getObliDistributableAmount(); sum = sum.add(obligatedDistributableAmount != null ? obligatedDistributableAmount : ScaleTwoDecimal.ZERO); } return sum; } /** * This method finds the latest final expiration date from the collection of AmnoutInfos * @return The latest final expiration date from the collection of AmnoutInfos. If there are no AmoutInfos, 1/1/1900 is returned */ public Date findLatestFinalExpirationDate() { Date latestExpDate = new Date(new GregorianCalendar(1900, Calendar.JANUARY, 1).getTimeInMillis()); for (AwardAmountInfo amountInfo : getAwardAmountInfos()) { Date expDate = amountInfo.getFinalExpirationDate(); if (expDate != null && expDate.after(latestExpDate)) { latestExpDate = expDate; } } return latestExpDate; } public boolean isParentInHierarchyComplete() { return true; } public String getDefaultBudgetStatusParameter() { return KeyConstants.AWARD_BUDGET_STATUS_IN_PROGRESS; } /** * * @return awardHierarchyTempObjects */ public List<AwardHierarchyTempObject> getAwardHierarchyTempObjects() { return awardHierarchyTempObjects; } public AwardHierarchyTempObject getAwardHierarchyTempObject(int index) { if (awardHierarchyTempObjects == null) { initializeAwardHierarchyTempObjects(); } return awardHierarchyTempObjects.get(index); } public AwardType getAwardType() { return awardType; } public void setAwardType(AwardType awardType) { this.awardType = awardType; } /** * * This method text area tag need this method. * @param index * @return */ public AwardComment getAwardComment(int index) { while (getAwardComments().size() <= index) { getAwardComments().add(new AwardComment()); } return getAwardComments().get(index); } public String getDocIdStatus() { return docIdStatus; } public String getAwardIdAccount() { if (awardIdAccount == null) { if (StringUtils.isNotBlank(getAccountNumber())) { awardIdAccount = getAwardNumber() + ":" + getAccountNumber(); } else { awardIdAccount = getAwardNumber() + ":"; } } return awardIdAccount; } public void setLookupOspAdministratorName(String lookupOspAdministratorName) { this.lookupOspAdministratorName = lookupOspAdministratorName; } public String getLookupOspAdministratorName() { return lookupOspAdministratorName; } /** * * Returns a list of central admin contacts based on the lead unit of this award. * @return */ public List<AwardUnitContact> getCentralAdminContacts() { if (centralAdminContacts == null) { initCentralAdminContacts(); } return centralAdminContacts; } /** * Builds the list of central admin contacts based on the lead unit of this * award. Build here instead of on a form bean as ospAdministrator * must be accessible during Award lookup. * */ public void initCentralAdminContacts() { centralAdminContacts = new ArrayList<AwardUnitContact>(); List<UnitAdministrator> unitAdministrators = KcServiceLocator.getService(UnitService.class).retrieveUnitAdministratorsByUnitNumber(getUnitNumber()); for (UnitAdministrator unitAdministrator : unitAdministrators) { if(unitAdministrator.getUnitAdministratorType().getDefaultGroupFlag().equals(DEFAULT_GROUP_CODE_FOR_CENTRAL_ADMIN_CONTACTS)) { KcPerson person = getKcPersonService().getKcPersonByPersonId(unitAdministrator.getPersonId()); AwardUnitContact newAwardUnitContact = new AwardUnitContact(); newAwardUnitContact.setAward(this); newAwardUnitContact.setPerson(person); newAwardUnitContact.setUnitAdministratorType(unitAdministrator.getUnitAdministratorType()); newAwardUnitContact.setFullName(person.getFullName()); centralAdminContacts.add(newAwardUnitContact); } } } public boolean isAwardInMultipleNodeHierarchy() { return awardInMultipleNodeHierarchy; } public void setAwardInMultipleNodeHierarchy(boolean awardInMultipleNodeHierarchy) { this.awardInMultipleNodeHierarchy = awardInMultipleNodeHierarchy; } public boolean isAwardHasAssociatedTandMOrIsVersioned() { return awardHasAssociatedTandMOrIsVersioned; } public void setAwardHasAssociatedTandMOrIsVersioned(boolean awardHasAssociatedTandMOrIsVersioned) { this.awardHasAssociatedTandMOrIsVersioned = awardHasAssociatedTandMOrIsVersioned; } public boolean isSyncChild() { return syncChild; } public void setSyncChild(boolean syncChild) { this.syncChild = syncChild; } public List<AwardSyncChange> getSyncChanges() { return syncChanges; } public void setSyncChanges(List<AwardSyncChange> syncChanges) { this.syncChanges = syncChanges; } public List<AwardSyncStatus> getSyncStatuses() { return syncStatuses; } public void setSyncStatuses(List<AwardSyncStatus> syncStatuses) { this.syncStatuses = syncStatuses; } public void setSponsorNihMultiplePi(boolean sponsorNihMultiplePi) { this.sponsorNihMultiplePi = sponsorNihMultiplePi; } /* * Used by Current Report to determine if award in Active, Pending, or Hold state. */ private static String reportedStatus = "1 3 6"; public boolean isActiveVersion() { return (reportedStatus.indexOf(getAwardStatus().getStatusCode()) != -1); } public List<AwardBudgetLimit> getAwardBudgetLimits() { return awardBudgetLimits; } public void setAwardBudgetLimits(List<AwardBudgetLimit> awardBudgetLimits) { this.awardBudgetLimits = awardBudgetLimits; } public ScaleTwoDecimal getTotalCostBudgetLimit() { return getSpecificBudgetLimit(AwardBudgetLimit.LIMIT_TYPE.TOTAL_COST).getLimit(); } public ScaleTwoDecimal getDirectCostBudgetLimit() { return getSpecificBudgetLimit(AwardBudgetLimit.LIMIT_TYPE.DIRECT_COST).getLimit(); } public ScaleTwoDecimal getIndirectCostBudgetLimit() { return getSpecificBudgetLimit(AwardBudgetLimit.LIMIT_TYPE.INDIRECT_COST).getLimit(); } protected AwardBudgetLimit getSpecificBudgetLimit(AwardBudgetLimit.LIMIT_TYPE type) { for (AwardBudgetLimit limit : getAwardBudgetLimits()) { if (limit.getLimitType() == type) { return limit; } } return new AwardBudgetLimit(type); } public List<Boolean> getAwardCommentHistoryFlags() { return awardCommentHistoryFlags; } public void setAwardCommentHistoryFlags(List<Boolean> awardCommentHistoryFlags) { this.awardCommentHistoryFlags = awardCommentHistoryFlags; } public void orderStaticCloseOutReportItems(List<AwardCloseout> awardCloseoutItems) { if(awardCloseoutItems != null && awardCloseoutItems.size() == TOTAL_STATIC_REPORTS){ awardCloseoutNewItems.clear(); List<AwardCloseout> staticCloseoutItems = new ArrayList<AwardCloseout>(); for(int i = 0; i < TOTAL_STATIC_REPORTS ; i++){ staticCloseoutItems.add(awardCloseoutItems.get(i)); awardCloseoutNewItems.add(awardCloseoutItems.get(i)); } awardCloseoutItems.removeAll(staticCloseoutItems); for(AwardCloseout awardCloseout : staticCloseoutItems){ if(awardCloseout.getCloseoutReportCode() != null && awardCloseout.getCloseoutReportCode().equalsIgnoreCase(CLOSE_OUT_REPORT_TYPE_FINANCIAL_REPORT)){ awardCloseoutNewItems.remove(awardCloseout); awardCloseoutNewItems.add(0,awardCloseout); }else if(awardCloseout.getCloseoutReportCode() != null && awardCloseout.getCloseoutReportCode().equalsIgnoreCase(CLOSE_OUT_REPORT_TYPE_TECHNICAL)){ awardCloseoutNewItems.remove(awardCloseout); awardCloseoutNewItems.add(1,awardCloseout); }else if(awardCloseout.getCloseoutReportCode() != null && awardCloseout.getCloseoutReportCode().equalsIgnoreCase(CLOSE_OUT_REPORT_TYPE_PATENT)){ awardCloseoutNewItems.remove(awardCloseout); awardCloseoutNewItems.add(2,awardCloseout); }else if(awardCloseout.getCloseoutReportCode() != null && awardCloseout.getCloseoutReportCode().equalsIgnoreCase(CLOSE_OUT_REPORT_TYPE_PROPERTY)){ awardCloseoutNewItems.remove(awardCloseout); awardCloseoutNewItems.add(3,awardCloseout); }else if(awardCloseout.getCloseoutReportCode() != null && awardCloseout.getCloseoutReportCode().equalsIgnoreCase(CLOSE_OUT_REPORT_TYPE_INVOICE)){ awardCloseoutNewItems.remove(awardCloseout); awardCloseoutNewItems.add(4,awardCloseout); } } awardCloseoutItems.addAll(0,awardCloseoutNewItems); } } @Override public String getLeadUnitName() { String name = getLeadUnit() == null ? EMPTY_STRING : getLeadUnit().getUnitName(); return name; } @Override public String getPiName() { return getPiEmployeeName(); } @Override public String getPiEmployeeName() { return getPrincipalInvestigatorName(); } @Override public String getPiNonEmployeeName() { return EMPTY_STRING; } @Override public String getAdminPersonName() { return EMPTY_STRING; } @Override public String getPrimeSponsorName() { String name = getPrimeSponsor() == null ? EMPTY_STRING : getPrimeSponsor().getSponsorName(); return name; } @Override public String getSubAwardOrganizationName() { return EMPTY_STRING; } @Override public List<NegotiationPersonDTO> getProjectPeople() { List<NegotiationPersonDTO> kcPeople = new ArrayList<NegotiationPersonDTO>(); for (AwardPerson person : getProjectPersons()) { kcPeople.add(new NegotiationPersonDTO(person.getPerson(), person.getContactRoleCode())); } return kcPeople; } public String getNegotiableProposalTypeCode() { return EMPTY_STRING; } public String getParentNumber() { return this.getAwardNumber(); } public String getParentPIName() { String investigatorName = null; for (AwardPerson aPerson : this.getProjectPersons()) { if (aPerson != null && aPerson.isPrincipalInvestigator() ) { investigatorName = aPerson.getFullName(); break; } } return investigatorName; } public String getParentTitle() { return this.getTitle(); } public String getIsOwnedByUnit() { return this.getLeadUnitName(); } public Integer getParentInvestigatorFlag(String personId, Integer flag) { for (AwardPerson aPerson : this.getProjectPersons()) { if (aPerson.getPersonId() != null && aPerson.getPersonId().equals(personId) || aPerson.getRolodexId() != null && aPerson.getRolodexId().equals(personId)) { flag = 2; if (aPerson.isPrincipalInvestigator()) { flag = 1; break; } } } return flag; } /** * This method gets the current rate. * If there are multiple current rates, return the one with the higher rate * @param award * @return currentFandaRate */ public AwardFandaRate getCurrentFandaRate() { List<AwardFandaRate> rates = this.getAwardFandaRate(); Calendar calendar = Calendar.getInstance(); int currentYear = calendar.get(Calendar.YEAR); AwardFandaRate currentFandaRate; // when both On and Off campus rates are in, send the higher one. Ideally only one should be there // the single rate validation parameter needs to be set on award ScaleTwoDecimal currentRateValue = new ScaleTwoDecimal(0.0); currentFandaRate = rates.get(0); for (AwardFandaRate rate : rates) { if (Integer.parseInt(rate.getFiscalYear()) == currentYear) { if (rate.getApplicableFandaRate().isGreaterThan(currentRateValue)) { currentFandaRate = rate; currentRateValue = rate.getApplicableFandaRate(); } } } return currentFandaRate; } public String getParentTypeName(){ return "Award"; } @Override public String getAssociatedDocumentId() { return getAwardNumber(); } public String getAwardSequenceStatus() { return awardSequenceStatus; } public void setAwardSequenceStatus(String awardSequenceStatus) { this.awardSequenceStatus = awardSequenceStatus; } @Override public ProposalType getNegotiableProposalType() { return null; } @Override public String getSubAwardRequisitionerName() { return EMPTY_STRING; } @Override public String getSubAwardRequisitionerUnitNumber() { return EMPTY_STRING; } @Override public String getSubAwardRequisitionerUnitName() { return EMPTY_STRING; } @Override public String getSubAwardRequisitionerId() { return EMPTY_STRING; } public List<SubAward> getSubAwardList() { return subAwardList; } public void setSubAwardList(List<SubAward> subAwardList) { this.subAwardList = subAwardList; } @Override public String getProjectName() { return getTitle(); } @Override public String getProjectId() { return getAwardNumber(); } public boolean isAllowUpdateTimestampToBeReset() { return allowUpdateTimestampToBeReset; } /** * * Setting this value to false will prevent the update timestamp field from being upddate just once. After that, the update timestamp field will update as regular. * @param allowUpdateTimestampToBeReset */ public void setAllowUpdateTimestampToBeReset(boolean allowUpdateTimestampToBeReset) { this.allowUpdateTimestampToBeReset = allowUpdateTimestampToBeReset; } @Override public void setUpdateTimestamp(Timestamp updateTimestamp) { if (isAllowUpdateTimestampToBeReset()) { super.setUpdateTimestamp(updateTimestamp); } else { setAllowUpdateTimestampToBeReset(true); } } public List<Award> getAwardVersions() { Map<String, String> fieldValues = new HashMap<String,String>(); fieldValues.put("awardNumber", getAwardNumber()); BusinessObjectService businessObjectService = KcServiceLocator.getService(BusinessObjectService.class); List<Award> awards = (List<Award>)businessObjectService.findMatchingOrderBy(Award.class, fieldValues, "sequenceNumber", true); return awards; } public String getAwardDescriptionLine() { AwardAmountInfo aai = getLastAwardAmountInfo(); String transactionTypeDescription; String versionNumber; if(aai == null || aai.getOriginatingAwardVersion() == null) { versionNumber = getSequenceNumber().toString(); }else { versionNumber = aai.getOriginatingAwardVersion().toString(); } if(!(getAwardTransactionType() == null)) { transactionTypeDescription = getAwardTransactionType().getDescription(); }else { transactionTypeDescription = "None"; } return "Award Version " + versionNumber + ", " + transactionTypeDescription + ", updated " + getUpdateTimeAndUser(); } public String getUpdateTimeAndUser() { String createDateStr = null; String updateUser = null; if (getUpdateTimestamp() != null) { createDateStr = CoreApiServiceLocator.getDateTimeService().toString(getUpdateTimestamp(), "hh:mm:ss a MM/dd/yyyy"); updateUser = getUpdateUser().length() > 30 ? getUpdateUser().substring(0, 30) : getUpdateUser(); } return createDateStr + ", by " + updateUser; } public List<TimeAndMoneyDocumentHistory>getTimeAndMoneyDocumentHistoryList() throws WorkflowException { List<TimeAndMoneyDocument> tnmDocs = getTimeAndMoneyHistoryService().buildTimeAndMoneyListForAwardDisplay(this); List<TimeAndMoneyDocumentHistory> timeAndMoneyHistoryList = getTimeAndMoneyHistoryService().getDocHistoryAndValidInfosAssociatedWithAwardVersion(tnmDocs,getAwardAmountInfos(), this); return timeAndMoneyHistoryList; } public VersionHistorySearchBo getVersionHistory() { return versionHistory; } public void setVersionHistory(VersionHistorySearchBo versionHistory) { this.versionHistory = versionHistory; } public void setProjectPersons(List<AwardPerson> projectPersons) { this.projectPersons = projectPersons; } protected KcPersonService getKcPersonService() { if (this.kcPersonService == null) { this.kcPersonService = KcServiceLocator.getService(KcPersonService.class); } return this.kcPersonService; } /* * This method is used by the tag file to display the F&A rate totals. * Needed to convert to KualiDecimal to avoid rounding issues. */ public KualiDecimal getFandATotals() { KualiDecimal total = new KualiDecimal(0); for (AwardFandaRate currentRate : getAwardFandaRate()) { if (currentRate.getUnderrecoveryOfIndirectCost() != null) { total = total.add(new KualiDecimal(currentRate.getUnderrecoveryOfIndirectCost().bigDecimalValue())); } } return total; } @Override public boolean isProposalBudget() { return false; } @Override public BudgetParentDocument<Award> getDocument() { return getAwardDocument(); } @Override public Budget getNewBudget() { return new AwardBudgetExt(); } private List<AwardBudgetExt> budgets; public List<AwardBudgetExt> getBudgetVersionOverviews() { return budgets; } public void setBudgetVersionOverviews( List<AwardBudgetExt> budgetVersionOverviews) { this.budgets = budgetVersionOverviews; } @Override public Integer getNextBudgetVersionNumber() { return getAwardDocument().getNextBudgetVersionNumber(); } public List<AwardBudgetExt> getBudgets() { return budgets; } public void setBudgets(List<AwardBudgetExt> budgets) { this.budgets = budgets; } /* * This method will return true when the Active award is editing */ public boolean isEditAward() { return editAward; } public void setEditAward(boolean editAward) { this.editAward = editAward; } }
kcmit-impl/src/main/java/org/kuali/kra/award/home/Award.java
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php * * 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.kuali.kra.award.home; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.kuali.coeus.common.framework.keyword.KeywordsManager; import org.kuali.coeus.common.framework.keyword.ScienceKeyword; import org.kuali.coeus.common.framework.person.KcPerson; import org.kuali.coeus.common.framework.person.KcPersonService; import org.kuali.coeus.common.framework.version.sequence.owner.SequenceOwner; import org.kuali.coeus.common.framework.sponsor.Sponsor; import org.kuali.coeus.common.framework.sponsor.Sponsorable; import org.kuali.coeus.common.framework.type.ActivityType; import org.kuali.coeus.common.framework.type.ProposalType; import org.kuali.coeus.common.framework.unit.Unit; import org.kuali.coeus.common.framework.unit.UnitService; import org.kuali.coeus.common.framework.unit.admin.UnitAdministrator; import org.kuali.coeus.common.framework.version.VersionStatus; import org.kuali.coeus.common.framework.version.history.VersionHistorySearchBo; import org.kuali.coeus.common.permissions.impl.PermissionableKeys; import org.kuali.coeus.common.framework.auth.SystemAuthorizationService; import org.kuali.coeus.common.framework.auth.perm.Permissionable; import org.kuali.coeus.sys.framework.gv.GlobalVariableService; import org.kuali.coeus.sys.framework.model.KcPersistableBusinessObjectBase; import org.kuali.coeus.sys.framework.service.KcServiceLocator; import org.kuali.kra.award.AwardAmountInfoService; import org.kuali.kra.award.AwardTemplateSyncScope; import org.kuali.kra.award.awardhierarchy.AwardHierarchyService; import org.kuali.kra.award.awardhierarchy.AwardHierarchyTempObject; import org.kuali.kra.award.awardhierarchy.sync.AwardSyncChange; import org.kuali.kra.award.awardhierarchy.sync.AwardSyncStatus; import org.kuali.kra.award.awardhierarchy.sync.AwardSyncableProperty; import org.kuali.kra.award.budget.AwardBudgetExt; import org.kuali.kra.award.budget.AwardBudgetLimit; import org.kuali.kra.award.commitments.AwardCostShare; import org.kuali.kra.award.commitments.AwardFandaRate; import org.kuali.kra.award.contacts.AwardPerson; import org.kuali.kra.award.contacts.AwardSponsorContact; import org.kuali.kra.award.contacts.AwardUnitContact; import org.kuali.kra.award.customdata.AwardCustomData; import org.kuali.kra.award.document.AwardDocument; import org.kuali.kra.award.home.approvedsubawards.AwardApprovedSubaward; import org.kuali.kra.award.home.fundingproposal.AwardFundingProposal; import org.kuali.kra.award.home.keywords.AwardScienceKeyword; import org.kuali.kra.award.notesandattachments.attachments.AwardAttachment; import org.kuali.kra.award.notesandattachments.notes.AwardNotepad; import org.kuali.kra.award.paymentreports.awardreports.AwardReportTerm; import org.kuali.kra.award.paymentreports.closeout.AwardCloseout; import org.kuali.kra.award.paymentreports.paymentschedule.AwardPaymentSchedule; import org.kuali.kra.award.paymentreports.specialapproval.approvedequipment.AwardApprovedEquipment; import org.kuali.kra.award.paymentreports.specialapproval.foreigntravel.AwardApprovedForeignTravel; import org.kuali.kra.award.specialreview.AwardSpecialReview; import org.kuali.kra.award.timeandmoney.AwardDirectFandADistribution; import org.kuali.kra.bo.*; import org.kuali.coeus.common.budget.framework.core.Budget; import org.kuali.coeus.common.budget.framework.core.BudgetParent; import org.kuali.coeus.common.budget.framework.core.BudgetParentDocument; import org.kuali.coeus.common.framework.rolodex.PersonRolodex; import org.kuali.kra.coi.Disclosurable; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.infrastructure.KeyConstants; import org.kuali.kra.infrastructure.RoleConstants; import org.kuali.kra.institutionalproposal.home.InstitutionalProposal; import org.kuali.kra.institutionalproposal.service.InstitutionalProposalService; import org.kuali.kra.negotiations.bo.Negotiable; import org.kuali.kra.negotiations.bo.NegotiationPersonDTO; import org.kuali.kra.subaward.bo.SubAward; import org.kuali.kra.timeandmoney.TimeAndMoneyDocumentHistory; import org.kuali.kra.timeandmoney.document.TimeAndMoneyDocument; import org.kuali.kra.timeandmoney.service.TimeAndMoneyHistoryService; import org.kuali.kra.timeandmoney.transactions.AwardTransactionType; import org.kuali.rice.core.api.CoreApiServiceLocator; import org.kuali.rice.core.api.util.type.KualiDecimal; import org.kuali.coeus.sys.api.model.ScaleTwoDecimal; import org.kuali.rice.kew.api.exception.WorkflowException; import org.kuali.rice.kim.api.role.Role; import org.kuali.rice.krad.service.BusinessObjectService; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.util.AutoPopulatingList; import edu.mit.kc.coi.KcCoiLinkService; import edu.mit.kc.coi.KcCoiLinkServiceImpl; import java.sql.Date; import java.sql.SQLException; import java.sql.Timestamp; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * * This class is Award Business Object. * It implements ProcessKeywords to process all operations related to AwardScenceKeywords. */ public class Award extends KcPersistableBusinessObjectBase implements KeywordsManager<AwardScienceKeyword>, Permissionable, SequenceOwner<Award>, BudgetParent, Sponsorable, Negotiable, Disclosurable { public static final String DEFAULT_AWARD_NUMBER = "000000-00000"; public static final String BLANK_COMMENT = ""; public static final String ICR_RATE_CODE_NONE = "ICRNONE"; private static final String NO_FLAG = "N"; private static final int TOTAL_STATIC_REPORTS = 5; public static final String CLOSE_OUT_REPORT_TYPE_FINANCIAL_REPORT = "1"; public static final String CLOSE_OUT_REPORT_TYPE_TECHNICAL = "4"; public static final String CLOSE_OUT_REPORT_TYPE_PATENT = "3"; public static final String CLOSE_OUT_REPORT_TYPE_PROPERTY = "2"; public static final String CLOSE_OUT_REPORT_TYPE_INVOICE = "6"; private static final String DEFAULT_GROUP_CODE_FOR_CENTRAL_ADMIN_CONTACTS = "C"; public static final String NOTIFICATION_IRB_SPECIAL_REVIEW_LINK_ADDED = "552"; public static final String NOTIFICATION_IRB_SPECIAL_REVIEW_LINK_DELETED = "553"; public static final String NOTIFICATION_IACUC_SPECIAL_REVIEW_LINK_ADDED = "554"; public static final String NOTIFICATION_IACUC_SPECIAL_REVIEW_LINK_DELETED = "555"; private static final long serialVersionUID = 3797220122448310165L; private Long awardId; private AwardDocument awardDocument; private String awardNumber; private Integer sequenceNumber; @AwardSyncableProperty private String sponsorCode; @AwardSyncableProperty private Integer statusCode; private AwardStatus awardStatus; private String accountNumber; private String approvedEquipmentIndicator; private String approvedForeignTripIndicator; private String subContractIndicator; private Date awardEffectiveDate; private Date awardExecutionDate; private Date beginDate; private String costSharingIndicator; private String indirectCostIndicator; private String modificationNumber; private String nsfCode; private String paymentScheduleIndicator; private String scienceCodeIndicator; private String specialReviewIndicator; private String sponsorAwardNumber; private String transferSponsorIndicator; private Integer accountTypeCode; private String activityTypeCode; private Integer awardTypeCode; private AwardType awardType; private String cfdaNumber; private String documentFundingId; private ScaleTwoDecimal preAwardAuthorizedAmount; private Date preAwardEffectiveDate; private ScaleTwoDecimal preAwardInstitutionalAuthorizedAmount; private Date preAwardInstitutionalEffectiveDate; private String procurementPriorityCode; private String proposalNumber; private ScaleTwoDecimal specialEbRateOffCampus; private ScaleTwoDecimal specialEbRateOnCampus; private String subPlanFlag; private String title; private String archiveLocation; private Date closeoutDate; private Integer awardTransactionTypeCode; private Date noticeDate; private String currentActionComments; private String financialAccountDocumentNumber; private Date financialAccountCreationDate; private String financialChartOfAccountsCode; private String awardSequenceStatus; // private String sequenceOwnerVersionNameValue; // private Integer sequenceOwnerSequenceNumber; private boolean newVersion; private Integer templateCode; @AwardSyncable(scopes = { AwardTemplateSyncScope.AWARD_PAGE }) private String primeSponsorCode; @AwardSyncable(impactSourceScopeEmpty = false, scopes = { AwardTemplateSyncScope.PAYMENTS_AND_INVOICES_TAB }) private String basisOfPaymentCode; @AwardSyncable(impactSourceScopeEmpty = false, scopes = { AwardTemplateSyncScope.PAYMENTS_AND_INVOICES_TAB }) private String methodOfPaymentCode; private AwardTemplate awardTemplate; private AwardBasisOfPayment awardBasisOfPayment; private AwardMethodOfPayment awardMethodOfPayment; private AwardTransactionType awardTransactionType; private ActivityType activityType; private Sponsor sponsor; private Sponsor primeSponsor; @AwardSyncableList(syncClass = AwardComment.class, syncSourceClass = AwardTemplateComment.class, scopes={AwardTemplateSyncScope.COST_SHARE,AwardTemplateSyncScope.PAYMENTS_AND_INVOICES_TAB,AwardTemplateSyncScope.COMMENTS_TAB}, removeMissingListElementsFromTarget=false) private List<AwardComment> awardComments; @AwardSyncableList(syncClass = AwardReportTerm.class, syncSourceClass = AwardTemplateReportTerm.class, scopes = {AwardTemplateSyncScope.PAYMENTS_AND_INVOICES_TAB,AwardTemplateSyncScope.REPORTS_TAB}) private List<AwardReportTerm> awardReportTermItems; @AwardSyncableList(syncClass = AwardSponsorTerm.class, syncSourceClass = AwardTemplateTerm.class, scopes = { AwardTemplateSyncScope.TERMS_TAB }) private List<AwardSponsorTerm> awardSponsorTerms; @AwardSyncableList(syncClass = AwardSponsorContact.class, syncSourceClass = AwardTemplateContact.class, scopes = { AwardTemplateSyncScope.SPONSOR_CONTACTS_TAB }) private List<AwardSponsorContact> sponsorContacts; private List<AwardCustomData> awardCustomDataList; private List<Boolean> awardCommentHistoryFlags; private Map<String, AwardComment> commentMap; private List<AwardCostShare> awardCostShares; private List<AwardFandaRate> awardFandaRate; private List<AwardDirectFandADistribution> awardDirectFandADistributions; private List<AwardApprovedSubaward> awardApprovedSubawards; private List<AwardScienceKeyword> keywords; private List<AwardPerson> projectPersons; private List<AwardUnitContact> awardUnitContacts; private List<AwardSpecialReview> specialReviews; private List<AwardApprovedEquipment> approvedEquipmentItems; private List<AwardApprovedForeignTravel> approvedForeignTravelTrips; private List<AwardPaymentSchedule> paymentScheduleItems; private List<AwardTransferringSponsor> awardTransferringSponsors; private List<AwardAmountInfo> awardAmountInfos; private List<AwardCloseout> awardCloseoutItems; private List<AwardCloseout> awardCloseoutNewItems; private List<AwardNotepad> awardNotepads; private List<AwardAttachment> awardAttachments; private List<AwardSyncChange> syncChanges; private List<AwardSyncStatus> syncStatuses; private boolean syncChild; private List<AwardFundingProposal> fundingProposals; private List<AwardBudgetLimit> awardBudgetLimits; // Additional fields for lookup private Unit leadUnit; private String unitNumber; private KcPerson ospAdministrator; private String ospAdministratorName; private String principalInvestigatorName; private String statusDescription; private String sponsorName; // For award-account integration private String icrRateCode; private transient boolean awardInMultipleNodeHierarchy; private transient boolean awardHasAssociatedTandMOrIsVersioned; private transient boolean sponsorNihMultiplePi; private transient List<AwardHierarchyTempObject> awardHierarchyTempObjects; // transient for award header label private transient String docIdStatus; private transient String awardIdAccount; private transient String lookupOspAdministratorName; transient AwardAmountInfoService awardAmountInfoService; transient TimeAndMoneyHistoryService timeAndMoneyHistoryService; private transient AwardHierarchyService awardHierarchyService; private transient List<AwardUnitContact> centralAdminContacts; private List<SubAward> subAwardList; private transient boolean allowUpdateTimestampToBeReset = true; private VersionHistorySearchBo versionHistory; private transient KcPersonService kcPersonService; private transient boolean editAward = false; protected final Log LOG = LogFactory.getLog(Award.class); Logger LOGGER; @Qualifier("globalVariableService") private GlobalVariableService globalVariableService; public GlobalVariableService getGlobalVariableService() { if (globalVariableService == null) { globalVariableService = KcServiceLocator.getService(GlobalVariableService.class); } return globalVariableService; } public void setGlobalVariableService(GlobalVariableService globalVariableService) { this.globalVariableService = globalVariableService; } public KcCoiLinkService kcCoiLinkService; public KcCoiLinkService getKcCoiLinkService() { if (kcCoiLinkService == null) { kcCoiLinkService = KcServiceLocator.getService(KcCoiLinkService.class); } return kcCoiLinkService; } public void setKcCoiLinkService(KcCoiLinkService kcCoiLinkService) { this.kcCoiLinkService = kcCoiLinkService; } /** * * Constructs an Award BO. */ public Award() { super(); initializeAwardWithDefaultValues(); initializeCollections(); } /** * * This method sets the default values for initial persistence as part of skeleton. * As various panels are developed; corresponding field initializations should be removed from * this method. */ private void initializeAwardWithDefaultValues() { setAwardNumber(DEFAULT_AWARD_NUMBER); setSequenceNumber(1); setApprovedEquipmentIndicator(NO_FLAG); setApprovedForeignTripIndicator(NO_FLAG); setSubContractIndicator(NO_FLAG); setCostSharingIndicator(NO_FLAG); setIdcIndicator(NO_FLAG); setPaymentScheduleIndicator(NO_FLAG); setScienceCodeIndicator(NO_FLAG); setSpecialReviewIndicator(NO_FLAG); setTransferSponsorIndicator(NO_FLAG); awardComments = new AutoPopulatingList<AwardComment>(AwardComment.class); setCurrentActionComments(""); setNewVersion(false); awardSequenceStatus = VersionStatus.PENDING.name(); } private Map<String, AwardComment> getCommentMap() { if (commentMap == null || getNewVersion()) { commentMap = new HashMap<String, AwardComment>(); for (AwardComment ac : awardComments) { if (getNewVersion() && ac.getCommentType().getCommentTypeCode().equals(Constants.CURRENT_ACTION_COMMENT_TYPE_CODE)) { ac.setComments(BLANK_COMMENT); } commentMap.put(ac.getCommentType().getCommentTypeCode(), ac); } } return commentMap; } /** * Gets the templateCode attribute. * @return Returns the templateCode. */ public Integer getTemplateCode() { return templateCode; } public String getFinancialChartOfAccountsCode() { return financialChartOfAccountsCode; } public void setFinancialChartOfAccountsCode(String financialChartOfAccountsCode) { this.financialChartOfAccountsCode = financialChartOfAccountsCode; } public Long getAwardId() { return awardId; } /** * * @param awardId */ public void setAwardId(Long awardId) { this.awardId = awardId; } public String getAwardNumber() { return awardNumber; } /** * * @param awardNumber */ public void setAwardNumber(String awardNumber) { this.awardNumber = awardNumber; } @Override public Integer getSequenceNumber() { return sequenceNumber; } /** * * @param sequenceNumber */ public void setSequenceNumber(Integer sequenceNumber) { this.sequenceNumber = sequenceNumber; } public int getIndexOfLastAwardAmountInfo() { return awardAmountInfos.size() - 1; } public AwardAmountInfo getLastAwardAmountInfo() { return awardAmountInfos.get(getIndexOfLastAwardAmountInfo()); } public int getIndexOfAwardAmountInfoForDisplay() throws WorkflowException { AwardAmountInfo aai = getAwardAmountInfoService().fetchLastAwardAmountInfoForAwardVersionAndFinalizedTandMDocumentNumber(this); int returnVal = 0; int index = 0; if (aai.getAwardAmountInfoId() != null && this.isAwardInMultipleNodeHierarchy()) { this.refreshReferenceObject("awardAmountInfos"); } if (isAwardInitialCopy()) { // if it's copied, on initialization we want to return index of last AwardAmountInfo in collection. returnVal = getAwardAmountInfos().size() - 1; }else { for (AwardAmountInfo awardAmountInfo : getAwardAmountInfos()) { if (awardAmountInfo.getAwardAmountInfoId() == null && aai.getAwardAmountInfoId() == null) { returnVal = index; }else if(awardAmountInfo.getAwardAmountInfoId().equals(aai.getAwardAmountInfoId())) { returnVal = index; }else { index++; } } } return returnVal; } public int getIndexOfAwardAmountInfoForDisplayFromTimeAndMoneyDocNumber(String docNum) throws WorkflowException { AwardAmountInfo aai = getAwardAmountInfoService().fetchLastAwardAmountInfoForDocNum(this, docNum); int returnVal = 0; int index = 0; if (aai.getAwardAmountInfoId() != null && this.isAwardInMultipleNodeHierarchy()) { this.refreshReferenceObject("awardAmountInfos"); } if (isAwardInitialCopy()) { // if it's copied, on initialization we want to return index of last AwardAmountInfo in collection. returnVal = getAwardAmountInfos().size() - 1; }else { for (AwardAmountInfo awardAmountInfo : getAwardAmountInfos()) { if (awardAmountInfo.getAwardAmountInfoId() == null && aai.getAwardAmountInfoId() == null) { returnVal = index; }else if(awardAmountInfo.getAwardAmountInfoId().equals(aai.getAwardAmountInfoId())) { returnVal = index; }else { index++; } } } return returnVal; } /** * If the Award is copied then initially the AwardAmountInfos will have two entries without AwardAmountInfoId's. We need to recognize this * so we can display the correct data on initialization. * @return */ public boolean isAwardInitialCopy() { boolean returnValue = true; if (this.getAwardAmountInfos().size() > 1) { for (AwardAmountInfo aai : getAwardAmountInfos()) { if (aai.getAwardAmountInfoId() != null) { returnValue = false; break; } } } return returnValue; } /** * Gets the awardAmountInfoService attribute. * @return Returns the awardAmountInfoService. */ public AwardAmountInfoService getAwardAmountInfoService() { awardAmountInfoService = KcServiceLocator.getService(AwardAmountInfoService.class); return awardAmountInfoService; } public AwardHierarchyService getAwardHierarchyService() { if (awardHierarchyService == null) { awardHierarchyService = KcServiceLocator.getService(AwardHierarchyService.class); } return awardHierarchyService; } public TimeAndMoneyHistoryService getTimeAndMoneyHistoryService() { if (timeAndMoneyHistoryService == null) { timeAndMoneyHistoryService = KcServiceLocator.getService(TimeAndMoneyHistoryService.class); } return timeAndMoneyHistoryService; } /** * Sets the awardAmountInfoService attribute value. * @param awardAmountInfoService The awardAmountInfoService to set. */ public void setAwardAmountInfoService(AwardAmountInfoService awardAmountInfoService) { this.awardAmountInfoService = awardAmountInfoService; } public String getSponsorCode() { return sponsorCode; } /** * * @param sponsorCode */ public void setSponsorCode(String sponsorCode) { this.sponsorCode = sponsorCode; } public String getAccountTypeDescription() { AccountType accountType = (AccountType) getBusinessObjectService().findByPrimaryKey (AccountType.class, Collections.singletonMap("accountTypeCode", getAccountTypeCode())); if (accountType == null) { return "None Selected"; }else { return accountType.getDescription(); } } public Integer getStatusCode() { return statusCode; } /** * * @param statusCode */ public void setStatusCode(Integer statusCode) { this.statusCode = statusCode; } public String getAccountNumber() { return accountNumber; } /** * * @param accountNumber */ public void setAccountNumber(String accountNumber) { this.accountNumber = accountNumber; } public List<AwardApprovedEquipment> getApprovedEquipmentItems() { return approvedEquipmentItems; } public List<AwardUnitContact> getAwardUnitContacts() { return awardUnitContacts; } /** * @param index * @return */ public AwardPerson getProjectPerson(int index) { return projectPersons.get(index); } /** * Retrieve the AwardPerson for the given personId, if it exists. * * @param personId String * @return AwardPerson */ public AwardPerson getProjectPerson(String personId) { if (!StringUtils.isBlank(personId)) { for (AwardPerson awardPerson : this.getProjectPersons()) { if (personId.equals(awardPerson.getPersonId())) { return awardPerson; } } } return null; } /** * Retrieve the AwardPerson for the given rolodexId, if it exists. * * @param rolodexId Integer * @return AwardPerson */ public AwardPerson getProjectPerson(Integer rolodexId) { if (rolodexId != null) { for (AwardPerson awardPerson : this.getProjectPersons()) { if (rolodexId.equals(awardPerson.getRolodexId())) { return awardPerson; } } } return null; } public List<AwardPerson> getProjectPersons() { return projectPersons; } public List<AwardPerson> getProjectPersonsSorted() { List<AwardPerson> aList = new ArrayList<AwardPerson>(); if (this.getPrincipalInvestigator() != null) { aList.add(this.getPrincipalInvestigator()); } aList.addAll(this.getMultiplePis()); aList.addAll(this.getCoInvestigators()); aList.addAll(this.getKeyPersons()); return aList; } /** * This method returns all PIs and co-PIs. * @return */ public List<AwardPerson> getInvestigators() { List<AwardPerson> investigators = new ArrayList<AwardPerson>(); for (AwardPerson person : projectPersons) { if (person.isPrincipalInvestigator() || person.isCoInvestigator()) { investigators.add(person); } } Collections.sort(investigators); return investigators; } /** * This method returns all co-PIs. * @return */ public List<AwardPerson> getCoInvestigators() { List<AwardPerson> coInvestigators = new ArrayList<AwardPerson>(); for (AwardPerson person : projectPersons) { if (person.isCoInvestigator()) { coInvestigators.add(person); } } Collections.sort(coInvestigators); return coInvestigators; } /** * When the sponsor is in the NIH multiple PI hierarchy this will return any multiple pis, otherwise, empty list. * @return */ public List<AwardPerson> getMultiplePis() { List<AwardPerson> multiplePis = new ArrayList<AwardPerson>(); if (isSponsorNihMultiplePi()) { for (AwardPerson person : projectPersons) { if (person.isMultiplePi()) { multiplePis.add(person); } } Collections.sort(multiplePis); } return multiplePis; } /** * This method returns all key persons * @return */ public List<AwardPerson> getKeyPersons() { List<AwardPerson> keyPersons = new ArrayList<AwardPerson>(); for (AwardPerson person : projectPersons) { if (person.isKeyPerson()) { keyPersons.add(person); } } Collections.sort(keyPersons); return keyPersons; } /** * This method returns the combined number of units for all project personnel. * @return */ public int getTotalUnitCount() { int count = 0; for (AwardPerson person : projectPersons) count += person.getUnits().size(); return count; } public int getAwardContactsCount() { return awardUnitContacts.size(); } public int getApprovedEquipmentItemCount() { return approvedEquipmentItems.size(); } public int getApprovedForeignTravelTripCount() { return approvedForeignTravelTrips.size(); } public List<AwardApprovedForeignTravel> getApprovedForeignTravelTrips() { return approvedForeignTravelTrips; } /** * @param awardUnitContacts */ public void setAwardUnitContacts(List<AwardUnitContact> awardUnitContacts) { this.awardUnitContacts = awardUnitContacts; } /** * */ public void setApprovedEquipmentItems(List<AwardApprovedEquipment> awardApprovedEquipmentItems) { this.approvedEquipmentItems = awardApprovedEquipmentItems; } /** * */ public void setApprovedForeignTravelTrips(List<AwardApprovedForeignTravel> approvedForeignTravelTrips) { this.approvedForeignTravelTrips = approvedForeignTravelTrips; } public String getApprovedEquipmentIndicator() { return approvedEquipmentIndicator; } /** * * @param approvedEquipmentIndicator */ public void setApprovedEquipmentIndicator(String approvedEquipmentIndicator) { this.approvedEquipmentIndicator = approvedEquipmentIndicator; } public String getApprovedForeignTripIndicator() { return approvedForeignTripIndicator; } /** * * @param approvedForeignTripIndicator */ public void setApprovedForeignTripIndicator(String approvedForeignTripIndicator) { this.approvedForeignTripIndicator = approvedForeignTripIndicator; } public String getSubContractIndicator() { return subContractIndicator; } /** * * @param subContractIndicator */ public void setSubContractIndicator(String subContractIndicator) { this.subContractIndicator = subContractIndicator; } public Date getAwardEffectiveDate() { return awardEffectiveDate; } /** * * @param awardEffectiveDate */ public void setAwardEffectiveDate(Date awardEffectiveDate) { this.awardEffectiveDate = awardEffectiveDate; } public Date getAwardExecutionDate() { return awardExecutionDate; } /** * * @param awardExecutionDate */ public void setAwardExecutionDate(Date awardExecutionDate) { this.awardExecutionDate = awardExecutionDate; } public Date getBeginDate() { return beginDate; } /** * This method returns the project end date which is housed in the Amount Info list index[0] on the award. * @return */ public Date getProjectEndDate() { return awardAmountInfos.get(0).getFinalExpirationDate(); } /** * This method sets the project end date which is housed in the Amount Info list index[0] on the award. * @return */ public void setProjectEndDate(Date date) { this.awardAmountInfos.get(0).setFinalExpirationDate(date); } public Date getObligationExpirationDate() { // return awardAmountInfos.get(0).getObligationExpirationDate(); return getLastAwardAmountInfo().getObligationExpirationDate(); } public void setObligationExpirationDate(Date date) { this.awardAmountInfos.get(0).setObligationExpirationDate(date); } /** * * @param beginDate */ public void setBeginDate(Date beginDate) { this.beginDate = beginDate; } public String getCostSharingIndicator() { return costSharingIndicator; } /** * * @param costSharingIndicator */ public void setCostSharingIndicator(String costSharingIndicator) { this.costSharingIndicator = costSharingIndicator; } public List<AwardFundingProposal> getFundingProposals() { return fundingProposals; } /** * * For ease of use in JSP and tag files; the getter method uses acronym instead of full meaning. * idcIndicator is an acronym. Its full meaning is Indirect Cost Indicator * @return */ public String getIdcIndicator() { return indirectCostIndicator; } /** * * For ease of use in JSP and tag files; the setter method uses acronym instead of full meaning. * idcIndicator is an acronym. Its full meaning is Indirect Cost Indicator * @param indirectCostIndicator */ public void setIdcIndicator(String indirectCostIndicator) { this.indirectCostIndicator = indirectCostIndicator; } public String getModificationNumber() { return modificationNumber; } /** * * @param modificationNumber */ public void setModificationNumber(String modificationNumber) { this.modificationNumber = modificationNumber; } /** * NSFCode is an acronym. Its full meaning is National Science Foundation. * @return */ public String getNsfCode() { return nsfCode; } /** * NSFCode is an acronym. Its full meaning is National Science Foundation. * @param nsfCode */ public void setNsfCode(String nsfCode) { this.nsfCode = nsfCode; } public String getPaymentScheduleIndicator() { return paymentScheduleIndicator; } /** * * @param paymentScheduleIndicator */ public void setPaymentScheduleIndicator(String paymentScheduleIndicator) { this.paymentScheduleIndicator = paymentScheduleIndicator; } public String getScienceCodeIndicator() { return scienceCodeIndicator; } /** * * @param scienceCodeIndicator */ public void setScienceCodeIndicator(String scienceCodeIndicator) { this.scienceCodeIndicator = scienceCodeIndicator; } public String getSpecialReviewIndicator() { return specialReviewIndicator; } /** * * @param specialReviewIndicator */ public void setSpecialReviewIndicator(String specialReviewIndicator) { this.specialReviewIndicator = specialReviewIndicator; } /**\ * * @return */ public String getSponsorAwardNumber() { return sponsorAwardNumber; } /** * * @param sponsorAwardNumber */ public void setSponsorAwardNumber(String sponsorAwardNumber) { this.sponsorAwardNumber = sponsorAwardNumber; } public String getTransferSponsorIndicator() { return transferSponsorIndicator; } /** * This method finds the lead unit name, if any * @return */ public String getUnitName() { Unit leadUnit = getLeadUnit(); return leadUnit != null ? leadUnit.getUnitName() : null; } /** * This method finds the lead unit number, if any * @return */ public String getUnitNumber() { return unitNumber; } public String getLeadUnitNumber() { return getUnitNumber(); } /** * * @param transferSponsorIndicator */ public void setTransferSponsorIndicator(String transferSponsorIndicator) { this.transferSponsorIndicator = transferSponsorIndicator; } public Integer getAccountTypeCode() { return accountTypeCode; } /** * * @param accountTypeCode */ public void setAccountTypeCode(Integer accountTypeCode) { this.accountTypeCode = accountTypeCode; } public String getActivityTypeCode() { return activityTypeCode; } /** * * @param activityTypeCode */ public void setActivityTypeCode(String activityTypeCode) { this.activityTypeCode = activityTypeCode; } public Integer getAwardTypeCode() { return awardTypeCode; } /** * * @param awardTypeCode */ public void setAwardTypeCode(Integer awardTypeCode) { this.awardTypeCode = awardTypeCode; } /** * * cfdaNumber is an acronym. Its full meaning is Catalog of Federal Domestic Assistance * @return */ public String getCfdaNumber() { return cfdaNumber; } /** * * cfdaNumber is an acronym. Its full meaning is Catalog of Federal Domestic Assistance * @param cfdaNumber */ public void setCfdaNumber(String cfdaNumber) { this.cfdaNumber = cfdaNumber; } public String getDocumentFundingId() { return documentFundingId; } public void setDocumentFundingId(String documentFundingId) { this.documentFundingId = documentFundingId; } public KcPerson getOspAdministrator() { for (AwardUnitContact contact : getCentralAdminContacts()) { if (contact.isOspAdministrator()) { ospAdministrator = contact.getPerson(); break; } } return ospAdministrator; } public String getOspAdministratorName() { KcPerson ospAdministrator = getOspAdministrator(); ospAdministratorName = ospAdministrator != null ? ospAdministrator.getFullName() : null; return ospAdministratorName; } public ScaleTwoDecimal getPreAwardAuthorizedAmount() { return preAwardAuthorizedAmount; } /** * For negative values, this method makes the number positive by dropping the negative sign. * @param preAwardAuthorizedAmount */ public void setPreAwardAuthorizedAmount(ScaleTwoDecimal preAwardAuthorizedAmount) { // if preAwardAuthorizedAmount is negative, make it positive if (preAwardAuthorizedAmount != null && preAwardAuthorizedAmount.isNegative()) { this.preAwardAuthorizedAmount = ScaleTwoDecimal.ZERO.subtract(preAwardAuthorizedAmount); } else { this.preAwardAuthorizedAmount = preAwardAuthorizedAmount; } } public Date getPreAwardEffectiveDate() { return preAwardEffectiveDate; } /** * * @param preAwardEffectiveDate */ public void setPreAwardEffectiveDate(Date preAwardEffectiveDate) { this.preAwardEffectiveDate = preAwardEffectiveDate; } public String getProcurementPriorityCode() { return procurementPriorityCode; } /** * * @param procurementPriorityCode */ public void setProcurementPriorityCode(String procurementPriorityCode) { this.procurementPriorityCode = procurementPriorityCode; } public String getProposalNumber() { return proposalNumber; } /** * * @param proposalNumber */ public void setProposalNumber(String proposalNumber) { this.proposalNumber = proposalNumber; } public ScaleTwoDecimal getSpecialEbRateOffCampus() { return specialEbRateOffCampus; } /** * * @param specialEbRateOffCampus */ public void setSpecialEbRateOffCampus(ScaleTwoDecimal specialEbRateOffCampus) { this.specialEbRateOffCampus = specialEbRateOffCampus; } public ScaleTwoDecimal getSpecialEbRateOnCampus() { return specialEbRateOnCampus; } /** * * @param specialEbRateOnCampus */ public void setSpecialEbRateOnCampus(ScaleTwoDecimal specialEbRateOnCampus) { this.specialEbRateOnCampus = specialEbRateOnCampus; } public String getSubPlanFlag() { return subPlanFlag; } /** * * @param subPlanFlag */ public void setSubPlanFlag(String subPlanFlag) { this.subPlanFlag = subPlanFlag; } public String getTitle() { return title; } /** * * @param title */ public void setTitle(String title) { this.title = title; } public String getArchiveLocation() { return archiveLocation; } public void setArchiveLocation(String archiveLocation) { this.archiveLocation = archiveLocation; } public Date getCloseoutDate() { return closeoutDate; } public void setCloseoutDate(Date closeoutDate) { this.closeoutDate = closeoutDate; } /** * Gets the awardTransactionTypeCode attribute. * @return Returns the awardTransactionTypeCode. */ public Integer getAwardTransactionTypeCode() { return awardTransactionTypeCode; } /** * Sets the awardTransactionTypeCode attribute value. * @param awardTransactionTypeCode The awardTransactionTypeCode to set. */ public void setAwardTransactionTypeCode(Integer awardTransactionTypeCode) { this.awardTransactionTypeCode = awardTransactionTypeCode; } /** * Gets the noticeDate attribute. * @return Returns the noticeDate. */ public Date getNoticeDate() { return noticeDate; } /** * Sets the noticeDate attribute value. * @param noticeDate The noticeDate to set. */ public void setNoticeDate(Date noticeDate) { if (getNewVersion()) { this.noticeDate = null; } else { this.noticeDate = noticeDate; } } /** * Gets the currentActionComments attribute. * @return Returns the currentActionComments. */ public String getCurrentActionComments() { return currentActionComments; } /** * Sets the currentActionComments attribute value. * @param currentActionComments The currentActionComments to set. */ public void setCurrentActionComments(String currentActionComments) { if (getNewVersion()) { this.currentActionComments = BLANK_COMMENT; } else { this.currentActionComments = currentActionComments; } } /** * sets newVersion to specified value * @param newVersion the newVersion to be set */ public void setNewVersion (boolean newVersion) { this.newVersion = newVersion; if (this.newVersion) { commentMap = getCommentMap(); setCurrentActionComments(BLANK_COMMENT); setNoticeDate(null); } } /** * Gets the newVersion attribute * @return Returns the newVersion attribute */ public boolean getNewVersion () { return this.newVersion; } /** * Gets the awardTransactionType attribute. * @return Returns the awardTransactionType. */ public AwardTransactionType getAwardTransactionType() { return awardTransactionType; } /** * Sets the awardTransactionType attribute value. * @param awardTransactionType The awardTransactionType to set. */ public void setAwardTransactionType(AwardTransactionType awardTransactionType) { this.awardTransactionType = awardTransactionType; } public String getFinancialAccountDocumentNumber() { return financialAccountDocumentNumber; } public void setFinancialAccountDocumentNumber(String financialAccountDocumentNumber) { this.financialAccountDocumentNumber = financialAccountDocumentNumber; } public Date getFinancialAccountCreationDate() { return financialAccountCreationDate; } public void setFinancialAccountCreationDate(Date financialAccountCreationDate) { this.financialAccountCreationDate = financialAccountCreationDate; } public AwardDocument getAwardDocument() { if (awardDocument == null) { this.refreshReferenceObject("awardDocument"); } return awardDocument; } public String getAwardDocumentUrl() { return getAwardDocument().buildForwardUrl(); } public void setAwardDocument(AwardDocument awardDocument) { this.awardDocument = awardDocument; } public List<AwardComment> getAwardComments() { return awardComments; } public void setAwardComments(List<AwardComment> awardComments) { this.awardComments = awardComments; } public List<AwardCostShare> getAwardCostShares() { return awardCostShares; } public void setAwardCostShares(List<AwardCostShare> awardCostShares) { this.awardCostShares = awardCostShares; } public List<AwardApprovedSubaward> getAwardApprovedSubawards() { return awardApprovedSubawards; } public void setAwardApprovedSubawards(List<AwardApprovedSubaward> awardApprovedSubawards) { this.awardApprovedSubawards = awardApprovedSubawards; } /** * * Get the award Cost Share Comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardCostShareComment() { return getAwardCommentByType(Constants.COST_SHARE_COMMENT_TYPE_CODE, Constants.AWARD_COMMENT_INCLUDE_IN_CHECKLIST, true); } /** * * Get the award PreAward Sponsor Authorizations comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getawardPreAwardSponsorAuthorizationComment() { return getAwardCommentByType( Constants.PREAWARD_SPONSOR_AUTHORIZATION_COMMENT_TYPE_CODE,Constants.AWARD_COMMENT_EXCLUDE_FROM_CHECKLIST, true ); } /** * * Get the award PreAward Institutional Authorizations comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getawardPreAwardInstitutionalAuthorizationComment() { return getAwardCommentByType( Constants.PREAWARD_INSTITUTIONAL_AUTHORIZATION_COMMENT_TYPE_CODE,Constants.AWARD_COMMENT_EXCLUDE_FROM_CHECKLIST, true ); } /** * * Get the award F & A Rates Comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardFandaRateComment() { return getAwardCommentByType(Constants.FANDA_RATE_COMMENT_TYPE_CODE, Constants.AWARD_COMMENT_INCLUDE_IN_CHECKLIST, true); } /** * * Get the award AwardPaymentAndInvoiceRequirementsComments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardPaymentAndInvoiceRequirementsComments() { return getAwardCommentByType( Constants.PAYMENT_AND_INVOICES_COMMENT_TYPE_CODE,Constants.AWARD_COMMENT_INCLUDE_IN_CHECKLIST, true ); } /** * * Get the award Benefits Rate comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardBenefitsRateComment() { return getAwardCommentByType(Constants.BENEFITS_RATES_COMMENT_TYPE_CODE, Constants.AWARD_COMMENT_INCLUDE_IN_CHECKLIST, true); } /** * * Get the award General Comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardGeneralComments() { return getAwardCommentByType(Constants.GENERAL_COMMENT_TYPE_CODE, Constants.AWARD_COMMENT_INCLUDE_IN_CHECKLIST, true); } /** * * Get the award fiscal report comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardFiscalReportComments() { return getAwardCommentByType(Constants.FISCAL_REPORT_COMMENT_TYPE_CODE, Constants.AWARD_COMMENT_INCLUDE_IN_CHECKLIST, true); } /** * * Get the award current action comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardCurrentActionComments() { return getAwardCommentByType( Constants.CURRENT_ACTION_COMMENT_TYPE_CODE,Constants.AWARD_COMMENT_EXCLUDE_FROM_CHECKLIST, true ); } /** * * Get the award Intellectual Property comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardIntellectualPropertyComments() { return getAwardCommentByType( Constants.INTELLECTUAL_PROPERTY_COMMENT_TYPE_CODE,Constants.AWARD_COMMENT_EXCLUDE_FROM_CHECKLIST, true ); } /** * * Get the award Procurement Comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardProcurementComments() { return getAwardCommentByType(Constants.PROCUREMENT_COMMENT_TYPE_CODE, Constants.AWARD_COMMENT_INCLUDE_IN_CHECKLIST, true); } /** * * Get the award Award Property Comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardPropertyComments() { return getAwardCommentByType(Constants.PROPERTY_COMMENT_TYPE_CODE, Constants.AWARD_COMMENT_INCLUDE_IN_CHECKLIST, true); } /** * * Get the award Special Rate comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardSpecialRate() { return getAwardCommentByType(Constants.SPECIAL_RATE_COMMENT_TYPE_CODE, Constants.AWARD_COMMENT_EXCLUDE_FROM_CHECKLIST, true); } /** * * Get the award Special Review Comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardSpecialReviewComments() { return getAwardCommentByType( Constants.SPECIAL_REVIEW_COMMENT_TYPE_CODE,Constants.AWARD_COMMENT_EXCLUDE_FROM_CHECKLIST, true ); } /** * * Get the award Proposal Summary comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getawardProposalSummary() { return getAwardCommentByType( Constants.PROPOSAL_SUMMARY_COMMENT_TYPE_CODE,Constants.AWARD_COMMENT_EXCLUDE_FROM_CHECKLIST, true ); } /** * * Get the award Proposal comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getawardProposalComments() { return getAwardCommentByType(Constants.PROPOSAL_COMMENT_TYPE_CODE, Constants.AWARD_COMMENT_EXCLUDE_FROM_CHECKLIST, true); } /** * * Get the award Proposal IP Review Comments. If the comment has not been set...... initialize and return new Comment. */ public AwardComment getAwardProposalIPReviewComment() { return getAwardCommentByType( Constants.PROPOSAL_IP_REVIEW_COMMENT_TYPE_CODE,Constants.AWARD_COMMENT_EXCLUDE_FROM_CHECKLIST, true ); } /* * Get a comment by type. If it does not exist, then create it. */ public AwardComment getAwardCommentByType(String awardTypeCode, Boolean checklistPrintFlag, boolean createNew) { AwardCommentFactory awardCommentFactory = new AwardCommentFactory(); AwardComment awardComment = getCommentMap().get(awardTypeCode); if ((awardComment == null && createNew)) { awardComment = awardCommentFactory.createAwardComment(awardTypeCode, (checklistPrintFlag == null ? false : checklistPrintFlag.booleanValue())); add(awardComment); commentMap.put(awardComment.getCommentType().getCommentTypeCode(), awardComment); } return awardComment; } /* * Get a sponsor term by sponsor term id. */ public AwardSponsorTerm getAwardSponsorTermByTemplateTerm(AwardTemplateTerm templateTerm, boolean createNew) { AwardSponsorTerm result = null; for (AwardSponsorTerm term : this.getAwardSponsorTerms()) { if (term.getSponsorTermId().equals(templateTerm.getSponsorTermId())) { result = term; break; } } if (result == null && createNew) { result = new AwardSponsorTerm(); result.setSponsorTermId(templateTerm.getSponsorTermId()); result.setSponsorTerm(templateTerm.getSponsorTerm()); } return result; } /** * This method calls getTotalAmount to calculate the total of all Commitment Amounts. * @return */ public ScaleTwoDecimal getTotalCostShareCommitmentAmount() { return getTotalAmount(awardCostShares); } /** * This method calculates the total Cost Share Met amount for all Award Cost Shares. * @param valuableItems * @return The total value */ public ScaleTwoDecimal getTotalCostShareMetAmount() { ScaleTwoDecimal returnVal = new ScaleTwoDecimal(0.00); for (AwardCostShare awardCostShare : awardCostShares) { ScaleTwoDecimal amount = awardCostShare.getCostShareMet() != null ? awardCostShare.getCostShareMet() : new ScaleTwoDecimal(0.00); returnVal = returnVal.add(amount); } return returnVal; } /** * This method calculates the total Direct Cost Amount for all Direct F and A Distributions. * @return The total value */ public ScaleTwoDecimal getTotalDirectFandADistributionDirectCostAmount() { ScaleTwoDecimal returnVal = new ScaleTwoDecimal(0.00); for (AwardDirectFandADistribution awardDirectFandADistribution : awardDirectFandADistributions) { ScaleTwoDecimal amount; if (awardDirectFandADistribution.getDirectCost() != null) { amount = awardDirectFandADistribution.getDirectCost(); }else { amount = new ScaleTwoDecimal(0.00); } returnVal = returnVal.add(amount); } return returnVal; } /** * This method calculates the total Direct Cost Amount for all Direct F and A Distributions. * @return The total value */ public ScaleTwoDecimal getTotalDirectFandADistributionIndirectCostAmount() { ScaleTwoDecimal returnVal = new ScaleTwoDecimal(0.00); for (AwardDirectFandADistribution awardDirectFandADistribution : awardDirectFandADistributions) { ScaleTwoDecimal amount; if (awardDirectFandADistribution.getIndirectCost() != null) { amount = awardDirectFandADistribution.getIndirectCost(); }else { amount = new ScaleTwoDecimal(0.00); } returnVal = returnVal.add(amount); } return returnVal; } /** * This method calculates the total Direct Cost Amount for all Direct F and A Distributions. * @return The total value */ public ScaleTwoDecimal getTotalDirectFandADistributionAnticipatedCostAmount() { ScaleTwoDecimal returnVal = new ScaleTwoDecimal(0.00); returnVal = returnVal.add(getTotalDirectFandADistributionDirectCostAmount()); returnVal = returnVal.add(getTotalDirectFandADistributionIndirectCostAmount()); return returnVal; } /** * This method totals Approved SubAward amounts * @return */ public ScaleTwoDecimal getTotalApprovedSubawardAmount() { return getTotalAmount(awardApprovedSubawards); } /** * This method totals Approved Equipment amounts * @return */ public ScaleTwoDecimal getTotalApprovedEquipmentAmount() { return getTotalAmount(approvedEquipmentItems); } /** * This method Approved Foreign Travel trip amounts * @return */ public ScaleTwoDecimal getTotalApprovedApprovedForeignTravelAmount() { return getTotalAmount(approvedForeignTravelTrips); } public List<AwardFandaRate> getAwardFandaRate() { return awardFandaRate; } public void setAwardFandaRate(List<AwardFandaRate> awardFandaRate) { this.awardFandaRate = awardFandaRate; } /** * Gets the keywords attribute. * @return Returns the keywords. */ @Override public List<AwardScienceKeyword> getKeywords() { return keywords; } /** * Sets the keywords attribute value. * @param keywords The keywords to set. */ public void setKeywords(List<AwardScienceKeyword> keywords) { this.keywords = keywords; } /** * @param leadUnit */ public void setLeadUnit(Unit leadUnit) { this.leadUnit = leadUnit; this.unitNumber = leadUnit != null ? leadUnit.getUnitNumber() : null; } public void setUnitNumber(String unitNumber) { this.unitNumber = unitNumber; } /** * Add selected science keyword to award science keywords list. * @see org.kuali.coeus.common.framework.keyword.KeywordsManager#addKeyword(org.kuali.coeus.common.framework.keyword.ScienceKeyword) */ public void addKeyword(ScienceKeyword scienceKeyword) { AwardScienceKeyword awardScienceKeyword = new AwardScienceKeyword(getAwardId(), scienceKeyword); getKeywords().add(awardScienceKeyword); } /** * It returns the ScienceKeyword object from keywords list * @see org.kuali.coeus.common.framework.keyword.KeywordsManager#getKeyword(int) */ public AwardScienceKeyword getKeyword(int index) { return getKeywords().get(index); } /** * Sets the awardSpecialReviews attribute value. * @param awardSpecialReviews The awardSpecialReviews to set. */ public void setSpecialReviews(List<AwardSpecialReview> awardSpecialReviews) { this.specialReviews = awardSpecialReviews; } /** * Add AwardSpecialReview to the AwardSpecialReview list * @see org.kuali.kra.document.SpecialReviewHandler#addSpecialReview(java.lang.Object) */ public void addSpecialReview(AwardSpecialReview specialReview) { specialReview.setSequenceOwner(this); getSpecialReviews().add(specialReview); } /** * Get AwardSpecialReview from special review list * @see org.kuali.kra.document.SpecialReviewHandler#getSpecialReview(int) */ public AwardSpecialReview getSpecialReview(int index) { return getSpecialReviews().get(index); } /** * Get special review list * @see org.kuali.kra.document.SpecialReviewHandler#getSpecialReviews() */ public List<AwardSpecialReview> getSpecialReviews() { return specialReviews; } /** * Add an ApprovedEquipment item * @param newAwardApprovedEquipment */ public void add(AwardApprovedEquipment approvedEquipmentItem) { approvedEquipmentItems.add(0, approvedEquipmentItem); approvedEquipmentItem.setAward(this); } /** * Add an AwardFandaRate * @param fandaRate */ public void add(AwardFandaRate fandaRate) { awardFandaRate.add(fandaRate); fandaRate.setAward(this); } /** * @param awardSpecialReview */ public void add(AwardSpecialReview awardSpecialReview) { specialReviews.add(awardSpecialReview); awardSpecialReview.setSequenceOwner(this); } public void add(AwardSponsorContact awardSponsorContact) { sponsorContacts.add(awardSponsorContact); awardSponsorContact.setAward(this); } public void add(AwardReportTerm awardReportTerm) { awardReportTermItems.add(awardReportTerm); awardReportTerm.setAward(this); } public void add(AwardCloseout awardCloseoutItem) { awardCloseoutNewItems.clear(); if(awardCloseoutItems != null && awardCloseoutItems.size() > TOTAL_STATIC_REPORTS){ for(int i = TOTAL_STATIC_REPORTS ;i < awardCloseoutItems.size() ; i++){ awardCloseoutNewItems.add(awardCloseoutItems.get(i)); } } awardCloseoutItems.removeAll(awardCloseoutNewItems); awardCloseoutNewItems.add(awardCloseoutItem); Collections.sort(awardCloseoutNewItems, new Comparator(){ public int compare(Object o1, Object o2) { if(o1 instanceof AwardCloseout && o2 instanceof AwardCloseout) { AwardCloseout awardCloseout1 = (AwardCloseout)o1; AwardCloseout awardCloseout2 = (AwardCloseout)o2; return awardCloseout1.getCloseoutReportName().compareTo(awardCloseout2.getCloseoutReportName()); } return 0; }}); awardCloseoutItems.addAll(TOTAL_STATIC_REPORTS, awardCloseoutNewItems); awardCloseoutItem.setAward(this); } public void addStaticCloseout(AwardCloseout awardCloseoutItem) { awardCloseoutItems.add(awardCloseoutItem); awardCloseoutItem.setAward(this); } /** * Add an Award Unit or Central Administration contact * @param newAwardApprovedEquipment */ public void add(AwardUnitContact awardUnitContact) { awardUnitContacts.add(awardUnitContact); awardUnitContact.setAward(this); } /** * Creates an AwardFundingProposal and adds it to the collection * * It also adds the AwardFundingProposal to the InstitutionalProposal * * @param institutionalProposal */ public void add(InstitutionalProposal institutionalProposal) { if (institutionalProposal != null) { AwardFundingProposal afp = new AwardFundingProposal(this, institutionalProposal); fundingProposals.add(afp); institutionalProposal.add(afp); //IP is Linked with award COI integration point MITKC-611 case 2 try { getKcCoiLinkService().updateCOIOnLinkIPToAward(afp.getAward().getAwardNumber(),institutionalProposal.getInstProposalNumber(),getGlobalVariableService().getUserSession().getPrincipalName()); } catch(NullPointerException e){ LOGGER.log(Level.ALL,"Input parameters return null"); }catch (SQLException e) { LOGGER.log(Level.ALL, e.getMessage(), e); LOGGER.log(Level.ALL,"DBLINK is not accessible or the parameter value returning null"); } } } /** * @param awardSponsorContact */ public void addSponsorContact(AwardSponsorContact awardSponsorContact) { sponsorContacts.add(awardSponsorContact); awardSponsorContact.setAward(this); } /** * This method adds a Project Person to the award * @param projectPerson */ public void add(AwardPerson projectPerson) { projectPersons.add(projectPerson); projectPerson.setAward(this); } /** * Add an * @param newAwardPaymentSchedule */ public void add(AwardPaymentSchedule paymentScheduleItem) { paymentScheduleItems.add(paymentScheduleItem); paymentScheduleItem.setAward(this); } public void addAwardTransferringSponsor(Sponsor sponsor) { AwardTransferringSponsor awardTransferringSponsor = new AwardTransferringSponsor(this, sponsor); awardTransferringSponsors.add(0, awardTransferringSponsor); } protected void initializeCollections() { setAwardCostShares(new ArrayList<AwardCostShare>()); setAwardComments(new ArrayList<AwardComment>()); awardApprovedSubawards = new ArrayList<AwardApprovedSubaward>(); setAwardFandaRate(new ArrayList<AwardFandaRate>()); setAwardReportTermItems(new ArrayList<AwardReportTerm>()); keywords = new ArrayList<AwardScienceKeyword>(); specialReviews = new ArrayList<AwardSpecialReview>(); approvedEquipmentItems = new ArrayList<AwardApprovedEquipment>(); approvedForeignTravelTrips = new ArrayList<AwardApprovedForeignTravel>(); setAwardSponsorTerms(new ArrayList<AwardSponsorTerm>()); paymentScheduleItems = new ArrayList<AwardPaymentSchedule>(); awardTransferringSponsors = new ArrayList<AwardTransferringSponsor>(); awardDirectFandADistributions = new ArrayList<AwardDirectFandADistribution>(); awardCustomDataList = new ArrayList<AwardCustomData>(); awardCloseoutItems = new ArrayList<AwardCloseout>(); awardCloseoutNewItems = new ArrayList<AwardCloseout>(); awardNotepads = new ArrayList<AwardNotepad>(); initializeAwardAmountInfoObjects(); projectPersons = new ArrayList<AwardPerson>(); awardUnitContacts = new ArrayList<AwardUnitContact>(); sponsorContacts = new ArrayList<AwardSponsorContact>(); awardBudgetLimits = new ArrayList<AwardBudgetLimit>(); fundingProposals = new ArrayList<AwardFundingProposal>(); initializeAwardHierarchyTempObjects(); syncChanges = new ArrayList<AwardSyncChange>(); syncStatuses = new ArrayList<AwardSyncStatus>(); subAwardList = new ArrayList<SubAward>(); budgets = new ArrayList<AwardBudgetExt>(); } public void initializeAwardAmountInfoObjects() { awardAmountInfos = new ArrayList<AwardAmountInfo>(); AwardAmountInfo awardAmountInfo = new AwardAmountInfo(); awardAmountInfo.setAward(this); awardAmountInfo.setOriginatingAwardVersion(1); awardAmountInfos.add(awardAmountInfo); } public void initializeAwardHierarchyTempObjects() { awardHierarchyTempObjects = new AutoPopulatingList<AwardHierarchyTempObject>(AwardHierarchyTempObject.class); } public ScaleTwoDecimal getPreAwardInstitutionalAuthorizedAmount() { return preAwardInstitutionalAuthorizedAmount; } /** * For negative values, this method makes the number positive by dropping the negative sign. * @param preAwardInstitutionalAuthorizedAmount */ public void setPreAwardInstitutionalAuthorizedAmount(ScaleTwoDecimal preAwardInstitutionalAuthorizedAmount) { // if preAwardInstitutionalAuthorizedAmount is negative, make it positive if (preAwardInstitutionalAuthorizedAmount != null && preAwardInstitutionalAuthorizedAmount.isNegative()) { this.preAwardInstitutionalAuthorizedAmount = ScaleTwoDecimal.ZERO.subtract(preAwardInstitutionalAuthorizedAmount); } else { this.preAwardInstitutionalAuthorizedAmount = preAwardInstitutionalAuthorizedAmount; } } public Date getPreAwardInstitutionalEffectiveDate() { return preAwardInstitutionalEffectiveDate; } public void setPreAwardInstitutionalEffectiveDate(Date preAwardInstitutionalEffectiveDate) { this.preAwardInstitutionalEffectiveDate = preAwardInstitutionalEffectiveDate; } public void add(AwardCostShare awardCostShare) { awardCostShares.add(awardCostShare); awardCostShare.setAward(this); } public void add(AwardApprovedSubaward awardApprovedSubaward) { awardApprovedSubawards.add(awardApprovedSubaward); awardApprovedSubaward.setAward(this); } public void add(AwardComment awardComment) { awardComments.add(awardComment); awardComment.setAward(this); } /** * This method adds template comments to award when sync to template is being applied. * @param awardComment */ public void addTemplateComments(List<AwardTemplateComment> awardTemplateComments) { AwardCommentFactory awardCommentFactory = new AwardCommentFactory(); for (AwardTemplateComment awardTemplateComment : awardTemplateComments) { AwardComment testAwardComment = getCommentMap().get(awardTemplateComment.getCommentTypeCode()); if (testAwardComment == null) { AwardComment awardComment = awardCommentFactory.createAwardComment(awardTemplateComment.getCommentTypeCode(), awardTemplateComment.getChecklistPrintFlag()); awardComment.setComments(awardTemplateComment.getComments()); add(awardComment); commentMap.put(awardComment.getCommentType().getCommentTypeCode(), awardComment); }else { testAwardComment.setComments(awardTemplateComment.getComments()); } } } public void add(AwardSponsorTerm awardSponsorTerm) { awardSponsorTerms.add(awardSponsorTerm); awardSponsorTerm.setAward(this); } /** * This method adds template sponsor terms to award when sync to template is being applied. * @param awardTemplateTerms */ public void addTemplateTerms(List<AwardTemplateTerm> awardTemplateTerms) { List<AwardSponsorTerm> tempAwardSponsorTerms = new ArrayList<AwardSponsorTerm>(); for (AwardTemplateTerm awardTemplateTerm : awardTemplateTerms) { tempAwardSponsorTerms.add(new AwardSponsorTerm(awardTemplateTerm.getSponsorTermId(), awardTemplateTerm.getSponsorTerm())); } setAwardSponsorTerms(tempAwardSponsorTerms); } /** * This method adds AwardDirectFandADistribution to end of list. * @param awardDirectFandADistribution */ public void add(AwardDirectFandADistribution awardDirectFandADistribution) { awardDirectFandADistributions.add(awardDirectFandADistribution); awardDirectFandADistribution.setAward(this); awardDirectFandADistribution.setBudgetPeriod(awardDirectFandADistributions.size()); } /** * This method adds AwardDirectFandADistribution to the given index in the list. * @param awardDirectFandADistribution */ public void add(int index, AwardDirectFandADistribution awardDirectFandADistribution) { awardDirectFandADistributions.add(index, awardDirectFandADistribution); awardDirectFandADistribution.setAward(this); awardDirectFandADistribution.setBudgetPeriod(index + 1); updateDirectFandADistributionBudgetPeriods(index + 1); } public void add(AwardNotepad awardNotepad) { awardNotepad.setEntryNumber(awardNotepads.size() + 1); awardNotepad.setAwardNumber(this.getAwardNumber()); awardNotepads.add(awardNotepad); awardNotepad.setAward(this); } /** * This method updates the budget periods in the Award after insertion of new Award Direct F and A Distribution into list. * @param index */ public void updateDirectFandADistributionBudgetPeriods(int index) { for (int newIndex = index; newIndex < awardDirectFandADistributions.size(); newIndex++) { awardDirectFandADistributions.get(newIndex).setBudgetPeriod(newIndex + 1); } } /** * This method calculates the total value of a list of ValuableItems * @param valuableItems * @return The total value */ ScaleTwoDecimal getTotalAmount(List<? extends ValuableItem> valuableItems) { ScaleTwoDecimal returnVal = new ScaleTwoDecimal(0.00); for (ValuableItem item : valuableItems) { ScaleTwoDecimal amount = item.getAmount() != null ? item.getAmount() : new ScaleTwoDecimal(0.00); returnVal = returnVal.add(amount); } return returnVal; } /** * Gets the awardSponsorTerms attribute. * @return Returns the awardSponsorTerms. */ public List<AwardSponsorTerm> getAwardSponsorTerms() { return awardSponsorTerms; } public AwardStatus getAwardStatus() { if (awardStatus == null && statusCode != null) { refreshReferenceObject("awardStatus"); } return awardStatus; } /** * Sets the awardSponsorTerms attribute value. * @param awardSponsorTerms The awardSponsorTerms to set. */ public void setAwardSponsorTerms(List<AwardSponsorTerm> awardSponsorTerms) { this.awardSponsorTerms = awardSponsorTerms; } /** * This method violates our policy of not calling a service in a getter. * This will only call the service once to set a sponsor when a sponsor code exists, * but no sponsor was fetched * * Seems like a persistence design issue to me. Why wouldn't Sponsor:Award be a 1:M * relationship handled automagically by the persistence framework? * * @return */ public Sponsor getSponsor() { if (!StringUtils.isEmpty(sponsorCode)) { this.refreshReferenceObject("sponsor"); } return sponsor; } public List<AwardSponsorContact> getSponsorContacts() { return sponsorContacts; } public void setSponsorContacts(List<AwardSponsorContact> awardSponsorContacts) { this.sponsorContacts = awardSponsorContacts; } public void setSponsor(Sponsor sponsor) { this.sponsor = sponsor; this.sponsorCode = sponsor != null ? sponsor.getSponsorCode() : null; } public String getSponsorName() { Sponsor sponsor = getSponsor(); sponsorName = sponsor != null ? sponsor.getSponsorName() : null; return sponsorName; } public String getIcrRateCode() { return icrRateCode; } public void setIcrRateCode(String icrRateCode) { this.icrRateCode = icrRateCode; } /** * This method adds an approved foreign travel trip * @param approvedForeignTravelTrip */ public void add(AwardApprovedForeignTravel approvedForeignTravelTrip) { approvedForeignTravelTrips.add(approvedForeignTravelTrip); approvedForeignTravelTrip.setAward(this); } /** * Gets the paymentScheduleItems attribute. * @return Returns the paymentScheduleItems. */ public List<AwardPaymentSchedule> getPaymentScheduleItems() { return paymentScheduleItems; } /** * Sets the paymentScheduleItems attribute value. * @param paymentScheduleItems The paymentScheduleItems to set. */ public void setPaymentScheduleItems(List<AwardPaymentSchedule> paymentScheduleItems) { this.paymentScheduleItems = paymentScheduleItems; } public ScaleTwoDecimal getTotalPaymentScheduleAmount() { ScaleTwoDecimal amount = ScaleTwoDecimal.ZERO; for (AwardPaymentSchedule schedule : paymentScheduleItems) { if (schedule.getAmount() != null) { amount = amount.add(schedule.getAmount()); } } return amount; } // Note: following the pattern of Sponsor, this getter indirectly calls a service. // Is there a better way? public Sponsor getPrimeSponsor() { if (!StringUtils.isEmpty(getPrimeSponsorCode())) { this.refreshReferenceObject("primeSponsor"); } return primeSponsor; } public void setPrimeSponsor(Sponsor primeSponsor) { this.primeSponsor = primeSponsor; } public List<AwardTransferringSponsor> getAwardTransferringSponsors() { return awardTransferringSponsors; } /** * @param awardStatus */ public void setAwardStatus(AwardStatus awardStatus) { this.awardStatus = awardStatus; } public void setAwardTransferringSponsors(List<AwardTransferringSponsor> awardTransferringSponsors) { this.awardTransferringSponsors = awardTransferringSponsors; } /** * Gets the awardDirectFandADistribution attribute. * @return Returns the awardDirectFandADistribution. */ public List<AwardDirectFandADistribution> getAwardDirectFandADistributions() { return awardDirectFandADistributions; } /** * Sets the awardDirectFandADistribution attribute value. * @param awardDirectFandADistribution The awardDirectFandADistribution to set. */ public void setAwardDirectFandADistributions(List<AwardDirectFandADistribution> awardDirectFandADistributions) { for (AwardDirectFandADistribution awardDirectFandADistribution : awardDirectFandADistributions) { awardDirectFandADistribution.setAward(this); } this.awardDirectFandADistributions = awardDirectFandADistributions; } /** * Gets the awardNotepads attribute. * @return Returns the awardNotepads. */ public List<AwardNotepad> getAwardNotepads() { return awardNotepads; } /** * Sets the awardNotepads attribute value. * @param awardNotepads The awardNotepads to set. */ public void setAwardNotepads(List<AwardNotepad> awardNotepads) { this.awardNotepads = awardNotepads; } /** * Gets the indirectCostIndicator attribute. * @return Returns the indirectCostIndicator. */ public String getIndirectCostIndicator() { return indirectCostIndicator; } /** * Sets the indirectCostIndicator attribute value. * @param indirectCostIndicator The indirectCostIndicator to set. */ public void setIndirectCostIndicator(String indirectCostIndicator) { this.indirectCostIndicator = indirectCostIndicator; } /** * Gets the obligatedTotal attribute. * @return Returns the obligatedTotal. */ public ScaleTwoDecimal getObligatedTotal() { ScaleTwoDecimal returnValue = new ScaleTwoDecimal(0.00); // if(awardAmountInfos.get(0).getAmountObligatedToDate()!=null){ // returnValue = returnValue.add(awardAmountInfos.get(0).getAmountObligatedToDate()); // } if (getLastAwardAmountInfo().getAmountObligatedToDate() != null) { returnValue = returnValue.add(getLastAwardAmountInfo().getAmountObligatedToDate()); } return returnValue; } public ScaleTwoDecimal getObligatedDistributableTotal() { ScaleTwoDecimal returnValue = ScaleTwoDecimal.ZERO; if (getLastAwardAmountInfo().getObliDistributableAmount() != null) { returnValue = getLastAwardAmountInfo().getObliDistributableAmount(); } return returnValue; } /** * Returns the obligated distributable total or the total cost limit * whichever is less. * @return */ public ScaleTwoDecimal getBudgetTotalCostLimit() { ScaleTwoDecimal limit = getTotalCostBudgetLimit(); ScaleTwoDecimal obliTotal = getObligatedDistributableTotal(); if (limit != null && limit.isLessEqual(obliTotal)) { return limit; } else { return obliTotal; } } /** * Gets the obligatedTotal attribute. * @return Returns the obligatedTotal. */ public ScaleTwoDecimal getObligatedTotalDirect() { ScaleTwoDecimal returnValue = new ScaleTwoDecimal(0.00); // if(awardAmountInfos.get(0).getAmountObligatedToDate()!=null){ // returnValue = returnValue.add(awardAmountInfos.get(0).getAmountObligatedToDate()); // } if (getLastAwardAmountInfo().getObligatedTotalDirect() != null) { returnValue = returnValue.add(getLastAwardAmountInfo().getObligatedTotalDirect()); } return returnValue; } /** * Gets the obligatedTotal attribute. * @return Returns the obligatedTotal. */ public ScaleTwoDecimal getObligatedTotalIndirect() { ScaleTwoDecimal returnValue = new ScaleTwoDecimal(0.00); // if(awardAmountInfos.get(0).getAmountObligatedToDate()!=null){ // returnValue = returnValue.add(awardAmountInfos.get(0).getAmountObligatedToDate()); // } if (getLastAwardAmountInfo().getObligatedTotalIndirect() != null) { returnValue = returnValue.add(getLastAwardAmountInfo().getObligatedTotalIndirect()); } return returnValue; } /** * Gets the anticipatedTotal attribute. * @return Returns the anticipatedTotal. */ public ScaleTwoDecimal getAnticipatedTotal() { ScaleTwoDecimal returnValue = new ScaleTwoDecimal(0.00); // if(awardAmountInfos.get(0).getAnticipatedTotalAmount()!=null){ // returnValue = returnValue.add(awardAmountInfos.get(0).getAnticipatedTotalAmount()); // } if (getLastAwardAmountInfo().getAnticipatedTotalAmount() != null) { returnValue = returnValue.add(getLastAwardAmountInfo().getAnticipatedTotalAmount()); } return returnValue; } /** * Gets the anticipatedTotal attribute. * @return Returns the anticipatedTotal. */ public ScaleTwoDecimal getAnticipatedTotalDirect() { ScaleTwoDecimal returnValue = new ScaleTwoDecimal(0.00); // if(awardAmountInfos.get(0).getAnticipatedTotalAmount()!=null){ // returnValue = returnValue.add(awardAmountInfos.get(0).getAnticipatedTotalAmount()); // } if (getLastAwardAmountInfo().getAnticipatedTotalDirect() != null) { returnValue = returnValue.add(getLastAwardAmountInfo().getAnticipatedTotalDirect()); } return returnValue; } /** * Gets the anticipatedTotal attribute. * @return Returns the anticipatedTotal. */ public ScaleTwoDecimal getAnticipatedTotalIndirect() { ScaleTwoDecimal returnValue = new ScaleTwoDecimal(0.00); // if(awardAmountInfos.get(0).getAnticipatedTotalAmount()!=null){ // returnValue = returnValue.add(awardAmountInfos.get(0).getAnticipatedTotalAmount()); // } if (getLastAwardAmountInfo().getAnticipatedTotalIndirect() != null) { returnValue = returnValue.add(getLastAwardAmountInfo().getAnticipatedTotalIndirect()); } return returnValue; } @Override public String getDocumentNumberForPermission() { return awardId != null ? awardId.toString() : ""; } @Override public String getDocumentKey() { return PermissionableKeys.AWARD_KEY; } @Override public List<String> getRoleNames() { List<String> roles = new ArrayList<String>(); SystemAuthorizationService systemAuthorizationService = KcServiceLocator.getService("systemAuthorizationService"); List<Role> roleBOs = systemAuthorizationService.getRoles(Constants.MODULE_NAMESPACE_AWARD); for(Role role : roleBOs) { roles.add(role.getName()); } return roles; } public List<AwardAmountInfo> getAwardAmountInfos() { return awardAmountInfos; } public void setAwardAmountInfos(List<AwardAmountInfo> awardAmountInfos) { this.awardAmountInfos = awardAmountInfos; } public AwardAmountInfo getAwardAmountInfo() { return awardAmountInfos.get(0); } /** * Find the lead unit for the award * @return */ public Unit getLeadUnit() { if (leadUnit == null && unitNumber != null) { loadLeadUnit(); } return leadUnit; } public boolean isNew() { return awardId == null; } class ARTComparator implements Comparator { public int compare(Object art1, Object art2) { try { String art1Desc = ((AwardReportTerm) art1).getReport().getDescription(); String art2Desc = ((AwardReportTerm) art2).getReport().getDescription(); if (art1Desc == null) { art1Desc = ""; } if (art2Desc == null) { art2Desc = ""; } return art1Desc.compareTo(art2Desc); } catch (Exception e) { return 0; } } } /** * Gets the awardReportTermItems attribute. * @return Returns the awardReportTermItems. */ public List<AwardReportTerm> getAwardReportTermItems() { Collections.sort(awardReportTermItems, new ARTComparator()); return awardReportTermItems; } /** * Sets the awardReportTermItems attribute value. * @param awardReportTermItems The awardReportTermItems to set. */ public void setAwardReportTermItems(List<AwardReportTerm> awardReportTermItems) { this.awardReportTermItems = awardReportTermItems; } /** * Find principle investigator, if any * @return Principle investigator. May return null */ public AwardPerson getPrincipalInvestigator() { AwardPerson principleInvestigator = null; for (AwardPerson person : projectPersons) { if (person.isPrincipalInvestigator()) { principleInvestigator = person; break; } } return principleInvestigator; } /** * This method find PI name * @return PI name; may return null */ public String getPrincipalInvestigatorName() { AwardPerson pi = getPrincipalInvestigator(); if (pi != null) { if (pi.getIsRolodexPerson()) { principalInvestigatorName = pi.getRolodex().getOrganization(); } else { principalInvestigatorName = pi.getFullName(); } } return principalInvestigatorName; } /** * @param principalInvestigatorName */ public void setPrincipalInvestigatorName(String principalInvestigatorName) { this.principalInvestigatorName = principalInvestigatorName; } /** * This method returns the status description * @return */ public String getStatusDescription() { AwardStatus status = getAwardStatus(); statusDescription = status != null ? status.getDescription() : null; return statusDescription; } /** * Gets the awardCustomDataList attribute. * @return Returns the awardCustomDataList. */ public List<AwardCustomData> getAwardCustomDataList() { return awardCustomDataList; } /** * Sets the awardCustomDataList attribute value. * @param awardCustomDataList The awardCustomDataList to set. */ public void setAwardCustomDataList(List<AwardCustomData> awardCustomDataList) { this.awardCustomDataList = awardCustomDataList; } /** * Gets the awardCloseoutItems attribute. * @return Returns the awardCloseoutItems. */ public List<AwardCloseout> getAwardCloseoutItems() { return awardCloseoutItems; } /** * Sets the awardCloseoutItems attribute value. * @param awardCloseoutItems The awardCloseoutItems to set. */ public void setAwardCloseoutItems(List<AwardCloseout> awardCloseoutItems) { if(awardCloseoutItems != null && awardCloseoutItems.size() > TOTAL_STATIC_REPORTS){ awardCloseoutNewItems.clear(); for(int i = TOTAL_STATIC_REPORTS ;i < awardCloseoutItems.size() ; i++){ awardCloseoutNewItems.add(awardCloseoutItems.get(i)); } for (int i = awardCloseoutItems.size();i > TOTAL_STATIC_REPORTS; i--) { awardCloseoutItems.remove(i - 1); } Collections.sort(awardCloseoutNewItems, new Comparator(){ public int compare(Object o1, Object o2) { if(o1 instanceof AwardCloseout && o2 instanceof AwardCloseout) { AwardCloseout awardCloseout1 = (AwardCloseout)o1; AwardCloseout awardCloseout2 = (AwardCloseout)o2; return awardCloseout1.getCloseoutReportName().compareTo(awardCloseout2.getCloseoutReportName()); } return 0; }}); awardCloseoutItems.addAll(TOTAL_STATIC_REPORTS, awardCloseoutNewItems); } this.awardCloseoutItems = awardCloseoutItems; } /** * Gets the awardCloseoutNewItems attribute. * @return Returns the awardCloseoutNewItems. */ public List<AwardCloseout> getAwardCloseoutNewItems() { return awardCloseoutNewItems; } /** * Sets the awardCloseoutNewItems attribute value. * @param awardCloseoutNewItems The awardCloseoutNewItems to set. */ public void setAwardCloseoutNewItems(List<AwardCloseout> awardCloseoutNewItems) { this.awardCloseoutNewItems = awardCloseoutNewItems; } /** * Sets the templateCode attribute value. * @param templateCode The templateCode to set. */ public void setTemplateCode(Integer templateCode) { this.templateCode = templateCode; } /** * Gets the primeSponsorCode attribute. * @return Returns the primeSponsorCode. */ public String getPrimeSponsorCode() { return primeSponsorCode; } /** * Sets the primeSponsorCode attribute value. * @param primeSponsorCode The primeSponsorCode to set. */ public void setPrimeSponsorCode(String primeSponsorCode) { this.primeSponsorCode = primeSponsorCode; } /** * Gets the basisOfPaymentCode attribute. * @return Returns the basisOfPaymentCode. */ public String getBasisOfPaymentCode() { return basisOfPaymentCode; } /** * Sets the basisOfPaymentCode attribute value. * @param basisOfPaymentCode The basisOfPaymentCode to set. */ public void setBasisOfPaymentCode(String basisOfPaymentCode) { this.basisOfPaymentCode = basisOfPaymentCode; } /** * Gets the methodOfPaymentCode attribute. * @return Returns the methodOfPaymentCode. */ public String getMethodOfPaymentCode() { return methodOfPaymentCode; } /** * Sets the methodOfPaymentCode attribute value. * @param methodOfPaymentCode The methodOfPaymentCode to set. */ public void setMethodOfPaymentCode(String methodOfPaymentCode) { this.methodOfPaymentCode = methodOfPaymentCode; } /** * Gets the awardTemplate attribute. * @return Returns the awardTemplate. */ public AwardTemplate getAwardTemplate() { return awardTemplate; } /** * Sets the awardTemplate attribute value. * @param awardTemplate The awardTemplate to set. */ public void setAwardTemplate(AwardTemplate awardTemplate) { this.awardTemplate = awardTemplate; } /** * Gets the awardBasisOfPayment attribute. * @return Returns the awardBasisOfPayment. */ public AwardBasisOfPayment getAwardBasisOfPayment() { return awardBasisOfPayment; } /** * Sets the awardBasisOfPayment attribute value. * @param awardBasisOfPayment The awardBasisOfPayment to set. */ public void setAwardBasisOfPayment(AwardBasisOfPayment awardBasisOfPayment) { this.awardBasisOfPayment = awardBasisOfPayment; } /** * Gets the awardMethodOfPayment attribute. * @return Returns the awardMethodOfPayment. */ public AwardMethodOfPayment getAwardMethodOfPayment() { return awardMethodOfPayment; } /** * Sets the awardMethodOfPayment attribute value. * @param awardMethodOfPayment The awardMethodOfPayment to set. */ public void setAwardMethodOfPayment(AwardMethodOfPayment awardMethodOfPayment) { this.awardMethodOfPayment = awardMethodOfPayment; } @Override public Integer getOwnerSequenceNumber() { return null; } @Override public void incrementSequenceNumber() { this.sequenceNumber++; } @Override public Award getSequenceOwner() { return this; } @Override public void setSequenceOwner(Award newOwner) { // no-op } @Override public void resetPersistenceState() { this.awardId = null; } @Override public String getVersionNameField() { return "awardNumber"; } /** * Gets the activityType attribute. * @return Returns the activityType. */ public ActivityType getActivityType() { return activityType; } /** * Sets the activityType attribute value. * @param activityType The activityType to set. */ public void setActivityType(ActivityType activityType) { this.activityType = activityType; } /** * This method removes Funding Proposal for specified index from list * * It also removes the AwardFundingProposal from the InstitutionalProposal * * @param index */ public AwardFundingProposal removeFundingProposal(int index) { AwardFundingProposal afp = (index >= 0) ? fundingProposals.remove(index) : null; afp.getProposalId(); InstitutionalProposal proposal = getInstitutionalProposalService().getInstitutionalProposal(afp.getProposalId().toString()); if (proposal != null) { proposal.remove(afp); } return afp; } private InstitutionalProposalService getInstitutionalProposalService() { return KcServiceLocator.getService(InstitutionalProposalService.class); } /** * Given an AwardComment as a template, try to find an existing AwardComment of that type * @param template * @return The found awardComment of a specific type. If an existing comment is not found, return null */ public AwardComment findCommentOfSpecifiedType(AwardComment template) { return findCommentOfSpecifiedType(template.getCommentTypeCode()); } /** * For a given type code, this method returns the award comment, or null if none exists. * @param commentTypeCode One of the ..._COMMENT_TYPE_CODE values in org.kuali.kra.infrastructure.Constants * @return */ public AwardComment findCommentOfSpecifiedType(String commentTypeCode) { AwardComment comment = null; for (AwardComment ac : getAwardComments()) { if (ac.getCommentTypeCode().equals(commentTypeCode)) { comment = ac; break; } } return comment; } public String getBudgetStatus() { // hard coded as completed return "2"; } public List getPersonRolodexList() { return getProjectPersons(); } public PersonRolodex getProposalEmployee(String personId) { return getPerson(personId, true); } private PersonRolodex getPerson(String personId, boolean personFindFlag) { List<AwardPerson> awardPersons = getProjectPersons(); for (AwardPerson awardPerson : awardPersons) { // rearranged order of condition to handle null personId if ((personId != null) && personId.equals(awardPerson.getPersonId())) { if (personFindFlag && awardPerson.isEmployee()) { return awardPerson; }else{ return awardPerson; } } } return null; } public ContactRole getProposalEmployeeRole(String personId) { if (getProposalEmployee(personId) != null) { return ((AwardPerson) getProposalEmployee(personId)).getContactRole(); } else { return null; } } public PersonRolodex getProposalNonEmployee(Integer rolodexId) { List<AwardPerson> awardPersons = getProjectPersons(); for (AwardPerson awardPerson : awardPersons) { if (rolodexId.equals(awardPerson.getRolodexId())) { return awardPerson; } } return null; } public ContactRole getProposalNonEmployeeRole(Integer rolodexId) { if (getProposalNonEmployee(rolodexId) != null) { return ((AwardPerson) getProposalNonEmployee(rolodexId)).getContactRole(); } else { return null; } } public Date getRequestedEndDateInitial() { return getObligationExpirationDate(); } public Date getRequestedStartDateInitial() { AwardAmountInfo awardAmountInfo = getLastAwardAmountInfo(); return awardAmountInfo == null ? null : awardAmountInfo.getCurrentFundEffectiveDate(); } public Unit getUnit() { return getLeadUnit(); } public boolean isSponsorNihMultiplePi() { return sponsorNihMultiplePi; } public void setBudgetStatus(String budgetStatus) { } /** * Gets the attachmentsw. Cannot return {@code null}. * @return the attachments */ public List<AwardAttachment> getAwardAttachments() { if (this.awardAttachments == null) { this.awardAttachments = new ArrayList<AwardAttachment>(); } return this.awardAttachments; } public void setAttachments(List<AwardAttachment> attachments) { this.awardAttachments = attachments; } /** * Gets an attachment. * @param index the index * @return an attachment personnel */ public AwardAttachment getAwardAttachment(int index) { return this.awardAttachments.get(index); } /** * add an attachment. * @param attachment the attachment * @throws IllegalArgumentException if attachment is null */ public void addAttachment(AwardAttachment attachment) { this.getAwardAttachments().add(attachment); attachment.setAward(this); } /** * This method indicates if the Awrd has been persisted * @return True if persisted */ public boolean isPersisted() { return awardId != null; } public AwardApprovedSubaward getAwardApprovedSubawards(int index) { return getAwardApprovedSubawards().get(index); } public String getNamespace() { return Constants.MODULE_NAMESPACE_AWARD; } public String getDocumentRoleTypeCode() { return RoleConstants.AWARD_ROLE_TYPE; } protected void loadLeadUnit() { leadUnit = (Unit) getBusinessObjectService().findByPrimaryKey(Unit.class, Collections.singletonMap("unitNumber", getUnitNumber())); } public void populateAdditionalQualifiedRoleAttributes(Map<String, String> qualifiedRoleAttributes) { /** * when we check to see if the logged in user can create an award account, this function is called, but awardDocument is null at that time. */ String documentNumber = getAwardDocument() != null ? getAwardDocument().getDocumentNumber() : ""; qualifiedRoleAttributes.put("documentNumber", documentNumber); } protected BusinessObjectService getBusinessObjectService() { return KcServiceLocator.getService(BusinessObjectService.class); } public String getHierarchyStatus() { return "N"; } /** * This method gets the obligated, distributable amount for the Award. This may be replacable with the Award TimeAndMoney obligatedAmount value, but * at the time of its creation, TimeAndMoney wasn't complete * @return */ public ScaleTwoDecimal calculateObligatedDistributedAmountTotal() { ScaleTwoDecimal sum = ScaleTwoDecimal.ZERO; for (AwardAmountInfo amountInfo : getAwardAmountInfos()) { ScaleTwoDecimal obligatedDistributableAmount = amountInfo.getObliDistributableAmount(); sum = sum.add(obligatedDistributableAmount != null ? obligatedDistributableAmount : ScaleTwoDecimal.ZERO); } return sum; } /** * This method finds the latest final expiration date from the collection of AmnoutInfos * @return The latest final expiration date from the collection of AmnoutInfos. If there are no AmoutInfos, 1/1/1900 is returned */ public Date findLatestFinalExpirationDate() { Date latestExpDate = new Date(new GregorianCalendar(1900, Calendar.JANUARY, 1).getTimeInMillis()); for (AwardAmountInfo amountInfo : getAwardAmountInfos()) { Date expDate = amountInfo.getFinalExpirationDate(); if (expDate != null && expDate.after(latestExpDate)) { latestExpDate = expDate; } } return latestExpDate; } public boolean isParentInHierarchyComplete() { return true; } public String getDefaultBudgetStatusParameter() { return KeyConstants.AWARD_BUDGET_STATUS_IN_PROGRESS; } /** * * @return awardHierarchyTempObjects */ public List<AwardHierarchyTempObject> getAwardHierarchyTempObjects() { return awardHierarchyTempObjects; } public AwardHierarchyTempObject getAwardHierarchyTempObject(int index) { if (awardHierarchyTempObjects == null) { initializeAwardHierarchyTempObjects(); } return awardHierarchyTempObjects.get(index); } public AwardType getAwardType() { return awardType; } public void setAwardType(AwardType awardType) { this.awardType = awardType; } /** * * This method text area tag need this method. * @param index * @return */ public AwardComment getAwardComment(int index) { while (getAwardComments().size() <= index) { getAwardComments().add(new AwardComment()); } return getAwardComments().get(index); } public String getDocIdStatus() { return docIdStatus; } public String getAwardIdAccount() { if (awardIdAccount == null) { if (StringUtils.isNotBlank(getAccountNumber())) { awardIdAccount = getAwardNumber() + ":" + getAccountNumber(); } else { awardIdAccount = getAwardNumber() + ":"; } } return awardIdAccount; } public void setLookupOspAdministratorName(String lookupOspAdministratorName) { this.lookupOspAdministratorName = lookupOspAdministratorName; } public String getLookupOspAdministratorName() { return lookupOspAdministratorName; } /** * * Returns a list of central admin contacts based on the lead unit of this award. * @return */ public List<AwardUnitContact> getCentralAdminContacts() { if (centralAdminContacts == null) { initCentralAdminContacts(); } return centralAdminContacts; } /** * Builds the list of central admin contacts based on the lead unit of this * award. Build here instead of on a form bean as ospAdministrator * must be accessible during Award lookup. * */ public void initCentralAdminContacts() { centralAdminContacts = new ArrayList<AwardUnitContact>(); List<UnitAdministrator> unitAdministrators = KcServiceLocator.getService(UnitService.class).retrieveUnitAdministratorsByUnitNumber(getUnitNumber()); for (UnitAdministrator unitAdministrator : unitAdministrators) { if(unitAdministrator.getUnitAdministratorType().getDefaultGroupFlag().equals(DEFAULT_GROUP_CODE_FOR_CENTRAL_ADMIN_CONTACTS)) { KcPerson person = getKcPersonService().getKcPersonByPersonId(unitAdministrator.getPersonId()); AwardUnitContact newAwardUnitContact = new AwardUnitContact(); newAwardUnitContact.setAward(this); newAwardUnitContact.setPerson(person); newAwardUnitContact.setUnitAdministratorType(unitAdministrator.getUnitAdministratorType()); newAwardUnitContact.setFullName(person.getFullName()); centralAdminContacts.add(newAwardUnitContact); } } } public boolean isAwardInMultipleNodeHierarchy() { return awardInMultipleNodeHierarchy; } public void setAwardInMultipleNodeHierarchy(boolean awardInMultipleNodeHierarchy) { this.awardInMultipleNodeHierarchy = awardInMultipleNodeHierarchy; } public boolean isAwardHasAssociatedTandMOrIsVersioned() { return awardHasAssociatedTandMOrIsVersioned; } public void setAwardHasAssociatedTandMOrIsVersioned(boolean awardHasAssociatedTandMOrIsVersioned) { this.awardHasAssociatedTandMOrIsVersioned = awardHasAssociatedTandMOrIsVersioned; } public boolean isSyncChild() { return syncChild; } public void setSyncChild(boolean syncChild) { this.syncChild = syncChild; } public List<AwardSyncChange> getSyncChanges() { return syncChanges; } public void setSyncChanges(List<AwardSyncChange> syncChanges) { this.syncChanges = syncChanges; } public List<AwardSyncStatus> getSyncStatuses() { return syncStatuses; } public void setSyncStatuses(List<AwardSyncStatus> syncStatuses) { this.syncStatuses = syncStatuses; } public void setSponsorNihMultiplePi(boolean sponsorNihMultiplePi) { this.sponsorNihMultiplePi = sponsorNihMultiplePi; } /* * Used by Current Report to determine if award in Active, Pending, or Hold state. */ private static String reportedStatus = "1 3 6"; public boolean isActiveVersion() { return (reportedStatus.indexOf(getAwardStatus().getStatusCode()) != -1); } public List<AwardBudgetLimit> getAwardBudgetLimits() { return awardBudgetLimits; } public void setAwardBudgetLimits(List<AwardBudgetLimit> awardBudgetLimits) { this.awardBudgetLimits = awardBudgetLimits; } public ScaleTwoDecimal getTotalCostBudgetLimit() { return getSpecificBudgetLimit(AwardBudgetLimit.LIMIT_TYPE.TOTAL_COST).getLimit(); } public ScaleTwoDecimal getDirectCostBudgetLimit() { return getSpecificBudgetLimit(AwardBudgetLimit.LIMIT_TYPE.DIRECT_COST).getLimit(); } public ScaleTwoDecimal getIndirectCostBudgetLimit() { return getSpecificBudgetLimit(AwardBudgetLimit.LIMIT_TYPE.INDIRECT_COST).getLimit(); } protected AwardBudgetLimit getSpecificBudgetLimit(AwardBudgetLimit.LIMIT_TYPE type) { for (AwardBudgetLimit limit : getAwardBudgetLimits()) { if (limit.getLimitType() == type) { return limit; } } return new AwardBudgetLimit(type); } public List<Boolean> getAwardCommentHistoryFlags() { return awardCommentHistoryFlags; } public void setAwardCommentHistoryFlags(List<Boolean> awardCommentHistoryFlags) { this.awardCommentHistoryFlags = awardCommentHistoryFlags; } public void orderStaticCloseOutReportItems(List<AwardCloseout> awardCloseoutItems) { if(awardCloseoutItems != null && awardCloseoutItems.size() == TOTAL_STATIC_REPORTS){ awardCloseoutNewItems.clear(); List<AwardCloseout> staticCloseoutItems = new ArrayList<AwardCloseout>(); for(int i = 0; i < TOTAL_STATIC_REPORTS ; i++){ staticCloseoutItems.add(awardCloseoutItems.get(i)); awardCloseoutNewItems.add(awardCloseoutItems.get(i)); } awardCloseoutItems.removeAll(staticCloseoutItems); for(AwardCloseout awardCloseout : staticCloseoutItems){ if(awardCloseout.getCloseoutReportCode() != null && awardCloseout.getCloseoutReportCode().equalsIgnoreCase(CLOSE_OUT_REPORT_TYPE_FINANCIAL_REPORT)){ awardCloseoutNewItems.remove(awardCloseout); awardCloseoutNewItems.add(0,awardCloseout); }else if(awardCloseout.getCloseoutReportCode() != null && awardCloseout.getCloseoutReportCode().equalsIgnoreCase(CLOSE_OUT_REPORT_TYPE_TECHNICAL)){ awardCloseoutNewItems.remove(awardCloseout); awardCloseoutNewItems.add(1,awardCloseout); }else if(awardCloseout.getCloseoutReportCode() != null && awardCloseout.getCloseoutReportCode().equalsIgnoreCase(CLOSE_OUT_REPORT_TYPE_PATENT)){ awardCloseoutNewItems.remove(awardCloseout); awardCloseoutNewItems.add(2,awardCloseout); }else if(awardCloseout.getCloseoutReportCode() != null && awardCloseout.getCloseoutReportCode().equalsIgnoreCase(CLOSE_OUT_REPORT_TYPE_PROPERTY)){ awardCloseoutNewItems.remove(awardCloseout); awardCloseoutNewItems.add(3,awardCloseout); }else if(awardCloseout.getCloseoutReportCode() != null && awardCloseout.getCloseoutReportCode().equalsIgnoreCase(CLOSE_OUT_REPORT_TYPE_INVOICE)){ awardCloseoutNewItems.remove(awardCloseout); awardCloseoutNewItems.add(4,awardCloseout); } } awardCloseoutItems.addAll(0,awardCloseoutNewItems); } } @Override public String getLeadUnitName() { String name = getLeadUnit() == null ? EMPTY_STRING : getLeadUnit().getUnitName(); return name; } @Override public String getPiName() { return getPiEmployeeName(); } @Override public String getPiEmployeeName() { return getPrincipalInvestigatorName(); } @Override public String getPiNonEmployeeName() { return EMPTY_STRING; } @Override public String getAdminPersonName() { return EMPTY_STRING; } @Override public String getPrimeSponsorName() { String name = getPrimeSponsor() == null ? EMPTY_STRING : getPrimeSponsor().getSponsorName(); return name; } @Override public String getSubAwardOrganizationName() { return EMPTY_STRING; } @Override public List<NegotiationPersonDTO> getProjectPeople() { List<NegotiationPersonDTO> kcPeople = new ArrayList<NegotiationPersonDTO>(); for (AwardPerson person : getProjectPersons()) { kcPeople.add(new NegotiationPersonDTO(person.getPerson(), person.getContactRoleCode())); } return kcPeople; } public String getNegotiableProposalTypeCode() { return EMPTY_STRING; } public String getParentNumber() { return this.getAwardNumber(); } public String getParentPIName() { String investigatorName = null; for (AwardPerson aPerson : this.getProjectPersons()) { if (aPerson != null && aPerson.isPrincipalInvestigator() ) { investigatorName = aPerson.getFullName(); break; } } return investigatorName; } public String getParentTitle() { return this.getTitle(); } public String getIsOwnedByUnit() { return this.getLeadUnitName(); } public Integer getParentInvestigatorFlag(String personId, Integer flag) { for (AwardPerson aPerson : this.getProjectPersons()) { if (aPerson.getPersonId() != null && aPerson.getPersonId().equals(personId) || aPerson.getRolodexId() != null && aPerson.getRolodexId().equals(personId)) { flag = 2; if (aPerson.isPrincipalInvestigator()) { flag = 1; break; } } } return flag; } /** * This method gets the current rate. * If there are multiple current rates, return the one with the higher rate * @param award * @return currentFandaRate */ public AwardFandaRate getCurrentFandaRate() { List<AwardFandaRate> rates = this.getAwardFandaRate(); Calendar calendar = Calendar.getInstance(); int currentYear = calendar.get(Calendar.YEAR); AwardFandaRate currentFandaRate; // when both On and Off campus rates are in, send the higher one. Ideally only one should be there // the single rate validation parameter needs to be set on award ScaleTwoDecimal currentRateValue = new ScaleTwoDecimal(0.0); currentFandaRate = rates.get(0); for (AwardFandaRate rate : rates) { if (Integer.parseInt(rate.getFiscalYear()) == currentYear) { if (rate.getApplicableFandaRate().isGreaterThan(currentRateValue)) { currentFandaRate = rate; currentRateValue = rate.getApplicableFandaRate(); } } } return currentFandaRate; } public String getParentTypeName(){ return "Award"; } @Override public String getAssociatedDocumentId() { return getAwardNumber(); } public String getAwardSequenceStatus() { return awardSequenceStatus; } public void setAwardSequenceStatus(String awardSequenceStatus) { this.awardSequenceStatus = awardSequenceStatus; } @Override public ProposalType getNegotiableProposalType() { return null; } @Override public String getSubAwardRequisitionerName() { return EMPTY_STRING; } @Override public String getSubAwardRequisitionerUnitNumber() { return EMPTY_STRING; } @Override public String getSubAwardRequisitionerUnitName() { return EMPTY_STRING; } @Override public String getSubAwardRequisitionerId() { return EMPTY_STRING; } public List<SubAward> getSubAwardList() { return subAwardList; } public void setSubAwardList(List<SubAward> subAwardList) { this.subAwardList = subAwardList; } @Override public String getProjectName() { return getTitle(); } @Override public String getProjectId() { return getAwardNumber(); } public boolean isAllowUpdateTimestampToBeReset() { return allowUpdateTimestampToBeReset; } /** * * Setting this value to false will prevent the update timestamp field from being upddate just once. After that, the update timestamp field will update as regular. * @param allowUpdateTimestampToBeReset */ public void setAllowUpdateTimestampToBeReset(boolean allowUpdateTimestampToBeReset) { this.allowUpdateTimestampToBeReset = allowUpdateTimestampToBeReset; } @Override public void setUpdateTimestamp(Timestamp updateTimestamp) { if (isAllowUpdateTimestampToBeReset()) { super.setUpdateTimestamp(updateTimestamp); } else { setAllowUpdateTimestampToBeReset(true); } } public List<Award> getAwardVersions() { Map<String, String> fieldValues = new HashMap<String,String>(); fieldValues.put("awardNumber", getAwardNumber()); BusinessObjectService businessObjectService = KcServiceLocator.getService(BusinessObjectService.class); List<Award> awards = (List<Award>)businessObjectService.findMatchingOrderBy(Award.class, fieldValues, "sequenceNumber", true); return awards; } public String getAwardDescriptionLine() { AwardAmountInfo aai = getLastAwardAmountInfo(); String transactionTypeDescription; String versionNumber; if(aai == null || aai.getOriginatingAwardVersion() == null) { versionNumber = getSequenceNumber().toString(); }else { versionNumber = aai.getOriginatingAwardVersion().toString(); } if(!(getAwardTransactionType() == null)) { transactionTypeDescription = getAwardTransactionType().getDescription(); }else { transactionTypeDescription = "None"; } return "Award Version " + versionNumber + ", " + transactionTypeDescription + ", updated " + getUpdateTimeAndUser(); } public String getUpdateTimeAndUser() { String createDateStr = null; String updateUser = null; if (getUpdateTimestamp() != null) { createDateStr = CoreApiServiceLocator.getDateTimeService().toString(getUpdateTimestamp(), "hh:mm:ss a MM/dd/yyyy"); updateUser = getUpdateUser().length() > 30 ? getUpdateUser().substring(0, 30) : getUpdateUser(); } return createDateStr + ", by " + updateUser; } public List<TimeAndMoneyDocumentHistory>getTimeAndMoneyDocumentHistoryList() throws WorkflowException { List<TimeAndMoneyDocument> tnmDocs = getTimeAndMoneyHistoryService().buildTimeAndMoneyListForAwardDisplay(this); List<TimeAndMoneyDocumentHistory> timeAndMoneyHistoryList = getTimeAndMoneyHistoryService().getDocHistoryAndValidInfosAssociatedWithAwardVersion(tnmDocs,getAwardAmountInfos(), this); return timeAndMoneyHistoryList; } public VersionHistorySearchBo getVersionHistory() { return versionHistory; } public void setVersionHistory(VersionHistorySearchBo versionHistory) { this.versionHistory = versionHistory; } public void setProjectPersons(List<AwardPerson> projectPersons) { this.projectPersons = projectPersons; } protected KcPersonService getKcPersonService() { if (this.kcPersonService == null) { this.kcPersonService = KcServiceLocator.getService(KcPersonService.class); } return this.kcPersonService; } /* * This method is used by the tag file to display the F&A rate totals. * Needed to convert to KualiDecimal to avoid rounding issues. */ public KualiDecimal getFandATotals() { KualiDecimal total = new KualiDecimal(0); for (AwardFandaRate currentRate : getAwardFandaRate()) { if (currentRate.getUnderrecoveryOfIndirectCost() != null) { total = total.add(new KualiDecimal(currentRate.getUnderrecoveryOfIndirectCost().bigDecimalValue())); } } return total; } @Override public boolean isProposalBudget() { return false; } @Override public BudgetParentDocument<Award> getDocument() { return getAwardDocument(); } @Override public Budget getNewBudget() { return new AwardBudgetExt(); } private List<AwardBudgetExt> budgets; public List<AwardBudgetExt> getBudgetVersionOverviews() { return budgets; } public void setBudgetVersionOverviews( List<AwardBudgetExt> budgetVersionOverviews) { this.budgets = budgetVersionOverviews; } @Override public Integer getNextBudgetVersionNumber() { return getAwardDocument().getNextBudgetVersionNumber(); } public List<AwardBudgetExt> getBudgets() { return budgets; } public void setBudgets(List<AwardBudgetExt> budgets) { this.budgets = budgets; } /* * This method will return true when the Active award is editing */ public boolean isEditAward() { return editAward; } public void setEditAward(boolean editAward) { this.editAward = editAward; } }
MITKC-755
kcmit-impl/src/main/java/org/kuali/kra/award/home/Award.java
MITKC-755
<ide><path>cmit-impl/src/main/java/org/kuali/kra/award/home/Award.java <ide> import org.springframework.util.AutoPopulatingList; <ide> <ide> import edu.mit.kc.coi.KcCoiLinkService; <del>import edu.mit.kc.coi.KcCoiLinkServiceImpl; <del> <ide> import java.sql.Date; <ide> import java.sql.SQLException; <ide> import java.sql.Timestamp; <ide> Logger LOGGER; <ide> <ide> @Qualifier("globalVariableService") <del> private GlobalVariableService globalVariableService; <add> private transient GlobalVariableService globalVariableService; <ide> public GlobalVariableService getGlobalVariableService() { <ide> <ide> if (globalVariableService == null) { <ide> } <ide> <ide> <del> public KcCoiLinkService kcCoiLinkService; <add> private transient KcCoiLinkService kcCoiLinkService; <ide> <ide> public KcCoiLinkService getKcCoiLinkService() { <ide> if (kcCoiLinkService == null) {
JavaScript
apache-2.0
c76b6199ae97b4e8bc1d90cac5e604104fc7d7d8
0
bumgardnera07/bloc-jams-angular,bumgardnera07/bloc-jams-angular
(function() { function SongPlayer() { /** * @desc object returned by the songplayer service for public use * @type {Object} */ var SongPlayer = {}; /** * @desc current song object from album songs array * @type {Object} */ var currentSong = null; /** * @desc Buzz object audio file * @type {Object} */ var currentBuzzObject = null; /** * @function playSong * @desc Plays currently scoped song and sets playing property to true */ var playSong = function() { currentBuzzObject.play(); song.playing = true; } /** * @function setSong * @desc Stops currently playing song and loads new audio file as currentBuzzObject * @param {Object} song */ var setSong = function(song) { if (currentBuzzObject) { currentBuzzObject.stop(); currentSong.playing = null; } currentBuzzObject = new buzz.sound(song.audioUrl, { formats: ['mp3'], preload: true }); currentSong = song; }; /** * @function .play * @desc public method for switching songs and playing songs when none are playing * @param {Object} song */ SongPlayer.play = function(song) { if (currentSong !== song) { setSong(song); playSong(); } else if (currentSong === song) { if (currentBuzzObject.isPaused()) { playSong(); } } }; /** * @function .pause * @desc public method for pausing the song * @param {Object} song */ SongPlayer.pause = function(song) { currentBuzzObject.pause(); song.playing = false; }; return SongPlayer; } angular .module('blocJams') .factory('SongPlayer', SongPlayer); })();
app/scripts/services/SongPlayer.js
(function() { function SongPlayer() { var SongPlayer = {}; var currentSong = null; /** * @desc Buzz object audio file * @type {Object} */ var currentBuzzObject = null; /** * @function setSong * @desc Stops currently playing song and loads new audio file as currentBuzzObject * @param {Object} song */ var setSong = function(song) { if (currentBuzzObject) { currentBuzzObject.stop(); currentSong.playing = null; } currentBuzzObject = new buzz.sound(song.audioUrl, { formats: ['mp3'], preload: true }); currentSong = song; }; SongPlayer.play = function(song) { if (currentSong !== song) { setSong(song); currentBuzzObject.play(); song.playing = true; } else if (currentSong === song) { if (currentBuzzObject.isPaused()) { currentBuzzObject.play(); } } }; SongPlayer.pause = function(song) { currentBuzzObject.pause(); song.playing = false; }; return SongPlayer; } angular .module('blocJams') .factory('SongPlayer', SongPlayer); })();
documentation added
app/scripts/services/SongPlayer.js
documentation added
<ide><path>pp/scripts/services/SongPlayer.js <ide> (function() { <ide> function SongPlayer() { <add> /** <add> * @desc object returned by the songplayer service for public use <add> * @type {Object} <add> */ <ide> var SongPlayer = {}; <del> <add> /** <add> * @desc current song object from album songs array <add> * @type {Object} <add> */ <ide> var currentSong = null; <ide> /** <ide> * @desc Buzz object audio file <ide> * @type {Object} <ide> */ <ide> var currentBuzzObject = null; <add> /** <add> * @function playSong <add> * @desc Plays currently scoped song and sets playing property to true <add> */ <add> var playSong = function() { <add> currentBuzzObject.play(); <add> song.playing = true; <add> } <ide> /** <ide> * @function setSong <ide> * @desc Stops currently playing song and loads new audio file as currentBuzzObject <ide> <ide> currentSong = song; <ide> }; <del> SongPlayer.play = function(song) { <add> <add> /** <add> * @function .play <add> * @desc public method for switching songs and playing songs when none are playing <add> * @param {Object} song <add> */ <add> SongPlayer.play = function(song) { <ide> if (currentSong !== song) { <ide> setSong(song); <del> currentBuzzObject.play(); <del> song.playing = true; <add> playSong(); <ide> } else if (currentSong === song) { <ide> if (currentBuzzObject.isPaused()) { <del> currentBuzzObject.play(); <add> playSong(); <ide> } <ide> } <ide> }; <del> <add> /** <add> * @function .pause <add> * @desc public method for pausing the song <add> * @param {Object} song <add> */ <ide> SongPlayer.pause = function(song) { <ide> currentBuzzObject.pause(); <ide> song.playing = false;
Java
lgpl-2.1
414595b68f3edf7bf7e6e695362cdb86fd58fc98
0
jensopetersen/exist,zwobit/exist,zwobit/exist,jensopetersen/exist,ambs/exist,hungerburg/exist,patczar/exist,zwobit/exist,eXist-db/exist,wolfgangmm/exist,wshager/exist,windauer/exist,RemiKoutcherawy/exist,olvidalo/exist,windauer/exist,zwobit/exist,joewiz/exist,kohsah/exist,dizzzz/exist,zwobit/exist,lcahlander/exist,patczar/exist,ambs/exist,joewiz/exist,kohsah/exist,olvidalo/exist,RemiKoutcherawy/exist,wolfgangmm/exist,RemiKoutcherawy/exist,windauer/exist,patczar/exist,opax/exist,joewiz/exist,kohsah/exist,lcahlander/exist,opax/exist,zwobit/exist,jensopetersen/exist,wshager/exist,kohsah/exist,ljo/exist,hungerburg/exist,jensopetersen/exist,joewiz/exist,wshager/exist,joewiz/exist,RemiKoutcherawy/exist,adamretter/exist,opax/exist,opax/exist,olvidalo/exist,joewiz/exist,eXist-db/exist,adamretter/exist,lcahlander/exist,hungerburg/exist,eXist-db/exist,wolfgangmm/exist,eXist-db/exist,RemiKoutcherawy/exist,opax/exist,adamretter/exist,dizzzz/exist,windauer/exist,patczar/exist,jensopetersen/exist,ljo/exist,ambs/exist,olvidalo/exist,eXist-db/exist,adamretter/exist,wolfgangmm/exist,hungerburg/exist,wolfgangmm/exist,patczar/exist,wshager/exist,ambs/exist,wshager/exist,wolfgangmm/exist,ambs/exist,eXist-db/exist,dizzzz/exist,ljo/exist,dizzzz/exist,dizzzz/exist,hungerburg/exist,windauer/exist,ljo/exist,dizzzz/exist,adamretter/exist,windauer/exist,lcahlander/exist,RemiKoutcherawy/exist,wshager/exist,patczar/exist,ljo/exist,adamretter/exist,lcahlander/exist,olvidalo/exist,lcahlander/exist,ljo/exist,kohsah/exist,ambs/exist,jensopetersen/exist,kohsah/exist
/* * eXist Open Source Native XML Database * Copyright (C) 2010 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * $Id$ */ package org.exist.xquery.modules.file; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.file.Files; import java.nio.file.Path; import java.util.Properties; import javax.xml.transform.OutputKeys; import static java.nio.file.StandardOpenOption.APPEND; import static java.nio.file.StandardOpenOption.CREATE; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.dom.QName; import org.exist.storage.serializers.Serializer; import org.exist.xquery.BasicFunction; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionSignature; import org.exist.xquery.Option; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.util.SerializerUtils; import org.exist.xquery.value.*; import org.xml.sax.SAXException; public class SerializeToFile extends BasicFunction { private final static Logger logger = LogManager.getLogger(SerializeToFile.class); private final static String FN_SERIALIZE_LN = "serialize"; private final static String FN_SERIALIZE_BINARY_LN = "serialize-binary"; public final static FunctionSignature signatures[] = { new FunctionSignature( new QName( FN_SERIALIZE_LN, FileModule.NAMESPACE_URI, FileModule.PREFIX ), "Writes the node set into a file on the file system. $parameters contains a " + "sequence of zero or more serialization parameters specified as key=value pairs. The " + "serialization options are the same as those recognized by \"declare option exist:serialize\". " + "The function does NOT automatically inherit the serialization options of the XQuery it is " + "called from. This method is only available to the DBA role.", new SequenceType[] { new FunctionParameterSequenceType( "node-set", Type.NODE, Cardinality.ZERO_OR_MORE, "The contents to write to the file system." ), new FunctionParameterSequenceType( "path", Type.ITEM, Cardinality.EXACTLY_ONE, "The full path or URI to the file" ), new FunctionParameterSequenceType( "parameters", Type.ITEM, Cardinality.ZERO_OR_MORE, "The serialization parameters: either a sequence of key=value pairs or an output:serialization-parameters " + "element as defined by the standard fn:serialize function." ) }, new FunctionReturnSequenceType( Type.BOOLEAN, Cardinality.ZERO_OR_ONE, "true on success - false if the specified file can not be " + "created or is not writable. The empty sequence is returned if the argument sequence is empty." ) ), new FunctionSignature( new QName( FN_SERIALIZE_LN, FileModule.NAMESPACE_URI, FileModule.PREFIX ), "Writes the node set into a file on the file system, optionally appending to it. " + "$parameters contains a sequence of zero or more serialization parameters specified as " + "key=value pairs. The serialization options are the same as those recognized by " + "\"declare option exist:serialize\". " + "The function does NOT automatically inherit the serialization options of the XQuery it is " + "called from. This method is only available to the DBA role.", new SequenceType[] { new FunctionParameterSequenceType( "node-set", Type.NODE, Cardinality.ZERO_OR_MORE, "The contents to write to the file system." ), new FunctionParameterSequenceType( "path", Type.ITEM, Cardinality.EXACTLY_ONE, "The full path or URI to the file" ), new FunctionParameterSequenceType( "parameters", Type.ITEM, Cardinality.ZERO_OR_MORE, "The serialization parameters: either a sequence of key=value pairs or an output:serialization-parameters " + "element as defined by the standard fn:serialize function." ), new FunctionParameterSequenceType( "append", Type.BOOLEAN, Cardinality.EXACTLY_ONE, "Should content be appended?") }, new FunctionReturnSequenceType( Type.BOOLEAN, Cardinality.ZERO_OR_ONE, "true on success - false if the specified file can " + "not be created or is not writable. The empty sequence is returned if the argument sequence is empty." ) ), new FunctionSignature( new QName(FN_SERIALIZE_BINARY_LN, FileModule.NAMESPACE_URI, FileModule.PREFIX), "Writes binary data into a file on the file system. This method is only available to the DBA role.", new SequenceType[]{ new FunctionParameterSequenceType("binarydata", Type.BASE64_BINARY, Cardinality.EXACTLY_ONE, "The contents to write to the file system."), new FunctionParameterSequenceType("path", Type.ITEM, Cardinality.EXACTLY_ONE, "The full path or URI to the file") }, new FunctionReturnSequenceType(Type.BOOLEAN, Cardinality.EXACTLY_ONE, "true on success - false if the specified file can not be created or is not writable") ), new FunctionSignature( new QName(FN_SERIALIZE_BINARY_LN, FileModule.NAMESPACE_URI, FileModule.PREFIX), "Writes binary data into a file on the file system, optionally appending the content. This method is only available to the DBA role.", new SequenceType[]{ new FunctionParameterSequenceType("binarydata", Type.BASE64_BINARY, Cardinality.EXACTLY_ONE, "The contents to write to the file system."), new FunctionParameterSequenceType("path", Type.ITEM, Cardinality.EXACTLY_ONE, "The full path or URI to the file"), new FunctionParameterSequenceType("append", Type.BOOLEAN, Cardinality.EXACTLY_ONE, "Should content be appended?") }, new FunctionReturnSequenceType(Type.BOOLEAN, Cardinality.EXACTLY_ONE, "true on success - false if the specified file can not be created or is not writable") ) }; public SerializeToFile(final XQueryContext context, final FunctionSignature signature) { super(context, signature); } @Override public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException { if(args[0].isEmpty()) { return Sequence.EMPTY_SEQUENCE; } if(!context.getSubject().hasDbaRole()) { final XPathException xPathException = new XPathException(this, "Permission denied, calling user '" + context.getSubject().getName() + "' must be a DBA to call this function."); logger.error("Invalid user", xPathException); throw xPathException; } //check the file output path final String inputPath = args[1].getStringValue(); final Path file = FileModuleHelper.getFile(inputPath); if(Files.isDirectory(file)) { logger.debug("Cannot serialize file. Output file is a directory: " + file.toAbsolutePath().toString()); return BooleanValue.FALSE; } if(Files.exists(file) && !Files.isWritable(file)) { logger.debug("Cannot serialize file. Cannot write to file " + file.toAbsolutePath().toString() ); return BooleanValue.FALSE; } if(isCalledAs(FN_SERIALIZE_LN)) { //parse serialization options from third argument to function final Properties outputProperties = parseXMLSerializationOptions( args[2] ); final boolean doAppend = (args.length > 3) && "true".equals(args[3].itemAt(0).getStringValue()); //do the serialization serializeXML(args[0].iterate(), outputProperties, file, doAppend); } else if(isCalledAs(FN_SERIALIZE_BINARY_LN)) { final boolean doAppend = (args.length > 2) && "true".equals(args[2].itemAt(0).getStringValue()); serializeBinary((BinaryValue)args[0].itemAt(0), file, doAppend); } else { throw new XPathException(this, "Unknown function name"); } return BooleanValue.TRUE; } private Properties parseXMLSerializationOptions(final Sequence sSerializeParams) throws XPathException { //parse serialization options final Properties outputProperties = new Properties(); outputProperties.setProperty( OutputKeys.INDENT, "yes" ); outputProperties.setProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" ); if (sSerializeParams.hasOne() && Type.subTypeOf(sSerializeParams.getItemType(), Type.NODE)) { SerializerUtils.getSerializationOptions(this, (NodeValue) sSerializeParams.itemAt(0), outputProperties); } else { SequenceIterator siSerializeParams = sSerializeParams.iterate(); while(siSerializeParams.hasNext()) { final String serializeParam = siSerializeParams.nextItem().getStringValue(); final String opt[] = Option.parseKeyValuePair(serializeParam); if(opt != null && opt.length == 2) { outputProperties.setProperty( opt[0], opt[1] ); } } } return outputProperties; } private void serializeXML(final SequenceIterator siNode, final Properties outputProperties, final Path file, final boolean doAppend) throws XPathException { final Serializer serializer = context.getBroker().getSerializer(); serializer.reset(); try(final OutputStream os = Files.newOutputStream(file, doAppend ? APPEND : CREATE); final Writer writer = new OutputStreamWriter(os)) { serializer.setProperties(outputProperties); while(siNode.hasNext()) { final NodeValue nv = (NodeValue)siNode.nextItem(); serializer.serialize(nv, writer); } } catch(final IOException | SAXException e) { throw new XPathException(this, "Cannot serialize file. A problem occurred while serializing the node set: " + e.getMessage(), e); } } private void serializeBinary(final BinaryValue binary, final Path file, final boolean doAppend) throws XPathException { try(final OutputStream os = Files.newOutputStream(file, doAppend ? APPEND : CREATE)) { binary.streamBinaryTo(os); } catch(final IOException ioe) { throw new XPathException(this, "Cannot serialize file. A problem occurred while serializing the binary data: " + ioe.getMessage(), ioe); } } }
extensions/modules/src/org/exist/xquery/modules/file/SerializeToFile.java
/* * eXist Open Source Native XML Database * Copyright (C) 2010 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * $Id$ */ package org.exist.xquery.modules.file; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.file.Files; import java.nio.file.Path; import java.util.Properties; import javax.xml.transform.OutputKeys; import static java.nio.file.StandardOpenOption.APPEND; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.dom.QName; import org.exist.storage.serializers.Serializer; import org.exist.xquery.BasicFunction; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionSignature; import org.exist.xquery.Option; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.util.SerializerUtils; import org.exist.xquery.value.*; import org.xml.sax.SAXException; public class SerializeToFile extends BasicFunction { private final static Logger logger = LogManager.getLogger(SerializeToFile.class); private final static String FN_SERIALIZE_LN = "serialize"; private final static String FN_SERIALIZE_BINARY_LN = "serialize-binary"; public final static FunctionSignature signatures[] = { new FunctionSignature( new QName( FN_SERIALIZE_LN, FileModule.NAMESPACE_URI, FileModule.PREFIX ), "Writes the node set into a file on the file system. $parameters contains a " + "sequence of zero or more serialization parameters specified as key=value pairs. The " + "serialization options are the same as those recognized by \"declare option exist:serialize\". " + "The function does NOT automatically inherit the serialization options of the XQuery it is " + "called from. This method is only available to the DBA role.", new SequenceType[] { new FunctionParameterSequenceType( "node-set", Type.NODE, Cardinality.ZERO_OR_MORE, "The contents to write to the file system." ), new FunctionParameterSequenceType( "path", Type.ITEM, Cardinality.EXACTLY_ONE, "The full path or URI to the file" ), new FunctionParameterSequenceType( "parameters", Type.ITEM, Cardinality.ZERO_OR_MORE, "The serialization parameters: either a sequence of key=value pairs or an output:serialization-parameters " + "element as defined by the standard fn:serialize function." ) }, new FunctionReturnSequenceType( Type.BOOLEAN, Cardinality.ZERO_OR_ONE, "true on success - false if the specified file can not be " + "created or is not writable. The empty sequence is returned if the argument sequence is empty." ) ), new FunctionSignature( new QName( FN_SERIALIZE_LN, FileModule.NAMESPACE_URI, FileModule.PREFIX ), "Writes the node set into a file on the file system, optionally appending to it. " + "$parameters contains a sequence of zero or more serialization parameters specified as " + "key=value pairs. The serialization options are the same as those recognized by " + "\"declare option exist:serialize\". " + "The function does NOT automatically inherit the serialization options of the XQuery it is " + "called from. This method is only available to the DBA role.", new SequenceType[] { new FunctionParameterSequenceType( "node-set", Type.NODE, Cardinality.ZERO_OR_MORE, "The contents to write to the file system." ), new FunctionParameterSequenceType( "path", Type.ITEM, Cardinality.EXACTLY_ONE, "The full path or URI to the file" ), new FunctionParameterSequenceType( "parameters", Type.ITEM, Cardinality.ZERO_OR_MORE, "The serialization parameters: either a sequence of key=value pairs or an output:serialization-parameters " + "element as defined by the standard fn:serialize function." ), new FunctionParameterSequenceType( "append", Type.BOOLEAN, Cardinality.EXACTLY_ONE, "Should content be appended?") }, new FunctionReturnSequenceType( Type.BOOLEAN, Cardinality.ZERO_OR_ONE, "true on success - false if the specified file can " + "not be created or is not writable. The empty sequence is returned if the argument sequence is empty." ) ), new FunctionSignature( new QName(FN_SERIALIZE_BINARY_LN, FileModule.NAMESPACE_URI, FileModule.PREFIX), "Writes binary data into a file on the file system. This method is only available to the DBA role.", new SequenceType[]{ new FunctionParameterSequenceType("binarydata", Type.BASE64_BINARY, Cardinality.EXACTLY_ONE, "The contents to write to the file system."), new FunctionParameterSequenceType("path", Type.ITEM, Cardinality.EXACTLY_ONE, "The full path or URI to the file") }, new FunctionReturnSequenceType(Type.BOOLEAN, Cardinality.EXACTLY_ONE, "true on success - false if the specified file can not be created or is not writable") ), new FunctionSignature( new QName(FN_SERIALIZE_BINARY_LN, FileModule.NAMESPACE_URI, FileModule.PREFIX), "Writes binary data into a file on the file system, optionally appending the content. This method is only available to the DBA role.", new SequenceType[]{ new FunctionParameterSequenceType("binarydata", Type.BASE64_BINARY, Cardinality.EXACTLY_ONE, "The contents to write to the file system."), new FunctionParameterSequenceType("path", Type.ITEM, Cardinality.EXACTLY_ONE, "The full path or URI to the file"), new FunctionParameterSequenceType("append", Type.BOOLEAN, Cardinality.EXACTLY_ONE, "Should content be appended?") }, new FunctionReturnSequenceType(Type.BOOLEAN, Cardinality.EXACTLY_ONE, "true on success - false if the specified file can not be created or is not writable") ) }; public SerializeToFile(final XQueryContext context, final FunctionSignature signature) { super(context, signature); } @Override public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException { if(args[0].isEmpty()) { return Sequence.EMPTY_SEQUENCE; } if(!context.getSubject().hasDbaRole()) { final XPathException xPathException = new XPathException(this, "Permission denied, calling user '" + context.getSubject().getName() + "' must be a DBA to call this function."); logger.error("Invalid user", xPathException); throw xPathException; } //check the file output path final String inputPath = args[1].getStringValue(); final Path file = FileModuleHelper.getFile(inputPath); if(Files.isDirectory(file)) { logger.debug("Cannot serialize file. Output file is a directory: " + file.toAbsolutePath().toString()); return BooleanValue.FALSE; } if(Files.exists(file) && !Files.isWritable(file)) { logger.debug("Cannot serialize file. Cannot write to file " + file.toAbsolutePath().toString() ); return BooleanValue.FALSE; } if(isCalledAs(FN_SERIALIZE_LN)) { //parse serialization options from third argument to function final Properties outputProperties = parseXMLSerializationOptions( args[2] ); final boolean doAppend = (args.length > 3) && "true".equals(args[3].itemAt(0).getStringValue()); //do the serialization serializeXML(args[0].iterate(), outputProperties, file, doAppend); } else if(isCalledAs(FN_SERIALIZE_BINARY_LN)) { final boolean doAppend = (args.length > 2) && "true".equals(args[2].itemAt(0).getStringValue()); serializeBinary((BinaryValue)args[0].itemAt(0), file, doAppend); } else { throw new XPathException(this, "Unknown function name"); } return BooleanValue.TRUE; } private Properties parseXMLSerializationOptions(final Sequence sSerializeParams) throws XPathException { //parse serialization options final Properties outputProperties = new Properties(); outputProperties.setProperty( OutputKeys.INDENT, "yes" ); outputProperties.setProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" ); if (sSerializeParams.hasOne() && Type.subTypeOf(sSerializeParams.getItemType(), Type.NODE)) { SerializerUtils.getSerializationOptions(this, (NodeValue) sSerializeParams.itemAt(0), outputProperties); } else { SequenceIterator siSerializeParams = sSerializeParams.iterate(); while(siSerializeParams.hasNext()) { final String serializeParam = siSerializeParams.nextItem().getStringValue(); final String opt[] = Option.parseKeyValuePair(serializeParam); if(opt != null && opt.length == 2) { outputProperties.setProperty( opt[0], opt[1] ); } } } return outputProperties; } private void serializeXML(final SequenceIterator siNode, final Properties outputProperties, final Path file, final boolean doAppend) throws XPathException { final Serializer serializer = context.getBroker().getSerializer(); serializer.reset(); try(final OutputStream os = Files.newOutputStream(file, doAppend ? APPEND : TRUNCATE_EXISTING); final Writer writer = new OutputStreamWriter(os)) { serializer.setProperties(outputProperties); while(siNode.hasNext()) { final NodeValue nv = (NodeValue)siNode.nextItem(); serializer.serialize(nv, writer); } } catch(final IOException | SAXException e) { throw new XPathException(this, "Cannot serialize file. A problem occurred while serializing the node set: " + e.getMessage(), e); } } private void serializeBinary(final BinaryValue binary, final Path file, final boolean doAppend) throws XPathException { try(final OutputStream os = Files.newOutputStream(file, doAppend ? APPEND : TRUNCATE_EXISTING)) { binary.streamBinaryTo(os); } catch(final IOException ioe) { throw new XPathException(this, "Cannot serialize file. A problem occurred while serializing the binary data: " + ioe.getMessage(), ioe); } } }
Fix for file:serialize and file:serialize-binary when working with NIO.2
extensions/modules/src/org/exist/xquery/modules/file/SerializeToFile.java
Fix for file:serialize and file:serialize-binary when working with NIO.2
<ide><path>xtensions/modules/src/org/exist/xquery/modules/file/SerializeToFile.java <ide> import java.util.Properties; <ide> import javax.xml.transform.OutputKeys; <ide> import static java.nio.file.StandardOpenOption.APPEND; <del>import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; <add>import static java.nio.file.StandardOpenOption.CREATE; <ide> <ide> import org.apache.logging.log4j.LogManager; <ide> import org.apache.logging.log4j.Logger; <ide> final Serializer serializer = context.getBroker().getSerializer(); <ide> serializer.reset(); <ide> <del> try(final OutputStream os = Files.newOutputStream(file, doAppend ? APPEND : TRUNCATE_EXISTING); <add> try(final OutputStream os = Files.newOutputStream(file, doAppend ? APPEND : CREATE); <ide> final Writer writer = new OutputStreamWriter(os)) { <ide> <ide> serializer.setProperties(outputProperties); <ide> } <ide> <ide> private void serializeBinary(final BinaryValue binary, final Path file, final boolean doAppend) throws XPathException { <del> try(final OutputStream os = Files.newOutputStream(file, doAppend ? APPEND : TRUNCATE_EXISTING)) { <add> try(final OutputStream os = Files.newOutputStream(file, doAppend ? APPEND : CREATE)) { <ide> binary.streamBinaryTo(os); <ide> } catch(final IOException ioe) { <ide> throw new XPathException(this, "Cannot serialize file. A problem occurred while serializing the binary data: " + ioe.getMessage(), ioe);
Java
apache-2.0
b75be9c20edda8731e3d802b52a23ff1fce34b94
0
wyona/yanel,baszero/yanel,baszero/yanel,wyona/yanel,baszero/yanel,baszero/yanel,wyona/yanel,wyona/yanel,baszero/yanel,wyona/yanel,baszero/yanel,wyona/yanel
package org.wyona.yanel.servlet; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.HashMap; import org.apache.commons.io.IOUtils; import org.wyona.yanel.core.Environment; import org.wyona.yanel.core.ResourceConfiguration; import org.wyona.yanel.core.map.Realm; import org.apache.log4j.Logger; /** * Resource type matcher for all global resources */ class YanelGlobalResourceTypeMatcher { private static Logger log = Logger.getLogger(YanelGlobalResourceTypeMatcher.class); private String pathPrefix; private String globalRCsBasePath; public YanelGlobalResourceTypeMatcher(String pathPrefix, String globalRCsBasePath) { this.pathPrefix = pathPrefix; this.globalRCsBasePath = globalRCsBasePath; } /** * Get global resource configuration */ public ResourceConfiguration getResourceConfiguration(Environment environment, Realm realm, String path) throws Exception { log.debug("Get global resource config: " + path); java.util.Map<String, String> properties = new HashMap<String, String>(); //XXX: maybe we should use a configuration file instead! java.util.Map<String, String> globalRCmap = new HashMap<String, String>(); globalRCmap.put("workflow-dashboard.html", "workflow-dashboard_yanel-rc.xml"); globalRCmap.put("session-manager.html", "session-manager_yanel-rc.xml"); globalRCmap.put("search.html", "search_yanel-rc.xml"); globalRCmap.put("data-repository-sitetree.html", "data-repo-sitetree_yanel-rc.xml"); globalRCmap.put("user-forgot-pw.html", "user-forgot-pw_yanel-rc.xml"); final String ADMIN_PREFIX = "admin/"; globalRCmap.put(ADMIN_PREFIX + "list-groups.html", "user-mgmt/list-groups_yanel-rc.xml"); globalRCmap.put(ADMIN_PREFIX + "list-users.html", "user-mgmt/list-users_yanel-rc.xml"); globalRCmap.put(ADMIN_PREFIX + "delete-group.html", "user-mgmt/delete-group_yanel-rc.xml"); globalRCmap.put(ADMIN_PREFIX + "create-group.html", "user-mgmt/create-group_yanel-rc.xml"); globalRCmap.put(ADMIN_PREFIX + "view-group.html", "user-mgmt/view-group_yanel-rc.xml"); globalRCmap.put(ADMIN_PREFIX + "delete-user.html", "user-mgmt/delete-user_yanel-rc.xml"); globalRCmap.put(ADMIN_PREFIX + "update-user.html", "user-mgmt/update-user_yanel-rc.xml"); globalRCmap.put(ADMIN_PREFIX + "create-user.html", "user-mgmt/create-user_yanel-rc.xml"); globalRCmap.put(ADMIN_PREFIX + "update-user-admin.html", "user-mgmt/update-user-admin_yanel-rc.xml"); final String API_PREFIX = "api/"; globalRCmap.put(API_PREFIX + "usermanager", "api/usermanager-api_yanel-rc.xml"); String pathSuffix = path.substring(pathPrefix.length()); String globalRCfilename = globalRCmap.get(pathSuffix); final String usersPathPrefix = pathPrefix + "users/"; if (path.startsWith(usersPathPrefix)) { log.warn("DEBUG: Get generic yanel resource config ..."); /* Deprecated final String userName = path.substring(usersPathPrefix.length(), path.length() - ".html".length()); properties.put("user", userName); properties.put("xslt", "rthtdocs:/yanel-user-profile.xsl"); properties.put("mime-type", "text/html"); // INFO: Because of IE we use text/html instead application/xhtml+xml return new ResourceConfiguration("yanel-user", "http://www.wyona.org/yanel/resource/1.0", properties); */ return getGlobalResourceConfiguration("user-profile_yanel-rc.xml", realm, globalRCsBasePath); } else if (globalRCfilename != null) { return getGlobalResourceConfiguration(globalRCfilename, realm, globalRCsBasePath); } else { log.debug("No such global resource configuration for path (nothing to worry about): " + path); return null; } } /** * Get resource configuration from global location of the realm or if not available there, then from global location of Yanel * * @param resConfigName Filename of resource configuration * @param realm Current realm */ static ResourceConfiguration getGlobalResourceConfiguration(String resConfigName, Realm realm, String globalRCsBasePath) { log.debug("Get global resource config, whereas check within realm first ..."); // TODO: Introduce a repository for the Yanel webapp File realmDir = new File(realm.getConfigFile().getParent()); File globalResConfigFile = org.wyona.commons.io.FileUtil.file(realmDir.getAbsolutePath(), "src" + File.separator + "webapp" + File.separator + "global-resource-configs/" + resConfigName); if (!globalResConfigFile.isFile()) { // Fallback to global configuration globalResConfigFile = org.wyona.commons.io.FileUtil.file(globalRCsBasePath, "global-resource-configs/" + resConfigName); } InputStream is; try { log.debug("Read resource config: " + globalResConfigFile); is = new java.io.FileInputStream(globalResConfigFile); } catch (FileNotFoundException e) { throw new RuntimeException(e); } try { return new ResourceConfiguration(is); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(is); } } }
src/webapp/src/java/org/wyona/yanel/servlet/YanelGlobalResourceTypeMatcher.java
package org.wyona.yanel.servlet; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.HashMap; import org.apache.commons.io.IOUtils; import org.wyona.yanel.core.Environment; import org.wyona.yanel.core.ResourceConfiguration; import org.wyona.yanel.core.map.Realm; import org.apache.log4j.Logger; /** * Resource type matcher for all global resources */ class YanelGlobalResourceTypeMatcher { private static Logger log = Logger.getLogger(YanelGlobalResourceTypeMatcher.class); private String pathPrefix; private String globalRCsBasePath; public YanelGlobalResourceTypeMatcher(String pathPrefix, String globalRCsBasePath) { this.pathPrefix = pathPrefix; this.globalRCsBasePath = globalRCsBasePath; } /** * Get global resource configuration */ public ResourceConfiguration getResourceConfiguration(Environment environment, Realm realm, String path) throws Exception { log.debug("Get global resource config: " + path); java.util.Map<String, String> properties = new HashMap<String, String>(); //XXX: maybe we should use a configuration file instead! java.util.Map<String, String> globalRCmap = new HashMap<String, String>(); globalRCmap.put("workflow-dashboard.html", "workflow-dashboard_yanel-rc.xml"); globalRCmap.put("session-manager.html", "session-manager_yanel-rc.xml"); globalRCmap.put("search.html", "search_yanel-rc.xml"); globalRCmap.put("data-repository-sitetree.html", "data-repo-sitetree_yanel-rc.xml"); globalRCmap.put("user-forgot-pw.html", "user-forgot-pw_yanel-rc.xml"); final String ADMIN_PREFIX = "admin/"; globalRCmap.put(ADMIN_PREFIX + "list-groups.html", "user-mgmt/list-groups_yanel-rc.xml"); globalRCmap.put(ADMIN_PREFIX + "list-users.html", "user-mgmt/list-users_yanel-rc.xml"); globalRCmap.put(ADMIN_PREFIX + "delete-group.html", "user-mgmt/delete-group_yanel-rc.xml"); globalRCmap.put(ADMIN_PREFIX + "create-group.html", "user-mgmt/create-group_yanel-rc.xml"); globalRCmap.put(ADMIN_PREFIX + "view-group.html", "user-mgmt/view-group_yanel-rc.xml"); globalRCmap.put(ADMIN_PREFIX + "delete-user.html", "user-mgmt/delete-user_yanel-rc.xml"); globalRCmap.put(ADMIN_PREFIX + "update-user.html", "user-mgmt/update-user_yanel-rc.xml"); globalRCmap.put(ADMIN_PREFIX + "create-user.html", "user-mgmt/create-user_yanel-rc.xml"); globalRCmap.put(ADMIN_PREFIX + "update-user-admin.html", "user-mgmt/update-user-admin_yanel-rc.xml"); final String API_PREFIX = "api/"; globalRCmap.put(API_PREFIX + "usermanager", "api/usermanager-api_yanel-rc.xml"); String pathSuffix = path.substring(pathPrefix.length()); String globalRCfilename = globalRCmap.get(pathSuffix); final String usersPathPrefix = pathPrefix + "users/"; if (path.startsWith(usersPathPrefix)) { log.debug("Get generic yanel resource config ..."); final String userName = path.substring(usersPathPrefix.length(), path.length() - ".html".length()); properties.put("user", userName); properties.put("xslt", "rthtdocs:/yanel-user-profile.xsl"); properties.put("mime-type", "text/html"); // INFO: Because of IE we use text/html instead application/xhtml+xml return new ResourceConfiguration("yanel-user", "http://www.wyona.org/yanel/resource/1.0", properties); } else if (globalRCfilename != null) { return getGlobalResourceConfiguration(globalRCfilename, realm, globalRCsBasePath); } else { log.debug("No such global resource configuration for path (nothing to worry about): " + path); return null; } } /** * Get resource configuration from global location of the realm or if not available there, then from global location of Yanel * * @param resConfigName Filename of resource configuration * @param realm Current realm */ static ResourceConfiguration getGlobalResourceConfiguration(String resConfigName, Realm realm, String globalRCsBasePath) { log.debug("Get global resource config, whereas check within realm first ..."); // TODO: Introduce a repository for the Yanel webapp File realmDir = new File(realm.getConfigFile().getParent()); File globalResConfigFile = org.wyona.commons.io.FileUtil.file(realmDir.getAbsolutePath(), "src" + File.separator + "webapp" + File.separator + "global-resource-configs/" + resConfigName); if (!globalResConfigFile.isFile()) { // Fallback to global configuration globalResConfigFile = org.wyona.commons.io.FileUtil.file(globalRCsBasePath, "global-resource-configs/" + resConfigName); } InputStream is; try { log.debug("Read resource config: " + globalResConfigFile); is = new java.io.FileInputStream(globalResConfigFile); } catch (FileNotFoundException e) { throw new RuntimeException(e); } try { return new ResourceConfiguration(is); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(is); } } }
use global resource configuration instead hardcoded
src/webapp/src/java/org/wyona/yanel/servlet/YanelGlobalResourceTypeMatcher.java
use global resource configuration instead hardcoded
<ide><path>rc/webapp/src/java/org/wyona/yanel/servlet/YanelGlobalResourceTypeMatcher.java <ide> <ide> //XXX: maybe we should use a configuration file instead! <ide> java.util.Map<String, String> globalRCmap = new HashMap<String, String>(); <add> <ide> globalRCmap.put("workflow-dashboard.html", "workflow-dashboard_yanel-rc.xml"); <ide> globalRCmap.put("session-manager.html", "session-manager_yanel-rc.xml"); <ide> globalRCmap.put("search.html", "search_yanel-rc.xml"); <ide> globalRCmap.put("data-repository-sitetree.html", "data-repo-sitetree_yanel-rc.xml"); <ide> globalRCmap.put("user-forgot-pw.html", "user-forgot-pw_yanel-rc.xml"); <add> <ide> final String ADMIN_PREFIX = "admin/"; <ide> globalRCmap.put(ADMIN_PREFIX + "list-groups.html", "user-mgmt/list-groups_yanel-rc.xml"); <ide> globalRCmap.put(ADMIN_PREFIX + "list-users.html", "user-mgmt/list-users_yanel-rc.xml"); <ide> globalRCmap.put(ADMIN_PREFIX + "update-user.html", "user-mgmt/update-user_yanel-rc.xml"); <ide> globalRCmap.put(ADMIN_PREFIX + "create-user.html", "user-mgmt/create-user_yanel-rc.xml"); <ide> globalRCmap.put(ADMIN_PREFIX + "update-user-admin.html", "user-mgmt/update-user-admin_yanel-rc.xml"); <add> <ide> final String API_PREFIX = "api/"; <ide> globalRCmap.put(API_PREFIX + "usermanager", "api/usermanager-api_yanel-rc.xml"); <ide> <ide> <ide> final String usersPathPrefix = pathPrefix + "users/"; <ide> if (path.startsWith(usersPathPrefix)) { <del> log.debug("Get generic yanel resource config ..."); <add> log.warn("DEBUG: Get generic yanel resource config ..."); <add>/* Deprecated <ide> final String userName = path.substring(usersPathPrefix.length(), path.length() - ".html".length()); <ide> properties.put("user", userName); <ide> properties.put("xslt", "rthtdocs:/yanel-user-profile.xsl"); <ide> properties.put("mime-type", "text/html"); // INFO: Because of IE we use text/html instead application/xhtml+xml <ide> return new ResourceConfiguration("yanel-user", "http://www.wyona.org/yanel/resource/1.0", properties); <add>*/ <add> return getGlobalResourceConfiguration("user-profile_yanel-rc.xml", realm, globalRCsBasePath); <ide> } else if (globalRCfilename != null) { <ide> return getGlobalResourceConfiguration(globalRCfilename, realm, globalRCsBasePath); <ide> } else {
JavaScript
mit
e8cef7a72f223782489757bbf0f4e83b2cbb7848
0
icetee/remote-ftp,mgrenier/remote-ftp
var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, $ = require('atom').$, FileView = require('./file-view'), View = require('atom').View; module.exports = DirectoryView = (function (parent) { __extends(DirectoryView, parent); function DirectoryView () { DirectoryView.__super__.constructor.apply(this, arguments); } DirectoryView.content = function () { return this.li({ 'class': 'directory entry list-nested-item collapsed' }, function () { this.div({ 'class': 'header list-item', 'outlet': 'header' }, function () { return this.span({ 'class': 'name icon', 'outlet': 'name' }) }.bind(this)); this.ol({ 'class': 'entries list-tree', 'outlet': 'entries' }); }.bind(this)); }; DirectoryView.prototype.initialize = function (directory) { //DirectoryView.__super__.initialize.apply(this, arguments); var self = this; self.item = directory; self.name.text(self.item.name); self.name.attr('data-name', self.item.name); self.name.attr('data-path', self.item.remote); self.name.addClass(self.item.type && self.item.type == 'l' ? 'icon-file-symlink-directory' : 'icon-file-directory') if (self.item.isExpanded || self.item.isRoot) self.expand(); // Trigger repaint self.item.$folders.onValue(function () { self.repaint(); }); self.item.$files.onValue(function () { self.repaint(); }); self.item.on('destroyed', function () { self.destroy(); }); self.repaint(); // Events self.on('mousedown', function (e) { e.stopPropagation(); var view = $(this).view(), button = e.originalEvent ? e.originalEvent.button : 0; if (!view) return; switch (button) { case 2: if (view.is('.selected')) return; default: if (!e.ctrlKey) $('.remote-ftp-view .selected').removeClass('selected'); view.toggleClass('selected'); if (button == 0) { if (view.item.status == 0) view.open(); if (button == 0) view.toggle(); else view.expand(); } } }); self.on('dblclick', function (e) { e.stopPropagation(); var view = $(this).view(); if (!view) return; view.open(); }); } DirectoryView.prototype.destroy = function () { this.item = null; this.remove(); } DirectoryView.prototype.repaint = function (recursive) { var self = this, views = self.entries.children().map(function () { return $(this).view(); }).get(), folders = [], files = []; self.entries.children().detach(); self.item.folders.forEach(function (item) { for (var a = 0, b = views.length; a < b; ++a) if (views[a] && views[a] instanceof DirectoryView && views[a].item == item) { folders.push(views[a]); return; } folders.push(new DirectoryView(item)); }); self.item.files.forEach(function (item) { for (var a = 0, b = views.length; a < b; ++a) if (views[a] && views[a] instanceof FileView && views[a].item == item) { files.push(views[a]); return; } files.push(new FileView(item)); }); // TODO Destroy left over... views = folders.concat(files); views.sort(function (a, b) { if (a.constructor != b.constructor) return a instanceof DirectoryView ? -1 : 1; if (a.item.name == b.item.name) return 0; return a.item.name.toLowerCase().localeCompare(b.item.name.toLowerCase()); }); views.forEach(function (view) { self.entries.append(view); }); } DirectoryView.prototype.expand = function (recursive) { this.addClass('expanded').removeClass('collapsed'); this.item.isExpanded = true; if (recursive) { this.entries.children().each(function () { var view = $(this).view(); if (view && view instanceof DirectoryView) view.expand(true); }); } } DirectoryView.prototype.collapse = function (recursive) { this.addClass('collapsed').removeClass('expanded'); this.item.isExpanded = false; if (recursive) { this.entries.children().each(function () { var view = $(this).view(); if (view && view instanceof DirectoryView) view.collapse(true); }); } } DirectoryView.prototype.toggle = function (recursive) { if (this.item.isExpanded) this.collapse(recursive); else this.expand(recursive); } DirectoryView.prototype.open = function () { this.item.open(); } DirectoryView.prototype.refresh = function () { this.item.open(); } return DirectoryView; })(View);
lib/views/directory-view.js
var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, $ = require('atom').$, FileView = require('./file-view'), View = require('atom').View; module.exports = DirectoryView = (function (parent) { __extends(DirectoryView, parent); function DirectoryView () { DirectoryView.__super__.constructor.apply(this, arguments); } DirectoryView.content = function () { return this.li({ 'class': 'directory entry list-nested-item collapsed' }, function () { this.div({ 'class': 'header list-item', 'outlet': 'header' }, function () { return this.span({ 'class': 'name icon', 'outlet': 'name' }) }.bind(this)); this.ol({ 'class': 'entries list-tree', 'outlet': 'entries' }); }.bind(this)); }; DirectoryView.prototype.initialize = function (directory) { //DirectoryView.__super__.initialize.apply(this, arguments); var self = this; self.item = directory; self.name.text(self.item.name); self.name.attr('data-name', self.item.name); self.name.attr('data-path', self.item.remote); self.name.addClass(self.item.type && self.item.type == 'l' ? 'icon-file-symlink-directory' : 'icon-file-directory') if (self.item.isExpanded || self.item.isRoot) self.expand(); // Trigger repaint self.item.$folders.onValue(function () { self.repaint(); }); self.item.$files.onValue(function () { self.repaint(); }); self.item.on('destroyed', function () { self.destroy(); }); self.repaint(); // Events self.on('mousedown', function (e) { e.stopPropagation(); var view = $(this).view(), button = e.originalEvent ? e.originalEvent.button : 0; if (!view) return; switch (button) { case 2: if (view.is('.selected')) return; default: if (!e.ctrlKey) $('.remote-ftp-view .selected').removeClass('selected'); view.toggleClass('selected'); if (button == 0) { if (view.item.status == 0) view.open(); if (button == 0) view.toggle(); else view.expand(); } } }); self.on('dblclick', function (e) { e.stopPropagation(); var view = $(this).view(); if (!view) return; view.open(); }); } DirectoryView.prototype.destroy = function () { this.item = null; this.remove(); } DirectoryView.prototype.repaint = function (recursive) { var self = this, views = self.entries.children().map(function () { return $(this).view(); }).get(), folders = [], files = []; self.entries.children().detach(); self.item.folders.forEach(function (item) { for (var a = 0, b = views.length; a < b; ++a) if (views[a] && views[a] instanceof DirectoryView && views[a].item == item) { folders.push(views[a]); return; } folders.push(new DirectoryView(item)); }); self.item.files.forEach(function (item) { for (var a = 0, b = views.length; a < b; ++a) if (views[a] && views[a] instanceof FileView && views[a].item == item) { files.push(views[a]); return; } files.push(new FileView(item)); }); // TODO Destroy left over... views = folders.concat(files); views.sort(function (a, b) { if (a.constructor != b.constructor) return a instanceof DirectoryView ? -1 : 1; if (a.item.name == b.item.name) return 0; return a.item.name > b.item.name ? 1 : -1; }); views.forEach(function (view) { self.entries.append(view); }); } DirectoryView.prototype.expand = function (recursive) { this.addClass('expanded').removeClass('collapsed'); this.item.isExpanded = true; if (recursive) { this.entries.children().each(function () { var view = $(this).view(); if (view && view instanceof DirectoryView) view.expand(true); }); } } DirectoryView.prototype.collapse = function (recursive) { this.addClass('collapsed').removeClass('expanded'); this.item.isExpanded = false; if (recursive) { this.entries.children().each(function () { var view = $(this).view(); if (view && view instanceof DirectoryView) view.collapse(true); }); } } DirectoryView.prototype.toggle = function (recursive) { if (this.item.isExpanded) this.collapse(recursive); else this.expand(recursive); } DirectoryView.prototype.open = function () { this.item.open(); } DirectoryView.prototype.refresh = function () { this.item.open(); } return DirectoryView; })(View);
Switch to case insensitive sorting Case sensitive sorting makes no sense
lib/views/directory-view.js
Switch to case insensitive sorting
<ide><path>ib/views/directory-view.js <ide> return a instanceof DirectoryView ? -1 : 1; <ide> if (a.item.name == b.item.name) <ide> return 0; <del> return a.item.name > b.item.name ? 1 : -1; <add> <add> return a.item.name.toLowerCase().localeCompare(b.item.name.toLowerCase()); <ide> }); <ide> <ide> views.forEach(function (view) {
Java
apache-2.0
81a654684d7fc8f40337e54c56b348abcc19ac07
0
carlosmontoyargz/Sistemas-Operativos-II
package administracion_de_memoria; /** * Clase que permite administrar una lista de segmentos de memoria mediante el * algoritmo del peor ajuste. * * @author carlosmontoya */ public class ListaPeorAjuste extends ListaSegmentos { public ListaPeorAjuste(int memoriaTotal) { super(memoriaTotal); } @Override protected synchronized Segmento buscarHueco(int longitud) { // Busca el primer hueco compatible Segmento mayor = super.buscarHueco(longitud, null, null); if (mayor != null) { int longitudMayor = mayor.getLongitud(); Segmento s = mayor.getSiguiente(); while (s != null) { if (s.isHueco() && s.getLongitud() > longitudMayor) { mayor = s; longitudMayor = mayor.getLongitud(); } else s = s.getSiguiente(); } } return mayor; } }
Sistemas-Operativos-II/src/administracion_de_memoria/ListaPeorAjuste.java
package administracion_de_memoria; /** * Clase que permite administrar una lista de segmentos de memoria mediante el * algoritmo del peor ajuste. * * @author carlosmontoya */ public class ListaPeorAjuste extends ListaSegmentos { public ListaPeorAjuste(int memoriaTotal) { super(memoriaTotal); } @Override protected Segmento buscarHueco(int longitud) { // Busca el primer hueco compatible Segmento mayor = super.buscarHueco(longitud, null, null); if (mayor != null) { int longitudMayor = mayor.getLongitud(); Segmento s = mayor.getSiguiente(); while (s != null) { if (s.isHueco() && s.getLongitud() > longitudMayor) { mayor = s; longitudMayor = mayor.getLongitud(); } else s = s.getSiguiente(); } } return mayor; } }
Metodos synchronized.
Sistemas-Operativos-II/src/administracion_de_memoria/ListaPeorAjuste.java
Metodos synchronized.
<ide><path>istemas-Operativos-II/src/administracion_de_memoria/ListaPeorAjuste.java <ide> } <ide> <ide> @Override <del> protected Segmento buscarHueco(int longitud) <add> protected synchronized Segmento buscarHueco(int longitud) <ide> { <ide> // Busca el primer hueco compatible <ide> Segmento mayor = super.buscarHueco(longitud, null, null);
Java
bsd-3-clause
1796642bea8a749e189095bc699368fa6ab22e59
0
lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon
/* * $Id$ */ /* Copyright (c) 2000-2015 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.plugin.atypon.wageningen; import java.io.*; import junit.framework.Test; import org.lockss.util.*; import org.lockss.config.ConfigManager; import org.lockss.config.Configuration; import org.lockss.daemon.PluginException; import org.lockss.plugin.ArchivalUnit; import org.lockss.plugin.FilterFactory; import org.lockss.plugin.PluginManager; import org.lockss.plugin.PluginTestUtil; import org.lockss.test.*; public class TestWageningenJournalsHtmlFilterFactory extends LockssTestCase { FilterFactory variantFact; ArchivalUnit wau; String tempDirPath; MockLockssDaemon daemon; PluginManager pluginMgr; private static final String PLUGIN_ID = "org.lockss.plugin.atypon.wageningen.ClockssWageningenJournalsPlugin"; private static final String filteredStr = "<div class=\"block\"></div>"; // breadcrumbs private static final String withBreadcrumbs = "<div class=\"block\">" + "<ul class=\"breadcrumbs\">" + "<li class=\"\"><a href=\"/\">Home</a>" + "<span class=\"divider\">></span></li>" + "<li class=\"\"><a href=\"/loi/jid\">ABC Journals</a>" + "<span class=\"divider\">></span></li>" + "<li class=\"\"><a href=\"/loi/jid\">issues</a>" + "<span class=\"divider\">></span></li>" + "<li class=\"\"><a href=\"/toc/jid/26/1\">Volume 9, Issue 9</a>" + "<span class=\"divider\">></span></li>" + "<li class=\"truncate\">The development of blah</li>" + "</ul>" + "</div>"; private static final String withAriaRelevant = "<div class=\"block\">" + "<div class=\"tabs tabs-widget\" aria-relevant=\"additions\" " + "aria-atomic=\"true\" aria-live=\"polite\">" + "<div class=\"tab-content\">" + "<div id=\"19a\" class=\"tab-pane active\">" + "<div data-pb-dropzone-name=\"Most Read\" " + "data-pb-dropzone=\"tab-59a\">" + "<div id=\"753\" class=\"widget literatumMostReadWidget none " + "widget-none widget-compact-all\">" + "<div class=\"widget-body body body-none body-compact-all\">" + "<section class=\"popular\">" + "<div class=\"mostRead\">" + "<ul>" + "<li><div class=\"title\">" + "<a href=\"/doi/abs/11.1111/jid.22.2.3\">Canada blah blah</a>" + "</div>" + "<div class=\"authors\">" + "<div class=\"contrib\">" + "<span class=\"authors\">Tim Ra</span>" + "</div></div></ul>" + "</div></section>" + "</div></div></div></div></div></div>" + "</div>"; private static final String withRelatedContent = "<div class=\"block\">" + "<div class=\"tab tab-pane\" id=\"relatedContent\"></div>" + "</div>"; // for testcrawl // from abs - all Articles Options and Tools except Download Citation private static final String withArticleToolsExceptDownloadCitation1 = "<div class=\"block\">" + "<div class=\"articleTools\">" + "<ul class=\"linkList blockLinks separators centered\">" + "<li class=\"addToFavs\"><a href=\"/linktoaddfav\">Add to Fav</a></li>" + "<li class=\"email\"><a href=\"/linktoemail\">Email friends</a></li>" + "<li class=\"downloadCitations\">" + "<a href=\"/action/showCitFormats?doi=10.3828%2Fjid.2013.2\">" + "Send to Citation Mgr</a>" + "</li></ul></div>" + "</div>"; // id tag also got filtered private static final String articleToolsFilteredStr1 = "<div class=\"block\">" + "<div class=\"articleTools\">" + "<ul class=\"linkList blockLinks separators centered\">" + "<li class=\"downloadCitations\">" + "<a href=\"/action/showCitFormats?doi=10.3828%2Fjid.2013.2\">" + "Send to Citation Mgr</a>" + "</li></ul></div>" + "</div>"; private static final String withPublicationToolContainer = "<div class=\"block\">" + "<div class=\"widget tocListWidget none widget-none " + "widget-compact-all\" id=\"3f3\">" + "<div class=\"widget-body body body-none body-compact-all\">" + "<fieldset class=\"tocListWidgetContainer\">" + "<div class=\"publicationToolContainer\">" + "<div class=\"publicationToolCheckboxContainer\">" + "<input type=\"checkbox\" name=\"markall\" id=\"markall\" " + "onclick=\"onClickMarkAll(frmAbs,'')\"><span>Select All</span>" + "</div>" + "<div class=\"publicationTooldropdownContainer\">" + "<span class=\"dropdownLabel\">" + "For selected items:" + "</span>" + "<select name=\"articleTool\" class=\"items-choice " + "publicationToolSelect\" title=\"Article Tools\">" + "<option value=\"\">Please select</option>" + "<option value=\"/addfav\">Add to Favorites</option>" + "<option value=\"/trackcit\">Track Citation</option>" + "<option value=\"/showcit\">Download Citation</option>" + "<option value=\"/emailto\">Email</option>" + "</select>" + "</div>" + "</div>" + "</fieldset>" + "</div>" + "</div>" + "</div>"; // attributes separated by 1 space private static final String publicationToolContainerFilteredStr = "<div class=\"widget tocListWidget none widget-none " + "widget-compact-all\" >" + "<div class=\"widget-body body body-none body-compact-all\">" + "<fieldset class=\"tocListWidgetContainer\">" + "</fieldset>" + "</div>" + "</div>"; private static final String withArticleMetaDrop = "<div class=\"block\">" + "<div class=\"widget literatumPublicationContentWidget none " + "widget-none\" id=\"1ca\">" + "<div class=\"articleMetaDrop publicationContentDropZone\" " + "data-pb-dropzone=\"articleMetaDropZone\">" + "</div>" + "</div>" + "</div>"; private static final String articleMetaDropFilteredStr = "<div class=\"widget literatumPublicationContentWidget none " + "widget-none\" >" + "</div>"; private static final String withArticleToolsExceptDownloadCitation2 = "<div class=\"block\">" + "<section class=\"widget literatumArticleToolsWidget none " + "margin-bottom-15px widget-regular widget-border-toggle\" " + "id=\"3a3\">" + "<div class=\"articleTools\">" + "<ul class=\"linkList blockLinks separators centered\">" + "<li class=\"addToFavs\"><a href=\"/linktoaddfav\">" + "Add to Fav</a></li>" + "<li class=\"email\"><a href=\"/linktoemail\">Email friends</a></li>" + "<li class=\"downloadCitations\">" + "<a href=\"/action/showCitFormats?doi=11.1111%jid.2013.2\">" + "Send to Citation Mgr</a>" + "</li></ul></div>" + "</section>" + "</div>"; private static final String articleToolsFilteredStr2 = "<section class=\"widget literatumArticleToolsWidget none " + "margin-bottom-15px widget-regular widget-border-toggle\" >" + "<div class=\"articleTools\">" + "<ul class=\"linkList blockLinks separators centered\">" + "<li class=\"downloadCitations\">" + "<a href=\"/action/showCitFormats?doi=11.1111%jid.2013.2\">" + "Send to Citation Mgr</a></li></ul></div></section>"; // ?? use this block when manifest pages are up // private static final String manifestList = // "<ul>" + // "<li>" + // "<a href=\"http://www.example.com/toc/abcj/123/4\">" + // "2012 (Vol. 123 Issue 4 Page 456-789)</a>" + // "</li>" + // "</ul>"; // private static final String manifestListFilteredStr = // "<a href=\"http://www.example.com/toc/abcj/123/4\">" + // "2012 (Vol. 123 Issue 4 Page 456-789)</a>"; // // private static final String nonManifestList1 = // "<ul class=\"breadcrumbs\">" + // "<li>" + // "<a href=\"/toc/abcj/123/4\">Volume 123, Issue 4</a>" + // "</li>" + // "</ul>"; // private static final String nonManifestList1FilteredStr = ""; // // private static final String nonManifestList2 = // "<ul>" + // "<li id=\"forthcomingIssue\">" + // "<a href=\"/toc/abcj/123/5\">EarlyCite</a>" + // "</li>" + // "<li id=\"currIssue\">" + // "<a href=\"/toc/abcj/199/1\">Current Issue</a>" + // "</li>" + // "</ul>"; // private static final String nonManifestList2FilteredStr = ""; protected ArchivalUnit createAu() throws ArchivalUnit.ConfigurationException { return PluginTestUtil.createAndStartAu(PLUGIN_ID, wageningenAuConfig()); } private Configuration wageningenAuConfig() { Configuration conf = ConfigManager.newConfiguration(); conf.put("base_url", "http://www.example.com/"); conf.put("journal_id", "abc"); conf.put("volume_name", "99"); return conf; } private static void doFilterTest(ArchivalUnit au, FilterFactory fact, String nameToHash, String expectedStr) throws PluginException, IOException { InputStream actIn; actIn = fact.createFilteredInputStream(au, new StringInputStream(nameToHash), Constants.DEFAULT_ENCODING); // for debug // String actualStr = StringUtil.fromInputStream(actIn); // assertEquals(expectedStr, actualStr); assertEquals(expectedStr, StringUtil.fromInputStream(actIn)); } public void startMockDaemon() { daemon = getMockLockssDaemon(); pluginMgr = daemon.getPluginManager(); pluginMgr.setLoadablePluginsReady(true); daemon.setDaemonInited(true); pluginMgr.startService(); daemon.getAlertManager(); daemon.getCrawlManager(); } public void setUp() throws Exception { super.setUp(); tempDirPath = setUpDiskSpace(); startMockDaemon(); wau = createAu(); } // Variant to test with Crawl Filter public static class TestCrawl extends TestWageningenJournalsHtmlFilterFactory { public void testFiltering() throws Exception { variantFact = new WageningenJournalsHtmlCrawlFilterFactory(); doFilterTest(wau, variantFact, withBreadcrumbs, filteredStr); doFilterTest(wau, variantFact, withAriaRelevant, filteredStr); doFilterTest(wau, variantFact, withRelatedContent, filteredStr); doFilterTest(wau, variantFact, withArticleToolsExceptDownloadCitation1, articleToolsFilteredStr1); } } // Variant to test with Hash Filter public static class TestHash extends TestWageningenJournalsHtmlFilterFactory { public void testFiltering() throws Exception { variantFact = new WageningenJournalsHtmlHashFilterFactory(); doFilterTest(wau, variantFact, withPublicationToolContainer, publicationToolContainerFilteredStr); doFilterTest(wau, variantFact, withArticleMetaDrop, articleMetaDropFilteredStr); doFilterTest(wau, variantFact, withArticleToolsExceptDownloadCitation2, articleToolsFilteredStr2); // doFilterTest(eau, variantFact, manifestList, // manifestListFilteredStr); // doFilterTest(eau, variantFact, nonManifestList1, // nonManifestList1FilteredStr); // doFilterTest(eau, variantFact, nonManifestList2, // nonManifestList2FilteredStr); } } public static Test suite() { return variantSuites(new Class[] { TestCrawl.class, TestHash.class }); } }
plugins/test/src/org/lockss/plugin/atypon/wageningen/TestWageningenJournalsHtmlFilterFactory.java
/* * $Id$ */ /* Copyright (c) 2000-2015 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.plugin.atypon.wageningen; import java.io.*; import junit.framework.Test; import org.lockss.util.*; import org.lockss.config.ConfigManager; import org.lockss.config.Configuration; import org.lockss.daemon.PluginException; import org.lockss.plugin.ArchivalUnit; import org.lockss.plugin.FilterFactory; import org.lockss.plugin.PluginManager; import org.lockss.plugin.PluginTestUtil; import org.lockss.test.*; public class TestWageningenJournalsHtmlFilterFactory extends LockssTestCase { FilterFactory variantFact; ArchivalUnit wau; String tempDirPath; MockLockssDaemon daemon; PluginManager pluginMgr; private static final String PLUGIN_ID = "org.lockss.plugin.atypon.wageningen.ClockssWageningenAtyponPlugin"; private static final String filteredStr = "<div class=\"block\"></div>"; // breadcrumbs private static final String withBreadcrumbs = "<div class=\"block\">" + "<ul class=\"breadcrumbs\">" + "<li class=\"\"><a href=\"/\">Home</a>" + "<span class=\"divider\">></span></li>" + "<li class=\"\"><a href=\"/loi/jid\">ABC Journals</a>" + "<span class=\"divider\">></span></li>" + "<li class=\"\"><a href=\"/loi/jid\">issues</a>" + "<span class=\"divider\">></span></li>" + "<li class=\"\"><a href=\"/toc/jid/26/1\">Volume 9, Issue 9</a>" + "<span class=\"divider\">></span></li>" + "<li class=\"truncate\">The development of blah</li>" + "</ul>" + "</div>"; private static final String withAriaRelevant = "<div class=\"block\">" + "<div class=\"tabs tabs-widget\" aria-relevant=\"additions\" " + "aria-atomic=\"true\" aria-live=\"polite\">" + "<div class=\"tab-content\">" + "<div id=\"19a\" class=\"tab-pane active\">" + "<div data-pb-dropzone-name=\"Most Read\" " + "data-pb-dropzone=\"tab-59a\">" + "<div id=\"753\" class=\"widget literatumMostReadWidget none " + "widget-none widget-compact-all\">" + "<div class=\"widget-body body body-none body-compact-all\">" + "<section class=\"popular\">" + "<div class=\"mostRead\">" + "<ul>" + "<li><div class=\"title\">" + "<a href=\"/doi/abs/11.1111/jid.22.2.3\">Canada blah blah</a>" + "</div>" + "<div class=\"authors\">" + "<div class=\"contrib\">" + "<span class=\"authors\">Tim Ra</span>" + "</div></div></ul>" + "</div></section>" + "</div></div></div></div></div></div>" + "</div>"; private static final String withRelatedContent = "<div class=\"block\">" + "<div class=\"tab tab-pane\" id=\"relatedContent\"></div>" + "</div>"; // for testcrawl // from abs - all Articles Options and Tools except Download Citation private static final String withArticleToolsExceptDownloadCitation1 = "<div class=\"block\">" + "<div class=\"articleTools\">" + "<ul class=\"linkList blockLinks separators centered\">" + "<li class=\"addToFavs\"><a href=\"/linktoaddfav\">Add to Fav</a></li>" + "<li class=\"email\"><a href=\"/linktoemail\">Email friends</a></li>" + "<li class=\"downloadCitations\">" + "<a href=\"/action/showCitFormats?doi=10.3828%2Fjid.2013.2\">" + "Send to Citation Mgr</a>" + "</li></ul></div>" + "</div>"; // id tag also got filtered private static final String articleToolsFilteredStr1 = "<div class=\"block\">" + "<div class=\"articleTools\">" + "<ul class=\"linkList blockLinks separators centered\">" + "<li class=\"downloadCitations\">" + "<a href=\"/action/showCitFormats?doi=10.3828%2Fjid.2013.2\">" + "Send to Citation Mgr</a>" + "</li></ul></div>" + "</div>"; private static final String withPublicationToolContainer = "<div class=\"block\">" + "<div class=\"widget tocListWidget none widget-none " + "widget-compact-all\" id=\"3f3\">" + "<div class=\"widget-body body body-none body-compact-all\">" + "<fieldset class=\"tocListWidgetContainer\">" + "<div class=\"publicationToolContainer\">" + "<div class=\"publicationToolCheckboxContainer\">" + "<input type=\"checkbox\" name=\"markall\" id=\"markall\" " + "onclick=\"onClickMarkAll(frmAbs,'')\"><span>Select All</span>" + "</div>" + "<div class=\"publicationTooldropdownContainer\">" + "<span class=\"dropdownLabel\">" + "For selected items:" + "</span>" + "<select name=\"articleTool\" class=\"items-choice " + "publicationToolSelect\" title=\"Article Tools\">" + "<option value=\"\">Please select</option>" + "<option value=\"/addfav\">Add to Favorites</option>" + "<option value=\"/trackcit\">Track Citation</option>" + "<option value=\"/showcit\">Download Citation</option>" + "<option value=\"/emailto\">Email</option>" + "</select>" + "</div>" + "</div>" + "</fieldset>" + "</div>" + "</div>" + "</div>"; // attributes separated by 1 space private static final String publicationToolContainerFilteredStr = "<div class=\"widget tocListWidget none widget-none " + "widget-compact-all\" >" + "<div class=\"widget-body body body-none body-compact-all\">" + "<fieldset class=\"tocListWidgetContainer\">" + "</fieldset>" + "</div>" + "</div>"; private static final String withArticleMetaDrop = "<div class=\"block\">" + "<div class=\"widget literatumPublicationContentWidget none " + "widget-none\" id=\"1ca\">" + "<div class=\"articleMetaDrop publicationContentDropZone\" " + "data-pb-dropzone=\"articleMetaDropZone\">" + "</div>" + "</div>" + "</div>"; private static final String articleMetaDropFilteredStr = "<div class=\"widget literatumPublicationContentWidget none " + "widget-none\" >" + "</div>"; private static final String withArticleToolsExceptDownloadCitation2 = "<div class=\"block\">" + "<section class=\"widget literatumArticleToolsWidget none " + "margin-bottom-15px widget-regular widget-border-toggle\" " + "id=\"3a3\">" + "<div class=\"articleTools\">" + "<ul class=\"linkList blockLinks separators centered\">" + "<li class=\"addToFavs\"><a href=\"/linktoaddfav\">" + "Add to Fav</a></li>" + "<li class=\"email\"><a href=\"/linktoemail\">Email friends</a></li>" + "<li class=\"downloadCitations\">" + "<a href=\"/action/showCitFormats?doi=11.1111%jid.2013.2\">" + "Send to Citation Mgr</a>" + "</li></ul></div>" + "</section>" + "</div>"; private static final String articleToolsFilteredStr2 = "<section class=\"widget literatumArticleToolsWidget none " + "margin-bottom-15px widget-regular widget-border-toggle\" >" + "<div class=\"articleTools\">" + "<ul class=\"linkList blockLinks separators centered\">" + "<li class=\"downloadCitations\">" + "<a href=\"/action/showCitFormats?doi=11.1111%jid.2013.2\">" + "Send to Citation Mgr</a></li></ul></div></section>"; // ?? use this block when manifest pages are up // private static final String manifestList = // "<ul>" + // "<li>" + // "<a href=\"http://www.example.com/toc/abcj/123/4\">" + // "2012 (Vol. 123 Issue 4 Page 456-789)</a>" + // "</li>" + // "</ul>"; // private static final String manifestListFilteredStr = // "<a href=\"http://www.example.com/toc/abcj/123/4\">" + // "2012 (Vol. 123 Issue 4 Page 456-789)</a>"; // // private static final String nonManifestList1 = // "<ul class=\"breadcrumbs\">" + // "<li>" + // "<a href=\"/toc/abcj/123/4\">Volume 123, Issue 4</a>" + // "</li>" + // "</ul>"; // private static final String nonManifestList1FilteredStr = ""; // // private static final String nonManifestList2 = // "<ul>" + // "<li id=\"forthcomingIssue\">" + // "<a href=\"/toc/abcj/123/5\">EarlyCite</a>" + // "</li>" + // "<li id=\"currIssue\">" + // "<a href=\"/toc/abcj/199/1\">Current Issue</a>" + // "</li>" + // "</ul>"; // private static final String nonManifestList2FilteredStr = ""; protected ArchivalUnit createAu() throws ArchivalUnit.ConfigurationException { return PluginTestUtil.createAndStartAu(PLUGIN_ID, wageningenAuConfig()); } private Configuration wageningenAuConfig() { Configuration conf = ConfigManager.newConfiguration(); conf.put("base_url", "http://www.example.com/"); conf.put("journal_id", "abc"); conf.put("volume_name", "99"); return conf; } private static void doFilterTest(ArchivalUnit au, FilterFactory fact, String nameToHash, String expectedStr) throws PluginException, IOException { InputStream actIn; actIn = fact.createFilteredInputStream(au, new StringInputStream(nameToHash), Constants.DEFAULT_ENCODING); // for debug // String actualStr = StringUtil.fromInputStream(actIn); // assertEquals(expectedStr, actualStr); assertEquals(expectedStr, StringUtil.fromInputStream(actIn)); } public void startMockDaemon() { daemon = getMockLockssDaemon(); pluginMgr = daemon.getPluginManager(); pluginMgr.setLoadablePluginsReady(true); daemon.setDaemonInited(true); pluginMgr.startService(); daemon.getAlertManager(); daemon.getCrawlManager(); } public void setUp() throws Exception { super.setUp(); tempDirPath = setUpDiskSpace(); startMockDaemon(); wau = createAu(); } // Variant to test with Crawl Filter public static class TestCrawl extends TestWageningenJournalsHtmlFilterFactory { public void testFiltering() throws Exception { variantFact = new WageningenJournalsHtmlCrawlFilterFactory(); doFilterTest(wau, variantFact, withBreadcrumbs, filteredStr); doFilterTest(wau, variantFact, withAriaRelevant, filteredStr); doFilterTest(wau, variantFact, withRelatedContent, filteredStr); doFilterTest(wau, variantFact, withArticleToolsExceptDownloadCitation1, articleToolsFilteredStr1); } } // Variant to test with Hash Filter public static class TestHash extends TestWageningenJournalsHtmlFilterFactory { public void testFiltering() throws Exception { variantFact = new WageningenJournalsHtmlHashFilterFactory(); doFilterTest(wau, variantFact, withPublicationToolContainer, publicationToolContainerFilteredStr); doFilterTest(wau, variantFact, withArticleMetaDrop, articleMetaDropFilteredStr); doFilterTest(wau, variantFact, withArticleToolsExceptDownloadCitation2, articleToolsFilteredStr2); // doFilterTest(eau, variantFact, manifestList, // manifestListFilteredStr); // doFilterTest(eau, variantFact, nonManifestList1, // nonManifestList1FilteredStr); // doFilterTest(eau, variantFact, nonManifestList2, // nonManifestList2FilteredStr); } } public static Test suite() { return variantSuites(new Class[] { TestCrawl.class, TestHash.class }); } }
Changed plugin name. git-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@42162 4f837ed2-42f5-46e7-a7a5-fa17313484d4
plugins/test/src/org/lockss/plugin/atypon/wageningen/TestWageningenJournalsHtmlFilterFactory.java
Changed plugin name.
<ide><path>lugins/test/src/org/lockss/plugin/atypon/wageningen/TestWageningenJournalsHtmlFilterFactory.java <ide> PluginManager pluginMgr; <ide> <ide> private static final String PLUGIN_ID = <del> "org.lockss.plugin.atypon.wageningen.ClockssWageningenAtyponPlugin"; <add> "org.lockss.plugin.atypon.wageningen.ClockssWageningenJournalsPlugin"; <ide> <ide> private static final String filteredStr = <ide> "<div class=\"block\"></div>";
JavaScript
lgpl-2.1
1d13b2a37f4d9be0f0ed2e8bdc2e5ace63b53af9
0
erasche/jbrowse,nathandunn/jbrowse,erasche/jbrowse,limeng12/jbrowse,igemsoftware/Shenzhen_BGIC_0101_2013,limeng12/jbrowse,GMOD/jbrowse,Arabidopsis-Information-Portal/jbrowse,igemsoftware/Shenzhen_BGIC_0101_2013,SuLab/jbrowse,limeng12/jbrowse,Arabidopsis-Information-Portal/jbrowse,GMOD/jbrowse,Arabidopsis-Information-Portal/jbrowse,Arabidopsis-Information-Portal/jbrowse,SuLab/jbrowse,nathandunn/jbrowse,igemsoftware/Shenzhen_BGIC_0101_2013,SuLab/jbrowse,igemsoftware/Shenzhen_BGIC_0101_2013,SuLab/jbrowse,nathandunn/jbrowse,SuLab/jbrowse,SuLab/jbrowse,erasche/jbrowse,limeng12/jbrowse,Arabidopsis-Information-Portal/jbrowse,limeng12/jbrowse,Arabidopsis-Information-Portal/jbrowse,erasche/jbrowse,limeng12/jbrowse,erasche/jbrowse,igemsoftware/Shenzhen_BGIC_0101_2013,GMOD/jbrowse,limeng12/jbrowse,erasche/jbrowse,igemsoftware/Shenzhen_BGIC_0101_2013,SuLab/jbrowse,GMOD/jbrowse,igemsoftware/Shenzhen_BGIC_0101_2013,GMOD/jbrowse,erasche/jbrowse,erasche/jbrowse,igemsoftware/Shenzhen_BGIC_0101_2013,Arabidopsis-Information-Portal/jbrowse,limeng12/jbrowse,nathandunn/jbrowse,nathandunn/jbrowse
require([ 'JBrowse/Browser', 'JBrowse/Store/BigWig', 'JBrowse/Model/XHRBlob' ], function( Browser, BigWig, XHRBlob ) { describe( 'BigWig with volvox_microarray.bw', function() { var b = new BigWig({ browser: new Browser({ unitTestMode: true }), blob: new XHRBlob('../../sample_data/raw/volvox/volvox_microarray.bw') }); it('constructs', function(){ expect(b).toBeTruthy(); }); it('returns empty array of features for a nonexistent chrom', function() { var v = b.getUnzoomedView(); var wigData; v.readWigData( 'nonexistent', 1, 10000, function(features) { wigData = features; }); waitsFor(function() { return wigData; }); runs(function() { expect(wigData.length).toEqual(0); }); }); it('reads some good data unzoomed', function() { var v = b.getUnzoomedView(); var wigData; v.readWigData( 'ctgA', 0, 10000, function(features) { wigData = features; }); waitsFor(function() { return wigData; },1000); runs(function() { expect(wigData.length).toBeGreaterThan(100); dojo.forEach( wigData.slice(1,20), function(feature) { expect(feature.get('start')).toBeGreaterThan(0); expect(feature.get('end')).toBeLessThan(10000); }); //console.log(wigData); }); }); it('reads some good data when zoomed out', function() { var v = b.getView( 1/20000 ); var wigData; v.readWigData( 'ctgA', 100, 20000, function(features) { wigData = features; }); waitsFor(function() { return wigData; },500); runs(function() { expect(wigData.length).toEqual(2); dojo.forEach( wigData, function(feature) { expect(feature.get('start')).toBeGreaterThan( -1 ); expect(feature.get('end')).toBeLessThan( 40000 ); }); //console.log(wigData); }); }); it('reads the file stats (the totalSummary section)', function() { var stats; b.getGlobalStats(function(s) { stats = s; }); waitsFor(function() { return stats; }); runs( function() { //console.log(stats); expect(stats.basesCovered).toEqual(50690); expect(stats.scoreMin).toEqual(100); expect(stats.scoreMax).toEqual(899); expect(stats.scoreSum).toEqual(16863706); expect(stats.scoreSumSquares).toEqual(8911515204); expect(stats.scoreStdDev).toEqual(255.20080383762445); expect(stats.scoreMean).toEqual(332.6830933122904); }); }); it('reads good data when zoomed very little', function() { var v = b.getView( 1/17.34 ); var wigData; v.readWigData( 'ctgA', 19999, 24999, function(features) { wigData = features; }); waitsFor(function() { return wigData; },1000); runs(function() { expect(wigData.length).toBeGreaterThan(19); expect(wigData.length).toBeLessThan(1000); dojo.forEach( wigData, function(feature) { expect(feature.get('start')).toBeGreaterThan(10000); expect(feature.get('end')).toBeLessThan(30000); }); //console.log(wigData); }); }); }); // only run the tomato_rnaseq test if it's in the URL someplace if( document.location.href.indexOf('tomato_rnaseq') > -1 ) { describe( 'BigWig with tomato RNAseq coverage', function() { var b = new BigWig({ browser: new Browser({ unitTestMode: true }), blob: new XHRBlob('../data/SL2.40_all_rna_seq.v1.bigwig') }); it('constructs', function(){ expect(b).toBeTruthy(); }); it('returns empty array of features for a nonexistent chrom', function() { var v = b.getUnzoomedView(); var wigData; v.readWigData( 'nonexistent', 1, 10000, function(features) { wigData = features; }); waitsFor(function() { return wigData; }); runs(function() { expect(wigData.length).toEqual(0); }); }); it('reads some good data unzoomed', function() { var v = b.getUnzoomedView(); var wigData; v.readWigData( 'SL2.40ch01', 1, 100000, function(features) { wigData = features; }); waitsFor(function() { return wigData; },1000); runs(function() { expect(wigData.length).toBeGreaterThan(10000); dojo.forEach( wigData.slice(0,20), function(feature) { expect(feature.get('start')).toBeGreaterThan(0); expect(feature.get('end')).toBeLessThan(100001); }); //console.log(wigData); }); }); it('reads some good data when zoomed', function() { var v = b.getView( 1/100000 ); var wigData; v.readWigData( 'SL2.40ch01', 100000, 2000000, function(features) { wigData = features; }); waitsFor(function() { return wigData; },1000); runs(function() { expect(wigData.length).toBeGreaterThan(19); expect(wigData.length).toBeLessThan(100); dojo.forEach( wigData, function(feature) { expect(feature.get('start')).toBeGreaterThan(80000); expect(feature.get('end')).toBeLessThan(2050000); }); //console.log(wigData); }); }); it('reads the file stats (the totalSummary section)', function() { var stats = b.getGlobalStats(); expect(stats.basesCovered).toEqual(141149153); expect(stats.minVal).toEqual(1); expect(stats.maxVal).toEqual(62066); expect(stats.sumData).toEqual(16922295025); expect(stats.sumSquares).toEqual(45582937421360); expect(stats.stdDev).toEqual(555.4891087210976); expect(stats.mean).toEqual(119.88945498666932); }); it('reads good data when zoomed very little', function() { var v = b.getView( 1/17.34 ); var wigData; v.readWigData( 'SL2.40ch01', 19999, 24999, function(features) { wigData = features; }); waitsFor(function() { return wigData; },1000); runs(function() { expect(wigData.length).toBeGreaterThan(19); expect(wigData.length).toBeLessThan(1000); dojo.forEach( wigData, function(feature) { expect(feature.get('start')).toBeGreaterThan(10000); expect(feature.get('end')).toBeLessThan(30000); }); //console.log(wigData); }); }); }); } });
tests/js_tests/spec/BigWig.spec.js
require(['JBrowse/Store/BigWig','JBrowse/Model/XHRBlob'], function( BigWig, XHRBlob ) { describe( 'BigWig with volvox_microarray.bw', function() { var b = new BigWig({ browser: {}, blob: new XHRBlob('../../sample_data/raw/volvox/volvox_microarray.bw') }); it('constructs', function(){ expect(b).toBeTruthy(); }); it('returns empty array of features for a nonexistent chrom', function() { var v = b.getUnzoomedView(); var wigData; v.readWigData( 'nonexistent', 1, 10000, function(features) { wigData = features; }); waitsFor(function() { return wigData; }); runs(function() { expect(wigData.length).toEqual(0); }); }); it('reads some good data unzoomed', function() { var v = b.getUnzoomedView(); var wigData; v.readWigData( 'ctgA', 0, 10000, function(features) { wigData = features; }); waitsFor(function() { return wigData; },1000); runs(function() { expect(wigData.length).toBeGreaterThan(100); dojo.forEach( wigData.slice(1,20), function(feature) { expect(feature.get('start')).toBeGreaterThan(0); expect(feature.get('end')).toBeLessThan(10000); }); //console.log(wigData); }); }); it('reads some good data when zoomed out', function() { var v = b.getView( 1/20000 ); var wigData; v.readWigData( 'ctgA', 100, 20000, function(features) { wigData = features; }); waitsFor(function() { return wigData; },500); runs(function() { expect(wigData.length).toEqual(2); dojo.forEach( wigData, function(feature) { expect(feature.get('start')).toBeGreaterThan( -1 ); expect(feature.get('end')).toBeLessThan( 40000 ); }); //console.log(wigData); }); }); it('reads the file stats (the totalSummary section)', function() { var stats; b.getGlobalStats(function(s) { stats = s; }); waitsFor(function() { return stats; }); runs( function() { //console.log(stats); expect(stats.basesCovered).toEqual(50690); expect(stats.scoreMin).toEqual(100); expect(stats.scoreMax).toEqual(899); expect(stats.scoreSum).toEqual(16863706); expect(stats.scoreSumSquares).toEqual(8911515204); expect(stats.scoreStdDev).toEqual(255.20080383762445); expect(stats.scoreMean).toEqual(332.6830933122904); }); }); it('reads good data when zoomed very little', function() { var v = b.getView( 1/17.34 ); var wigData; v.readWigData( 'ctgA', 19999, 24999, function(features) { wigData = features; }); waitsFor(function() { return wigData; },1000); runs(function() { expect(wigData.length).toBeGreaterThan(19); expect(wigData.length).toBeLessThan(1000); dojo.forEach( wigData, function(feature) { expect(feature.get('start')).toBeGreaterThan(10000); expect(feature.get('end')).toBeLessThan(30000); }); //console.log(wigData); }); }); }); // only run the tomato_rnaseq test if it's in the URL someplace if( document.location.href.indexOf('tomato_rnaseq') > -1 ) { describe( 'BigWig with tomato RNAseq coverage', function() { var b = new BigWig({ browser: {}, blob: new XHRBlob('../data/SL2.40_all_rna_seq.v1.bigwig') }); it('constructs', function(){ expect(b).toBeTruthy(); }); it('returns empty array of features for a nonexistent chrom', function() { var v = b.getUnzoomedView(); var wigData; v.readWigData( 'nonexistent', 1, 10000, function(features) { wigData = features; }); waitsFor(function() { return wigData; }); runs(function() { expect(wigData.length).toEqual(0); }); }); it('reads some good data unzoomed', function() { var v = b.getUnzoomedView(); var wigData; v.readWigData( 'SL2.40ch01', 1, 100000, function(features) { wigData = features; }); waitsFor(function() { return wigData; },1000); runs(function() { expect(wigData.length).toBeGreaterThan(10000); dojo.forEach( wigData.slice(0,20), function(feature) { expect(feature.get('start')).toBeGreaterThan(0); expect(feature.get('end')).toBeLessThan(100001); }); //console.log(wigData); }); }); it('reads some good data when zoomed', function() { var v = b.getView( 1/100000 ); var wigData; v.readWigData( 'SL2.40ch01', 100000, 2000000, function(features) { wigData = features; }); waitsFor(function() { return wigData; },1000); runs(function() { expect(wigData.length).toBeGreaterThan(19); expect(wigData.length).toBeLessThan(100); dojo.forEach( wigData, function(feature) { expect(feature.get('start')).toBeGreaterThan(80000); expect(feature.get('end')).toBeLessThan(2050000); }); //console.log(wigData); }); }); it('reads the file stats (the totalSummary section)', function() { var stats = b.getGlobalStats(); expect(stats.basesCovered).toEqual(141149153); expect(stats.minVal).toEqual(1); expect(stats.maxVal).toEqual(62066); expect(stats.sumData).toEqual(16922295025); expect(stats.sumSquares).toEqual(45582937421360); expect(stats.stdDev).toEqual(555.4891087210976); expect(stats.mean).toEqual(119.88945498666932); }); it('reads good data when zoomed very little', function() { var v = b.getView( 1/17.34 ); var wigData; v.readWigData( 'SL2.40ch01', 19999, 24999, function(features) { wigData = features; }); waitsFor(function() { return wigData; },1000); runs(function() { expect(wigData.length).toBeGreaterThan(19); expect(wigData.length).toBeLessThan(1000); dojo.forEach( wigData, function(feature) { expect(feature.get('start')).toBeGreaterThan(10000); expect(feature.get('end')).toBeLessThan(30000); }); //console.log(wigData); }); }); }); } });
WIP fixing BigWig unit tests
tests/js_tests/spec/BigWig.spec.js
WIP fixing BigWig unit tests
<ide><path>ests/js_tests/spec/BigWig.spec.js <del>require(['JBrowse/Store/BigWig','JBrowse/Model/XHRBlob'], function( BigWig, XHRBlob ) { <add>require([ <add> 'JBrowse/Browser', <add> 'JBrowse/Store/BigWig', <add> 'JBrowse/Model/XHRBlob' <add> ], function( <add> Browser, <add> BigWig, <add> XHRBlob <add> ) { <ide> <ide> describe( 'BigWig with volvox_microarray.bw', function() { <ide> var b = new BigWig({ <del> browser: {}, <add> browser: new Browser({ unitTestMode: true }), <ide> blob: new XHRBlob('../../sample_data/raw/volvox/volvox_microarray.bw') <ide> }); <ide> it('constructs', function(){ expect(b).toBeTruthy(); }); <ide> <ide> describe( 'BigWig with tomato RNAseq coverage', function() { <ide> var b = new BigWig({ <del> browser: {}, <add> browser: new Browser({ unitTestMode: true }), <ide> blob: new XHRBlob('../data/SL2.40_all_rna_seq.v1.bigwig') <ide> }); <ide>
JavaScript
bsd-3-clause
41cdcf5734e1bf4b0488ca81c08520ef955bc555
0
forcedotcom/kylie,sdgdsffdsfff/boomerang,lognormal/boomerang,forcedotcom/kylie,FredXue/boomerang,lognormal/boomerang,levexis/boomerang,levexis/boomerang,FredXue/boomerang,sdgdsffdsfff/boomerang
boomerang-0.9.1280532889.js
/* * Copyright (c) 2011, Yahoo! Inc. All rights reserved. * Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms. */ (function(a){var e,c,b,g=a.document;if(typeof BOOMR==="undefined"){BOOMR={}}if(BOOMR.version){return}BOOMR.version="0.9";e={beacon_url:"",site_domain:a.location.hostname.replace(/.*?([^.]+\.[^.]+)\.?$/,"$1").toLowerCase(),user_ip:"",events:{page_ready:[],page_unload:[],before_beacon:[]},vars:{},disabled_plugins:{},fireEvent:function(d,l){var j,k,m;if(!this.events.hasOwnProperty(d)){return false}m=this.events[d];for(j=0;j<m.length;j++){k=m[j];k[0].call(k[2],l,k[1])}return true},addListener:function(i,j,h,d){if(i.addEventListener){i.addEventListener(j,h,(d))}else{if(i.attachEvent){i.attachEvent("on"+j,h)}}}};c={utils:{getCookie:function(d){if(!d){return null}d=" "+d+"=";var h,j;j=" "+g.cookie+";";if((h=j.indexOf(d))>=0){h+=d.length;j=j.substring(h,j.indexOf(";",h));return j}return null},setCookie:function(h,d,n,r,l,m){var q="",j,p,o,i="";if(!h){return false}for(j in d){if(d.hasOwnProperty(j)){q+="&"+encodeURIComponent(j)+"="+encodeURIComponent(d[j])}}q=q.replace(/^&/,"");if(n){i=new Date();i.setTime(i.getTime()+n*1000);i=i.toGMTString()}p=h+"="+q;o=p+((n)?"; expires="+i:"")+((r)?"; path="+r:"")+((typeof l!=="undefined")?"; domain="+(l!==null?l:e.site_domain):"")+((m)?"; secure":"");if(p.length<4000){g.cookie=o;return(q===this.getCookie(h))}return false},getSubCookies:function(k){var j,h,d,n,m={};if(!k){return null}j=k.split("&");if(j.length===0){return null}for(h=0,d=j.length;h<d;h++){n=j[h].split("=");n.push("");m[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return m},removeCookie:function(d){return this.setCookie(d,{},0,"/",null)},pluginConfig:function(m,d,k,j){var h,l=0;if(!d||!d[k]){return false}for(h=0;h<j.length;h++){if(typeof d[k][j[h]]!=="undefined"){m[j[h]]=d[k][j[h]];l++}}return(l>0)}},init:function(h){var l,d,j=["beacon_url","site_domain","user_ip"];if(!h){h={}}for(l=0;l<j.length;l++){if(typeof h[j[l]]!=="undefined"){e[j[l]]=h[j[l]]}}if(typeof h.log!=="undefined"){this.log=h.log}if(!this.log){this.log=function(i,k,n){}}for(d in this.plugins){if(h[d]&&typeof h[d].enabled!=="undefined"&&h[d].enabled===false){e.disabled_plugins[d]=1;continue}else{if(e.disabled_plugins[d]){delete e.disabled_plugins[d]}}if(this.plugins.hasOwnProperty(d)&&typeof this.plugins[d].init==="function"){this.plugins[d].init(h)}}if(typeof h.autorun==="undefined"||h.autorun!==false){e.addListener(a,"load",function(){e.fireEvent("page_ready")})}e.addListener(a,"unload",function(){a=null});return this},page_ready:function(){e.fireEvent("page_ready");return this},subscribe:function(d,m,j,o){var k,l,n;if(!e.events.hasOwnProperty(d)){return this}n=e.events[d];for(k=0;k<n.length;k++){l=n[k];if(l[0]===m&&l[1]===j&&l[2]===o){return this}}n.push([m,j||{},o||null]);if(d==="page_unload"){e.addListener(a,"unload",function(){if(m){m.call(o,null,j)}m=o=j=null});e.addListener(a,"beforeunload",function(){if(m){m.call(o,null,j)}m=o=j=null})}return this},addVar:function(h,i){if(typeof h==="string"){e.vars[h]=i}else{if(typeof h==="object"){var j=h,d;for(d in j){if(j.hasOwnProperty(d)){e.vars[d]=j[d]}}}}return this},removeVar:function(){var d,h;if(!arguments.length){return this}if(arguments.length===1&&Object.prototype.toString.apply(arguments[0])==="[object Array]"){h=arguments[0]}else{h=arguments}for(d=0;d<h.length;d++){if(e.vars.hasOwnProperty(h[d])){delete e.vars[h[d]]}}return this},sendBeacon:function(){var i,j,h,d=0;for(i in this.plugins){if(this.plugins.hasOwnProperty(i)){if(e.disabled_plugins[i]){continue}if(!this.plugins[i].is_complete()){return this}}}e.fireEvent("before_beacon",e.vars);if(!e.beacon_url){return this}j=e.beacon_url+"?v="+encodeURIComponent(BOOMR.version);for(i in e.vars){if(e.vars.hasOwnProperty(i)){d++;j+="&"+encodeURIComponent(i)+"="+encodeURIComponent(e.vars[i])}}if(d){h=new Image();h.src=j}return this}};var f=function(d){return function(h,i){this.log(h,d,"boomerang"+(i?"."+i:""));return this}};c.debug=f("debug");c.info=f("info");c.warn=f("warn");c.error=f("error");if(a.YAHOO&&a.YAHOO.widget&&a.YAHOO.widget.Logger){c.log=a.YAHOO.log}else{if(typeof a.Y!=="undefined"&&typeof a.Y.log!=="undefined"){c.log=a.Y.log}else{if(typeof console!=="undefined"&&typeof console.log!=="undefined"){c.log=function(d,h,i){console.log(i+": ["+h+"] ",d)}}}}for(b in c){if(c.hasOwnProperty(b)){BOOMR[b]=c[b]}}BOOMR.plugins=BOOMR.plugins||{}}(window));(function(a){var c=a.document;BOOMR=BOOMR||{};BOOMR.plugins=BOOMR.plugins||{};var b={complete:false,timers:{},cookie:"RT",cookie_exp:600,strict_referrer:true,start:function(){var e,d=new Date().getTime();if(!BOOMR.utils.setCookie(b.cookie,{s:d,r:c.URL.replace(/#.*/,"")},b.cookie_exp,"/",null)){BOOMR.error("cannot set start cookie","rt");return this}e=new Date().getTime();if(e-d>50){BOOMR.utils.removeCookie(b.cookie);BOOMR.error("took more than 50ms to set cookie... aborting: "+d+" -> "+e,"rt")}return this}};BOOMR.plugins.RT={init:function(d){b.complete=false;b.timers={};BOOMR.utils.pluginConfig(b,d,"RT",["cookie","cookie_exp","strict_referrer"]);BOOMR.subscribe("page_ready",this.done,null,this);BOOMR.subscribe("page_unload",b.start,null,this);return this},startTimer:function(d){if(d){b.timers[d]={start:new Date().getTime()};b.complete=false}return this},endTimer:function(d,e){if(d){b.timers[d]=b.timers[d]||{};if(typeof b.timers[d].end==="undefined"){b.timers[d].end=(typeof e==="number"?e:new Date().getTime())}}return this},setTimer:function(d,e){if(d){b.timers[d]={delta:e}}return this},done:function(){var l,o,d,j,e,k={t_done:1,t_resp:1,t_page:1},i=0,m,h,n=[],f,g;if(b.complete){return this}this.endTimer("t_done");o=c.URL.replace(/#.*/,"");d=j=c.referrer.replace(/#.*/,"");e=BOOMR.utils.getSubCookies(BOOMR.utils.getCookie(b.cookie));BOOMR.utils.removeCookie(b.cookie);if(e!==null&&typeof e.s!=="undefined"&&typeof e.r!=="undefined"){d=e.r;if(!b.strict_referrer||d===j){l=parseInt(e.s,10)}}if(!l){BOOMR.warn("start cookie not set, trying WebTiming API","rt");g=a.performance||a.msPerformance||a.webkitPerformance||a.mozPerformance;if(g&&g.timing){f=g.timing}else{if(a.chrome&&a.chrome.csi){f={requestStart:a.chrome.csi().startE}}}if(f){l=f.requestStart||f.fetchStart||f.navigationStart||undefined}else{BOOMR.warn("This browser doesn't support the WebTiming API","rt")}}BOOMR.removeVar("t_done","t_page","t_resp","u","r","r2");for(m in b.timers){if(!b.timers.hasOwnProperty(m)){continue}h=b.timers[m];if(typeof h.delta!=="number"){if(typeof h.start!=="number"){h.start=l}h.delta=h.end-h.start}if(isNaN(h.delta)){continue}if(k.hasOwnProperty(m)){BOOMR.addVar(m,h.delta)}else{n.push(m+"|"+h.delta)}i++}if(i){BOOMR.addVar({u:o,r:d});if(j!==d){BOOMR.addVar("r2",j)}if(n.length){BOOMR.addVar("t_other",n.join(","))}}b.timers={};b.complete=true;BOOMR.sendBeacon();return this},is_complete:function(){return b.complete}}}(window));(function(b){var e=b.document;BOOMR=BOOMR||{};BOOMR.plugins=BOOMR.plugins||{};var a=[{name:"image-0.png",size:11483,timeout:1400},{name:"image-1.png",size:40658,timeout:1200},{name:"image-2.png",size:164897,timeout:1300},{name:"image-3.png",size:381756,timeout:1500},{name:"image-4.png",size:1234664,timeout:1200},{name:"image-5.png",size:4509613,timeout:1200},{name:"image-6.png",size:9084559,timeout:1200}];a.end=a.length;a.start=0;a.l={name:"image-l.gif",size:35,timeout:1000};var c={base_url:"images/",timeout:15000,nruns:5,latency_runs:10,user_ip:"",cookie_exp:7*86400,cookie:"BA",results:[],latencies:[],latency:null,runs_left:0,aborted:false,complete:false,running:false,ncmp:function(f,d){return(f-d)},iqr:function(h){var g=h.length-1,f,m,k,d=[],j;f=(h[Math.floor(g*0.25)]+h[Math.ceil(g*0.25)])/2;m=(h[Math.floor(g*0.75)]+h[Math.ceil(g*0.75)])/2;k=(m-f)*1.5;g++;for(j=0;j<g&&h[j]<m+k;j++){if(h[j]>f-k){d.push(h[j])}}return d},calc_latency:function(){var h,f,j=0,g=0,k,m,d,o,l;l=this.iqr(this.latencies.sort(this.ncmp));f=l.length;BOOMR.debug(l,"bw");for(h=1;h<f;h++){j+=l[h];g+=l[h]*l[h]}f--;k=Math.round(j/f);d=Math.sqrt(g/f-j*j/(f*f));o=(1.96*d/Math.sqrt(f)).toFixed(2);d=d.toFixed(2);f=l.length-1;m=Math.round((l[Math.floor(f/2)]+l[Math.ceil(f/2)])/2);return{mean:k,median:m,stddev:d,stderr:o}},calc_bw:function(){var y,x,t=0,p,g=[],v=[],f=0,o=0,C=0,u=0,q,A,B,h,d,w,k,m,l,z,s;for(y=0;y<this.nruns;y++){if(!this.results[y]||!this.results[y].r){continue}p=this.results[y].r;l=0;for(x=p.length-1;x>=0&&l<3;x--){if(typeof p[x]==="undefined"){break}if(p[x].t===null){continue}t++;l++;z=a[x].size*1000/p[x].t;g.push(z);s=a[x].size*1000/(p[x].t-this.latency.mean);v.push(s)}}BOOMR.debug("got "+t+" readings","bw");BOOMR.debug("bandwidths: "+g,"bw");BOOMR.debug("corrected: "+v,"bw");if(g.length>3){g=this.iqr(g.sort(this.ncmp));v=this.iqr(v.sort(this.ncmp))}else{g=g.sort(this.ncmp);v=v.sort(this.ncmp)}BOOMR.debug("after iqr: "+g,"bw");BOOMR.debug("corrected: "+v,"bw");t=Math.max(g.length,v.length);for(y=0;y<t;y++){if(y<g.length){f+=g[y];o+=Math.pow(g[y],2)}if(y<v.length){C+=v[y];u+=Math.pow(v[y],2)}}t=g.length;q=Math.round(f/t);A=Math.sqrt(o/t-Math.pow(f/t,2));B=Math.round(1.96*A/Math.sqrt(t));A=Math.round(A);t=g.length-1;h=Math.round((g[Math.floor(t/2)]+g[Math.ceil(t/2)])/2);t=v.length;d=Math.round(C/t);w=Math.sqrt(u/t-Math.pow(C/t,2));k=(1.96*w/Math.sqrt(t)).toFixed(2);w=w.toFixed(2);t=v.length-1;m=Math.round((v[Math.floor(t/2)]+v[Math.ceil(t/2)])/2);BOOMR.debug("amean: "+q+", median: "+h,"bw");BOOMR.debug("corrected amean: "+d+", median: "+m,"bw");return{mean:q,stddev:A,stderr:B,median:h,mean_corrected:d,stddev_corrected:w,stderr_corrected:k,median_corrected:m}},defer:function(f){var d=this;return setTimeout(function(){f.call(d);d=null},10)},load_img:function(g,k,m){var f=this.base_url+a[g].name+"?t="+(new Date().getTime())+Math.random(),l=0,j=0,d=new Image(),h=this;d.onload=function(){d.onload=d.onerror=null;d=null;clearTimeout(l);if(m){m.call(h,g,j,k,true)}h=m=null};d.onerror=function(){d.onload=d.onerror=null;d=null;clearTimeout(l);if(m){m.call(h,g,j,k,false)}h=m=null};l=setTimeout(function(){if(m){m.call(h,g,j,k,null)}},a[g].timeout+Math.min(400,this.latency?this.latency.mean:400));j=new Date().getTime();d.src=f},lat_loaded:function(d,f,h,j){if(h!==this.latency_runs+1){return}if(j!==null){var g=new Date().getTime()-f;this.latencies.push(g)}if(this.latency_runs===0){this.latency=this.calc_latency()}this.defer(this.iterate)},img_loaded:function(f,g,h,j){if(h!==this.runs_left+1){return}if(this.results[this.nruns-h].r[f]){return}if(j===null){this.results[this.nruns-h].r[f+1]={t:null,state:null,run:h};return}var d={start:g,end:new Date().getTime(),t:null,state:j,run:h};if(j){d.t=d.end-d.start}this.results[this.nruns-h].r[f]=d;if(f>=a.end-1||typeof this.results[this.nruns-h].r[f+1]!=="undefined"){BOOMR.debug(this.results[this.nruns-h],"bw");if(h===this.nruns){a.start=f}this.defer(this.iterate)}else{this.load_img(f+1,h,this.img_loaded)}},finish:function(){if(!this.latency){this.latency=this.calc_latency()}var f=this.calc_bw(),d={bw:f.median_corrected,bw_err:parseFloat(f.stderr_corrected,10),lat:this.latency.mean,lat_err:parseFloat(this.latency.stderr,10),bw_time:Math.round(new Date().getTime()/1000)};BOOMR.addVar(d);if(!isNaN(d.bw)){BOOMR.utils.setCookie(this.cookie,{ba:Math.round(d.bw),be:d.bw_err,l:d.lat,le:d.lat_err,ip:this.user_ip,t:d.bw_time},(this.user_ip?this.cookie_exp:0),"/",null)}this.complete=true;BOOMR.sendBeacon();this.running=false},iterate:function(){if(this.aborted){return false}if(!this.runs_left){this.finish()}else{if(this.latency_runs){this.load_img("l",this.latency_runs--,this.lat_loaded)}else{this.results.push({r:[]});this.load_img(a.start,this.runs_left--,this.img_loaded)}}},setVarsFromCookie:function(l){var i=parseInt(l.ba,10),k=parseFloat(l.be,10),j=parseInt(l.l,10)||0,f=parseFloat(l.le,10)||0,d=l.ip.replace(/\.\d+$/,"0"),m=parseInt(l.t,10),h=this.user_ip.replace(/\.\d+$/,"0"),g=Math.round((new Date().getTime())/1000);if(d===h&&m>=g-this.cookie_exp){this.complete=true;BOOMR.addVar({bw:i,lat:j,bw_err:k,lat_err:f});return true}return false}};BOOMR.plugins.BW={init:function(d){var f;BOOMR.utils.pluginConfig(c,d,"BW",["base_url","timeout","nruns","cookie","cookie_exp"]);if(d&&d.user_ip){c.user_ip=d.user_ip}a.start=0;c.runs_left=c.nruns;c.latency_runs=10;c.results=[];c.latencies=[];c.latency=null;c.complete=false;c.aborted=false;BOOMR.removeVar("ba","ba_err","lat","lat_err");f=BOOMR.utils.getSubCookies(BOOMR.utils.getCookie(c.cookie));if(!f||!f.ba||!c.setVarsFromCookie(f)){BOOMR.subscribe("page_ready",this.run,null,this)}return this},run:function(){if(c.running||c.complete){return this}if(b.location.protocol==="https:"){BOOMR.info("HTTPS detected, skipping bandwidth test","bw");c.complete=true;return this}c.running=true;setTimeout(this.abort,c.timeout);c.defer(c.iterate);return this},abort:function(){c.aborted=true;c.finish();return this},is_complete:function(){return c.complete}}}(window));
remove old build of boomerang file
boomerang-0.9.1280532889.js
remove old build of boomerang file
<ide><path>oomerang-0.9.1280532889.js <del>/* <del> * Copyright (c) 2011, Yahoo! Inc. All rights reserved. <del> * Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms. <del> */ <del>(function(a){var e,c,b,g=a.document;if(typeof BOOMR==="undefined"){BOOMR={}}if(BOOMR.version){return}BOOMR.version="0.9";e={beacon_url:"",site_domain:a.location.hostname.replace(/.*?([^.]+\.[^.]+)\.?$/,"$1").toLowerCase(),user_ip:"",events:{page_ready:[],page_unload:[],before_beacon:[]},vars:{},disabled_plugins:{},fireEvent:function(d,l){var j,k,m;if(!this.events.hasOwnProperty(d)){return false}m=this.events[d];for(j=0;j<m.length;j++){k=m[j];k[0].call(k[2],l,k[1])}return true},addListener:function(i,j,h,d){if(i.addEventListener){i.addEventListener(j,h,(d))}else{if(i.attachEvent){i.attachEvent("on"+j,h)}}}};c={utils:{getCookie:function(d){if(!d){return null}d=" "+d+"=";var h,j;j=" "+g.cookie+";";if((h=j.indexOf(d))>=0){h+=d.length;j=j.substring(h,j.indexOf(";",h));return j}return null},setCookie:function(h,d,n,r,l,m){var q="",j,p,o,i="";if(!h){return false}for(j in d){if(d.hasOwnProperty(j)){q+="&"+encodeURIComponent(j)+"="+encodeURIComponent(d[j])}}q=q.replace(/^&/,"");if(n){i=new Date();i.setTime(i.getTime()+n*1000);i=i.toGMTString()}p=h+"="+q;o=p+((n)?"; expires="+i:"")+((r)?"; path="+r:"")+((typeof l!=="undefined")?"; domain="+(l!==null?l:e.site_domain):"")+((m)?"; secure":"");if(p.length<4000){g.cookie=o;return(q===this.getCookie(h))}return false},getSubCookies:function(k){var j,h,d,n,m={};if(!k){return null}j=k.split("&");if(j.length===0){return null}for(h=0,d=j.length;h<d;h++){n=j[h].split("=");n.push("");m[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return m},removeCookie:function(d){return this.setCookie(d,{},0,"/",null)},pluginConfig:function(m,d,k,j){var h,l=0;if(!d||!d[k]){return false}for(h=0;h<j.length;h++){if(typeof d[k][j[h]]!=="undefined"){m[j[h]]=d[k][j[h]];l++}}return(l>0)}},init:function(h){var l,d,j=["beacon_url","site_domain","user_ip"];if(!h){h={}}for(l=0;l<j.length;l++){if(typeof h[j[l]]!=="undefined"){e[j[l]]=h[j[l]]}}if(typeof h.log!=="undefined"){this.log=h.log}if(!this.log){this.log=function(i,k,n){}}for(d in this.plugins){if(h[d]&&typeof h[d].enabled!=="undefined"&&h[d].enabled===false){e.disabled_plugins[d]=1;continue}else{if(e.disabled_plugins[d]){delete e.disabled_plugins[d]}}if(this.plugins.hasOwnProperty(d)&&typeof this.plugins[d].init==="function"){this.plugins[d].init(h)}}if(typeof h.autorun==="undefined"||h.autorun!==false){e.addListener(a,"load",function(){e.fireEvent("page_ready")})}e.addListener(a,"unload",function(){a=null});return this},page_ready:function(){e.fireEvent("page_ready");return this},subscribe:function(d,m,j,o){var k,l,n;if(!e.events.hasOwnProperty(d)){return this}n=e.events[d];for(k=0;k<n.length;k++){l=n[k];if(l[0]===m&&l[1]===j&&l[2]===o){return this}}n.push([m,j||{},o||null]);if(d==="page_unload"){e.addListener(a,"unload",function(){if(m){m.call(o,null,j)}m=o=j=null});e.addListener(a,"beforeunload",function(){if(m){m.call(o,null,j)}m=o=j=null})}return this},addVar:function(h,i){if(typeof h==="string"){e.vars[h]=i}else{if(typeof h==="object"){var j=h,d;for(d in j){if(j.hasOwnProperty(d)){e.vars[d]=j[d]}}}}return this},removeVar:function(){var d,h;if(!arguments.length){return this}if(arguments.length===1&&Object.prototype.toString.apply(arguments[0])==="[object Array]"){h=arguments[0]}else{h=arguments}for(d=0;d<h.length;d++){if(e.vars.hasOwnProperty(h[d])){delete e.vars[h[d]]}}return this},sendBeacon:function(){var i,j,h,d=0;for(i in this.plugins){if(this.plugins.hasOwnProperty(i)){if(e.disabled_plugins[i]){continue}if(!this.plugins[i].is_complete()){return this}}}e.fireEvent("before_beacon",e.vars);if(!e.beacon_url){return this}j=e.beacon_url+"?v="+encodeURIComponent(BOOMR.version);for(i in e.vars){if(e.vars.hasOwnProperty(i)){d++;j+="&"+encodeURIComponent(i)+"="+encodeURIComponent(e.vars[i])}}if(d){h=new Image();h.src=j}return this}};var f=function(d){return function(h,i){this.log(h,d,"boomerang"+(i?"."+i:""));return this}};c.debug=f("debug");c.info=f("info");c.warn=f("warn");c.error=f("error");if(a.YAHOO&&a.YAHOO.widget&&a.YAHOO.widget.Logger){c.log=a.YAHOO.log}else{if(typeof a.Y!=="undefined"&&typeof a.Y.log!=="undefined"){c.log=a.Y.log}else{if(typeof console!=="undefined"&&typeof console.log!=="undefined"){c.log=function(d,h,i){console.log(i+": ["+h+"] ",d)}}}}for(b in c){if(c.hasOwnProperty(b)){BOOMR[b]=c[b]}}BOOMR.plugins=BOOMR.plugins||{}}(window));(function(a){var c=a.document;BOOMR=BOOMR||{};BOOMR.plugins=BOOMR.plugins||{};var b={complete:false,timers:{},cookie:"RT",cookie_exp:600,strict_referrer:true,start:function(){var e,d=new Date().getTime();if(!BOOMR.utils.setCookie(b.cookie,{s:d,r:c.URL.replace(/#.*/,"")},b.cookie_exp,"/",null)){BOOMR.error("cannot set start cookie","rt");return this}e=new Date().getTime();if(e-d>50){BOOMR.utils.removeCookie(b.cookie);BOOMR.error("took more than 50ms to set cookie... aborting: "+d+" -> "+e,"rt")}return this}};BOOMR.plugins.RT={init:function(d){b.complete=false;b.timers={};BOOMR.utils.pluginConfig(b,d,"RT",["cookie","cookie_exp","strict_referrer"]);BOOMR.subscribe("page_ready",this.done,null,this);BOOMR.subscribe("page_unload",b.start,null,this);return this},startTimer:function(d){if(d){b.timers[d]={start:new Date().getTime()};b.complete=false}return this},endTimer:function(d,e){if(d){b.timers[d]=b.timers[d]||{};if(typeof b.timers[d].end==="undefined"){b.timers[d].end=(typeof e==="number"?e:new Date().getTime())}}return this},setTimer:function(d,e){if(d){b.timers[d]={delta:e}}return this},done:function(){var l,o,d,j,e,k={t_done:1,t_resp:1,t_page:1},i=0,m,h,n=[],f,g;if(b.complete){return this}this.endTimer("t_done");o=c.URL.replace(/#.*/,"");d=j=c.referrer.replace(/#.*/,"");e=BOOMR.utils.getSubCookies(BOOMR.utils.getCookie(b.cookie));BOOMR.utils.removeCookie(b.cookie);if(e!==null&&typeof e.s!=="undefined"&&typeof e.r!=="undefined"){d=e.r;if(!b.strict_referrer||d===j){l=parseInt(e.s,10)}}if(!l){BOOMR.warn("start cookie not set, trying WebTiming API","rt");g=a.performance||a.msPerformance||a.webkitPerformance||a.mozPerformance;if(g&&g.timing){f=g.timing}else{if(a.chrome&&a.chrome.csi){f={requestStart:a.chrome.csi().startE}}}if(f){l=f.requestStart||f.fetchStart||f.navigationStart||undefined}else{BOOMR.warn("This browser doesn't support the WebTiming API","rt")}}BOOMR.removeVar("t_done","t_page","t_resp","u","r","r2");for(m in b.timers){if(!b.timers.hasOwnProperty(m)){continue}h=b.timers[m];if(typeof h.delta!=="number"){if(typeof h.start!=="number"){h.start=l}h.delta=h.end-h.start}if(isNaN(h.delta)){continue}if(k.hasOwnProperty(m)){BOOMR.addVar(m,h.delta)}else{n.push(m+"|"+h.delta)}i++}if(i){BOOMR.addVar({u:o,r:d});if(j!==d){BOOMR.addVar("r2",j)}if(n.length){BOOMR.addVar("t_other",n.join(","))}}b.timers={};b.complete=true;BOOMR.sendBeacon();return this},is_complete:function(){return b.complete}}}(window));(function(b){var e=b.document;BOOMR=BOOMR||{};BOOMR.plugins=BOOMR.plugins||{};var a=[{name:"image-0.png",size:11483,timeout:1400},{name:"image-1.png",size:40658,timeout:1200},{name:"image-2.png",size:164897,timeout:1300},{name:"image-3.png",size:381756,timeout:1500},{name:"image-4.png",size:1234664,timeout:1200},{name:"image-5.png",size:4509613,timeout:1200},{name:"image-6.png",size:9084559,timeout:1200}];a.end=a.length;a.start=0;a.l={name:"image-l.gif",size:35,timeout:1000};var c={base_url:"images/",timeout:15000,nruns:5,latency_runs:10,user_ip:"",cookie_exp:7*86400,cookie:"BA",results:[],latencies:[],latency:null,runs_left:0,aborted:false,complete:false,running:false,ncmp:function(f,d){return(f-d)},iqr:function(h){var g=h.length-1,f,m,k,d=[],j;f=(h[Math.floor(g*0.25)]+h[Math.ceil(g*0.25)])/2;m=(h[Math.floor(g*0.75)]+h[Math.ceil(g*0.75)])/2;k=(m-f)*1.5;g++;for(j=0;j<g&&h[j]<m+k;j++){if(h[j]>f-k){d.push(h[j])}}return d},calc_latency:function(){var h,f,j=0,g=0,k,m,d,o,l;l=this.iqr(this.latencies.sort(this.ncmp));f=l.length;BOOMR.debug(l,"bw");for(h=1;h<f;h++){j+=l[h];g+=l[h]*l[h]}f--;k=Math.round(j/f);d=Math.sqrt(g/f-j*j/(f*f));o=(1.96*d/Math.sqrt(f)).toFixed(2);d=d.toFixed(2);f=l.length-1;m=Math.round((l[Math.floor(f/2)]+l[Math.ceil(f/2)])/2);return{mean:k,median:m,stddev:d,stderr:o}},calc_bw:function(){var y,x,t=0,p,g=[],v=[],f=0,o=0,C=0,u=0,q,A,B,h,d,w,k,m,l,z,s;for(y=0;y<this.nruns;y++){if(!this.results[y]||!this.results[y].r){continue}p=this.results[y].r;l=0;for(x=p.length-1;x>=0&&l<3;x--){if(typeof p[x]==="undefined"){break}if(p[x].t===null){continue}t++;l++;z=a[x].size*1000/p[x].t;g.push(z);s=a[x].size*1000/(p[x].t-this.latency.mean);v.push(s)}}BOOMR.debug("got "+t+" readings","bw");BOOMR.debug("bandwidths: "+g,"bw");BOOMR.debug("corrected: "+v,"bw");if(g.length>3){g=this.iqr(g.sort(this.ncmp));v=this.iqr(v.sort(this.ncmp))}else{g=g.sort(this.ncmp);v=v.sort(this.ncmp)}BOOMR.debug("after iqr: "+g,"bw");BOOMR.debug("corrected: "+v,"bw");t=Math.max(g.length,v.length);for(y=0;y<t;y++){if(y<g.length){f+=g[y];o+=Math.pow(g[y],2)}if(y<v.length){C+=v[y];u+=Math.pow(v[y],2)}}t=g.length;q=Math.round(f/t);A=Math.sqrt(o/t-Math.pow(f/t,2));B=Math.round(1.96*A/Math.sqrt(t));A=Math.round(A);t=g.length-1;h=Math.round((g[Math.floor(t/2)]+g[Math.ceil(t/2)])/2);t=v.length;d=Math.round(C/t);w=Math.sqrt(u/t-Math.pow(C/t,2));k=(1.96*w/Math.sqrt(t)).toFixed(2);w=w.toFixed(2);t=v.length-1;m=Math.round((v[Math.floor(t/2)]+v[Math.ceil(t/2)])/2);BOOMR.debug("amean: "+q+", median: "+h,"bw");BOOMR.debug("corrected amean: "+d+", median: "+m,"bw");return{mean:q,stddev:A,stderr:B,median:h,mean_corrected:d,stddev_corrected:w,stderr_corrected:k,median_corrected:m}},defer:function(f){var d=this;return setTimeout(function(){f.call(d);d=null},10)},load_img:function(g,k,m){var f=this.base_url+a[g].name+"?t="+(new Date().getTime())+Math.random(),l=0,j=0,d=new Image(),h=this;d.onload=function(){d.onload=d.onerror=null;d=null;clearTimeout(l);if(m){m.call(h,g,j,k,true)}h=m=null};d.onerror=function(){d.onload=d.onerror=null;d=null;clearTimeout(l);if(m){m.call(h,g,j,k,false)}h=m=null};l=setTimeout(function(){if(m){m.call(h,g,j,k,null)}},a[g].timeout+Math.min(400,this.latency?this.latency.mean:400));j=new Date().getTime();d.src=f},lat_loaded:function(d,f,h,j){if(h!==this.latency_runs+1){return}if(j!==null){var g=new Date().getTime()-f;this.latencies.push(g)}if(this.latency_runs===0){this.latency=this.calc_latency()}this.defer(this.iterate)},img_loaded:function(f,g,h,j){if(h!==this.runs_left+1){return}if(this.results[this.nruns-h].r[f]){return}if(j===null){this.results[this.nruns-h].r[f+1]={t:null,state:null,run:h};return}var d={start:g,end:new Date().getTime(),t:null,state:j,run:h};if(j){d.t=d.end-d.start}this.results[this.nruns-h].r[f]=d;if(f>=a.end-1||typeof this.results[this.nruns-h].r[f+1]!=="undefined"){BOOMR.debug(this.results[this.nruns-h],"bw");if(h===this.nruns){a.start=f}this.defer(this.iterate)}else{this.load_img(f+1,h,this.img_loaded)}},finish:function(){if(!this.latency){this.latency=this.calc_latency()}var f=this.calc_bw(),d={bw:f.median_corrected,bw_err:parseFloat(f.stderr_corrected,10),lat:this.latency.mean,lat_err:parseFloat(this.latency.stderr,10),bw_time:Math.round(new Date().getTime()/1000)};BOOMR.addVar(d);if(!isNaN(d.bw)){BOOMR.utils.setCookie(this.cookie,{ba:Math.round(d.bw),be:d.bw_err,l:d.lat,le:d.lat_err,ip:this.user_ip,t:d.bw_time},(this.user_ip?this.cookie_exp:0),"/",null)}this.complete=true;BOOMR.sendBeacon();this.running=false},iterate:function(){if(this.aborted){return false}if(!this.runs_left){this.finish()}else{if(this.latency_runs){this.load_img("l",this.latency_runs--,this.lat_loaded)}else{this.results.push({r:[]});this.load_img(a.start,this.runs_left--,this.img_loaded)}}},setVarsFromCookie:function(l){var i=parseInt(l.ba,10),k=parseFloat(l.be,10),j=parseInt(l.l,10)||0,f=parseFloat(l.le,10)||0,d=l.ip.replace(/\.\d+$/,"0"),m=parseInt(l.t,10),h=this.user_ip.replace(/\.\d+$/,"0"),g=Math.round((new Date().getTime())/1000);if(d===h&&m>=g-this.cookie_exp){this.complete=true;BOOMR.addVar({bw:i,lat:j,bw_err:k,lat_err:f});return true}return false}};BOOMR.plugins.BW={init:function(d){var f;BOOMR.utils.pluginConfig(c,d,"BW",["base_url","timeout","nruns","cookie","cookie_exp"]);if(d&&d.user_ip){c.user_ip=d.user_ip}a.start=0;c.runs_left=c.nruns;c.latency_runs=10;c.results=[];c.latencies=[];c.latency=null;c.complete=false;c.aborted=false;BOOMR.removeVar("ba","ba_err","lat","lat_err");f=BOOMR.utils.getSubCookies(BOOMR.utils.getCookie(c.cookie));if(!f||!f.ba||!c.setVarsFromCookie(f)){BOOMR.subscribe("page_ready",this.run,null,this)}return this},run:function(){if(c.running||c.complete){return this}if(b.location.protocol==="https:"){BOOMR.info("HTTPS detected, skipping bandwidth test","bw");c.complete=true;return this}c.running=true;setTimeout(this.abort,c.timeout);c.defer(c.iterate);return this},abort:function(){c.aborted=true;c.finish();return this},is_complete:function(){return c.complete}}}(window));
Java
mit
36263b1d099d97ae7373cd29077f6cd17a62ec3e
0
BartMassey/chomp
/* * Copyright © 2013 Bart Massey * [This program is licensed under the "MIT License"] * Please see the file COPYING in the source * distribution of this software for license terms. */ /* Java player for the simple game "Chomp" (http://en.wikipedia.org/wiki/Chomp) */ import java.io.*; class Move { int r, c; Move(int r, int c) { this.r = r; this.c = c; } } public class Chomp { /* http://www.abbeyworkshop.com/howto/java/readLine */ static InputStreamReader converter = new InputStreamReader(System.in); static BufferedReader in = new BufferedReader(converter); static final int dimx = 4, dimy = 3; static boolean[][] board; static void initBoard() { board = new boolean[dimy][dimx]; for (int r = 0; r < dimy; r++) for (int c = 0; c < dimx; c++) board[r][c] = true; } static void makeMove(boolean[][] b, int r0, int c0) { for (int r = r0; r < dimy; r++) for (int c = c0; c < dimx; c++) b[r][c] = false; } static void printBoard(boolean b[][]) { for (int r = 0; r < dimy; r++) { for (int c = 0; c < dimx; c++) { if (b[r][c]) { if (r == 0 && c == 0) System.out.print("*"); else System.out.print("o"); } else { System.out.print("."); } } System.out.println(); } } static Move getMove() throws IOException { printBoard(board); System.out.print("? "); String move = in.readLine(); System.out.println(); int moveDigits = Integer.parseInt(move); int r = moveDigits / 10 - 1; int c = moveDigits % 10 - 1; return new Move(r, c); } static boolean[][] copyBoard(boolean[][] b) { boolean[][] cb = new boolean[dimy][dimx]; for (int r = 0; r < dimy; r++) for (int c = 0; c < dimx; c++) cb[r][c] = b[r][c]; return cb; } static boolean negamax(boolean[][] b, int d) { int rx = 0; int cx = 0; for (int r = 0; r < dimy; r++) { for (int c = 0; c < dimx; c++) { if (b[r][c]) { if (r == 0 && c == 0) continue; rx = r; cx = c; boolean[][] mb = copyBoard(b); makeMove(mb, r, c); if (negamax(mb, d + 1)) continue; if (d == 0) { System.out.println("> " + (10 * (r + 1) + (c + 1)) + " :-)"); makeMove(b, r, c); } return true; } } } if (d == 0) { System.out.print("> " + (10 * (rx + 1) + (cx + 1))); if (rx == 0 && cx == 0) System.out.println(" :-("); else System.out.println(" :-P"); makeMove(b, rx, cx); System.out.println(); } return false; } static void computeMove() { printBoard(board); negamax(board, 0); } public static void main(String args[]) throws IOException { initBoard(); while (true) { Move m = getMove(); if (!board[m.r][m.c]) { System.out.println("Illegal Move"); continue; } if (m.r == 0 && m.c == 0) { System.out.println("I win"); break; } makeMove(board, m.r, m.c); computeMove(); if (!board[0][0]) { System.out.println("You win"); break; } } } }
Chomp.java
/* * Copyright © 2013 Bart Massey * [This program is licensed under the "MIT License"] * Please see the file COPYING in the source * distribution of this software for license terms. */ /* Java player for the simple game "Chomp" (http://en.wikipedia.org/wiki/Chomp) */ import java.io.*; class Move { int r, c; Move(int r, int c) { this.r = r; this.c = c; } } public class Chomp { /* http://www.abbeyworkshop.com/howto/java/readLine */ static InputStreamReader converter = new InputStreamReader(System.in); static BufferedReader in = new BufferedReader(converter); static final int dimx = 4, dimy = 3; static boolean[][] board; static void initBoard() { board = new boolean[dimy][dimx]; for (int r = 0; r < dimy; r++) for (int c = 0; c < dimx; c++) board[r][c] = true; } static void makeMove(boolean[][] b, int r0, int c0) { for (int r = r0; r < dimy; r++) for (int c = c0; c < dimx; c++) b[r][c] = false; } static void printBoard(boolean b[][]) { for (int r = 0; r < dimy; r++) { for (int c = 0; c < dimx; c++) { if (b[r][c]) { System.out.print("o"); } else { System.out.print("."); } } System.out.println(); } } static Move getMove() throws IOException { printBoard(board); System.out.print("? "); String move = in.readLine(); System.out.println(); int moveDigits = Integer.parseInt(move); int r = moveDigits / 10 - 1; int c = moveDigits % 10 - 1; return new Move(r, c); } static boolean[][] copyBoard(boolean[][] b) { boolean[][] cb = new boolean[dimy][dimx]; for (int r = 0; r < dimy; r++) for (int c = 0; c < dimx; c++) cb[r][c] = b[r][c]; return cb; } static boolean negamax(boolean[][] b, int d) { int rx = 0; int cx = 0; for (int r = 0; r < dimy; r++) { for (int c = 0; c < dimx; c++) { if (b[r][c]) { if (r == 0 && c == 0) continue; rx = r; cx = c; boolean[][] mb = copyBoard(b); makeMove(mb, r, c); if (negamax(mb, d + 1)) continue; if (d == 0) { System.out.println("> " + (10 * (r + 1) + (c + 1)) + " :-)"); makeMove(b, r, c); } return true; } } } if (d == 0) { System.out.print("> " + (10 * (rx + 1) + (cx + 1))); if (rx == 0 && cx == 0) System.out.println(" :-("); else System.out.println(" :-P"); makeMove(b, rx, cx); System.out.println(); } return false; } static void computeMove() { printBoard(board); negamax(board, 0); } public static void main(String args[]) throws IOException { initBoard(); while (true) { Move m = getMove(); if (!board[m.r][m.c]) { System.out.println("Illegal Move"); continue; } if (m.r == 0 && m.c == 0) { System.out.println("I win"); break; } makeMove(board, m.r, m.c); computeMove(); if (!board[0][0]) { System.out.println("You win"); break; } } } }
decorated poison square with *
Chomp.java
decorated poison square with *
<ide><path>homp.java <ide> for (int r = 0; r < dimy; r++) { <ide> for (int c = 0; c < dimx; c++) { <ide> if (b[r][c]) { <del> System.out.print("o"); <add> if (r == 0 && c == 0) <add> System.out.print("*"); <add> else <add> System.out.print("o"); <ide> } else { <ide> System.out.print("."); <ide> }
JavaScript
bsd-3-clause
3ac8479d17a09ac3f27ebe8b492e544dc425b492
0
Anaethelion/django-mapentity,makinacorpus/django-mapentity,makinacorpus/django-mapentity,Anaethelion/django-mapentity,Anaethelion/django-mapentity,makinacorpus/django-mapentity
if (!MapEntity) var MapEntity = {}; MapEntity.ObjectsLayer = L.GeoJSON.extend({ COLOR: 'blue', HIGHLIGHT: 'red', WEIGHT: 2, OPACITY: 0.8, includes: L.Mixin.Events, initialize: function (geojson, options) { // Hold the definition of all layers - immutable this._objects = {}; // Hold the currently added layers (subset of _objects) this._current_objects = {}; this.spinner = null; this.rtree = new RTree(); var onFeatureParse = function (geojson, layer) { this._mapObjects(geojson, layer); if (this._onEachFeature) this._onEachFeature(geojson, layer); }; var pointToLayer = function (geojson, latlng) { if (this._pointToLayer) return this._pointToLayer(geojson, latlng); return new L.CircleMarker(latlng); }; if (!options) options = {}; options.highlight = options.highlight || typeof(options.objectUrl) != 'undefined'; this._onEachFeature = options.onEachFeature; options.onEachFeature = L.Util.bind(onFeatureParse, this); this._pointToLayer = options.pointToLayer; options.pointToLayer = L.Util.bind(pointToLayer, this); var self = this; if (!options.style) { options.style = function (geojson) { return { color: self.COLOR, opacity: self.OPACITY, fillOpacity: self.OPACITY * 0.9, weight: self.WEIGHT } }; } var dataurl = null; if (typeof(geojson) == 'string') { dataurl = geojson; geojson = null; } L.GeoJSON.prototype.initialize.call(this, geojson, options); if (dataurl) { this.load(dataurl); } }, _rtbounds: function (bounds) { return {x: bounds.getSouthWest().lng, y: bounds.getSouthWest().lat, w: bounds.getSouthEast().lng - bounds.getSouthWest().lng, h: bounds.getNorthWest().lat - bounds.getSouthWest().lat}; }, _mapObjects: function (geojson, layer) { var pk = geojson.properties.pk this._objects[pk] = this._current_objects[pk] = layer; layer.properties = geojson.properties; // Spatial indexing var bounds = null; if (layer instanceof L.MultiPolyline) { bounds = new L.LatLngBounds(); for (var i in layer._layers) { bounds.extend(layer._layers[i].getBounds()); } } else if (layer.getBounds) { bounds = layer.getBounds(); } else { bounds = new L.LatLngBounds(layer.getLatLng(), layer.getLatLng()); } this.rtree.insert(this._rtbounds(bounds), layer); // Highlight on mouse over if (this.options.highlight) { layer.on('mouseover', L.Util.bind(function (e) { this.highlight(pk); }, this)); layer.on('mouseout', L.Util.bind(function (e) { this.highlight(pk, false); }, this)); } // Optionnaly make them clickable if (this.options.objectUrl) { layer.on('click', L.Util.bind(function (e) { window.location = this.options.objectUrl(geojson, layer); }, this)); } }, load: function (url) { var jsonLoad = function (data) { this.addData(data); this.fire('load'); if (this.spinner) this.spinner.stop(); }; if (this._map) this.spinner = new Spinner().spin(this._map._container); $.getJSON(url, L.Util.bind(jsonLoad, this)); }, getLayer: function (pk) { return this._objects[pk]; }, getPk: function(layer) { return layer.properties && layer.properties.pk; }, search: function (bounds) { var rtbounds = this._rtbounds(bounds); return this.rtree.search(rtbounds) || []; }, // Show all layers matching the pks updateFromPks: function(pks) { var self = this , new_objects = {} , already_added_layer , to_add_layer ; // Gather all layer to see in new objects // Remove them from _current_objects if they are already shown // This way _current_objects will only contain layer to be removed $.each(pks, function(idx, to_add_pk) { already_added_layer = self._current_objects[to_add_pk]; if (already_added_layer) { new_objects[to_add_pk] = already_added_layer; delete self._current_objects[to_add_pk] } else { to_add_layer = new_objects[to_add_pk] = self._objects[to_add_pk]; // list can be ready before map, on first load if (to_add_layer) self.addLayer(to_add_layer); } }); // Remove all remaining layer $.each(self._current_objects, function(pk, layer) { self.removeLayer(layer); }); self._current_objects = new_objects; }, highlight: function (pk, on) { var off = false; if (arguments.length == 2) off = !on; var l = this.getLayer(pk); if (l) l.setStyle({ 'opacity': off ? 0.8 : 1.0, 'color': off ? 'blue' : 'red', 'weight': off ? 2 : 5, }); }, }); MapEntity.getWKT = function(layer) { coord2str = function (obj) { if(obj.lng) return obj.lng + ' ' + obj.lat + ' 0.0'; var n, wkt = []; for (n in obj) { wkt.push(coord2str(obj[n])); } return ("(" + String(wkt) + ")"); }; var coords = '()'; if(layer.getLatLng) { coords = '(' + coord2str(layer.getLatLng()) + ')'; } else if (layer.getLatLngs) { coords = '(' + coord2str(layer.getLatLngs()) + ')'; } var wkt = ''; if (layer instanceof L.Marker) wkt += 'POINT'+coords; else if (layer instanceof L.Polygon) wkt += 'POLYGON'+coords; else if (layer instanceof L.MultiPolygon) wkt += 'MULTIPOLYGON'+coords; else if (layer instanceof L.Polyline) wkt += 'LINESTRING'+coords; else if (layer instanceof L.MultiPolyline) wkt += 'MULTILINESTRING'+coords; else { wkt += 'GEOMETRY'+coords; } return wkt; }; L.Control.Information = L.Control.extend({ options: { position: 'bottomright', }, onAdd: function (map) { this._container = L.DomUtil.create('div', 'leaflet-control-attribution'); L.DomEvent.disableClickPropagation(this._container); map.on('layeradd', this._onLayerAdd, this) .on('layerremove', this._onLayerRemove, this); return this._container; }, onRemove: function (map) { map.off('layeradd', this._onLayerAdd) .off('layerremove', this._onLayerRemove); }, _onLayerAdd: function (e) { e.layer.on('info', L.Util.bind(function (ei) { this._container.innerHTML = ei.info; }, this)); }, _onLayerRemove: function (e) { e.layer.off('info'); } }); MapEntity.MarkerSnapping = L.Handler.extend({ SNAP_DISTANCE: 15, // snap on marker move TOLERANCE: 0.00005, // snap existing object initialize: function (map, marker) { L.Handler.prototype.initialize.call(this, map); this._snaplist = []; this._markers = [] if (marker) { // new markers should be draggable ! if (!marker.dragging) marker.dragging = new L.Handler.MarkerDrag(marker); marker.dragging.enable(); this.snapMarker(marker); } }, enable: function () { this.disable(); for (var i=0; i<this._markers.length; i++) { this.snapMarker(this._markers[i]); } }, disable: function () { for (var i=0; i<this._markers.length; i++) { this.unsnapMarker(this._markers[i]); } }, snapMarker: function (marker) { var i=0; for (; i<this._markers.length; i++) { if (this._markers[i] == marker) break; } if (i==this._markers.length) this._markers.push(marker); marker.on('move', this._snapMarker, this); }, unsnapMarker: function (marker) { marker.off('move', this._snapMarker); }, setSnapList: function (l) { l = l || []; this._snaplist = l; for (var i=0; i<this._markers.length; i++) { var marker = this._markers[i]; // Mark as snap if any object of snaplist is already snapped ! var closest = this._closest(marker), chosen = closest[0], point = closest[1]; if (point && (Math.abs(point.lat - marker.getLatLng().lat) < this.TOLERANCE) && (Math.abs(point.lng - marker.getLatLng().lng) < this.TOLERANCE)) { $(marker._icon).addClass('marker-snapped'); } } }, distance: function (latlng1, latlng2) { return this._map.latLngToLayerPoint(latlng1).distanceTo(this._map.latLngToLayerPoint(latlng2)); }, distanceSegment: function (latlng, latlngA, latlngB) { var p = this._map.latLngToLayerPoint(latlng), p1 = this._map.latLngToLayerPoint(latlngA), p2 = this._map.latLngToLayerPoint(latlngB); return L.LineUtil.pointToSegmentDistance(p, p1, p2); }, latlngOnSegment: function (latlng, latlngA, latlngB) { var p = this._map.latLngToLayerPoint(latlng), p1 = this._map.latLngToLayerPoint(latlngA), p2 = this._map.latLngToLayerPoint(latlngB); closest = L.LineUtil.closestPointOnSegment(p, p1, p2); return this._map.layerPointToLatLng(closest); }, _closest: function (marker) { var mindist = Number.MAX_VALUE, chosen = null, point = null; var n = this._snaplist.length; // /!\ Careful with size of this list, iterated at every marker move! if (n>1000) console.warn("Snap list is very big : " + n + " objects!"); // Iterate the whole snaplist for (var i = 0; i < n ; i++) { var object = this._snaplist[i], ll = null, distance = Number.MAX_VALUE; if (object.getLatLng) { // Single dimension, snap on points ll = object.getLatLng(); distance = this.distance(marker.getLatLng(), ll); } else { // Iterate on line segments var lls = object.getLatLngs(), segmentmindist = Number.MAX_VALUE; // Keep the closest point of all segments for (var j = 0; j < lls.length - 1; j++) { var p1 = lls[j], p2 = lls[j+1], d = this.distanceSegment(marker.getLatLng(), p1, p2); if (d < segmentmindist) { segmentmindist = d; ll = this.latlngOnSegment(marker.getLatLng(), p1, p2); distance = d; } } } // Keep the closest point of all objects if (distance < this.SNAP_DISTANCE && distance < mindist) { mindist = distance; chosen = object; point = ll; } } return [chosen, point]; }, _snapMarker: function (e) { var marker = e.target var closest = this._closest(marker), chosen = closest[0], point = closest[1]; if (chosen) { marker.setLatLng(point); if (marker.snap != chosen) { marker.snap = chosen; $(marker._icon).addClass('marker-snapped'); marker.fire('snap', {object:chosen, location: point}); } } else { if (marker.snap) { $(marker._icon).removeClass('marker-snapped'); marker.fire('unsnap', {object:marker.snap}); } marker.snap = null; } }, }); L.Handler.SnappedEdit = L.Handler.PolyEdit.extend({ initialize: function (map, poly, options) { L.Handler.PolyEdit.prototype.initialize.call(this, poly, options); this._snapper = new MapEntity.MarkerSnapping(map); }, setSnapList: function (l) { this._snapper.setSnapList(l); }, _createMarker: function (latlng, index) { var marker = L.Handler.PolyEdit.prototype._createMarker.call(this, latlng, index); this._snapper.snapMarker(marker); return marker; }, }); MapEntity.SnapObserver = L.Class.extend({ MIN_SNAP_ZOOM: 7, initialize: function (map, guidesLayer) { this._map = map; this._guidesLayer = guidesLayer; this._editionLayers = []; guidesLayer.on('load', this._refresh, this); map.on('viewreset moveend', this._refresh, this); }, add: function (editionLayer) { if (editionLayer.eachLayer) { editionLayer.eachLayer(function (l) { this.add(l); }, this); } else { this._editionLayers.push(editionLayer); editionLayer.editing.setSnapList(this.snapList()); } }, remove: function (editionLayer) { //TODO }, snapList: function () { if (this._map.getZoom() > this.MIN_SNAP_ZOOM) { return this._guidesLayer.search(this._map.getBounds()); } console.log('No snapping at zoom level ' + this._map.getZoom()); return []; }, _refresh: function () { for (var i=0; i < this._editionLayers.length; i++) { var editionLayer = this._editionLayers[i]; editionLayer.editing.setSnapList(this.snapList()); } } }); MapEntity.makeGeoFieldProxy = function($field, layer) { // Proxy to field storing WKT. It also stores the matching layer. var _current_layer = layer || null; return { storeLayerGeomInField: function(layer) { var old_layer = _current_layer; _current_layer = layer; var wkt = layer ? MapEntity.getWKT(layer) : ''; $field.val(wkt); return old_layer; }, getLayer: function () { return _current_layer; }, storeTopologyInField: function (topology) { var old_layer = _current_layer; _current_layer = topology; $field.val(JSON.stringify(topology)); return old_layer; }, }; }; MapEntity.resetForm = function resetForm($form) { $form.find('input:text, input:password, input:file, select, textarea').val(''); $form.find('input:radio, input:checkbox') .removeAttr('checked').removeAttr('selected'); } MapEntity.showNumberSearchResults = function (nb) { if (arguments.length > 0) { localStorage.setItem('list-search-results', nb); } else { nb = localStorage.getItem('list-search-results') || '?'; } $('#nbresults').text(nb); }
mapentity/static/mapentity/mapentity.js
if (!MapEntity) var MapEntity = {}; MapEntity.ObjectsLayer = L.GeoJSON.extend({ COLOR: 'blue', HIGHLIGHT: 'red', WEIGHT: 2, OPACITY: 0.8, includes: L.Mixin.Events, initialize: function (geojson, options) { // Hold the definition of all layers - immutable this._objects = {}; // Hold the currently added layers (subset of _objects) this._current_objects = {}; this.spinner = null; this.rtree = new RTree(); var onFeatureParse = function (geojson, layer) { this._mapObjects(geojson, layer); if (this._onEachFeature) this._onEachFeature(geojson, layer); }; var pointToLayer = function (geojson, latlng) { if (this._pointToLayer) return this._pointToLayer(geojson, latlng); return new L.CircleMarker(latlng); }; if (!options) options = {}; options.highlight = options.highlight || typeof(options.objectUrl) != 'undefined'; this._onEachFeature = options.onEachFeature; options.onEachFeature = L.Util.bind(onFeatureParse, this); this._pointToLayer = options.pointToLayer; options.pointToLayer = L.Util.bind(pointToLayer, this); var self = this; if (!options.style) { options.style = function (geojson) { return { color: self.COLOR, opacity: self.OPACITY, fillOpacity: self.OPACITY * 0.9, weight: self.WEIGHT } }; } var dataurl = null; if (typeof(geojson) == 'string') { dataurl = geojson; geojson = null; } L.GeoJSON.prototype.initialize.call(this, geojson, options); if (dataurl) { this.load(dataurl); } }, _rtbounds: function (bounds) { return {x: bounds.getSouthWest().lng, y: bounds.getSouthWest().lat, w: bounds.getSouthEast().lng - bounds.getSouthWest().lng, h: bounds.getNorthWest().lat - bounds.getSouthWest().lat}; }, _mapObjects: function (geojson, layer) { var pk = geojson.properties.pk this._objects[pk] = this._current_objects[pk] = layer; layer.properties = geojson.properties; // Spatial indexing var bounds = null; if (layer instanceof L.MultiPolyline) { bounds = new L.LatLngBounds(); for (var i in layer._layers) { bounds.extend(layer._layers[i].getBounds()); } console.log(bounds); } else if (layer.getBounds) { bounds = layer.getBounds(); } else { bounds = new L.LatLngBounds(layer.getLatLng(), layer.getLatLng()); } this.rtree.insert(this._rtbounds(bounds), layer); // Highlight on mouse over if (this.options.highlight) { layer.on('mouseover', L.Util.bind(function (e) { this.highlight(pk); }, this)); layer.on('mouseout', L.Util.bind(function (e) { this.highlight(pk, false); }, this)); } // Optionnaly make them clickable if (this.options.objectUrl) { layer.on('click', L.Util.bind(function (e) { window.location = this.options.objectUrl(geojson, layer); }, this)); } }, load: function (url) { var jsonLoad = function (data) { this.addData(data); this.fire('load'); if (this.spinner) this.spinner.stop(); }; if (this._map) this.spinner = new Spinner().spin(this._map._container); $.getJSON(url, L.Util.bind(jsonLoad, this)); }, getLayer: function (pk) { return this._objects[pk]; }, getPk: function(layer) { return layer.properties && layer.properties.pk; }, search: function (bounds) { var rtbounds = this._rtbounds(bounds); return this.rtree.search(rtbounds) || []; }, // Show all layers matching the pks updateFromPks: function(pks) { var self = this , new_objects = {} , already_added_layer , to_add_layer ; // Gather all layer to see in new objects // Remove them from _current_objects if they are already shown // This way _current_objects will only contain layer to be removed $.each(pks, function(idx, to_add_pk) { already_added_layer = self._current_objects[to_add_pk]; if (already_added_layer) { new_objects[to_add_pk] = already_added_layer; delete self._current_objects[to_add_pk] } else { to_add_layer = new_objects[to_add_pk] = self._objects[to_add_pk]; // list can be ready before map, on first load if (to_add_layer) self.addLayer(to_add_layer); } }); // Remove all remaining layer $.each(self._current_objects, function(pk, layer) { self.removeLayer(layer); }); self._current_objects = new_objects; }, highlight: function (pk, on) { var off = false; if (arguments.length == 2) off = !on; var l = this.getLayer(pk); if (l) l.setStyle({ 'opacity': off ? 0.8 : 1.0, 'color': off ? 'blue' : 'red', 'weight': off ? 2 : 5, }); }, }); MapEntity.getWKT = function(layer) { coord2str = function (obj) { if(obj.lng) return obj.lng + ' ' + obj.lat + ' 0.0'; var n, wkt = []; for (n in obj) { wkt.push(coord2str(obj[n])); } return ("(" + String(wkt) + ")"); }; var coords = '()'; if(layer.getLatLng) { coords = '(' + coord2str(layer.getLatLng()) + ')'; } else if (layer.getLatLngs) { coords = '(' + coord2str(layer.getLatLngs()) + ')'; } var wkt = ''; if (layer instanceof L.Marker) wkt += 'POINT'+coords; else if (layer instanceof L.Polygon) wkt += 'POLYGON'+coords; else if (layer instanceof L.MultiPolygon) wkt += 'MULTIPOLYGON'+coords; else if (layer instanceof L.Polyline) wkt += 'LINESTRING'+coords; else if (layer instanceof L.MultiPolyline) wkt += 'MULTILINESTRING'+coords; else { wkt += 'GEOMETRY'+coords; } return wkt; }; L.Control.Information = L.Control.extend({ options: { position: 'bottomright', }, onAdd: function (map) { this._container = L.DomUtil.create('div', 'leaflet-control-attribution'); L.DomEvent.disableClickPropagation(this._container); map.on('layeradd', this._onLayerAdd, this) .on('layerremove', this._onLayerRemove, this); return this._container; }, onRemove: function (map) { map.off('layeradd', this._onLayerAdd) .off('layerremove', this._onLayerRemove); }, _onLayerAdd: function (e) { e.layer.on('info', L.Util.bind(function (ei) { this._container.innerHTML = ei.info; }, this)); }, _onLayerRemove: function (e) { e.layer.off('info'); } }); MapEntity.MarkerSnapping = L.Handler.extend({ SNAP_DISTANCE: 15, // snap on marker move TOLERANCE: 0.00005, // snap existing object initialize: function (map, marker) { L.Handler.prototype.initialize.call(this, map); this._snaplist = []; this._markers = [] if (marker) { // new markers should be draggable ! if (!marker.dragging) marker.dragging = new L.Handler.MarkerDrag(marker); marker.dragging.enable(); this.snapMarker(marker); } }, enable: function () { this.disable(); for (var i=0; i<this._markers.length; i++) { this.snapMarker(this._markers[i]); } }, disable: function () { for (var i=0; i<this._markers.length; i++) { this.unsnapMarker(this._markers[i]); } }, snapMarker: function (marker) { var i=0; for (; i<this._markers.length; i++) { if (this._markers[i] == marker) break; } if (i==this._markers.length) this._markers.push(marker); marker.on('move', this._snapMarker, this); }, unsnapMarker: function (marker) { marker.off('move', this._snapMarker); }, setSnapList: function (l) { l = l || []; this._snaplist = l; for (var i=0; i<this._markers.length; i++) { var marker = this._markers[i]; // Mark as snap if any object of snaplist is already snapped ! var closest = this._closest(marker), chosen = closest[0], point = closest[1]; if (point && (Math.abs(point.lat - marker.getLatLng().lat) < this.TOLERANCE) && (Math.abs(point.lng - marker.getLatLng().lng) < this.TOLERANCE)) { $(marker._icon).addClass('marker-snapped'); } } }, distance: function (latlng1, latlng2) { return this._map.latLngToLayerPoint(latlng1).distanceTo(this._map.latLngToLayerPoint(latlng2)); }, distanceSegment: function (latlng, latlngA, latlngB) { var p = this._map.latLngToLayerPoint(latlng), p1 = this._map.latLngToLayerPoint(latlngA), p2 = this._map.latLngToLayerPoint(latlngB); return L.LineUtil.pointToSegmentDistance(p, p1, p2); }, latlngOnSegment: function (latlng, latlngA, latlngB) { var p = this._map.latLngToLayerPoint(latlng), p1 = this._map.latLngToLayerPoint(latlngA), p2 = this._map.latLngToLayerPoint(latlngB); closest = L.LineUtil.closestPointOnSegment(p, p1, p2); return this._map.layerPointToLatLng(closest); }, _closest: function (marker) { var mindist = Number.MAX_VALUE, chosen = null, point = null; var n = this._snaplist.length; // /!\ Careful with size of this list, iterated at every marker move! if (n>1000) console.warn("Snap list is very big : " + n + " objects!"); // Iterate the whole snaplist for (var i = 0; i < n ; i++) { var object = this._snaplist[i], ll = null, distance = Number.MAX_VALUE; if (object.getLatLng) { // Single dimension, snap on points ll = object.getLatLng(); distance = this.distance(marker.getLatLng(), ll); } else { // Iterate on line segments var lls = object.getLatLngs(), segmentmindist = Number.MAX_VALUE; // Keep the closest point of all segments for (var j = 0; j < lls.length - 1; j++) { var p1 = lls[j], p2 = lls[j+1], d = this.distanceSegment(marker.getLatLng(), p1, p2); if (d < segmentmindist) { segmentmindist = d; ll = this.latlngOnSegment(marker.getLatLng(), p1, p2); distance = d; } } } // Keep the closest point of all objects if (distance < this.SNAP_DISTANCE && distance < mindist) { mindist = distance; chosen = object; point = ll; } } return [chosen, point]; }, _snapMarker: function (e) { var marker = e.target var closest = this._closest(marker), chosen = closest[0], point = closest[1]; if (chosen) { marker.setLatLng(point); if (marker.snap != chosen) { marker.snap = chosen; $(marker._icon).addClass('marker-snapped'); marker.fire('snap', {object:chosen, location: point}); } } else { if (marker.snap) { $(marker._icon).removeClass('marker-snapped'); marker.fire('unsnap', {object:marker.snap}); } marker.snap = null; } }, }); L.Handler.SnappedEdit = L.Handler.PolyEdit.extend({ initialize: function (map, poly, options) { L.Handler.PolyEdit.prototype.initialize.call(this, poly, options); this._snapper = new MapEntity.MarkerSnapping(map); }, setSnapList: function (l) { this._snapper.setSnapList(l); }, _createMarker: function (latlng, index) { var marker = L.Handler.PolyEdit.prototype._createMarker.call(this, latlng, index); this._snapper.snapMarker(marker); return marker; }, }); MapEntity.SnapObserver = L.Class.extend({ MIN_SNAP_ZOOM: 7, initialize: function (map, guidesLayer) { this._map = map; this._guidesLayer = guidesLayer; this._editionLayers = []; guidesLayer.on('load', this._refresh, this); map.on('viewreset moveend', this._refresh, this); }, add: function (editionLayer) { if (editionLayer.eachLayer) { editionLayer.eachLayer(function (l) { this.add(l); }, this); } else { this._editionLayers.push(editionLayer); editionLayer.editing.setSnapList(this.snapList()); } }, remove: function (editionLayer) { //TODO }, snapList: function () { if (this._map.getZoom() > this.MIN_SNAP_ZOOM) { return this._guidesLayer.search(this._map.getBounds()); } console.log('No snapping at zoom level ' + this._map.getZoom()); return []; }, _refresh: function () { for (var i=0; i < this._editionLayers.length; i++) { var editionLayer = this._editionLayers[i]; editionLayer.editing.setSnapList(this.snapList()); } } }); MapEntity.makeGeoFieldProxy = function($field, layer) { // Proxy to field storing WKT. It also stores the matching layer. var _current_layer = layer || null; return { storeLayerGeomInField: function(layer) { var old_layer = _current_layer; _current_layer = layer; var wkt = layer ? MapEntity.getWKT(layer) : ''; $field.val(wkt); return old_layer; }, getLayer: function () { return _current_layer; }, storeTopologyInField: function (topology) { var old_layer = _current_layer; _current_layer = topology; $field.val(JSON.stringify(topology)); return old_layer; }, }; }; MapEntity.resetForm = function resetForm($form) { $form.find('input:text, input:password, input:file, select, textarea').val(''); $form.find('input:radio, input:checkbox') .removeAttr('checked').removeAttr('selected'); } MapEntity.showNumberSearchResults = function (nb) { if (arguments.length > 0) { localStorage.setItem('list-search-results', nb); } else { nb = localStorage.getItem('list-search-results') || '?'; } $('#nbresults').text(nb); }
Show first column clickable for infrastructure (ref #141)
mapentity/static/mapentity/mapentity.js
Show first column clickable for infrastructure (ref #141)
<ide><path>apentity/static/mapentity/mapentity.js <ide> for (var i in layer._layers) { <ide> bounds.extend(layer._layers[i].getBounds()); <ide> } <del> console.log(bounds); <ide> } <ide> else if (layer.getBounds) { <ide> bounds = layer.getBounds();
Java
apache-2.0
43007368acf25889a4620d34d123073e3accabf1
0
euclio/learnalanguage
package com.acrussell.learnalanguage; import java.awt.Font; import java.io.IOException; import java.io.OutputStream; import javax.swing.JTextArea; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultCaret; @SuppressWarnings("serial") public class Console extends JTextArea { private static final Font TERMINAL_FONT = new Font("Monospaced", Font.PLAIN, 12); private int maxLines = 80; private void updateTextArea(final String text) { Console.this.append(text); } private OutputStream writer = new OutputStream() { @Override public void write(int b) throws IOException { updateTextArea(String.valueOf((char) b)); } @Override public void write(byte[] b, int off, int len) throws IOException { updateTextArea(new String(b, off, len)); } @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } }; /** * Constructs a new Console with the given rows and columns, and initializes * with the given text. * * @param text * The text displayed initially on the Console * @param rows * The number of rows in the Console * @param cols * The number of columns in the Console */ public Console(String text, int rows, int cols) { super(rows, cols); this.setFont(TERMINAL_FONT); this.setCaretPosition(0); DefaultCaret caret = (DefaultCaret) this.getCaret(); caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); this.setEditable(false); this.append(text); } /** * Constructs a new Console with the given rows and columns * * @param rows * The number of rows in the Console * @param cols * The number of columns in the Console */ public Console(int rows, int cols) { this(null, rows, cols); } /** * Appends the given text to the component with a trailing newline. * * @param text * The text to be added to the component * @see #append(String) */ public void appendLine(String text) { append(text + "\n"); } /** * Appends the given parameter to the component. Works similarly to * JTextArea's append, but it limits the amount of lines that can be written * to the component. * * @param text * The text to be added to the component */ @Override public void append(String text) { try { getDocument().insertString(getDocument().getLength(), text, null); int lines = getDocument().getDefaultRootElement().getElementCount(); if (lines > maxLines) { int firstGoodLine = lines - maxLines; // Delete each line above the max number of lines, oldest first replaceRange(null, 0, getDocument().getDefaultRootElement() .getElement(firstGoodLine).getStartOffset()); } } catch (BadLocationException e) { System.err.println("Error: Could not write to console."); } // Ensure that the cursor remains at the end of the console this.setCaretPosition(this.getDocument().getLength()); } /** * @return The output stream that writes to this component */ public OutputStream getStream() { return writer; } /** * @param num * The max number lines this component should show */ public void setMaxLines(int num) { this.maxLines = num; } }
src/com/acrussell/learnalanguage/Console.java
package com.acrussell.learnalanguage; import java.awt.Font; import java.io.IOException; import java.io.OutputStream; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultCaret; @SuppressWarnings("serial") public class Console extends JTextArea { private static final Font TERMINAL_FONT = new Font("Monospaced", Font.PLAIN, 12); private int maxLines = 80; /* * Writes an output stream byte by byte to the underlying Text component. */ // private OutputStream writer = new OutputStream() { // public void write(final int b) { // append(String.valueOf((char) b)); // } // }; private void updateTextArea(final String text) { SwingUtilities.invokeLater(new Runnable() { public void run() { Console.this.append(text); } }); } private OutputStream writer = new OutputStream() { @Override public void write(int b) throws IOException { updateTextArea(String.valueOf((char) b)); } @Override public void write(byte[] b, int off, int len) throws IOException { updateTextArea(new String(b, off, len)); } @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } }; /** * Constructs a new Console with the given rows and columns, and initializes * with the given text. * * @param text * The text displayed initially on the Console * @param rows * The number of rows in the Console * @param cols * The number of columns in the Console */ public Console(String text, int rows, int cols) { super(rows, cols); this.setFont(TERMINAL_FONT); this.setCaretPosition(0); DefaultCaret caret = (DefaultCaret) this.getCaret(); caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); this.setEditable(false); this.append(text); } /** * Constructs a new Console with the given rows and columns * * @param rows * The number of rows in the Console * @param cols * The number of columns in the Console */ public Console(int rows, int cols) { this(null, rows, cols); } /** * Appends the given text to the component with a trailing newline. * * @param text * The text to be added to the component * @see #append(String) */ public void appendLine(String text) { append(text + "\n"); } /** * Appends the given parameter to the component. Works similarly to * JTextArea's append, but it limits the amount of lines that can be written * to the component. * * @param text * The text to be added to the component */ @Override public void append(String text) { try { getDocument().insertString(getDocument().getLength(), text, null); int lines = getDocument().getDefaultRootElement().getElementCount(); if (lines > maxLines) { int firstGoodLine = lines - maxLines; // Delete each line above the max number of lines, oldest first replaceRange(null, 0, getDocument().getDefaultRootElement() .getElement(firstGoodLine).getStartOffset()); } } catch (BadLocationException e) { System.err.println("Error: Could not write to console."); } // Ensure that the cursor remains at the end of the console this.setCaretPosition(this.getDocument().getLength()); } /** * @return The output stream that writes to this component */ public OutputStream getStream() { return writer; } /** * @param num * The max number lines this component should show */ public void setMaxLines(int num) { this.maxLines = num; } }
Rewrote updateTextArea() to not depend on new threads
src/com/acrussell/learnalanguage/Console.java
Rewrote updateTextArea() to not depend on new threads
<ide><path>rc/com/acrussell/learnalanguage/Console.java <ide> import java.io.OutputStream; <ide> <ide> import javax.swing.JTextArea; <del>import javax.swing.SwingUtilities; <ide> import javax.swing.text.BadLocationException; <ide> import javax.swing.text.DefaultCaret; <ide> <ide> <ide> private int maxLines = 80; <ide> <del> /* <del> * Writes an output stream byte by byte to the underlying Text component. <del> */ <del>// private OutputStream writer = new OutputStream() { <del>// public void write(final int b) { <del>// append(String.valueOf((char) b)); <del>// } <del>// }; <del> <ide> private void updateTextArea(final String text) { <del> SwingUtilities.invokeLater(new Runnable() { <del> public void run() { <del> Console.this.append(text); <del> } <del> }); <add> Console.this.append(text); <ide> } <del> <add> <ide> private OutputStream writer = new OutputStream() { <ide> @Override <ide> public void write(int b) throws IOException { <del> updateTextArea(String.valueOf((char) b)); <add> updateTextArea(String.valueOf((char) b)); <ide> } <del> <add> <ide> @Override <ide> public void write(byte[] b, int off, int len) throws IOException { <del> updateTextArea(new String(b, off, len)); <add> updateTextArea(new String(b, off, len)); <ide> } <del> <add> <ide> @Override <ide> public void write(byte[] b) throws IOException { <del> write(b, 0, b.length); <add> write(b, 0, b.length); <ide> } <del> }; <add> }; <ide> <ide> /** <ide> * Constructs a new Console with the given rows and columns, and initializes
Java
apache-2.0
21a7cc1b0470865b70e557e75768639eb146cbc5
0
Peppe/vaadin,shahrzadmn/vaadin,sitexa/vaadin,oalles/vaadin,fireflyc/vaadin,udayinfy/vaadin,shahrzadmn/vaadin,shahrzadmn/vaadin,oalles/vaadin,peterl1084/framework,Legioth/vaadin,Scarlethue/vaadin,peterl1084/framework,travisfw/vaadin,udayinfy/vaadin,Scarlethue/vaadin,travisfw/vaadin,udayinfy/vaadin,jdahlstrom/vaadin.react,udayinfy/vaadin,asashour/framework,Darsstar/framework,synes/vaadin,cbmeeks/vaadin,asashour/framework,jdahlstrom/vaadin.react,cbmeeks/vaadin,sitexa/vaadin,shahrzadmn/vaadin,peterl1084/framework,mstahv/framework,carrchang/vaadin,synes/vaadin,jdahlstrom/vaadin.react,Scarlethue/vaadin,mittop/vaadin,Flamenco/vaadin,Scarlethue/vaadin,peterl1084/framework,kironapublic/vaadin,sitexa/vaadin,oalles/vaadin,synes/vaadin,fireflyc/vaadin,Darsstar/framework,synes/vaadin,synes/vaadin,Peppe/vaadin,kironapublic/vaadin,travisfw/vaadin,fireflyc/vaadin,mstahv/framework,mittop/vaadin,magi42/vaadin,Peppe/vaadin,carrchang/vaadin,oalles/vaadin,Flamenco/vaadin,Legioth/vaadin,asashour/framework,bmitc/vaadin,asashour/framework,udayinfy/vaadin,magi42/vaadin,kironapublic/vaadin,Peppe/vaadin,sitexa/vaadin,bmitc/vaadin,Darsstar/framework,carrchang/vaadin,kironapublic/vaadin,Legioth/vaadin,peterl1084/framework,Darsstar/framework,mstahv/framework,jdahlstrom/vaadin.react,fireflyc/vaadin,travisfw/vaadin,bmitc/vaadin,mstahv/framework,mittop/vaadin,Peppe/vaadin,asashour/framework,travisfw/vaadin,magi42/vaadin,sitexa/vaadin,magi42/vaadin,Legioth/vaadin,jdahlstrom/vaadin.react,cbmeeks/vaadin,shahrzadmn/vaadin,cbmeeks/vaadin,Legioth/vaadin,Flamenco/vaadin,Scarlethue/vaadin,bmitc/vaadin,Flamenco/vaadin,carrchang/vaadin,magi42/vaadin,kironapublic/vaadin,fireflyc/vaadin,oalles/vaadin,mstahv/framework,mittop/vaadin,Darsstar/framework
/* ************************************************************************* IT Mill Toolkit Development of Browser User Intarfaces Made Easy Copyright (C) 2000-2006 IT Mill Ltd ************************************************************************* This product is distributed under commercial license that can be found from the product package on license/license.txt. Use of this product might require purchasing a commercial license from IT Mill Ltd. For guidelines on usage, see license/licensing-guidelines.html ************************************************************************* For more information, contact: IT Mill Ltd phone: +358 2 4802 7180 Ruukinkatu 2-4 fax: +358 2 4802 7181 20540, Turku email: [email protected] Finland company www: www.itmill.com Primary source for information and releases: www.itmill.com ********************************************************************** */ package com.itmill.toolkit.service; import java.io.ByteArrayInputStream; import java.io.CharArrayWriter; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Calendar; import java.util.Iterator; import java.util.TreeSet; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; public class License { /** IT Mill License Manager certificate */ private static String certificate = "-----BEGIN CERTIFICATE-----\n" + "MIIDJjCCAuQCBEVqxNwwCwYHKoZIzjgEAwUAMHkxCzAJBgNVBAYTAkZJMRAwDgYDVQQIEwdVbmtu\n" + "b3duMQ4wDAYDVQQHEwVUdXJrdTEUMBIGA1UEChMLSVQgTWlsbCBMdGQxEDAOBgNVBAsTB1Vua25v\n" + "d24xIDAeBgNVBAMTF0lUIE1pbGwgTGljZW5zZSBNYW5hZ2VyMB4XDTA2MTEyNzEwNTgzNloXDTQ3\n" + "MTIyMjEwNTgzNloweTELMAkGA1UEBhMCRkkxEDAOBgNVBAgTB1Vua25vd24xDjAMBgNVBAcTBVR1\n" + "cmt1MRQwEgYDVQQKEwtJVCBNaWxsIEx0ZDEQMA4GA1UECxMHVW5rbm93bjEgMB4GA1UEAxMXSVQg\n" + "TWlsbCBMaWNlbnNlIE1hbmFnZXIwggG3MIIBLAYHKoZIzjgEATCCAR8CgYEA/X9TgR11EilS30qc\n" + "Luzk5/YRt1I870QAwx4/gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZUKWk\n" + "n5/oBHsQIsJPu6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOuK2HXKu/yIgMZndFI\n" + "AccCFQCXYFCPFSMLzLKSuYKi64QL8Fgc9QKBgQD34aCF1ps93su8q1w2uFe5eZSvu/o66oL5V0wL\n" + "PQeCZ1FZV4661FlP5nEHEIGAtEkWcSPoTCgWE7fPCTKMyKbhPBZ6i1R8jSjgo64eK7OmdZFuo38L\n" + "+iE1YvH7YnoBJDvMpPG+qFGQiaiD3+Fa5Z8GkotmXoB7VSVkAUw7/s9JKgOBhAACgYB2wjpuZXqK\n" + "Ldgw1uZRlNCON7vo4m420CSna0mhETqzW9UMFHmZfn9edD0B1dDh6NwmRIDjljf8+ODuhwZKkzl8\n" + "DHUq3HPnipEsr0C3g1Dz7ZbjcvUhzsPDElpKBZhHRaoqfAfWiNxeVF2Kh2IlIMwuJ2xZeSaUH7Pj\n" + "LwAkKye6dzALBgcqhkjOOAQDBQADLwAwLAIUDgvWt7ItRyZfpWNEeJ0P9yaxOwoCFC21LRtwLi1t\n" + "c+yomHtX+mpxF7VO\n" + "-----END CERTIFICATE-----\n"; /** License XML Document */ private Document licenseXML = null; /** The signature has already been checked and is valid */ private boolean signatureIsValid = false; /** * Read the license-file from input stream. * * License file can only ne read once, after it has been read it stays. * * @param is * Input stream where the license file is read from. * @throws SAXException * Error parsing the license file * @throws IOException * Error reading the license file * @throws LicenseFileHasAlreadyBeenRead * License file has already been read. */ public void readLicenseFile(InputStream is) throws SAXException, IOException, LicenseFileHasAlreadyBeenRead { // Once the license has been read, it stays if (hasBeenRead()) throw new LicenseFileHasAlreadyBeenRead(); // Parse XML DocumentBuilder db; try { db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); licenseXML = db.parse(is); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } } /** * Is the license file already been read. * * @return true if the license-file has already been read. */ public boolean hasBeenRead() { return licenseXML != null; } /** Should the license description be printed on (first) application init. */ public boolean shouldLimitsBePrintedOnInit() throws LicenseFileHasNotBeenRead, LicenseSignatureIsInvalid, InvalidLicenseFile { checkThatLicenseDOMisValid(); NodeList lL = licenseXML.getElementsByTagName("limits"); if (lL == null || lL.getLength() > 0) throw new InvalidLicenseFile("limits not found from license-file"); Element e = (Element) lL.item(0); String print = e.getAttribute("print-limits-on-init"); return "true".equalsIgnoreCase(print); } public String getDescription() throws LicenseFileHasNotBeenRead, InvalidLicenseFile, LicenseSignatureIsInvalid { checkThatLicenseDOMisValid(); StringBuffer d = new StringBuffer(); d.append("------------------ License Info -----------------------\n"); d.append("License number: " + getLicenseNumber() + "\n"); d.append("Product: " + getProductName()); if (getProductEdition() != null) d.append(" Edition: " + getProductEdition()); d.append("\n"); // Print version info String versionDescription = getVersionDescription(); if (versionDescription != null) d.append("Version: " + versionDescription + "\n"); if (getLicenseeName() != null) d.append("Licensed to: " + getLicenseeName() + "\n"); if (getPurpose() != null) d.append("Use is limited to: " + getPurpose() + "\n"); if (getMaxConcurrentUsers() >= 0) d.append("Maximum number of concurrent (active) users allowed: " + getMaxConcurrentUsers() + "\n"); if (getMaxJVMs() >= 0) d.append("Maximum number of JVM:s this license" + " can be used concurrently: " + getMaxJVMs() + "\n"); // Print valid-until date NodeList vuL = licenseXML.getElementsByTagName("valid-until"); if (vuL != null && vuL.getLength() > 0) { Element e = (Element) vuL.item(0); String year = e.getAttribute("year"); String month = e.getAttribute("month"); String day = e.getAttribute("day"); d.append("License is valid until: " + year + "-" + month + "-" + day + "\n"); } // Print application info NodeList aL = licenseXML.getElementsByTagName("application"); if (aL != null && aL.getLength() > 0) { Element e = (Element) aL.item(0); String app = e.getAttribute("name"); String purpose = e.getAttribute("purpose"); String prefix = e.getAttribute("classPrefix"); if (app != null && app.length() > 0) d.append("For use with this application only: " + app + "\n"); if (app != null && app.length() > 0) d.append("Application usage purpose is limited to: " + purpose + "\n"); if (app != null && app.length() > 0) d.append("Application class name must match prefix: " + prefix + "\n"); } d.append("--------------------------------------------------------\n"); return d.toString(); } private void checkThatLicenseDOMisValid() throws LicenseFileHasNotBeenRead, InvalidLicenseFile, LicenseSignatureIsInvalid { // Check that the license file has already been read if (!hasBeenRead()) throw new LicenseFileHasNotBeenRead(); // Check validity of the signature if (!isSignatureValid()) throw new LicenseSignatureIsInvalid(); } /** * Check if the license valid for given usage? * * Checks that the license is valid for specified usage. Throws an exception * if there is something wrong with the license or use. * * @param applicationClass * Class of the application this license is used for * @param concurrentUsers * Number if users concurrently using this application * @param majorVersion * Major version number (for example 4 if version is 4.1.7) * @param minorVersion * Minor version number (for example 1 if version is 4.1.7) * @param productName * The name of the product * @param productEdition * The name of the product edition * @throws LicenseFileHasNotBeenRead * if the license file has not been read * @throws LicenseSignatureIsInvalid * if the license file has been changed or signature is * otherwise invalid * @throws InvalidLicenseFile * License if the license file is not of correct XML format * @throws LicenseViolation * */ public void check(Class applicationClass, int concurrentUsers, int majorVersion, int minorVersion, String productName, String productEdition) throws LicenseFileHasNotBeenRead, LicenseSignatureIsInvalid, InvalidLicenseFile, LicenseViolation { checkThatLicenseDOMisValid(); // Check usage checkProductNameAndEdition(productName, productEdition); checkVersion(majorVersion, minorVersion); checkConcurrentUsers(concurrentUsers); checkApplicationClass(applicationClass); checkDate(); } private void checkDate() throws LicenseViolation { NodeList vuL = licenseXML.getElementsByTagName("valid-until"); if (vuL != null && vuL.getLength() > 0) { Element e = (Element) vuL.item(0); String year = e.getAttribute("year"); String month = e.getAttribute("month"); String day = e.getAttribute("day"); Calendar cal = Calendar.getInstance(); if ((year != null && year.length() > 0 && Integer.parseInt(year) < cal .get(Calendar.YEAR)) || (month != null && month.length() > 0 && Integer .parseInt(month) < (1 + cal.get(Calendar.MONTH))) || (day != null && day.length() > 0 && Integer .parseInt(day) < cal.get(Calendar.DAY_OF_MONTH))) throw new LicenseViolation("The license is valid until " + year + "-" + month + "-" + day); } } private void checkApplicationClass(Class applicationClass) throws LicenseViolation { // check class NodeList appL = licenseXML.getElementsByTagName("application"); if (appL != null && appL.getLength() > 0) { String classPrefix = ((Element) appL.item(0)) .getAttribute("classPrefix"); if (classPrefix != null && classPrefix.length() > 0 && applicationClass.getName().startsWith(classPrefix)) throw new LicenseViolation( "License limits application class prefix to '" + classPrefix + "' but requested application class is '" + applicationClass.getName() + "'"); } } private void checkConcurrentUsers(int concurrentUsers) throws TooManyConcurrentUsers { int max = getMaxConcurrentUsers(); if (max >= 0 && concurrentUsers > max) throw new TooManyConcurrentUsers( "Currently " + concurrentUsers + " concurrent users are connected, while license sets limit to " + max); } private int getMaxConcurrentUsers() { NodeList cuL = licenseXML .getElementsByTagName("concurrent-users-per-server"); if (cuL == null && cuL.getLength() == 0) return -1; String limit = ((Element) cuL.item(0)).getAttribute("limit"); if (limit != null && limit.length() > 0 && !limit.equalsIgnoreCase("unlimited")) return Integer.parseInt(limit); return -1; } private int getMaxJVMs() { NodeList cuL = licenseXML.getElementsByTagName("concurrent-jvms"); if (cuL == null && cuL.getLength() == 0) return -1; String limit = ((Element) cuL.item(0)).getAttribute("limit"); if (limit != null && limit.length() > 0 && !limit.equalsIgnoreCase("unlimited")) return Integer.parseInt(limit); return -1; } private void checkVersion(int majorVersion, int minorVersion) throws LicenseViolation { // check version NodeList verL = licenseXML.getElementsByTagName("version"); if (verL != null && verL.getLength() > 0) { NodeList checks = verL.item(0).getChildNodes(); for (int i = 0; i < checks.getLength(); i++) { Node n = checks.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Element e = (Element) n; String tag = e.getTagName(); String eq = e.getAttribute("equals-to"); String eqol = e.getAttribute("equals-to-or-is-less-than"); String eqom = e.getAttribute("equals-to-or-is-more-than"); int value = -1; if ("major".equalsIgnoreCase(tag)) { value = majorVersion; } else if ("minor".equalsIgnoreCase(tag)) { value = minorVersion; } if (value >= 0) { if (eq != null && eq.length() > 0) if (value != Integer.parseInt(eq)) throw new LicenseViolation("Product " + tag + " version is " + value + " but license requires it to be " + eq); if (eqol != null && eqol.length() > 0) if (value <= Integer.parseInt(eqol)) throw new LicenseViolation( "Product " + tag + " version is " + value + " but license requires it to be equal or less than" + eqol); if (eqom != null && eqom.length() > 0) if (value != Integer.parseInt(eqom)) throw new LicenseViolation( "Product " + tag + " version is " + value + " but license requires it to be equal or more than" + eqom); } } } } } private String getVersionDescription() { StringBuffer v = new StringBuffer(); NodeList verL = licenseXML.getElementsByTagName("version"); if (verL != null && verL.getLength() > 0) { NodeList checks = verL.item(0).getChildNodes(); for (int i = 0; i < checks.getLength(); i++) { Node n = checks.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Element e = (Element) n; String tag = e.getTagName(); appendVersionDescription(e.getAttribute("equals-to"),v,tag,"="); appendVersionDescription(e.getAttribute("equals-to-or-is-less-than"),v,tag,"<="); appendVersionDescription(e.getAttribute("equals-to-or-is-more-than"),v,tag,">="); } } } if (v.length() == 0) return null; return v.toString(); } private void appendVersionDescription(String num, StringBuffer v, String tag, String relation) { if (num == null || num.length() == 0) return; if (v.length() == 0) v.append(" and "); v.append(tag + " version " + relation + " " + num); } private void checkProductNameAndEdition(String productName, String productEdition) throws InvalidLicenseFile, LicenseViolation { // Check product name if (productName == null || productName.length() == 0) throw new IllegalArgumentException( "productName must not be empty or null"); if (productEdition != null && productEdition.length() == 0) throw new IllegalArgumentException( "productEdition must either be null (not present) or non-empty string"); String name = getProductName(); if (!name.equals(productName)) throw new LicenseViolation("The license file is for product '" + name + "' but it was requested to be used with '" + productName + "'"); // Check product edition String edition = getProductEdition(); if (productEdition != null || edition != null) if (edition == null || !edition.equals(productEdition)) throw new LicenseViolation("Requested edition '" + productEdition + "', but license-file is for '" + edition + "'"); } private String getProductEdition() throws InvalidLicenseFile { Element prod = (Element) licenseXML.getElementsByTagName("product") .item(0); if (prod == null) throw new InvalidLicenseFile("product not found in license-file"); NodeList editionE = (NodeList) prod.getElementsByTagName("edition"); if (editionE == null || editionE.getLength() == 0) return null; return editionE.item(0).getTextContent(); } private String getProductName() throws InvalidLicenseFile { Element prod = (Element) licenseXML.getElementsByTagName("product") .item(0); if (prod == null) throw new InvalidLicenseFile("product not found in license-file"); String name = ((Element) prod.getElementsByTagName("name").item(0)) .getTextContent(); if (name == null || name.length() == 0) throw new InvalidLicenseFile( "product name not found in license-file"); return name; } private String getLicenseeName() { NodeList licenseeL = licenseXML.getElementsByTagName("licensee"); if (licenseeL == null || licenseeL.getLength() == 0) return null; NodeList nameL = ((Element) licenseeL.item(0)) .getElementsByTagName("name"); if (nameL == null || nameL.getLength() == 0) return null; String name = nameL.item(0).getTextContent(); if (name == null || name.length() == 0) return null; return name; } private String getPurpose() { NodeList purposeL = licenseXML.getElementsByTagName("purpose"); if (purposeL == null || purposeL.getLength() == 0) return null; return purposeL.item(0).getTextContent(); } private String getLicenseNumber() throws InvalidLicenseFile { Element lic = (Element) licenseXML.getElementsByTagName("license") .item(0); if (lic == null) throw new InvalidLicenseFile( "license element not found in license-file"); return lic.getAttribute("number"); } private String getNormalizedLisenceData() throws InvalidLicenseFile, LicenseFileHasNotBeenRead { // License must be read before if (licenseXML == null) throw new LicenseFileHasNotBeenRead(); // Initialize result CharArrayWriter sink = new CharArrayWriter(); // Serialize document to sink try { serialize(licenseXML, sink); } catch (IOException e) { throw new InvalidLicenseFile("Can not serialize the license file."); } return new String(sink.toCharArray()); } private static void serialize(Node node, Writer sink) throws IOException { // Do not serialize comments and processing instructions if (node.getNodeType() == Node.COMMENT_NODE || node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) return; // Do not serialize whitespace text-nodes if (node.getNodeType() == Node.TEXT_NODE) { String value = node.getNodeValue(); if (value.matches("^\\s*$")) return; } // Do not serialize signature if (node.getNodeType() == Node.ELEMENT_NODE && "signature".equals(node.getNodeName())) return; // Serialize node name sink.write(node.getNodeName().toLowerCase()); // Serialize value of the node String value = node.getNodeValue(); if (value != null) sink.write("='" + value + "'"); // Serialize attributes if it has any, in sorted order NamedNodeMap attrs = node.getAttributes(); if (attrs != null) { TreeSet names = new TreeSet(); for (int i = 0; i < attrs.getLength(); i++) names.add(attrs.item(i).getNodeName()); for (Iterator i = names.iterator(); i.hasNext();) serialize(attrs.getNamedItem((String) i.next()), sink); } // Serialize child nodes (other than attributes) Node child = node.getFirstChild(); if (child != null && node.getNodeType() != Node.ATTRIBUTE_NODE) { sink.write("{"); while (child != null) { if (child.getNodeType() != Node.ATTRIBUTE_NODE) serialize(child, sink); child = child.getNextSibling(); } sink.write("}"); } } private byte[] getSignature() throws InvalidLicenseFile { if (licenseXML == null) return null; // Get the base64 encoded signature from license-file NodeList nl = licenseXML.getElementsByTagName("signature"); if (nl == null || nl.getLength() != 1) throw new InvalidLicenseFile("Signature element not found"); Node text = nl.item(0).getFirstChild(); if (text == null || text.getNodeType() != Node.TEXT_NODE) throw new InvalidLicenseFile("Invalid signature element"); String base64 = text.getNodeValue(); return base64_decode(base64); } private boolean isSignatureValid() throws InvalidLicenseFile, LicenseFileHasNotBeenRead, LicenseSignatureIsInvalid { if (signatureIsValid) return true; try { // Get X.509 factory implementation CertificateFactory x509factory = CertificateFactory .getInstance("X.509"); // Decode statically linked X.509 certificate X509Certificate cert = (X509Certificate) x509factory .generateCertificate(new ByteArrayInputStream(certificate .getBytes())); PublicKey publicKey = cert.getPublicKey(); // Verify signature with DSA Signature dsa = Signature.getInstance("SHA1withDSA"); dsa.initVerify(publicKey); dsa.update(getNormalizedLisenceData().getBytes("UTF-8")); if (dsa.verify(getSignature())) { signatureIsValid = true; return true; } } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeyException e) { throw new RuntimeException(e); } catch (SignatureException e) { throw new LicenseSignatureIsInvalid(); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (CertificateException e) { throw new RuntimeException(e); } // Verification failed return false; } public class LicenseViolation extends Exception { public LicenseViolation(String msg) { super(msg); } } public class LicenseFileHasAlreadyBeenRead extends Exception { } public class LicenseFileHasNotBeenRead extends Exception { } public class LicenseSignatureIsInvalid extends Exception { } public class TooManyConcurrentUsers extends LicenseViolation { public TooManyConcurrentUsers(String msg) { super(msg); } } public class LicenseHasExpired extends LicenseViolation { public LicenseHasExpired(String msg) { super(msg); } } public class ApplicationClassNameDoesNotMatch extends LicenseViolation { public ApplicationClassNameDoesNotMatch(String msg) { super(msg); } } public class InvalidLicenseFile extends Exception { InvalidLicenseFile(String message) { super(message); } } public class LicenseFileCanNotBeRead extends Exception { LicenseFileCanNotBeRead(String message) { super(message); } } /* ****** BASE64 implementation created by Robert Harder ****** */ /** Specify encoding. */ private final static int Base64_ENCODE = 1; /** Specify decoding. */ private final static int Base64_DECODE = 0; /** Don't break lines when encoding (violates strict Base64 specification) */ private final static int Base64_DONT_BREAK_LINES = 8; /** Maximum line length (76) of Base64 output. */ private final static int Base64_MAX_LINE_LENGTH = 76; /** The equals sign (=) as a byte. */ private final static byte Base64_EQUALS_SIGN = (byte) '='; /** The new line character (\n) as a byte. */ private final static byte Base64_NEW_LINE = (byte) '\n'; /** Preferred encoding. */ private final static String Base64_PREFERRED_ENCODING = "UTF-8"; /** The 64 valid Base64 values. */ private final static byte[] Base64_ALPHABET; private final static byte[] Base64_NATIVE_ALPHABET = { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/' }; /** Determine which ALPHABET to use. */ static { byte[] __bytes; try { __bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" .getBytes(Base64_PREFERRED_ENCODING); } // end try catch (java.io.UnsupportedEncodingException use) { __bytes = Base64_NATIVE_ALPHABET; // Fall back to native encoding } // end catch Base64_ALPHABET = __bytes; } // end static /** * Translates a Base64 value to either its 6-bit reconstruction value or a * negative number indicating some other meaning. */ private final static byte[] Base64_DECODABET = { -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - // 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9, -9, -9, // Decimal 44 - 46 63, // Slash at decimal 47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' // through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' // through 'Z' -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' // through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' // through 'z' -9, -9, -9, -9 // Decimal 123 - 126 }; // I think I end up not using the BAD_ENCODING indicator. // private final static byte BAD_ENCODING = -9; // Indicates error in // encoding private final static byte Base64_WHITE_SPACE_ENC = -5; // Indicates white // space in encoding private final static byte Base64_EQUALS_SIGN_ENC = -1; // Indicates equals // sign in encoding /** * Encodes up to the first three bytes of array <var>threeBytes</var> and * returns a four-byte array in Base64 notation. The actual number of * significant bytes in your array is given by <var>numSigBytes</var>. The * array <var>threeBytes</var> needs only be as big as <var>numSigBytes</var>. * Code can reuse a byte array by passing a four-byte array as <var>b4</var>. * * @param b4 * A reusable byte array to reduce array instantiation * @param threeBytes * the array to convert * @param numSigBytes * the number of significant bytes in your array * @return four byte array in Base64 notation. * @since 1.5.1 */ private static byte[] base64_encode3to4(byte[] b4, byte[] threeBytes, int numSigBytes) { base64_encode3to4(threeBytes, 0, numSigBytes, b4, 0); return b4; } // end encode3to4 /** * Encodes up to three bytes of the array <var>source</var> and writes the * resulting four Base64 bytes to <var>destination</var>. The source and * destination arrays can be manipulated anywhere along their length by * specifying <var>srcOffset</var> and <var>destOffset</var>. This method * does not check to make sure your arrays are large enough to accomodate * <var>srcOffset</var> + 3 for the <var>source</var> array or * <var>destOffset</var> + 4 for the <var>destination</var> array. The * actual number of significant bytes in your array is given by * <var>numSigBytes</var>. * * @param source * the array to convert * @param srcOffset * the index where conversion begins * @param numSigBytes * the number of significant bytes in your array * @param destination * the array to hold the conversion * @param destOffset * the index where output will be put * @return the <var>destination</var> array * @since 1.3 */ private static byte[] base64_encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset) { // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index ALPHABET // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an // int. int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); switch (numSigBytes) { case 3: destination[destOffset] = Base64_ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = Base64_ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = Base64_ALPHABET[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = Base64_ALPHABET[(inBuff) & 0x3f]; return destination; case 2: destination[destOffset] = Base64_ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = Base64_ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = Base64_ALPHABET[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = Base64_EQUALS_SIGN; return destination; case 1: destination[destOffset] = Base64_ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = Base64_ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = Base64_EQUALS_SIGN; destination[destOffset + 3] = Base64_EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Decodes four bytes from array <var>source</var> and writes the resulting * bytes (up to three of them) to <var>destination</var>. The source and * destination arrays can be manipulated anywhere along their length by * specifying <var>srcOffset</var> and <var>destOffset</var>. This method * does not check to make sure your arrays are large enough to accomodate * <var>srcOffset</var> + 4 for the <var>source</var> array or * <var>destOffset</var> + 3 for the <var>destination</var> array. This * method returns the actual number of bytes that were converted from the * Base64 encoding. * * * @param source * the array to convert * @param srcOffset * the index where conversion begins * @param destination * the array to hold the conversion * @param destOffset * the index where output will be put * @return the number of decoded bytes converted * @since 1.3 */ private static int base64_decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset) { // Example: Dk== if (source[srcOffset + 2] == Base64_EQUALS_SIGN) { // Two ways to do the same thing. Don't know which way I like best. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 // ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff = ((Base64_DECODABET[source[srcOffset]] & 0xFF) << 18) | ((Base64_DECODABET[source[srcOffset + 1]] & 0xFF) << 12); destination[destOffset] = (byte) (outBuff >>> 16); return 1; } // Example: DkL= else if (source[srcOffset + 3] == Base64_EQUALS_SIGN) { // Two ways to do the same thing. Don't know which way I like best. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 // ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff = ((Base64_DECODABET[source[srcOffset]] & 0xFF) << 18) | ((Base64_DECODABET[source[srcOffset + 1]] & 0xFF) << 12) | ((Base64_DECODABET[source[srcOffset + 2]] & 0xFF) << 6); destination[destOffset] = (byte) (outBuff >>> 16); destination[destOffset + 1] = (byte) (outBuff >>> 8); return 2; } // Example: DkLE else { try { // Two ways to do the same thing. Don't know which way I like // best. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) // >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = ((Base64_DECODABET[source[srcOffset]] & 0xFF) << 18) | ((Base64_DECODABET[source[srcOffset + 1]] & 0xFF) << 12) | ((Base64_DECODABET[source[srcOffset + 2]] & 0xFF) << 6) | ((Base64_DECODABET[source[srcOffset + 3]] & 0xFF)); destination[destOffset] = (byte) (outBuff >> 16); destination[destOffset + 1] = (byte) (outBuff >> 8); destination[destOffset + 2] = (byte) (outBuff); return 3; } catch (Exception e) { System.out.println("" + source[srcOffset] + ": " + (Base64_DECODABET[source[srcOffset]])); System.out.println("" + source[srcOffset + 1] + ": " + (Base64_DECODABET[source[srcOffset + 1]])); System.out.println("" + source[srcOffset + 2] + ": " + (Base64_DECODABET[source[srcOffset + 2]])); System.out.println("" + source[srcOffset + 3] + ": " + (Base64_DECODABET[source[srcOffset + 3]])); return -1; } // e nd catch } } // end decodeToBytes /** * Very low-level access to decoding ASCII characters in the form of a byte * array. Does not support automatically gunzipping or any other "fancy" * features. * * @param source * The Base64 encoded data * @param off * The offset of where to begin decoding * @param len * The length of characters to decode * @return decoded data * @since 1.3 */ private static byte[] base64_decode(byte[] source, int off, int len) { int len34 = len * 3 / 4; byte[] outBuff = new byte[len34]; // Upper limit on size of output int outBuffPosn = 0; byte[] b4 = new byte[4]; int b4Posn = 0; int i = 0; byte sbiCrop = 0; byte sbiDecode = 0; for (i = off; i < off + len; i++) { sbiCrop = (byte) (source[i] & 0x7f); // Only the low seven bits sbiDecode = Base64_DECODABET[sbiCrop]; if (sbiDecode >= Base64_WHITE_SPACE_ENC) // White space, Equals // sign or better { if (sbiDecode >= Base64_EQUALS_SIGN_ENC) { b4[b4Posn++] = sbiCrop; if (b4Posn > 3) { outBuffPosn += base64_decode4to3(b4, 0, outBuff, outBuffPosn); b4Posn = 0; // If that was the equals sign, break out of 'for' loop if (sbiCrop == Base64_EQUALS_SIGN) break; } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better else { System.err.println("Bad Base64 input character at " + i + ": " + source[i] + "(decimal)"); return null; } // end else: } // each input character byte[] out = new byte[outBuffPosn]; System.arraycopy(outBuff, 0, out, 0, outBuffPosn); return out; } // end decode /** * Decodes data from Base64 notation, automatically detecting * gzip-compressed data and decompressing it. * * @param s * the string to decode * @return the decoded data * @since 1.4 */ private static byte[] base64_decode(String s) { byte[] bytes; try { bytes = s.getBytes(Base64_PREFERRED_ENCODING); } // end try catch (java.io.UnsupportedEncodingException uee) { bytes = s.getBytes(); } // end catch // </change> // Decode bytes = base64_decode(bytes, 0, bytes.length); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) if (bytes != null && bytes.length >= 4) { int head = ((int) bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream(bytes); gzis = new java.util.zip.GZIPInputStream(bais); while ((length = gzis.read(buffer)) >= 0) { baos.write(buffer, 0, length); } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); } // end try catch (java.io.IOException e) { // Just return originally-decoded bytes } // end catch finally { try { baos.close(); } catch (Exception e) { } try { gzis.close(); } catch (Exception e) { } try { bais.close(); } catch (Exception e) { } } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; } // end decode /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ /** * A {@link Base64_InputStream} will read data from another * <tt>java.io.InputStream</tt>, given in the constructor, and * encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ private static class Base64_InputStream extends java.io.FilterInputStream { private boolean encode; // Encoding or decoding private int position; // Current position in the buffer private byte[] buffer; // Small buffer holding converted data private int bufferLength; // Length of buffer (3 or 4) private int numSigBytes; // Number of meaningful bytes in the buffer private int lineLength; private boolean breakLines; // Break lines at less than 80 characters /** * Constructs a {@link Base64_InputStream} in DECODE mode. * * @param in * the <tt>java.io.InputStream</tt> from which to read * data. * @since 1.3 */ public Base64_InputStream(java.io.InputStream in) { this(in, Base64_DECODE); } // end constructor /** * Constructs a {@link Base64_InputStream} in either ENCODE or DECODE * mode. * <p> * Valid options: * * <pre> * ENCODE or DECODE: Encode or Decode as data is read. * DONT_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding) * &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt; * </pre> * * <p> * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code> * * * @param in * the <tt>java.io.InputStream</tt> from which to read * data. * @param options * Specified options * @see Base64#Base64_ENCODE * @see Base64#Base64_DECODE * @see Base64#Base64_DONT_BREAK_LINES * @since 2.0 */ public Base64_InputStream(java.io.InputStream in, int options) { super(in); this.breakLines = (options & Base64_DONT_BREAK_LINES) != Base64_DONT_BREAK_LINES; this.encode = (options & Base64_ENCODE) == Base64_ENCODE; this.bufferLength = encode ? 4 : 3; this.buffer = new byte[bufferLength]; this.position = -1; this.lineLength = 0; } // end constructor /** * Reads enough of the input stream to convert to/from Base64 and * returns the next byte. * * @return next byte * @since 1.3 */ public int read() throws java.io.IOException { // Do we need to get data? if (position < 0) { if (encode) { byte[] b3 = new byte[3]; int numBinaryBytes = 0; for (int i = 0; i < 3; i++) { try { int b = in.read(); // If end of stream, b is -1. if (b >= 0) { b3[i] = (byte) b; numBinaryBytes++; } // end if: not end of stream } // end try: read catch (java.io.IOException e) { // Only a problem if we got no data at all. if (i == 0) throw e; } // end catch } // end for: each needed input byte if (numBinaryBytes > 0) { base64_encode3to4(b3, 0, numBinaryBytes, buffer, 0); position = 0; numSigBytes = 4; } // end if: got data else { return -1; } // end else } // end if: encoding // Else decoding else { byte[] b4 = new byte[4]; int i = 0; for (i = 0; i < 4; i++) { // Read four "meaningful" bytes: int b = 0; do { b = in.read(); } while (b >= 0 && Base64_DECODABET[b & 0x7f] <= Base64_WHITE_SPACE_ENC); if (b < 0) break; // Reads a -1 if end of stream b4[i] = (byte) b; } // end for: each needed input byte if (i == 4) { numSigBytes = base64_decode4to3(b4, 0, buffer, 0); position = 0; } // end if: got four characters else if (i == 0) { return -1; } // end else if: also padded correctly else { // Must have broken out from above. throw new java.io.IOException( "Improperly padded Base64 input."); } // end } // end else: decode } // end else: get data // Got data? if (position >= 0) { // End of relevant data? if ( /* !encode && */position >= numSigBytes) return -1; if (encode && breakLines && lineLength >= Base64_MAX_LINE_LENGTH) { lineLength = 0; return '\n'; } // end if else { lineLength++; // This isn't important when decoding // but throwing an extra "if" seems // just as wasteful. int b = buffer[position++]; if (position >= bufferLength) position = -1; return b & 0xFF; // This is how you "cast" a byte that's // intended to be unsigned. } // end else } // end if: position >= 0 // Else error else { // When JDK1.4 is more accepted, use an assertion here. throw new java.io.IOException( "Error in Base64 code reading stream."); } // end else } // end read /** * Calls {@link #read()} repeatedly until the end of stream is reached * or <var>len</var> bytes are read. Returns number of bytes read into * array or -1 if end of stream is encountered. * * @param dest * array to hold values * @param off * offset for array * @param len * max number of bytes to read into array * @return bytes read into array or -1 if end of stream is encountered. * @since 1.3 */ public int read(byte[] dest, int off, int len) throws java.io.IOException { int i; int b; for (i = 0; i < len; i++) { b = read(); // if( b < 0 && i == 0 ) // return -1; if (b >= 0) dest[off + i] = (byte) b; else if (i == 0) return -1; else break; // Out of 'for' loop } // end for: each byte read return i; } // end read } // end inner class InputStream /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ /** * A {@link Base64_OutputStream} will write data to another * <tt>java.io.OutputStream</tt>, given in the constructor, and * encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ private static class Base64_OutputStream extends java.io.FilterOutputStream { private boolean encode; private int position; private byte[] buffer; private int bufferLength; private int lineLength; private boolean breakLines; private byte[] b4; // Scratch used in a few places private boolean suspendEncoding; /** * Constructs a {@link Base64_OutputStream} in ENCODE mode. * * @param out * the <tt>java.io.OutputStream</tt> to which data will be * written. * @since 1.3 */ public Base64_OutputStream(java.io.OutputStream out) { this(out, Base64_ENCODE); } // end constructor /** * Constructs a {@link Base64_OutputStream} in either ENCODE or DECODE * mode. * <p> * Valid options: * * <pre> * ENCODE or DECODE: Encode or Decode as data is read. * DONT_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding) * &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt; * </pre> * * <p> * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code> * * @param out * the <tt>java.io.OutputStream</tt> to which data will be * written. * @param options * Specified options. * @see Base64#Base64_ENCODE * @see Base64#Base64_DECODE * @see Base64#Base64_DONT_BREAK_LINES * @since 1.3 */ public Base64_OutputStream(java.io.OutputStream out, int options) { super(out); this.breakLines = (options & Base64_DONT_BREAK_LINES) != Base64_DONT_BREAK_LINES; this.encode = (options & Base64_ENCODE) == Base64_ENCODE; this.bufferLength = encode ? 3 : 4; this.buffer = new byte[bufferLength]; this.position = 0; this.lineLength = 0; this.suspendEncoding = false; this.b4 = new byte[4]; } // end constructor /** * Writes the byte to the output stream after converting to/from Base64 * notation. When encoding, bytes are buffered three at a time before * the output stream actually gets a write() call. When decoding, bytes * are buffered four at a time. * * @param theByte * the byte to write * @since 1.3 */ public void write(int theByte) throws java.io.IOException { // Encoding suspended? if (suspendEncoding) { super.out.write(theByte); return; } // end if: supsended // Encode? if (encode) { buffer[position++] = (byte) theByte; if (position >= bufferLength) // Enough to encode. { out.write(base64_encode3to4(b4, buffer, bufferLength)); lineLength += 4; if (breakLines && lineLength >= Base64_MAX_LINE_LENGTH) { out.write(Base64_NEW_LINE); lineLength = 0; } // end if: end of line position = 0; } // end if: enough to output } // end if: encoding // Else, Decoding else { // Meaningful Base64 character? if (Base64_DECODABET[theByte & 0x7f] > Base64_WHITE_SPACE_ENC) { buffer[position++] = (byte) theByte; if (position >= bufferLength) // Enough to output. { int len = base64_decode4to3(buffer, 0, b4, 0); out.write(b4, 0, len); // out.write( Base64.decode4to3( buffer ) ); position = 0; } // end if: enough to output } // end if: meaningful base64 character else if (Base64_DECODABET[theByte & 0x7f] != Base64_WHITE_SPACE_ENC) { throw new java.io.IOException( "Invalid character in Base64 data."); } // end else: not white space either } // end else: decoding } // end write /** * Calls {@link #write(int)} repeatedly until <var>len</var> bytes are * written. * * @param theBytes * array from which to read bytes * @param off * offset for array * @param len * max number of bytes to read into array * @since 1.3 */ public void write(byte[] theBytes, int off, int len) throws java.io.IOException { // Encoding suspended? if (suspendEncoding) { super.out.write(theBytes, off, len); return; } // end if: supsended for (int i = 0; i < len; i++) { write(theBytes[off + i]); } // end for: each byte written } // end write /** * Method added by PHIL. [Thanks, PHIL. -Rob] This pads the buffer * without closing the stream. */ public void flushBase64() throws java.io.IOException { if (position > 0) { if (encode) { out.write(base64_encode3to4(b4, buffer, position)); position = 0; } // end if: encoding else { throw new java.io.IOException( "Base64 input not properly padded."); } // end else: decoding } // end if: buffer partially full } // end flush /** * Flushes and closes (I think, in the superclass) the stream. * * @since 1.3 */ public void close() throws java.io.IOException { // 1. Ensure that pending characters are written flushBase64(); // 2. Actually close the stream // Base class both flushes and closes. super.close(); buffer = null; out = null; } // end close /** * Suspends encoding of the stream. May be helpful if you need to embed * a piece of base640-encoded data in a stream. * * @since 1.5.1 */ public void suspendEncoding() throws java.io.IOException { flushBase64(); this.suspendEncoding = true; } // end suspendEncoding /** * Resumes encoding of the stream. May be helpful if you need to embed a * piece of base640-encoded data in a stream. * * @since 1.5.1 */ public void resumeEncoding() { this.suspendEncoding = false; } // end resumeEncoding } // end inner class OutputStream }
src/com/itmill/toolkit/service/License.java
/* ************************************************************************* IT Mill Toolkit Development of Browser User Intarfaces Made Easy Copyright (C) 2000-2006 IT Mill Ltd ************************************************************************* This product is distributed under commercial license that can be found from the product package on license/license.txt. Use of this product might require purchasing a commercial license from IT Mill Ltd. For guidelines on usage, see license/licensing-guidelines.html ************************************************************************* For more information, contact: IT Mill Ltd phone: +358 2 4802 7180 Ruukinkatu 2-4 fax: +358 2 4802 7181 20540, Turku email: [email protected] Finland company www: www.itmill.com Primary source for information and releases: www.itmill.com ********************************************************************** */ package com.itmill.toolkit.service; import java.io.ByteArrayInputStream; import java.io.CharArrayWriter; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Calendar; import java.util.Iterator; import java.util.TooManyListenersException; import java.util.TreeSet; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class License { /** IT Mill License Manager certificate */ private static String certificate = "-----BEGIN CERTIFICATE-----\n" + "MIIDJjCCAuQCBEVqxNwwCwYHKoZIzjgEAwUAMHkxCzAJBgNVBAYTAkZJMRAwDgYDVQQIEwdVbmtu\n" + "b3duMQ4wDAYDVQQHEwVUdXJrdTEUMBIGA1UEChMLSVQgTWlsbCBMdGQxEDAOBgNVBAsTB1Vua25v\n" + "d24xIDAeBgNVBAMTF0lUIE1pbGwgTGljZW5zZSBNYW5hZ2VyMB4XDTA2MTEyNzEwNTgzNloXDTQ3\n" + "MTIyMjEwNTgzNloweTELMAkGA1UEBhMCRkkxEDAOBgNVBAgTB1Vua25vd24xDjAMBgNVBAcTBVR1\n" + "cmt1MRQwEgYDVQQKEwtJVCBNaWxsIEx0ZDEQMA4GA1UECxMHVW5rbm93bjEgMB4GA1UEAxMXSVQg\n" + "TWlsbCBMaWNlbnNlIE1hbmFnZXIwggG3MIIBLAYHKoZIzjgEATCCAR8CgYEA/X9TgR11EilS30qc\n" + "Luzk5/YRt1I870QAwx4/gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZUKWk\n" + "n5/oBHsQIsJPu6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOuK2HXKu/yIgMZndFI\n" + "AccCFQCXYFCPFSMLzLKSuYKi64QL8Fgc9QKBgQD34aCF1ps93su8q1w2uFe5eZSvu/o66oL5V0wL\n" + "PQeCZ1FZV4661FlP5nEHEIGAtEkWcSPoTCgWE7fPCTKMyKbhPBZ6i1R8jSjgo64eK7OmdZFuo38L\n" + "+iE1YvH7YnoBJDvMpPG+qFGQiaiD3+Fa5Z8GkotmXoB7VSVkAUw7/s9JKgOBhAACgYB2wjpuZXqK\n" + "Ldgw1uZRlNCON7vo4m420CSna0mhETqzW9UMFHmZfn9edD0B1dDh6NwmRIDjljf8+ODuhwZKkzl8\n" + "DHUq3HPnipEsr0C3g1Dz7ZbjcvUhzsPDElpKBZhHRaoqfAfWiNxeVF2Kh2IlIMwuJ2xZeSaUH7Pj\n" + "LwAkKye6dzALBgcqhkjOOAQDBQADLwAwLAIUDgvWt7ItRyZfpWNEeJ0P9yaxOwoCFC21LRtwLi1t\n" + "c+yomHtX+mpxF7VO\n" + "-----END CERTIFICATE-----\n"; /** License XML Document */ private Document licenseXML = null; /** The signature has already been checked and is valid */ private boolean signatureIsValid = false; /** * Read the license-file from input stream. * * License file can only ne read once, after it has been read it stays. * * @param is * Input stream where the license file is read from. * @throws SAXException * Error parsing the license file * @throws IOException * Error reading the license file * @throws LicenseFileHasAlreadyBeenRead * License file has already been read. */ public void readLicenseFile(InputStream is) throws SAXException, IOException, LicenseFileHasAlreadyBeenRead { // Once the license has been read, it stays if (hasBeenRead()) throw new LicenseFileHasAlreadyBeenRead(); // Parse XML DocumentBuilder db; try { db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); licenseXML = db.parse(is); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } } /** * Is the license file already been read. * * @return true if the license-file has already been read. */ public boolean hasBeenRead() { return licenseXML != null; } /** Should the license description be printed on (first) application init. */ public boolean shouldLimitsBePrintedOnInit() throws LicenseFileHasNotBeenRead, LicenseSignatureIsInvalid, InvalidLicenseFile { checkThatLicenseDOMisValid(); NodeList lL = licenseXML.getElementsByTagName("limits"); if (lL == null || lL.getLength() > 0) throw new InvalidLicenseFile("limits not found from license-file"); Element e = (Element) lL.item(0); String print = e.getAttribute("print-limits-on-init"); return "true".equalsIgnoreCase(print); } public String getDescription() throws LicenseFileHasNotBeenRead, InvalidLicenseFile, LicenseSignatureIsInvalid { checkThatLicenseDOMisValid(); StringBuffer d = new StringBuffer(); d.append("------------------ License Info -----------------------\n"); d.append("License number: " + getLicenseNumber() + "\n"); d.append("Product: " + getProductName()); if (getProductEdition() != null) d.append(" Edition: " + getProductEdition()); d.append("\n"); // Print version info String versionDescription = getVersionDescription(); if (versionDescription != null) d.append("Version: " + versionDescription + "\n"); if (getLicenseeName() != null) d.append("Licensed to: " + getLicenseeName() + "\n"); if (getPurpose() != null) d.append("Use is limited to: " + getPurpose() + "\n"); if (getMaxConcurrentUsers() >= 0) d.append("Maximum number of concurrent (active) users allowed: " + getMaxConcurrentUsers() + "\n"); if (getMaxJVMs() >= 0) d.append("Maximum number of JVM:s this license" + " can be used concurrently: " + getMaxJVMs() + "\n"); // Print valid-until date NodeList vuL = licenseXML.getElementsByTagName("valid-until"); if (vuL != null && vuL.getLength() > 0) { Element e = (Element) vuL.item(0); String year = e.getAttribute("year"); String month = e.getAttribute("month"); String day = e.getAttribute("day"); d.append("License is valid until: " + year + "-" + month + "-" + day + "\n"); } // Print application info NodeList aL = licenseXML.getElementsByTagName("application"); if (aL != null && aL.getLength() > 0) { Element e = (Element) aL.item(0); String app = e.getAttribute("name"); String purpose = e.getAttribute("purpose"); String prefix = e.getAttribute("classPrefix"); if (app != null && app.length() > 0) d.append("For use with this application only: " + app + "\n"); if (app != null && app.length() > 0) d.append("Application usage purpose is limited to: " + purpose + "\n"); if (app != null && app.length() > 0) d.append("Application class name must match prefix: " + prefix + "\n"); } d.append("--------------------------------------------------------\n"); return d.toString(); } private void checkThatLicenseDOMisValid() throws LicenseFileHasNotBeenRead, InvalidLicenseFile, LicenseSignatureIsInvalid { // Check that the license file has already been read if (!hasBeenRead()) throw new LicenseFileHasNotBeenRead(); // Check validity of the signature if (!isSignatureValid()) throw new LicenseSignatureIsInvalid(); } /** * Check if the license valid for given usage? * * Checks that the license is valid for specified usage. Throws an exception * if there is something wrong with the license or use. * * @param applicationClass * Class of the application this license is used for * @param concurrentUsers * Number if users concurrently using this application * @param majorVersion * Major version number (for example 4 if version is 4.1.7) * @param minorVersion * Minor version number (for example 1 if version is 4.1.7) * @param productName * The name of the product * @param productEdition * The name of the product edition * @throws LicenseFileHasNotBeenRead * if the license file has not been read * @throws LicenseSignatureIsInvalid * if the license file has been changed or signature is * otherwise invalid * @throws InvalidLicenseFile * License if the license file is not of correct XML format * @throws LicenseViolation * */ public void check(Class applicationClass, int concurrentUsers, int majorVersion, int minorVersion, String productName, String productEdition) throws LicenseFileHasNotBeenRead, LicenseSignatureIsInvalid, InvalidLicenseFile, LicenseViolation { checkThatLicenseDOMisValid(); // Check usage checkProductNameAndEdition(productName, productEdition); checkVersion(majorVersion, minorVersion); checkConcurrentUsers(concurrentUsers); checkApplicationClass(applicationClass); checkDate(); } private void checkDate() throws LicenseViolation { NodeList vuL = licenseXML.getElementsByTagName("valid-until"); if (vuL != null && vuL.getLength() > 0) { Element e = (Element) vuL.item(0); String year = e.getAttribute("year"); String month = e.getAttribute("month"); String day = e.getAttribute("day"); Calendar cal = Calendar.getInstance(); if ((year != null && year.length() > 0 && Integer.parseInt(year) < cal .get(Calendar.YEAR)) || (month != null && month.length() > 0 && Integer .parseInt(month) < (1 + cal.get(Calendar.MONTH))) || (day != null && day.length() > 0 && Integer .parseInt(day) < cal.get(Calendar.DAY_OF_MONTH))) throw new LicenseViolation("The license is valid until " + year + "-" + month + "-" + day); } } private void checkApplicationClass(Class applicationClass) throws LicenseViolation { // check class NodeList appL = licenseXML.getElementsByTagName("application"); if (appL != null && appL.getLength() > 0) { String classPrefix = ((Element) appL.item(0)) .getAttribute("classPrefix"); if (classPrefix != null && classPrefix.length() > 0 && applicationClass.getName().startsWith(classPrefix)) throw new LicenseViolation( "License limits application class prefix to '" + classPrefix + "' but requested application class is '" + applicationClass.getName() + "'"); } } private void checkConcurrentUsers(int concurrentUsers) throws TooManyConcurrentUsers { int max = getMaxConcurrentUsers(); if (max >= 0 && concurrentUsers > max) throw new TooManyConcurrentUsers( "Currently " + concurrentUsers + " concurrent users are connected, while license sets limit to " + max); } private int getMaxConcurrentUsers() { NodeList cuL = licenseXML .getElementsByTagName("concurrent-users-per-server"); if (cuL == null && cuL.getLength() == 0) return -1; String limit = ((Element) cuL.item(0)).getAttribute("limit"); if (limit != null && limit.length() > 0 && !limit.equalsIgnoreCase("unlimited")) return Integer.parseInt(limit); return -1; } private int getMaxJVMs() { NodeList cuL = licenseXML.getElementsByTagName("concurrent-jvms"); if (cuL == null && cuL.getLength() == 0) return -1; String limit = ((Element) cuL.item(0)).getAttribute("limit"); if (limit != null && limit.length() > 0 && !limit.equalsIgnoreCase("unlimited")) return Integer.parseInt(limit); return -1; } private void checkVersion(int majorVersion, int minorVersion) throws LicenseViolation { // check version NodeList verL = licenseXML.getElementsByTagName("version"); if (verL != null && verL.getLength() > 0) { NodeList checks = verL.item(0).getChildNodes(); for (int i = 0; i < checks.getLength(); i++) { Node n = checks.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Element e = (Element) n; String tag = e.getTagName(); String eq = e.getAttribute("equals-to"); String eqol = e.getAttribute("equals-to-or-is-less-than"); String eqom = e.getAttribute("equals-to-or-is-more-than"); int value = -1; if ("major".equalsIgnoreCase(tag)) { value = majorVersion; } else if ("minor".equalsIgnoreCase(tag)) { value = minorVersion; } if (value >= 0) { if (eq != null && eq.length() > 0) if (value != Integer.parseInt(eq)) throw new LicenseViolation("Product " + tag + " version is " + value + " but license requires it to be " + eq); if (eqol != null && eqol.length() > 0) if (value <= Integer.parseInt(eqol)) throw new LicenseViolation( "Product " + tag + " version is " + value + " but license requires it to be equal or less than" + eqol); if (eqom != null && eqom.length() > 0) if (value != Integer.parseInt(eqom)) throw new LicenseViolation( "Product " + tag + " version is " + value + " but license requires it to be equal or more than" + eqom); } } } } } private String getVersionDescription() { StringBuffer v = new StringBuffer(); NodeList verL = licenseXML.getElementsByTagName("version"); if (verL != null && verL.getLength() > 0) { NodeList checks = verL.item(0).getChildNodes(); for (int i = 0; i < checks.getLength(); i++) { Node n = checks.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Element e = (Element) n; String tag = e.getTagName(); appendVersionDescription(e.getAttribute("equals-to"),v,tag,"="); appendVersionDescription(e.getAttribute("equals-to-or-is-less-than"),v,tag,"<="); appendVersionDescription(e.getAttribute("equals-to-or-is-more-than"),v,tag,">="); } } } if (v.length() == 0) return null; return v.toString(); } private void appendVersionDescription(String num, StringBuffer v, String tag, String relation) { if (num == null || num.length() == 0) return; if (v.length() == 0) v.append(" and "); v.append(tag + " version " + relation + " " + num); } private void checkProductNameAndEdition(String productName, String productEdition) throws InvalidLicenseFile, LicenseViolation { // Check product name if (productName == null || productName.length() == 0) throw new IllegalArgumentException( "productName must not be empty or null"); if (productEdition != null && productEdition.length() == 0) throw new IllegalArgumentException( "productEdition must either be null (not present) or non-empty string"); String name = getProductName(); if (!name.equals(productName)) throw new LicenseViolation("The license file is for product '" + name + "' but it was requested to be used with '" + productName + "'"); // Check product edition String edition = getProductEdition(); if (productEdition != null || edition != null) if (edition == null || !edition.equals(productEdition)) throw new LicenseViolation("Requested edition '" + productEdition + "', but license-file is for '" + edition + "'"); } private String getProductEdition() throws InvalidLicenseFile { Element prod = (Element) licenseXML.getElementsByTagName("product") .item(0); if (prod == null) throw new InvalidLicenseFile("product not found in license-file"); NodeList editionE = (NodeList) prod.getElementsByTagName("edition"); if (editionE == null || editionE.getLength() == 0) return null; return editionE.item(0).getTextContent(); } private String getProductName() throws InvalidLicenseFile { Element prod = (Element) licenseXML.getElementsByTagName("product") .item(0); if (prod == null) throw new InvalidLicenseFile("product not found in license-file"); String name = ((Element) prod.getElementsByTagName("name").item(0)) .getTextContent(); if (name == null || name.length() == 0) throw new InvalidLicenseFile( "product name not found in license-file"); return name; } private String getLicenseeName() { NodeList licenseeL = licenseXML.getElementsByTagName("licensee"); if (licenseeL == null || licenseeL.getLength() == 0) return null; NodeList nameL = ((Element) licenseeL.item(0)) .getElementsByTagName("name"); if (nameL == null || nameL.getLength() == 0) return null; String name = nameL.item(0).getTextContent(); if (name == null || name.length() == 0) return null; return name; } private String getPurpose() { NodeList purposeL = licenseXML.getElementsByTagName("purpose"); if (purposeL == null || purposeL.getLength() == 0) return null; return purposeL.item(0).getTextContent(); } private String getLicenseNumber() throws InvalidLicenseFile { Element lic = (Element) licenseXML.getElementsByTagName("license") .item(0); if (lic == null) throw new InvalidLicenseFile( "license element not found in license-file"); return lic.getAttribute("number"); } private String getNormalizedLisenceData() throws InvalidLicenseFile, LicenseFileHasNotBeenRead { // License must be read before if (licenseXML == null) throw new LicenseFileHasNotBeenRead(); // Initialize result CharArrayWriter sink = new CharArrayWriter(); // Serialize document to sink try { serialize(licenseXML, sink); } catch (IOException e) { throw new InvalidLicenseFile("Can not serialize the license file."); } return new String(sink.toCharArray()); } private static void serialize(Node node, Writer sink) throws IOException { // Do not serialize comments and processing instructions if (node.getNodeType() == Node.COMMENT_NODE || node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) return; // Do not serialize whitespace text-nodes if (node.getNodeType() == Node.TEXT_NODE) { String value = node.getNodeValue(); if (value.matches("^\\s*$")) return; } // Do not serialize signature if (node.getNodeType() == Node.ELEMENT_NODE && "signature".equals(node.getNodeName())) return; // Serialize node name sink.write(node.getNodeName().toLowerCase()); // Serialize value of the node String value = node.getNodeValue(); if (value != null) sink.write("='" + value + "'"); // Serialize attributes if it has any, in sorted order NamedNodeMap attrs = node.getAttributes(); if (attrs != null) { TreeSet names = new TreeSet(); for (int i = 0; i < attrs.getLength(); i++) names.add(attrs.item(i).getNodeName()); for (Iterator i = names.iterator(); i.hasNext();) serialize(attrs.getNamedItem((String) i.next()), sink); } // Serialize child nodes (other than attributes) Node child = node.getFirstChild(); if (child != null && node.getNodeType() != Node.ATTRIBUTE_NODE) { sink.write("{"); while (child != null) { if (child.getNodeType() != Node.ATTRIBUTE_NODE) serialize(child, sink); child = child.getNextSibling(); } sink.write("}"); } } private byte[] getSignature() throws InvalidLicenseFile { if (licenseXML == null) return null; // Get the base64 encoded signature from license-file NodeList nl = licenseXML.getElementsByTagName("signature"); if (nl == null || nl.getLength() != 1) throw new InvalidLicenseFile("Signature element not found"); Node text = nl.item(0).getFirstChild(); if (text == null || text.getNodeType() != Node.TEXT_NODE) throw new InvalidLicenseFile("Invalid signature element"); String base64 = text.getNodeValue(); return base64_decode(base64); } private boolean isSignatureValid() throws InvalidLicenseFile, LicenseFileHasNotBeenRead, LicenseSignatureIsInvalid { if (signatureIsValid) return true; try { // Get X.509 factory implementation CertificateFactory x509factory = CertificateFactory .getInstance("X.509"); // Decode statically linked X.509 certificate X509Certificate cert = (X509Certificate) x509factory .generateCertificate(new ByteArrayInputStream(certificate .getBytes())); PublicKey publicKey = cert.getPublicKey(); // Verify signature with DSA Signature dsa = Signature.getInstance("SHA1withDSA"); dsa.initVerify(publicKey); dsa.update(getNormalizedLisenceData().getBytes("UTF-8")); if (dsa.verify(getSignature())) { signatureIsValid = true; return true; } } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeyException e) { throw new RuntimeException(e); } catch (SignatureException e) { throw new LicenseSignatureIsInvalid(); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (CertificateException e) { throw new RuntimeException(e); } // Verification failed return false; } public class LicenseViolation extends Exception { public LicenseViolation(String msg) { super(msg); } } public class LicenseFileHasAlreadyBeenRead extends Exception { } public class LicenseFileHasNotBeenRead extends Exception { } public class LicenseSignatureIsInvalid extends Exception { } public class TooManyConcurrentUsers extends LicenseViolation { public TooManyConcurrentUsers(String msg) { super(msg); } } public class LicenseHasExpired extends LicenseViolation { public LicenseHasExpired(String msg) { super(msg); } } public class ApplicationClassNameDoesNotMatch extends LicenseViolation { public ApplicationClassNameDoesNotMatch(String msg) { super(msg); } } public class InvalidLicenseFile extends Exception { InvalidLicenseFile(String message) { super(message); } } public class LicenseFileCanNotBeRead extends Exception { LicenseFileCanNotBeRead(String message) { super(message); } } /* ****** BASE64 implementation created by Robert Harder ****** */ /** Specify encoding. */ private final static int Base64_ENCODE = 1; /** Specify decoding. */ private final static int Base64_DECODE = 0; /** Don't break lines when encoding (violates strict Base64 specification) */ private final static int Base64_DONT_BREAK_LINES = 8; /** Maximum line length (76) of Base64 output. */ private final static int Base64_MAX_LINE_LENGTH = 76; /** The equals sign (=) as a byte. */ private final static byte Base64_EQUALS_SIGN = (byte) '='; /** The new line character (\n) as a byte. */ private final static byte Base64_NEW_LINE = (byte) '\n'; /** Preferred encoding. */ private final static String Base64_PREFERRED_ENCODING = "UTF-8"; /** The 64 valid Base64 values. */ private final static byte[] Base64_ALPHABET; private final static byte[] Base64_NATIVE_ALPHABET = { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/' }; /** Determine which ALPHABET to use. */ static { byte[] __bytes; try { __bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" .getBytes(Base64_PREFERRED_ENCODING); } // end try catch (java.io.UnsupportedEncodingException use) { __bytes = Base64_NATIVE_ALPHABET; // Fall back to native encoding } // end catch Base64_ALPHABET = __bytes; } // end static /** * Translates a Base64 value to either its 6-bit reconstruction value or a * negative number indicating some other meaning. */ private final static byte[] Base64_DECODABET = { -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - // 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9, -9, -9, // Decimal 44 - 46 63, // Slash at decimal 47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' // through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' // through 'Z' -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' // through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' // through 'z' -9, -9, -9, -9 // Decimal 123 - 126 }; // I think I end up not using the BAD_ENCODING indicator. // private final static byte BAD_ENCODING = -9; // Indicates error in // encoding private final static byte Base64_WHITE_SPACE_ENC = -5; // Indicates white // space in encoding private final static byte Base64_EQUALS_SIGN_ENC = -1; // Indicates equals // sign in encoding /** * Encodes up to the first three bytes of array <var>threeBytes</var> and * returns a four-byte array in Base64 notation. The actual number of * significant bytes in your array is given by <var>numSigBytes</var>. The * array <var>threeBytes</var> needs only be as big as <var>numSigBytes</var>. * Code can reuse a byte array by passing a four-byte array as <var>b4</var>. * * @param b4 * A reusable byte array to reduce array instantiation * @param threeBytes * the array to convert * @param numSigBytes * the number of significant bytes in your array * @return four byte array in Base64 notation. * @since 1.5.1 */ private static byte[] base64_encode3to4(byte[] b4, byte[] threeBytes, int numSigBytes) { base64_encode3to4(threeBytes, 0, numSigBytes, b4, 0); return b4; } // end encode3to4 /** * Encodes up to three bytes of the array <var>source</var> and writes the * resulting four Base64 bytes to <var>destination</var>. The source and * destination arrays can be manipulated anywhere along their length by * specifying <var>srcOffset</var> and <var>destOffset</var>. This method * does not check to make sure your arrays are large enough to accomodate * <var>srcOffset</var> + 3 for the <var>source</var> array or * <var>destOffset</var> + 4 for the <var>destination</var> array. The * actual number of significant bytes in your array is given by * <var>numSigBytes</var>. * * @param source * the array to convert * @param srcOffset * the index where conversion begins * @param numSigBytes * the number of significant bytes in your array * @param destination * the array to hold the conversion * @param destOffset * the index where output will be put * @return the <var>destination</var> array * @since 1.3 */ private static byte[] base64_encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset) { // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index ALPHABET // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an // int. int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); switch (numSigBytes) { case 3: destination[destOffset] = Base64_ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = Base64_ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = Base64_ALPHABET[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = Base64_ALPHABET[(inBuff) & 0x3f]; return destination; case 2: destination[destOffset] = Base64_ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = Base64_ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = Base64_ALPHABET[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = Base64_EQUALS_SIGN; return destination; case 1: destination[destOffset] = Base64_ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = Base64_ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = Base64_EQUALS_SIGN; destination[destOffset + 3] = Base64_EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Decodes four bytes from array <var>source</var> and writes the resulting * bytes (up to three of them) to <var>destination</var>. The source and * destination arrays can be manipulated anywhere along their length by * specifying <var>srcOffset</var> and <var>destOffset</var>. This method * does not check to make sure your arrays are large enough to accomodate * <var>srcOffset</var> + 4 for the <var>source</var> array or * <var>destOffset</var> + 3 for the <var>destination</var> array. This * method returns the actual number of bytes that were converted from the * Base64 encoding. * * * @param source * the array to convert * @param srcOffset * the index where conversion begins * @param destination * the array to hold the conversion * @param destOffset * the index where output will be put * @return the number of decoded bytes converted * @since 1.3 */ private static int base64_decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset) { // Example: Dk== if (source[srcOffset + 2] == Base64_EQUALS_SIGN) { // Two ways to do the same thing. Don't know which way I like best. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 // ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff = ((Base64_DECODABET[source[srcOffset]] & 0xFF) << 18) | ((Base64_DECODABET[source[srcOffset + 1]] & 0xFF) << 12); destination[destOffset] = (byte) (outBuff >>> 16); return 1; } // Example: DkL= else if (source[srcOffset + 3] == Base64_EQUALS_SIGN) { // Two ways to do the same thing. Don't know which way I like best. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 // ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff = ((Base64_DECODABET[source[srcOffset]] & 0xFF) << 18) | ((Base64_DECODABET[source[srcOffset + 1]] & 0xFF) << 12) | ((Base64_DECODABET[source[srcOffset + 2]] & 0xFF) << 6); destination[destOffset] = (byte) (outBuff >>> 16); destination[destOffset + 1] = (byte) (outBuff >>> 8); return 2; } // Example: DkLE else { try { // Two ways to do the same thing. Don't know which way I like // best. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) // >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = ((Base64_DECODABET[source[srcOffset]] & 0xFF) << 18) | ((Base64_DECODABET[source[srcOffset + 1]] & 0xFF) << 12) | ((Base64_DECODABET[source[srcOffset + 2]] & 0xFF) << 6) | ((Base64_DECODABET[source[srcOffset + 3]] & 0xFF)); destination[destOffset] = (byte) (outBuff >> 16); destination[destOffset + 1] = (byte) (outBuff >> 8); destination[destOffset + 2] = (byte) (outBuff); return 3; } catch (Exception e) { System.out.println("" + source[srcOffset] + ": " + (Base64_DECODABET[source[srcOffset]])); System.out.println("" + source[srcOffset + 1] + ": " + (Base64_DECODABET[source[srcOffset + 1]])); System.out.println("" + source[srcOffset + 2] + ": " + (Base64_DECODABET[source[srcOffset + 2]])); System.out.println("" + source[srcOffset + 3] + ": " + (Base64_DECODABET[source[srcOffset + 3]])); return -1; } // e nd catch } } // end decodeToBytes /** * Very low-level access to decoding ASCII characters in the form of a byte * array. Does not support automatically gunzipping or any other "fancy" * features. * * @param source * The Base64 encoded data * @param off * The offset of where to begin decoding * @param len * The length of characters to decode * @return decoded data * @since 1.3 */ private static byte[] base64_decode(byte[] source, int off, int len) { int len34 = len * 3 / 4; byte[] outBuff = new byte[len34]; // Upper limit on size of output int outBuffPosn = 0; byte[] b4 = new byte[4]; int b4Posn = 0; int i = 0; byte sbiCrop = 0; byte sbiDecode = 0; for (i = off; i < off + len; i++) { sbiCrop = (byte) (source[i] & 0x7f); // Only the low seven bits sbiDecode = Base64_DECODABET[sbiCrop]; if (sbiDecode >= Base64_WHITE_SPACE_ENC) // White space, Equals // sign or better { if (sbiDecode >= Base64_EQUALS_SIGN_ENC) { b4[b4Posn++] = sbiCrop; if (b4Posn > 3) { outBuffPosn += base64_decode4to3(b4, 0, outBuff, outBuffPosn); b4Posn = 0; // If that was the equals sign, break out of 'for' loop if (sbiCrop == Base64_EQUALS_SIGN) break; } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better else { System.err.println("Bad Base64 input character at " + i + ": " + source[i] + "(decimal)"); return null; } // end else: } // each input character byte[] out = new byte[outBuffPosn]; System.arraycopy(outBuff, 0, out, 0, outBuffPosn); return out; } // end decode /** * Decodes data from Base64 notation, automatically detecting * gzip-compressed data and decompressing it. * * @param s * the string to decode * @return the decoded data * @since 1.4 */ private static byte[] base64_decode(String s) { byte[] bytes; try { bytes = s.getBytes(Base64_PREFERRED_ENCODING); } // end try catch (java.io.UnsupportedEncodingException uee) { bytes = s.getBytes(); } // end catch // </change> // Decode bytes = base64_decode(bytes, 0, bytes.length); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) if (bytes != null && bytes.length >= 4) { int head = ((int) bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream(bytes); gzis = new java.util.zip.GZIPInputStream(bais); while ((length = gzis.read(buffer)) >= 0) { baos.write(buffer, 0, length); } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); } // end try catch (java.io.IOException e) { // Just return originally-decoded bytes } // end catch finally { try { baos.close(); } catch (Exception e) { } try { gzis.close(); } catch (Exception e) { } try { bais.close(); } catch (Exception e) { } } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; } // end decode /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ /** * A {@link Base64_InputStream} will read data from another * <tt>java.io.InputStream</tt>, given in the constructor, and * encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ private static class Base64_InputStream extends java.io.FilterInputStream { private boolean encode; // Encoding or decoding private int position; // Current position in the buffer private byte[] buffer; // Small buffer holding converted data private int bufferLength; // Length of buffer (3 or 4) private int numSigBytes; // Number of meaningful bytes in the buffer private int lineLength; private boolean breakLines; // Break lines at less than 80 characters /** * Constructs a {@link Base64_InputStream} in DECODE mode. * * @param in * the <tt>java.io.InputStream</tt> from which to read * data. * @since 1.3 */ public Base64_InputStream(java.io.InputStream in) { this(in, Base64_DECODE); } // end constructor /** * Constructs a {@link Base64_InputStream} in either ENCODE or DECODE * mode. * <p> * Valid options: * * <pre> * ENCODE or DECODE: Encode or Decode as data is read. * DONT_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding) * &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt; * </pre> * * <p> * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code> * * * @param in * the <tt>java.io.InputStream</tt> from which to read * data. * @param options * Specified options * @see Base64#Base64_ENCODE * @see Base64#Base64_DECODE * @see Base64#Base64_DONT_BREAK_LINES * @since 2.0 */ public Base64_InputStream(java.io.InputStream in, int options) { super(in); this.breakLines = (options & Base64_DONT_BREAK_LINES) != Base64_DONT_BREAK_LINES; this.encode = (options & Base64_ENCODE) == Base64_ENCODE; this.bufferLength = encode ? 4 : 3; this.buffer = new byte[bufferLength]; this.position = -1; this.lineLength = 0; } // end constructor /** * Reads enough of the input stream to convert to/from Base64 and * returns the next byte. * * @return next byte * @since 1.3 */ public int read() throws java.io.IOException { // Do we need to get data? if (position < 0) { if (encode) { byte[] b3 = new byte[3]; int numBinaryBytes = 0; for (int i = 0; i < 3; i++) { try { int b = in.read(); // If end of stream, b is -1. if (b >= 0) { b3[i] = (byte) b; numBinaryBytes++; } // end if: not end of stream } // end try: read catch (java.io.IOException e) { // Only a problem if we got no data at all. if (i == 0) throw e; } // end catch } // end for: each needed input byte if (numBinaryBytes > 0) { base64_encode3to4(b3, 0, numBinaryBytes, buffer, 0); position = 0; numSigBytes = 4; } // end if: got data else { return -1; } // end else } // end if: encoding // Else decoding else { byte[] b4 = new byte[4]; int i = 0; for (i = 0; i < 4; i++) { // Read four "meaningful" bytes: int b = 0; do { b = in.read(); } while (b >= 0 && Base64_DECODABET[b & 0x7f] <= Base64_WHITE_SPACE_ENC); if (b < 0) break; // Reads a -1 if end of stream b4[i] = (byte) b; } // end for: each needed input byte if (i == 4) { numSigBytes = base64_decode4to3(b4, 0, buffer, 0); position = 0; } // end if: got four characters else if (i == 0) { return -1; } // end else if: also padded correctly else { // Must have broken out from above. throw new java.io.IOException( "Improperly padded Base64 input."); } // end } // end else: decode } // end else: get data // Got data? if (position >= 0) { // End of relevant data? if ( /* !encode && */position >= numSigBytes) return -1; if (encode && breakLines && lineLength >= Base64_MAX_LINE_LENGTH) { lineLength = 0; return '\n'; } // end if else { lineLength++; // This isn't important when decoding // but throwing an extra "if" seems // just as wasteful. int b = buffer[position++]; if (position >= bufferLength) position = -1; return b & 0xFF; // This is how you "cast" a byte that's // intended to be unsigned. } // end else } // end if: position >= 0 // Else error else { // When JDK1.4 is more accepted, use an assertion here. throw new java.io.IOException( "Error in Base64 code reading stream."); } // end else } // end read /** * Calls {@link #read()} repeatedly until the end of stream is reached * or <var>len</var> bytes are read. Returns number of bytes read into * array or -1 if end of stream is encountered. * * @param dest * array to hold values * @param off * offset for array * @param len * max number of bytes to read into array * @return bytes read into array or -1 if end of stream is encountered. * @since 1.3 */ public int read(byte[] dest, int off, int len) throws java.io.IOException { int i; int b; for (i = 0; i < len; i++) { b = read(); // if( b < 0 && i == 0 ) // return -1; if (b >= 0) dest[off + i] = (byte) b; else if (i == 0) return -1; else break; // Out of 'for' loop } // end for: each byte read return i; } // end read } // end inner class InputStream /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ /** * A {@link Base64_OutputStream} will write data to another * <tt>java.io.OutputStream</tt>, given in the constructor, and * encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ private static class Base64_OutputStream extends java.io.FilterOutputStream { private boolean encode; private int position; private byte[] buffer; private int bufferLength; private int lineLength; private boolean breakLines; private byte[] b4; // Scratch used in a few places private boolean suspendEncoding; /** * Constructs a {@link Base64_OutputStream} in ENCODE mode. * * @param out * the <tt>java.io.OutputStream</tt> to which data will be * written. * @since 1.3 */ public Base64_OutputStream(java.io.OutputStream out) { this(out, Base64_ENCODE); } // end constructor /** * Constructs a {@link Base64_OutputStream} in either ENCODE or DECODE * mode. * <p> * Valid options: * * <pre> * ENCODE or DECODE: Encode or Decode as data is read. * DONT_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding) * &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt; * </pre> * * <p> * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code> * * @param out * the <tt>java.io.OutputStream</tt> to which data will be * written. * @param options * Specified options. * @see Base64#Base64_ENCODE * @see Base64#Base64_DECODE * @see Base64#Base64_DONT_BREAK_LINES * @since 1.3 */ public Base64_OutputStream(java.io.OutputStream out, int options) { super(out); this.breakLines = (options & Base64_DONT_BREAK_LINES) != Base64_DONT_BREAK_LINES; this.encode = (options & Base64_ENCODE) == Base64_ENCODE; this.bufferLength = encode ? 3 : 4; this.buffer = new byte[bufferLength]; this.position = 0; this.lineLength = 0; this.suspendEncoding = false; this.b4 = new byte[4]; } // end constructor /** * Writes the byte to the output stream after converting to/from Base64 * notation. When encoding, bytes are buffered three at a time before * the output stream actually gets a write() call. When decoding, bytes * are buffered four at a time. * * @param theByte * the byte to write * @since 1.3 */ public void write(int theByte) throws java.io.IOException { // Encoding suspended? if (suspendEncoding) { super.out.write(theByte); return; } // end if: supsended // Encode? if (encode) { buffer[position++] = (byte) theByte; if (position >= bufferLength) // Enough to encode. { out.write(base64_encode3to4(b4, buffer, bufferLength)); lineLength += 4; if (breakLines && lineLength >= Base64_MAX_LINE_LENGTH) { out.write(Base64_NEW_LINE); lineLength = 0; } // end if: end of line position = 0; } // end if: enough to output } // end if: encoding // Else, Decoding else { // Meaningful Base64 character? if (Base64_DECODABET[theByte & 0x7f] > Base64_WHITE_SPACE_ENC) { buffer[position++] = (byte) theByte; if (position >= bufferLength) // Enough to output. { int len = base64_decode4to3(buffer, 0, b4, 0); out.write(b4, 0, len); // out.write( Base64.decode4to3( buffer ) ); position = 0; } // end if: enough to output } // end if: meaningful base64 character else if (Base64_DECODABET[theByte & 0x7f] != Base64_WHITE_SPACE_ENC) { throw new java.io.IOException( "Invalid character in Base64 data."); } // end else: not white space either } // end else: decoding } // end write /** * Calls {@link #write(int)} repeatedly until <var>len</var> bytes are * written. * * @param theBytes * array from which to read bytes * @param off * offset for array * @param len * max number of bytes to read into array * @since 1.3 */ public void write(byte[] theBytes, int off, int len) throws java.io.IOException { // Encoding suspended? if (suspendEncoding) { super.out.write(theBytes, off, len); return; } // end if: supsended for (int i = 0; i < len; i++) { write(theBytes[off + i]); } // end for: each byte written } // end write /** * Method added by PHIL. [Thanks, PHIL. -Rob] This pads the buffer * without closing the stream. */ public void flushBase64() throws java.io.IOException { if (position > 0) { if (encode) { out.write(base64_encode3to4(b4, buffer, position)); position = 0; } // end if: encoding else { throw new java.io.IOException( "Base64 input not properly padded."); } // end else: decoding } // end if: buffer partially full } // end flush /** * Flushes and closes (I think, in the superclass) the stream. * * @since 1.3 */ public void close() throws java.io.IOException { // 1. Ensure that pending characters are written flushBase64(); // 2. Actually close the stream // Base class both flushes and closes. super.close(); buffer = null; out = null; } // end close /** * Suspends encoding of the stream. May be helpful if you need to embed * a piece of base640-encoded data in a stream. * * @since 1.5.1 */ public void suspendEncoding() throws java.io.IOException { flushBase64(); this.suspendEncoding = true; } // end suspendEncoding /** * Resumes encoding of the stream. May be helpful if you need to embed a * piece of base640-encoded data in a stream. * * @since 1.5.1 */ public void resumeEncoding() { this.suspendEncoding = false; } // end resumeEncoding } // end inner class OutputStream }
Minor corrections svn changeset:160/svn branch:toolkit
src/com/itmill/toolkit/service/License.java
Minor corrections
<ide><path>rc/com/itmill/toolkit/service/License.java <ide> import java.security.cert.X509Certificate; <ide> import java.util.Calendar; <ide> import java.util.Iterator; <del>import java.util.TooManyListenersException; <ide> import java.util.TreeSet; <ide> <ide> import javax.xml.parsers.DocumentBuilder; <ide> import org.w3c.dom.Node; <ide> import org.w3c.dom.NodeList; <ide> import org.xml.sax.SAXException; <add> <add>import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; <ide> <ide> public class License { <ide>
JavaScript
mit
1807a60dbf8e24d08bad6655efa7fa652738de80
0
iuap-design/tinper.org,iuap-design/tinper.org,iuap-design/tinper.org
var fs = require('fs'); var gulp = require('gulp'); var sass = require('gulp-sass'); var path = require('path'); var concat = require('gulp-concat'); var webpack = require('gulp-webpack'); var rename = require('gulp-rename'); var zip = require('gulp-zip'); var clean = require('gulp-clean'); // 获取Neoui es6模块依赖关系 var neojson = require('../bin/neoui.json'); var neoModule = neojson.es6; var koModule = neojson.ko; var zipPath; var tinperPoly = 'tinper-neoui-polyfill'; var tinperNeoui = 'tinper-neoui'; var showError = function(err){ console.log( '\n错误文件:',err.file,'\n错误行数:',err.line,'\n错误信息:',err.message); } module.exports = function(data, self, cb){ /** * Poly Match: polyselect * Neoui Match: neoselect 已作废 * CSS Match:cssselect * JS Match: jsselect */ var dataJson = data; // console.log(dataJson); var basePath = '../node_modules/'; /** * polyfill定制部分 */ var polyBasePath = path.resolve(__dirname, basePath + tinperPoly); var polyJs = []; if(dataJson.polyselect) { for(var pi = 0, polyLen = dataJson.polyselect.length; pi < polyLen; pi++) { polyJs.push(polyBasePath + '/dist/' + dataJson.polyselect[pi] + '.js'); } } gulp.task('poly', function(){ if(polyJs.length === 2){ return gulp.src(polyJs) .pipe(concat('u-polyfill.js')) .pipe(gulp.dest(path.resolve(__dirname,'../download'))); } else if (polyJs.length === 1 && dataJson.polyselect[0] === 'u-polyfill-core') { return gulp.src(polyJs) .pipe(rename('u-polyfill.js')) .pipe(gulp.dest(path.resolve(__dirname,'../download'))); } else if (polyJs.length === 1 && dataJson.polyselect[0] === 'u-polyfill-respond') { return gulp.src(polyJs) .pipe(rename('u-polyfill.js')) .pipe(gulp.dest(path.resolve(__dirname,'../download'))); } else { return ; } }); /** * 模板颜色定制部分 */ var dataColor = dataJson.themeColor; var corPath = path.resolve(__dirname, basePath + tinperNeoui +'/scss/core/minxin-themeColors.scss'); var corData = fs.readFileSync(corPath, 'utf-8'); var corNewData = corData.replace(/(\$color-primary: ).*(;)/g,`$1"${dataColor}"$2`); fs.writeFileSync(corPath,corNewData, 'utf-8'); /** * neoui定制部分 */ // 数组填充 var neouiBasePath = path.resolve(__dirname,basePath + tinperNeoui); var neouiCss =[]; var neouiJs =[]; /** * 以下注释部分为线上scss编译css准备,对应gulp任务为gulp sass */ // if(dataJson.cssselect) { // for (var ci=0; ci<dataJson.cssselect.length; ci++) { // neouiCss.push(neouiBasePath + '/scss/ui/' + dataJson.cssselect[ci] + '.scss'); // } // } // if(dataJson.jsselect) { // for (var ji=0; ji<dataJson.jsselect.length; ji++) { // neouiCss.push(neouiBasePath + '/scss/ui/' + dataJson.jsselect[ji] + '.scss'); // neouiJs.push(neouiBasePath + '/js/' + dataJson.jsselect[ji] + '.js'); // } // // if(dataJson.adselect){ // // console.log('选择ko'); // } // } if(dataJson.cssselect) { for (var ci=0; ci<dataJson.cssselect.length; ci++) { neouiCss.push(neouiBasePath + '/custom/' + dataJson.cssselect[ci] + '.css'); } } if(dataJson.jsselect) { for (var ji=0; ji<dataJson.jsselect.length; ji++) { neouiCss.push(neouiBasePath + '/custom/' + dataJson.jsselect[ji] + '.css'); neouiJs.push(neouiBasePath + '/js/' + dataJson.jsselect[ji] + '.js'); } if(dataJson.adselect){ // console.log('选择ko'); } } // js内容 var entryPath = path.resolve(__dirname,'../entry.js'); var dataNeo = ["import {extend} from \'tinper-sparrow/js/extend\';"]; var ex = {}; var entryFun = function() { if(dataJson.jsselect){ for(var i=0, neoLength = dataJson.jsselect.length; i < neoLength; i++ ) { var pluginModule = neoModule[dataJson.jsselect[i]]; for (var key in pluginModule) { dataNeo.push(pluginModule[key]); ex[key] = key; } } } }; entryFun(); // kero-adapter内容 var dataKo = [""]; var koFun = function(){ if(dataJson.adselect && dataJson.jsselect) { for(var i=0, neoLength = dataJson.jsselect.length; i < neoLength; i++ ) { var koName = 'keroa-' + dataJson.jsselect[i].substr(6); var koObj = koModule[koName]; for(var key in koObj) { dataKo.push(koObj[key]); ex[key] = key; } } } }; koFun(); // 写入入口文件 var dataImport = dataNeo.concat(dataKo).join('\n'); // var dataNeoStr = dataNeo.join('\n'); fs.writeFileSync(entryPath,dataImport); var exBefore = '\nvar ex = '; var exStr = JSON.stringify(ex); var exAfter = [ "\nextend(ex,window.u || {});", "window.u = ex;", "export {ex as u};" ].join("\n"); var exportStr = exBefore + exStr + exAfter; fs.appendFileSync(entryPath,exportStr); // 入口文件字符串替换 var dataFsOrigin = fs.readFileSync(entryPath, 'utf-8'); var dataFs = dataFsOrigin.replace(/:"([\w-]+)"/g,":$1"); fs.writeFileSync(entryPath, dataFs); /** * 取消在线编译 */ // gulp.task('sass', function() { // return gulp.src(neouiCss) // .pipe(sass()).on('error', function(err){ showError(err) }) // .pipe(concat('u.css')) // .pipe(gulp.dest(path.resolve(__dirname,'../download'))) // }); gulp.task('styleconcat',function(){ return gulp.src(neouiCss) .pipe(concat('u.css')) .pipe(gulp.dest(path.resolve(__dirname,'../download'))) }) // js部分 gulp.task('webpack', ['styleconcat','poly'], function() { return gulp.src(path.resolve(__dirname, '../entry.js')) .pipe(webpack({ module:{ loaders:[ { test: /(\.jsx|\.js)$/, loader: 'babel', exclude: /(bower_components)/ } ] }, output:{ filename:'u.js', libraryTarget:'umd', umdNamedDefine: true }, resolve:{ extensions: ['','.js','.jsx'] }, resolveLoader: { root: path.join(__dirname, "../node_modules") } })).on('error', function(err){ showError(err) }) .pipe(gulp.dest(path.resolve(__dirname,'../download'))); }); var downFiles = path.resolve(__dirname, '../download/'); // zip压缩 gulp.task('zip', ['webpack'], function() { return gulp.src([downFiles + '/*.js', downFiles + '/*.css']) .pipe(zip('down.zip')) .pipe(gulp.dest(path.resolve(__dirname, '../download'))); }); gulp.task('clean',['zip'], function(){ return gulp.src([downFiles + '/*.js', downFiles + '/*.css']) .pipe(clean()); }) gulp.start('clean', function(){ zipPath = '/download/down.zip'; console.log(zipPath); self.body = zipPath; cb(null,""); }); // gulp.watch(path.resolve(__dirname, '../entry.js'), ['zip']); };
server/pack.js
var fs = require('fs'); var gulp = require('gulp'); var sass = require('gulp-sass'); var path = require('path'); var concat = require('gulp-concat'); var webpack = require('gulp-webpack'); var rename = require('gulp-rename'); var zip = require('gulp-zip'); var clean = require('gulp-clean'); // 获取Neoui es6模块依赖关系 var neojson = require('../bin/neoui.json'); var neoModule = neojson.es6; var koModule = neojson.ko; var zipPath; var tinperPoly = 'tinper-neoui-polyfill'; var tinperNeoui = 'tinper-neoui'; var showError = function(err){ console.log( '\n错误文件:',err.file,'\n错误行数:',err.line,'\n错误信息:',err.message); } module.exports = function(data, self, cb){ /** * Poly Match: polyselect * Neoui Match: neoselect 已作废 * CSS Match:cssselect * JS Match: jsselect */ var dataJson = data; console.log(dataJson); var basePath = '../node_modules/'; /** * polyfill定制部分 */ var polyBasePath = path.resolve(__dirname, basePath + tinperPoly); var polyJs = []; if(dataJson.polyselect) { for(var pi = 0, polyLen = dataJson.polyselect.length; pi < polyLen; pi++) { polyJs.push(polyBasePath + '/dist/' + dataJson.polyselect[pi] + '.js'); } } gulp.task('poly', function(){ if(polyJs.length === 2){ return gulp.src(polyJs) .pipe(concat('u-polyfill.js')) .pipe(gulp.dest(path.resolve(__dirname,'../download'))); } else if (polyJs.length === 1 && dataJson.polyselect[0] === 'u-polyfill-core') { return gulp.src(polyJs) .pipe(rename('u-polyfill.js')) .pipe(gulp.dest(path.resolve(__dirname,'../download'))); } else if (polyJs.length === 1 && dataJson.polyselect[0] === 'u-polyfill-respond') { return gulp.src(polyJs) .pipe(rename('u-polyfill.js')) .pipe(gulp.dest(path.resolve(__dirname,'../download'))); } else { return ; } }); /** * 模板颜色定制部分 */ var dataColor = dataJson.themeColor; var corPath = path.resolve(__dirname, basePath + tinperNeoui +'/scss/core/minxin-themeColors.scss'); var corData = fs.readFileSync(corPath, 'utf-8'); var corNewData = corData.replace(/(\$color-primary: ).*(;)/g,`$1"${dataColor}"$2`); fs.writeFileSync(corPath,corNewData, 'utf-8'); /** * neoui定制部分 */ // 数组填充 var neouiBasePath = path.resolve(__dirname,basePath + tinperNeoui); var neouiCss =[]; var neouiJs =[]; if(dataJson.cssselect) { for (var ci=0; ci<dataJson.cssselect.length; ci++) { neouiCss.push(neouiBasePath + '/scss/ui/' + dataJson.cssselect[ci] + '.scss'); } } if(dataJson.jsselect) { for (var ji=0; ji<dataJson.jsselect.length; ji++) { neouiCss.push(neouiBasePath + '/scss/ui/' + dataJson.jsselect[ji] + '.scss'); neouiJs.push(neouiBasePath + '/js/' + dataJson.jsselect[ji] + '.js'); } if(dataJson.adselect){ // console.log('选择ko'); } } // js内容 var entryPath = path.resolve(__dirname,'../entry.js'); var dataNeo = ["import {extend} from \'tinper-sparrow/js/extend\';"]; var ex = {}; var entryFun = function() { if(dataJson.jsselect){ for(var i=0, neoLength = dataJson.jsselect.length; i < neoLength; i++ ) { var pluginModule = neoModule[dataJson.jsselect[i]]; for (var key in pluginModule) { dataNeo.push(pluginModule[key]); ex[key] = key; } } } }; entryFun(); // kero-adapter内容 var dataKo = [""]; var koFun = function(){ if(dataJson.adselect && dataJson.jsselect) { for(var i=0, neoLength = dataJson.jsselect.length; i < neoLength; i++ ) { var koName = 'keroa-' + dataJson.jsselect[i].substr(6); var koObj = koModule[koName]; for(var key in koObj) { dataKo.push(koObj[key]); ex[key] = key; } } } }; koFun(); // 写入入口文件 var dataImport = dataNeo.concat(dataKo).join('\n'); // var dataNeoStr = dataNeo.join('\n'); fs.writeFileSync(entryPath,dataImport); var exBefore = '\nvar ex = '; var exStr = JSON.stringify(ex); var exAfter = [ "\nextend(ex,window.u || {});", "window.u = ex;", "export {ex as u};" ].join("\n"); var exportStr = exBefore + exStr + exAfter; fs.appendFileSync(entryPath,exportStr); // 入口文件字符串替换 var dataFsOrigin = fs.readFileSync(entryPath, 'utf-8'); var dataFs = dataFsOrigin.replace(/:"([\w-]+)"/g,":$1"); fs.writeFileSync(entryPath, dataFs); // sass部分 gulp.task('sass', function() { return gulp.src(neouiCss) .pipe(sass()).on('error', function(err){ showError(err) }) .pipe(concat('u.css')) .pipe(gulp.dest(path.resolve(__dirname,'../download'))) }); // js部分 gulp.task('webpack', ['sass','poly'], function() { return gulp.src(path.resolve(__dirname, '../entry.js')) .pipe(webpack({ module:{ loaders:[ { test: /(\.jsx|\.js)$/, loader: 'babel', exclude: /(bower_components)/ } ] }, output:{ filename:'u.js', libraryTarget:'umd', umdNamedDefine: true }, resolve:{ extensions: ['','.js','.jsx'] }, resolveLoader: { root: path.join(__dirname, "../node_modules") } })).on('error', function(err){ showError(err) }) .pipe(gulp.dest(path.resolve(__dirname,'../download'))); }); var downFiles = path.resolve(__dirname, '../download/'); // zip压缩 gulp.task('zip', ['webpack'], function() { return gulp.src([downFiles + '/*.js', downFiles + '/*.css']) .pipe(zip('down.zip')) .pipe(gulp.dest(path.resolve(__dirname, '../download'))); }); gulp.task('clean',['zip'], function(){ return gulp.src([downFiles + '/*.js', downFiles + '/*.css']) .pipe(clean()); }) gulp.start('clean', function(){ zipPath = '/download/down.zip'; console.log(zipPath); self.body = zipPath; cb(null,""); }); // gulp.watch(path.resolve(__dirname, '../entry.js'), ['zip']); };
feat: 取消sass编译,直接合并
server/pack.js
feat: 取消sass编译,直接合并
<ide><path>erver/pack.js <ide> * JS Match: jsselect <ide> */ <ide> var dataJson = data; <del> console.log(dataJson); <add> // console.log(dataJson); <ide> var basePath = '../node_modules/'; <ide> <ide> /** <ide> var neouiBasePath = path.resolve(__dirname,basePath + tinperNeoui); <ide> var neouiCss =[]; <ide> var neouiJs =[]; <add> /** <add> * 以下注释部分为线上scss编译css准备,对应gulp任务为gulp sass <add> */ <add> // if(dataJson.cssselect) { <add> // for (var ci=0; ci<dataJson.cssselect.length; ci++) { <add> // neouiCss.push(neouiBasePath + '/scss/ui/' + dataJson.cssselect[ci] + '.scss'); <add> // } <add> // } <add> // if(dataJson.jsselect) { <add> // for (var ji=0; ji<dataJson.jsselect.length; ji++) { <add> // neouiCss.push(neouiBasePath + '/scss/ui/' + dataJson.jsselect[ji] + '.scss'); <add> // neouiJs.push(neouiBasePath + '/js/' + dataJson.jsselect[ji] + '.js'); <add> // } <add> // <add> // if(dataJson.adselect){ <add> // // console.log('选择ko'); <add> // } <add> // } <add> <ide> if(dataJson.cssselect) { <ide> for (var ci=0; ci<dataJson.cssselect.length; ci++) { <del> neouiCss.push(neouiBasePath + '/scss/ui/' + dataJson.cssselect[ci] + '.scss'); <add> neouiCss.push(neouiBasePath + '/custom/' + dataJson.cssselect[ci] + '.css'); <ide> } <ide> } <ide> if(dataJson.jsselect) { <ide> for (var ji=0; ji<dataJson.jsselect.length; ji++) { <del> neouiCss.push(neouiBasePath + '/scss/ui/' + dataJson.jsselect[ji] + '.scss'); <add> neouiCss.push(neouiBasePath + '/custom/' + dataJson.jsselect[ji] + '.css'); <ide> neouiJs.push(neouiBasePath + '/js/' + dataJson.jsselect[ji] + '.js'); <ide> } <ide> <ide> <ide> <ide> <del> // sass部分 <del> gulp.task('sass', function() { <add> /** <add> * 取消在线编译 <add> */ <add> // gulp.task('sass', function() { <add> // return gulp.src(neouiCss) <add> // .pipe(sass()).on('error', function(err){ showError(err) }) <add> // .pipe(concat('u.css')) <add> // .pipe(gulp.dest(path.resolve(__dirname,'../download'))) <add> // }); <add> <add> gulp.task('styleconcat',function(){ <ide> return gulp.src(neouiCss) <del> .pipe(sass()).on('error', function(err){ showError(err) }) <del> .pipe(concat('u.css')) <del> .pipe(gulp.dest(path.resolve(__dirname,'../download'))) <del> }); <add> .pipe(concat('u.css')) <add> .pipe(gulp.dest(path.resolve(__dirname,'../download'))) <add> }) <ide> <ide> // js部分 <del> gulp.task('webpack', ['sass','poly'], function() { <add> gulp.task('webpack', ['styleconcat','poly'], function() { <ide> return gulp.src(path.resolve(__dirname, '../entry.js')) <ide> .pipe(webpack({ <ide> module:{
Java
apache-2.0
f31d6465944adb4e4a6b66f4e35538610e6f4bbd
0
apache/helix,dasahcc/helix,apache/helix,lei-xia/helix,lei-xia/helix,lei-xia/helix,lei-xia/helix,dasahcc/helix,lei-xia/helix,dasahcc/helix,apache/helix,apache/helix,lei-xia/helix,apache/helix,dasahcc/helix,apache/helix,dasahcc/helix,dasahcc/helix
package org.apache.helix.monitoring.mbeans; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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. */ import com.codahale.metrics.Histogram; import com.codahale.metrics.SlidingTimeWindowArrayReservoir; import java.util.concurrent.TimeUnit; import org.apache.helix.HelixDefinedState; import org.apache.helix.model.ExternalView; import org.apache.helix.model.IdealState; import org.apache.helix.model.StateModelDefinition; import org.apache.helix.monitoring.mbeans.dynamicMBeans.DynamicMBeanProvider; import org.apache.helix.monitoring.mbeans.dynamicMBeans.DynamicMetric; import org.apache.helix.monitoring.mbeans.dynamicMBeans.HistogramDynamicMetric; import org.apache.helix.monitoring.mbeans.dynamicMBeans.SimpleDynamicMetric; import javax.management.JMException; import javax.management.ObjectName; import java.util.*; public class ResourceMonitor extends DynamicMBeanProvider { // Gauges private SimpleDynamicMetric<Integer> _numOfPartitions; private SimpleDynamicMetric<Integer> _numOfPartitionsInExternalView; private SimpleDynamicMetric<Integer> _numOfErrorPartitions; private SimpleDynamicMetric<Integer> _numNonTopStatePartitions; private SimpleDynamicMetric<Long> _numLessMinActiveReplicaPartitions; private SimpleDynamicMetric<Long> _numLessReplicaPartitions; private SimpleDynamicMetric<Long> _numPendingRecoveryRebalancePartitions; private SimpleDynamicMetric<Long> _numPendingLoadRebalancePartitions; private SimpleDynamicMetric<Long> _numRecoveryRebalanceThrottledPartitions; private SimpleDynamicMetric<Long> _numLoadRebalanceThrottledPartitions; private SimpleDynamicMetric<Integer> _externalViewIdealStateDiff; // Counters private SimpleDynamicMetric<Long> _successfulTopStateHandoffDurationCounter; private SimpleDynamicMetric<Long> _successTopStateHandoffCounter; private SimpleDynamicMetric<Long> _failedTopStateHandoffCounter; private SimpleDynamicMetric<Long> _maxSinglePartitionTopStateHandoffDuration; private HistogramDynamicMetric _partitionTopStateHandoffDurationGauge; private SimpleDynamicMetric<Long> _totalMessageReceived; private String _tag = ClusterStatusMonitor.DEFAULT_TAG; private long _lastResetTime; private final String _resourceName; private final String _clusterName; private final ObjectName _initObjectName; @Override public ResourceMonitor register() throws JMException { List<DynamicMetric<?, ?>> attributeList = new ArrayList<>(); attributeList.add(_numOfPartitions); attributeList.add(_numOfPartitionsInExternalView); attributeList.add(_numOfErrorPartitions); attributeList.add(_numNonTopStatePartitions); attributeList.add(_numLessMinActiveReplicaPartitions); attributeList.add(_numLessReplicaPartitions); attributeList.add(_numPendingRecoveryRebalancePartitions); attributeList.add(_numPendingLoadRebalancePartitions); attributeList.add(_numRecoveryRebalanceThrottledPartitions); attributeList.add(_numLoadRebalanceThrottledPartitions); attributeList.add(_externalViewIdealStateDiff); attributeList.add(_successfulTopStateHandoffDurationCounter); attributeList.add(_successTopStateHandoffCounter); attributeList.add(_failedTopStateHandoffCounter); attributeList.add(_maxSinglePartitionTopStateHandoffDuration); attributeList.add(_partitionTopStateHandoffDurationGauge); attributeList.add(_totalMessageReceived); doRegister(attributeList, _initObjectName); return this; } public enum MonitorState { TOP_STATE } public ResourceMonitor(String clusterName, String resourceName, ObjectName objectName) throws JMException { _clusterName = clusterName; _resourceName = resourceName; _initObjectName = objectName; _externalViewIdealStateDiff = new SimpleDynamicMetric("DifferenceWithIdealStateGauge", 0l); _numLoadRebalanceThrottledPartitions = new SimpleDynamicMetric("LoadRebalanceThrottledPartitionGauge", 0l); _numRecoveryRebalanceThrottledPartitions = new SimpleDynamicMetric("RecoveryRebalanceThrottledPartitionGauge", 0l); _numPendingLoadRebalancePartitions = new SimpleDynamicMetric("PendingLoadRebalancePartitionGauge", 0l); _numPendingRecoveryRebalancePartitions = new SimpleDynamicMetric("PendingRecoveryRebalancePartitionGauge", 0l); _numLessReplicaPartitions = new SimpleDynamicMetric("MissingReplicaPartitionGauge", 0l); _numLessMinActiveReplicaPartitions = new SimpleDynamicMetric("MissingMinActiveReplicaPartitionGauge", 0l); _numNonTopStatePartitions = new SimpleDynamicMetric("MissingTopStatePartitionGauge", 0l); _numOfErrorPartitions = new SimpleDynamicMetric("ErrorPartitionGauge", 0l); _numOfPartitionsInExternalView = new SimpleDynamicMetric("ExternalViewPartitionGauge", 0l); _numOfPartitions = new SimpleDynamicMetric("PartitionGauge", 0l); _partitionTopStateHandoffDurationGauge = new HistogramDynamicMetric("PartitionTopStateHandoffDurationGauge", new Histogram( new SlidingTimeWindowArrayReservoir(DEFAULT_RESET_INTERVAL_MS, TimeUnit.MILLISECONDS))); _totalMessageReceived = new SimpleDynamicMetric("TotalMessageReceived", 0l); _maxSinglePartitionTopStateHandoffDuration = new SimpleDynamicMetric("MaxSinglePartitionTopStateHandoffDurationGauge", 0l); _failedTopStateHandoffCounter = new SimpleDynamicMetric("FailedTopStateHandoffCounter", 0l); _successTopStateHandoffCounter = new SimpleDynamicMetric("SucceededTopStateHandoffCounter", 0l); _successfulTopStateHandoffDurationCounter = new SimpleDynamicMetric("SuccessfulTopStateHandoffDurationCounter", 0l); } @Override public String getSensorName() { return String .format("%s.%s.%s.%s", ClusterStatusMonitor.RESOURCE_STATUS_KEY, _clusterName, _tag, _resourceName); } public long getPartitionGauge() { return _numOfPartitions.getValue(); } public long getErrorPartitionGauge() { return _numOfErrorPartitions.getValue(); } public long getMissingTopStatePartitionGauge() { return _numNonTopStatePartitions.getValue(); } public long getDifferenceWithIdealStateGauge() { return _externalViewIdealStateDiff.getValue(); } public long getSuccessfulTopStateHandoffDurationCounter() { return _successfulTopStateHandoffDurationCounter.getValue(); } public long getSucceededTopStateHandoffCounter() { return _successTopStateHandoffCounter.getValue(); } public long getMaxSinglePartitionTopStateHandoffDurationGauge() { return _maxSinglePartitionTopStateHandoffDuration.getValue(); } public long getFailedTopStateHandoffCounter() { return _failedTopStateHandoffCounter.getValue(); } public long getTotalMessageReceived() { return _totalMessageReceived.getValue(); } public synchronized void increaseMessageCount(long messageReceived) { _totalMessageReceived.updateValue(_totalMessageReceived.getValue() + messageReceived); } public String getResourceName() { return _resourceName; } public String getBeanName() { return _clusterName + " " + _resourceName; } public void updateResource(ExternalView externalView, IdealState idealState, StateModelDefinition stateModelDef) { if (externalView == null) { _logger.warn("External view is null"); return; } String topState = null; if (stateModelDef != null) { List<String> priorityList = stateModelDef.getStatesPriorityList(); if (!priorityList.isEmpty()) { topState = priorityList.get(0); } } resetGauges(); if (idealState == null) { _logger.warn("ideal state is null for " + _resourceName); return; } assert (_resourceName.equals(idealState.getId())); assert (_resourceName.equals(externalView.getId())); int numOfErrorPartitions = 0; int numOfDiff = 0; int numOfPartitionWithTopState = 0; Set<String> partitions = idealState.getPartitionSet(); _numOfPartitions.updateValue(partitions.size()); int replica = -1; try { replica = Integer.valueOf(idealState.getReplicas()); } catch (NumberFormatException e) { _logger.error("Invalid replica count for " + _resourceName + ", failed to update its ResourceMonitor Mbean!"); return; } int minActiveReplica = idealState.getMinActiveReplicas(); minActiveReplica = (minActiveReplica >= 0) ? minActiveReplica : replica; Set<String> activeStates = new HashSet<>(stateModelDef.getStatesPriorityList()); activeStates.remove(stateModelDef.getInitialState()); activeStates.remove(HelixDefinedState.DROPPED.name()); activeStates.remove(HelixDefinedState.ERROR.name()); for (String partition : partitions) { Map<String, String> idealRecord = idealState.getInstanceStateMap(partition); Map<String, String> externalViewRecord = externalView.getStateMap(partition); if (idealRecord == null) { idealRecord = Collections.emptyMap(); } if (externalViewRecord == null) { externalViewRecord = Collections.emptyMap(); } if (!idealRecord.entrySet().equals(externalViewRecord.entrySet())) { numOfDiff++; } int activeReplicaCount = 0; boolean hasTopState = false; for (String host : externalViewRecord.keySet()) { String currentState = externalViewRecord.get(host); if (HelixDefinedState.ERROR.toString().equalsIgnoreCase(currentState)) { numOfErrorPartitions++; } if (topState != null && topState.equalsIgnoreCase(currentState)) { hasTopState = true; } if (currentState != null && activeStates.contains(currentState)) { activeReplicaCount++; } } if (hasTopState) { numOfPartitionWithTopState ++; } if (replica > 0 && activeReplicaCount < replica) { _numLessReplicaPartitions.updateValue(_numLessReplicaPartitions.getValue() + 1); } if (minActiveReplica >= 0 && activeReplicaCount < minActiveReplica) { _numLessMinActiveReplicaPartitions .updateValue(_numLessMinActiveReplicaPartitions.getValue() + 1); } } _numOfErrorPartitions.updateValue(numOfErrorPartitions); _externalViewIdealStateDiff.updateValue(numOfDiff); _numOfPartitionsInExternalView.updateValue(externalView.getPartitionSet().size()); _numNonTopStatePartitions.updateValue(_numOfPartitions.getValue() - numOfPartitionWithTopState); String tag = idealState.getInstanceGroupTag(); if (tag == null || tag.equals("") || tag.equals("null")) { _tag = ClusterStatusMonitor.DEFAULT_TAG; } else { _tag = tag; } } private void resetGauges() { _numOfErrorPartitions.updateValue(0); _numNonTopStatePartitions.updateValue(0); _externalViewIdealStateDiff.updateValue(0); _numOfPartitionsInExternalView.updateValue(0); _numLessMinActiveReplicaPartitions.updateValue(0l); _numLessReplicaPartitions.updateValue(0l); _numPendingRecoveryRebalancePartitions.updateValue(0l); _numPendingLoadRebalancePartitions.updateValue(0l); _numRecoveryRebalanceThrottledPartitions.updateValue(0l); _numLoadRebalanceThrottledPartitions.updateValue(0l); } public void updateStateHandoffStats(MonitorState monitorState, long duration, boolean succeeded) { switch (monitorState) { case TOP_STATE: if (succeeded) { _successTopStateHandoffCounter.updateValue(_successTopStateHandoffCounter.getValue() + 1); _successfulTopStateHandoffDurationCounter .updateValue(_successfulTopStateHandoffDurationCounter.getValue() + duration); _partitionTopStateHandoffDurationGauge.updateValue(duration); if (duration > _maxSinglePartitionTopStateHandoffDuration.getValue()) { _maxSinglePartitionTopStateHandoffDuration.updateValue(duration); _lastResetTime = System.currentTimeMillis(); } } else { _failedTopStateHandoffCounter.updateValue(_failedTopStateHandoffCounter.getValue() + 1); } break; default: _logger.warn( String.format("Wrong monitor state \"%s\" that not supported ", monitorState.name())); } } public void updateRebalancerStat(long numPendingRecoveryRebalancePartitions, long numPendingLoadRebalancePartitions, long numRecoveryRebalanceThrottledPartitions, long numLoadRebalanceThrottledPartitions) { _numPendingRecoveryRebalancePartitions.updateValue(numPendingRecoveryRebalancePartitions); _numPendingLoadRebalancePartitions.updateValue(numPendingLoadRebalancePartitions); _numRecoveryRebalanceThrottledPartitions.updateValue(numRecoveryRebalanceThrottledPartitions); _numLoadRebalanceThrottledPartitions.updateValue(numLoadRebalanceThrottledPartitions); } public long getExternalViewPartitionGauge() { return _numOfPartitionsInExternalView.getValue(); } public long getMissingMinActiveReplicaPartitionGauge() { return _numLessMinActiveReplicaPartitions.getValue(); } public long getMissingReplicaPartitionGauge() { return _numLessReplicaPartitions.getValue(); } public long getPendingRecoveryRebalancePartitionGauge() { return _numPendingRecoveryRebalancePartitions.getValue(); } public long getPendingLoadRebalancePartitionGauge() { return _numPendingLoadRebalancePartitions.getValue(); } public long getRecoveryRebalanceThrottledPartitionGauge() { return _numRecoveryRebalanceThrottledPartitions.getValue(); } public long getLoadRebalanceThrottledPartitionGauge() { return _numLoadRebalanceThrottledPartitions.getValue(); } public void resetMaxTopStateHandoffGauge() { if (_lastResetTime + DEFAULT_RESET_INTERVAL_MS <= System.currentTimeMillis()) { _maxSinglePartitionTopStateHandoffDuration.updateValue(0l); _lastResetTime = System.currentTimeMillis(); } } }
helix-core/src/main/java/org/apache/helix/monitoring/mbeans/ResourceMonitor.java
package org.apache.helix.monitoring.mbeans; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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. */ import com.codahale.metrics.Histogram; import com.codahale.metrics.SlidingTimeWindowArrayReservoir; import java.util.concurrent.TimeUnit; import org.apache.helix.HelixDefinedState; import org.apache.helix.model.ExternalView; import org.apache.helix.model.IdealState; import org.apache.helix.model.StateModelDefinition; import org.apache.helix.monitoring.mbeans.dynamicMBeans.DynamicMBeanProvider; import org.apache.helix.monitoring.mbeans.dynamicMBeans.DynamicMetric; import org.apache.helix.monitoring.mbeans.dynamicMBeans.HistogramDynamicMetric; import org.apache.helix.monitoring.mbeans.dynamicMBeans.SimpleDynamicMetric; import javax.management.JMException; import javax.management.ObjectName; import java.util.*; public class ResourceMonitor extends DynamicMBeanProvider { // Gauges private SimpleDynamicMetric<Integer> _numOfPartitions; private SimpleDynamicMetric<Integer> _numOfPartitionsInExternalView; private SimpleDynamicMetric<Integer> _numOfErrorPartitions; private SimpleDynamicMetric<Integer> _numNonTopStatePartitions; private SimpleDynamicMetric<Long> _numLessMinActiveReplicaPartitions; private SimpleDynamicMetric<Long> _numLessReplicaPartitions; private SimpleDynamicMetric<Long> _numPendingRecoveryRebalancePartitions; private SimpleDynamicMetric<Long> _numPendingLoadRebalancePartitions; private SimpleDynamicMetric<Long> _numRecoveryRebalanceThrottledPartitions; private SimpleDynamicMetric<Long> _numLoadRebalanceThrottledPartitions; private SimpleDynamicMetric<Integer> _externalViewIdealStateDiff; // Counters private SimpleDynamicMetric<Long> _successfulTopStateHandoffDurationCounter; private SimpleDynamicMetric<Long> _successTopStateHandoffCounter; private SimpleDynamicMetric<Long> _failedTopStateHandoffCounter; private SimpleDynamicMetric<Long> _maxSinglePartitionTopStateHandoffDuration; private HistogramDynamicMetric _partitionTopStateHandoffDurationGauge; private SimpleDynamicMetric<Long> _totalMessageReceived; private String _tag = ClusterStatusMonitor.DEFAULT_TAG; private long _lastResetTime; private final String _resourceName; private final String _clusterName; private final ObjectName _initObjectName; @Override public ResourceMonitor register() throws JMException { List<DynamicMetric<?, ?>> attributeList = new ArrayList<>(); attributeList.add(_numOfPartitions); attributeList.add(_numOfPartitionsInExternalView); attributeList.add(_numOfErrorPartitions); attributeList.add(_numNonTopStatePartitions); attributeList.add(_numLessMinActiveReplicaPartitions); attributeList.add(_numLessReplicaPartitions); attributeList.add(_numPendingRecoveryRebalancePartitions); attributeList.add(_numPendingLoadRebalancePartitions); attributeList.add(_numRecoveryRebalanceThrottledPartitions); attributeList.add(_numLoadRebalanceThrottledPartitions); attributeList.add(_externalViewIdealStateDiff); attributeList.add(_successfulTopStateHandoffDurationCounter); attributeList.add(_successTopStateHandoffCounter); attributeList.add(_failedTopStateHandoffCounter); attributeList.add(_maxSinglePartitionTopStateHandoffDuration); attributeList.add(_partitionTopStateHandoffDurationGauge); attributeList.add(_totalMessageReceived); doRegister(attributeList, _initObjectName); return this; } public enum MonitorState { TOP_STATE } public ResourceMonitor(String clusterName, String resourceName, ObjectName objectName) throws JMException { _clusterName = clusterName; _resourceName = resourceName; _initObjectName = objectName; _externalViewIdealStateDiff = new SimpleDynamicMetric("DifferenceWithIdealStateGauge", 0l); _numLoadRebalanceThrottledPartitions = new SimpleDynamicMetric("LoadRebalanceThrottledPartitionGauge", 0l); _numRecoveryRebalanceThrottledPartitions = new SimpleDynamicMetric("RecoveryRebalanceThrottledPartitionGauge", 0l); _numPendingLoadRebalancePartitions = new SimpleDynamicMetric("PendingLoadRebalancePartitionGauge", 0l); _numPendingRecoveryRebalancePartitions = new SimpleDynamicMetric("PendingRecoveryRebalancePartitionGauge", 0l); _numLessReplicaPartitions = new SimpleDynamicMetric("MissingReplicaPartitionGauge", 0l); _numLessMinActiveReplicaPartitions = new SimpleDynamicMetric("MissingMinActiveReplicaPartitionGauge", 0l); _numNonTopStatePartitions = new SimpleDynamicMetric("MissingTopStatePartitionGauge", 0l); _numOfErrorPartitions = new SimpleDynamicMetric("ErrorPartitionGauge", 0l); _numOfPartitionsInExternalView = new SimpleDynamicMetric("ExternalViewPartitionGauge", 0l); _numOfPartitions = new SimpleDynamicMetric("PartitionGauge", 0l); _partitionTopStateHandoffDurationGauge = new HistogramDynamicMetric("PartitionTopStateHandoffDurationGauge", new Histogram( new SlidingTimeWindowArrayReservoir(DEFAULT_RESET_INTERVAL_MS, TimeUnit.MILLISECONDS))); _totalMessageReceived = new SimpleDynamicMetric("TotalMessageReceived", 0l); _maxSinglePartitionTopStateHandoffDuration = new SimpleDynamicMetric("MaxSinglePartitionTopStateHandoffDurationGauge", 0l); _failedTopStateHandoffCounter = new SimpleDynamicMetric("FailedTopStateHandoffCounter", 0l); _successTopStateHandoffCounter = new SimpleDynamicMetric("SucceededTopStateHandoffCounter", 0l); _successfulTopStateHandoffDurationCounter = new SimpleDynamicMetric("SuccessfulTopStateHandoffDurationCounter", 0l); } @Override public String getSensorName() { return String .format("%s.%s.%s.%s", ClusterStatusMonitor.RESOURCE_STATUS_KEY, _clusterName, _tag, _resourceName); } public long getPartitionGauge() { return _numOfPartitions.getValue(); } public long getErrorPartitionGauge() { return _numOfErrorPartitions.getValue(); } public long getMissingTopStatePartitionGauge() { return _numNonTopStatePartitions.getValue(); } public long getDifferenceWithIdealStateGauge() { return _externalViewIdealStateDiff.getValue(); } public long getSuccessfulTopStateHandoffDurationCounter() { return _successfulTopStateHandoffDurationCounter.getValue(); } public long getSucceededTopStateHandoffCounter() { return _successTopStateHandoffCounter.getValue(); } public long getMaxSinglePartitionTopStateHandoffDurationGauge() { return _maxSinglePartitionTopStateHandoffDuration.getValue(); } public long getFailedTopStateHandoffCounter() { return _failedTopStateHandoffCounter.getValue(); } public long getTotalMessageReceived() { return _totalMessageReceived.getValue(); } public synchronized void increaseMessageCount(long messageReceived) { _totalMessageReceived.updateValue(_totalMessageReceived.getValue() + messageReceived); } public String getResourceName() { return _resourceName; } public String getBeanName() { return _clusterName + " " + _resourceName; } public void updateResource(ExternalView externalView, IdealState idealState, StateModelDefinition stateModelDef) { if (externalView == null) { _logger.warn("External view is null"); return; } String topState = null; if (stateModelDef != null) { List<String> priorityList = stateModelDef.getStatesPriorityList(); if (!priorityList.isEmpty()) { topState = priorityList.get(0); } } resetGauges(); if (idealState == null) { _logger.warn("ideal state is null for " + _resourceName); return; } assert (_resourceName.equals(idealState.getId())); assert (_resourceName.equals(externalView.getId())); int numOfErrorPartitions = 0; int numOfDiff = 0; int numOfPartitionWithTopState = 0; Set<String> partitions = idealState.getPartitionSet(); _numOfPartitions.updateValue(partitions.size()); int replica = -1; try { replica = Integer.valueOf(idealState.getReplicas()); } catch (NumberFormatException e) { } int minActiveReplica = idealState.getMinActiveReplicas(); minActiveReplica = (minActiveReplica >= 0) ? minActiveReplica : replica; for (String partition : partitions) { Map<String, String> idealRecord = idealState.getInstanceStateMap(partition); Map<String, String> externalViewRecord = externalView.getStateMap(partition); if (idealRecord == null) { idealRecord = Collections.emptyMap(); } if (externalViewRecord == null) { externalViewRecord = Collections.emptyMap(); } if (!idealRecord.entrySet().equals(externalViewRecord.entrySet())) { numOfDiff++; } int activeReplicaCount = 0; boolean hasTopState = false; for (String host : externalViewRecord.keySet()) { String currentState = externalViewRecord.get(host); if (HelixDefinedState.ERROR.toString().equalsIgnoreCase(currentState)) { numOfErrorPartitions++; } if (topState != null && topState.equalsIgnoreCase(currentState)) { hasTopState = true; } Map<String, Integer> stateCount = stateModelDef.getStateCountMap(idealRecord.size(), replica); Set<String> activeStates = stateCount.keySet(); if (currentState != null && activeStates.contains(currentState)) { activeReplicaCount++; } } if (hasTopState) { numOfPartitionWithTopState ++; } if (replica > 0 && activeReplicaCount < replica) { _numLessReplicaPartitions.updateValue(_numLessReplicaPartitions.getValue() + 1); } if (minActiveReplica >= 0 && activeReplicaCount < minActiveReplica) { _numLessMinActiveReplicaPartitions .updateValue(_numLessMinActiveReplicaPartitions.getValue() + 1); } } _numOfErrorPartitions.updateValue(numOfErrorPartitions); _externalViewIdealStateDiff.updateValue(numOfDiff); _numOfPartitionsInExternalView.updateValue(externalView.getPartitionSet().size()); _numNonTopStatePartitions.updateValue(_numOfPartitions.getValue() - numOfPartitionWithTopState); String tag = idealState.getInstanceGroupTag(); if (tag == null || tag.equals("") || tag.equals("null")) { _tag = ClusterStatusMonitor.DEFAULT_TAG; } else { _tag = tag; } } private void resetGauges() { _numOfErrorPartitions.updateValue(0); _numNonTopStatePartitions.updateValue(0); _externalViewIdealStateDiff.updateValue(0); _numOfPartitionsInExternalView.updateValue(0); _numLessMinActiveReplicaPartitions.updateValue(0l); _numLessReplicaPartitions.updateValue(0l); _numPendingRecoveryRebalancePartitions.updateValue(0l); _numPendingLoadRebalancePartitions.updateValue(0l); _numRecoveryRebalanceThrottledPartitions.updateValue(0l); _numLoadRebalanceThrottledPartitions.updateValue(0l); } public void updateStateHandoffStats(MonitorState monitorState, long duration, boolean succeeded) { switch (monitorState) { case TOP_STATE: if (succeeded) { _successTopStateHandoffCounter.updateValue(_successTopStateHandoffCounter.getValue() + 1); _successfulTopStateHandoffDurationCounter .updateValue(_successfulTopStateHandoffDurationCounter.getValue() + duration); _partitionTopStateHandoffDurationGauge.updateValue(duration); if (duration > _maxSinglePartitionTopStateHandoffDuration.getValue()) { _maxSinglePartitionTopStateHandoffDuration.updateValue(duration); _lastResetTime = System.currentTimeMillis(); } } else { _failedTopStateHandoffCounter.updateValue(_failedTopStateHandoffCounter.getValue() + 1); } break; default: _logger.warn( String.format("Wrong monitor state \"%s\" that not supported ", monitorState.name())); } } public void updateRebalancerStat(long numPendingRecoveryRebalancePartitions, long numPendingLoadRebalancePartitions, long numRecoveryRebalanceThrottledPartitions, long numLoadRebalanceThrottledPartitions) { _numPendingRecoveryRebalancePartitions.updateValue(numPendingRecoveryRebalancePartitions); _numPendingLoadRebalancePartitions.updateValue(numPendingLoadRebalancePartitions); _numRecoveryRebalanceThrottledPartitions.updateValue(numRecoveryRebalanceThrottledPartitions); _numLoadRebalanceThrottledPartitions.updateValue(numLoadRebalanceThrottledPartitions); } public long getExternalViewPartitionGauge() { return _numOfPartitionsInExternalView.getValue(); } public long getMissingMinActiveReplicaPartitionGauge() { return _numLessMinActiveReplicaPartitions.getValue(); } public long getMissingReplicaPartitionGauge() { return _numLessReplicaPartitions.getValue(); } public long getPendingRecoveryRebalancePartitionGauge() { return _numPendingRecoveryRebalancePartitions.getValue(); } public long getPendingLoadRebalancePartitionGauge() { return _numPendingLoadRebalancePartitions.getValue(); } public long getRecoveryRebalanceThrottledPartitionGauge() { return _numRecoveryRebalanceThrottledPartitions.getValue(); } public long getLoadRebalanceThrottledPartitionGauge() { return _numLoadRebalanceThrottledPartitions.getValue(); } public void resetMaxTopStateHandoffGauge() { if (_lastResetTime + DEFAULT_RESET_INTERVAL_MS <= System.currentTimeMillis()) { _maxSinglePartitionTopStateHandoffDuration.updateValue(0l); _lastResetTime = System.currentTimeMillis(); } } }
Fix issue in reporting MissingMinActiveReplicaPartitionGauge metric in ResourceMonitor when there is no IdealMapping persisted in IdealState.
helix-core/src/main/java/org/apache/helix/monitoring/mbeans/ResourceMonitor.java
Fix issue in reporting MissingMinActiveReplicaPartitionGauge metric in ResourceMonitor when there is no IdealMapping persisted in IdealState.
<ide><path>elix-core/src/main/java/org/apache/helix/monitoring/mbeans/ResourceMonitor.java <ide> try { <ide> replica = Integer.valueOf(idealState.getReplicas()); <ide> } catch (NumberFormatException e) { <add> _logger.error("Invalid replica count for " + _resourceName + ", failed to update its ResourceMonitor Mbean!"); <add> return; <ide> } <ide> <ide> int minActiveReplica = idealState.getMinActiveReplicas(); <ide> minActiveReplica = (minActiveReplica >= 0) ? minActiveReplica : replica; <add> <add> Set<String> activeStates = new HashSet<>(stateModelDef.getStatesPriorityList()); <add> activeStates.remove(stateModelDef.getInitialState()); <add> activeStates.remove(HelixDefinedState.DROPPED.name()); <add> activeStates.remove(HelixDefinedState.ERROR.name()); <ide> <ide> for (String partition : partitions) { <ide> Map<String, String> idealRecord = idealState.getInstanceStateMap(partition); <ide> if (topState != null && topState.equalsIgnoreCase(currentState)) { <ide> hasTopState = true; <ide> } <del> <del> Map<String, Integer> stateCount = <del> stateModelDef.getStateCountMap(idealRecord.size(), replica); <del> Set<String> activeStates = stateCount.keySet(); <ide> if (currentState != null && activeStates.contains(currentState)) { <ide> activeReplicaCount++; <ide> }
Java
lgpl-2.1
ba6c3133d47b28d8ab81cc0b4bfb92463bf139f6
0
bjalon/nuxeo-features,deadcyclo/nuxeo-features,nuxeo-archives/nuxeo-features,deadcyclo/nuxeo-features,bjalon/nuxeo-features,nuxeo-archives/nuxeo-features,bjalon/nuxeo-features,nuxeo-archives/nuxeo-features,bjalon/nuxeo-features,nuxeo-archives/nuxeo-features,deadcyclo/nuxeo-features,nuxeo-archives/nuxeo-features,deadcyclo/nuxeo-features,deadcyclo/nuxeo-features,bjalon/nuxeo-features,bjalon/nuxeo-features,deadcyclo/nuxeo-features
package org.nuxeo.ecm.automation.jaxrs.io.documents; import static org.nuxeo.ecm.core.api.security.SecurityConstants.BROWSE; import static org.nuxeo.ecm.core.api.security.SecurityConstants.EVERYONE; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.ws.rs.Produces; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.ext.Provider; import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonGenerator; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.security.ACE; import org.nuxeo.ecm.core.api.security.ACL; import org.nuxeo.ecm.core.api.security.ACP; import org.nuxeo.ecm.core.security.SecurityService; import org.nuxeo.ecm.platform.tag.Tag; import org.nuxeo.ecm.platform.tag.TagService; import org.nuxeo.runtime.api.Framework; /** * JSon writer that outputs a format ready to eat by elasticsearch. * * * @since 5.9.3 */ @Provider @Produces({ JsonESDocumentWriter.MIME_TYPE }) public class JsonESDocumentWriter extends JsonDocumentWriter { public static final String MIME_TYPE = "application/json+esentity"; @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return super.isWriteable(type, genericType, annotations, mediaType) && MIME_TYPE.equals(mediaType.toString()); } public static void writeDoc(JsonGenerator jg, DocumentModel doc, String[] schemas, Map<String, String> contextParameters, HttpHeaders headers) throws Exception { jg.writeStartObject(); jg.writeStringField("ecm:repository", doc.getRepositoryName()); jg.writeStringField("ecm:uuid", doc.getId()); jg.writeStringField("ecm:name", doc.getName()); jg.writeStringField("ecm:title", doc.getTitle()); jg.writeStringField("ecm:path", doc.getPathAsString()); jg.writeStringField("ecm:primaryType", doc.getType()); jg.writeStringField("ecm:parentId", doc.getParentRef().toString()); jg.writeStringField("ecm:currentLifeCycleState", doc.getCurrentLifeCycleState()); jg.writeStringField("ecm:versionLabel", doc.getVersionLabel()); jg.writeBooleanField("ecm:isCheckedIn", !doc.isCheckedOut()); jg.writeBooleanField("ecm:isProxy", doc.isProxy()); jg.writeBooleanField("ecm:isVersion", doc.isVersion()); jg.writeArrayFieldStart("ecm:mixinType"); for (String facet : doc.getFacets()) { jg.writeString(facet); } jg.writeEndArray(); TagService tagService = Framework.getService(TagService.class); if (tagService != null) { jg.writeArrayFieldStart("ecm:tag"); for (Tag tag : tagService.getDocumentTags(doc.getCoreSession(), doc.getId(), null)) { jg.writeString(tag.getLabel()); } jg.writeEndArray(); } jg.writeStringField("ecm:changeToken", doc.getChangeToken()); // Add a positive ACL only SecurityService securityService = Framework.getService(SecurityService.class); List<String> browsePermissions = new ArrayList<String>( Arrays.asList(securityService.getPermissionsToCheck(BROWSE))); ACP acp = doc.getACP(); ACL acl = acp.getACL(ACL.INHERITED_ACL); if (acl==null) { // blocked inheritance at this level acl = acp.getACL(ACL.LOCAL_ACL); } jg.writeArrayFieldStart("ecm:acl"); for (ACE ace : acl.getACEs()) { if (ace.isGranted() && browsePermissions.contains(ace.getPermission())) { jg.writeString(ace.getUsername()); } if (ace.isDenied()) { if (!EVERYONE.equals(ace.getUsername())) { jg.writeString("UNSUPPORTED_DENIED_ACL"); } break; } } jg.writeEndArray(); // TODO Add binary fulltext if (schemas == null || (schemas.length == 1 && "*".equals(schemas[0]))) { schemas = doc.getSchemas(); } for (String schema : schemas) { writeProperties(jg, doc, schema, null); } if (contextParameters != null && !contextParameters.isEmpty()) { for (Map.Entry<String, String> parameter : contextParameters.entrySet()) { jg.writeStringField(parameter.getKey(), parameter.getValue()); } } jg.writeEndObject(); jg.flush(); } @Override public void writeDocument(OutputStream out, DocumentModel doc, String[] schemas, Map<String, String> contextParameters) throws Exception { writeDoc(factory.createJsonGenerator(out, JsonEncoding.UTF8), doc, schemas, contextParameters, headers); } public static void writeESDocument(JsonGenerator jg, DocumentModel doc, String[] schemas, Map<String, String> contextParameters) throws Exception { writeDoc(jg, doc, schemas, contextParameters, null); } }
nuxeo-automation/nuxeo-automation-io/src/main/java/org/nuxeo/ecm/automation/jaxrs/io/documents/JsonESDocumentWriter.java
package org.nuxeo.ecm.automation.jaxrs.io.documents; import static org.nuxeo.ecm.core.api.security.SecurityConstants.BROWSE; import static org.nuxeo.ecm.core.api.security.SecurityConstants.EVERYONE; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.ws.rs.Produces; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.ext.Provider; import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonGenerator; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.security.ACE; import org.nuxeo.ecm.core.api.security.ACL; import org.nuxeo.ecm.core.api.security.ACP; import org.nuxeo.ecm.core.security.SecurityService; import org.nuxeo.ecm.platform.tag.Tag; import org.nuxeo.ecm.platform.tag.TagService; import org.nuxeo.runtime.api.Framework; /** * JSon writer that outputs a format ready to eat by elasticsearch. * * * @since 5.9.3 */ @Provider @Produces({ JsonESDocumentWriter.MIME_TYPE }) public class JsonESDocumentWriter extends JsonDocumentWriter { public static final String MIME_TYPE = "application/json+esentity"; @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return super.isWriteable(type, genericType, annotations, mediaType) && MIME_TYPE.equals(mediaType.toString()); } public static void writeDoc(JsonGenerator jg, DocumentModel doc, String[] schemas, Map<String, String> contextParameters, HttpHeaders headers) throws Exception { jg.writeStartObject(); jg.writeStringField("ecm:repository", doc.getRepositoryName()); jg.writeStringField("ecm:uuid", doc.getId()); jg.writeStringField("ecm:name", doc.getName()); jg.writeStringField("ecm:title", doc.getTitle()); jg.writeStringField("ecm:path", doc.getPathAsString()); jg.writeStringField("ecm:primarytype", doc.getType()); jg.writeStringField("ecm:parentId", doc.getParentRef().toString()); jg.writeStringField("ecm:currentLifeCycleState", doc.getCurrentLifeCycleState()); jg.writeStringField("ecm:versionLabel", doc.getVersionLabel()); jg.writeBooleanField("ecm:isCheckedIn", !doc.isCheckedOut()); jg.writeBooleanField("ecm:isProxy", doc.isProxy()); jg.writeBooleanField("ecm:isVersion", doc.isVersion()); jg.writeArrayFieldStart("ecm:mixinType"); for (String facet : doc.getFacets()) { jg.writeString(facet); } jg.writeEndArray(); TagService tagService = Framework.getService(TagService.class); if (tagService != null) { jg.writeArrayFieldStart("ecm:tag"); for (Tag tag : tagService.getDocumentTags(doc.getCoreSession(), doc.getId(), null)) { jg.writeString(tag.getLabel()); } jg.writeEndArray(); } jg.writeStringField("ecm:changeToken", doc.getChangeToken()); // Add a positive ACL only SecurityService securityService = Framework.getService(SecurityService.class); List<String> browsePermissions = new ArrayList<String>( Arrays.asList(securityService.getPermissionsToCheck(BROWSE))); ACP acp = doc.getACP(); ACL acl = acp.getACL(ACL.INHERITED_ACL); if (acl==null) { // blocked inheritance at this level acl = acp.getACL(ACL.LOCAL_ACL); } jg.writeArrayFieldStart("ecm:acl"); for (ACE ace : acl.getACEs()) { if (ace.isGranted() && browsePermissions.contains(ace.getPermission())) { jg.writeString(ace.getUsername()); } if (ace.isDenied()) { if (!EVERYONE.equals(ace.getUsername())) { jg.writeString("UNSUPPORTED_DENIED_ACL"); } break; } } jg.writeEndArray(); // TODO Add binary fulltext if (schemas == null || (schemas.length == 1 && "*".equals(schemas[0]))) { schemas = doc.getSchemas(); } for (String schema : schemas) { writeProperties(jg, doc, schema, null); } if (contextParameters != null && !contextParameters.isEmpty()) { for (Map.Entry<String, String> parameter : contextParameters.entrySet()) { jg.writeStringField(parameter.getKey(), parameter.getValue()); } } jg.writeEndObject(); jg.flush(); } @Override public void writeDocument(OutputStream out, DocumentModel doc, String[] schemas, Map<String, String> contextParameters) throws Exception { writeDoc(factory.createJsonGenerator(out, JsonEncoding.UTF8), doc, schemas, contextParameters, headers); } public static void writeESDocument(JsonGenerator jg, DocumentModel doc, String[] schemas, Map<String, String> contextParameters) throws Exception { writeDoc(jg, doc, schemas, contextParameters, null); } }
NXP-14009 fix typo in primaryType
nuxeo-automation/nuxeo-automation-io/src/main/java/org/nuxeo/ecm/automation/jaxrs/io/documents/JsonESDocumentWriter.java
NXP-14009 fix typo in primaryType
<ide><path>uxeo-automation/nuxeo-automation-io/src/main/java/org/nuxeo/ecm/automation/jaxrs/io/documents/JsonESDocumentWriter.java <ide> jg.writeStringField("ecm:name", doc.getName()); <ide> jg.writeStringField("ecm:title", doc.getTitle()); <ide> jg.writeStringField("ecm:path", doc.getPathAsString()); <del> jg.writeStringField("ecm:primarytype", doc.getType()); <add> jg.writeStringField("ecm:primaryType", doc.getType()); <ide> jg.writeStringField("ecm:parentId", doc.getParentRef().toString()); <ide> jg.writeStringField("ecm:currentLifeCycleState", <ide> doc.getCurrentLifeCycleState());
JavaScript
mit
72b3cd76048e90fb71b6528af716f171b7340820
0
seznam/IMA.js-core,seznam/IMA.js-core
let gulp = require('gulp'); let babel = require('gulp-babel'); let plumber = require('gulp-plumber'); let sourcemaps = require('gulp-sourcemaps'); let tap = require('gulp-tap'); gulp.task('ima:compile', () => { return ( gulp .src([ __dirname + '/main.js', __dirname + '/namespace.js', __dirname + '/Bootstrap.js', __dirname + '/ObjectContainer.js', __dirname + '/!(node_modules)/**/!(*Spec).js' ]) .pipe(plumber()) .pipe(sourcemaps.init()) .pipe(babel({ moduleIds: true, presets: ['es2015'], plugins: ['external-helpers-2'] })) .pipe(plumber.stop()) .pipe(tap((file) => { let moduleName = 'ima' + file.path.slice(__dirname.length, -3); let fileContents = file.contents.toString(); let dependencyMatcher = /require\(['"]([^'"]+)['"]\)/g; let dependencies = []; let match = dependencyMatcher.exec(fileContents); while (match) { dependencies.push(match[1]); match = dependencyMatcher.exec(fileContents); } let exportMatcher = /\nexports\.([a-zA-Z_][a-zA-Z_1-9]*)\s*=\s*([^;]+);/g; let moduleExports = []; match = exportMatcher.exec(fileContents); while (match) { moduleExports.push({ symbol: match[1], value: match[2] }); match = exportMatcher.exec(fileContents); } file.contents = new Buffer( fileContents + '\n\n' + `$IMA.Loader.register('${moduleName}', [${dependencies.map(dependency => `'${dependency}'`).join(', ')}], function (_export, _context) {\n` + ` 'use strict';\n` + ` return {\n` + ` setters: [${dependencies.map(() => 'function () {}').join(', ')}],\n` + ` execute: function () {\n` + moduleExports.map(({ symbol, value }) => ` _export('${symbol}', exports.${symbol});\n`).join('') + ` }\n` + ` };\n` + `});\n` ); })) .pipe(sourcemaps.write()) .pipe(gulp.dest('.')) ); });
gulpfile.js
let gulp = require('gulp'); let babel = require('gulp-babel'); let plumber = require('gulp-plumber'); let sourcemaps = require('gulp-sourcemaps'); let tap = require('gulp-tap'); gulp.task('ima:compile', () => { return ( gulp .src([ __dirname + '/main.js', __dirname + '/namespace.js', __dirname + '/ObjectContainer.js', __dirname + '/!(node_modules)/**/!(*Spec).js' ]) .pipe(plumber()) .pipe(sourcemaps.init()) .pipe(babel({ moduleIds: true, presets: ['es2015'], plugins: ['external-helpers-2'] })) .pipe(plumber.stop()) .pipe(tap((file) => { let moduleName = 'ima' + file.path.slice(__dirname.length, -3); let fileContents = file.contents.toString(); let dependencyMatcher = /require\(['"]([^'"]+)['"]\)/g; let dependencies = []; let match = dependencyMatcher.exec(fileContents); while (match) { dependencies.push(match[1]); match = dependencyMatcher.exec(fileContents); } let exportMatcher = /\nexports\.([a-zA-Z_][a-zA-Z_1-9]*)\s*=\s*([^;]+);/g; let moduleExports = []; match = exportMatcher.exec(fileContents); while (match) { moduleExports.push({ symbol: match[1], value: match[2] }); match = exportMatcher.exec(fileContents); } file.contents = new Buffer( fileContents + '\n\n' + `$IMA.Loader.register('${moduleName}', [${dependencies.map(dependency => `'${dependency}'`).join(', ')}], function (_export, _context) {\n` + ` 'use strict';\n` + ` return {\n` + ` setters: [${dependencies.map(() => 'function () {}').join(', ')}],\n` + ` execute: function () {\n` + moduleExports.map(({ symbol, value }) => ` _export('${symbol}', exports.${symbol});\n`).join('') + ` }\n` + ` };\n` + `});\n` ); })) .pipe(sourcemaps.write()) .pipe(gulp.dest('.')) ); });
added Boostrap.js to the compiled files
gulpfile.js
added Boostrap.js to the compiled files
<ide><path>ulpfile.js <ide> .src([ <ide> __dirname + '/main.js', <ide> __dirname + '/namespace.js', <add> __dirname + '/Bootstrap.js', <ide> __dirname + '/ObjectContainer.js', <ide> __dirname + '/!(node_modules)/**/!(*Spec).js' <ide> ])
Java
lgpl-2.1
4dae1cadf569becae2be6a4868a3d7b47d6e2743
0
rhusar/wildfly,99sono/wildfly,golovnin/wildfly,pferraro/wildfly,wildfly/wildfly,tadamski/wildfly,iweiss/wildfly,xasx/wildfly,tomazzupan/wildfly,pferraro/wildfly,wildfly/wildfly,iweiss/wildfly,xasx/wildfly,rhusar/wildfly,99sono/wildfly,wildfly/wildfly,xasx/wildfly,pferraro/wildfly,golovnin/wildfly,jstourac/wildfly,99sono/wildfly,iweiss/wildfly,jstourac/wildfly,pferraro/wildfly,tadamski/wildfly,rhusar/wildfly,jstourac/wildfly,wildfly/wildfly,tadamski/wildfly,tomazzupan/wildfly,tomazzupan/wildfly,golovnin/wildfly,iweiss/wildfly,rhusar/wildfly,jstourac/wildfly
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.messaging.activemq.jms; import static org.jboss.as.server.Services.addServerExecutorDependency; import static org.jboss.msc.service.ServiceController.Mode.ACTIVE; import static org.jboss.msc.service.ServiceController.Mode.REMOVE; import static org.jboss.msc.service.ServiceController.State.REMOVED; import static org.jboss.msc.service.ServiceController.State.STOPPING; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import org.apache.activemq.artemis.core.security.ActiveMQPrincipal; import org.apache.activemq.artemis.core.server.ActivateCallback; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.jms.server.JMSServerManager; import org.apache.activemq.artemis.jms.server.impl.JMSServerManagerImpl; import org.jboss.msc.service.AbstractServiceListener; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceContainer; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceController.Mode; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.jboss.msc.value.InjectedValue; import org.wildfly.extension.messaging.activemq.ActiveMQActivationService; import org.wildfly.extension.messaging.activemq.DefaultCredentials; import org.wildfly.extension.messaging.activemq.MessagingServices; import org.wildfly.extension.messaging.activemq.logging.MessagingLogger; import org.wildfly.security.manager.WildFlySecurityManager; /** * The {@code JMSServerManager} service. * * @author Emanuel Muckenhuber */ public class JMSService implements Service<JMSServerManager> { private final InjectedValue<ActiveMQServer> activeMQServer = new InjectedValue<>(); private final InjectedValue<ExecutorService> serverExecutor = new InjectedValue<>(); private final ServiceName serverServiceName; private final boolean overrideInVMSecurity; private JMSServerManager jmsServer; public static ServiceController<JMSServerManager> addService(final ServiceTarget target, ServiceName serverServiceName, boolean overrideInVMSecurity) { final JMSService service = new JMSService(serverServiceName, overrideInVMSecurity); ServiceBuilder<JMSServerManager> builder = target.addService(JMSServices.getJmsManagerBaseServiceName(serverServiceName), service) .addDependency(serverServiceName, ActiveMQServer.class, service.activeMQServer) .addDependency(MessagingServices.ACTIVEMQ_CLIENT_THREAD_POOL) .setInitialMode(Mode.ACTIVE); addServerExecutorDependency(builder, service.serverExecutor); return builder.install(); } protected JMSService(ServiceName serverServiceName, boolean overrideInVMSecurity) { this.serverServiceName = serverServiceName; this.overrideInVMSecurity = overrideInVMSecurity; } public synchronized JMSServerManager getValue() throws IllegalStateException { if (jmsServer == null) { throw new IllegalStateException(); } return jmsServer; } @Override public void start(final StartContext context) throws StartException { final Runnable task = new Runnable() { @Override public void run() { try { doStart(context); context.complete(); } catch (StartException e) { context.failed(e); } } }; try { serverExecutor.getValue().submit(task); } catch (RejectedExecutionException e) { task.run(); } finally { context.asynchronous(); } } @Override public void stop(final StopContext context) { final Runnable task = new Runnable() { @Override public void run() { doStop(context); context.complete(); } }; try { serverExecutor.getValue().submit(task); } catch (RejectedExecutionException e) { task.run(); } finally { context.asynchronous(); } } private synchronized void doStart(final StartContext context) throws StartException { final ServiceContainer serviceContainer = context.getController().getServiceContainer(); ClassLoader oldTccl = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(getClass()); try { jmsServer = new JMSServerManagerImpl(activeMQServer.getValue(), new WildFlyBindingRegistry(context.getController().getServiceContainer())); activeMQServer.getValue().registerActivationFailureListener(e -> { StartException se = new StartException(e); context.failed(se); }); activeMQServer.getValue().registerActivateCallback(new ActivateCallback() { private volatile ServiceController<Void> activeMQActivationController; public void preActivate() { } public void activated() { if (overrideInVMSecurity) { activeMQServer.getValue().getRemotingService().allowInvmSecurityOverride(new ActiveMQPrincipal(DefaultCredentials.getUsername(), DefaultCredentials.getPassword())); } // ActiveMQ only provides a callback to be notified when ActiveMQ core server is activated. // but the JMS service start must not be completed until the JMSServerManager wrappee is indeed started (and has deployed the JMS resources, etc.). // It is possible that the activation service has already been installed but becomes passive when a backup server has failed over (-> ACTIVE) and failed back (-> PASSIVE) // [WFLY-6178] check if the service container is shutdown to avoid an IllegalStateException if an // ActiveMQ backup server is activated during failover while the WildFly server is shutting down. if (serviceContainer.isShutdown()) { return; } if (activeMQActivationController == null) { activeMQActivationController = serviceContainer.addService(ActiveMQActivationService.getServiceName(serverServiceName), new ActiveMQActivationService()) .setInitialMode(Mode.ACTIVE) .install(); } else { activeMQActivationController.setMode(ACTIVE); } } @Override public void activationComplete() { } public void deActivate() { // passivate the activation service only if the ActiveMQ server is deactivated when it fails back // and *not* during AS7 service container shutdown or reload (AS7-6840 / AS7-6881) if (activeMQActivationController != null) { if (!activeMQActivationController.getState().in(STOPPING, REMOVED)) { // [WFLY-4597] When Artemis is deactivated during failover, we block until its // activation controller is REMOVED before giving back control to Artemis. // This allow to properly stop any service depending on the activation controller // and avoid spurious warning messages because the resources used by the services // are stopped outside the control of the services. final CountDownLatch latch = new CountDownLatch(1); activeMQActivationController.compareAndSetMode(ACTIVE, REMOVE); activeMQActivationController.addListener(new AbstractServiceListener<Void>() { @Override public void transition(ServiceController<? extends Void> controller, ServiceController.Transition transition) { if (transition.enters(REMOVED)) { latch.countDown(); } } }); try { latch.await(5, TimeUnit.SECONDS); } catch (InterruptedException e) { } activeMQActivationController = null; } } } }); jmsServer.start(); } catch(StartException e){ throw e; } catch (Throwable t) { throw new StartException(t); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl); } } private synchronized void doStop(StopContext context) { try { jmsServer.stop(); jmsServer = null; } catch (Exception e) { MessagingLogger.ROOT_LOGGER.errorStoppingJmsServer(e); } } }
messaging-activemq/src/main/java/org/wildfly/extension/messaging/activemq/jms/JMSService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.messaging.activemq.jms; import static org.jboss.as.server.Services.addServerExecutorDependency; import static org.jboss.msc.service.ServiceController.Mode.ACTIVE; import static org.jboss.msc.service.ServiceController.Mode.REMOVE; import static org.jboss.msc.service.ServiceController.State.REMOVED; import static org.jboss.msc.service.ServiceController.State.STOPPING; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import org.apache.activemq.artemis.core.security.ActiveMQPrincipal; import org.apache.activemq.artemis.core.server.ActivateCallback; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.jms.server.JMSServerManager; import org.apache.activemq.artemis.jms.server.impl.JMSServerManagerImpl; import org.jboss.msc.service.AbstractServiceListener; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceContainer; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceController.Mode; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.jboss.msc.value.InjectedValue; import org.wildfly.extension.messaging.activemq.ActiveMQActivationService; import org.wildfly.extension.messaging.activemq.DefaultCredentials; import org.wildfly.extension.messaging.activemq.logging.MessagingLogger; import org.wildfly.security.manager.WildFlySecurityManager; /** * The {@code JMSServerManager} service. * * @author Emanuel Muckenhuber */ public class JMSService implements Service<JMSServerManager> { private final InjectedValue<ActiveMQServer> activeMQServer = new InjectedValue<>(); private final InjectedValue<ExecutorService> serverExecutor = new InjectedValue<>(); private final ServiceName serverServiceName; private final boolean overrideInVMSecurity; private JMSServerManager jmsServer; public static ServiceController<JMSServerManager> addService(final ServiceTarget target, ServiceName serverServiceName, boolean overrideInVMSecurity) { final JMSService service = new JMSService(serverServiceName, overrideInVMSecurity); ServiceBuilder<JMSServerManager> builder = target.addService(JMSServices.getJmsManagerBaseServiceName(serverServiceName), service) .addDependency(serverServiceName, ActiveMQServer.class, service.activeMQServer) .setInitialMode(Mode.ACTIVE); addServerExecutorDependency(builder, service.serverExecutor); return builder.install(); } protected JMSService(ServiceName serverServiceName, boolean overrideInVMSecurity) { this.serverServiceName = serverServiceName; this.overrideInVMSecurity = overrideInVMSecurity; } public synchronized JMSServerManager getValue() throws IllegalStateException { if (jmsServer == null) { throw new IllegalStateException(); } return jmsServer; } @Override public void start(final StartContext context) throws StartException { final Runnable task = new Runnable() { @Override public void run() { try { doStart(context); context.complete(); } catch (StartException e) { context.failed(e); } } }; try { serverExecutor.getValue().submit(task); } catch (RejectedExecutionException e) { task.run(); } finally { context.asynchronous(); } } @Override public void stop(final StopContext context) { final Runnable task = new Runnable() { @Override public void run() { doStop(context); context.complete(); } }; try { serverExecutor.getValue().submit(task); } catch (RejectedExecutionException e) { task.run(); } finally { context.asynchronous(); } } private synchronized void doStart(final StartContext context) throws StartException { final ServiceContainer serviceContainer = context.getController().getServiceContainer(); ClassLoader oldTccl = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(getClass()); try { jmsServer = new JMSServerManagerImpl(activeMQServer.getValue(), new WildFlyBindingRegistry(context.getController().getServiceContainer())); activeMQServer.getValue().registerActivationFailureListener(e -> { StartException se = new StartException(e); context.failed(se); }); activeMQServer.getValue().registerActivateCallback(new ActivateCallback() { private volatile ServiceController<Void> activeMQActivationController; public void preActivate() { } public void activated() { if (overrideInVMSecurity) { activeMQServer.getValue().getRemotingService().allowInvmSecurityOverride(new ActiveMQPrincipal(DefaultCredentials.getUsername(), DefaultCredentials.getPassword())); } // ActiveMQ only provides a callback to be notified when ActiveMQ core server is activated. // but the JMS service start must not be completed until the JMSServerManager wrappee is indeed started (and has deployed the JMS resources, etc.). // It is possible that the activation service has already been installed but becomes passive when a backup server has failed over (-> ACTIVE) and failed back (-> PASSIVE) // [WFLY-6178] check if the service container is shutdown to avoid an IllegalStateException if an // ActiveMQ backup server is activated during failover while the WildFly server is shutting down. if (serviceContainer.isShutdown()) { return; } if (activeMQActivationController == null) { activeMQActivationController = serviceContainer.addService(ActiveMQActivationService.getServiceName(serverServiceName), new ActiveMQActivationService()) .setInitialMode(Mode.ACTIVE) .install(); } else { activeMQActivationController.setMode(ACTIVE); } } @Override public void activationComplete() { } public void deActivate() { // passivate the activation service only if the ActiveMQ server is deactivated when it fails back // and *not* during AS7 service container shutdown or reload (AS7-6840 / AS7-6881) if (activeMQActivationController != null) { if (!activeMQActivationController.getState().in(STOPPING, REMOVED)) { // [WFLY-4597] When Artemis is deactivated during failover, we block until its // activation controller is REMOVED before giving back control to Artemis. // This allow to properly stop any service depending on the activation controller // and avoid spurious warning messages because the resources used by the services // are stopped outside the control of the services. final CountDownLatch latch = new CountDownLatch(1); activeMQActivationController.compareAndSetMode(ACTIVE, REMOVE); activeMQActivationController.addListener(new AbstractServiceListener<Void>() { @Override public void transition(ServiceController<? extends Void> controller, ServiceController.Transition transition) { if (transition.enters(REMOVED)) { latch.countDown(); } } }); try { latch.await(5, TimeUnit.SECONDS); } catch (InterruptedException e) { } activeMQActivationController = null; } } } }); jmsServer.start(); } catch(StartException e){ throw e; } catch (Throwable t) { throw new StartException(t); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl); } } private synchronized void doStop(StopContext context) { try { jmsServer.stop(); jmsServer = null; } catch (Exception e) { MessagingLogger.ROOT_LOGGER.errorStoppingJmsServer(e); } } }
[WFLY-8746] RejectedExecutionException in the MDB during shutdown Add a dependency from the JMS server service to the Artemis client thread pools to ensure that the thread pools are cleaned up after the JMS servers are stopped. JIRA: https://issues.jboss.org/browse/WFLY-8746
messaging-activemq/src/main/java/org/wildfly/extension/messaging/activemq/jms/JMSService.java
[WFLY-8746] RejectedExecutionException in the MDB during shutdown
<ide><path>essaging-activemq/src/main/java/org/wildfly/extension/messaging/activemq/jms/JMSService.java <ide> import org.jboss.msc.value.InjectedValue; <ide> import org.wildfly.extension.messaging.activemq.ActiveMQActivationService; <ide> import org.wildfly.extension.messaging.activemq.DefaultCredentials; <add>import org.wildfly.extension.messaging.activemq.MessagingServices; <ide> import org.wildfly.extension.messaging.activemq.logging.MessagingLogger; <ide> import org.wildfly.security.manager.WildFlySecurityManager; <ide> <ide> final JMSService service = new JMSService(serverServiceName, overrideInVMSecurity); <ide> ServiceBuilder<JMSServerManager> builder = target.addService(JMSServices.getJmsManagerBaseServiceName(serverServiceName), service) <ide> .addDependency(serverServiceName, ActiveMQServer.class, service.activeMQServer) <add> .addDependency(MessagingServices.ACTIVEMQ_CLIENT_THREAD_POOL) <ide> .setInitialMode(Mode.ACTIVE); <ide> addServerExecutorDependency(builder, service.serverExecutor); <ide> return builder.install();
Java
apache-2.0
e815567d6834ffcbae920c4be5128b8f3ca2060f
0
reinert/requestor,reinert/requestor,reinert/requestor
/* * Copyright 2022 Danilo Reinert * * 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. */ package io.reinert.requestor.core; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; class StoreManager implements Store { private final Store owner; private final boolean concurrent; private final AsyncRunner asyncRunner; private Map<String, Data> dataMap; private Map<String, Set<Handler>> savedHandlers; private Map<String, Set<Handler>> removedHandlers; private Map<String, Set<Handler>> expiredHandlers; public StoreManager(Store owner, boolean concurrent, AsyncRunner asyncRunner) { this.owner = owner; this.concurrent = concurrent; this.asyncRunner = asyncRunner; } StoreManager copy(Store owner) { final StoreManager copy = new StoreManager(owner, concurrent, asyncRunner); if (dataMap != null) { copy.dataMap = concurrent ? new ConcurrentHashMap<String, Data>(dataMap) : new HashMap<String, Data>(dataMap); } if (savedHandlers != null) { copy.savedHandlers = concurrent ? new ConcurrentHashMap<String, Set<Handler>>(savedHandlers) : new HashMap<String, Set<Handler>>(savedHandlers); } if (removedHandlers != null) { copy.removedHandlers = concurrent ? new ConcurrentHashMap<String, Set<Handler>>(removedHandlers) : new HashMap<String, Set<Handler>>(removedHandlers); } if (expiredHandlers != null) { copy.expiredHandlers = concurrent ? new ConcurrentHashMap<String, Set<Handler>>(expiredHandlers) : new HashMap<String, Set<Handler>>(expiredHandlers); } return copy; } public boolean isConcurrent() { return concurrent; } @SuppressWarnings("unchecked") @Override public <T> T retrieve(String key) { checkNotNull(key, "The key argument cannot be null"); if (dataMap == null) return null; final Data data = dataMap.get(key); if (data == null) return null; return (T) data.getValue(); } @Override public Store save(String key, Object value) { return save(key, value, 0L); } @Override public Store save(String key, Object value, Level level) { throw new UnsupportedOperationException(); } @Override public Store save(String key, Object value, long ttl, Level level) { throw new UnsupportedOperationException(); } @Override public Store save(final String key, Object value, long ttl) { checkNotNull(key, "The key argument cannot be null"); checkNotNull(value, "The value argument cannot be null"); Data removedData = ensureDataMap().remove(key); Data savedData = new Data(key, value, ttl); final long createdAt = savedData.getCreatedAt(); dataMap.put(key, savedData); if (ttl > 0L) { asyncRunner.run(new Runnable() { public void run() { Data data = dataMap.get(key); if (data != null && data.getCreatedAt() == createdAt) { if (!exists(Store.REMOVE_ON_EXPIRED_DISABLED, Boolean.TRUE)) { dataMap.remove(key); triggerRemovedHandlers(key, data); } triggerExpiredHandlers(key, data); } } }, ttl); } triggerSavedHandlers(key, removedData, savedData); return null; } @Override public boolean exists(String key) { checkNotNull(key, "The key argument cannot be null"); return dataMap != null && dataMap.containsKey(key); } @Override public boolean exists(String key, Object value) { checkNotNull(key, "The key argument cannot be null"); checkNotNull(value, "The value argument cannot be null. Try the exists method instead."); Data retrieved = dataMap == null ? null : dataMap.get(key); return retrieved != null && (retrieved.getValue() == value || retrieved.getValue().equals(value)); } @Override public Data remove(String key) { checkNotNull(key, "The key argument cannot be null"); if (dataMap != null) { Data removedData = dataMap.remove(key); if (removedData != null) { triggerRemovedHandlers(key, removedData); return removedData; } } return null; } @Override public void clear() { clear(true); } @Override public void clear(boolean fireRemovedEvent) { if (dataMap != null) { if (fireRemovedEvent) { List<Data> values = new ArrayList<Data>(dataMap.values()); dataMap.clear(); for (Data data : values) { triggerRemovedHandlers(data.getKey(), data); } return; } dataMap.clear(); } } @Override public Store onSaved(String key, Handler handler) { addHandler(key, handler, ensureSavedHandlers()); return null; } @Override public Store onRemoved(String key, Handler handler) { addHandler(key, handler, ensureRemovedHandlers()); return null; } @Override public Store onExpired(String key, Handler handler) { addHandler(key, handler, ensureExpiredHandlers()); return null; } private synchronized void addHandler(String key, Handler handler, Map<String, Set<Handler>> handlersMap) { Set<Handler> handlers = handlersMap.get(key); if (handlers == null) { handlers = new HashSet<Handler>(); handlersMap.put(key, handlers); } handlers.add(handler); } private void triggerSavedHandlers(String key, Data removedData, Data savedData) { triggerHandlers(savedHandlers, key, removedData, savedData); } private void triggerRemovedHandlers(String key, Data removedData) { triggerHandlers(removedHandlers, key, removedData, null); } private void triggerExpiredHandlers(String key, Data expiredData) { triggerHandlers(expiredHandlers, key, expiredData, null); } private void triggerHandlers(Map<String, Set<Handler>> handlersMap, String key, Data oldData, Data newData) { if (handlersMap == null) return; final Set<Handler> handlers = handlersMap.get(key); if (handlers == null) return; final Event.Impl event = new Event.Impl(owner, key, oldData, newData); final Iterator<Handler> it = handlers.iterator(); // Should we run the handlers asynchronously? while (it.hasNext()) { Handler handler = it.next(); if (handler.isCanceled()) { it.remove(); continue; } handler.execute(event); } } private void checkNotNull(Object arg, String msg) { if (arg == null) throw new IllegalArgumentException(msg); } private Map<String, Data> ensureDataMap() { if (dataMap == null) { dataMap = concurrent ? new ConcurrentHashMap<String, Data>() : new HashMap<String, Data>(); } return dataMap; } private Map<String, Set<Handler>> ensureSavedHandlers() { if (savedHandlers == null) { savedHandlers = concurrent ? new ConcurrentHashMap<String, Set<Handler>>() : new HashMap<String, Set<Handler>>(); } return savedHandlers; } private Map<String, Set<Handler>> ensureRemovedHandlers() { if (removedHandlers == null) { removedHandlers = concurrent ? new ConcurrentHashMap<String, Set<Handler>>() : new HashMap<String, Set<Handler>>(); } return removedHandlers; } private Map<String, Set<Handler>> ensureExpiredHandlers() { if (expiredHandlers == null) { expiredHandlers = concurrent ? new ConcurrentHashMap<String, Set<Handler>>() : new HashMap<String, Set<Handler>>(); } return expiredHandlers; } }
requestor/core/requestor-core/src/main/java/io/reinert/requestor/core/StoreManager.java
/* * Copyright 2022 Danilo Reinert * * 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. */ package io.reinert.requestor.core; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; class StoreManager implements Store { private final Store owner; private final boolean concurrent; private final AsyncRunner asyncRunner; private Map<String, Data> dataMap; private Map<String, Set<Handler>> savedHandlers; private Map<String, Set<Handler>> removedHandlers; private Map<String, Set<Handler>> expiredHandlers; public StoreManager(Store owner, boolean concurrent, AsyncRunner asyncRunner) { this.owner = owner; this.concurrent = concurrent; this.asyncRunner = asyncRunner; } StoreManager copy(Store owner) { final StoreManager copy = new StoreManager(owner, concurrent, asyncRunner); if (dataMap != null) { copy.dataMap = concurrent ? new ConcurrentHashMap<String, Data>(dataMap) : new HashMap<String, Data>(dataMap); } if (savedHandlers != null) { copy.savedHandlers = concurrent ? new ConcurrentHashMap<String, Set<Handler>>(savedHandlers) : new HashMap<String, Set<Handler>>(savedHandlers); } if (removedHandlers != null) { copy.removedHandlers = concurrent ? new ConcurrentHashMap<String, Set<Handler>>(removedHandlers) : new HashMap<String, Set<Handler>>(removedHandlers); } if (expiredHandlers != null) { copy.expiredHandlers = concurrent ? new ConcurrentHashMap<String, Set<Handler>>(expiredHandlers) : new HashMap<String, Set<Handler>>(expiredHandlers); } return copy; } public boolean isConcurrent() { return concurrent; } @SuppressWarnings("unchecked") @Override public <T> T retrieve(String key) { checkNotNull(key, "The key argument cannot be null"); if (dataMap == null) return null; final Data data = dataMap.get(key); if (data == null || data.isExpired()) return null; return (T) data.getValue(); } @Override public Store save(String key, Object value) { return save(key, value, 0L); } @Override public Store save(String key, Object value, Level level) { throw new UnsupportedOperationException(); } @Override public Store save(String key, Object value, long ttl, Level level) { throw new UnsupportedOperationException(); } @Override public Store save(final String key, Object value, long ttl) { checkNotNull(key, "The key argument cannot be null"); checkNotNull(value, "The value argument cannot be null"); Data removedData = ensureDataMap().remove(key); Data savedData = new Data(key, value, ttl); final long createdAt = savedData.getCreatedAt(); dataMap.put(key, savedData); if (ttl > 0L) { asyncRunner.run(new Runnable() { public void run() { Data data = dataMap.get(key); if (data != null && data.getCreatedAt() == createdAt) { if (!exists(Store.REMOVE_ON_EXPIRED_DISABLED, Boolean.TRUE)) { dataMap.remove(key); triggerRemovedHandlers(key, data); } triggerExpiredHandlers(key, data); } } }, ttl); } triggerSavedHandlers(key, removedData, savedData); return null; } @Override public boolean exists(String key) { checkNotNull(key, "The key argument cannot be null"); return dataMap != null && dataMap.containsKey(key) && !dataMap.get(key).isExpired(); } @Override public boolean exists(String key, Object value) { checkNotNull(key, "The key argument cannot be null"); checkNotNull(value, "The value argument cannot be null. Try the exists method instead."); Data retrieved = dataMap == null ? null : dataMap.get(key); return retrieved != null && !retrieved.isExpired() && (retrieved.getValue() == value || retrieved.getValue().equals(value)); } @Override public Data remove(String key) { checkNotNull(key, "The key argument cannot be null"); if (dataMap != null) { Data removedData = dataMap.remove(key); if (removedData != null && !removedData.isExpired()) { triggerRemovedHandlers(key, removedData); return removedData; } } return null; } @Override public void clear() { clear(true); } @Override public void clear(boolean fireRemovedEvent) { if (dataMap != null) { if (fireRemovedEvent) { List<Data> values = new ArrayList<Data>(dataMap.values()); dataMap.clear(); for (Data data : values) { triggerRemovedHandlers(data.getKey(), data); } return; } dataMap.clear(); } } @Override public Store onSaved(String key, Handler handler) { addHandler(key, handler, ensureSavedHandlers()); return null; } @Override public Store onRemoved(String key, Handler handler) { addHandler(key, handler, ensureRemovedHandlers()); return null; } @Override public Store onExpired(String key, Handler handler) { addHandler(key, handler, ensureExpiredHandlers()); return null; } private synchronized void addHandler(String key, Handler handler, Map<String, Set<Handler>> handlersMap) { Set<Handler> handlers = handlersMap.get(key); if (handlers == null) { handlers = new HashSet<Handler>(); handlersMap.put(key, handlers); } handlers.add(handler); } private void triggerSavedHandlers(String key, Data removedData, Data savedData) { triggerHandlers(savedHandlers, key, removedData, savedData); } private void triggerRemovedHandlers(String key, Data removedData) { triggerHandlers(removedHandlers, key, removedData, null); } private void triggerExpiredHandlers(String key, Data expiredData) { triggerHandlers(expiredHandlers, key, expiredData, null); } private void triggerHandlers(Map<String, Set<Handler>> handlersMap, String key, Data oldData, Data newData) { if (handlersMap == null) return; final Set<Handler> handlers = handlersMap.get(key); if (handlers == null) return; final Event.Impl event = new Event.Impl(owner, key, oldData, newData); final Iterator<Handler> it = handlers.iterator(); // Should we run the handlers asynchronously? while (it.hasNext()) { Handler handler = it.next(); if (handler.isCanceled()) { it.remove(); continue; } handler.execute(event); } } private void checkNotNull(Object arg, String msg) { if (arg == null) throw new IllegalArgumentException(msg); } private Map<String, Data> ensureDataMap() { if (dataMap == null) { dataMap = concurrent ? new ConcurrentHashMap<String, Data>() : new HashMap<String, Data>(); } return dataMap; } private Map<String, Set<Handler>> ensureSavedHandlers() { if (savedHandlers == null) { savedHandlers = concurrent ? new ConcurrentHashMap<String, Set<Handler>>() : new HashMap<String, Set<Handler>>(); } return savedHandlers; } private Map<String, Set<Handler>> ensureRemovedHandlers() { if (removedHandlers == null) { removedHandlers = concurrent ? new ConcurrentHashMap<String, Set<Handler>>() : new HashMap<String, Set<Handler>>(); } return removedHandlers; } private Map<String, Set<Handler>> ensureExpiredHandlers() { if (expiredHandlers == null) { expiredHandlers = concurrent ? new ConcurrentHashMap<String, Set<Handler>>() : new HashMap<String, Set<Handler>>(); } return expiredHandlers; } }
#142 [core] Consider data in store available even if expired
requestor/core/requestor-core/src/main/java/io/reinert/requestor/core/StoreManager.java
#142 [core] Consider data in store available even if expired
<ide><path>equestor/core/requestor-core/src/main/java/io/reinert/requestor/core/StoreManager.java <ide> <ide> final Data data = dataMap.get(key); <ide> <del> if (data == null || data.isExpired()) return null; <add> if (data == null) return null; <ide> <ide> return (T) data.getValue(); <ide> } <ide> @Override <ide> public boolean exists(String key) { <ide> checkNotNull(key, "The key argument cannot be null"); <del> return dataMap != null && dataMap.containsKey(key) && !dataMap.get(key).isExpired(); <add> return dataMap != null && dataMap.containsKey(key); <ide> } <ide> <ide> @Override <ide> checkNotNull(value, "The value argument cannot be null. Try the exists method instead."); <ide> <ide> Data retrieved = dataMap == null ? null : dataMap.get(key); <del> return retrieved != null && !retrieved.isExpired() && <del> (retrieved.getValue() == value || retrieved.getValue().equals(value)); <add> return retrieved != null && (retrieved.getValue() == value || retrieved.getValue().equals(value)); <ide> } <ide> <ide> @Override <ide> if (dataMap != null) { <ide> Data removedData = dataMap.remove(key); <ide> <del> if (removedData != null && !removedData.isExpired()) { <add> if (removedData != null) { <ide> triggerRemovedHandlers(key, removedData); <ide> return removedData; <ide> }
JavaScript
mit
614820919dc2072ef886ce2ea07e0549e8d26883
0
team-kke/erichika
"use strict"; var error = require('debug')('error'); var generate = require('./base'); var room = require('../room'); var verbose = require('debug')('verbose:queue'); var TEAMSIZE = 6; var user = {}; var teams = { waitPlayer: [], waitConfirm: [] }; var queue = []; function Team() { verbose('Team() constructor called'); this.room = new room.Room(); this.members = []; this.confirmed = {}; } Team.prototype.push = function (username) { verbose('Team.push(%s)', username); var socket = user[username].socket; this.room.push(socket); this.members.push(username); user[username].team = this; this.confirmed[username] = false; }; Team.prototype.move = function (src, dest) { verbose('Team.move(%s, %s)', src, dest); var index = src.indexOf(this); if (index > -1) { src.splice(index, 1); if (dest) { dest.push(this); } } }; Team.prototype.removeUser = function (username) { verbose('Team.removeUser(%s)', username); var index = this.members.indexOf(username); if (index > -1) { this.members.splice(index, 1); this.room.remove(user[username].socket); user[username].team = null; delete this.confirmed[username]; } }; function updateClient(team, state) { var current; if (state === 'wait-player') { current = team.members.length; } else if (state === 'wait-confirmed') { current = Object.keys(team.confirmed) .map(function (k) { return team.confirmed[k]; }).filter(function (v) { return v; }).length; } else { error('queue/update, abnormal state); return; } verbose('emit queue/update, state: %s, current: %s', state, current); team.room.emit('queue/update', { state: state, current: current }); } function assignTeam() { verbose('assignTeam'); if (queue.length && teams.waitPlayer.length === 0) { verbose('no team waiting player. make a new one.'); teams.waitPlayer.push(new Team()); verbose('teams.waitPlayer.length = %s', teams.waitPlayer.length); } for (var i = 0; i < teams.waitPlayer.length && queue.length; i++) { var team = teams.waitPlayer[i]; var changed = false; while (team.members.length < TEAMSIZE && queue.length) { team.push(queue.shift()); changed = true; } // if any changes, emit queue/update(wait-player) to every team member if (changed) { verbose('player(s) assigned. broadcast wait-player'); updateClient(team, 'wait-player'); } if (team.members.length === TEAMSIZE) { verbose('team is full(%s). move this team to wait-confirm list', TEAMSIZE); // add this team to wait-confirm list team.move(teams.waitPlayer, teams.waitConfirm); // emit wait-confirm to every team member. updateClient(team, 'wait-confirm'); } } } function join() { verbose('queue/join, username: %s', this.socket.username); queue.push(this.socket.username); user[this.socket.username] = { socket: this.socket }; assignTeam(); } function exit() { var username = this.socket.username; verbose('queue/exit, username: %s', username); var team = user[username].team; var isWaitingPlayer = teams.waitPlayer.indexOf(team) > -1; var isWaitingConfirm = teams.waitConfirm.indexOf(team) > -1; if (isWaitingPlayer || isWaitingConfirm) { team.removeUser(username); if (isWaitingConfirm) { updateClient(team, 'wait-player'); team.move(teams.waitConfirm, teams.waitPlayer); } } else { error('queue/exit, abnormal state'); } } function confirm() { var username = this.socket.username; verbose('queue/confirm, username: %s', username); var team = user[username].team; if (teams.waitConfirm.indexOf(team) > -1) { error('queue/confirm, abnormal state'); return; } team.confirmed[username] = true; updateClient('wait-confirm'); // from now, client knows this confirm makes game start or not. var everyoneConfirmed = true; for (var u in team.confirmed) { if (!team.confirmed[u]) { verbose('queue/confirm, not everyone confirmed yet'); everyoneConfirmed = false; break; } } if (everyoneConfirmed) { verbose('queue/confirm, everyone confirmed! start a game'); team.move(teams.waitConfirm, null); // TODO: start game! } } function dodge() { } function disconnect() { var username = this.socket.username; verbose('disconnect. %s', username); var index = queue.indexOf(username); if (index > -1) { queue.splice(index, 1); } if (user[username]) { var team = user[username].team; if (team) { var isWaitingPlayer = teams.waitPlayer.indexOf(team) > -1; var isWaitingConfirm = teams.waitConfirm.indexOf(team) > -1; if (isWaitingPlayer || isWaitingConfirm) { team.removeUser(username); updateClient(team, 'wait-player'); if (isWaitingConfirm) { verbose('user disconnected was in the team waiting confirm.. this team goes waiting players again '); team.move(teams.waitConfirm, teams.waitPlayer); } } } } } module.exports = generate({ 'queue/join': { name: 'join', function: join }, 'queue/exit': { name: 'exit', function: exit }, 'queue/confirm': { name: 'confirm', function: confirm }, 'queue/dodge': { name: 'dodge', function: dodge }, 'disconnect': { name: 'disconnect', function: disconnect } });
backend/sockets/queue.js
"use strict"; var error = require('debug')('error'); var generate = require('./base'); var room = require('../room'); var verbose = require('debug')('verbose:queue'); var TEAMSIZE = 6; var user = {}; var teams = { waitPlayer: [], waitConfirm: [] }; var queue = []; function Team() { verbose('Team() constructor called'); this.room = new room.Room(); this.members = []; this.confirmed = {}; } Team.prototype.push = function (username) { verbose('Team.push(%s)', username); var socket = user[username].socket; this.room.push(socket); this.members.push(username); user[username].team = this; this.confirmed[username] = false; }; Team.prototype.move = function (src, dest) { verbose('Team.move(%s, %s)', src, dest); var index = src.indexOf(this); if (index > -1) { src.splice(index, 1); if (dest) { dest.push(this); } } }; Team.prototype.removeUser = function (username) { verbose('Team.removeUser(%s)', username); var index = this.members.indexOf(username); if (index > -1) { this.members.splice(index, 1); this.room.remove(user[username].socket); user[username].team = null; delete this.confirmed[username]; } }; function updateClient(team, state) { verbose('emit queue/update, state: %s, current: %s', state, team.members.length); team.room.emit('queue/update', { state: state, current: team.members.length }); } function assignTeam() { verbose('assignTeam'); if (queue.length && teams.waitPlayer.length === 0) { verbose('no team waiting player. make a new one.'); teams.waitPlayer.push(new Team()); verbose('teams.waitPlayer.length = %s', teams.waitPlayer.length); } for (var i = 0; i < teams.waitPlayer.length && queue.length; i++) { var team = teams.waitPlayer[i]; var changed = false; while (team.members.length < TEAMSIZE && queue.length) { team.push(queue.shift()); changed = true; } // if any changes, emit queue/update(wait-player) to every team member if (changed) { verbose('player(s) assigned. broadcast wait-player'); updateClient(team, 'wait-player'); } if (team.members.length === TEAMSIZE) { verbose('team is full(%s). move this team to wait-confirm list', TEAMSIZE); // add this team to wait-confirm list team.move(teams.waitPlayer, teams.waitConfirm); // emit wait-confirm to every team member. updateClient(team, 'wait-confirm'); } } } function join() { verbose('queue/join, username: %s', this.socket.username); queue.push(this.socket.username); user[this.socket.username] = { socket: this.socket }; assignTeam(); } function exit() { var username = this.socket.username; verbose('queue/exit, username: %s', username); var team = user[username].team; var isWaitingPlayer = teams.waitPlayer.indexOf(team) > -1; var isWaitingConfirm = teams.waitConfirm.indexOf(team) > -1; if (isWaitingPlayer || isWaitingConfirm) { team.removeUser(username); if (isWaitingConfirm) { updateClient(team, 'wait-player'); team.move(teams.waitConfirm, teams.waitPlayer); } } else { error('queue/exit, abnormal state'); } } function confirm() { var username = this.socket.username; verbose('queue/confirm, username: %s', username); var team = user[username].team; if (teams.waitConfirm.indexOf(team) > -1) { error('queue/confirm, abnormal state'); return; } team.confirmed[username] = true; updateClient('wait-confirm'); // from now, client knows this confirm makes game start or not. var everyoneConfirmed = true; for (var u in team.confirmed) { if (!team.confirmed[u]) { verbose('queue/confirm, not everyone confirmed yet'); everyoneConfirmed = false; break; } } if (everyoneConfirmed) { verbose('queue/confirm, everyone confirmed! start a game'); team.move(teams.waitConfirm, null); // TODO: start game! } } function dodge() { } function disconnect() { var username = this.socket.username; verbose('disconnect. %s', username); var index = queue.indexOf(username); if (index > -1) { queue.splice(index, 1); } if (user[username]) { var team = user[username].team; if (team) { var isWaitingPlayer = teams.waitPlayer.indexOf(team) > -1; var isWaitingConfirm = teams.waitConfirm.indexOf(team) > -1; if (isWaitingPlayer || isWaitingConfirm) { team.removeUser(username); updateClient(team, 'wait-player'); if (isWaitingConfirm) { verbose('user disconnected was in the team waiting confirm.. this team goes waiting players again '); team.move(teams.waitConfirm, teams.waitPlayer); } } } } } module.exports = generate({ 'queue/join': { name: 'join', function: join }, 'queue/exit': { name: 'exit', function: exit }, 'queue/confirm': { name: 'confirm', function: confirm }, 'queue/dodge': { name: 'dodge', function: dodge }, 'disconnect': { name: 'disconnect', function: disconnect } });
Fix 'current' value when state is 'wait-confirm'. Sorry
backend/sockets/queue.js
Fix 'current' value when state is 'wait-confirm'.
<ide><path>ackend/sockets/queue.js <ide> }; <ide> <ide> function updateClient(team, state) { <del> verbose('emit queue/update, state: %s, current: %s', state, team.members.length); <add> var current; <add> if (state === 'wait-player') { <add> current = team.members.length; <add> } else if (state === 'wait-confirmed') { <add> current = Object.keys(team.confirmed) <add> .map(function (k) { <add> return team.confirmed[k]; <add> }).filter(function (v) { <add> return v; <add> }).length; <add> } else { <add> error('queue/update, abnormal state); <add> return; <add> } <add> <add> verbose('emit queue/update, state: %s, current: %s', state, current); <ide> team.room.emit('queue/update', { <ide> state: state, <del> current: team.members.length <add> current: current <ide> }); <ide> } <ide>
Java
apache-2.0
421a300d8ba1af22bc64c61fef6cce266c3507de
0
williampma/relex,opencog/relex,linas/relex,ainishdave/relex,williampma/relex,ainishdave/relex,linas/relex,virneo/relex,AmeBel/relex,opencog/relex,anitzkin/relex,anitzkin/relex,rodsol/relex,ainishdave/relex,anitzkin/relex,rodsol/relex,leungmanhin/relex,anitzkin/relex,leungmanhin/relex,ainishdave/relex,rodsol/relex,anitzkin/relex,AmeBel/relex,williampma/relex,rodsol/relex,linas/relex,virneo/relex,opencog/relex,leungmanhin/relex,virneo/relex,AmeBel/relex,williampma/relex,virneo/relex
/* * Copyright 2009 Linas Vepstas * * 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. */ package relex.test; import java.util.ArrayList; import java.util.Collections; import relex.ParsedSentence; import relex.RelationExtractor; import relex.Sentence; import relex.output.SimpleView; public class TestRelEx { private RelationExtractor re; private int pass; private int fail; private int subpass; private int subfail; private static ArrayList<String> sentfail= new ArrayList<String>(); public TestRelEx() { re = new RelationExtractor(); pass = 0; fail = 0; subpass = 0; subfail = 0; } public ArrayList<String> split(String a) { String[] sa = a.split("\n"); ArrayList<String> saa = new ArrayList<String>(); for (String s : sa) { saa.add(s); } Collections.sort (saa); return saa; } /** * First argument is the sentence. * Second argument is a list of the relations that RelEx * should be generating. * Return true if RelEx generates the same dependencies * as the second argument. */ public boolean test_sentence (String sent, String sf) { re.do_penn_tagging = false; re.setMaxParses(1); Sentence sntc = re.processSentence(sent); ParsedSentence parse = sntc.getParses().get(0); String rs = SimpleView.printBinaryRelations(parse); String urs = SimpleView.printUnaryRelations(parse); ArrayList<String> exp = split(sf); ArrayList<String> brgot = split(rs); ArrayList<String> urgot = split(urs); //add number of binary relations from parser-output, to total number of relationships got int sizeOfGotRelations= brgot.size(); //check expected binary and unary relations //the below for-loop checks whether all expected binary relations are //contained in the parser-binary-relation-output arrayList "brgot". //if any unary relations are expected in the output it checks the //parser-unary-relation-output arrayList "urgot" for unary relationships for (int i=0; i< exp.size(); i++) { if(!brgot.contains((String)exp.get(i))) { if(!urgot.contains(exp.get(i))) { System.err.println("Error: content miscompare:\n" + "\tExpected = " + exp + "\n" + "\tGot Binary Relations = " + brgot + "\n" + "\tGot Unary Relations = " + urgot + "\n" + "\tSentence = " + sent); subfail ++; fail ++; sentfail.add(sent); return false; } //add the unary relation, count to totoal number of binary relations sizeOfGotRelations++; } } //The size checking of the expected relationships vs output relationships //is done here purposefully, to accommodate if there is any unary relationships present //in the expected output(see above for-loop also). //However it only checks whether parser-output resulted more relationships(binary+unary) than expected relations //If the parser-output resulted less relationships(binary+unary) than expected it would //catch that in the above for-loop if (exp.size() < sizeOfGotRelations) { System.err.println("Error: size miscompare:\n" + "\tExpected = " + exp + "\n" + "\tGot Binary Relations = " + brgot + "\n" + "\tGot Unary Relations = " + urgot + "\n" + "\tSentence = " + sent); subfail ++; fail ++; sentfail.add(sent); return false; } subpass ++; pass ++; return true; } public void report(boolean rc, String subsys) { if (rc) { System.err.println(subsys + ": Tested " + pass + " sentences, test passed OK"); } else { System.err.println(subsys + ": Test failed\n\t" + fail + " sentences failed\n\t" + pass + " sentences passed"); } subpass = 0; subfail = 0; } public boolean test_comparatives() { boolean rc = true; rc &= test_sentence ("Some people like pigs less than dogs.", "_advmod(like, less)\n" + "_obj(like, pig)\n" + "_quantity(people, some)\n" + "_subj(like, people)\n" + "than(pig, dog)\n"); rc &= test_sentence ("Some people like pigs more than dogs.", "_advmod(like, more)\n" + "_obj(like, pig)\n" + "_quantity(people, some)\n" + "_subj(like, people)\n" + "than(pig, dog)\n"); //Non-equal Gradable : Two entities one feature "more/less" rc &= test_sentence ("He is more intelligent than John.", "than(he, John)\n" + "more(intelligent, he)\n" + "degree(intelligent, comparative)\n"+ "_predadj(he, intelligent)\n"); rc &= test_sentence ("He is less intelligent than John.", "than(he, John)\n" + "_more(intelligent, he)\n" + "degree(intelligent, comparative)\n"+ "_advmod(intelligent, less)\n"+ "_predadj(he, intelligent)\n"); rc &= test_sentence ("He runs more quickly than John.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "than(he, John)\n" + "more(quickly, run)\n" + "degree(quickly, comparative)\n"); rc &= test_sentence ("He runs less quickly than John.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "_advmod(quickly, less)\n"+ "than(he, John)\n" + "_more(quickly, run)\n" + "degree(quickly, comparative)\n"); rc &= test_sentence ("He runs more quickly than John does.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "_subj(do, John)\n"+ "than(he, John)\n" + "more(quickly, run)\n" + "degree(quickly, comparative)\n"); rc &= test_sentence ("He runs less quickly than John does.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "_subj(do, John)\n"+ "_advmod(quickly, less)\n"+ "than(he, John)\n" + "_more(quickly, run)\n" + "degree(quickly, comparative)\n"); rc &= test_sentence ("He runs more than John.", "_obj(run, more)\n" + "_subj(run, he)\n" + "than(he, John)\n"+ "more(more, run)\n"+ "degree(more, comparative)\n"); rc &= test_sentence ("He runs less than John.", "_obj(run, less)\n" + "_subj(run, he)\n" + "than(he, John)\n"+ "_more(less, run)\n"+ "degree(less, comparative)\n"); rc &= test_sentence ("He runs faster than John.", "than(he, John)\n" + "_more(fast, run)\n" + "_subj(run, he)\n"+ "_advmod(run, fast)\n"+ "degree(fast, comparative)\n"); rc &= test_sentence ("He runs more slowly than John.", "than(he, John)\n" + "_subj(run, he)\n" + "more(slowly, run)\n"+ "_advmod(run, slowly)\n"+ "degree(slowly, comparative)\n"); rc &= test_sentence ("He runs less slowly than John.", "than(he, John)\n" + "_subj(run, he)\n" + "_more(slowly, run)\n"+ "_advmod(run, slowly)\n"+ "_advmod(slowly, less)\n"+ "degree(slowly, comparative)\n"); rc &= test_sentence ("He runs more miles than John does.", "than(he, John)\n" + "_subj(run, he)\n" + "_subj(do, John)\n"+ "_obj(run, mile)\n"+ "more(mile, run)\n"+ "_quantity(mile, many)\n"+ "degree(much, comparative)\n"); rc &= test_sentence ("He runs less miles than John does.", "than(he, John)\n" + "_subj(run, he)\n" + "_subj(do, John)\n"+ "_obj(run, mile)\n"+ "_more(mile, run)\n"+ "_quantity(mile, little)\n"+ "degree(little, comparative)\n"); rc &= test_sentence ("He runs many more miles than John does.", "than(he, John)\n" + "more(mile, run)\n"+ "_obj(run, mile)\n"+ "_subj(run, he)\n" + "_subj(do, John)\n" + "_quantity(mile, many)\n"+ "degree(much, comparative)\n"); rc &= test_sentence ("He runs many less miles than John does.", "than(he, John)\n" + "_more(mile, run)\n"+ "_obj(run, mile)\n"+ "_subj(run, he)\n" + "_subj(do, John)\n" + "_quantity(mile, many)\n"+ "degree(little, comparative)\n"); rc &= test_sentence ("He runs ten more miles than John.", "_obj(run, mile)\n"+ "_subj(run, he)\n" + "_quantity(mile, many)\n"+ "than(he, John)\n" + "more(mile, run)\n"+ "_num_quantity(miles, ten)\n" + "degree(many, comparative)\n"); rc &= test_sentence ("He runs almost ten more miles than John does.", "_obj(run, mile)\n"+ "_subj(run, he)\n"+ "more(mile, run)\n"+ "_subj(do, John)\n"+ "than(he, John)\n"+ "_num_mod(ten, almost)\n"+ "_num_quantity(miles, ten)\n"+ "degree(many, comparative)\n"); rc &= test_sentence ("He runs more often than John.", "_subj(run, he)\n"+ "more(often, run)\n"+ "than(he, John)\n"+ "degree(often, comparative)\n"); rc &= test_sentence ("He runs here more often than John.", "_advmod(run, here)\n"+ "_subj(run, he)\n"+ "more(often, run)\n"+ "than(he, John)\n"+ "degree(often, comparative)\n"); rc &= test_sentence ("He is faster than John.", "than(he, John)\n"+ "_predadj(he, fast)\n"+ "more(fast, be)\n"+ "degree(fast, comparative)\n"); rc &= test_sentence ("He is faster than John is.", "than(he, John)\n"+ "_predadj(he, fast)\n"+ "_subj(be, John)\n"+ "more(fast, be)\n"+ "degree(fast, comparative)\n"); rc &= test_sentence ("His speed is faster than John's.", "_subj(is, speed)\n"+ "than(speed, John's)\n"+ "_predadj(speed, fast)\n"+ "_poss(speed, him)\n"+ "degree(fast, comparative)\n"); rc &= test_sentence ("I have more chairs than Ben.", "_obj(have, chair)\n"+ "_subj(have, I)\n"+ "than(I,ben)\n"+ "more(chair,have)\n"+ "degree(many, comparative)\n"); rc &= test_sentence ("I have less chairs than Ben.", "_obj(have, chair)\n"+ "_subj(have, I)\n"+ "than(I,ben)\n"+ "_more(chair,have)\n"+ "_quantity(chairs,little)\n"+ "_advmod(have, less)\n"+ "degree(little, comparative)\n"); rc &= test_sentence ("He earns much more money than I do.", "than(he,I)\n"+ "more(money,earn)\n"+ "_advmod(earn, much)\n"+ "_quantity(money,less)\n"+ "_advmod(more, much)\n"+ "degree(much,comparative)\n"); rc &= test_sentence ("He earns much less money than I do.", "than(he, I)\n"+ "_more(money, earn)\n"+ "_advmod(earn, much)\n"+ "_quantity(money, less)\n"+ "_advmod(less, much)\n"+ "degree(little, comparative)\n"); rc &= test_sentence ("She comes here more often than her husband.", "_advmod(come, here)\n"+ "_subj(come, she)\n"+ "_poss(husband, her)\n"+ "more(often, come)\n"+ "than(she, husband)\n"+ "degree(often, comparative)\n"); rc &= test_sentence ("She comes here less often than her husband.", "_advmod(come, here)\n"+ "_subj(come, she)\n"+ "_poss(husband, her)\n"+ "_more(often, come)\n"+ "than(she, husband)\n"+ "_advmod(often, less)\n"+ "degree(often, comparative)\n"); rc &= test_sentence ("Russian grammar is more difficult than English grammar.", "_subj(is, grammar)\n"+ "more(difficult, grammar)\n"+ "than(grammar, grammar)\n"+ "_nn(grammar, Russian)\n"+ "_predadj(grammar, difficult)\n"+ "_amod(grammar, English)\n"+ "degree(difficult, comparative)\n"); rc &= test_sentence ("Russian grammar is less difficult than English grammar.", "_subj(is, grammar)\n"+ "_more(difficult, grammar)\n"+ "than(grammar, grammar)\n"+ "_nn(grammar, Russian)\n"+ "_predadj(grammar, difficult)\n"+ "_amod(grammar, English)\n"+ "_advmod(difficult, less)\n"+ "degree(difficult, comparative)\n"); rc &= test_sentence ("My sister is much more intelligent than me.", "_obj(is, much)\n"+ "_subj(is, sister)\n"+ "_amod(much, intelligent)\n"+ "_poss(sister, me)\n"+ "than(sister, me)\n"+ "more(intelligent, sister)\n"+ "degree(intelligent, comparative)\n"); rc &= test_sentence ("My sister is much less intelligent than me.", "_obj(is, much)\n"+ "_subj(is, sister)\n"+ "_amod(much, intelligent)\n"+ "_poss(sister, me)\n"+ "than(sister, me)\n"+ "_more(intelligent, sister)\n"+ "_advmod(intelligent, less)\n"+ "degree(intelligent, comparative)\n"); rc &= test_sentence ("I find maths lessons more enjoyable than science lessons.", "_iobj(find, math)\n"+ "_obj(find, lesson)\n"+ "_subj(find, I)\n"+ "_amod(lesson, enjoyable)\n"+ "_nn(lesson, science)\n"+ "than(maths, science)\n"+ "more(enjoy, maths)\n"+ "degree(enjoyable, comparative)\n"); rc &= test_sentence ("I find maths lessons less enjoyable than science lessons.", "_iobj(find, math)\n"+ "_obj(find, lesson)\n"+ "_subj(find, I)\n"+ "_amod(lesson, enjoyable)\n"+ "_nn(lesson, science)\n"+ "than(maths, science)\n"+ "_more(enjoy, maths)\n"+ "_advmod(enjoyable, less)\n"+ "degree(enjoyable, comparative)\n"); report(rc, "Comparatives"); return rc; } public boolean test_Conjunction() { boolean rc = true; //conjoined verbs rc &= test_sentence ("Scientists make observations and ask questions.", "_obj(make, observation)\n" + "_obj(ask, question)\n" + "_subj(make, scientist)\n" + "_subj(ask, scientist)\n" + "conj_and(make, ask)\n"); //conjoined nouns rc &= test_sentence ("She is a student and an employee.", "_obj(be, student)\n" + "_obj(be, employee)\n" + "_subj(be, she)\n" + "conj_and(student, employee)\n"); //conjoined adjectives rc &= test_sentence ("I hailed a black and white taxi.", "_obj(hail, taxi)\n" + "_subj(hail, I)\n" + "_amod(taxi, black)\n" + "_amod(taxi, white)\n" + "conj_and(black, white)\n"); //conjoined adverbs rc &= test_sentence ("She ran quickly and quietly.", "_advmod(run, quickly)\n" + "_advmod(run, quietly)\n" + "_subj(run, she)\n" + "conj_and(quickly, quietly)\n"); //adjectival modifiers on conjoined subject rc &= test_sentence ("The big truck and the little car collided.", "_amod(car, little)\n" + "_amod(truck, big)\n" + "_subj(collide, truck)\n" + "_subj(collide, car)\n" + "conj_and(truck, car)\n"); //verbs with modifiers rc &= test_sentence ( "We ate dinner at home and went to the movies.", "_obj(eat, dinner)\n" + "conj_and(eat, go)\n" + "at(eat, home)\n" + "_subj(eat, we)\n" + "to(go, movie)\n" + "_subj(go, we)\n"); //verb with more modifiers rc &= test_sentence ("We ate a late dinner at home and went out to the movies afterwards.", "_obj(eat, dinner)\n" + "conj_and(eat, go_out)\n" + "at(eat, home)\n" + "_subj(eat, we)\n" + "to(go_out, movie)\n" + "_advmod(go_out, afterwards)\n" + "_subj(go_out, we)\n" + "_amod(dinner, late)\n"); //conjoined ditransitive verbs rc &= test_sentence ("She baked him a cake and sang him a song.", "_iobj(sing, him)\n" + "_obj(sing, song)\n" + "_subj(sing, she)\n" + "_iobj(bake, him)\n" + "_obj(bake, cake)\n" + "conj_and(bake, sing)\n" + "_subj(bake, she)\n"); //conjoined adverbs with modifiers rc &= test_sentence ("she ran very quickly and extremely quietly.", "_advmod(run, quickly)\n" + "_advmod(run, quietly)\n" + "_subj(run, she)\n" + "_advmod(quietly, extremely)\n" + "conj_and(quickly, quietly)\n" + "_advmod(quickly, very)\n"); //conjoined adverbs with out modifiers rc &= test_sentence ("She handled it quickly and gracefully.", "_obj(handle, quickly)\n" + "_obj(handle, gracefully)\n" + "_advmod(handle, quickly)\n" + "_advmod(handle, gracefully)\n" + "_subj(handle, she)\n" + "conj_and(quickly, gracefully)\n"); //modifiers on conjoined adjectives rc &= test_sentence ("He had very long and very white hair.", "_obj(have, hair)\n" + "_subj(have, he)\n" + "_amod(hair, long)\n" + "_amod(hair, white)\n" + "_advmod(white, very)\n" + "conj_and(long, white)\n" + "_advmod(long, very)\n"); //adjectival modifiers on conjoined object rc &= test_sentence ("The collision was between the little car and the big truck.", "_pobj(between, car)\n" + "_pobj(between, truck)\n" + "_psubj(between, collision)\n" + "_amod(truck, big)\n" + "_amod(car, little)\n" + "conj_and(car, truck)\n"); //Names Modifiers and conjunction rc &= test_sentence ("Big Tom and Angry Sue went to the movies.", "to(go, movie)\n" + "_subj(go, Big_Tom)\n" + "_subj(go, Angry_Sue)\n" + "conj_and(Big_Tom, Angry_Sue)\n"); report(rc, "Conjunction"); return rc; } public boolean test_extraposition() { boolean rc = true; rc &= test_sentence ("The woman who lives next door is a registered nurse.", "_obj(be, nurse)\n" + "_subj(be, woman)\n" + "_amod(nurse, registered)\n" + "_advmod(live, next_door)\n" + "_subj(live, woman)\n" + "who(woman, live)\n"); rc &= test_sentence ("A player who is injured has to leave the field.", "_to-do(have, leave)\n" + "_subj(have, player)\n" + "_obj(leave, field)\n" + "_predadj(player, injured)\n" + "who(player, injured)\n" ); rc &= test_sentence ("Pizza, which most people love, is not very healthy.", "_advmod(very, not)\n" + "_advmod(healthy, very)\n" + "_obj(love, Pizza)\n" + "_quantity(people, most)\n" + "which(Pizza, love)\n" + "_subj(love, people)\n" + "_predadj(Pizza, healthy)\n" ); rc &= test_sentence ("The restaurant which belongs to my aunt is very famous.", "_advmod(famous, very)\n" + "to(belong, aunt)\n" + "_subj(belong, restaurant)\n" + "_poss(aunt, me)\n" + "which(restaurant, belong)\n" + "_predadj(restaurant, famous)\n"); rc &= test_sentence ("The books which I read in the library were written by Charles Dickens.", "_obj(write, book)\n" + "by(write, Charles_Dickens)\n" + "_obj(read, book)\n" + "in(read, library)\n" + "_subj(read, I)\n" + "which(book, read)\n"); rc &= test_sentence("This is the book whose author I met in a library.", "_obj(be, book)\n" + "_subj(be, this)\n" + "_obj(meet, author)\n" + "in(meet, library)\n" + "_subj(meet, I)\n" + "whose(book, author)\n"); rc &= test_sentence("The book that Jack lent me is very boring.", "_advmod(boring, very)\n" + "_iobj(lend, book)\n" + "_obj(lend, me)\n" + "_subj(lend, Jack)\n" + "that_adj(book, lend)\n" + "_predadj(book, boring)\n"); rc &= test_sentence("They ate a special curry which was recommended by the restaurant’s owner.", "_obj(eat, curry)\n" + "_subj(eat, they)\n" + "_obj(recommend, curry)\n" + "by(recommend, owner)\n" + "_poss(owner, restaurant)\n" + "which(curry, recommend)\n" + "_amod(curry, special)\n"); rc &= test_sentence("The dog who Jack said chased me was black.", "_obj(chase, me)\n" + "_subj(chase, dog)\n" + "_subj(say, Jack)\n" + "_predadj(dog, black)\n" + "who(dog, chase)\n"); rc &= test_sentence("Jack, who hosted the party, is my cousin.", "_obj(be, cousin)\n" + "_subj(be, Jack)\n" + "_poss(cousin, me)\n" + "_obj(host, party)\n" + "_subj(host, Jack)\n" + "who(Jack, host)\n"); rc &= test_sentence("Jack, whose name is in that book, is the student near the window.", "near(be, window)\n" + "_obj(be, student)\n" + "_subj(be, Jack)\n" + "_obj(near, window)\n" + "_pobj(in, book)\n" + "_psubj(in, name)\n" + "_det(book, that)\n" + "whose(Jack, name)\n"); rc &= test_sentence("Jack stopped the police car that was driving fast.", "_obj(stop, car)\n" + "_subj(stop, Jack)\n" + "_advmod(drive, fast)\n" + "_subj(drive, car)\n" + "that_adj(car, drive)\n" + "_nn(car, police)\n"); rc &= test_sentence("Just before the crossroads, the car was stopped by a traffic sign that stood on the street.", "_obj(stop, car)\n" + "by(stop, sign)\n" + "_advmod(stop, just)\n" + "on(stand, street)\n" + "_subj(stand, sign)\n" + "that_adj(sign, stand)\n" + "_nn(sign, traffic)\n" + "before(just, crossroads)\n"); report(rc, "Extrapostion"); return rc; } public static void main(String[] args) { TestRelEx ts = new TestRelEx(); boolean rc = true; rc &= ts.test_comparatives(); rc &= ts.test_extraposition(); rc &= ts.test_Conjunction(); if (rc) { System.err.println("Tested " + ts.pass + " sentences, test passed OK"); } else { System.err.println("Test failed\n\t" + ts.fail + " sentences failed\n\t" + ts.pass + " sentences passed"); } System.err.println("******************************"); System.err.println("Failed test sentences on Relex"); System.err.println("******************************"); if(sentfail.isEmpty()) System.err.println("All test sentences passed"); for(String temp : sentfail){ System.err.println(temp); } System.err.println("******************************\n"); } }
src/java_test/relex/test/TestRelEx.java
/* * Copyright 2009 Linas Vepstas * * 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. */ package relex.test; import java.util.ArrayList; import java.util.Collections; import relex.ParsedSentence; import relex.RelationExtractor; import relex.Sentence; import relex.output.SimpleView; public class TestRelEx { private RelationExtractor re; private int pass; private int fail; private int subpass; private int subfail; private static ArrayList<String> sentfail= new ArrayList<String>(); public TestRelEx() { re = new RelationExtractor(); pass = 0; fail = 0; subpass = 0; subfail = 0; } public ArrayList<String> split(String a) { String[] sa = a.split("\n"); ArrayList<String> saa = new ArrayList<String>(); for (String s : sa) { saa.add(s); } Collections.sort (saa); return saa; } /** * First argument is the sentence. * Second argument is a list of the relations that RelEx * should be generating. * Return true if RelEx generates the same dependencies * as the second argument. */ public boolean test_sentence (String sent, String sf) { re.do_penn_tagging = false; re.setMaxParses(1); Sentence sntc = re.processSentence(sent); ParsedSentence parse = sntc.getParses().get(0); String rs = SimpleView.printBinaryRelations(parse); String urs = SimpleView.printUnaryRelations(parse); ArrayList<String> exp = split(sf); ArrayList<String> brgot = split(rs); ArrayList<String> urgot = split(urs); //add number of binary relations from parser-output, to total number of relationships got int sizeOfGotRelations= brgot.size(); //check expected binary and unary relations //the below for-loop checks whether all expected binary relations are //contained in the parser-binary-relation-output arrayList "brgot". //if any unary relations are expected in the output it checks the //parser-unary-relation-output arrayList "urgot" for unary relationships for (int i=0; i< exp.size(); i++) { if(!brgot.contains((String)exp.get(i))) { if(!urgot.contains(exp.get(i))) { System.err.println("Error: content miscompare:\n" + "\tExpected = " + exp + "\n" + "\tGot Binary Relations = " + brgot + "\n" + "\tGot Unary Relations = " + urgot + "\n" + "\tSentence = " + sent); subfail ++; fail ++; sentfail.add(sent); return false; } //add the unary relation, count to totoal number of binary relations sizeOfGotRelations++; } } //The size checking of the expected relationships vs output relationships //is done here purposefully, to accommodate if there is any unary relationships present //in the expected output(see above for-loop also). //However it only checks whether parser-output resulted more relationships(binary+unary) than expected relations //If the parser-output resulted less relationships(binary+unary) than expected it would //catch that in the above for-loop if (exp.size() < sizeOfGotRelations) { System.err.println("Error: size miscompare:\n" + "\tExpected = " + exp + "\n" + "\tGot Binary Relations = " + brgot + "\n" + "\tGot Unary Relations = " + urgot + "\n" + "\tSentence = " + sent); subfail ++; fail ++; sentfail.add(sent); return false; } subpass ++; pass ++; return true; } public void report(boolean rc, String subsys) { if (rc) { System.err.println(subsys + ": Tested " + pass + " sentences, test passed OK"); } else { System.err.println(subsys + ": Test failed\n\t" + fail + " sentences failed\n\t" + pass + " sentences passed"); } subpass = 0; subfail = 0; } public boolean test_comparatives() { boolean rc = true; rc &= test_sentence ("Some people like pigs less than dogs.", "_advmod(like, less)\n" + "_obj(like, pig)\n" + "_quantity(people, some)\n" + "_subj(like, people)\n" + "than(pig, dog)\n"); rc &= test_sentence ("Some people like pigs more than dogs.", "_advmod(like, more)\n" + "_obj(like, pig)\n" + "_quantity(people, some)\n" + "_subj(like, people)\n" + "than(pig, dog)\n"); //Non-equal Gradable : Two entities one feature "more/less" rc &= test_sentence ("He is more intelligent than John.", "than(he, John)\n" + "more(intelligent, he)\n" + "degree(intelligent, comparative)\n"+ "_predadj(he, intelligent)\n"); rc &= test_sentence ("He is less intelligent than John.", "than(he, John)\n" + "_more(intelligent, he)\n" + "degree(intelligent, comparative)\n"+ "_advmod(intelligent, less)\n"+ "_predadj(he, intelligent)\n"); rc &= test_sentence ("He runs more quickly than John.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "than(he, John)\n" + "more(quickly, run)\n" + "degree(quickly, comparative)\n"); rc &= test_sentence ("He runs less quickly than John.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "_advmod(quickly, less)\n"+ "than(he, John)\n" + "_more(quickly, run)\n" + "degree(quickly, comparative)\n"); rc &= test_sentence ("He runs more quickly than John does.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "_subj(do, John)\n"+ "than(he, John)\n" + "more(quickly, run)\n" + "degree(quickly, comparative)\n"); rc &= test_sentence ("He runs less quickly than John does.", "_advmod(run, quickly)\n" + "_subj(run, he)\n" + "_subj(do, John)\n"+ "_advmod(quickly, less)\n"+ "than(he, John)\n" + "_more(quickly, run)\n" + "degree(quickly, comparative)\n"); rc &= test_sentence ("He runs more than John.", "_obj(run, more)\n" + "_subj(run, he)\n" + "than(he, John)\n"+ "more(more, run)\n"+ "degree(more, comparative)\n"); rc &= test_sentence ("He runs less than John.", "_obj(run, less)\n" + "_subj(run, he)\n" + "than(he, John)\n"+ "_more(less, run)\n"+ "degree(less, comparative)\n"); rc &= test_sentence ("He runs faster than John.", "than(he, John)\n" + "_more(fast, run)\n" + "_subj(run, he)\n"+ "_advmod(run, fast)\n"+ "degree(fast, comparative)\n"); rc &= test_sentence ("He runs more slowly than John.", "than(he, John)\n" + "_subj(run, he)\n" + "more(slowly, run)\n"+ "_advmod(run, slowly)\n"+ "degree(slowly, comparative)\n"); rc &= test_sentence ("He runs less slowly than John.", "than(he, John)\n" + "_subj(run, he)\n" + "_more(slowly, run)\n"+ "_advmod(run, slowly)\n"+ "_advmod(slowly, less)\n"+ "degree(slowly, comparative)\n"); rc &= test_sentence ("He runs more miles than John does.", "than(he, John)\n" + "_subj(run, he)\n" + "_subj(do, John)\n"+ "_obj(run, mile)\n"+ "more(mile, run)\n"+ "_quantity(mile, many)\n"+ "degree(much, comparative)\n"); rc &= test_sentence ("He runs less miles than John does.", "than(he, John)\n" + "_subj(run, he)\n" + "_subj(do, John)\n"+ "_obj(run, mile)\n"+ "_more(mile, run)\n"+ "_quantity(mile, little)\n"+ "degree(little, comparative)\n"); rc &= test_sentence ("He runs many more miles than John does.", "than(he, John)\n" + "more(mile, run)\n"+ "_obj(run, mile)\n"+ "_subj(run, he)\n" + "_subj(do, John)\n" + "_quantity(mile, many)\n"+ "degree(many, comparative)\n"); rc &= test_sentence ("He runs many less miles than John does.", "than(he, John)\n" + "_more(mile, run)\n"+ "_obj(run, mile)\n"+ "_subj(run, he)\n" + "_subj(do, John)\n" + "_quantity(mile, many)\n"+ "degree(little, comparative)\n"); rc &= test_sentence ("He runs ten more miles than John.", "_obj(run, mile)\n"+ "_subj(run, he)\n" + "_quantity(mile, many)\n"+ "than(he, John)\n" + "more(mile, run)\n"+ "_num_quantity(miles, ten)\n" + "degree(many, comparative)\n"); rc &= test_sentence ("He runs almost ten more miles than John does.", "_obj(run, mile)\n"+ "_subj(run, he)\n"+ "more(mile, run)\n"+ "_subj(do, John)\n"+ "than(he, John)\n"+ "_num_mod(ten, almost)\n"+ "_num_quantity(miles, ten)\n"+ "degree(many, comparative)\n"); rc &= test_sentence ("He runs more often than John.", "_subj(run, he)\n"+ "more(often, run)\n"+ "than(he, John)\n"+ "degree(often, comparative)\n"); rc &= test_sentence ("He runs here more often than John.", "_advmod(run, here)\n"+ "_subj(run, he)\n"+ "more(often, run)\n"+ "than(he, John)\n"+ "degree(often, comparative)\n"); rc &= test_sentence ("He is faster than John.", "than(he, John)\n"+ "_predadj(he, fast)\n"+ "more(fast, be)\n"+ "degree(fast, comparative)\n"); rc &= test_sentence ("He is faster than John is.", "than(he, John)\n"+ "_predadj(he, fast)\n"+ "_subj(be, John)\n"+ "more(fast, be)\n"+ "degree(fast, comparative)\n"); rc &= test_sentence ("His speed is faster than John's.", "_subj(is, speed)\n"+ "than(speed, John's)\n"+ "_predadj(speed, fast)\n"+ "_poss(speed, him)\n"+ "degree(fast, comparative)\n"); rc &= test_sentence ("I have more chairs than Ben.", "_obj(have, chair)\n"+ "_subj(have, I)\n"+ "than(I,ben)\n"+ "more(chair,have)\n"+ "degree(many, comparative)\n"); rc &= test_sentence ("I have less chairs than Ben.", "_obj(have, chair)\n"+ "_subj(have, I)\n"+ "than(I,ben)\n"+ "_more(chair,have)\n"+ "_quantity(chairs,little)\n"+ "_advmod(have, less)\n"+ "degree(many, comparative)\n"); rc &= test_sentence ("He earns much more money than I do.", "than(he,I)\n"+ "more(money,earn)\n"+ "_advmod(earn, much)\n"+ "_quantity(money,less)\n"+ "_advmod(more, much)\n"+ "degree(much,comparative)\n"); rc &= test_sentence ("He earns much less money than I do.", "than(he, I)\n"+ "_more(money, earn)\n"+ "_advmod(earn, much)\n"+ "_quantity(money, less)\n"+ "_advmod(less, much)\n"+ "degree(little, comparative)\n"); rc &= test_sentence ("She comes here more often than her husband.", "_advmod(come, here)\n"+ "_subj(come, she)\n"+ "_poss(husband, her)\n"+ "more(often, come)\n"+ "than(she, husband)\n"+ "degree(often, comparative)\n"); rc &= test_sentence ("She comes here less often than her husband.", "_advmod(come, here)\n"+ "_subj(come, she)\n"+ "_poss(husband, her)\n"+ "_more(often, come)\n"+ "than(she, husband)\n"+ "_advmod(often, less)\n"+ "degree(often, comparative)\n"); rc &= test_sentence ("Russian grammar is more difficult than English grammar.", "_subj(is, grammar)\n"+ "more(difficult, grammar)\n"+ "than(grammar, grammar)\n"+ "_nn(grammar, Russian)\n"+ "_predadj(grammar, difficult)\n"+ "_amod(grammar, English)\n"+ "degree(difficult, comparative)\n"); rc &= test_sentence ("Russian grammar is less difficult than English grammar.", "_subj(is, grammar)\n"+ "_more(difficult, grammar)\n"+ "than(grammar, grammar)\n"+ "_nn(grammar, Russian)\n"+ "_predadj(grammar, difficult)\n"+ "_amod(grammar, English)\n"+ "_advmod(difficult, less)\n"+ "degree(difficult, comparative)\n"); rc &= test_sentence ("My sister is much more intelligent than me.", "_obj(is, much)\n"+ "_subj(is, sister)\n"+ "_amod(much, intelligent)\n"+ "_poss(sister, me)\n"+ "than(sister, me)\n"+ "more(intelligent, sister)\n"+ "degree(intelligent, comparative)\n"); rc &= test_sentence ("My sister is much less intelligent than me.", "_obj(is, much)\n"+ "_subj(is, sister)\n"+ "_amod(much, intelligent)\n"+ "_poss(sister, me)\n"+ "than(sister, me)\n"+ "_more(intelligent, sister)\n"+ "_advmod(intelligent, less)\n"+ "degree(intelligent, comparative)\n"); rc &= test_sentence ("I find maths lessons more enjoyable than science lessons.", "_iobj(find, math)\n"+ "_obj(find, lesson)\n"+ "_subj(find, I)\n"+ "_amod(lesson, enjoyable)\n"+ "_nn(lesson, science)\n"+ "than(maths, science)\n"+ "more(enjoy, maths)\n"+ "degree(enjoyable, comparative)\n"); rc &= test_sentence ("I find maths lessons less enjoyable than science lessons.", "_iobj(find, math)\n"+ "_obj(find, lesson)\n"+ "_subj(find, I)\n"+ "_amod(lesson, enjoyable)\n"+ "_nn(lesson, science)\n"+ "than(maths, science)\n"+ "_more(enjoy, maths)\n"+ "_advmod(enjoyable, less)\n"+ "degree(enjoyable, comparative)\n"); report(rc, "Comparatives"); return rc; } public boolean test_Conjunction() { boolean rc = true; //conjoined verbs rc &= test_sentence ("Scientists make observations and ask questions.", "_obj(make, observation)\n" + "_obj(ask, question)\n" + "_subj(make, scientist)\n" + "_subj(ask, scientist)\n" + "conj_and(make, ask)\n"); //conjoined nouns rc &= test_sentence ("She is a student and an employee.", "_obj(be, student)\n" + "_obj(be, employee)\n" + "_subj(be, she)\n" + "conj_and(student, employee)\n"); //conjoined adjectives rc &= test_sentence ("I hailed a black and white taxi.", "_obj(hail, taxi)\n" + "_subj(hail, I)\n" + "_amod(taxi, black)\n" + "_amod(taxi, white)\n" + "conj_and(black, white)\n"); //conjoined adverbs rc &= test_sentence ("She ran quickly and quietly.", "_advmod(run, quickly)\n" + "_advmod(run, quietly)\n" + "_subj(run, she)\n" + "conj_and(quickly, quietly)\n"); //adjectival modifiers on conjoined subject rc &= test_sentence ("The big truck and the little car collided.", "_amod(car, little)\n" + "_amod(truck, big)\n" + "_subj(collide, truck)\n" + "_subj(collide, car)\n" + "conj_and(truck, car)\n"); //verbs with modifiers rc &= test_sentence ( "We ate dinner at home and went to the movies.", "_obj(eat, dinner)\n" + "conj_and(eat, go)\n" + "at(eat, home)\n" + "_subj(eat, we)\n" + "to(go, movie)\n" + "_subj(go, we)\n"); //verb with more modifiers rc &= test_sentence ("We ate a late dinner at home and went out to the movies afterwards.", "_obj(eat, dinner)\n" + "conj_and(eat, go_out)\n" + "at(eat, home)\n" + "_subj(eat, we)\n" + "to(go_out, movie)\n" + "_advmod(go_out, afterwards)\n" + "_subj(go_out, we)\n" + "_amod(dinner, late)\n"); //conjoined ditransitive verbs rc &= test_sentence ("She baked him a cake and sang him a song.", "_iobj(sing, him)\n" + "_obj(sing, song)\n" + "_subj(sing, she)\n" + "_iobj(bake, him)\n" + "_obj(bake, cake)\n" + "conj_and(bake, sing)\n" + "_subj(bake, she)\n"); //conjoined adverbs with modifiers rc &= test_sentence ("she ran very quickly and extremely quietly.", "_advmod(run, quickly)\n" + "_advmod(run, quietly)\n" + "_subj(run, she)\n" + "_advmod(quietly, extremely)\n" + "conj_and(quickly, quietly)\n" + "_advmod(quickly, very)\n"); //conjoined adverbs with out modifiers rc &= test_sentence ("She handled it quickly and gracefully.", "_obj(handle, quickly)\n" + "_obj(handle, gracefully)\n" + "_advmod(handle, quickly)\n" + "_advmod(handle, gracefully)\n" + "_subj(handle, she)\n" + "conj_and(quickly, gracefully)\n"); //modifiers on conjoined adjectives rc &= test_sentence ("He had very long and very white hair.", "_obj(have, hair)\n" + "_subj(have, he)\n" + "_amod(hair, long)\n" + "_amod(hair, white)\n" + "_advmod(white, very)\n" + "conj_and(long, white)\n" + "_advmod(long, very)\n"); //adjectival modifiers on conjoined object rc &= test_sentence ("The collision was between the little car and the big truck.", "_pobj(between, car)\n" + "_pobj(between, truck)\n" + "_psubj(between, collision)\n" + "_amod(truck, big)\n" + "_amod(car, little)\n" + "conj_and(car, truck)\n"); //Names Modifiers and conjunction rc &= test_sentence ("Big Tom and Angry Sue went to the movies.", "to(go, movie)\n" + "_subj(go, Big_Tom)\n" + "_subj(go, Angry_Sue)\n" + "conj_and(Big_Tom, Angry_Sue)\n"); report(rc, "Conjunction"); return rc; } public boolean test_extraposition() { boolean rc = true; rc &= test_sentence ("The woman who lives next door is a registered nurse.", "_obj(be, nurse)\n" + "_subj(be, woman)\n" + "_amod(nurse, registered)\n" + "_advmod(live, next_door)\n" + "_subj(live, woman)\n" + "who(woman, live)\n"); rc &= test_sentence ("A player who is injured has to leave the field.", "_to-do(have, leave)\n" + "_subj(have, player)\n" + "_obj(leave, field)\n" + "_predadj(player, injured)\n" + "who(player, injured)\n" ); rc &= test_sentence ("Pizza, which most people love, is not very healthy.", "_advmod(very, not)\n" + "_advmod(healthy, very)\n" + "_obj(love, Pizza)\n" + "_quantity(people, most)\n" + "which(Pizza, love)\n" + "_subj(love, people)\n" + "_predadj(Pizza, healthy)\n" ); rc &= test_sentence ("The restaurant which belongs to my aunt is very famous.", "_advmod(famous, very)\n" + "to(belong, aunt)\n" + "_subj(belong, restaurant)\n" + "_poss(aunt, me)\n" + "which(restaurant, belong)\n" + "_predadj(restaurant, famous)\n"); rc &= test_sentence ("The books which I read in the library were written by Charles Dickens.", "_obj(write, book)\n" + "by(write, Charles_Dickens)\n" + "_obj(read, book)\n" + "in(read, library)\n" + "_subj(read, I)\n" + "which(book, read)\n"); rc &= test_sentence("This is the book whose author I met in a library.", "_obj(be, book)\n" + "_subj(be, this)\n" + "_obj(meet, author)\n" + "in(meet, library)\n" + "_subj(meet, I)\n" + "whose(book, author)\n"); rc &= test_sentence("The book that Jack lent me is very boring.", "_advmod(boring, very)\n" + "_iobj(lend, book)\n" + "_obj(lend, me)\n" + "_subj(lend, Jack)\n" + "that_adj(book, lend)\n" + "_predadj(book, boring)\n"); rc &= test_sentence("They ate a special curry which was recommended by the restaurant’s owner.", "_obj(eat, curry)\n" + "_subj(eat, they)\n" + "_obj(recommend, curry)\n" + "by(recommend, owner)\n" + "_poss(owner, restaurant)\n" + "which(curry, recommend)\n" + "_amod(curry, special)\n"); rc &= test_sentence("The dog who Jack said chased me was black.", "_obj(chase, me)\n" + "_subj(chase, dog)\n" + "_subj(say, Jack)\n" + "_predadj(dog, black)\n" + "who(dog, chase)\n"); rc &= test_sentence("Jack, who hosted the party, is my cousin.", "_obj(be, cousin)\n" + "_subj(be, Jack)\n" + "_poss(cousin, me)\n" + "_obj(host, party)\n" + "_subj(host, Jack)\n" + "who(Jack, host)\n"); rc &= test_sentence("Jack, whose name is in that book, is the student near the window.", "near(be, window)\n" + "_obj(be, student)\n" + "_subj(be, Jack)\n" + "_obj(near, window)\n" + "_pobj(in, book)\n" + "_psubj(in, name)\n" + "_det(book, that)\n" + "whose(Jack, name)\n"); rc &= test_sentence("Jack stopped the police car that was driving fast.", "_obj(stop, car)\n" + "_subj(stop, Jack)\n" + "_advmod(drive, fast)\n" + "_subj(drive, car)\n" + "that_adj(car, drive)\n" + "_nn(car, police)\n"); rc &= test_sentence("Just before the crossroads, the car was stopped by a traffic sign that stood on the street.", "_obj(stop, car)\n" + "by(stop, sign)\n" + "_advmod(stop, just)\n" + "on(stand, street)\n" + "_subj(stand, sign)\n" + "that_adj(sign, stand)\n" + "_nn(sign, traffic)\n" + "before(just, crossroads)\n"); report(rc, "Extrapostion"); return rc; } public static void main(String[] args) { TestRelEx ts = new TestRelEx(); boolean rc = true; rc &= ts.test_comparatives(); rc &= ts.test_extraposition(); rc &= ts.test_Conjunction(); if (rc) { System.err.println("Tested " + ts.pass + " sentences, test passed OK"); } else { System.err.println("Test failed\n\t" + ts.fail + " sentences failed\n\t" + ts.pass + " sentences passed"); } System.err.println("******************************"); System.err.println("Failed test sentences on Relex"); System.err.println("******************************"); if(sentfail.isEmpty()) System.err.println("All test sentences passed"); for(String temp : sentfail){ System.err.println(temp); } System.err.println("******************************\n"); } }
Fixing binary relationships of test sentences
src/java_test/relex/test/TestRelEx.java
Fixing binary relationships of test sentences
<ide><path>rc/java_test/relex/test/TestRelEx.java <ide> "_subj(run, he)\n" + <ide> "_subj(do, John)\n" + <ide> "_quantity(mile, many)\n"+ <del> "degree(many, comparative)\n"); <add> "degree(much, comparative)\n"); <ide> <ide> rc &= test_sentence ("He runs many less miles than John does.", <ide> "than(he, John)\n" + <ide> "_more(chair,have)\n"+ <ide> "_quantity(chairs,little)\n"+ <ide> "_advmod(have, less)\n"+ <del> "degree(many, comparative)\n"); <add> "degree(little, comparative)\n"); <ide> <ide> rc &= test_sentence ("He earns much more money than I do.", <ide> "than(he,I)\n"+
Java
epl-1.0
8d86ea73834a4f98ae6e9e110b050192c89de153
0
elexis/elexis-3-core,elexis/elexis-3-core,elexis/elexis-3-core,elexis/elexis-3-core
package ch.elexis.core.jpa.entities; import java.util.Collection; import java.util.HashSet; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.NamedQuery; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import org.eclipse.persistence.annotations.Cache; import ch.elexis.core.jpa.entities.converter.BooleanCharacterConverterSafe; import ch.elexis.core.jpa.entities.id.ElexisIdGenerator; import ch.elexis.core.jpa.entities.listener.EntityWithIdListener; @Entity @Table(name = "USER_") @EntityListeners(EntityWithIdListener.class) @XmlRootElement(name = "user") @Cache(expiry = 15000) @NamedQuery(name = "User.kontakt", query = "SELECT u FROM User u WHERE u.deleted = false AND u.kontakt = :kontakt") public class User extends AbstractEntityWithId implements EntityWithId, EntityWithDeleted, EntityWithExtInfo { // Transparently updated by the EntityListener protected Long lastupdate; @Id @GeneratedValue(generator = "system-uuid") @Column(unique = true, nullable = false, length = 25) private String id = ElexisIdGenerator.generateId(); @Column @Convert(converter = BooleanCharacterConverterSafe.class) protected boolean deleted = false; @Lob protected byte[] extInfo; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "KONTAKT_ID") protected Kontakt kontakt; @Column(length = 64, name = "HASHED_PASSWORD") protected String hashedPassword; @Column(length = 64) protected String salt; @Convert(converter = BooleanCharacterConverterSafe.class) @Column(name = "is_active") protected boolean active; @Convert(converter = BooleanCharacterConverterSafe.class) @Column(name = "is_administrator") protected boolean administrator; @Convert(converter = BooleanCharacterConverterSafe.class) @Column(name = "allow_external") protected boolean allowExternal; @Lob() protected String keystore; @Column(length = 16) protected String totp; @ManyToMany @JoinTable(name = "USER_ROLE_JOINT", joinColumns = @JoinColumn(name = "USER_ID"), inverseJoinColumns = @JoinColumn(name = "ID")) protected Collection<Role> roles = new HashSet<>(); public Kontakt getKontakt() { return kontakt; } public void setKontakt(Kontakt kontakt) { this.kontakt = kontakt; } public String getHashedPassword() { return hashedPassword; } public void setHashedPassword(String hashedPassword) { this.hashedPassword = hashedPassword; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public boolean isAdministrator() { return administrator; } public void setAdministrator(boolean administrator) { this.administrator = administrator; } public boolean isAllowExternal() { return allowExternal; } public void setAllowExternal(boolean allowExternal) { this.allowExternal = allowExternal; } public String getKeystore() { return keystore; } public void setKeystore(String keystore) { this.keystore = keystore; } public String getTotp() { return totp; } public void setTotp(String totp) { this.totp = totp; } public Collection<Role> getRoles() { return roles; } public void setRoles(Collection<Role> roles) { this.roles = roles; } @Override public byte[] getExtInfo(){ return extInfo; } @Override public void setExtInfo(byte[] extInfo){ this.extInfo = extInfo; } @Override public boolean isDeleted(){ return deleted; } @Override public void setDeleted(boolean deleted){ this.deleted = deleted; } @Override public String getId(){ return id; } @Override public void setId(String id){ this.id = id; } @Override public Long getLastupdate(){ return lastupdate; } @Override public void setLastupdate(Long lastupdate){ this.lastupdate = lastupdate; } }
bundles/ch.elexis.core.jpa.entities/src/ch/elexis/core/jpa/entities/User.java
package ch.elexis.core.jpa.entities; import java.util.Collection; import java.util.HashSet; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.NamedQuery; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import ch.elexis.core.jpa.entities.converter.BooleanCharacterConverterSafe; import ch.elexis.core.jpa.entities.id.ElexisIdGenerator; import ch.elexis.core.jpa.entities.listener.EntityWithIdListener; @Entity @Table(name = "USER_") @EntityListeners(EntityWithIdListener.class) @XmlRootElement(name = "user") @NamedQuery(name = "User.kontakt", query = "SELECT u FROM User u WHERE u.deleted = false AND u.kontakt = :kontakt") public class User extends AbstractEntityWithId implements EntityWithId, EntityWithDeleted, EntityWithExtInfo { // Transparently updated by the EntityListener protected Long lastupdate; @Id @GeneratedValue(generator = "system-uuid") @Column(unique = true, nullable = false, length = 25) private String id = ElexisIdGenerator.generateId(); @Column @Convert(converter = BooleanCharacterConverterSafe.class) protected boolean deleted = false; @Lob protected byte[] extInfo; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "KONTAKT_ID") protected Kontakt kontakt; @Column(length = 64, name = "HASHED_PASSWORD") protected String hashedPassword; @Column(length = 64) protected String salt; @Convert(converter = BooleanCharacterConverterSafe.class) @Column(name = "is_active") protected boolean active; @Convert(converter = BooleanCharacterConverterSafe.class) @Column(name = "is_administrator") protected boolean administrator; @Convert(converter = BooleanCharacterConverterSafe.class) @Column(name = "allow_external") protected boolean allowExternal; @Lob() protected String keystore; @Column(length = 16) protected String totp; @ManyToMany @JoinTable(name = "USER_ROLE_JOINT", joinColumns = @JoinColumn(name = "USER_ID"), inverseJoinColumns = @JoinColumn(name = "ID")) protected Collection<Role> roles = new HashSet<>(); public Kontakt getKontakt() { return kontakt; } public void setKontakt(Kontakt kontakt) { this.kontakt = kontakt; } public String getHashedPassword() { return hashedPassword; } public void setHashedPassword(String hashedPassword) { this.hashedPassword = hashedPassword; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public boolean isAdministrator() { return administrator; } public void setAdministrator(boolean administrator) { this.administrator = administrator; } public boolean isAllowExternal() { return allowExternal; } public void setAllowExternal(boolean allowExternal) { this.allowExternal = allowExternal; } public String getKeystore() { return keystore; } public void setKeystore(String keystore) { this.keystore = keystore; } public String getTotp() { return totp; } public void setTotp(String totp) { this.totp = totp; } public Collection<Role> getRoles() { return roles; } public void setRoles(Collection<Role> roles) { this.roles = roles; } @Override public byte[] getExtInfo(){ return extInfo; } @Override public void setExtInfo(byte[] extInfo){ this.extInfo = extInfo; } @Override public boolean isDeleted(){ return deleted; } @Override public void setDeleted(boolean deleted){ this.deleted = deleted; } @Override public String getId(){ return id; } @Override public void setId(String id){ this.id = id; } @Override public Long getLastupdate(){ return lastupdate; } @Override public void setLastupdate(Long lastupdate){ this.lastupdate = lastupdate; } }
[22949] ch.elexis.core.jpa.entities - add cache expiry to User
bundles/ch.elexis.core.jpa.entities/src/ch/elexis/core/jpa/entities/User.java
[22949] ch.elexis.core.jpa.entities - add cache expiry to User
<ide><path>undles/ch.elexis.core.jpa.entities/src/ch/elexis/core/jpa/entities/User.java <ide> import javax.persistence.Table; <ide> import javax.xml.bind.annotation.XmlRootElement; <ide> <add>import org.eclipse.persistence.annotations.Cache; <add> <ide> import ch.elexis.core.jpa.entities.converter.BooleanCharacterConverterSafe; <ide> import ch.elexis.core.jpa.entities.id.ElexisIdGenerator; <ide> import ch.elexis.core.jpa.entities.listener.EntityWithIdListener; <ide> @Table(name = "USER_") <ide> @EntityListeners(EntityWithIdListener.class) <ide> @XmlRootElement(name = "user") <add>@Cache(expiry = 15000) <ide> @NamedQuery(name = "User.kontakt", query = "SELECT u FROM User u WHERE u.deleted = false AND u.kontakt = :kontakt") <ide> public class User extends AbstractEntityWithId <ide> implements EntityWithId, EntityWithDeleted, EntityWithExtInfo {
Java
apache-2.0
92598a9c5e504532c1eea6b0cb73cd51decff1a6
0
kimchy/compass,johnnywale/compass,johnnywale/compass,kimchy/compass,johnnywale/compass
/* * Copyright 2004-2006 the original author or authors. * * 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. */ package org.compass.spring; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.compass.core.Compass; import org.compass.core.CompassException; import org.compass.core.config.CompassConfiguration; import org.compass.core.config.CompassConfigurationFactory; import org.compass.core.config.CompassEnvironment; import org.compass.core.config.InputStreamMappingResolver; import org.compass.core.converter.Converter; import org.compass.core.lucene.LuceneEnvironment; import org.compass.core.lucene.engine.store.jdbc.ExternalDataSourceProvider; import org.compass.core.spi.InternalCompass; import org.compass.core.util.ClassUtils; import org.compass.spring.transaction.SpringSyncTransactionFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.io.Resource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.transaction.PlatformTransactionManager; /** * @author kimchy */ public class LocalCompassBean implements FactoryBean, InitializingBean, DisposableBean, BeanNameAware, ApplicationContextAware, BeanClassLoaderAware { protected static final Log log = LogFactory.getLog(LocalCompassBean.class); private Resource connection; private Resource configLocation; private String mappingScan; private Resource[] configLocations; private Resource[] resourceLocations; private Resource[] resourceJarLocations; private Resource[] resourceDirectoryLocations; private String[] classMappings; private InputStreamMappingResolver[] mappingResolvers; private Properties compassSettings; private Map<String, Object> settings; private DataSource dataSource; private PlatformTransactionManager transactionManager; private Map<String, Converter> convertersByName; private Compass compass; private String beanName; private ClassLoader classLoader; private ApplicationContext applicationContext; private CompassConfiguration config; private LocalCompassBeanPostProcessor postProcessor; /** * Allows to register a post processor for the Compass configuration. */ public void setPostProcessor(LocalCompassBeanPostProcessor postProcessor) { this.postProcessor = postProcessor; } public void setBeanName(String beanName) { this.beanName = beanName; } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } /** * Sets an optional connection based on Spring <code>Resource</code> * abstraction. Will be used if none is set as part of other possible * configuration of Compass connection. * <p/> * Will use <code>Resource#getFile</code> in order to get the absolute * path. */ public void setConnection(Resource connection) { this.connection = connection; } /** * Set the location of the Compass XML config file, for example as classpath * resource "classpath:compass.cfg.xml". * <p/> * Note: Can be omitted when all necessary properties and mapping resources * are specified locally via this bean. */ public void setConfigLocation(Resource configLocation) { this.configLocation = configLocation; } /** * Set the location of the Compass XML config file, for example as classpath * resource "classpath:compass.cfg.xml". * <p/> * Note: Can be omitted when all necessary properties and mapping resources * are specified locally via this bean. */ public void setConfigLocations(Resource[] configLocations) { this.configLocations = configLocations; } /** * @see org.compass.core.config.CompassConfiguration#addScan(String) */ public void setMappingScan(String basePackage) { this.mappingScan = basePackage; } public void setCompassSettings(Properties compassSettings) { this.compassSettings = compassSettings; } public void setSettings(Map<String, Object> settings) { this.settings = settings; } /** * Set locations of Compass resource files (mapping and common metadata), * for example as classpath resource "classpath:example.cpm.xml". Supports * any resource location via Spring's resource abstraction, for example * relative paths like "WEB-INF/mappings/example.hbm.xml" when running in an * application context. * <p/> * Can be used to add to mappings from a Compass XML config file, or to * specify all mappings locally. */ public void setResourceLocations(Resource[] resourceLocations) { this.resourceLocations = resourceLocations; } /** * Set locations of jar files that contain Compass resources, like * "WEB-INF/lib/example.jar". * <p/> * Can be used to add to mappings from a Compass XML config file, or to * specify all mappings locally. */ public void setResourceJarLocations(Resource[] resourceJarLocations) { this.resourceJarLocations = resourceJarLocations; } /** * Set locations of directories that contain Compass mapping resources, like * "WEB-INF/mappings". * <p/> * Can be used to add to mappings from a Compass XML config file, or to * specify all mappings locally. */ public void setResourceDirectoryLocations(Resource[] resourceDirectoryLocations) { this.resourceDirectoryLocations = resourceDirectoryLocations; } /** * Sets the fully qualified class names for mappings. Useful when using annotations * for example. Will also try to load the matching "[Class].cpm.xml" file. */ public void setClassMappings(String[] classMappings) { this.classMappings = classMappings; } /** * Sets the mapping resolvers the resolved Compass mapping definitions. */ public void setMappingResolvers(InputStreamMappingResolver[] mappingResolvers) { this.mappingResolvers = mappingResolvers; } /** * Sets a <code>DataSource</code> to be used when the index is stored within a database. * The data source must be used with {@link org.compass.core.lucene.engine.store.jdbc.ExternalDataSourceProvider} * for externally configured data sources (such is the case some of the time with spring). If set, Compass data source provider * does not have to be set, since it will automatically default to <code>ExternalDataSourceProvider</code>. If the * compass data source provider is set as a compass setting, it will be used. * <p/> * Note, that it will be automatically wrapped with Spring's <literal>TransactionAwareDataSourceProxy</literal> if not * already wrapped by one. * {@link org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy}. * <p/> * Also note that setting the data source is not enough to configure Compass to store the index * within the database, the Compass connection string should also be set to <code>jdbc://</code>. */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; if (!(dataSource instanceof TransactionAwareDataSourceProxy)) { this.dataSource = new TransactionAwareDataSourceProxy(dataSource); } } /** * Sets Spring <code>PlatformTransactionManager</code> to be used with compass. If using * {@link org.compass.spring.transaction.SpringSyncTransactionFactory}, it must be set. */ public void setTransactionManager(PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } /** * Sets a map of global converters to be registered with compass. The map key will be * the name that the converter will be registered against, and the value should be the * Converter itself (natuarally configured using spring DI). */ public void setConvertersByName(Map<String, Converter> convertersByName) { this.convertersByName = convertersByName; } public void setCompassConfiguration(CompassConfiguration config) { this.config = config; } public void afterPropertiesSet() throws Exception { CompassConfiguration config = this.config; if (config == null) { config = newConfiguration(); } if (classLoader != null) { config.setClassLoader(getClassLoader()); } if (this.configLocation != null) { config.configure(this.configLocation.getURL()); } if (this.configLocations != null) { for (Resource configLocation1 : configLocations) { config.configure(configLocation1.getURL()); } } if (this.mappingScan != null) { config.addScan(this.mappingScan); } if (this.compassSettings != null) { config.getSettings().addSettings(this.compassSettings); } if (this.settings != null) { config.getSettings().addSettings(this.settings); } if (resourceLocations != null) { for (Resource resourceLocation : resourceLocations) { config.addInputStream(resourceLocation.getInputStream(), resourceLocation.getFilename()); } } if (resourceJarLocations != null) { for (Resource resourceJarLocation : resourceJarLocations) { config.addJar(resourceJarLocation.getFile()); } } if (classMappings != null) { for (String classMapping : classMappings) { config.addClass(ClassUtils.forName(classMapping, getClassLoader())); } } if (resourceDirectoryLocations != null) { for (Resource resourceDirectoryLocation : resourceDirectoryLocations) { File file = resourceDirectoryLocation.getFile(); if (!file.isDirectory()) { throw new IllegalArgumentException("Resource directory location [" + resourceDirectoryLocation + "] does not denote a directory"); } config.addDirectory(file); } } if (mappingResolvers != null) { for (InputStreamMappingResolver mappingResolver : mappingResolvers) { config.addMappingResover(mappingResolver); } } if (dataSource != null) { ExternalDataSourceProvider.setDataSource(dataSource); if (config.getSettings().getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.CLASS) == null) { config.getSettings().setSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.CLASS, ExternalDataSourceProvider.class.getName()); } } String compassTransactionFactory = config.getSettings().getSetting(CompassEnvironment.Transaction.FACTORY); if (compassTransactionFactory == null && transactionManager != null) { // if the transaciton manager is set and a transcation factory is not set, default to the SpringSync one. config.getSettings().setSetting(CompassEnvironment.Transaction.FACTORY, SpringSyncTransactionFactory.class.getName()); } if (compassTransactionFactory != null && compassTransactionFactory.equals(SpringSyncTransactionFactory.class.getName())) { if (transactionManager == null) { throw new IllegalArgumentException("When using SpringSyncTransactionFactory the transactionManager property must be set"); } } SpringSyncTransactionFactory.setTransactionManager(transactionManager); if (convertersByName != null) { for (Map.Entry<String, Converter> entry : convertersByName.entrySet()) { config.registerConverter(entry.getKey(), entry.getValue()); } } if (config.getSettings().getSetting(CompassEnvironment.NAME) == null) { config.getSettings().setSetting(CompassEnvironment.NAME, beanName); } if (config.getSettings().getSetting(CompassEnvironment.CONNECTION) == null && connection != null) { config.getSettings().setSetting(CompassEnvironment.CONNECTION, connection.getFile().getAbsolutePath()); } if (applicationContext != null) { String[] names = applicationContext.getBeanNamesForType(PropertyPlaceholderConfigurer.class); for (String name : names) { try { PropertyPlaceholderConfigurer propConfigurer = (PropertyPlaceholderConfigurer) applicationContext.getBean(name); Method method = findMethod(propConfigurer.getClass(), "mergeProperties"); method.setAccessible(true); Properties props = (Properties) method.invoke(propConfigurer); method = findMethod(propConfigurer.getClass(), "convertProperties", Properties.class); method.setAccessible(true); method.invoke(propConfigurer, props); method = findMethod(propConfigurer.getClass(), "parseStringValue", String.class, Properties.class, Set.class); method.setAccessible(true); String nullValue = null; try { Field field = propConfigurer.getClass().getDeclaredField("nullValue"); field.setAccessible(true); nullValue = (String) field.get(propConfigurer); } catch (NoSuchFieldException e) { // no field (old spring version) } for (Map.Entry entry : config.getSettings().getProperties().entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); value = (String) method.invoke(propConfigurer, value, props, new HashSet()); config.getSettings().setSetting(key, value.equals(nullValue) ? null : value); } } catch (Exception e) { log.debug("Failed to apply property placeholder defined in bean [" + name + "]", e); } } } if (postProcessor != null) { postProcessor.process(config); } this.compass = newCompass(config); this.compass = (Compass) Proxy.newProxyInstance(SpringCompassInvocationHandler.class.getClassLoader(), new Class[]{InternalCompass.class}, new SpringCompassInvocationHandler(this.compass)); } protected CompassConfiguration newConfiguration() { return CompassConfigurationFactory.newConfiguration(); } protected Compass newCompass(CompassConfiguration config) throws CompassException { return config.buildCompass(); } public Object getObject() throws Exception { return this.compass; } public Class getObjectType() { return (compass != null) ? compass.getClass() : Compass.class; } public boolean isSingleton() { return true; } public void destroy() throws Exception { this.compass.close(); } protected ClassLoader getClassLoader() { if (classLoader != null) { return classLoader; } return Thread.currentThread().getContextClassLoader(); } private Method findMethod(Class clazz, String methodName, Class ... parameterTypes) { if (clazz.equals(Object.class)) { return null; } try { return clazz.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { return findMethod(clazz.getSuperclass(), methodName, parameterTypes); } } /** * Invocation handler that handles close methods. */ private class SpringCompassInvocationHandler implements InvocationHandler { private static final String GET_TARGET_COMPASS_METHOD_NAME = "getTargetCompass"; private static final String CLONE_METHOD = "clone"; private Compass targetCompass; public SpringCompassInvocationHandler(Compass targetCompass) { this.targetCompass = targetCompass; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on ConnectionProxy interface coming in... if (method.getName().equals(GET_TARGET_COMPASS_METHOD_NAME)) { return compass; } if (method.getName().equals(CLONE_METHOD) && args.length == 1) { if (dataSource != null) { ExternalDataSourceProvider.setDataSource(dataSource); } SpringSyncTransactionFactory.setTransactionManager(transactionManager); } // Invoke method on target connection. try { return method.invoke(targetCompass, args); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } } }
src/main/src/org/compass/spring/LocalCompassBean.java
/* * Copyright 2004-2006 the original author or authors. * * 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. */ package org.compass.spring; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.compass.core.Compass; import org.compass.core.CompassException; import org.compass.core.config.CompassConfiguration; import org.compass.core.config.CompassConfigurationFactory; import org.compass.core.config.CompassEnvironment; import org.compass.core.config.InputStreamMappingResolver; import org.compass.core.converter.Converter; import org.compass.core.lucene.LuceneEnvironment; import org.compass.core.lucene.engine.store.jdbc.ExternalDataSourceProvider; import org.compass.core.spi.InternalCompass; import org.compass.core.util.ClassUtils; import org.compass.spring.transaction.SpringSyncTransactionFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.io.Resource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.transaction.PlatformTransactionManager; /** * @author kimchy */ public class LocalCompassBean implements FactoryBean, InitializingBean, DisposableBean, BeanNameAware, ApplicationContextAware { protected static final Log log = LogFactory.getLog(LocalCompassBean.class); private Resource connection; private Resource configLocation; private String mappingScan; private Resource[] configLocations; private Resource[] resourceLocations; private Resource[] resourceJarLocations; private Resource[] resourceDirectoryLocations; private String[] classMappings; private InputStreamMappingResolver[] mappingResolvers; private Properties compassSettings; private Map<String, Object> settings; private DataSource dataSource; private PlatformTransactionManager transactionManager; private Map<String, Converter> convertersByName; private Compass compass; private String beanName; private ApplicationContext applicationContext; private CompassConfiguration config; private LocalCompassBeanPostProcessor postProcessor; /** * Allows to register a post processor for the Compass configuration. */ public void setPostProcessor(LocalCompassBeanPostProcessor postProcessor) { this.postProcessor = postProcessor; } public void setBeanName(String beanName) { this.beanName = beanName; } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } /** * Sets an optional connection based on Spring <code>Resource</code> * abstraction. Will be used if none is set as part of other possible * configuration of Compass connection. * <p/> * Will use <code>Resource#getFile</code> in order to get the absolute * path. */ public void setConnection(Resource connection) { this.connection = connection; } /** * Set the location of the Compass XML config file, for example as classpath * resource "classpath:compass.cfg.xml". * <p/> * Note: Can be omitted when all necessary properties and mapping resources * are specified locally via this bean. */ public void setConfigLocation(Resource configLocation) { this.configLocation = configLocation; } /** * Set the location of the Compass XML config file, for example as classpath * resource "classpath:compass.cfg.xml". * <p/> * Note: Can be omitted when all necessary properties and mapping resources * are specified locally via this bean. */ public void setConfigLocations(Resource[] configLocations) { this.configLocations = configLocations; } /** * @see org.compass.core.config.CompassConfiguration#addScan(String) */ public void setMappingScan(String basePackage) { this.mappingScan = basePackage; } public void setCompassSettings(Properties compassSettings) { this.compassSettings = compassSettings; } public void setSettings(Map<String, Object> settings) { this.settings = settings; } /** * Set locations of Compass resource files (mapping and common metadata), * for example as classpath resource "classpath:example.cpm.xml". Supports * any resource location via Spring's resource abstraction, for example * relative paths like "WEB-INF/mappings/example.hbm.xml" when running in an * application context. * <p/> * Can be used to add to mappings from a Compass XML config file, or to * specify all mappings locally. */ public void setResourceLocations(Resource[] resourceLocations) { this.resourceLocations = resourceLocations; } /** * Set locations of jar files that contain Compass resources, like * "WEB-INF/lib/example.jar". * <p/> * Can be used to add to mappings from a Compass XML config file, or to * specify all mappings locally. */ public void setResourceJarLocations(Resource[] resourceJarLocations) { this.resourceJarLocations = resourceJarLocations; } /** * Set locations of directories that contain Compass mapping resources, like * "WEB-INF/mappings". * <p/> * Can be used to add to mappings from a Compass XML config file, or to * specify all mappings locally. */ public void setResourceDirectoryLocations(Resource[] resourceDirectoryLocations) { this.resourceDirectoryLocations = resourceDirectoryLocations; } /** * Sets the fully qualified class names for mappings. Useful when using annotations * for example. Will also try to load the matching "[Class].cpm.xml" file. */ public void setClassMappings(String[] classMappings) { this.classMappings = classMappings; } /** * Sets the mapping resolvers the resolved Compass mapping definitions. */ public void setMappingResolvers(InputStreamMappingResolver[] mappingResolvers) { this.mappingResolvers = mappingResolvers; } /** * Sets a <code>DataSource</code> to be used when the index is stored within a database. * The data source must be used with {@link org.compass.core.lucene.engine.store.jdbc.ExternalDataSourceProvider} * for externally configured data sources (such is the case some of the time with spring). If set, Compass data source provider * does not have to be set, since it will automatically default to <code>ExternalDataSourceProvider</code>. If the * compass data source provider is set as a compass setting, it will be used. * <p/> * Note, that it will be automatically wrapped with Spring's <literal>TransactionAwareDataSourceProxy</literal> if not * already wrapped by one. * {@link org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy}. * <p/> * Also note that setting the data source is not enough to configure Compass to store the index * within the database, the Compass connection string should also be set to <code>jdbc://</code>. */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; if (!(dataSource instanceof TransactionAwareDataSourceProxy)) { this.dataSource = new TransactionAwareDataSourceProxy(dataSource); } } /** * Sets Spring <code>PlatformTransactionManager</code> to be used with compass. If using * {@link org.compass.spring.transaction.SpringSyncTransactionFactory}, it must be set. */ public void setTransactionManager(PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } /** * Sets a map of global converters to be registered with compass. The map key will be * the name that the converter will be registered against, and the value should be the * Converter itself (natuarally configured using spring DI). */ public void setConvertersByName(Map<String, Converter> convertersByName) { this.convertersByName = convertersByName; } public void setCompassConfiguration(CompassConfiguration config) { this.config = config; } public void afterPropertiesSet() throws Exception { CompassConfiguration config = this.config; if (config == null) { config = newConfiguration(); } if (this.configLocation != null) { config.configure(this.configLocation.getURL()); } if (this.configLocations != null) { for (Resource configLocation1 : configLocations) { config.configure(configLocation1.getURL()); } } if (this.mappingScan != null) { config.addScan(this.mappingScan); } if (this.compassSettings != null) { config.getSettings().addSettings(this.compassSettings); } if (this.settings != null) { config.getSettings().addSettings(this.settings); } if (resourceLocations != null) { for (Resource resourceLocation : resourceLocations) { config.addInputStream(resourceLocation.getInputStream(), resourceLocation.getFilename()); } } if (resourceJarLocations != null) { for (Resource resourceJarLocation : resourceJarLocations) { config.addJar(resourceJarLocation.getFile()); } } if (classMappings != null) { for (String classMapping : classMappings) { config.addClass(ClassUtils.forName(classMapping, getClassLoader())); } } if (resourceDirectoryLocations != null) { for (Resource resourceDirectoryLocation : resourceDirectoryLocations) { File file = resourceDirectoryLocation.getFile(); if (!file.isDirectory()) { throw new IllegalArgumentException("Resource directory location [" + resourceDirectoryLocation + "] does not denote a directory"); } config.addDirectory(file); } } if (mappingResolvers != null) { for (InputStreamMappingResolver mappingResolver : mappingResolvers) { config.addMappingResover(mappingResolver); } } if (dataSource != null) { ExternalDataSourceProvider.setDataSource(dataSource); if (config.getSettings().getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.CLASS) == null) { config.getSettings().setSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.CLASS, ExternalDataSourceProvider.class.getName()); } } String compassTransactionFactory = config.getSettings().getSetting(CompassEnvironment.Transaction.FACTORY); if (compassTransactionFactory == null && transactionManager != null) { // if the transaciton manager is set and a transcation factory is not set, default to the SpringSync one. config.getSettings().setSetting(CompassEnvironment.Transaction.FACTORY, SpringSyncTransactionFactory.class.getName()); } if (compassTransactionFactory != null && compassTransactionFactory.equals(SpringSyncTransactionFactory.class.getName())) { if (transactionManager == null) { throw new IllegalArgumentException("When using SpringSyncTransactionFactory the transactionManager property must be set"); } } SpringSyncTransactionFactory.setTransactionManager(transactionManager); if (convertersByName != null) { for (Map.Entry<String, Converter> entry : convertersByName.entrySet()) { config.registerConverter(entry.getKey(), entry.getValue()); } } if (config.getSettings().getSetting(CompassEnvironment.NAME) == null) { config.getSettings().setSetting(CompassEnvironment.NAME, beanName); } if (config.getSettings().getSetting(CompassEnvironment.CONNECTION) == null && connection != null) { config.getSettings().setSetting(CompassEnvironment.CONNECTION, connection.getFile().getAbsolutePath()); } if (applicationContext != null) { String[] names = applicationContext.getBeanNamesForType(PropertyPlaceholderConfigurer.class); for (String name : names) { try { PropertyPlaceholderConfigurer propConfigurer = (PropertyPlaceholderConfigurer) applicationContext.getBean(name); Method method = findMethod(propConfigurer.getClass(), "mergeProperties"); method.setAccessible(true); Properties props = (Properties) method.invoke(propConfigurer); method = findMethod(propConfigurer.getClass(), "convertProperties", Properties.class); method.setAccessible(true); method.invoke(propConfigurer, props); method = findMethod(propConfigurer.getClass(), "parseStringValue", String.class, Properties.class, Set.class); method.setAccessible(true); String nullValue = null; try { Field field = propConfigurer.getClass().getDeclaredField("nullValue"); field.setAccessible(true); nullValue = (String) field.get(propConfigurer); } catch (NoSuchFieldException e) { // no field (old spring version) } for (Map.Entry entry : config.getSettings().getProperties().entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); value = (String) method.invoke(propConfigurer, value, props, new HashSet()); config.getSettings().setSetting(key, value.equals(nullValue) ? null : value); } } catch (Exception e) { log.debug("Failed to apply property placeholder defined in bean [" + name + "]", e); } } } if (postProcessor != null) { postProcessor.process(config); } this.compass = newCompass(config); this.compass = (Compass) Proxy.newProxyInstance(SpringCompassInvocationHandler.class.getClassLoader(), new Class[]{InternalCompass.class}, new SpringCompassInvocationHandler(this.compass)); } protected CompassConfiguration newConfiguration() { return CompassConfigurationFactory.newConfiguration(); } protected Compass newCompass(CompassConfiguration config) throws CompassException { return config.buildCompass(); } public Object getObject() throws Exception { return this.compass; } public Class getObjectType() { return (compass != null) ? compass.getClass() : Compass.class; } public boolean isSingleton() { return true; } public void destroy() throws Exception { this.compass.close(); } protected ClassLoader getClassLoader() { return Thread.currentThread().getContextClassLoader(); } private Method findMethod(Class clazz, String methodName, Class ... parameterTypes) { if (clazz.equals(Object.class)) { return null; } try { return clazz.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { return findMethod(clazz.getSuperclass(), methodName, parameterTypes); } } /** * Invocation handler that handles close methods. */ private class SpringCompassInvocationHandler implements InvocationHandler { private static final String GET_TARGET_COMPASS_METHOD_NAME = "getTargetCompass"; private static final String CLONE_METHOD = "clone"; private Compass targetCompass; public SpringCompassInvocationHandler(Compass targetCompass) { this.targetCompass = targetCompass; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on ConnectionProxy interface coming in... if (method.getName().equals(GET_TARGET_COMPASS_METHOD_NAME)) { return compass; } if (method.getName().equals(CLONE_METHOD) && args.length == 1) { if (dataSource != null) { ExternalDataSourceProvider.setDataSource(dataSource); } SpringSyncTransactionFactory.setTransactionManager(transactionManager); } // Invoke method on target connection. try { return method.invoke(targetCompass, args); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } } }
CMP-735 LocalCompassBean MUST implement org.springframework.beans.factory.BeanClassLoaderAware
src/main/src/org/compass/spring/LocalCompassBean.java
CMP-735 LocalCompassBean MUST implement org.springframework.beans.factory.BeanClassLoaderAware
<ide><path>rc/main/src/org/compass/spring/LocalCompassBean.java <ide> import org.compass.core.util.ClassUtils; <ide> import org.compass.spring.transaction.SpringSyncTransactionFactory; <ide> import org.springframework.beans.BeansException; <add>import org.springframework.beans.factory.BeanClassLoaderAware; <ide> import org.springframework.beans.factory.BeanNameAware; <ide> import org.springframework.beans.factory.DisposableBean; <ide> import org.springframework.beans.factory.FactoryBean; <ide> /** <ide> * @author kimchy <ide> */ <del>public class LocalCompassBean implements FactoryBean, InitializingBean, DisposableBean, BeanNameAware, ApplicationContextAware { <add>public class LocalCompassBean implements FactoryBean, InitializingBean, DisposableBean, BeanNameAware, ApplicationContextAware, BeanClassLoaderAware { <ide> <ide> protected static final Log log = LogFactory.getLog(LocalCompassBean.class); <ide> <ide> private Compass compass; <ide> <ide> private String beanName; <add> <add> private ClassLoader classLoader; <ide> <ide> private ApplicationContext applicationContext; <ide> <ide> <ide> public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { <ide> this.applicationContext = applicationContext; <add> } <add> <add> public void setBeanClassLoader(ClassLoader classLoader) { <add> this.classLoader = classLoader; <ide> } <ide> <ide> /** <ide> CompassConfiguration config = this.config; <ide> if (config == null) { <ide> config = newConfiguration(); <add> } <add> <add> if (classLoader != null) { <add> config.setClassLoader(getClassLoader()); <ide> } <ide> <ide> if (this.configLocation != null) { <ide> } <ide> <ide> protected ClassLoader getClassLoader() { <add> if (classLoader != null) { <add> return classLoader; <add> } <ide> return Thread.currentThread().getContextClassLoader(); <ide> } <ide>
Java
apache-2.0
33f08c8a9258d371fe5b3ef03f38ce78466f44fc
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
package de.plushnikov.intellij.plugin.util; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiAnnotation; import com.intellij.psi.PsiAnnotationOwner; import com.intellij.psi.PsiJavaCodeReferenceElement; import com.intellij.psi.PsiModifierList; import com.intellij.psi.PsiModifierListOwner; import com.intellij.psi.impl.source.SourceJavaCodeReference; import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.regex.Pattern; public class PsiAnnotationSearchUtil { private static final Key<String> LOMBOK_ANNOTATION_FQN_KEY = Key.create("LOMBOK_ANNOTATION_FQN"); @Nullable public static PsiAnnotation findAnnotation(@NotNull PsiModifierListOwner psiModifierListOwner, @NotNull String annotationFQN) { return findAnnotationQuick(psiModifierListOwner.getModifierList(), annotationFQN); } @Nullable public static PsiAnnotation findAnnotation(@NotNull PsiModifierListOwner psiModifierListOwner, @NotNull final Class<? extends Annotation> annotationType) { return findAnnotationQuick(psiModifierListOwner.getModifierList(), annotationType.getName()); } @Nullable public static PsiAnnotation findAnnotation(@NotNull PsiModifierListOwner psiModifierListOwner, @NotNull final Class<? extends Annotation>... annotationTypes) { if (annotationTypes.length == 1) { return findAnnotation(psiModifierListOwner, annotationTypes[0]); } final String[] qualifiedNames = new String[annotationTypes.length]; for (int i = 0; i < annotationTypes.length; i++) { qualifiedNames[i] = annotationTypes[i].getName(); } return findAnnotationQuick(psiModifierListOwner.getModifierList(), qualifiedNames); } @Nullable private static PsiAnnotation findAnnotationQuick(@Nullable PsiAnnotationOwner annotationOwner, @NotNull String qualifiedName) { if (annotationOwner == null) { return null; } PsiAnnotation[] annotations = annotationOwner.getAnnotations(); if (annotations.length == 0) { return null; } final String shortName = StringUtil.getShortName(qualifiedName); for (PsiAnnotation annotation : annotations) { PsiJavaCodeReferenceElement referenceElement = annotation.getNameReferenceElement(); if (null != referenceElement) { final String referenceName = referenceElement.getReferenceName(); if (shortName.equals(referenceName)) { if (referenceElement.isQualified() && referenceElement instanceof SourceJavaCodeReference) { String possibleFullQualifiedName = ((SourceJavaCodeReference) referenceElement).getClassNameText(); if (qualifiedName.equals(possibleFullQualifiedName)) { return annotation; } } final String annotationQualifiedName = getAndCacheFQN(annotation, referenceName); if (qualifiedName.equals(annotationQualifiedName)) { return annotation; } } } } return null; } @Nullable private static PsiAnnotation findAnnotationQuick(@Nullable PsiAnnotationOwner annotationOwner, @NotNull String... qualifiedNames) { if (annotationOwner == null || qualifiedNames.length == 0) { return null; } PsiAnnotation[] annotations = annotationOwner.getAnnotations(); if (annotations.length == 0) { return null; } final String[] shortNames = new String[qualifiedNames.length]; for (int i = 0; i < qualifiedNames.length; i++) { shortNames[i] = StringUtil.getShortName(qualifiedNames[i]); } for (PsiAnnotation annotation : annotations) { final PsiJavaCodeReferenceElement referenceElement = annotation.getNameReferenceElement(); if (null != referenceElement) { final String referenceName = referenceElement.getReferenceName(); if (ArrayUtil.find(shortNames, referenceName) > -1) { if (referenceElement.isQualified() && referenceElement instanceof SourceJavaCodeReference) { final String possibleFullQualifiedName = ((SourceJavaCodeReference) referenceElement).getClassNameText(); if (ArrayUtil.find(qualifiedNames, possibleFullQualifiedName) > -1) { return annotation; } } final String annotationQualifiedName = getAndCacheFQN(annotation, referenceName); if (ArrayUtil.find(qualifiedNames, annotationQualifiedName) > -1) { return annotation; } } } } return null; } @Nullable private static String getAndCacheFQN(@NotNull PsiAnnotation annotation, @Nullable String referenceName) { String annotationQualifiedName = annotation.getCopyableUserData(LOMBOK_ANNOTATION_FQN_KEY); // if not cached or cache is not up to date (because existing annotation was renamed for example) if (null == annotationQualifiedName || (null != referenceName && !annotationQualifiedName.endsWith(".".concat(referenceName)))) { annotationQualifiedName = annotation.getQualifiedName(); if (null != annotationQualifiedName && annotationQualifiedName.indexOf('.') > -1) { annotation.putCopyableUserData(LOMBOK_ANNOTATION_FQN_KEY, annotationQualifiedName); } } return annotationQualifiedName; } public static boolean isAnnotatedWith(@NotNull PsiModifierListOwner psiModifierListOwner, @NotNull final Class<? extends Annotation> annotationType) { return null != findAnnotation(psiModifierListOwner, annotationType); } public static boolean isNotAnnotatedWith(@NotNull PsiModifierListOwner psiModifierListOwner, @NotNull final Class<? extends Annotation> annotationType) { return !isAnnotatedWith(psiModifierListOwner, annotationType); } public static boolean isAnnotatedWith(@NotNull PsiModifierListOwner psiModifierListOwner, @NotNull final Class<? extends Annotation>... annotationTypes) { return null != findAnnotation(psiModifierListOwner, annotationTypes); } public static boolean isNotAnnotatedWith(@NotNull PsiModifierListOwner psiModifierListOwner, @NotNull final Class<? extends Annotation>... annotationTypes) { return !isAnnotatedWith(psiModifierListOwner, annotationTypes); } public static boolean isAnnotatedWith(@NotNull PsiModifierListOwner psiModifierListOwner, @NotNull final Pattern annotationPattern) { final PsiModifierList psiModifierList = psiModifierListOwner.getModifierList(); if (psiModifierList != null) { for (PsiAnnotation psiAnnotation : psiModifierList.getAnnotations()) { final String suspect = getSimpleNameOf(psiAnnotation); if (annotationPattern.matcher(suspect).matches()) { return true; } } } return false; } @NotNull public static String getSimpleNameOf(@NotNull PsiAnnotation psiAnnotation) { PsiJavaCodeReferenceElement referenceElement = psiAnnotation.getNameReferenceElement(); return StringUtil.notNullize(null == referenceElement ? null : referenceElement.getReferenceName()); } public static boolean checkAnnotationsSimpleNameExistsIn(@NotNull PsiModifierListOwner modifierListOwner, @NotNull Collection<String> annotationNames) { final PsiModifierList modifierList = modifierListOwner.getModifierList(); if (null != modifierList) { for (PsiAnnotation psiAnnotation : modifierList.getAnnotations()) { final String simpleName = getSimpleNameOf(psiAnnotation); if (annotationNames.contains(simpleName)) { return true; } } } return false; } }
plugins/lombok/src/main/java/de/plushnikov/intellij/plugin/util/PsiAnnotationSearchUtil.java
package de.plushnikov.intellij.plugin.util; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiAnnotation; import com.intellij.psi.PsiAnnotationOwner; import com.intellij.psi.PsiJavaCodeReferenceElement; import com.intellij.psi.PsiModifierList; import com.intellij.psi.PsiModifierListOwner; import com.intellij.psi.impl.source.SourceJavaCodeReference; import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.regex.Pattern; public class PsiAnnotationSearchUtil { private static final Key<String> LOMBOK_ANNOTATION_FQN_KEY = Key.create("LOMBOK_ANNOTATION_FQN"); @Nullable public static PsiAnnotation findAnnotation(@NotNull PsiModifierListOwner psiModifierListOwner, @NotNull String annotationFQN) { return findAnnotationQuick(psiModifierListOwner.getModifierList(), annotationFQN); } @Nullable public static PsiAnnotation findAnnotation(@NotNull PsiModifierListOwner psiModifierListOwner, @NotNull final Class<? extends Annotation> annotationType) { return findAnnotationQuick(psiModifierListOwner.getModifierList(), annotationType.getName()); } @Nullable public static PsiAnnotation findAnnotation(@NotNull PsiModifierListOwner psiModifierListOwner, @NotNull final Class<? extends Annotation>... annotationTypes) { if (annotationTypes.length == 1) { return findAnnotation(psiModifierListOwner, annotationTypes[0]); } final String[] qualifiedNames = new String[annotationTypes.length]; for (int i = 0; i < annotationTypes.length; i++) { qualifiedNames[i] = annotationTypes[i].getName(); } return findAnnotationQuick(psiModifierListOwner.getModifierList(), qualifiedNames); } @Nullable private static PsiAnnotation findAnnotationQuick(@Nullable PsiAnnotationOwner annotationOwner, @NotNull String qualifiedName) { if (annotationOwner == null) { return null; } PsiAnnotation[] annotations = annotationOwner.getAnnotations(); if (annotations.length == 0) { return null; } final String shortName = StringUtil.getShortName(qualifiedName); for (PsiAnnotation annotation : annotations) { PsiJavaCodeReferenceElement referenceElement = annotation.getNameReferenceElement(); if (null != referenceElement) { if (shortName.equals(referenceElement.getReferenceName())) { if (referenceElement.isQualified() && referenceElement instanceof SourceJavaCodeReference) { String possibleFullQualifiedName = ((SourceJavaCodeReference) referenceElement).getClassNameText(); if (qualifiedName.equals(possibleFullQualifiedName)) { return annotation; } } final String annotationQualifiedName = getAndCacheFQN(annotation); if (qualifiedName.equals(annotationQualifiedName)) { return annotation; } } } } return null; } @Nullable private static PsiAnnotation findAnnotationQuick(@Nullable PsiAnnotationOwner annotationOwner, @NotNull String... qualifiedNames) { if (annotationOwner == null || qualifiedNames.length == 0) { return null; } PsiAnnotation[] annotations = annotationOwner.getAnnotations(); if (annotations.length == 0) { return null; } final String[] shortNames = new String[qualifiedNames.length]; for (int i = 0; i < qualifiedNames.length; i++) { shortNames[i] = StringUtil.getShortName(qualifiedNames[i]); } for (PsiAnnotation annotation : annotations) { final PsiJavaCodeReferenceElement referenceElement = annotation.getNameReferenceElement(); if (null != referenceElement) { if (ArrayUtil.find(shortNames, referenceElement.getReferenceName()) > -1) { if (referenceElement.isQualified() && referenceElement instanceof SourceJavaCodeReference) { final String possibleFullQualifiedName = ((SourceJavaCodeReference) referenceElement).getClassNameText(); if (ArrayUtil.find(qualifiedNames, possibleFullQualifiedName) > -1) { return annotation; } } final String annotationQualifiedName = getAndCacheFQN(annotation); if (ArrayUtil.find(qualifiedNames, annotationQualifiedName) > -1) { return annotation; } } } } return null; } @Nullable private static String getAndCacheFQN(PsiAnnotation annotation) { String annotationQualifiedName = annotation.getCopyableUserData(LOMBOK_ANNOTATION_FQN_KEY); if (null == annotationQualifiedName) { annotationQualifiedName = annotation.getQualifiedName(); if (null != annotationQualifiedName && annotationQualifiedName.indexOf('.') > -1) { annotation.putCopyableUserData(LOMBOK_ANNOTATION_FQN_KEY, annotationQualifiedName); } } return annotationQualifiedName; } public static boolean isAnnotatedWith(@NotNull PsiModifierListOwner psiModifierListOwner, @NotNull final Class<? extends Annotation> annotationType) { return null != findAnnotation(psiModifierListOwner, annotationType); } public static boolean isNotAnnotatedWith(@NotNull PsiModifierListOwner psiModifierListOwner, @NotNull final Class<? extends Annotation> annotationType) { return !isAnnotatedWith(psiModifierListOwner, annotationType); } public static boolean isAnnotatedWith(@NotNull PsiModifierListOwner psiModifierListOwner, @NotNull final Class<? extends Annotation>... annotationTypes) { return null != findAnnotation(psiModifierListOwner, annotationTypes); } public static boolean isNotAnnotatedWith(@NotNull PsiModifierListOwner psiModifierListOwner, @NotNull final Class<? extends Annotation>... annotationTypes) { return !isAnnotatedWith(psiModifierListOwner, annotationTypes); } public static boolean isAnnotatedWith(@NotNull PsiModifierListOwner psiModifierListOwner, @NotNull final Pattern annotationPattern) { final PsiModifierList psiModifierList = psiModifierListOwner.getModifierList(); if (psiModifierList != null) { for (PsiAnnotation psiAnnotation : psiModifierList.getAnnotations()) { final String suspect = getSimpleNameOf(psiAnnotation); if (annotationPattern.matcher(suspect).matches()) { return true; } } } return false; } @NotNull public static String getSimpleNameOf(@NotNull PsiAnnotation psiAnnotation) { PsiJavaCodeReferenceElement referenceElement = psiAnnotation.getNameReferenceElement(); return StringUtil.notNullize(null == referenceElement ? null : referenceElement.getReferenceName()); } public static boolean checkAnnotationsSimpleNameExistsIn(@NotNull PsiModifierListOwner modifierListOwner, @NotNull Collection<String> annotationNames) { final PsiModifierList modifierList = modifierListOwner.getModifierList(); if (null != modifierList) { for (PsiAnnotation psiAnnotation : modifierList.getAnnotations()) { final String simpleName = getSimpleNameOf(psiAnnotation); if (annotationNames.contains(simpleName)) { return true; } } } return false; } }
Recalculate cached FQN if annotation name changed Fixed #210, #270, #423 GitOrigin-RevId: 37c2f4f23ff1722541cd99e77195369a3087ffa9
plugins/lombok/src/main/java/de/plushnikov/intellij/plugin/util/PsiAnnotationSearchUtil.java
Recalculate cached FQN if annotation name changed Fixed #210, #270, #423
<ide><path>lugins/lombok/src/main/java/de/plushnikov/intellij/plugin/util/PsiAnnotationSearchUtil.java <ide> for (PsiAnnotation annotation : annotations) { <ide> PsiJavaCodeReferenceElement referenceElement = annotation.getNameReferenceElement(); <ide> if (null != referenceElement) { <del> if (shortName.equals(referenceElement.getReferenceName())) { <add> final String referenceName = referenceElement.getReferenceName(); <add> if (shortName.equals(referenceName)) { <ide> <ide> if (referenceElement.isQualified() && referenceElement instanceof SourceJavaCodeReference) { <ide> String possibleFullQualifiedName = ((SourceJavaCodeReference) referenceElement).getClassNameText(); <ide> } <ide> } <ide> <del> final String annotationQualifiedName = getAndCacheFQN(annotation); <add> final String annotationQualifiedName = getAndCacheFQN(annotation, referenceName); <ide> if (qualifiedName.equals(annotationQualifiedName)) { <ide> return annotation; <ide> } <ide> for (PsiAnnotation annotation : annotations) { <ide> final PsiJavaCodeReferenceElement referenceElement = annotation.getNameReferenceElement(); <ide> if (null != referenceElement) { <del> if (ArrayUtil.find(shortNames, referenceElement.getReferenceName()) > -1) { <add> final String referenceName = referenceElement.getReferenceName(); <add> if (ArrayUtil.find(shortNames, referenceName) > -1) { <ide> <ide> if (referenceElement.isQualified() && referenceElement instanceof SourceJavaCodeReference) { <ide> final String possibleFullQualifiedName = ((SourceJavaCodeReference) referenceElement).getClassNameText(); <ide> } <ide> } <ide> <del> final String annotationQualifiedName = getAndCacheFQN(annotation); <add> final String annotationQualifiedName = getAndCacheFQN(annotation, referenceName); <ide> if (ArrayUtil.find(qualifiedNames, annotationQualifiedName) > -1) { <ide> return annotation; <ide> } <ide> } <ide> <ide> @Nullable <del> private static String getAndCacheFQN(PsiAnnotation annotation) { <add> private static String getAndCacheFQN(@NotNull PsiAnnotation annotation, @Nullable String referenceName) { <ide> String annotationQualifiedName = annotation.getCopyableUserData(LOMBOK_ANNOTATION_FQN_KEY); <del> if (null == annotationQualifiedName) { <add> // if not cached or cache is not up to date (because existing annotation was renamed for example) <add> if (null == annotationQualifiedName || (null != referenceName && !annotationQualifiedName.endsWith(".".concat(referenceName)))) { <ide> annotationQualifiedName = annotation.getQualifiedName(); <ide> if (null != annotationQualifiedName && annotationQualifiedName.indexOf('.') > -1) { <ide> annotation.putCopyableUserData(LOMBOK_ANNOTATION_FQN_KEY, annotationQualifiedName);
Java
mit
3ffd891e436f52dd7249496ce240699aa7aa43e9
0
elancom/jvm.go,elancom/jvm.go,zxh0/jvm.go,rednaxelafx/jvm.go,zxh0/jvm.go,rednaxelafx/jvm.go,rednaxelafx/jvm.go,zxh0/jvm.go,elancom/jvm.go
public class ThreadTest { public static void main(String[] args) { new Thread();//.start(); } }
testclasses/src/main/java/ThreadTest.java
public class ThreadTest { public static void main(String[] args) { new Thread().start(); } }
add ThreadTest.java
testclasses/src/main/java/ThreadTest.java
add ThreadTest.java
<ide><path>estclasses/src/main/java/ThreadTest.java <ide> public class ThreadTest { <ide> <ide> public static void main(String[] args) { <del> new Thread().start(); <add> new Thread();//.start(); <ide> } <ide> <ide> }
JavaScript
mit
d7641e5bcc3c63e45842bc95726c63509c3d6b65
0
sindresorhus/got,floatdrop/got
'use strict'; const util = require('util'); const EventEmitter = require('events'); const http = require('http'); const https = require('https'); const {PassThrough, Transform} = require('stream'); const urlLib = require('url'); const fs = require('fs'); const querystring = require('querystring'); const CacheableRequest = require('cacheable-request'); const duplexer3 = require('duplexer3'); const toReadableStream = require('to-readable-stream'); const is = require('@sindresorhus/is'); const getStream = require('get-stream'); const timedOut = require('timed-out'); const urlParseLax = require('url-parse-lax'); const urlToOptions = require('url-to-options'); const lowercaseKeys = require('lowercase-keys'); const decompressResponse = require('decompress-response'); const mimicResponse = require('mimic-response'); const isRetryAllowed = require('is-retry-allowed'); const isURL = require('isurl'); const PCancelable = require('p-cancelable'); const pTimeout = require('p-timeout'); const pkg = require('./package.json'); const errors = require('./errors'); const getMethodRedirectCodes = new Set([300, 301, 302, 303, 304, 305, 307, 308]); const allMethodRedirectCodes = new Set([300, 303, 307, 308]); const isFormData = body => is.nodeStream(body) && is.function(body.getBoundary); const getBodySize = async opts => { const {body} = opts; if (opts.headers['content-length']) { return Number(opts.headers['content-length']); } if (!body && !opts.stream) { return 0; } if (is.string(body)) { return Buffer.byteLength(body); } if (isFormData(body)) { return util.promisify(body.getLength.bind(body))(); } if (body instanceof fs.ReadStream) { const {size} = await util.promisify(fs.stat)(body.path); return size; } if (is.nodeStream(body) && is.buffer(body._buffer)) { return body._buffer.length; } return null; }; function requestAsEventEmitter(opts) { opts = opts || {}; const ee = new EventEmitter(); const requestUrl = opts.href || urlLib.resolve(urlLib.format(opts), opts.path); const redirects = []; const agents = is.object(opts.agent) ? opts.agent : null; let retryCount = 0; let redirectUrl; let uploadBodySize; let uploaded = 0; const get = opts => { if (opts.protocol !== 'http:' && opts.protocol !== 'https:') { ee.emit('error', new got.UnsupportedProtocolError(opts)); return; } let fn = opts.protocol === 'https:' ? https : http; if (agents) { const protocolName = opts.protocol === 'https:' ? 'https' : 'http'; opts.agent = agents[protocolName] || opts.agent; } if (opts.useElectronNet && process.versions.electron) { const electron = require('electron'); fn = electron.net || electron.remote.net; } let progressInterval; const cacheableRequest = new CacheableRequest(fn.request, opts.cache); const cacheReq = cacheableRequest(opts, res => { clearInterval(progressInterval); ee.emit('uploadProgress', { percent: 1, transferred: uploaded, total: uploadBodySize }); const {statusCode} = res; res.url = redirectUrl || requestUrl; res.requestUrl = requestUrl; const followRedirect = opts.followRedirect && 'location' in res.headers; const redirectGet = followRedirect && getMethodRedirectCodes.has(statusCode); const redirectAll = followRedirect && allMethodRedirectCodes.has(statusCode); if (redirectAll || (redirectGet && (opts.method === 'GET' || opts.method === 'HEAD'))) { res.resume(); if (statusCode === 303) { // Server responded with "see other", indicating that the resource exists at another location, // and the client should request it from that location via GET or HEAD. opts.method = 'GET'; } if (redirects.length >= 10) { ee.emit('error', new got.MaxRedirectsError(statusCode, redirects, opts), null, res); return; } const bufferString = Buffer.from(res.headers.location, 'binary').toString(); redirectUrl = urlLib.resolve(urlLib.format(opts), bufferString); redirects.push(redirectUrl); const redirectOpts = { ...opts, ...urlLib.parse(redirectUrl) }; ee.emit('redirect', res, redirectOpts); get(redirectOpts); return; } setImmediate(() => { try { getResponse(res, opts, ee, redirects); } catch (e) { ee.emit('error', e); } }); }); cacheReq.on('error', err => { if (err instanceof CacheableRequest.RequestError) { ee.emit('error', new got.RequestError(err, opts)); } else { ee.emit('error', new got.CacheError(err, opts)); } }); cacheReq.once('request', req => { let aborted = false; req.once('abort', _ => { aborted = true; }); req.once('error', err => { clearInterval(progressInterval); if (aborted) { return; } const backoff = opts.retries(++retryCount, err); if (backoff) { setTimeout(get, backoff, opts); return; } ee.emit('error', new got.RequestError(err, opts)); }); ee.once('request', req => { ee.emit('uploadProgress', { percent: 0, transferred: 0, total: uploadBodySize }); const socket = req.connection; if (socket) { const onSocketConnect = () => { const uploadEventFrequency = 150; progressInterval = setInterval(() => { if (socket.destroyed) { clearInterval(progressInterval); return; } const lastUploaded = uploaded; const headersSize = req._header ? Buffer.byteLength(req._header) : 0; uploaded = socket.bytesWritten - headersSize; // Prevent the known issue of `bytesWritten` being larger than body size if (uploadBodySize && uploaded > uploadBodySize) { uploaded = uploadBodySize; } // Don't emit events with unchanged progress and // prevent last event from being emitted, because // it's emitted when `response` is emitted if (uploaded === lastUploaded || uploaded === uploadBodySize) { return; } ee.emit('uploadProgress', { percent: uploadBodySize ? uploaded / uploadBodySize : 0, transferred: uploaded, total: uploadBodySize }); }, uploadEventFrequency); }; // Only subscribe to `connect` event if we're actually connecting a new // socket, otherwise if we're already connected (because this is a // keep-alive connection) do not bother. This is important since we won't // get a `connect` event for an already connected socket. if (socket.connecting) { socket.once('connect', onSocketConnect); } else { onSocketConnect(); } } }); if (opts.gotTimeout) { clearInterval(progressInterval); timedOut(req, opts.gotTimeout); } setImmediate(() => { ee.emit('request', req); }); }); }; setImmediate(async () => { try { uploadBodySize = await getBodySize(opts); // This is the second try at setting a `content-length` header. // This supports getting the size async, in contrast to // https://github.com/sindresorhus/got/blob/82763c8089596dcee5eaa7f57f5dbf8194842fe6/index.js#L579-L582 // TODO: We should unify these two at some point if ( uploadBodySize > 0 && is.undefined(opts.headers['content-length']) && is.undefined(opts.headers['transfer-encoding']) ) { opts.headers['content-length'] = uploadBodySize; } get(opts); } catch (err) { ee.emit('error', err); } }); return ee; } function getResponse(res, opts, ee, redirects) { const downloadBodySize = Number(res.headers['content-length']) || null; let downloaded = 0; const progressStream = new Transform({ transform(chunk, encoding, callback) { downloaded += chunk.length; const percent = downloadBodySize ? downloaded / downloadBodySize : 0; // Let flush() be responsible for emitting the last event if (percent < 1) { ee.emit('downloadProgress', { percent, transferred: downloaded, total: downloadBodySize }); } callback(null, chunk); }, flush(callback) { ee.emit('downloadProgress', { percent: 1, transferred: downloaded, total: downloadBodySize }); callback(); } }); mimicResponse(res, progressStream); progressStream.redirectUrls = redirects; const response = opts.decompress === true && is.function(decompressResponse) && opts.method !== 'HEAD' ? decompressResponse(progressStream) : progressStream; if (!opts.decompress && ['gzip', 'deflate'].includes(res.headers['content-encoding'])) { opts.encoding = null; } ee.emit('response', response); ee.emit('downloadProgress', { percent: 0, transferred: 0, total: downloadBodySize }); res.pipe(progressStream); } function asPromise(opts) { const timeoutFn = requestPromise => opts.gotTimeout && opts.gotTimeout.request ? pTimeout(requestPromise, opts.gotTimeout.request, new got.RequestError({message: 'Request timed out', code: 'ETIMEDOUT'}, opts)) : requestPromise; const proxy = new EventEmitter(); const cancelable = new PCancelable((resolve, reject, onCancel) => { const ee = requestAsEventEmitter(opts); let cancelOnRequest = false; onCancel(() => { cancelOnRequest = true; }); ee.on('request', req => { if (cancelOnRequest) { req.abort(); } onCancel(() => { req.abort(); }); if (is.nodeStream(opts.body)) { opts.body.pipe(req); opts.body = undefined; return; } req.end(opts.body); }); ee.on('response', async res => { const stream = is.null(opts.encoding) ? getStream.buffer(res) : getStream(res, opts); let data; try { data = await stream; } catch (err) { reject(new got.ReadError(err, opts)); return; } const {statusCode} = res; const limitStatusCode = opts.followRedirect ? 299 : 399; res.body = data; if (opts.json && res.body) { try { res.body = JSON.parse(res.body); } catch (err) { if (statusCode >= 200 && statusCode < 300) { const parseError = new got.ParseError(err, statusCode, opts, data); Object.defineProperty(parseError, 'response', {value: res}); reject(parseError); } } } if (opts.throwHttpErrors && statusCode !== 304 && (statusCode < 200 || statusCode > limitStatusCode)) { const err = new got.HTTPError(statusCode, res.statusMessage, res.headers, opts); Object.defineProperty(err, 'response', {value: res}); reject(err); } resolve(res); }); ee.once('error', reject); ee.on('redirect', proxy.emit.bind(proxy, 'redirect')); ee.on('uploadProgress', proxy.emit.bind(proxy, 'uploadProgress')); ee.on('downloadProgress', proxy.emit.bind(proxy, 'downloadProgress')); }); const promise = timeoutFn(cancelable); promise.cancel = cancelable.cancel.bind(cancelable); promise.on = (name, fn) => { proxy.on(name, fn); return promise; }; return promise; } function asStream(opts) { opts.stream = true; const input = new PassThrough(); const output = new PassThrough(); const proxy = duplexer3(input, output); let timeout; if (opts.gotTimeout && opts.gotTimeout.request) { timeout = setTimeout(() => { proxy.emit('error', new got.RequestError({message: 'Request timed out', code: 'ETIMEDOUT'}, opts)); }, opts.gotTimeout.request); } if (opts.json) { throw new Error('Got can not be used as a stream when the `json` option is used'); } if (opts.body) { proxy.write = () => { throw new Error('Got\'s stream is not writable when the `body` option is used'); }; } const ee = requestAsEventEmitter(opts); ee.on('request', req => { proxy.emit('request', req); if (is.nodeStream(opts.body)) { opts.body.pipe(req); return; } if (opts.body) { req.end(opts.body); return; } if (opts.method === 'POST' || opts.method === 'PUT' || opts.method === 'PATCH') { input.pipe(req); return; } req.end(); }); ee.on('response', res => { clearTimeout(timeout); const {statusCode} = res; res.on('error', err => { proxy.emit('error', new got.ReadError(err, opts)); }); res.pipe(output); if (opts.throwHttpErrors && statusCode !== 304 && (statusCode < 200 || statusCode > 299)) { proxy.emit('error', new got.HTTPError(statusCode, res.statusMessage, res.headers, opts), null, res); return; } proxy.emit('response', res); }); ee.on('error', proxy.emit.bind(proxy, 'error')); ee.on('redirect', proxy.emit.bind(proxy, 'redirect')); ee.on('uploadProgress', proxy.emit.bind(proxy, 'uploadProgress')); ee.on('downloadProgress', proxy.emit.bind(proxy, 'downloadProgress')); return proxy; } function normalizeArguments(url, opts) { if (!is.string(url) && !is.object(url)) { throw new TypeError(`Parameter \`url\` must be a string or object, not ${is(url)}`); } else if (is.string(url)) { url = url.replace(/^unix:/, 'http://$&'); try { decodeURI(url); } catch (err) { throw new Error('Parameter `url` must contain valid UTF-8 character sequences'); } url = urlParseLax(url); if (url.auth) { throw new Error('Basic authentication must be done with the `auth` option'); } } else if (isURL.lenient(url)) { url = urlToOptions(url); } const defaults = { path: '', retries: 2, cache: false, decompress: true, useElectronNet: false, throwHttpErrors: true }; opts = { ...defaults, ...url, protocol: url.protocol || 'http:', // Override both null/undefined with default protocol ...opts }; const headers = lowercaseKeys(opts.headers); for (const [key, value] of Object.entries(headers)) { if (is.nullOrUndefined(value)) { delete headers[key]; } } opts.headers = { 'user-agent': `${pkg.name}/${pkg.version} (https://github.com/sindresorhus/got)`, ...headers }; if (opts.decompress && is.undefined(opts.headers['accept-encoding'])) { opts.headers['accept-encoding'] = 'gzip, deflate'; } const {query} = opts; if (query) { if (!is.string(query)) { opts.query = querystring.stringify(query); } opts.path = `${opts.path.split('?')[0]}?${opts.query}`; delete opts.query; } if (opts.json && is.undefined(opts.headers.accept)) { opts.headers.accept = 'application/json'; } const {body} = opts; if (is.nullOrUndefined(body)) { opts.method = (opts.method || 'GET').toUpperCase(); } else { const {headers} = opts; if (!is.nodeStream(body) && !is.string(body) && !is.buffer(body) && !(opts.form || opts.json)) { throw new TypeError('The `body` option must be a stream.Readable, string, Buffer or plain Object'); } const canBodyBeStringified = is.plainObject(body) || is.array(body); if ((opts.form || opts.json) && !canBodyBeStringified) { throw new TypeError('The `body` option must be a plain Object or Array when the `form` or `json` option is used'); } if (isFormData(body)) { // Special case for https://github.com/form-data/form-data headers['content-type'] = headers['content-type'] || `multipart/form-data; boundary=${body.getBoundary()}`; } else if (opts.form && canBodyBeStringified) { headers['content-type'] = headers['content-type'] || 'application/x-www-form-urlencoded'; opts.body = querystring.stringify(body); } else if (opts.json && canBodyBeStringified) { headers['content-type'] = headers['content-type'] || 'application/json'; opts.body = JSON.stringify(body); } if (is.undefined(headers['content-length']) && is.undefined(headers['transfer-encoding']) && !is.nodeStream(body)) { const length = is.string(opts.body) ? Buffer.byteLength(opts.body) : opts.body.length; headers['content-length'] = length; } // Convert buffer to stream to receive upload progress events (#322) if (is.buffer(body)) { opts.body = toReadableStream(body); opts.body._buffer = body; } opts.method = (opts.method || 'POST').toUpperCase(); } if (opts.hostname === 'unix') { const matches = /(.+?):(.+)/.exec(opts.path); if (matches) { const [, socketPath, path] = matches; opts = { ...opts, socketPath, path, host: null }; } } if (!is.function(opts.retries)) { const {retries} = opts; opts.retries = (iter, err) => { if (iter > retries || !isRetryAllowed(err)) { return 0; } const noise = Math.random() * 100; return ((1 << iter) * 1000) + noise; }; } if (is.undefined(opts.followRedirect)) { opts.followRedirect = true; } if (opts.timeout) { if (is.number(opts.timeout)) { opts.gotTimeout = {request: opts.timeout}; } else { opts.gotTimeout = opts.timeout; } delete opts.timeout; } return opts; } function got(url, opts) { try { const normalizedArgs = normalizeArguments(url, opts); if (normalizedArgs.stream) { return asStream(normalizedArgs); } return asPromise(normalizedArgs); } catch (err) { return Promise.reject(err); } } got.stream = (url, opts) => asStream(normalizeArguments(url, opts)); const methods = [ 'get', 'post', 'put', 'patch', 'head', 'delete' ]; for (const method of methods) { got[method] = (url, options) => got(url, {...options, method}); got.stream[method] = (url, options) => got.stream(url, {...options, method}); } Object.assign(got, errors); module.exports = got;
index.js
'use strict'; const util = require('util'); const EventEmitter = require('events'); const http = require('http'); const https = require('https'); const {PassThrough, Transform} = require('stream'); const urlLib = require('url'); const fs = require('fs'); const querystring = require('querystring'); const CacheableRequest = require('cacheable-request'); const duplexer3 = require('duplexer3'); const toReadableStream = require('to-readable-stream'); const is = require('@sindresorhus/is'); const getStream = require('get-stream'); const timedOut = require('timed-out'); const urlParseLax = require('url-parse-lax'); const urlToOptions = require('url-to-options'); const lowercaseKeys = require('lowercase-keys'); const decompressResponse = require('decompress-response'); const mimicResponse = require('mimic-response'); const isRetryAllowed = require('is-retry-allowed'); const isURL = require('isurl'); const PCancelable = require('p-cancelable'); const pTimeout = require('p-timeout'); const pkg = require('./package.json'); const errors = require('./errors'); const getMethodRedirectCodes = new Set([300, 301, 302, 303, 304, 305, 307, 308]); const allMethodRedirectCodes = new Set([300, 303, 307, 308]); const isFormData = body => is.nodeStream(body) && is.function(body.getBoundary); const getBodySize = async opts => { const {body} = opts; if (opts.headers['content-length']) { return Number(opts.headers['content-length']); } if (!body && !opts.stream) { return 0; } if (is.string(body)) { return Buffer.byteLength(body); } if (isFormData(body)) { return util.promisify(body.getLength.bind(body))(); } if (body instanceof fs.ReadStream) { const {size} = await util.promisify(fs.stat)(body.path); return size; } if (is.nodeStream(body) && is.buffer(body._buffer)) { return body._buffer.length; } return null; }; function requestAsEventEmitter(opts) { opts = opts || {}; const ee = new EventEmitter(); const requestUrl = opts.href || urlLib.resolve(urlLib.format(opts), opts.path); const redirects = []; const agents = is.object(opts.agent) ? opts.agent : null; let retryCount = 0; let redirectUrl; let uploadBodySize; let uploaded = 0; const get = opts => { if (opts.protocol !== 'http:' && opts.protocol !== 'https:') { ee.emit('error', new got.UnsupportedProtocolError(opts)); return; } let fn = opts.protocol === 'https:' ? https : http; if (agents) { const protocolName = opts.protocol === 'https:' ? 'https' : 'http'; opts.agent = agents[protocolName] || opts.agent; } if (opts.useElectronNet && process.versions.electron) { const electron = require('electron'); fn = electron.net || electron.remote.net; } let progressInterval; const cacheableRequest = new CacheableRequest(fn.request, opts.cache); const cacheReq = cacheableRequest(opts, res => { clearInterval(progressInterval); ee.emit('uploadProgress', { percent: 1, transferred: uploaded, total: uploadBodySize }); const {statusCode} = res; res.url = redirectUrl || requestUrl; res.requestUrl = requestUrl; const followRedirect = opts.followRedirect && 'location' in res.headers; const redirectGet = followRedirect && getMethodRedirectCodes.has(statusCode); const redirectAll = followRedirect && allMethodRedirectCodes.has(statusCode); if (redirectAll || (redirectGet && (opts.method === 'GET' || opts.method === 'HEAD'))) { res.resume(); if (statusCode === 303) { // Server responded with "see other", indicating that the resource exists at another location, // and the client should request it from that location via GET or HEAD. opts.method = 'GET'; } if (redirects.length >= 10) { ee.emit('error', new got.MaxRedirectsError(statusCode, redirects, opts), null, res); return; } const bufferString = Buffer.from(res.headers.location, 'binary').toString(); redirectUrl = urlLib.resolve(urlLib.format(opts), bufferString); redirects.push(redirectUrl); const redirectOpts = { ...opts, ...urlLib.parse(redirectUrl) }; ee.emit('redirect', res, redirectOpts); get(redirectOpts); return; } setImmediate(() => { try { getResponse(res, opts, ee, redirects); } catch (e) { ee.emit('error', e); } }); }); cacheReq.on('error', err => { if (err instanceof CacheableRequest.RequestError) { ee.emit('error', new got.RequestError(err, opts)); } else { ee.emit('error', new got.CacheError(err, opts)); } }); cacheReq.once('request', req => { let aborted = false; req.once('abort', _ => { aborted = true; }); req.once('error', err => { clearInterval(progressInterval); if (aborted) { return; } const backoff = opts.retries(++retryCount, err); if (backoff) { setTimeout(get, backoff, opts); return; } ee.emit('error', new got.RequestError(err, opts)); }); ee.once('request', req => { ee.emit('uploadProgress', { percent: 0, transferred: 0, total: uploadBodySize }); const socket = req.connection; if (socket) { const onSocketConnect = () => { const uploadEventFrequency = 150; progressInterval = setInterval(() => { if (socket.destroyed) { clearInterval(progressInterval); return; } const lastUploaded = uploaded; const headersSize = Buffer.byteLength(req._header); uploaded = socket.bytesWritten - headersSize; // Prevent the known issue of `bytesWritten` being larger than body size if (uploadBodySize && uploaded > uploadBodySize) { uploaded = uploadBodySize; } // Don't emit events with unchanged progress and // prevent last event from being emitted, because // it's emitted when `response` is emitted if (uploaded === lastUploaded || uploaded === uploadBodySize) { return; } ee.emit('uploadProgress', { percent: uploadBodySize ? uploaded / uploadBodySize : 0, transferred: uploaded, total: uploadBodySize }); }, uploadEventFrequency); }; // Only subscribe to `connect` event if we're actually connecting a new // socket, otherwise if we're already connected (because this is a // keep-alive connection) do not bother. This is important since we won't // get a `connect` event for an already connected socket. if (socket.connecting) { socket.once('connect', onSocketConnect); } else { onSocketConnect(); } } }); if (opts.gotTimeout) { clearInterval(progressInterval); timedOut(req, opts.gotTimeout); } setImmediate(() => { ee.emit('request', req); }); }); }; setImmediate(async () => { try { uploadBodySize = await getBodySize(opts); // This is the second try at setting a `content-length` header. // This supports getting the size async, in contrast to // https://github.com/sindresorhus/got/blob/82763c8089596dcee5eaa7f57f5dbf8194842fe6/index.js#L579-L582 // TODO: We should unify these two at some point if ( uploadBodySize > 0 && is.undefined(opts.headers['content-length']) && is.undefined(opts.headers['transfer-encoding']) ) { opts.headers['content-length'] = uploadBodySize; } get(opts); } catch (err) { ee.emit('error', err); } }); return ee; } function getResponse(res, opts, ee, redirects) { const downloadBodySize = Number(res.headers['content-length']) || null; let downloaded = 0; const progressStream = new Transform({ transform(chunk, encoding, callback) { downloaded += chunk.length; const percent = downloadBodySize ? downloaded / downloadBodySize : 0; // Let flush() be responsible for emitting the last event if (percent < 1) { ee.emit('downloadProgress', { percent, transferred: downloaded, total: downloadBodySize }); } callback(null, chunk); }, flush(callback) { ee.emit('downloadProgress', { percent: 1, transferred: downloaded, total: downloadBodySize }); callback(); } }); mimicResponse(res, progressStream); progressStream.redirectUrls = redirects; const response = opts.decompress === true && is.function(decompressResponse) && opts.method !== 'HEAD' ? decompressResponse(progressStream) : progressStream; if (!opts.decompress && ['gzip', 'deflate'].includes(res.headers['content-encoding'])) { opts.encoding = null; } ee.emit('response', response); ee.emit('downloadProgress', { percent: 0, transferred: 0, total: downloadBodySize }); res.pipe(progressStream); } function asPromise(opts) { const timeoutFn = requestPromise => opts.gotTimeout && opts.gotTimeout.request ? pTimeout(requestPromise, opts.gotTimeout.request, new got.RequestError({message: 'Request timed out', code: 'ETIMEDOUT'}, opts)) : requestPromise; const proxy = new EventEmitter(); const cancelable = new PCancelable((resolve, reject, onCancel) => { const ee = requestAsEventEmitter(opts); let cancelOnRequest = false; onCancel(() => { cancelOnRequest = true; }); ee.on('request', req => { if (cancelOnRequest) { req.abort(); } onCancel(() => { req.abort(); }); if (is.nodeStream(opts.body)) { opts.body.pipe(req); opts.body = undefined; return; } req.end(opts.body); }); ee.on('response', async res => { const stream = is.null(opts.encoding) ? getStream.buffer(res) : getStream(res, opts); let data; try { data = await stream; } catch (err) { reject(new got.ReadError(err, opts)); return; } const {statusCode} = res; const limitStatusCode = opts.followRedirect ? 299 : 399; res.body = data; if (opts.json && res.body) { try { res.body = JSON.parse(res.body); } catch (err) { if (statusCode >= 200 && statusCode < 300) { const parseError = new got.ParseError(err, statusCode, opts, data); Object.defineProperty(parseError, 'response', {value: res}); reject(parseError); } } } if (opts.throwHttpErrors && statusCode !== 304 && (statusCode < 200 || statusCode > limitStatusCode)) { const err = new got.HTTPError(statusCode, res.statusMessage, res.headers, opts); Object.defineProperty(err, 'response', {value: res}); reject(err); } resolve(res); }); ee.once('error', reject); ee.on('redirect', proxy.emit.bind(proxy, 'redirect')); ee.on('uploadProgress', proxy.emit.bind(proxy, 'uploadProgress')); ee.on('downloadProgress', proxy.emit.bind(proxy, 'downloadProgress')); }); const promise = timeoutFn(cancelable); promise.cancel = cancelable.cancel.bind(cancelable); promise.on = (name, fn) => { proxy.on(name, fn); return promise; }; return promise; } function asStream(opts) { opts.stream = true; const input = new PassThrough(); const output = new PassThrough(); const proxy = duplexer3(input, output); let timeout; if (opts.gotTimeout && opts.gotTimeout.request) { timeout = setTimeout(() => { proxy.emit('error', new got.RequestError({message: 'Request timed out', code: 'ETIMEDOUT'}, opts)); }, opts.gotTimeout.request); } if (opts.json) { throw new Error('Got can not be used as a stream when the `json` option is used'); } if (opts.body) { proxy.write = () => { throw new Error('Got\'s stream is not writable when the `body` option is used'); }; } const ee = requestAsEventEmitter(opts); ee.on('request', req => { proxy.emit('request', req); if (is.nodeStream(opts.body)) { opts.body.pipe(req); return; } if (opts.body) { req.end(opts.body); return; } if (opts.method === 'POST' || opts.method === 'PUT' || opts.method === 'PATCH') { input.pipe(req); return; } req.end(); }); ee.on('response', res => { clearTimeout(timeout); const {statusCode} = res; res.on('error', err => { proxy.emit('error', new got.ReadError(err, opts)); }); res.pipe(output); if (opts.throwHttpErrors && statusCode !== 304 && (statusCode < 200 || statusCode > 299)) { proxy.emit('error', new got.HTTPError(statusCode, res.statusMessage, res.headers, opts), null, res); return; } proxy.emit('response', res); }); ee.on('error', proxy.emit.bind(proxy, 'error')); ee.on('redirect', proxy.emit.bind(proxy, 'redirect')); ee.on('uploadProgress', proxy.emit.bind(proxy, 'uploadProgress')); ee.on('downloadProgress', proxy.emit.bind(proxy, 'downloadProgress')); return proxy; } function normalizeArguments(url, opts) { if (!is.string(url) && !is.object(url)) { throw new TypeError(`Parameter \`url\` must be a string or object, not ${is(url)}`); } else if (is.string(url)) { url = url.replace(/^unix:/, 'http://$&'); try { decodeURI(url); } catch (err) { throw new Error('Parameter `url` must contain valid UTF-8 character sequences'); } url = urlParseLax(url); if (url.auth) { throw new Error('Basic authentication must be done with the `auth` option'); } } else if (isURL.lenient(url)) { url = urlToOptions(url); } const defaults = { path: '', retries: 2, cache: false, decompress: true, useElectronNet: false, throwHttpErrors: true }; opts = { ...defaults, ...url, protocol: url.protocol || 'http:', // Override both null/undefined with default protocol ...opts }; const headers = lowercaseKeys(opts.headers); for (const [key, value] of Object.entries(headers)) { if (is.nullOrUndefined(value)) { delete headers[key]; } } opts.headers = { 'user-agent': `${pkg.name}/${pkg.version} (https://github.com/sindresorhus/got)`, ...headers }; if (opts.decompress && is.undefined(opts.headers['accept-encoding'])) { opts.headers['accept-encoding'] = 'gzip, deflate'; } const {query} = opts; if (query) { if (!is.string(query)) { opts.query = querystring.stringify(query); } opts.path = `${opts.path.split('?')[0]}?${opts.query}`; delete opts.query; } if (opts.json && is.undefined(opts.headers.accept)) { opts.headers.accept = 'application/json'; } const {body} = opts; if (is.nullOrUndefined(body)) { opts.method = (opts.method || 'GET').toUpperCase(); } else { const {headers} = opts; if (!is.nodeStream(body) && !is.string(body) && !is.buffer(body) && !(opts.form || opts.json)) { throw new TypeError('The `body` option must be a stream.Readable, string, Buffer or plain Object'); } const canBodyBeStringified = is.plainObject(body) || is.array(body); if ((opts.form || opts.json) && !canBodyBeStringified) { throw new TypeError('The `body` option must be a plain Object or Array when the `form` or `json` option is used'); } if (isFormData(body)) { // Special case for https://github.com/form-data/form-data headers['content-type'] = headers['content-type'] || `multipart/form-data; boundary=${body.getBoundary()}`; } else if (opts.form && canBodyBeStringified) { headers['content-type'] = headers['content-type'] || 'application/x-www-form-urlencoded'; opts.body = querystring.stringify(body); } else if (opts.json && canBodyBeStringified) { headers['content-type'] = headers['content-type'] || 'application/json'; opts.body = JSON.stringify(body); } if (is.undefined(headers['content-length']) && is.undefined(headers['transfer-encoding']) && !is.nodeStream(body)) { const length = is.string(opts.body) ? Buffer.byteLength(opts.body) : opts.body.length; headers['content-length'] = length; } // Convert buffer to stream to receive upload progress events (#322) if (is.buffer(body)) { opts.body = toReadableStream(body); opts.body._buffer = body; } opts.method = (opts.method || 'POST').toUpperCase(); } if (opts.hostname === 'unix') { const matches = /(.+?):(.+)/.exec(opts.path); if (matches) { const [, socketPath, path] = matches; opts = { ...opts, socketPath, path, host: null }; } } if (!is.function(opts.retries)) { const {retries} = opts; opts.retries = (iter, err) => { if (iter > retries || !isRetryAllowed(err)) { return 0; } const noise = Math.random() * 100; return ((1 << iter) * 1000) + noise; }; } if (is.undefined(opts.followRedirect)) { opts.followRedirect = true; } if (opts.timeout) { if (is.number(opts.timeout)) { opts.gotTimeout = {request: opts.timeout}; } else { opts.gotTimeout = opts.timeout; } delete opts.timeout; } return opts; } function got(url, opts) { try { const normalizedArgs = normalizeArguments(url, opts); if (normalizedArgs.stream) { return asStream(normalizedArgs); } return asPromise(normalizedArgs); } catch (err) { return Promise.reject(err); } } got.stream = (url, opts) => asStream(normalizeArguments(url, opts)); const methods = [ 'get', 'post', 'put', 'patch', 'head', 'delete' ]; for (const method of methods) { got[method] = (url, options) => got(url, {...options, method}); got.stream[method] = (url, options) => got.stream(url, {...options, method}); } Object.assign(got, errors); module.exports = got;
fix Buffer.byteLength(req._header) throwing error (#490)
index.js
fix Buffer.byteLength(req._header) throwing error (#490)
<ide><path>ndex.js <ide> } <ide> <ide> const lastUploaded = uploaded; <del> const headersSize = Buffer.byteLength(req._header); <add> const headersSize = req._header ? Buffer.byteLength(req._header) : 0; <ide> uploaded = socket.bytesWritten - headersSize; <ide> <ide> // Prevent the known issue of `bytesWritten` being larger than body size
JavaScript
mit
a30e034265b5157efddc27aaba591f0683a4a63f
0
Flieral/Dashboard-Panel,Flieral/Dashboard-Panel,Flieral/Dashboard-Panel,Flieral/Dashboard-Panel
function wrapAccessToken(url, accessToken) { if (url.indexOf('?') !== -1) return url + '&access_token=' + accessToken else return url + '?access_token=' + accessToken } function wrapFilter(url, filter) { if (url.indexOf('?') !== -1) return url + '&filter=' + filter else return url + '?filter=' + filter } function timeConvertor(myDate) { var parts = myDate.split(" ") var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] return Math.floor((new Date(parseInt(parts[3]), months.indexOf(parts[2]), parseInt(parts[1]))).getTime()) } function dateConvertor(myDate) { var d = new Date(myDate) var weekday = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] return ('' + weekday[d.getDay()] + ' ' + d.getDate() + ' ' + months[d.getMonth()] + ' ' + d.getFullYear()) } function generateQueryString(data) { var ret = [] for (var d in data) if (data[d]) ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d])) return ret.join("&") } var announcer_url = "http://127.0.0.1:3000/api/"; var coreEngine_url = "http://127.0.0.1:3015/api/"; $(document).ready(function () { var clientInstance; var fullCampaignResult var campaignsArray = [] var totalSubcampaignsArray = [] var editableSubcampaignId var editableSettingId var prefredSubcampaign var userId, serviceAccessToken, coreAccessToken if (localStorage.getItem('userId')) userId = localStorage.getItem('userId') else window.location.href = '../AAA/sign-in.html'; if (localStorage.getItem('serviceAccessToken')) serviceAccessToken = localStorage.getItem('serviceAccessToken') else window.location.href = '../AAA/sign-in.html'; if (localStorage.getItem('coreAccessToken')) coreAccessToken = localStorage.getItem('coreAccessToken') else window.location.href = '../AAA/sign-in.html'; getAccountModel(); initDateTimePicker(); initJQueryTable(); function initDateTimePicker() { //Textare auto growth autosize($('textarea.auto-growth')); //Datetimepicker plugin $('.datetimepicker').bootstrapMaterialDatePicker({ format: 'dddd DD MMMM YYYY - HH:mm', clearButton: true, weekStart: 1 }); $('.datepicker').bootstrapMaterialDatePicker({ format: 'dddd DD MMMM YYYY', clearButton: true, weekStart: 1, time: false }); $('.timepicker').bootstrapMaterialDatePicker({ format: 'HH:mm', clearButton: true, date: false }); } function initJQueryTable() { //Exportable table $('.js-exportable').DataTable({ dom: 'Bfrtip', buttons: [ 'copy', 'csv', 'excel', 'pdf', 'print' ] }); } function fillEditSubcampaignFields(selected) { for (var i = 0; i < totalSubcampaignsArray.length; i++) { if (totalSubcampaignsArray[i].name === selected) { editableSubcampaignId = totalSubcampaignsArray[i].id $("#editSubcampaignName").val(totalSubcampaignsArray[i].name) $("#editSubcampaignStyle").selectpicker('val', totalSubcampaignsArray[i].style) $("#editSubcampaignMinBudget").val(totalSubcampaignsArray[i].minBudget) $("#editSubcampaignPlan").selectpicker('val', totalSubcampaignsArray[i].plan) $("#editSubcampaignPrice").val(totalSubcampaignsArray[i].price) break } } } function fillSettingSubcampaignFields(selected) { for (var i = 0; i < totalSubcampaignsArray.length; i++) { if (totalSubcampaignsArray[i].name === selected) { editableSettingId = totalSubcampaignsArray[i].id $("#selectSettingPriority").selectpicker('val', totalSubcampaignsArray[i].settingModel.priority) $("#selectSettingUserLabel").selectpicker('val', totalSubcampaignsArray[i].settingModel.userLabel) $("#selectSettingDevice").selectpicker('val', totalSubcampaignsArray[i].settingModel.device) $("#selectSettingCategory").selectpicker('val', totalSubcampaignsArray[i].settingModel.category) $("#selectSettingCountry").selectpicker('val', totalSubcampaignsArray[i].settingModel.country) $("#selectSettingLanguage").selectpicker('val', totalSubcampaignsArray[i].settingModel.language) $("#selectSettingOS").selectpicker('val', totalSubcampaignsArray[i].settingModel.os) $("#selectSettingConnection").selectpicker('val', totalSubcampaignsArray[i].settingModel.connection) break } } } function tabHandler(e) { if ($(e.target).attr('id') === 'nav1') { $("#mySubcampaigns").show(); $("#editSubcampaign").hide(); $("#addSubcampaign").hide(); $("#contentProviding").hide(); $("#selectSetting").hide(); } else if ($(e.target).attr('id') === 'nav3') { if (localStorage.getItem('editableSubcampaignName')) { var subcampName = localStorage.getItem('editableSubcampaignName') $("#editSubcampaignSelect").selectpicker('val', subcampName) fillEditSubcampaignFields(subcampName); $("#selectSettingSelect").selectpicker('val', subcampName) fillSettingSubcampaignFields(subcampName); localStorage.removeItem("editableSubcampaignName") } $("#mySubcampaigns").hide(); $("#selectSetting").show(); $("#contentProviding").hide(); $("#editSubcampaign").show(); $("#addSubcampaign").hide(); } else if ($(e.target).attr('id') === 'nav2') { if (localStorage.getItem('newCreatedCampaign')) { var campName = localStorage.getItem('newCreatedCampaign') $("#addSubcampaignSelectCampaign").selectpicker('val', campName) localStorage.removeItem("newCreatedCampaign") } $("#mySubcampaigns").hide(); $("#editSubcampaign").hide(); $("#addSubcampaign").show(); $("#contentProviding").show(); $("#selectSetting").show(); } } $('a[data-toggle="tab"]').on('show.bs.tab', function (e) { tabHandler(e) }); if (!window.location.hash) { $("#mySubcampaigns").show(); $("#editSubcampaign").hide(); $("#addSubcampaign").hide(); $("#contentProviding").hide(); $("#selectSetting").hide(); } else if (window.location.hash === '#addSubcampaign') $('.nav-tabs a[id="nav2"]').tab('show'); else if (window.location.hash === '#editSubcampaign') $('.nav-tabs a[id="nav3"]').tab('show'); else if (window.location.hash === '#mySubcampaigns') $('.nav-tabs a[id="nav1"]').tab('show'); $('#editSubcampaignSelect').on('changed.bs.select', function (e, clickedIndex, newValue, oldValue) { var selected = $(this).find('option').eq(clickedIndex).text() fillEditSubcampaignFields(selected) }); $('#selectSettingSelect').on('changed.bs.select', function (e, clickedIndex, newValue, oldValue) { var selected = $(this).find('option').eq(clickedIndex).text() fillSettingSubcampaignFields(selected) }); function getAccountModel() { var accountURLWithAT = wrapAccessToken(announcer_url + 'clients/' + userId, serviceAccessToken) var accountURL = wrapFilter(accountURLWithAT, '{"include":["announcerAccount", "campaigns"]}') $.ajax({ url: accountURL, type: "GET", success: function (accountResult) { clientInstance = accountResult var campaignURLWithAT = wrapAccessToken(announcer_url + 'clients/' + userId + '/campaigns', serviceAccessToken) var campaignURL = wrapFilter(campaignURLWithAT, '{"include":["subcampaigns"]}') $.ajax({ url: campaignURL, type: "GET", success: function (campaignResult) { totalSubcampaignsArray = [] fullCampaignResult = campaignResult $('#addSubcampaignSelectCampaign').find('option').remove() $('#mySubcampaignSelectCampaign').find('option').remove() $('#selectSettingSelect').find('option').remove() $('#contentProvidingSelect').find('option').remove() $('#editSubcampaignSelect').find('option').remove() for (var i = 0; i < accountResult.campaigns.length; i++) { $('#addSubcampaignSelectCampaign').append($('<option>', { value: accountResult.campaigns[i].id, text: accountResult.campaigns[i].name })).selectpicker('refresh'); $('#mySubcampaignSelectCampaign').append($('<option>', { value: accountResult.campaigns[i].id, text: accountResult.campaigns[i].name })).selectpicker('refresh'); } for (var i = 0; i < campaignResult.length; i++) { var group = $('<optgroup label="' + campaignResult[i].name + '"/>'); for (j = 0; j < campaignResult[i].subcampaigns.length; j++) { $('<option />').html(campaignResult[i].subcampaigns[j].name).appendTo(group); totalSubcampaignsArray.push(campaignResult[i].subcampaigns[j]) } group.appendTo('#editSubcampaignSelect'); $('#editSubcampaignSelect').selectpicker('refresh'); } for (var i = 0; i < campaignResult.length; i++) { var group = $('<optgroup label="' + campaignResult[i].name + '"/>'); for (j = 0; j < campaignResult[i].subcampaigns.length; j++) { $('<option />').html(campaignResult[i].subcampaigns[j].name).appendTo(group); } group.appendTo('#selectSettingSelect'); $('#selectSettingSelect').selectpicker('refresh'); } for (var i = 0; i < campaignResult.length; i++) { var group = $('<optgroup label="' + campaignResult[i].name + '"/>'); for (j = 0; j < campaignResult[i].subcampaigns.length; j++) { $('<option />').html(campaignResult[i].subcampaigns[j].name).appendTo(group); } group.appendTo('#contentProvidingSelect'); $('#contentProvidingSelect').selectpicker('refresh'); } $('#editSubcampaignSelect').trigger("chosen:updated") $('#selectSettingSelect').trigger("chosen:updated") $('#contentProvidingSelect').trigger("chosen:updated") if (localStorage.getItem("newAddedSubcampaign")) { var subcampName = localStorage.getItem("newAddedSubcampaign") var campaignName = localStorage.getItem("newAddedSubcampaignCampaign") $("#selectSettingSelect").selectpicker('val', subcampName) $("#selectSettingSelect").selectpicker('refresh'); $("#contentProvidingSelect").selectpicker('val', subcampName) $("#contentProvidingSelect").selectpicker('refresh'); $("#addSubcampaignSelectCampaign").selectpicker('val', campaignName) $("#addSubcampaignSelectCampaign").selectpicker('refresh'); $('#selectSettingSelect').selectpicker('render') $('#contentProvidingSelect').selectpicker('render') $('#addSubcampaignSelectCampaign').selectpicker('render') fillSettingSubcampaignFields(subcampName); localStorage.removeItem("newAddedSubcampaignCampaign") localStorage.removeItem("newAddedSubcampaign") } $('#addSubcampaignSelectCampaign').trigger("chosen:updated") $('#mySubcampaignSelectCampaign').trigger("chosen:updated") fillTable(totalSubcampaignsArray) if (localStorage.getItem('myCampaignSelectSubcampaign')) { var campName = localStorage.getItem('myCampaignSelectSubcampaign') $("#mySubcampaignSelectCampaign").selectpicker('val', campName).selectpicker('refresh') localStorage.removeItem("myCampaignSelectSubcampaign") } }, error: function (xhr, status, error) { $('.page-loader-wrapper').fadeOut(); alert(xhr.responseText); } }); $("#announcerUsername").html(localStorage.getItem('announcerCompanyName')); $("#announcerEmail").html(localStorage.getItem('announcerEmail')); $("#sharedBudget").html('Budget: $' + accountResult.announcerAccount.budget); $('.page-loader-wrapper').fadeOut(); }, error: function (xhr, status, error) { $('.page-loader-wrapper').fadeOut(); alert(xhr.responseText); } }); } function fillTable(subcampaignsArray) { $('#tab_logic>tbody').empty() for (var i = 0; i < subcampaignsArray.length; i++) { var statusColor if (subcampaignsArray[i].status === 'Pending') statusColor = 'bg-orange' else if (subcampaignsArray[i].status === 'Suspend') statusColor = 'bg-red' else if (subcampaignsArray[i].status === 'Approved') statusColor = 'bg-green' else if (subcampaignsArray[i].status === 'Created') statusColor = 'bg-grey' else if (subcampaignsArray[i].status === 'Finished') statusColor = 'bg-indigo' else if (subcampaignsArray[i].status === 'Started') statusColor = 'bg-blue' else if (subcampaignsArray[i].status === 'Stopped') statusColor = 'bg-deep-orange' else if (subcampaignsArray[i].status === 'UnStopped') statusColor = 'bg-teal' $('#tab_logic').append('<tr id="addr' + (i) + '"></tr>'); $('#addr' + i).html( '<td align="center" style="vertical-align: middle; white-space: nowrap; width: 5%;">' + subcampaignsArray[i].id + '</td>' + '<td align="center" style="vertical-align: middle; white-space: nowrap; width: 5%;">' + subcampaignsArray[i].campaignId + '</td>' + '<td align="center" style="vertical-align: middle; white-space: nowrap; width: 10%;">' + subcampaignsArray[i].name + '</td>' + '<td align="center" style="vertical-align: middle; white-space: nowrap; width: 5%;">' + subcampaignsArray[i].style + '</td>' + '<td align="center" style="vertical-align: middle; white-space: nowrap; width: 5%;">$' + subcampaignsArray[i].minBudget + '</td>' + '<td align="center" style="vertical-align: middle; white-space: nowrap; width: 5%;">' + subcampaignsArray[i].plan + '</td>' + '<td align="center" style="vertical-align: middle; white-space: nowrap; width: 5%;">$' + subcampaignsArray[i].price + '</td>' + '<td align="center" style="vertical-align: middle; white-space: nowrap; width: 5%;"><span class="label font-13 ' + statusColor + '">' + subcampaignsArray[i].status + '</span></td>' + '<td align="center" style="vertical-align: middle; white-space: nowrap; width: 1%;">' + '<button type="button" class="subcampaignEdit m-l-5 m-r-5 btn bg-green waves-effect"><i class="material-icons">mode_edit</i></button>' + '<button type="button" class="subcampaignDelete m-l-5 m-r-5 btn bg-red waves-effect"><i class="material-icons">clear</i></button>' + '</td>' ); } $('.js-basic-example').DataTable(); } $(document).on("click", ".subcampaignEdit", function (e) { e.preventDefault(); var campId = $(this).parent().siblings().eq(1).text() var subcampId = $(this).parent().siblings().eq(0).text() var subcampaignName, campaignName for (var i = 0; i < totalSubcampaignsArray.length; i++) if (totalSubcampaignsArray[i].id == subcampId) subcampaignName = totalSubcampaignsArray[i].name for (var i = 0; i < clientInstance.campaigns.length; i++) if (clientInstance.campaigns[i].id == campId) campaignName = clientInstance.campaigns[i].name localStorage.setItem('editableSubcampaignName', subcampaignName) $('.nav-tabs a[id="nav3"]').tab('show'); }) $(document).on("click", ".subcampaignDelete", function (e) { e.preventDefault(); var campId = $(this).parent().siblings().eq(1).text() var subcampId = $(this).parent().siblings().eq(0).text() swal({ title: "Are You Sure?", text: "You won't be able to recover the subcampaign after removing it.", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes, delete it!", cancelButtonText: "No, Cancel!", closeOnConfirm: false, closeOnCancel: true }, function (isConfirm) { if (isConfirm) { var subcampaignURLWithAT = wrapAccessToken(announcer_url + 'campaigns/' + campId + '/subcampaigns/' + subcampId, serviceAccessToken) $.ajax({ url: subcampaignURLWithAT, type: "DELETE", success: function (subcampaignResult) { swal("Deleted!", "Your subcampaign successfuly has been deleted.", "success"); getAccountModel() }, error: function (xhr, status, error) { swal("Oops!", "Something went wrong, Please try again somehow later.", "error"); alert(xhr.responseText); } }); } }); }) $("#mySubcampaignsSearch").click(function (e) { e.preventDefault(); var status = [], style = [], plan = [], campaign = [], limit if ($('#mySubcampaignSelectCampaign').val()) campaign = $('#mySubcampaignSelectCampaign').val() if ($('#mySubcampaignStatus').val()) status = $('#mySubcampaignStatus').val() if ($('#mySubcampaignStyle').val()) style = $('#mySubcampaignStyle').val() if ($('#mySubcampaignPlan').val()) plan = $('#mySubcampaignPlan').val() var limit = $('#mySubcampaignLimit').val() var filter = {} if (status.length > 0 || style.length > 0 || plan.length > 0 || campaign.length > 0) { filter.where = {} filter.where.and = [] if (status.length > 0) filter.where.and.push({ 'status': { 'inq': status } }) if (style.length > 0) filter.where.and.push({ 'style': { 'inq': style } }) if (plan.length > 0) filter.where.and.push({ 'plan': { 'inq': plan } }) if (campaign.length > 0) filter.where.and.push({ 'campaignId': { 'inq': campaign } }) } filter.limit = limit filter.fields = { 'settingModel': false } var subcampaignURLWithAT = wrapAccessToken(announcer_url + 'subcampaigns/getAllSubcampaigns?accountHashId=' + userId, serviceAccessToken) var subcampaignFilterURL = wrapFilter(subcampaignURLWithAT, JSON.stringify(filter)) $('.page-loader-wrapper').fadeIn(); $.ajax({ url: subcampaignFilterURL, type: "GET", success: function (subcampaignResult) { fillTable(subcampaignResult) $('.page-loader-wrapper').fadeOut(); }, error: function (xhr, status, error) { $('.page-loader-wrapper').fadeOut(); alert(xhr.responseText); } }); }) $("#editSubcamapignButton").click(function (e) { e.preventDefault(); var subcampaignName = $('#editSubcampaignSelect').find('option:selected').text() var campaignId, subcampaignId for (var i = 0; i < totalSubcampaignsArray.length; i++) if (totalSubcampaignsArray[i].name === subcampaignName) { campaignId = totalSubcampaignsArray[i].campaignId subcampaignId = totalSubcampaignsArray[i].id } if (!campaignId || !subcampaignId || !subcampaignName || !$('#editSubcampaignName').val() || !$('#editSubcampaignMinBudget').val() || !$('#editSubcampaignPrice').val() || !$('#editSubcampaignStyle').find('option:selected').text() || !$('#editSubcampaignPlan').find('option:selected').text()) return swal("Oops!", "You should enter required field of prepared form.", "warning"); var data = { name: $('#editSubcampaignName').val(), minBudget: $('#editSubcampaignMinBudget').val(), style: $('#editSubcampaignStyle').find('option:selected').text(), plan: $('#editSubcampaignPlan').find('option:selected').text(), price: $('#editSubcampaignPrice').val() } var subcampaignURL = wrapAccessToken(announcer_url + 'campaigns/' + campaignId + '/subcampaigns/' + subcampaignId, serviceAccessToken); $.ajax({ url: subcampaignURL, data: JSON.stringify(data), dataType: "json", contentType: "application/json; charset=utf-8", type: "PUT", success: function (subcampaignResult) { getAccountModel() swal("Congrates!", "You have successfuly edited a subcampaign.", "success"); }, error: function (xhr, status, error) { swal("Oops!", "Something went wrong, Please try again somehow later.", "error"); alert(xhr.responseText); } }); }) $("#addSubcamapignButton").click(function (e) { e.preventDefault(); var campaignName = $('#addSubcampaignSelectCampaign').find('option:selected').text() var campaignId for (var i = 0; i < clientInstance.campaigns.length; i++) if (clientInstance.campaigns[i].name === campaignName) campaignId = clientInstance.campaigns[i].id if (!campaignId || !campaignName || !$('#addSubcampaignName').val() || !$('#addSubcampaignMinBudget').val() || !$('#addSubcampaignPrice').val() || !$('#addSubcampaignStyle').find('option:selected').text() || !$('#addSubcampaignPlan').find('option:selected').text()) return swal("Oops!", "You should enter required field of prepared form.", "warning"); var data = { name: $('#addSubcampaignName').val(), minBudget: Number($('#addSubcampaignMinBudget').val()), style: $('#addSubcampaignStyle').find('option:selected').text(), plan: $('#addSubcampaignPlan').find('option:selected').text(), price: $('#addSubcampaignPrice').val() } var subcampaignURL = wrapAccessToken(announcer_url + 'campaigns/' + campaignId + '/subcampaigns', serviceAccessToken); $.ajax({ url: subcampaignURL, data: JSON.stringify(data), dataType: "json", contentType: "application/json; charset=utf-8", type: "POST", success: function (subcampaignResult) { localStorage.setItem("newAddedSubcampaign", subcampaignResult.name) localStorage.setItem('newAddedSubcampaignCampaign', campaignName) getAccountModel() swal("Congrates!", "You have successfuly created a subcampaign. Lets go for adding setting and content.", "success"); }, error: function (xhr, status, error) { swal("Oops!", "Something went wrong, Please try again somehow later.", "error"); alert(xhr.responseText); } }); }) $("#sendContentButton").click(function (e) { e.preventDefault(); var subcampaignName = $('#contentProvidingSelect').find('option:selected').text() var campaignId, subcampaignId for (var i = 0; i < totalSubcampaignsArray.length; i++) if (totalSubcampaignsArray[i].name === subcampaignName) { campaignId = totalSubcampaignsArray[i].campaignId subcampaignId = totalSubcampaignsArray[i].id } if (!campaignId || !subcampaignName || !subcampaignId || !$('#contentProvidingHeader').val() || !$('#contentProvidingHolding').val() || !$('#contentProvidingSubtitle').val() || !$('#contentProvidingTemplate').find('option:selected').text() || !$('#contentProvidingType').find('option:selected').text()) return swal("Oops!", "You should enter required field of prepared form.", "warning"); var isStatic = false if ($('#contentProvidingType').find('option:selected').text() === 'Static') isStatic = true var templateId = $('#contentProvidingTemplate').find('option:selected').text() var data = { header: $('#contentProvidingHeader').val(), time: (new Date()).toLocaleString(), holding: $('#contentProvidingHolding').val(), subtitle: $('#contentProvidingSubtitle').val(), } var queryData = { campaignHashId: campaignId, subcampaignHashId: subcampaignId, isStatic: isStatic, templateId: templateId, data: JSON.stringify(data) } var queryString = generateQueryString(queryData) var subcampaignURL = wrapAccessToken(announcer_url + 'containers/uploadFile?' + queryString, serviceAccessToken); $.ajax({ url: subcampaignURL, data: JSON.stringify(data), dataType: "json", contentType: "application/json; charset=utf-8", type: "POST", success: function (subcampaignResult) { getAccountModel() $("#selectSettingSelect").selectpicker('val', subcampaignResult.name) $("#contentProvidingSelect").selectpicker('val', subcampaignResult.name) swal("Congrates!", "You have successfuly added a content to a subcampaign.", "success"); }, error: function (xhr, status, error) { swal("Oops!", "Something went wrong, Please try again somehow later.", "error"); alert(xhr.responseText); } }); }) $("#saveSettingButton").click(function (e) { e.preventDefault(); var subcampaignName = $('#selectSettingSelect').find('option:selected').text() var campaignId, subcampaignId for (var i = 0; i < totalSubcampaignsArray.length; i++) if (totalSubcampaignsArray[i].name === subcampaignName) { campaignId = totalSubcampaignsArray[i].campaignId subcampaignId = totalSubcampaignsArray[i].id } if (!campaignId || !subcampaignName || !subcampaignId || !$('#selectSettingPriority').find('option:selected').text() || $('#selectSettingCategory').find('option:selected').text().length == 0 || $('#selectSettingCountry').find('option:selected').text().length == 0 || $('#selectSettingLanguage').find('option:selected').text().length == 0 || $('#selectSettingDevice').find('option:selected').text().length == 0 || $('#selectSettingOS').find('option:selected').text().length == 0 || $('#selectSettingUserLabel').find('option:selected').text().length == 0 || $('#selectSettingConnection').find('option:selected').text().length == 0 ) return swal("Oops!", "You should enter required field of prepared form.", "warning"); var data = { priority: $('#selectSettingPriority').find('option:selected').text(), category: $('#selectSettingCategory').find('option:selected').map(function () { return this.value }).get(), country: $('#selectSettingCountry').find('option:selected').map(function () { return this.value }).get(), language: $('#selectSettingLanguage').find('option:selected').map(function () { return this.value }).get(), device: $('#selectSettingDevice').find('option:selected').map(function () { return this.value }).get(), os: $('#selectSettingOS').find('option:selected').map(function () { return this.value }).get(), userLabel: $('#selectSettingUserLabel').find('option:selected').map(function () { return this.value }).get(), connection: $('#selectSettingConnection').find('option:selected').map(function () { return this.value }).get() } var settingURL = wrapAccessToken(announcer_url + 'subcampaigns/' + subcampaignId + '/setting', serviceAccessToken); $.ajax({ url: settingURL, data: JSON.stringify(data), dataType: "json", contentType: "application/json; charset=utf-8", type: "PUT", success: function (settingResult) { getAccountModel() swal("Congrates!", "You have successfuly edited the setting of a subcampaign.", "success"); }, error: function (xhr, status, error) { swal("Oops!", "Something went wrong, Please try again somehow later.", "error"); alert(xhr.responseText); } }); }) })
js/pages/announcer/subcampaigns.js
function wrapAccessToken(url, accessToken) { if (url.indexOf('?') !== -1) return url + '&access_token=' + accessToken else return url + '?access_token=' + accessToken } function wrapFilter(url, filter) { if (url.indexOf('?') !== -1) return url + '&filter=' + filter else return url + '?filter=' + filter } function timeConvertor(myDate) { var parts = myDate.split(" ") var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] return Math.floor((new Date(parseInt(parts[3]), months.indexOf(parts[2]), parseInt(parts[1]))).getTime()) } function dateConvertor(myDate) { var d = new Date(myDate) var weekday = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] return ('' + weekday[d.getDay()] + ' ' + d.getDate() + ' ' + months[d.getMonth()] + ' ' + d.getFullYear()) } function generateQueryString(data) { var ret = [] for (var d in data) if (data[d]) ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d])) return ret.join("&") } var announcer_url = "http://127.0.0.1:3000/api/"; var coreEngine_url = "http://127.0.0.1:3015/api/"; $(document).ready(function () { var clientInstance; var fullCampaignResult var campaignsArray = [] var totalSubcampaignsArray = [] var editableSubcampaignId var editableSettingId var prefredSubcampaign var userId, serviceAccessToken, coreAccessToken if (localStorage.getItem('userId')) userId = localStorage.getItem('userId') else window.location.href = '../AAA/sign-in.html'; if (localStorage.getItem('serviceAccessToken')) serviceAccessToken = localStorage.getItem('serviceAccessToken') else window.location.href = '../AAA/sign-in.html'; if (localStorage.getItem('coreAccessToken')) coreAccessToken = localStorage.getItem('coreAccessToken') else window.location.href = '../AAA/sign-in.html'; getAccountModel(); initDateTimePicker(); initJQueryTable(); function initDateTimePicker() { //Textare auto growth autosize($('textarea.auto-growth')); //Datetimepicker plugin $('.datetimepicker').bootstrapMaterialDatePicker({ format: 'dddd DD MMMM YYYY - HH:mm', clearButton: true, weekStart: 1 }); $('.datepicker').bootstrapMaterialDatePicker({ format: 'dddd DD MMMM YYYY', clearButton: true, weekStart: 1, time: false }); $('.timepicker').bootstrapMaterialDatePicker({ format: 'HH:mm', clearButton: true, date: false }); } function initJQueryTable() { //Exportable table $('.js-exportable').DataTable({ dom: 'Bfrtip', buttons: [ 'copy', 'csv', 'excel', 'pdf', 'print' ] }); } function fillEditSubcampaignFields(selected) { for (var i = 0; i < totalSubcampaignsArray.length; i++) { if (totalSubcampaignsArray[i].name === selected) { editableSubcampaignId = totalSubcampaignsArray[i].id $("#editSubcampaignName").val(totalSubcampaignsArray[i].name) $("#editSubcampaignStyle").selectpicker('val', totalSubcampaignsArray[i].style) $("#editSubcampaignMinBudget").val(totalSubcampaignsArray[i].minBudget) $("#editSubcampaignPlan").selectpicker('val', totalSubcampaignsArray[i].plan) $("#editSubcampaignPrice").val(totalSubcampaignsArray[i].price) break } } } function fillSettingSubcampaignFields(selected) { for (var i = 0; i < totalSubcampaignsArray.length; i++) { if (totalSubcampaignsArray[i].name === selected) { editableSettingId = totalSubcampaignsArray[i].id $("#selectSettingPriority").selectpicker('val', totalSubcampaignsArray[i].settingModel.priority) $("#selectSettingUserLabel").selectpicker('val', totalSubcampaignsArray[i].settingModel.userLabel) $("#selectSettingDevice").selectpicker('val', totalSubcampaignsArray[i].settingModel.device) $("#selectSettingCategory").selectpicker('val', totalSubcampaignsArray[i].settingModel.category) $("#selectSettingCountry").selectpicker('val', totalSubcampaignsArray[i].settingModel.country) $("#selectSettingLanguage").selectpicker('val', totalSubcampaignsArray[i].settingModel.language) $("#selectSettingOS").selectpicker('val', totalSubcampaignsArray[i].settingModel.os) $("#selectSettingConnection").selectpicker('val', totalSubcampaignsArray[i].settingModel.connection) break } } } function tabHandler(e) { if ($(e.target).attr('id') === 'nav1') { $("#mySubcampaigns").show(); $("#editSubcampaign").hide(); $("#addSubcampaign").hide(); $("#contentProviding").hide(); $("#selectSetting").hide(); } else if ($(e.target).attr('id') === 'nav3') { if (localStorage.getItem('editableSubcampaignName')) { var subcampName = localStorage.getItem('editableSubcampaignName') $("#editSubcampaignSelect").selectpicker('val', subcampName) fillEditSubcampaignFields(subcampName); $("#selectSettingSelect").selectpicker('val', subcampName) fillSettingSubcampaignFields(subcampName); } $("#mySubcampaigns").hide(); $("#selectSetting").show(); $("#contentProviding").hide(); $("#editSubcampaign").show(); $("#addSubcampaign").hide(); } else if ($(e.target).attr('id') === 'nav2') { if (localStorage.getItem('newCreatedCampaign')) { var campName = localStorage.getItem('newCreatedCampaign') $("#addSubcampaignSelectCampaign").selectpicker('val', campName) localStorage.removeItem("newCreatedCampaign") } $("#mySubcampaigns").hide(); $("#editSubcampaign").hide(); $("#addSubcampaign").show(); $("#contentProviding").show(); $("#selectSetting").show(); } } $('a[data-toggle="tab"]').on('show.bs.tab', function (e) { tabHandler(e) }); if (!window.location.hash) { $("#mySubcampaigns").show(); $("#editSubcampaign").hide(); $("#addSubcampaign").hide(); $("#contentProviding").hide(); $("#selectSetting").hide(); } else if (window.location.hash === '#addSubcampaign') $('.nav-tabs a[id="nav2"]').tab('show'); else if (window.location.hash === '#editSubcampaign') $('.nav-tabs a[id="nav3"]').tab('show'); else if (window.location.hash === '#mySubcampaigns') $('.nav-tabs a[id="nav1"]').tab('show'); $('#editSubcampaignSelect').on('changed.bs.select', function (e, clickedIndex, newValue, oldValue) { var selected = $(this).find('option').eq(clickedIndex).text() fillEditSubcampaignFields(selected) }); $('#selectSettingSelect').on('changed.bs.select', function (e, clickedIndex, newValue, oldValue) { var selected = $(this).find('option').eq(clickedIndex).text() fillSettingSubcampaignFields(selected) }); function getAccountModel() { var accountURLWithAT = wrapAccessToken(announcer_url + 'clients/' + userId, serviceAccessToken) var accountURL = wrapFilter(accountURLWithAT, '{"include":["announcerAccount", "campaigns"]}') $.ajax({ url: accountURL, type: "GET", success: function (accountResult) { clientInstance = accountResult var campaignURLWithAT = wrapAccessToken(announcer_url + 'clients/' + userId + '/campaigns', serviceAccessToken) var campaignURL = wrapFilter(campaignURLWithAT, '{"include":["subcampaigns"]}') $.ajax({ url: campaignURL, type: "GET", success: function (campaignResult) { totalSubcampaignsArray = [] fullCampaignResult = campaignResult $('#addSubcampaignSelectCampaign').find('option').remove() $('#mySubcampaignSelectCampaign').find('option').remove() $('#selectSettingSelect').find('option').remove() $('#contentProvidingSelect').find('option').remove() $('#editSubcampaignSelect').find('option').remove() for (var i = 0; i < accountResult.campaigns.length; i++) { $('#addSubcampaignSelectCampaign').append($('<option>', { value: accountResult.campaigns[i].id, text: accountResult.campaigns[i].name })).selectpicker('refresh'); $('#mySubcampaignSelectCampaign').append($('<option>', { value: accountResult.campaigns[i].id, text: accountResult.campaigns[i].name })).selectpicker('refresh'); } $('#addSubcampaignSelectCampaign').trigger("chosen:updated") $('#mySubcampaignSelectCampaign').trigger("chosen:updated") for (var i = 0; i < campaignResult.length; i++) { var group = $('<optgroup label="' + campaignResult[i].name + '"/>'); for (j = 0; j < campaignResult[i].subcampaigns.length; j++) { $('<option />').html(campaignResult[i].subcampaigns[j].name).appendTo(group); totalSubcampaignsArray.push(campaignResult[i].subcampaigns[j]) } group.appendTo('#editSubcampaignSelect'); $('#editSubcampaignSelect').selectpicker('refresh'); } for (var i = 0; i < campaignResult.length; i++) { var group = $('<optgroup label="' + campaignResult[i].name + '"/>'); for (j = 0; j < campaignResult[i].subcampaigns.length; j++) { $('<option />').html(campaignResult[i].subcampaigns[j].name).appendTo(group); } group.appendTo('#selectSettingSelect'); $('#selectSettingSelect').selectpicker('refresh'); } for (var i = 0; i < campaignResult.length; i++) { var group = $('<optgroup label="' + campaignResult[i].name + '"/>'); for (j = 0; j < campaignResult[i].subcampaigns.length; j++) { $('<option />').html(campaignResult[i].subcampaigns[j].name).appendTo(group); } group.appendTo('#contentProvidingSelect'); $('#contentProvidingSelect').selectpicker('refresh'); } $('#editSubcampaignSelect').trigger("chosen:updated") $('#selectSettingSelect').trigger("chosen:updated") $('#contentProvidingSelect').trigger("chosen:updated") fillTable(totalSubcampaignsArray) }, error: function (xhr, status, error) { $('.page-loader-wrapper').fadeOut(); alert(xhr.responseText); } }); $("#announcerUsername").html(localStorage.getItem('announcerCompanyName')); $("#announcerEmail").html(localStorage.getItem('announcerEmail')); $("#sharedBudget").html('Budget: $' + accountResult.announcerAccount.budget); $('.page-loader-wrapper').fadeOut(); }, error: function (xhr, status, error) { $('.page-loader-wrapper').fadeOut(); alert(xhr.responseText); } }); } function fillTable(subcampaignsArray) { $('#tab_logic>tbody').empty() for (var i = 0; i < subcampaignsArray.length; i++) { var statusColor if (subcampaignsArray[i].status === 'Pending') statusColor = 'bg-orange' else if (subcampaignsArray[i].status === 'Suspend') statusColor = 'bg-red' else if (subcampaignsArray[i].status === 'Approved') statusColor = 'bg-green' else if (subcampaignsArray[i].status === 'Created') statusColor = 'bg-grey' else if (subcampaignsArray[i].status === 'Finished') statusColor = 'bg-indigo' else if (subcampaignsArray[i].status === 'Started') statusColor = 'bg-blue' else if (subcampaignsArray[i].status === 'Stopped') statusColor = 'bg-deep-orange' else if (subcampaignsArray[i].status === 'UnStopped') statusColor = 'bg-teal' $('#tab_logic').append('<tr id="addr' + (i) + '"></tr>'); $('#addr' + i).html( '<td align="center" style="vertical-align: middle; white-space: nowrap; width: 5%;">' + subcampaignsArray[i].id + '</td>' + '<td align="center" style="vertical-align: middle; white-space: nowrap; width: 5%;">' + subcampaignsArray[i].campaignId + '</td>' + '<td align="center" style="vertical-align: middle; white-space: nowrap; width: 10%;">' + subcampaignsArray[i].name + '</td>' + '<td align="center" style="vertical-align: middle; white-space: nowrap; width: 5%;">' + subcampaignsArray[i].style + '</td>' + '<td align="center" style="vertical-align: middle; white-space: nowrap; width: 5%;">$' + subcampaignsArray[i].minBudget + '</td>' + '<td align="center" style="vertical-align: middle; white-space: nowrap; width: 5%;">' + subcampaignsArray[i].plan + '</td>' + '<td align="center" style="vertical-align: middle; white-space: nowrap; width: 5%;">$' + subcampaignsArray[i].price + '</td>' + '<td align="center" style="vertical-align: middle; white-space: nowrap; width: 5%;"><span class="label font-13 ' + statusColor + '">' + subcampaignsArray[i].status + '</span></td>' + '<td align="center" style="vertical-align: middle; white-space: nowrap; width: 1%;">' + '<button type="button" class="subcampaignEdit m-l-5 m-r-5 btn bg-green waves-effect"><i class="material-icons">mode_edit</i></button>' + '<button type="button" class="subcampaignDelete m-l-5 m-r-5 btn bg-red waves-effect"><i class="material-icons">clear</i></button>' + '</td>' ); } $('.js-basic-example').DataTable(); } $(document).on("click", ".subcampaignEdit", function (e) { e.preventDefault(); var campId = $(this).parent().siblings().eq(1).text() var subcampId = $(this).parent().siblings().eq(0).text() var subcampaignName for (var i = 0; i < totalSubcampaignsArray.length; i++) if (totalSubcampaignsArray[i].id == subcampId) subcampaignName = totalSubcampaignsArray[i].name localStorage.setItem('editableSubcampaignName', subcampaignName) $('.nav-tabs a[id="nav3"]').tab('show'); }) $(document).on("click", ".subcampaignDelete", function (e) { e.preventDefault(); var campId = $(this).parent().siblings().eq(1).text() var subcampId = $(this).parent().siblings().eq(0).text() swal({ title: "Are You Sure?", text: "You won't be able to recover the subcampaign after removing it.", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes, delete it!", cancelButtonText: "No, Cancel!", closeOnConfirm: false, closeOnCancel: true }, function (isConfirm) { if (isConfirm) { var subcampaignURLWithAT = wrapAccessToken(announcer_url + 'campaigns/' + campId + '/subcampaigns/' + subcampId, serviceAccessToken) $.ajax({ url: subcampaignURLWithAT, type: "DELETE", success: function (subcampaignResult) { swal("Deleted!", "Your subcampaign successfuly has been deleted.", "success"); getAccountModel() }, error: function (xhr, status, error) { swal("Oops!", "Something went wrong, Please try again somehow later.", "error"); alert(xhr.responseText); } }); } }); }) $("#mySubcampaignsSearch").click(function (e) { e.preventDefault(); var status = [], style = [], plan = [], campaign = [], limit if ($('#mySubcampaignSelectCampaign').val()) campaign = $('#mySubcampaignSelectCampaign').val() if ($('#mySubcampaignStatus').val()) status = $('#mySubcampaignStatus').val() if ($('#mySubcampaignStyle').val()) style = $('#mySubcampaignStyle').val() if ($('#mySubcampaignPlan').val()) plan = $('#mySubcampaignPlan').val() var limit = $('#mySubcampaignLimit').val() var filter = {} if (status.length > 0 || style.length > 0 || plan.length > 0 || campaign.length > 0) { filter.where = {} filter.where.and = [] if (status.length > 0) filter.where.and.push({ 'status': { 'inq': status } }) if (style.length > 0) filter.where.and.push({ 'style': { 'inq': style } }) if (plan.length > 0) filter.where.and.push({ 'plan': { 'inq': plan } }) if (campaign.length > 0) filter.where.and.push({ 'campaignId': { 'inq': campaign } }) } filter.limit = limit filter.fields = { 'settingModel': false } var subcampaignURLWithAT = wrapAccessToken(announcer_url + 'subcampaigns/getAllSubcampaigns?accountHashId=' + userId, serviceAccessToken) var subcampaignFilterURL = wrapFilter(subcampaignURLWithAT, JSON.stringify(filter)) $('.page-loader-wrapper').fadeIn(); $.ajax({ url: subcampaignFilterURL, type: "GET", success: function (subcampaignResult) { fillTable(subcampaignResult) $('.page-loader-wrapper').fadeOut(); }, error: function (xhr, status, error) { $('.page-loader-wrapper').fadeOut(); alert(xhr.responseText); } }); }) $("#editSubcamapignButton").click(function (e) { e.preventDefault(); var subcampaignName = $('#editSubcampaignSelect').find('option:selected').text() var campaignId, subcampaignId for (var i = 0; i < totalSubcampaignsArray.length; i++) if (totalSubcampaignsArray[i].name === subcampaignName) { campaignId = totalSubcampaignsArray[i].campaignId subcampaignId = totalSubcampaignsArray[i].id } if (!campaignId || !subcampaignId || !subcampaignName || !$('#editSubcampaignName').val() || !$('#editSubcampaignMinBudget').val() || !$('#editSubcampaignPrice').val() || !$('#editSubcampaignStyle').find('option:selected').text() || !$('#editSubcampaignPlan').find('option:selected').text()) return swal("Oops!", "You should enter required field of prepared form.", "warning"); var data = { name: $('#editSubcampaignName').val(), minBudget: $('#editSubcampaignMinBudget').val(), style: $('#editSubcampaignStyle').find('option:selected').text(), plan: $('#editSubcampaignPlan').find('option:selected').text(), price: $('#editSubcampaignPrice').val() } var subcampaignURL = wrapAccessToken(announcer_url + 'campaigns/' + campaignId + '/subcampaigns/' + subcampaignId, serviceAccessToken); $.ajax({ url: subcampaignURL, data: JSON.stringify(data), dataType: "json", contentType: "application/json; charset=utf-8", type: "PUT", success: function (subcampaignResult) { getAccountModel() swal("Congrates!", "You have successfuly edited a subcampaign.", "success"); }, error: function (xhr, status, error) { swal("Oops!", "Something went wrong, Please try again somehow later.", "error"); alert(xhr.responseText); } }); }) $("#addSubcamapignButton").click(function (e) { e.preventDefault(); var campaignName = $('#addSubcampaignSelectCampaign').find('option:selected').text() var campaignId for (var i = 0; i < clientInstance.campaigns.length; i++) if (clientInstance.campaigns[i].name === campaignName) campaignId = clientInstance.campaigns[i].id if (!campaignId || !campaignName || !$('#addSubcampaignName').val() || !$('#addSubcampaignMinBudget').val() || !$('#addSubcampaignPrice').val() || !$('#addSubcampaignStyle').find('option:selected').text() || !$('#addSubcampaignPlan').find('option:selected').text()) return swal("Oops!", "You should enter required field of prepared form.", "warning"); var data = { name: $('#addSubcampaignName').val(), minBudget: Number($('#addSubcampaignMinBudget').val()), style: $('#addSubcampaignStyle').find('option:selected').text(), plan: $('#addSubcampaignPlan').find('option:selected').text(), price: $('#addSubcampaignPrice').val() } var subcampaignURL = wrapAccessToken(announcer_url + 'campaigns/' + campaignId + '/subcampaigns', serviceAccessToken); $.ajax({ url: subcampaignURL, data: JSON.stringify(data), dataType: "json", contentType: "application/json; charset=utf-8", type: "POST", success: function (subcampaignResult) { getAccountModel() $("#selectSettingSelect").selectpicker('val', subcampaignResult.name) $("#contentProvidingSelect").selectpicker('val', subcampaignResult.name) swal("Congrates!", "You have successfuly created a subcampaign. Lets go for adding setting and content.", "success"); }, error: function (xhr, status, error) { swal("Oops!", "Something went wrong, Please try again somehow later.", "error"); alert(xhr.responseText); } }); }) $("#sendContentButton").click(function (e) { e.preventDefault(); var subcampaignName = $('#contentProvidingSelect').find('option:selected').text() var campaignId, subcampaignId for (var i = 0; i < totalSubcampaignsArray.length; i++) if (totalSubcampaignsArray[i].name === subcampaignName) { campaignId = totalSubcampaignsArray[i].campaignId subcampaignId = totalSubcampaignsArray[i].id } if (!campaignId || !subcampaignName || !subcampaignId || !$('#contentProvidingHeader').val() || !$('#contentProvidingHolding').val() || !$('#contentProvidingSubtitle').val() || !$('#contentProvidingTemplate').find('option:selected').text() || !$('#contentProvidingType').find('option:selected').text()) return swal("Oops!", "You should enter required field of prepared form.", "warning"); var isStatic = false if ($('#contentProvidingType').find('option:selected').text() === 'Static') isStatic = true var templateId = $('#contentProvidingTemplate').find('option:selected').text() var data = { header: $('#contentProvidingHeader').val(), time: (new Date()).toLocaleString(), holding: $('#contentProvidingHolding').val(), subtitle: $('#contentProvidingSubtitle').val(), } var queryData = { campaignHashId: campaignId, subcampaignHashId: subcampaignId, isStatic: isStatic, templateId: templateId, data: JSON.stringify(data) } var queryString = generateQueryString(queryData) var subcampaignURL = wrapAccessToken(announcer_url + 'containers/uploadFile?' + queryString, serviceAccessToken); $.ajax({ url: subcampaignURL, data: JSON.stringify(data), dataType: "json", contentType: "application/json; charset=utf-8", type: "POST", success: function (subcampaignResult) { getAccountModel() $("#selectSettingSelect").selectpicker('val', subcampaignResult.name) $("#contentProvidingSelect").selectpicker('val', subcampaignResult.name) swal("Congrates!", "You have successfuly added a content to a subcampaign.", "success"); }, error: function (xhr, status, error) { swal("Oops!", "Something went wrong, Please try again somehow later.", "error"); alert(xhr.responseText); } }); }) $("#saveSettingButton").click(function (e) { e.preventDefault(); var subcampaignName = $('#selectSettingSelect').find('option:selected').text() var campaignId, subcampaignId for (var i = 0; i < totalSubcampaignsArray.length; i++) if (totalSubcampaignsArray[i].name === subcampaignName) { campaignId = totalSubcampaignsArray[i].campaignId subcampaignId = totalSubcampaignsArray[i].id } if (!campaignId || !subcampaignName || !subcampaignId || !$('#selectSettingPriority').find('option:selected').text() || $('#selectSettingCategory').find('option:selected').text().length == 0 || $('#selectSettingCountry').find('option:selected').text().length == 0 || $('#selectSettingLanguage').find('option:selected').text().length == 0 || $('#selectSettingDevice').find('option:selected').text().length == 0 || $('#selectSettingOS').find('option:selected').text().length == 0 || $('#selectSettingUserLabel').find('option:selected').text().length == 0 || $('#selectSettingConnection').find('option:selected').text().length == 0 ) return swal("Oops!", "You should enter required field of prepared form.", "warning"); var data = { priority: $('#selectSettingPriority').find('option:selected').text(), category: $('#selectSettingCategory').find('option:selected').map(function () { return this.value }).get(), country: $('#selectSettingCountry').find('option:selected').map(function () { return this.value }).get(), language: $('#selectSettingLanguage').find('option:selected').map(function () { return this.value }).get(), device: $('#selectSettingDevice').find('option:selected').map(function () { return this.value }).get(), os: $('#selectSettingOS').find('option:selected').map(function () { return this.value }).get(), userLabel: $('#selectSettingUserLabel').find('option:selected').map(function () { return this.value }).get(), connection: $('#selectSettingConnection').find('option:selected').map(function () { return this.value }).get() } var settingURL = wrapAccessToken(announcer_url + 'subcampaigns/' + subcampaignId + '/setting', serviceAccessToken); $.ajax({ url: settingURL, data: JSON.stringify(data), dataType: "json", contentType: "application/json; charset=utf-8", type: "PUT", success: function (settingResult) { getAccountModel() swal("Congrates!", "You have successfuly edited the setting of a subcampaign.", "success"); }, error: function (xhr, status, error) { swal("Oops!", "Something went wrong, Please try again somehow later.", "error"); alert(xhr.responseText); } }); }) })
Add Handlers for Transition Between Pages
js/pages/announcer/subcampaigns.js
Add Handlers for Transition Between Pages
<ide><path>s/pages/announcer/subcampaigns.js <ide> fillEditSubcampaignFields(subcampName); <ide> $("#selectSettingSelect").selectpicker('val', subcampName) <ide> fillSettingSubcampaignFields(subcampName); <add> localStorage.removeItem("editableSubcampaignName") <ide> } <ide> $("#mySubcampaigns").hide(); <ide> $("#selectSetting").show(); <ide> text: accountResult.campaigns[i].name <ide> })).selectpicker('refresh'); <ide> } <del> $('#addSubcampaignSelectCampaign').trigger("chosen:updated") <del> $('#mySubcampaignSelectCampaign').trigger("chosen:updated") <ide> <ide> for (var i = 0; i < campaignResult.length; i++) { <ide> var group = $('<optgroup label="' + campaignResult[i].name + '"/>'); <ide> $('#selectSettingSelect').trigger("chosen:updated") <ide> $('#contentProvidingSelect').trigger("chosen:updated") <ide> <add> if (localStorage.getItem("newAddedSubcampaign")) { <add> var subcampName = localStorage.getItem("newAddedSubcampaign") <add> var campaignName = localStorage.getItem("newAddedSubcampaignCampaign") <add> $("#selectSettingSelect").selectpicker('val', subcampName) <add> $("#selectSettingSelect").selectpicker('refresh'); <add> $("#contentProvidingSelect").selectpicker('val', subcampName) <add> $("#contentProvidingSelect").selectpicker('refresh'); <add> $("#addSubcampaignSelectCampaign").selectpicker('val', campaignName) <add> $("#addSubcampaignSelectCampaign").selectpicker('refresh'); <add> $('#selectSettingSelect').selectpicker('render') <add> $('#contentProvidingSelect').selectpicker('render') <add> $('#addSubcampaignSelectCampaign').selectpicker('render') <add> fillSettingSubcampaignFields(subcampName); <add> localStorage.removeItem("newAddedSubcampaignCampaign") <add> localStorage.removeItem("newAddedSubcampaign") <add> } <add> <add> $('#addSubcampaignSelectCampaign').trigger("chosen:updated") <add> $('#mySubcampaignSelectCampaign').trigger("chosen:updated") <add> <ide> fillTable(totalSubcampaignsArray) <add> <add> if (localStorage.getItem('myCampaignSelectSubcampaign')) { <add> var campName = localStorage.getItem('myCampaignSelectSubcampaign') <add> $("#mySubcampaignSelectCampaign").selectpicker('val', campName).selectpicker('refresh') <add> localStorage.removeItem("myCampaignSelectSubcampaign") <add> } <ide> }, <ide> error: function (xhr, status, error) { <ide> $('.page-loader-wrapper').fadeOut(); <ide> e.preventDefault(); <ide> var campId = $(this).parent().siblings().eq(1).text() <ide> var subcampId = $(this).parent().siblings().eq(0).text() <del> var subcampaignName <add> var subcampaignName, campaignName <ide> for (var i = 0; i < totalSubcampaignsArray.length; i++) <ide> if (totalSubcampaignsArray[i].id == subcampId) <ide> subcampaignName = totalSubcampaignsArray[i].name <add> for (var i = 0; i < clientInstance.campaigns.length; i++) <add> if (clientInstance.campaigns[i].id == campId) <add> campaignName = clientInstance.campaigns[i].name <ide> localStorage.setItem('editableSubcampaignName', subcampaignName) <ide> $('.nav-tabs a[id="nav3"]').tab('show'); <ide> }) <ide> contentType: "application/json; charset=utf-8", <ide> type: "POST", <ide> success: function (subcampaignResult) { <add> localStorage.setItem("newAddedSubcampaign", subcampaignResult.name) <add> localStorage.setItem('newAddedSubcampaignCampaign', campaignName) <ide> getAccountModel() <del> $("#selectSettingSelect").selectpicker('val', subcampaignResult.name) <del> $("#contentProvidingSelect").selectpicker('val', subcampaignResult.name) <ide> swal("Congrates!", "You have successfuly created a subcampaign. Lets go for adding setting and content.", "success"); <ide> }, <ide> error: function (xhr, status, error) {
JavaScript
apache-2.0
6f60bfc69bcaa2f0fbea6baf34aef9d4c31fdae9
0
dennisausbremen/tunefish,dennisausbremen/tunefish,dennisausbremen/tunefish
var helper = (function ($) { 'use strict'; /* PRIVATE FUNCTIONS */ /** * Login Page */ var setActivePanel = function setActiveTab(target) { var tabs = $('.tabs'), children = tabs.children().length, steps = 100 / children, tab = tabs.find('a'), idx = target.parent().index(), content = $('.form-action-wrapper'); tab.removeClass('active'); tab.eq(idx).addClass('active'); content.css('transform', 'translate3d(-' + (steps * idx) + '%,0,0)'); }; var setLoginContainerHeight = function setLoginContainerHeight() { var i = $('.tabs a.active').parent().index(); var th = $('.tabs').outerHeight(); var h = $('.form-action-wrapper .form-action').eq(i).outerHeight(); $('.login-container').height(th + h); }; var checkInvalidLogin = function checkInvalidLogin() { var target = $('.fail').parents('.form-action').attr('id'); if (target) { setActivePanel($('[href=#' + target + ']')); } setLoginContainerHeight(); }; var initTabs = function initTabs() { $(document).on('click', '.tabs a:not(.active)', function () { var el = $(this), target = el.attr('href'); setActivePanel($('[href=' + target + ']')); setLoginContainerHeight(); return false; }); }; var App = { init: function initAmberApp() { //INIT MESSAGES $(document).on('ajaxComplete messageChange', Messages.init); if ($('#messages div').length) { $(document).trigger('messageChange'); } window.Tunefish = Ember.Application.create({ rootElement: '#app_container' }); Tunefish.ApplicationAdapter = DS.RESTAdapter.extend({ namespace: 'vote/ajax' }); Tunefish.Band = DS.Model.extend({ name: DS.attr('string'), members: DS.attr('number'), city: DS.attr('string'), website: DS.attr('string'), facebookUrl: DS.attr('string'), youtubeUrl: DS.attr('string'), descp: DS.attr('string'), image: DS.attr('string'), thumbnail: DS.attr('string'), distance: DS.attr('number'), voteCount: DS.attr('number'), voteAverage: DS.attr('number'), voted: DS.attr('boolean'), ownVote: DS.attr('number'), comments: DS.hasMany('comment'), tracks: DS.hasMany('track'), bandBG: function() { return 'background-image: url(\''+this.get('image') + '\');'; }.property('image'), map: function() { return 'http://maps.googleapis.com/maps/api/staticmap?key=AIzaSyDRzrscCqKGd66mLS6jOayfUw9d4SICKOY&markers=' + this.get('city') + '&zoom=10&size=550x300&sensor=false'; }.property('city') }); Tunefish.Comment = DS.Model.extend({ author: DS.attr('string'), timestamp: DS.attr('string'), message: DS.attr('string'), band: DS.belongsTo('band') }); Tunefish.Track = DS.Model.extend({ trackname: DS.attr('string'), url: DS.attr('string'), band: DS.belongsTo('band') }); Ember.LinkView.reopen({ attributeBindings: ['data-sort', 'data-voted'] }); Tunefish.VotecontrolsView = Ember.View.extend({ templateName: 'votecontrols', classNames: ['voting'] }); Tunefish.StarView = Ember.View.extend(Ember.ViewTargetActionSupport, { tagName: 'a', templateName: 'star', classNameBindings: ['active'], attributeBindings: ['href'], href: '#', active: function () { return this.get('band.ownVote') >= this.get('vote'); }.property('band.ownVote', 'vote'), click: function() { this.triggerAction({ action: 'vote', actionContext: this.get('vote') }); return false; } }); Tunefish.MainView = Ember.View.extend({ didInsertElement: function () { var seek = document.getElementById('seek'); var audio = document.getElementById('tunefishPlayer'); var seekBlocked, audioPaused = false; function createRangeInputChangeHelper(range, inputFn, changeFn) { var inputTimer, releaseTimer, isActive; var destroyRelease = function() { clearTimeout(releaseTimer); range.removeEventListener('blur', releaseRange, false); document.removeEventListener('mouseup', releaseRange, false); }; var setupRelease = function () { if (!isActive) { destroyRelease(); isActive = true; range.addEventListener('blur', releaseRange, false); document.addEventListener('mouseup', releaseRange, true); } }; var _releaseRange = function () { if (isActive) { destroyRelease(); isActive = false; if (changeFn) { changeFn(); } } }; var releaseRange = function () { setTimeout(_releaseRange, 9); }; var onInput = function () { if (inputFn) { clearTimeout(inputTimer); inputTimer = setTimeout(inputFn); } clearTimeout(releaseTimer); releaseTimer = setTimeout(releaseRange, 999); if (!isActive) { setupRelease(); } }; range.addEventListener('input', onInput, false); range.addEventListener('change', onInput, false); } function onSeek() { if (!seekBlocked) { seekBlocked = true; audioPaused = audio.paused; audio.pause(); } audio.currentTime = seek.value; } function onSeekRelease() { if (!audioPaused) { audio.play(); } seekBlocked = false; } createRangeInputChangeHelper(seek, onSeek, onSeekRelease); } }); Tunefish.QueueitemView = Ember.View.extend({ tagName: 'li', classNameBindings: ['isPlaying:playing'], isPlaying: function () { return this.get('item.index') === this.get('controller.currentIndex'); }.property('item', 'controller.currentIndex') }); Tunefish.BandsingleView = Ember.View.extend({ tagName: 'div', classNames: ['content-area band-view'], didInsertElement: function () { $('#tunefish_loading').hide(); } }); Tunefish.BandgridView = Ember.View.extend({ tagName: 'div', classNames: ['content-area band-grid'], didInsertElement: function () { $('#tunefish_loading').hide(); // TODO add me for funky animations /* this.$().mixItUp({ selectors: { target: '.band-tile' }, animation: { duration: 700, effects: 'fade translateY(50px) stagger(25ms)', //easing: 'cubic-bezier(0.86, 0, 0.07, 1)', reverseOut: true } }); */ } }); Tunefish.Router.map(function () { this.resource('main', {'path': '/'}, function () { this.resource('bands', { path: '/bands/' }); this.resource('band', { path: '/bands/:band_id'}); }); }); Tunefish.BandsRoute = Ember.Route.extend({ model: function () { return this.store.find('band'); } }); Tunefish.BandRoute = Ember.Route.extend({ model: function (params) { return this.store.find('band', params.band_id); } }); function shuffleArray(array) { // see http://stackoverflow.com/a/2450976 var currentIndex = array.length, temporaryValue, randomIndex; while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } } Tunefish.MainController = Ember.ObjectController.extend({ tracks: [], currentIndex: -1, current: null, currentTime: 0, currentDuration: 0, playerState: 'idle', player: function () { return document.getElementById('#tunefishPlayer'); }, actions: { vote: function (vote) { var current = this.get('current'); if (current === null) { return; } var band = current.get('band'); band.set('ownVote', vote); band.save(); }, clear: function() { var tracks = this.get('tracks'); this.send('pause'); this.set('current', null); this.set('currentIndex', -1); this.set('currentTime', '0'); this.set('currentDuration', '0'); tracks.clear(); }, addTrack: function (track, autoplay) { autoplay = typeof autoplay !== 'undefined' ? autoplay : true; var currentIndex = this.get('currentIndex'); var tracks = this.get('tracks'); tracks.pushObject({ 'index': tracks.length, 'track': track }); if (currentIndex < 0 && tracks.length > 0) { this.send('next'); if (autoplay) { this.send('play'); } } }, jumpTo: function (index) { var tracks = this.get('tracks'); if (index >= 0 && index < tracks.length) { this.set('currentIndex', index); this.set('current', tracks.get(index).track); } }, play: function () { var self = this; var currentIndex = this.get('currentIndex'); var $player = $('#tunefishPlayer'); if (currentIndex === -1) { return; } this.set('playerState', 'playing'); $player.attr('autoplay', 'autoplay'); $player.get(0).play(); $player.on('ended', function () { self.send('next'); }); $player.on('timeupdate', function () { self.set('currentTime', Math.ceil($player.get(0).currentTime)); self.set('currentDuration', Math.ceil($player.get(0).duration)); }); }, pause: function () { var $player = $('#tunefishPlayer'); $player.removeAttr('autoplay'); $player.get(0).pause(); $player.off('ended'); $player.off('timeupdate'); this.set('playerState', 'idle'); }, next: function () { var currentIndex = this.get('currentIndex'); var tracks = this.get('tracks'); if (currentIndex < tracks.length - 1) { this.set('currentIndex', currentIndex + 1); this.set('current', tracks.get(currentIndex + 1).track); } }, prev: function () { var currentIndex = this.get('currentIndex'); var tracks = this.get('tracks'); if (currentIndex > 0) { this.set('currentIndex', currentIndex - 1); this.set('current', tracks.get(currentIndex - 1).track); } }, addUnvotedTracks: function () { var self = this; this.store.findAll('band').then(function(bands) { bands.forEach(function(band) { var voted = band.get('voted'); if(!voted) { var tracks = band.get('tracks'); var length = tracks.get('length'); var idx = Math.floor(Math.random() * length); var track = tracks.objectAt(idx); self.send('addTrack', track, false); } }); }); }, shuffle: function() { var tracks = []; var shuffledTracks = []; this.get('tracks').forEach(function(track) { shuffledTracks.pushObject(track.track); }); shuffleArray(shuffledTracks); for (var i = 0; i < shuffledTracks.length; i++) { tracks.pushObject({ index: i, track: shuffledTracks[i] }); } this.set('tracks', tracks); this.send('jumpTo', 0); } } }); Tunefish.BandController = Ember.ObjectController.extend({ needs: ['main'], comment: '', actions: { vote: function (vote) { var band = this.get('model'); band.set('ownVote', vote); band.save(); }, addComment: function () { var comment = this.store.createRecord('comment', { message: this.get('comment'), band: this.get('model') }); comment.save(); this.set('comment', ''); }, addAllTracks: function () { var self = this; var tracks = this.get('model.tracks'); tracks.forEach(function(track){ self.get('controllers.main').send('addTrack', track); }); }, addTrack: function (track) { this.get('controllers.main').send('addTrack', track); } } }); } }; var Login = { init: function initLoginPage() { checkInvalidLogin(); initTabs(); } }; var Messages = { init: function initMessages() { var messageContainer = $('#messages'), messages = $('div', messageContainer); messages .velocity('transition.slideDownIn', {stagger: 250}) .delay(5000) .velocity('transition.slideUpOut', {stagger: 250, backwards: true}); } }; /* PUBLIC FUNCTION EXPORTS */ return { /* PUBLIC FUNCTIONS HERE */ App: App, Login: Login, Messages: Messages }; })(jQuery, window);
client/src/js/lib/helpers-vote.js
var helper = (function ($) { 'use strict'; /* PRIVATE FUNCTIONS */ /** * Login Page */ var setActivePanel = function setActiveTab(target) { var tabs = $('.tabs'), children = tabs.children().length, steps = 100 / children, tab = tabs.find('a'), idx = target.parent().index(), content = $('.form-action-wrapper'); tab.removeClass('active'); tab.eq(idx).addClass('active'); content.css('transform', 'translate3d(-' + (steps * idx) + '%,0,0)'); }; var setLoginContainerHeight = function setLoginContainerHeight() { var i = $('.tabs a.active').parent().index(); var th = $('.tabs').outerHeight(); var h = $('.form-action-wrapper .form-action').eq(i).outerHeight(); $('.login-container').height(th + h); }; var checkInvalidLogin = function checkInvalidLogin() { var target = $('.fail').parents('.form-action').attr('id'); if (target) { setActivePanel($('[href=#' + target + ']')); } setLoginContainerHeight(); }; var initTabs = function initTabs() { $(document).on('click', '.tabs a:not(.active)', function () { var el = $(this), target = el.attr('href'); setActivePanel($('[href=' + target + ']')); setLoginContainerHeight(); return false; }); }; var App = { init: function initAmberApp() { //INIT MESSAGES $(document).on('ajaxComplete messageChange', Messages.init); if ($('#messages div').length) { $(document).trigger('messageChange'); } window.Tunefish = Ember.Application.create({ rootElement: '#app_container' }); Tunefish.ApplicationAdapter = DS.RESTAdapter.extend({ namespace: 'vote/ajax' }); Tunefish.Band = DS.Model.extend({ name: DS.attr('string'), members: DS.attr('number'), city: DS.attr('string'), website: DS.attr('string'), facebookUrl: DS.attr('string'), youtubeUrl: DS.attr('string'), descp: DS.attr('string'), image: DS.attr('string'), thumbnail: DS.attr('string'), distance: DS.attr('number'), voteCount: DS.attr('number'), voteAverage: DS.attr('number'), voted: DS.attr('boolean'), ownVote: DS.attr('number'), comments: DS.hasMany('comment'), tracks: DS.hasMany('track'), bandBG: function() { return 'background-image: url(\''+this.get('image') + '\');'; }.property('image'), map: function() { return 'http://maps.googleapis.com/maps/api/staticmap?key=AIzaSyDRzrscCqKGd66mLS6jOayfUw9d4SICKOY&markers=' + this.get('city') + '&zoom=10&size=550x300&sensor=false'; }.property('city') }); Tunefish.Comment = DS.Model.extend({ author: DS.attr('string'), timestamp: DS.attr('string'), message: DS.attr('string'), band: DS.belongsTo('band') }); Tunefish.Track = DS.Model.extend({ trackname: DS.attr('string'), url: DS.attr('string'), band: DS.belongsTo('band') }); Ember.LinkView.reopen({ attributeBindings: ['data-sort', 'data-voted'] }); Tunefish.VotecontrolsView = Ember.View.extend({ templateName: 'votecontrols', classNames: ['voting'] }); Tunefish.StarView = Ember.View.extend(Ember.ViewTargetActionSupport, { tagName: 'a', templateName: 'star', classNameBindings: ['active'], attributeBindings: ['href'], href: '#', active: function () { return this.get('band.ownVote') >= this.get('vote'); }.property('band.ownVote', 'vote'), click: function() { this.triggerAction({ action: 'vote', actionContext: this.get('vote') }); return false; } }); Tunefish.MainView = Ember.View.extend({ didInsertElement: function () { var seek = document.getElementById('seek'); var audio = document.getElementById('tunefishPlayer'); var seekBlocked, audioPaused = false; function createRangeInputChangeHelper(range, inputFn, changeFn) { var inputTimer, releaseTimer, isActive; var destroyRelease = function() { clearTimeout(releaseTimer); range.removeEventListener('blur', releaseRange, false); document.removeEventListener('mouseup', releaseRange, false); }; var setupRelease = function () { if (!isActive) { destroyRelease(); isActive = true; range.addEventListener('blur', releaseRange, false); document.addEventListener('mouseup', releaseRange, true); } }; var _releaseRange = function () { if (isActive) { destroyRelease(); isActive = false; if (changeFn) { changeFn(); } } }; var releaseRange = function () { setTimeout(_releaseRange, 9); }; var onInput = function () { if (inputFn) { clearTimeout(inputTimer); inputTimer = setTimeout(inputFn); } clearTimeout(releaseTimer); releaseTimer = setTimeout(releaseRange, 999); if (!isActive) { setupRelease(); } }; range.addEventListener('input', onInput, false); range.addEventListener('change', onInput, false); } function onSeek() { if (!seekBlocked) { seekBlocked = true; audioPaused = audio.paused; audio.pause(); } audio.currentTime = seek.value; } function onSeekRelease() { if (!audioPaused) { audio.play(); } seekBlocked = false; } createRangeInputChangeHelper(seek, onSeek, onSeekRelease); } }); Tunefish.QueueitemView = Ember.View.extend({ tagName: 'li', classNameBindings: ['isPlaying:playing'], isPlaying: function () { return this.get('item.index') === this.get('controller.currentIndex'); }.property('item', 'controller.currentIndex') }); Tunefish.BandsingleView = Ember.View.extend({ tagName: 'div', classNames: ['content-area band-view'], didInsertElement: function () { $('#tunefish_loading').hide(); } }); Tunefish.BandgridView = Ember.View.extend({ tagName: 'div', classNames: ['content-area band-grid'], didInsertElement: function () { $('#tunefish_loading').hide(); // TODO add me for funky animations /* this.$().mixItUp({ selectors: { target: '.band-tile' }, animation: { duration: 700, effects: 'fade translateY(50px) stagger(25ms)', //easing: 'cubic-bezier(0.86, 0, 0.07, 1)', reverseOut: true } }); */ } }); Tunefish.Router.map(function () { this.resource('main', {'path': '/'}, function () { this.resource('bands', { path: '/bands/' }); this.resource('band', { path: '/bands/:band_id'}); }); }); Tunefish.BandsRoute = Ember.Route.extend({ model: function () { return this.store.find('band'); } }); Tunefish.BandRoute = Ember.Route.extend({ model: function (params) { return this.store.find('band', params.band_id); } }); function shuffleArray(array) { // see http://stackoverflow.com/a/2450976 var currentIndex = array.length, temporaryValue, randomIndex; while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } } Tunefish.MainController = Ember.ObjectController.extend({ tracks: [], currentIndex: -1, current: null, currentTime: 0, currentDuration: 0, playerState: 'idle', player: function () { return document.getElementById('#tunefishPlayer'); }, actions: { vote: function (vote) { var current = this.get('current'); if (current === null) { return; } var band = current.get('band'); band.set('ownVote', vote); band.save(); }, clear: function() { var tracks = this.get('tracks'); this.send('pause'); this.set('current', null); this.set('currentIndex', -1); this.set('currentTime', '0'); this.set('currentDuration', '0'); tracks.clear(); }, addTrack: function (track, autoplay) { autoplay = typeof autoplay !== 'undefined' ? autoplay : true; var currentIndex = this.get('currentIndex'); var tracks = this.get('tracks'); tracks.pushObject({ 'index': tracks.length, 'track': track }); if (currentIndex < 0 && tracks.length > 0) { this.send('next'); if (autoplay) { this.send('play'); } } }, jumpTo: function (index) { var tracks = this.get('tracks'); if (index >= 0 && index < tracks.length) { this.set('currentIndex', index); this.set('current', tracks.get(index).track); } }, play: function () { var self = this; var currentIndex = this.get('currentIndex'); var $player = $('#tunefishPlayer'); if (currentIndex === -1) { return; } this.set('playerState', 'playing'); $player.attr('autoplay', 'autoplay'); $player.get(0).play(); $player.on('ended', function () { self.send('next'); }); $player.on('timeupdate', function () { self.set('currentTime', Math.ceil($player.get(0).currentTime)); self.set('currentDuration', Math.ceil($player.get(0).duration)); }); }, pause: function () { var $player = $('#tunefishPlayer'); $player.removeAttr('autoplay'); $player.get(0).pause(); $player.off('ended'); $player.off('timeupdate'); this.set('playerState', 'idle'); }, next: function () { var currentIndex = this.get('currentIndex'); var tracks = this.get('tracks'); if (currentIndex < tracks.length - 1) { this.set('currentIndex', currentIndex + 1); this.set('current', tracks.get(currentIndex + 1).track); } }, prev: function () { var currentIndex = this.get('currentIndex'); var tracks = this.get('tracks'); if (currentIndex > 0) { this.set('currentIndex', currentIndex - 1); this.set('current', tracks.get(currentIndex - 1).track); } }, addUnvotedTracks: function () { var self = this; this.store.findAll('band').then(function(bands) { bands.forEach(function(band) { var voted = band.get('voted'); if(!voted) { var tracks = band.get('tracks'); var length = tracks.get('length'); var idx = Math.floor(Math.random() * length); var track = tracks.objectAt(idx); self.send('addTrack', track, false); } }); }); }, shuffle: function() { var tracks = []; var shuffledTracks = []; this.get('tracks').forEach(function(track) { shuffledTracks.pushObject(track.track); }); shuffleArray(shuffledTracks); for (var i = 0; i < shuffledTracks.length; i++) { tracks.pushObject({ index: i, track: shuffledTracks[i] }); } this.set('tracks', tracks); this.send('jumpTo', 0); } } }); Tunefish.BandController = Ember.ObjectController.extend({ needs: ['main'], comment: '', actions: { vote: function (vote) { var band = this.get('model'); band.set('ownVote', vote); band.save(); }, addComment: function () { var comment = this.store.createRecord('comment', { message: this.get('comment'), band: this.get('model') }); comment.save(); }, addAllTracks: function () { var self = this; var tracks = this.get('model.tracks'); tracks.forEach(function(track){ self.get('controllers.main').send('addTrack', track); }); }, addTrack: function (track) { this.get('controllers.main').send('addTrack', track); } } }); } }; var Login = { init: function initLoginPage() { checkInvalidLogin(); initTabs(); } }; var Messages = { init: function initMessages() { var messageContainer = $('#messages'), messages = $('div', messageContainer); messages .velocity('transition.slideDownIn', {stagger: 250}) .delay(5000) .velocity('transition.slideUpOut', {stagger: 250, backwards: true}); } }; /* PUBLIC FUNCTION EXPORTS */ return { /* PUBLIC FUNCTIONS HERE */ App: App, Login: Login, Messages: Messages }; })(jQuery, window);
Clean comment after submit
client/src/js/lib/helpers-vote.js
Clean comment after submit
<ide><path>lient/src/js/lib/helpers-vote.js <ide> band: this.get('model') <ide> }); <ide> comment.save(); <add> this.set('comment', ''); <ide> }, <ide> <ide> addAllTracks: function () {
JavaScript
mit
d3d5d4d78d65baab572803f031e5eb267f8d1952
0
ethantw/Han,ethantw/Han
define(function() { var $ = { /** * Query selectors which return arrays of the resulted * node lists. */ id: function( selector, $context ) { return ( $context || document ).getElementById( selector ) }, tag: function( selector, $context ) { return this.makeArray( ( $context || document ).getElementsByTagName( selector ) ) }, qs: function( selector, $context ) { return ( $context || document ).querySelector( selector ) }, qsa: function( selector, $context ) { return this.makeArray( ( $context || document ).querySelectorAll( selector ) ) }, /** * Create a document fragment, a text node with text * or an element with/without classes. */ create: function( name, clazz ) { var $elmt = '!' === name ? document.createDocumentFragment() : '' === name ? document.createTextNode( clazz || '' ) : document.createElement( name ) try { if ( clazz ) { $elmt.className = clazz } } catch (e) {} return $elmt }, /** * Clone a DOM node (text, element or fragment) deeply * or childlessly. */ clone: function( $node, deep ) { return $node.cloneNode( typeof deep === 'boolean' ? deep : true ) }, /** * Remove a node (text, element or fragment). */ remove: function( $node ) { return $node.parentNode.removeChild( $node ) }, /** * Set attributes all in once with an object. */ setAttr: function( target, attr ) { if ( typeof attr !== 'object' ) return var len = attr.length // Native `NamedNodeMap``: if ( typeof attr[0] === 'object' && 'name' in attr[0] ) { for ( var i = 0; i < len; i++ ) { if ( attr[ i ].value !== undefined ) { target.setAttribute( attr[ i ].name, attr[ i ].value ) } } // Plain object: } else { for ( var name in attr ) { if ( attr.hasOwnProperty( name ) && attr[ name ] !== undefined ) { target.setAttribute( name, attr[ name ] ) } } } return target }, /** * Indicate whether or not the given node is an * element. */ isElmt: function( $node ) { return $node && $node.nodeType === Node.ELEMENT_NODE }, /** * Indicate whether or not the given node should * be ignored (`<wbr>` or comments). */ isIgnorable: function( $node ) { if ( !$node ) return false return ( $node.nodeName === 'WBR' || $node.nodeType === Node.COMMENT_NODE ) }, /** * Convert array-like objects into real arrays. */ makeArray: function( object ) { return Array.prototype.slice.call( object ) }, /** * Extend target with an object. */ extend: function( target, object ) { if (( typeof target === 'object' || typeof target === 'function' ) && typeof object === 'object' ) { for ( var name in object ) { if (object.hasOwnProperty( name )) { target[ name ] = object[ name ] } } } return target } } return $ })
src/js/method.js
define(function() { var $ = { /** * Query selectors which return arrays of the resulted * node lists. */ id: function( selector, $context ) { return ( $context || document ).getElementById( selector ) }, tag: function( selector, $context ) { return this.makeArray( ( $context || document ).getElementsByTagName( selector ) ) }, qsa: function( selector, $context ) { return this.makeArray( ( $context || document ).querySelectorAll( selector ) ) }, /** * Create a document fragment, a text node with text * or an element with/without classes. */ create: function( name, clazz ) { var $elmt = '!' === name ? document.createDocumentFragment() : '' === name ? document.createTextNode( clazz || '' ) : document.createElement( name ) try { if ( clazz ) { $elmt.className = clazz } } catch (e) {} return $elmt }, /** * Clone a DOM node (text, element or fragment) deeply * or childlessly. */ clone: function( $node, deep ) { return $node.cloneNode( typeof deep === 'boolean' ? deep : true ) }, /** * Remove a node (text, element or fragment). */ remove: function( $node ) { return $node.parentNode.removeChild( $node ) }, /** * Set attributes all in once with an object. */ setAttr: function( target, attr ) { if ( typeof attr !== 'object' ) return var len = attr.length // Native `NamedNodeMap``: if ( typeof attr[0] === 'object' && 'name' in attr[0] ) { for ( var i = 0; i < len; i++ ) { if ( attr[ i ].value !== undefined ) { target.setAttribute( attr[ i ].name, attr[ i ].value ) } } // Plain object: } else { for ( var name in attr ) { if ( attr.hasOwnProperty( name ) && attr[ name ] !== undefined ) { target.setAttribute( name, attr[ name ] ) } } } return target }, /** * Indicate whether or not the given node is an * element. */ isElmt: function( $node ) { return $node && $node.nodeType === Node.ELEMENT_NODE }, /** * Indicate whether or not the given node should * be ignored (`<wbr>` or comments). */ isIgnorable: function( $node ) { if ( !$node ) return false return ( $node.nodeName === 'WBR' || $node.nodeType === Node.COMMENT_NODE ) }, /** * Convert array-like objects into real arrays. */ makeArray: function( object ) { return Array.prototype.slice.call( object ) }, /** * Extend target with an object. */ extend: function( target, object ) { if (( typeof target === 'object' || typeof target === 'function' ) && typeof object === 'object' ) { for ( var name in object ) { if (object.hasOwnProperty( name )) { target[ name ] = object[ name ] } } } return target } } return $ })
Add `.qs()` method
src/js/method.js
Add `.qs()` method
<ide><path>rc/js/method.js <ide> return this.makeArray( <ide> ( $context || document ).getElementsByTagName( selector ) <ide> ) <add> }, <add> <add> qs: function( selector, $context ) { <add> return ( $context || document ).querySelector( selector ) <ide> }, <ide> <ide> qsa: function( selector, $context ) {
JavaScript
mit
34155fff8f074adf8aa2558304838be7139de192
0
undoZen/oauth2-errorhandlers
'use strict'; module.exports = function (os) { var result = []; result.push(function(req, res, next) { var err; err = new Error('Resource not found.'); err.code = 'invalid_request'; err.status = 404; return next(err); }); result.push(function(err, req, res, next) { if (err.message === 'Unauthorized') { err.message = req.url === '/token' ? 'auth failed' : 'access token is required'; err.code = 'access_denied'; err.status = 403; } else if (!err.status || err.status >= 500) { console.error(err.stack); } return next(err); }); if (os && 'function' === typeof os.errorHandler) { result.push(os.errorHandler()); } return result; }
index.js
'use strict'; module.exports = function (os) { var result = []; result.push(function(req, res, next) { var err; err = new Error('Resource not found.'); err.code = 'invalid_request'; err.status = 404; return next(err); }); result.push(function(err, req, res, next) { if (err.message === 'Unauthorized') { err.message = req.url === '/token' ? 'auth failed' : 'access token is required'; err.code = 'access_denied'; err.status = 403; } else if ((err.status != null) && err.status >= 500) { console.error(err.stack); } return next(err); }); if (os && 'function' === typeof os.errorHandler) { result.push(os.errorHandler()); } return result; }
print out unknown error to stderr
index.js
print out unknown error to stderr
<ide><path>ndex.js <ide> err.message = req.url === '/token' ? 'auth failed' : 'access token is required'; <ide> err.code = 'access_denied'; <ide> err.status = 403; <del> } else if ((err.status != null) && err.status >= 500) { <add> } else if (!err.status || err.status >= 500) { <ide> console.error(err.stack); <ide> } <ide> return next(err);
Java
bsd-3-clause
error: pathspec 'projects/core/src/main/java/gov/nih/nci/cabig/caaers/domain/GridIdentifiable.java' did not match any file(s) known to git
b0f3e6a958b5672a6afdb956a3c7b629997df7ee
1
CBIIT/caaers,NCIP/caaers,NCIP/caaers,NCIP/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,CBIIT/caaers,CBIIT/caaers
package gov.nih.nci.cabig.caaers.domain; /** * * @author Sujith Vellat Thayyilthodi * */ public interface GridIdentifiable { /** * @return the grid-scoped unique identifier for this object */ String getGridId(); /** * Specify the grid-scoped unique identifier for this object * @param gridId */ void setGridId(String gridId); }
projects/core/src/main/java/gov/nih/nci/cabig/caaers/domain/GridIdentifiable.java
Interface for Grid Identifiable Domain objects. SVN-Revision: 288
projects/core/src/main/java/gov/nih/nci/cabig/caaers/domain/GridIdentifiable.java
Interface for Grid Identifiable Domain objects.
<ide><path>rojects/core/src/main/java/gov/nih/nci/cabig/caaers/domain/GridIdentifiable.java <add>package gov.nih.nci.cabig.caaers.domain; <add> <add>/** <add> * <add> * @author Sujith Vellat Thayyilthodi <add> * */ <add>public interface GridIdentifiable { <add> <add> /** <add> * @return the grid-scoped unique identifier for this object <add> */ <add> String getGridId(); <add> <add> /** <add> * Specify the grid-scoped unique identifier for this object <add> * @param gridId <add> */ <add> void setGridId(String gridId); <add> <add>}
JavaScript
mit
e47fbac0ab5a539e57494ef190896b4d36f528f9
0
oropezahector/the-project,oropezahector/the-project
var path = require('path'); var models = require('../models'); module.exports = function(app, passport) { app.get('/logout', function(req, res) { req.logout(); res.redirect('/'); }); app.get('/', function(req, res) { res.render('index', { title: 'Test' }); }); app.get('/:id/:name', function(req, res) { var id = req.params.id; var name = req.params.name; res.render('index', { user: name, id: id }); }); app.get('/auth/facebook', passport.authenticate('facebook', { authType: 'reauthenticate', scope: ['email', 'user_friends'] })); app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/errorlogin' }), function(req, res) { console.log(req.user); res.redirect('/' + req.user.id + '/' + req.user._json.name) }); app.get('/errorlogin', function(req, res) { console.log('Error Logging in'); res.redirect('/'); }); }
controllers/html-routes.js
var path = require('path'); var models = require('../models'); module.exports = function(app, passport) { app.get('/logout', function(req, res) { req.logout(); res.redirect('/'); }); app.get('/', function(req, res) { res.render('index', { title: 'Test' }); }); app.get('/:id/:name', function(req, res) { var id = req.params.id; var name = req.params.name; res.render('index', { user: name, id:id }); }); }); app.get('/auth/facebook', passport.authenticate('facebook', {authType: 'reauthenticate', scope: ['email', 'user_friends'] })); app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/errorlogin' }), function(req, res) { console.log(req.user); res.redirect('/'+ req.user.id + '/'+ req.user._json.name) }); app.get('/errorlogin', function(req, res) { console.log('Error Logging in'); res.redirect('/'); }); }
Fixed callback after login
controllers/html-routes.js
Fixed callback after login
<ide><path>ontrollers/html-routes.js <ide> app.get('/:id/:name', function(req, res) { <ide> var id = req.params.id; <ide> var name = req.params.name; <del> res.render('index', { user: name, id:id }); <del> }); <add> res.render('index', { user: name, id: id }); <ide> }); <ide> <ide> app.get('/auth/facebook', <del> passport.authenticate('facebook', {authType: 'reauthenticate', scope: ['email', 'user_friends'] })); <add> passport.authenticate('facebook', { authType: 'reauthenticate', scope: ['email', 'user_friends'] })); <ide> <ide> app.get('/auth/facebook/callback', <ide> passport.authenticate('facebook', { failureRedirect: '/errorlogin' }), <ide> function(req, res) { <ide> console.log(req.user); <del> res.redirect('/'+ req.user.id + '/'+ req.user._json.name) <add> res.redirect('/' + req.user.id + '/' + req.user._json.name) <ide> }); <ide> <ide> app.get('/errorlogin', function(req, res) {
Java
bsd-3-clause
081d07fcb6ac88e9c1a981576e2142acb227b3ed
0
Chiru/ServiceFusionAR,Chiru/ServiceFusionAR
package fi.cie.chiru.servicefusionar.calendar; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import commands.Command; import util.IO; import util.Vec; import fi.cie.chiru.servicefusionar.R; import fi.cie.chiru.servicefusionar.serviceApi.ServiceManager; import gl.GLFactory; import gl.scenegraph.MeshComponent; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.GridLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.GridLayout.Spec; public class ServiceFusionCalendar { private static final String LOG_TAG = "ServiceFusionCalendar"; private ServiceManager serviceManager; private String eventsFile = "calendar_events.txt"; private List<CalendarEvent> events; int currentdayOfMonth; private MeshComponent calendar; private MeshComponent eventsToday; private int curCol, curRow; private float dayGridWidth = 1.7f; private float dayGridHeight = 1.4f; private boolean eventsVisible; private float camOffsetX = 12.0f; private float camOffsetY = 6.0f; private float camOffsetZ = -40.0f; private float eventsOffsetX = 10.0f; private float eventsOffsetY = 6.1f; private String months[] = { "TAMMIKUU", "HELMIKUU", "MAALISKUU", "HUHTIKUU", "TOUKOKUU", "KESÄKUU", "HEINÄKUU", "ELOKUU", "SYYSKUU", "LOKAKUU", "MARRASKUU", "JOULUKUU" }; public ServiceFusionCalendar(ServiceManager serviceManager) { events = new ArrayList<CalendarEvent>(); this.serviceManager = serviceManager; eventsVisible = false; currentdayOfMonth = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); // initEventsList(); createCalendar(); } private void createCalendar() { Handler mHandler = new Handler(Looper.getMainLooper()); mHandler.post(new Runnable() { @Override public void run() { LayoutInflater li = (LayoutInflater) serviceManager.getSetup().myTargetActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = li.inflate(R.layout.calendar2, null); GridLayout gl = (GridLayout)v.findViewById(R.id.kalenteri_gridlayout); populateCalendar(gl); TextView month = (TextView)v.findViewById(R.id.kuukausi); month.setText(months[Calendar.MONTH]); TextView year = (TextView)v.findViewById(R.id.vuosi); year.setText(""+Calendar.getInstance().get(Calendar.YEAR)); RelativeLayout root = (RelativeLayout) serviceManager.getSetup().getGuiSetup().getMainContainerView(); root.addView(v); v.setVisibility(View.GONE); calendar = GLFactory.getInstance().newTexturedSquare("calendar", IO.loadBitmapFromView(v, 35, 35)); calendar.setOnClickCommand(new FlipEventsVisibility()); Vec camPos = serviceManager.getSetup().getCamera().getPosition(); serviceManager.getSetup().world.add(calendar); calendar.setPosition(new Vec(camPos.x + camOffsetX, camPos.y + camOffsetY, camPos.z + camOffsetZ)); calendar.setRotation(new Vec(90.0f, 0.0f, 180.0f)); calendar.setScale(new Vec(12.0f, 1.0f, 10.0f)); View eventv = createEvents(li); root.addView(eventv); eventv.setVisibility(View.GONE); eventsToday = GLFactory.getInstance().newTexturedSquare("eventsToday", IO.loadBitmapFromView(eventv, 35, 35)); eventsToday.setPosition(new Vec(camPos.x + eventsOffsetX +((float)curCol)*dayGridWidth , camPos.y + eventsOffsetY-((float)curRow)*dayGridHeight, camPos.z + camOffsetZ)); eventsToday.setRotation(new Vec(90.0f, 0.0f, 180.0f)); eventsToday.setScale(new Vec(8.0f, 1.0f, 7.0f)); serviceManager.getSetup().camera.attachToCamera(calendar); serviceManager.getSetup().camera.attachToCamera(eventsToday); } }); } private void populateCalendar(GridLayout gl) { Spec colSpec; Spec rowSpec; GridLayout.LayoutParams p; TextView tv; GregorianCalendar gCal = new GregorianCalendar(2013, Calendar.MONTH, 1); int currentDay = gCal.get(Calendar.DAY_OF_WEEK); gCal.add(Calendar.DAY_OF_YEAR, Calendar.SUNDAY - currentDay); for (int i = 0; i < gl.getRowCount()-1; i++) { for (int j = 0; j < gl.getColumnCount()-1; j++) { colSpec = GridLayout.spec(j, 1); rowSpec = GridLayout.spec(i, 1); p = new GridLayout.LayoutParams(rowSpec, colSpec); p.setGravity(Gravity.START|Gravity.END); //p.setMargins(0, 10, 0, 0); tv = new TextView(serviceManager.getSetup().myTargetActivity); tv.setTextSize(40); tv.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL); if(gCal.get(Calendar.DAY_OF_MONTH) == currentdayOfMonth) { tv.setBackgroundResource(R.drawable.bordersblue); curCol = j; curRow = i; } else tv.setBackgroundResource(R.drawable.borders); tv.setText((""+ gCal.get(Calendar.DAY_OF_MONTH))); gl.addView(tv, p); gCal.add(Calendar.DAY_OF_YEAR, 1); } } } public View createEvents(LayoutInflater li) { View v = li.inflate(R.layout.calendar_events, null); TextView curDay = (TextView)v.findViewById(R.id.tänään); curDay.setText(""+currentdayOfMonth); return v; } public void addEvent(final CalendarEvent ce) { Handler mHandler = new Handler(Looper.getMainLooper()); mHandler.post(new Runnable() { @Override public void run() { LayoutInflater li = (LayoutInflater) serviceManager.getSetup().myTargetActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = li.inflate(R.layout.calendar_events, null); TextView curDay = (TextView)v.findViewById(R.id.tänään); curDay.setText(""+currentdayOfMonth); TextView newTime = (TextView)v.findViewById(R.id.aika_tapahtuma3); newTime.setText(ce.getTime()); newTime.setVisibility(View.VISIBLE); TextView newEvent = (TextView)v.findViewById(R.id.tapahtuma3); newEvent.setText(ce.getEvent()); newEvent.setVisibility(View.VISIBLE); RelativeLayout root = (RelativeLayout) serviceManager.getSetup().getGuiSetup().getMainContainerView(); root.addView(v); v.setVisibility(View.GONE); Vec eventPos = eventsToday.getPosition(); Vec eventRot = calendar.getRotation(); serviceManager.getSetup().camera.detachFromCamera(eventsToday); serviceManager.getSetup().world.remove(eventsToday); //eventsToday = null; eventsToday = GLFactory.getInstance().newTexturedSquare("eventsTodayUpdated", IO.loadBitmapFromView(v, 35, 35)); serviceManager.getSetup().world.add(eventsToday); eventsToday.setPosition(new Vec(eventPos.x, eventPos.y, eventPos.z)); eventsToday.setRotation(new Vec(90.0f, eventRot.y, 180.0f)); eventsToday.setScale(new Vec(8.0f, 1.0f, 7.0f)); serviceManager.getSetup().camera.attachToCamera(eventsToday); showEvents(true); } }); } public void showEvents(boolean visible) { if(visible) { //calendar.addChild(eventsToday); // Vec camPos = serviceManager.getSetup().getCamera().getPosition(); serviceManager.getSetup().world.add(eventsToday); // eventsToday.setPosition(new Vec(camPos.x + eventsOffsetX +((float)curCol)*dayGridWidth , camPos.y + eventsOffsetY-((float)curRow)*dayGridHeight, camPos.z + camOffsetZ)); // eventsToday.setRotation(new Vec(90.0f, 0.0f, 180.0f)); // eventsToday.setScale(new Vec(8.0f, 1.0f, 7.0f)); eventsVisible = true; } else { serviceManager.getSetup().world.remove(eventsToday); eventsVisible = false; } } public void visible(boolean visible) { if(!visible) { serviceManager.getSetup().world.remove(calendar); serviceManager.getSetup().world.remove(eventsToday); } else { serviceManager.getSetup().world.add(calendar); serviceManager.getSetup().world.add(eventsToday); } } public void initEventsList() { try { InputStream in; in = serviceManager.getSetup().myTargetActivity.getAssets().open(eventsFile); String fileContent = IO.convertInputStreamToString(in); String tmpEvents[] = fileContent.split("/n"); for(int i=0; i<tmpEvents.length; i++) { String singleEvent[] = tmpEvents[i].split("#"); events.add(new CalendarEvent(singleEvent[0], singleEvent[1])); } } catch (IOException e) { Log.d(LOG_TAG, "couldn't open file: " + eventsFile); e.printStackTrace(); } } private class FlipEventsVisibility extends Command { @Override public boolean execute() { if(eventsVisible) showEvents(false); else showEvents(true); return true; } } }
src/fi/cie/chiru/servicefusionar/calendar/ServiceFusionCalendar.java
package fi.cie.chiru.servicefusionar.calendar; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import commands.Command; import util.IO; import util.Vec; import fi.cie.chiru.servicefusionar.R; import fi.cie.chiru.servicefusionar.serviceApi.ServiceManager; import gl.GLFactory; import gl.scenegraph.MeshComponent; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.GridLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.GridLayout.Spec; public class ServiceFusionCalendar { private static final String LOG_TAG = "ServiceFusionCalendar"; private ServiceManager serviceManager; private String eventsFile = "calendar_events.txt"; private List<CalendarEvent> events; int currentdayOfMonth; private MeshComponent calendar; private MeshComponent eventsToday; private int curCol, curRow; private float dayGridWidth = 1.7f; private float dayGridHeight = 1.4f; private boolean eventsVisible; private float camOffsetX = 12.0f; private float camOffsetY = 6.0f; private float camOffsetZ = -40.0f; private float eventsOffsetX = 10.0f; private float eventsOffsetY = 6.1f; private String months[] = { "TAMMIKUU", "HELMIKUU", "MAALISKUU", "HUHTIKUU", "TOUKOKUU", "KESÄKUU", "HEINÄKUU", "ELOKUU", "SYYSKUU", "LOKAKUU", "MARRASKUU", "JOULUKUU" }; public ServiceFusionCalendar(ServiceManager serviceManager) { events = new ArrayList<CalendarEvent>(); this.serviceManager = serviceManager; eventsVisible = false; currentdayOfMonth = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); // initEventsList(); createCalendar(); } private void createCalendar() { Handler mHandler = new Handler(Looper.getMainLooper()); mHandler.post(new Runnable() { @Override public void run() { LayoutInflater li = (LayoutInflater) serviceManager.getSetup().myTargetActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = li.inflate(R.layout.calendar2, null); GridLayout gl = (GridLayout)v.findViewById(R.id.kalenteri_gridlayout); populateCalendar(gl); TextView month = (TextView)v.findViewById(R.id.kuukausi); month.setText(months[Calendar.MONTH]); TextView year = (TextView)v.findViewById(R.id.vuosi); year.setText(""+Calendar.getInstance().get(Calendar.YEAR)); RelativeLayout root = (RelativeLayout) serviceManager.getSetup().getGuiSetup().getMainContainerView(); root.addView(v); v.setVisibility(View.GONE); calendar = GLFactory.getInstance().newTexturedSquare("calendar", IO.loadBitmapFromView(v, 35, 35)); calendar.setOnClickCommand(new FlipEventsVisibility()); Vec camPos = serviceManager.getSetup().getCamera().getPosition(); serviceManager.getSetup().world.add(calendar); calendar.setPosition(new Vec(camPos.x + camOffsetX, camPos.y + camOffsetY, camPos.z + camOffsetZ)); calendar.setRotation(new Vec(90.0f, 0.0f, 180.0f)); calendar.setScale(new Vec(12.0f, 1.0f, 10.0f)); View eventv = createEvents(li); root.addView(eventv); eventv.setVisibility(View.GONE); eventsToday = GLFactory.getInstance().newTexturedSquare("eventsToday", IO.loadBitmapFromView(eventv, 35, 35)); eventsToday.setPosition(new Vec(camPos.x + eventsOffsetX +((float)curCol)*dayGridWidth , camPos.y + eventsOffsetY-((float)curRow)*dayGridHeight, camPos.z + camOffsetZ)); eventsToday.setRotation(new Vec(90.0f, 0.0f, 180.0f)); eventsToday.setScale(new Vec(8.0f, 1.0f, 7.0f)); serviceManager.getSetup().camera.attachToCamera(calendar); serviceManager.getSetup().camera.attachToCamera(eventsToday); } }); } private void populateCalendar(GridLayout gl) { Spec colSpec; Spec rowSpec; GridLayout.LayoutParams p; TextView tv; GregorianCalendar gCal = new GregorianCalendar(2013, Calendar.MONTH, 1); int currentDay = gCal.get(Calendar.DAY_OF_WEEK); gCal.add(Calendar.DAY_OF_YEAR, Calendar.SUNDAY - currentDay); for (int i = 0; i < gl.getRowCount()-1; i++) { for (int j = 0; j < gl.getColumnCount()-1; j++) { colSpec = GridLayout.spec(j, 1); rowSpec = GridLayout.spec(i, 1); p = new GridLayout.LayoutParams(rowSpec, colSpec); p.setGravity(Gravity.START|Gravity.END); //p.setMargins(0, 10, 0, 0); tv = new TextView(serviceManager.getSetup().myTargetActivity); tv.setTextSize(40); tv.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL); if(gCal.get(Calendar.DAY_OF_MONTH) == currentdayOfMonth) { tv.setBackgroundResource(R.drawable.bordersblue); curCol = j; curRow = i; } else tv.setBackgroundResource(R.drawable.borders); tv.setText((""+ gCal.get(Calendar.DAY_OF_MONTH))); gl.addView(tv, p); gCal.add(Calendar.DAY_OF_YEAR, 1); } } } public View createEvents(LayoutInflater li) { View v = li.inflate(R.layout.calendar_events, null); TextView curDay = (TextView)v.findViewById(R.id.tänään); curDay.setText(""+currentdayOfMonth); return v; } public void addEvent(final CalendarEvent ce) { Handler mHandler = new Handler(Looper.getMainLooper()); mHandler.post(new Runnable() { @Override public void run() { LayoutInflater li = (LayoutInflater) serviceManager.getSetup().myTargetActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = li.inflate(R.layout.calendar_events, null); TextView curDay = (TextView)v.findViewById(R.id.tänään); curDay.setText(""+currentdayOfMonth); TextView newTime = (TextView)v.findViewById(R.id.aika_tapahtuma3); newTime.setText(ce.getTime()); newTime.setVisibility(View.VISIBLE); TextView newEvent = (TextView)v.findViewById(R.id.tapahtuma3); newEvent.setText(ce.getEvent()); newEvent.setVisibility(View.VISIBLE); RelativeLayout root = (RelativeLayout) serviceManager.getSetup().getGuiSetup().getMainContainerView(); root.addView(v); v.setVisibility(View.GONE); serviceManager.getSetup().world.remove(eventsToday); eventsToday = null; eventsToday = GLFactory.getInstance().newTexturedSquare("eventsTodayUpdated", IO.loadBitmapFromView(v, 35, 35)); showEvents(true); } }); } public void showEvents(boolean visible) { if(visible == true) { //calendar.addChild(eventsToday); // Vec camPos = serviceManager.getSetup().getCamera().getPosition(); serviceManager.getSetup().world.add(eventsToday); // eventsToday.setPosition(new Vec(camPos.x + eventsOffsetX +((float)curCol)*dayGridWidth , camPos.y + eventsOffsetY-((float)curRow)*dayGridHeight, camPos.z + camOffsetZ)); // eventsToday.setRotation(new Vec(90.0f, 0.0f, 180.0f)); // eventsToday.setScale(new Vec(8.0f, 1.0f, 7.0f)); eventsVisible = true; } else { serviceManager.getSetup().world.remove(eventsToday); eventsVisible = false; } } public void initEventsList() { try { InputStream in; in = serviceManager.getSetup().myTargetActivity.getAssets().open(eventsFile); String fileContent = IO.convertInputStreamToString(in); String tmpEvents[] = fileContent.split("/n"); for(int i=0; i<tmpEvents.length; i++) { String singleEvent[] = tmpEvents[i].split("#"); events.add(new CalendarEvent(singleEvent[0], singleEvent[1])); } } catch (IOException e) { Log.d(LOG_TAG, "couldn't open file: " + eventsFile); e.printStackTrace(); } } private class FlipEventsVisibility extends Command { @Override public boolean execute() { if(eventsVisible) showEvents(false); else showEvents(true); return true; } } }
The visibility of the camera can be changed.
src/fi/cie/chiru/servicefusionar/calendar/ServiceFusionCalendar.java
The visibility of the camera can be changed.
<ide><path>rc/fi/cie/chiru/servicefusionar/calendar/ServiceFusionCalendar.java <ide> root.addView(v); <ide> v.setVisibility(View.GONE); <ide> <add> Vec eventPos = eventsToday.getPosition(); <add> Vec eventRot = calendar.getRotation(); <add> <add> serviceManager.getSetup().camera.detachFromCamera(eventsToday); <ide> serviceManager.getSetup().world.remove(eventsToday); <del> eventsToday = null; <add> //eventsToday = null; <ide> eventsToday = GLFactory.getInstance().newTexturedSquare("eventsTodayUpdated", IO.loadBitmapFromView(v, 35, 35)); <del> showEvents(true); <add> serviceManager.getSetup().world.add(eventsToday); <add> <add> eventsToday.setPosition(new Vec(eventPos.x, eventPos.y, eventPos.z)); <add> eventsToday.setRotation(new Vec(90.0f, eventRot.y, 180.0f)); <add> eventsToday.setScale(new Vec(8.0f, 1.0f, 7.0f)); <add> serviceManager.getSetup().camera.attachToCamera(eventsToday); <add> showEvents(true); <ide> } <ide> }); <ide> } <ide> public void showEvents(boolean visible) <ide> { <ide> <del> if(visible == true) <add> if(visible) <ide> { <ide> //calendar.addChild(eventsToday); <ide> // Vec camPos = serviceManager.getSetup().getCamera().getPosition(); <ide> { <ide> serviceManager.getSetup().world.remove(eventsToday); <ide> eventsVisible = false; <add> } <add> } <add> <add> public void visible(boolean visible) <add> { <add> if(!visible) <add> { <add> serviceManager.getSetup().world.remove(calendar); <add> serviceManager.getSetup().world.remove(eventsToday); <add> } <add> else <add> { <add> serviceManager.getSetup().world.add(calendar); <add> serviceManager.getSetup().world.add(eventsToday); <ide> } <ide> } <ide>
Java
apache-2.0
error: pathspec 'tests/junit/org/jgroups/tests/UnicastLoopbackTest.java' did not match any file(s) known to git
26d70cf0c60c9125680d61dc1530381935090f3e
1
rpelisse/JGroups,TarantulaTechnology/JGroups,pferraro/JGroups,pruivo/JGroups,Sanne/JGroups,ibrahimshbat/JGroups,rhusar/JGroups,slaskawi/JGroups,deepnarsay/JGroups,vjuranek/JGroups,pruivo/JGroups,danberindei/JGroups,pferraro/JGroups,ibrahimshbat/JGroups,rhusar/JGroups,ligzy/JGroups,dimbleby/JGroups,rpelisse/JGroups,belaban/JGroups,TarantulaTechnology/JGroups,dimbleby/JGroups,TarantulaTechnology/JGroups,tristantarrant/JGroups,ibrahimshbat/JGroups,Sanne/JGroups,slaskawi/JGroups,pruivo/JGroups,kedzie/JGroups,belaban/JGroups,ibrahimshbat/JGroups,dimbleby/JGroups,rhusar/JGroups,vjuranek/JGroups,rvansa/JGroups,slaskawi/JGroups,deepnarsay/JGroups,Sanne/JGroups,rvansa/JGroups,rpelisse/JGroups,danberindei/JGroups,belaban/JGroups,pferraro/JGroups,kedzie/JGroups,ligzy/JGroups,ligzy/JGroups,danberindei/JGroups,kedzie/JGroups,tristantarrant/JGroups,vjuranek/JGroups,deepnarsay/JGroups
package org.jgroups.tests; import junit.framework.TestCase; import org.jgroups.*; /** * Tests unicasts to self (loopback of transport protocol) * @author Bela Ban Dec 31 2003 * @version $Id: UnicastLoopbackTest.java,v 1.1 2004/01/01 00:54:55 belaban Exp $ */ public class UnicastLoopbackTest extends TestCase { JChannel channel=null; public UnicastLoopbackTest(String name) { super(name); } protected void setUp() throws Exception { channel=new JChannel(); channel.connect("demo-group"); } protected void tearDown() throws Exception { if(channel != null) { channel.close(); channel=null; } } public void testUnicastMsgs() throws ChannelClosedException, ChannelNotConnectedException, TimeoutException { int NUM=1000; for(int i=1; i <= NUM; i++) { channel.send(new Message(null, null, new Integer(i))); if(i % 100 == 0) System.out.println("-- sent " + i); } int received=0; while(received < NUM) { Object o=channel.receive(0); if(o instanceof Message) { Message m=(Message)o; Integer num=(Integer)m.getObject(); received++; if(num.intValue() % 100 == 0) System.out.println("-- received " + num); } } assertEquals(NUM, received); } public static void main(String[] args) { String[] testCaseName={UnicastLoopbackTest.class.getName()}; junit.textui.TestRunner.main(testCaseName); } }
tests/junit/org/jgroups/tests/UnicastLoopbackTest.java
new unit test
tests/junit/org/jgroups/tests/UnicastLoopbackTest.java
new unit test
<ide><path>ests/junit/org/jgroups/tests/UnicastLoopbackTest.java <add>package org.jgroups.tests; <add> <add>import junit.framework.TestCase; <add>import org.jgroups.*; <add> <add>/** <add> * Tests unicasts to self (loopback of transport protocol) <add> * @author Bela Ban Dec 31 2003 <add> * @version $Id: UnicastLoopbackTest.java,v 1.1 2004/01/01 00:54:55 belaban Exp $ <add> */ <add>public class UnicastLoopbackTest extends TestCase { <add> JChannel channel=null; <add> <add> <add> public UnicastLoopbackTest(String name) { <add> super(name); <add> } <add> <add> protected void setUp() throws Exception { <add> channel=new JChannel(); <add> channel.connect("demo-group"); <add> } <add> <add> protected void tearDown() throws Exception { <add> if(channel != null) { <add> channel.close(); <add> channel=null; <add> } <add> } <add> <add> <add> public void testUnicastMsgs() throws ChannelClosedException, ChannelNotConnectedException, TimeoutException { <add> int NUM=1000; <add> for(int i=1; i <= NUM; i++) { <add> channel.send(new Message(null, null, new Integer(i))); <add> if(i % 100 == 0) <add> System.out.println("-- sent " + i); <add> } <add> int received=0; <add> while(received < NUM) { <add> Object o=channel.receive(0); <add> if(o instanceof Message) { <add> Message m=(Message)o; <add> Integer num=(Integer)m.getObject(); <add> received++; <add> if(num.intValue() % 100 == 0) <add> System.out.println("-- received " + num); <add> } <add> } <add> assertEquals(NUM, received); <add> } <add> <add> public static void main(String[] args) { <add> String[] testCaseName={UnicastLoopbackTest.class.getName()}; <add> junit.textui.TestRunner.main(testCaseName); <add> } <add>}
Java
apache-2.0
db5c3a76674e52ad52c7dbb5b366b8532fe8a125
0
jayeshrpatel/githelp,jayeshrpatel/githelp,teosoft123/maven-php-plugin,Vaysman/maven-php-plugin,Vaysman/maven-php-plugin,teosoft123/maven-php-plugin,Vaysman/maven-php-plugin,jayeshrpatel/githelp,jayeshrpatel/githelp,php-maven/maven-php-plugin,Vaysman/maven-php-plugin,jayeshrpatel/githelp,php-maven/maven-php-plugin,Vaysman/maven-php-plugin,teosoft123/maven-php-plugin,teosoft123/maven-php-plugin,php-maven/maven-php-plugin,teosoft123/maven-php-plugin
/** * Copyright 2010-2012 by PHP-maven.org * * 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. */ package org.phpmaven.pear.impl; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.StringTokenizer; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.ArtifactResolutionRequest; import org.apache.maven.artifact.resolver.ArtifactResolutionResult; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Build; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.DefaultDependencyResolutionRequest; import org.apache.maven.project.DefaultProjectBuildingRequest; import org.apache.maven.project.DependencyResolutionException; import org.apache.maven.project.DependencyResolutionRequest; import org.apache.maven.project.DependencyResolutionResult; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuilder; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.project.ProjectBuildingRequest; import org.apache.maven.project.ProjectBuildingResult; import org.apache.maven.project.ProjectDependenciesResolver; import org.apache.maven.repository.RepositorySystem; import org.apache.maven.settings.Proxy; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.configuration.PlexusConfigurationException; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.phpmaven.core.ConfigurationParameter; import org.phpmaven.core.DeserializePhp; import org.phpmaven.core.IComponentFactory; import org.phpmaven.exec.IPhpExecutable; import org.phpmaven.exec.IPhpExecutableConfiguration; import org.phpmaven.exec.PhpCoreException; import org.phpmaven.exec.PhpException; import org.phpmaven.exec.PhpWarningException; import org.phpmaven.pear.IPearChannel; import org.phpmaven.pear.IPearUtility; import org.sonatype.aether.util.version.GenericVersionScheme; import org.sonatype.aether.version.InvalidVersionSpecificationException; /** * Implementation of a pear utility via PHP.EXE and http-client. * * @author Martin Eisengardt <[email protected]> * @since 2.0.0 */ @Component(role = IPearUtility.class, hint = "PHP_EXE", instantiationStrategy = "per-lookup") public class PearUtility implements IPearUtility { private static final class LogWrapper implements Log { /** * underlying log. */ private Log theLog; /** * true if the log is inactive (used to set the proxies). */ private boolean silent; /** * Sets the log. * @param log log */ public void setLog(Log log) { this.theLog = log; } /** * Sets the silent flag. * @param s silent */ public void setSilent(boolean s) { this.silent = s; } @Override public void debug(CharSequence arg0) { if (!this.silent) { this.theLog.debug(arg0); } } @Override public void debug(Throwable arg0) { if (!this.silent) { this.theLog.debug(arg0); } } @Override public void debug(CharSequence arg0, Throwable arg1) { if (!this.silent) { this.theLog.debug(arg0, arg1); } } @Override public void error(CharSequence arg0) { if (!this.silent) { this.theLog.error(arg0); } } @Override public void error(Throwable arg0) { if (!this.silent) { this.theLog.error(arg0); } } @Override public void error(CharSequence arg0, Throwable arg1) { if (!this.silent) { this.theLog.error(arg0, arg1); } } @Override public void info(CharSequence arg0) { if (!this.silent) { this.theLog.info(arg0); } } @Override public void info(Throwable arg0) { if (!this.silent) { this.theLog.info(arg0); } } @Override public void info(CharSequence arg0, Throwable arg1) { if (!this.silent) { this.theLog.info(arg0, arg1); } } @Override public boolean isDebugEnabled() { if (!this.silent) { return this.theLog.isDebugEnabled(); } return false; } @Override public boolean isErrorEnabled() { if (!this.silent) { return this.theLog.isErrorEnabled(); } return false; } @Override public boolean isInfoEnabled() { if (!this.silent) { return this.theLog.isInfoEnabled(); } return false; } @Override public boolean isWarnEnabled() { if (!this.silent) { return this.theLog.isWarnEnabled(); } return false; } @Override public void warn(CharSequence arg0) { if (!this.silent) { this.theLog.warn(arg0); } } @Override public void warn(Throwable arg0) { if (!this.silent) { this.theLog.warn(arg0); } } @Override public void warn(CharSequence arg0, Throwable arg1) { if (!this.silent) { this.theLog.warn(arg0, arg1); } } } /** the generic version scheme. */ private static final GenericVersionScheme SCHEME = new GenericVersionScheme(); /** * The installation directory. */ private File installDir; /** * The php executable. */ private IPhpExecutable exec; /** * The pear channels. * * <p> * Will be initialized by method {@link #initChannels()} * </p> */ private List<IPearChannel> knownChannels; /** * The logger. */ private LogWrapper log = new LogWrapper(); /** * The component factory. */ @Requirement private IComponentFactory factory; /** * The maven session. */ @ConfigurationParameter(name = "session", expression = "${session}") private MavenSession session; private File tempDir; private File binDir; private File phpDir; private File docDir; private File dataDir; private File cfgDir; private File wwwDir; private File testDir; private File downloadDir; /** * true if the proxy was initialized. */ private boolean initializedProxy; /** * the repository system. */ @Requirement private RepositorySystem reposSystem; /** * The project builder. */ @Requirement private ProjectBuilder projectBuilder; /** * The dependencies resolver */ @Requirement private ProjectDependenciesResolver dependencyResolver; /** * initializes the proxy for pear. * @throws PhpException */ private void initializeProxy() throws PhpException { if (!this.initializedProxy) { this.initializedProxy = true; final List<Proxy> proxies = this.session.getRequest().getProxies(); for (final Proxy proxy : proxies) { if (proxy.isActive()) { String proxyString = ""; if (proxy.getProtocol() != null && proxy.getProtocol().length() > 0) { proxyString += proxy.getProtocol(); proxyString += "://"; } if (proxy.getUsername() != null && proxy.getUsername().length() > 0) { proxyString += proxy.getUsername(); if (proxy.getPassword() != null && proxy.getPassword().length() > 0) { proxyString += ":"; proxyString += proxy.getPassword(); } proxyString += "@"; } proxyString += proxy.getHost(); proxyString += ":"; proxyString += proxy.getPort(); this.log.setSilent(true); try { this.executePearCmd("config-set http_proxy " + proxyString); } finally { this.log.setSilent(false); } return; } } // no active proxy configured this.executePearCmd("config-set http_proxy \" \""); } } /** * {@inheritDoc} */ @Override public boolean isInstalled() throws PhpException { final File installedFile = new File(this.installDir, "pear.conf"); final File installedFile2 = new File(this.installDir, "pear.ini"); return installedFile.exists() || installedFile2.exists(); } /** * {@inheritDoc} */ @Override public void installPear(boolean autoUpdatePear) throws PhpException { if (this.isInstalled()) { return; } if (!this.installDir.exists()) { this.installDir.mkdirs(); } this.clearDirectory(this.installDir); final File goPear = new File(this.installDir, "go-pear.phar"); try { FileUtils.copyURLToFile( this.getClass().getResource("/org/phpmaven/pear/gophar/go-pear.phar"), goPear); } catch (IOException e) { throw new PhpCoreException("failed installing pear", e); } final IPhpExecutable php = this.getExec(); final String result = php.executeCode("", "error_reporting(0);\n" + "Phar::loadPhar('" + goPear.getAbsolutePath().replace("\\", "\\\\") + "', 'go-pear.phar');\n" + "require_once 'phar://go-pear.phar/PEAR/Start/CLI.php';\n" + "PEAR::setErrorHandling(PEAR_ERROR_DIE);\n" + "$a = new PEAR_Start_CLI;\n" + "$a->prefix = getcwd();\n" + "if (OS_WINDOWS) {\n" + " $a->localInstall = true;\n" + " $a->pear_conf = '$prefix\\\\pear.ini';\n" + "} else {\n" + " if (get_current_user() != 'root') {\n" + " $a->pear_conf = $a->safeGetenv('HOME') . '/.pearrc';\n" + " }\n" + " $a->temp_dir='$prefix/tmp';\n" + " $a->download_dir='$prefix/tmp';\n" + "}\n" + "if (PEAR::isError($err = $a->locatePackagesToInstall())) {\n" + " die();\n" + "}\n" + "$a->setupTempStuff();\n" + "if (PEAR::isError($err = $a->postProcessConfigVars())) {\n" + " die();\n" + "}\n" + "$a->doInstall();\n" ); if (!this.isInstalled()) { throw new PhpCoreException("Installation failed.\n" + result); } if (autoUpdatePear) { this.initializeProxy(); this.executePearCmd("upgrade-all"); } } /** * Clears a directory. * @param dir directory to be cleared. */ private void clearDirectory(final File dir) { for (final File file : dir.listFiles()) { if (file.isDirectory()) { this.clearDirectory(file); } file.delete(); } } /** * {@inheritDoc} */ @Override public void uninstall() throws PhpException { // TODO Auto-generated method stub throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ @Override public File getInstallDir() { return this.installDir; } /** * Returns the php executable. * * @return php executable. * * @throws PhpException thrown on configuration or execution errors. */ private IPhpExecutable getExec() throws PhpException { if (this.exec != null) { return this.exec; } Xpp3Dom execConfig = this.factory.getBuildConfig( this.session.getCurrentProject(), "org.phpmaven", "maven-php-pear"); if (execConfig != null) { execConfig = execConfig.getChild("executableConfig"); } try { final IPhpExecutableConfiguration config = this.factory.lookup(IPhpExecutableConfiguration.class, execConfig, session); // TODO set Working directory. config.getEnv().put( "PHP_PEAR_INSTALL_DIR", new File(this.installDir, "PEAR").getAbsolutePath()); config.getEnv().put( "PHP_PEAR_BIN_DIR", this.installDir.getAbsolutePath()); config.getEnv().put( "PHP_PEAR_SYSCONF_DIR", this.installDir.getAbsolutePath()); // TODO PHP_BIN ??? /*config.getEnv().put( "PHP_PEAR_PHP_BIN", new File(this.installDir, "PEAR").getAbsolutePath());*/ config.setAdditionalPhpParameters( "-C -d date.timezone=UTC -d output_buffering=1 -d safe_mode=0 -d open_basedir=\"\" " + "-d auto_prepend_file=\"\" -d auto_append_file=\"\" -d variables_order=EGPCS " + "-d register_argc_argv=\"On\" " + // the following parameter is required for the susohin plugin (typically present under debian) "-d suhosin.executor.include.whitelist=\"phar\""); config.setWorkDirectory(this.getInstallDir()); config.getIncludePath().add(new File(this.installDir, "PEAR").getAbsolutePath()); this.exec = config.getPhpExecutable(this.log); return this.exec; } catch (ComponentLookupException ex) { throw new PhpCoreException("Unable to create php executable.", ex); } catch (PlexusConfigurationException ex) { throw new PhpCoreException("Unable to create php executable.", ex); } } /** * {@inheritDoc} */ @Override public String executePearCmd(String arguments) throws PhpException { this.initializeProxy(); final IPhpExecutable ex = this.getExec(); final File pearCmd = new File(this.getPhpDir(), "pearcmd.php"); try { return ex.execute("\"" + pearCmd.getAbsolutePath() + "\" " + arguments, pearCmd); } catch (PhpWarningException e) { // ignore it return e.getAppendedOutput(); } } /** * Initialized the known channels and ensures that there is a pear installation at {@link #installDir}. * @throws PhpException thrown if something is wrong. */ private void initChannels() throws PhpException { // already installed if (this.knownChannels != null) { return; } if (!this.isInstalled()) { throw new PhpCoreException("Pear not installed in " + this.installDir); } final List<IPearChannel> channels = new ArrayList<IPearChannel>(); final String output = this.executePearCmd("list-channels"); final StringTokenizer tokenizer = new StringTokenizer(output.trim(), "\n"); try { // table headers... tokenizer.nextToken(); tokenizer.nextToken(); tokenizer.nextToken(); while (tokenizer.hasMoreTokens()) { final String token = tokenizer.nextToken(); if (token.startsWith(" ")) continue; if (token.startsWith("__uri")) continue; if (token.startsWith("CHANNEL")) continue; // if (token.startsWith("doc.")) continue; final PearChannel channel = new PearChannel(); channel.initialize(this, new StringTokenizer(token, " ").nextToken()); channels.add(channel); } } catch (NoSuchElementException ex) { throw new PhpCoreException("Unexpected output from pear:\n" + output, ex); } this.knownChannels = channels; } /** * {@inheritDoc} */ @Override public Iterable<IPearChannel> listKnownChannels() throws PhpException { this.initChannels(); return this.knownChannels; } /** * {@inheritDoc} */ @Override public IPearChannel channelDiscover(String channelName) throws PhpException { for (final IPearChannel channel : this.listKnownChannels()) { if (channel.getName().equals(channelName) || channelName.equals(channel.getSuggestedAlias())) { return channel; } } // TODO fetch result and check if the channel was installed. final String output = this.executePearCmd("channel-discover " + channelName); final IPearChannel result = new PearChannel(); result.initialize(this, channelName); this.knownChannels.add(result); return result; } /** * {@inheritDoc} */ @Override public IPearChannel channelDiscoverLocal(File channel) throws PhpException { final IPearChannel result = new PearChannel(); result.initialize(this, "file://" + channel.getAbsolutePath()); return result; } /** * {@inheritDoc} */ @Override public void upgrade() throws PhpException { // TODO check result for errors this.executePearCmd("upgrade"); } /** * {@inheritDoc} */ @Override public IPearChannel lookupChannel(String channelName) throws PhpException { for (final IPearChannel channel : this.listKnownChannels()) { if (channel.getName().equals(channelName) || channelName.equals(channel.getSuggestedAlias())) { return channel; } } return null; } /** * {@inheritDoc} */ @Override public void clearCache() throws PhpException { this.executePearCmd("clear-cache"); } /** * {@inheritDoc} */ @Override public void configure(File dir, Log logger) { if (this.installDir != null) { throw new IllegalStateException("Must not be called twice!"); } this.installDir = dir; this.log.setLog(logger); } /** * {@inheritDoc} */ @Override public String convertMavenVersionToPearVersion(String src) { return Package.convertMavenVersionToPearVersion(src); } /** * {@inheritDoc} */ @Override public String convertPearVersionToMavenVersion(String src) { return Package.convertPearVersionToMavenVersion(src); } private void initConfig() throws PhpException { if (this.tempDir == null) { final File cfgFile = new File(this.getInstallDir(), "pear.conf"); final File cfgFile2 = new File(this.getInstallDir(), "pear.ini"); try { String cfgFileContents = FileUtils.fileRead(cfgFile.exists() ? cfgFile : cfgFile2); while (cfgFileContents.startsWith("#")) { final int indexOf = cfgFileContents.indexOf("\n"); if (indexOf == -1) { cfgFileContents = ""; } else { cfgFileContents = cfgFileContents.substring(indexOf).trim(); } } final DeserializePhp parser = new DeserializePhp(cfgFileContents); @SuppressWarnings("unchecked") final Map<String, Object> value = (Map<String, Object>) parser.parse(); this.tempDir = new File((String) value.get("temp_dir")); this.downloadDir = new File((String) value.get("download_dir")); this.binDir = new File((String) value.get("bin_dir")); this.phpDir = new File((String) value.get("php_dir")); this.docDir = new File((String) value.get("doc_dir")); this.dataDir = new File((String) value.get("data_dir")); this.cfgDir = new File((String) value.get("cfg_dir")); this.wwwDir = new File((String) value.get("www_dir")); this.testDir = new File((String) value.get("test_dir")); } catch (Exception ex) { throw new PhpCoreException("Problems reading and parsing pear configuration", ex); } } } @Override public File getTempDir() throws PhpException { this.initConfig(); return this.tempDir; } @Override public File getDownloadDir() throws PhpException { this.initConfig(); return this.downloadDir; } @Override public File getBinDir() throws PhpException { this.initConfig(); return this.binDir; } @Override public File getPhpDir() throws PhpException { this.initConfig(); return this.phpDir; } @Override public File getDocDir() throws PhpException { this.initConfig(); return this.docDir; } @Override public File getDataDir() throws PhpException { this.initConfig(); return this.dataDir; } @Override public File getCfgDir() throws PhpException { this.initConfig(); return this.cfgDir; } @Override public File getWwwDir() throws PhpException { this.initConfig(); return this.wwwDir; } @Override public File getTestDir() throws PhpException { this.initConfig(); return this.testDir; } /** * Resolves the artifact. * @param groupId group id * @param artifactId artifact id * @param version version * @param type type * @param classifier classifier * @return the resolved artifact * @throws PhpException thrown on resolve errors */ private Artifact resolveArtifact(String groupId, String artifactId, String version, String type, String classifier) throws PhpException { final Artifact artifact = this.reposSystem.createArtifactWithClassifier( groupId, artifactId, version, type, classifier); final ArtifactResolutionRequest request = new ArtifactResolutionRequest(); request.setArtifact(artifact); request.setLocalRepository(this.session.getLocalRepository()); request.setOffline(this.session.isOffline()); final Set<ArtifactRepository> setRepos = new HashSet<ArtifactRepository>( this.session.getRequest().getRemoteRepositories()); setRepos.addAll(this.session.getCurrentProject().getRemoteArtifactRepositories()); request.setRemoteRepositories(new ArrayList<ArtifactRepository>(setRepos)); final ArtifactResolutionResult result = this.reposSystem.resolve(request); if (!result.isSuccess()) { throw new PhpCoreException("dependency resolution failed for " + groupId + ":" + artifactId + ":" + version); } final Artifact resultArtifact = result.getArtifacts().iterator().next(); return resultArtifact; } /** * {@inheritDoc} */ @Override public void installFromMavenRepository(String groupId, String artifactId, String version) throws PhpException { final Artifact artifact = this.resolveArtifact(groupId, artifactId, version, "pom", null); final File pomFile = artifact.getFile(); final ProjectBuildingRequest pbr = new DefaultProjectBuildingRequest(this.session.getProjectBuildingRequest()); try { pbr.setProcessPlugins(false); final ProjectBuildingResult pbres = this.projectBuilder.build(pomFile, pbr); final MavenProject project = pbres.getProject(); final DependencyResolutionRequest drr = new DefaultDependencyResolutionRequest( project, session.getRepositorySession()); final DependencyResolutionResult drres = this.dependencyResolver.resolve(drr); // dependencies may be duplicate. ensure we have only one version (the newest). final Map<String, org.sonatype.aether.graph.Dependency> deps = new HashMap<String, org.sonatype.aether.graph.Dependency>(); for (final org.sonatype.aether.graph.Dependency dep : drres.getDependencies()) { final String key = dep.getArtifact().getGroupId() + ":" + dep.getArtifact().getArtifactId(); if (!deps.containsKey(key)) { deps.put(key, dep); } else { final org.sonatype.aether.graph.Dependency dep2 = deps.get(key); final org.sonatype.aether.version.Version ver = SCHEME.parseVersion(dep.getArtifact().getVersion()); final org.sonatype.aether.version.Version ver2 = SCHEME.parseVersion(dep2.getArtifact().getVersion()); if (ver2.compareTo(ver) < 0) { deps.put(key, dep); } } } final List<File> filesToInstall = new ArrayList<File>(); // first the dependencies this.log.debug( "resolving tgz and project for " + groupId + ":" + artifactId + ":" + version); this.resolveTgz(groupId, artifactId, version, filesToInstall); this.resolveChannels(project); for (final org.sonatype.aether.graph.Dependency dep : deps.values()) { this.log.debug( "resolving tgz and project for " + dep.getArtifact().getGroupId() + ":" + dep.getArtifact().getArtifactId() + ":" + dep.getArtifact().getVersion()); if (this.isMavenCorePackage( dep.getArtifact().getGroupId(), dep.getArtifact().getArtifactId())) { // ignore core packages continue; } this.resolveTgz( dep.getArtifact().getGroupId(), dep.getArtifact().getArtifactId(), dep.getArtifact().getVersion(), filesToInstall); final Artifact depPomArtifact = this.resolveArtifact( dep.getArtifact().getGroupId(), dep.getArtifact().getArtifactId(), dep.getArtifact().getVersion(), "pom", null); final File depPomFile = depPomArtifact.getFile(); final ProjectBuildingResult depPbres = this.projectBuilder.build(depPomFile, pbr); final MavenProject depProject = depPbres.getProject(); this.resolveChannels(depProject); } Collections.reverse(filesToInstall); for (final File file : filesToInstall) { this.executePearCmd("install --force --nodeps \"" + file.getAbsolutePath() + "\""); } } catch (InvalidVersionSpecificationException ex) { throw new PhpCoreException(ex); } catch (ProjectBuildingException ex) { throw new PhpCoreException(ex); } catch (DependencyResolutionException ex) { throw new PhpCoreException(ex); } } /** * resolving the pear channels from given project. * @param project the project * @throws PhpException thrown on discover errors */ private void resolveChannels(MavenProject project) throws PhpException { final Build build = project.getBuild(); if (build != null) { for (final Plugin plugin : build.getPlugins()) { if ("org.phpmaven".equals(plugin.getGroupId()) && "maven-php-plugin".equals(plugin.getArtifactId())) { final Xpp3Dom dom = (Xpp3Dom) plugin.getConfiguration(); final Xpp3Dom pearChannelsDom = dom.getChild("pearChannels"); if (pearChannelsDom != null) { for (final Xpp3Dom child : pearChannelsDom.getChildren()) { this.channelDiscover(child.getValue()); } } } } } } /** * Resolves the tgz and adds it to the files for installation. * @param groupId group id * @param artifactId artifact id * @param version version * @param filesToInstall files to be installed * @throws PhpException thrown on resolve errors. */ private void resolveTgz(String groupId, String artifactId, String version, List<File> filesToInstall) throws PhpException { if (!this.isMavenCorePackage(groupId, artifactId)) { final Artifact artifact = this.resolveArtifact(groupId, artifactId, version, "tgz", "pear-tgz"); filesToInstall.add(artifact.getFile()); } } @Override public boolean isMavenCorePackage(String groupId, String artifactId) { if (("net.php".equals(groupId)) && ( "Archive_Tar".equals(artifactId) || "Console_Getopt".equals(artifactId) || "PEAR".equals(artifactId) || "Structures_Graph".equals(artifactId) || "XML_Util".equals(artifactId))) { return true; } return false; } @Override public boolean isPearCorePackage(String channel, String pkg) { if (("pear".equals(channel) || "pear.php.net".equals(channel)) && ( "Archive_Tar".equals(pkg) || "Console_Getopt".equals(pkg) || "PEAR".equals(pkg) || "Structures_Graph".equals(pkg) || "XML_Util".equals(pkg))) { return true; } return false; } }
branches/2.0-SNAPSHOT/maven-php-pear/src/main/java/org/phpmaven/pear/impl/PearUtility.java
/** * Copyright 2010-2012 by PHP-maven.org * * 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. */ package org.phpmaven.pear.impl; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.StringTokenizer; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.ArtifactResolutionRequest; import org.apache.maven.artifact.resolver.ArtifactResolutionResult; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Build; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.DefaultDependencyResolutionRequest; import org.apache.maven.project.DefaultProjectBuildingRequest; import org.apache.maven.project.DependencyResolutionException; import org.apache.maven.project.DependencyResolutionRequest; import org.apache.maven.project.DependencyResolutionResult; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuilder; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.project.ProjectBuildingRequest; import org.apache.maven.project.ProjectBuildingResult; import org.apache.maven.project.ProjectDependenciesResolver; import org.apache.maven.repository.RepositorySystem; import org.apache.maven.settings.Proxy; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.configuration.PlexusConfigurationException; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.phpmaven.core.ConfigurationParameter; import org.phpmaven.core.DeserializePhp; import org.phpmaven.core.IComponentFactory; import org.phpmaven.exec.IPhpExecutable; import org.phpmaven.exec.IPhpExecutableConfiguration; import org.phpmaven.exec.PhpCoreException; import org.phpmaven.exec.PhpException; import org.phpmaven.exec.PhpWarningException; import org.phpmaven.pear.IPearChannel; import org.phpmaven.pear.IPearUtility; import org.sonatype.aether.util.version.GenericVersionScheme; import org.sonatype.aether.version.InvalidVersionSpecificationException; /** * Implementation of a pear utility via PHP.EXE and http-client. * * @author Martin Eisengardt <[email protected]> * @since 2.0.0 */ @Component(role = IPearUtility.class, hint = "PHP_EXE", instantiationStrategy = "per-lookup") public class PearUtility implements IPearUtility { private static final class LogWrapper implements Log { /** * underlying log. */ private Log theLog; /** * true if the log is inactive (used to set the proxies). */ private boolean silent; /** * Sets the log. * @param log log */ public void setLog(Log log) { this.theLog = log; } /** * Sets the silent flag. * @param s silent */ public void setSilent(boolean s) { this.silent = s; } @Override public void debug(CharSequence arg0) { if (!this.silent) { this.theLog.debug(arg0); } } @Override public void debug(Throwable arg0) { if (!this.silent) { this.theLog.debug(arg0); } } @Override public void debug(CharSequence arg0, Throwable arg1) { if (!this.silent) { this.theLog.debug(arg0, arg1); } } @Override public void error(CharSequence arg0) { if (!this.silent) { this.theLog.error(arg0); } } @Override public void error(Throwable arg0) { if (!this.silent) { this.theLog.error(arg0); } } @Override public void error(CharSequence arg0, Throwable arg1) { if (!this.silent) { this.theLog.error(arg0, arg1); } } @Override public void info(CharSequence arg0) { if (!this.silent) { this.theLog.info(arg0); } } @Override public void info(Throwable arg0) { if (!this.silent) { this.theLog.info(arg0); } } @Override public void info(CharSequence arg0, Throwable arg1) { if (!this.silent) { this.theLog.info(arg0, arg1); } } @Override public boolean isDebugEnabled() { if (!this.silent) { return this.theLog.isDebugEnabled(); } return false; } @Override public boolean isErrorEnabled() { if (!this.silent) { return this.theLog.isErrorEnabled(); } return false; } @Override public boolean isInfoEnabled() { if (!this.silent) { return this.theLog.isInfoEnabled(); } return false; } @Override public boolean isWarnEnabled() { if (!this.silent) { return this.theLog.isWarnEnabled(); } return false; } @Override public void warn(CharSequence arg0) { if (!this.silent) { this.theLog.warn(arg0); } } @Override public void warn(Throwable arg0) { if (!this.silent) { this.theLog.warn(arg0); } } @Override public void warn(CharSequence arg0, Throwable arg1) { if (!this.silent) { this.theLog.warn(arg0, arg1); } } } /** the generic version scheme. */ private static final GenericVersionScheme SCHEME = new GenericVersionScheme(); /** * The installation directory. */ private File installDir; /** * The php executable. */ private IPhpExecutable exec; /** * The pear channels. * * <p> * Will be initialized by method {@link #initChannels()} * </p> */ private List<IPearChannel> knownChannels; /** * The logger. */ private LogWrapper log = new LogWrapper(); /** * The component factory. */ @Requirement private IComponentFactory factory; /** * The maven session. */ @ConfigurationParameter(name = "session", expression = "${session}") private MavenSession session; private File tempDir; private File binDir; private File phpDir; private File docDir; private File dataDir; private File cfgDir; private File wwwDir; private File testDir; private File downloadDir; /** * true if the proxy was initialized. */ private boolean initializedProxy; /** * the repository system. */ @Requirement private RepositorySystem reposSystem; /** * The project builder. */ @Requirement private ProjectBuilder projectBuilder; /** * The dependencies resolver */ @Requirement private ProjectDependenciesResolver dependencyResolver; /** * initializes the proxy for pear. * @throws PhpException */ private void initializeProxy() throws PhpException { if (!this.initializedProxy) { this.initializedProxy = true; final List<Proxy> proxies = this.session.getRequest().getProxies(); for (final Proxy proxy : proxies) { if (proxy.isActive()) { String proxyString = ""; if (proxy.getProtocol() != null && proxy.getProtocol().length() > 0) { proxyString += proxy.getProtocol(); proxyString += "://"; } if (proxy.getUsername() != null && proxy.getUsername().length() > 0) { proxyString += proxy.getUsername(); if (proxy.getPassword() != null && proxy.getPassword().length() > 0) { proxyString += ":"; proxyString += proxy.getPassword(); } proxyString += "@"; } proxyString += proxy.getHost(); proxyString += ":"; proxyString += proxy.getPort(); this.log.setSilent(true); try { this.executePearCmd("config-set http_proxy " + proxyString); } finally { this.log.setSilent(false); } return; } } // no active proxy configured this.executePearCmd("config-set http_proxy \" \""); } } /** * {@inheritDoc} */ @Override public boolean isInstalled() throws PhpException { final File installedFile = new File(this.installDir, "pear.conf"); final File installedFile2 = new File(this.installDir, "pear.ini"); return installedFile.exists() || installedFile2.exists(); } /** * {@inheritDoc} */ @Override public void installPear(boolean autoUpdatePear) throws PhpException { if (this.isInstalled()) { return; } if (!this.installDir.exists()) { this.installDir.mkdirs(); } this.clearDirectory(this.installDir); final File goPear = new File(this.installDir, "go-pear.phar"); try { FileUtils.copyURLToFile( this.getClass().getResource("/org/phpmaven/pear/gophar/go-pear.phar"), goPear); } catch (IOException e) { throw new PhpCoreException("failed installing pear", e); } final IPhpExecutable php = this.getExec(); final String result = php.executeCode("", "error_reporting(0);\n" + "Phar::loadPhar('" + goPear.getAbsolutePath().replace("\\", "\\\\") + "', 'go-pear.phar');\n" + "require_once 'phar://go-pear.phar/PEAR/Start/CLI.php';\n" + "PEAR::setErrorHandling(PEAR_ERROR_DIE);\n" + "$a = new PEAR_Start_CLI;\n" + "$a->prefix = getcwd();\n" + "if (OS_WINDOWS) {\n" + " $a->localInstall = true;\n" + " $a->pear_conf = '$prefix\\\\pear.ini';\n" + "} else {\n" + " if (get_current_user() != 'root') {\n" + " $a->pear_conf = $a->safeGetenv('HOME') . '/.pearrc';\n" + " }\n" + " $a->temp_dir='$prefix/tmp';\n" + " $a->download_dir='$prefix/tmp';\n" + "}\n" + "if (PEAR::isError($err = $a->locatePackagesToInstall())) {\n" + " die();\n" + "}\n" + "$a->setupTempStuff();\n" + "if (PEAR::isError($err = $a->postProcessConfigVars())) {\n" + " die();\n" + "}\n" + "$a->doInstall();\n" ); if (!this.isInstalled()) { throw new PhpCoreException("Installation failed.\n" + result); } if (autoUpdatePear) { this.initializeProxy(); this.executePearCmd("upgrade-all"); } } /** * Clears a directory. * @param dir directory to be cleared. */ private void clearDirectory(final File dir) { for (final File file : dir.listFiles()) { if (file.isDirectory()) { this.clearDirectory(file); } file.delete(); } } /** * {@inheritDoc} */ @Override public void uninstall() throws PhpException { // TODO Auto-generated method stub throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ @Override public File getInstallDir() { return this.installDir; } /** * Returns the php executable. * * @return php executable. * * @throws PhpException thrown on configuration or execution errors. */ private IPhpExecutable getExec() throws PhpException { if (this.exec != null) { return this.exec; } Xpp3Dom execConfig = this.factory.getBuildConfig( this.session.getCurrentProject(), "org.phpmaven", "maven-php-pear"); if (execConfig != null) { execConfig = execConfig.getChild("executableConfig"); } try { final IPhpExecutableConfiguration config = this.factory.lookup(IPhpExecutableConfiguration.class, execConfig, session); // TODO set Working directory. config.getEnv().put( "PHP_PEAR_INSTALL_DIR", new File(this.installDir, "PEAR").getAbsolutePath()); config.getEnv().put( "PHP_PEAR_BIN_DIR", this.installDir.getAbsolutePath()); config.getEnv().put( "PHP_PEAR_SYSCONF_DIR", this.installDir.getAbsolutePath()); // TODO PHP_BIN ??? /*config.getEnv().put( "PHP_PEAR_PHP_BIN", new File(this.installDir, "PEAR").getAbsolutePath());*/ config.setAdditionalPhpParameters( "-C -d date.timezone=UTC -d output_buffering=1 -d safe_mode=0 -d open_basedir=\"\" " + "-d auto_prepend_file=\"\" -d auto_append_file=\"\" -d variables_order=EGPCS " + "-d register_argc_argv=\"On\" " + // the following parameter is required for the susohin plugin (typically present under debian) "-d suhosin.executor.include.whitelist=\"phar\""); config.setWorkDirectory(this.getInstallDir()); config.getIncludePath().add(new File(this.installDir, "PEAR").getAbsolutePath()); this.exec = config.getPhpExecutable(this.log); return this.exec; } catch (ComponentLookupException ex) { throw new PhpCoreException("Unable to create php executable.", ex); } catch (PlexusConfigurationException ex) { throw new PhpCoreException("Unable to create php executable.", ex); } } /** * {@inheritDoc} */ @Override public String executePearCmd(String arguments) throws PhpException { this.initializeProxy(); final IPhpExecutable ex = this.getExec(); final File pearCmd = new File(this.getPhpDir(), "pearcmd.php"); try { return ex.execute("\"" + pearCmd.getAbsolutePath() + "\" " + arguments, pearCmd); } catch (PhpWarningException e) { // ignore it return e.getAppendedOutput(); } } /** * Initialized the known channels and ensures that there is a pear installation at {@link #installDir}. * @throws PhpException thrown if something is wrong. */ private void initChannels() throws PhpException { // already installed if (this.knownChannels != null) { return; } if (!this.isInstalled()) { throw new PhpCoreException("Pear not installed in " + this.installDir); } final List<IPearChannel> channels = new ArrayList<IPearChannel>(); final String output = this.executePearCmd("list-channels"); final StringTokenizer tokenizer = new StringTokenizer(output.trim(), "\n"); try { // table headers... tokenizer.nextToken(); tokenizer.nextToken(); tokenizer.nextToken(); while (tokenizer.hasMoreTokens()) { final String token = tokenizer.nextToken(); if (token.startsWith(" ")) continue; if (token.startsWith("__uri")) continue; if (token.startsWith("CHANNEL")) continue; // if (token.startsWith("doc.")) continue; final PearChannel channel = new PearChannel(); channel.initialize(this, new StringTokenizer(token, " ").nextToken()); channels.add(channel); } } catch (NoSuchElementException ex) { throw new PhpCoreException("Unexpected output from pear:\n" + output, ex); } this.knownChannels = channels; } /** * {@inheritDoc} */ @Override public Iterable<IPearChannel> listKnownChannels() throws PhpException { this.initChannels(); return this.knownChannels; } /** * {@inheritDoc} */ @Override public IPearChannel channelDiscover(String channelName) throws PhpException { for (final IPearChannel channel : this.listKnownChannels()) { if (channel.getName().equals(channelName) || channelName.equals(channel.getSuggestedAlias())) { return channel; } } // TODO fetch result and check if the channel was installed. final String output = this.executePearCmd("channel-discover " + channelName); final IPearChannel result = new PearChannel(); result.initialize(this, channelName); this.knownChannels.add(result); return result; } /** * {@inheritDoc} */ @Override public IPearChannel channelDiscoverLocal(File channel) throws PhpException { final IPearChannel result = new PearChannel(); result.initialize(this, "file://" + channel.getAbsolutePath()); return result; } /** * {@inheritDoc} */ @Override public void upgrade() throws PhpException { // TODO check result for errors this.executePearCmd("upgrade"); } /** * {@inheritDoc} */ @Override public IPearChannel lookupChannel(String channelName) throws PhpException { for (final IPearChannel channel : this.listKnownChannels()) { if (channel.getName().equals(channelName) || channelName.equals(channel.getSuggestedAlias())) { return channel; } } return null; } /** * {@inheritDoc} */ @Override public void clearCache() throws PhpException { this.executePearCmd("clear-cache"); } /** * {@inheritDoc} */ @Override public void configure(File dir, Log logger) { if (this.installDir != null) { throw new IllegalStateException("Must not be called twice!"); } this.installDir = dir; this.log.setLog(logger); } /** * {@inheritDoc} */ @Override public String convertMavenVersionToPearVersion(String src) { return Package.convertMavenVersionToPearVersion(src); } /** * {@inheritDoc} */ @Override public String convertPearVersionToMavenVersion(String src) { return Package.convertPearVersionToMavenVersion(src); } private void initConfig() throws PhpException { if (this.tempDir == null) { final File cfgFile = new File(this.getInstallDir(), "pear.conf"); final File cfgFile2 = new File(this.getInstallDir(), "pear.ini"); try { String cfgFileContents = FileUtils.fileRead(cfgFile.exists() ? cfgFile : cfgFile2); while (cfgFileContents.startsWith("#")) { final int indexOf = cfgFileContents.indexOf("\n"); if (indexOf == -1) { cfgFileContents = ""; } else { cfgFileContents = cfgFileContents.substring(indexOf).trim(); } } final DeserializePhp parser = new DeserializePhp(cfgFileContents); @SuppressWarnings("unchecked") final Map<String, Object> value = (Map<String, Object>) parser.parse(); this.tempDir = new File((String) value.get("temp_dir")); this.downloadDir = new File((String) value.get("download_dir")); this.binDir = new File((String) value.get("bin_dir")); this.phpDir = new File((String) value.get("php_dir")); this.docDir = new File((String) value.get("doc_dir")); this.dataDir = new File((String) value.get("data_dir")); this.cfgDir = new File((String) value.get("cfg_dir")); this.wwwDir = new File((String) value.get("www_dir")); this.testDir = new File((String) value.get("test_dir")); } catch (Exception ex) { throw new PhpCoreException("Problems reading and parsing pear configuration", ex); } } } @Override public File getTempDir() throws PhpException { this.initConfig(); return this.tempDir; } @Override public File getDownloadDir() throws PhpException { this.initConfig(); return this.downloadDir; } @Override public File getBinDir() throws PhpException { this.initConfig(); return this.binDir; } @Override public File getPhpDir() throws PhpException { this.initConfig(); return this.phpDir; } @Override public File getDocDir() throws PhpException { this.initConfig(); return this.docDir; } @Override public File getDataDir() throws PhpException { this.initConfig(); return this.dataDir; } @Override public File getCfgDir() throws PhpException { this.initConfig(); return this.cfgDir; } @Override public File getWwwDir() throws PhpException { this.initConfig(); return this.wwwDir; } @Override public File getTestDir() throws PhpException { this.initConfig(); return this.testDir; } /** * Resolves the artifact. * @param groupId group id * @param artifactId artifact id * @param version version * @param type type * @param classifier classifier * @return the resolved artifact * @throws PhpException thrown on resolve errors */ private Artifact resolveArtifact(String groupId, String artifactId, String version, String type, String classifier) throws PhpException { final Artifact artifact = this.reposSystem.createArtifactWithClassifier( groupId, artifactId, version, type, classifier); final ArtifactResolutionRequest request = new ArtifactResolutionRequest(); request.setArtifact(artifact); request.setLocalRepository(this.session.getLocalRepository()); request.setOffline(this.session.isOffline()); final Set<ArtifactRepository> setRepos = new HashSet<ArtifactRepository>( this.session.getRequest().getRemoteRepositories()); setRepos.addAll(this.session.getCurrentProject().getRemoteArtifactRepositories()); request.setRemoteRepositories(new ArrayList<ArtifactRepository>(setRepos)); final ArtifactResolutionResult result = this.reposSystem.resolve(request); if (!result.isSuccess()) { throw new PhpCoreException("dependency resolution failed for " + groupId + ":" + artifactId + ":" + version); } final Artifact resultArtifact = result.getArtifacts().iterator().next(); return resultArtifact; } /** * {@inheritDoc} */ @Override public void installFromMavenRepository(String groupId, String artifactId, String version) throws PhpException { final Artifact artifact = this.resolveArtifact(groupId, artifactId, version, "pom", null); final File pomFile = artifact.getFile(); final ProjectBuildingRequest pbr = new DefaultProjectBuildingRequest(this.session.getProjectBuildingRequest()); try { pbr.setProcessPlugins(false); final ProjectBuildingResult pbres = this.projectBuilder.build(pomFile, pbr); final MavenProject project = pbres.getProject(); final DependencyResolutionRequest drr = new DefaultDependencyResolutionRequest( project, session.getRepositorySession()); final DependencyResolutionResult drres = this.dependencyResolver.resolve(drr); // dependencies may be duplicate. ensure we have only one version (the newest). final Map<String, org.sonatype.aether.graph.Dependency> deps = new HashMap<String, org.sonatype.aether.graph.Dependency>(); for (final org.sonatype.aether.graph.Dependency dep : drres.getDependencies()) { final String key = dep.getArtifact().getGroupId() + ":" + dep.getArtifact().getArtifactId(); if (!deps.containsKey(key)) { deps.put(key, dep); } else { final org.sonatype.aether.graph.Dependency dep2 = deps.get(key); final org.sonatype.aether.version.Version ver = SCHEME.parseVersion(dep.getArtifact().getVersion()); final org.sonatype.aether.version.Version ver2 = SCHEME.parseVersion(dep2.getArtifact().getVersion()); if (ver2.compareTo(ver) < 0) { deps.put(key, dep); } } } final List<File> filesToInstall = new ArrayList<File>(); // first the dependencies this.log.debug( "resolving tgz and project for " + groupId + ":" + artifactId + ":" + version); this.resolveTgz(groupId, artifactId, version, filesToInstall); this.resolveChannels(project); for (final org.sonatype.aether.graph.Dependency dep : deps.values()) { this.log.debug( "resolving tgz and project for " + dep.getArtifact().getGroupId() + ":" + dep.getArtifact().getArtifactId() + ":" + dep.getArtifact().getVersion()); if (this.isMavenCorePackage( dep.getArtifact().getGroupId(), dep.getArtifact().getArtifactId())) { // ignore core packages continue; } this.resolveTgz( dep.getArtifact().getGroupId(), dep.getArtifact().getArtifactId(), dep.getArtifact().getVersion(), filesToInstall); final Artifact depPomArtifact = this.resolveArtifact( dep.getArtifact().getGroupId(), dep.getArtifact().getArtifactId(), dep.getArtifact().getVersion(), "pom", null); final File depPomFile = depPomArtifact.getFile(); final ProjectBuildingResult depPbres = this.projectBuilder.build(depPomFile, pbr); final MavenProject depProject = depPbres.getProject(); this.resolveChannels(depProject); } Collections.reverse(filesToInstall); for (final File file : filesToInstall) { this.executePearCmd("install \"" + file.getAbsolutePath() + "\""); } } catch (InvalidVersionSpecificationException ex) { throw new PhpCoreException(ex); } catch (ProjectBuildingException ex) { throw new PhpCoreException(ex); } catch (DependencyResolutionException ex) { throw new PhpCoreException(ex); } } /** * resolving the pear channels from given project. * @param project the project * @throws PhpException thrown on discover errors */ private void resolveChannels(MavenProject project) throws PhpException { final Build build = project.getBuild(); if (build != null) { for (final Plugin plugin : build.getPlugins()) { if ("org.phpmaven".equals(plugin.getGroupId()) && "maven-php-plugin".equals(plugin.getArtifactId())) { final Xpp3Dom dom = (Xpp3Dom) plugin.getConfiguration(); final Xpp3Dom pearChannelsDom = dom.getChild("pearChannels"); if (pearChannelsDom != null) { for (final Xpp3Dom child : pearChannelsDom.getChildren()) { this.channelDiscover(child.getValue()); } } } } } } /** * Resolves the tgz and adds it to the files for installation. * @param groupId group id * @param artifactId artifact id * @param version version * @param filesToInstall files to be installed * @throws PhpException thrown on resolve errors. */ private void resolveTgz(String groupId, String artifactId, String version, List<File> filesToInstall) throws PhpException { if (!this.isMavenCorePackage(groupId, artifactId)) { final Artifact artifact = this.resolveArtifact(groupId, artifactId, version, "tgz", "pear-tgz"); filesToInstall.add(artifact.getFile()); } } @Override public boolean isMavenCorePackage(String groupId, String artifactId) { if (("net.php".equals(groupId)) && ( "Archive_Tar".equals(artifactId) || "Console_Getopt".equals(artifactId) || "PEAR".equals(artifactId) || "Structures_Graph".equals(artifactId) || "XML_Util".equals(artifactId))) { return true; } return false; } @Override public boolean isPearCorePackage(String channel, String pkg) { if (("pear".equals(channel) || "pear.php.net".equals(channel)) && ( "Archive_Tar".equals(pkg) || "Console_Getopt".equals(pkg) || "PEAR".equals(pkg) || "Structures_Graph".equals(pkg) || "XML_Util".equals(pkg))) { return true; } return false; } }
adding force and nodeps version
branches/2.0-SNAPSHOT/maven-php-pear/src/main/java/org/phpmaven/pear/impl/PearUtility.java
adding force and nodeps version
<ide><path>ranches/2.0-SNAPSHOT/maven-php-pear/src/main/java/org/phpmaven/pear/impl/PearUtility.java <ide> <ide> Collections.reverse(filesToInstall); <ide> for (final File file : filesToInstall) { <del> this.executePearCmd("install \"" + file.getAbsolutePath() + "\""); <add> this.executePearCmd("install --force --nodeps \"" + file.getAbsolutePath() + "\""); <ide> } <ide> } catch (InvalidVersionSpecificationException ex) { <ide> throw new PhpCoreException(ex);
Java
apache-2.0
20de4090ace7585a66ad79035a4f040a0db996a4
0
Terasology/Minimap
/* * Copyright 2015 MovingBlocks * * 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. */ package org.terasology.minimap.rendering.nui.layers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.asset.Assets; import org.terasology.math.Vector2i; import org.terasology.math.geom.Vector3i; import org.terasology.math.geom.Vector2f; import org.terasology.minimap.DisplayAxisType; import org.terasology.registry.CoreRegistry; import org.terasology.rendering.assets.texture.BasicTextureRegion; import org.terasology.rendering.assets.texture.Texture; import org.terasology.rendering.assets.texture.TextureRegion; import org.terasology.rendering.nui.Canvas; import org.terasology.rendering.nui.CoreWidget; import org.terasology.rendering.nui.databinding.Binding; import org.terasology.rendering.nui.databinding.DefaultBinding; import org.terasology.rendering.nui.databinding.ReadOnlyBinding; import org.terasology.world.WorldProvider; import org.terasology.world.block.Block; import org.terasology.world.block.BlockAppearance; import org.terasology.world.block.BlockPart; /** * @author Immortius */ public class MinimapCell extends CoreWidget { private static final Logger logger = LoggerFactory.getLogger(MinimapCell.class); private final Texture textureAtlas; private final TextureRegion questionMarkTextureRegion; private MapLocationIcon mapLocationIcon = new MapLocationIcon(); private Vector2i relativeCellLocation; private Binding<Vector3i> centerLocationBinding = new DefaultBinding<>(null); private Binding<DisplayAxisType> displayAxisTypeBinding = new DefaultBinding<>(null); public MinimapCell() { textureAtlas = Assets.getTexture("engine:terrain").get(); questionMarkTextureRegion = Assets.getTextureRegion("engine:items.questionMark").get(); mapLocationIcon.bindIcon(new ReadOnlyBinding<TextureRegion>() { @Override public TextureRegion get() { Vector3i centerLocation = getCenterLocation(); if (null == centerLocation) { return null; } WorldProvider worldProvider = CoreRegistry.get(WorldProvider.class); DisplayAxisType displayAxis = getDisplayAxisType(); Vector3i relativeLocation; switch (displayAxis) { case XZ_AXIS: // top down view relativeLocation = new Vector3i(-relativeCellLocation.x, 0, relativeCellLocation.y); break; case XY_AXIS: relativeLocation = new Vector3i(-relativeCellLocation.y, -relativeCellLocation.x, 0); break; case YZ_AXIS: relativeLocation = new Vector3i(0, -relativeCellLocation.x, -relativeCellLocation.y); break; default: throw new RuntimeException("displayAxisType containts invalid value"); } relativeLocation.add(centerLocation); Block block = worldProvider.getBlock(relativeLocation); if (null != block) { BlockAppearance primaryAppearance = block.getPrimaryAppearance(); BlockPart blockPart; switch (displayAxis) { case XZ_AXIS: // top down view blockPart = BlockPart.TOP; break; case XY_AXIS: blockPart = BlockPart.FRONT; // todo: front/left/right/back needs to be picked base on viewpoint break; case YZ_AXIS: blockPart = BlockPart.LEFT; // todo: front/left/right/back needs to be picked base on viewpoint break; default: throw new RuntimeException("displayAxisType containts invalid value"); } // TODO: security issues // WorldAtlas worldAtlas = CoreRegistry.get(WorldAtlas.class); // float tileSize = worldAtlas.getRelativeTileSize(); float tileSize = 16f / 256f; // 256f could be replaced by textureAtlas.getWidth(); Vector2f textureAtlasPos = primaryAppearance.getTextureAtlasPos(blockPart); TextureRegion textureRegion = new BasicTextureRegion(textureAtlas, textureAtlasPos, new Vector2f(tileSize, tileSize)); return textureRegion; } logger.info("No block found for location " + relativeLocation); return questionMarkTextureRegion; } }); } @Override public void onDraw(Canvas canvas) { canvas.drawWidget(mapLocationIcon); } @Override public Vector2i getPreferredContentSize(Canvas canvas, Vector2i sizeHint) { return canvas.calculateRestrictedSize(mapLocationIcon, sizeHint); } public Vector2i getCellRelativeLocation() { return relativeCellLocation; } public void setRelativeCellLocation(Vector2i relativeLocation) { this.relativeCellLocation = relativeLocation; } public void bindCenterLocation(Binding<Vector3i> binding) { centerLocationBinding = binding; } public Vector3i getCenterLocation() { return centerLocationBinding.get(); } public void setCenterLocation(Vector3i location) { centerLocationBinding.set(location); } public void bindDisplayAxisType(Binding<DisplayAxisType> binding) { displayAxisTypeBinding = binding; } public DisplayAxisType getDisplayAxisType() { return displayAxisTypeBinding.get(); } public void setDisplayAxisType(DisplayAxisType displayAxis) { displayAxisTypeBinding.set(displayAxis); } }
src/main/java/org/terasology/minimap/rendering/nui/layers/MinimapCell.java
/* * Copyright 2015 MovingBlocks * * 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. */ package org.terasology.minimap.rendering.nui.layers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.asset.Assets; import org.terasology.math.Vector2i; import org.terasology.math.geom.Vector3i; import org.terasology.math.geom.Vector2f; import org.terasology.minimap.DisplayAxisType; import org.terasology.registry.CoreRegistry; import org.terasology.rendering.assets.texture.BasicTextureRegion; import org.terasology.rendering.assets.texture.Texture; import org.terasology.rendering.assets.texture.TextureRegion; import org.terasology.rendering.nui.Canvas; import org.terasology.rendering.nui.CoreWidget; import org.terasology.rendering.nui.databinding.Binding; import org.terasology.rendering.nui.databinding.DefaultBinding; import org.terasology.rendering.nui.databinding.ReadOnlyBinding; import org.terasology.world.WorldProvider; import org.terasology.world.block.Block; import org.terasology.world.block.BlockAppearance; import org.terasology.world.block.BlockPart; /** * @author Immortius */ public class MinimapCell extends CoreWidget { private static final Logger logger = LoggerFactory.getLogger(MinimapCell.class); private final Texture textureAtlas; private final TextureRegion questionMarkTextureRegion; private MapLocationIcon mapLocationIcon = new MapLocationIcon(); private Vector2i relativeCellLocation; private Binding<Vector3i> centerLocationBinding = new DefaultBinding<>(null); private Binding<DisplayAxisType> displayAxisTypeBinding = new DefaultBinding<>(null); public MinimapCell() { textureAtlas = Assets.getTexture("engine:terrain"); questionMarkTextureRegion = Assets.getTextureRegion("engine:items.questionMark"); mapLocationIcon.bindIcon(new ReadOnlyBinding<TextureRegion>() { @Override public TextureRegion get() { Vector3i centerLocation = getCenterLocation(); if (null == centerLocation) { return null; } WorldProvider worldProvider = CoreRegistry.get(WorldProvider.class); DisplayAxisType displayAxis = getDisplayAxisType(); Vector3i relativeLocation; switch (displayAxis) { case XZ_AXIS: // top down view relativeLocation = new Vector3i(-relativeCellLocation.x, 0, relativeCellLocation.y); break; case XY_AXIS: relativeLocation = new Vector3i(-relativeCellLocation.y, -relativeCellLocation.x, 0); break; case YZ_AXIS: relativeLocation = new Vector3i(0, -relativeCellLocation.x, -relativeCellLocation.y); break; default: throw new RuntimeException("displayAxisType containts invalid value"); } relativeLocation.add(centerLocation); Block block = worldProvider.getBlock(relativeLocation); if (null != block) { BlockAppearance primaryAppearance = block.getPrimaryAppearance(); BlockPart blockPart; switch (displayAxis) { case XZ_AXIS: // top down view blockPart = BlockPart.TOP; break; case XY_AXIS: blockPart = BlockPart.FRONT; // todo: front/left/right/back needs to be picked base on viewpoint break; case YZ_AXIS: blockPart = BlockPart.LEFT; // todo: front/left/right/back needs to be picked base on viewpoint break; default: throw new RuntimeException("displayAxisType containts invalid value"); } // TODO: security issues // WorldAtlas worldAtlas = CoreRegistry.get(WorldAtlas.class); // float tileSize = worldAtlas.getRelativeTileSize(); float tileSize = 16f / 256f; // 256f could be replaced by textureAtlas.getWidth(); Vector2f textureAtlasPos = primaryAppearance.getTextureAtlasPos(blockPart); TextureRegion textureRegion = new BasicTextureRegion(textureAtlas, textureAtlasPos, new Vector2f(tileSize, tileSize)); return textureRegion; } logger.info("No block found for location " + relativeLocation); return questionMarkTextureRegion; } }); } @Override public void onDraw(Canvas canvas) { canvas.drawWidget(mapLocationIcon); } @Override public Vector2i getPreferredContentSize(Canvas canvas, Vector2i sizeHint) { return canvas.calculateRestrictedSize(mapLocationIcon, sizeHint); } public Vector2i getCellRelativeLocation() { return relativeCellLocation; } public void setRelativeCellLocation(Vector2i relativeLocation) { this.relativeCellLocation = relativeLocation; } public void bindCenterLocation(Binding<Vector3i> binding) { centerLocationBinding = binding; } public Vector3i getCenterLocation() { return centerLocationBinding.get(); } public void setCenterLocation(Vector3i location) { centerLocationBinding.set(location); } public void bindDisplayAxisType(Binding<DisplayAxisType> binding) { displayAxisTypeBinding = binding; } public DisplayAxisType getDisplayAxisType() { return displayAxisTypeBinding.get(); } public void setDisplayAxisType(DisplayAxisType displayAxis) { displayAxisTypeBinding.set(displayAxis); } }
Fix for engine change (gestalt-asset-core)
src/main/java/org/terasology/minimap/rendering/nui/layers/MinimapCell.java
Fix for engine change (gestalt-asset-core)
<ide><path>rc/main/java/org/terasology/minimap/rendering/nui/layers/MinimapCell.java <ide> <ide> public MinimapCell() { <ide> <del> textureAtlas = Assets.getTexture("engine:terrain"); <del> questionMarkTextureRegion = Assets.getTextureRegion("engine:items.questionMark"); <add> textureAtlas = Assets.getTexture("engine:terrain").get(); <add> questionMarkTextureRegion = Assets.getTextureRegion("engine:items.questionMark").get(); <ide> <ide> mapLocationIcon.bindIcon(new ReadOnlyBinding<TextureRegion>() { <ide> @Override
Java
apache-2.0
a6c6ac4b9dce7900691d3454dc7f9a602c24cd49
0
mission-peace/interview,mission-peace/interview,mission-peace/interview
package com.interview.multiarray; /** * Date 10/20/2016 * @author Tushar Roy * Given a board with m by n cells, each cell has an initial state live (1) or dead (0). * Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following * four rules (taken from the above Wikipedia article): * Read full qs on leetcode. * * Solution - Keep two array prev and current. Fill the values in current array. As soon as current row is done * replace elemments of board with prev array. * * Time complexity O(n * m) * * https://leetcode.com/problems/game-of-life/ */ public class GameOfLife { public void gameOfLife(int[][] board) { if (board.length == 0 || board[0].length == 0) { return; } int n = board.length; int m = board[0].length; int[] prevRow = new int[m]; int[] currentRow = new int[m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { currentRow[j] = doesLive(i, j, board) ? 1 : 0; } if (i != 0) { copyRow(prevRow, board[i - 1]); } if (i != n - 1) { copyRow(currentRow, prevRow); } } copyRow(currentRow, board[n - 1]); } private void copyRow(int[] source, int[] dest) { for (int i = 0; i < source.length; i++) { dest[i] = source[i]; } } private boolean doesLive(int x, int y, int[][] board) { int count = 0; for (int i = x - 1; i <= x + 1; i++) { for (int j = y - 1; j <= y + 1; j++) { if (x == i && y == j) { continue; } if (i < 0 || i >= board.length) { break; } if (j < 0 || j >= board[0].length) { continue; } count += board[i][j]; } } if (board[x][y] == 1) { return count == 2 || count == 3; } else { return count == 3; } } }
src/com/interview/multiarray/GameOfLife.java
package com.interview.multiarray; public class GameOfLife { boolean [][]board = null; boolean [][]tempBoard = null; public GameOfLife(boolean[][] initialState){ board = initialState; tempBoard = new boolean[board.length][board.length]; } public void printState(){ for(int i=0; i < board.length; i++){ for(int j=0; j < board[i].length; j++){ if(board[i][j]){ System.out.print("1 "); }else{ System.out.print("0 "); } } System.out.print("\n"); } System.out.print("\n\n"); } public void next(){ int count=0; for(int i=0; i < board.length; i++){ for(int j=0; j < board[i].length; j++){ count = countNeighbors(i, j); tempBoard[i][j] = board[i][j]; if(count <= 1){ tempBoard[i][j] = false; } if(count ==3){ tempBoard[i][j] = true; } if(count >= 4){ tempBoard[i][j] = false; } } } boolean[][] rBoard = tempBoard; tempBoard = board; board = rBoard; } public void nextOptimized(){ boolean temp1[] = new boolean[board[0].length]; boolean temp2[] = new boolean[board[0].length]; calculate(board,temp1,0); for(int i=1; i < board.length; i++){ calculate(board,temp2,i); copy(i-1,temp1); copy(temp1,temp2); } copy(board.length-1,temp1); } void copy(boolean arr1[],boolean arr2[]){ for(int i=0; i <arr2.length; i++){ arr1[i] = arr2[i]; } } void calculate(boolean [][]board,boolean temp[],int i){ int count=0; for(int j=0; j < board[i].length; j++){ count = countNeighbors(i, j); temp[j] = board[i][j]; if(count <= 1){ temp[j] = false; } if(count ==3){ temp[j] = true; } if(count >= 4){ temp[j] = false; } } } private void copy(int i,boolean []temp){ for(int x=0; x < temp.length; x++){ board[i][x] = temp[x]; } } private int countNeighbors(int i,int j){ int count =0; for(int k = i-1; k <= i+1; k++){ for(int l = j-1; l <= j+1; l++){ if((i ==k && j == l) || k < 0 || l < 0 || k >= board.length || l >= board[k].length){ continue; } if(board[k][l]){ count++; } } } return count; } public static void main(String args[]){ boolean[][] initialState = new boolean[10][10]; initialState[3][6] = true; initialState[4][6] = true; initialState[5][6] = true; initialState[5][7] = true; initialState[5][8] = true; GameOfLife gol = new GameOfLife(initialState); gol.printState(); gol.nextOptimized(); gol.printState(); gol.nextOptimized(); gol.printState(); gol.nextOptimized(); gol.printState(); gol.nextOptimized(); gol.printState(); } }
Update game of life
src/com/interview/multiarray/GameOfLife.java
Update game of life
<ide><path>rc/com/interview/multiarray/GameOfLife.java <ide> package com.interview.multiarray; <ide> <add>/** <add> * Date 10/20/2016 <add> * @author Tushar Roy <add> * Given a board with m by n cells, each cell has an initial state live (1) or dead (0). <add> * Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following <add> * four rules (taken from the above Wikipedia article): <add> * Read full qs on leetcode. <add> * <add> * Solution - Keep two array prev and current. Fill the values in current array. As soon as current row is done <add> * replace elemments of board with prev array. <add> * <add> * Time complexity O(n * m) <add> * <add> * https://leetcode.com/problems/game-of-life/ <add> */ <ide> public class GameOfLife { <add> public void gameOfLife(int[][] board) { <add> if (board.length == 0 || board[0].length == 0) { <add> return; <add> } <add> int n = board.length; <add> int m = board[0].length; <add> int[] prevRow = new int[m]; <add> int[] currentRow = new int[m]; <ide> <del> boolean [][]board = null; <del> boolean [][]tempBoard = null; <del> public GameOfLife(boolean[][] initialState){ <del> board = initialState; <del> tempBoard = new boolean[board.length][board.length]; <del> } <del> <del> public void printState(){ <del> for(int i=0; i < board.length; i++){ <del> for(int j=0; j < board[i].length; j++){ <del> if(board[i][j]){ <del> System.out.print("1 "); <del> }else{ <del> System.out.print("0 "); <del> } <del> } <del> System.out.print("\n"); <del> } <del> System.out.print("\n\n"); <del> } <del> <del> public void next(){ <del> <del> int count=0; <del> for(int i=0; i < board.length; i++){ <del> for(int j=0; j < board[i].length; j++){ <del> count = countNeighbors(i, j); <del> tempBoard[i][j] = board[i][j]; <del> if(count <= 1){ <del> tempBoard[i][j] = false; <del> } <del> if(count ==3){ <del> tempBoard[i][j] = true; <del> } <del> if(count >= 4){ <del> tempBoard[i][j] = false; <del> } <del> } <del> } <del> boolean[][] rBoard = tempBoard; <del> tempBoard = board; <del> board = rBoard; <del> } <add> for (int i = 0; i < n; i++) { <add> for (int j = 0; j < m; j++) { <add> currentRow[j] = doesLive(i, j, board) ? 1 : 0; <add> } <add> if (i != 0) { <add> copyRow(prevRow, board[i - 1]); <add> } <add> if (i != n - 1) { <add> copyRow(currentRow, prevRow); <add> } <add> } <add> copyRow(currentRow, board[n - 1]); <add> } <ide> <del> public void nextOptimized(){ <del> <del> boolean temp1[] = new boolean[board[0].length]; <del> boolean temp2[] = new boolean[board[0].length]; <del> calculate(board,temp1,0); <del> for(int i=1; i < board.length; i++){ <del> calculate(board,temp2,i); <del> copy(i-1,temp1); <del> copy(temp1,temp2); <del> } <del> copy(board.length-1,temp1); <del> } <del> <del> void copy(boolean arr1[],boolean arr2[]){ <del> for(int i=0; i <arr2.length; i++){ <del> arr1[i] = arr2[i]; <del> } <del> } <del> <del> void calculate(boolean [][]board,boolean temp[],int i){ <del> int count=0; <del> for(int j=0; j < board[i].length; j++){ <del> count = countNeighbors(i, j); <del> temp[j] = board[i][j]; <del> if(count <= 1){ <del> temp[j] = false; <del> } <del> if(count ==3){ <del> temp[j] = true; <del> } <del> if(count >= 4){ <del> temp[j] = false; <del> } <del> } <add> private void copyRow(int[] source, int[] dest) { <add> for (int i = 0; i < source.length; i++) { <add> dest[i] = source[i]; <add> } <add> } <ide> <del> } <del> <del> private void copy(int i,boolean []temp){ <del> for(int x=0; x < temp.length; x++){ <del> board[i][x] = temp[x]; <del> } <del> } <del> <del> private int countNeighbors(int i,int j){ <del> int count =0; <del> for(int k = i-1; k <= i+1; k++){ <del> for(int l = j-1; l <= j+1; l++){ <del> if((i ==k && j == l) || k < 0 || l < 0 || k >= board.length || l >= board[k].length){ <del> continue; <del> } <del> if(board[k][l]){ <del> count++; <del> } <del> } <del> } <del> return count; <del> } <del> <del> public static void main(String args[]){ <del> boolean[][] initialState = new boolean[10][10]; <del> initialState[3][6] = true; <del> initialState[4][6] = true; <del> initialState[5][6] = true; <del> initialState[5][7] = true; <del> initialState[5][8] = true; <del> GameOfLife gol = new GameOfLife(initialState); <del> gol.printState(); <del> gol.nextOptimized(); <del> gol.printState(); <del> gol.nextOptimized(); <del> gol.printState(); <del> gol.nextOptimized(); <del> gol.printState(); <del> gol.nextOptimized(); <del> gol.printState(); <del> <del> } <add> private boolean doesLive(int x, int y, int[][] board) { <add> int count = 0; <add> for (int i = x - 1; i <= x + 1; i++) { <add> for (int j = y - 1; j <= y + 1; j++) { <add> if (x == i && y == j) { <add> continue; <add> } <add> if (i < 0 || i >= board.length) { <add> break; <add> } <add> if (j < 0 || j >= board[0].length) { <add> continue; <add> } <add> count += board[i][j]; <add> } <add> } <add> if (board[x][y] == 1) { <add> return count == 2 || count == 3; <add> } else { <add> return count == 3; <add> } <add> } <ide> }
JavaScript
mit
8c12f786a2f0c48d62f0d3c1671728f8903ae464
0
packrat386/Website
var http = require('http'); var getPageData = function(title, callback){ //this is the link format var link = "/starcraft2/api.php?format=json&action=query&titles="+ title + "&prop=revisions&rvprop=content"; //here we have the variable we're going to run the callback on var holder; //these are the options for the http request var options = { host: 'wiki.teamliquid.net', port: 80, path: link }; //do a get request http.get(options, function(resp){ var output = ''; //put together the output resp.on('data', function(chunk){ output += chunk; }); //when we're at the end, put the object together and store it resp.on('end', function(){ holder = JSON.parse(output); //console.log("In end function"); //console.log(resp.statusCode); //console.log(holder); callback(holder); }); }); }; var parsePage = function(page){ //first we split it into an array called lines var lines = page.split(/\r\n|\r|\n/g); var count = 1; var inBracket = false; var result; for(i in lines){ if(/{{(.*)bracket$/i.test(lines[i])){ inBracket = true; } if(inBracket){ if(/\|R(\d+)(D|W)\d+race=([ztpr])/i.test(lines[i])){ result = /\|R(\d+)(D|W)\d+race=([ztpr])/i.exec(lines[i]); console.log("Found Round " + result[1] + " " + result[2] + " race: " + result[3]); } } if(/{{:(.*)}}/.test(lines[i])){ result = /{{:(.*)}}/.exec(lines[i]); console.log("found link: "); console.log(result[1]); } } }; var parseGroupStage = function(lines) { var inGroupStage = false, groupStageCount = 1, groupStageHeadingLevel = 0, inGroupTable = false, result; for(i in lines){ // If we are in a group stage section, look for a heading that could close this section if (inGroupStage && /^(=+).*=+$/.test(lines[i])) { result = /^(=+).*=+$/.exec(lines[i]); // Close the current group stage if section ends // (new heading with at same level, or level closer to 1) if (result[1].match(/=/g).length <= groupStageHeadingLevel) { groupStageCount++; inGroupStage = false; groupStageHeadingLevel = 0; } } // Look for a Group Stage heading (not mandatory) if(/^(=+)[\s]*Group Stage.*=+$/i.test(lines[i])) { result = /^(=+)[\s]*Group Stage.*=+$/i.exec(lines[i]); inGroupStage = true; groupStageHeadingLevel = result[1].match(/=/g).length; } // Look for a GroupTableStart line if(/\{\{(Template:)?GroupTableStart/i.test(lines[i])) { inGroupTable = true; } if(inGroupTable){ if(/\{\{(Template\:)*GroupTableSlot[\s]?\|(.*)race=([ztpr])/i.test(lines[i])) { result = /\{\{(Template\:)*GroupTableSlot[\s]*\|.*race=([ztpr])/i.exec(lines[i]); console.log("Found Group Stage " + groupStageCount + " race:", result[2]); } } } }; module.exports.getPageData = getPageData; module.exports.parsePage = parsePage;
parser.js
var http = require('http'); var getPageData = function(title, callback){ //this is the link format var link = "/starcraft2/api.php?format=json&action=query&titles="+ title + "&prop=revisions&rvprop=content"; //here we have the variable we're going to run the callback on var holder; //these are the options for the http request var options = { host: 'wiki.teamliquid.net', port: 80, path: link }; //do a get request http.get(options, function(resp){ var output = ''; //put together the output resp.on('data', function(chunk){ output += chunk; }); //when we're at the end, put the object together and store it resp.on('end', function(){ holder = JSON.parse(output); //console.log("In end function"); //console.log(resp.statusCode); //console.log(holder); callback(holder); }); }); }; var parsePage = function(page){ //first we split it into an array called lines var lines = page.split(/\r\n|\r|\n/g); var count = 1; var inBracket = false; var result; for(i in lines){ if(/{{(.*)bracket$/i.test(lines[i])){ inBracket = true; } if(inBracket){ if(/\|R(\d+)(D|W)\d+race=([ztpr])/i.test(lines[i])){ result = /\|R(\d+)(D|W)\d+race=([ztpr])/i.exec(lines[i]); console.log("Found Round " + result[1] + " " + result[2] + " race: " + result[3]); } } if(/{{:(.*)}}/.test(lines[i])){ result = /{{:(.*)}}/.exec(lines[i]); console.log("found link: "); console.log(result[1]); } } }; var parseGroupStage = function(lines) { var inGroupTable = false, result; for(i in lines){ if(/\{\{(Template:)?GroupTableStart/i.test(lines[i])) { inGroupTable = true; } if(inGroupTable){ if(/\{\{(Template\:)*GroupTableSlot[\s]?\|(.*)race=([ztpr])/i.test(lines[i])) { result = /\{\{(Template\:)*GroupTableSlot[\s]*\|.*race=([ztpr])/i.exec(lines[i]); console.log("Found Group Stage " + groupStageCount + " race:", result[2]); } } } }; module.exports.getPageData = getPageData; module.exports.parsePage = parsePage;
Added support for headings to separate group stages
parser.js
Added support for headings to separate group stages
<ide><path>arser.js <ide> }; <ide> <ide> var parseGroupStage = function(lines) { <del> var inGroupTable = false, <add> var inGroupStage = false, <add> groupStageCount = 1, <add> groupStageHeadingLevel = 0, <add> inGroupTable = false, <ide> result; <ide> <ide> for(i in lines){ <add> // If we are in a group stage section, look for a heading that could close this section <add> if (inGroupStage && /^(=+).*=+$/.test(lines[i])) { <add> result = /^(=+).*=+$/.exec(lines[i]); <add> // Close the current group stage if section ends <add> // (new heading with at same level, or level closer to 1) <add> if (result[1].match(/=/g).length <= groupStageHeadingLevel) { <add> groupStageCount++; <add> inGroupStage = false; <add> groupStageHeadingLevel = 0; <add> } <add> } <add> // Look for a Group Stage heading (not mandatory) <add> if(/^(=+)[\s]*Group Stage.*=+$/i.test(lines[i])) { <add> result = /^(=+)[\s]*Group Stage.*=+$/i.exec(lines[i]); <add> inGroupStage = true; <add> groupStageHeadingLevel = result[1].match(/=/g).length; <add> } <add> // Look for a GroupTableStart line <ide> if(/\{\{(Template:)?GroupTableStart/i.test(lines[i])) { <ide> inGroupTable = true; <ide> }
Java
mit
bd557c5c6800e8bc2f65db3a3f268445c85faf53
0
diirt/diirt,diirt/diirt,diirt/diirt,berryma4/diirt,berryma4/diirt,ControlSystemStudio/diirt,ControlSystemStudio/diirt,richardfearn/diirt,ControlSystemStudio/diirt,berryma4/diirt,richardfearn/diirt,berryma4/diirt,diirt/diirt,ControlSystemStudio/diirt,richardfearn/diirt
/** * Copyright (C) 2010-14 diirt developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ package org.diirt.service.exec; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.diirt.service.Service; import org.diirt.service.ServiceFactory; import org.diirt.util.config.Configuration; /** * A service factory that crawls a directory for xml files, and creates a JDBC * service from each of them. * * @author carcassi */ public class ExecServiceFactory implements ServiceFactory { private static final Logger log = Logger.getLogger(ExecServiceFactory.class.getName()); private final File directory; private final boolean includeGenericExecService; /** * Creates a new factory that reads from the given directory. * <p> * If the directory does not exist, it simply returns an empty set. * * @param directory a directory * @param includeGenericExecService whether to include the general purpose * exec service */ public ExecServiceFactory(File directory, boolean includeGenericExecService) { this.directory = directory; this.includeGenericExecService = includeGenericExecService; } /** * Creates a new factory using the default configuration directory. */ public ExecServiceFactory() { this(new File(Configuration.getDirectory(), "services/exec"), true); } /** * Crawls the directory and creates JDBC services. * <p> * XML files that do not parse correctly are skipped. * * @return the created services */ @Override public Collection<Service> createServices() { List<Service> services = new ArrayList<>(); if (includeGenericExecService) { services.add(new GenericExecService()); } if (directory.exists()) { if (directory.isDirectory()) { // We have a configuration directory log.log(Level.CONFIG, "Loading exec services from ''{0}''", directory); for (File file : directory.listFiles()) { if (file.getName().endsWith(".xml")) { try { ExecService service = ExecServices.createFromXml(new FileInputStream(file)); services.add(service); log.log(Level.CONFIG, "Adding exec service '{0}'", service.getName()); } catch (Exception ex) { log.log(Level.WARNING, "Failed to create exec service from '" + file + "'", ex); } } } } else { // The path is not a directory log.log(Level.WARNING, "Configuration path for exec services '{0}' is not a directory", directory); } } else { // The path does not exist directory.mkdirs(); log.log(Level.CONFIG, "Creating configuration path for exec services at '{0}'", directory); } return services; } }
pvmanager/pvmanager-exec/src/main/java/org/diirt/service/exec/ExecServiceFactory.java
/** * Copyright (C) 2010-14 diirt developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ package org.diirt.service.exec; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.diirt.service.Service; import org.diirt.service.ServiceFactory; import org.diirt.util.config.Configuration; /** * A service factory that crawls a directory for xml files, and creates a JDBC * service from each of them. * * @author carcassi */ public class ExecServiceFactory implements ServiceFactory { private static final Logger log = Logger.getLogger(ExecServiceFactory.class.getName()); private final File directory; private final boolean includeGenericExecService; /** * Creates a new factory that reads from the given directory. * <p> * If the directory does not exist, it simply returns an empty set. * * @param directory a directory * @param includeGenericExecService whether to include the general purpose * exec service */ public ExecServiceFactory(File directory, boolean includeGenericExecService) { this.directory = directory; this.includeGenericExecService = includeGenericExecService; } /** * Creates a new factory using the default configuration directory. */ public ExecServiceFactory() { this(new File(Configuration.getDirectory(), "services/exec"), true); } /** * Crawls the directory and creates JDBC services. * <p> * XML files that do not parse correctly are skipped. * * @return the created services */ @Override public Collection<Service> createServices() { List<Service> services = new ArrayList<>(); if (includeGenericExecService) { services.add(new GenericExecService()); } if (directory.exists()) { if (directory.isDirectory()) { // We have a configuration directory log.log(Level.CONFIG, "Loading exec services from '{0}'", directory); for (File file : directory.listFiles()) { if (file.getName().endsWith(".xml")) { try { ExecService service = ExecServices.createFromXml(new FileInputStream(file)); services.add(service); log.log(Level.CONFIG, "Adding exec service '{0}'", service.getName()); } catch (Exception ex) { log.log(Level.WARNING, "Failed to create exec service from '" + file + "'", ex); } } } } else { // The path is not a directory log.log(Level.WARNING, "Configuration path for exec services '{0}' is not a directory", directory); } } else { // The path does not exist directory.mkdirs(); log.log(Level.CONFIG, "Creating configuration path for exec services at '{0}'", directory); } return services; } }
exec: fix log
pvmanager/pvmanager-exec/src/main/java/org/diirt/service/exec/ExecServiceFactory.java
exec: fix log
<ide><path>vmanager/pvmanager-exec/src/main/java/org/diirt/service/exec/ExecServiceFactory.java <ide> } <ide> if (directory.exists()) { <ide> if (directory.isDirectory()) { // We have a configuration directory <del> log.log(Level.CONFIG, "Loading exec services from '{0}'", directory); <add> log.log(Level.CONFIG, "Loading exec services from ''{0}''", directory); <ide> for (File file : directory.listFiles()) { <ide> if (file.getName().endsWith(".xml")) { <ide> try {
Java
bsd-3-clause
e056954467767e3462f80318f15546d8893913a7
0
xizi-xu/Argus,rajsarkapally-sfdc/Argus,SalesforceEng/Argus,rajsarkapally/Argus,rajsarkapally/Argus,salesforce/Argus,dilipdevaraj-sfdc/Argus-1,xizi-xu/Argus,rajsarkapally/Argus,salesforce/Argus,xizi-xu/Argus,rajsarkapally-sfdc/Argus,rajsarkapally-sfdc/Argus,rajsarkapally/Argus,dilipdevaraj-sfdc/Argus-1,salesforce/Argus,dilipdevaraj-sfdc/Argus-1,SalesforceEng/Argus,SalesforceEng/Argus,rajsarkapally-sfdc/Argus,SalesforceEng/Argus,xizi-xu/Argus,dilipdevaraj-sfdc/Argus-1,salesforce/Argus,rajsarkapally/Argus
/* * Copyright (c) 2016, Salesforce.com, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Salesforce.com nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.salesforce.dva.argus.service.schema; import com.google.inject.Inject; import com.google.inject.Singleton; import com.salesforce.dva.argus.entity.KeywordQuery; import com.salesforce.dva.argus.entity.Metric; import com.salesforce.dva.argus.entity.MetricSchemaRecord; import com.salesforce.dva.argus.entity.MetricSchemaRecordQuery; import com.salesforce.dva.argus.service.AsyncHBaseClientFactory; import com.salesforce.dva.argus.service.MonitorService; import com.salesforce.dva.argus.service.SchemaService; import com.salesforce.dva.argus.system.SystemAssert; import com.salesforce.dva.argus.system.SystemConfiguration; import com.salesforce.dva.argus.system.SystemException; import com.stumbleupon.async.Callback; import com.stumbleupon.async.Deferred; import com.stumbleupon.async.TimeoutException; import org.apache.hadoop.hbase.util.Bytes; import org.hbase.async.CompareFilter.CompareOp; import org.hbase.async.FilterList; import org.hbase.async.FirstKeyOnlyFilter; import org.hbase.async.HBaseClient; import org.hbase.async.KeyOnlyFilter; import org.hbase.async.KeyValue; import org.hbase.async.PutRequest; import org.hbase.async.RegexStringComparator; import org.hbase.async.RowFilter; import org.hbase.async.ScanFilter; import org.hbase.async.Scanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.Charset; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; /** * Implementation of the schema service using Asynchbase. * * @author Bhinav Sura ([email protected]) */ @Singleton public class AsyncHbaseSchemaService extends AbstractSchemaService { //~ Static fields/initializers ******************************************************************************************************************* private static String METRIC_SCHEMA_TABLENAME; private static String SCOPE_SCHEMA_TABLENAME ; private static final byte[] COLUMN_FAMILY = "f".getBytes(Charset.forName("UTF-8")); private static final byte[] COLUMN_QUALIFIER = "c".getBytes(Charset.forName("UTF-8")); private static final byte[] CELL_VALUE = new byte[1]; private static final char ROWKEY_SEPARATOR = '\u0000'; private static final char PLACEHOLDER_FOR_NULL_STRINGS = '\u0023'; private static final long TIMEOUT_MS = 30 * 1000; private static final long SCAN_TIMEOUT_MS = 2 * 60 * 1000; //~ Instance fields ****************************************************************************************************************************** private Logger _logger = LoggerFactory.getLogger(AsyncHbaseSchemaService.class); private final HBaseClient _client; private final boolean _syncPut; private final MonitorService _monitorService; //~ Constructors ********************************************************************************************************************************* @Inject private AsyncHbaseSchemaService(SystemConfiguration systemConfig, AsyncHBaseClientFactory factory, MonitorService monitorService) { super(systemConfig); _monitorService = monitorService; _syncPut = Boolean.parseBoolean(systemConfig.getValue(Property.HBASE_SYNC_PUT.getName(), Property.HBASE_SYNC_PUT.getDefaultValue())); METRIC_SCHEMA_TABLENAME = systemConfig.getValue(Property.HBASE_METRICSCHEMA_TABLE.getName(), Property.HBASE_METRICSCHEMA_TABLE.getDefaultValue()); SCOPE_SCHEMA_TABLENAME = systemConfig.getValue(Property.HBASE_SCOPESCHEMA_TABLE.getName(), Property.HBASE_SCOPESCHEMA_TABLE.getDefaultValue()); _client = factory.getClient(); } //~ Methods ************************************************************************************************************************************** private static String _constructRowKey(String namespace, String scope, String metric, String tagKey, String tagValue, String tableName) { namespace = namespace == null ? Character.toString(PLACEHOLDER_FOR_NULL_STRINGS) : namespace; tagKey = tagKey == null ? Character.toString(PLACEHOLDER_FOR_NULL_STRINGS) : tagKey; tagValue = tagValue == null ? Character.toString(PLACEHOLDER_FOR_NULL_STRINGS) : tagValue; String key; if (SCOPE_SCHEMA_TABLENAME.equals(tableName)) { key = MessageFormat.format("{0}{5}{1}{5}{2}{5}{3}{5}{4}", scope, metric, tagKey, tagValue, namespace, ROWKEY_SEPARATOR); } else if (METRIC_SCHEMA_TABLENAME.equals(tableName)) { key = MessageFormat.format("{0}{5}{1}{5}{2}{5}{3}{5}{4}", metric, scope, tagKey, tagValue, namespace, ROWKEY_SEPARATOR); } else { throw new SystemException(new IllegalArgumentException("Unknown table: " + tableName)); } return key; } private static String _constructRowKey(MetricSchemaRecord schema, String tableName){ return _constructRowKey(schema.getNamespace(), schema.getScope(), schema.getMetric(), schema.getTagKey(), schema.getTagValue(), tableName); } private static MetricSchemaRecord _constructMetricSchemaRecord(String rowKey, String tableName) { SystemAssert.requireArgument(rowKey != null && !rowKey.isEmpty(), "This should never happen. Rowkey should never be null or empty."); String[] parts = rowKey.split(String.valueOf(ROWKEY_SEPARATOR)); MetricSchemaRecord record; if (SCOPE_SCHEMA_TABLENAME.equals(tableName)) { record = new MetricSchemaRecord(parts[0], parts[1]); } else if (METRIC_SCHEMA_TABLENAME.equals(tableName)) { record = new MetricSchemaRecord(parts[1], parts[0]); } else { throw new SystemException(new IllegalArgumentException("Unknown table: " + tableName)); } String placeholder = Character.toString(PLACEHOLDER_FOR_NULL_STRINGS); if (!placeholder.equals(parts[2])) { record.setTagKey(parts[2]); } if (!placeholder.equals(parts[3])) { record.setTagValue(parts[3]); } if (!placeholder.equals(parts[4])) { record.setNamespace(parts[4]); } return record; } private String _plusOneNConstructRowKey(MetricSchemaRecord record, String tableName, RecordType type){ if(type==null){ return _plusOne(_constructRowKey(record, tableName)); }else{ switch (type) { case NAMESPACE: record.setNamespace(_plusOne(record.getNamespace())); break; case SCOPE: record.setScope(_plusOne(record.getScope())); break; case METRIC: record.setMetric(_plusOne(record.getMetric())); break; case TAGK: record.setTagKey(_plusOne(record.getTagKey())); break; case TAGV: record.setTagValue(_plusOne(record.getTagValue())); } } return _constructRowKey(record, tableName); } //~ Methods ************************************************************************************************************************************** @Override protected void implementationSpecificPut(List<Metric> metrics) { requireNotDisposed(); SystemAssert.requireArgument(metrics != null, "Metric list cannot be null."); for (Metric metric : metrics) { if (metric.getTags().isEmpty()) { _putWithoutTag(metric); } for (Entry<String, String> tag : metric.getTags().entrySet()) { _putWithTag(metric, tag); } } } @Override public List<MetricSchemaRecord> get(final MetricSchemaRecordQuery query) { requireNotDisposed(); SystemAssert.requireArgument(query != null, "Metric Schema Record query cannot be null."); final List<MetricSchemaRecord> records = new ArrayList<MetricSchemaRecord>(query.getLimit()); final ScanMetadata metadata = _constructScanMetadata(query); String namespace = SchemaService.convertToRegex(query.getNamespace()); String scope = SchemaService.convertToRegex(query.getScope()); String metric = SchemaService.convertToRegex(query.getMetric()); String tagKey = SchemaService.convertToRegex(query.getTagKey()); String tagValue = SchemaService.convertToRegex(query.getTagValue()); MetricSchemaRecord scanFrom = query.getScanFrom(); String rowKeyRegex = "^" + _constructRowKey(namespace, scope, metric, tagKey, tagValue, metadata.tableName) + "$"; String scanStartRow = scanFrom == null ? Bytes.toString(metadata.startRow) : _plusOneNConstructRowKey(scanFrom, metadata.tableName, null); _logger.info("Using table: " + metadata.tableName); _logger.info("Rowkey: " + rowKeyRegex); _logger.debug("Scan startRow: " + scanStartRow); _logger.debug("Scan stopRow: " + metadata.stopRow.toString()); List<ScanFilter> filters = new ArrayList<ScanFilter>(); filters.add(new RowFilter(CompareOp.EQUAL, new RegexStringComparator(rowKeyRegex))); filters.add(new KeyOnlyFilter()); filters.add(new FirstKeyOnlyFilter()); FilterList fl = new FilterList(filters, FilterList.Operator.MUST_PASS_ALL); final Scanner scanner = _client.newScanner(metadata.tableName); scanner.setStartKey(scanStartRow.getBytes()); scanner.setStopKey(metadata.stopRow); scanner.setFilter(fl); scanner.setMaxNumRows(Math.min(query.getLimit(), 10000)); final Deferred<List<MetricSchemaRecord>> results = new Deferred<List<MetricSchemaRecord>>(); /** * Scans HBASE rows. * * @author Bhinav Sura ([email protected]) */ final class ScannerCB implements Callback<Object, ArrayList<ArrayList<KeyValue>>> { /** * Scans rows. * * @return The list of metric schema records. */ public Object scan() { _logger.trace("Getting next set of rows."); return scanner.nextRows().addCallback(this); } @Override public Object call(ArrayList<ArrayList<KeyValue>> rows) throws Exception { _logger.trace("Inside nextRows() callback.."); try { if (rows == null) { results.callback(records); scanner.close(); return null; } _logger.debug("Retrieved " + rows.size() + " rows."); for(ArrayList<KeyValue> row:rows){ byte[] rowKey=row.get(0).key(); MetricSchemaRecord record = _constructMetricSchemaRecord(Bytes.toString(rowKey), metadata.tableName); records.add(record); if (records.size() == query.getLimit()) { results.callback(records); scanner.close(); return null; } } return scan(); } catch (Exception e) { scanner.close(); return null; } } } new ScannerCB().scan(); try { return results.join(SCAN_TIMEOUT_MS); } catch (InterruptedException e) { throw new SystemException("Interrupted while waiting to obtain results for query: " + query, e); } catch (TimeoutException e) { _logger.warn("Timed out while waiting to obtain results for query: {}. Will return an empty list.", query); return Collections.emptyList(); } catch (Exception e) { throw new SystemException("Exception occurred in getting results for query: " + query, e); } } /** * Fast scan works when trying to discover either scopes or metrics with all other fields being *. * In this case, when the first result is obtained, we skip all other rows starting with that prefix and directly move * on to the next possible value which is obtained value incremented by 1 Ascii character. If that value exists, then * it is returned, otherwise HBase returns the next possible value in lexicographical order. * * For e.g. suppose if we have the following rows in HBase: * * scope\0metric1\0$\0$\0$ * scope\0metric2\0$\0$\0$ * . * . * . * scope\0metric1000\0$\0$\0$ * scopu\0metric1\0$\0$\0$ * scopu\0metric2\0$\0$\0$ * . * . * . * scopu\0metric1000\0$\0$\0$ * * And our start row is "sco", then this method would first find "scope" and then jump the next 1000 rows * to start from the next possible value of scopf. Since nothing like scopf exists, HBase would directly * jump to scopu and return that. * */ private List<MetricSchemaRecord> _getUniqueFastScan(MetricSchemaRecordQuery query, final RecordType type) { requireNotDisposed(); SystemAssert.requireArgument(RecordType.METRIC.equals(type) || RecordType.SCOPE.equals(type), "This method is only for use with metric or scope."); _logger.info("Using FastScan. Will skip rows while scanning."); final Set<MetricSchemaRecord> records = new HashSet<>(); final ScanMetadata metadata = _constructScanMetadata(query); String namespace = SchemaService.convertToRegex(query.getNamespace()); String scope = SchemaService.convertToRegex(query.getScope()); String metric = SchemaService.convertToRegex(query.getMetric()); String tagKey = SchemaService.convertToRegex(query.getTagKey()); String tagValue = SchemaService.convertToRegex(query.getTagValue()); MetricSchemaRecord scanFrom = query.getScanFrom(); String rowKeyRegex = "^" + _constructRowKey(namespace, scope, metric, tagKey, tagValue, metadata.tableName) + "$"; List<ScanFilter> filters = new ArrayList<ScanFilter>(); filters.add(new RowFilter(CompareOp.EQUAL, new RegexStringComparator(rowKeyRegex))); filters.add(new KeyOnlyFilter()); filters.add(new FirstKeyOnlyFilter()); FilterList filterList = new FilterList(filters, FilterList.Operator.MUST_PASS_ALL); String start = scanFrom == null ? Bytes.toString(metadata.startRow) : _plusOneNConstructRowKey(scanFrom, metadata.tableName, type); String end = Bytes.toString(metadata.stopRow); ArrayList<ArrayList<KeyValue>> rows = _getSingleRow(start, end, filterList, metadata.tableName); while(rows != null && !rows.isEmpty()) { String rowKey = Bytes.toString(rows.get(0).get(0).key()); String splits[] = rowKey.split(String.valueOf(ROWKEY_SEPARATOR)); String record = (RecordType.METRIC.equals(type) && metadata.tableName.equals(METRIC_SCHEMA_TABLENAME)) || (RecordType.SCOPE.equals(type) && metadata.tableName.equals(SCOPE_SCHEMA_TABLENAME)) ? splits[0] : splits[1]; MetricSchemaRecord schemaRecord = RecordType.METRIC.equals(type) ? new MetricSchemaRecord(null, record) : new MetricSchemaRecord(record, null); records.add(schemaRecord); if(records.size() == query.getLimit()) { break; } String newScanStart; if(!SchemaService.containsFilter(query.getScope()) || !SchemaService.containsFilter(query.getMetric())) { newScanStart = _plusOne(record); } else { newScanStart = _plusOne(splits[0] + ROWKEY_SEPARATOR + splits[1]); } rows = _getSingleRow(newScanStart, end, filterList, metadata.tableName); } return new ArrayList<>(records); } private ArrayList<ArrayList<KeyValue>> _getSingleRow(final String start, final String end, final FilterList filterList, final String tableName) { final Scanner scanner = _client.newScanner(tableName); scanner.setStartKey(start); scanner.setStopKey(end); scanner.setMaxNumRows(1); scanner.setFilter(filterList); _logger.debug("Using table: " + tableName); _logger.debug("Scan startRow: " + start); _logger.debug("Scan stopRow: " + end); Deferred<ArrayList<ArrayList<KeyValue>>> deferred = scanner.nextRows(); deferred.addCallback(new Callback<ArrayList<ArrayList<KeyValue>>, ArrayList<ArrayList<KeyValue>>>() { @Override public ArrayList<ArrayList<KeyValue>> call(ArrayList<ArrayList<KeyValue>> rows) throws Exception { scanner.close(); return rows; } }); try { ArrayList<ArrayList<KeyValue>> result = deferred.join(SCAN_TIMEOUT_MS); return result; } catch (InterruptedException e) { throw new SystemException("Interrupted while waiting to obtain results for query", e); } catch (TimeoutException e) { _logger.warn("Timed out while waiting to obtain results."); } catch (Exception e) { throw new SystemException("Exception occurred in getting results for query", e); } return null; } //TSDB allowed characteers are: [A-Za-z0-9./-_]. The lowest ASCII value (45) out of these is for hyphen (-). private String _plusOne(String prefix) { char newChar = 45; return prefix + newChar; } /** * Check if we can perform a faster scan. We can only perform a faster scan when we are trying to discover scopes or metrics * without having information on any other fields. */ private boolean _canSkipWhileScanning(MetricSchemaRecordQuery query, RecordType type) { if( (RecordType.METRIC.equals(type) || RecordType.SCOPE.equals(type)) && !SchemaService.containsFilter(query.getTagKey()) && !SchemaService.containsFilter(query.getTagValue()) && !SchemaService.containsFilter(query.getNamespace())) { if(RecordType.METRIC.equals(type) && !SchemaService.containsFilter(query.getMetric())) { return false; } if(RecordType.SCOPE.equals(type) && !SchemaService.containsFilter(query.getScope())) { return false; } return true; } return false; } @Override public List<MetricSchemaRecord> getUnique(final MetricSchemaRecordQuery query, final RecordType type) { requireNotDisposed(); SystemAssert.requireArgument(query != null, "Metric Schema Record query cannot be null."); SystemAssert.requireArgument(type != null, "Record type cannot be null."); SystemAssert.requireArgument(!query.getScope().startsWith("*") || !query.getMetric().startsWith("*"), "Must specify at least some filtering criteria on either scope or metric name."); if(_canSkipWhileScanning(query, type)) { return _getUniqueFastScan(query, type); } final Set<String> records = new TreeSet<String>(); final ScanMetadata metadata = _constructScanMetadata(query); String namespace = SchemaService.convertToRegex(query.getNamespace()); String scope = SchemaService.convertToRegex(query.getScope()); String metric = SchemaService.convertToRegex(query.getMetric()); String tagKey = SchemaService.convertToRegex(query.getTagKey()); String tagValue = SchemaService.convertToRegex(query.getTagValue()); MetricSchemaRecord scanFrom = query.getScanFrom(); String rowKeyRegex = "^" + _constructRowKey(namespace, scope, metric, tagKey, tagValue, metadata.tableName) + "$"; String scanStartRow = scanFrom == null ? Bytes.toString(metadata.startRow) : _plusOneNConstructRowKey(scanFrom, metadata.tableName, type); _logger.info("Using table: " + metadata.tableName); _logger.info("Rowkey: " + rowKeyRegex); _logger.debug("Scan startRow: " + scanStartRow); _logger.debug("Scan stopRow: " + Bytes.toString(metadata.stopRow)); List<ScanFilter> filters = new ArrayList<ScanFilter>(); filters.add(new RowFilter(CompareOp.EQUAL, new RegexStringComparator(rowKeyRegex))); filters.add(new KeyOnlyFilter()); filters.add(new FirstKeyOnlyFilter()); FilterList filterList = new FilterList(filters, FilterList.Operator.MUST_PASS_ALL); final Scanner scanner = _client.newScanner(metadata.tableName); scanner.setStartKey(scanStartRow); scanner.setStopKey(metadata.stopRow); scanner.setFilter(filterList); scanner.setMaxNumRows(10000); final Deferred<List<MetricSchemaRecord>> results = new Deferred<List<MetricSchemaRecord>>(); List<MetricSchemaRecord> listMetricSchemarecords = new ArrayList<>(); final class ScannerCB implements Callback<Object, ArrayList<ArrayList<KeyValue>>> { /** * Scans rows. * * @return The list of metric schema records. */ public Object scan() { return scanner.nextRows().addCallback(this); } @Override public Object call(ArrayList<ArrayList<KeyValue>> rows) throws Exception { try { if (rows == null) { results.callback(listMetricSchemarecords); scanner.close(); return null; } for (ArrayList<KeyValue> row : rows) { String rowKey = Bytes.toString(row.get(0).key()); MetricSchemaRecord record = _constructMetricSchemaRecord(rowKey, metadata.tableName); if(records.add(_getValueForType(record, type))){ listMetricSchemarecords.add(record); } if (records.size() == query.getLimit()) { results.callback(listMetricSchemarecords); scanner.close(); return null; } } return scan(); } catch (Exception e) { scanner.close(); return null; } } } new ScannerCB().scan(); try { return new ArrayList<>(results.join(SCAN_TIMEOUT_MS)); } catch (InterruptedException e) { throw new SystemException("Interrupted while waiting to obtain results for query: " + query, e); } catch (TimeoutException e) { _logger.warn("Timed out while waiting to obtain results for query: {}. Will return an empty list.", query); return Collections.emptyList(); } catch (Exception e) { throw new SystemException("Exception occurred in getting results for query: " + query, e); } } @Override public List<MetricSchemaRecord> keywordSearch(KeywordQuery query) { throw new UnsupportedOperationException("Keyword search is not supported by AsyncHbaseSchemaService. " + "Please use ElasticSearchSchemaService. "); } @Override public Properties getServiceProperties() { Properties serviceProps = new Properties(); for (Property property : Property.values()) { serviceProps.put(property.getName(), property.getDefaultValue()); } return serviceProps; } @Override public void dispose() { super.dispose(); if (_client != null) { _logger.info("Shutting down asynchbase client."); Deferred<Object> deferred = _client.shutdown(); deferred.addCallback(new Callback<Void, Object>() { @Override public Void call(Object arg) throws Exception { _logger.info("Shutdown of asynchbase client complete."); return null; } }); deferred.addErrback(new Callback<Void, Exception>() { @Override public Void call(Exception arg) throws Exception { _logger.warn("Error occurred while shutting down asynchbase client."); return null; } }); try { deferred.join(TIMEOUT_MS); } catch (Exception e) { throw new SystemException("Exception while waiting for shutdown to complete.", e); } } } private void _putWithoutTag(Metric metric) { String rowKeyScopeTable = _constructRowKey(metric.getNamespace(), metric.getScope(), metric.getMetric(), null, null, SCOPE_SCHEMA_TABLENAME); String rowKeyMetricTable = _constructRowKey(metric.getNamespace(), metric.getScope(), metric.getMetric(), null, null, METRIC_SCHEMA_TABLENAME); _put(SCOPE_SCHEMA_TABLENAME, rowKeyScopeTable); _put(METRIC_SCHEMA_TABLENAME, rowKeyMetricTable); _monitorService.modifyCounter(MonitorService.Counter.SCHEMARECORDS_WRITTEN, 2, null); } private void _putWithTag(Metric metric, Entry<String, String> tag) { String rowKeyScopeTable = _constructRowKey(metric.getNamespace(), metric.getScope(), metric.getMetric(), tag.getKey(), tag.getValue(), SCOPE_SCHEMA_TABLENAME); String rowKeyMetricTable = _constructRowKey(metric.getNamespace(), metric.getScope(), metric.getMetric(), tag.getKey(), tag.getValue(), METRIC_SCHEMA_TABLENAME); _put(SCOPE_SCHEMA_TABLENAME, rowKeyScopeTable); _put(METRIC_SCHEMA_TABLENAME, rowKeyMetricTable); _monitorService.modifyCounter(MonitorService.Counter.SCHEMARECORDS_WRITTEN, 2, null); } private void _put(String tableName, String rowKey) { _logger.debug(MessageFormat.format("Inserting rowkey {0} into table {1}", rowKey, tableName)); final PutRequest put = new PutRequest(Bytes.toBytes(tableName), Bytes.toBytes(rowKey), COLUMN_FAMILY, COLUMN_QUALIFIER, CELL_VALUE); Deferred<Object> deferred = _client.put(put); deferred.addCallback(new Callback<Object, Object>() { @Override public Object call(Object arg) throws Exception { _logger.trace(MessageFormat.format("Put to {0} successfully.", tableName)); return null; } }); deferred.addErrback(new Callback<Object, Exception>() { @Override public Object call(Exception e) throws Exception { throw new SystemException("Error occurred while trying to execute put().", e); } }); if(_syncPut) { try { deferred.join(TIMEOUT_MS); } catch (InterruptedException e) { _logger.warn("Interrupted while waiting for put to finish.", e); } catch (Exception e) { _logger.error("Exception while trying to put schema records.", e); throw new SystemException(e); } } } private String _getValueForType(MetricSchemaRecord record, RecordType type) { switch (type) { case NAMESPACE: return record.getNamespace(); case SCOPE: return record.getScope(); case METRIC: return record.getMetric(); case TAGK: return record.getTagKey(); case TAGV: return record.getTagValue(); default: return null; } } /** * Construct scan metadata depending on the query. This includes determining the table to query and the start and stop rows for the scan. * * <p>For e.g., if scope == "system.chi*" and metric = "app_runtime" then the 2 row keys will be,</p> * * <p>scopeRowKey = system.chi*:app_runtime:tagk:tagv:namespace metricRowKey = app_runtime:system.chi*:tagk:tagv:namespace</p> * * <p>Based on these 2 rowkeys we will select, tableType = METRIC startRow = "app_runtime:system.chi" and stopRow = "app_runtime:system.chj"</p> * * @param query The metric schema query. * * @return A metadata object that contains information about the table to use for querying data, and the start and stop rows for our scan. */ private ScanMetadata _constructScanMetadata(MetricSchemaRecordQuery query) { ScanMetadata metadata = new ScanMetadata(); char[] scopeTableRowKey = _constructRowKey(query.getNamespace(), query.getScope(), query.getMetric(), query.getTagKey(), query.getTagValue(), SCOPE_SCHEMA_TABLENAME).toCharArray(); char[] metricTableRowKey = _constructRowKey(query.getNamespace(), query.getScope(), query.getMetric(), query.getTagKey(), query.getTagValue(), METRIC_SCHEMA_TABLENAME).toCharArray(); // Find first occurrence of any wildcard character in both rowKeys. // Everything until this character will represent our entry point into the table. // We will therefore use the corresponding table where the index of wildcard in the rowKey is higher. int i = 0, j = 0; for (; (i < scopeTableRowKey.length && j < metricTableRowKey.length); i++, j++) { if (SchemaService.isWildcardCharacter(scopeTableRowKey[i]) || SchemaService.isWildcardCharacter(metricTableRowKey[j])) { break; } } while (i < scopeTableRowKey.length && !SchemaService.isWildcardCharacter(scopeTableRowKey[i])) { i++; } while (j < metricTableRowKey.length && !SchemaService.isWildcardCharacter(metricTableRowKey[j])) { j++; } // If the first wildcard character is OR, then we have to backtrack until the last ROW_SEPARATOR occurrence. if (i < scopeTableRowKey.length && scopeTableRowKey[i] == '|') { while (i >= 0 && scopeTableRowKey[i] != ROWKEY_SEPARATOR) { i--; } i++; } if (j < metricTableRowKey.length && metricTableRowKey[j] == '|') { while (j >= 0 && metricTableRowKey[j] != ROWKEY_SEPARATOR) { j--; } j++; } int indexOfWildcard; String rowKey; if (i < j) { metadata.tableName = METRIC_SCHEMA_TABLENAME; indexOfWildcard = j; rowKey = new String(metricTableRowKey); } else { metadata.tableName = SCOPE_SCHEMA_TABLENAME; indexOfWildcard = i; rowKey = new String(scopeTableRowKey); } String start = rowKey.substring(0, indexOfWildcard); metadata.startRow = start.getBytes(Charset.forName("UTF-8")); String end = ""; if (indexOfWildcard > 0) { // Also determine the character before the wildcard and increment it by 1. // This will represent the stopping condition for our scan. char prev = rowKey.charAt(indexOfWildcard - 1); char prevPlusOne = (char) (prev + 1); end = rowKey.substring(0, indexOfWildcard - 1) + prevPlusOne; } metadata.stopRow = end.getBytes(Charset.forName("UTF-8")); return metadata; } /** * The set of implementation specific configuration properties. * * @author Bhinav Sura ([email protected]) */ public enum Property { HBASE_SYNC_PUT("service.property.schema.hbase.sync.put", "false"), HBASE_METRICSCHEMA_TABLE("service.property.schema.hbase.metricschema.table", "metric-schema"), HBASE_SCOPESCHEMA_TABLE("service.property.schema.hbase.scopeschema.table", "scope-schema"); private final String _name; private final String _defaultValue; private Property(String name, String defaultValue) { _name = name; _defaultValue = defaultValue; } /** * Returns the property name. * * @return The property name. */ public String getName() { return _name; } /** * Returns the default value for the property. * * @return The default value. */ public String getDefaultValue() { return _defaultValue; } } //~ Inner Classes ******************************************************************************************************************************** /** * Represents the scan meta data. * * @author Bhinav Sura ([email protected]) */ static class ScanMetadata { /** The start row. */ public byte[] startRow = new byte[0]; /** The end row. */ public byte[] stopRow = new byte[0]; /** The table type. */ public String tableName = SCOPE_SCHEMA_TABLENAME; } } /* Copyright (c) 2016, Salesforce.com, Inc. All rights reserved. */
ArgusCore/src/main/java/com/salesforce/dva/argus/service/schema/AsyncHbaseSchemaService.java
/* * Copyright (c) 2016, Salesforce.com, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Salesforce.com nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.salesforce.dva.argus.service.schema; import com.google.inject.Inject; import com.google.inject.Singleton; import com.salesforce.dva.argus.entity.KeywordQuery; import com.salesforce.dva.argus.entity.Metric; import com.salesforce.dva.argus.entity.MetricSchemaRecord; import com.salesforce.dva.argus.entity.MetricSchemaRecordQuery; import com.salesforce.dva.argus.service.AsyncHBaseClientFactory; import com.salesforce.dva.argus.service.MonitorService; import com.salesforce.dva.argus.service.SchemaService; import com.salesforce.dva.argus.system.SystemAssert; import com.salesforce.dva.argus.system.SystemConfiguration; import com.salesforce.dva.argus.system.SystemException; import com.stumbleupon.async.Callback; import com.stumbleupon.async.Deferred; import com.stumbleupon.async.TimeoutException; import org.apache.hadoop.hbase.util.Bytes; import org.hbase.async.CompareFilter.CompareOp; import org.hbase.async.FilterList; import org.hbase.async.FirstKeyOnlyFilter; import org.hbase.async.HBaseClient; import org.hbase.async.KeyOnlyFilter; import org.hbase.async.KeyValue; import org.hbase.async.PutRequest; import org.hbase.async.RegexStringComparator; import org.hbase.async.RowFilter; import org.hbase.async.ScanFilter; import org.hbase.async.Scanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.Charset; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; /** * Implementation of the schema service using Asynchbase. * * @author Bhinav Sura ([email protected]) */ @Singleton public class AsyncHbaseSchemaService extends AbstractSchemaService { //~ Static fields/initializers ******************************************************************************************************************* private static String METRIC_SCHEMA_TABLENAME; private static String SCOPE_SCHEMA_TABLENAME ; private static final byte[] COLUMN_FAMILY = "f".getBytes(Charset.forName("UTF-8")); private static final byte[] COLUMN_QUALIFIER = "c".getBytes(Charset.forName("UTF-8")); private static final byte[] CELL_VALUE = new byte[1]; private static final char ROWKEY_SEPARATOR = '\u0000'; private static final char PLACEHOLDER_FOR_NULL_STRINGS = '\u0023'; private static final long TIMEOUT_MS = 30 * 1000; private static final long SCAN_TIMEOUT_MS = 2 * 60 * 1000; //~ Instance fields ****************************************************************************************************************************** private Logger _logger = LoggerFactory.getLogger(AsyncHbaseSchemaService.class); private final HBaseClient _client; private final boolean _syncPut; private final MonitorService _monitorService; //~ Constructors ********************************************************************************************************************************* @Inject private AsyncHbaseSchemaService(SystemConfiguration systemConfig, AsyncHBaseClientFactory factory, MonitorService monitorService) { super(systemConfig); _monitorService = monitorService; _syncPut = Boolean.parseBoolean(systemConfig.getValue(Property.HBASE_SYNC_PUT.getName(), Property.HBASE_SYNC_PUT.getDefaultValue())); METRIC_SCHEMA_TABLENAME = systemConfig.getValue(Property.HBASE_METRICSCHEMA_TABLE.getName(), Property.HBASE_METRICSCHEMA_TABLE.getDefaultValue()); SCOPE_SCHEMA_TABLENAME = systemConfig.getValue(Property.HBASE_SCOPESCHEMA_TABLE.getName(), Property.HBASE_SCOPESCHEMA_TABLE.getDefaultValue()); _client = factory.getClient(); } //~ Methods ************************************************************************************************************************************** private static String _constructRowKey(String namespace, String scope, String metric, String tagKey, String tagValue, String tableName) { namespace = namespace == null ? Character.toString(PLACEHOLDER_FOR_NULL_STRINGS) : namespace; tagKey = tagKey == null ? Character.toString(PLACEHOLDER_FOR_NULL_STRINGS) : tagKey; tagValue = tagValue == null ? Character.toString(PLACEHOLDER_FOR_NULL_STRINGS) : tagValue; String key; if (SCOPE_SCHEMA_TABLENAME.equals(tableName)) { key = MessageFormat.format("{0}{5}{1}{5}{2}{5}{3}{5}{4}", scope, metric, tagKey, tagValue, namespace, ROWKEY_SEPARATOR); } else if (METRIC_SCHEMA_TABLENAME.equals(tableName)) { key = MessageFormat.format("{0}{5}{1}{5}{2}{5}{3}{5}{4}", metric, scope, tagKey, tagValue, namespace, ROWKEY_SEPARATOR); } else { throw new SystemException(new IllegalArgumentException("Unknown table: " + tableName)); } return key; } private static String _constructRowKey(MetricSchemaRecord schema, String tableName){ return _constructRowKey(schema.getNamespace(), schema.getScope(), schema.getMetric(), schema.getTagKey(), schema.getTagValue(), tableName); } private static MetricSchemaRecord _constructMetricSchemaRecord(String rowKey, String tableName) { SystemAssert.requireArgument(rowKey != null && !rowKey.isEmpty(), "This should never happen. Rowkey should never be null or empty."); String[] parts = rowKey.split(String.valueOf(ROWKEY_SEPARATOR)); MetricSchemaRecord record; if (SCOPE_SCHEMA_TABLENAME.equals(tableName)) { record = new MetricSchemaRecord(parts[0], parts[1]); } else if (METRIC_SCHEMA_TABLENAME.equals(tableName)) { record = new MetricSchemaRecord(parts[1], parts[0]); } else { throw new SystemException(new IllegalArgumentException("Unknown table: " + tableName)); } String placeholder = Character.toString(PLACEHOLDER_FOR_NULL_STRINGS); if (!placeholder.equals(parts[2])) { record.setTagKey(parts[2]); } if (!placeholder.equals(parts[3])) { record.setTagValue(parts[3]); } if (!placeholder.equals(parts[4])) { record.setNamespace(parts[4]); } return record; } private String _plusOneNConstructRowKey(MetricSchemaRecord record, String tableName, RecordType type){ if(type==null){ return _plusOne(_constructRowKey(record, tableName)); }else{ switch (type) { case NAMESPACE: record.setNamespace(_plusOne(record.getNamespace())); break; case SCOPE: record.setScope(_plusOne(record.getScope())); break; case METRIC: record.setMetric(_plusOne(record.getMetric())); break; case TAGK: record.setTagKey(_plusOne(record.getTagKey())); break; case TAGV: record.setTagValue(_plusOne(record.getTagValue())); } } return _constructRowKey(record, tableName); } //~ Methods ************************************************************************************************************************************** @Override protected void implementationSpecificPut(List<Metric> metrics) { requireNotDisposed(); SystemAssert.requireArgument(metrics != null, "Metric list cannot be null."); for (Metric metric : metrics) { if (metric.getTags().isEmpty()) { _putWithoutTag(metric); } for (Entry<String, String> tag : metric.getTags().entrySet()) { _putWithTag(metric, tag); } } } @Override public List<MetricSchemaRecord> get(final MetricSchemaRecordQuery query) { requireNotDisposed(); SystemAssert.requireArgument(query != null, "Metric Schema Record query cannot be null."); final List<MetricSchemaRecord> records = new ArrayList<MetricSchemaRecord>(query.getLimit()); final ScanMetadata metadata = _constructScanMetadata(query); String namespace = SchemaService.convertToRegex(query.getNamespace()); String scope = SchemaService.convertToRegex(query.getScope()); String metric = SchemaService.convertToRegex(query.getMetric()); String tagKey = SchemaService.convertToRegex(query.getTagKey()); String tagValue = SchemaService.convertToRegex(query.getTagValue()); MetricSchemaRecord scanFrom = query.getScanFrom(); String rowKeyRegex = "^" + _constructRowKey(namespace, scope, metric, tagKey, tagValue, metadata.tableName) + "$"; String scanStartRow = scanFrom == null ? Bytes.toString(metadata.startRow) : _plusOneNConstructRowKey(scanFrom, metadata.tableName, null); _logger.info("Using table: " + metadata.tableName); _logger.info("Rowkey: " + rowKeyRegex); _logger.debug("Scan startRow: " + scanStartRow); _logger.debug("Scan stopRow: " + metadata.stopRow.toString()); List<ScanFilter> filters = new ArrayList<ScanFilter>(); filters.add(new RowFilter(CompareOp.EQUAL, new RegexStringComparator(rowKeyRegex))); filters.add(new KeyOnlyFilter()); filters.add(new FirstKeyOnlyFilter()); FilterList fl = new FilterList(filters, FilterList.Operator.MUST_PASS_ALL); final Scanner scanner = _client.newScanner(metadata.tableName); scanner.setStartKey(scanStartRow.getBytes()); scanner.setStopKey(metadata.stopRow); scanner.setFilter(fl); scanner.setMaxNumRows(Math.min(query.getLimit(), 10000)); final Deferred<List<MetricSchemaRecord>> results = new Deferred<List<MetricSchemaRecord>>(); /** * Scans HBASE rows. * * @author Bhinav Sura ([email protected]) */ final class ScannerCB implements Callback<Object, ArrayList<ArrayList<KeyValue>>> { /** * Scans rows. * * @return The list of metric schema records. */ public Object scan() { _logger.trace("Getting next set of rows."); return scanner.nextRows().addCallback(this); } @Override public Object call(ArrayList<ArrayList<KeyValue>> rows) throws Exception { _logger.trace("Inside nextRows() callback.."); try { if (rows == null) { results.callback(records); scanner.close(); return null; } _logger.debug("Retrieved " + rows.size() + " rows."); for(ArrayList<KeyValue> row:rows){ byte[] rowKey=row.get(0).key(); MetricSchemaRecord record = _constructMetricSchemaRecord(Bytes.toString(rowKey), metadata.tableName); records.add(record); if (records.size() == query.getLimit()) { results.callback(records); scanner.close(); return null; } } return scan(); } catch (Exception e) { scanner.close(); return null; } } } new ScannerCB().scan(); try { return results.join(SCAN_TIMEOUT_MS); } catch (InterruptedException e) { throw new SystemException("Interrupted while waiting to obtain results for query: " + query, e); } catch (TimeoutException e) { _logger.warn("Timed out while waiting to obtain results for query: {}. Will return an empty list.", query); return Collections.emptyList(); } catch (Exception e) { throw new SystemException("Exception occurred in getting results for query: " + query, e); } } /** * Fast scan works when trying to discover either scopes or metrics with all other fields being *. * In this case, when the first result is obtained, we skip all other rows starting with that prefix and directly move * on to the next possible value which is obtained value incremented by 1 Ascii character. If that value exists, then * it is returned, otherwise HBase returns the next possible value in lexicographical order. * * For e.g. suppose if we have the following rows in HBase: * * scope\0metric1\0$\0$\0$ * scope\0metric2\0$\0$\0$ * . * . * . * scope\0metric1000\0$\0$\0$ * scopu\0metric1\0$\0$\0$ * scopu\0metric2\0$\0$\0$ * . * . * . * scopu\0metric1000\0$\0$\0$ * * And our start row is "sco", then this method would first find "scope" and then jump the next 1000 rows * to start from the next possible value of scopf. Since nothing like scopf exists, HBase would directly * jump to scopu and return that. * */ private List<MetricSchemaRecord> _getUniqueFastScan(MetricSchemaRecordQuery query, final RecordType type) { requireNotDisposed(); SystemAssert.requireArgument(RecordType.METRIC.equals(type) || RecordType.SCOPE.equals(type), "This method is only for use with metric or scope."); _logger.info("Using FastScan. Will skip rows while scanning."); final Set<MetricSchemaRecord> records = new HashSet<>(); final ScanMetadata metadata = _constructScanMetadata(query); String namespace = SchemaService.convertToRegex(query.getNamespace()); String scope = SchemaService.convertToRegex(query.getScope()); String metric = SchemaService.convertToRegex(query.getMetric()); String tagKey = SchemaService.convertToRegex(query.getTagKey()); String tagValue = SchemaService.convertToRegex(query.getTagValue()); MetricSchemaRecord scanFrom = query.getScanFrom(); String rowKeyRegex = "^" + _constructRowKey(namespace, scope, metric, tagKey, tagValue, metadata.tableName) + "$"; List<ScanFilter> filters = new ArrayList<ScanFilter>(); filters.add(new RowFilter(CompareOp.EQUAL, new RegexStringComparator(rowKeyRegex))); filters.add(new KeyOnlyFilter()); filters.add(new FirstKeyOnlyFilter()); FilterList filterList = new FilterList(filters, FilterList.Operator.MUST_PASS_ALL); String start = scanFrom == null ? Bytes.toString(metadata.startRow) : _plusOneNConstructRowKey(scanFrom, metadata.tableName, type); String end = Bytes.toString(metadata.stopRow); ArrayList<ArrayList<KeyValue>> rows = _getSingleRow(start, end, filterList, metadata.tableName); while(rows != null && !rows.isEmpty()) { String rowKey = Bytes.toString(rows.get(0).get(0).key()); String splits[] = rowKey.split(String.valueOf(ROWKEY_SEPARATOR)); String record = (RecordType.METRIC.equals(type) && metadata.tableName.equals(METRIC_SCHEMA_TABLENAME)) || (RecordType.SCOPE.equals(type) && metadata.tableName.equals(SCOPE_SCHEMA_TABLENAME)) ? splits[0] : splits[1]; MetricSchemaRecord schemaRecord = RecordType.METRIC.equals(type) ? new MetricSchemaRecord(null, record) : new MetricSchemaRecord(record, null); //MetricSchemaRecord schemaRecord = _constructMetricSchemaRecord(rowKey, metadata.tableName); records.add(schemaRecord); if(records.size() == query.getLimit()) { break; } String newScanStart; if(!SchemaService.containsFilter(query.getScope()) || !SchemaService.containsFilter(query.getMetric())) { newScanStart = _plusOne(record); } else { newScanStart = _plusOne(splits[0] + ROWKEY_SEPARATOR + splits[1]); } rows = _getSingleRow(newScanStart, end, filterList, metadata.tableName); } return new ArrayList<>(records); } private ArrayList<ArrayList<KeyValue>> _getSingleRow(final String start, final String end, final FilterList filterList, final String tableName) { final Scanner scanner = _client.newScanner(tableName); scanner.setStartKey(start); scanner.setStopKey(end); scanner.setMaxNumRows(1); scanner.setFilter(filterList); _logger.debug("Using table: " + tableName); _logger.debug("Scan startRow: " + start); _logger.debug("Scan stopRow: " + end); Deferred<ArrayList<ArrayList<KeyValue>>> deferred = scanner.nextRows(); deferred.addCallback(new Callback<ArrayList<ArrayList<KeyValue>>, ArrayList<ArrayList<KeyValue>>>() { @Override public ArrayList<ArrayList<KeyValue>> call(ArrayList<ArrayList<KeyValue>> rows) throws Exception { scanner.close(); return rows; } }); try { ArrayList<ArrayList<KeyValue>> result = deferred.join(SCAN_TIMEOUT_MS); return result; } catch (InterruptedException e) { throw new SystemException("Interrupted while waiting to obtain results for query", e); } catch (TimeoutException e) { _logger.warn("Timed out while waiting to obtain results."); } catch (Exception e) { throw new SystemException("Exception occurred in getting results for query", e); } return null; } //TSDB allowed characteers are: [A-Za-z0-9./-_]. The lowest ASCII value (45) out of these is for hyphen (-). private String _plusOne(String prefix) { char newChar = 45; return prefix + newChar; } /** * Check if we can perform a faster scan. We can only perform a faster scan when we are trying to discover scopes or metrics * without having information on any other fields. */ private boolean _canSkipWhileScanning(MetricSchemaRecordQuery query, RecordType type) { if( (RecordType.METRIC.equals(type) || RecordType.SCOPE.equals(type)) && !SchemaService.containsFilter(query.getTagKey()) && !SchemaService.containsFilter(query.getTagValue()) && !SchemaService.containsFilter(query.getNamespace())) { if(RecordType.METRIC.equals(type) && !SchemaService.containsFilter(query.getMetric())) { return false; } if(RecordType.SCOPE.equals(type) && !SchemaService.containsFilter(query.getScope())) { return false; } return true; } return false; } @Override public List<MetricSchemaRecord> getUnique(final MetricSchemaRecordQuery query, final RecordType type) { requireNotDisposed(); SystemAssert.requireArgument(query != null, "Metric Schema Record query cannot be null."); SystemAssert.requireArgument(type != null, "Record type cannot be null."); SystemAssert.requireArgument(!query.getScope().startsWith("*") || !query.getMetric().startsWith("*"), "Must specify at least some filtering criteria on either scope or metric name."); if(_canSkipWhileScanning(query, type)) { return _getUniqueFastScan(query, type); } final Set<String> records = new TreeSet<String>(); final ScanMetadata metadata = _constructScanMetadata(query); String namespace = SchemaService.convertToRegex(query.getNamespace()); String scope = SchemaService.convertToRegex(query.getScope()); String metric = SchemaService.convertToRegex(query.getMetric()); String tagKey = SchemaService.convertToRegex(query.getTagKey()); String tagValue = SchemaService.convertToRegex(query.getTagValue()); MetricSchemaRecord scanFrom = query.getScanFrom(); String rowKeyRegex = "^" + _constructRowKey(namespace, scope, metric, tagKey, tagValue, metadata.tableName) + "$"; String scanStartRow = scanFrom == null ? Bytes.toString(metadata.startRow) : _plusOneNConstructRowKey(scanFrom, metadata.tableName, type); _logger.info("Using table: " + metadata.tableName); _logger.info("Rowkey: " + rowKeyRegex); _logger.debug("Scan startRow: " + scanStartRow); _logger.debug("Scan stopRow: " + Bytes.toString(metadata.stopRow)); List<ScanFilter> filters = new ArrayList<ScanFilter>(); filters.add(new RowFilter(CompareOp.EQUAL, new RegexStringComparator(rowKeyRegex))); filters.add(new KeyOnlyFilter()); filters.add(new FirstKeyOnlyFilter()); FilterList filterList = new FilterList(filters, FilterList.Operator.MUST_PASS_ALL); final Scanner scanner = _client.newScanner(metadata.tableName); scanner.setStartKey(scanStartRow); scanner.setStopKey(metadata.stopRow); scanner.setFilter(filterList); scanner.setMaxNumRows(10000); final Deferred<List<MetricSchemaRecord>> results = new Deferred<List<MetricSchemaRecord>>(); List<MetricSchemaRecord> listMetricSchemarecords = new ArrayList<>(); final class ScannerCB implements Callback<Object, ArrayList<ArrayList<KeyValue>>> { /** * Scans rows. * * @return The list of metric schema records. */ public Object scan() { return scanner.nextRows().addCallback(this); } @Override public Object call(ArrayList<ArrayList<KeyValue>> rows) throws Exception { try { if (rows == null) { results.callback(listMetricSchemarecords); scanner.close(); return null; } for (ArrayList<KeyValue> row : rows) { String rowKey = Bytes.toString(row.get(0).key()); MetricSchemaRecord record = _constructMetricSchemaRecord(rowKey, metadata.tableName); if(records.add(_getValueForType(record, type))){ listMetricSchemarecords.add(record); } if (records.size() == query.getLimit()) { results.callback(listMetricSchemarecords); scanner.close(); return null; } } return scan(); } catch (Exception e) { scanner.close(); return null; } } } new ScannerCB().scan(); try { return new ArrayList<>(results.join(SCAN_TIMEOUT_MS)); } catch (InterruptedException e) { throw new SystemException("Interrupted while waiting to obtain results for query: " + query, e); } catch (TimeoutException e) { _logger.warn("Timed out while waiting to obtain results for query: {}. Will return an empty list.", query); return Collections.emptyList(); } catch (Exception e) { throw new SystemException("Exception occurred in getting results for query: " + query, e); } } @Override public List<MetricSchemaRecord> keywordSearch(KeywordQuery query) { throw new UnsupportedOperationException("Keyword search is not supported by AsyncHbaseSchemaService. " + "Please use ElasticSearchSchemaService. "); } @Override public Properties getServiceProperties() { Properties serviceProps = new Properties(); for (Property property : Property.values()) { serviceProps.put(property.getName(), property.getDefaultValue()); } return serviceProps; } @Override public void dispose() { super.dispose(); if (_client != null) { _logger.info("Shutting down asynchbase client."); Deferred<Object> deferred = _client.shutdown(); deferred.addCallback(new Callback<Void, Object>() { @Override public Void call(Object arg) throws Exception { _logger.info("Shutdown of asynchbase client complete."); return null; } }); deferred.addErrback(new Callback<Void, Exception>() { @Override public Void call(Exception arg) throws Exception { _logger.warn("Error occurred while shutting down asynchbase client."); return null; } }); try { deferred.join(TIMEOUT_MS); } catch (Exception e) { throw new SystemException("Exception while waiting for shutdown to complete.", e); } } } private void _putWithoutTag(Metric metric) { String rowKeyScopeTable = _constructRowKey(metric.getNamespace(), metric.getScope(), metric.getMetric(), null, null, SCOPE_SCHEMA_TABLENAME); String rowKeyMetricTable = _constructRowKey(metric.getNamespace(), metric.getScope(), metric.getMetric(), null, null, METRIC_SCHEMA_TABLENAME); _put(SCOPE_SCHEMA_TABLENAME, rowKeyScopeTable); _put(METRIC_SCHEMA_TABLENAME, rowKeyMetricTable); _monitorService.modifyCounter(MonitorService.Counter.SCHEMARECORDS_WRITTEN, 2, null); } private void _putWithTag(Metric metric, Entry<String, String> tag) { String rowKeyScopeTable = _constructRowKey(metric.getNamespace(), metric.getScope(), metric.getMetric(), tag.getKey(), tag.getValue(), SCOPE_SCHEMA_TABLENAME); String rowKeyMetricTable = _constructRowKey(metric.getNamespace(), metric.getScope(), metric.getMetric(), tag.getKey(), tag.getValue(), METRIC_SCHEMA_TABLENAME); _put(SCOPE_SCHEMA_TABLENAME, rowKeyScopeTable); _put(METRIC_SCHEMA_TABLENAME, rowKeyMetricTable); _monitorService.modifyCounter(MonitorService.Counter.SCHEMARECORDS_WRITTEN, 2, null); } private void _put(String tableName, String rowKey) { _logger.debug(MessageFormat.format("Inserting rowkey {0} into table {1}", rowKey, tableName)); final PutRequest put = new PutRequest(Bytes.toBytes(tableName), Bytes.toBytes(rowKey), COLUMN_FAMILY, COLUMN_QUALIFIER, CELL_VALUE); Deferred<Object> deferred = _client.put(put); deferred.addCallback(new Callback<Object, Object>() { @Override public Object call(Object arg) throws Exception { _logger.trace(MessageFormat.format("Put to {0} successfully.", tableName)); return null; } }); deferred.addErrback(new Callback<Object, Exception>() { @Override public Object call(Exception e) throws Exception { throw new SystemException("Error occurred while trying to execute put().", e); } }); if(_syncPut) { try { deferred.join(TIMEOUT_MS); } catch (InterruptedException e) { _logger.warn("Interrupted while waiting for put to finish.", e); } catch (Exception e) { _logger.error("Exception while trying to put schema records.", e); throw new SystemException(e); } } } private String _getValueForType(MetricSchemaRecord record, RecordType type) { switch (type) { case NAMESPACE: return record.getNamespace(); case SCOPE: return record.getScope(); case METRIC: return record.getMetric(); case TAGK: return record.getTagKey(); case TAGV: return record.getTagValue(); default: return null; } } /** * Construct scan metadata depending on the query. This includes determining the table to query and the start and stop rows for the scan. * * <p>For e.g., if scope == "system.chi*" and metric = "app_runtime" then the 2 row keys will be,</p> * * <p>scopeRowKey = system.chi*:app_runtime:tagk:tagv:namespace metricRowKey = app_runtime:system.chi*:tagk:tagv:namespace</p> * * <p>Based on these 2 rowkeys we will select, tableType = METRIC startRow = "app_runtime:system.chi" and stopRow = "app_runtime:system.chj"</p> * * @param query The metric schema query. * * @return A metadata object that contains information about the table to use for querying data, and the start and stop rows for our scan. */ private ScanMetadata _constructScanMetadata(MetricSchemaRecordQuery query) { ScanMetadata metadata = new ScanMetadata(); char[] scopeTableRowKey = _constructRowKey(query.getNamespace(), query.getScope(), query.getMetric(), query.getTagKey(), query.getTagValue(), SCOPE_SCHEMA_TABLENAME).toCharArray(); char[] metricTableRowKey = _constructRowKey(query.getNamespace(), query.getScope(), query.getMetric(), query.getTagKey(), query.getTagValue(), METRIC_SCHEMA_TABLENAME).toCharArray(); // Find first occurrence of any wildcard character in both rowKeys. // Everything until this character will represent our entry point into the table. // We will therefore use the corresponding table where the index of wildcard in the rowKey is higher. int i = 0, j = 0; for (; (i < scopeTableRowKey.length && j < metricTableRowKey.length); i++, j++) { if (SchemaService.isWildcardCharacter(scopeTableRowKey[i]) || SchemaService.isWildcardCharacter(metricTableRowKey[j])) { break; } } while (i < scopeTableRowKey.length && !SchemaService.isWildcardCharacter(scopeTableRowKey[i])) { i++; } while (j < metricTableRowKey.length && !SchemaService.isWildcardCharacter(metricTableRowKey[j])) { j++; } // If the first wildcard character is OR, then we have to backtrack until the last ROW_SEPARATOR occurrence. if (i < scopeTableRowKey.length && scopeTableRowKey[i] == '|') { while (i >= 0 && scopeTableRowKey[i] != ROWKEY_SEPARATOR) { i--; } i++; } if (j < metricTableRowKey.length && metricTableRowKey[j] == '|') { while (j >= 0 && metricTableRowKey[j] != ROWKEY_SEPARATOR) { j--; } j++; } int indexOfWildcard; String rowKey; if (i < j) { metadata.tableName = METRIC_SCHEMA_TABLENAME; indexOfWildcard = j; rowKey = new String(metricTableRowKey); } else { metadata.tableName = SCOPE_SCHEMA_TABLENAME; indexOfWildcard = i; rowKey = new String(scopeTableRowKey); } String start = rowKey.substring(0, indexOfWildcard); metadata.startRow = start.getBytes(Charset.forName("UTF-8")); String end = ""; if (indexOfWildcard > 0) { // Also determine the character before the wildcard and increment it by 1. // This will represent the stopping condition for our scan. char prev = rowKey.charAt(indexOfWildcard - 1); char prevPlusOne = (char) (prev + 1); end = rowKey.substring(0, indexOfWildcard - 1) + prevPlusOne; } metadata.stopRow = end.getBytes(Charset.forName("UTF-8")); return metadata; } /** * The set of implementation specific configuration properties. * * @author Bhinav Sura ([email protected]) */ public enum Property { HBASE_SYNC_PUT("service.property.schema.hbase.sync.put", "false"), HBASE_METRICSCHEMA_TABLE("service.property.schema.hbase.metricschema.table", "metric-schema"), HBASE_SCOPESCHEMA_TABLE("service.property.schema.hbase.scopeschema.table", "scope-schema"); private final String _name; private final String _defaultValue; private Property(String name, String defaultValue) { _name = name; _defaultValue = defaultValue; } /** * Returns the property name. * * @return The property name. */ public String getName() { return _name; } /** * Returns the default value for the property. * * @return The default value. */ public String getDefaultValue() { return _defaultValue; } } //~ Inner Classes ******************************************************************************************************************************** /** * Represents the scan meta data. * * @author Bhinav Sura ([email protected]) */ static class ScanMetadata { /** The start row. */ public byte[] startRow = new byte[0]; /** The end row. */ public byte[] stopRow = new byte[0]; /** The table type. */ public String tableName = SCOPE_SCHEMA_TABLENAME; } } /* Copyright (c) 2016, Salesforce.com, Inc. All rights reserved. */
Update AsyncHbaseSchemaService.java
ArgusCore/src/main/java/com/salesforce/dva/argus/service/schema/AsyncHbaseSchemaService.java
Update AsyncHbaseSchemaService.java
<ide><path>rgusCore/src/main/java/com/salesforce/dva/argus/service/schema/AsyncHbaseSchemaService.java <ide> <ide> MetricSchemaRecord schemaRecord = RecordType.METRIC.equals(type) ? <ide> new MetricSchemaRecord(null, record) : new MetricSchemaRecord(record, null); <del> //MetricSchemaRecord schemaRecord = _constructMetricSchemaRecord(rowKey, metadata.tableName); <ide> records.add(schemaRecord); <ide> if(records.size() == query.getLimit()) { <ide> break;
Java
mit
68732ed35ea52502b2989df8ae8822d13eed89ee
0
kaffeel/PhilHackerNews,kkkkxu/PhilHackerNews,GeorgeMe/PhilHackerNews,Ternence/PhilHackerNews,kmdupr33/PhilHackerNews
package com.philosophicalhacker.philhackernews; import android.app.Application; import android.content.Context; import android.os.Bundle; import android.support.test.runner.AndroidJUnitRunner; import android.util.Log; /** * Created by MattDupree on 7/16/15. */ public class DaggerModuleOverridingAndroidJUnitRunner extends AndroidJUnitRunner { @Override public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException { String canonicalName = TestApplication.class.getCanonicalName(); Log.d("class name", canonicalName); return super.newApplication(cl, canonicalName, context); } }
app/src/androidTest/java/com/philosophicalhacker/philhackernews/DaggerModuleOverridingAndroidJUnitRunner.java
package com.philosophicalhacker.philhackernews; import android.app.Application; import android.content.Context; import android.os.Bundle; import android.support.test.runner.AndroidJUnitRunner; import android.util.Log; /** * Created by MattDupree on 7/16/15. */ public class DaggerModuleOverridingAndroidJUnitRunner extends AndroidJUnitRunner { @Override public void onCreate(Bundle arguments) { super.onCreate(arguments); } @Override public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException { String canonicalName = TestApplication.class.getCanonicalName(); Log.d("class name", canonicalName); return super.newApplication(cl, canonicalName, context); } }
removed unnecessary oncreate method
app/src/androidTest/java/com/philosophicalhacker/philhackernews/DaggerModuleOverridingAndroidJUnitRunner.java
removed unnecessary oncreate method
<ide><path>pp/src/androidTest/java/com/philosophicalhacker/philhackernews/DaggerModuleOverridingAndroidJUnitRunner.java <ide> public class DaggerModuleOverridingAndroidJUnitRunner extends AndroidJUnitRunner { <ide> <ide> @Override <del> public void onCreate(Bundle arguments) { <del> super.onCreate(arguments); <del> } <del> <del> @Override <ide> public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException { <ide> String canonicalName = TestApplication.class.getCanonicalName(); <ide> Log.d("class name", canonicalName);
Java
mit
145ba9416b14caea2475d8ff5d31676e8f32eb73
0
lemmy/tlaplus,tlaplus/tlaplus,lemmy/tlaplus,tlaplus/tlaplus,tlaplus/tlaplus,lemmy/tlaplus,lemmy/tlaplus,tlaplus/tlaplus
package org.lamport.tla.toolbox; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.ui.application.IWorkbenchConfigurer; import org.eclipse.ui.application.IWorkbenchWindowConfigurer; import org.eclipse.ui.application.WorkbenchAdvisor; import org.eclipse.ui.application.WorkbenchWindowAdvisor; import org.lamport.tla.toolbox.tool.ToolboxHandle; import org.lamport.tla.toolbox.util.UIHelper; /** * This workbench advisor creates the window advisor, and specifies * the perspective id for the initial window. * @author Simon Zambrovski * @version $Id$ */ public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor { public static final String PERSPECTIVE_ID = "org.lamport.tla.toolbox.ui.perspective.initial"; public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) { return new ApplicationWorkbenchWindowAdvisor(configurer); } public String getInitialWindowPerspectiveId() { return PERSPECTIVE_ID; } public IAdaptable getDefaultPageInput() { IWorkspace workspace = ResourcesPlugin.getWorkspace(); return workspace.getRoot(); } /* * @see org.eclipse.ui.application.WorkbenchAdvisor#initialize(org.eclipse.ui.application.IWorkbenchConfigurer) */ public void initialize(IWorkbenchConfigurer configurer) { super.initialize(configurer); // save the positions of windows etc... configurer.setSaveAndRestore(true); /* // REMOVE: only required for the navigator, will be removed WorkbenchAdapterBuilder.registerAdapters(); final String ICONS_PATH = "icons/full/"; final String PATH_OBJECT = ICONS_PATH + "obj16/"; Bundle ideBundle = Platform.getBundle(IDEWorkbenchPlugin.IDE_WORKBENCH); declareWorkbenchImage(configurer, ideBundle, IDE.SharedImages.IMG_OBJ_PROJECT, PATH_OBJECT + "prj_obj.gif", true); declareWorkbenchImage(configurer, ideBundle, IDE.SharedImages.IMG_OBJ_PROJECT_CLOSED, PATH_OBJECT + "cprj_obj.gif", true); */ } /* private void declareWorkbenchImage(IWorkbenchConfigurer configurer_p, Bundle ideBundle, String symbolicName, String path, boolean shared) { URL url = ideBundle.getEntry(path); ImageDescriptor desc = ImageDescriptor.createFromURL(url); configurer_p.declareImage(symbolicName, desc, shared); } */ public boolean preShutdown() { if (! ToolboxHandle.getInstanceStore().getBoolean(ToolboxHandle.I_RESTORE_LAST_SPEC)) { UIHelper.getActivePage().closeAllEditors(true); UIHelper.switchPerspective(getInitialWindowPerspectiveId()); } return super.preShutdown(); } }
org.lamport.tla.toolbox.product.standalone/src/org/lamport/tla/toolbox/ApplicationWorkbenchAdvisor.java
package org.lamport.tla.toolbox; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.ui.application.IWorkbenchConfigurer; import org.eclipse.ui.application.IWorkbenchWindowConfigurer; import org.eclipse.ui.application.WorkbenchAdvisor; import org.eclipse.ui.application.WorkbenchWindowAdvisor; import org.lamport.tla.toolbox.util.UIHelper; import org.lamport.tla.toolbox.util.pref.IPreferenceConstants; import org.lamport.tla.toolbox.util.pref.PreferenceStoreHelper; /** * This workbench advisor creates the window advisor, and specifies * the perspective id for the initial window. * @author Simon Zambrovski * @version $Id$ */ public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor { public static final String PERSPECTIVE_ID = "org.lamport.tla.toolbox.ui.perspective.initial"; public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) { return new ApplicationWorkbenchWindowAdvisor(configurer); } public String getInitialWindowPerspectiveId() { return PERSPECTIVE_ID; } public IAdaptable getDefaultPageInput() { IWorkspace workspace = ResourcesPlugin.getWorkspace(); return workspace.getRoot(); } /* * @see org.eclipse.ui.application.WorkbenchAdvisor#initialize(org.eclipse.ui.application.IWorkbenchConfigurer) */ public void initialize(IWorkbenchConfigurer configurer) { super.initialize(configurer); // save the positions of windows etc... configurer.setSaveAndRestore(true); /* // REMOVE: only required for the navigator, will be removed WorkbenchAdapterBuilder.registerAdapters(); final String ICONS_PATH = "icons/full/"; final String PATH_OBJECT = ICONS_PATH + "obj16/"; Bundle ideBundle = Platform.getBundle(IDEWorkbenchPlugin.IDE_WORKBENCH); declareWorkbenchImage(configurer, ideBundle, IDE.SharedImages.IMG_OBJ_PROJECT, PATH_OBJECT + "prj_obj.gif", true); declareWorkbenchImage(configurer, ideBundle, IDE.SharedImages.IMG_OBJ_PROJECT_CLOSED, PATH_OBJECT + "cprj_obj.gif", true); */ } /* private void declareWorkbenchImage(IWorkbenchConfigurer configurer_p, Bundle ideBundle, String symbolicName, String path, boolean shared) { URL url = ideBundle.getEntry(path); ImageDescriptor desc = ImageDescriptor.createFromURL(url); configurer_p.declareImage(symbolicName, desc, shared); } */ public boolean preShutdown() { if (!PreferenceStoreHelper.getInstancePreferenceStore().getBoolean( IPreferenceConstants.I_RESTORE_LAST_SPEC)) { UIHelper.getActivePage().closeAllEditors(true); UIHelper.switchPerspective(getInitialWindowPerspectiveId()); } return super.preShutdown(); } }
git-svn-id: svn+ssh://svn.msr-inria.inria.fr/var/lib/svn/repository/tla/trunk/tla2-inria@12829 76a6fc44-f60b-0410-a9a8-e67b0e8fc65c
org.lamport.tla.toolbox.product.standalone/src/org/lamport/tla/toolbox/ApplicationWorkbenchAdvisor.java
<ide><path>rg.lamport.tla.toolbox.product.standalone/src/org/lamport/tla/toolbox/ApplicationWorkbenchAdvisor.java <ide> import org.eclipse.ui.application.IWorkbenchWindowConfigurer; <ide> import org.eclipse.ui.application.WorkbenchAdvisor; <ide> import org.eclipse.ui.application.WorkbenchWindowAdvisor; <add>import org.lamport.tla.toolbox.tool.ToolboxHandle; <ide> import org.lamport.tla.toolbox.util.UIHelper; <del>import org.lamport.tla.toolbox.util.pref.IPreferenceConstants; <del>import org.lamport.tla.toolbox.util.pref.PreferenceStoreHelper; <ide> <ide> /** <ide> * This workbench advisor creates the window advisor, and specifies <ide> <ide> public boolean preShutdown() <ide> { <del> if (!PreferenceStoreHelper.getInstancePreferenceStore().getBoolean( <del> IPreferenceConstants.I_RESTORE_LAST_SPEC)) <add> if (! ToolboxHandle.getInstanceStore().getBoolean(ToolboxHandle.I_RESTORE_LAST_SPEC)) <ide> { <ide> UIHelper.getActivePage().closeAllEditors(true); <ide> UIHelper.switchPerspective(getInitialWindowPerspectiveId());
JavaScript
isc
aef4e2981d4527fe986db0a68ea74d7a30b58aa4
0
d3/d3-transition
var tape = require("tape"), jsdom = require("jsdom"), d3 = require("../build/d3"); tape.Test.prototype.inDelta = function(actual, expected) { this._assert(expected - 1e-6 < actual && actual < expected + 1e-6, { message: "should be in delta", operator: "inDelta", actual: actual, expected: expected }); }; tape('d3.ease("linear") returns the expected results', function(test) { var ease = d3.ease("linear"); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.1); test.inDelta(ease(0.2), 0.2); test.inDelta(ease(0.3), 0.3); test.inDelta(ease(0.4), 0.4); test.inDelta(ease(0.5), 0.5); test.inDelta(ease(0.6), 0.6); test.inDelta(ease(0.7), 0.7); test.inDelta(ease(0.8), 0.8); test.inDelta(ease(0.9), 0.9); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("linear-in") is an alias for d3.ease("linear")', function(test) { test.equal(d3.ease("linear-in"), d3.ease("linear")); test.end(); }); tape('d3.ease("linear-out") is an alias for d3.ease("linear")', function(test) { test.equal(d3.ease("linear-out"), d3.ease("linear")); test.end(); }); tape('d3.ease("linear-in-out") is an alias for d3.ease("linear")', function(test) { test.equal(d3.ease("linear-in-out"), d3.ease("linear")); test.end(); }); tape('d3.ease("linear-out-in") is an alias for d3.ease("linear")', function(test) { test.equal(d3.ease("linear-out-in"), d3.ease("linear")); test.end(); }); tape('d3.ease("quad") returns the expected results', function(test) { var ease = d3.ease("quad"); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.01); test.inDelta(ease(0.2), 0.04); test.inDelta(ease(0.3), 0.09); test.inDelta(ease(0.4), 0.16); test.inDelta(ease(0.5), 0.25); test.inDelta(ease(0.6), 0.36); test.inDelta(ease(0.7), 0.49); test.inDelta(ease(0.8), 0.64); test.inDelta(ease(0.9), 0.81); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("quad-in") is an alias for d3.ease("quad")', function(test) { test.equal(d3.ease("quad-in"), d3.ease("quad")); test.end(); }); tape('d3.ease("quad-out") returns the expected results', function(test) { var ease = d3.ease("quad-out"); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.19); test.inDelta(ease(0.2), 0.36); test.inDelta(ease(0.3), 0.51); test.inDelta(ease(0.4), 0.64); test.inDelta(ease(0.5), 0.75); test.inDelta(ease(0.6), 0.84); test.inDelta(ease(0.7), 0.91); test.inDelta(ease(0.8), 0.96); test.inDelta(ease(0.9), 0.99); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("quad-in-out") returns the expected results', function(test) { var ease = d3.ease("quad-in-out"); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.02); test.inDelta(ease(0.2), 0.08); test.inDelta(ease(0.3), 0.18); test.inDelta(ease(0.4), 0.32); test.inDelta(ease(0.5), 0.50); test.inDelta(ease(0.6), 0.68); test.inDelta(ease(0.7), 0.82); test.inDelta(ease(0.8), 0.92); test.inDelta(ease(0.9), 0.98); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("quad-out-in") returns the expected results', function(test) { var ease = d3.ease("quad-out-in"); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.18); test.inDelta(ease(0.2), 0.32); test.inDelta(ease(0.3), 0.42); test.inDelta(ease(0.4), 0.48); test.inDelta(ease(0.5), 0.50); test.inDelta(ease(0.6), 0.52); test.inDelta(ease(0.7), 0.58); test.inDelta(ease(0.8), 0.68); test.inDelta(ease(0.9), 0.82); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("cubic") returns the expected results', function(test) { var ease = d3.ease("cubic"); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.001); test.inDelta(ease(0.2), 0.008); test.inDelta(ease(0.3), 0.027); test.inDelta(ease(0.4), 0.064); test.inDelta(ease(0.5), 0.125); test.inDelta(ease(0.6), 0.216); test.inDelta(ease(0.7), 0.343); test.inDelta(ease(0.8), 0.512); test.inDelta(ease(0.9), 0.729); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("cubic-in") is an alias for d3.ease("cubic")', function(test) { test.equal(d3.ease("cubic-in"), d3.ease("cubic")); test.end(); }); tape('d3.ease("cubic-out") returns the expected results', function(test) { var ease = d3.ease("cubic-out"); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.271); test.inDelta(ease(0.2), 0.488); test.inDelta(ease(0.3), 0.657); test.inDelta(ease(0.4), 0.784); test.inDelta(ease(0.5), 0.875); test.inDelta(ease(0.6), 0.936); test.inDelta(ease(0.7), 0.973); test.inDelta(ease(0.8), 0.992); test.inDelta(ease(0.9), 0.999); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("cubic-in-out") returns the expected results', function(test) { var ease = d3.ease("cubic-in-out"); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.004); test.inDelta(ease(0.2), 0.032); test.inDelta(ease(0.3), 0.108); test.inDelta(ease(0.4), 0.256); test.inDelta(ease(0.5), 0.500); test.inDelta(ease(0.6), 0.744); test.inDelta(ease(0.7), 0.892); test.inDelta(ease(0.8), 0.968); test.inDelta(ease(0.9), 0.996); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("cubic-out-in") returns the expected results', function(test) { var ease = d3.ease("cubic-out-in"); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.244); test.inDelta(ease(0.2), 0.392); test.inDelta(ease(0.3), 0.468); test.inDelta(ease(0.4), 0.496); test.inDelta(ease(0.5), 0.500); test.inDelta(ease(0.6), 0.504); test.inDelta(ease(0.7), 0.532); test.inDelta(ease(0.8), 0.608); test.inDelta(ease(0.9), 0.756); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("poly") is an alias for d3.ease("cubic")', function(test) { test.equal(d3.ease("poly"), d3.ease("cubic")); test.end(); }); tape('d3.ease("poly-in") is an alias for d3.ease("cubic")', function(test) { test.equal(d3.ease("poly-in"), d3.ease("cubic")); test.end(); }); tape('d3.ease("poly-out") is an alias for d3.ease("cubic-out")', function(test) { test.equal(d3.ease("poly-out"), d3.ease("cubic-out")); test.end(); }); tape('d3.ease("poly-in-out") is an alias for d3.ease("cubic-in-out")', function(test) { test.equal(d3.ease("poly-in-out"), d3.ease("cubic-in-out")); test.end(); }); tape('d3.ease("poly-out-in") is an alias for d3.ease("cubic-out-in")', function(test) { test.equal(d3.ease("poly-out-in"), d3.ease("cubic-out-in")); test.end(); }); tape('d3.ease("poly", 2.5) returns the expected results', function(test) { var ease = d3.ease("poly", 2.5); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.003162); test.inDelta(ease(0.2), 0.017889); test.inDelta(ease(0.3), 0.049295); test.inDelta(ease(0.4), 0.101193); test.inDelta(ease(0.5), 0.176777); test.inDelta(ease(0.6), 0.278855); test.inDelta(ease(0.7), 0.409963); test.inDelta(ease(0.8), 0.572433); test.inDelta(ease(0.9), 0.768433); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("poly-in", 2.5) returns the expected results', function(test) { var ease = d3.ease("poly-in", 2.5); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.003162); test.inDelta(ease(0.2), 0.017889); test.inDelta(ease(0.3), 0.049295); test.inDelta(ease(0.4), 0.101193); test.inDelta(ease(0.5), 0.176777); test.inDelta(ease(0.6), 0.278855); test.inDelta(ease(0.7), 0.409963); test.inDelta(ease(0.8), 0.572433); test.inDelta(ease(0.9), 0.768433); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("poly-out", 2.5) returns the expected results', function(test) { var ease = d3.ease("poly-out", 2.5); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.231567); test.inDelta(ease(0.2), 0.427567); test.inDelta(ease(0.3), 0.590037); test.inDelta(ease(0.4), 0.721145); test.inDelta(ease(0.5), 0.823223); test.inDelta(ease(0.6), 0.898807); test.inDelta(ease(0.7), 0.950705); test.inDelta(ease(0.8), 0.982111); test.inDelta(ease(0.9), 0.996838); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("poly-in-out", 2.5) returns the expected results', function(test) { var ease = d3.ease("poly-in-out", 2.5); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.008944); test.inDelta(ease(0.2), 0.050596); test.inDelta(ease(0.3), 0.139427); test.inDelta(ease(0.4), 0.286217); test.inDelta(ease(0.5), 0.500000); test.inDelta(ease(0.6), 0.713783); test.inDelta(ease(0.7), 0.860573); test.inDelta(ease(0.8), 0.949404); test.inDelta(ease(0.9), 0.991056); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("poly-out-in", 2.5) returns the expected results', function(test) { var ease = d3.ease("poly-out-in", 2.5); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.213783); test.inDelta(ease(0.2), 0.360573); test.inDelta(ease(0.3), 0.449404); test.inDelta(ease(0.4), 0.491056); test.inDelta(ease(0.5), 0.500000); test.inDelta(ease(0.6), 0.508944); test.inDelta(ease(0.7), 0.550596); test.inDelta(ease(0.8), 0.639427); test.inDelta(ease(0.9), 0.786217); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); });
test/ease-test.js
var tape = require("tape"), jsdom = require("jsdom"), d3 = require("../build/d3"); tape.Test.prototype.inDelta = function(actual, expected) { this._assert(expected - 1e-6 < actual && actual < expected + 1e-6, { message: "should be in delta", operator: "inDelta", actual: actual, expected: expected }); }; tape('d3.ease("linear") returns the expected results', function(test) { var ease = d3.ease("linear"); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.1); test.inDelta(ease(0.2), 0.2); test.inDelta(ease(0.3), 0.3); test.inDelta(ease(0.4), 0.4); test.inDelta(ease(0.5), 0.5); test.inDelta(ease(0.6), 0.6); test.inDelta(ease(0.7), 0.7); test.inDelta(ease(0.8), 0.8); test.inDelta(ease(0.9), 0.9); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("linear-in") is an alias for d3.ease("linear")', function(test) { test.equal(d3.ease("linear-in"), d3.ease("linear")); test.end(); }); tape('d3.ease("linear-out") is an alias for d3.ease("linear")', function(test) { test.equal(d3.ease("linear-out"), d3.ease("linear")); test.end(); }); tape('d3.ease("linear-in-out") is an alias for d3.ease("linear")', function(test) { test.equal(d3.ease("linear-in-out"), d3.ease("linear")); test.end(); }); tape('d3.ease("linear-out-in") is an alias for d3.ease("linear")', function(test) { test.equal(d3.ease("linear-out-in"), d3.ease("linear")); test.end(); }); tape('d3.ease("quad") returns the expected results', function(test) { var ease = d3.ease("quad"); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.01); test.inDelta(ease(0.2), 0.04); test.inDelta(ease(0.3), 0.09); test.inDelta(ease(0.4), 0.16); test.inDelta(ease(0.5), 0.25); test.inDelta(ease(0.6), 0.36); test.inDelta(ease(0.7), 0.49); test.inDelta(ease(0.8), 0.64); test.inDelta(ease(0.9), 0.81); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("quad-in") is an alias for d3.ease("quad")', function(test) { test.equal(d3.ease("quad-in"), d3.ease("quad")); test.end(); }); tape('d3.ease("quad-out") returns the expected results', function(test) { var ease = d3.ease("quad-out"); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.19); test.inDelta(ease(0.2), 0.36); test.inDelta(ease(0.3), 0.51); test.inDelta(ease(0.4), 0.64); test.inDelta(ease(0.5), 0.75); test.inDelta(ease(0.6), 0.84); test.inDelta(ease(0.7), 0.91); test.inDelta(ease(0.8), 0.96); test.inDelta(ease(0.9), 0.99); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("quad-in-out") returns the expected results', function(test) { var ease = d3.ease("quad-in-out"); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.02); test.inDelta(ease(0.2), 0.08); test.inDelta(ease(0.3), 0.18); test.inDelta(ease(0.4), 0.32); test.inDelta(ease(0.5), 0.50); test.inDelta(ease(0.6), 0.68); test.inDelta(ease(0.7), 0.82); test.inDelta(ease(0.8), 0.92); test.inDelta(ease(0.9), 0.98); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("quad-out-in") returns the expected results', function(test) { var ease = d3.ease("quad-out-in"); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.18); test.inDelta(ease(0.2), 0.32); test.inDelta(ease(0.3), 0.42); test.inDelta(ease(0.4), 0.48); test.inDelta(ease(0.5), 0.50); test.inDelta(ease(0.6), 0.52); test.inDelta(ease(0.7), 0.58); test.inDelta(ease(0.8), 0.68); test.inDelta(ease(0.9), 0.82); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("cubic") returns the expected results', function(test) { var ease = d3.ease("cubic"); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.001); test.inDelta(ease(0.2), 0.008); test.inDelta(ease(0.3), 0.027); test.inDelta(ease(0.4), 0.064); test.inDelta(ease(0.5), 0.125); test.inDelta(ease(0.6), 0.216); test.inDelta(ease(0.7), 0.343); test.inDelta(ease(0.8), 0.512); test.inDelta(ease(0.9), 0.729); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("cubic-in") is an alias for d3.ease("cubic")', function(test) { test.equal(d3.ease("cubic-in"), d3.ease("cubic")); test.end(); }); tape('d3.ease("cubic-out") returns the expected results', function(test) { var ease = d3.ease("cubic-out"); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.271); test.inDelta(ease(0.2), 0.488); test.inDelta(ease(0.3), 0.657); test.inDelta(ease(0.4), 0.784); test.inDelta(ease(0.5), 0.875); test.inDelta(ease(0.6), 0.936); test.inDelta(ease(0.7), 0.973); test.inDelta(ease(0.8), 0.992); test.inDelta(ease(0.9), 0.999); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("cubic-in-out") returns the expected results', function(test) { var ease = d3.ease("cubic-in-out"); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.004); test.inDelta(ease(0.2), 0.032); test.inDelta(ease(0.3), 0.108); test.inDelta(ease(0.4), 0.256); test.inDelta(ease(0.5), 0.500); test.inDelta(ease(0.6), 0.744); test.inDelta(ease(0.7), 0.892); test.inDelta(ease(0.8), 0.968); test.inDelta(ease(0.9), 0.996); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); }); tape('d3.ease("cubic-out-in") returns the expected results', function(test) { var ease = d3.ease("cubic-out-in"); test.equal(ease(-0.01), 0); test.equal(ease(0), 0); test.inDelta(ease(0.1), 0.244); test.inDelta(ease(0.2), 0.392); test.inDelta(ease(0.3), 0.468); test.inDelta(ease(0.4), 0.496); test.inDelta(ease(0.5), 0.500); test.inDelta(ease(0.6), 0.504); test.inDelta(ease(0.7), 0.532); test.inDelta(ease(0.8), 0.608); test.inDelta(ease(0.9), 0.756); test.equal(ease(".9"), ease(0.9)); // test numeric coercion test.equal(ease(1), 1); test.equal(ease(1.01), 1); test.end(); });
Tests for ease("poly").
test/ease-test.js
Tests for ease("poly").
<ide><path>est/ease-test.js <ide> test.equal(ease(1.01), 1); <ide> test.end(); <ide> }); <add> <add>tape('d3.ease("poly") is an alias for d3.ease("cubic")', function(test) { <add> test.equal(d3.ease("poly"), d3.ease("cubic")); <add> test.end(); <add>}); <add> <add>tape('d3.ease("poly-in") is an alias for d3.ease("cubic")', function(test) { <add> test.equal(d3.ease("poly-in"), d3.ease("cubic")); <add> test.end(); <add>}); <add> <add>tape('d3.ease("poly-out") is an alias for d3.ease("cubic-out")', function(test) { <add> test.equal(d3.ease("poly-out"), d3.ease("cubic-out")); <add> test.end(); <add>}); <add> <add>tape('d3.ease("poly-in-out") is an alias for d3.ease("cubic-in-out")', function(test) { <add> test.equal(d3.ease("poly-in-out"), d3.ease("cubic-in-out")); <add> test.end(); <add>}); <add> <add>tape('d3.ease("poly-out-in") is an alias for d3.ease("cubic-out-in")', function(test) { <add> test.equal(d3.ease("poly-out-in"), d3.ease("cubic-out-in")); <add> test.end(); <add>}); <add> <add>tape('d3.ease("poly", 2.5) returns the expected results', function(test) { <add> var ease = d3.ease("poly", 2.5); <add> test.equal(ease(-0.01), 0); <add> test.equal(ease(0), 0); <add> test.inDelta(ease(0.1), 0.003162); <add> test.inDelta(ease(0.2), 0.017889); <add> test.inDelta(ease(0.3), 0.049295); <add> test.inDelta(ease(0.4), 0.101193); <add> test.inDelta(ease(0.5), 0.176777); <add> test.inDelta(ease(0.6), 0.278855); <add> test.inDelta(ease(0.7), 0.409963); <add> test.inDelta(ease(0.8), 0.572433); <add> test.inDelta(ease(0.9), 0.768433); <add> test.equal(ease(".9"), ease(0.9)); // test numeric coercion <add> test.equal(ease(1), 1); <add> test.equal(ease(1.01), 1); <add> test.end(); <add>}); <add> <add>tape('d3.ease("poly-in", 2.5) returns the expected results', function(test) { <add> var ease = d3.ease("poly-in", 2.5); <add> test.equal(ease(-0.01), 0); <add> test.equal(ease(0), 0); <add> test.inDelta(ease(0.1), 0.003162); <add> test.inDelta(ease(0.2), 0.017889); <add> test.inDelta(ease(0.3), 0.049295); <add> test.inDelta(ease(0.4), 0.101193); <add> test.inDelta(ease(0.5), 0.176777); <add> test.inDelta(ease(0.6), 0.278855); <add> test.inDelta(ease(0.7), 0.409963); <add> test.inDelta(ease(0.8), 0.572433); <add> test.inDelta(ease(0.9), 0.768433); <add> test.equal(ease(".9"), ease(0.9)); // test numeric coercion <add> test.equal(ease(1), 1); <add> test.equal(ease(1.01), 1); <add> test.end(); <add>}); <add> <add>tape('d3.ease("poly-out", 2.5) returns the expected results', function(test) { <add> var ease = d3.ease("poly-out", 2.5); <add> test.equal(ease(-0.01), 0); <add> test.equal(ease(0), 0); <add> test.inDelta(ease(0.1), 0.231567); <add> test.inDelta(ease(0.2), 0.427567); <add> test.inDelta(ease(0.3), 0.590037); <add> test.inDelta(ease(0.4), 0.721145); <add> test.inDelta(ease(0.5), 0.823223); <add> test.inDelta(ease(0.6), 0.898807); <add> test.inDelta(ease(0.7), 0.950705); <add> test.inDelta(ease(0.8), 0.982111); <add> test.inDelta(ease(0.9), 0.996838); <add> test.equal(ease(".9"), ease(0.9)); // test numeric coercion <add> test.equal(ease(1), 1); <add> test.equal(ease(1.01), 1); <add> test.end(); <add>}); <add> <add>tape('d3.ease("poly-in-out", 2.5) returns the expected results', function(test) { <add> var ease = d3.ease("poly-in-out", 2.5); <add> test.equal(ease(-0.01), 0); <add> test.equal(ease(0), 0); <add> test.inDelta(ease(0.1), 0.008944); <add> test.inDelta(ease(0.2), 0.050596); <add> test.inDelta(ease(0.3), 0.139427); <add> test.inDelta(ease(0.4), 0.286217); <add> test.inDelta(ease(0.5), 0.500000); <add> test.inDelta(ease(0.6), 0.713783); <add> test.inDelta(ease(0.7), 0.860573); <add> test.inDelta(ease(0.8), 0.949404); <add> test.inDelta(ease(0.9), 0.991056); <add> test.equal(ease(".9"), ease(0.9)); // test numeric coercion <add> test.equal(ease(1), 1); <add> test.equal(ease(1.01), 1); <add> test.end(); <add>}); <add> <add>tape('d3.ease("poly-out-in", 2.5) returns the expected results', function(test) { <add> var ease = d3.ease("poly-out-in", 2.5); <add> test.equal(ease(-0.01), 0); <add> test.equal(ease(0), 0); <add> test.inDelta(ease(0.1), 0.213783); <add> test.inDelta(ease(0.2), 0.360573); <add> test.inDelta(ease(0.3), 0.449404); <add> test.inDelta(ease(0.4), 0.491056); <add> test.inDelta(ease(0.5), 0.500000); <add> test.inDelta(ease(0.6), 0.508944); <add> test.inDelta(ease(0.7), 0.550596); <add> test.inDelta(ease(0.8), 0.639427); <add> test.inDelta(ease(0.9), 0.786217); <add> test.equal(ease(".9"), ease(0.9)); // test numeric coercion <add> test.equal(ease(1), 1); <add> test.equal(ease(1.01), 1); <add> test.end(); <add>});