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
JavaScript
mit
1ed1be7deacf3e40905b623c611433b17e1f8dd8
0
warmuuh/yaap
/** @license MIT License (c) copyright 2013 original author or authors */ /** * @Autowired annotation processor. * * Autowires parameters of function calls based on a given or the parameter name. * * needs wire to be in the configuration object. * * * Licensed under the MIT License at: * http://www.opensource.org/licenses/mit-license.php * * @author Peter Mucha * * @version 0.0.4 */ "use strict"; (function(define) { define([ "when", "underscore"], function(when, _) { function registerExpressCallback(path, fnExpress, obj, fnDescription, context){ path = path || '/' + fnDescription.name; //in case of no-argument annotation, use fnName as endpoint //prepend basename if (obj["@Path"] != null) //null or undefind path = obj["@Path"] + path; console.log("Registering route: " + path); var authFn = null; try{authFn = getAuthentification(fnDescription)} catch(e){console.log(e)} fnExpress(path, authFn, function(req, res, next){ var responseSent = false; var sendResponse = function(result){ responseSent = true; processResponse(result, res, fnDescription, context); }; var args = processParameters(req, fnDescription, sendResponse); //execution var result = obj[fnDescription.name].apply(obj, args); //dynamic call because there could be other annotations //if it is undefined, then there *should* be a callback ;) if (result !== undefined && !responseSent) sendResponse(result); }); } function getAuthentification(fnDescription){ var useAuth = (getAnnotation(fnDescription, "@Auth") !== undefined); var authFn = function(req, res, next){next()}; if (useAuth) authFn = function(req, res, next) { if (req.isAuthenticated === undefined){ console.error("connect-auth is missing"); next(); } if (!req.isAuthenticated()) { req.authenticate(function(err, succ){ if (err) console.log(err); next(); }); return; } else{ next(); } }; return authFn; } function processParameters(req, fnDescription, responseCallback){ var args = []; var processEveryParameter = (getAnnotation(fnDescription, "@Param") !== undefined); for(var i = 0; i < fnDescription.parameters.length; ++i){ var param = fnDescription.parameters[i]; //handle @Param var annoParam = getAnnotation(param, "@Param"); if ((processEveryParameter && param.annotations.length == 0) //NO other annotations allowed because it would be overwritten || (annoParam !== undefined)) { var parameterName = param.name; if (annoParam !== undefined && annoParam.parameters.length > 0) parameterName = annoParam.parameters[0]; args[param.index] = getParameter(req, parameterName); } //handle @Body if ( getAnnotation(param, "@Body") !== undefined) args[param.index] = req.body; if ( getAnnotation(param, "@Req") !== undefined) args[param.index] = req; if ( getAnnotation(param, "@Res") !== undefined) args[param.index] = req; if ( getAnnotation(param, "@Session") !== undefined) args[param.index] = req.session; //handle @Callback if (getAnnotation(param, "@Callback") !== undefined) { args[param.index] = responseCallback; } } return args; } function getParameter(req, name){ if (req.params && req.params[name]) return req.params[name]; if (req.query && req.query[name]) return req.query[name]; if (req.body && req.body[name]) return req.body[name]; } function processResponse(result, res, fnDescription, context){ //raw? if (getAnnotation(fnDescription, "@Body") !== undefined){ res.send(result); } else if (getAnnotation(fnDescription, "@JSON") !== undefined){ res.json(result); } else { //forwarding to view if (typeof result === 'string') if (result.lastIndexOf("redirect:", 0) === 0) //starts with 'redirect:'? res.redirect(result.split(":")[1]); else res.render(result + '.' + context.express_view); else if (result && result.view){ res.render(result.view + '.' + context.express_view, result.model); } } } function getAnnotation(fnDescription, annotationName){ return _(fnDescription.annotations).chain().findWhere({name: annotationName}).value(); } return [ { annotation: "@GET", processFunction: function(obj, fnDescription, annotationParams, context){ registerExpressCallback(annotationParams[0], context.express.get.bind(context.express), obj, fnDescription, context); } }, { annotation: "@PUT", processFunction: function(obj, fnDescription, annotationParams, context){ registerExpressCallback(annotationParams[0], context.express.put.bind(context.express), obj, fnDescription, context); } }, { annotation: "@POST", processFunction: function(obj, fnDescription, annotationParams, context){ registerExpressCallback(annotationParams[0], context.express.post.bind(context.express), obj, fnDescription, context); } }, { annotation: "@DELETE", processFunction: function(obj, fnDescription, annotationParams, context){ registerExpressCallback(annotationParams[0], context.express["delete"].bind(context.express), obj, fnDescription, context); } } ]; });})(typeof define == 'function'? define: function(deps, factory) {module.exports = factory.apply(this, deps.map(function(x) {return require(x);}));});
yaap/wire/express/plugins/VerbProcessors.js
/** @license MIT License (c) copyright 2013 original author or authors */ /** * @Autowired annotation processor. * * Autowires parameters of function calls based on a given or the parameter name. * * needs wire to be in the configuration object. * * * Licensed under the MIT License at: * http://www.opensource.org/licenses/mit-license.php * * @author Peter Mucha * * @version 0.0.4 */ "use strict"; (function(define) { define([ "when", "underscore"], function(when, _) { function registerExpressCallback(path, fnExpress, obj, fnDescription, context){ path = path || '/' + fnDescription.name; //in case of no-argument annotation, use fnName as endpoint //prepend basename if (obj["@Path"] != null) //null or undefind path = obj["@Path"] + path; console.log("Registering route: " + path); var authFn = null; try{authFn = getAuthentification(fnDescription)} catch(e){console.log(e)} fnExpress(path, authFn, function(req, res, next){ var responseSent = false; var sendResponse = function(result){ responseSent = true; processResponse(result, res, fnDescription, context); }; var args = processParameters(req, fnDescription, sendResponse); //execution var result = obj[fnDescription.name].apply(obj, args); //dynamic call because there could be other annotations //if it is undefined, then there *should* be a callback ;) if (result !== undefined && !responseSent) sendResponse(result); }); } function getAuthentification(fnDescription){ var useAuth = (getAnnotation(fnDescription, "@Auth") !== undefined); var authFn = function(req, res, next){next()}; if (useAuth) authFn = function(req, res, next) { if (req.isAuthenticated === undefined){ console.error("connect-auth is missing"); next(); } if (!req.isAuthenticated()) { req.authenticate(function(err, succ){ if (err) console.log(err); next(); }); return; } else{ next(); } }; return authFn; } function processParameters(req, fnDescription, responseCallback){ var args = []; var processEveryParameter = (getAnnotation(fnDescription, "@Param") !== undefined); for(var i = 0; i < fnDescription.parameters.length; ++i){ var param = fnDescription.parameters[i]; //handle @Param var annoParam = getAnnotation(param, "@Param"); if ((processEveryParameter && param.annotations.length == 0) //NO other annotations allowed because it would be overwritten || (annoParam !== undefined)) { var parameterName = param.name; if (annoParam !== undefined && annoParam.parameters.length > 0) parameterName = annoParam.parameters[0]; args[param.index] = getParameter(req, parameterName); } //handle @Body if ( getAnnotation(param, "@Body") !== undefined) { args[param.index] = req.body; } //handle @Body if ( getAnnotation(param, "@Session") !== undefined) { args[param.index] = req.session; } //handle @Callback if (getAnnotation(param, "@Callback") !== undefined) { args[param.index] = responseCallback; } } return args; } function getParameter(req, name){ if (req.params && req.params[name]) return req.params[name]; if (req.query && req.query[name]) return req.query[name]; if (req.body && req.body[name]) return req.body[name]; } function processResponse(result, res, fnDescription, context){ //raw? if (getAnnotation(fnDescription, "@Body") !== undefined){ res.send(result); } else if (getAnnotation(fnDescription, "@JSON") !== undefined){ res.json(result); } else { //forwarding to view if (typeof result === 'string') if (result.lastIndexOf("redirect:", 0) === 0) //starts with 'redirect:'? res.redirect(result.split(":")[1]); else res.render(result + '.' + context.express_view); else if (result && result.view){ res.render(result.view + '.' + context.express_view, result.model); } } } function getAnnotation(fnDescription, annotationName){ return _(fnDescription.annotations).chain().findWhere({name: annotationName}).value(); } return [ { annotation: "@GET", processFunction: function(obj, fnDescription, annotationParams, context){ registerExpressCallback(annotationParams[0], context.express.get.bind(context.express), obj, fnDescription, context); } }, { annotation: "@PUT", processFunction: function(obj, fnDescription, annotationParams, context){ registerExpressCallback(annotationParams[0], context.express.put.bind(context.express), obj, fnDescription, context); } }, { annotation: "@POST", processFunction: function(obj, fnDescription, annotationParams, context){ registerExpressCallback(annotationParams[0], context.express.post.bind(context.express), obj, fnDescription, context); } }, { annotation: "@DELETE", processFunction: function(obj, fnDescription, annotationParams, context){ registerExpressCallback(annotationParams[0], context.express["delete"].bind(context.express), obj, fnDescription, context); } } ]; });})(typeof define == 'function'? define: function(deps, factory) {module.exports = factory.apply(this, deps.map(function(x) {return require(x);}));});
wire/express req res parameter injection
yaap/wire/express/plugins/VerbProcessors.js
wire/express req res parameter injection
<ide><path>aap/wire/express/plugins/VerbProcessors.js <ide> <ide> <ide> function registerExpressCallback(path, fnExpress, obj, fnDescription, context){ <add> <ide> path = path || '/' + fnDescription.name; //in case of no-argument annotation, use fnName as endpoint <ide> <ide> //prepend basename <ide> <ide> //handle @Body <ide> if ( getAnnotation(param, "@Body") !== undefined) <del> { <ide> args[param.index] = req.body; <del> } <ide> <del> //handle @Body <add> if ( getAnnotation(param, "@Req") !== undefined) <add> args[param.index] = req; <add> <add> if ( getAnnotation(param, "@Res") !== undefined) <add> args[param.index] = req; <add> <ide> if ( getAnnotation(param, "@Session") !== undefined) <del> { <ide> args[param.index] = req.session; <del> } <ide> <ide> //handle @Callback <ide> if (getAnnotation(param, "@Callback") !== undefined) <ide> { <ide> annotation: "@GET", <ide> processFunction: function(obj, fnDescription, annotationParams, context){ <add> <ide> registerExpressCallback(annotationParams[0], context.express.get.bind(context.express), obj, fnDescription, context); <ide> } <ide> },
Java
apache-2.0
28e6ea721ac08eba498949cf2be2c06e146664cc
0
GabrielBrascher/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,wido/cloudstack,wido/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,wido/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack
// 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.cloudstack.api.command.admin.user; import javax.inject.Inject; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.region.RegionService; import org.apache.log4j.Logger; import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.user.UserAccount; @APICommand(name = "updateUser", description = "Updates a user account", responseObject = UserResponse.class, requestHasSensitiveInfo = true, responseHasSensitiveInfo = true) public class UpdateUserCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateUserCmd.class.getName()); private static final String s_name = "updateuserresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.USER_API_KEY, type = CommandType.STRING, description = "The API key for the user. Must be specified with userSecretKey") private String apiKey; @Parameter(name = ApiConstants.EMAIL, type = CommandType.STRING, description = "email") private String email; @Parameter(name = ApiConstants.FIRSTNAME, type = CommandType.STRING, description = "first name") private String firstname; @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = UserResponse.class, required = true, description = "User uuid") private Long id; @Parameter(name = ApiConstants.LASTNAME, type = CommandType.STRING, description = "last name") private String lastname; @Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, description = "Clear text password (default hashed to SHA256SALT). If you wish to use any other hashing algorithm, you would need to write a custom authentication adapter. Can't be passed when command is executed via integration.api.port", acceptedOnAdminPort = false) private String password; @Parameter(name = ApiConstants.SECRET_KEY, type = CommandType.STRING, description = "The secret key for the user. Must be specified with userApiKey") private String secretKey; @Parameter(name = ApiConstants.TIMEZONE, type = CommandType.STRING, description = "Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format.") private String timezone; @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, description = "Unique username") private String username; @Inject RegionService _regionService; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public String getApiKey() { return apiKey; } public String getEmail() { return email; } public String getFirstname() { return firstname; } public Long getId() { return id; } public String getLastname() { return lastname; } public String getPassword() { return password; } public String getSecretKey() { return secretKey; } public String getTimezone() { return timezone; } public String getUsername() { return username; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { User user = _entityMgr.findById(User.class, getId()); if (user != null) { return user.getAccountId(); } return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } @Override public void execute() { CallContext.current().setEventDetails("UserId: " + getId()); UserAccount user = _regionService.updateUser(this); if (user != null) { UserResponse response = _responseGenerator.createUserResponse(user); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update user"); } } }
api/src/main/java/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.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.cloudstack.api.command.admin.user; import javax.inject.Inject; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.region.RegionService; import org.apache.log4j.Logger; import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.user.UserAccount; @APICommand(name = "updateUser", description = "Updates a user account", responseObject = UserResponse.class, requestHasSensitiveInfo = true, responseHasSensitiveInfo = true) public class UpdateUserCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateUserCmd.class.getName()); private static final String s_name = "updateuserresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.USER_API_KEY, type = CommandType.STRING, description = "The API key for the user. Must be specified with userSecretKey") private String apiKey; @Parameter(name = ApiConstants.EMAIL, type = CommandType.STRING, description = "email") private String email; @Parameter(name = ApiConstants.FIRSTNAME, type = CommandType.STRING, description = "first name") private String firstname; @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = UserResponse.class, required = true, description = "User uuid") private Long id; @Parameter(name = ApiConstants.LASTNAME, type = CommandType.STRING, description = "last name") private String lastname; @Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, description = "Clear text password (default hashed to SHA256SALT). If you wish to use any other hasing algorithm, you would need to write a custom authentication adapter. Can't be passed when command is executed via integration.api.port", acceptedOnAdminPort = false) private String password; @Parameter(name = ApiConstants.SECRET_KEY, type = CommandType.STRING, description = "The secret key for the user. Must be specified with userSecretKey") private String secretKey; @Parameter(name = ApiConstants.TIMEZONE, type = CommandType.STRING, description = "Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format.") private String timezone; @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, description = "Unique username") private String username; @Inject RegionService _regionService; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public String getApiKey() { return apiKey; } public String getEmail() { return email; } public String getFirstname() { return firstname; } public Long getId() { return id; } public String getLastname() { return lastname; } public String getPassword() { return password; } public String getSecretKey() { return secretKey; } public String getTimezone() { return timezone; } public String getUsername() { return username; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { User user = _entityMgr.findById(User.class, getId()); if (user != null) { return user.getAccountId(); } return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } @Override public void execute() { CallContext.current().setEventDetails("UserId: " + getId()); UserAccount user = _regionService.updateUser(this); if (user != null) { UserResponse response = _responseGenerator.createUserResponse(user); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update user"); } } }
UpdateUserCmd: apiSecretKey refers to itself (#2597) * UpdateUserCmd: apiSecretKey refers to itself * typo: hasing -> hashing
api/src/main/java/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java
UpdateUserCmd: apiSecretKey refers to itself (#2597)
<ide><path>pi/src/main/java/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java <ide> <ide> @Parameter(name = ApiConstants.PASSWORD, <ide> type = CommandType.STRING, <del> description = "Clear text password (default hashed to SHA256SALT). If you wish to use any other hasing algorithm, you would need to write a custom authentication adapter. Can't be passed when command is executed via integration.api.port", <add> description = "Clear text password (default hashed to SHA256SALT). If you wish to use any other hashing algorithm, you would need to write a custom authentication adapter. Can't be passed when command is executed via integration.api.port", <ide> acceptedOnAdminPort = false) <ide> private String password; <ide> <ide> <del> @Parameter(name = ApiConstants.SECRET_KEY, type = CommandType.STRING, description = "The secret key for the user. Must be specified with userSecretKey") <add> @Parameter(name = ApiConstants.SECRET_KEY, type = CommandType.STRING, description = "The secret key for the user. Must be specified with userApiKey") <ide> private String secretKey; <ide> <ide> @Parameter(name = ApiConstants.TIMEZONE,
JavaScript
mit
9e2bfc82a927c45f6f7f988bac85812b15250382
0
BeamNG/ui,BeamNG/ui
$.widget( "beamNG.app", $.ui.dialog, { options: { app: null, persistance: undefined, active: true, editMode: false, refPointOffset : [0, 0], referencePoint : [0, 0] // [0,0] = upper left, [1,1] = lower right }, _create : function(){ this.app = this.options.app; this.appName = this.app.name = this.app.constructor.name; this.appInfo = AppEngine.appSettings[this.appName]; // Persistance if(this.options.persistance === undefined){ this.options.persistance = { options : {}, custom : {} }; } this.app.options = this.options.persistance.options; this.app.persistance = this.options.persistance.custom; // Configuration this.options.title = this.appInfo.info.name; // Resize if(this.appInfo.appearance.resize === false){ this.options.resizable = false; } // inner size modifier var sizeOffset = 10 * ( this.appInfo.appearance.opaque === true); // Sizes if(this.appInfo.appearance.size.initial !== undefined){ this.options.width = this.appInfo.appearance.size.initial[0] + sizeOffset; this.options.height = this.appInfo.appearance.size.initial[1] + sizeOffset; } // minimal size if(this.appInfo.appearance.size.minimal !== undefined){ this.options.minWidth = this.appInfo.appearance.size.minimal[0] + sizeOffset; this.options.minHeight = this.appInfo.appearance.size.minimal[1] + sizeOffset; } // minsize must be <= size this.options.minWidth = Math.min(this.options.minWidth, this.options.width); if(this.options.height != "auto"){ this.log("setting minsize"); this.options.minHeight = Math.min(this.options.minHeight, this.options.height); this.log(this.options.minHeight); } // maximal size if(this.appInfo.appearance.size.maximal !== undefined){ this.options.maxWidth = this.appInfo.appearance.size.maximal[0] + sizeOffset; this.options.maxHeight = this.appInfo.appearance.size.maximal[1] + sizeOffset; } // maximal size must be >= size if(this.options.maxWidth){ this.options.maxWidth = Math.max(this.options.maxWidth, this.options.width); } if(this.options.maxHeight){ this.options.maxHeight = Math.max(this.options.maxHeight, this.options.height); } // add helpervariables this.app._widget = $(this.element); this.app.path = "apps/"+this.appName+"/"; this._super(); }, _init:function(){ // Initialize Widget this._super("_init"); // Background var backgroundClasses = ["opaque","opaque-simple","transparent"]; if(backgroundClasses.indexOf(this.appInfo.appearance.background)!= -1){ this.element.addClass(this.appInfo.appearance.background); }else{ this.log("Error parsing app.json attribute appearance.backround: invalid value"); } // adding properties this.element.addClass("app"); this.app.rootElement = $("<div></div>").css({ width: '100%', height: '100%', 'min-width': '10px', 'min-height': '10px' }).appendTo($(this.element)); this.app.rootElement.addClass(this.appName); // adding savemethod this.app.save = function(){ AppEngine.savePreset(); }; // adding logmethod var appname = this.appName; this.app.log = function(message){ Logger.log("App", message, appname); }; // Initialize App try{ this.app.initialize(); }catch(e){ this.log("An Error occured while trying to call "+this.app.name+".initialize() : "+e.toString()+". Killing App."); var self = this; setTimeout(function(){self.close();},0); } // installing handlers this._on(this.element.parent(), { resize:"resize", dragstart:"dragStart", drag:"drag", dragstop:"dragStop" }); $(this.element).parents('.ui-dialog').addClass("ui-app"); this.dialogParent = $(this.element).parents('.ui-dialog'); this.dialogParent.draggable('option', 'snap', '.preset-'+AppEngine.preset+' .ui-app'); // this.dialogParent.draggable('option', 'grid', [ 10, 10 ]); this._setOption('editMode',AppEngine.editMode); }, _setOption: function( key, value ) { if(key == "editMode"){ this._optionEditMode(value); }else if(key == "referencePoint"){ this._super(key, value); this.calculatePosition(); }else{ this._super(key, value); } }, _optionEditMode: function( value ){ if(value){ this.element.addClass('ui-app-editmode'); this.dialogParent.children('.ui-dialog-titlebar').show(); this.dialogParent.children('.ui-resizable-handle').show(); }else{ this.element.removeClass('ui-app-editmode'); this.dialogParent.children('.ui-dialog-titlebar').hide(); this.dialogParent.children('.ui-resizable-handle').hide(); } }, close:function() { AppEngine.unregisterApp(this.app); if (typeof this.app.destroy === 'function') { try{ this.app.destroy(); }catch(e){ this.log("An Error occured while trying to call "+this.app.name+".destroy() : "+e.toString()); } } this._super(); this.element.remove(); }, resize: function(event) { event.stopPropagation(); if (typeof this.app.resize === 'function') { try{ this.app.resize(); }catch(e){ this.log("An Error occured while trying to call "+this.app.name+".resize() : "+e.toString()); } } }, dragStart: function(){ RPIndicator.show(this.options.referencePoint); }, drag: function(event,ui) { event.stopPropagation(); var position = [ui.position.left,ui.position.top]; var size = [this.element.width(), this.element.height()]; var windowsize = [$(window).width(),$(window).height()]; var border = 50; var change = false; // changing refpoint for (var i = 0; i < 2; i++) { if(position[i] < border && this.options.referencePoint[i] !== 0){ this.options.referencePoint[i] = 0; change = true; }else if(position[i]+size[i]>=windowsize[i]-border && this.options.referencePoint[i] != 1){ this.options.referencePoint[i] = 1; change = true; } } if(change){ RPIndicator.move(this.options.referencePoint); } }, dragStop: function(event,ui){ this.options.position = [ui.position.left,ui.position.top]; // Updating position manually since the hook happens before changing the optionvalues this._calculateRefPointOffset(); RPIndicator.hide(); }, windowResize: function(){ if(this.options.active){ this.calculatePosition(); RPIndicator.move(this.options.referencePoint); } }, _calculateRefPointOffset: function(){ this.log("calculateRefPointOffset()"); var windowsize = [$(window).width(),$(window).height()]; for (var i = 0; i < 2; i++) { this.options.refPointOffset[i] = this.options.position[i] - ( this.options.referencePoint[i] * windowsize[i] ); } }, calculatePosition: function(){ this.log("calculatePosition() offset: "+this.options.refPointOffset); var windowsize = [$(window).width(),$(window).height()]; var position = [0,0]; for (var i = 0; i < 2; i++) { position[i] = ( this.options.referencePoint[i] * windowsize[i] ) + this.options.refPointOffset[i]; } this._setOption("position",position); }, log: function(message){ Logger.log("AppContainer",message,this.appName); } }); $.widget("beamNG.appButton", { _create : function(){ var appName = this.options.app; this.appSettings = AppEngine.appSettings[appName]; // creating the widget this.element.addClass('appButton'); this.front = $("<div class='appButtonImage'></div>").appendTo(this.element); this.title = $("<div class='appButtonTitle'>"+this.appSettings.info.name+" <span class='appButtonSmall'>v"+this.appSettings.info.version+"</span></div>").appendTo(this.element); this.detail = $("<div class='appButtonInfo'></div>").appendTo(this.element); $("<div class='appButtonSmall'>by "+this.appSettings.info.author+"</div>").appendTo(this.detail); $("<div>"+this.appSettings.info.description+"</div>").appendTo(this.detail); this.front.css('background-image', 'url(apps/'+appName+'/app.png), url(images/appDefault.png)'); // interactivity this.element.hover(function(obj) { $(this).children('.appButtonImage').first().stop(true, false).animate({height: 0}, 300); }, function() { $(this).children('.appButtonImage').first().stop(true, false).animate({height: 120}, 300); }); this.element.click(function(event) { AppEngine.loadApp(appName); AppStore.close(); }); } }); $(document).ready(function() { callGameEngineFuncCallback("getAppList()", function(res){ AppLoader.installedApps = res; AppLoader.initialize(); }); }); // Appengine ------------------------------------------------------ var AppEngine = { runningApps : {}, loadedApps : [], appSettings : {}, editMode : false, preset : undefined, runningRequests : 0, presetPanel : {}, initialized : false, initialize : function(){ // adding blendingdiv for editingmode $("<div class='appengine-blending'></div>").hide().appendTo('body'); // Install resizehandler $(window).resize(function(event) { AppEngine.resize(event); }); beamng.sendGameEngine('vlua("streams.reset()");'); // load persistance this._loadPersistance(); AppStore.initialize(); DebugManager.initialize(); this.initialized = true; }, toggleEditMode: function() { this.editMode = !this.editMode; if (this.editMode) { $('.appengine-blending').show(); } else{ $('.appengine-blending').hide(); AppStore.close(); this.savePreset(); } // changing appstates $.each(this.runningApps[AppEngine.preset], function(index, app){ app._widget.app("option", "editMode", AppEngine.editMode); }); }, update : function(data){ if(this.initialized){ for(var j = 0; j<this.runningApps[this.preset].length; j++){ var app = this.runningApps[this.preset][j]; var streamList = {}; var streams = this.appSettings[app.name].data.streams; for(var i=0; i<streams.length; i++){ var stream = streams[i]; if(state.streams[stream] > 0){ streamList[stream] = data[stream]; } } try{ app.update(streamList); }catch(e){ this.log("An Error occured while trying to call "+app.name+".update() : "+e.toString()); } } } }, registerApp : function(app){ this.runningApps[this.preset].push(app); //Adding streams var streams = this.appSettings[app.name].data.streams; for(var i=0; i<streams.length; i++){ streamAdd(streams[i]); } }, unregisterApp : function(app){ this.runningApps[this.preset].splice(this.runningApps[this.preset].indexOf(app),1); // removing streams var streams = this.appSettings[app.name].data.streams; for(var i=0; i<streams.length; i++){ streamRemove(streams[i]); } }, loadApp : function(app, position, size, persistance){ for(var i = 0 ; i < this.loadedApps.length; i++){ if(this.loadedApps[i] == app){ if(typeof window[app] !== 'function'){ this.log("App '"+app+"' can't be spawned. Appclass not found."); return; } var appInstance = new window[app](); this.log("Adding app "+app+" to Screen"); var appElement = $('<div></div>').appendTo($('body')); appElement.app({ app: appInstance, "persistance" : persistance, appendTo : this.presetPanel[this.preset] }); if(position !== undefined){ this.log("position:"); this.log(position[0]); this.log(position[1]); appElement.app("option","refPointOffset",position[1]); appElement.app("option","referencePoint",position[0]); }else{ appElement.app("option","refPointOffset",[$(window).width()/3,$(window).height()/3]); appElement.app("option","referencePoint",[0,0]); } if(size !== undefined){ this.log("size defined: "+size); appElement.app("option","width",size[0]); appElement.app("option","height",size[1]); }else{ //heighthack :| appElement.app("option","height",this.appSettings[app].appearance.size.initial[1]); } this.registerApp(appInstance); return; } } this.log("App "+app+" can't be displayed. A Error occurred while loading."); }, addPreset : function(preset){ this.persistance.presets[preset] = {}; }, deletePreset : function(preset){ if(typeof this.persistance.presets[preset] !== undefined){ this.persistance.presets[preset] = undefined; } }, loadPreset : function(preset){ if(this.persistance.presets[preset] !== undefined){ this.log("Preset exists"); if(this.presetPanel[this.preset] !== undefined){ //desactivate old apps $.each(this.runningApps[this.preset], function(index, app) { app._widget.app("option","active",false); }); //hide old preset this.presetPanel[this.preset].fadeOut(250); } this.preset = preset; if(this.runningApps[preset] === undefined){ // Preset wasn't loaded before this.runningApps[preset] = []; // creating presetpanel this.presetPanel[preset] = $("<div class='preset-"+preset+"'></div>").appendTo($("body")).css({ width: "100%", height: "100%" }); $("<span>"+preset+"</span>").appendTo(this.presetPanel[preset]); this.log("loading preset '"+preset+"'"); $.each(this.persistance.presets[preset].apps, function(index, app) { AppEngine.loadApp(app.name, app.position, app.size, app.persistance); }); this.log("done"); }else{ this.presetPanel[this.preset].fadeIn(250); $.each(this.runningApps[this.preset], function(index, app) { app._widget.app("option","active",true); app._widget.app("calculatePosition"); }); } } }, savePreset : function(){ // empty Preset this.persistance.presets[this.preset].apps = []; this.log("Saving Preset "+this.preset); $.each(this.runningApps[this.preset], function(index, app) { appData = {}; appData.name = app.constructor.name; appData.position = [app._widget.app("option","referencePoint"), app._widget.app("option","refPointOffset")]; appData.size = [app._widget.app("option","width"),app._widget.app("option","height")]; appData.persistance = { options : app.options, custom : app.persistance}; // Don't save size if its unchanged or resizing is disallowed if (appData.size == AppEngine.appSettings[appData.name].appearance.size.initial || AppEngine.appSettings[appData.name].appearance.resize === false){ appData.size = undefined; } AppEngine.log(" - "+JSON.stringify(appData)); AppEngine.persistance.presets[AppEngine.preset].apps.push(appData); }); this._savePersistance(); this.log("done."); }, _loadPersistance : function(){ if (localStorage.getItem("AppEngine") !== null) { this.persistance = JSON.parse(localStorage.getItem("AppEngine")); AppEngine.loadPreset("default"); } else{ $.getJSON('apps/persistance.json', function(data) { AppEngine.log( "worked"); AppEngine.persistance = data; AppEngine._savePersistance(); location.reload(); }).fail(function(data) { AppEngine.log( "error" ); AppEngine.log( JSON.stringify(data) ); }); } }, _savePersistance : function(){ localStorage.setItem("AppEngine",JSON.stringify(this.persistance)); }, resize : function(event){ windowsize = [$(window).width(),$(window).height()]; $.each(this.runningApps[this.preset], function(index, app) { app._widget.app("calculatePosition"); position = app._widget.app("option","position"); size = [app._widget.app("option","width"),app._widget.app("option","height")]; change = 0; for (var i = 0; i < 2; i++) { if(position[i]+size[i] > windowsize[i]){ change++; position[i] = windowsize[i] - size[i]; } } if(change>0){ app._widget.app("option","position",position); } }); }, log: function(message){ Logger.log("AppEngine",message); } }; var AppStore = { initialize: function(){ this.mainDiv = $("<div id='AppStore'></div>").appendTo("body"); this.mainDiv.dialog({ title: "Add App", width: $(window).width()-70, height: $(window).height()-70, beforeClose : function(event, ui){ AppStore.close(); return false; }, draggable: false, resizable: false, closeOnEscape: true }); this.close(); $.each(AppEngine.loadedApps, function(index, val) { $("<a></a>").appendTo(AppStore.mainDiv).appButton({app: val}); }); $(window).resize(function(event) { AppStore.resize(); }); // button $("<a class='appstorebutton'>+</a>").appendTo($(".appengine-blending")).css({ position: 'absolute', right: 50, top: 10 }).button().click(function(event) { AppStore.open(); }); }, open: function(){ this.mainDiv.parent().show(); this.resize(); this.mainDiv.dialog( "moveToTop" ); }, close: function(){ this.mainDiv.parent().hide(); }, resize: function(){ this.mainDiv.dialog("option","width",$(window).width()-70); this.mainDiv.dialog("option","height",$(window).height()-70); } }; var AppLoader = { installedApps : [], loadstates : {}, loadInitialized : false, LOADSTATE : { DONE : 1, ERROR: -1, LOADING : 0 }, initialize: function(){ this.log("Starting to load apps."); this.loadApps(); this.loadInitialized = true; this._checkProgress(); }, loadApps : function(app){ // Load all apps for (var i = 0; i<this.installedApps.length;i++) { app = this.installedApps[i]; this._loadAppJs(app); this._loadAppJson(app); // load css var cssNode = document.createElement("link"); cssNode.setAttribute("rel", "stylesheet"); cssNode.setAttribute("type", "text/css"); cssNode.setAttribute("href", "apps/"+app+"/app.css"); $(cssNode).appendTo("head"); } }, _loadAppJs : function(app){ this._setLoadState(app,'js',this.LOADSTATE.LOADING); $.getScript( "apps/"+app+"/app.js", function( data, textStatus, jqxhr) { AppLoader._setLoadState(app,'js',AppLoader.LOADSTATE.DONE); }).fail(function(){ AppLoader._setLoadState(app,'js',AppLoader.LOADSTATE.ERROR); if(arguments[0].readyState === 0){ //script failed to load this.log("app.js of '"+app+"' failed to load. Check your filenames."); }else{ //script loaded but failed to parse this.log("app.js of '"+app+"' failed to parse: "+arguments[2].toString()); } }); }, _loadAppJson : function(app){ this._setLoadState(app,'json',this.LOADSTATE.LOADING); $.getJSON("apps/"+app+"/app.json", function(data) { AppLoader.log(data); AppEngine.appSettings[app] = data; AppLoader._setLoadState(app,'json',AppLoader.LOADSTATE.DONE); }).fail(function(){ AppLoader._setLoadState(app,'json',AppLoader.LOADSTATE.ERROR); AppLoader.log("app.json of '"+app+"' failed to load. Check your filenames."); }); }, _setLoadState : function(app,type,state){ if(this.loadstates[app] === undefined){ this.loadstates[app] = {}; } this.loadstates[app][type] = state; if(state == this.LOADSTATE.DONE || state == this.LOADSTATE.ERROR){ this._checkProgress(); } }, _checkProgress : function(){ //this.log(JSON.stringify(this.loadstates)); allLoaded = true; $.each(this.loadstates, function(appindex, app) { $.each(app, function(typeindex, state) { if(state == AppLoader.LOADSTATE.LOADING){ allLoaded=false; } }); }); //this.log("Progress ["+new Date().toLocaleTimeString()+"]: Status [LOADING/ERROR/DONE]: "+loading+"/"+error+"/"+done+" "+allLoaded); if(this.loadInitialized && allLoaded){ this.log("Loading done"); $.each(this.loadstates, function(appindex, app) { if(app.js == AppLoader.LOADSTATE.DONE && app.json == AppLoader.LOADSTATE.DONE ){ // && app['data'] != AppLoader.LOADSTATE.LOADING AppEngine.loadedApps.push(appindex); } }); this.log("loadedApps: "+JSON.stringify(AppEngine.loadedApps)); AppEngine.initialize(); } }, log: function(message){ Logger.log("AppLoader",message); } }; var HookManager = { hooks : [], registerHook : function(object, methodname, hookname){ this.hooks.push([object, methodname, hookname]); }, unregisterHook : function(object){ if(arguments[1]!==undefined){ hookname = arguments[1]; for(i = 0; i<this.hooks.length; i++){ hook = this.hooks[i]; if(hook[0] == object && hook[2] == hookname){ this.hooks.splice(i,1); } } }else{ for(i = 0; i<this.hooks.length; i++){ hook = this.hooks[i]; if(hook[0] == object){ this.hooks.splice(i,1); } } } }, triggerHook : function(hookname, data){ this.log(hookname+" triggered"); for(i = 0; i<this.hooks.length; i++){ hook = this.hooks[i]; if(hook[2] == hookname){ object = hook[0]; methodname = hook[1]; object[methodname](data); } } }, triggerHooks : function(hooks){ for(i = 0; i<hooks.length; i++){ this.triggerHook(hooks[i]); } }, log: function(message){ Logger.log("HookManager",message); } }; var DebugManager = { presets: [], presetPosition: -1, initialize: function(){ $.each(AppEngine.persistance.presets, function(index, preset) { if(preset.debug){ DebugManager.presets.push(index); } }); this.log("Debugpresets: "+JSON.stringify(this.presets)); $(document).keyup(function(event) { DebugManager.log("KEY: "+JSON.stringify(event.which)); if(event.which == 75){ DebugManager.previousDebug(); }else if(event.which == 76){ DebugManager.nextDebug(); } }); }, nextDebug: function(){ this.presetPosition++; if(this.presetPosition == this.presets.length){ this.presetPosition = -1; } this.updatePreset(); }, previousDebug: function(){ this.presetPosition--; if(this.presetPosition == -2){ this.presetPosition = this.presets.length - 1; } this.updatePreset(); }, updatePreset: function(){ if(this.presetPosition == -1){ AppEngine.loadPreset("default"); return; } AppEngine.loadPreset(this.presets[this.presetPosition]); }, log: function(message){ Logger.log("DebugManager",message); } }; var RPIndicator = { size: 20, element: undefined, initialize: function(){ this.element = $("<div class='RPIndicator'></div>").hide().appendTo($("body")); }, show: function(position){ if(this.element === undefined){ this.initialize(); } this.move(position); this.element.show(); }, move: function(position){ if(this.element === undefined){ this.initialize(); } this.element.css({ left: (position[0]*($(window).width()))-(this.size/2), top: (position[1]*($(window).height()))-(this.size/2) }); }, hide: function(){ if(this.element === undefined){ this.initialize(); } this.element.hide(); } }; $(document).ready(function() { DebugKeySimulator.initialize(); }); var DebugKeySimulator = { initialize: function(){ this.panel = $("<div></div>").appendTo($("body")).css({ bottom: '0', left: '200px', position: 'absolute' }); $("<a>&lt;</a>").appendTo(this.panel).button().click(function(event) { DebugManager.previousDebug(); }); $("<a>&gt;</a>").appendTo(this.panel).button().click(function(event) { DebugManager.nextDebug(); }); } }; var Logger = { log: function(system, message, instance){ var logMessage = "["+system+"]"; if(instance){ logMessage += "["+instance+"]"; } logMessage += ": "+message; console.log(logMessage); } };
js/app.js
$.widget( "beamNG.app", $.ui.dialog, { options: { app: null, persistance: undefined, active: true, editMode: false, refPointOffset : [0, 0], referencePoint : [0, 0] // [0,0] = upper left, [1,1] = lower right }, _create : function(){ this.app = this.options.app; this.appName = this.app.name = this.app.constructor.name; this.appInfo = AppEngine.appSettings[this.appName]; // Persistance if(this.options.persistance === undefined){ this.options.persistance = { options : {}, custom : {} }; } this.app.options = this.options.persistance.options; this.app.persistance = this.options.persistance.custom; // Configuration this.options.title = this.appInfo.info.name; // Resize if(this.appInfo.appearance.resize === false){ this.options.resizable = false; } // inner size modifier var sizeOffset = 10 * ( this.appInfo.appearance.opaque === true); // Sizes if(this.appInfo.appearance.size.initial !== undefined){ this.options.width = this.appInfo.appearance.size.initial[0] + sizeOffset; this.options.height = this.appInfo.appearance.size.initial[1] + sizeOffset; } // minimal size if(this.appInfo.appearance.size.minimal !== undefined){ this.options.minWidth = this.appInfo.appearance.size.minimal[0] + sizeOffset; this.options.minHeight = this.appInfo.appearance.size.minimal[1] + sizeOffset; } // minsize must be <= size this.options.minWidth = Math.min(this.options.minWidth, this.options.width); if(this.options.height != "auto"){ this.log("setting minsize"); this.options.minHeight = Math.min(this.options.minHeight, this.options.height); this.log(this.options.minHeight); } // maximal size if(this.appInfo.appearance.size.maximal !== undefined){ this.options.maxWidth = this.appInfo.appearance.size.maximal[0] + sizeOffset; this.options.maxHeight = this.appInfo.appearance.size.maximal[1] + sizeOffset; } // maximal size must be >= size if(this.options.maxWidth){ this.options.maxWidth = Math.max(this.options.maxWidth, this.options.width); } if(this.options.maxHeight){ this.options.maxHeight = Math.max(this.options.maxHeight, this.options.height); } // add helpervariables this.app._widget = $(this.element); this.app.path = "apps/"+this.appName+"/"; this._super(); }, _init:function(){ // Initialize Widget this._super("_init"); // Background var backgroundClasses = ["opaque","opaque-simple","transparent"]; if(backgroundClasses.indexOf(this.appInfo.appearance.background)!= -1){ this.element.addClass(this.appInfo.appearance.background); }else{ this.log("Error parsing app.json attribute appearance.backround: invalid value"); } // adding properties this.element.addClass("app"); this.app.rootElement = $("<div></div>").css({ width: '100%', height: '100%', 'min-width': '10px', 'min-height': '10px' }).appendTo($(this.element)); this.app.rootElement.addClass(this.appName); // adding savemethod this.app.save = function(){ AppEngine.savePreset(); }; // adding logmethod var appname = this.appName; this.app.log = function(message){ Logger.log("App", message, appname); }; // Initialize App try{ this.app.initialize(); }catch(e){ this.log("An Error occured while trying to call "+this.app.name+".initialize() : "+e.toString()+". Killing App."); var self = this; setTimeout(function(){self.close();},0); } // installing handlers this._on(this.element.parent(), { resize:"resize", dragstart:"dragStart", drag:"drag", dragstop:"dragStop" }); $(this.element).parents('.ui-dialog').addClass("ui-app"); this.dialogParent = $(this.element).parents('.ui-dialog'); this.dialogParent.draggable('option', 'snap', '.preset-'+AppEngine.preset+' .ui-app'); // this.dialogParent.draggable('option', 'grid', [ 10, 10 ]); this._setOption('editMode',AppEngine.editMode); }, _setOption: function( key, value ) { if(key == "editMode"){ this._optionEditMode(value); }else if(key == "referencePoint"){ this._super(key, value); this.calculatePosition(); }else{ this._super(key, value); } }, _optionEditMode: function( value ){ if(value){ this.element.addClass('ui-app-editmode'); this.dialogParent.children('.ui-dialog-titlebar').show(); this.dialogParent.children('.ui-resizable-handle').show(); }else{ this.element.removeClass('ui-app-editmode'); this.dialogParent.children('.ui-dialog-titlebar').hide(); this.dialogParent.children('.ui-resizable-handle').hide(); } }, close:function() { AppEngine.unregisterApp(this.app); if (typeof this.app.destroy === 'function') { try{ this.app.destroy(); }catch(e){ this.log("An Error occured while trying to call "+this.app.name+".destroy() : "+e.toString()); } } this._super(); this.element.remove(); }, resize: function(event) { event.stopPropagation(); if (typeof this.app.resize === 'function') { try{ this.app.resize(); }catch(e){ this.log("An Error occured while trying to call "+this.app.name+".resize() : "+e.toString()); } } }, dragStart: function(){ RPIndicator.show(this.options.referencePoint); }, drag: function(event,ui) { event.stopPropagation(); var position = [ui.position.left,ui.position.top]; var size = [this.element.width(), this.element.height()]; var windowsize = [$(window).width(),$(window).height()]; var border = 50; var change = false; // changing refpoint for (var i = 0; i < 2; i++) { if(position[i] < border && this.options.referencePoint[i] !== 0){ this.options.referencePoint[i] = 0; change = true; }else if(position[i]+size[i]>=windowsize[i]-border && this.options.referencePoint[i] != 1){ this.options.referencePoint[i] = 1; change = true; } } if(change){ RPIndicator.move(this.options.referencePoint); } }, dragStop: function(event,ui){ this.options.position = [ui.position.left,ui.position.top]; // Updating position manually since the hook happens before changing the optionvalues this._calculateRefPointOffset(); RPIndicator.hide(); }, windowResize: function(){ if(this.options.active){ this.calculatePosition(); RPIndicator.move(this.options.referencePoint); } }, _calculateRefPointOffset: function(){ this.log("calculateRefPointOffset()"); var windowsize = [$(window).width(),$(window).height()]; for (var i = 0; i < 2; i++) { this.options.refPointOffset[i] = this.options.position[i] - ( this.options.referencePoint[i] * windowsize[i] ); } }, calculatePosition: function(){ this.log("calculatePosition() offset: "+this.options.refPointOffset); var windowsize = [$(window).width(),$(window).height()]; var position = [0,0]; for (var i = 0; i < 2; i++) { position[i] = ( this.options.referencePoint[i] * windowsize[i] ) + this.options.refPointOffset[i]; } this._setOption("position",position); }, log: function(message){ Logger.log("AppContainer",message,this.appName); } }); $.widget("beamNG.appButton", { _create : function(){ var appName = this.options.app; this.appSettings = AppEngine.appSettings[appName]; // creating the widget this.element.addClass('appButton'); this.front = $("<div class='appButtonImage'></div>").appendTo(this.element); this.title = $("<div class='appButtonTitle'>"+this.appSettings.info.name+" <span class='appButtonSmall'>v"+this.appSettings.info.version+"</span></div>").appendTo(this.element); this.detail = $("<div class='appButtonInfo'></div>").appendTo(this.element); $("<div class='appButtonSmall'>by "+this.appSettings.info.author+"</div>").appendTo(this.detail); $("<div>"+this.appSettings.info.description+"</div>").appendTo(this.detail); this.front.css('background-image', 'url(apps/'+appName+'/app.png), url(images/appDefault.png)'); // interactivity this.element.hover(function(obj) { $(this).children('.appButtonImage').first().stop(true, false).animate({height: 0}, 300); }, function() { $(this).children('.appButtonImage').first().stop(true, false).animate({height: 120}, 300); }); this.element.click(function(event) { AppEngine.loadApp(appName); AppStore.close(); }); } }); $(document).ready(function() { AppLoader.installedApps = ["Tacho","WheelsDebug", "Debug","NodeBeamDebug","EngineDebug","TorqueCurve","gForcesDebug","SimpleTacho","SimpleSpeedo","SimpleSteering","SimplePedals","SimpleDash","SimpleAGears","SimpleNBDebug","SimpleEngineDebug","SimpleRPMDebug","SimpleGears","SimpleDigSpeedo","SimpleDigTacho","WeightDistribution"]; // Call a beamNG function later AppLoader.initialize(); }); // Appengine ------------------------------------------------------ var AppEngine = { runningApps : {}, loadedApps : [], appSettings : {}, editMode : false, preset : undefined, runningRequests : 0, presetPanel : {}, initialized : false, initialize : function(){ // adding blendingdiv for editingmode $("<div class='appengine-blending'></div>").hide().appendTo('body'); // Install resizehandler $(window).resize(function(event) { AppEngine.resize(event); }); beamng.sendGameEngine('vlua("streams.reset()");'); // load persistance this._loadPersistance(); AppStore.initialize(); DebugManager.initialize(); this.initialized = true; }, toggleEditMode: function() { this.editMode = !this.editMode; if (this.editMode) { $('.appengine-blending').show(); } else{ $('.appengine-blending').hide(); AppStore.close(); this.savePreset(); } // changing appstates $.each(this.runningApps[AppEngine.preset], function(index, app){ app._widget.app("option", "editMode", AppEngine.editMode); }); }, update : function(data){ if(this.initialized){ for(var j = 0; j<this.runningApps[this.preset].length; j++){ var app = this.runningApps[this.preset][j]; var streamList = {}; var streams = this.appSettings[app.name].data.streams; for(var i=0; i<streams.length; i++){ var stream = streams[i]; if(state.streams[stream] > 0){ streamList[stream] = data[stream]; } } try{ app.update(streamList); }catch(e){ this.log("An Error occured while trying to call "+app.name+".update() : "+e.toString()); } } } }, registerApp : function(app){ this.runningApps[this.preset].push(app); //Adding streams var streams = this.appSettings[app.name].data.streams; for(var i=0; i<streams.length; i++){ streamAdd(streams[i]); } }, unregisterApp : function(app){ this.runningApps[this.preset].splice(this.runningApps[this.preset].indexOf(app),1); // removing streams var streams = this.appSettings[app.name].data.streams; for(var i=0; i<streams.length; i++){ streamRemove(streams[i]); } }, loadApp : function(app, position, size, persistance){ for(var i = 0 ; i < this.loadedApps.length; i++){ if(this.loadedApps[i] == app){ if(typeof window[app] !== 'function'){ this.log("App '"+app+"' can't be spawned. Appclass not found."); return; } var appInstance = new window[app](); this.log("Adding app "+app+" to Screen"); var appElement = $('<div></div>').appendTo($('body')); appElement.app({ app: appInstance, "persistance" : persistance, appendTo : this.presetPanel[this.preset] }); if(position !== undefined){ this.log("position:"); this.log(position[0]); this.log(position[1]); appElement.app("option","refPointOffset",position[1]); appElement.app("option","referencePoint",position[0]); }else{ appElement.app("option","refPointOffset",[$(window).width()/3,$(window).height()/3]); appElement.app("option","referencePoint",[0,0]); } if(size !== undefined){ this.log("size defined: "+size); appElement.app("option","width",size[0]); appElement.app("option","height",size[1]); }else{ //heighthack :| appElement.app("option","height",this.appSettings[app].appearance.size.initial[1]); } this.registerApp(appInstance); return; } } this.log("App "+app+" can't be displayed. A Error occurred while loading."); }, addPreset : function(preset){ this.persistance.presets[preset] = {}; }, deletePreset : function(preset){ if(typeof this.persistance.presets[preset] !== undefined){ this.persistance.presets[preset] = undefined; } }, loadPreset : function(preset){ if(this.persistance.presets[preset] !== undefined){ this.log("Preset exists"); if(this.presetPanel[this.preset] !== undefined){ //desactivate old apps $.each(this.runningApps[this.preset], function(index, app) { app._widget.app("option","active",false); }); //hide old preset this.presetPanel[this.preset].fadeOut(250); } this.preset = preset; if(this.runningApps[preset] === undefined){ // Preset wasn't loaded before this.runningApps[preset] = []; // creating presetpanel this.presetPanel[preset] = $("<div class='preset-"+preset+"'></div>").appendTo($("body")).css({ width: "100%", height: "100%" }); $("<span>"+preset+"</span>").appendTo(this.presetPanel[preset]); this.log("loading preset '"+preset+"'"); $.each(this.persistance.presets[preset].apps, function(index, app) { AppEngine.loadApp(app.name, app.position, app.size, app.persistance); }); this.log("done"); }else{ this.presetPanel[this.preset].fadeIn(250); $.each(this.runningApps[this.preset], function(index, app) { app._widget.app("option","active",true); app._widget.app("calculatePosition"); }); } } }, savePreset : function(){ // empty Preset this.persistance.presets[this.preset].apps = []; this.log("Saving Preset "+this.preset); $.each(this.runningApps[this.preset], function(index, app) { appData = {}; appData.name = app.constructor.name; appData.position = [app._widget.app("option","referencePoint"), app._widget.app("option","refPointOffset")]; appData.size = [app._widget.app("option","width"),app._widget.app("option","height")]; appData.persistance = { options : app.options, custom : app.persistance}; // Don't save size if its unchanged or resizing is disallowed if (appData.size == AppEngine.appSettings[appData.name].appearance.size.initial || AppEngine.appSettings[appData.name].appearance.resize === false){ appData.size = undefined; } AppEngine.log(" - "+JSON.stringify(appData)); AppEngine.persistance.presets[AppEngine.preset].apps.push(appData); }); this._savePersistance(); this.log("done."); }, _loadPersistance : function(){ if (localStorage.getItem("AppEngine") !== null) { this.persistance = JSON.parse(localStorage.getItem("AppEngine")); AppEngine.loadPreset("default"); } else{ $.getJSON('apps/persistance.json', function(data) { AppEngine.log( "worked"); AppEngine.persistance = data; AppEngine._savePersistance(); location.reload(); }).fail(function(data) { AppEngine.log( "error" ); AppEngine.log( JSON.stringify(data) ); }); } }, _savePersistance : function(){ localStorage.setItem("AppEngine",JSON.stringify(this.persistance)); }, resize : function(event){ windowsize = [$(window).width(),$(window).height()]; $.each(this.runningApps[this.preset], function(index, app) { app._widget.app("calculatePosition"); position = app._widget.app("option","position"); size = [app._widget.app("option","width"),app._widget.app("option","height")]; change = 0; for (var i = 0; i < 2; i++) { if(position[i]+size[i] > windowsize[i]){ change++; position[i] = windowsize[i] - size[i]; } } if(change>0){ app._widget.app("option","position",position); } }); }, log: function(message){ Logger.log("AppEngine",message); } }; var AppStore = { initialize: function(){ this.mainDiv = $("<div id='AppStore'></div>").appendTo("body"); this.mainDiv.dialog({ title: "Add App", width: $(window).width()-70, height: $(window).height()-70, beforeClose : function(event, ui){ AppStore.close(); return false; }, draggable: false, resizable: false, closeOnEscape: true }); this.close(); $.each(AppEngine.loadedApps, function(index, val) { $("<a></a>").appendTo(AppStore.mainDiv).appButton({app: val}); }); $(window).resize(function(event) { AppStore.resize(); }); // button $("<a class='appstorebutton'>+</a>").appendTo($(".appengine-blending")).css({ position: 'absolute', right: 50, top: 10 }).button().click(function(event) { AppStore.open(); }); }, open: function(){ this.mainDiv.parent().show(); this.resize(); this.mainDiv.dialog( "moveToTop" ); }, close: function(){ this.mainDiv.parent().hide(); }, resize: function(){ this.mainDiv.dialog("option","width",$(window).width()-70); this.mainDiv.dialog("option","height",$(window).height()-70); } }; var AppLoader = { installedApps : [], loadstates : {}, loadInitialized : false, LOADSTATE : { DONE : 1, ERROR: -1, LOADING : 0 }, initialize: function(){ this.log("Starting to load apps."); this.loadApps(); this.loadInitialized = true; this._checkProgress(); }, loadApps : function(app){ // Load all apps for (var i = 0; i<this.installedApps.length;i++) { app = this.installedApps[i]; this._loadAppJs(app); this._loadAppJson(app); // load css var cssNode = document.createElement("link"); cssNode.setAttribute("rel", "stylesheet"); cssNode.setAttribute("type", "text/css"); cssNode.setAttribute("href", "apps/"+app+"/app.css"); $(cssNode).appendTo("head"); } }, _loadAppJs : function(app){ this._setLoadState(app,'js',this.LOADSTATE.LOADING); $.getScript( "apps/"+app+"/app.js", function( data, textStatus, jqxhr) { AppLoader._setLoadState(app,'js',AppLoader.LOADSTATE.DONE); }).fail(function(){ AppLoader._setLoadState(app,'js',AppLoader.LOADSTATE.ERROR); if(arguments[0].readyState === 0){ //script failed to load this.log("app.js of '"+app+"' failed to load. Check your filenames."); }else{ //script loaded but failed to parse this.log("app.js of '"+app+"' failed to parse: "+arguments[2].toString()); } }); }, _loadAppJson : function(app){ this._setLoadState(app,'json',this.LOADSTATE.LOADING); $.getJSON("apps/"+app+"/app.json", function(data) { AppLoader.log(data); AppEngine.appSettings[app] = data; AppLoader._setLoadState(app,'json',AppLoader.LOADSTATE.DONE); }).fail(function(){ AppLoader._setLoadState(app,'json',AppLoader.LOADSTATE.ERROR); AppLoader.log("app.json of '"+app+"' failed to load. Check your filenames."); }); }, _setLoadState : function(app,type,state){ if(this.loadstates[app] === undefined){ this.loadstates[app] = {}; } this.loadstates[app][type] = state; if(state == this.LOADSTATE.DONE || state == this.LOADSTATE.ERROR){ this._checkProgress(); } }, _checkProgress : function(){ //this.log(JSON.stringify(this.loadstates)); allLoaded = true; $.each(this.loadstates, function(appindex, app) { $.each(app, function(typeindex, state) { if(state == AppLoader.LOADSTATE.LOADING){ allLoaded=false; } }); }); //this.log("Progress ["+new Date().toLocaleTimeString()+"]: Status [LOADING/ERROR/DONE]: "+loading+"/"+error+"/"+done+" "+allLoaded); if(this.loadInitialized && allLoaded){ this.log("Loading done"); $.each(this.loadstates, function(appindex, app) { if(app.js == AppLoader.LOADSTATE.DONE && app.json == AppLoader.LOADSTATE.DONE ){ // && app['data'] != AppLoader.LOADSTATE.LOADING AppEngine.loadedApps.push(appindex); } }); this.log("loadedApps: "+JSON.stringify(AppEngine.loadedApps)); AppEngine.initialize(); } }, log: function(message){ Logger.log("AppLoader",message); } }; var HookManager = { hooks : [], registerHook : function(object, methodname, hookname){ this.hooks.push([object, methodname, hookname]); }, unregisterHook : function(object){ if(arguments[1]!==undefined){ hookname = arguments[1]; for(i = 0; i<this.hooks.length; i++){ hook = this.hooks[i]; if(hook[0] == object && hook[2] == hookname){ this.hooks.splice(i,1); } } }else{ for(i = 0; i<this.hooks.length; i++){ hook = this.hooks[i]; if(hook[0] == object){ this.hooks.splice(i,1); } } } }, triggerHook : function(hookname, data){ this.log(hookname+" triggered"); for(i = 0; i<this.hooks.length; i++){ hook = this.hooks[i]; if(hook[2] == hookname){ object = hook[0]; methodname = hook[1]; object[methodname](data); } } }, triggerHooks : function(hooks){ for(i = 0; i<hooks.length; i++){ this.triggerHook(hooks[i]); } }, log: function(message){ Logger.log("HookManager",message); } }; var DebugManager = { presets: [], presetPosition: -1, initialize: function(){ $.each(AppEngine.persistance.presets, function(index, preset) { if(preset.debug){ DebugManager.presets.push(index); } }); this.log("Debugpresets: "+JSON.stringify(this.presets)); $(document).keyup(function(event) { DebugManager.log("KEY: "+JSON.stringify(event.which)); if(event.which == 75){ DebugManager.previousDebug(); }else if(event.which == 76){ DebugManager.nextDebug(); } }); }, nextDebug: function(){ this.presetPosition++; if(this.presetPosition == this.presets.length){ this.presetPosition = -1; } this.updatePreset(); }, previousDebug: function(){ this.presetPosition--; if(this.presetPosition == -2){ this.presetPosition = this.presets.length - 1; } this.updatePreset(); }, updatePreset: function(){ if(this.presetPosition == -1){ AppEngine.loadPreset("default"); return; } AppEngine.loadPreset(this.presets[this.presetPosition]); }, log: function(message){ Logger.log("DebugManager",message); } }; var RPIndicator = { size: 20, element: undefined, initialize: function(){ this.element = $("<div class='RPIndicator'></div>").hide().appendTo($("body")); }, show: function(position){ if(this.element === undefined){ this.initialize(); } this.move(position); this.element.show(); }, move: function(position){ if(this.element === undefined){ this.initialize(); } this.element.css({ left: (position[0]*($(window).width()))-(this.size/2), top: (position[1]*($(window).height()))-(this.size/2) }); }, hide: function(){ if(this.element === undefined){ this.initialize(); } this.element.hide(); } }; $(document).ready(function() { DebugKeySimulator.initialize(); }); var DebugKeySimulator = { initialize: function(){ this.panel = $("<div></div>").appendTo($("body")).css({ bottom: '0', left: '200px', position: 'absolute' }); $("<a>&lt;</a>").appendTo(this.panel).button().click(function(event) { DebugManager.previousDebug(); }); $("<a>&gt;</a>").appendTo(this.panel).button().click(function(event) { DebugManager.nextDebug(); }); } }; var Logger = { log: function(system, message, instance){ var logMessage = "["+system+"]"; if(instance){ logMessage += "["+instance+"]"; } logMessage += ": "+message; console.log(logMessage); } };
[improved] apploading, list of apps isn't hardcoded anymore
js/app.js
[improved] apploading, list of apps isn't hardcoded anymore
<ide><path>s/app.js <ide> }); <ide> <ide> $(document).ready(function() { <del> AppLoader.installedApps = ["Tacho","WheelsDebug", "Debug","NodeBeamDebug","EngineDebug","TorqueCurve","gForcesDebug","SimpleTacho","SimpleSpeedo","SimpleSteering","SimplePedals","SimpleDash","SimpleAGears","SimpleNBDebug","SimpleEngineDebug","SimpleRPMDebug","SimpleGears","SimpleDigSpeedo","SimpleDigTacho","WeightDistribution"]; // Call a beamNG function later <del> AppLoader.initialize(); <add> callGameEngineFuncCallback("getAppList()", function(res){ <add> AppLoader.installedApps = res; <add> AppLoader.initialize(); <add> }); <ide> }); <ide> <ide>
Java
apache-2.0
603cc8de6aded0fd36802ec06f3bebb96b676a88
0
TKnudsen/ComplexDataObject
package com.github.TKnudsen.ComplexDataObject.data.distanceMatrix; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.github.TKnudsen.ComplexDataObject.model.distanceMeasure.IDistanceMeasure; /** * <p> * Title: DistanceMatrix * </p> * * <p> * Description: Stores and manages distances of pairs of objects (T's) * </p> * * <p> * Copyright: Copyright (c) 2017 * </p> * * @author Juergen Bernard * @version 1.04 */ public class DistanceMatrix<T> implements IDistanceMatrix<T> { // constructor properties protected List<T> objects; protected IDistanceMeasure<T> distanceMeasure; // storage, indexing protected double[][] distanceMatrix = null; protected Map<T, Integer> objectIndex; // statistics private double min; private double max; // elements associated to statistics private List<T> closestElements = new ArrayList<>(2); private List<T> farestElements = new ArrayList<>(2); public DistanceMatrix(List<T> objects, IDistanceMeasure<T> distanceMeasure) { if (distanceMeasure == null) throw new IllegalArgumentException("DistanceMatrix: given distance measures was null"); this.objects = objects; this.distanceMeasure = distanceMeasure; initializeDistanceMatrix(); } protected void initializeObjectIndex() { // create index objectIndex = new HashMap<>(); for (int i = 0; i < objects.size(); i++) objectIndex.put(objects.get(i), i); } protected void initializeDistanceMatrix() { initializeObjectIndex(); distanceMatrix = new double[objectIndex.size()][objectIndex.size()]; for (int x = 0; x < distanceMatrix.length; x++) for (int y = 0; y < distanceMatrix[x].length; y++) distanceMatrix[x][y] = Double.NaN; updateMinDistance(Double.POSITIVE_INFINITY, null, null); updateMaxDistance(Double.NEGATIVE_INFINITY, null, null); // create distance matrix - optimized for inheriting index-based access for (T t1 : objectIndex.keySet()) for (T t2 : objectIndex.keySet()) { double distance = distanceMeasure.getDistance(t1, t2); distanceMatrix[getObjectIndex(t1)][getObjectIndex(t2)] = distance; if (getMin() > distance) { updateMinDistance(distance, t1, t2); } if (getMax() < distance) { updateMaxDistance(distance, t1, t2); } // min = Math.min(min, distance); // max = Math.max(max, distance); } // // create distance matrix - would be at least as good as the upper // // variant. but does not generalize for inheriting classes // for (int i = 0; i < objectIndex.size() - 1; i++) // for (int j = i; j < objectIndex.size(); j++) { // double d1 = distanceMeasure.getDistance(objects.get(i), // objects.get(j)); // double d2 = distanceMeasure.getDistance(objects.get(j), // objects.get(i)); // // distanceMatrix[i][j] = d1; // distanceMatrix[j][i] = d2; // // min = Math.min(min, d1); // min = Math.min(min, d2); // // max = Math.max(max, d1); // max = Math.max(max, d2); // } } protected Integer getObjectIndex(T object) { // if (objectIndex == null) // initializeDistanceMatrix(); return objectIndex.get(object); } @Override public double getDistance(T o1, T o2) { Integer index1 = getObjectIndex(o1); Integer index2 = getObjectIndex(o2); // better let it burn. it is a bad design if these indices would be null // if (index1 == null || index2 == null) // return distanceMeasure.getDistance(o1, o2); return getDistanceMatrix()[index1][index2]; } @Override public String getName() { return "Distance Matrix using " + distanceMeasure.toString(); } @Override public String getDescription() { return getName() + ", size: " + objects.size() + " x " + objects.size() + "."; } @Override public double applyAsDouble(T t, T u) { return getDistance(t, u); } @Override public double[][] getDistanceMatrix() { if (distanceMatrix == null) initializeDistanceMatrix(); return distanceMatrix; } public int size() { return objects.size(); } @Override public double getMinDistance() { return getMin(); } @Override public double getMaxDistance() { return getMax(); } public List<T> getClosestElements() { return closestElements; } public void setClosestElements(List<T> closestElements) { this.closestElements = closestElements; } public List<T> getFarestElements() { return farestElements; } public void setFarestElements(List<T> farestElements) { this.farestElements = farestElements; } public double getMin() { return min; } /** * sets the minimum distance between two elements. these elements are also * queried. * * @param min * @param t1 * @param t2 */ public void updateMinDistance(double min, T t1, T t2) { this.min = min; closestElements.clear(); closestElements.add(t1); closestElements.add(t2); } public double getMax() { return max; } public void updateMaxDistance(double max, T t1, T t2) { this.max = max; farestElements.clear(); farestElements.add(t1); farestElements.add(t2); } }
src/main/java/com/github/TKnudsen/ComplexDataObject/data/distanceMatrix/DistanceMatrix.java
package com.github.TKnudsen.ComplexDataObject.data.distanceMatrix; import java.util.HashMap; import java.util.List; import java.util.Map; import com.github.TKnudsen.ComplexDataObject.model.distanceMeasure.IDistanceMeasure; /** * <p> * Title: DistanceMatrix * </p> * * <p> * Description: Stores and manages distances of pairs of objects (T's) * </p> * * <p> * Copyright: Copyright (c) 2017 * </p> * * @author Juergen Bernard * @version 1.04 */ public class DistanceMatrix<T> implements IDistanceMatrix<T> { // constructor properties protected List<T> objects; protected IDistanceMeasure<T> distanceMeasure; // storage, indexing protected double[][] distanceMatrix = null; protected Map<T, Integer> objectIndex; // statistics protected double min; protected double max; public DistanceMatrix(List<T> objects, IDistanceMeasure<T> distanceMeasure) { if (distanceMeasure == null) throw new IllegalArgumentException("DistanceMatrix: given distance measures was null"); this.objects = objects; this.distanceMeasure = distanceMeasure; initializeDistanceMatrix(); } protected void initializeObjectIndex() { // create index objectIndex = new HashMap<>(); for (int i = 0; i < objects.size(); i++) objectIndex.put(objects.get(i), i); } protected void initializeDistanceMatrix() { initializeObjectIndex(); distanceMatrix = new double[objectIndex.size()][objectIndex.size()]; for (int x = 0; x < distanceMatrix.length; x++) for (int y = 0; y < distanceMatrix[x].length; y++) distanceMatrix[x][y] = Double.NaN; min = Double.POSITIVE_INFINITY; max = Double.NEGATIVE_INFINITY; // create distance matrix - optimized for inheriting index-based access for (T t1 : objectIndex.keySet()) for (T t2 : objectIndex.keySet()) { double distance = distanceMeasure.getDistance(t1, t2); distanceMatrix[getObjectIndex(t1)][getObjectIndex(t2)] = distance; min = Math.min(min, distance); max = Math.max(max, distance); } // // create distance matrix - would be at least as good as the upper // // variant. but does not generalize for inheriting classes // for (int i = 0; i < objectIndex.size() - 1; i++) // for (int j = i; j < objectIndex.size(); j++) { // double d1 = distanceMeasure.getDistance(objects.get(i), // objects.get(j)); // double d2 = distanceMeasure.getDistance(objects.get(j), // objects.get(i)); // // distanceMatrix[i][j] = d1; // distanceMatrix[j][i] = d2; // // min = Math.min(min, d1); // min = Math.min(min, d2); // // max = Math.max(max, d1); // max = Math.max(max, d2); // } } protected Integer getObjectIndex(T object) { // if (objectIndex == null) // initializeDistanceMatrix(); return objectIndex.get(object); } @Override public double getDistance(T o1, T o2) { Integer index1 = getObjectIndex(o1); Integer index2 = getObjectIndex(o2); // better let it burn. it is a bad design if these indices would be null // if (index1 == null || index2 == null) // return distanceMeasure.getDistance(o1, o2); return getDistanceMatrix()[index1][index2]; } @Override public String getName() { return "Distance Matrix using " + distanceMeasure.toString(); } @Override public String getDescription() { return getName() + ", size: " + objects.size() + " x " + objects.size() + "."; } @Override public double applyAsDouble(T t, T u) { return getDistance(t, u); } @Override public double[][] getDistanceMatrix() { if (distanceMatrix == null) initializeDistanceMatrix(); return distanceMatrix; } public int size() { return objects.size(); } @Override public double getMinDistance() { return min; } @Override public double getMaxDistance() { return max; } }
distance matrix
src/main/java/com/github/TKnudsen/ComplexDataObject/data/distanceMatrix/DistanceMatrix.java
distance matrix
<ide><path>rc/main/java/com/github/TKnudsen/ComplexDataObject/data/distanceMatrix/DistanceMatrix.java <ide> package com.github.TKnudsen.ComplexDataObject.data.distanceMatrix; <ide> <add>import java.util.ArrayList; <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <ide> protected Map<T, Integer> objectIndex; <ide> <ide> // statistics <del> protected double min; <del> protected double max; <add> private double min; <add> private double max; <add> <add> // elements associated to statistics <add> private List<T> closestElements = new ArrayList<>(2); <add> private List<T> farestElements = new ArrayList<>(2); <ide> <ide> public DistanceMatrix(List<T> objects, IDistanceMeasure<T> distanceMeasure) { <ide> if (distanceMeasure == null) <ide> for (int y = 0; y < distanceMatrix[x].length; y++) <ide> distanceMatrix[x][y] = Double.NaN; <ide> <del> min = Double.POSITIVE_INFINITY; <del> max = Double.NEGATIVE_INFINITY; <add> updateMinDistance(Double.POSITIVE_INFINITY, null, null); <add> updateMaxDistance(Double.NEGATIVE_INFINITY, null, null); <ide> <ide> // create distance matrix - optimized for inheriting index-based access <ide> for (T t1 : objectIndex.keySet()) <ide> <ide> distanceMatrix[getObjectIndex(t1)][getObjectIndex(t2)] = distance; <ide> <del> min = Math.min(min, distance); <del> max = Math.max(max, distance); <add> if (getMin() > distance) { <add> updateMinDistance(distance, t1, t2); <add> } <add> <add> if (getMax() < distance) { <add> updateMaxDistance(distance, t1, t2); <add> } <add> <add> // min = Math.min(min, distance); <add> // max = Math.max(max, distance); <ide> } <ide> <ide> // // create distance matrix - would be at least as good as the upper <ide> } <ide> <ide> protected Integer getObjectIndex(T object) { <del>// if (objectIndex == null) <del>// initializeDistanceMatrix(); <add> // if (objectIndex == null) <add> // initializeDistanceMatrix(); <ide> <ide> return objectIndex.get(object); <ide> } <ide> <ide> @Override <ide> public double getMinDistance() { <add> return getMin(); <add> } <add> <add> @Override <add> public double getMaxDistance() { <add> return getMax(); <add> } <add> <add> public List<T> getClosestElements() { <add> return closestElements; <add> } <add> <add> public void setClosestElements(List<T> closestElements) { <add> this.closestElements = closestElements; <add> } <add> <add> public List<T> getFarestElements() { <add> return farestElements; <add> } <add> <add> public void setFarestElements(List<T> farestElements) { <add> this.farestElements = farestElements; <add> } <add> <add> public double getMin() { <ide> return min; <ide> } <ide> <del> @Override <del> public double getMaxDistance() { <add> /** <add> * sets the minimum distance between two elements. these elements are also <add> * queried. <add> * <add> * @param min <add> * @param t1 <add> * @param t2 <add> */ <add> public void updateMinDistance(double min, T t1, T t2) { <add> this.min = min; <add> <add> closestElements.clear(); <add> closestElements.add(t1); <add> closestElements.add(t2); <add> } <add> <add> public double getMax() { <ide> return max; <ide> } <add> <add> public void updateMaxDistance(double max, T t1, T t2) { <add> this.max = max; <add> <add> farestElements.clear(); <add> farestElements.add(t1); <add> farestElements.add(t2); <add> } <ide> }
Java
agpl-3.0
7f777a6202ca9eeffde4432a15f7c97531af4496
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
86ee9ab6-2e60-11e5-9284-b827eb9e62be
hello.java
86e9196a-2e60-11e5-9284-b827eb9e62be
86ee9ab6-2e60-11e5-9284-b827eb9e62be
hello.java
86ee9ab6-2e60-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>86e9196a-2e60-11e5-9284-b827eb9e62be <add>86ee9ab6-2e60-11e5-9284-b827eb9e62be
Java
apache-2.0
33f71e1250da5ab6afbd75010472265c22c996e7
0
argv0/cloudstack,cinderella/incubator-cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,jcshen007/cloudstack,resmo/cloudstack,mufaddalq/cloudstack-datera-driver,DaanHoogland/cloudstack,wido/cloudstack,mufaddalq/cloudstack-datera-driver,wido/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,cinderella/incubator-cloudstack,jcshen007/cloudstack,argv0/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,argv0/cloudstack,wido/cloudstack,resmo/cloudstack,argv0/cloudstack,mufaddalq/cloudstack-datera-driver,GabrielBrascher/cloudstack,mufaddalq/cloudstack-datera-driver,mufaddalq/cloudstack-datera-driver,cinderella/incubator-cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,cinderella/incubator-cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,mufaddalq/cloudstack-datera-driver,resmo/cloudstack,argv0/cloudstack,jcshen007/cloudstack,argv0/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,cinderella/incubator-cloudstack,resmo/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,DaanHoogland/cloudstack
/** * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. * * This software is licensed under the GNU General Public License v3 or later. * * It is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.cloud.storage; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.Formatter; 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.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.ejb.Local; import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.BackupSnapshotCommand; import com.cloud.agent.api.Command; import com.cloud.agent.api.CreateVolumeFromSnapshotAnswer; import com.cloud.agent.api.CreateVolumeFromSnapshotCommand; import com.cloud.agent.api.DeleteStoragePoolCommand; import com.cloud.agent.api.ManageSnapshotCommand; import com.cloud.agent.api.ModifyStoragePoolAnswer; import com.cloud.agent.api.ModifyStoragePoolCommand; import com.cloud.agent.api.storage.CopyVolumeAnswer; import com.cloud.agent.api.storage.CopyVolumeCommand; import com.cloud.agent.api.storage.CreateAnswer; import com.cloud.agent.api.storage.CreateCommand; import com.cloud.agent.api.storage.DeleteTemplateCommand; import com.cloud.agent.api.storage.DestroyCommand; import com.cloud.agent.api.to.StorageFilerTO; import com.cloud.agent.api.to.VolumeTO; import com.cloud.agent.manager.Commands; import com.cloud.alert.AlertManager; import com.cloud.api.BaseCmd; import com.cloud.api.ServerApiException; import com.cloud.api.commands.CancelPrimaryStorageMaintenanceCmd; import com.cloud.api.commands.CreateStoragePoolCmd; import com.cloud.api.commands.CreateVolumeCmd; import com.cloud.api.commands.DeletePoolCmd; import com.cloud.api.commands.DeleteVolumeCmd; import com.cloud.api.commands.PreparePrimaryStorageForMaintenanceCmd; import com.cloud.api.commands.UpdateStoragePoolCmd; import com.cloud.async.AsyncInstanceCreateStatus; import com.cloud.async.AsyncJobManager; import com.cloud.capacity.CapacityVO; import com.cloud.capacity.dao.CapacityDao; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ResourceCount.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.consoleproxy.ConsoleProxyManager; import com.cloud.dc.ClusterVO; import com.cloud.dc.DataCenterVO; import com.cloud.dc.HostPodVO; import com.cloud.dc.dao.ClusterDao; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.HostPodDao; import com.cloud.deploy.DeployDestination; import com.cloud.domain.Domain; import com.cloud.domain.dao.DomainDao; import com.cloud.event.Event; import com.cloud.event.EventTypes; import com.cloud.event.EventVO; import com.cloud.event.dao.EventDao; import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.DiscoveryException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InsufficientStorageCapacityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.OperationTimedoutException; import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceInUseException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.exception.StorageUnavailableException; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.Status; import com.cloud.host.dao.DetailsDao; import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.network.NetworkManager; import com.cloud.network.router.DomainRouterManager; import com.cloud.offering.ServiceOffering; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.Storage.StorageResourceType; import com.cloud.storage.Volume.MirrorState; import com.cloud.storage.Volume.SourceType; import com.cloud.storage.Volume.VolumeType; import com.cloud.storage.allocator.StoragePoolAllocator; import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.storage.dao.SnapshotDao; import com.cloud.storage.dao.StoragePoolDao; import com.cloud.storage.dao.StoragePoolHostDao; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VMTemplateHostDao; import com.cloud.storage.dao.VMTemplatePoolDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.listener.StoragePoolMonitor; import com.cloud.storage.secondary.SecondaryStorageVmManager; import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.storage.snapshot.SnapshotScheduler; import com.cloud.template.TemplateManager; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.User; import com.cloud.user.UserContext; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserDao; import com.cloud.uservm.UserVm; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.ExecutionException; import com.cloud.vm.DiskProfile; import com.cloud.vm.State; import com.cloud.vm.UserVmManager; import com.cloud.vm.UserVmVO; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.dao.ConsoleProxyDao; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; @Local(value = { StorageManager.class, StorageService.class }) public class StorageManagerImpl implements StorageManager, StorageService, Manager { private static final Logger s_logger = Logger.getLogger(StorageManagerImpl.class); protected String _name; @Inject protected UserVmManager _userVmMgr; @Inject protected AgentManager _agentMgr; @Inject protected TemplateManager _tmpltMgr; @Inject protected AsyncJobManager _asyncMgr; @Inject protected SnapshotManager _snapshotMgr; @Inject protected SnapshotScheduler _snapshotScheduler; @Inject protected AccountManager _accountMgr; @Inject protected ConfigurationManager _configMgr; @Inject protected ConsoleProxyManager _consoleProxyMgr; @Inject protected SecondaryStorageVmManager _secStorageMgr; @Inject protected NetworkManager _networkMgr; @Inject protected VolumeDao _volsDao; @Inject protected HostDao _hostDao; @Inject protected ConsoleProxyDao _consoleProxyDao; @Inject protected DetailsDao _detailsDao; @Inject protected SnapshotDao _snapshotDao; @Inject protected StoragePoolHostDao _storagePoolHostDao; @Inject protected AlertManager _alertMgr; @Inject protected VMTemplateHostDao _vmTemplateHostDao = null; @Inject protected VMTemplatePoolDao _vmTemplatePoolDao = null; @Inject protected VMTemplateDao _vmTemplateDao = null; @Inject protected StoragePoolHostDao _poolHostDao = null; @Inject protected UserVmDao _userVmDao; @Inject protected VMInstanceDao _vmInstanceDao; @Inject protected StoragePoolDao _storagePoolDao = null; @Inject protected CapacityDao _capacityDao; @Inject protected DiskOfferingDao _diskOfferingDao; @Inject protected AccountDao _accountDao; @Inject protected EventDao _eventDao = null; @Inject protected DataCenterDao _dcDao = null; @Inject protected HostPodDao _podDao = null; @Inject protected VMTemplateDao _templateDao; @Inject protected VMTemplateHostDao _templateHostDao; @Inject protected ServiceOfferingDao _offeringDao; @Inject protected DomainDao _domainDao; @Inject protected UserDao _userDao; @Inject protected ClusterDao _clusterDao; @Inject protected DomainRouterManager _routerMgr; @Inject(adapter=StoragePoolAllocator.class) protected Adapters<StoragePoolAllocator> _storagePoolAllocators; @Inject(adapter=StoragePoolDiscoverer.class) protected Adapters<StoragePoolDiscoverer> _discoverers; protected SearchBuilder<VMTemplateHostVO> HostTemplateStatesSearch; protected SearchBuilder<StoragePoolVO> PoolsUsedByVmSearch; ScheduledExecutorService _executor = null; boolean _storageCleanupEnabled; int _storageCleanupInterval; int _storagePoolAcquisitionWaitSeconds = 1800; // 30 minutes protected int _retry = 2; protected int _pingInterval = 60; // seconds protected int _hostRetry; protected int _overProvisioningFactor = 1; private int _maxVolumeSizeInGb; private int _totalRetries; private int _pauseInterval; private final boolean _shouldBeSnapshotCapable = true; @Override public boolean share(VMInstanceVO vm, List<VolumeVO> vols, HostVO host, boolean cancelPreviousShare) { //if pool is in maintenance and it is the ONLY pool available; reject List<VolumeVO> rootVolForGivenVm = _volsDao.findByInstanceAndType(vm.getId(), VolumeType.ROOT); if(rootVolForGivenVm != null && rootVolForGivenVm.size() > 0){ boolean isPoolAvailable = isPoolAvailable(rootVolForGivenVm.get(0).getPoolId()); if(!isPoolAvailable){ return false; } } //this check is done for maintenance mode for primary storage //if any one of the volume is unusable, we return false //if we return false, the allocator will try to switch to another PS if available for(VolumeVO vol: vols) { if(vol.getRemoved()!=null) { s_logger.warn("Volume id:"+vol.getId()+" is removed, cannot share on this instance"); //not ok to share return false; } } //ok to share return true; } @DB public List<VolumeVO> allocate(DiskProfile rootDisk, List<DiskProfile> dataDisks, VMInstanceVO vm, DataCenterVO dc, Account owner) { ArrayList<VolumeVO> vols = new ArrayList<VolumeVO>(dataDisks.size() + 1); VolumeVO dataVol = null; VolumeVO rootVol = null; long deviceId = 0; Transaction txn = Transaction.currentTxn(); txn.start(); rootVol = new VolumeVO(VolumeType.ROOT, rootDisk.getName(), dc.getId(), owner.getDomainId(), owner.getId(), rootDisk.getDiskOfferingId(), rootDisk.getSize()); if (rootDisk.getTemplateId() != null) { rootVol.setTemplateId(rootDisk.getTemplateId()); } rootVol.setInstanceId(vm.getId()); rootVol.setDeviceId(deviceId++); rootVol = _volsDao.persist(rootVol); vols.add(rootVol); for (DiskProfile dataDisk : dataDisks) { dataVol = new VolumeVO(VolumeType.DATADISK, dataDisk.getName(), dc.getId(), owner.getDomainId(), owner.getId(), dataDisk.getDiskOfferingId(), dataDisk.getSize()); dataVol.setDeviceId(deviceId++); dataVol.setInstanceId(vm.getId()); dataVol = _volsDao.persist(dataVol); vols.add(dataVol); } txn.commit(); return vols; } @Override public VolumeVO allocateIsoInstalledVm(VMInstanceVO vm, VMTemplateVO template, DiskOfferingVO rootOffering, Long size, DataCenterVO dc, Account account) { assert (template.getFormat() == ImageFormat.ISO) : "The template has to be ISO"; long rootId = _volsDao.getNextInSequence(Long.class, "volume_seq"); DiskProfile rootDisk = new DiskProfile(rootId, VolumeType.ROOT, "ROOT-" + vm.getId() + "-" + rootId, rootOffering.getId(), size != null ? size : rootOffering.getDiskSizeInBytes(), rootOffering.getTagsArray(), rootOffering.getUseLocalStorage(), rootOffering.isRecreatable(), null); List<VolumeVO> vols = allocate(rootDisk, null, vm, dc, account); return vols.get(0); } VolumeVO allocateDuplicateVolume(VolumeVO oldVol) { VolumeVO newVol = new VolumeVO(oldVol.getVolumeType(), oldVol.getName(), oldVol.getDataCenterId(), oldVol.getDomainId(), oldVol.getAccountId(), oldVol.getDiskOfferingId(), oldVol.getSize()); newVol.setTemplateId(oldVol.getTemplateId()); newVol.setDeviceId(oldVol.getDeviceId()); newVol.setInstanceId(oldVol.getInstanceId()); return _volsDao.persist(newVol); } private boolean isPoolAvailable(Long poolId){ //get list of all pools List<StoragePoolVO> pools = _storagePoolDao.listAll(); //if no pools or 1 pool which is in maintenance if(pools == null || pools.size() == 0 || (pools.size() == 1 && pools.get(0).getStatus().equals(Status.Maintenance) )){ return false; }else{ return true; } } @Override public List<VolumeVO> prepare(VMInstanceVO vm, HostVO host) { List<VolumeVO> vols = _volsDao.findCreatedByInstance(vm.getId()); List<VolumeVO> recreateVols = new ArrayList<VolumeVO>(vols.size()); for (VolumeVO vol : vols) { if (!vol.isRecreatable()) { return vols; } //if pool is in maintenance and it is the ONLY pool available; reject List<VolumeVO> rootVolForGivenVm = _volsDao.findByInstanceAndType(vm.getId(), VolumeType.ROOT); if(rootVolForGivenVm != null && rootVolForGivenVm.size() > 0){ boolean isPoolAvailable = isPoolAvailable(rootVolForGivenVm.get(0).getPoolId()); if(!isPoolAvailable){ return new ArrayList<VolumeVO>(); } } //if we have a system vm //get the storage pool //if pool is in prepareformaintenance //add to recreate vols, and continue if(vm.getType().equals(VirtualMachine.Type.ConsoleProxy) || vm.getType().equals(VirtualMachine.Type.DomainRouter) || vm.getType().equals(VirtualMachine.Type.SecondaryStorageVm)) { StoragePoolVO sp = _storagePoolDao.findById(vol.getPoolId()); if(sp!=null && sp.getStatus().equals(Status.PrepareForMaintenance)) { recreateVols.add(vol); continue; } } StoragePoolHostVO ph = _storagePoolHostDao.findByPoolHost(vol.getPoolId(), host.getId()); if (ph == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Must recreate " + vol + " since " + vol.getPoolId() + " has is not hooked up with host " + host.getId()); } recreateVols.add(vol); } } if (recreateVols.size() == 0) { s_logger.debug("No need to recreate the volumes"); return vols; } List<VolumeVO> createds = new ArrayList<VolumeVO>(recreateVols.size()); for (VolumeVO vol : recreateVols) { VolumeVO create = new VolumeVO(vol.getVolumeType(), vol.getInstanceId(), vol.getTemplateId(), vol.getName(), vol.getDataCenterId(), host.getPodId(), vol.getAccountId(), vol.getDomainId(), vol.isRecreatable()); create.setDiskOfferingId(vol.getDiskOfferingId()); create.setDeviceId(vol.getDeviceId()); create = _volsDao.persist(create); VMTemplateVO template = _templateDao.findById(create.getTemplateId()); DataCenterVO dc = _dcDao.findById(create.getDataCenterId()); HostPodVO pod = _podDao.findById(host.getPodId()); DiskOfferingVO diskOffering = null; diskOffering = _diskOfferingDao.findById(vol.getDiskOfferingId()); ServiceOfferingVO offering; if (vm instanceof UserVmVO) { offering = _offeringDao.findById(((UserVmVO)vm).getServiceOfferingId()); } else { offering = _offeringDao.findById(vol.getDiskOfferingId()); } VolumeVO created = createVolume(create, vm, template, dc, pod, host.getClusterId(), offering, diskOffering, new ArrayList<StoragePoolVO>(),0, template.getHypervisorType()); if (created == null) { break; } createds.add(created); } for (VolumeVO vol : recreateVols) { _volsDao.remove(vol.getId()); } return createds; } @Override public List<Pair<VolumeVO, StoragePoolVO>> isStoredOn(VMInstanceVO vm) { List<Pair<VolumeVO, StoragePoolVO>> lst = new ArrayList<Pair<VolumeVO, StoragePoolVO>>(); List<VolumeVO> vols = _volsDao.findByInstance(vm.getId()); for (VolumeVO vol : vols) { StoragePoolVO pool = _storagePoolDao.findById(vol.getPoolId()); lst.add(new Pair<VolumeVO, StoragePoolVO>(vol, pool)); } return lst; } @Override public boolean isLocalStorageActiveOnHost(Host host) { List<StoragePoolHostVO> storagePoolHostRefs = _storagePoolHostDao.listByHostId(host.getId()); for (StoragePoolHostVO storagePoolHostRef : storagePoolHostRefs) { StoragePoolVO storagePool = _storagePoolDao.findById(storagePoolHostRef.getPoolId()); if (storagePool.getPoolType() == StoragePoolType.LVM) { SearchBuilder<VolumeVO> volumeSB = _volsDao.createSearchBuilder(); volumeSB.and("poolId", volumeSB.entity().getPoolId(), SearchCriteria.Op.EQ); volumeSB.and("removed", volumeSB.entity().getRemoved(), SearchCriteria.Op.NULL); SearchBuilder<VMInstanceVO> activeVmSB = _vmInstanceDao.createSearchBuilder(); activeVmSB.and("state", activeVmSB.entity().getState(), SearchCriteria.Op.IN); volumeSB.join("activeVmSB", activeVmSB, volumeSB.entity().getInstanceId(), activeVmSB.entity().getId(), JoinBuilder.JoinType.INNER); SearchCriteria<VolumeVO> volumeSC = volumeSB.create(); volumeSC.setParameters("poolId", storagePool.getId()); volumeSC.setJoinParameters("activeVmSB", "state", new Object[] {State.Creating, State.Starting, State.Running, State.Stopping, State.Migrating}); List<VolumeVO> volumes = _volsDao.search(volumeSC, null); if (volumes.size() > 0) { return true; } } } return false; } @Override public List<VolumeVO> unshare(VMInstanceVO vm, HostVO host) { final List<VolumeVO> vols = _volsDao.findCreatedByInstance(vm.getId()); if (vols.size() == 0) { return vols; } return unshare(vm, vols, host) ? vols : null; } protected StoragePoolVO findStoragePool(DiskProfile dskCh, final DataCenterVO dc, HostPodVO pod, Long clusterId, final ServiceOffering offering, final VMInstanceVO vm, final VMTemplateVO template, final Set<StoragePool> avoid) { Enumeration<StoragePoolAllocator> en = _storagePoolAllocators.enumeration(); while (en.hasMoreElements()) { final StoragePoolAllocator allocator = en.nextElement(); final StoragePool pool = allocator.allocateToPool(dskCh, dc, pod, clusterId, vm, template, avoid); if (pool != null) { return (StoragePoolVO) pool; } } return null; } @Override public Long findHostIdForStoragePool(StoragePool pool) { List<StoragePoolHostVO> poolHosts = _poolHostDao.listByHostStatus(pool.getId(), Status.Up); if (poolHosts.size() == 0) { return null; } else { return poolHosts.get(0).getHostId(); } } @Override public Answer[] sendToPool(StoragePool pool, Commands cmds) { List<StoragePoolHostVO> poolHosts = _poolHostDao.listByHostStatus(pool.getId(), Status.Up); Collections.shuffle(poolHosts); for (StoragePoolHostVO poolHost: poolHosts) { try { Answer[] answerRet = _agentMgr.send(poolHost.getHostId(), cmds); return answerRet; } catch (AgentUnavailableException e) { s_logger.debug("Moving on because unable to send to " + poolHost.getHostId() + " due to " + e.getMessage()); } catch (OperationTimedoutException e) { s_logger.debug("Moving on because unable to send to " + poolHost.getHostId() + " due to " + e.getMessage()); } } if( !poolHosts.isEmpty() ) { s_logger.warn("Unable to send commands to the pool because we ran out of hosts to send to"); } return null; } @Override public Answer sendToPool(StoragePool pool, Command cmd) { Commands cmds = new Commands(cmd); Answer[] answers = sendToPool(pool, cmds); if (answers == null) { return null; } return answers[0]; } protected DiskProfile createDiskCharacteristics(VolumeVO volume, VMTemplateVO template, DataCenterVO dc, DiskOfferingVO diskOffering) { if (volume.getVolumeType() == VolumeType.ROOT && Storage.ImageFormat.ISO != template.getFormat()) { SearchCriteria<VMTemplateHostVO> sc = HostTemplateStatesSearch.create(); sc.setParameters("id", template.getId()); sc.setParameters("state", com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOADED); sc.setJoinParameters("host", "dcId", dc.getId()); List<VMTemplateHostVO> sss = _vmTemplateHostDao.search(sc, null); if (sss.size() == 0) { throw new CloudRuntimeException("Template " + template.getName() + " has not been completely downloaded to zone " + dc.getId()); } VMTemplateHostVO ss = sss.get(0); return new DiskProfile(volume.getId(), volume.getVolumeType(), volume.getName(), diskOffering.getId(), ss.getSize(), diskOffering.getTagsArray(), diskOffering.getUseLocalStorage(), diskOffering.isRecreatable(), Storage.ImageFormat.ISO != template.getFormat() ? template.getId() : null); } else { return new DiskProfile(volume.getId(), volume.getVolumeType(), volume.getName(), diskOffering.getId(), diskOffering.getDiskSizeInBytes(), diskOffering.getTagsArray(), diskOffering.getUseLocalStorage(), diskOffering.isRecreatable(), null); } } @Override public boolean canVmRestartOnAnotherServer(long vmId) { List<VolumeVO> vols = _volsDao.findCreatedByInstance(vmId); for (VolumeVO vol : vols) { if (!vol.isRecreatable() && !vol.getPoolType().isShared()) { return false; } } return true; } @DB protected Pair<VolumeVO, String> createVolumeFromSnapshot(VolumeVO volume, SnapshotVO snapshot, VMTemplateVO template, long virtualsize) { VolumeVO createdVolume = null; Long volumeId = volume.getId(); String volumeFolder = null; // Create the Volume object and save it so that we can return it to the user Account account = _accountDao.findById(volume.getAccountId()); final HashSet<StoragePool> poolsToAvoid = new HashSet<StoragePool>(); StoragePoolVO pool = null; boolean success = false; Set<Long> podsToAvoid = new HashSet<Long>(); Pair<HostPodVO, Long> pod = null; String volumeUUID = null; String details = null; DiskOfferingVO diskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId()); DataCenterVO dc = _dcDao.findById(volume.getDataCenterId()); DiskProfile dskCh = new DiskProfile(volume, diskOffering, template.getHypervisorType()); int retry = 0; // Determine what pod to store the volume in while ((pod = _agentMgr.findPod(null, null, dc, account.getId(), podsToAvoid)) != null) { podsToAvoid.add(pod.first().getId()); // Determine what storage pool to store the volume in while ((pool = findStoragePool(dskCh, dc, pod.first(), null, null, null, null, poolsToAvoid)) != null) { poolsToAvoid.add(pool); volumeFolder = pool.getPath(); if (s_logger.isDebugEnabled()) { s_logger.debug("Attempting to create volume from snapshotId: " + snapshot.getId() + " on storage pool " + pool.getName()); } // Get the newly created VDI from the snapshot. // This will return a null volumePath if it could not be created Pair<String, String> volumeDetails = createVDIFromSnapshot(UserContext.current().getUserId(), snapshot, pool); volumeUUID = volumeDetails.first(); details = volumeDetails.second(); if (volumeUUID != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Volume with UUID " + volumeUUID + " was created on storage pool " + pool.getName()); } success = true; break; // break out of the "find storage pool" loop } else { retry++; if( retry >= 3 ) { _volsDao.expunge(volumeId); String msg = "Unable to create volume from snapshot " + snapshot.getId() + " after retrying 3 times, due to " + details; s_logger.debug(msg); throw new CloudRuntimeException(msg); } } s_logger.warn("Unable to create volume on pool " + pool.getName() + ", reason: " + details); } if (success) { break; // break out of the "find pod" loop } } if( !success ) { _volsDao.expunge(volumeId); String msg = "Unable to create volume from snapshot " + snapshot.getId() + " due to " + details; s_logger.debug(msg); throw new CloudRuntimeException(msg); } // Update the volume in the database Transaction txn = Transaction.currentTxn(); txn.start(); createdVolume = _volsDao.findById(volumeId); if (success) { // Increment the number of volumes _accountMgr.incrementResourceCount(account.getId(), ResourceType.volume); createdVolume.setStatus(AsyncInstanceCreateStatus.Created); createdVolume.setPodId(pod.first().getId()); createdVolume.setPoolId(pool.getId()); createdVolume.setPoolType(pool.getPoolType()); createdVolume.setFolder(volumeFolder); createdVolume.setPath(volumeUUID); createdVolume.setDomainId(account.getDomainId()); createdVolume.setState(Volume.State.Ready); } else { createdVolume.setStatus(AsyncInstanceCreateStatus.Corrupted); createdVolume.setDestroyed(true); } _volsDao.update(volumeId, createdVolume); txn.commit(); return new Pair<VolumeVO, String>(createdVolume, details); } @DB protected VolumeVO createVolumeFromSnapshot(VolumeVO volume, long snapshotId, long startEventId) { EventVO event = new EventVO(); event.setUserId(UserContext.current().getUserId()); event.setAccountId(volume.getAccountId()); event.setType(EventTypes.EVENT_VOLUME_CREATE); event.setState(Event.State.Started); event.setStartId(startEventId); event.setDescription("Creating volume from snapshot with id: "+snapshotId); _eventDao.persist(event); // By default, assume failure. VolumeVO createdVolume = null; String details = null; Long volumeId = null; SnapshotVO snapshot = _snapshotDao.findById(snapshotId); // Precondition: snapshot is not null and not removed. Long origVolumeId = snapshot.getVolumeId(); VolumeVO originalVolume = _volsDao.findById(origVolumeId); // NOTE: Original volume could be destroyed and removed. VMTemplateVO template = null; if (originalVolume != null) { template = _templateDao.findById(originalVolume.getTemplateId()); } // everything went well till now DataCenterVO dc = _dcDao.findById(originalVolume.getDataCenterId()); Pair<VolumeVO, String> volumeDetails = createVolumeFromSnapshot(volume, snapshot, template, originalVolume.getSize()); createdVolume = volumeDetails.first(); if (createdVolume != null) { volumeId = createdVolume.getId(); } details = volumeDetails.second(); Transaction txn = Transaction.currentTxn(); txn.start(); // Create an event long templateId = -1; long diskOfferingId = -1; if(originalVolume.getTemplateId() != null){ templateId = originalVolume.getTemplateId(); } diskOfferingId = originalVolume.getDiskOfferingId(); long sizeMB = createdVolume.getSize()/(1024*1024); String poolName = _storagePoolDao.findById(createdVolume.getPoolId()).getName(); String eventParams = "id=" + volumeId +"\ndoId="+diskOfferingId+"\ntId="+templateId+"\ndcId="+originalVolume.getDataCenterId()+"\nsize="+sizeMB; event = new EventVO(); event.setAccountId(volume.getAccountId()); event.setUserId(UserContext.current().getUserId()); event.setType(EventTypes.EVENT_VOLUME_CREATE); event.setParameters(eventParams); event.setStartId(startEventId); event.setState(Event.State.Completed); if (createdVolume.getPath() != null) { event.setDescription("Created volume: "+ createdVolume.getName() + " with size: " + sizeMB + " MB in pool: " + poolName + " from snapshot id: " + snapshotId); event.setLevel(EventVO.LEVEL_INFO); } else { details = "CreateVolume From Snapshot for snapshotId: " + snapshotId + " failed at the backend, reason " + details; event.setDescription(details); event.setLevel(EventVO.LEVEL_ERROR); } _eventDao.persist(event); txn.commit(); return createdVolume; } protected Pair<String, String> createVDIFromSnapshot(long userId, SnapshotVO snapshot, StoragePoolVO pool) { String vdiUUID = null; Long volumeId = snapshot.getVolumeId(); VolumeVO volume = _volsDao.findById(volumeId); String primaryStoragePoolNameLabel = pool.getUuid(); // pool's uuid is actually the namelabel. String secondaryStoragePoolUrl = getSecondaryStorageURL(volume.getDataCenterId()); Long dcId = volume.getDataCenterId(); long accountId = volume.getAccountId(); String backedUpSnapshotUuid = snapshot.getBackupSnapshotId(); CreateVolumeFromSnapshotCommand createVolumeFromSnapshotCommand = new CreateVolumeFromSnapshotCommand(primaryStoragePoolNameLabel, secondaryStoragePoolUrl, dcId, accountId, volumeId, backedUpSnapshotUuid, snapshot.getName()); String basicErrMsg = "Failed to create volume from " + snapshot.getName() + " for volume: " + volume.getId(); CreateVolumeFromSnapshotAnswer answer = (CreateVolumeFromSnapshotAnswer) sendToHostsOnStoragePool(pool.getId(), createVolumeFromSnapshotCommand, basicErrMsg, _totalRetries, _pauseInterval, _shouldBeSnapshotCapable, null); if (answer != null && answer.getResult()) { vdiUUID = answer.getVdi(); } else if (answer != null) { s_logger.error(basicErrMsg); } return new Pair<String, String>(vdiUUID, basicErrMsg); } @Override @DB public VolumeVO createVolume(VolumeVO volume, VMInstanceVO vm, VMTemplateVO template, DataCenterVO dc, HostPodVO pod, Long clusterId, ServiceOfferingVO offering, DiskOfferingVO diskOffering, List<StoragePoolVO> avoids, long size, HypervisorType hyperType) { StoragePoolVO pool = null; final HashSet<StoragePool> avoidPools = new HashSet<StoragePool>(avoids); if(diskOffering != null && diskOffering.isCustomized()){ diskOffering.setDiskSize(size); } DiskProfile dskCh = null; if (volume.getVolumeType() == VolumeType.ROOT && Storage.ImageFormat.ISO != template.getFormat()) { dskCh = createDiskCharacteristics(volume, template, dc, offering); } else { dskCh = createDiskCharacteristics(volume, template, dc, diskOffering); } dskCh.setHyperType(hyperType); VolumeTO created = null; int retry = _retry; while (--retry >= 0) { created = null; long podId = pod.getId(); pod = _podDao.findById(podId); if (pod == null) { s_logger.warn("Unable to find pod " + podId + " when create volume " + volume.getName()); break; } pool = findStoragePool(dskCh, dc, pod, clusterId, offering, vm, template, avoidPools); if (pool == null) { s_logger.warn("Unable to find storage poll when create volume " + volume.getName()); break; } avoidPools.add(pool); if (s_logger.isDebugEnabled()) { s_logger.debug("Trying to create " + volume + " on " + pool); } CreateCommand cmd = null; VMTemplateStoragePoolVO tmpltStoredOn = null; if (volume.getVolumeType() == VolumeType.ROOT && Storage.ImageFormat.ISO != template.getFormat()) { tmpltStoredOn = _tmpltMgr.prepareTemplateForCreate(template, pool); if (tmpltStoredOn == null) { continue; } cmd = new CreateCommand(dskCh, tmpltStoredOn.getLocalDownloadPath(), new StorageFilerTO(pool)); } else { cmd = new CreateCommand(dskCh, new StorageFilerTO(pool)); } Answer answer = sendToPool(pool, cmd); if (answer != null && answer.getResult()) { created = ((CreateAnswer)answer).getVolume(); break; } s_logger.debug("Retrying the create because it failed on pool " + pool); } Transaction txn = Transaction.currentTxn(); txn.start(); if (created == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to create a volume for " + volume); } volume.setStatus(AsyncInstanceCreateStatus.Failed); volume.setDestroyed(true); _volsDao.persist(volume); _volsDao.remove(volume.getId()); volume = null; } else { volume.setStatus(AsyncInstanceCreateStatus.Created); volume.setFolder(pool.getPath()); volume.setPath(created.getPath()); volume.setSize(created.getSize()); volume.setPoolType(pool.getPoolType()); volume.setPoolId(pool.getId()); volume.setPodId(pod.getId()); volume.setState(Volume.State.Ready); _volsDao.persist(volume); } txn.commit(); return volume; } @Override public List<VolumeVO> create(Account account, VMInstanceVO vm, VMTemplateVO template, DataCenterVO dc, HostPodVO pod, ServiceOfferingVO offering, DiskOfferingVO diskOffering, long size) throws StorageUnavailableException, ExecutionException { List<StoragePoolVO> avoids = new ArrayList<StoragePoolVO>(); return create(account, vm, template, dc, pod, offering, diskOffering, avoids, size); } @DB protected List<VolumeVO> create(Account account, VMInstanceVO vm, VMTemplateVO template, DataCenterVO dc, HostPodVO pod, ServiceOfferingVO offering, DiskOfferingVO diskOffering, List<StoragePoolVO> avoids, long size) { ArrayList<VolumeVO> vols = new ArrayList<VolumeVO>(2); VolumeVO dataVol = null; VolumeVO rootVol = null; Transaction txn = Transaction.currentTxn(); txn.start(); if (Storage.ImageFormat.ISO == template.getFormat()) { rootVol = new VolumeVO(VolumeType.ROOT, vm.getId(), vm.getInstanceName() + "-ROOT", dc.getId(), pod.getId(), account.getId(), account.getDomainId(),(size>0)? size : diskOffering.getDiskSizeInBytes()); createStartedEvent(account, rootVol); rootVol.setDiskOfferingId(diskOffering.getId()); rootVol.setSourceType(SourceType.Template); rootVol.setSourceId(template.getId()); rootVol.setDeviceId(0l); rootVol = _volsDao.persist(rootVol); } else { rootVol = new VolumeVO(VolumeType.ROOT, vm.getId(), template.getId(), vm.getInstanceName() + "-ROOT", dc.getId(), pod.getId(), account.getId(), account.getDomainId(), offering.isRecreatable()); createStartedEvent(account, rootVol); rootVol.setDiskOfferingId(offering.getId()); rootVol.setTemplateId(template.getId()); rootVol.setSourceId(template.getId()); rootVol.setSourceType(SourceType.Template); rootVol.setDeviceId(0l); rootVol = _volsDao.persist(rootVol); if ((diskOffering != null && diskOffering.getDiskSizeInBytes() > 0) || (diskOffering != null && diskOffering.isCustomized())) { dataVol = new VolumeVO(VolumeType.DATADISK, vm.getId(), vm.getInstanceName() + "-DATA", dc.getId(), pod.getId(), account.getId(), account.getDomainId(), (size>0)? size : diskOffering.getDiskSizeInBytes()); createStartedEvent(account, dataVol); dataVol.setDiskOfferingId(diskOffering.getId()); dataVol.setSourceType(SourceType.DiskOffering); dataVol.setSourceId(diskOffering.getId()); dataVol.setDeviceId(1l); dataVol = _volsDao.persist(dataVol); } } txn.commit(); VolumeVO dataCreated = null; VolumeVO rootCreated = null; try { rootCreated = createVolume(rootVol, vm, template, dc, pod, null, offering, diskOffering, avoids,size, template.getHypervisorType()); if (rootCreated == null) { throw new CloudRuntimeException("Unable to create " + rootVol); } vols.add(rootCreated); if (dataVol != null) { StoragePoolVO pool = _storagePoolDao.findById(rootCreated.getPoolId()); dataCreated = createVolume(dataVol, vm, null, dc, pod, pool.getClusterId(), offering, diskOffering, avoids,size, template.getHypervisorType()); if (dataCreated == null) { throw new CloudRuntimeException("Unable to create " + dataVol); } vols.add(dataCreated); } return vols; } catch (Exception e) { if (s_logger.isDebugEnabled()) { s_logger.debug(e.getMessage()); } if (rootCreated != null) { destroyVolume(rootCreated); } throw new CloudRuntimeException("Unable to create volumes for " + vm, e); } } private void createStartedEvent(Account account, VolumeVO rootVol) { EventVO event1 = new EventVO(); event1.setAccountId(account.getId()); event1.setUserId(1L); event1.setType(EventTypes.EVENT_VOLUME_CREATE); event1.setState(Event.State.Started); event1.setDescription("Create volume: " + rootVol.getName()+ "started"); _eventDao.persist(event1); } @Override public long createUserVM(Account account, VMInstanceVO vm, VMTemplateVO template, DataCenterVO dc, HostPodVO pod, ServiceOfferingVO offering, DiskOfferingVO diskOffering, List<StoragePoolVO> avoids, long size) { List<VolumeVO> volumes = create(account, vm, template, dc, pod, offering, diskOffering, avoids, size); if( volumes == null || volumes.size() == 0) { throw new CloudRuntimeException("Unable to create volume for " + vm.getHostName()); } for (VolumeVO v : volumes) { //when the user vm is created, the volume is attached upon creation //set the attached datetime try{ v.setAttached(new Date()); _volsDao.update(v.getId(), v); }catch(Exception e) { s_logger.warn("Error updating the attached value for volume "+v.getId()+":"+e); } long templateId = -1; long doId = v.getDiskOfferingId(); if(v.getVolumeType() == VolumeType.ROOT && Storage.ImageFormat.ISO != template.getFormat()){ templateId = template.getId(); doId = -1; } long volumeId = v.getId(); // Create an event long sizeMB = v.getSize() / (1024 * 1024); String eventParams = "id=" + volumeId + "\ndoId=" + doId + "\ntId=" + templateId + "\ndcId=" + dc.getId() + "\nsize=" + sizeMB; EventVO event = new EventVO(); event.setAccountId(account.getId()); event.setUserId(1L); event.setType(EventTypes.EVENT_VOLUME_CREATE); event.setParameters(eventParams); event.setDescription("Created volume: " + v.getName() + " with size: " + sizeMB + " MB"); _eventDao.persist(event); } return volumes.get(0).getPoolId(); } public Long chooseHostForStoragePool(StoragePoolVO poolVO, List<Long> avoidHosts, boolean sendToVmResidesOn, Long vmId) { if (sendToVmResidesOn) { if (vmId != null) { VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId); if (vmInstance != null) { Long hostId = vmInstance.getHostId(); if (hostId != null && !avoidHosts.contains(vmInstance.getHostId())) { return hostId; } } } /*Can't find the vm where host resides on(vm is destroyed? or volume is detached from vm), randomly choose a host to send the cmd */ } List<StoragePoolHostVO> poolHosts = _poolHostDao.listByHostStatus(poolVO.getId(), Status.Up); Collections.shuffle(poolHosts); if (poolHosts != null && poolHosts.size() > 0) { for (StoragePoolHostVO sphvo : poolHosts) { if (!avoidHosts.contains(sphvo.getHostId())) { return sphvo.getHostId(); } } } return null; } @Override public String chooseStorageIp(VMInstanceVO vm, Host host, Host storage) { Enumeration<StoragePoolAllocator> en = _storagePoolAllocators.enumeration(); while (en.hasMoreElements()) { StoragePoolAllocator allocator = en.nextElement(); String ip = allocator.chooseStorageIp(vm, host, storage); if (ip != null) { return ip; } } assert false : "Hmm....fell thru the loop"; return null; } @Override public boolean unshare(VMInstanceVO vm, List<VolumeVO> vols, HostVO host) { if (s_logger.isDebugEnabled()) { s_logger.debug("Asking for volumes of " + vm.toString() + " to be unshared to " + (host != null ? host.toString() : "all")); } return true; } @Override public void destroy(VMInstanceVO vm, List<VolumeVO> vols) { if (s_logger.isDebugEnabled() && vm != null) { s_logger.debug("Destroying volumes of " + vm.toString()); } for (VolumeVO vol : vols) { _volsDao.detachVolume(vol.getId()); _volsDao.destroyVolume(vol.getId()); // First delete the entries in the snapshot_policy and // snapshot_schedule table for the volume. // They should not get executed after the volume is destroyed. _snapshotMgr.deletePoliciesForVolume(vol.getId()); String volumePath = vol.getPath(); Long poolId = vol.getPoolId(); if (poolId != null && volumePath != null && !volumePath.trim().isEmpty()) { Answer answer = null; StoragePoolVO pool = _storagePoolDao.findById(poolId); String vmName = null; if (vm != null) { vmName = vm.getInstanceName(); } final DestroyCommand cmd = new DestroyCommand(pool, vol, vmName); boolean removed = false; List<StoragePoolHostVO> poolhosts = _storagePoolHostDao.listByPoolId(poolId); for (StoragePoolHostVO poolhost : poolhosts) { answer = _agentMgr.easySend(poolhost.getHostId(), cmd); if (answer != null && answer.getResult()) { removed = true; break; } } if (removed) { _volsDao.remove(vol.getId()); } else { _alertMgr.sendAlert(AlertManager.ALERT_TYPE_STORAGE_MISC, vol.getDataCenterId(), vol.getPodId(), "Storage cleanup required for storage pool: " + pool.getName(), "Volume folder: " + vol.getFolder() + ", Volume Path: " + vol.getPath() + ", Volume id: " +vol.getId()+ ", Volume Name: " +vol.getName()+ ", Storage PoolId: " +vol.getPoolId()); s_logger.warn("destroy volume " + vol.getFolder() + " : " + vol.getPath() + " failed for Volume id : " +vol.getId()+ " Volume Name: " +vol.getName()+ " Storage PoolId : " +vol.getPoolId()); } } else { _volsDao.remove(vol.getId()); } } } @Override public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { _name = name; ComponentLocator locator = ComponentLocator.getCurrentLocator(); ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); if (configDao == null) { s_logger.error("Unable to get the configuration dao."); return false; } Map<String, String> configs = configDao.getConfiguration("management-server", params); String overProvisioningFactorStr = configs.get("storage.overprovisioning.factor"); if (overProvisioningFactorStr != null) { _overProvisioningFactor = Integer.parseInt(overProvisioningFactorStr); } _retry = NumbersUtil.parseInt(configs.get(Config.StartRetry.key()), 10); _pingInterval = NumbersUtil.parseInt(configs.get("ping.interval"), 60); _hostRetry = NumbersUtil.parseInt(configs.get("host.retry"), 2); _storagePoolAcquisitionWaitSeconds = NumbersUtil.parseInt(configs.get("pool.acquisition.wait.seconds"), 1800); s_logger.info("pool.acquisition.wait.seconds is configured as " + _storagePoolAcquisitionWaitSeconds + " seconds"); _totalRetries = NumbersUtil.parseInt(configDao.getValue("total.retries"), 2); _pauseInterval = 2*NumbersUtil.parseInt(configDao.getValue("ping.interval"), 60); _agentMgr.registerForHostEvents(new StoragePoolMonitor(this, _hostDao, _storagePoolDao), true, false, true); String storageCleanupEnabled = configs.get("storage.cleanup.enabled"); _storageCleanupEnabled = (storageCleanupEnabled == null) ? true : Boolean.parseBoolean(storageCleanupEnabled); String time = configs.get("storage.cleanup.interval"); _storageCleanupInterval = NumbersUtil.parseInt(time, 86400); String workers = configs.get("expunge.workers"); int wrks = NumbersUtil.parseInt(workers, 10); _executor = Executors.newScheduledThreadPool(wrks, new NamedThreadFactory("StorageManager-Scavenger")); boolean localStorage = Boolean.parseBoolean(configs.get(Config.UseLocalStorage.key())); if (localStorage) { _agentMgr.registerForHostEvents(ComponentLocator.inject(LocalStoragePoolListener.class), true, false, false); } String maxVolumeSizeInGbString = configDao.getValue("storage.max.volume.size"); _maxVolumeSizeInGb = NumbersUtil.parseInt(maxVolumeSizeInGbString, 2000); PoolsUsedByVmSearch = _storagePoolDao.createSearchBuilder(); SearchBuilder<VolumeVO> volSearch = _volsDao.createSearchBuilder(); PoolsUsedByVmSearch.join("volumes", volSearch, volSearch.entity().getPoolId(), PoolsUsedByVmSearch.entity().getId(), JoinBuilder.JoinType.INNER); volSearch.and("vm", volSearch.entity().getInstanceId(), SearchCriteria.Op.EQ); volSearch.and("status", volSearch.entity().getStatus(), SearchCriteria.Op.EQ); volSearch.done(); PoolsUsedByVmSearch.done(); HostTemplateStatesSearch = _vmTemplateHostDao.createSearchBuilder(); HostTemplateStatesSearch.and("id", HostTemplateStatesSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); HostTemplateStatesSearch.and("state", HostTemplateStatesSearch.entity().getDownloadState(), SearchCriteria.Op.EQ); SearchBuilder<HostVO> HostSearch = _hostDao.createSearchBuilder(); HostSearch.and("dcId", HostSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); HostTemplateStatesSearch.join("host", HostSearch, HostSearch.entity().getId(), HostTemplateStatesSearch.entity().getHostId(), JoinBuilder.JoinType.INNER); HostSearch.done(); HostTemplateStatesSearch.done(); return true; } public String getVolumeFolder(String parentDir, long accountId, String diskFolderName) { StringBuilder diskFolderBuilder = new StringBuilder(); Formatter diskFolderFormatter = new Formatter(diskFolderBuilder); diskFolderFormatter.format("%s/u%06d/%s", parentDir, accountId, diskFolderName); return diskFolderBuilder.toString(); } public String getRandomVolumeName() { return UUID.randomUUID().toString(); } @Override public boolean volumeOnSharedStoragePool(VolumeVO volume) { Long poolId = volume.getPoolId(); if (poolId == null) { return false; } else { StoragePoolVO pool = _storagePoolDao.findById(poolId); if (pool == null) { return false; } else { return pool.isShared(); } } } @Override public boolean volumeInactive(VolumeVO volume) { Long vmId = volume.getInstanceId(); if (vmId != null) { UserVm vm = _userVmDao.findById(vmId); if (vm == null) { return false; } if (!vm.getState().equals(State.Stopped)) { return false; } } return true; } @Override public String getVmNameOnVolume(VolumeVO volume) { Long vmId = volume.getInstanceId(); if (vmId != null) { VMInstanceVO vm = _vmInstanceDao.findById(vmId); if (vm == null) { return null; } return vm.getInstanceName(); } return null; } @Override public Pair<String, String> getAbsoluteIsoPath(long templateId, long dataCenterId) { String isoPath = null; List<HostVO> storageHosts = _hostDao.listBy(Host.Type.SecondaryStorage, dataCenterId); if (storageHosts != null) { for (HostVO storageHost : storageHosts) { VMTemplateHostVO templateHostVO = _vmTemplateHostDao.findByHostTemplate(storageHost.getId(), templateId); if (templateHostVO != null) { isoPath = storageHost.getStorageUrl() + "/" + templateHostVO.getInstallPath(); return new Pair<String, String>(isoPath, storageHost.getStorageUrl()); } } } return null; } @Override public String getSecondaryStorageURL(long zoneId) { // Determine the secondary storage URL HostVO secondaryStorageHost = _hostDao.findSecondaryStorageHost(zoneId); if (secondaryStorageHost == null) { return null; } return secondaryStorageHost.getStorageUrl(); } @Override public HostVO getSecondaryStorageHost(long zoneId) { return _hostDao.findSecondaryStorageHost(zoneId); } @Override public String getStoragePoolTags(long poolId) { return _configMgr.listToCsvTags(_storagePoolDao.searchForStoragePoolDetails(poolId, "true")); } @Override public String getName() { return _name; } @Override public boolean start() { if (_storageCleanupEnabled) { _executor.scheduleWithFixedDelay(new StorageGarbageCollector(), _storageCleanupInterval, _storageCleanupInterval, TimeUnit.SECONDS); } else { s_logger.debug("Storage cleanup is not enabled, so the storage cleanup thread is not being scheduled."); } return true; } @Override public boolean stop() { if (_storageCleanupEnabled) { _executor.shutdown(); } return true; } protected StorageManagerImpl() { } @Override @SuppressWarnings("rawtypes") public StoragePoolVO createPool(CreateStoragePoolCmd cmd) throws ResourceInUseException, IllegalArgumentException, UnknownHostException, ResourceAllocationException { Long clusterId = cmd.getClusterId(); Long podId = cmd.getPodId(); Map ds = cmd.getDetails(); if (clusterId != null && podId == null) { throw new ServerApiException(BaseCmd.PARAM_ERROR, "Cluster id requires pod id"); } Map<String, String> details = new HashMap<String, String>(); if (ds != null) { Collection detailsCollection = ds.values(); Iterator it = detailsCollection.iterator(); while (it.hasNext()) { HashMap d = (HashMap)it.next(); Iterator it2 = d.entrySet().iterator(); while (it2.hasNext()) { Map.Entry entry = (Map.Entry)it2.next(); details.put((String)entry.getKey(), (String)entry.getValue()); } } } //verify input parameters Long zoneId = cmd.getZoneId(); DataCenterVO zone = _dcDao.findById(cmd.getZoneId()); if (zone == null) { throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to find zone by id " + zoneId); } URI uri = null; try { uri = new URI(cmd.getUrl()); if (uri.getScheme() == null) { throw new ServerApiException(BaseCmd.PARAM_ERROR, "scheme is null " + cmd.getUrl() + ", add nfs:// as a prefix"); } else if (uri.getScheme().equalsIgnoreCase("nfs")) { String uriHost = uri.getHost(); String uriPath = uri.getPath(); if (uriHost == null || uriPath == null || uriHost.trim().isEmpty() || uriPath.trim().isEmpty()) { throw new ServerApiException(BaseCmd.PARAM_ERROR, "host or path is null, should be nfs://hostname/path"); } } } catch (URISyntaxException e) { throw new ServerApiException(BaseCmd.PARAM_ERROR, cmd.getUrl() + " is not a valid uri"); } String tags = cmd.getTags(); if (tags != null) { String[] tokens = tags.split(","); for (String tag : tokens) { tag = tag.trim(); if (tag.length() == 0) { continue; } details.put(tag, "true"); } } List<HostVO> hosts = null; if (clusterId != null) { hosts = _hostDao.listByCluster(clusterId); } else if (podId != null) { hosts = _hostDao.listByHostPod(podId); } else { hosts = _hostDao.listByDataCenter(zoneId); } String scheme = uri.getScheme(); String storageHost = uri.getHost(); String hostPath = uri.getPath(); int port = uri.getPort(); StoragePoolVO pool = null; if (s_logger.isDebugEnabled()) { s_logger.debug("createPool Params @ scheme - " +scheme+ " storageHost - " +storageHost+ " hostPath - " +hostPath+ " port - " +port); } if (scheme.equalsIgnoreCase("nfs")) { if (port == -1) { port = 2049; } pool = new StoragePoolVO(StoragePoolType.NetworkFilesystem, storageHost, port, hostPath); if (clusterId == null) { throw new IllegalArgumentException("NFS need to have clusters specified for XenServers"); } } else if (scheme.equalsIgnoreCase("file")) { if (port == -1) { port = 0; } pool = new StoragePoolVO(StoragePoolType.Filesystem, "localhost", 0, hostPath); } else if (scheme.equalsIgnoreCase("iscsi")) { String[] tokens = hostPath.split("/"); int lun = NumbersUtil.parseInt(tokens[tokens.length - 1], -1); if (port == -1) { port = 3260; } if (lun != -1) { if (clusterId == null) { throw new IllegalArgumentException("IscsiLUN need to have clusters specified"); } hostPath.replaceFirst("/", ""); pool = new StoragePoolVO(StoragePoolType.IscsiLUN, storageHost, port, hostPath); } else { Enumeration<StoragePoolDiscoverer> en = _discoverers.enumeration(); while (en.hasMoreElements()) { Map<StoragePoolVO, Map<String, String>> pools; try { pools = en.nextElement().find(cmd.getZoneId(), podId, uri, details); } catch (DiscoveryException e) { throw new IllegalArgumentException("Not enough information for discovery " + uri, e); } if (pools != null) { Map.Entry<StoragePoolVO, Map<String, String>> entry = pools.entrySet().iterator().next(); pool = entry.getKey(); details = entry.getValue(); break; } } } } else if (scheme.equalsIgnoreCase("iso")) { if (port == -1) { port = 2049; } pool = new StoragePoolVO(StoragePoolType.ISO, storageHost, port, hostPath); } else if (scheme.equalsIgnoreCase("vmfs")) { pool = new StoragePoolVO(StoragePoolType.VMFS, storageHost, 0, hostPath); } else { s_logger.warn("Unable to figure out the scheme for URI: " + uri); throw new IllegalArgumentException("Unable to figure out the scheme for URI: " + uri); } if (pool == null) { s_logger.warn("Unable to figure out the scheme for URI: " + uri); throw new IllegalArgumentException("Unable to figure out the scheme for URI: " + uri); } List<StoragePoolVO> pools = _storagePoolDao.listPoolByHostPath(storageHost, hostPath); if (!pools.isEmpty()) { Long oldPodId = pools.get(0).getPodId(); throw new ResourceInUseException("Storage pool " + uri + " already in use by another pod (id=" + oldPodId + ")", "StoragePool", uri.toASCIIString()); } // iterate through all the hosts and ask them to mount the filesystem. // FIXME Not a very scalable implementation. Need an async listener, or // perhaps do this on demand, or perhaps mount on a couple of hosts per // pod List<HostVO> allHosts = _hostDao.listBy(Host.Type.Routing, clusterId, podId, zoneId); if (allHosts.isEmpty()) { throw new ResourceAllocationException("No host exists to associate a storage pool with"); } long poolId = _storagePoolDao.getNextInSequence(Long.class, "id"); String uuid = UUID.nameUUIDFromBytes(new String(storageHost + hostPath).getBytes()).toString(); List<StoragePoolVO> spHandles = _storagePoolDao.findIfDuplicatePoolsExistByUUID(uuid); if ((spHandles != null) && (spHandles.size() > 0)) { if (s_logger.isDebugEnabled()) { s_logger.debug("Another active pool with the same uuid already exists"); } throw new ResourceInUseException("Another active pool with the same uuid already exists"); } if (s_logger.isDebugEnabled()) { s_logger.debug("In createPool Setting poolId - " +poolId+ " uuid - " +uuid+ " zoneId - " +zoneId+ " podId - " +podId+ " poolName - " + cmd.getStoragePoolName()); } pool.setId(poolId); pool.setUuid(uuid); pool.setDataCenterId(cmd.getZoneId()); pool.setPodId(podId); pool.setName(cmd.getStoragePoolName()); pool.setClusterId(clusterId); pool.setStatus(Status.Up); pool = _storagePoolDao.persist(pool, details); if (allHosts.isEmpty()) { return pool; } s_logger.debug("In createPool Adding the pool to each of the hosts"); List<HostVO> poolHosts = new ArrayList<HostVO>(); for (HostVO h : allHosts) { boolean success = addPoolToHost(h.getId(), pool); if (success) { poolHosts.add(h); } } if (poolHosts.isEmpty()) { _storagePoolDao.expunge(pool.getId()); pool = null; } else { createCapacityEntry(pool); } return pool; } @Override public StoragePoolVO updateStoragePool(UpdateStoragePoolCmd cmd) throws IllegalArgumentException { //Input validation Long id = cmd.getId(); String tags = cmd.getTags(); StoragePoolVO pool = _storagePoolDao.findById(id); if (pool == null) { throw new IllegalArgumentException("Unable to find storage pool with ID: " + id); } if (tags != null) { Map<String, String> details = _storagePoolDao.getDetails(id); String[] tagsList = tags.split(","); for (String tag : tagsList) { tag = tag.trim(); if (tag.length() > 0 && !details.containsKey(tag)) { details.put(tag, "true"); } } _storagePoolDao.updateDetails(id, details); } return pool; } @Override @DB public boolean deletePool(DeletePoolCmd command) throws InvalidParameterValueException{ Long id = command.getId(); boolean deleteFlag = false; //verify parameters StoragePoolVO sPool = _storagePoolDao.findById(id); if (sPool == null) { s_logger.warn("Unable to find pool:"+id); throw new InvalidParameterValueException("Unable to find pool by id " + id); } if (sPool.getPoolType().equals(StoragePoolType.LVM)) { s_logger.warn("Unable to delete local storage id:"+id); throw new InvalidParameterValueException("Unable to delete local storage id: " + id); } // for the given pool id, find all records in the storage_pool_host_ref List<StoragePoolHostVO> hostPoolRecords = _storagePoolHostDao.listByPoolId(id); // if not records exist, delete the given pool (base case) if (hostPoolRecords.size() == 0) { sPool.setUuid(null); _storagePoolDao.update(id, sPool); _storagePoolDao.remove(id); return true; } else { // 1. Check if the pool has associated volumes in the volumes table // 2. If it does, then you cannot delete the pool Pair<Long, Long> volumeRecords = _volsDao.getCountAndTotalByPool(id); if (volumeRecords.first() > 0) { s_logger.warn("Cannot delete pool "+sPool.getName()+" as there are associated vols for this pool"); return false; // cannot delete as there are associated vols } // 3. Else part, remove the SR associated with the Xenserver else { // First get the host_id from storage_pool_host_ref for given // pool id StoragePoolVO lock = _storagePoolDao.acquireInLockTable(sPool.getId()); try { if (lock == null) { if(s_logger.isDebugEnabled()) { s_logger.debug("Failed to acquire lock when deleting StoragePool with ID: " + sPool.getId()); } return false; } for (StoragePoolHostVO host : hostPoolRecords) { DeleteStoragePoolCommand cmd = new DeleteStoragePoolCommand(sPool); final Answer answer = _agentMgr.easySend(host.getHostId(), cmd); if (answer != null) { if (answer.getResult() == true) { deleteFlag = true; break; } } } } finally { if (lock != null) { _storagePoolDao.releaseFromLockTable(lock.getId()); } } if (deleteFlag) { // now delete the storage_pool_host_ref and storage_pool // records for (StoragePoolHostVO host : hostPoolRecords) { _storagePoolHostDao.deleteStoragePoolHostDetails(host.getHostId(),host.getPoolId()); } sPool.setUuid(null); _storagePoolDao.update(id, sPool); _storagePoolDao.remove(id); return true; } } } return false; } @Override public boolean addPoolToHost(long hostId, StoragePoolVO pool) { s_logger.debug("Adding pool " + pool.getName() + " to host " + hostId); if (pool.getPoolType() != StoragePoolType.NetworkFilesystem && pool.getPoolType() != StoragePoolType.Filesystem && pool.getPoolType() != StoragePoolType.IscsiLUN && pool.getPoolType() != StoragePoolType.Iscsi && pool.getPoolType() != StoragePoolType.VMFS) { return true; } ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand(true, pool); final Answer answer = _agentMgr.easySend(hostId, cmd); if (answer != null) { if (answer.getResult() == false) { String msg = "Add host failed due to ModifyStoragePoolCommand failed" + answer.getDetails(); _alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, pool.getDataCenterId(), pool.getPodId(), msg, msg); s_logger.warn(msg); return false; } if (answer instanceof ModifyStoragePoolAnswer) { ModifyStoragePoolAnswer mspAnswer = (ModifyStoragePoolAnswer) answer; StoragePoolHostVO poolHost = _poolHostDao.findByPoolHost(pool.getId(), hostId); if (poolHost == null) { poolHost = new StoragePoolHostVO(pool.getId(), hostId, mspAnswer.getPoolInfo().getLocalPath().replaceAll("//", "/")); _poolHostDao.persist(poolHost); } else { poolHost.setLocalPath(mspAnswer.getPoolInfo().getLocalPath().replaceAll("//", "/")); } pool.setAvailableBytes(mspAnswer.getPoolInfo().getAvailableBytes()); pool.setCapacityBytes(mspAnswer.getPoolInfo().getCapacityBytes()); _storagePoolDao.update(pool.getId(), pool); return true; } } else { return false; } return false; } @Override public VolumeVO moveVolume(VolumeVO volume, long destPoolDcId, Long destPoolPodId, Long destPoolClusterId) { // Find a destination storage pool with the specified criteria DiskOfferingVO diskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId()); DiskProfile dskCh = new DiskProfile(volume.getId(), volume.getVolumeType(), volume.getName(), diskOffering.getId(), diskOffering.getDiskSizeInBytes(), diskOffering.getTagsArray(), diskOffering.getUseLocalStorage(), diskOffering.isRecreatable(), null); DataCenterVO destPoolDataCenter = _dcDao.findById(destPoolDcId); HostPodVO destPoolPod = _podDao.findById(destPoolPodId); StoragePoolVO destPool = findStoragePool(dskCh, destPoolDataCenter, destPoolPod, destPoolClusterId, null, null, null, new HashSet<StoragePool>()); if (destPool == null) { throw new CloudRuntimeException("Failed to find a storage pool with enough capacity to move the volume to."); } StoragePoolVO srcPool = _storagePoolDao.findById(volume.getPoolId()); String secondaryStorageURL = getSecondaryStorageURL(volume.getDataCenterId()); String secondaryStorageVolumePath = null; // Find hosts where the source and destination storage pools are visible Long sourceHostId = findHostIdForStoragePool(srcPool); Long destHostId = findHostIdForStoragePool(destPool); if (sourceHostId == null) { throw new CloudRuntimeException("Failed to find a host where the source storage pool is visible."); } else if (destHostId == null) { throw new CloudRuntimeException("Failed to find a host where the dest storage pool is visible."); } // Copy the volume from the source storage pool to secondary storage CopyVolumeCommand cvCmd = new CopyVolumeCommand(volume.getId(), volume.getPath(), srcPool, secondaryStorageURL, true); CopyVolumeAnswer cvAnswer = (CopyVolumeAnswer) _agentMgr.easySend(sourceHostId, cvCmd); if (cvAnswer == null || !cvAnswer.getResult()) { throw new CloudRuntimeException("Failed to copy the volume from the source primary storage pool to secondary storage."); } secondaryStorageVolumePath = cvAnswer.getVolumePath(); // Copy the volume from secondary storage to the destination storage // pool cvCmd = new CopyVolumeCommand(volume.getId(), secondaryStorageVolumePath, destPool, secondaryStorageURL, false); cvAnswer = (CopyVolumeAnswer) _agentMgr.easySend(destHostId, cvCmd); if (cvAnswer == null || !cvAnswer.getResult()) { throw new CloudRuntimeException("Failed to copy the volume from secondary storage to the destination primary storage pool."); } String destPrimaryStorageVolumePath = cvAnswer.getVolumePath(); String destPrimaryStorageVolumeFolder = cvAnswer.getVolumeFolder(); // Delete the volume on the source storage pool final DestroyCommand cmd = new DestroyCommand(srcPool, volume, null); Answer destroyAnswer = _agentMgr.easySend(sourceHostId, cmd); if (destroyAnswer == null || !destroyAnswer.getResult()) { throw new CloudRuntimeException("Failed to delete the volume from the source primary storage pool."); } volume.setPath(destPrimaryStorageVolumePath); volume.setFolder(destPrimaryStorageVolumeFolder); volume.setPodId(destPool.getPodId()); volume.setPoolId(destPool.getId()); _volsDao.update(volume.getId(), volume); return _volsDao.findById(volume.getId()); } /*Just allocate a volume in the database, don't send the createvolume cmd to hypervisor. The volume will be finally created only when it's attached to a VM.*/ @Override public VolumeVO allocVolume(CreateVolumeCmd cmd) throws InvalidParameterValueException, PermissionDeniedException, ResourceAllocationException { // FIXME: some of the scheduled event stuff might be missing here... Account account = UserContext.current().getAccount(); String accountName = cmd.getAccountName(); Long domainId = cmd.getDomainId(); Account targetAccount = null; if ((account == null) || isAdmin(account.getType())) { // Admin API call if ((domainId != null) && (accountName != null)) { if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), domainId)) { throw new PermissionDeniedException("Unable to create volume in domain " + domainId + ", permission denied."); } targetAccount = _accountDao.findActiveAccount(accountName, domainId); } else { targetAccount = account; } // If the account is null, this means that the accountName and domainId passed in were invalid if (targetAccount == null) { throw new InvalidParameterValueException("Unable to find account with name: " + accountName + " and domain ID: " + domainId); } } else { targetAccount = account; } // check if the volume can be created for the user // Check that the resource limit for volumes won't be exceeded if (_accountMgr.resourceLimitExceeded(targetAccount, ResourceType.volume)) { ResourceAllocationException rae = new ResourceAllocationException("Maximum number of volumes for account: " + targetAccount.getAccountName() + " has been exceeded."); rae.setResourceType("volume"); throw rae; } Long zoneId = null; Long diskOfferingId = null; Long size = null; // validate input parameters before creating the volume if(cmd.getSnapshotId() == null && cmd.getDiskOfferingId() == null){ throw new InvalidParameterValueException("Either disk Offering Id or snapshot Id must be passed whilst creating volume"); } if (cmd.getSnapshotId() == null) { zoneId = cmd.getZoneId(); if ((zoneId == null)) { throw new InvalidParameterValueException("Missing parameter, zoneid must be specified."); } diskOfferingId = cmd.getDiskOfferingId(); size = cmd.getSize(); if ((diskOfferingId == null) && (size == null)) { throw new InvalidParameterValueException("Missing parameter(s),either a positive volume size or a valid disk offering id must be specified."); } else if ((diskOfferingId == null) && (size != null)) { boolean ok = validateVolumeSizeRange(size); if (!ok) { throw new InvalidParameterValueException("Invalid size for custom volume creation: " + size); } //this is the case of creating var size vol with private disk offering List<DiskOfferingVO> privateTemplateList = _diskOfferingDao.findPrivateDiskOffering(); diskOfferingId = privateTemplateList.get(0).getId(); //we use this id for creating volume } else { // Check that the the disk offering is specified DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId); if ((diskOffering == null) || !DiskOfferingVO.Type.Disk.equals(diskOffering.getType())) { throw new InvalidParameterValueException("Please specify a valid disk offering."); } if(diskOffering.getDomainId() == null){ //do nothing as offering is public }else{ _configMgr.checkDiskOfferingAccess(account, diskOffering); } if(!validateVolumeSizeRange(diskOffering.getDiskSize()/1024)){//convert size from mb to gb for validation throw new InvalidParameterValueException("Invalid size for custom volume creation: " + size+" ,max volume size is:"+_maxVolumeSizeInGb); } if(diskOffering.getDiskSize() > 0) { size = (diskOffering.getDiskSize()*1024*1024);//the disk offering size is in MB, which needs to be converted into bytes } else{ if(!validateVolumeSizeRange(size)){ throw new InvalidParameterValueException("Invalid size for custom volume creation: " + size+" ,max volume size is:"+_maxVolumeSizeInGb); } size = (size*1024*1024*1024);//custom size entered is in GB, to be converted to bytes } } } else { Long snapshotId = cmd.getSnapshotId(); Snapshot snapshotCheck = _snapshotDao.findById(snapshotId); if (snapshotCheck == null) { throw new ServerApiException (BaseCmd.PARAM_ERROR, "unable to find a snapshot with id " + snapshotId); } VolumeVO vol = _volsDao.findById(snapshotCheck.getVolumeId()); zoneId = vol.getDataCenterId(); diskOfferingId = vol.getDiskOfferingId(); size = vol.getSize(); if (account != null) { if (isAdmin(account.getType())) { Account snapshotOwner = _accountDao.findById(snapshotCheck.getAccountId()); if (!_domainDao.isChildDomain(account.getDomainId(), snapshotOwner.getDomainId())) { throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to create volume from snapshot with id " + snapshotId + ", permission denied."); } } else if (account.getId() != snapshotCheck.getAccountId()) { throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to find a snapshot with id " + snapshotId + " for this account"); } } } // Check that there is a shared primary storage pool in the specified zone List<StoragePoolVO> storagePools = _storagePoolDao.listByDataCenterId(zoneId); boolean sharedPoolExists = false; for (StoragePoolVO storagePool : storagePools) { if (storagePool.isShared()) { sharedPoolExists = true; } } // Check that there is at least one host in the specified zone List<HostVO> hosts = _hostDao.listByDataCenter(zoneId); if (hosts.isEmpty()) { throw new InvalidParameterValueException("Please add a host in the specified zone before creating a new volume."); } if (!sharedPoolExists) { throw new InvalidParameterValueException("Please specify a zone that has at least one shared primary storage pool."); } String userSpecifiedName = cmd.getVolumeName(); if (userSpecifiedName == null) { userSpecifiedName = getRandomVolumeName(); } VolumeVO volume = new VolumeVO(userSpecifiedName, -1, -1, -1, -1, new Long(-1), null, null, 0, Volume.VolumeType.DATADISK); volume.setPoolId(null); volume.setDataCenterId(zoneId); volume.setPodId(null); volume.setAccountId(targetAccount.getId()); volume.setDomainId(((account == null) ? Domain.ROOT_DOMAIN : account.getDomainId())); volume.setMirrorState(MirrorState.NOT_MIRRORED); volume.setDiskOfferingId(diskOfferingId); volume.setSize(size); volume.setStorageResourceType(StorageResourceType.STORAGE_POOL); volume.setInstanceId(null); volume.setUpdated(new Date()); volume.setStatus(AsyncInstanceCreateStatus.Creating); volume.setDomainId((account == null) ? Domain.ROOT_DOMAIN : account.getDomainId()); volume.setState(Volume.State.Allocated); volume = _volsDao.persist(volume); return volume; } @Override @DB public VolumeVO createVolume(CreateVolumeCmd cmd) { VolumeVO volume = _volsDao.findById(cmd.getEntityId()); // VolumeVO createdVolume = null; Long userId = UserContext.current().getUserId(); if (cmd.getSnapshotId() != null) { return createVolumeFromSnapshot(volume, cmd.getSnapshotId(), cmd.getStartEventId()); } else { DataCenterVO dc = _dcDao.findById(cmd.getZoneId()); DiskOfferingVO diskOffering = _diskOfferingDao.findById(cmd.getDiskOfferingId()); long sizeMB = diskOffering.getDiskSize(); /* VMTemplateVO template = _templateDao.findById(volume.getTemplateId()); long size = diskOffering.getDiskSize(); try { List<StoragePoolVO> poolsToAvoid = new ArrayList<StoragePoolVO>(); Set<Long> podsToAvoid = new HashSet<Long>(); Pair<HostPodVO, Long> pod = null; HypervisorType hypervisorType = ((template == null) ? HypervisorType.None : template.getHypervisorType()); while ((pod = _agentMgr.findPod(null, null, dc, volume.getAccountId(), podsToAvoid)) != null) { if ((createdVolume = createVolume(volume, null, null, dc, pod.first(), null, null, diskOffering, poolsToAvoid, size, hypervisorType)) != null) { break; } else { podsToAvoid.add(pod.first().getId()); } } */ // Create an event EventVO event = new EventVO(); event.setAccountId(volume.getAccountId()); event.setUserId(userId); event.setType(EventTypes.EVENT_VOLUME_CREATE); event.setStartId(cmd.getStartEventId()); /* Transaction txn = Transaction.currentTxn(); txn.start(); if (createdVolume != null) { */ // Increment the number of volumes // _accountMgr.incrementResourceCount(createdVolume.getAccountId(), ResourceType.volume); _accountMgr.incrementResourceCount(volume.getAccountId(), ResourceType.volume); VolumeVO volForUpdate = _volsDao.createForUpdate(); volForUpdate.setSourceId(diskOffering.getId()); volForUpdate.setSourceType(SourceType.DiskOffering); volForUpdate.setStatus(AsyncInstanceCreateStatus.Created); _volsDao.update(volume.getId(), volForUpdate); // Set event parameters // long sizeMB = createdVolume.getSize() / (1024 * 1024); // StoragePoolVO pool = _storagePoolDao.findById(createdVolume.getPoolId()); // String eventParams = "id=" + createdVolume.getId() + "\ndoId=" + diskOffering.getId() + "\ntId=" + -1 + "\ndcId=" + dc.getId() + "\nsize=" + sizeMB; String eventParams = "id=" + volume.getId() + "\ndoId=" + diskOffering.getId() + "\ntId=" + -1 + "\ndcId=" + dc.getId() + "\nsize=" + sizeMB; event.setLevel(EventVO.LEVEL_INFO); // event.setDescription("Created volume: " + createdVolume.getName() + " with size: " + sizeMB + " MB in pool: " + pool.getName()); // event.setDescription("Created volume: " + createdVolume.getName() + " with size: " + sizeMB + " MB"); event.setDescription("Created volume: " + volume.getName() + " with size: " + sizeMB + " MB"); event.setParameters(eventParams); event.setState(Event.State.Completed); _eventDao.persist(event); /* } else { event.setDescription("Unable to create a volume for " + volume); event.setLevel(EventVO.LEVEL_ERROR); event.setState(Event.State.Completed); _eventDao.persist(event); } txn.commit(); } catch (Exception e) { s_logger.error("Unhandled exception while creating volume " + volume.getName(), e); } */ } // return createdVolume; return _volsDao.findById(volume.getId()); } @Override @DB public void destroyVolume(VolumeVO volume) { Transaction txn = Transaction.currentTxn(); txn.start(); Long volumeId = volume.getId(); _volsDao.destroyVolume(volumeId); String eventParams = "id=" + volumeId; EventVO event = new EventVO(); event.setAccountId(volume.getAccountId()); event.setUserId(1L); event.setType(EventTypes.EVENT_VOLUME_DELETE); event.setParameters(eventParams); event.setDescription("Volume " +volume.getName()+ " deleted"); event.setLevel(EventVO.LEVEL_INFO); _eventDao.persist(event); // Delete the recurring snapshot policies for this volume. _snapshotMgr.deletePoliciesForVolume(volumeId); // Decrement the resource count for volumes _accountMgr.decrementResourceCount(volume.getAccountId(), ResourceType.volume); txn.commit(); } @Override public void createCapacityEntry(StoragePoolVO storagePool) { createCapacityEntry(storagePool, 0); } @Override public void createCapacityEntry(StoragePoolVO storagePool, long allocated) { SearchCriteria<CapacityVO> capacitySC = _capacityDao.createSearchCriteria(); capacitySC.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, storagePool.getId()); capacitySC.addAnd("dataCenterId", SearchCriteria.Op.EQ, storagePool.getDataCenterId()); capacitySC.addAnd("capacityType", SearchCriteria.Op.EQ, CapacityVO.CAPACITY_TYPE_STORAGE); List<CapacityVO> capacities = _capacityDao.search(capacitySC, null); if (capacities.size() == 0) { CapacityVO capacity = new CapacityVO(storagePool.getId(), storagePool.getDataCenterId(), storagePool.getPodId(), storagePool.getAvailableBytes(), storagePool.getCapacityBytes(), CapacityVO.CAPACITY_TYPE_STORAGE); _capacityDao.persist(capacity); } else { CapacityVO capacity = capacities.get(0); capacity.setTotalCapacity(storagePool.getCapacityBytes()); long used = storagePool.getCapacityBytes() - storagePool.getAvailableBytes(); if( used <= 0 ) { used = 0; } capacity.setUsedCapacity(used); _capacityDao.update(capacity.getId(), capacity); } s_logger.debug("Successfully set Capacity - " +storagePool.getCapacityBytes()+ " for CAPACITY_TYPE_STORAGE, DataCenterId - " +storagePool.getDataCenterId()+ ", HostOrPoolId - " +storagePool.getId()+ ", PodId " +storagePool.getPodId()); capacitySC = _capacityDao.createSearchCriteria(); capacitySC.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, storagePool.getId()); capacitySC.addAnd("dataCenterId", SearchCriteria.Op.EQ, storagePool.getDataCenterId()); capacitySC.addAnd("capacityType", SearchCriteria.Op.EQ, CapacityVO.CAPACITY_TYPE_STORAGE_ALLOCATED); capacities = _capacityDao.search(capacitySC, null); int provFactor = 1; if( storagePool.getPoolType() == StoragePoolType.NetworkFilesystem ) { provFactor = _overProvisioningFactor; } if (capacities.size() == 0) { CapacityVO capacity = new CapacityVO(storagePool.getId(), storagePool.getDataCenterId(), storagePool.getPodId(), allocated, storagePool.getCapacityBytes() * provFactor, CapacityVO.CAPACITY_TYPE_STORAGE_ALLOCATED); _capacityDao.persist(capacity); } else { CapacityVO capacity = capacities.get(0); long currCapacity = provFactor * storagePool.getCapacityBytes(); boolean update = false; if (capacity.getTotalCapacity() != currCapacity) { capacity.setTotalCapacity(currCapacity); update = true; } if ( allocated != 0 ) { capacity.setUsedCapacity(allocated); update = true; } if ( update ) { _capacityDao.update(capacity.getId(), capacity); } } s_logger.debug("Successfully set Capacity - " +storagePool.getCapacityBytes()* _overProvisioningFactor+ " for CAPACITY_TYPE_STORAGE_ALLOCATED, DataCenterId - " +storagePool.getDataCenterId()+ ", HostOrPoolId - " +storagePool.getId()+ ", PodId " +storagePool.getPodId()); } @Override public Answer sendToHostsOnStoragePool(Long poolId, Command cmd, String basicErrMsg) { return sendToHostsOnStoragePool(poolId, cmd, basicErrMsg, 1, 0, false, null); } @Override public Answer sendToHostsOnStoragePool(Long poolId, Command cmd, String basicErrMsg, int totalRetries, int pauseBeforeRetry, boolean shouldBeSnapshotCapable, Long vmId) { Answer answer = null; Long hostId = null; StoragePoolVO storagePool = _storagePoolDao.findById(poolId); List<Long> hostsToAvoid = new ArrayList<Long>(); int tryCount = 0; boolean sendToVmHost = sendToVmResidesOn(storagePool, cmd); if (chooseHostForStoragePool(storagePool, hostsToAvoid, sendToVmHost, vmId) == null) { // Don't just fail. The host could be reconnecting. // wait for some time for it to get connected // Wait for 3*ping.interval, since the code attempts a manual // reconnect after that timeout. try { Thread.sleep(3 * _pingInterval * 1000); } catch (InterruptedException e) { s_logger.error("Interrupted while waiting for any host on poolId: " + poolId + " to get connected. " + e.getMessage()); // continue. } } while ((hostId = chooseHostForStoragePool(storagePool, hostsToAvoid, sendToVmHost, vmId)) != null && tryCount++ < totalRetries) { String errMsg = basicErrMsg + " on host: " + hostId + " try: " + tryCount + ", reason: "; hostsToAvoid.add(hostId); try { HostVO hostVO = _hostDao.findById(hostId); if (shouldBeSnapshotCapable) { if (hostVO == null ) { continue; } } s_logger.debug("Trying to execute Command: " + cmd + " on host: " + hostId + " try: " + tryCount); // set 120 min timeout for storage related command answer = _agentMgr.send(hostId, cmd, 120*60*1000); if (answer != null && answer.getResult()) { return answer; } else { s_logger.warn(errMsg + ((answer != null) ? answer.getDetails() : "null")); Thread.sleep(pauseBeforeRetry * 1000); } } catch (AgentUnavailableException e1) { s_logger.warn(errMsg + e1.getMessage(), e1); } catch (OperationTimedoutException e1) { s_logger.warn(errMsg + e1.getMessage(), e1); } catch (InterruptedException e) { s_logger.warn(errMsg + e.getMessage(), e); } } s_logger.error(basicErrMsg + ", no hosts available to execute command: " + cmd); return answer; } protected class StorageGarbageCollector implements Runnable { public StorageGarbageCollector() { } @Override public void run() { try { s_logger.info("Storage Garbage Collection Thread is running."); GlobalLock scanLock = GlobalLock.getInternLock(this.getClass().getName()); try { if (scanLock.lock(3)) { try { cleanupStorage(true); } finally { scanLock.unlock(); } } } finally { scanLock.releaseRef(); } } catch (Exception e) { s_logger.error("Caught the following Exception", e); } } } @Override public void cleanupStorage(boolean recurring) { // Cleanup primary storage pools List<StoragePoolVO> storagePools = _storagePoolDao.listAll(); for (StoragePoolVO pool : storagePools) { try { if (recurring && pool.isLocal()) { continue; } List<VMTemplateStoragePoolVO> unusedTemplatesInPool = _tmpltMgr.getUnusedTemplatesInPool(pool); s_logger.debug("Storage pool garbage collector found " + unusedTemplatesInPool.size() + " templates to clean up in storage pool: " + pool.getName()); for (VMTemplateStoragePoolVO templatePoolVO : unusedTemplatesInPool) { if (templatePoolVO.getDownloadState() != VMTemplateStorageResourceAssoc.Status.DOWNLOADED) { s_logger.debug("Storage pool garbage collector is skipping templatePoolVO with ID: " + templatePoolVO.getId() + " because it is not completely downloaded."); continue; } if (!templatePoolVO.getMarkedForGC()) { templatePoolVO.setMarkedForGC(true); _vmTemplatePoolDao.update(templatePoolVO.getId(), templatePoolVO); s_logger.debug("Storage pool garbage collector has marked templatePoolVO with ID: " + templatePoolVO.getId() + " for garbage collection."); continue; } _tmpltMgr.evictTemplateFromStoragePool(templatePoolVO); } } catch (Exception e) { s_logger.warn("Problem cleaning up primary storage pool " + pool, e); } } // Cleanup secondary storage hosts List<HostVO> secondaryStorageHosts = _hostDao.listSecondaryStorageHosts(); for (HostVO secondaryStorageHost : secondaryStorageHosts) { try { long hostId = secondaryStorageHost.getId(); List<VMTemplateHostVO> destroyedTemplateHostVOs = _vmTemplateHostDao.listDestroyed(hostId); s_logger.debug("Secondary storage garbage collector found " + destroyedTemplateHostVOs.size() + " templates to cleanup on secondary storage host: " + secondaryStorageHost.getName()); for (VMTemplateHostVO destroyedTemplateHostVO : destroyedTemplateHostVOs) { if (!_tmpltMgr.templateIsDeleteable(destroyedTemplateHostVO)) { s_logger.debug("Not deleting template at: " + destroyedTemplateHostVO.getInstallPath()); continue; } String installPath = destroyedTemplateHostVO.getInstallPath(); if (installPath != null) { Answer answer = _agentMgr.easySend(hostId, new DeleteTemplateCommand(destroyedTemplateHostVO.getInstallPath())); if (answer == null || !answer.getResult()) { s_logger.debug("Failed to delete template at: " + destroyedTemplateHostVO.getInstallPath()); } else { _vmTemplateHostDao.remove(destroyedTemplateHostVO.getId()); s_logger.debug("Deleted template at: " + destroyedTemplateHostVO.getInstallPath()); } } else { _vmTemplateHostDao.remove(destroyedTemplateHostVO.getId()); } } } catch (Exception e) { s_logger.warn("problem cleaning up secondary storage " + secondaryStorageHost, e); } } List<VolumeVO> vols = _volsDao.listRemovedButNotDestroyed(); for (VolumeVO vol : vols) { try { Long poolId = vol.getPoolId(); Answer answer = null; StoragePoolVO pool = _storagePoolDao.findById(poolId); final DestroyCommand cmd = new DestroyCommand(pool, vol, null); answer = sendToPool(pool, cmd); if (answer != null && answer.getResult()) { s_logger.debug("Destroyed " + vol); vol.setDestroyed(true); _volsDao.update(vol.getId(), vol); } } catch (Exception e) { s_logger.warn("Unable to destroy " + vol.getId(), e); } } } @Override public StoragePoolVO getStoragePoolForVm(long vmId) { SearchCriteria<StoragePoolVO> sc = PoolsUsedByVmSearch.create(); sc.setJoinParameters("volumes", "vm", vmId); sc.setJoinParameters("volumes", "status", AsyncInstanceCreateStatus.Created.toString()); List<StoragePoolVO> sps= _storagePoolDao.search(sc, null); if( sps.size() == 0 ) { throw new RuntimeException("Volume is not created for VM " + vmId); } StoragePoolVO sp = sps.get(0); for (StoragePoolVO tsp: sps ) { // use the local storage pool to choose host, // shared storage pool should be in the same cluster as local storage pool if( tsp.isLocal()) { sp = tsp; break; } } return sp; } @Override public String getPrimaryStorageNameLabel(VolumeVO volume) { Long poolId = volume.getPoolId(); // poolId is null only if volume is destroyed, which has been checked before. assert poolId != null; StoragePoolVO storagePoolVO = _storagePoolDao.findById(poolId); assert storagePoolVO != null; return storagePoolVO.getUuid(); } @Override @DB public synchronized StoragePoolVO preparePrimaryStorageForMaintenance(PreparePrimaryStorageForMaintenanceCmd cmd) throws ServerApiException{ Long primaryStorageId = cmd.getId(); Long userId = UserContext.current().getUserId(); boolean restart = true; StoragePoolVO primaryStorage = null; try { Transaction.currentTxn(); //1. Get the primary storage record and perform validation check primaryStorage = _storagePoolDao.acquireInLockTable(primaryStorageId); if(primaryStorage == null){ String msg = "Unable to obtain lock on the storage pool in preparePrimaryStorageForMaintenance()"; s_logger.error(msg); throw new ResourceUnavailableException(msg); } if (!primaryStorage.getStatus().equals(Status.Up) && !primaryStorage.getStatus().equals(Status.ErrorInMaintenance)) { throw new InvalidParameterValueException("Primary storage with id " + primaryStorageId + " is not ready for migration, as the status is:" + primaryStorage.getStatus().toString()); } //set the pool state to prepare for maintenance primaryStorage.setStatus(Status.PrepareForMaintenance); _storagePoolDao.persist(primaryStorage); //check to see if other ps exist //if they do, then we can migrate over the system vms to them //if they dont, then just stop all vms on this one List<StoragePoolVO> upPools = _storagePoolDao.listPoolsByStatus(Status.Up); if(upPools == null || upPools.size() == 0) { restart = false; } //2. Get a list of all the volumes within this storage pool List<VolumeVO> allVolumes = _volsDao.findByPoolId(primaryStorageId); //3. Each volume has an instance associated with it, stop the instance if running for(VolumeVO volume : allVolumes) { VMInstanceVO vmInstance = _vmInstanceDao.findById(volume.getInstanceId()); if(vmInstance == null) { continue; } //shut down the running vms if(vmInstance.getState().equals(State.Running) || vmInstance.getState().equals(State.Starting)) { //if the instance is of type consoleproxy, call the console proxy if(vmInstance.getType().equals(VirtualMachine.Type.ConsoleProxy)) { //make sure it is not restarted again, update config to set flag to false _configMgr.updateConfiguration(userId, "consoleproxy.restart", "false"); //create a dummy event long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_PROXY_STOP, "stopping console proxy with Id: "+vmInstance.getId()); //call the consoleproxymanager if(!_consoleProxyMgr.stopProxy(vmInstance.getId(), eventId)) { String errorMsg = "There was an error stopping the console proxy id: "+vmInstance.getId()+" ,cannot enable storage maintenance"; s_logger.warn(errorMsg); primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new CloudRuntimeException(errorMsg); } else if(restart) { //create a dummy event long eventId1 = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_PROXY_START, "starting console proxy with Id: "+vmInstance.getId()); //Restore config val for consoleproxy.restart to true _configMgr.updateConfiguration(userId, "consoleproxy.restart", "true"); if(_consoleProxyMgr.startProxy(vmInstance.getId(), eventId1)==null) { String errorMsg = "There was an error starting the console proxy id: "+vmInstance.getId()+" on another storage pool, cannot enable primary storage maintenance"; s_logger.warn(errorMsg); primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new CloudRuntimeException(errorMsg); } } } //if the instance is of type uservm, call the user vm manager if(vmInstance.getType().equals(VirtualMachine.Type.User)) { //create a dummy event long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_VM_STOP, "stopping user vm with Id: "+vmInstance.getId()); if(!_userVmMgr.stopVirtualMachine(userId, vmInstance.getId(),eventId)) { String errorMsg = "There was an error stopping the user vm id: "+vmInstance.getId()+" ,cannot enable storage maintenance"; s_logger.warn(errorMsg); primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new CloudRuntimeException(errorMsg); } } //if the instance is of type secondary storage vm, call the secondary storage vm manager if(vmInstance.getType().equals(VirtualMachine.Type.SecondaryStorageVm)) { //create a dummy event long eventId1 = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_SSVM_STOP, "stopping ssvm with Id: "+vmInstance.getId()); if(!_secStorageMgr.stopSecStorageVm(vmInstance.getId(), eventId1)) { String errorMsg = "There was an error stopping the ssvm id: "+vmInstance.getId()+" ,cannot enable storage maintenance"; s_logger.warn(errorMsg); primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new CloudRuntimeException(errorMsg); } else if(restart) { //create a dummy event and restart the ssvm immediately long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_SSVM_START, "starting ssvm with Id: "+vmInstance.getId()); if(_secStorageMgr.startSecStorageVm(vmInstance.getId(), eventId)==null) { String errorMsg = "There was an error starting the ssvm id: "+vmInstance.getId()+" on another storage pool, cannot enable primary storage maintenance"; s_logger.warn(errorMsg); primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new CloudRuntimeException(errorMsg); } } } //if the instance is of type domain router vm, call the network manager if(vmInstance.getType().equals(VirtualMachine.Type.DomainRouter)) { //create a dummy event long eventId2 = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_ROUTER_STOP, "stopping domain router with Id: "+vmInstance.getId()); if(!_routerMgr.stopRouter(vmInstance.getId(), eventId2)) { String errorMsg = "There was an error stopping the domain router id: "+vmInstance.getId()+" ,cannot enable primary storage maintenance"; s_logger.warn(errorMsg); primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new CloudRuntimeException(errorMsg); } else if(restart) { //create a dummy event and restart the domr immediately long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_PROXY_START, "starting domr with Id: "+vmInstance.getId()); if(_routerMgr.startRouter(vmInstance.getId(), eventId)==null) { String errorMsg = "There was an error starting the domain router id: "+vmInstance.getId()+" on another storage pool, cannot enable primary storage maintenance"; s_logger.warn(errorMsg); primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new CloudRuntimeException(errorMsg); } } } } } //5. Update the status primaryStorage.setStatus(Status.Maintenance); _storagePoolDao.persist(primaryStorage); return _storagePoolDao.findById(primaryStorageId); } catch (Exception e) { if(e instanceof ResourceUnavailableException){ s_logger.error("Exception in enabling primary storage maintenance:",e); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, e.getMessage()); } if(e instanceof InvalidParameterValueException){ s_logger.error("Exception in enabling primary storage maintenance:",e); throw new ServerApiException(BaseCmd.PARAM_ERROR, e.getMessage()); } //for everything else s_logger.error("Exception in enabling primary storage maintenance:",e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); }finally{ _storagePoolDao.releaseFromLockTable(primaryStorage.getId()); } } private Long saveScheduledEvent(Long userId, Long accountId, String type, String description) { EventVO event = new EventVO(); event.setUserId(userId); event.setAccountId(accountId); event.setType(type); event.setState(Event.State.Scheduled); event.setDescription("Scheduled async job for "+description); event = _eventDao.persist(event); return event.getId(); } @Override @DB public synchronized StoragePoolVO cancelPrimaryStorageForMaintenance(CancelPrimaryStorageMaintenanceCmd cmd) throws ServerApiException{ Long primaryStorageId = cmd.getId(); Long userId = UserContext.current().getUserId(); StoragePoolVO primaryStorage = null; try { Transaction.currentTxn(); //1. Get the primary storage record and perform validation check primaryStorage = _storagePoolDao.acquireInLockTable(primaryStorageId); if(primaryStorage == null){ String msg = "Unable to obtain lock on the storage pool in cancelPrimaryStorageForMaintenance()"; s_logger.error(msg); throw new ResourceUnavailableException(msg); } if (primaryStorage.getStatus().equals(Status.Up)) { throw new StorageUnavailableException("Primary storage with id " + primaryStorageId + " is not ready to complete migration, as the status is:" + primaryStorage.getStatus().toString(), primaryStorageId); } //set state to cancelmaintenance primaryStorage.setStatus(Status.CancelMaintenance); _storagePoolDao.persist(primaryStorage); //2. Get a list of all the volumes within this storage pool List<VolumeVO> allVolumes = _volsDao.findByPoolId(primaryStorageId); //3. If the volume is not removed AND not destroyed, start the vm corresponding to it for(VolumeVO volume: allVolumes) { if((!volume.destroyed) && (volume.removed == null)) { VMInstanceVO vmInstance = _vmInstanceDao.findById(volume.getInstanceId()); if(vmInstance.getState().equals(State.Stopping) || vmInstance.getState().equals(State.Stopped)) { //if the instance is of type consoleproxy, call the console proxy if(vmInstance.getType().equals(VirtualMachine.Type.ConsoleProxy)) { //create a dummy event long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_PROXY_START, "starting console proxy with Id: "+vmInstance.getId()); if(_consoleProxyMgr.startProxy(vmInstance.getId(), eventId) == null) { String msg = "There was an error starting the console proxy id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance"; s_logger.warn(msg); throw new ResourceUnavailableException(msg); } } //if the instance is of type ssvm, call the ssvm manager if(vmInstance.getType().equals(VirtualMachine.Type.SecondaryStorageVm)) { //create a dummy event long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_SSVM_START, "starting ssvm with Id: "+vmInstance.getId()); if(_secStorageMgr.startSecStorageVm(vmInstance.getId(), eventId) == null) { String msg = "There was an error starting the ssvm id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance"; s_logger.warn(msg); throw new ResourceUnavailableException(msg); } } //if the instance is of type user vm, call the user vm manager if(vmInstance.getType().equals(VirtualMachine.Type.User)) { //create a dummy event long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_VM_START, "starting user vm with Id: "+vmInstance.getId()); try { if(_userVmMgr.start(vmInstance.getId(), eventId) == null) { String msg = "There was an error starting the user vm id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance"; s_logger.warn(msg); throw new ResourceUnavailableException(msg); } } catch (StorageUnavailableException e) { String msg = "There was an error starting the user vm id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance"; s_logger.warn(msg,e); throw new ResourceUnavailableException(msg); } catch (InsufficientCapacityException e) { String msg = "There was an error starting the user vm id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance"; s_logger.warn(msg,e); throw new ResourceUnavailableException(msg); } catch (ConcurrentOperationException e) { String msg = "There was an error starting the user vm id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance"; s_logger.warn(msg,e); primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new ResourceUnavailableException(msg); } catch (ExecutionException e) { String msg = "There was an error starting the user vm id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance"; s_logger.warn(msg,e); throw new ResourceUnavailableException(msg); } } } } } //Restore config val for consoleproxy.restart to true try { _configMgr.updateConfiguration(userId, "consoleproxy.restart", "true"); } catch (InvalidParameterValueException e) { String msg = "Error changing consoleproxy.restart back to false at end of cancel maintenance:"; s_logger.warn(msg,e); throw new ResourceUnavailableException(msg); } catch (CloudRuntimeException e) { String msg = "Error changing consoleproxy.restart back to false at end of cancel maintenance:"; s_logger.warn(msg,e); throw new ResourceUnavailableException(msg); } //Change the storage state back to up primaryStorage.setStatus(Status.Up); _storagePoolDao.persist(primaryStorage); return primaryStorage; } catch (Exception e) { if(e instanceof ResourceUnavailableException){ primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, e.getMessage()); } else if(e instanceof InvalidParameterValueException){ primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new ServerApiException(BaseCmd.PARAM_ERROR, e.getMessage()); } else{//all other exceptions primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); } }finally{ _storagePoolDao.releaseFromLockTable(primaryStorage.getId()); } } private boolean sendToVmResidesOn(StoragePoolVO storagePool, Command cmd) { ClusterVO cluster = _clusterDao.findById(storagePool.getClusterId()); if ((cluster.getHypervisorType() == HypervisorType.KVM) && ((cmd instanceof ManageSnapshotCommand) || (cmd instanceof BackupSnapshotCommand))) { return true; } else { return false; } } private boolean isAdmin(short accountType) { return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); } @Override public boolean deleteVolume(DeleteVolumeCmd cmd) throws InvalidParameterValueException { Account account = UserContext.current().getAccount(); Long volumeId = cmd.getId(); boolean isAdmin; if (account == null) { // Admin API call isAdmin = true; } else { // User API call isAdmin = isAdmin(account.getType()); } // Check that the volume ID is valid VolumeVO volume = _volsDao.findById(volumeId); if (volume == null) { throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find volume with ID: " + volumeId); } // If the account is not an admin, check that the volume is owned by the account that was passed in if (!isAdmin) { if (account.getId() != volume.getAccountId()) { throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find volume with ID: " + volumeId + " for account: " + account.getAccountName()); } } else if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), volume.getDomainId())) { throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to delete volume with id " + volumeId + ", permission denied."); } // Check that the volume is stored on shared storage // NOTE: We used to ensure the volume is on shared storage before deleting. However, this seems like an unnecessary check since all we allow // is deleting a detached volume. Is there a technical reason why the volume has to be on shared storage? If so, uncomment this...otherwise, // just delete the detached volume regardless of storage pool. // if (!volumeOnSharedStoragePool(volume)) { // throw new InvalidParameterValueException("Please specify a volume that has been created on a shared storage pool."); // } // Check that the volume is not currently attached to any VM if (volume.getInstanceId() != null) { throw new InvalidParameterValueException("Please specify a volume that is not attached to any VM."); } // Check that the volume is not already destroyed if (volume.getDestroyed()) { throw new InvalidParameterValueException("Please specify a volume that is not already destroyed."); } try { // Destroy the volume destroyVolume(volume); } catch (Exception e) { s_logger.warn("Error destroying volume:"+e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Error destroying volume:"+e); } return true; } private boolean validateVolumeSizeRange(long size) throws InvalidParameterValueException { if (size<0 || (size>0 && size < 1)) { throw new InvalidParameterValueException("Please specify a size of at least 1 Gb."); } else if (size > _maxVolumeSizeInGb) { throw new InvalidParameterValueException("The maximum size allowed is " + _maxVolumeSizeInGb + " Gb."); } return true; } protected DiskProfile toDiskProfile(VolumeVO vol, DiskOfferingVO offering) { return new DiskProfile(vol.getId(), vol.getVolumeType(), vol.getName(), offering.getId(), vol.getSize(), offering.getTagsArray(), offering.getUseLocalStorage(), offering.isRecreatable(), vol.getTemplateId()); } @Override public <T extends VMInstanceVO> DiskProfile allocateRawVolume(VolumeType type, String name, DiskOfferingVO offering, Long size, T vm, Account owner) { if (size == null) { size = offering.getDiskSizeInBytes(); } VolumeVO vol = new VolumeVO(type, name, vm.getDataCenterId(), owner.getDomainId(), owner.getId(), offering.getId(), size); if (vm != null) { vol.setInstanceId(vm.getId()); } if(type.equals(VolumeType.ROOT)) { vol.setDeviceId(0l); } else { vol.setDeviceId(1l); } vol = _volsDao.persist(vol); return toDiskProfile(vol, offering); } @Override public <T extends VMInstanceVO> DiskProfile allocateTemplatedVolume(VolumeType type, String name, DiskOfferingVO offering, VMTemplateVO template, T vm, Account owner) { assert (template.getFormat() != ImageFormat.ISO) : "ISO is not a template really...."; SearchCriteria<VMTemplateHostVO> sc = HostTemplateStatesSearch.create(); sc.setParameters("id", template.getId()); sc.setParameters("state", com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOADED); sc.setJoinParameters("host", "dcId", vm.getDataCenterId()); List<VMTemplateHostVO> sss = _vmTemplateHostDao.search(sc, null); if (sss.size() == 0) { throw new CloudRuntimeException("Template " + template.getName() + " has not been completely downloaded to zone " + vm.getDataCenterId()); } VMTemplateHostVO ss = sss.get(0); VolumeVO vol = new VolumeVO(type, name, vm.getDataCenterId(), owner.getDomainId(), owner.getId(), offering.getId(), ss.getSize()); if (vm != null) { vol.setInstanceId(vm.getId()); } vol.setTemplateId(template.getId()); if(type.equals(VolumeType.ROOT)) { vol.setDeviceId(0l); } else { vol.setDeviceId(1l); } vol = _volsDao.persist(vol); return toDiskProfile(vol, offering); } final protected DiskProfile createDiskCharacteristics(VolumeVO volume, DiskOfferingVO offering) { return new DiskProfile(volume.getId(), volume.getVolumeType(), volume.getName(), offering.getId(), volume.getSize(), offering.getTagsArray(), offering.getUseLocalStorage(), offering.isRecreatable(), volume.getTemplateId()); } final protected DiskProfile createDiskCharacteristics(VolumeVO volume) { DiskOfferingVO offering = _diskOfferingDao.findById(volume.getDiskOfferingId()); return createDiskCharacteristics(volume, offering); } protected StoragePool findStorage(DiskProfile dskCh, DeployDestination dest, VirtualMachineProfile vm, List<? extends Volume> alreadyAllocated, Set<? extends StoragePool> avoid) { for (StoragePoolAllocator allocator : _storagePoolAllocators) { StoragePool pool = allocator.allocateTo(dskCh, vm, dest, alreadyAllocated, avoid); if (pool != null) { return pool; } } return null; } @Override public void prepare(VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest) throws StorageUnavailableException, InsufficientStorageCapacityException { List<VolumeVO> vols = _volsDao.findUsableVolumesForInstance(vm.getId()); if (s_logger.isDebugEnabled()) { s_logger.debug("Preparing " + vols.size() + " volumes for " + vm); } List<VolumeVO> recreateVols = new ArrayList<VolumeVO>(vols.size()); int i = 0; for (VolumeVO vol : vols) { Volume.State state = vol.getState(); if (state == Volume.State.Ready) { StoragePoolVO pool = _storagePoolDao.findById(vol.getPoolId()); if (pool.getRemoved() != null || pool.isInMaintenance()) { if (vol.isRecreatable()) { if (s_logger.isDebugEnabled()) { s_logger.debug("Volume " + vol + " has to be recreated due to storage pool " + pool + " is unavailable"); } recreateVols.add(vol); } else { throw new StorageUnavailableException("Volume " + vol + " is not available on the storage pool.", pool.getId()); } } else { if (s_logger.isDebugEnabled()) { s_logger.debug("Volume " + vol + " is ready."); } vm.addDisk(new VolumeTO(vol, pool)); } } else if (state == Volume.State.Allocated) { if (s_logger.isDebugEnabled()) { s_logger.debug("Creating volume " + vol + " for the first time."); } recreateVols.add(vol); } else { throw new StorageUnavailableException("Volume " + vol + " can not be used", vol.getPoolId()); } } for (VolumeVO vol : recreateVols) { VolumeVO newVol; if (vol.getState() == Volume.State.Allocated) { newVol = vol; } else { newVol = switchVolume(vol); if (s_logger.isDebugEnabled()) { s_logger.debug("Created new volume " + newVol + " for old volume " + vol); } } try { _volsDao.update(newVol, Volume.Event.Create); } catch(ConcurrentOperationException e) { throw new StorageUnavailableException("Unable to create " + newVol, newVol.getPoolId()); } Pair<VolumeTO, StoragePool> created = createVolume(newVol, _diskOfferingDao.findById(newVol.getDiskOfferingId()), vm, vols, dest); if (created == null) { newVol.setPoolId(null); try { _volsDao.update(newVol, Volume.Event.OperationFailed); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to update the failure on a volume: " + newVol, e); } throw new StorageUnavailableException("Unable to create " + newVol, newVol.getPoolId()); } created.first().setDeviceId(newVol.getDeviceId().intValue()); newVol.setStatus(AsyncInstanceCreateStatus.Created); newVol.setFolder(created.second().getPath()); newVol.setPath(created.first().getPath()); newVol.setSize(created.first().getSize()); newVol.setPoolType(created.second().getPoolType()); newVol.setPodId(created.second().getPodId()); try { _volsDao.update(newVol, Volume.Event.OperationSucceeded); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to update an CREATE operation succeeded on volume " + newVol, e); } if (s_logger.isDebugEnabled()) { s_logger.debug("Volume " + newVol + " is created on " + created.second()); } vm.addDisk(created.first()); } } @DB protected VolumeVO switchVolume(VolumeVO existingVolume) throws StorageUnavailableException { Transaction txn = Transaction.currentTxn(); try { txn.start(); _volsDao.update(existingVolume, Volume.Event.Destroy); VolumeVO newVolume = allocateDuplicateVolume(existingVolume); txn.commit(); return newVolume; } catch (ConcurrentOperationException e) { throw new StorageUnavailableException("Unable to duplicate the volume " + existingVolume, existingVolume.getPoolId(), e); } } public Pair<VolumeTO, StoragePool> createVolume(VolumeVO toBeCreated, DiskOfferingVO offering, VirtualMachineProfile<? extends VirtualMachine> vm, List<? extends Volume> alreadyCreated, DeployDestination dest) { if (s_logger.isDebugEnabled()) { s_logger.debug("Creating volume: " + toBeCreated); } DiskProfile diskProfile = new DiskProfile(toBeCreated, offering, vm.getHypervisorType()); VMTemplateVO template = null; if (toBeCreated.getTemplateId() != null) { template = _templateDao.findById(toBeCreated.getTemplateId()); } Set<StoragePool> avoids = new HashSet<StoragePool>(); StoragePool pool = null; while ((pool = findStorage(diskProfile, dest, vm, alreadyCreated, avoids)) != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Trying to create in " + pool); } avoids.add(pool); toBeCreated.setPoolId(pool.getId()); try { _volsDao.update(toBeCreated, Volume.Event.OperationRetry); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to retry a create operation on volume " + toBeCreated); } CreateCommand cmd = null; if (template != null && template.getFormat() != Storage.ImageFormat.ISO) { VMTemplateStoragePoolVO tmpltStoredOn = null; tmpltStoredOn = _tmpltMgr.prepareTemplateForCreate(template, pool); if (tmpltStoredOn == null) { s_logger.debug("Skipping " + pool + " because we can't propragate template " + template); continue; } cmd = new CreateCommand(diskProfile, tmpltStoredOn.getLocalDownloadPath(), new StorageFilerTO(pool)); } else { cmd = new CreateCommand(diskProfile, new StorageFilerTO(pool)); } Answer answer = sendToPool(pool, cmd); if (answer.getResult()) { CreateAnswer createAnswer = (CreateAnswer)answer; return new Pair<VolumeTO, StoragePool>(createAnswer.getVolume(), pool); } } if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to create volume " + toBeCreated); } return null; } @Override public void release(VirtualMachineProfile profile) { // Right now we don't do anything. } }
server/src/com/cloud/storage/StorageManagerImpl.java
/** * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. * * This software is licensed under the GNU General Public License v3 or later. * * It is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.cloud.storage; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.Formatter; 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.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.ejb.Local; import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.BackupSnapshotCommand; import com.cloud.agent.api.Command; import com.cloud.agent.api.CreateVolumeFromSnapshotAnswer; import com.cloud.agent.api.CreateVolumeFromSnapshotCommand; import com.cloud.agent.api.DeleteStoragePoolCommand; import com.cloud.agent.api.ManageSnapshotCommand; import com.cloud.agent.api.ModifyStoragePoolAnswer; import com.cloud.agent.api.ModifyStoragePoolCommand; import com.cloud.agent.api.storage.CopyVolumeAnswer; import com.cloud.agent.api.storage.CopyVolumeCommand; import com.cloud.agent.api.storage.CreateAnswer; import com.cloud.agent.api.storage.CreateCommand; import com.cloud.agent.api.storage.DeleteTemplateCommand; import com.cloud.agent.api.storage.DestroyCommand; import com.cloud.agent.api.to.StorageFilerTO; import com.cloud.agent.api.to.VolumeTO; import com.cloud.agent.manager.Commands; import com.cloud.alert.AlertManager; import com.cloud.api.BaseCmd; import com.cloud.api.ServerApiException; import com.cloud.api.commands.CancelPrimaryStorageMaintenanceCmd; import com.cloud.api.commands.CreateStoragePoolCmd; import com.cloud.api.commands.CreateVolumeCmd; import com.cloud.api.commands.DeletePoolCmd; import com.cloud.api.commands.DeleteVolumeCmd; import com.cloud.api.commands.PreparePrimaryStorageForMaintenanceCmd; import com.cloud.api.commands.UpdateStoragePoolCmd; import com.cloud.async.AsyncInstanceCreateStatus; import com.cloud.async.AsyncJobManager; import com.cloud.capacity.CapacityVO; import com.cloud.capacity.dao.CapacityDao; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ResourceCount.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.consoleproxy.ConsoleProxyManager; import com.cloud.dc.ClusterVO; import com.cloud.dc.DataCenterVO; import com.cloud.dc.HostPodVO; import com.cloud.dc.dao.ClusterDao; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.HostPodDao; import com.cloud.deploy.DeployDestination; import com.cloud.domain.Domain; import com.cloud.domain.dao.DomainDao; import com.cloud.event.Event; import com.cloud.event.EventTypes; import com.cloud.event.EventVO; import com.cloud.event.dao.EventDao; import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.DiscoveryException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InsufficientStorageCapacityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.OperationTimedoutException; import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceInUseException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.exception.StorageUnavailableException; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.Status; import com.cloud.host.dao.DetailsDao; import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.network.NetworkManager; import com.cloud.network.router.DomainRouterManager; import com.cloud.offering.ServiceOffering; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.Storage.StorageResourceType; import com.cloud.storage.Volume.MirrorState; import com.cloud.storage.Volume.SourceType; import com.cloud.storage.Volume.VolumeType; import com.cloud.storage.allocator.StoragePoolAllocator; import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.storage.dao.SnapshotDao; import com.cloud.storage.dao.StoragePoolDao; import com.cloud.storage.dao.StoragePoolHostDao; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VMTemplateHostDao; import com.cloud.storage.dao.VMTemplatePoolDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.listener.StoragePoolMonitor; import com.cloud.storage.secondary.SecondaryStorageVmManager; import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.storage.snapshot.SnapshotScheduler; import com.cloud.template.TemplateManager; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.User; import com.cloud.user.UserContext; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserDao; import com.cloud.uservm.UserVm; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.ExecutionException; import com.cloud.vm.DiskProfile; import com.cloud.vm.State; import com.cloud.vm.UserVmManager; import com.cloud.vm.UserVmVO; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.dao.ConsoleProxyDao; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; @Local(value = { StorageManager.class, StorageService.class }) public class StorageManagerImpl implements StorageManager, StorageService, Manager { private static final Logger s_logger = Logger.getLogger(StorageManagerImpl.class); protected String _name; @Inject protected UserVmManager _userVmMgr; @Inject protected AgentManager _agentMgr; @Inject protected TemplateManager _tmpltMgr; @Inject protected AsyncJobManager _asyncMgr; @Inject protected SnapshotManager _snapshotMgr; @Inject protected SnapshotScheduler _snapshotScheduler; @Inject protected AccountManager _accountMgr; @Inject protected ConfigurationManager _configMgr; @Inject protected ConsoleProxyManager _consoleProxyMgr; @Inject protected SecondaryStorageVmManager _secStorageMgr; @Inject protected NetworkManager _networkMgr; @Inject protected VolumeDao _volsDao; @Inject protected HostDao _hostDao; @Inject protected ConsoleProxyDao _consoleProxyDao; @Inject protected DetailsDao _detailsDao; @Inject protected SnapshotDao _snapshotDao; @Inject protected StoragePoolHostDao _storagePoolHostDao; @Inject protected AlertManager _alertMgr; @Inject protected VMTemplateHostDao _vmTemplateHostDao = null; @Inject protected VMTemplatePoolDao _vmTemplatePoolDao = null; @Inject protected VMTemplateDao _vmTemplateDao = null; @Inject protected StoragePoolHostDao _poolHostDao = null; @Inject protected UserVmDao _userVmDao; @Inject protected VMInstanceDao _vmInstanceDao; @Inject protected StoragePoolDao _storagePoolDao = null; @Inject protected CapacityDao _capacityDao; @Inject protected DiskOfferingDao _diskOfferingDao; @Inject protected AccountDao _accountDao; @Inject protected EventDao _eventDao = null; @Inject protected DataCenterDao _dcDao = null; @Inject protected HostPodDao _podDao = null; @Inject protected VMTemplateDao _templateDao; @Inject protected VMTemplateHostDao _templateHostDao; @Inject protected ServiceOfferingDao _offeringDao; @Inject protected DomainDao _domainDao; @Inject protected UserDao _userDao; @Inject protected ClusterDao _clusterDao; @Inject protected DomainRouterManager _routerMgr; @Inject(adapter=StoragePoolAllocator.class) protected Adapters<StoragePoolAllocator> _storagePoolAllocators; @Inject(adapter=StoragePoolDiscoverer.class) protected Adapters<StoragePoolDiscoverer> _discoverers; protected SearchBuilder<VMTemplateHostVO> HostTemplateStatesSearch; protected SearchBuilder<StoragePoolVO> PoolsUsedByVmSearch; ScheduledExecutorService _executor = null; boolean _storageCleanupEnabled; int _storageCleanupInterval; int _storagePoolAcquisitionWaitSeconds = 1800; // 30 minutes protected int _retry = 2; protected int _pingInterval = 60; // seconds protected int _hostRetry; protected int _overProvisioningFactor = 1; private int _maxVolumeSizeInGb; private int _totalRetries; private int _pauseInterval; private final boolean _shouldBeSnapshotCapable = true; @Override public boolean share(VMInstanceVO vm, List<VolumeVO> vols, HostVO host, boolean cancelPreviousShare) { //if pool is in maintenance and it is the ONLY pool available; reject List<VolumeVO> rootVolForGivenVm = _volsDao.findByInstanceAndType(vm.getId(), VolumeType.ROOT); if(rootVolForGivenVm != null && rootVolForGivenVm.size() > 0){ boolean isPoolAvailable = isPoolAvailable(rootVolForGivenVm.get(0).getPoolId()); if(!isPoolAvailable){ return false; } } //this check is done for maintenance mode for primary storage //if any one of the volume is unusable, we return false //if we return false, the allocator will try to switch to another PS if available for(VolumeVO vol: vols) { if(vol.getRemoved()!=null) { s_logger.warn("Volume id:"+vol.getId()+" is removed, cannot share on this instance"); //not ok to share return false; } } //ok to share return true; } @DB public List<VolumeVO> allocate(DiskProfile rootDisk, List<DiskProfile> dataDisks, VMInstanceVO vm, DataCenterVO dc, Account owner) { ArrayList<VolumeVO> vols = new ArrayList<VolumeVO>(dataDisks.size() + 1); VolumeVO dataVol = null; VolumeVO rootVol = null; long deviceId = 0; Transaction txn = Transaction.currentTxn(); txn.start(); rootVol = new VolumeVO(VolumeType.ROOT, rootDisk.getName(), dc.getId(), owner.getDomainId(), owner.getId(), rootDisk.getDiskOfferingId(), rootDisk.getSize()); if (rootDisk.getTemplateId() != null) { rootVol.setTemplateId(rootDisk.getTemplateId()); } rootVol.setInstanceId(vm.getId()); rootVol.setDeviceId(deviceId++); rootVol = _volsDao.persist(rootVol); vols.add(rootVol); for (DiskProfile dataDisk : dataDisks) { dataVol = new VolumeVO(VolumeType.DATADISK, dataDisk.getName(), dc.getId(), owner.getDomainId(), owner.getId(), dataDisk.getDiskOfferingId(), dataDisk.getSize()); dataVol.setDeviceId(deviceId++); dataVol.setInstanceId(vm.getId()); dataVol = _volsDao.persist(dataVol); vols.add(dataVol); } txn.commit(); return vols; } @Override public VolumeVO allocateIsoInstalledVm(VMInstanceVO vm, VMTemplateVO template, DiskOfferingVO rootOffering, Long size, DataCenterVO dc, Account account) { assert (template.getFormat() == ImageFormat.ISO) : "The template has to be ISO"; long rootId = _volsDao.getNextInSequence(Long.class, "volume_seq"); DiskProfile rootDisk = new DiskProfile(rootId, VolumeType.ROOT, "ROOT-" + vm.getId() + "-" + rootId, rootOffering.getId(), size != null ? size : rootOffering.getDiskSizeInBytes(), rootOffering.getTagsArray(), rootOffering.getUseLocalStorage(), rootOffering.isRecreatable(), null); List<VolumeVO> vols = allocate(rootDisk, null, vm, dc, account); return vols.get(0); } VolumeVO allocateDuplicateVolume(VolumeVO oldVol) { VolumeVO newVol = new VolumeVO(oldVol.getVolumeType(), oldVol.getName(), oldVol.getDataCenterId(), oldVol.getDomainId(), oldVol.getAccountId(), oldVol.getDiskOfferingId(), oldVol.getSize()); newVol.setTemplateId(oldVol.getTemplateId()); newVol.setDeviceId(oldVol.getDeviceId()); newVol.setInstanceId(oldVol.getInstanceId()); return _volsDao.persist(newVol); } private boolean isPoolAvailable(Long poolId){ //get list of all pools List<StoragePoolVO> pools = _storagePoolDao.listAll(); //if no pools or 1 pool which is in maintenance if(pools == null || pools.size() == 0 || (pools.size() == 1 && pools.get(0).getStatus().equals(Status.Maintenance) )){ return false; }else{ return true; } } @Override public List<VolumeVO> prepare(VMInstanceVO vm, HostVO host) { List<VolumeVO> vols = _volsDao.findCreatedByInstance(vm.getId()); List<VolumeVO> recreateVols = new ArrayList<VolumeVO>(vols.size()); for (VolumeVO vol : vols) { if (!vol.isRecreatable()) { return vols; } //if pool is in maintenance and it is the ONLY pool available; reject List<VolumeVO> rootVolForGivenVm = _volsDao.findByInstanceAndType(vm.getId(), VolumeType.ROOT); if(rootVolForGivenVm != null && rootVolForGivenVm.size() > 0){ boolean isPoolAvailable = isPoolAvailable(rootVolForGivenVm.get(0).getPoolId()); if(!isPoolAvailable){ return new ArrayList<VolumeVO>(); } } //if we have a system vm //get the storage pool //if pool is in prepareformaintenance //add to recreate vols, and continue if(vm.getType().equals(VirtualMachine.Type.ConsoleProxy) || vm.getType().equals(VirtualMachine.Type.DomainRouter) || vm.getType().equals(VirtualMachine.Type.SecondaryStorageVm)) { StoragePoolVO sp = _storagePoolDao.findById(vol.getPoolId()); if(sp!=null && sp.getStatus().equals(Status.PrepareForMaintenance)) { recreateVols.add(vol); continue; } } StoragePoolHostVO ph = _storagePoolHostDao.findByPoolHost(vol.getPoolId(), host.getId()); if (ph == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Must recreate " + vol + " since " + vol.getPoolId() + " has is not hooked up with host " + host.getId()); } recreateVols.add(vol); } } if (recreateVols.size() == 0) { s_logger.debug("No need to recreate the volumes"); return vols; } List<VolumeVO> createds = new ArrayList<VolumeVO>(recreateVols.size()); for (VolumeVO vol : recreateVols) { VolumeVO create = new VolumeVO(vol.getVolumeType(), vol.getInstanceId(), vol.getTemplateId(), vol.getName(), vol.getDataCenterId(), host.getPodId(), vol.getAccountId(), vol.getDomainId(), vol.isRecreatable()); create.setDiskOfferingId(vol.getDiskOfferingId()); create.setDeviceId(vol.getDeviceId()); create = _volsDao.persist(create); VMTemplateVO template = _templateDao.findById(create.getTemplateId()); DataCenterVO dc = _dcDao.findById(create.getDataCenterId()); HostPodVO pod = _podDao.findById(host.getPodId()); DiskOfferingVO diskOffering = null; diskOffering = _diskOfferingDao.findById(vol.getDiskOfferingId()); ServiceOfferingVO offering; if (vm instanceof UserVmVO) { offering = _offeringDao.findById(((UserVmVO)vm).getServiceOfferingId()); } else { offering = _offeringDao.findById(vol.getDiskOfferingId()); } VolumeVO created = createVolume(create, vm, template, dc, pod, host.getClusterId(), offering, diskOffering, new ArrayList<StoragePoolVO>(),0, template.getHypervisorType()); if (created == null) { break; } createds.add(created); } for (VolumeVO vol : recreateVols) { _volsDao.remove(vol.getId()); } return createds; } @Override public List<Pair<VolumeVO, StoragePoolVO>> isStoredOn(VMInstanceVO vm) { List<Pair<VolumeVO, StoragePoolVO>> lst = new ArrayList<Pair<VolumeVO, StoragePoolVO>>(); List<VolumeVO> vols = _volsDao.findByInstance(vm.getId()); for (VolumeVO vol : vols) { StoragePoolVO pool = _storagePoolDao.findById(vol.getPoolId()); lst.add(new Pair<VolumeVO, StoragePoolVO>(vol, pool)); } return lst; } @Override public boolean isLocalStorageActiveOnHost(Host host) { List<StoragePoolHostVO> storagePoolHostRefs = _storagePoolHostDao.listByHostId(host.getId()); for (StoragePoolHostVO storagePoolHostRef : storagePoolHostRefs) { StoragePoolVO storagePool = _storagePoolDao.findById(storagePoolHostRef.getPoolId()); if (storagePool.getPoolType() == StoragePoolType.LVM) { SearchBuilder<VolumeVO> volumeSB = _volsDao.createSearchBuilder(); volumeSB.and("poolId", volumeSB.entity().getPoolId(), SearchCriteria.Op.EQ); volumeSB.and("removed", volumeSB.entity().getRemoved(), SearchCriteria.Op.NULL); SearchBuilder<VMInstanceVO> activeVmSB = _vmInstanceDao.createSearchBuilder(); activeVmSB.and("state", activeVmSB.entity().getState(), SearchCriteria.Op.IN); volumeSB.join("activeVmSB", activeVmSB, volumeSB.entity().getInstanceId(), activeVmSB.entity().getId(), JoinBuilder.JoinType.INNER); SearchCriteria<VolumeVO> volumeSC = volumeSB.create(); volumeSC.setParameters("poolId", storagePool.getId()); volumeSC.setJoinParameters("activeVmSB", "state", new Object[] {State.Creating, State.Starting, State.Running, State.Stopping, State.Migrating}); List<VolumeVO> volumes = _volsDao.search(volumeSC, null); if (volumes.size() > 0) { return true; } } } return false; } @Override public List<VolumeVO> unshare(VMInstanceVO vm, HostVO host) { final List<VolumeVO> vols = _volsDao.findCreatedByInstance(vm.getId()); if (vols.size() == 0) { return vols; } return unshare(vm, vols, host) ? vols : null; } protected StoragePoolVO findStoragePool(DiskProfile dskCh, final DataCenterVO dc, HostPodVO pod, Long clusterId, final ServiceOffering offering, final VMInstanceVO vm, final VMTemplateVO template, final Set<StoragePool> avoid) { Enumeration<StoragePoolAllocator> en = _storagePoolAllocators.enumeration(); while (en.hasMoreElements()) { final StoragePoolAllocator allocator = en.nextElement(); final StoragePool pool = allocator.allocateToPool(dskCh, dc, pod, clusterId, vm, template, avoid); if (pool != null) { return (StoragePoolVO) pool; } } return null; } @Override public Long findHostIdForStoragePool(StoragePool pool) { List<StoragePoolHostVO> poolHosts = _poolHostDao.listByHostStatus(pool.getId(), Status.Up); if (poolHosts.size() == 0) { return null; } else { return poolHosts.get(0).getHostId(); } } @Override public Answer[] sendToPool(StoragePool pool, Commands cmds) { List<StoragePoolHostVO> poolHosts = _poolHostDao.listByHostStatus(pool.getId(), Status.Up); Collections.shuffle(poolHosts); for (StoragePoolHostVO poolHost: poolHosts) { try { Answer[] answerRet = _agentMgr.send(poolHost.getHostId(), cmds); return answerRet; } catch (AgentUnavailableException e) { s_logger.debug("Moving on because unable to send to " + poolHost.getHostId() + " due to " + e.getMessage()); } catch (OperationTimedoutException e) { s_logger.debug("Moving on because unable to send to " + poolHost.getHostId() + " due to " + e.getMessage()); } } if( !poolHosts.isEmpty() ) { s_logger.warn("Unable to send commands to the pool because we ran out of hosts to send to"); } return null; } @Override public Answer sendToPool(StoragePool pool, Command cmd) { Commands cmds = new Commands(cmd); Answer[] answers = sendToPool(pool, cmds); if (answers == null) { return null; } return answers[0]; } protected DiskProfile createDiskCharacteristics(VolumeVO volume, VMTemplateVO template, DataCenterVO dc, DiskOfferingVO diskOffering) { if (volume.getVolumeType() == VolumeType.ROOT && Storage.ImageFormat.ISO != template.getFormat()) { SearchCriteria<VMTemplateHostVO> sc = HostTemplateStatesSearch.create(); sc.setParameters("id", template.getId()); sc.setParameters("state", com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOADED); sc.setJoinParameters("host", "dcId", dc.getId()); List<VMTemplateHostVO> sss = _vmTemplateHostDao.search(sc, null); if (sss.size() == 0) { throw new CloudRuntimeException("Template " + template.getName() + " has not been completely downloaded to zone " + dc.getId()); } VMTemplateHostVO ss = sss.get(0); return new DiskProfile(volume.getId(), volume.getVolumeType(), volume.getName(), diskOffering.getId(), ss.getSize(), diskOffering.getTagsArray(), diskOffering.getUseLocalStorage(), diskOffering.isRecreatable(), Storage.ImageFormat.ISO != template.getFormat() ? template.getId() : null); } else { return new DiskProfile(volume.getId(), volume.getVolumeType(), volume.getName(), diskOffering.getId(), diskOffering.getDiskSizeInBytes(), diskOffering.getTagsArray(), diskOffering.getUseLocalStorage(), diskOffering.isRecreatable(), null); } } @Override public boolean canVmRestartOnAnotherServer(long vmId) { List<VolumeVO> vols = _volsDao.findCreatedByInstance(vmId); for (VolumeVO vol : vols) { if (!vol.isRecreatable() && !vol.getPoolType().isShared()) { return false; } } return true; } @DB protected Pair<VolumeVO, String> createVolumeFromSnapshot(VolumeVO volume, SnapshotVO snapshot, VMTemplateVO template, long virtualsize) { VolumeVO createdVolume = null; Long volumeId = volume.getId(); String volumeFolder = null; // Create the Volume object and save it so that we can return it to the user Account account = _accountDao.findById(volume.getAccountId()); final HashSet<StoragePool> poolsToAvoid = new HashSet<StoragePool>(); StoragePoolVO pool = null; boolean success = false; Set<Long> podsToAvoid = new HashSet<Long>(); Pair<HostPodVO, Long> pod = null; String volumeUUID = null; String details = null; DiskOfferingVO diskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId()); DataCenterVO dc = _dcDao.findById(volume.getDataCenterId()); DiskProfile dskCh = new DiskProfile(volume, diskOffering, template.getHypervisorType()); int retry = 0; // Determine what pod to store the volume in while ((pod = _agentMgr.findPod(null, null, dc, account.getId(), podsToAvoid)) != null) { podsToAvoid.add(pod.first().getId()); // Determine what storage pool to store the volume in while ((pool = findStoragePool(dskCh, dc, pod.first(), null, null, null, null, poolsToAvoid)) != null) { poolsToAvoid.add(pool); volumeFolder = pool.getPath(); if (s_logger.isDebugEnabled()) { s_logger.debug("Attempting to create volume from snapshotId: " + snapshot.getId() + " on storage pool " + pool.getName()); } // Get the newly created VDI from the snapshot. // This will return a null volumePath if it could not be created Pair<String, String> volumeDetails = createVDIFromSnapshot(UserContext.current().getUserId(), snapshot, pool); volumeUUID = volumeDetails.first(); details = volumeDetails.second(); if (volumeUUID != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Volume with UUID " + volumeUUID + " was created on storage pool " + pool.getName()); } success = true; break; // break out of the "find storage pool" loop } else { retry++; if( retry >= 3 ) { _volsDao.expunge(volumeId); String msg = "Unable to create volume from snapshot " + snapshot.getId() + " after retrying 3 times, due to " + details; s_logger.debug(msg); throw new CloudRuntimeException(msg); } } s_logger.warn("Unable to create volume on pool " + pool.getName() + ", reason: " + details); } if (success) { break; // break out of the "find pod" loop } } if( !success ) { _volsDao.expunge(volumeId); String msg = "Unable to create volume from snapshot " + snapshot.getId() + " due to " + details; s_logger.debug(msg); throw new CloudRuntimeException(msg); } // Update the volume in the database Transaction txn = Transaction.currentTxn(); txn.start(); createdVolume = _volsDao.findById(volumeId); if (success) { // Increment the number of volumes _accountMgr.incrementResourceCount(account.getId(), ResourceType.volume); createdVolume.setStatus(AsyncInstanceCreateStatus.Created); createdVolume.setPodId(pod.first().getId()); createdVolume.setPoolId(pool.getId()); createdVolume.setPoolType(pool.getPoolType()); createdVolume.setFolder(volumeFolder); createdVolume.setPath(volumeUUID); createdVolume.setDomainId(account.getDomainId()); createdVolume.setState(Volume.State.Ready); } else { createdVolume.setStatus(AsyncInstanceCreateStatus.Corrupted); createdVolume.setDestroyed(true); } _volsDao.update(volumeId, createdVolume); txn.commit(); return new Pair<VolumeVO, String>(createdVolume, details); } @DB protected VolumeVO createVolumeFromSnapshot(VolumeVO volume, long snapshotId, long startEventId) { EventVO event = new EventVO(); event.setUserId(UserContext.current().getUserId()); event.setAccountId(volume.getAccountId()); event.setType(EventTypes.EVENT_VOLUME_CREATE); event.setState(Event.State.Started); event.setStartId(startEventId); event.setDescription("Creating volume from snapshot with id: "+snapshotId); _eventDao.persist(event); // By default, assume failure. VolumeVO createdVolume = null; String details = null; Long volumeId = null; SnapshotVO snapshot = _snapshotDao.findById(snapshotId); // Precondition: snapshot is not null and not removed. Long origVolumeId = snapshot.getVolumeId(); VolumeVO originalVolume = _volsDao.findById(origVolumeId); // NOTE: Original volume could be destroyed and removed. VMTemplateVO template = null; if (originalVolume != null) { template = _templateDao.findById(originalVolume.getTemplateId()); } // everything went well till now DataCenterVO dc = _dcDao.findById(originalVolume.getDataCenterId()); Pair<VolumeVO, String> volumeDetails = createVolumeFromSnapshot(volume, snapshot, template, originalVolume.getSize()); createdVolume = volumeDetails.first(); if (createdVolume != null) { volumeId = createdVolume.getId(); } details = volumeDetails.second(); Transaction txn = Transaction.currentTxn(); txn.start(); // Create an event long templateId = -1; long diskOfferingId = -1; if(originalVolume.getTemplateId() != null){ templateId = originalVolume.getTemplateId(); } diskOfferingId = originalVolume.getDiskOfferingId(); long sizeMB = createdVolume.getSize()/(1024*1024); String poolName = _storagePoolDao.findById(createdVolume.getPoolId()).getName(); String eventParams = "id=" + volumeId +"\ndoId="+diskOfferingId+"\ntId="+templateId+"\ndcId="+originalVolume.getDataCenterId()+"\nsize="+sizeMB; event = new EventVO(); event.setAccountId(volume.getAccountId()); event.setUserId(UserContext.current().getUserId()); event.setType(EventTypes.EVENT_VOLUME_CREATE); event.setParameters(eventParams); event.setStartId(startEventId); event.setState(Event.State.Completed); if (createdVolume.getPath() != null) { event.setDescription("Created volume: "+ createdVolume.getName() + " with size: " + sizeMB + " MB in pool: " + poolName + " from snapshot id: " + snapshotId); event.setLevel(EventVO.LEVEL_INFO); } else { details = "CreateVolume From Snapshot for snapshotId: " + snapshotId + " failed at the backend, reason " + details; event.setDescription(details); event.setLevel(EventVO.LEVEL_ERROR); } _eventDao.persist(event); txn.commit(); return createdVolume; } protected Pair<String, String> createVDIFromSnapshot(long userId, SnapshotVO snapshot, StoragePoolVO pool) { String vdiUUID = null; Long volumeId = snapshot.getVolumeId(); VolumeVO volume = _volsDao.findById(volumeId); String primaryStoragePoolNameLabel = pool.getUuid(); // pool's uuid is actually the namelabel. String secondaryStoragePoolUrl = getSecondaryStorageURL(volume.getDataCenterId()); Long dcId = volume.getDataCenterId(); long accountId = volume.getAccountId(); String backedUpSnapshotUuid = snapshot.getBackupSnapshotId(); CreateVolumeFromSnapshotCommand createVolumeFromSnapshotCommand = new CreateVolumeFromSnapshotCommand(primaryStoragePoolNameLabel, secondaryStoragePoolUrl, dcId, accountId, volumeId, backedUpSnapshotUuid, snapshot.getName()); String basicErrMsg = "Failed to create volume from " + snapshot.getName() + " for volume: " + volume.getId(); CreateVolumeFromSnapshotAnswer answer = (CreateVolumeFromSnapshotAnswer) sendToHostsOnStoragePool(pool.getId(), createVolumeFromSnapshotCommand, basicErrMsg, _totalRetries, _pauseInterval, _shouldBeSnapshotCapable, null); if (answer != null && answer.getResult()) { vdiUUID = answer.getVdi(); } else if (answer != null) { s_logger.error(basicErrMsg); } return new Pair<String, String>(vdiUUID, basicErrMsg); } @Override @DB public VolumeVO createVolume(VolumeVO volume, VMInstanceVO vm, VMTemplateVO template, DataCenterVO dc, HostPodVO pod, Long clusterId, ServiceOfferingVO offering, DiskOfferingVO diskOffering, List<StoragePoolVO> avoids, long size, HypervisorType hyperType) { StoragePoolVO pool = null; final HashSet<StoragePool> avoidPools = new HashSet<StoragePool>(avoids); if(diskOffering != null && diskOffering.isCustomized()){ diskOffering.setDiskSize(size); } DiskProfile dskCh = null; if (volume.getVolumeType() == VolumeType.ROOT && Storage.ImageFormat.ISO != template.getFormat()) { dskCh = createDiskCharacteristics(volume, template, dc, offering); } else { dskCh = createDiskCharacteristics(volume, template, dc, diskOffering); } dskCh.setHyperType(hyperType); VolumeTO created = null; int retry = _retry; while (--retry >= 0) { created = null; long podId = pod.getId(); pod = _podDao.findById(podId); if (pod == null) { s_logger.warn("Unable to find pod " + podId + " when create volume " + volume.getName()); break; } pool = findStoragePool(dskCh, dc, pod, clusterId, offering, vm, template, avoidPools); if (pool == null) { s_logger.warn("Unable to find storage poll when create volume " + volume.getName()); break; } avoidPools.add(pool); if (s_logger.isDebugEnabled()) { s_logger.debug("Trying to create " + volume + " on " + pool); } CreateCommand cmd = null; VMTemplateStoragePoolVO tmpltStoredOn = null; if (volume.getVolumeType() == VolumeType.ROOT && Storage.ImageFormat.ISO != template.getFormat()) { tmpltStoredOn = _tmpltMgr.prepareTemplateForCreate(template, pool); if (tmpltStoredOn == null) { continue; } cmd = new CreateCommand(dskCh, tmpltStoredOn.getLocalDownloadPath(), new StorageFilerTO(pool)); } else { cmd = new CreateCommand(dskCh, new StorageFilerTO(pool)); } Answer answer = sendToPool(pool, cmd); if (answer != null && answer.getResult()) { created = ((CreateAnswer)answer).getVolume(); break; } s_logger.debug("Retrying the create because it failed on pool " + pool); } Transaction txn = Transaction.currentTxn(); txn.start(); if (created == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to create a volume for " + volume); } volume.setStatus(AsyncInstanceCreateStatus.Failed); volume.setDestroyed(true); _volsDao.persist(volume); _volsDao.remove(volume.getId()); volume = null; } else { volume.setStatus(AsyncInstanceCreateStatus.Created); volume.setFolder(pool.getPath()); volume.setPath(created.getPath()); volume.setSize(created.getSize()); volume.setPoolType(pool.getPoolType()); volume.setPoolId(pool.getId()); volume.setPodId(pod.getId()); volume.setState(Volume.State.Ready); _volsDao.persist(volume); } txn.commit(); return volume; } @Override public List<VolumeVO> create(Account account, VMInstanceVO vm, VMTemplateVO template, DataCenterVO dc, HostPodVO pod, ServiceOfferingVO offering, DiskOfferingVO diskOffering, long size) throws StorageUnavailableException, ExecutionException { List<StoragePoolVO> avoids = new ArrayList<StoragePoolVO>(); return create(account, vm, template, dc, pod, offering, diskOffering, avoids, size); } @DB protected List<VolumeVO> create(Account account, VMInstanceVO vm, VMTemplateVO template, DataCenterVO dc, HostPodVO pod, ServiceOfferingVO offering, DiskOfferingVO diskOffering, List<StoragePoolVO> avoids, long size) { ArrayList<VolumeVO> vols = new ArrayList<VolumeVO>(2); VolumeVO dataVol = null; VolumeVO rootVol = null; Transaction txn = Transaction.currentTxn(); txn.start(); if (Storage.ImageFormat.ISO == template.getFormat()) { rootVol = new VolumeVO(VolumeType.ROOT, vm.getId(), vm.getInstanceName() + "-ROOT", dc.getId(), pod.getId(), account.getId(), account.getDomainId(),(size>0)? size : diskOffering.getDiskSizeInBytes()); createStartedEvent(account, rootVol); rootVol.setDiskOfferingId(diskOffering.getId()); rootVol.setSourceType(SourceType.Template); rootVol.setSourceId(template.getId()); rootVol.setDeviceId(0l); rootVol = _volsDao.persist(rootVol); } else { rootVol = new VolumeVO(VolumeType.ROOT, vm.getId(), template.getId(), vm.getInstanceName() + "-ROOT", dc.getId(), pod.getId(), account.getId(), account.getDomainId(), offering.isRecreatable()); createStartedEvent(account, rootVol); rootVol.setDiskOfferingId(offering.getId()); rootVol.setTemplateId(template.getId()); rootVol.setSourceId(template.getId()); rootVol.setSourceType(SourceType.Template); rootVol.setDeviceId(0l); rootVol = _volsDao.persist(rootVol); if ((diskOffering != null && diskOffering.getDiskSizeInBytes() > 0) || (diskOffering != null && diskOffering.isCustomized())) { dataVol = new VolumeVO(VolumeType.DATADISK, vm.getId(), vm.getInstanceName() + "-DATA", dc.getId(), pod.getId(), account.getId(), account.getDomainId(), (size>0)? size : diskOffering.getDiskSizeInBytes()); createStartedEvent(account, dataVol); dataVol.setDiskOfferingId(diskOffering.getId()); dataVol.setSourceType(SourceType.DiskOffering); dataVol.setSourceId(diskOffering.getId()); dataVol.setDeviceId(1l); dataVol = _volsDao.persist(dataVol); } } txn.commit(); VolumeVO dataCreated = null; VolumeVO rootCreated = null; try { rootCreated = createVolume(rootVol, vm, template, dc, pod, null, offering, diskOffering, avoids,size, template.getHypervisorType()); if (rootCreated == null) { throw new CloudRuntimeException("Unable to create " + rootVol); } vols.add(rootCreated); if (dataVol != null) { StoragePoolVO pool = _storagePoolDao.findById(rootCreated.getPoolId()); dataCreated = createVolume(dataVol, vm, null, dc, pod, pool.getClusterId(), offering, diskOffering, avoids,size, template.getHypervisorType()); if (dataCreated == null) { throw new CloudRuntimeException("Unable to create " + dataVol); } vols.add(dataCreated); } return vols; } catch (Exception e) { if (s_logger.isDebugEnabled()) { s_logger.debug(e.getMessage()); } if (rootCreated != null) { destroyVolume(rootCreated); } throw new CloudRuntimeException("Unable to create volumes for " + vm, e); } } private void createStartedEvent(Account account, VolumeVO rootVol) { EventVO event1 = new EventVO(); event1.setAccountId(account.getId()); event1.setUserId(1L); event1.setType(EventTypes.EVENT_VOLUME_CREATE); event1.setState(Event.State.Started); event1.setDescription("Create volume: " + rootVol.getName()+ "started"); _eventDao.persist(event1); } @Override public long createUserVM(Account account, VMInstanceVO vm, VMTemplateVO template, DataCenterVO dc, HostPodVO pod, ServiceOfferingVO offering, DiskOfferingVO diskOffering, List<StoragePoolVO> avoids, long size) { List<VolumeVO> volumes = create(account, vm, template, dc, pod, offering, diskOffering, avoids, size); if( volumes == null || volumes.size() == 0) { throw new CloudRuntimeException("Unable to create volume for " + vm.getHostName()); } for (VolumeVO v : volumes) { //when the user vm is created, the volume is attached upon creation //set the attached datetime try{ v.setAttached(new Date()); _volsDao.update(v.getId(), v); }catch(Exception e) { s_logger.warn("Error updating the attached value for volume "+v.getId()+":"+e); } long templateId = -1; long doId = v.getDiskOfferingId(); if(v.getVolumeType() == VolumeType.ROOT && Storage.ImageFormat.ISO != template.getFormat()){ templateId = template.getId(); doId = -1; } long volumeId = v.getId(); // Create an event long sizeMB = v.getSize() / (1024 * 1024); String eventParams = "id=" + volumeId + "\ndoId=" + doId + "\ntId=" + templateId + "\ndcId=" + dc.getId() + "\nsize=" + sizeMB; EventVO event = new EventVO(); event.setAccountId(account.getId()); event.setUserId(1L); event.setType(EventTypes.EVENT_VOLUME_CREATE); event.setParameters(eventParams); event.setDescription("Created volume: " + v.getName() + " with size: " + sizeMB + " MB"); _eventDao.persist(event); } return volumes.get(0).getPoolId(); } public Long chooseHostForStoragePool(StoragePoolVO poolVO, List<Long> avoidHosts, boolean sendToVmResidesOn, Long vmId) { if (sendToVmResidesOn) { if (vmId != null) { VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId); if (vmInstance != null) { Long hostId = vmInstance.getHostId(); if (hostId != null && !avoidHosts.contains(vmInstance.getHostId())) { return hostId; } } } /*Can't find the vm where host resides on(vm is destroyed? or volume is detached from vm), randomly choose a host to send the cmd */ } List<StoragePoolHostVO> poolHosts = _poolHostDao.listByHostStatus(poolVO.getId(), Status.Up); Collections.shuffle(poolHosts); if (poolHosts != null && poolHosts.size() > 0) { for (StoragePoolHostVO sphvo : poolHosts) { if (!avoidHosts.contains(sphvo.getHostId())) { return sphvo.getHostId(); } } } return null; } @Override public String chooseStorageIp(VMInstanceVO vm, Host host, Host storage) { Enumeration<StoragePoolAllocator> en = _storagePoolAllocators.enumeration(); while (en.hasMoreElements()) { StoragePoolAllocator allocator = en.nextElement(); String ip = allocator.chooseStorageIp(vm, host, storage); if (ip != null) { return ip; } } assert false : "Hmm....fell thru the loop"; return null; } @Override public boolean unshare(VMInstanceVO vm, List<VolumeVO> vols, HostVO host) { if (s_logger.isDebugEnabled()) { s_logger.debug("Asking for volumes of " + vm.toString() + " to be unshared to " + (host != null ? host.toString() : "all")); } return true; } @Override public void destroy(VMInstanceVO vm, List<VolumeVO> vols) { if (s_logger.isDebugEnabled() && vm != null) { s_logger.debug("Destroying volumes of " + vm.toString()); } for (VolumeVO vol : vols) { _volsDao.detachVolume(vol.getId()); _volsDao.destroyVolume(vol.getId()); // First delete the entries in the snapshot_policy and // snapshot_schedule table for the volume. // They should not get executed after the volume is destroyed. _snapshotMgr.deletePoliciesForVolume(vol.getId()); String volumePath = vol.getPath(); Long poolId = vol.getPoolId(); if (poolId != null && volumePath != null && !volumePath.trim().isEmpty()) { Answer answer = null; StoragePoolVO pool = _storagePoolDao.findById(poolId); String vmName = null; if (vm != null) { vmName = vm.getInstanceName(); } final DestroyCommand cmd = new DestroyCommand(pool, vol, vmName); boolean removed = false; List<StoragePoolHostVO> poolhosts = _storagePoolHostDao.listByPoolId(poolId); for (StoragePoolHostVO poolhost : poolhosts) { answer = _agentMgr.easySend(poolhost.getHostId(), cmd); if (answer != null && answer.getResult()) { removed = true; break; } } if (removed) { _volsDao.remove(vol.getId()); } else { _alertMgr.sendAlert(AlertManager.ALERT_TYPE_STORAGE_MISC, vol.getDataCenterId(), vol.getPodId(), "Storage cleanup required for storage pool: " + pool.getName(), "Volume folder: " + vol.getFolder() + ", Volume Path: " + vol.getPath() + ", Volume id: " +vol.getId()+ ", Volume Name: " +vol.getName()+ ", Storage PoolId: " +vol.getPoolId()); s_logger.warn("destroy volume " + vol.getFolder() + " : " + vol.getPath() + " failed for Volume id : " +vol.getId()+ " Volume Name: " +vol.getName()+ " Storage PoolId : " +vol.getPoolId()); } } else { _volsDao.remove(vol.getId()); } } } @Override public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { _name = name; ComponentLocator locator = ComponentLocator.getCurrentLocator(); ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); if (configDao == null) { s_logger.error("Unable to get the configuration dao."); return false; } Map<String, String> configs = configDao.getConfiguration("management-server", params); String overProvisioningFactorStr = configs.get("storage.overprovisioning.factor"); if (overProvisioningFactorStr != null) { _overProvisioningFactor = Integer.parseInt(overProvisioningFactorStr); } _retry = NumbersUtil.parseInt(configs.get(Config.StartRetry.key()), 10); _pingInterval = NumbersUtil.parseInt(configs.get("ping.interval"), 60); _hostRetry = NumbersUtil.parseInt(configs.get("host.retry"), 2); _storagePoolAcquisitionWaitSeconds = NumbersUtil.parseInt(configs.get("pool.acquisition.wait.seconds"), 1800); s_logger.info("pool.acquisition.wait.seconds is configured as " + _storagePoolAcquisitionWaitSeconds + " seconds"); _totalRetries = NumbersUtil.parseInt(configDao.getValue("total.retries"), 2); _pauseInterval = 2*NumbersUtil.parseInt(configDao.getValue("ping.interval"), 60); _agentMgr.registerForHostEvents(new StoragePoolMonitor(this, _hostDao, _storagePoolDao), true, false, true); String storageCleanupEnabled = configs.get("storage.cleanup.enabled"); _storageCleanupEnabled = (storageCleanupEnabled == null) ? true : Boolean.parseBoolean(storageCleanupEnabled); String time = configs.get("storage.cleanup.interval"); _storageCleanupInterval = NumbersUtil.parseInt(time, 86400); String workers = configs.get("expunge.workers"); int wrks = NumbersUtil.parseInt(workers, 10); _executor = Executors.newScheduledThreadPool(wrks, new NamedThreadFactory("StorageManager-Scavenger")); boolean localStorage = Boolean.parseBoolean(configs.get(Config.UseLocalStorage.key())); if (localStorage) { _agentMgr.registerForHostEvents(ComponentLocator.inject(LocalStoragePoolListener.class), true, false, false); } String maxVolumeSizeInGbString = configDao.getValue("storage.max.volume.size"); _maxVolumeSizeInGb = NumbersUtil.parseInt(maxVolumeSizeInGbString, 2000); PoolsUsedByVmSearch = _storagePoolDao.createSearchBuilder(); SearchBuilder<VolumeVO> volSearch = _volsDao.createSearchBuilder(); PoolsUsedByVmSearch.join("volumes", volSearch, volSearch.entity().getPoolId(), PoolsUsedByVmSearch.entity().getId(), JoinBuilder.JoinType.INNER); volSearch.and("vm", volSearch.entity().getInstanceId(), SearchCriteria.Op.EQ); volSearch.and("status", volSearch.entity().getStatus(), SearchCriteria.Op.EQ); volSearch.done(); PoolsUsedByVmSearch.done(); HostTemplateStatesSearch = _vmTemplateHostDao.createSearchBuilder(); HostTemplateStatesSearch.and("id", HostTemplateStatesSearch.entity().getTemplateId(), SearchCriteria.Op.EQ); HostTemplateStatesSearch.and("state", HostTemplateStatesSearch.entity().getDownloadState(), SearchCriteria.Op.EQ); SearchBuilder<HostVO> HostSearch = _hostDao.createSearchBuilder(); HostSearch.and("dcId", HostSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); HostTemplateStatesSearch.join("host", HostSearch, HostSearch.entity().getId(), HostTemplateStatesSearch.entity().getHostId(), JoinBuilder.JoinType.INNER); HostSearch.done(); HostTemplateStatesSearch.done(); return true; } public String getVolumeFolder(String parentDir, long accountId, String diskFolderName) { StringBuilder diskFolderBuilder = new StringBuilder(); Formatter diskFolderFormatter = new Formatter(diskFolderBuilder); diskFolderFormatter.format("%s/u%06d/%s", parentDir, accountId, diskFolderName); return diskFolderBuilder.toString(); } public String getRandomVolumeName() { return UUID.randomUUID().toString(); } @Override public boolean volumeOnSharedStoragePool(VolumeVO volume) { Long poolId = volume.getPoolId(); if (poolId == null) { return false; } else { StoragePoolVO pool = _storagePoolDao.findById(poolId); if (pool == null) { return false; } else { return pool.isShared(); } } } @Override public boolean volumeInactive(VolumeVO volume) { Long vmId = volume.getInstanceId(); if (vmId != null) { UserVm vm = _userVmDao.findById(vmId); if (vm == null) { return false; } if (!vm.getState().equals(State.Stopped)) { return false; } } return true; } @Override public String getVmNameOnVolume(VolumeVO volume) { Long vmId = volume.getInstanceId(); if (vmId != null) { VMInstanceVO vm = _vmInstanceDao.findById(vmId); if (vm == null) { return null; } return vm.getInstanceName(); } return null; } @Override public Pair<String, String> getAbsoluteIsoPath(long templateId, long dataCenterId) { String isoPath = null; List<HostVO> storageHosts = _hostDao.listBy(Host.Type.SecondaryStorage, dataCenterId); if (storageHosts != null) { for (HostVO storageHost : storageHosts) { VMTemplateHostVO templateHostVO = _vmTemplateHostDao.findByHostTemplate(storageHost.getId(), templateId); if (templateHostVO != null) { isoPath = storageHost.getStorageUrl() + "/" + templateHostVO.getInstallPath(); return new Pair<String, String>(isoPath, storageHost.getStorageUrl()); } } } return null; } @Override public String getSecondaryStorageURL(long zoneId) { // Determine the secondary storage URL HostVO secondaryStorageHost = _hostDao.findSecondaryStorageHost(zoneId); if (secondaryStorageHost == null) { return null; } return secondaryStorageHost.getStorageUrl(); } @Override public HostVO getSecondaryStorageHost(long zoneId) { return _hostDao.findSecondaryStorageHost(zoneId); } @Override public String getStoragePoolTags(long poolId) { return _configMgr.listToCsvTags(_storagePoolDao.searchForStoragePoolDetails(poolId, "true")); } @Override public String getName() { return _name; } @Override public boolean start() { if (_storageCleanupEnabled) { _executor.scheduleWithFixedDelay(new StorageGarbageCollector(), _storageCleanupInterval, _storageCleanupInterval, TimeUnit.SECONDS); } else { s_logger.debug("Storage cleanup is not enabled, so the storage cleanup thread is not being scheduled."); } return true; } @Override public boolean stop() { if (_storageCleanupEnabled) { _executor.shutdown(); } return true; } protected StorageManagerImpl() { } @Override @SuppressWarnings("rawtypes") public StoragePoolVO createPool(CreateStoragePoolCmd cmd) throws ResourceInUseException, IllegalArgumentException, UnknownHostException, ResourceAllocationException { Long clusterId = cmd.getClusterId(); Long podId = cmd.getPodId(); Map ds = cmd.getDetails(); if (clusterId != null && podId == null) { throw new ServerApiException(BaseCmd.PARAM_ERROR, "Cluster id requires pod id"); } Map<String, String> details = new HashMap<String, String>(); if (ds != null) { Collection detailsCollection = ds.values(); Iterator it = detailsCollection.iterator(); while (it.hasNext()) { HashMap d = (HashMap)it.next(); Iterator it2 = d.entrySet().iterator(); while (it2.hasNext()) { Map.Entry entry = (Map.Entry)it2.next(); details.put((String)entry.getKey(), (String)entry.getValue()); } } } //verify input parameters Long zoneId = cmd.getZoneId(); DataCenterVO zone = _dcDao.findById(cmd.getZoneId()); if (zone == null) { throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to find zone by id " + zoneId); } URI uri = null; try { uri = new URI(cmd.getUrl()); if (uri.getScheme() == null) { throw new ServerApiException(BaseCmd.PARAM_ERROR, "scheme is null " + cmd.getUrl() + ", add nfs:// as a prefix"); } else if (uri.getScheme().equalsIgnoreCase("nfs")) { String uriHost = uri.getHost(); String uriPath = uri.getPath(); if (uriHost == null || uriPath == null || uriHost.trim().isEmpty() || uriPath.trim().isEmpty()) { throw new ServerApiException(BaseCmd.PARAM_ERROR, "host or path is null, should be nfs://hostname/path"); } } } catch (URISyntaxException e) { throw new ServerApiException(BaseCmd.PARAM_ERROR, cmd.getUrl() + " is not a valid uri"); } String tags = cmd.getTags(); if (tags != null) { String[] tokens = tags.split(","); for (String tag : tokens) { tag = tag.trim(); if (tag.length() == 0) { continue; } details.put(tag, "true"); } } List<HostVO> hosts = null; if (clusterId != null) { hosts = _hostDao.listByCluster(clusterId); } else if (podId != null) { hosts = _hostDao.listByHostPod(podId); } else { hosts = _hostDao.listByDataCenter(zoneId); } String scheme = uri.getScheme(); String storageHost = uri.getHost(); String hostPath = uri.getPath(); int port = uri.getPort(); StoragePoolVO pool = null; if (s_logger.isDebugEnabled()) { s_logger.debug("createPool Params @ scheme - " +scheme+ " storageHost - " +storageHost+ " hostPath - " +hostPath+ " port - " +port); } if (scheme.equalsIgnoreCase("nfs")) { if (port == -1) { port = 2049; } pool = new StoragePoolVO(StoragePoolType.NetworkFilesystem, storageHost, port, hostPath); if (clusterId == null) { throw new IllegalArgumentException("NFS need to have clusters specified for XenServers"); } } else if (scheme.equalsIgnoreCase("file")) { if (port == -1) { port = 0; } pool = new StoragePoolVO(StoragePoolType.Filesystem, "localhost", 0, hostPath); } else if (scheme.equalsIgnoreCase("iscsi")) { String[] tokens = hostPath.split("/"); int lun = NumbersUtil.parseInt(tokens[tokens.length - 1], -1); if (port == -1) { port = 3260; } if (lun != -1) { if (clusterId == null) { throw new IllegalArgumentException("IscsiLUN need to have clusters specified"); } hostPath.replaceFirst("/", ""); pool = new StoragePoolVO(StoragePoolType.IscsiLUN, storageHost, port, hostPath); } else { Enumeration<StoragePoolDiscoverer> en = _discoverers.enumeration(); while (en.hasMoreElements()) { Map<StoragePoolVO, Map<String, String>> pools; try { pools = en.nextElement().find(cmd.getZoneId(), podId, uri, details); } catch (DiscoveryException e) { throw new IllegalArgumentException("Not enough information for discovery " + uri, e); } if (pools != null) { Map.Entry<StoragePoolVO, Map<String, String>> entry = pools.entrySet().iterator().next(); pool = entry.getKey(); details = entry.getValue(); break; } } } } else if (scheme.equalsIgnoreCase("iso")) { if (port == -1) { port = 2049; } pool = new StoragePoolVO(StoragePoolType.ISO, storageHost, port, hostPath); } else if (scheme.equalsIgnoreCase("vmfs")) { pool = new StoragePoolVO(StoragePoolType.VMFS, storageHost, 0, hostPath); } else { s_logger.warn("Unable to figure out the scheme for URI: " + uri); throw new IllegalArgumentException("Unable to figure out the scheme for URI: " + uri); } if (pool == null) { s_logger.warn("Unable to figure out the scheme for URI: " + uri); throw new IllegalArgumentException("Unable to figure out the scheme for URI: " + uri); } List<StoragePoolVO> pools = _storagePoolDao.listPoolByHostPath(storageHost, hostPath); if (!pools.isEmpty()) { Long oldPodId = pools.get(0).getPodId(); throw new ResourceInUseException("Storage pool " + uri + " already in use by another pod (id=" + oldPodId + ")", "StoragePool", uri.toASCIIString()); } // iterate through all the hosts and ask them to mount the filesystem. // FIXME Not a very scalable implementation. Need an async listener, or // perhaps do this on demand, or perhaps mount on a couple of hosts per // pod List<HostVO> allHosts = _hostDao.listBy(Host.Type.Routing, clusterId, podId, zoneId); if (allHosts.isEmpty()) { throw new ResourceAllocationException("No host exists to associate a storage pool with"); } long poolId = _storagePoolDao.getNextInSequence(Long.class, "id"); String uuid = UUID.nameUUIDFromBytes(new String(storageHost + hostPath).getBytes()).toString(); List<StoragePoolVO> spHandles = _storagePoolDao.findIfDuplicatePoolsExistByUUID(uuid); if ((spHandles != null) && (spHandles.size() > 0)) { if (s_logger.isDebugEnabled()) { s_logger.debug("Another active pool with the same uuid already exists"); } throw new ResourceInUseException("Another active pool with the same uuid already exists"); } if (s_logger.isDebugEnabled()) { s_logger.debug("In createPool Setting poolId - " +poolId+ " uuid - " +uuid+ " zoneId - " +zoneId+ " podId - " +podId+ " poolName - " + cmd.getStoragePoolName()); } pool.setId(poolId); pool.setUuid(uuid); pool.setDataCenterId(cmd.getZoneId()); pool.setPodId(podId); pool.setName(cmd.getStoragePoolName()); pool.setClusterId(clusterId); pool.setStatus(Status.Up); pool = _storagePoolDao.persist(pool, details); if (allHosts.isEmpty()) { return pool; } s_logger.debug("In createPool Adding the pool to each of the hosts"); List<HostVO> poolHosts = new ArrayList<HostVO>(); for (HostVO h : allHosts) { boolean success = addPoolToHost(h.getId(), pool); if (success) { poolHosts.add(h); } } if (poolHosts.isEmpty()) { _storagePoolDao.expunge(pool.getId()); pool = null; } else { createCapacityEntry(pool); } return pool; } @Override public StoragePoolVO updateStoragePool(UpdateStoragePoolCmd cmd) throws IllegalArgumentException { //Input validation Long id = cmd.getId(); String tags = cmd.getTags(); StoragePoolVO pool = _storagePoolDao.findById(id); if (pool == null) { throw new IllegalArgumentException("Unable to find storage pool with ID: " + id); } if (tags != null) { Map<String, String> details = _storagePoolDao.getDetails(id); String[] tagsList = tags.split(","); for (String tag : tagsList) { tag = tag.trim(); if (tag.length() > 0 && !details.containsKey(tag)) { details.put(tag, "true"); } } _storagePoolDao.updateDetails(id, details); } return pool; } @Override @DB public boolean deletePool(DeletePoolCmd command) throws InvalidParameterValueException{ Long id = command.getId(); boolean deleteFlag = false; //verify parameters StoragePoolVO sPool = _storagePoolDao.findById(id); if (sPool == null) { s_logger.warn("Unable to find pool:"+id); throw new InvalidParameterValueException("Unable to find pool by id " + id); } if (sPool.getPoolType().equals(StoragePoolType.LVM)) { s_logger.warn("Unable to delete local storage id:"+id); throw new InvalidParameterValueException("Unable to delete local storage id: " + id); } // for the given pool id, find all records in the storage_pool_host_ref List<StoragePoolHostVO> hostPoolRecords = _storagePoolHostDao.listByPoolId(id); // if not records exist, delete the given pool (base case) if (hostPoolRecords.size() == 0) { sPool.setUuid(null); _storagePoolDao.update(id, sPool); _storagePoolDao.remove(id); return true; } else { // 1. Check if the pool has associated volumes in the volumes table // 2. If it does, then you cannot delete the pool Pair<Long, Long> volumeRecords = _volsDao.getCountAndTotalByPool(id); if (volumeRecords.first() > 0) { s_logger.warn("Cannot delete pool "+sPool.getName()+" as there are associated vols for this pool"); return false; // cannot delete as there are associated vols } // 3. Else part, remove the SR associated with the Xenserver else { // First get the host_id from storage_pool_host_ref for given // pool id StoragePoolVO lock = _storagePoolDao.acquireInLockTable(sPool.getId()); try { if (lock == null) { if(s_logger.isDebugEnabled()) { s_logger.debug("Failed to acquire lock when deleting StoragePool with ID: " + sPool.getId()); } return false; } for (StoragePoolHostVO host : hostPoolRecords) { DeleteStoragePoolCommand cmd = new DeleteStoragePoolCommand(sPool); final Answer answer = _agentMgr.easySend(host.getHostId(), cmd); if (answer != null) { if (answer.getResult() == true) { deleteFlag = true; break; } } } } finally { if (lock != null) { _storagePoolDao.releaseFromLockTable(lock.getId()); } } if (deleteFlag) { // now delete the storage_pool_host_ref and storage_pool // records for (StoragePoolHostVO host : hostPoolRecords) { _storagePoolHostDao.deleteStoragePoolHostDetails(host.getHostId(),host.getPoolId()); } sPool.setUuid(null); _storagePoolDao.update(id, sPool); _storagePoolDao.remove(id); return true; } } } return false; } @Override public boolean addPoolToHost(long hostId, StoragePoolVO pool) { s_logger.debug("Adding pool " + pool.getName() + " to host " + hostId); if (pool.getPoolType() != StoragePoolType.NetworkFilesystem && pool.getPoolType() != StoragePoolType.Filesystem && pool.getPoolType() != StoragePoolType.IscsiLUN && pool.getPoolType() != StoragePoolType.Iscsi && pool.getPoolType() != StoragePoolType.VMFS) { return true; } ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand(true, pool); final Answer answer = _agentMgr.easySend(hostId, cmd); if (answer != null) { if (answer.getResult() == false) { String msg = "Add host failed due to ModifyStoragePoolCommand failed" + answer.getDetails(); _alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, pool.getDataCenterId(), pool.getPodId(), msg, msg); s_logger.warn(msg); return false; } if (answer instanceof ModifyStoragePoolAnswer) { ModifyStoragePoolAnswer mspAnswer = (ModifyStoragePoolAnswer) answer; StoragePoolHostVO poolHost = _poolHostDao.findByPoolHost(pool.getId(), hostId); if (poolHost == null) { poolHost = new StoragePoolHostVO(pool.getId(), hostId, mspAnswer.getPoolInfo().getLocalPath().replaceAll("//", "/")); _poolHostDao.persist(poolHost); } else { poolHost.setLocalPath(mspAnswer.getPoolInfo().getLocalPath().replaceAll("//", "/")); } pool.setAvailableBytes(mspAnswer.getPoolInfo().getAvailableBytes()); pool.setCapacityBytes(mspAnswer.getPoolInfo().getCapacityBytes()); _storagePoolDao.update(pool.getId(), pool); return true; } } else { return false; } return false; } @Override public VolumeVO moveVolume(VolumeVO volume, long destPoolDcId, Long destPoolPodId, Long destPoolClusterId) { // Find a destination storage pool with the specified criteria DiskOfferingVO diskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId()); DiskProfile dskCh = new DiskProfile(volume.getId(), volume.getVolumeType(), volume.getName(), diskOffering.getId(), diskOffering.getDiskSizeInBytes(), diskOffering.getTagsArray(), diskOffering.getUseLocalStorage(), diskOffering.isRecreatable(), null); DataCenterVO destPoolDataCenter = _dcDao.findById(destPoolDcId); HostPodVO destPoolPod = _podDao.findById(destPoolPodId); StoragePoolVO destPool = findStoragePool(dskCh, destPoolDataCenter, destPoolPod, destPoolClusterId, null, null, null, new HashSet<StoragePool>()); if (destPool == null) { throw new CloudRuntimeException("Failed to find a storage pool with enough capacity to move the volume to."); } StoragePoolVO srcPool = _storagePoolDao.findById(volume.getPoolId()); String secondaryStorageURL = getSecondaryStorageURL(volume.getDataCenterId()); String secondaryStorageVolumePath = null; // Find hosts where the source and destination storage pools are visible Long sourceHostId = findHostIdForStoragePool(srcPool); Long destHostId = findHostIdForStoragePool(destPool); if (sourceHostId == null) { throw new CloudRuntimeException("Failed to find a host where the source storage pool is visible."); } else if (destHostId == null) { throw new CloudRuntimeException("Failed to find a host where the dest storage pool is visible."); } // Copy the volume from the source storage pool to secondary storage CopyVolumeCommand cvCmd = new CopyVolumeCommand(volume.getId(), volume.getPath(), srcPool, secondaryStorageURL, true); CopyVolumeAnswer cvAnswer = (CopyVolumeAnswer) _agentMgr.easySend(sourceHostId, cvCmd); if (cvAnswer == null || !cvAnswer.getResult()) { throw new CloudRuntimeException("Failed to copy the volume from the source primary storage pool to secondary storage."); } secondaryStorageVolumePath = cvAnswer.getVolumePath(); // Copy the volume from secondary storage to the destination storage // pool cvCmd = new CopyVolumeCommand(volume.getId(), secondaryStorageVolumePath, destPool, secondaryStorageURL, false); cvAnswer = (CopyVolumeAnswer) _agentMgr.easySend(destHostId, cvCmd); if (cvAnswer == null || !cvAnswer.getResult()) { throw new CloudRuntimeException("Failed to copy the volume from secondary storage to the destination primary storage pool."); } String destPrimaryStorageVolumePath = cvAnswer.getVolumePath(); String destPrimaryStorageVolumeFolder = cvAnswer.getVolumeFolder(); // Delete the volume on the source storage pool final DestroyCommand cmd = new DestroyCommand(srcPool, volume, null); Answer destroyAnswer = _agentMgr.easySend(sourceHostId, cmd); if (destroyAnswer == null || !destroyAnswer.getResult()) { throw new CloudRuntimeException("Failed to delete the volume from the source primary storage pool."); } volume.setPath(destPrimaryStorageVolumePath); volume.setFolder(destPrimaryStorageVolumeFolder); volume.setPodId(destPool.getPodId()); volume.setPoolId(destPool.getId()); _volsDao.update(volume.getId(), volume); return _volsDao.findById(volume.getId()); } /*Just allocate a volume in the database, don't send the createvolume cmd to hypervisor. The volume will be finally created only when it's attached to a VM.*/ @Override public VolumeVO allocVolume(CreateVolumeCmd cmd) throws InvalidParameterValueException, PermissionDeniedException, ResourceAllocationException { // FIXME: some of the scheduled event stuff might be missing here... Account account = UserContext.current().getAccount(); String accountName = cmd.getAccountName(); Long domainId = cmd.getDomainId(); Account targetAccount = null; if ((account == null) || isAdmin(account.getType())) { // Admin API call if ((domainId != null) && (accountName != null)) { if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), domainId)) { throw new PermissionDeniedException("Unable to create volume in domain " + domainId + ", permission denied."); } targetAccount = _accountDao.findActiveAccount(accountName, domainId); } else { targetAccount = account; } // If the account is null, this means that the accountName and domainId passed in were invalid if (targetAccount == null) { throw new InvalidParameterValueException("Unable to find account with name: " + accountName + " and domain ID: " + domainId); } } else { targetAccount = account; } // check if the volume can be created for the user // Check that the resource limit for volumes won't be exceeded if (_accountMgr.resourceLimitExceeded(targetAccount, ResourceType.volume)) { ResourceAllocationException rae = new ResourceAllocationException("Maximum number of volumes for account: " + targetAccount.getAccountName() + " has been exceeded."); rae.setResourceType("volume"); throw rae; } Long zoneId = null; Long diskOfferingId = null; Long size = null; // validate input parameters before creating the volume if(cmd.getSnapshotId() == null && cmd.getDiskOfferingId() == null){ throw new InvalidParameterValueException("Either disk Offering Id or snapshot Id must be passed whilst creating volume"); } if (cmd.getSnapshotId() == null) { zoneId = cmd.getZoneId(); if ((zoneId == null)) { throw new InvalidParameterValueException("Missing parameter, zoneid must be specified."); } diskOfferingId = cmd.getDiskOfferingId(); size = cmd.getSize(); if ((diskOfferingId == null) && (size == null)) { throw new InvalidParameterValueException("Missing parameter(s),either a positive volume size or a valid disk offering id must be specified."); } else if ((diskOfferingId == null) && (size != null)) { boolean ok = validateVolumeSizeRange(size); if (!ok) { throw new InvalidParameterValueException("Invalid size for custom volume creation: " + size); } //this is the case of creating var size vol with private disk offering List<DiskOfferingVO> privateTemplateList = _diskOfferingDao.findPrivateDiskOffering(); diskOfferingId = privateTemplateList.get(0).getId(); //we use this id for creating volume } else { // Check that the the disk offering is specified DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId); if ((diskOffering == null) || !DiskOfferingVO.Type.Disk.equals(diskOffering.getType())) { throw new InvalidParameterValueException("Please specify a valid disk offering."); } if(diskOffering.getDomainId() == null){ //do nothing as offering is public }else{ _configMgr.checkDiskOfferingAccess(account, diskOffering); } if(!validateVolumeSizeRange(diskOffering.getDiskSize()/1024)){//convert size from mb to gb for validation throw new InvalidParameterValueException("Invalid size for custom volume creation: " + size+" ,max volume size is:"+_maxVolumeSizeInGb); } if(diskOffering.getDiskSize() > 0) { size = (diskOffering.getDiskSize()*1024*1024);//the disk offering size is in MB, which needs to be converted into bytes } else{ if(!validateVolumeSizeRange(size)){ throw new InvalidParameterValueException("Invalid size for custom volume creation: " + size+" ,max volume size is:"+_maxVolumeSizeInGb); } size = (size*1024*1024*1024);//custom size entered is in GB, to be converted to bytes } } } else { Long snapshotId = cmd.getSnapshotId(); Snapshot snapshotCheck = _snapshotDao.findById(snapshotId); if (snapshotCheck == null) { throw new ServerApiException (BaseCmd.PARAM_ERROR, "unable to find a snapshot with id " + snapshotId); } VolumeVO vol = _volsDao.findById(snapshotCheck.getVolumeId()); zoneId = vol.getDataCenterId(); diskOfferingId = vol.getDiskOfferingId(); size = vol.getSize(); if (account != null) { if (isAdmin(account.getType())) { Account snapshotOwner = _accountDao.findById(snapshotCheck.getAccountId()); if (!_domainDao.isChildDomain(account.getDomainId(), snapshotOwner.getDomainId())) { throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to create volume from snapshot with id " + snapshotId + ", permission denied."); } } else if (account.getId() != snapshotCheck.getAccountId()) { throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to find a snapshot with id " + snapshotId + " for this account"); } } } // Check that there is a shared primary storage pool in the specified zone List<StoragePoolVO> storagePools = _storagePoolDao.listByDataCenterId(zoneId); boolean sharedPoolExists = false; for (StoragePoolVO storagePool : storagePools) { if (storagePool.isShared()) { sharedPoolExists = true; } } // Check that there is at least one host in the specified zone List<HostVO> hosts = _hostDao.listByDataCenter(zoneId); if (hosts.isEmpty()) { throw new InvalidParameterValueException("Please add a host in the specified zone before creating a new volume."); } if (!sharedPoolExists) { throw new InvalidParameterValueException("Please specify a zone that has at least one shared primary storage pool."); } String userSpecifiedName = cmd.getVolumeName(); if (userSpecifiedName == null) { userSpecifiedName = getRandomVolumeName(); } VolumeVO volume = new VolumeVO(userSpecifiedName, -1, -1, -1, -1, new Long(-1), null, null, 0, Volume.VolumeType.DATADISK); volume.setPoolId(null); volume.setDataCenterId(zoneId); volume.setPodId(null); volume.setAccountId(targetAccount.getId()); volume.setDomainId(((account == null) ? Domain.ROOT_DOMAIN : account.getDomainId())); volume.setMirrorState(MirrorState.NOT_MIRRORED); volume.setDiskOfferingId(diskOfferingId); volume.setSize(size); volume.setStorageResourceType(StorageResourceType.STORAGE_POOL); volume.setInstanceId(null); volume.setUpdated(new Date()); volume.setStatus(AsyncInstanceCreateStatus.Creating); volume.setDomainId((account == null) ? Domain.ROOT_DOMAIN : account.getDomainId()); volume.setState(Volume.State.Allocated); volume = _volsDao.persist(volume); return volume; } @Override @DB public VolumeVO createVolume(CreateVolumeCmd cmd) { VolumeVO volume = _volsDao.findById(cmd.getEntityId()); // VolumeVO createdVolume = null; Long userId = UserContext.current().getUserId(); if (cmd.getSnapshotId() != null) { return createVolumeFromSnapshot(volume, cmd.getSnapshotId(), cmd.getStartEventId()); } else { DataCenterVO dc = _dcDao.findById(cmd.getZoneId()); DiskOfferingVO diskOffering = _diskOfferingDao.findById(cmd.getDiskOfferingId()); long sizeMB = diskOffering.getDiskSize(); /* VMTemplateVO template = _templateDao.findById(volume.getTemplateId()); long size = diskOffering.getDiskSize(); try { List<StoragePoolVO> poolsToAvoid = new ArrayList<StoragePoolVO>(); Set<Long> podsToAvoid = new HashSet<Long>(); Pair<HostPodVO, Long> pod = null; HypervisorType hypervisorType = ((template == null) ? HypervisorType.None : template.getHypervisorType()); while ((pod = _agentMgr.findPod(null, null, dc, volume.getAccountId(), podsToAvoid)) != null) { if ((createdVolume = createVolume(volume, null, null, dc, pod.first(), null, null, diskOffering, poolsToAvoid, size, hypervisorType)) != null) { break; } else { podsToAvoid.add(pod.first().getId()); } } */ // Create an event EventVO event = new EventVO(); event.setAccountId(volume.getAccountId()); event.setUserId(userId); event.setType(EventTypes.EVENT_VOLUME_CREATE); event.setStartId(cmd.getStartEventId()); /* Transaction txn = Transaction.currentTxn(); txn.start(); if (createdVolume != null) { */ // Increment the number of volumes // _accountMgr.incrementResourceCount(createdVolume.getAccountId(), ResourceType.volume); _accountMgr.incrementResourceCount(volume.getAccountId(), ResourceType.volume); VolumeVO volForUpdate = _volsDao.createForUpdate(); volForUpdate.setStatus(AsyncInstanceCreateStatus.Created); _volsDao.update(volume.getId(), volForUpdate); // Set event parameters // long sizeMB = createdVolume.getSize() / (1024 * 1024); // StoragePoolVO pool = _storagePoolDao.findById(createdVolume.getPoolId()); // String eventParams = "id=" + createdVolume.getId() + "\ndoId=" + diskOffering.getId() + "\ntId=" + -1 + "\ndcId=" + dc.getId() + "\nsize=" + sizeMB; String eventParams = "id=" + volume.getId() + "\ndoId=" + diskOffering.getId() + "\ntId=" + -1 + "\ndcId=" + dc.getId() + "\nsize=" + sizeMB; event.setLevel(EventVO.LEVEL_INFO); // event.setDescription("Created volume: " + createdVolume.getName() + " with size: " + sizeMB + " MB in pool: " + pool.getName()); // event.setDescription("Created volume: " + createdVolume.getName() + " with size: " + sizeMB + " MB"); event.setDescription("Created volume: " + volume.getName() + " with size: " + sizeMB + " MB"); event.setParameters(eventParams); event.setState(Event.State.Completed); _eventDao.persist(event); /* } else { event.setDescription("Unable to create a volume for " + volume); event.setLevel(EventVO.LEVEL_ERROR); event.setState(Event.State.Completed); _eventDao.persist(event); } txn.commit(); } catch (Exception e) { s_logger.error("Unhandled exception while creating volume " + volume.getName(), e); } */ } // return createdVolume; return _volsDao.findById(volume.getId()); } @Override @DB public void destroyVolume(VolumeVO volume) { Transaction txn = Transaction.currentTxn(); txn.start(); Long volumeId = volume.getId(); _volsDao.destroyVolume(volumeId); String eventParams = "id=" + volumeId; EventVO event = new EventVO(); event.setAccountId(volume.getAccountId()); event.setUserId(1L); event.setType(EventTypes.EVENT_VOLUME_DELETE); event.setParameters(eventParams); event.setDescription("Volume " +volume.getName()+ " deleted"); event.setLevel(EventVO.LEVEL_INFO); _eventDao.persist(event); // Delete the recurring snapshot policies for this volume. _snapshotMgr.deletePoliciesForVolume(volumeId); // Decrement the resource count for volumes _accountMgr.decrementResourceCount(volume.getAccountId(), ResourceType.volume); txn.commit(); } @Override public void createCapacityEntry(StoragePoolVO storagePool) { createCapacityEntry(storagePool, 0); } @Override public void createCapacityEntry(StoragePoolVO storagePool, long allocated) { SearchCriteria<CapacityVO> capacitySC = _capacityDao.createSearchCriteria(); capacitySC.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, storagePool.getId()); capacitySC.addAnd("dataCenterId", SearchCriteria.Op.EQ, storagePool.getDataCenterId()); capacitySC.addAnd("capacityType", SearchCriteria.Op.EQ, CapacityVO.CAPACITY_TYPE_STORAGE); List<CapacityVO> capacities = _capacityDao.search(capacitySC, null); if (capacities.size() == 0) { CapacityVO capacity = new CapacityVO(storagePool.getId(), storagePool.getDataCenterId(), storagePool.getPodId(), storagePool.getAvailableBytes(), storagePool.getCapacityBytes(), CapacityVO.CAPACITY_TYPE_STORAGE); _capacityDao.persist(capacity); } else { CapacityVO capacity = capacities.get(0); capacity.setTotalCapacity(storagePool.getCapacityBytes()); long used = storagePool.getCapacityBytes() - storagePool.getAvailableBytes(); if( used <= 0 ) { used = 0; } capacity.setUsedCapacity(used); _capacityDao.update(capacity.getId(), capacity); } s_logger.debug("Successfully set Capacity - " +storagePool.getCapacityBytes()+ " for CAPACITY_TYPE_STORAGE, DataCenterId - " +storagePool.getDataCenterId()+ ", HostOrPoolId - " +storagePool.getId()+ ", PodId " +storagePool.getPodId()); capacitySC = _capacityDao.createSearchCriteria(); capacitySC.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, storagePool.getId()); capacitySC.addAnd("dataCenterId", SearchCriteria.Op.EQ, storagePool.getDataCenterId()); capacitySC.addAnd("capacityType", SearchCriteria.Op.EQ, CapacityVO.CAPACITY_TYPE_STORAGE_ALLOCATED); capacities = _capacityDao.search(capacitySC, null); int provFactor = 1; if( storagePool.getPoolType() == StoragePoolType.NetworkFilesystem ) { provFactor = _overProvisioningFactor; } if (capacities.size() == 0) { CapacityVO capacity = new CapacityVO(storagePool.getId(), storagePool.getDataCenterId(), storagePool.getPodId(), allocated, storagePool.getCapacityBytes() * provFactor, CapacityVO.CAPACITY_TYPE_STORAGE_ALLOCATED); _capacityDao.persist(capacity); } else { CapacityVO capacity = capacities.get(0); long currCapacity = provFactor * storagePool.getCapacityBytes(); boolean update = false; if (capacity.getTotalCapacity() != currCapacity) { capacity.setTotalCapacity(currCapacity); update = true; } if ( allocated != 0 ) { capacity.setUsedCapacity(allocated); update = true; } if ( update ) { _capacityDao.update(capacity.getId(), capacity); } } s_logger.debug("Successfully set Capacity - " +storagePool.getCapacityBytes()* _overProvisioningFactor+ " for CAPACITY_TYPE_STORAGE_ALLOCATED, DataCenterId - " +storagePool.getDataCenterId()+ ", HostOrPoolId - " +storagePool.getId()+ ", PodId " +storagePool.getPodId()); } @Override public Answer sendToHostsOnStoragePool(Long poolId, Command cmd, String basicErrMsg) { return sendToHostsOnStoragePool(poolId, cmd, basicErrMsg, 1, 0, false, null); } @Override public Answer sendToHostsOnStoragePool(Long poolId, Command cmd, String basicErrMsg, int totalRetries, int pauseBeforeRetry, boolean shouldBeSnapshotCapable, Long vmId) { Answer answer = null; Long hostId = null; StoragePoolVO storagePool = _storagePoolDao.findById(poolId); List<Long> hostsToAvoid = new ArrayList<Long>(); int tryCount = 0; boolean sendToVmHost = sendToVmResidesOn(storagePool, cmd); if (chooseHostForStoragePool(storagePool, hostsToAvoid, sendToVmHost, vmId) == null) { // Don't just fail. The host could be reconnecting. // wait for some time for it to get connected // Wait for 3*ping.interval, since the code attempts a manual // reconnect after that timeout. try { Thread.sleep(3 * _pingInterval * 1000); } catch (InterruptedException e) { s_logger.error("Interrupted while waiting for any host on poolId: " + poolId + " to get connected. " + e.getMessage()); // continue. } } while ((hostId = chooseHostForStoragePool(storagePool, hostsToAvoid, sendToVmHost, vmId)) != null && tryCount++ < totalRetries) { String errMsg = basicErrMsg + " on host: " + hostId + " try: " + tryCount + ", reason: "; hostsToAvoid.add(hostId); try { HostVO hostVO = _hostDao.findById(hostId); if (shouldBeSnapshotCapable) { if (hostVO == null ) { continue; } } s_logger.debug("Trying to execute Command: " + cmd + " on host: " + hostId + " try: " + tryCount); // set 120 min timeout for storage related command answer = _agentMgr.send(hostId, cmd, 120*60*1000); if (answer != null && answer.getResult()) { return answer; } else { s_logger.warn(errMsg + ((answer != null) ? answer.getDetails() : "null")); Thread.sleep(pauseBeforeRetry * 1000); } } catch (AgentUnavailableException e1) { s_logger.warn(errMsg + e1.getMessage(), e1); } catch (OperationTimedoutException e1) { s_logger.warn(errMsg + e1.getMessage(), e1); } catch (InterruptedException e) { s_logger.warn(errMsg + e.getMessage(), e); } } s_logger.error(basicErrMsg + ", no hosts available to execute command: " + cmd); return answer; } protected class StorageGarbageCollector implements Runnable { public StorageGarbageCollector() { } @Override public void run() { try { s_logger.info("Storage Garbage Collection Thread is running."); GlobalLock scanLock = GlobalLock.getInternLock(this.getClass().getName()); try { if (scanLock.lock(3)) { try { cleanupStorage(true); } finally { scanLock.unlock(); } } } finally { scanLock.releaseRef(); } } catch (Exception e) { s_logger.error("Caught the following Exception", e); } } } @Override public void cleanupStorage(boolean recurring) { // Cleanup primary storage pools List<StoragePoolVO> storagePools = _storagePoolDao.listAll(); for (StoragePoolVO pool : storagePools) { try { if (recurring && pool.isLocal()) { continue; } List<VMTemplateStoragePoolVO> unusedTemplatesInPool = _tmpltMgr.getUnusedTemplatesInPool(pool); s_logger.debug("Storage pool garbage collector found " + unusedTemplatesInPool.size() + " templates to clean up in storage pool: " + pool.getName()); for (VMTemplateStoragePoolVO templatePoolVO : unusedTemplatesInPool) { if (templatePoolVO.getDownloadState() != VMTemplateStorageResourceAssoc.Status.DOWNLOADED) { s_logger.debug("Storage pool garbage collector is skipping templatePoolVO with ID: " + templatePoolVO.getId() + " because it is not completely downloaded."); continue; } if (!templatePoolVO.getMarkedForGC()) { templatePoolVO.setMarkedForGC(true); _vmTemplatePoolDao.update(templatePoolVO.getId(), templatePoolVO); s_logger.debug("Storage pool garbage collector has marked templatePoolVO with ID: " + templatePoolVO.getId() + " for garbage collection."); continue; } _tmpltMgr.evictTemplateFromStoragePool(templatePoolVO); } } catch (Exception e) { s_logger.warn("Problem cleaning up primary storage pool " + pool, e); } } // Cleanup secondary storage hosts List<HostVO> secondaryStorageHosts = _hostDao.listSecondaryStorageHosts(); for (HostVO secondaryStorageHost : secondaryStorageHosts) { try { long hostId = secondaryStorageHost.getId(); List<VMTemplateHostVO> destroyedTemplateHostVOs = _vmTemplateHostDao.listDestroyed(hostId); s_logger.debug("Secondary storage garbage collector found " + destroyedTemplateHostVOs.size() + " templates to cleanup on secondary storage host: " + secondaryStorageHost.getName()); for (VMTemplateHostVO destroyedTemplateHostVO : destroyedTemplateHostVOs) { if (!_tmpltMgr.templateIsDeleteable(destroyedTemplateHostVO)) { s_logger.debug("Not deleting template at: " + destroyedTemplateHostVO.getInstallPath()); continue; } String installPath = destroyedTemplateHostVO.getInstallPath(); if (installPath != null) { Answer answer = _agentMgr.easySend(hostId, new DeleteTemplateCommand(destroyedTemplateHostVO.getInstallPath())); if (answer == null || !answer.getResult()) { s_logger.debug("Failed to delete template at: " + destroyedTemplateHostVO.getInstallPath()); } else { _vmTemplateHostDao.remove(destroyedTemplateHostVO.getId()); s_logger.debug("Deleted template at: " + destroyedTemplateHostVO.getInstallPath()); } } else { _vmTemplateHostDao.remove(destroyedTemplateHostVO.getId()); } } } catch (Exception e) { s_logger.warn("problem cleaning up secondary storage " + secondaryStorageHost, e); } } List<VolumeVO> vols = _volsDao.listRemovedButNotDestroyed(); for (VolumeVO vol : vols) { try { Long poolId = vol.getPoolId(); Answer answer = null; StoragePoolVO pool = _storagePoolDao.findById(poolId); final DestroyCommand cmd = new DestroyCommand(pool, vol, null); answer = sendToPool(pool, cmd); if (answer != null && answer.getResult()) { s_logger.debug("Destroyed " + vol); vol.setDestroyed(true); _volsDao.update(vol.getId(), vol); } } catch (Exception e) { s_logger.warn("Unable to destroy " + vol.getId(), e); } } } @Override public StoragePoolVO getStoragePoolForVm(long vmId) { SearchCriteria<StoragePoolVO> sc = PoolsUsedByVmSearch.create(); sc.setJoinParameters("volumes", "vm", vmId); sc.setJoinParameters("volumes", "status", AsyncInstanceCreateStatus.Created.toString()); List<StoragePoolVO> sps= _storagePoolDao.search(sc, null); if( sps.size() == 0 ) { throw new RuntimeException("Volume is not created for VM " + vmId); } StoragePoolVO sp = sps.get(0); for (StoragePoolVO tsp: sps ) { // use the local storage pool to choose host, // shared storage pool should be in the same cluster as local storage pool if( tsp.isLocal()) { sp = tsp; break; } } return sp; } @Override public String getPrimaryStorageNameLabel(VolumeVO volume) { Long poolId = volume.getPoolId(); // poolId is null only if volume is destroyed, which has been checked before. assert poolId != null; StoragePoolVO storagePoolVO = _storagePoolDao.findById(poolId); assert storagePoolVO != null; return storagePoolVO.getUuid(); } @Override @DB public synchronized StoragePoolVO preparePrimaryStorageForMaintenance(PreparePrimaryStorageForMaintenanceCmd cmd) throws ServerApiException{ Long primaryStorageId = cmd.getId(); Long userId = UserContext.current().getUserId(); boolean restart = true; StoragePoolVO primaryStorage = null; try { Transaction.currentTxn(); //1. Get the primary storage record and perform validation check primaryStorage = _storagePoolDao.acquireInLockTable(primaryStorageId); if(primaryStorage == null){ String msg = "Unable to obtain lock on the storage pool in preparePrimaryStorageForMaintenance()"; s_logger.error(msg); throw new ResourceUnavailableException(msg); } if (!primaryStorage.getStatus().equals(Status.Up) && !primaryStorage.getStatus().equals(Status.ErrorInMaintenance)) { throw new InvalidParameterValueException("Primary storage with id " + primaryStorageId + " is not ready for migration, as the status is:" + primaryStorage.getStatus().toString()); } //set the pool state to prepare for maintenance primaryStorage.setStatus(Status.PrepareForMaintenance); _storagePoolDao.persist(primaryStorage); //check to see if other ps exist //if they do, then we can migrate over the system vms to them //if they dont, then just stop all vms on this one List<StoragePoolVO> upPools = _storagePoolDao.listPoolsByStatus(Status.Up); if(upPools == null || upPools.size() == 0) { restart = false; } //2. Get a list of all the volumes within this storage pool List<VolumeVO> allVolumes = _volsDao.findByPoolId(primaryStorageId); //3. Each volume has an instance associated with it, stop the instance if running for(VolumeVO volume : allVolumes) { VMInstanceVO vmInstance = _vmInstanceDao.findById(volume.getInstanceId()); if(vmInstance == null) { continue; } //shut down the running vms if(vmInstance.getState().equals(State.Running) || vmInstance.getState().equals(State.Starting)) { //if the instance is of type consoleproxy, call the console proxy if(vmInstance.getType().equals(VirtualMachine.Type.ConsoleProxy)) { //make sure it is not restarted again, update config to set flag to false _configMgr.updateConfiguration(userId, "consoleproxy.restart", "false"); //create a dummy event long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_PROXY_STOP, "stopping console proxy with Id: "+vmInstance.getId()); //call the consoleproxymanager if(!_consoleProxyMgr.stopProxy(vmInstance.getId(), eventId)) { String errorMsg = "There was an error stopping the console proxy id: "+vmInstance.getId()+" ,cannot enable storage maintenance"; s_logger.warn(errorMsg); primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new CloudRuntimeException(errorMsg); } else if(restart) { //create a dummy event long eventId1 = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_PROXY_START, "starting console proxy with Id: "+vmInstance.getId()); //Restore config val for consoleproxy.restart to true _configMgr.updateConfiguration(userId, "consoleproxy.restart", "true"); if(_consoleProxyMgr.startProxy(vmInstance.getId(), eventId1)==null) { String errorMsg = "There was an error starting the console proxy id: "+vmInstance.getId()+" on another storage pool, cannot enable primary storage maintenance"; s_logger.warn(errorMsg); primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new CloudRuntimeException(errorMsg); } } } //if the instance is of type uservm, call the user vm manager if(vmInstance.getType().equals(VirtualMachine.Type.User)) { //create a dummy event long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_VM_STOP, "stopping user vm with Id: "+vmInstance.getId()); if(!_userVmMgr.stopVirtualMachine(userId, vmInstance.getId(),eventId)) { String errorMsg = "There was an error stopping the user vm id: "+vmInstance.getId()+" ,cannot enable storage maintenance"; s_logger.warn(errorMsg); primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new CloudRuntimeException(errorMsg); } } //if the instance is of type secondary storage vm, call the secondary storage vm manager if(vmInstance.getType().equals(VirtualMachine.Type.SecondaryStorageVm)) { //create a dummy event long eventId1 = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_SSVM_STOP, "stopping ssvm with Id: "+vmInstance.getId()); if(!_secStorageMgr.stopSecStorageVm(vmInstance.getId(), eventId1)) { String errorMsg = "There was an error stopping the ssvm id: "+vmInstance.getId()+" ,cannot enable storage maintenance"; s_logger.warn(errorMsg); primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new CloudRuntimeException(errorMsg); } else if(restart) { //create a dummy event and restart the ssvm immediately long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_SSVM_START, "starting ssvm with Id: "+vmInstance.getId()); if(_secStorageMgr.startSecStorageVm(vmInstance.getId(), eventId)==null) { String errorMsg = "There was an error starting the ssvm id: "+vmInstance.getId()+" on another storage pool, cannot enable primary storage maintenance"; s_logger.warn(errorMsg); primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new CloudRuntimeException(errorMsg); } } } //if the instance is of type domain router vm, call the network manager if(vmInstance.getType().equals(VirtualMachine.Type.DomainRouter)) { //create a dummy event long eventId2 = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_ROUTER_STOP, "stopping domain router with Id: "+vmInstance.getId()); if(!_routerMgr.stopRouter(vmInstance.getId(), eventId2)) { String errorMsg = "There was an error stopping the domain router id: "+vmInstance.getId()+" ,cannot enable primary storage maintenance"; s_logger.warn(errorMsg); primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new CloudRuntimeException(errorMsg); } else if(restart) { //create a dummy event and restart the domr immediately long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_PROXY_START, "starting domr with Id: "+vmInstance.getId()); if(_routerMgr.startRouter(vmInstance.getId(), eventId)==null) { String errorMsg = "There was an error starting the domain router id: "+vmInstance.getId()+" on another storage pool, cannot enable primary storage maintenance"; s_logger.warn(errorMsg); primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new CloudRuntimeException(errorMsg); } } } } } //5. Update the status primaryStorage.setStatus(Status.Maintenance); _storagePoolDao.persist(primaryStorage); return _storagePoolDao.findById(primaryStorageId); } catch (Exception e) { if(e instanceof ResourceUnavailableException){ s_logger.error("Exception in enabling primary storage maintenance:",e); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, e.getMessage()); } if(e instanceof InvalidParameterValueException){ s_logger.error("Exception in enabling primary storage maintenance:",e); throw new ServerApiException(BaseCmd.PARAM_ERROR, e.getMessage()); } //for everything else s_logger.error("Exception in enabling primary storage maintenance:",e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); }finally{ _storagePoolDao.releaseFromLockTable(primaryStorage.getId()); } } private Long saveScheduledEvent(Long userId, Long accountId, String type, String description) { EventVO event = new EventVO(); event.setUserId(userId); event.setAccountId(accountId); event.setType(type); event.setState(Event.State.Scheduled); event.setDescription("Scheduled async job for "+description); event = _eventDao.persist(event); return event.getId(); } @Override @DB public synchronized StoragePoolVO cancelPrimaryStorageForMaintenance(CancelPrimaryStorageMaintenanceCmd cmd) throws ServerApiException{ Long primaryStorageId = cmd.getId(); Long userId = UserContext.current().getUserId(); StoragePoolVO primaryStorage = null; try { Transaction.currentTxn(); //1. Get the primary storage record and perform validation check primaryStorage = _storagePoolDao.acquireInLockTable(primaryStorageId); if(primaryStorage == null){ String msg = "Unable to obtain lock on the storage pool in cancelPrimaryStorageForMaintenance()"; s_logger.error(msg); throw new ResourceUnavailableException(msg); } if (primaryStorage.getStatus().equals(Status.Up)) { throw new StorageUnavailableException("Primary storage with id " + primaryStorageId + " is not ready to complete migration, as the status is:" + primaryStorage.getStatus().toString(), primaryStorageId); } //set state to cancelmaintenance primaryStorage.setStatus(Status.CancelMaintenance); _storagePoolDao.persist(primaryStorage); //2. Get a list of all the volumes within this storage pool List<VolumeVO> allVolumes = _volsDao.findByPoolId(primaryStorageId); //3. If the volume is not removed AND not destroyed, start the vm corresponding to it for(VolumeVO volume: allVolumes) { if((!volume.destroyed) && (volume.removed == null)) { VMInstanceVO vmInstance = _vmInstanceDao.findById(volume.getInstanceId()); if(vmInstance.getState().equals(State.Stopping) || vmInstance.getState().equals(State.Stopped)) { //if the instance is of type consoleproxy, call the console proxy if(vmInstance.getType().equals(VirtualMachine.Type.ConsoleProxy)) { //create a dummy event long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_PROXY_START, "starting console proxy with Id: "+vmInstance.getId()); if(_consoleProxyMgr.startProxy(vmInstance.getId(), eventId) == null) { String msg = "There was an error starting the console proxy id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance"; s_logger.warn(msg); throw new ResourceUnavailableException(msg); } } //if the instance is of type ssvm, call the ssvm manager if(vmInstance.getType().equals(VirtualMachine.Type.SecondaryStorageVm)) { //create a dummy event long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_SSVM_START, "starting ssvm with Id: "+vmInstance.getId()); if(_secStorageMgr.startSecStorageVm(vmInstance.getId(), eventId) == null) { String msg = "There was an error starting the ssvm id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance"; s_logger.warn(msg); throw new ResourceUnavailableException(msg); } } //if the instance is of type user vm, call the user vm manager if(vmInstance.getType().equals(VirtualMachine.Type.User)) { //create a dummy event long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_VM_START, "starting user vm with Id: "+vmInstance.getId()); try { if(_userVmMgr.start(vmInstance.getId(), eventId) == null) { String msg = "There was an error starting the user vm id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance"; s_logger.warn(msg); throw new ResourceUnavailableException(msg); } } catch (StorageUnavailableException e) { String msg = "There was an error starting the user vm id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance"; s_logger.warn(msg,e); throw new ResourceUnavailableException(msg); } catch (InsufficientCapacityException e) { String msg = "There was an error starting the user vm id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance"; s_logger.warn(msg,e); throw new ResourceUnavailableException(msg); } catch (ConcurrentOperationException e) { String msg = "There was an error starting the user vm id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance"; s_logger.warn(msg,e); primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new ResourceUnavailableException(msg); } catch (ExecutionException e) { String msg = "There was an error starting the user vm id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance"; s_logger.warn(msg,e); throw new ResourceUnavailableException(msg); } } } } } //Restore config val for consoleproxy.restart to true try { _configMgr.updateConfiguration(userId, "consoleproxy.restart", "true"); } catch (InvalidParameterValueException e) { String msg = "Error changing consoleproxy.restart back to false at end of cancel maintenance:"; s_logger.warn(msg,e); throw new ResourceUnavailableException(msg); } catch (CloudRuntimeException e) { String msg = "Error changing consoleproxy.restart back to false at end of cancel maintenance:"; s_logger.warn(msg,e); throw new ResourceUnavailableException(msg); } //Change the storage state back to up primaryStorage.setStatus(Status.Up); _storagePoolDao.persist(primaryStorage); return primaryStorage; } catch (Exception e) { if(e instanceof ResourceUnavailableException){ primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, e.getMessage()); } else if(e instanceof InvalidParameterValueException){ primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new ServerApiException(BaseCmd.PARAM_ERROR, e.getMessage()); } else{//all other exceptions primaryStorage.setStatus(Status.ErrorInMaintenance); _storagePoolDao.persist(primaryStorage); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); } }finally{ _storagePoolDao.releaseFromLockTable(primaryStorage.getId()); } } private boolean sendToVmResidesOn(StoragePoolVO storagePool, Command cmd) { ClusterVO cluster = _clusterDao.findById(storagePool.getClusterId()); if ((cluster.getHypervisorType() == HypervisorType.KVM) && ((cmd instanceof ManageSnapshotCommand) || (cmd instanceof BackupSnapshotCommand))) { return true; } else { return false; } } private boolean isAdmin(short accountType) { return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); } @Override public boolean deleteVolume(DeleteVolumeCmd cmd) throws InvalidParameterValueException { Account account = UserContext.current().getAccount(); Long volumeId = cmd.getId(); boolean isAdmin; if (account == null) { // Admin API call isAdmin = true; } else { // User API call isAdmin = isAdmin(account.getType()); } // Check that the volume ID is valid VolumeVO volume = _volsDao.findById(volumeId); if (volume == null) { throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find volume with ID: " + volumeId); } // If the account is not an admin, check that the volume is owned by the account that was passed in if (!isAdmin) { if (account.getId() != volume.getAccountId()) { throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find volume with ID: " + volumeId + " for account: " + account.getAccountName()); } } else if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), volume.getDomainId())) { throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to delete volume with id " + volumeId + ", permission denied."); } // Check that the volume is stored on shared storage // NOTE: We used to ensure the volume is on shared storage before deleting. However, this seems like an unnecessary check since all we allow // is deleting a detached volume. Is there a technical reason why the volume has to be on shared storage? If so, uncomment this...otherwise, // just delete the detached volume regardless of storage pool. // if (!volumeOnSharedStoragePool(volume)) { // throw new InvalidParameterValueException("Please specify a volume that has been created on a shared storage pool."); // } // Check that the volume is not currently attached to any VM if (volume.getInstanceId() != null) { throw new InvalidParameterValueException("Please specify a volume that is not attached to any VM."); } // Check that the volume is not already destroyed if (volume.getDestroyed()) { throw new InvalidParameterValueException("Please specify a volume that is not already destroyed."); } try { // Destroy the volume destroyVolume(volume); } catch (Exception e) { s_logger.warn("Error destroying volume:"+e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Error destroying volume:"+e); } return true; } private boolean validateVolumeSizeRange(long size) throws InvalidParameterValueException { if (size<0 || (size>0 && size < 1)) { throw new InvalidParameterValueException("Please specify a size of at least 1 Gb."); } else if (size > _maxVolumeSizeInGb) { throw new InvalidParameterValueException("The maximum size allowed is " + _maxVolumeSizeInGb + " Gb."); } return true; } protected DiskProfile toDiskProfile(VolumeVO vol, DiskOfferingVO offering) { return new DiskProfile(vol.getId(), vol.getVolumeType(), vol.getName(), offering.getId(), vol.getSize(), offering.getTagsArray(), offering.getUseLocalStorage(), offering.isRecreatable(), vol.getTemplateId()); } @Override public <T extends VMInstanceVO> DiskProfile allocateRawVolume(VolumeType type, String name, DiskOfferingVO offering, Long size, T vm, Account owner) { if (size == null) { size = offering.getDiskSizeInBytes(); } VolumeVO vol = new VolumeVO(type, name, vm.getDataCenterId(), owner.getDomainId(), owner.getId(), offering.getId(), size); if (vm != null) { vol.setInstanceId(vm.getId()); } if(type.equals(VolumeType.ROOT)) { vol.setDeviceId(0l); } else { vol.setDeviceId(1l); } vol = _volsDao.persist(vol); return toDiskProfile(vol, offering); } @Override public <T extends VMInstanceVO> DiskProfile allocateTemplatedVolume(VolumeType type, String name, DiskOfferingVO offering, VMTemplateVO template, T vm, Account owner) { assert (template.getFormat() != ImageFormat.ISO) : "ISO is not a template really...."; SearchCriteria<VMTemplateHostVO> sc = HostTemplateStatesSearch.create(); sc.setParameters("id", template.getId()); sc.setParameters("state", com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOADED); sc.setJoinParameters("host", "dcId", vm.getDataCenterId()); List<VMTemplateHostVO> sss = _vmTemplateHostDao.search(sc, null); if (sss.size() == 0) { throw new CloudRuntimeException("Template " + template.getName() + " has not been completely downloaded to zone " + vm.getDataCenterId()); } VMTemplateHostVO ss = sss.get(0); VolumeVO vol = new VolumeVO(type, name, vm.getDataCenterId(), owner.getDomainId(), owner.getId(), offering.getId(), ss.getSize()); if (vm != null) { vol.setInstanceId(vm.getId()); } vol.setTemplateId(template.getId()); if(type.equals(VolumeType.ROOT)) { vol.setDeviceId(0l); } else { vol.setDeviceId(1l); } vol = _volsDao.persist(vol); return toDiskProfile(vol, offering); } final protected DiskProfile createDiskCharacteristics(VolumeVO volume, DiskOfferingVO offering) { return new DiskProfile(volume.getId(), volume.getVolumeType(), volume.getName(), offering.getId(), volume.getSize(), offering.getTagsArray(), offering.getUseLocalStorage(), offering.isRecreatable(), volume.getTemplateId()); } final protected DiskProfile createDiskCharacteristics(VolumeVO volume) { DiskOfferingVO offering = _diskOfferingDao.findById(volume.getDiskOfferingId()); return createDiskCharacteristics(volume, offering); } protected StoragePool findStorage(DiskProfile dskCh, DeployDestination dest, VirtualMachineProfile vm, List<? extends Volume> alreadyAllocated, Set<? extends StoragePool> avoid) { for (StoragePoolAllocator allocator : _storagePoolAllocators) { StoragePool pool = allocator.allocateTo(dskCh, vm, dest, alreadyAllocated, avoid); if (pool != null) { return pool; } } return null; } @Override public void prepare(VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest) throws StorageUnavailableException, InsufficientStorageCapacityException { List<VolumeVO> vols = _volsDao.findUsableVolumesForInstance(vm.getId()); if (s_logger.isDebugEnabled()) { s_logger.debug("Preparing " + vols.size() + " volumes for " + vm); } List<VolumeVO> recreateVols = new ArrayList<VolumeVO>(vols.size()); int i = 0; for (VolumeVO vol : vols) { Volume.State state = vol.getState(); if (state == Volume.State.Ready) { StoragePoolVO pool = _storagePoolDao.findById(vol.getPoolId()); if (pool.getRemoved() != null || pool.isInMaintenance()) { if (vol.isRecreatable()) { if (s_logger.isDebugEnabled()) { s_logger.debug("Volume " + vol + " has to be recreated due to storage pool " + pool + " is unavailable"); } recreateVols.add(vol); } else { throw new StorageUnavailableException("Volume " + vol + " is not available on the storage pool.", pool.getId()); } } else { if (s_logger.isDebugEnabled()) { s_logger.debug("Volume " + vol + " is ready."); } vm.addDisk(new VolumeTO(vol, pool)); } } else if (state == Volume.State.Allocated) { if (s_logger.isDebugEnabled()) { s_logger.debug("Creating volume " + vol + " for the first time."); } recreateVols.add(vol); } else { throw new StorageUnavailableException("Volume " + vol + " can not be used", vol.getPoolId()); } } for (VolumeVO vol : recreateVols) { VolumeVO newVol; if (vol.getState() == Volume.State.Allocated) { newVol = vol; } else { newVol = switchVolume(vol); if (s_logger.isDebugEnabled()) { s_logger.debug("Created new volume " + newVol + " for old volume " + vol); } } try { _volsDao.update(newVol, Volume.Event.Create); } catch(ConcurrentOperationException e) { throw new StorageUnavailableException("Unable to create " + newVol, newVol.getPoolId()); } Pair<VolumeTO, StoragePool> created = createVolume(newVol, _diskOfferingDao.findById(newVol.getDiskOfferingId()), vm, vols, dest); if (created == null) { newVol.setPoolId(null); try { _volsDao.update(newVol, Volume.Event.OperationFailed); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to update the failure on a volume: " + newVol, e); } throw new StorageUnavailableException("Unable to create " + newVol, newVol.getPoolId()); } created.first().setDeviceId(newVol.getDeviceId().intValue()); newVol.setStatus(AsyncInstanceCreateStatus.Created); newVol.setFolder(created.second().getPath()); newVol.setPath(created.first().getPath()); newVol.setSize(created.first().getSize()); newVol.setPoolType(created.second().getPoolType()); newVol.setPodId(created.second().getPodId()); try { _volsDao.update(newVol, Volume.Event.OperationSucceeded); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to update an CREATE operation succeeded on volume " + newVol, e); } if (s_logger.isDebugEnabled()) { s_logger.debug("Volume " + newVol + " is created on " + created.second()); } vm.addDisk(created.first()); } } @DB protected VolumeVO switchVolume(VolumeVO existingVolume) throws StorageUnavailableException { Transaction txn = Transaction.currentTxn(); try { txn.start(); _volsDao.update(existingVolume, Volume.Event.Destroy); VolumeVO newVolume = allocateDuplicateVolume(existingVolume); txn.commit(); return newVolume; } catch (ConcurrentOperationException e) { throw new StorageUnavailableException("Unable to duplicate the volume " + existingVolume, existingVolume.getPoolId(), e); } } public Pair<VolumeTO, StoragePool> createVolume(VolumeVO toBeCreated, DiskOfferingVO offering, VirtualMachineProfile<? extends VirtualMachine> vm, List<? extends Volume> alreadyCreated, DeployDestination dest) { if (s_logger.isDebugEnabled()) { s_logger.debug("Creating volume: " + toBeCreated); } DiskProfile diskProfile = new DiskProfile(toBeCreated, offering, vm.getHypervisorType()); VMTemplateVO template = null; if (toBeCreated.getTemplateId() != null) { template = _templateDao.findById(toBeCreated.getTemplateId()); } Set<StoragePool> avoids = new HashSet<StoragePool>(); StoragePool pool = null; while ((pool = findStorage(diskProfile, dest, vm, alreadyCreated, avoids)) != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Trying to create in " + pool); } avoids.add(pool); toBeCreated.setPoolId(pool.getId()); try { _volsDao.update(toBeCreated, Volume.Event.OperationRetry); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to retry a create operation on volume " + toBeCreated); } CreateCommand cmd = null; if (template != null && template.getFormat() != Storage.ImageFormat.ISO) { VMTemplateStoragePoolVO tmpltStoredOn = null; tmpltStoredOn = _tmpltMgr.prepareTemplateForCreate(template, pool); if (tmpltStoredOn == null) { s_logger.debug("Skipping " + pool + " because we can't propragate template " + template); continue; } cmd = new CreateCommand(diskProfile, tmpltStoredOn.getLocalDownloadPath(), new StorageFilerTO(pool)); } else { cmd = new CreateCommand(diskProfile, new StorageFilerTO(pool)); } Answer answer = sendToPool(pool, cmd); if (answer.getResult()) { CreateAnswer createAnswer = (CreateAnswer)answer; return new Pair<VolumeTO, StoragePool>(createAnswer.getVolume(), pool); } } if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to create volume " + toBeCreated); } return null; } @Override public void release(VirtualMachineProfile profile) { // Right now we don't do anything. } }
bug 7408: returning the source id and source type for vol creation status 7408: resolved fixed
server/src/com/cloud/storage/StorageManagerImpl.java
bug 7408: returning the source id and source type for vol creation status 7408: resolved fixed
<ide><path>erver/src/com/cloud/storage/StorageManagerImpl.java <ide> // _accountMgr.incrementResourceCount(createdVolume.getAccountId(), ResourceType.volume); <ide> _accountMgr.incrementResourceCount(volume.getAccountId(), ResourceType.volume); <ide> VolumeVO volForUpdate = _volsDao.createForUpdate(); <add> volForUpdate.setSourceId(diskOffering.getId()); <add> volForUpdate.setSourceType(SourceType.DiskOffering); <ide> volForUpdate.setStatus(AsyncInstanceCreateStatus.Created); <ide> _volsDao.update(volume.getId(), volForUpdate); <ide>
Java
mit
c0872d762eae578e24e5212e08a1958d249f6f89
0
RootServices/otter
package org.rootservices.otter.servlet; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.rootservices.otter.config.OtterAppFactory; import org.rootservices.otter.controller.entity.DefaultSession; import org.rootservices.otter.controller.entity.DefaultUser; import org.rootservices.otter.gateway.Configure; import org.rootservices.otter.gateway.entity.Group; import org.rootservices.otter.gateway.entity.Shape; import org.rootservices.otter.gateway.servlet.ServletGateway; import org.rootservices.otter.security.exception.SessionCtorException; import org.rootservices.otter.servlet.async.OtterAsyncListener; import org.rootservices.otter.servlet.async.ReadListenerImpl; import javax.servlet.*; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Entry Servlet for all incoming requests Otter will handle. */ public abstract class OtterEntryServlet extends HttpServlet { public static final String DESTROYING_SERVLET = "destroying servlet"; public static final String INIT_AGAIN = "Servlet initializing after being destroyed. Not initializing Otter again"; public static final String INIT_OTTER = "Initializing Otter"; protected static Logger LOGGER = LogManager.getLogger(OtterEntryServlet.class); protected static OtterAppFactory otterAppFactory; protected static ServletGateway servletGateway; @Override public void init() throws ServletException { if (hasBeenDestroyed()) { LOGGER.info(INIT_AGAIN); } else { LOGGER.info(INIT_OTTER); initOtter(); } } public void initOtter() throws ServletException { otterAppFactory = new OtterAppFactory(); Configure configure = makeConfigure(); Shape shape = configure.shape(); List<Group<? extends DefaultSession, ? extends DefaultUser>> groups = configure.groups(); try { servletGateway = otterAppFactory.servletGateway(shape, groups); } catch (SessionCtorException e) { LOGGER.error(e.getMessage(), e); throw new ServletException(e); } configure.routes(servletGateway); } /** * Determines if this servlet has been destroyed. It is possible to check because * otterAppFactory and servletGateway are static. * * @return True if its been destroyed before. False if it has not been destroyed. */ public Boolean hasBeenDestroyed() { Boolean hasBeenDestroyed = false; if (otterAppFactory != null || servletGateway != null) { hasBeenDestroyed = true; } return hasBeenDestroyed; } public abstract Configure makeConfigure(); public void doAsync(HttpServletRequest request, HttpServletResponse response) throws IOException { AsyncContext context = request.startAsync(request, response); AsyncListener asyncListener = new OtterAsyncListener(); context.addListener(asyncListener); ServletInputStream input = request.getInputStream(); ReadListener readListener = new ReadListenerImpl(servletGateway, input, context); input.setReadListener(readListener); } @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { doAsync(req, resp); } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { doAsync(req, resp); } @Override public void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException { doAsync(req, resp); } @Override public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { doAsync(req, resp); } @Override protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws IOException { doAsync(req, resp); } @Override public void destroy() { LOGGER.info(DESTROYING_SERVLET); super.destroy(); } }
otter/src/main/java/org/rootservices/otter/servlet/OtterEntryServlet.java
package org.rootservices.otter.servlet; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.rootservices.otter.config.OtterAppFactory; import org.rootservices.otter.controller.entity.DefaultSession; import org.rootservices.otter.controller.entity.DefaultUser; import org.rootservices.otter.gateway.Configure; import org.rootservices.otter.gateway.entity.Group; import org.rootservices.otter.gateway.entity.Shape; import org.rootservices.otter.gateway.servlet.ServletGateway; import org.rootservices.otter.security.exception.SessionCtorException; import org.rootservices.otter.servlet.async.OtterAsyncListener; import org.rootservices.otter.servlet.async.ReadListenerImpl; import javax.servlet.*; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Entry Servlet for all incoming requests Otter will handle. */ public abstract class OtterEntryServlet extends HttpServlet { public static final String DESTROYING_SERVLET = "destroying servlet"; protected static Logger logger = LogManager.getLogger(OtterEntryServlet.class); protected OtterAppFactory otterAppFactory; protected ServletGateway servletGateway; @Override public void init() throws ServletException { otterAppFactory = new OtterAppFactory(); Configure configure = makeConfigure(); Shape shape = configure.shape(); List<Group<? extends DefaultSession, ? extends DefaultUser>> groups = configure.groups(); try { servletGateway = otterAppFactory.servletGateway(shape, groups); } catch (SessionCtorException e) { logger.error(e.getMessage(), e); throw new ServletException(e); } configure.routes(servletGateway); } public abstract Configure makeConfigure(); public void doAsync(HttpServletRequest request, HttpServletResponse response) throws IOException { AsyncContext context = request.startAsync(request, response); AsyncListener asyncListener = new OtterAsyncListener(); context.addListener(asyncListener); ServletInputStream input = request.getInputStream(); ReadListener readListener = new ReadListenerImpl(servletGateway, input, context); input.setReadListener(readListener); } @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { doAsync(req, resp); } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { doAsync(req, resp); } @Override public void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException { doAsync(req, resp); } @Override public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { doAsync(req, resp); } @Override protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws IOException { doAsync(req, resp); } @Override public void destroy() { logger.info(DESTROYING_SERVLET); super.destroy(); } }
107: doesn't re init otter when entry servlet is re created.
otter/src/main/java/org/rootservices/otter/servlet/OtterEntryServlet.java
107: doesn't re init otter when entry servlet is re created.
<ide><path>tter/src/main/java/org/rootservices/otter/servlet/OtterEntryServlet.java <ide> */ <ide> public abstract class OtterEntryServlet extends HttpServlet { <ide> public static final String DESTROYING_SERVLET = "destroying servlet"; <del> protected static Logger logger = LogManager.getLogger(OtterEntryServlet.class); <del> protected OtterAppFactory otterAppFactory; <del> protected ServletGateway servletGateway; <add> public static final String INIT_AGAIN = "Servlet initializing after being destroyed. Not initializing Otter again"; <add> public static final String INIT_OTTER = "Initializing Otter"; <add> protected static Logger LOGGER = LogManager.getLogger(OtterEntryServlet.class); <add> protected static OtterAppFactory otterAppFactory; <add> protected static ServletGateway servletGateway; <ide> <ide> @Override <ide> public void init() throws ServletException { <add> <add> if (hasBeenDestroyed()) { <add> LOGGER.info(INIT_AGAIN); <add> } else { <add> LOGGER.info(INIT_OTTER); <add> initOtter(); <add> } <add> } <add> <add> public void initOtter() throws ServletException { <ide> otterAppFactory = new OtterAppFactory(); <ide> Configure configure = makeConfigure(); <ide> Shape shape = configure.shape(); <ide> try { <ide> servletGateway = otterAppFactory.servletGateway(shape, groups); <ide> } catch (SessionCtorException e) { <del> logger.error(e.getMessage(), e); <add> LOGGER.error(e.getMessage(), e); <ide> throw new ServletException(e); <ide> } <ide> <ide> configure.routes(servletGateway); <add> } <add> <add> /** <add> * Determines if this servlet has been destroyed. It is possible to check because <add> * otterAppFactory and servletGateway are static. <add> * <add> * @return True if its been destroyed before. False if it has not been destroyed. <add> */ <add> public Boolean hasBeenDestroyed() { <add> Boolean hasBeenDestroyed = false; <add> if (otterAppFactory != null || servletGateway != null) { <add> hasBeenDestroyed = true; <add> } <add> return hasBeenDestroyed; <ide> } <ide> <ide> public abstract Configure makeConfigure(); <ide> <ide> @Override <ide> public void destroy() { <del> logger.info(DESTROYING_SERVLET); <add> LOGGER.info(DESTROYING_SERVLET); <ide> super.destroy(); <ide> } <ide> }
Java
apache-2.0
b92934bc671ef990d371ccb72fbf474f09a680ad
0
apache/logging-log4j2,codescale/logging-log4j2,GFriedrich/logging-log4j2,xnslong/logging-log4j2,GFriedrich/logging-log4j2,GFriedrich/logging-log4j2,apache/logging-log4j2,codescale/logging-log4j2,xnslong/logging-log4j2,apache/logging-log4j2,xnslong/logging-log4j2,codescale/logging-log4j2
/* * 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.logging.log4j.core.appender; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.GroupPrincipal; import java.nio.file.attribute.PosixFileAttributeView; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; import java.nio.file.attribute.UserPrincipal; import java.nio.file.attribute.UserPrincipalLookupService; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.util.Constants; import org.apache.logging.log4j.core.util.FileUtils; /** * Manages actual File I/O for File Appenders. */ public class FileManager extends OutputStreamManager { private static final FileManagerFactory FACTORY = new FileManagerFactory(); private final boolean isAppend; private final boolean createOnDemand; private final boolean isLocking; private final String advertiseURI; private final int bufferSize; private final Set<PosixFilePermission> filePermissions; private final String fileOwner; private final String fileGroup; /** * @deprecated */ @Deprecated protected FileManager(final String fileName, final OutputStream os, final boolean append, final boolean locking, final String advertiseURI, final Layout<? extends Serializable> layout, final int bufferSize, final boolean writeHeader) { this(fileName, os, append, locking, advertiseURI, layout, writeHeader, ByteBuffer.wrap(new byte[bufferSize])); } /** * @deprecated * @since 2.6 */ @Deprecated protected FileManager(final String fileName, final OutputStream os, final boolean append, final boolean locking, final String advertiseURI, final Layout<? extends Serializable> layout, final boolean writeHeader, final ByteBuffer buffer) { super(os, fileName, layout, writeHeader, buffer); this.isAppend = append; this.createOnDemand = false; this.isLocking = locking; this.advertiseURI = advertiseURI; this.bufferSize = buffer.capacity(); this.filePermissions = null; this.fileOwner = null; this.fileGroup = null; } /** * @deprecated * @since 2.7 */ @Deprecated protected FileManager(final LoggerContext loggerContext, final String fileName, final OutputStream os, final boolean append, final boolean locking, final boolean createOnDemand, final String advertiseURI, final Layout<? extends Serializable> layout, final boolean writeHeader, final ByteBuffer buffer) { super(loggerContext, os, fileName, createOnDemand, layout, writeHeader, buffer); this.isAppend = append; this.createOnDemand = createOnDemand; this.isLocking = locking; this.advertiseURI = advertiseURI; this.bufferSize = buffer.capacity(); this.filePermissions = null; this.fileOwner = null; this.fileGroup = null; } /** * @since 2.8.3 */ protected FileManager(final LoggerContext loggerContext, final String fileName, final OutputStream os, final boolean append, final boolean locking, final boolean createOnDemand, final String advertiseURI, final Layout<? extends Serializable> layout, final String filePermissions, final String fileOwner, final String fileGroup, final boolean writeHeader, final ByteBuffer buffer) { super(loggerContext, os, fileName, createOnDemand, layout, writeHeader, buffer); this.isAppend = append; this.createOnDemand = createOnDemand; this.isLocking = locking; this.advertiseURI = advertiseURI; this.bufferSize = buffer.capacity(); final Set<String> views = FileSystems.getDefault().supportedFileAttributeViews(); this.filePermissions = filePermissions != null && views.contains("posix") ? PosixFilePermissions.fromString(filePermissions) : null; this.fileOwner = views.contains("owner") ? fileOwner : null; this.fileGroup = views.contains("group") ? fileGroup : null; } /** * Returns the FileManager. * @param fileName The name of the file to manage. * @param append true if the file should be appended to, false if it should be overwritten. * @param locking true if the file should be locked while writing, false otherwise. * @param bufferedIo true if the contents should be buffered as they are written. * @param createOnDemand true if you want to lazy-create the file (a.k.a. on-demand.) * @param advertiseUri the URI to use when advertising the file * @param layout The layout * @param bufferSize buffer size for buffered IO * @param filePermissions File permissions * @param fileOwner File owner * @param fileOwner File group * @param configuration The configuration. * @return A FileManager for the File. */ public static FileManager getFileManager(final String fileName, final boolean append, boolean locking, final boolean bufferedIo, final boolean createOnDemand, final String advertiseUri, final Layout<? extends Serializable> layout, final int bufferSize, final String filePermissions, final String fileOwner, final String fileGroup, final Configuration configuration) { if (locking && bufferedIo) { locking = false; } return (FileManager) getManager(fileName, new FactoryData(append, locking, bufferedIo, bufferSize, createOnDemand, advertiseUri, layout, filePermissions, fileOwner, fileGroup, configuration), FACTORY); } @Override protected OutputStream createOutputStream() throws IOException { final String filename = getFileName(); LOGGER.debug("Now writing to {} at {}", filename, new Date()); final FileOutputStream fos = new FileOutputStream(filename, isAppend); definePathAttributeView(Paths.get(filename)); return fos; } protected void definePathAttributeView(final Path path) throws IOException { if (filePermissions != null || fileOwner != null || fileGroup != null) { // FileOutputStream may not create new file on all jvm path.toFile().createNewFile(); final PosixFileAttributeView view = Files.getFileAttributeView(path, PosixFileAttributeView.class); if (view != null) { final UserPrincipalLookupService lookupService = FileSystems.getDefault() .getUserPrincipalLookupService(); if (fileOwner != null) { final UserPrincipal userPrincipal = lookupService.lookupPrincipalByName(fileOwner); if (userPrincipal != null) { view.setOwner(userPrincipal); } } if (fileGroup != null) { final GroupPrincipal groupPrincipal = lookupService.lookupPrincipalByGroupName(fileGroup); if (groupPrincipal != null) { view.setGroup(groupPrincipal); } } if (filePermissions != null) { view.setPermissions(filePermissions); } } } } @Override protected synchronized void write(final byte[] bytes, final int offset, final int length, final boolean immediateFlush) { if (isLocking) { try { @SuppressWarnings("resource") final FileChannel channel = ((FileOutputStream) getOutputStream()).getChannel(); /* * Lock the whole file. This could be optimized to only lock from the current file position. Note that * locking may be advisory on some systems and mandatory on others, so locking just from the current * position would allow reading on systems where locking is mandatory. Also, Java 6 will throw an * exception if the region of the file is already locked by another FileChannel in the same JVM. * Hopefully, that will be avoided since every file should have a single file manager - unless two * different files strings are configured that somehow map to the same file. */ try (final FileLock lock = channel.lock(0, Long.MAX_VALUE, false)) { super.write(bytes, offset, length, immediateFlush); } } catch (final IOException ex) { throw new AppenderLoggingException("Unable to obtain lock on " + getName(), ex); } } else { super.write(bytes, offset, length, immediateFlush); } } /** * Overrides {@link OutputStreamManager#writeToDestination(byte[], int, int)} to add support for file locking. * * @param bytes the array containing data * @param offset from where to write * @param length how many bytes to write * @since 2.8 */ @Override protected synchronized void writeToDestination(final byte[] bytes, final int offset, final int length) { if (isLocking) { try { @SuppressWarnings("resource") final FileChannel channel = ((FileOutputStream) getOutputStream()).getChannel(); /* * Lock the whole file. This could be optimized to only lock from the current file position. Note that * locking may be advisory on some systems and mandatory on others, so locking just from the current * position would allow reading on systems where locking is mandatory. Also, Java 6 will throw an * exception if the region of the file is already locked by another FileChannel in the same JVM. * Hopefully, that will be avoided since every file should have a single file manager - unless two * different files strings are configured that somehow map to the same file. */ try (final FileLock lock = channel.lock(0, Long.MAX_VALUE, false)) { super.writeToDestination(bytes, offset, length); } } catch (final IOException ex) { throw new AppenderLoggingException("Unable to obtain lock on " + getName(), ex); } } else { super.writeToDestination(bytes, offset, length); } } /** * Returns the name of the File being managed. * @return The name of the File being managed. */ public String getFileName() { return getName(); } /** * Returns the append status. * @return true if the file will be appended to, false if it is overwritten. */ public boolean isAppend() { return isAppend; } /** * Returns the lazy-create. * @return true if the file will be lazy-created. */ public boolean isCreateOnDemand() { return createOnDemand; } /** * Returns the lock status. * @return true if the file will be locked when writing, false otherwise. */ public boolean isLocking() { return isLocking; } /** * Returns the buffer size to use if the appender was configured with BufferedIO=true, otherwise returns a negative * number. * @return the buffer size, or a negative number if the output stream is not buffered */ public int getBufferSize() { return bufferSize; } /** * FileManager's content format is specified by: <code>Key: "fileURI" Value: provided "advertiseURI" param</code>. * * @return Map of content format keys supporting FileManager */ @Override public Map<String, String> getContentFormat() { final Map<String, String> result = new HashMap<>(super.getContentFormat()); result.put("fileURI", advertiseURI); return result; } /** * Factory Data. */ private static class FactoryData extends ConfigurationFactoryData { private final boolean append; private final boolean locking; private final boolean bufferedIo; private final int bufferSize; private final boolean createOnDemand; private final String advertiseURI; private final Layout<? extends Serializable> layout; private final String filePermissions; private final String fileOwner; private final String fileGroup; /** * Constructor. * @param append Append status. * @param locking Locking status. * @param bufferedIo Buffering flag. * @param bufferSize Buffer size. * @param createOnDemand if you want to lazy-create the file (a.k.a. on-demand.) * @param advertiseURI the URI to use when advertising the file * @param layout The layout * @param filePermissions File permissions * @param fileOwner File owner * @param fileGroup File group * @param configuration the configuration */ public FactoryData(final boolean append, final boolean locking, final boolean bufferedIo, final int bufferSize, final boolean createOnDemand, final String advertiseURI, final Layout<? extends Serializable> layout, final String filePermissions, final String fileOwner, final String fileGroup, final Configuration configuration) { super(configuration); this.append = append; this.locking = locking; this.bufferedIo = bufferedIo; this.bufferSize = bufferSize; this.createOnDemand = createOnDemand; this.advertiseURI = advertiseURI; this.layout = layout; this.filePermissions = filePermissions; this.fileOwner = fileOwner; this.fileGroup = fileGroup; } } /** * Factory to create a FileManager. */ private static class FileManagerFactory implements ManagerFactory<FileManager, FactoryData> { /** * Creates a FileManager. * @param name The name of the File. * @param data The FactoryData * @return The FileManager for the File. */ @Override public FileManager createManager(final String name, final FactoryData data) { final File file = new File(name); try { FileUtils.makeParentDirs(file); final boolean writeHeader = !data.append || !file.exists(); final int actualSize = data.bufferedIo ? data.bufferSize : Constants.ENCODER_BYTE_BUFFER_SIZE; final ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[actualSize]); final FileOutputStream fos = data.createOnDemand ? null : new FileOutputStream(file, data.append); return new FileManager(data.getLoggerContext(), name, fos, data.append, data.locking, data.createOnDemand, data.advertiseURI, data.layout, data.filePermissions, data.fileOwner, data.fileGroup, writeHeader, byteBuffer); } catch (final IOException ex) { LOGGER.error("FileManager (" + name + ") " + ex, ex); } return null; } } }
log4j-core/src/main/java/org/apache/logging/log4j/core/appender/FileManager.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.logging.log4j.core.appender; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.GroupPrincipal; import java.nio.file.attribute.PosixFileAttributeView; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; import java.nio.file.attribute.UserPrincipal; import java.nio.file.attribute.UserPrincipalLookupService; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.util.Constants; import org.apache.logging.log4j.core.util.FileUtils; /** * Manages actual File I/O for File Appenders. */ public class FileManager extends OutputStreamManager { private static final FileManagerFactory FACTORY = new FileManagerFactory(); private final boolean isAppend; private final boolean createOnDemand; private final boolean isLocking; private final String advertiseURI; private final int bufferSize; private final Set<PosixFilePermission> filePermissions; private final String fileOwner; private final String fileGroup; /** * @deprecated */ @Deprecated protected FileManager(final String fileName, final OutputStream os, final boolean append, final boolean locking, final String advertiseURI, final Layout<? extends Serializable> layout, final int bufferSize, final boolean writeHeader) { this(fileName, os, append, locking, advertiseURI, layout, writeHeader, ByteBuffer.wrap(new byte[bufferSize])); } /** * @deprecated * @since 2.6 */ @Deprecated protected FileManager(final String fileName, final OutputStream os, final boolean append, final boolean locking, final String advertiseURI, final Layout<? extends Serializable> layout, final boolean writeHeader, final ByteBuffer buffer) { super(os, fileName, layout, writeHeader, buffer); this.isAppend = append; this.createOnDemand = false; this.isLocking = locking; this.advertiseURI = advertiseURI; this.bufferSize = buffer.capacity(); this.filePermissions = null; this.fileOwner = null; this.fileGroup = null; } /** * @deprecated * @since 2.7 */ @Deprecated protected FileManager(final LoggerContext loggerContext, final String fileName, final OutputStream os, final boolean append, final boolean locking, final boolean createOnDemand, final String advertiseURI, final Layout<? extends Serializable> layout, final boolean writeHeader, final ByteBuffer buffer) { super(loggerContext, os, fileName, createOnDemand, layout, writeHeader, buffer); this.isAppend = append; this.createOnDemand = createOnDemand; this.isLocking = locking; this.advertiseURI = advertiseURI; this.bufferSize = buffer.capacity(); this.filePermissions = null; this.fileOwner = null; this.fileGroup = null; } /** * @since 2.8.3 */ protected FileManager(final LoggerContext loggerContext, final String fileName, final OutputStream os, final boolean append, final boolean locking, final boolean createOnDemand, final String advertiseURI, final Layout<? extends Serializable> layout, final String filePermissions, final String fileOwner, final String fileGroup, final boolean writeHeader, final ByteBuffer buffer) { super(loggerContext, os, fileName, createOnDemand, layout, writeHeader, buffer); this.isAppend = append; this.createOnDemand = createOnDemand; this.isLocking = locking; this.advertiseURI = advertiseURI; this.bufferSize = buffer.capacity(); final Set<String> views = FileSystems.getDefault().supportedFileAttributeViews(); this.filePermissions = filePermissions != null && views.contains("posix") ? PosixFilePermissions.fromString(filePermissions) : null; this.fileOwner = views.contains("owner") ? fileOwner : null; this.fileGroup = views.contains("group") ? fileGroup : null; } /** * Returns the FileManager. * @param fileName The name of the file to manage. * @param append true if the file should be appended to, false if it should be overwritten. * @param locking true if the file should be locked while writing, false otherwise. * @param bufferedIo true if the contents should be buffered as they are written. * @param createOnDemand true if you want to lazy-create the file (a.k.a. on-demand.) * @param advertiseUri the URI to use when advertising the file * @param layout The layout * @param bufferSize buffer size for buffered IO * @param filePermissions File permissions * @param fileOwner File owner * @param fileOwner File group * @param configuration The configuration. * @return A FileManager for the File. */ public static FileManager getFileManager(final String fileName, final boolean append, boolean locking, final boolean bufferedIo, final boolean createOnDemand, final String advertiseUri, final Layout<? extends Serializable> layout, final int bufferSize, final String filePermissions, final String fileOwner, final String fileGroup, final Configuration configuration) { if (locking && bufferedIo) { locking = false; } return (FileManager) getManager(fileName, new FactoryData(append, locking, bufferedIo, bufferSize, createOnDemand, advertiseUri, layout, filePermissions, fileOwner, fileGroup, configuration), FACTORY); } @Override protected OutputStream createOutputStream() throws IOException { final String filename = getFileName(); LOGGER.debug("Now writing to {} at {}", filename, new Date()); final FileOutputStream fos = new FileOutputStream(filename, isAppend); definePathAttributeView(Paths.get(filename)); return fos; } protected void definePathAttributeView(final Path path) throws IOException { if (filePermissions != null || fileOwner != null || fileGroup != null) { // FileOutputStream may not create new file on all jvm path.toFile().createNewFile(); final PosixFileAttributeView view = Files.getFileAttributeView(path, PosixFileAttributeView.class); if (view != null) { final UserPrincipalLookupService lookupService = FileSystems.getDefault() .getUserPrincipalLookupService(); if (fileOwner != null) { final UserPrincipal userPrincipal = lookupService.lookupPrincipalByName(fileOwner); if (userPrincipal != null) { view.setOwner(userPrincipal); } } if (fileGroup != null) { final GroupPrincipal groupPrincipal = lookupService .lookupPrincipalByGroupName(fileGroup); if (groupPrincipal != null) { view.setGroup(groupPrincipal); } } if (filePermissions != null) { view.setPermissions(filePermissions); } } } } @Override protected synchronized void write(final byte[] bytes, final int offset, final int length, final boolean immediateFlush) { if (isLocking) { try { @SuppressWarnings("resource") final FileChannel channel = ((FileOutputStream) getOutputStream()).getChannel(); /* * Lock the whole file. This could be optimized to only lock from the current file position. Note that * locking may be advisory on some systems and mandatory on others, so locking just from the current * position would allow reading on systems where locking is mandatory. Also, Java 6 will throw an * exception if the region of the file is already locked by another FileChannel in the same JVM. * Hopefully, that will be avoided since every file should have a single file manager - unless two * different files strings are configured that somehow map to the same file. */ try (final FileLock lock = channel.lock(0, Long.MAX_VALUE, false)) { super.write(bytes, offset, length, immediateFlush); } } catch (final IOException ex) { throw new AppenderLoggingException("Unable to obtain lock on " + getName(), ex); } } else { super.write(bytes, offset, length, immediateFlush); } } /** * Overrides {@link OutputStreamManager#writeToDestination(byte[], int, int)} to add support for file locking. * * @param bytes the array containing data * @param offset from where to write * @param length how many bytes to write * @since 2.8 */ @Override protected synchronized void writeToDestination(final byte[] bytes, final int offset, final int length) { if (isLocking) { try { @SuppressWarnings("resource") final FileChannel channel = ((FileOutputStream) getOutputStream()).getChannel(); /* * Lock the whole file. This could be optimized to only lock from the current file position. Note that * locking may be advisory on some systems and mandatory on others, so locking just from the current * position would allow reading on systems where locking is mandatory. Also, Java 6 will throw an * exception if the region of the file is already locked by another FileChannel in the same JVM. * Hopefully, that will be avoided since every file should have a single file manager - unless two * different files strings are configured that somehow map to the same file. */ try (final FileLock lock = channel.lock(0, Long.MAX_VALUE, false)) { super.writeToDestination(bytes, offset, length); } } catch (final IOException ex) { throw new AppenderLoggingException("Unable to obtain lock on " + getName(), ex); } } else { super.writeToDestination(bytes, offset, length); } } /** * Returns the name of the File being managed. * @return The name of the File being managed. */ public String getFileName() { return getName(); } /** * Returns the append status. * @return true if the file will be appended to, false if it is overwritten. */ public boolean isAppend() { return isAppend; } /** * Returns the lazy-create. * @return true if the file will be lazy-created. */ public boolean isCreateOnDemand() { return createOnDemand; } /** * Returns the lock status. * @return true if the file will be locked when writing, false otherwise. */ public boolean isLocking() { return isLocking; } /** * Returns the buffer size to use if the appender was configured with BufferedIO=true, otherwise returns a negative * number. * @return the buffer size, or a negative number if the output stream is not buffered */ public int getBufferSize() { return bufferSize; } /** * FileManager's content format is specified by: <code>Key: "fileURI" Value: provided "advertiseURI" param</code>. * * @return Map of content format keys supporting FileManager */ @Override public Map<String, String> getContentFormat() { final Map<String, String> result = new HashMap<>(super.getContentFormat()); result.put("fileURI", advertiseURI); return result; } /** * Factory Data. */ private static class FactoryData extends ConfigurationFactoryData { private final boolean append; private final boolean locking; private final boolean bufferedIo; private final int bufferSize; private final boolean createOnDemand; private final String advertiseURI; private final Layout<? extends Serializable> layout; private final String filePermissions; private final String fileOwner; private final String fileGroup; /** * Constructor. * @param append Append status. * @param locking Locking status. * @param bufferedIo Buffering flag. * @param bufferSize Buffer size. * @param createOnDemand if you want to lazy-create the file (a.k.a. on-demand.) * @param advertiseURI the URI to use when advertising the file * @param layout The layout * @param filePermissions File permissions * @param fileOwner File owner * @param fileGroup File group * @param configuration the configuration */ public FactoryData(final boolean append, final boolean locking, final boolean bufferedIo, final int bufferSize, final boolean createOnDemand, final String advertiseURI, final Layout<? extends Serializable> layout, final String filePermissions, final String fileOwner, final String fileGroup, final Configuration configuration) { super(configuration); this.append = append; this.locking = locking; this.bufferedIo = bufferedIo; this.bufferSize = bufferSize; this.createOnDemand = createOnDemand; this.advertiseURI = advertiseURI; this.layout = layout; this.filePermissions = filePermissions; this.fileOwner = fileOwner; this.fileGroup = fileGroup; } } /** * Factory to create a FileManager. */ private static class FileManagerFactory implements ManagerFactory<FileManager, FactoryData> { /** * Creates a FileManager. * @param name The name of the File. * @param data The FactoryData * @return The FileManager for the File. */ @Override public FileManager createManager(final String name, final FactoryData data) { final File file = new File(name); try { FileUtils.makeParentDirs(file); final boolean writeHeader = !data.append || !file.exists(); final int actualSize = data.bufferedIo ? data.bufferSize : Constants.ENCODER_BYTE_BUFFER_SIZE; final ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[actualSize]); final FileOutputStream fos = data.createOnDemand ? null : new FileOutputStream(file, data.append); return new FileManager(data.getLoggerContext(), name, fos, data.append, data.locking, data.createOnDemand, data.advertiseURI, data.layout, data.filePermissions, data.fileOwner, data.fileGroup, writeHeader, byteBuffer); } catch (final IOException ex) { LOGGER.error("FileManager (" + name + ") " + ex, ex); } return null; } } }
[LOG4J2-1699] Configurable Log File Permissions with PosixFilePermission. Reformat the new method definePathAttributeView().
log4j-core/src/main/java/org/apache/logging/log4j/core/appender/FileManager.java
[LOG4J2-1699] Configurable Log File Permissions with PosixFilePermission. Reformat the new method definePathAttributeView().
<ide><path>og4j-core/src/main/java/org/apache/logging/log4j/core/appender/FileManager.java <ide> } <ide> <ide> protected void definePathAttributeView(final Path path) throws IOException { <del> if (filePermissions != null || fileOwner != null || fileGroup != null) { <del> // FileOutputStream may not create new file on all jvm <del> path.toFile().createNewFile(); <del> <del> final PosixFileAttributeView view = Files.getFileAttributeView(path, <del> PosixFileAttributeView.class); <del> if (view != null) { <del> final UserPrincipalLookupService lookupService = FileSystems.getDefault() <del> .getUserPrincipalLookupService(); <del> if (fileOwner != null) { <del> final UserPrincipal userPrincipal = lookupService.lookupPrincipalByName(fileOwner); <del> if (userPrincipal != null) { <del> view.setOwner(userPrincipal); <add> if (filePermissions != null || fileOwner != null || fileGroup != null) { <add> // FileOutputStream may not create new file on all jvm <add> path.toFile().createNewFile(); <add> <add> final PosixFileAttributeView view = Files.getFileAttributeView(path, PosixFileAttributeView.class); <add> if (view != null) { <add> final UserPrincipalLookupService lookupService = FileSystems.getDefault() <add> .getUserPrincipalLookupService(); <add> if (fileOwner != null) { <add> final UserPrincipal userPrincipal = lookupService.lookupPrincipalByName(fileOwner); <add> if (userPrincipal != null) { <add> view.setOwner(userPrincipal); <add> } <add> } <add> if (fileGroup != null) { <add> final GroupPrincipal groupPrincipal = lookupService.lookupPrincipalByGroupName(fileGroup); <add> if (groupPrincipal != null) { <add> view.setGroup(groupPrincipal); <add> } <add> } <add> if (filePermissions != null) { <add> view.setPermissions(filePermissions); <add> } <ide> } <del> } <del> if (fileGroup != null) { <del> final GroupPrincipal groupPrincipal = lookupService <del> .lookupPrincipalByGroupName(fileGroup); <del> if (groupPrincipal != null) { <del> view.setGroup(groupPrincipal); <del> } <del> } <del> if (filePermissions != null) { <del> view.setPermissions(filePermissions); <del> } <del> } <del> } <add> } <ide> } <ide> <ide> @Override
Java
mit
07ffe7e02e23173b5a45dd78c302c1c252d0da2d
0
mhogrefe/qbar
package mho.qbar.objects; import mho.wheels.iterables.IterableUtils; import mho.wheels.misc.FloatingPointUtils; import mho.wheels.misc.Readers; import mho.wheels.ordering.Ordering; import mho.wheels.structures.Pair; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.*; import static mho.wheels.iterables.IterableUtils.*; import static mho.wheels.ordering.Ordering.*; /** * <p>The {@code Interval} class represents an interval of real numbers. If we let p and q be rationals, p≤q, the * representable intervals are (–∞, ∞), (–∞, q], [p, ∞), and [p, q]. If p = q, the {@code Interval} represents a single * number. The empty interval cannot be represented. * * <p>In general, f(I), where I is an {@code Interval}, is taken to mean the image of I under f. Often this image is * not an {@code Interval} itself, in which case the function might return a set of {@code Interval}s, whose closed * union is the image, or it may just return the closure of the image's convex hull. Similar considerations apply for * functions of two {@code Interval}s, etc. * * <p>This class is immutable. */ public final class Interval implements Comparable<Interval> { /** * [0, 0] */ public static final @NotNull Interval ZERO = new Interval(Rational.ZERO, Rational.ZERO); /** * [1, 1] */ public static final @NotNull Interval ONE = new Interval(Rational.ONE, Rational.ONE); /** * (–∞, ∞) */ public static final @NotNull Interval ALL = new Interval(null, null); /** * The lower bound of this interval if the lower bound is finite, or null if the lower bound is –∞ */ private final @Nullable Rational lower; /** * The upper bound of this interval if the upper bound is finite, or null if the upper bound is ∞ */ private final @Nullable Rational upper; /** * Private constructor from {@link Rational}s; assumes arguments are valid. If lower is null, the * {@code Interval}'s lower bound is –∞; if upper is null, the {@code Interval}'s upper bound is ∞. * * <ul> * <li>{@code lower} may be any {@code Rational}, or null.</li> * <li>{@code upper} may be any {@code Rational}, or null.</li> * <li>If {@code lower} and {@code upper} are both non-null, {@code lower} must be less than or equal to * {@code upper}.</li> * </ul> * * @param lower the lower bound * @param upper the upper bound */ private Interval(@Nullable Rational lower, @Nullable Rational upper) { this.lower = lower; this.upper = upper; } /** * Returns this {@code Interval}'s lower bound. If the lower bound is –∞, an empty {@code Optional} is returned. * * <ul> * <li>The result is non-null.</li> * </ul> * * @return the lower bound */ public @NotNull Optional<Rational> getLower() { return lower == null ? Optional.<Rational>empty() : Optional.of(lower); } /** * Returns this {@code Interval}'s upper bound. If the lower bound is ∞, an empty {@code Optional} is returned. * * <ul> * <li>The result is non-null.</li> * </ul> * * @return the upper bound */ public @NotNull Optional<Rational> getUpper() { return upper == null ? Optional.<Rational>empty() : Optional.of(upper); } /** * Creates a finitely-bounded {@code Interval} from {@code Rationals}. * * <ul> * <li>{@code lower} cannot be null.</li> * <li>{@code upper} cannot be null.</li> * <li>{@code lower} must be less than or equal to {@code upper}.</li> * </ul> * * @param lower the lower bound * @param upper the upper bound * @return [{@code lower}, {@code upper}] */ public static @NotNull Interval of(@NotNull Rational lower, @NotNull Rational upper) { if (gt(lower, upper)) throw new IllegalArgumentException("lower bound cannot be greater than upper bound"); return new Interval(lower, upper); } /** * Creates an interval whose lower bound is –∞. * * <ul> * <li>{@code upper} cannot be null.</li> * </ul> * * @param upper the upper bound * @return (–∞, {@code upper}] */ @SuppressWarnings("JavaDoc") public static @NotNull Interval lessThanOrEqualTo(@NotNull Rational upper) { return new Interval(null, upper); } /** * Creates an interval whose upper bound is ∞. * * <ul> * <li>{@code lower} cannot be null.</li> * </ul> * * @param lower the lower bound * @return [{@code lower}, ∞) */ public static @NotNull Interval greaterThanOrEqualTo(@NotNull Rational lower) { return new Interval(lower, null); } /** * Creates an interval containing exactly one {@code Rational}. * * <ul> * <li>{@code x} cannot be null.</li> * </ul> * * @param x the value contained in this {@code Interval} * @return [{@code x}, {@code x}] */ public static @NotNull Interval of(@NotNull Rational x) { return new Interval(x, x); } /** * Determines whether {@code this} has finite bounds. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @return whether {@code this} is finitely-bounded */ public boolean isFinitelyBounded() { return lower != null && upper != null; } /** * Determines whether {@code this} contains a {@code Rational}. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code x} cannot be null.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @param x the test {@code Rational} * @return {@code x}∈{@code this} */ public boolean contains(@NotNull Rational x) { if (lower == null && upper == null) return true; if (lower == null) return le(x, upper); if (upper == null) return ge(x, lower); return ge(x, lower) && le(x, upper); } /** * Determines whether {@code this} contains (is a superset of) an {@code Interval}. Every {@code Interval} contains * itself. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @param that the test {@code Interval} * @return {@code that}⊆{@code this} */ public boolean contains(@NotNull Interval that) { return (lower == null || (that.lower != null && ge(that.lower, lower))) && (upper == null || (that.upper != null && le(that.upper, upper))); } /** * Determines the diameter (length) of {@code this}. If {@code this} has infinite diameter, an empty * {@code Optional} is returned. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>The result may be empty, or it may contain a non-negative {@code Rational}.</li> * </ul> * * @return the diameter of {@code this} */ public @NotNull Optional<Rational> diameter() { if (lower == null || upper == null) return Optional.empty(); return Optional.of(upper.subtract(lower)); } /** * Determines the convex hull of two {@code Interval}s, or the {@code Interval} with minimal diameter that is a * superset of the two {@code Interval}s. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code Interval} to be hulled with {@code this} * @return Conv({@code this}, {@code that}) */ @SuppressWarnings("JavaDoc") public @NotNull Interval convexHull(@NotNull Interval that) { return new Interval( lower == null || that.lower == null ? null : min(lower, that.lower), upper == null || that.upper == null ? null : max(upper, that.upper) ); } /** * Determines the convex hull of a set of {@code Interval}s, or the {@code Interval} with minimal diameter that is * a superset of all of the {@code Interval}s. * * <ul> * <li>{@code as} cannot be empty and may not contain any null elements.</li> * <li>The result is not null.</li> * </ul> * * @param as the {@code Interval}s. * @return Conv({@code as}) */ @SuppressWarnings("JavaDoc") public static @NotNull Interval convexHull(@NotNull List<Interval> as) { if (any(a -> a == null, as)) throw new NullPointerException(); //noinspection ConstantConditions return foldl1(p -> p.a.convexHull(p.b), as); } /** * Returns the intersection of two {@code Interval}s. If the intersection is empty, an empty {@code Optional} is * returned. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code Interval} to be intersected with {@code this} * @return {@code this}∩{@code that} */ public @NotNull Optional<Interval> intersection(@NotNull Interval that) { Rational iLower; if (lower == null && that.lower == null) { iLower = null; } else if (lower == null) { iLower = that.lower; } else if (that.lower == null) { iLower = lower; } else { iLower = max(lower, that.lower); } Rational iUpper; if (upper == null && that.upper == null) { iUpper = null; } else if (upper == null) { iUpper = that.upper; } else if (that.upper == null) { iUpper = upper; } else { iUpper = min(upper, that.upper); } if (iLower != null && iUpper != null && gt(iLower, iUpper)) return Optional.empty(); return Optional.of(new Interval(iLower, iUpper)); } /** * Determines whether two {@code Interval}s are disjoint (whether their intersections are empty). * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @param that the {@code Interval} tested for disjointness with {@code this} * @return {@code this}∩{@code that}=∅ */ public boolean disjoint(@NotNull Interval that) { return !intersection(that).isPresent(); } /** * Transforms a list of {@code Interval}s into a list of disjoint {@code Interval}s with the same union as the * original set. * * <ul> * <li>{@code as} cannot be null and may not contain any null elements.</li> * <li>The result is a sorted list of pairwise disjoint {@code Interval}s.</li> * </ul> * * @param as a list of {@code Interval}s * @return a list of disjoint {@code Interval}s whose union is the same as the union of {@code as} */ public static @NotNull List<Interval> makeDisjoint(@NotNull List<Interval> as) { List<Interval> simplified = new ArrayList<>(); Interval acc = null; for (Interval a : sort(as)) { if (acc == null) { acc = a; } else if (acc.disjoint(a)) { simplified.add(acc); acc = a; } else { acc = acc.convexHull(a); } } if (acc != null) simplified.add(acc); return simplified; } /** * The complement of an {@code Interval} generally involves open intervals, so it can't be represented as a union * of {@code Interval}s. However, we can get close; we can represent the complement's closure. This is equal to the * complement, except that it includes the endpoints of the original {@code Interval}. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li> * The result is in one of these forms: * <ul> * <li>an empty list</li> * <li>a list containing one {@code Interval}, unbounded on one side</li> * <li>a list containing (–∞, ∞); this happens when {@code this} has diameter 0</li> * <li>a list containing two disjoint {@code Intervals}, the first unbounded on the left and the second * unbounded on the right</li> * </ul> * </li> * </ul> * * @return the closure of ℝ\{@code this} */ public @NotNull List<Interval> complement() { if (lower == null && upper == null) return new ArrayList<>(); if (lower == null) return Arrays.asList(new Interval(upper, null)); if (upper == null) return Arrays.asList(new Interval(null, lower)); if (lower.equals(upper)) return Arrays.asList(ALL); return Arrays.asList(new Interval(null, lower), new Interval(upper, null)); } /** * Returns the midpoint of {@code this}. * * <ul> * <li>{@code this} must be finitely bounded.</li> * <li>The result is not null.</li> * </ul> * * @return the average of {@code lower} and {@code upper}. */ public @NotNull Rational midpoint() { if (lower == null || upper == null) throw new ArithmeticException("an unbounded interval has no midpoint"); return lower.add(upper).shiftRight(1); } /** * Splits {@code this} into two intervals at {@code x}. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code x} cannot be null.</li> * <li>{@code this} must contain {@code x}.</li> * <li>The result is a pair of {@code Interval}s, neither null, such that the upper bound of the first is equal * to the lower bound of the second.</li> * </ul> * * @param x the point at which {@code this} is split. * @return the two pieces of {@code this}. */ public @NotNull Pair<Interval, Interval> split(@NotNull Rational x) { if (!contains(x)) throw new ArithmeticException("interval does not contain specified split point"); return new Pair<>(new Interval(lower, x), new Interval(x, upper)); } /** * Splits {@code this} into two equal {@code Interval}s. * * <ul> * <li>{@code this} must be finitely bounded.</li> * <li>The result is a pair of equal-diameter, finitely-bounded {@code Interval}s such the the upper bound of the * first is equal to the lower bound of the second.</li> * </ul> * * @return the two halves of {@code this}. */ public @NotNull Pair<Interval, Interval> bisect() { return split(midpoint()); } /** * Returns the smallest {@code Interval} containing all reals that are closer to a given {@code float} than to * any other {@code float}. Some special cases must be taken into account: * <ul> * <li>If the {@code float} is positive infinity, the result contains all reals that are greater than or equal to * {@code Float.MAX_VALUE}.</li> * <li>If the {@code float} is negative infinity, the result contains all reals that are less than or equal to * {@code -Float.MAX_VALUE}.</li> * <li>If the {@code float} is {@code Float.MAX_VALUE}, the result contains all reals that are less than or equal * to {@code Float.MAX_VALUE} and closer to it than to any other {@code float}.</li> * <li>If the {@code float} is {@code -Float.MAX_VALUE}, the result contains all reals that are greater than or * equal to {@code -Float.MAX_VALUE} and closer to it than to any other {@code float}.</li> * </ul> * * Positive and negative 0 yield the same result. * * <ul> * <li>{@code f} may be any {@code float} except NaN.</li> * <li>The result is one of * <ul> * <li>[{@code Float.MAX_VALUE}, ∞)</li> * <li>(–∞, –{@code Float.MAX_VALUE}]</li> * <li>[({@code a}+{@code b})/2, {@code b}], where {@code b} is {@code Float.MAX_VALUE} and {@code a} is * {@code b}'s predecessor</li> * <li>[{@code a}, ({@code a}+{@code b})/2], where {@code a} is –{@code Float.MAX_VALUE} and {@code b} is * {@code a}'s successor</li> * <li>[({@code a}+{@code b})/2, ({@code b}+{@code c})/2], where {@code a}, {@code b}, and {@code c} are * equal to three consecutive finite {@code float}s (but + and / correspond to real operations, not * {@code float} operations).</li> * </ul> * </li> * </ul> * * @param f a {@code float}. * @return the closure of the preimage of {@code f} with respect to rounding-to-nearest-{@code float}. */ public static @NotNull Interval roundingPreimage(float f) { if (Float.isNaN(f)) throw new ArithmeticException("cannot find preimage of NaN"); if (Float.isInfinite(f)) { if (f > 0) { return new Interval(Rational.LARGEST_FLOAT, null); } else { return new Interval(null, Rational.LARGEST_FLOAT.negate()); } } if (f == Float.MAX_VALUE) { //noinspection ConstantConditions return new Interval( Rational.ofExact(FloatingPointUtils.predecessor(f)).add(Rational.LARGEST_FLOAT).shiftRight(1), Rational.LARGEST_FLOAT ); } if (f == -Float.MAX_VALUE) { //noinspection ConstantConditions return new Interval( Rational.LARGEST_FLOAT.negate(), Rational.ofExact(FloatingPointUtils.successor(f)).subtract(Rational.LARGEST_FLOAT).shiftRight(1) ); } Rational r = Rational.ofExact(f); float predecessor = FloatingPointUtils.predecessor(f); @SuppressWarnings("ConstantConditions") Rational lower = predecessor == Float.NEGATIVE_INFINITY ? null : r.add(Rational.ofExact(predecessor)).shiftRight(1); float successor = FloatingPointUtils.successor(f); @SuppressWarnings("ConstantConditions") Rational upper = successor == Float.POSITIVE_INFINITY ? null : r.add(Rational.ofExact(successor)).shiftRight(1); return new Interval(lower, upper); } /** * Returns the smallest {@code Interval} containing all reals that are closer to a given {@link double} than to any * other {@code double}. * * Some special cases must be taken into account: * <ul> * <li>If the {@code double} is positive infinity, the result contains all reals that are greater than or equal to * {@code Double.MAX_VALUE}.</li> * <li>If the {@code double} is negative infinity, the result contains all reals that are less than or equal to * {@code -Double.MAX_VALUE}.</li> * <li>If the {@code double} is {@code Double.MAX_VALUE}, the result contains all reals that are less than or * equal to {@code Double.MAX_VALUE} and closer to it than to any other {@code double}.</li> * <li>If the {@code double} is {@code -Double.MAX_VALUE}, the result contains all reals that are greater than or * equal to {@code -Double.MAX_VALUE} and closer to it than to any other {@code double}.</li> * </ul> * * Positive and negative 0 yield the same result. * * <ul> * <li>{@code d} may be any {@code double} except {@code NaN}.</li> * <li>The result is one of * <ul> * <li>[{@code Double.MAX_VALUE}, ∞)</li> * <li>(–∞, –{@code Double.MAX_VALUE}]</li> * <li>[({@code a}+{@code b})/2, {@code b}], where {@code b} is {@code Double.MAX_VALUE} and {@code a} is * {@code b}'s predecessor</li> * <li>[{@code a}, ({@code a}+{@code b})/2], where {@code a} is –{@code Double.MAX_VALUE} and {@code b} is * {@code a}'s successor</li> * <li>[({@code a}+{@code b})/2, ({@code b}+{@code c})/2], where {@code a}, {@code b}, and {@code c} are equal * to three consecutive finite {@code double}s (but + and / correspond to real operations, not {@code double} * operations).</li> * </ul> * </li> * </ul> * * @param d a {@code double}. * @return the closure of the preimage of {@code d} with respect to rounding-to-nearest-{@code double}. */ public static @NotNull Interval roundingPreimage(double d) { if (Double.isNaN(d)) throw new ArithmeticException("cannot find preimage of NaN"); if (Double.isInfinite(d)) { if (d > 0) { return new Interval(Rational.LARGEST_DOUBLE, null); } else { return new Interval(null, Rational.LARGEST_DOUBLE.negate()); } } if (d == Double.MAX_VALUE) { //noinspection ConstantConditions return new Interval( Rational.ofExact(FloatingPointUtils.predecessor(d)).add(Rational.LARGEST_DOUBLE).shiftRight(1), Rational.LARGEST_DOUBLE ); } if (d == -Double.MAX_VALUE) { //noinspection ConstantConditions return new Interval( Rational.LARGEST_DOUBLE.negate(), Rational.ofExact(FloatingPointUtils.successor(d)).subtract(Rational.LARGEST_DOUBLE).shiftRight(1) ); } Rational r = Rational.ofExact(d); double predecessor = FloatingPointUtils.predecessor(d); @SuppressWarnings("ConstantConditions") Rational lower = predecessor == Double.NEGATIVE_INFINITY ? null : r.add(Rational.ofExact(predecessor)).shiftRight(1); double successor = FloatingPointUtils.successor(d); @SuppressWarnings("ConstantConditions") Rational upper = predecessor == Double.POSITIVE_INFINITY ? null : r.add(Rational.ofExact(successor)).shiftRight(1); return new Interval(lower, upper); } /** * Returns an {@code Interval} representing all real numbers that round to a specified {@link BigDecimal} (taking * scale into account). * * <ul> * <li>{@code bd} cannot be null.</li> * <li>The result is an interval of the form [a×10<sup>b</sup>–5×10<sup>c</sup>, * a×10<sup>b</sup>+5×10<sup>c</sup>], where a, b, and c are integers and c{@literal <}b.</li> * </ul> * * @param bd a {@code BigDecimal} * @return the closure of the preimage of {@code bd} with respect to rounding-to-nearest-{@code BigDecimal}. */ public static @NotNull Interval roundingPreimage(@NotNull BigDecimal bd) { Rational center = Rational.of(bd); Rational maxAbsoluteError = Rational.of(10).pow(-bd.scale()).shiftRight(1); return new Interval(center.subtract(maxAbsoluteError), center.add(maxAbsoluteError)); } /** * Returns a pair of {@code float}s x, y such that [x, y] is the smallest interval with {@code float} bounds which * contains {@code this}. x or y may be infinite if {@code this}'s bounds are infinite or very large in magnitude. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>Neither of the result's elements are null or {@code NaN}. The second element is greater than or equal to * the first. The first element cannot be {@code Infinity} or negative zero. The second element cannot be * {@code -Infinity}. If the second element is negative zero, the first element cannot be positive zero.</li> * </ul> * * @return the smallest {@code float} interval containing {@code this}. */ public @NotNull Pair<Float, Float> floatRange() { float fLower = lower == null ? Float.NEGATIVE_INFINITY : lower.floatValue(RoundingMode.FLOOR); float fUpper = upper == null ? Float.POSITIVE_INFINITY : upper.floatValue(RoundingMode.CEILING); return new Pair<>(fLower, fUpper); } /** * Returns a pair of {@code double}s x, y such that [x, y] is the smallest interval with {@code double} bounds * which contains {@code this}. x or y may be infinite if {@code this}'s bounds are infinite or very large in * magnitude. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>Neither of the result's elements are null or {@code NaN}. The second element is greater than or equal to * the first. The first element cannot be {@code Infinity} or negative zero. The second element cannot be * {@code -Infinity}. If the second element is negative zero, the first element cannot be positive zero.</li> * </ul> * * @return the smallest {@code double} interval containing {@code this}. */ public @NotNull Pair<Double, Double> doubleRange() { double dLower = lower == null ? Double.NEGATIVE_INFINITY : lower.doubleValue(RoundingMode.FLOOR); double dUpper = upper == null ? Double.POSITIVE_INFINITY : upper.doubleValue(RoundingMode.CEILING); return new Pair<>(dLower, dUpper); } /** * Returns the smallest interval z such that if a∈{@code this} and b∈{@code that}, a+b∈z. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code Interval} added to {@code this} * @return {@code this}+{@code that} */ public @NotNull Interval add(@NotNull Interval that) { Rational lowerSum = lower == null || that.lower == null ? null : lower.add(that.lower); Rational upperSum = upper == null || that.upper == null ? null : upper.add(that.upper); return new Interval(lowerSum, upperSum); } /** * Returns the smallest interval a such that if x∈{@code this}, –x∈a. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>The result is not null.</li> * </ul> * * @return –{@code this} */ public @NotNull Interval negate() { if (lower == null && upper == null) return this; if (lower == null) return new Interval(upper.negate(), null); if (upper == null) return new Interval(null, lower.negate()); return new Interval(upper.negate(), lower.negate()); } /** * Returns the smallest interval a such that if x∈{@code this}, |x|∈a. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>The result is an interval whose lower bound is finite and non-negative.</li> * </ul> * * @return |{@code this}| */ public @NotNull Interval abs() { if (lower == null && upper == null) return new Interval(Rational.ZERO, null); if (lower == null) { return new Interval(upper.signum() == -1 ? upper.negate() : Rational.ZERO, null); } if (upper == null) { return lower.signum() == -1 ? new Interval(Rational.ZERO, null) : this; } if (lower.signum() == 1 && upper.signum() == 1) return this; if (lower.signum() == -1 && upper.signum() == -1) return negate(); return new Interval(Rational.ZERO, max(lower.negate(), upper)); } /** * If every real in {@code this} has the same sign, returns that sign; otherwise, returns an empty * {@code Optional}. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>The result is either empty, or contains -1, 0, or 1.</li> * </ul> * * @return sgn(x) for all x∈{@code this}, if sgn(x) is unique */ public @NotNull Optional<Integer> signum() { int lowerSignum = lower == null ? -1 : lower.signum(); int upperSignum = upper == null ? 1 : upper.signum(); return lowerSignum == upperSignum ? Optional.of(lowerSignum) : Optional.<Integer>empty(); } /** * Returns the smallest interval z such that if a∈{@code this} and b∈{@code that}, a–b∈z. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code Interval} subtracted from {@code this} * @return {@code this}–{@code that} */ public @NotNull Interval subtract(@NotNull Interval that) { return add(that.negate()); } /** * Returns the smallest interval z such that if a∈{@code this} and b∈{@code that}, a×b∈z. Interval addition does * not distribute over interval multiplication: for example, ([0, 1] + (–∞, -1]) × [0, 1] = (–∞, 0], but * [0, 1] × [0, 1] + (–∞, -1] × [0, 1] = (–∞, 1]. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code Interval} that {@code this} is multiplied by * @return {@code this}×{@code that} */ public @NotNull Interval multiply(@NotNull Interval that) { boolean thisHasPositive = upper == null || upper.signum() == 1; boolean thatHasPositive = that.upper == null || that.upper.signum() == 1; boolean thisHasNegative = lower == null || lower.signum() == -1; boolean thatHasNegative = that.lower == null || that.lower.signum() == -1; boolean minIsNegInf = lower == null && thatHasPositive || upper == null && thatHasNegative || that.lower == null && thisHasPositive || that.upper == null && thisHasNegative; boolean maxIsPosInf = upper == null && thatHasPositive || lower == null && thatHasNegative || that.upper == null && thisHasPositive || that.lower == null && thisHasNegative; if (minIsNegInf && maxIsPosInf) return ALL; List<Rational> extremes = new ArrayList<>(); if (lower != null) { if (that.lower != null) extremes.add(lower.multiply(that.lower)); if (that.upper != null) extremes.add(lower.multiply(that.upper)); } if (upper != null) { if (that.lower != null) extremes.add(upper.multiply(that.lower)); if (that.upper != null) extremes.add(upper.multiply(that.upper)); } if (extremes.isEmpty()) extremes.add(Rational.ZERO); if (minIsNegInf) return new Interval(null, maximum(extremes)); if (maxIsPosInf) return new Interval(minimum(extremes), null); return new Interval(minimum(extremes), maximum(extremes)); } /** * Returns the smallest interval a such that if x∈{@code this}, x×{@code that}∈a. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code Rational} that {@code this} is multiplied by * @return {@code this}×{@code that} */ public @NotNull Interval multiply(@NotNull Rational that) { if (that == Rational.ZERO) return ZERO; if (that == Rational.ONE) return this; if (that.signum() == 1) { return new Interval( lower == null ? null : lower.multiply(that), upper == null ? null : upper.multiply(that) ); } else { return new Interval( upper == null ? null : upper.multiply(that), lower == null ? null : lower.multiply(that) ); } } /** * Returns the smallest interval a such that if x∈{@code this}, x×{@code that}∈a. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code BigInteger} that {@code this} is multiplied by * @return {@code this}×{@code that} */ public @NotNull Interval multiply(@NotNull BigInteger that) { if (that.equals(BigInteger.ZERO)) return ZERO; if (that.equals(BigInteger.ONE)) return this; if (that.signum() == 1) { return new Interval( lower == null ? null : lower.multiply(that), upper == null ? null : upper.multiply(that) ); } else { return new Interval( upper == null ? null : upper.multiply(that), lower == null ? null : lower.multiply(that) ); } } /** * Returns the smallest interval a such that if x∈{@code this}, x×{@code that}∈a. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code int} that {@code this} is multiplied by * @return {@code this}×{@code that} */ public @NotNull Interval multiply(int that) { if (that == 0) return ZERO; if (that == 1) return this; if (that > 0) { return new Interval( lower == null ? null : lower.multiply(that), upper == null ? null : upper.multiply(that) ); } else { return new Interval( upper == null ? null : upper.multiply(that), lower == null ? null : lower.multiply(that) ); } } /** * Returns the closure of the image of {@code this} under multiplicative inversion. In general this is not one * {@code Interval}, so this method returns a list of disjoint {@code Interval}s whose union is the closure of the * image. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li> * The result is one of the following: * <li> * <ul>[]</ul> * <ul>[(–∞, ∞)]</ul> * <ul>[(–∞, q]] where q≤0</ul> * <ul>[[p, ∞)] where p≥0</ul> * <ul>[[p, q]] where p≠q, p and q both positive</ul> * <ul>[[p, q]] where p≠q, p and q both negative</ul> * <ul>[[p, p]] where p≠0</ul> * <ul>[(–∞, q], [0, ∞)] where q<0</ul> * <ul>[(–∞, 0], [p, ∞)] where p>0</ul> * <ul>[(–∞, q], [p, ∞)] where q<0, p>0</ul> * <ul></ul> * </li> * </li> * </ul> * * @return 1/{@code this} */ public @NotNull List<Interval> invert() { List<Interval> intervals = new ArrayList<>(); if (lower == null && upper == null) { intervals.add(ALL); } else if (lower == null) { if (upper == Rational.ZERO) { intervals.add(this); } else if (upper.signum() == 1) { intervals.add(new Interval(null, Rational.ZERO)); intervals.add(new Interval(upper.invert(), null)); } else { intervals.add(new Interval(null, upper.invert())); } return intervals; } else if (upper == null) { if (lower == Rational.ZERO) { intervals.add(this); } else if (lower.signum() == 1) { intervals.add(new Interval(lower.invert(), null)); } else { intervals.add(new Interval(null, lower.invert())); intervals.add(new Interval(Rational.ZERO, null)); } } else if (lower == Rational.ZERO) { if (upper != Rational.ZERO) { intervals.add(new Interval(upper.invert(), null)); } } else if (lower.signum() == 1) { intervals.add(new Interval(upper.invert(), lower.invert())); } else { if (upper == Rational.ZERO) { intervals.add(new Interval(null, lower.invert())); } else if (upper.signum() == -1) { intervals.add(new Interval(upper.invert(), lower.invert())); } else { intervals.add(new Interval(null, lower.invert())); intervals.add(new Interval(upper.invert(), null)); } } return intervals; } /** * Returns the smallest interval a such that if x∈{@code this}, 1/x∈a. * * <ul> * <li>{@code this} cannot be [0, 0].</li> * <li> * The result is one of the following: * <li> * <ul>(–∞, ∞)</ul> * <ul>(–∞, q] where q≤0</ul> * <ul>[p, ∞) where p≥0</ul> * <ul>[p, q] where p≠q, p and q both positive</ul> * <ul>[p, q] where p≠q, p and q both negative</ul> * <ul>[p, p] where p≠0</ul> * </li> * </li> * </ul> * * @return Conv(1/{@code this}) */ public @NotNull Interval invertHull() { return convexHull(invert()); } public @NotNull List<Interval> divide(@NotNull Interval that) { return makeDisjoint(toList(map(this::multiply, that.invert()))); } public @NotNull Interval divideHull(@NotNull Interval that) { return convexHull(toList(map(this::multiply, that.invert()))); } public @NotNull Interval divide(@NotNull Rational that) { if (that == Rational.ONE) return this; if (that.signum() == 1) { return new Interval( lower == null ? null : lower.divide(that), upper == null ? null : upper.divide(that) ); } else { return new Interval( upper == null ? null : upper.divide(that), lower == null ? null : lower.divide(that) ); } } public @NotNull Interval divide(@NotNull BigInteger that) { if (that.equals(BigInteger.ONE)) return this; if (that.signum() == 1) { return new Interval( lower == null ? null : lower.divide(that), upper == null ? null : upper.divide(that) ); } else { return new Interval( upper == null ? null : upper.divide(that), lower == null ? null : lower.divide(that) ); } } public @NotNull Interval divide(int that) { if (that == 1) return this; if (that > 0) { return new Interval( lower == null ? null : lower.divide(that), upper == null ? null : upper.divide(that) ); } else { return new Interval( upper == null ? null : upper.divide(that), lower == null ? null : lower.divide(that) ); } } public @NotNull Interval shiftLeft(int bits) { return new Interval( lower == null ? null : lower.shiftLeft(bits), upper == null ? null : upper.shiftLeft(bits) ); } public @NotNull Interval shiftRight(int bits) { return new Interval( lower == null ? null : lower.shiftRight(bits), upper == null ? null : upper.shiftRight(bits) ); } // public @NotNull Interval pow(int p) { // if (p == 0) return ONE; // if (p == 1) return this; // if (p < 0) return pow(-p).invert(); // if (p % 2 == 0) { // int ls = lower == null ? -1 : lower.signum(); // int us = upper == null ? 1 : upper.signum(); // if (ls != -1 && us != -1) { // return new Interval(lower.pow(p), upper == null ? null : upper.pow(p)); // } // if (ls != 1 && us != 1) { // return new Interval(upper.pow(p), lower == null ? null : lower.pow(p)); // } // Rational a = lower == null ? null : lower.pow(p); // Rational b = upper == null ? null : upper.pow(p); // Rational max = a == null || b == null ? null : max(a, b); // return new Interval(Rational.ZERO, max); // } else { // return new Interval(lower == null ? null : lower.pow(p), upper == null ? null : upper.pow(p)); // } // } /** * If {@code this} and {@code that} are disjoint, returns the ordering between any element of {@code this} and any * element of {@code that}; otherwise, returns an empty {@code Optional}. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result may be any {@code Optional<Ordering>}.</li> * </ul> * * @param that the interval whose elements we're comparing {@code this}'s elements to * @return compare(x, y) for all x∈{@code this} and y∈{@code that}, if compare(x, y) is unique */ public @NotNull Optional<Ordering> elementCompare(@NotNull Interval that) { if (lower != null && lower.equals(upper) && equals(that)) return Optional.of(EQ); if (!disjoint(that)) return Optional.empty(); Rational thisSample = lower == null ? upper : lower; Rational thatSample = that.lower == null ? that.upper : that.lower; assert thisSample != null; assert thatSample != null; return Optional.of(compare(thisSample, thatSample)); } /** * Determines whether {@code this} is equal to {@code that}. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} may be any {@code Object}.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @param that The {@code Interval} to be compared with {@code this} * @return {@code this}={@code that} */ @Override public boolean equals(Object that) { if (this == that) return true; if (that == null || getClass() != that.getClass()) return false; Interval interval = (Interval) that; return (lower == null ? interval.lower == null : lower.equals(interval.lower)) && (upper == null ? interval.upper == null : upper.equals(interval.upper)); } /** * Calculates the hash code of {@code this}. * * <ul> * <li>@{code this} may be any {@code Interval}.</li> * <li>(conjecture) The result may be any {@code int}.</li> * </ul> * * @return {@code this}'s hash code. */ @Override public int hashCode() { int result = lower != null ? lower.hashCode() : 0; result = 31 * result + (upper != null ? upper.hashCode() : 0); return result; } /** * Compares {@code this} to {@code that}, returning 1, –1, or 0 if the answer is "greater than", "less than", or * "equal to", respectively. {@code Interval}s are ordered on their lower bound, then on their upper bound; –∞ and * ∞ behave as expected. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result may be –1, 0, or 1.</li> * </ul> * * @param that The {@code Interval} to be compared with {@code this} * @return {@code this} compared to {@code that} */ @Override public int compareTo(@NotNull Interval that) { if (this == that) return 0; if (lower == null && that.lower != null) return -1; if (lower != null && that.lower == null) return 1; Ordering lowerOrdering = lower == null ? EQ : compare(lower, that.lower); if (lowerOrdering != EQ) return lowerOrdering.toInt(); if (upper == null && that.upper != null) return 1; if (upper != null && that.upper == null) return -1; return (upper == null ? EQ : compare(upper, that.upper)).toInt(); } /** * Creates an {@code Interval} from a {@code String}. Valid strings are in one of these four forms: * {@code "(-Infinity, Infinity)"}, {@code "(-Infinity, " + q + "]"}, * {@code "[" + p + ", Infinity)"}, or {@code "[" + p + ", " + q + "]"}, where {@code p} and {@code q} are valid * inputs to {@link mho.qbar.objects.Rational#read}, and {@code p}≤{@code q} * * <ul> * <li>{@code s} cannot be null.</li> * <li>The result may be any {@code Optional<Interval>}, or null.</li> * </ul> * * @param s a string representation of a {@code Rational}. * @return the wrapped {@code Rational} represented by {@code s}, or {@code empty} if {@code s} is invalid. */ public static @NotNull Optional<Interval> read(@NotNull String s) { if (s.isEmpty()) return Optional.empty(); char left = s.charAt(0); if (left != '[' && left != '(') return Optional.empty(); char right = s.charAt(s.length() - 1); if (right != ']' && right != ')') return Optional.empty(); int commaIndex = s.indexOf(", "); if (commaIndex == -1) return Optional.empty(); String leftString = s.substring(1, commaIndex); String rightString = s.substring(commaIndex + 2, s.length() - 1); Rational lower = null; if (left == '(') { if (!leftString.equals("-Infinity")) return Optional.empty(); } else { Optional<Rational> optLower = Rational.read(leftString); if (!optLower.isPresent()) return Optional.empty(); lower = optLower.get(); } Rational upper = null; if (right == ')') { if (!rightString.equals("Infinity")) return Optional.empty(); } else { Optional<Rational> optUpper = Rational.read(rightString); if (!optUpper.isPresent()) return Optional.empty(); upper = optUpper.get(); } if (lower == null && upper == null) return Optional.of(ALL); if (lower == null) return Optional.of(lessThanOrEqualTo(upper)); if (upper == null) return Optional.of(greaterThanOrEqualTo(lower)); return le(lower, upper) ? Optional.of(of(lower, upper)) : Optional.<Interval>empty(); } /** * Finds the first occurrence of an {@code Interval} in a {@code String}. Returns the {@code Interval} and the * index at which it was found. Returns an empty {@code Optional} if no {@code Interval} is found. Only * {@code String}s which could have been emitted by {@link Interval#toString} are recognized. The longest possible * {@code Interval} is parsed. * * <ul> * <li>{@code s} must be non-null.</li> * <li>The result is non-null. If it is non-empty, then neither of the {@code Pair}'s components is null, and the * second component is non-negative.</li> * </ul> * * @param s the input {@code String} * @return the first {@code Interval} found in {@code s}, and the index at which it was found */ public static @NotNull Optional<Pair<Interval, Integer>> findIn(@NotNull String s) { return Readers.genericFindIn(Interval::read, " (),-/0123456789I[]finty", s); } /** * Creates a string representation of {@code this}. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>The result is a string in on of four forms: {@code "(-Infinity, Infinity)"}, * {@code "(-Infinity, " + q.toString() + "]"}, {@code "[" + p.toString() + ", Infinity)"}, or * {@code "[" + p.toString() + ", " + q.toString() + "]"}, where {@code p} and {@code q} are {@code Rational}s * such that {@code p} is less than or equal to {@code q}.</li> * </ul> * * @return a string representation of {@code this}. */ public @NotNull String toString() { return (lower == null ? "(-Infinity" : "[" + lower) + ", " + (upper == null ? "Infinity)" : upper + "]"); } }
src/main/java/mho/qbar/objects/Interval.java
package mho.qbar.objects; import mho.wheels.iterables.IterableUtils; import mho.wheels.misc.FloatingPointUtils; import mho.wheels.misc.Readers; import mho.wheels.ordering.Ordering; import mho.wheels.structures.Pair; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.*; import static mho.wheels.iterables.IterableUtils.*; import static mho.wheels.ordering.Ordering.*; /** * <p>The {@code Interval} class represents an interval of real numbers. If we let p and q be rationals, p≤q, the * representable intervals are (–∞, ∞), (–∞, q], [p, ∞), and [p, q]. If p = q, the {@code Interval} represents a single * number. The empty interval cannot be represented. * * <p>In general, f(I), where I is an {@code Interval}, is taken to mean the image of I under f. Often this image is * not an {@code Interval} itself, in which case the function might return a set of {@code Interval}s, whose closed * union is the image, or it may just return the closure of the image's convex hull. Similar considerations apply for * functions of two {@code Interval}s, etc. * * <p>This class is immutable. */ public final class Interval implements Comparable<Interval> { /** * [0, 0] */ public static final @NotNull Interval ZERO = new Interval(Rational.ZERO, Rational.ZERO); /** * [1, 1] */ public static final @NotNull Interval ONE = new Interval(Rational.ONE, Rational.ONE); /** * (–∞, ∞) */ public static final @NotNull Interval ALL = new Interval(null, null); /** * The lower bound of this interval if the lower bound is finite, or null if the lower bound is –∞ */ private final @Nullable Rational lower; /** * The upper bound of this interval if the upper bound is finite, or null if the upper bound is ∞ */ private final @Nullable Rational upper; /** * Private constructor from {@link Rational}s; assumes arguments are valid. If lower is null, the * {@code Interval}'s lower bound is –∞; if upper is null, the {@code Interval}'s upper bound is ∞. * * <ul> * <li>{@code lower} may be any {@code Rational}, or null.</li> * <li>{@code upper} may be any {@code Rational}, or null.</li> * <li>If {@code lower} and {@code upper} are both non-null, {@code lower} must be less than or equal to * {@code upper}.</li> * </ul> * * @param lower the lower bound * @param upper the upper bound */ private Interval(@Nullable Rational lower, @Nullable Rational upper) { this.lower = lower; this.upper = upper; } /** * Returns this {@code Interval}'s lower bound. If the lower bound is –∞, an empty {@code Optional} is returned. * * <ul> * <li>The result is non-null.</li> * </ul> * * @return the lower bound */ public @NotNull Optional<Rational> getLower() { return lower == null ? Optional.<Rational>empty() : Optional.of(lower); } /** * Returns this {@code Interval}'s upper bound. If the lower bound is ∞, an empty {@code Optional} is returned. * * <ul> * <li>The result is non-null.</li> * </ul> * * @return the upper bound */ public @NotNull Optional<Rational> getUpper() { return upper == null ? Optional.<Rational>empty() : Optional.of(upper); } /** * Creates a finitely-bounded {@code Interval} from {@code Rationals}. * * <ul> * <li>{@code lower} cannot be null.</li> * <li>{@code upper} cannot be null.</li> * <li>{@code lower} must be less than or equal to {@code upper}.</li> * </ul> * * @param lower the lower bound * @param upper the upper bound * @return [{@code lower}, {@code upper}] */ public static @NotNull Interval of(@NotNull Rational lower, @NotNull Rational upper) { if (gt(lower, upper)) throw new IllegalArgumentException("lower bound cannot be greater than upper bound"); return new Interval(lower, upper); } /** * Creates an interval whose lower bound is –∞. * * <ul> * <li>{@code upper} cannot be null.</li> * </ul> * * @param upper the upper bound * @return (–∞, {@code upper}] */ @SuppressWarnings("JavaDoc") public static @NotNull Interval lessThanOrEqualTo(@NotNull Rational upper) { return new Interval(null, upper); } /** * Creates an interval whose upper bound is ∞. * * <ul> * <li>{@code lower} cannot be null.</li> * </ul> * * @param lower the lower bound * @return [{@code lower}, ∞) */ public static @NotNull Interval greaterThanOrEqualTo(@NotNull Rational lower) { return new Interval(lower, null); } /** * Creates an interval containing exactly one {@code Rational}. * * <ul> * <li>{@code x} cannot be null.</li> * </ul> * * @param x the value contained in this {@code Interval} * @return [{@code x}, {@code x}] */ public static @NotNull Interval of(@NotNull Rational x) { return new Interval(x, x); } /** * Determines whether {@code this} has finite bounds. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @return whether {@code this} is finitely-bounded */ public boolean isFinitelyBounded() { return lower != null && upper != null; } /** * Determines whether {@code this} contains a {@code Rational}. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code x} cannot be null.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @param x the test {@code Rational} * @return {@code x}∈{@code this} */ public boolean contains(@NotNull Rational x) { if (lower == null && upper == null) return true; if (lower == null) return le(x, upper); if (upper == null) return ge(x, lower); return ge(x, lower) && le(x, upper); } /** * Determines whether {@code this} contains (is a superset of) an {@code Interval}. Every {@code Interval} contains * itself. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @param that the test {@code Interval} * @return {@code that}⊆{@code this} */ public boolean contains(@NotNull Interval that) { return (lower == null || (that.lower != null && ge(that.lower, lower))) && (upper == null || (that.upper != null && le(that.upper, upper))); } /** * Determines the diameter (length) of {@code this}. If {@code this} has infinite diameter, an empty * {@code Optional} is returned. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>The result may be empty, or it may contain a non-negative {@code Rational}.</li> * </ul> * * @return the diameter of {@code this} */ public @NotNull Optional<Rational> diameter() { if (lower == null || upper == null) return Optional.empty(); return Optional.of(upper.subtract(lower)); } /** * Determines the convex hull of two {@code Interval}s, or the {@code Interval} with minimal diameter that is a * superset of the two {@code Interval}s. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code Interval} to be hulled with {@code this} * @return Conv({@code this}, {@code that}) */ @SuppressWarnings("JavaDoc") public @NotNull Interval convexHull(@NotNull Interval that) { return new Interval( lower == null || that.lower == null ? null : min(lower, that.lower), upper == null || that.upper == null ? null : max(upper, that.upper) ); } /** * Determines the convex hull of a set of {@code Interval}s, or the {@code Interval} with minimal diameter that is * a superset of all of the {@code Interval}s. * * <ul> * <li>{@code as} cannot be empty and may not contain any null elements.</li> * <li>The result is not null.</li> * </ul> * * @param as the {@code Interval}s. * @return Conv({@code as}) */ @SuppressWarnings("JavaDoc") public static @NotNull Interval convexHull(@NotNull List<Interval> as) { if (any(a -> a == null, as)) throw new NullPointerException(); //noinspection ConstantConditions return foldl1(p -> p.a.convexHull(p.b), as); } /** * Returns the intersection of two {@code Interval}s. If the intersection is empty, an empty {@code Optional} is * returned. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code Interval} to be intersected with {@code this} * @return {@code this}∩{@code that} */ public @NotNull Optional<Interval> intersection(@NotNull Interval that) { Rational iLower; if (lower == null && that.lower == null) { iLower = null; } else if (lower == null) { iLower = that.lower; } else if (that.lower == null) { iLower = lower; } else { iLower = max(lower, that.lower); } Rational iUpper; if (upper == null && that.upper == null) { iUpper = null; } else if (upper == null) { iUpper = that.upper; } else if (that.upper == null) { iUpper = upper; } else { iUpper = min(upper, that.upper); } if (iLower != null && iUpper != null && gt(iLower, iUpper)) return Optional.empty(); return Optional.of(new Interval(iLower, iUpper)); } /** * Determines whether two {@code Interval}s are disjoint (whether their intersections are empty). * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @param that the {@code Interval} tested for disjointness with {@code this} * @return {@code this}∩{@code that}=∅ */ public boolean disjoint(@NotNull Interval that) { return !intersection(that).isPresent(); } /** * Transforms a list of {@code Interval}s into a list of disjoint {@code Interval}s with the same union as the * original set. * * <ul> * <li>{@code as} cannot be null and may not contain any null elements.</li> * <li>The result is a sorted list of pairwise disjoint {@code Interval}s.</li> * </ul> * * @param as a list of {@code Interval}s * @return a list of disjoint {@code Interval}s whose union is the same as the union of {@code as} */ public static @NotNull List<Interval> makeDisjoint(@NotNull List<Interval> as) { List<Interval> simplified = new ArrayList<>(); Interval acc = null; for (Interval a : sort(as)) { if (acc == null) { acc = a; } else if (acc.disjoint(a)) { simplified.add(acc); acc = a; } else { acc = acc.convexHull(a); } } if (acc != null) simplified.add(acc); return simplified; } /** * The complement of an {@code Interval} generally involves open intervals, so it can't be represented as a union * of {@code Interval}s. However, we can get close; we can represent the complement's closure. This is equal to the * complement, except that it includes the endpoints of the original {@code Interval}. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li> * The result is in one of these forms: * <ul> * <li>an empty list</li> * <li>a list containing one {@code Interval}, unbounded on one side</li> * <li>a list containing (–∞, ∞); this happens when {@code this} has diameter 0</li> * <li>a list containing two disjoint {@code Intervals}, the first unbounded on the left and the second * unbounded on the right</li> * </ul> * </li> * </ul> * * @return the closure of ℝ\{@code this} */ public @NotNull List<Interval> complement() { if (lower == null && upper == null) return new ArrayList<>(); if (lower == null) return Arrays.asList(new Interval(upper, null)); if (upper == null) return Arrays.asList(new Interval(null, lower)); if (lower.equals(upper)) return Arrays.asList(ALL); return Arrays.asList(new Interval(null, lower), new Interval(upper, null)); } /** * Returns the midpoint of {@code this}. * * <ul> * <li>{@code this} must be finitely bounded.</li> * <li>The result is not null.</li> * </ul> * * @return the average of {@code lower} and {@code upper}. */ public @NotNull Rational midpoint() { if (lower == null || upper == null) throw new ArithmeticException("an unbounded interval has no midpoint"); return lower.add(upper).shiftRight(1); } /** * Splits {@code this} into two intervals at {@code x}. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code x} cannot be null.</li> * <li>{@code this} must contain {@code x}.</li> * <li>The result is a pair of {@code Interval}s, neither null, such that the upper bound of the first is equal * to the lower bound of the second.</li> * </ul> * * @param x the point at which {@code this} is split. * @return the two pieces of {@code this}. */ public @NotNull Pair<Interval, Interval> split(@NotNull Rational x) { if (!contains(x)) throw new ArithmeticException("interval does not contain specified split point"); return new Pair<>(new Interval(lower, x), new Interval(x, upper)); } /** * Splits {@code this} into two equal {@code Interval}s. * * <ul> * <li>{@code this} must be finitely bounded.</li> * <li>The result is a pair of equal-diameter, finitely-bounded {@code Interval}s such the the upper bound of the * first is equal to the lower bound of the second.</li> * </ul> * * @return the two halves of {@code this}. */ public @NotNull Pair<Interval, Interval> bisect() { return split(midpoint()); } /** * Returns the smallest {@code Interval} containing all reals that are closer to a given {@code float} than to * any other {@code float}. Some special cases must be taken into account: * <ul> * <li>If the {@code float} is positive infinity, the result contains all reals that are greater than or equal to * {@code Float.MAX_VALUE}.</li> * <li>If the {@code float} is negative infinity, the result contains all reals that are less than or equal to * {@code -Float.MAX_VALUE}.</li> * <li>If the {@code float} is {@code Float.MAX_VALUE}, the result contains all reals that are less than or equal * to {@code Float.MAX_VALUE} and closer to it than to any other {@code float}.</li> * <li>If the {@code float} is {@code -Float.MAX_VALUE}, the result contains all reals that are greater than or * equal to {@code -Float.MAX_VALUE} and closer to it than to any other {@code float}.</li> * </ul> * * Positive and negative 0 yield the same result. * * <ul> * <li>{@code f} may be any {@code float} except NaN.</li> * <li>The result is one of * <ul> * <li>[{@code Float.MAX_VALUE}, ∞)</li> * <li>(–∞, –{@code Float.MAX_VALUE}]</li> * <li>[({@code a}+{@code b})/2, {@code b}], where {@code b} is {@code Float.MAX_VALUE} and {@code a} is * {@code b}'s predecessor</li> * <li>[{@code a}, ({@code a}+{@code b})/2], where {@code a} is –{@code Float.MAX_VALUE} and {@code b} is * {@code a}'s successor</li> * <li>[({@code a}+{@code b})/2, ({@code b}+{@code c})/2], where {@code a}, {@code b}, and {@code c} are * equal to three consecutive finite {@code float}s (but + and / correspond to real operations, not * {@code float} operations).</li> * </ul> * </li> * </ul> * * @param f a {@code float}. * @return the closure of the preimage of {@code f} with respect to rounding-to-nearest-{@code float}. */ public static @NotNull Interval roundingPreimage(float f) { if (Float.isNaN(f)) throw new ArithmeticException("cannot find preimage of NaN"); if (Float.isInfinite(f)) { if (f > 0) { return new Interval(Rational.LARGEST_FLOAT, null); } else { return new Interval(null, Rational.LARGEST_FLOAT.negate()); } } if (f == Float.MAX_VALUE) { //noinspection ConstantConditions return new Interval( Rational.ofExact(FloatingPointUtils.predecessor(f)).add(Rational.LARGEST_FLOAT).shiftRight(1), Rational.LARGEST_FLOAT ); } if (f == -Float.MAX_VALUE) { //noinspection ConstantConditions return new Interval( Rational.LARGEST_FLOAT.negate(), Rational.ofExact(FloatingPointUtils.successor(f)).subtract(Rational.LARGEST_FLOAT).shiftRight(1) ); } Rational r = Rational.ofExact(f); float predecessor = FloatingPointUtils.predecessor(f); @SuppressWarnings("ConstantConditions") Rational lower = predecessor == Float.NEGATIVE_INFINITY ? null : r.add(Rational.ofExact(predecessor)).shiftRight(1); float successor = FloatingPointUtils.successor(f); @SuppressWarnings("ConstantConditions") Rational upper = successor == Float.POSITIVE_INFINITY ? null : r.add(Rational.ofExact(successor)).shiftRight(1); return new Interval(lower, upper); } /** * Returns the smallest {@code Interval} containing all reals that are closer to a given {@link double} than to any * other {@code double}. * * Some special cases must be taken into account: * <ul> * <li>If the {@code double} is positive infinity, the result contains all reals that are greater than or equal to * {@code Double.MAX_VALUE}.</li> * <li>If the {@code double} is negative infinity, the result contains all reals that are less than or equal to * {@code -Double.MAX_VALUE}.</li> * <li>If the {@code double} is {@code Double.MAX_VALUE}, the result contains all reals that are less than or * equal to {@code Double.MAX_VALUE} and closer to it than to any other {@code double}.</li> * <li>If the {@code double} is {@code -Double.MAX_VALUE}, the result contains all reals that are greater than or * equal to {@code -Double.MAX_VALUE} and closer to it than to any other {@code double}.</li> * </ul> * * Positive and negative 0 yield the same result. * * <ul> * <li>{@code d} may be any {@code double} except {@code NaN}.</li> * <li>The result is one of * <ul> * <li>[{@code Double.MAX_VALUE}, ∞)</li> * <li>(–∞, –{@code Double.MAX_VALUE}]</li> * <li>[({@code a}+{@code b})/2, {@code b}], where {@code b} is {@code Double.MAX_VALUE} and {@code a} is * {@code b}'s predecessor</li> * <li>[{@code a}, ({@code a}+{@code b})/2], where {@code a} is –{@code Double.MAX_VALUE} and {@code b} is * {@code a}'s successor</li> * <li>[({@code a}+{@code b})/2, ({@code b}+{@code c})/2], where {@code a}, {@code b}, and {@code c} are equal * to three consecutive finite {@code double}s (but + and / correspond to real operations, not {@code double} * operations).</li> * </ul> * </li> * </ul> * * @param d a {@code double}. * @return the closure of the preimage of {@code d} with respect to rounding-to-nearest-{@code double}. */ public static @NotNull Interval roundingPreimage(double d) { if (Double.isNaN(d)) throw new ArithmeticException("cannot find preimage of NaN"); if (Double.isInfinite(d)) { if (d > 0) { return new Interval(Rational.LARGEST_DOUBLE, null); } else { return new Interval(null, Rational.LARGEST_DOUBLE.negate()); } } if (d == Double.MAX_VALUE) { //noinspection ConstantConditions return new Interval( Rational.ofExact(FloatingPointUtils.predecessor(d)).add(Rational.LARGEST_DOUBLE).shiftRight(1), Rational.LARGEST_DOUBLE ); } if (d == -Double.MAX_VALUE) { //noinspection ConstantConditions return new Interval( Rational.LARGEST_DOUBLE.negate(), Rational.ofExact(FloatingPointUtils.successor(d)).subtract(Rational.LARGEST_DOUBLE).shiftRight(1) ); } Rational r = Rational.ofExact(d); double predecessor = FloatingPointUtils.predecessor(d); @SuppressWarnings("ConstantConditions") Rational lower = predecessor == Double.NEGATIVE_INFINITY ? null : r.add(Rational.ofExact(predecessor)).shiftRight(1); double successor = FloatingPointUtils.successor(d); @SuppressWarnings("ConstantConditions") Rational upper = predecessor == Double.POSITIVE_INFINITY ? null : r.add(Rational.ofExact(successor)).shiftRight(1); return new Interval(lower, upper); } /** * Returns an {@code Interval} representing all real numbers that round to a specified {@link BigDecimal} (taking * scale into account). * * <ul> * <li>{@code bd} cannot be null.</li> * <li>The result is an interval of the form [a×10<sup>b</sup>–5×10<sup>c</sup>, * a×10<sup>b</sup>+5×10<sup>c</sup>], where a, b, and c are integers and c{@literal <}b.</li> * </ul> * * @param bd a {@code BigDecimal} * @return the closure of the preimage of {@code bd} with respect to rounding-to-nearest-{@code BigDecimal}. */ public static @NotNull Interval roundingPreimage(@NotNull BigDecimal bd) { Rational center = Rational.of(bd); Rational maxAbsoluteError = Rational.of(10).pow(-bd.scale()).shiftRight(1); return new Interval(center.subtract(maxAbsoluteError), center.add(maxAbsoluteError)); } /** * Returns a pair of {@code float}s x, y such that [x, y] is the smallest interval with {@code float} bounds which * contains {@code this}. x or y may be infinite if {@code this}'s bounds are infinite or very large in magnitude. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>Neither of the result's elements are null or {@code NaN}. The second element is greater than or equal to * the first. The first element cannot be {@code Infinity} or negative zero. The second element cannot be * {@code -Infinity}. If the second element is negative zero, the first element cannot be positive zero.</li> * </ul> * * @return the smallest {@code float} interval containing {@code this}. */ public @NotNull Pair<Float, Float> floatRange() { float fLower = lower == null ? Float.NEGATIVE_INFINITY : lower.floatValue(RoundingMode.FLOOR); float fUpper = upper == null ? Float.POSITIVE_INFINITY : upper.floatValue(RoundingMode.CEILING); return new Pair<>(fLower, fUpper); } /** * Returns a pair of {@code double}s x, y such that [x, y] is the smallest interval with {@code double} bounds * which contains {@code this}. x or y may be infinite if {@code this}'s bounds are infinite or very large in * magnitude. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>Neither of the result's elements are null or {@code NaN}. The second element is greater than or equal to * the first. The first element cannot be {@code Infinity} or negative zero. The second element cannot be * {@code -Infinity}. If the second element is negative zero, the first element cannot be positive zero.</li> * </ul> * * @return the smallest {@code double} interval containing {@code this}. */ public @NotNull Pair<Double, Double> doubleRange() { double dLower = lower == null ? Double.NEGATIVE_INFINITY : lower.doubleValue(RoundingMode.FLOOR); double dUpper = upper == null ? Double.POSITIVE_INFINITY : upper.doubleValue(RoundingMode.CEILING); return new Pair<>(dLower, dUpper); } /** * Returns the smallest interval z such that if a∈{@code this} and b∈{@code that}, a+b∈z. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code Interval} added to {@code this} * @return {@code this}+{@code that} */ public @NotNull Interval add(@NotNull Interval that) { Rational lowerSum = lower == null || that.lower == null ? null : lower.add(that.lower); Rational upperSum = upper == null || that.upper == null ? null : upper.add(that.upper); return new Interval(lowerSum, upperSum); } /** * Returns the smallest interval a such that if x∈{@code this}, –x∈a. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>The result is not null.</li> * </ul> * * @return –{@code this} */ public @NotNull Interval negate() { if (lower == null && upper == null) return this; if (lower == null) return new Interval(upper.negate(), null); if (upper == null) return new Interval(null, lower.negate()); return new Interval(upper.negate(), lower.negate()); } /** * Returns the smallest interval a such that if x∈{@code this}, |x|∈a. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>The result is an interval whose lower bound is finite and non-negative.</li> * </ul> * * @return |{@code this}| */ public @NotNull Interval abs() { if (lower == null && upper == null) return new Interval(Rational.ZERO, null); if (lower == null) { return new Interval(upper.signum() == -1 ? upper.negate() : Rational.ZERO, null); } if (upper == null) { return lower.signum() == -1 ? new Interval(Rational.ZERO, null) : this; } if (lower.signum() == 1 && upper.signum() == 1) return this; if (lower.signum() == -1 && upper.signum() == -1) return negate(); return new Interval(Rational.ZERO, max(lower.negate(), upper)); } /** * If every real in {@code this} has the same sign, returns that sign; otherwise, returns an empty * {@code Optional}. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>The result is either empty, or contains -1, 0, or 1.</li> * </ul> * * @return sgn(x) for all x∈{@code this}, if sgn(x) is unique */ public @NotNull Optional<Integer> signum() { int lowerSignum = lower == null ? -1 : lower.signum(); int upperSignum = upper == null ? 1 : upper.signum(); return lowerSignum == upperSignum ? Optional.of(lowerSignum) : Optional.<Integer>empty(); } /** * Returns the smallest interval z such that if a∈{@code this} and b∈{@code that}, a–b∈z. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code Interval} subtracted from {@code this} * @return {@code this}–{@code that} */ public @NotNull Interval subtract(@NotNull Interval that) { return add(that.negate()); } /** * Returns the smallest interval z such that if a∈{@code this} and b∈{@code that}, a×b∈z. Interval addition does * not distribute over interval multiplication: for example, ([0, 1] + (–∞, -1]) × [0, 1] = (–∞, 0], but * [0, 1] × [0, 1] + (–∞, -1] × [0, 1] = (–∞, 1]. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code Interval} that {@code this} is multiplied by * @return {@code this}×{@code that} */ public @NotNull Interval multiply(@NotNull Interval that) { boolean thisHasPositive = upper == null || upper.signum() == 1; boolean thatHasPositive = that.upper == null || that.upper.signum() == 1; boolean thisHasNegative = lower == null || lower.signum() == -1; boolean thatHasNegative = that.lower == null || that.lower.signum() == -1; boolean minIsNegInf = lower == null && thatHasPositive || upper == null && thatHasNegative || that.lower == null && thisHasPositive || that.upper == null && thisHasNegative; boolean maxIsPosInf = upper == null && thatHasPositive || lower == null && thatHasNegative || that.upper == null && thisHasPositive || that.lower == null && thisHasNegative; if (minIsNegInf && maxIsPosInf) return ALL; List<Rational> extremes = new ArrayList<>(); if (lower != null) { if (that.lower != null) extremes.add(lower.multiply(that.lower)); if (that.upper != null) extremes.add(lower.multiply(that.upper)); } if (upper != null) { if (that.lower != null) extremes.add(upper.multiply(that.lower)); if (that.upper != null) extremes.add(upper.multiply(that.upper)); } if (extremes.isEmpty()) extremes.add(Rational.ZERO); if (minIsNegInf) return new Interval(null, maximum(extremes)); if (maxIsPosInf) return new Interval(minimum(extremes), null); return new Interval(minimum(extremes), maximum(extremes)); } /** * Returns the smallest interval a such that if x∈{@code this}, x×{@code that}∈a. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code Rational} that {@code this} is multiplied by * @return {@code this}×{@code that} */ public @NotNull Interval multiply(@NotNull Rational that) { if (that == Rational.ZERO) return ZERO; if (that == Rational.ONE) return this; if (that.signum() == 1) { return new Interval( lower == null ? null : lower.multiply(that), upper == null ? null : upper.multiply(that) ); } else { return new Interval( upper == null ? null : upper.multiply(that), lower == null ? null : lower.multiply(that) ); } } /** * Returns the smallest interval a such that if x∈{@code this}, x×{@code that}∈a. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code BigInteger} that {@code this} is multiplied by * @return {@code this}×{@code that} */ public @NotNull Interval multiply(@NotNull BigInteger that) { if (that.equals(BigInteger.ZERO)) return ZERO; if (that.equals(BigInteger.ONE)) return this; if (that.signum() == 1) { return new Interval( lower == null ? null : lower.multiply(that), upper == null ? null : upper.multiply(that) ); } else { return new Interval( upper == null ? null : upper.multiply(that), lower == null ? null : lower.multiply(that) ); } } /** * Returns the smallest interval a such that if x∈{@code this}, x×{@code that}∈a. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code int} that {@code this} is multiplied by * @return {@code this}×{@code that} */ public @NotNull Interval multiply(int that) { if (that == 0) return ZERO; if (that == 1) return this; if (that > 0) { return new Interval( lower == null ? null : lower.multiply(that), upper == null ? null : upper.multiply(that) ); } else { return new Interval( upper == null ? null : upper.multiply(that), lower == null ? null : lower.multiply(that) ); } } public @NotNull List<Interval> invert() { List<Interval> intervals = new ArrayList<>(); if (lower == null && upper == null) { intervals.add(ALL); } else if (lower == null) { if (upper == Rational.ZERO) { intervals.add(this); } else if (upper.signum() == 1) { intervals.add(new Interval(null, Rational.ZERO)); intervals.add(new Interval(upper.invert(), null)); } else { intervals.add(new Interval(null, upper.invert())); } return intervals; } else if (upper == null) { if (lower == Rational.ZERO) { intervals.add(this); } else if (lower.signum() == 1) { intervals.add(new Interval(lower.invert(), null)); } else { intervals.add(new Interval(null, lower.invert())); intervals.add(new Interval(Rational.ZERO, null)); } } else if (lower == Rational.ZERO) { if (upper != Rational.ZERO) { intervals.add(new Interval(upper.invert(), Rational.ZERO)); } } else if (lower.signum() == 1) { intervals.add(new Interval(upper.invert(), lower.invert())); } else { if (upper == Rational.ZERO) { intervals.add(new Interval(null, lower.invert())); } else if (upper.signum() == -1) { intervals.add(new Interval(upper.invert(), lower.invert())); } else { intervals.add(new Interval(null, lower.invert())); intervals.add(new Interval(upper.invert(), null)); } } return intervals; } public @NotNull Interval invertHull() { return convexHull(invert()); } public @NotNull List<Interval> divide(@NotNull Interval that) { return makeDisjoint(toList(map(this::multiply, that.invert()))); } public @NotNull Interval divideHull(@NotNull Interval that) { return convexHull(toList(map(this::multiply, that.invert()))); } public @NotNull Interval divide(@NotNull Rational that) { if (that == Rational.ONE) return this; if (that.signum() == 1) { return new Interval( lower == null ? null : lower.divide(that), upper == null ? null : upper.divide(that) ); } else { return new Interval( upper == null ? null : upper.divide(that), lower == null ? null : lower.divide(that) ); } } public @NotNull Interval divide(@NotNull BigInteger that) { if (that.equals(BigInteger.ONE)) return this; if (that.signum() == 1) { return new Interval( lower == null ? null : lower.divide(that), upper == null ? null : upper.divide(that) ); } else { return new Interval( upper == null ? null : upper.divide(that), lower == null ? null : lower.divide(that) ); } } public @NotNull Interval divide(@NotNull int that) { if (that == 1) return this; if (that > 0) { return new Interval( lower == null ? null : lower.divide(that), upper == null ? null : upper.divide(that) ); } else { return new Interval( upper == null ? null : upper.divide(that), lower == null ? null : lower.divide(that) ); } } public @NotNull Interval shiftLeft(int bits) { return new Interval( lower == null ? null : lower.shiftLeft(bits), upper == null ? null : upper.shiftLeft(bits) ); } public @NotNull Interval shiftRight(int bits) { return new Interval( lower == null ? null : lower.shiftRight(bits), upper == null ? null : upper.shiftRight(bits) ); } // public @NotNull Interval pow(int p) { // if (p == 0) return ONE; // if (p == 1) return this; // if (p < 0) return pow(-p).invert(); // if (p % 2 == 0) { // int ls = lower == null ? -1 : lower.signum(); // int us = upper == null ? 1 : upper.signum(); // if (ls != -1 && us != -1) { // return new Interval(lower.pow(p), upper == null ? null : upper.pow(p)); // } // if (ls != 1 && us != 1) { // return new Interval(upper.pow(p), lower == null ? null : lower.pow(p)); // } // Rational a = lower == null ? null : lower.pow(p); // Rational b = upper == null ? null : upper.pow(p); // Rational max = a == null || b == null ? null : max(a, b); // return new Interval(Rational.ZERO, max); // } else { // return new Interval(lower == null ? null : lower.pow(p), upper == null ? null : upper.pow(p)); // } // } /** * If {@code this} and {@code that} are disjoint, returns the ordering between any element of {@code this} and any * element of {@code that}; otherwise, returns an empty {@code Optional}. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result may be any {@code Optional<Ordering>}.</li> * </ul> * * @param that the interval whose elements we're comparing {@code this}'s elements to * @return compare(x, y) for all x∈{@code this} and y∈{@code that}, if compare(x, y) is unique */ public @NotNull Optional<Ordering> elementCompare(@NotNull Interval that) { if (lower != null && lower.equals(upper) && equals(that)) return Optional.of(EQ); if (!disjoint(that)) return Optional.empty(); Rational thisSample = lower == null ? upper : lower; Rational thatSample = that.lower == null ? that.upper : that.lower; assert thisSample != null; assert thatSample != null; return Optional.of(compare(thisSample, thatSample)); } /** * Determines whether {@code this} is equal to {@code that}. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} may be any {@code Object}.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @param that The {@code Interval} to be compared with {@code this} * @return {@code this}={@code that} */ @Override public boolean equals(Object that) { if (this == that) return true; if (that == null || getClass() != that.getClass()) return false; Interval interval = (Interval) that; return (lower == null ? interval.lower == null : lower.equals(interval.lower)) && (upper == null ? interval.upper == null : upper.equals(interval.upper)); } /** * Calculates the hash code of {@code this}. * * <ul> * <li>@{code this} may be any {@code Interval}.</li> * <li>(conjecture) The result may be any {@code int}.</li> * </ul> * * @return {@code this}'s hash code. */ @Override public int hashCode() { int result = lower != null ? lower.hashCode() : 0; result = 31 * result + (upper != null ? upper.hashCode() : 0); return result; } /** * Compares {@code this} to {@code that}, returning 1, –1, or 0 if the answer is "greater than", "less than", or * "equal to", respectively. {@code Interval}s are ordered on their lower bound, then on their upper bound; –∞ and * ∞ behave as expected. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} cannot be null.</li> * <li>The result may be –1, 0, or 1.</li> * </ul> * * @param that The {@code Interval} to be compared with {@code this} * @return {@code this} compared to {@code that} */ @Override public int compareTo(@NotNull Interval that) { if (this == that) return 0; if (lower == null && that.lower != null) return -1; if (lower != null && that.lower == null) return 1; Ordering lowerOrdering = lower == null ? EQ : compare(lower, that.lower); if (lowerOrdering != EQ) return lowerOrdering.toInt(); if (upper == null && that.upper != null) return 1; if (upper != null && that.upper == null) return -1; return (upper == null ? EQ : compare(upper, that.upper)).toInt(); } /** * Creates an {@code Interval} from a {@code String}. Valid strings are in one of these four forms: * {@code "(-Infinity, Infinity)"}, {@code "(-Infinity, " + q + "]"}, * {@code "[" + p + ", Infinity)"}, or {@code "[" + p + ", " + q + "]"}, where {@code p} and {@code q} are valid * inputs to {@link mho.qbar.objects.Rational#read}, and {@code p}≤{@code q} * * <ul> * <li>{@code s} cannot be null.</li> * <li>The result may be any {@code Optional<Interval>}, or null.</li> * </ul> * * @param s a string representation of a {@code Rational}. * @return the wrapped {@code Rational} represented by {@code s}, or {@code empty} if {@code s} is invalid. */ public static @NotNull Optional<Interval> read(@NotNull String s) { if (s.isEmpty()) return Optional.empty(); char left = s.charAt(0); if (left != '[' && left != '(') return Optional.empty(); char right = s.charAt(s.length() - 1); if (right != ']' && right != ')') return Optional.empty(); int commaIndex = s.indexOf(", "); if (commaIndex == -1) return Optional.empty(); String leftString = s.substring(1, commaIndex); String rightString = s.substring(commaIndex + 2, s.length() - 1); Rational lower = null; if (left == '(') { if (!leftString.equals("-Infinity")) return Optional.empty(); } else { Optional<Rational> optLower = Rational.read(leftString); if (!optLower.isPresent()) return Optional.empty(); lower = optLower.get(); } Rational upper = null; if (right == ')') { if (!rightString.equals("Infinity")) return Optional.empty(); } else { Optional<Rational> optUpper = Rational.read(rightString); if (!optUpper.isPresent()) return Optional.empty(); upper = optUpper.get(); } if (lower == null && upper == null) return Optional.of(ALL); if (lower == null) return Optional.of(lessThanOrEqualTo(upper)); if (upper == null) return Optional.of(greaterThanOrEqualTo(lower)); return le(lower, upper) ? Optional.of(of(lower, upper)) : Optional.<Interval>empty(); } /** * Finds the first occurrence of an {@code Interval} in a {@code String}. Returns the {@code Interval} and the * index at which it was found. Returns an empty {@code Optional} if no {@code Interval} is found. Only * {@code String}s which could have been emitted by {@link Interval#toString} are recognized. The longest possible * {@code Interval} is parsed. * * <ul> * <li>{@code s} must be non-null.</li> * <li>The result is non-null. If it is non-empty, then neither of the {@code Pair}'s components is null, and the * second component is non-negative.</li> * </ul> * * @param s the input {@code String} * @return the first {@code Interval} found in {@code s}, and the index at which it was found */ public static @NotNull Optional<Pair<Interval, Integer>> findIn(@NotNull String s) { return Readers.genericFindIn(Interval::read, " (),-/0123456789I[]finty", s); } /** * Creates a string representation of {@code this}. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>The result is a string in on of four forms: {@code "(-Infinity, Infinity)"}, * {@code "(-Infinity, " + q.toString() + "]"}, {@code "[" + p.toString() + ", Infinity)"}, or * {@code "[" + p.toString() + ", " + q.toString() + "]"}, where {@code p} and {@code q} are {@code Rational}s * such that {@code p} is less than or equal to {@code q}.</li> * </ul> * * @return a string representation of {@code this}. */ public @NotNull String toString() { return (lower == null ? "(-Infinity" : "[" + lower) + ", " + (upper == null ? "Infinity)" : upper + "]"); } }
added invert and invertHull docs
src/main/java/mho/qbar/objects/Interval.java
added invert and invertHull docs
<ide><path>rc/main/java/mho/qbar/objects/Interval.java <ide> } <ide> } <ide> <add> /** <add> * Returns the closure of the image of {@code this} under multiplicative inversion. In general this is not one <add> * {@code Interval}, so this method returns a list of disjoint {@code Interval}s whose union is the closure of the <add> * image. <add> * <add> * <ul> <add> * <li>{@code this} may be any {@code Interval}.</li> <add> * <li> <add> * The result is one of the following: <add> * <li> <add> * <ul>[]</ul> <add> * <ul>[(–∞, ∞)]</ul> <add> * <ul>[(–∞, q]] where q≤0</ul> <add> * <ul>[[p, ∞)] where p≥0</ul> <add> * <ul>[[p, q]] where p≠q, p and q both positive</ul> <add> * <ul>[[p, q]] where p≠q, p and q both negative</ul> <add> * <ul>[[p, p]] where p≠0</ul> <add> * <ul>[(–∞, q], [0, ∞)] where q<0</ul> <add> * <ul>[(–∞, 0], [p, ∞)] where p>0</ul> <add> * <ul>[(–∞, q], [p, ∞)] where q<0, p>0</ul> <add> * <ul></ul> <add> * </li> <add> * </li> <add> * </ul> <add> * <add> * @return 1/{@code this} <add> */ <ide> public @NotNull List<Interval> invert() { <ide> List<Interval> intervals = new ArrayList<>(); <ide> if (lower == null && upper == null) { <ide> } <ide> } else if (lower == Rational.ZERO) { <ide> if (upper != Rational.ZERO) { <del> intervals.add(new Interval(upper.invert(), Rational.ZERO)); <add> intervals.add(new Interval(upper.invert(), null)); <ide> } <ide> } else if (lower.signum() == 1) { <ide> intervals.add(new Interval(upper.invert(), lower.invert())); <ide> return intervals; <ide> } <ide> <add> /** <add> * Returns the smallest interval a such that if x∈{@code this}, 1/x∈a. <add> * <add> * <ul> <add> * <li>{@code this} cannot be [0, 0].</li> <add> * <li> <add> * The result is one of the following: <add> * <li> <add> * <ul>(–∞, ∞)</ul> <add> * <ul>(–∞, q] where q≤0</ul> <add> * <ul>[p, ∞) where p≥0</ul> <add> * <ul>[p, q] where p≠q, p and q both positive</ul> <add> * <ul>[p, q] where p≠q, p and q both negative</ul> <add> * <ul>[p, p] where p≠0</ul> <add> * </li> <add> * </li> <add> * </ul> <add> * <add> * @return Conv(1/{@code this}) <add> */ <ide> public @NotNull Interval invertHull() { <ide> return convexHull(invert()); <ide> } <ide> } <ide> } <ide> <del> public @NotNull Interval divide(@NotNull int that) { <add> public @NotNull Interval divide(int that) { <ide> if (that == 1) return this; <ide> if (that > 0) { <ide> return new Interval(
Java
bsd-2-clause
2ee80d6c16f08d790b7230707f7007f4ff5f0904
0
KronosDesign/runelite,runelite/runelite,Sethtroll/runelite,Sethtroll/runelite,KronosDesign/runelite,abelbriggs1/runelite,l2-/runelite,runelite/runelite,runelite/runelite,abelbriggs1/runelite,abelbriggs1/runelite,l2-/runelite
/* * Copyright (c) 2018, SomeoneWithAnInternetConnection * Copyright (c) 2018, Psikoi <https://github.com/psikoi> * 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. * * 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 OWNER 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 net.runelite.client.plugins.grandexchange; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.io.IOException; import javax.annotation.Nullable; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import lombok.extern.slf4j.Slf4j; import net.runelite.api.GrandExchangeOffer; import net.runelite.api.GrandExchangeOfferState; import static net.runelite.api.GrandExchangeOfferState.CANCELLED_BUY; import static net.runelite.api.GrandExchangeOfferState.CANCELLED_SELL; import static net.runelite.api.GrandExchangeOfferState.EMPTY; import net.runelite.api.ItemComposition; import net.runelite.client.ui.ColorScheme; import net.runelite.client.ui.FontManager; import net.runelite.client.ui.components.ThinProgressBar; import net.runelite.client.util.StackFormatter; import net.runelite.client.util.SwingUtil; @Slf4j public class GrandExchangeOfferSlot extends JPanel { private static final String FACE_CARD = "FACE_CARD"; private static final String DETAILS_CARD = "DETAILS_CARD"; private static final ImageIcon RIGHT_ARROW_ICON; private static final ImageIcon LEFT_ARROW_ICON; private final JPanel container = new JPanel(); private final CardLayout cardLayout = new CardLayout(); private final JLabel itemIcon = new JLabel(); private final JLabel itemName = new JLabel(); private final JLabel offerInfo = new JLabel(); private final JLabel switchFaceViewIcon = new JLabel(); private final JLabel itemPrice = new JLabel(); private final JLabel offerSpent = new JLabel(); private final JLabel switchDetailsViewIcon = new JLabel(); private final ThinProgressBar progressBar = new ThinProgressBar(); private boolean showingFace = true; static { try { synchronized (ImageIO.class) { RIGHT_ARROW_ICON = new ImageIcon(ImageIO.read(GrandExchangeOfferSlot.class.getResourceAsStream("arrow_right.png"))); LEFT_ARROW_ICON = new ImageIcon(ImageIO.read(GrandExchangeOfferSlot.class.getResourceAsStream("arrow_left.png"))); } } catch (IOException e) { throw new RuntimeException(e); } } /** * This (sub)panel is used for each GE slot displayed * in the sidebar */ GrandExchangeOfferSlot() { buildPanel(); } private void buildPanel() { setLayout(new BorderLayout()); setBackground(ColorScheme.DARK_GRAY_COLOR); setBorder(new EmptyBorder(7, 0, 0, 0)); final MouseListener ml = new MouseAdapter() { @Override public void mousePressed(MouseEvent mouseEvent) { super.mousePressed(mouseEvent); switchPanel(); } @Override public void mouseEntered(MouseEvent mouseEvent) { super.mouseEntered(mouseEvent); container.setBackground(ColorScheme.MEDIUM_GRAY_COLOR.brighter()); } @Override public void mouseExited(MouseEvent mouseEvent) { super.mouseExited(mouseEvent); container.setBackground(ColorScheme.MEDIUM_GRAY_COLOR); } }; container.setLayout(cardLayout); container.setBackground(ColorScheme.MEDIUM_GRAY_COLOR); JPanel faceCard = new JPanel(); faceCard.setBackground(ColorScheme.MEDIUM_GRAY_COLOR); faceCard.setLayout(new BorderLayout()); faceCard.addMouseListener(ml); itemIcon.setVerticalAlignment(JLabel.CENTER); itemIcon.setHorizontalAlignment(JLabel.CENTER); itemIcon.setPreferredSize(new Dimension(45, 45)); itemName.setForeground(Color.WHITE); itemName.setVerticalAlignment(JLabel.BOTTOM); itemName.setFont(FontManager.getRunescapeSmallFont()); offerInfo.setForeground(ColorScheme.LIGHT_GRAY_COLOR); offerInfo.setVerticalAlignment(JLabel.TOP); offerInfo.setFont(FontManager.getRunescapeSmallFont()); switchFaceViewIcon.setIcon(RIGHT_ARROW_ICON); switchFaceViewIcon.setVerticalAlignment(JLabel.CENTER); switchFaceViewIcon.setHorizontalAlignment(JLabel.CENTER); switchFaceViewIcon.setPreferredSize(new Dimension(30, 45)); JPanel offerFaceDetails = new JPanel(); offerFaceDetails.setBackground(ColorScheme.MEDIUM_GRAY_COLOR); offerFaceDetails.setLayout(new GridLayout(2, 1, 0, 2)); offerFaceDetails.add(itemName); offerFaceDetails.add(offerInfo); faceCard.add(offerFaceDetails, BorderLayout.CENTER); faceCard.add(itemIcon, BorderLayout.WEST); faceCard.add(switchFaceViewIcon, BorderLayout.EAST); JPanel detailsCard = new JPanel(); detailsCard.setBackground(ColorScheme.MEDIUM_GRAY_COLOR); detailsCard.setLayout(new BorderLayout()); detailsCard.setBorder(new EmptyBorder(0, 15, 0, 0)); detailsCard.addMouseListener(ml); itemPrice.setForeground(Color.WHITE); itemPrice.setVerticalAlignment(JLabel.BOTTOM); itemPrice.setFont(FontManager.getRunescapeSmallFont()); offerSpent.setForeground(Color.WHITE); offerSpent.setVerticalAlignment(JLabel.TOP); offerSpent.setFont(FontManager.getRunescapeSmallFont()); switchDetailsViewIcon.setIcon(LEFT_ARROW_ICON); switchDetailsViewIcon.setVerticalAlignment(JLabel.CENTER); switchDetailsViewIcon.setHorizontalAlignment(JLabel.CENTER); switchDetailsViewIcon.setPreferredSize(new Dimension(30, 45)); JPanel offerDetails = new JPanel(); offerDetails.setBackground(ColorScheme.MEDIUM_GRAY_COLOR); offerDetails.setLayout(new GridLayout(2, 1)); offerDetails.add(itemPrice); offerDetails.add(offerSpent); detailsCard.add(offerDetails, BorderLayout.CENTER); detailsCard.add(switchDetailsViewIcon, BorderLayout.EAST); container.add(faceCard, FACE_CARD); container.add(detailsCard, DETAILS_CARD); cardLayout.show(container, FACE_CARD); add(container, BorderLayout.CENTER); add(progressBar, BorderLayout.SOUTH); } void updateOffer(ItemComposition offerItem, BufferedImage itemImage, @Nullable GrandExchangeOffer newOffer) { if (newOffer == null || newOffer.getState() == EMPTY) { return; } else { cardLayout.show(container, FACE_CARD); itemName.setText(offerItem.getName()); itemIcon.setIcon(new ImageIcon(itemImage)); boolean buying = newOffer.getState() == GrandExchangeOfferState.BOUGHT || newOffer.getState() == GrandExchangeOfferState.BUYING || newOffer.getState() == GrandExchangeOfferState.CANCELLED_BUY; String offerState = (buying ? "Bought " : "Sold ") + StackFormatter.quantityToRSDecimalStack(newOffer.getQuantitySold()) + " / " + StackFormatter.quantityToRSDecimalStack(newOffer.getTotalQuantity()); offerInfo.setText(offerState); itemPrice.setText(htmlLabel("Price each: ", StackFormatter.formatNumber(newOffer.getPrice()))); String action = buying ? "Spent: " : "Received: "; offerSpent.setText(htmlLabel(action, StackFormatter.formatNumber(newOffer.getSpent()) + " / " + StackFormatter.formatNumber(newOffer.getPrice() * newOffer.getTotalQuantity()))); progressBar.setForeground(getProgressColor(newOffer)); progressBar.setMaximumValue(newOffer.getTotalQuantity()); progressBar.setValue(newOffer.getQuantitySold()); progressBar.update(); /* Couldn't set the tooltip for the container panel as the children override it, so I'm setting * the tooltips on the children instead. */ for (Component c : container.getComponents()) { if (c instanceof JPanel) { JPanel panel = (JPanel) c; panel.setToolTipText(htmlTooltip(((int) progressBar.getPercentage()) + "%")); } } } revalidate(); repaint(); } private String htmlTooltip(String value) { return "<html><body style = 'color:" + SwingUtil.toHexColor(ColorScheme.LIGHT_GRAY_COLOR) + "'>Progress: <span style = 'color:white'>" + value + "</span></body></html>"; } private String htmlLabel(String key, String value) { return "<html><body style = 'color:white'>" + key + "<span style = 'color:" + SwingUtil.toHexColor(ColorScheme.LIGHT_GRAY_COLOR) + "'>" + value + "</span></body></html>"; } private void switchPanel() { this.showingFace = !this.showingFace; cardLayout.show(container, showingFace ? FACE_CARD : DETAILS_CARD); } private Color getProgressColor(GrandExchangeOffer offer) { if (offer.getState() == CANCELLED_BUY || offer.getState() == CANCELLED_SELL) { return ColorScheme.PROGRESS_ERROR_COLOR; } if (offer.getQuantitySold() == offer.getTotalQuantity()) { return ColorScheme.PROGRESS_COMPLETE_COLOR; } return ColorScheme.PROGRESS_INPROGRESS_COLOR; } }
runelite-client/src/main/java/net/runelite/client/plugins/grandexchange/GrandExchangeOfferSlot.java
/* * Copyright (c) 2018, SomeoneWithAnInternetConnection * Copyright (c) 2018, Psikoi <https://github.com/psikoi> * 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. * * 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 OWNER 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 net.runelite.client.plugins.grandexchange; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.io.IOException; import javax.annotation.Nullable; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import lombok.extern.slf4j.Slf4j; import net.runelite.api.GrandExchangeOffer; import net.runelite.api.GrandExchangeOfferState; import static net.runelite.api.GrandExchangeOfferState.CANCELLED_BUY; import static net.runelite.api.GrandExchangeOfferState.CANCELLED_SELL; import static net.runelite.api.GrandExchangeOfferState.EMPTY; import net.runelite.api.ItemComposition; import net.runelite.client.ui.ColorScheme; import net.runelite.client.ui.FontManager; import net.runelite.client.ui.components.ThinProgressBar; import net.runelite.client.util.StackFormatter; import net.runelite.client.util.SwingUtil; @Slf4j public class GrandExchangeOfferSlot extends JPanel { private static final String FACE_CARD = "FACE_CARD"; private static final String DETAILS_CARD = "DETAILS_CARD"; private static final ImageIcon RIGHT_ARROW_ICON; private static final ImageIcon LEFT_ARROW_ICON; private final JPanel container = new JPanel(); private final CardLayout cardLayout = new CardLayout(); private final JLabel itemIcon = new JLabel(); private final JLabel itemName = new JLabel(); private final JLabel offerInfo = new JLabel(); private final JLabel switchFaceViewIcon = new JLabel(); private final JLabel itemPrice = new JLabel(); private final JLabel offerSpent = new JLabel(); private final JLabel switchDetailsViewIcon = new JLabel(); private final ThinProgressBar progressBar = new ThinProgressBar(); private boolean showingFace = true; static { try { synchronized (ImageIO.class) { RIGHT_ARROW_ICON = new ImageIcon(ImageIO.read(GrandExchangeOfferSlot.class.getResourceAsStream("arrow_right.png"))); LEFT_ARROW_ICON = new ImageIcon(ImageIO.read(GrandExchangeOfferSlot.class.getResourceAsStream("arrow_left.png"))); } } catch (IOException e) { throw new RuntimeException(e); } } /** * This (sub)panel is used for each GE slot displayed * in the sidebar */ GrandExchangeOfferSlot() { buildPanel(); } private void buildPanel() { setLayout(new BorderLayout()); setBackground(ColorScheme.DARK_GRAY_COLOR); setBorder(new EmptyBorder(7, 0, 0, 0)); final MouseListener ml = new MouseAdapter() { @Override public void mousePressed(MouseEvent mouseEvent) { super.mousePressed(mouseEvent); switchPanel(); } @Override public void mouseEntered(MouseEvent mouseEvent) { super.mouseEntered(mouseEvent); container.setBackground(ColorScheme.MEDIUM_GRAY_COLOR.brighter()); } @Override public void mouseExited(MouseEvent mouseEvent) { super.mouseExited(mouseEvent); container.setBackground(ColorScheme.MEDIUM_GRAY_COLOR); } }; container.setLayout(cardLayout); container.setBackground(ColorScheme.MEDIUM_GRAY_COLOR); JPanel faceCard = new JPanel(); faceCard.setBackground(ColorScheme.MEDIUM_GRAY_COLOR); faceCard.setLayout(new BorderLayout()); faceCard.addMouseListener(ml); itemIcon.setVerticalAlignment(JLabel.CENTER); itemIcon.setHorizontalAlignment(JLabel.CENTER); itemIcon.setPreferredSize(new Dimension(45, 45)); itemName.setForeground(Color.WHITE); itemName.setVerticalAlignment(JLabel.BOTTOM); itemName.setFont(FontManager.getRunescapeSmallFont()); offerInfo.setForeground(ColorScheme.LIGHT_GRAY_COLOR); offerInfo.setVerticalAlignment(JLabel.TOP); offerInfo.setFont(FontManager.getRunescapeSmallFont()); switchFaceViewIcon.setIcon(RIGHT_ARROW_ICON); switchFaceViewIcon.setVerticalAlignment(JLabel.CENTER); switchFaceViewIcon.setHorizontalAlignment(JLabel.CENTER); switchFaceViewIcon.setPreferredSize(new Dimension(30, 45)); JPanel offerFaceDetails = new JPanel(); offerFaceDetails.setBackground(ColorScheme.MEDIUM_GRAY_COLOR); offerFaceDetails.setLayout(new GridLayout(2, 1, 0, 2)); offerFaceDetails.add(itemName); offerFaceDetails.add(offerInfo); faceCard.add(offerFaceDetails, BorderLayout.CENTER); faceCard.add(itemIcon, BorderLayout.WEST); faceCard.add(switchFaceViewIcon, BorderLayout.EAST); JPanel detailsCard = new JPanel(); detailsCard.setBackground(ColorScheme.MEDIUM_GRAY_COLOR); detailsCard.setLayout(new BorderLayout()); detailsCard.setBorder(new EmptyBorder(0, 15, 0, 0)); detailsCard.addMouseListener(ml); itemPrice.setForeground(Color.WHITE); itemPrice.setVerticalAlignment(JLabel.BOTTOM); itemPrice.setFont(FontManager.getRunescapeSmallFont()); offerSpent.setForeground(Color.WHITE); offerSpent.setVerticalAlignment(JLabel.TOP); offerSpent.setFont(FontManager.getRunescapeSmallFont()); switchDetailsViewIcon.setIcon(LEFT_ARROW_ICON); switchDetailsViewIcon.setVerticalAlignment(JLabel.CENTER); switchDetailsViewIcon.setHorizontalAlignment(JLabel.CENTER); switchDetailsViewIcon.setPreferredSize(new Dimension(30, 45)); JPanel offerDetails = new JPanel(); offerDetails.setBackground(ColorScheme.MEDIUM_GRAY_COLOR); offerDetails.setLayout(new GridLayout(2, 1)); offerDetails.add(itemPrice); offerDetails.add(offerSpent); detailsCard.add(offerDetails, BorderLayout.CENTER); detailsCard.add(switchDetailsViewIcon, BorderLayout.EAST); container.add(faceCard, FACE_CARD); container.add(detailsCard, DETAILS_CARD); cardLayout.show(container, FACE_CARD); add(container, BorderLayout.CENTER); add(progressBar, BorderLayout.SOUTH); } void updateOffer(ItemComposition offerItem, BufferedImage itemImage, @Nullable GrandExchangeOffer newOffer) { if (newOffer == null || newOffer.getState() == EMPTY) { return; } else { cardLayout.show(container, FACE_CARD); itemName.setText(offerItem.getName()); itemIcon.setIcon(new ImageIcon(itemImage)); boolean buying = newOffer.getState() == GrandExchangeOfferState.BOUGHT || newOffer.getState() == GrandExchangeOfferState.BUYING || newOffer.getState() == GrandExchangeOfferState.CANCELLED_BUY; String offerState = (buying ? "Bought " : "Sold ") + StackFormatter.quantityToRSDecimalStack(newOffer.getQuantitySold()) + " / " + StackFormatter.quantityToRSDecimalStack(newOffer.getTotalQuantity()); offerInfo.setText(offerState); itemPrice.setText(htmlLabel("Price each: ", newOffer.getPrice() + "")); String action = buying ? "Spent: " : "Received: "; offerSpent.setText(htmlLabel(action, StackFormatter.formatNumber(newOffer.getSpent()) + " / " + StackFormatter.formatNumber(newOffer.getPrice() * newOffer.getTotalQuantity()))); progressBar.setForeground(getProgressColor(newOffer)); progressBar.setMaximumValue(newOffer.getTotalQuantity()); progressBar.setValue(newOffer.getQuantitySold()); progressBar.update(); /* Couldn't set the tooltip for the container panel as the children override it, so I'm setting * the tooltips on the children instead. */ for (Component c : container.getComponents()) { if (c instanceof JPanel) { JPanel panel = (JPanel) c; panel.setToolTipText(htmlTooltip(((int) progressBar.getPercentage()) + "%")); } } } revalidate(); repaint(); } private String htmlTooltip(String value) { return "<html><body style = 'color:" + SwingUtil.toHexColor(ColorScheme.LIGHT_GRAY_COLOR) + "'>Progress: <span style = 'color:white'>" + value + "</span></body></html>"; } private String htmlLabel(String key, String value) { return "<html><body style = 'color:white'>" + key + "<span style = 'color:" + SwingUtil.toHexColor(ColorScheme.LIGHT_GRAY_COLOR) + "'>" + value + "</span></body></html>"; } private void switchPanel() { this.showingFace = !this.showingFace; cardLayout.show(container, showingFace ? FACE_CARD : DETAILS_CARD); } private Color getProgressColor(GrandExchangeOffer offer) { if (offer.getState() == CANCELLED_BUY || offer.getState() == CANCELLED_SELL) { return ColorScheme.PROGRESS_ERROR_COLOR; } if (offer.getQuantitySold() == offer.getTotalQuantity()) { return ColorScheme.PROGRESS_COMPLETE_COLOR; } return ColorScheme.PROGRESS_INPROGRESS_COLOR; } }
grandexchange: Format 'Price each' value for items in additional information layout
runelite-client/src/main/java/net/runelite/client/plugins/grandexchange/GrandExchangeOfferSlot.java
grandexchange: Format 'Price each' value for items in additional information layout
<ide><path>unelite-client/src/main/java/net/runelite/client/plugins/grandexchange/GrandExchangeOfferSlot.java <ide> <ide> offerInfo.setText(offerState); <ide> <del> itemPrice.setText(htmlLabel("Price each: ", newOffer.getPrice() + "")); <add> itemPrice.setText(htmlLabel("Price each: ", StackFormatter.formatNumber(newOffer.getPrice()))); <ide> <ide> String action = buying ? "Spent: " : "Received: "; <ide>
Java
apache-2.0
772bb5d6f25035f1e912053685e36a18ed4b6591
0
tmurakami/dexopener,tmurakami/dexopener
package com.github.tmurakami.dexopener; import android.app.Instrumentation; import android.content.Context; import android.content.pm.ApplicationInfo; import android.support.annotation.NonNull; /** * This is an object that provides the ability to mock final classes and methods. */ @SuppressWarnings("WeakerAccess") public abstract class DexOpener { DexOpener() { } /** * Provides the ability to mock final classes and methods. * <p> * This is equivalent to the following code: * <pre>{@code * Context context = instrumentation.getTargetContext(); * builder(context).build().installTo(context.getClassLoader()); * }</pre> * * @param instrumentation the instrumentation * @see #builder(Context) * @see #installTo(ClassLoader) * @see Builder#build() */ public static void install(@NonNull Instrumentation instrumentation) { Context context = instrumentation.getTargetContext(); if (context == null) { throw new IllegalArgumentException("'instrumentation' has not been initialized yet"); } builder(context).build().installTo(context.getClassLoader()); } /** * Provides the ability to mock final classes and methods. * After calling this method, you can mock classes loaded by the given class loader. * <p> * Note that final classes loaded before calling this cannot be mocked. * * @param classLoader the class loader */ public abstract void installTo(@NonNull ClassLoader classLoader); /** * Instantiates a new {@link Builder} instance. * <p> * By default, mockable final classes and methods are restricted under the package obtained by * {@link Context#getPackageName()}. * To change this restriction, use {@link Builder#classNameFilter(ClassNameFilter)} or * {@link Builder#openIf(ClassNameFilter)}. * * @param context the context * @return the {@link Builder} */ @NonNull public static Builder builder(@NonNull Context context) { return new Builder(context.getApplicationInfo(), new DefaultClassNameFilter(context.getPackageName() + '.')); } /** * The builder for {@link DexOpener}. */ public static final class Builder { private final ApplicationInfo applicationInfo; private ClassNameFilter classNameFilter; private Builder(ApplicationInfo applicationInfo, ClassNameFilter classNameFilter) { this.applicationInfo = applicationInfo; this.classNameFilter = classNameFilter; } /** * Sets a {@link ClassNameFilter}. * This is an alias of {@link #classNameFilter(ClassNameFilter)}. Using this makes code more * readable with lambda expressions, as in the following code: * <pre>{@code * openIf(name -> name.startsWith("package.you.want.to.mock.")) * }</pre> * * @param filter the {@link ClassNameFilter} * @return this builder */ @NonNull public Builder openIf(@NonNull ClassNameFilter filter) { return classNameFilter(filter); } /** * Sets a {@link ClassNameFilter}. * * @param filter the {@link ClassNameFilter} * @return this builder */ @NonNull public Builder classNameFilter(@NonNull ClassNameFilter filter) { classNameFilter = filter; return this; } /** * Instantiates a new {@link DexOpener} instance. * * @return the {@link DexOpener} */ @NonNull public DexOpener build() { return new DexOpenerImpl(applicationInfo, new ClassNameFilterWrapper(classNameFilter), DexFileLoader.INSTANCE, DexClassFileFactory.INSTANCE); } } private static class DefaultClassNameFilter implements ClassNameFilter { private final String packagePrefix; private DefaultClassNameFilter(String packagePrefix) { this.packagePrefix = packagePrefix; } @Override public boolean accept(@NonNull String className) { return className.startsWith(packagePrefix); } } }
dexopener/src/main/java/com/github/tmurakami/dexopener/DexOpener.java
package com.github.tmurakami.dexopener; import android.app.Instrumentation; import android.content.Context; import android.content.pm.ApplicationInfo; import android.support.annotation.NonNull; /** * This is an object that provides the ability to mock final classes and methods. */ @SuppressWarnings("WeakerAccess") public abstract class DexOpener { DexOpener() { } /** * Provides the ability to mock final classes and methods. * <p> * This is equivalent to the following code: * <pre>{@code * Context context = instrumentation.getTargetContext(); * builder(context).build().installTo(context.getClassLoader()); * }</pre> * * @param instrumentation the instrumentation * @see #builder(Context) * @see #installTo(ClassLoader) * @see Builder#build() */ public static void install(@NonNull Instrumentation instrumentation) { Context context = instrumentation.getTargetContext(); if (context == null) { throw new IllegalArgumentException("'instrumentation' has not been initialized yet"); } builder(context).build().installTo(context.getClassLoader()); } /** * Provides the ability to mock final classes and methods. * After calling this method, you can mock classes loaded by the given class loader. * <p> * Note that final classes loaded before calling this cannot be mocked. * * @param classLoader the class loader * @deprecated use {@link #installTo(ClassLoader)} instead */ @Deprecated public final void install(@NonNull ClassLoader classLoader) { installTo(classLoader); } /** * Provides the ability to mock final classes and methods. * After calling this method, you can mock classes loaded by the given class loader. * <p> * Note that final classes loaded before calling this cannot be mocked. * * @param classLoader the class loader */ public abstract void installTo(@NonNull ClassLoader classLoader); /** * Instantiates a new {@link Builder} instance. * <p> * By default, mockable final classes and methods are restricted under the package obtained by * {@link Context#getPackageName()}. * To change this restriction, use {@link Builder#classNameFilter(ClassNameFilter)} or * {@link Builder#openIf(ClassNameFilter)}. * * @param context the context * @return the {@link Builder} */ @NonNull public static Builder builder(@NonNull Context context) { return new Builder(context.getApplicationInfo(), new DefaultClassNameFilter(context.getPackageName() + '.')); } /** * The builder for {@link DexOpener}. */ public static final class Builder { private final ApplicationInfo applicationInfo; private ClassNameFilter classNameFilter; private Builder(ApplicationInfo applicationInfo, ClassNameFilter classNameFilter) { this.applicationInfo = applicationInfo; this.classNameFilter = classNameFilter; } /** * Throws an {@link UnsupportedOperationException}. * * @throws UnsupportedOperationException this method is deprecated * @deprecated use {@link #openIf(ClassNameFilter)} or {@link #classNameFilter(ClassNameFilter)} instead. */ @Deprecated @NonNull public Builder classNameFilters(@SuppressWarnings("unused") @NonNull ClassNameFilter... filters) throws UnsupportedOperationException { throw new UnsupportedOperationException( "Use openIf(ClassNameFilter) or classNameFilter(ClassNameFilter) instead"); } /** * Sets a {@link ClassNameFilter}. * This is an alias of {@link #classNameFilter(ClassNameFilter)}. Using this makes code more * readable with lambda expressions, as in the following code: * <pre>{@code * openIf(name -> name.startsWith("package.you.want.to.mock.")) * }</pre> * * @param filter the {@link ClassNameFilter} * @return this builder */ @NonNull public Builder openIf(@NonNull ClassNameFilter filter) { return classNameFilter(filter); } /** * Sets a {@link ClassNameFilter}. * * @param filter the {@link ClassNameFilter} * @return this builder */ @NonNull public Builder classNameFilter(@NonNull ClassNameFilter filter) { classNameFilter = filter; return this; } /** * Instantiates a new {@link DexOpener} instance. * * @return the {@link DexOpener} */ @NonNull public DexOpener build() { return new DexOpenerImpl(applicationInfo, new ClassNameFilterWrapper(classNameFilter), DexFileLoader.INSTANCE, DexClassFileFactory.INSTANCE); } } private static class DefaultClassNameFilter implements ClassNameFilter { private final String packagePrefix; private DefaultClassNameFilter(String packagePrefix) { this.packagePrefix = packagePrefix; } @Override public boolean accept(@NonNull String className) { return className.startsWith(packagePrefix); } } }
Remove deprecated methods
dexopener/src/main/java/com/github/tmurakami/dexopener/DexOpener.java
Remove deprecated methods
<ide><path>exopener/src/main/java/com/github/tmurakami/dexopener/DexOpener.java <ide> * Note that final classes loaded before calling this cannot be mocked. <ide> * <ide> * @param classLoader the class loader <del> * @deprecated use {@link #installTo(ClassLoader)} instead <del> */ <del> @Deprecated <del> public final void install(@NonNull ClassLoader classLoader) { <del> installTo(classLoader); <del> } <del> <del> /** <del> * Provides the ability to mock final classes and methods. <del> * After calling this method, you can mock classes loaded by the given class loader. <del> * <p> <del> * Note that final classes loaded before calling this cannot be mocked. <del> * <del> * @param classLoader the class loader <ide> */ <ide> public abstract void installTo(@NonNull ClassLoader classLoader); <ide> <ide> private Builder(ApplicationInfo applicationInfo, ClassNameFilter classNameFilter) { <ide> this.applicationInfo = applicationInfo; <ide> this.classNameFilter = classNameFilter; <del> } <del> <del> /** <del> * Throws an {@link UnsupportedOperationException}. <del> * <del> * @throws UnsupportedOperationException this method is deprecated <del> * @deprecated use {@link #openIf(ClassNameFilter)} or {@link #classNameFilter(ClassNameFilter)} instead. <del> */ <del> @Deprecated <del> @NonNull <del> public Builder classNameFilters(@SuppressWarnings("unused") @NonNull ClassNameFilter... filters) <del> throws UnsupportedOperationException { <del> throw new UnsupportedOperationException( <del> "Use openIf(ClassNameFilter) or classNameFilter(ClassNameFilter) instead"); <ide> } <ide> <ide> /**
Java
apache-2.0
304be2a9eed78281d1252e90a08486235ed51448
0
fnouama/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,kdwink/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,ftomassetti/intellij-community,consulo/consulo,lucafavatella/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,ernestp/consulo,blademainer/intellij-community,caot/intellij-community,holmes/intellij-community,adedayo/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,semonte/intellij-community,youdonghai/intellij-community,slisson/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,ernestp/consulo,caot/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,izonder/intellij-community,adedayo/intellij-community,holmes/intellij-community,caot/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,kool79/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,kool79/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,holmes/intellij-community,asedunov/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,caot/intellij-community,ryano144/intellij-community,asedunov/intellij-community,vladmm/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,semonte/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,signed/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,signed/intellij-community,ernestp/consulo,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,tmpgit/intellij-community,kool79/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,consulo/consulo,fitermay/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,jagguli/intellij-community,fnouama/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,allotria/intellij-community,vvv1559/intellij-community,consulo/consulo,gnuhub/intellij-community,supersven/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,kool79/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,ryano144/intellij-community,petteyg/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,slisson/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,signed/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,fnouama/intellij-community,xfournet/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,kool79/intellij-community,hurricup/intellij-community,ibinti/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,xfournet/intellij-community,izonder/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,allotria/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,jagguli/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,ernestp/consulo,holmes/intellij-community,caot/intellij-community,adedayo/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,caot/intellij-community,slisson/intellij-community,semonte/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,caot/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,jagguli/intellij-community,supersven/intellij-community,kool79/intellij-community,consulo/consulo,kool79/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,idea4bsd/idea4bsd,supersven/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,hurricup/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,da1z/intellij-community,robovm/robovm-studio,diorcety/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,slisson/intellij-community,apixandru/intellij-community,adedayo/intellij-community,semonte/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,clumsy/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,semonte/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,samthor/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,izonder/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,ibinti/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,da1z/intellij-community,holmes/intellij-community,blademainer/intellij-community,joewalnes/idea-community,robovm/robovm-studio,diorcety/intellij-community,ryano144/intellij-community,semonte/intellij-community,slisson/intellij-community,adedayo/intellij-community,xfournet/intellij-community,retomerz/intellij-community,ryano144/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,jagguli/intellij-community,joewalnes/idea-community,signed/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,joewalnes/idea-community,TangHao1987/intellij-community,signed/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,jagguli/intellij-community,semonte/intellij-community,supersven/intellij-community,holmes/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,signed/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,samthor/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,kool79/intellij-community,jagguli/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,joewalnes/idea-community,diorcety/intellij-community,vvv1559/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,allotria/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,adedayo/intellij-community,retomerz/intellij-community,fitermay/intellij-community,clumsy/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,joewalnes/idea-community,alphafoobar/intellij-community,gnuhub/intellij-community,allotria/intellij-community,ernestp/consulo,akosyakov/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,joewalnes/idea-community,idea4bsd/idea4bsd,diorcety/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,allotria/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,signed/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,da1z/intellij-community,asedunov/intellij-community,holmes/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,robovm/robovm-studio,hurricup/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,apixandru/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,izonder/intellij-community,allotria/intellij-community,nicolargo/intellij-community,semonte/intellij-community,hurricup/intellij-community,slisson/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,da1z/intellij-community,ryano144/intellij-community,robovm/robovm-studio,da1z/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,joewalnes/idea-community,FHannes/intellij-community,ibinti/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,caot/intellij-community,da1z/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,semonte/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,retomerz/intellij-community,ernestp/consulo,alphafoobar/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,dslomov/intellij-community,asedunov/intellij-community,kool79/intellij-community,asedunov/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,dslomov/intellij-community,caot/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,adedayo/intellij-community,FHannes/intellij-community,signed/intellij-community,amith01994/intellij-community,izonder/intellij-community,asedunov/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,samthor/intellij-community,petteyg/intellij-community,joewalnes/idea-community,tmpgit/intellij-community,hurricup/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,FHannes/intellij-community,supersven/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,kdwink/intellij-community,clumsy/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,izonder/intellij-community,da1z/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,consulo/consulo,ol-loginov/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,holmes/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,joewalnes/idea-community,Distrotech/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,signed/intellij-community,holmes/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,FHannes/intellij-community,da1z/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,izonder/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,ibinti/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,robovm/robovm-studio,petteyg/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,caot/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,kdwink/intellij-community,amith01994/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,retomerz/intellij-community,xfournet/intellij-community,jagguli/intellij-community,FHannes/intellij-community,allotria/intellij-community,petteyg/intellij-community,dslomov/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community
/* * Copyright 2000-2007 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 org.jetbrains.groovy.compiler.rt; import groovy.lang.GroovyClassLoader; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.classgen.GeneratorContext; import org.codehaus.groovy.control.*; import org.codehaus.groovy.control.messages.WarningMessage; import org.codehaus.groovy.tools.javac.JavaAwareResolveVisitor; import org.codehaus.groovy.tools.javac.JavaStubGenerator; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.*; /** * @author: Dmitry.Krasilschikov * @date: 16.04.2007 * @noinspection UseOfSystemOutOrSystemErr,CallToPrintStackTrace */ public class GroovycRunner { public static final String PATCHERS = "patchers"; public static final String ENCODING = "encoding"; public static final String OUTPUTPATH = "outputpath"; public static final String FINAL_OUTPUTPATH = "final_outputpath"; public static final String END = "end"; public static final String SRC_FILE = "src_file"; public static final String COMPILED_START = "%%c"; public static final String COMPILED_END = "/%c"; public static final String TO_RECOMPILE_START = "%%rc"; public static final String TO_RECOMPILE_END = "/%rc"; public static final String MESSAGES_START = "%%m"; public static final String MESSAGES_END = "/%m"; public static final String SEPARATOR = "#%%#%%%#%%%%%%%%%#"; //public static final Controller ourController = initController(); public static final String PRESENTABLE_MESSAGE = "@#$%@# Presentable:"; public static final String CLEAR_PRESENTABLE = "$@#$%^ CLEAR_PRESENTABLE"; private GroovycRunner() { } /* private static Controller initController() { if (!"true".equals(System.getProperty("profile.groovy.compiler"))) { return null; } try { return new Controller(); } catch (Exception ex) { ex.printStackTrace(); return null; } } */ public static void main(String[] args) { /* if (ourController != null) { try { ourController.startCPUProfiling(ProfilingModes.CPU_SAMPLING, null); } catch (Exception e) { e.printStackTrace(); } } */ if (args.length != 2) { System.err.println("There is no arguments for groovy compiler"); return; } final boolean forStubs = "stubs".equals(args[0]); final File argsFile = new File(args[1]); if (!argsFile.exists()) { System.err.println("Arguments file for groovy compiler not found"); return; } try { final CompilerConfiguration compilerConfiguration = new CompilerConfiguration(); compilerConfiguration.setOutput(new PrintWriter(System.err)); compilerConfiguration.setWarningLevel(WarningMessage.PARANOIA); final List compilerMessages = new ArrayList(); final List patchers = new ArrayList(); final List srcFiles = new ArrayList(); final Map class2File = new HashMap(); final String[] finalOutput = new String[1]; fillFromArgsFile(argsFile, compilerConfiguration, patchers, compilerMessages, srcFiles, class2File, finalOutput); if (srcFiles.isEmpty()) return; System.out.println(PRESENTABLE_MESSAGE + "Groovy compiler: loading sources..."); final CompilationUnit unit = createCompilationUnit(forStubs, compilerConfiguration, finalOutput[0]); addSources(forStubs, srcFiles, unit); runPatchers(patchers, compilerMessages, class2File, unit); System.out.println(PRESENTABLE_MESSAGE + "Groovyc: compiling..."); final List compiledFiles = GroovyCompilerWrapper.compile(compilerMessages, forStubs, unit); System.out.println(CLEAR_PRESENTABLE); System.out.println(); reportCompiledItems(compiledFiles); System.out.println(); if (compiledFiles.isEmpty()) { reportNotCompiledItems(srcFiles); } int errorCount = 0; for (int i = 0; i < compilerMessages.size(); i++) { CompilerMessage message = (CompilerMessage)compilerMessages.get(i); if (message.getCategory() == CompilerMessage.ERROR) { if (errorCount > 100) { continue; } errorCount++; } printMessage(message); } } catch (Throwable e) { e.printStackTrace(); } /* finally { if (ourController != null) { try { ourController.captureSnapshot(ProfilingModes.SNAPSHOT_WITHOUT_HEAP); ourController.stopCPUProfiling(); } catch (Exception e) { e.printStackTrace(); } } } */ } private static String fillFromArgsFile(File argsFile, CompilerConfiguration compilerConfiguration, List patchers, List compilerMessages, List srcFiles, Map class2File, String[] finalOutput) { String moduleClasspath = null; BufferedReader reader = null; FileInputStream stream; try { stream = new FileInputStream(argsFile); reader = new BufferedReader(new InputStreamReader(stream)); String line; while ((line = reader.readLine()) != null) { if (!SRC_FILE.equals(line)) { break; } final File file = new File(reader.readLine()); srcFiles.add(file); while (!END.equals(line = reader.readLine())) { class2File.put(line, file); } } while (line != null) { if (line.startsWith(PATCHERS)) { String s; while (!END.equals(s = reader.readLine())) { try { final CompilationUnitPatcher patcher = (CompilationUnitPatcher)Class.forName(s).newInstance(); patchers.add(patcher); } catch (InstantiationException e) { addExceptionInfo(compilerMessages, e, "Couldn't instantiate " + s); } catch (IllegalAccessException e) { addExceptionInfo(compilerMessages, e, "Couldn't instantiate " + s); } catch (ClassNotFoundException e) { addExceptionInfo(compilerMessages, e, "Couldn't instantiate " + s); } } } else if (line.startsWith(ENCODING)) { compilerConfiguration.setSourceEncoding(reader.readLine()); } else if (line.startsWith(OUTPUTPATH)) { compilerConfiguration.setTargetDirectory(reader.readLine()); } else if (line.startsWith(FINAL_OUTPUTPATH)) { finalOutput[0] = reader.readLine(); } line = reader.readLine(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { argsFile.delete(); } } return moduleClasspath; } private static void addSources(boolean forStubs, List srcFiles, final CompilationUnit unit) { for (int i = 0; i < srcFiles.size(); i++) { final File file = (File)srcFiles.get(i); if (forStubs && file.getName().endsWith(".java")) { // unit.addSources(new File[]{file}); continue; } unit.addSource(new SourceUnit(file, unit.getConfiguration(), unit.getClassLoader(), unit.getErrorCollector()) { public void parse() throws CompilationFailedException { System.out.println(PRESENTABLE_MESSAGE + "Parsing " + file.getName() + "..."); super.parse(); System.out.println(CLEAR_PRESENTABLE); } }); } } private static void runPatchers(List patchers, List compilerMessages, Map class2File, CompilationUnit unit) { if (!patchers.isEmpty()) { final PsiAwareResourceLoader loader = new PsiAwareResourceLoader(class2File); for (int i = 0; i < patchers.size(); i++) { final CompilationUnitPatcher patcher = (CompilationUnitPatcher)patchers.get(i); try { patcher.patchCompilationUnit(unit, loader); } catch (LinkageError e) { addExceptionInfo(compilerMessages, e, "Couldn't run " + patcher.getClass().getName()); } } } } private static void reportNotCompiledItems(Collection toRecompile) { for (Iterator iterator = toRecompile.iterator(); iterator.hasNext();) { File file = (File)iterator.next(); System.out.print(TO_RECOMPILE_START); System.out.print(file.getAbsolutePath()); System.out.print(TO_RECOMPILE_END); System.out.println(); } } private static void reportCompiledItems(List compiledFiles) { for (int i = 0; i < compiledFiles.size(); i++) { /* * output path * source file * output root directory */ GroovyCompilerWrapper.OutputItem compiledOutputItem = (GroovyCompilerWrapper.OutputItem)compiledFiles.get(i); System.out.print(COMPILED_START); System.out.print(compiledOutputItem.getOutputPath()); System.out.print(SEPARATOR); System.out.print(compiledOutputItem.getSourceFile()); System.out.print(SEPARATOR); System.out.print(compiledOutputItem.getOutputRootDirectory()); System.out.print(COMPILED_END); System.out.println(); } } private static void printMessage(CompilerMessage message) { System.out.print(MESSAGES_START); System.out.print(message.getCategory()); System.out.print(SEPARATOR); System.out.print(message.getMessage()); System.out.print(SEPARATOR); System.out.print(message.getUrl()); System.out.print(SEPARATOR); System.out.print(message.getLineNum()); System.out.print(SEPARATOR); System.out.print(message.getColumnNum()); System.out.print(SEPARATOR); System.out.print(MESSAGES_END); System.out.println(); } private static void addExceptionInfo(List compilerMessages, Throwable e, String message) { final StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); compilerMessages.add(new CompilerMessage(CompilerMessage.WARNING, message + ":\n" + writer, "<exception>", -1, -1)); } private static CompilationUnit createCompilationUnit(final boolean forStubs, final CompilerConfiguration config, final String finalOutput) { config.setClasspath(""); final GroovyClassLoader classLoader = buildClassLoaderFor(config); final GroovyClassLoader transformLoader = new GroovyClassLoader(classLoader) { public Enumeration getResources(String name) throws IOException { if (name.endsWith("org.codehaus.groovy.transform.ASTTransformation")) { final Enumeration resources = super.getResources(name); final ArrayList list = Collections.list(resources); for (Iterator iterator = list.iterator(); iterator.hasNext();) { final URL url = (URL)iterator.next(); try { final String file = new File(new URI(url.toString())).getCanonicalPath(); System.out.println("Enumerated:" + file); if (file.startsWith(finalOutput) || file.startsWith("/" + finalOutput)) { iterator.remove(); } } catch (URISyntaxException ignored) { System.out.println("Invalid URI syntax: " + url.toString()); } } return Collections.enumeration(list); } return super.getResources(name); } }; CompilationUnit unit; try { unit = new CompilationUnit(config, null, classLoader, transformLoader) { public void gotoPhase(int phase) throws CompilationFailedException { super.gotoPhase(phase); if (phase <= Phases.ALL) { System.out.println(PRESENTABLE_MESSAGE + (forStubs ? "Groovy stub generator: " : "Groovy compiler: ") + getPhaseDescription()); } } }; } catch (NoSuchMethodError e) { //groovy 1.5.x unit = new CompilationUnit(config, null, classLoader) { public void gotoPhase(int phase) throws CompilationFailedException { super.gotoPhase(phase); if (phase <= Phases.ALL) { System.out.println(PRESENTABLE_MESSAGE + (forStubs ? "Groovy stub generator: " : "Groovy compiler: ") + getPhaseDescription()); } } }; } if (forStubs) { try { addStubGeneration(config, unit); } catch (LinkageError e) { //older groovy distributions, just don't generate stubs } } return unit; } private static void addStubGeneration(CompilerConfiguration config, final CompilationUnit unit) { //todo reuse JavaStubCompilationUnit in groovy 1.7 boolean useJava5 = config.getTargetBytecode().equals(CompilerConfiguration.POST_JDK5); final JavaStubGenerator stubGenerator = new JavaStubGenerator(config.getTargetDirectory(), false, useJava5); //but JavaStubCompilationUnit doesn't have this... unit.addPhaseOperation(new CompilationUnit.PrimaryClassNodeOperation() { public void call(SourceUnit source, GeneratorContext context, ClassNode node) throws CompilationFailedException { new JavaAwareResolveVisitor(unit).startResolving(node, source); } }, Phases.CONVERSION); unit.addPhaseOperation(new CompilationUnit.PrimaryClassNodeOperation() { public void call(final SourceUnit source, final GeneratorContext context, final ClassNode node) throws CompilationFailedException { final String name = node.getNameWithoutPackage(); if ("package-info".equals(name)) { return; } System.out.println(PRESENTABLE_MESSAGE + "Generating stub for " + name); try { stubGenerator.generateClass(node); } catch (FileNotFoundException e) { source.addException(e); } } },Phases.CONVERSION); } static GroovyClassLoader buildClassLoaderFor(final CompilerConfiguration compilerConfiguration) { return (GroovyClassLoader) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return new GroovyClassLoader(getClass().getClassLoader(), compilerConfiguration) { public Class loadClass(String name, boolean lookupScriptFiles, boolean preferClassOverScript) throws ClassNotFoundException, CompilationFailedException { try { return super.loadClass(name, lookupScriptFiles, preferClassOverScript); } catch (NoClassDefFoundError e) { final String ncdfe = e.getMessage(); throw new RuntimeException("Groovyc error: " + ncdfe + " class not found while resolving class " + name + "; try compiling " + ncdfe + " explicitly", e); } catch (LinkageError e) { throw new RuntimeException("Problem loading class " + name, e); } } }; } }); } }
plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovycRunner.java
/* * Copyright 2000-2007 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 org.jetbrains.groovy.compiler.rt; import groovy.lang.GroovyClassLoader; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.classgen.GeneratorContext; import org.codehaus.groovy.control.*; import org.codehaus.groovy.control.messages.WarningMessage; import org.codehaus.groovy.tools.javac.JavaAwareResolveVisitor; import org.codehaus.groovy.tools.javac.JavaStubGenerator; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.*; /** * @author: Dmitry.Krasilschikov * @date: 16.04.2007 * @noinspection UseOfSystemOutOrSystemErr,CallToPrintStackTrace */ public class GroovycRunner { public static final String PATCHERS = "patchers"; public static final String ENCODING = "encoding"; public static final String OUTPUTPATH = "outputpath"; public static final String FINAL_OUTPUTPATH = "final_outputpath"; public static final String END = "end"; public static final String SRC_FILE = "src_file"; public static final String COMPILED_START = "%%c"; public static final String COMPILED_END = "/%c"; public static final String TO_RECOMPILE_START = "%%rc"; public static final String TO_RECOMPILE_END = "/%rc"; public static final String MESSAGES_START = "%%m"; public static final String MESSAGES_END = "/%m"; public static final String SEPARATOR = "#%%#%%%#%%%%%%%%%#"; //public static final Controller ourController = initController(); public static final String PRESENTABLE_MESSAGE = "@#$%@# Presentable:"; public static final String CLEAR_PRESENTABLE = "$@#$%^ CLEAR_PRESENTABLE"; private GroovycRunner() { } /* private static Controller initController() { if (!"true".equals(System.getProperty("profile.groovy.compiler"))) { return null; } try { return new Controller(); } catch (Exception ex) { ex.printStackTrace(); return null; } } */ public static void main(String[] args) { /* if (ourController != null) { try { ourController.startCPUProfiling(ProfilingModes.CPU_SAMPLING, null); } catch (Exception e) { e.printStackTrace(); } } */ if (args.length != 2) { System.err.println("There is no arguments for groovy compiler"); return; } final boolean forStubs = "stubs".equals(args[0]); final File argsFile = new File(args[1]); if (!argsFile.exists()) { System.err.println("Arguments file for groovy compiler not found"); return; } try { final CompilerConfiguration compilerConfiguration = new CompilerConfiguration(); compilerConfiguration.setOutput(new PrintWriter(System.err)); compilerConfiguration.setWarningLevel(WarningMessage.PARANOIA); final List compilerMessages = new ArrayList(); final List patchers = new ArrayList(); final List srcFiles = new ArrayList(); final Map class2File = new HashMap(); final String[] finalOutput = new String[1]; fillFromArgsFile(argsFile, compilerConfiguration, patchers, compilerMessages, srcFiles, class2File, finalOutput); if (srcFiles.isEmpty()) return; System.out.println(PRESENTABLE_MESSAGE + "Groovy compiler: loading sources..."); final CompilationUnit unit = createCompilationUnit(forStubs, compilerConfiguration, finalOutput[0]); addSources(forStubs, srcFiles, unit); runPatchers(patchers, compilerMessages, class2File, unit); System.out.println(PRESENTABLE_MESSAGE + "Groovyc: compiling..."); final List compiledFiles = GroovyCompilerWrapper.compile(compilerMessages, forStubs, unit); System.out.println(CLEAR_PRESENTABLE); System.out.println(); reportCompiledItems(compiledFiles); System.out.println(); if (compiledFiles.isEmpty()) { reportNotCompiledItems(srcFiles); } int errorCount = 0; for (int i = 0; i < compilerMessages.size(); i++) { CompilerMessage message = (CompilerMessage)compilerMessages.get(i); if (message.getCategory() == CompilerMessage.ERROR) { if (errorCount > 100) { continue; } errorCount++; } printMessage(message); } } catch (Throwable e) { e.printStackTrace(); } /* finally { if (ourController != null) { try { ourController.captureSnapshot(ProfilingModes.SNAPSHOT_WITHOUT_HEAP); ourController.stopCPUProfiling(); } catch (Exception e) { e.printStackTrace(); } } } */ } private static String fillFromArgsFile(File argsFile, CompilerConfiguration compilerConfiguration, List patchers, List compilerMessages, List srcFiles, Map class2File, String[] finalOutput) { String moduleClasspath = null; BufferedReader reader = null; FileInputStream stream; try { stream = new FileInputStream(argsFile); reader = new BufferedReader(new InputStreamReader(stream)); String line; while ((line = reader.readLine()) != null) { if (!SRC_FILE.equals(line)) { break; } final File file = new File(reader.readLine()); srcFiles.add(file); while (!END.equals(line = reader.readLine())) { class2File.put(line, file); } } while (line != null) { if (line.startsWith(PATCHERS)) { String s; while (!END.equals(s = reader.readLine())) { try { final CompilationUnitPatcher patcher = (CompilationUnitPatcher)Class.forName(s).newInstance(); patchers.add(patcher); } catch (InstantiationException e) { addExceptionInfo(compilerMessages, e, "Couldn't instantiate " + s); } catch (IllegalAccessException e) { addExceptionInfo(compilerMessages, e, "Couldn't instantiate " + s); } catch (ClassNotFoundException e) { addExceptionInfo(compilerMessages, e, "Couldn't instantiate " + s); } } } else if (line.startsWith(ENCODING)) { compilerConfiguration.setSourceEncoding(reader.readLine()); } else if (line.startsWith(OUTPUTPATH)) { compilerConfiguration.setTargetDirectory(reader.readLine()); } else if (line.startsWith(FINAL_OUTPUTPATH)) { finalOutput[0] = reader.readLine(); } line = reader.readLine(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { argsFile.delete(); } } return moduleClasspath; } private static void addSources(boolean forStubs, List srcFiles, final CompilationUnit unit) { for (int i = 0; i < srcFiles.size(); i++) { final File file = (File)srcFiles.get(i); if (forStubs && file.getName().endsWith(".java")) { // unit.addSources(new File[]{file}); continue; } unit.addSource(new SourceUnit(file, unit.getConfiguration(), unit.getClassLoader(), unit.getErrorCollector()) { public void parse() throws CompilationFailedException { System.out.println(PRESENTABLE_MESSAGE + "Parsing " + file.getName() + "..."); super.parse(); System.out.println(CLEAR_PRESENTABLE); } }); } } private static void runPatchers(List patchers, List compilerMessages, Map class2File, CompilationUnit unit) { if (!patchers.isEmpty()) { final PsiAwareResourceLoader loader = new PsiAwareResourceLoader(class2File); for (int i = 0; i < patchers.size(); i++) { final CompilationUnitPatcher patcher = (CompilationUnitPatcher)patchers.get(i); try { patcher.patchCompilationUnit(unit, loader); } catch (LinkageError e) { addExceptionInfo(compilerMessages, e, "Couldn't run " + patcher.getClass().getName()); } } } } private static void reportNotCompiledItems(Collection toRecompile) { for (Iterator iterator = toRecompile.iterator(); iterator.hasNext();) { File file = (File)iterator.next(); System.out.print(TO_RECOMPILE_START); System.out.print(file.getAbsolutePath()); System.out.print(TO_RECOMPILE_END); System.out.println(); } } private static void reportCompiledItems(List compiledFiles) { for (int i = 0; i < compiledFiles.size(); i++) { /* * output path * source file * output root directory */ GroovyCompilerWrapper.OutputItem compiledOutputItem = (GroovyCompilerWrapper.OutputItem)compiledFiles.get(i); System.out.print(COMPILED_START); System.out.print(compiledOutputItem.getOutputPath()); System.out.print(SEPARATOR); System.out.print(compiledOutputItem.getSourceFile()); System.out.print(SEPARATOR); System.out.print(compiledOutputItem.getOutputRootDirectory()); System.out.print(COMPILED_END); System.out.println(); } } private static void printMessage(CompilerMessage message) { System.out.print(MESSAGES_START); System.out.print(message.getCategory()); System.out.print(SEPARATOR); System.out.print(message.getMessage()); System.out.print(SEPARATOR); System.out.print(message.getUrl()); System.out.print(SEPARATOR); System.out.print(message.getLineNum()); System.out.print(SEPARATOR); System.out.print(message.getColumnNum()); System.out.print(SEPARATOR); System.out.print(MESSAGES_END); System.out.println(); } private static void addExceptionInfo(List compilerMessages, Throwable e, String message) { final StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); compilerMessages.add(new CompilerMessage(CompilerMessage.WARNING, message + ":\n" + writer, "<exception>", -1, -1)); } private static CompilationUnit createCompilationUnit(final boolean forStubs, final CompilerConfiguration config, final String finalOutput) { config.setClasspath(""); final GroovyClassLoader classLoader = buildClassLoaderFor(config); final GroovyClassLoader transformLoader = new GroovyClassLoader(classLoader) { public Enumeration getResources(String name) throws IOException { if (name.endsWith("org.codehaus.groovy.transform.ASTTransformation")) { final Enumeration resources = super.getResources(name); final ArrayList list = Collections.list(resources); for (Iterator iterator = list.iterator(); iterator.hasNext();) { final URL url = (URL)iterator.next(); if ("file".equals(url.getProtocol())) { try { final String file = new File(new URI(url.toString())).getCanonicalPath(); System.out.println("Enumerated:" + file); if (file.startsWith(finalOutput) || file.startsWith("/" + finalOutput)) { iterator.remove(); } } catch (URISyntaxException ignored) { } } } return Collections.enumeration(list); } return super.getResources(name); } }; CompilationUnit unit; try { unit = new CompilationUnit(config, null, classLoader, transformLoader) { public void gotoPhase(int phase) throws CompilationFailedException { super.gotoPhase(phase); if (phase <= Phases.ALL) { System.out.println(PRESENTABLE_MESSAGE + (forStubs ? "Groovy stub generator: " : "Groovy compiler: ") + getPhaseDescription()); } } }; } catch (NoSuchMethodError e) { //groovy 1.5.x unit = new CompilationUnit(config, null, classLoader) { public void gotoPhase(int phase) throws CompilationFailedException { super.gotoPhase(phase); if (phase <= Phases.ALL) { System.out.println(PRESENTABLE_MESSAGE + (forStubs ? "Groovy stub generator: " : "Groovy compiler: ") + getPhaseDescription()); } } }; } if (forStubs) { try { addStubGeneration(config, unit); } catch (LinkageError e) { //older groovy distributions, just don't generate stubs } } return unit; } private static void addStubGeneration(CompilerConfiguration config, final CompilationUnit unit) { //todo reuse JavaStubCompilationUnit in groovy 1.7 boolean useJava5 = config.getTargetBytecode().equals(CompilerConfiguration.POST_JDK5); final JavaStubGenerator stubGenerator = new JavaStubGenerator(config.getTargetDirectory(), false, useJava5); //but JavaStubCompilationUnit doesn't have this... unit.addPhaseOperation(new CompilationUnit.PrimaryClassNodeOperation() { public void call(SourceUnit source, GeneratorContext context, ClassNode node) throws CompilationFailedException { new JavaAwareResolveVisitor(unit).startResolving(node, source); } }, Phases.CONVERSION); unit.addPhaseOperation(new CompilationUnit.PrimaryClassNodeOperation() { public void call(final SourceUnit source, final GeneratorContext context, final ClassNode node) throws CompilationFailedException { final String name = node.getNameWithoutPackage(); if ("package-info".equals(name)) { return; } System.out.println(PRESENTABLE_MESSAGE + "Generating stub for " + name); try { stubGenerator.generateClass(node); } catch (FileNotFoundException e) { source.addException(e); } } },Phases.CONVERSION); } static GroovyClassLoader buildClassLoaderFor(final CompilerConfiguration compilerConfiguration) { return (GroovyClassLoader) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return new GroovyClassLoader(getClass().getClassLoader(), compilerConfiguration) { public Class loadClass(String name, boolean lookupScriptFiles, boolean preferClassOverScript) throws ClassNotFoundException, CompilationFailedException { try { return super.loadClass(name, lookupScriptFiles, preferClassOverScript); } catch (NoClassDefFoundError e) { final String ncdfe = e.getMessage(); throw new RuntimeException("Groovyc error: " + ncdfe + " class not found while resolving class " + name + "; try compiling " + ncdfe + " explicitly", e); } catch (LinkageError e) { throw new RuntimeException("Problem loading class " + name, e); } } }; } }); } }
more diagnostics
plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovycRunner.java
more diagnostics
<ide><path>lugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovycRunner.java <ide> final ArrayList list = Collections.list(resources); <ide> for (Iterator iterator = list.iterator(); iterator.hasNext();) { <ide> final URL url = (URL)iterator.next(); <del> if ("file".equals(url.getProtocol())) { <del> try { <del> final String file = new File(new URI(url.toString())).getCanonicalPath(); <del> System.out.println("Enumerated:" + file); <del> if (file.startsWith(finalOutput) || file.startsWith("/" + finalOutput)) { <del> iterator.remove(); <del> } <add> try { <add> final String file = new File(new URI(url.toString())).getCanonicalPath(); <add> System.out.println("Enumerated:" + file); <add> if (file.startsWith(finalOutput) || file.startsWith("/" + finalOutput)) { <add> iterator.remove(); <ide> } <del> catch (URISyntaxException ignored) { <del> } <add> } <add> catch (URISyntaxException ignored) { <add> System.out.println("Invalid URI syntax: " + url.toString()); <ide> } <ide> } <ide> return Collections.enumeration(list);
Java
apache-2.0
5a75dc18159e7fb3a445159b479a56877218bcd7
0
zawn/cas,zawn/cas,moghaddam/cas,PetrGasparik/cas,joansmith/cas,yisiqi/cas,joansmith/cas,moghaddam/cas,joansmith/cas,PetrGasparik/cas,yisiqi/cas,moghaddam/cas,PetrGasparik/cas,moghaddam/cas,joansmith/cas,zawn/cas,zhoffice/cas,yisiqi/cas,PetrGasparik/cas,yisiqi/cas,zhoffice/cas,zhoffice/cas,zawn/cas,zhoffice/cas
/* * Licensed to Apereo under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Apereo 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 the following location: * * 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.jasig.cas.adaptors.trusted.web.flow; import org.jasig.cas.CentralAuthenticationServiceImpl; import org.jasig.cas.adaptors.trusted.authentication.handler.support.PrincipalBearingCredentialsAuthenticationHandler; import org.jasig.cas.adaptors.trusted.authentication.principal.PrincipalBearingPrincipalResolver; import org.jasig.cas.authentication.AuthenticationHandler; import org.jasig.cas.authentication.AuthenticationManager; import org.jasig.cas.authentication.PolicyBasedAuthenticationManager; import org.jasig.cas.authentication.principal.DefaultPrincipalFactory; import org.jasig.cas.authentication.principal.PrincipalResolver; import org.jasig.cas.authentication.principal.SimpleWebApplicationServiceImpl; import org.jasig.cas.logout.LogoutManager; import org.jasig.cas.services.ServicesManager; import org.jasig.cas.ticket.registry.DefaultTicketRegistry; import org.jasig.cas.ticket.support.NeverExpiresExpirationPolicy; import org.jasig.cas.util.DefaultUniqueTicketIdGenerator; import org.jasig.cas.util.UniqueTicketIdGenerator; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationEventPublisher; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletContext; import org.springframework.webflow.context.servlet.ServletExternalContext; import org.springframework.webflow.test.MockRequestContext; import java.security.Principal; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; import static org.mockito.Mockito.*; /** * @author Scott Battaglia * @since 3.0.0.5 */ public class PrincipalFromRequestUserPrincipalNonInteractiveCredentialsActionTests { private PrincipalFromRequestUserPrincipalNonInteractiveCredentialsAction action; @Before public void setUp() throws Exception { this.action = new PrincipalFromRequestUserPrincipalNonInteractiveCredentialsAction(); this.action.setPrincipalFactory(new DefaultPrincipalFactory()); final Map<String, UniqueTicketIdGenerator> idGenerators = new HashMap<>(); idGenerators.put(SimpleWebApplicationServiceImpl.class.getName(), new DefaultUniqueTicketIdGenerator()); final AuthenticationManager authenticationManager = new PolicyBasedAuthenticationManager( Collections.<AuthenticationHandler, PrincipalResolver>singletonMap( new PrincipalBearingCredentialsAuthenticationHandler(), new PrincipalBearingPrincipalResolver())); final CentralAuthenticationServiceImpl centralAuthenticationService = new CentralAuthenticationServiceImpl( new DefaultTicketRegistry(), authenticationManager, new DefaultUniqueTicketIdGenerator(), idGenerators, new NeverExpiresExpirationPolicy(), new NeverExpiresExpirationPolicy(), mock(ServicesManager.class), mock(LogoutManager.class)); centralAuthenticationService.setApplicationEventPublisher(mock(ApplicationEventPublisher.class)); this.action.setCentralAuthenticationService(centralAuthenticationService); } @Test public void verifyRemoteUserExists() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest(); request.setUserPrincipal(new Principal() { @Override public String getName() { return "test"; } }); final MockRequestContext context = new MockRequestContext(); context.setExternalContext(new ServletExternalContext( new MockServletContext(), request, new MockHttpServletResponse())); assertEquals("success", this.action.execute(context).getId()); } @Test public void verifyRemoteUserDoesntExists() throws Exception { final MockRequestContext context = new MockRequestContext(); context.setExternalContext(new ServletExternalContext( new MockServletContext(), new MockHttpServletRequest(), new MockHttpServletResponse())); assertEquals("error", this.action.execute(context).getId()); } }
cas-server-support-trusted/src/test/java/org/jasig/cas/adaptors/trusted/web/flow/PrincipalFromRequestUserPrincipalNonInteractiveCredentialsActionTests.java
/* * Licensed to Apereo under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Apereo 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 the following location: * * 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.jasig.cas.adaptors.trusted.web.flow; import org.jasig.cas.CentralAuthenticationServiceImpl; import org.jasig.cas.adaptors.trusted.authentication.handler.support.PrincipalBearingCredentialsAuthenticationHandler; import org.jasig.cas.adaptors.trusted.authentication.principal.PrincipalBearingPrincipalResolver; import org.jasig.cas.authentication.AuthenticationHandler; import org.jasig.cas.authentication.AuthenticationManager; import org.jasig.cas.authentication.PolicyBasedAuthenticationManager; import org.jasig.cas.authentication.principal.DefaultPrincipalFactory; import org.jasig.cas.authentication.principal.PrincipalResolver; import org.jasig.cas.authentication.principal.SimpleWebApplicationServiceImpl; import org.jasig.cas.logout.LogoutManager; import org.jasig.cas.services.ServicesManager; import org.jasig.cas.ticket.registry.DefaultTicketRegistry; import org.jasig.cas.ticket.support.NeverExpiresExpirationPolicy; import org.jasig.cas.util.DefaultUniqueTicketIdGenerator; import org.jasig.cas.util.UniqueTicketIdGenerator; import org.junit.Before; import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletContext; import org.springframework.webflow.context.servlet.ServletExternalContext; import org.springframework.webflow.test.MockRequestContext; import java.security.Principal; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; import static org.mockito.Mockito.*; /** * @author Scott Battaglia * @since 3.0.0.5 */ public class PrincipalFromRequestUserPrincipalNonInteractiveCredentialsActionTests { private PrincipalFromRequestUserPrincipalNonInteractiveCredentialsAction action; @Before public void setUp() throws Exception { this.action = new PrincipalFromRequestUserPrincipalNonInteractiveCredentialsAction(); this.action.setPrincipalFactory(new DefaultPrincipalFactory()); final Map<String, UniqueTicketIdGenerator> idGenerators = new HashMap<>(); idGenerators.put(SimpleWebApplicationServiceImpl.class.getName(), new DefaultUniqueTicketIdGenerator()); final AuthenticationManager authenticationManager = new PolicyBasedAuthenticationManager( Collections.<AuthenticationHandler, PrincipalResolver>singletonMap( new PrincipalBearingCredentialsAuthenticationHandler(), new PrincipalBearingPrincipalResolver())); final CentralAuthenticationServiceImpl centralAuthenticationService = new CentralAuthenticationServiceImpl( new DefaultTicketRegistry(), authenticationManager, new DefaultUniqueTicketIdGenerator(), idGenerators, new NeverExpiresExpirationPolicy(), new NeverExpiresExpirationPolicy(), mock(ServicesManager.class), mock(LogoutManager.class)); this.action.setCentralAuthenticationService(centralAuthenticationService); } @Test public void verifyRemoteUserExists() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest(); request.setUserPrincipal(new Principal() { @Override public String getName() { return "test"; } }); final MockRequestContext context = new MockRequestContext(); context.setExternalContext(new ServletExternalContext( new MockServletContext(), request, new MockHttpServletResponse())); assertEquals("success", this.action.execute(context).getId()); } @Test public void verifyRemoteUserDoesntExists() throws Exception { final MockRequestContext context = new MockRequestContext(); context.setExternalContext(new ServletExternalContext( new MockServletContext(), new MockHttpServletRequest(), new MockHttpServletResponse())); assertEquals("error", this.action.execute(context).getId()); } }
working on test cases
cas-server-support-trusted/src/test/java/org/jasig/cas/adaptors/trusted/web/flow/PrincipalFromRequestUserPrincipalNonInteractiveCredentialsActionTests.java
working on test cases
<ide><path>as-server-support-trusted/src/test/java/org/jasig/cas/adaptors/trusted/web/flow/PrincipalFromRequestUserPrincipalNonInteractiveCredentialsActionTests.java <ide> import org.jasig.cas.util.UniqueTicketIdGenerator; <ide> import org.junit.Before; <ide> import org.junit.Test; <add>import org.springframework.context.ApplicationEventPublisher; <ide> import org.springframework.mock.web.MockHttpServletRequest; <ide> import org.springframework.mock.web.MockHttpServletResponse; <ide> import org.springframework.mock.web.MockServletContext; <ide> new DefaultTicketRegistry(), authenticationManager, new DefaultUniqueTicketIdGenerator(), <ide> idGenerators, new NeverExpiresExpirationPolicy(), new NeverExpiresExpirationPolicy(), <ide> mock(ServicesManager.class), mock(LogoutManager.class)); <del> <add> centralAuthenticationService.setApplicationEventPublisher(mock(ApplicationEventPublisher.class)); <ide> this.action.setCentralAuthenticationService(centralAuthenticationService); <ide> } <ide>
JavaScript
cc0-1.0
38322e1412e37112faa46fd3eec8ece464462bd2
0
badges/shields,badges/shields,badges/shields
'use strict' const request = require('request') const queryString = require('query-string') const makeBadge = require('../../badge-maker/lib/make-badge') const { setCacheHeaders } = require('./cache-headers') const { Inaccessible, InvalidResponse, ShieldsRuntimeError, } = require('./errors') const { makeSend } = require('./legacy-result-sender') const LruCache = require('./lru-cache') const coalesceBadge = require('./coalesce-badge') const userAgent = 'Shields.io/2003a' // We avoid calling the vendor's server for computation of the information in a // number of badges. const minAccuracy = 0.75 // The quotient of (vendor) data change frequency by badge request frequency // must be lower than this to trigger sending the cached data *before* // updating our data from the vendor's server. // Indeed, the accuracy of our badges are: // A(Δt) = 1 - min(# data change over Δt, # requests over Δt) // / (# requests over Δt) // = 1 - max(1, df) / rf const freqRatioMax = 1 - minAccuracy // Request cache size of 5MB (~5000 bytes/image). const requestCache = new LruCache(1000) // These query parameters are available to any badge. They are handled by // `coalesceBadge`. const globalQueryParams = new Set([ 'label', 'style', 'link', 'logo', 'logoColor', 'logoPosition', 'logoWidth', 'link', 'colorA', 'colorB', 'color', 'labelColor', ]) function flattenQueryParams(queryParams) { const union = new Set(globalQueryParams) ;(queryParams || []).forEach(name => { union.add(name) }) return Array.from(union).sort() } function promisify(cachingRequest) { return (uri, options) => new Promise((resolve, reject) => { cachingRequest(uri, options, (err, res, buffer) => { if (err) { if (err instanceof ShieldsRuntimeError) { reject(err) } else { // Wrap the error in an Inaccessible so it can be identified // by the BaseService handler. reject(new Inaccessible({ underlyingError: err })) } } else { resolve({ res, buffer }) } }) }) } // handlerOptions can contain: // - handler: The service's request handler function // - queryParams: An array of the field names of any custom query parameters // the service uses // - cacheLength: An optional badge or category-specific cache length // (in number of seconds) to be used in preference to the default // - fetchLimitBytes: A limit on the response size we're willing to parse // // For safety, the service must declare the query parameters it wants to use. // Only the declared parameters (and the global parameters) are provided to // the service. Consequently, failure to declare a parameter results in the // parameter not working at all (which is undesirable, but easy to debug) // rather than indeterminate behavior that depends on the cache state // (undesirable and hard to debug). // // Pass just the handler function as shorthand. function handleRequest(cacheHeaderConfig, handlerOptions) { if (!cacheHeaderConfig) { throw Error('cacheHeaderConfig is required') } if (typeof handlerOptions === 'function') { handlerOptions = { handler: handlerOptions } } const allowedKeys = flattenQueryParams(handlerOptions.queryParams) const { cacheLength: serviceDefaultCacheLengthSeconds, fetchLimitBytes, } = handlerOptions return (queryParams, match, end, ask) => { /* This is here for legacy reasons. The badge server and frontend used to live on two different servers. When we merged them there was a conflict so we did this to avoid moving the endpoint docs to another URL. Never ever do this again. */ if (match[0] === '/endpoint' && Object.keys(queryParams).length === 0) { ask.res.statusCode = 301 ask.res.setHeader('Location', '/endpoint/') ask.res.end() return } const reqTime = new Date() // `defaultCacheLengthSeconds` can be overridden by // `serviceDefaultCacheLengthSeconds` (either by category or on a badge- // by-badge basis). Then in turn that can be overridden by // `serviceOverrideCacheLengthSeconds` (which we expect to be used only in // the dynamic badge) but only if `serviceOverrideCacheLengthSeconds` is // longer than `serviceDefaultCacheLengthSeconds` and then the `cacheSeconds` // query param can also override both of those but again only if `cacheSeconds` // is longer. // // When the legacy services have been rewritten, all the code in here // will go away, which should achieve this goal in a simpler way. // // Ref: https://github.com/badges/shields/pull/2755 function setCacheHeadersOnResponse(res, serviceOverrideCacheLengthSeconds) { setCacheHeaders({ cacheHeaderConfig, serviceDefaultCacheLengthSeconds, serviceOverrideCacheLengthSeconds, queryParams, res, }) } const filteredQueryParams = {} allowedKeys.forEach(key => { filteredQueryParams[key] = queryParams[key] }) // Use sindresorhus query-string because it sorts the keys, whereas the // builtin querystring module relies on the iteration order. const stringified = queryString.stringify(filteredQueryParams) const cacheIndex = `${match[0]}?${stringified}` // Should we return the data right away? const cached = requestCache.get(cacheIndex) let cachedVersionSent = false if (cached !== undefined) { // A request was made not long ago. const tooSoon = +reqTime - cached.time < cached.interval if (tooSoon || cached.dataChange / cached.reqs <= freqRatioMax) { const svg = makeBadge(cached.data.badgeData) setCacheHeadersOnResponse( ask.res, cached.data.badgeData.cacheLengthSeconds ) makeSend(cached.data.format, ask.res, end)(svg) cachedVersionSent = true // We do not wish to call the vendor servers. if (tooSoon) { return } } } // In case our vendor servers are unresponsive. let serverUnresponsive = false const serverResponsive = setTimeout(() => { serverUnresponsive = true if (cachedVersionSent) { return } if (requestCache.has(cacheIndex)) { const cached = requestCache.get(cacheIndex) const svg = makeBadge(cached.data.badgeData) setCacheHeadersOnResponse( ask.res, cached.data.badgeData.cacheLengthSeconds ) makeSend(cached.data.format, ask.res, end)(svg) return } ask.res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate') const badgeData = coalesceBadge( filteredQueryParams, { label: 'vendor', message: 'unresponsive' }, {} ) const svg = makeBadge(badgeData) const extension = (match.slice(-1)[0] || '.svg').replace(/^\./, '') setCacheHeadersOnResponse(ask.res) makeSend(extension, ask.res, end)(svg) }, 25000) // Only call vendor servers when last request is older than… let cacheInterval = 5000 // milliseconds function cachingRequest(uri, options, callback) { if (typeof options === 'function' && !callback) { callback = options } if (options && typeof options === 'object') { options.uri = uri } else if (typeof uri === 'string') { options = { uri } } else { options = uri } options.headers = options.headers || {} options.headers['User-Agent'] = userAgent let bufferLength = 0 const r = request(options, (err, res, body) => { if (res != null && res.headers != null) { const cacheControl = res.headers['cache-control'] if (cacheControl != null) { const age = cacheControl.match(/max-age=([0-9]+)/) // Would like to get some more test coverage on this before changing it. // eslint-disable-next-line no-self-compare if (age != null && +age[1] === +age[1]) { cacheInterval = +age[1] * 1000 } } } callback(err, res, body) }) r.on('data', chunk => { bufferLength += chunk.length if (bufferLength > fetchLimitBytes) { r.abort() r.emit( 'error', new InvalidResponse({ prettyMessage: 'Maximum response size exceeded', }) ) } }) } // Wrapper around `cachingRequest` that returns a promise rather than needing // to pass a callback. cachingRequest.asPromise = promisify(cachingRequest) const result = handlerOptions.handler( filteredQueryParams, match, // eslint-disable-next-line mocha/prefer-arrow-callback function sendBadge(format, badgeData) { if (serverUnresponsive) { return } clearTimeout(serverResponsive) // Check for a change in the data. let dataHasChanged = false if ( cached !== undefined && cached.data.badgeData.text[1] !== badgeData.text[1] ) { dataHasChanged = true } // Add format to badge data. badgeData.format = format // Update information in the cache. const updatedCache = { reqs: cached ? cached.reqs + 1 : 1, dataChange: cached ? cached.dataChange + (dataHasChanged ? 1 : 0) : 1, time: +reqTime, interval: cacheInterval, data: { format, badgeData }, } requestCache.set(cacheIndex, updatedCache) if (!cachedVersionSent) { const svg = makeBadge(badgeData) setCacheHeadersOnResponse(ask.res, badgeData.cacheLengthSeconds) makeSend(format, ask.res, end)(svg) } }, cachingRequest ) if (result && result.catch) { result.catch(err => { throw err }) } } } function clearRequestCache() { requestCache.clear() } module.exports = { handleRequest, promisify, clearRequestCache, // Expose for testing. _requestCache: requestCache, userAgent, }
core/base-service/legacy-request-handler.js
'use strict' const request = require('request') const queryString = require('query-string') const makeBadge = require('../../badge-maker/lib/make-badge') const { setCacheHeaders } = require('./cache-headers') const { Inaccessible, InvalidResponse, ShieldsRuntimeError, } = require('./errors') const { makeSend } = require('./legacy-result-sender') const LruCache = require('./lru-cache') const coalesceBadge = require('./coalesce-badge') const userAgent = 'Shields.io/2003a' // We avoid calling the vendor's server for computation of the information in a // number of badges. const minAccuracy = 0.75 // The quotient of (vendor) data change frequency by badge request frequency // must be lower than this to trigger sending the cached data *before* // updating our data from the vendor's server. // Indeed, the accuracy of our badges are: // A(Δt) = 1 - min(# data change over Δt, # requests over Δt) // / (# requests over Δt) // = 1 - max(1, df) / rf const freqRatioMax = 1 - minAccuracy // Request cache size of 5MB (~5000 bytes/image). const requestCache = new LruCache(1000) // These query parameters are available to any badge. They are handled by // `coalesceBadge`. const globalQueryParams = new Set([ 'label', 'style', 'link', 'logo', 'logoColor', 'logoPosition', 'logoWidth', 'link', 'colorA', 'colorB', 'color', 'labelColor', ]) function flattenQueryParams(queryParams) { const union = new Set(globalQueryParams) ;(queryParams || []).forEach(name => { union.add(name) }) return Array.from(union).sort() } function promisify(cachingRequest) { return (uri, options) => new Promise((resolve, reject) => { cachingRequest(uri, options, (err, res, buffer) => { if (err) { if (err instanceof ShieldsRuntimeError) { reject(err) } else { // Wrap the error in an Inaccessible so it can be identified // by the BaseService handler. reject(new Inaccessible({ underlyingError: err })) } } else { resolve({ res, buffer }) } }) }) } // handlerOptions can contain: // - handler: The service's request handler function // - queryParams: An array of the field names of any custom query parameters // the service uses // - cacheLength: An optional badge or category-specific cache length // (in number of seconds) to be used in preference to the default // - fetchLimitBytes: A limit on the response size we're willing to parse // // For safety, the service must declare the query parameters it wants to use. // Only the declared parameters (and the global parameters) are provided to // the service. Consequently, failure to declare a parameter results in the // parameter not working at all (which is undesirable, but easy to debug) // rather than indeterminate behavior that depends on the cache state // (undesirable and hard to debug). // // Pass just the handler function as shorthand. function handleRequest(cacheHeaderConfig, handlerOptions) { if (!cacheHeaderConfig) { throw Error('cacheHeaderConfig is required') } if (typeof handlerOptions === 'function') { handlerOptions = { handler: handlerOptions } } const allowedKeys = flattenQueryParams(handlerOptions.queryParams) const { cacheLength: serviceDefaultCacheLengthSeconds, fetchLimitBytes, } = handlerOptions return (queryParams, match, end, ask) => { const reqTime = new Date() // `defaultCacheLengthSeconds` can be overridden by // `serviceDefaultCacheLengthSeconds` (either by category or on a badge- // by-badge basis). Then in turn that can be overridden by // `serviceOverrideCacheLengthSeconds` (which we expect to be used only in // the dynamic badge) but only if `serviceOverrideCacheLengthSeconds` is // longer than `serviceDefaultCacheLengthSeconds` and then the `cacheSeconds` // query param can also override both of those but again only if `cacheSeconds` // is longer. // // When the legacy services have been rewritten, all the code in here // will go away, which should achieve this goal in a simpler way. // // Ref: https://github.com/badges/shields/pull/2755 function setCacheHeadersOnResponse(res, serviceOverrideCacheLengthSeconds) { setCacheHeaders({ cacheHeaderConfig, serviceDefaultCacheLengthSeconds, serviceOverrideCacheLengthSeconds, queryParams, res, }) } const filteredQueryParams = {} allowedKeys.forEach(key => { filteredQueryParams[key] = queryParams[key] }) // Use sindresorhus query-string because it sorts the keys, whereas the // builtin querystring module relies on the iteration order. const stringified = queryString.stringify(filteredQueryParams) const cacheIndex = `${match[0]}?${stringified}` // Should we return the data right away? const cached = requestCache.get(cacheIndex) let cachedVersionSent = false if (cached !== undefined) { // A request was made not long ago. const tooSoon = +reqTime - cached.time < cached.interval if (tooSoon || cached.dataChange / cached.reqs <= freqRatioMax) { const svg = makeBadge(cached.data.badgeData) setCacheHeadersOnResponse( ask.res, cached.data.badgeData.cacheLengthSeconds ) makeSend(cached.data.format, ask.res, end)(svg) cachedVersionSent = true // We do not wish to call the vendor servers. if (tooSoon) { return } } } // In case our vendor servers are unresponsive. let serverUnresponsive = false const serverResponsive = setTimeout(() => { serverUnresponsive = true if (cachedVersionSent) { return } if (requestCache.has(cacheIndex)) { const cached = requestCache.get(cacheIndex) const svg = makeBadge(cached.data.badgeData) setCacheHeadersOnResponse( ask.res, cached.data.badgeData.cacheLengthSeconds ) makeSend(cached.data.format, ask.res, end)(svg) return } ask.res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate') const badgeData = coalesceBadge( filteredQueryParams, { label: 'vendor', message: 'unresponsive' }, {} ) const svg = makeBadge(badgeData) const extension = (match.slice(-1)[0] || '.svg').replace(/^\./, '') setCacheHeadersOnResponse(ask.res) makeSend(extension, ask.res, end)(svg) }, 25000) // Only call vendor servers when last request is older than… let cacheInterval = 5000 // milliseconds function cachingRequest(uri, options, callback) { if (typeof options === 'function' && !callback) { callback = options } if (options && typeof options === 'object') { options.uri = uri } else if (typeof uri === 'string') { options = { uri } } else { options = uri } options.headers = options.headers || {} options.headers['User-Agent'] = userAgent let bufferLength = 0 const r = request(options, (err, res, body) => { if (res != null && res.headers != null) { const cacheControl = res.headers['cache-control'] if (cacheControl != null) { const age = cacheControl.match(/max-age=([0-9]+)/) // Would like to get some more test coverage on this before changing it. // eslint-disable-next-line no-self-compare if (age != null && +age[1] === +age[1]) { cacheInterval = +age[1] * 1000 } } } callback(err, res, body) }) r.on('data', chunk => { bufferLength += chunk.length if (bufferLength > fetchLimitBytes) { r.abort() r.emit( 'error', new InvalidResponse({ prettyMessage: 'Maximum response size exceeded', }) ) } }) } // Wrapper around `cachingRequest` that returns a promise rather than needing // to pass a callback. cachingRequest.asPromise = promisify(cachingRequest) const result = handlerOptions.handler( filteredQueryParams, match, // eslint-disable-next-line mocha/prefer-arrow-callback function sendBadge(format, badgeData) { if (serverUnresponsive) { return } clearTimeout(serverResponsive) // Check for a change in the data. let dataHasChanged = false if ( cached !== undefined && cached.data.badgeData.text[1] !== badgeData.text[1] ) { dataHasChanged = true } // Add format to badge data. badgeData.format = format // Update information in the cache. const updatedCache = { reqs: cached ? cached.reqs + 1 : 1, dataChange: cached ? cached.dataChange + (dataHasChanged ? 1 : 0) : 1, time: +reqTime, interval: cacheInterval, data: { format, badgeData }, } requestCache.set(cacheIndex, updatedCache) if (!cachedVersionSent) { const svg = makeBadge(badgeData) setCacheHeadersOnResponse(ask.res, badgeData.cacheLengthSeconds) makeSend(format, ask.res, end)(svg) } }, cachingRequest ) if (result && result.catch) { result.catch(err => { throw err }) } } } function clearRequestCache() { requestCache.clear() } module.exports = { handleRequest, promisify, clearRequestCache, // Expose for testing. _requestCache: requestCache, userAgent, }
redirect /endpoint with no query params to endpoint docs (#5137) Co-authored-by: repo-ranger[bot] <4f5691a0f42c9db700937238e633bc238b94b55c@users.noreply.github.com>
core/base-service/legacy-request-handler.js
redirect /endpoint with no query params to endpoint docs (#5137)
<ide><path>ore/base-service/legacy-request-handler.js <ide> } = handlerOptions <ide> <ide> return (queryParams, match, end, ask) => { <add> /* <add> This is here for legacy reasons. The badge server and frontend used to live <add> on two different servers. When we merged them there was a conflict so we <add> did this to avoid moving the endpoint docs to another URL. <add> <add> Never ever do this again. <add> */ <add> if (match[0] === '/endpoint' && Object.keys(queryParams).length === 0) { <add> ask.res.statusCode = 301 <add> ask.res.setHeader('Location', '/endpoint/') <add> ask.res.end() <add> return <add> } <add> <ide> const reqTime = new Date() <ide> <ide> // `defaultCacheLengthSeconds` can be overridden by
Java
mit
9fa80fd12570b4752ee8a776857f9a00b9f7ab53
0
paveyry/LyreLand,paveyry/LyreLand
package tonality; import java.util.Arrays; import java.util.List; /** * Created by olivier on 16/05/16. */ public class Chord { private int _root; private int _mediant; private int _dominante; public Chord (int root, String s) { _root = root; _mediant = root + (s.equals("major")? 4 : 3); _dominante = root + 7; } // ---------- Getters ---------- public List<Integer> getChord() { return Arrays.asList(_root, _mediant, _dominante); } // FIXME: We can add function for the different kinds of chords (eg. augmented etc.) }
src/tonality/Chord.java
package tonality; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by olivier on 16/05/16. */ public class Chord { private int _root; private int _mediant; private int _dominante; public Chord (int root, String s) { _root = root; _mediant = root + (s.equals("major")? 4 : 3); _dominante = root + 7; } // ---------- Getters ---------- public List<Integer> getChord() { return Arrays.asList(_root, _mediant, _dominante); } // FIXME: We can add function for the different kinds of chords (eg. augmented etc.) }
tonality: remove useless imports
src/tonality/Chord.java
tonality: remove useless imports
<ide><path>rc/tonality/Chord.java <ide> package tonality; <ide> <del>import java.lang.reflect.Array; <del>import java.util.ArrayList; <ide> import java.util.Arrays; <ide> import java.util.List; <ide>
Java
mit
70749ff26a95d4cc5fafad0efa0da2add3ac36c7
0
pickles-dev/SocialSharing-PhoneGap-Plugin,pickles-dev/SocialSharing-PhoneGap-Plugin,pickles-dev/SocialSharing-PhoneGap-Plugin
package nl.xservices.plugins; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.util.Base64; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.apache.http.util.ByteArrayBuffer; import org.json.JSONArray; import org.json.JSONException; import java.io.*; import java.net.URL; import java.util.ArrayList; import java.util.List; public class SocialSharing extends CordovaPlugin { private static final String ACTION_AVAILABLE_EVENT = "available"; private static final String ACTION_SHARE_EVENT = "share"; private static final String ACTION_CAN_SHARE_VIA = "canShareVia"; private static final String ACTION_SHARE_VIA = "shareVia"; private static final String ACTION_SHARE_VIA_TWITTER_EVENT = "shareViaTwitter"; private static final String ACTION_SHARE_VIA_FACEBOOK_EVENT = "shareViaFacebook"; private static final String ACTION_SHARE_VIA_WHATSAPP_EVENT = "shareViaWhatsApp"; private File tempFile; private CallbackContext callbackContext; @Override public boolean execute(String action, JSONArray args, CallbackContext pCallbackContext) throws JSONException { this.callbackContext = pCallbackContext; if (ACTION_AVAILABLE_EVENT.equals(action)) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); return true; } else if (ACTION_SHARE_EVENT.equals(action)) { return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), null, false); } else if (ACTION_SHARE_VIA_TWITTER_EVENT.equals(action)) { return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), "twitter", false); } else if (ACTION_SHARE_VIA_FACEBOOK_EVENT.equals(action)) { return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), "facebook", false); } else if (ACTION_SHARE_VIA_WHATSAPP_EVENT.equals(action)) { return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), "whatsapp", false); } else if (ACTION_CAN_SHARE_VIA.equals(action)) { return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), args.getString(4), true); } else if (ACTION_SHARE_VIA.equals(action)) { return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), args.getString(4), false); } else { callbackContext.error("socialSharing." + action + " is not a supported function. Did you mean '" + ACTION_SHARE_EVENT + "'?"); return false; } } private boolean doSendIntent(final String msg, final String subject, final String image, final String url, final String appPackageName, final boolean peek) { final CordovaInterface mycordova = cordova; final CordovaPlugin plugin = this; cordova.getThreadPool().execute(new Runnable() { public void run() { String message = msg; try { final Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND); final String dir = webView.getContext().getExternalFilesDir(null) + "/socialsharing-downloads"; createDir(dir); sendIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); String localImage = image; if ("".equals(image) || "null".equalsIgnoreCase(image)) { sendIntent.setType("text/plain"); } else { sendIntent.setType("image/*"); if (image.startsWith("http") || image.startsWith("www/")) { final String filename = getFileName(image); localImage = "file://" + dir + "/" + filename; if (image.startsWith("http")) { saveFile(getBytes(new URL(image).openConnection().getInputStream()), dir, filename); } else { saveFile(getBytes(webView.getContext().getAssets().open(image)), dir, filename); } } else if (image.startsWith("data:")) { // image looks like this: data:image/png;base64,R0lGODlhDAA... final String encodedImg = image.substring(image.indexOf(";base64,") + 8); // the filename needs a valid extension, so it renders correctly in target apps final String imgExtension = image.substring(image.indexOf("image/") + 6, image.indexOf(";base64")); final String fileName = "image." + imgExtension; saveFile(Base64.decode(encodedImg, Base64.DEFAULT), dir, fileName); localImage = "file://" + dir + "/" + fileName; } else if (!image.startsWith("file://")) { throw new IllegalArgumentException("URL_NOT_SUPPORTED"); } sendIntent.putExtra(android.content.Intent.EXTRA_STREAM, Uri.parse(localImage)); } if (!"".equals(subject) && !"null".equalsIgnoreCase(subject)) { sendIntent.putExtra(Intent.EXTRA_SUBJECT, subject); } // add the URL to the message, as there seems to be no separate field if (!"".equals(url) && !"null".equalsIgnoreCase(url)) { if (!"".equals(message) && !"null".equalsIgnoreCase(message)) { message += " " + url; } else { message = url; } } if (!"".equals(message) && !"null".equalsIgnoreCase(message)) { sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, message); } if (appPackageName != null) { final ActivityInfo activity = getActivity(sendIntent, appPackageName); if (activity != null) { if (peek) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); } else { sendIntent.addCategory(Intent.CATEGORY_LAUNCHER); sendIntent.setComponent(new ComponentName(activity.applicationInfo.packageName, activity.name)); mycordova.startActivityForResult(plugin, sendIntent, 0); } } } else { if (peek) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); } else { mycordova.startActivityForResult(plugin, Intent.createChooser(sendIntent, null), 1); } } } catch (IOException e) { callbackContext.error(e.getMessage()); } } }); return true; } private ActivityInfo getActivity(final Intent shareIntent, final String appPackageName) { final PackageManager pm = webView.getContext().getPackageManager(); List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0); for (final ResolveInfo app : activityList) { if ((app.activityInfo.packageName).contains(appPackageName)) { return app.activityInfo; } } // no matching app found callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, getShareActivities(activityList))); return null; } private JSONArray getShareActivities(List<ResolveInfo> activityList) { List<String> packages = new ArrayList<String>(); for (final ResolveInfo app : activityList) { packages.add(app.activityInfo.packageName); } return new JSONArray(packages); } // cleanup after ourselves public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (tempFile != null) { //noinspection ResultOfMethodCallIgnored tempFile.delete(); } // note that the resultCode needs to be sent correctly by the sharing app, which is not always the case :( callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, resultCode == Activity.RESULT_OK)); } private void createDir(final String downloadDir) throws IOException { final File dir = new File(downloadDir); if (!dir.exists()) { if (!dir.mkdirs()) { throw new IOException("CREATE_DIRS_FAILED"); } } } private String getFileName(String url) { final int lastIndexOfSlash = url.lastIndexOf('/'); if (lastIndexOfSlash == -1) { return url; } else { return url.substring(lastIndexOfSlash + 1); } } private byte[] getBytes(InputStream is) throws IOException { BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(5000); int current; while ((current = bis.read()) != -1) { baf.append((byte) current); } return baf.toByteArray(); } private void saveFile(byte[] bytes, String dirName, String fileName) throws IOException { final File dir = new File(dirName); tempFile = new File(dir, fileName); FileOutputStream fos = new FileOutputStream(tempFile); fos.write(bytes); fos.flush(); fos.close(); } }
src/android/nl/xservices/plugins/SocialSharing.java
package nl.xservices.plugins; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.util.Base64; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.apache.http.util.ByteArrayBuffer; import org.json.JSONArray; import org.json.JSONException; import java.io.*; import java.net.URL; import java.util.ArrayList; import java.util.List; public class SocialSharing extends CordovaPlugin { private static final String ACTION_AVAILABLE_EVENT = "available"; private static final String ACTION_SHARE_EVENT = "share"; private static final String ACTION_CAN_SHARE_VIA = "canShareVia"; private static final String ACTION_SHARE_VIA = "shareVia"; private static final String ACTION_SHARE_VIA_TWITTER_EVENT = "shareViaTwitter"; private static final String ACTION_SHARE_VIA_FACEBOOK_EVENT = "shareViaFacebook"; private static final String ACTION_SHARE_VIA_WHATSAPP_EVENT = "shareViaWhatsApp"; private File tempFile; private CallbackContext callbackContext; @Override public boolean execute(String action, JSONArray args, CallbackContext pCallbackContext) throws JSONException { this.callbackContext = pCallbackContext; try { if (ACTION_AVAILABLE_EVENT.equals(action)) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); return true; } else if (ACTION_SHARE_EVENT.equals(action)) { return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), null, false); } else if (ACTION_SHARE_VIA_TWITTER_EVENT.equals(action)) { return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), "twitter", false); } else if (ACTION_SHARE_VIA_FACEBOOK_EVENT.equals(action)) { return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), "facebook", false); } else if (ACTION_SHARE_VIA_WHATSAPP_EVENT.equals(action)) { return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), "whatsapp", false); } else if (ACTION_CAN_SHARE_VIA.equals(action)) { return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), args.getString(4), true); } else if (ACTION_SHARE_VIA.equals(action)) { return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), args.getString(4), false); } else { callbackContext.error("socialSharing." + action + " is not a supported function. Did you mean '" + ACTION_SHARE_EVENT + "'?"); return false; } } catch (Exception e) { callbackContext.error(e.getMessage()); return false; } } private boolean doSendIntent(String message, String subject, String image, String url, String appPackageName, boolean peek) throws IOException { final Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND); final String dir = webView.getContext().getExternalFilesDir(null) + "/socialsharing-downloads"; createDir(dir); sendIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); String localImage = image; if ("".equals(image) || "null".equalsIgnoreCase(image)) { sendIntent.setType("text/plain"); } else { sendIntent.setType("image/*"); if (image.startsWith("http") || image.startsWith("www/")) { final String filename = getFileName(image); localImage = "file://" + dir + "/" + filename; if (image.startsWith("http")) { saveFile(getBytes(new URL(image).openConnection().getInputStream()), dir, filename); } else { saveFile(getBytes(webView.getContext().getAssets().open(image)), dir, filename); } } else if (image.startsWith("data:")) { // image looks like this: data:image/png;base64,R0lGODlhDAA... final String encodedImg = image.substring(image.indexOf(";base64,") + 8); // the filename needs a valid extension, so it renders correctly in target apps final String imgExtension = image.substring(image.indexOf("image/") + 6, image.indexOf(";base64")); final String fileName = "image." + imgExtension; saveFile(Base64.decode(encodedImg, Base64.DEFAULT), dir, fileName); localImage = "file://" + dir + "/" + fileName; } else if (!image.startsWith("file://")) { throw new IllegalArgumentException("URL_NOT_SUPPORTED"); } sendIntent.putExtra(android.content.Intent.EXTRA_STREAM, Uri.parse(localImage)); } if (!"".equals(subject) && !"null".equalsIgnoreCase(subject)) { sendIntent.putExtra(Intent.EXTRA_SUBJECT, subject); } // add the URL to the message, as there seems to be no separate field if (!"".equals(url) && !"null".equalsIgnoreCase(url)) { if (!"".equals(message) && !"null".equalsIgnoreCase(message)) { message += " " + url; } else { message = url; } } if (!"".equals(message) && !"null".equalsIgnoreCase(message)) { sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, message); } if (appPackageName != null) { final ActivityInfo activity = getActivity(sendIntent, appPackageName); if (activity == null) { return false; } if (peek) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); } else { sendIntent.addCategory(Intent.CATEGORY_LAUNCHER); sendIntent.setComponent(new ComponentName(activity.applicationInfo.packageName, activity.name)); this.cordova.startActivityForResult(this, sendIntent, 0); } } else { if (peek) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); } else { this.cordova.startActivityForResult(this, Intent.createChooser(sendIntent, null), 1); } } return true; } private ActivityInfo getActivity(final Intent shareIntent, final String appPackageName) { final PackageManager pm = webView.getContext().getPackageManager(); List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0); for (final ResolveInfo app : activityList) { if ((app.activityInfo.packageName).contains(appPackageName)) { return app.activityInfo; } } // no matching app found callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, getShareActivities(activityList))); return null; } private JSONArray getShareActivities(List<ResolveInfo> activityList) { List<String> packages = new ArrayList<String>(); for (final ResolveInfo app : activityList) { packages.add(app.activityInfo.packageName); } return new JSONArray(packages); } // cleanup after ourselves public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (tempFile != null) { //noinspection ResultOfMethodCallIgnored tempFile.delete(); } // note that the resultCode needs to be sent correctly by the sharing app, which is not always the case :( callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, resultCode == Activity.RESULT_OK)); } private void createDir(final String downloadDir) throws IOException { final File dir = new File(downloadDir); if (!dir.exists()) { if (!dir.mkdirs()) { throw new IOException("CREATE_DIRS_FAILED"); } } } private String getFileName(String url) { final int lastIndexOfSlash = url.lastIndexOf('/'); if (lastIndexOfSlash == -1) { return url; } else { return url.substring(lastIndexOfSlash + 1); } } private byte[] getBytes(InputStream is) throws IOException { BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(5000); int current; while ((current = bis.read()) != -1) { baf.append((byte) current); } return baf.toByteArray(); } private void saveFile(byte[] bytes, String dirName, String fileName) throws IOException { final File dir = new File(dirName); tempFile = new File(dir, fileName); FileOutputStream fos = new FileOutputStream(tempFile); fos.write(bytes); fos.flush(); fos.close(); } }
Not blocking the WebCore thread anymore (issue 34)
src/android/nl/xservices/plugins/SocialSharing.java
Not blocking the WebCore thread anymore (issue 34)
<ide><path>rc/android/nl/xservices/plugins/SocialSharing.java <ide> import android.net.Uri; <ide> import android.util.Base64; <ide> import org.apache.cordova.CallbackContext; <add>import org.apache.cordova.CordovaInterface; <ide> import org.apache.cordova.CordovaPlugin; <ide> import org.apache.cordova.PluginResult; <ide> import org.apache.http.util.ByteArrayBuffer; <ide> @Override <ide> public boolean execute(String action, JSONArray args, CallbackContext pCallbackContext) throws JSONException { <ide> this.callbackContext = pCallbackContext; <del> try { <del> if (ACTION_AVAILABLE_EVENT.equals(action)) { <del> callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); <del> return true; <del> } else if (ACTION_SHARE_EVENT.equals(action)) { <del> return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), null, false); <del> } else if (ACTION_SHARE_VIA_TWITTER_EVENT.equals(action)) { <del> return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), "twitter", false); <del> } else if (ACTION_SHARE_VIA_FACEBOOK_EVENT.equals(action)) { <del> return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), "facebook", false); <del> } else if (ACTION_SHARE_VIA_WHATSAPP_EVENT.equals(action)) { <del> return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), "whatsapp", false); <del> } else if (ACTION_CAN_SHARE_VIA.equals(action)) { <del> return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), args.getString(4), true); <del> } else if (ACTION_SHARE_VIA.equals(action)) { <del> return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), args.getString(4), false); <del> } else { <del> callbackContext.error("socialSharing." + action + " is not a supported function. Did you mean '" + ACTION_SHARE_EVENT + "'?"); <del> return false; <add> if (ACTION_AVAILABLE_EVENT.equals(action)) { <add> callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); <add> return true; <add> } else if (ACTION_SHARE_EVENT.equals(action)) { <add> return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), null, false); <add> } else if (ACTION_SHARE_VIA_TWITTER_EVENT.equals(action)) { <add> return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), "twitter", false); <add> } else if (ACTION_SHARE_VIA_FACEBOOK_EVENT.equals(action)) { <add> return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), "facebook", false); <add> } else if (ACTION_SHARE_VIA_WHATSAPP_EVENT.equals(action)) { <add> return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), "whatsapp", false); <add> } else if (ACTION_CAN_SHARE_VIA.equals(action)) { <add> return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), args.getString(4), true); <add> } else if (ACTION_SHARE_VIA.equals(action)) { <add> return doSendIntent(args.getString(0), args.getString(1), args.getString(2), args.getString(3), args.getString(4), false); <add> } else { <add> callbackContext.error("socialSharing." + action + " is not a supported function. Did you mean '" + ACTION_SHARE_EVENT + "'?"); <add> return false; <add> } <add> } <add> <add> private boolean doSendIntent(final String msg, final String subject, final String image, final String url, final String appPackageName, final boolean peek) { <add> <add> final CordovaInterface mycordova = cordova; <add> final CordovaPlugin plugin = this; <add> <add> cordova.getThreadPool().execute(new Runnable() { <add> public void run() { <add> String message = msg; <add> try { <add> final Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND); <add> final String dir = webView.getContext().getExternalFilesDir(null) + "/socialsharing-downloads"; <add> createDir(dir); <add> sendIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); <add> <add> String localImage = image; <add> if ("".equals(image) || "null".equalsIgnoreCase(image)) { <add> sendIntent.setType("text/plain"); <add> } else { <add> sendIntent.setType("image/*"); <add> if (image.startsWith("http") || image.startsWith("www/")) { <add> final String filename = getFileName(image); <add> localImage = "file://" + dir + "/" + filename; <add> if (image.startsWith("http")) { <add> saveFile(getBytes(new URL(image).openConnection().getInputStream()), dir, filename); <add> } else { <add> saveFile(getBytes(webView.getContext().getAssets().open(image)), dir, filename); <add> } <add> } else if (image.startsWith("data:")) { <add> // image looks like this: data:image/png;base64,R0lGODlhDAA... <add> final String encodedImg = image.substring(image.indexOf(";base64,") + 8); <add> // the filename needs a valid extension, so it renders correctly in target apps <add> final String imgExtension = image.substring(image.indexOf("image/") + 6, image.indexOf(";base64")); <add> final String fileName = "image." + imgExtension; <add> saveFile(Base64.decode(encodedImg, Base64.DEFAULT), dir, fileName); <add> localImage = "file://" + dir + "/" + fileName; <add> } else if (!image.startsWith("file://")) { <add> throw new IllegalArgumentException("URL_NOT_SUPPORTED"); <add> } <add> sendIntent.putExtra(android.content.Intent.EXTRA_STREAM, Uri.parse(localImage)); <add> } <add> if (!"".equals(subject) && !"null".equalsIgnoreCase(subject)) { <add> sendIntent.putExtra(Intent.EXTRA_SUBJECT, subject); <add> } <add> // add the URL to the message, as there seems to be no separate field <add> if (!"".equals(url) && !"null".equalsIgnoreCase(url)) { <add> if (!"".equals(message) && !"null".equalsIgnoreCase(message)) { <add> message += " " + url; <add> } else { <add> message = url; <add> } <add> } <add> if (!"".equals(message) && !"null".equalsIgnoreCase(message)) { <add> sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, message); <add> } <add> <add> if (appPackageName != null) { <add> final ActivityInfo activity = getActivity(sendIntent, appPackageName); <add> if (activity != null) { <add> if (peek) { <add> callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); <add> } else { <add> sendIntent.addCategory(Intent.CATEGORY_LAUNCHER); <add> sendIntent.setComponent(new ComponentName(activity.applicationInfo.packageName, activity.name)); <add> mycordova.startActivityForResult(plugin, sendIntent, 0); <add> } <add> } <add> } else { <add> if (peek) { <add> callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); <add> } else { <add> mycordova.startActivityForResult(plugin, Intent.createChooser(sendIntent, null), 1); <add> } <add> } <add> } catch (IOException e) { <add> callbackContext.error(e.getMessage()); <add> } <ide> } <del> } catch (Exception e) { <del> callbackContext.error(e.getMessage()); <del> return false; <del> } <del> } <del> <del> private boolean doSendIntent(String message, String subject, String image, String url, String appPackageName, boolean peek) throws IOException { <del> final Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND); <del> final String dir = webView.getContext().getExternalFilesDir(null) + "/socialsharing-downloads"; <del> createDir(dir); <del> sendIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); <del> <del> String localImage = image; <del> if ("".equals(image) || "null".equalsIgnoreCase(image)) { <del> sendIntent.setType("text/plain"); <del> } else { <del> sendIntent.setType("image/*"); <del> if (image.startsWith("http") || image.startsWith("www/")) { <del> final String filename = getFileName(image); <del> localImage = "file://" + dir + "/" + filename; <del> if (image.startsWith("http")) { <del> saveFile(getBytes(new URL(image).openConnection().getInputStream()), dir, filename); <del> } else { <del> saveFile(getBytes(webView.getContext().getAssets().open(image)), dir, filename); <del> } <del> } else if (image.startsWith("data:")) { <del> // image looks like this: data:image/png;base64,R0lGODlhDAA... <del> final String encodedImg = image.substring(image.indexOf(";base64,") + 8); <del> // the filename needs a valid extension, so it renders correctly in target apps <del> final String imgExtension = image.substring(image.indexOf("image/") + 6, image.indexOf(";base64")); <del> final String fileName = "image." + imgExtension; <del> saveFile(Base64.decode(encodedImg, Base64.DEFAULT), dir, fileName); <del> localImage = "file://" + dir + "/" + fileName; <del> } else if (!image.startsWith("file://")) { <del> throw new IllegalArgumentException("URL_NOT_SUPPORTED"); <del> } <del> sendIntent.putExtra(android.content.Intent.EXTRA_STREAM, Uri.parse(localImage)); <del> } <del> if (!"".equals(subject) && !"null".equalsIgnoreCase(subject)) { <del> sendIntent.putExtra(Intent.EXTRA_SUBJECT, subject); <del> } <del> // add the URL to the message, as there seems to be no separate field <del> if (!"".equals(url) && !"null".equalsIgnoreCase(url)) { <del> if (!"".equals(message) && !"null".equalsIgnoreCase(message)) { <del> message += " " + url; <del> } else { <del> message = url; <del> } <del> } <del> if (!"".equals(message) && !"null".equalsIgnoreCase(message)) { <del> sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, message); <del> } <del> <del> if (appPackageName != null) { <del> final ActivityInfo activity = getActivity(sendIntent, appPackageName); <del> if (activity == null) { <del> return false; <del> } <del> if (peek) { <del> callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); <del> } else { <del> sendIntent.addCategory(Intent.CATEGORY_LAUNCHER); <del> sendIntent.setComponent(new ComponentName(activity.applicationInfo.packageName, activity.name)); <del> this.cordova.startActivityForResult(this, sendIntent, 0); <del> } <del> } else { <del> if (peek) { <del> callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); <del> } else { <del> this.cordova.startActivityForResult(this, Intent.createChooser(sendIntent, null), 1); <del> } <del> } <add> }); <ide> return true; <ide> } <ide>
Java
apache-2.0
90a1374750f3f92749b4876a043a13f9dcc0ced5
0
openzipkin/zipkin-reporter-java,openzipkin/zipkin-reporter-java
/* * Copyright 2016-2020 The OpenZipkin 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 zipkin2.reporter.kafka; import com.github.charithe.kafka.EphemeralKafkaBroker; import com.github.charithe.kafka.KafkaJunitRule; import java.lang.management.ManagementFactory; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.TimeoutException; import java.util.stream.Stream; import javax.management.ObjectName; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.errors.RecordTooLargeException; import org.apache.kafka.common.serialization.ByteArraySerializer; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import zipkin2.Call; import zipkin2.CheckResult; import zipkin2.Span; import zipkin2.codec.Encoding; import zipkin2.codec.SpanBytesDecoder; import zipkin2.codec.SpanBytesEncoder; import zipkin2.reporter.AsyncReporter; import zipkin2.reporter.Sender; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static zipkin2.TestObjects.CLIENT_SPAN; public class ITKafkaSender { EphemeralKafkaBroker broker = EphemeralKafkaBroker.create(); @Rule public KafkaJunitRule kafka = new KafkaJunitRule(broker).waitForStartup(); @Rule public ExpectedException thrown = ExpectedException.none(); KafkaSender sender; @Before public void open() { sender = KafkaSender.create(broker.getBrokerList().get()); } @After public void close() { sender.close(); } @Test public void sendsSpans() throws Exception { send(CLIENT_SPAN, CLIENT_SPAN).execute(); assertThat(SpanBytesDecoder.JSON_V2.decodeList(readMessage())) .containsExactly(CLIENT_SPAN, CLIENT_SPAN); } @Test public void sendsSpans_PROTO3() throws Exception { sender.close(); sender = sender.toBuilder().encoding(Encoding.PROTO3).build(); send(CLIENT_SPAN, CLIENT_SPAN).execute(); assertThat(SpanBytesDecoder.PROTO3.decodeList(readMessage())) .containsExactly(CLIENT_SPAN, CLIENT_SPAN); } @Test public void sendsSpans_THRIFT() throws Exception { sender.close(); sender = sender.toBuilder().encoding(Encoding.THRIFT).build(); send(CLIENT_SPAN, CLIENT_SPAN).execute(); assertThat(SpanBytesDecoder.THRIFT.decodeList(readMessage())) .containsExactly(CLIENT_SPAN, CLIENT_SPAN); } @Test public void sendsSpansToCorrectTopic() throws Exception { sender.close(); sender = sender.toBuilder().topic("customzipkintopic").build(); send(CLIENT_SPAN, CLIENT_SPAN).execute(); assertThat(SpanBytesDecoder.JSON_V2.decodeList(readMessage("customzipkintopic"))) .containsExactly(CLIENT_SPAN, CLIENT_SPAN); } @Test public void checkFalseWhenKafkaIsDown() throws Exception { broker.stop(); // Make a new tracer that fails faster than 60 seconds sender.close(); Map<String, String> overrides = new LinkedHashMap<>(); overrides.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, "100"); sender = sender.toBuilder().overrides(overrides).build(); CheckResult check = sender.check(); assertThat(check.ok()).isFalse(); assertThat(check.error()).isInstanceOf(TimeoutException.class); } @Test public void illegalToSendWhenClosed() throws Exception { thrown.expect(IllegalStateException.class); sender.close(); send(CLIENT_SPAN, CLIENT_SPAN).execute(); } @Test public void shouldCloseKafkaProducerOnClose() throws Exception { send(CLIENT_SPAN, CLIENT_SPAN).execute(); final ObjectName kafkaProducerMXBeanName = new ObjectName("kafka.producer:*"); final Set<ObjectName> withProducers = ManagementFactory.getPlatformMBeanServer().queryNames( kafkaProducerMXBeanName, null); assertThat(withProducers).isNotEmpty(); sender.close(); final Set<ObjectName> withNoProducers = ManagementFactory.getPlatformMBeanServer().queryNames( kafkaProducerMXBeanName, null); assertThat(withNoProducers).isEmpty(); } @Test public void shouldFailWhenMessageIsBiggerThanMaxSize() throws Exception { thrown.expect(RecordTooLargeException.class); sender.close(); sender = sender.toBuilder().messageMaxBytes(1).build(); send(CLIENT_SPAN, CLIENT_SPAN).execute(); } /** * The output of toString() on {@link Sender} implementations appears in thread names created by * {@link AsyncReporter}. Since thread names are likely to be exposed in logs and other monitoring * tools, care should be taken to ensure the toString() output is a reasonable length and does not * contain sensitive information. */ @Test public void toStringContainsOnlySummaryInformation() { assertThat(sender.toString()).isEqualTo( "KafkaSender{bootstrapServers=" + broker.getBrokerList().get() + ", topic=zipkin}" ); } @Test public void checkFilterPropertiesProducerToAdminClient() { Properties producerProperties = new Properties(); producerProperties.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, "100"); producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class.getName()); producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class.getName()); producerProperties.put(ProducerConfig.BATCH_SIZE_CONFIG, "0"); producerProperties.put(ProducerConfig.ACKS_CONFIG, "0"); producerProperties.put(ProducerConfig.LINGER_MS_CONFIG, "500"); producerProperties.put(ProducerConfig.BUFFER_MEMORY_CONFIG, "33554432"); producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092"); producerProperties.put(ProducerConfig.SECURITY_PROVIDERS_CONFIG, "sun.security.provider.Sun"); Map<String, Object> filteredProperties = sender.filterPropertiesForAdminClient(producerProperties); assertThat(filteredProperties.size()).isEqualTo(2); assertThat(filteredProperties.get(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)).isNotNull(); assertThat(filteredProperties.get(ProducerConfig.SECURITY_PROVIDERS_CONFIG)).isNotNull(); } Call<Void> send(Span... spans) { SpanBytesEncoder bytesEncoder; switch (sender.encoding()) { case JSON: bytesEncoder = SpanBytesEncoder.JSON_V2; break; case THRIFT: bytesEncoder = SpanBytesEncoder.THRIFT; break; case PROTO3: bytesEncoder = SpanBytesEncoder.PROTO3; break; default: throw new UnsupportedOperationException("encoding: " + sender.encoding()); } return sender.sendSpans(Stream.of(spans).map(bytesEncoder::encode).collect(toList())); } private byte[] readMessage(String topic) throws Exception { KafkaConsumer<byte[], byte[]> consumer = kafka.helper().createByteConsumer(); return kafka.helper().consume(topic, consumer, 1) .get().stream().map(ConsumerRecord::value).findFirst().get(); } private byte[] readMessage() throws Exception { return readMessage("zipkin"); } }
kafka/src/test/java/zipkin2/reporter/kafka/ITKafkaSender.java
/* * Copyright 2016-2019 The OpenZipkin 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 zipkin2.reporter.kafka; import com.github.charithe.kafka.EphemeralKafkaBroker; import com.github.charithe.kafka.KafkaJunitRule; import java.lang.management.ManagementFactory; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.TimeoutException; import java.util.stream.Stream; import javax.management.ObjectName; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.errors.RecordTooLargeException; import org.apache.kafka.common.serialization.ByteArraySerializer; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import zipkin2.Call; import zipkin2.CheckResult; import zipkin2.Span; import zipkin2.codec.Encoding; import zipkin2.codec.SpanBytesDecoder; import zipkin2.codec.SpanBytesEncoder; import zipkin2.reporter.AsyncReporter; import zipkin2.reporter.Sender; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static zipkin2.TestObjects.CLIENT_SPAN; public class ITKafkaSender { EphemeralKafkaBroker broker = EphemeralKafkaBroker.create(); @Rule public KafkaJunitRule kafka = new KafkaJunitRule(broker).waitForStartup(); @Rule public ExpectedException thrown = ExpectedException.none(); KafkaSender sender; @Before public void open() { sender = KafkaSender.create(broker.getBrokerList().get()); } @After public void close() { sender.close(); } @Test public void sendsSpans() throws Exception { send(CLIENT_SPAN, CLIENT_SPAN).execute(); assertThat(SpanBytesDecoder.JSON_V2.decodeList(readMessage())) .containsExactly(CLIENT_SPAN, CLIENT_SPAN); } @Test public void sendsSpans_PROTO3() throws Exception { sender.close(); sender = sender.toBuilder().encoding(Encoding.PROTO3).build(); send(CLIENT_SPAN, CLIENT_SPAN).execute(); assertThat(SpanBytesDecoder.PROTO3.decodeList(readMessage())) .containsExactly(CLIENT_SPAN, CLIENT_SPAN); } @Test public void sendsSpans_THRIFT() throws Exception { sender.close(); sender = sender.toBuilder().encoding(Encoding.THRIFT).build(); send(CLIENT_SPAN, CLIENT_SPAN).execute(); assertThat(SpanBytesDecoder.THRIFT.decodeList(readMessage())) .containsExactly(CLIENT_SPAN, CLIENT_SPAN); } @Test public void sendsSpansToCorrectTopic() throws Exception { sender.close(); sender = sender.toBuilder().topic("customzipkintopic").build(); send(CLIENT_SPAN, CLIENT_SPAN).execute(); assertThat(SpanBytesDecoder.JSON_V2.decodeList(readMessage("customzipkintopic"))) .containsExactly(CLIENT_SPAN, CLIENT_SPAN); } @Test public void checkFalseWhenKafkaIsDown() throws Exception { broker.stop(); // Make a new tracer that fails faster than 60 seconds sender.close(); Map<String, String> overrides = new LinkedHashMap<>(); overrides.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, "100"); sender = sender.toBuilder().overrides(overrides).build(); CheckResult check = sender.check(); assertThat(check.ok()).isFalse(); assertThat(check.error()).isInstanceOf(TimeoutException.class); } @Test public void illegalToSendWhenClosed() throws Exception { thrown.expect(IllegalStateException.class); sender.close(); send(CLIENT_SPAN, CLIENT_SPAN).execute(); } @Test public void shouldCloseKafkaProducerOnClose() throws Exception { send(CLIENT_SPAN, CLIENT_SPAN).execute(); final ObjectName kafkaProducerMXBeanName = new ObjectName("kafka.producer:*"); final Set<ObjectName> withProducers = ManagementFactory.getPlatformMBeanServer().queryNames( kafkaProducerMXBeanName, null); assertThat(withProducers).isNotEmpty(); sender.close(); final Set<ObjectName> withNoProducers = ManagementFactory.getPlatformMBeanServer().queryNames( kafkaProducerMXBeanName, null); assertThat(withNoProducers).isEmpty(); } @Test public void shouldFailWhenMessageIsBiggerThanMaxSize() throws Exception { thrown.expect(RecordTooLargeException.class); sender.close(); sender = sender.toBuilder().messageMaxBytes(1).build(); send(CLIENT_SPAN, CLIENT_SPAN).execute(); } /** * The output of toString() on {@link Sender} implementations appears in thread names created by * {@link AsyncReporter}. Since thread names are likely to be exposed in logs and other monitoring * tools, care should be taken to ensure the toString() output is a reasonable length and does not * contain sensitive information. */ @Test public void toStringContainsOnlySummaryInformation() { assertThat(sender.toString()).isEqualTo( "KafkaSender{bootstrapServers=" + broker.getBrokerList().get() + ", topic=zipkin}" ); } @Test public void checkFilterPropertiesProducerToAdminClient() { Properties producerProperties = new Properties(); producerProperties.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, "100"); producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class.getName()); producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class.getName()); producerProperties.put(ProducerConfig.BATCH_SIZE_CONFIG, "0"); producerProperties.put(ProducerConfig.ACKS_CONFIG, "0"); producerProperties.put(ProducerConfig.LINGER_MS_CONFIG, "500"); producerProperties.put(ProducerConfig.BUFFER_MEMORY_CONFIG, "33554432"); producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092"); producerProperties.put(ProducerConfig.SECURITY_PROVIDERS_CONFIG, "sun.security.provider.Sun"); Map<String, Object> filteredProperties = sender.filterPropertiesForAdminClient(producerProperties); assertThat(filteredProperties.size()).isEqualTo(2); assertThat(filteredProperties.get(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)).isNotNull(); assertThat(filteredProperties.get(ProducerConfig.SECURITY_PROVIDERS_CONFIG)).isNotNull(); } Call<Void> send(Span... spans) { SpanBytesEncoder bytesEncoder; switch (sender.encoding()) { case JSON: bytesEncoder = SpanBytesEncoder.JSON_V2; break; case THRIFT: bytesEncoder = SpanBytesEncoder.THRIFT; break; case PROTO3: bytesEncoder = SpanBytesEncoder.PROTO3; break; default: throw new UnsupportedOperationException("encoding: " + sender.encoding()); } return sender.sendSpans(Stream.of(spans).map(bytesEncoder::encode).collect(toList())); } private byte[] readMessage(String topic) throws Exception { KafkaConsumer<byte[], byte[]> consumer = kafka.helper().createByteConsumer(); return kafka.helper().consume(topic, consumer, 1) .get().stream().map(ConsumerRecord::value).findFirst().get(); } private byte[] readMessage() throws Exception { return readMessage("zipkin"); } }
license
kafka/src/test/java/zipkin2/reporter/kafka/ITKafkaSender.java
license
<ide><path>afka/src/test/java/zipkin2/reporter/kafka/ITKafkaSender.java <ide> /* <del> * Copyright 2016-2019 The OpenZipkin Authors <add> * Copyright 2016-2020 The OpenZipkin Authors <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except <ide> * in compliance with the License. You may obtain a copy of the License at
Java
apache-2.0
93d8aac7c4e962da72cf70e3e88142a302ae94d1
0
mosoft521/wicket,aldaris/wicket,AlienQueen/wicket,mosoft521/wicket,AlienQueen/wicket,bitstorm/wicket,dashorst/wicket,freiheit-com/wicket,AlienQueen/wicket,freiheit-com/wicket,bitstorm/wicket,astrapi69/wicket,selckin/wicket,dashorst/wicket,aldaris/wicket,dashorst/wicket,bitstorm/wicket,astrapi69/wicket,apache/wicket,klopfdreh/wicket,AlienQueen/wicket,apache/wicket,topicusonderwijs/wicket,klopfdreh/wicket,selckin/wicket,mosoft521/wicket,klopfdreh/wicket,apache/wicket,freiheit-com/wicket,selckin/wicket,aldaris/wicket,astrapi69/wicket,topicusonderwijs/wicket,aldaris/wicket,selckin/wicket,topicusonderwijs/wicket,dashorst/wicket,bitstorm/wicket,apache/wicket,aldaris/wicket,klopfdreh/wicket,astrapi69/wicket,freiheit-com/wicket,topicusonderwijs/wicket,mosoft521/wicket,freiheit-com/wicket,selckin/wicket,apache/wicket,mosoft521/wicket,klopfdreh/wicket,AlienQueen/wicket,topicusonderwijs/wicket,dashorst/wicket,bitstorm/wicket
/* * 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.wicket.core.request.handler; import org.apache.wicket.Page; import org.apache.wicket.request.component.IRequestableComponent; import org.apache.wicket.request.component.IRequestablePage; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.util.lang.Args; /** * Extension of {@link PageProvider} that is also capable of providing a Component belonging to the * page. * * @see PageProvider * * @author Matej Knopp */ public class PageAndComponentProvider extends PageProvider implements IPageAndComponentProvider { private IRequestableComponent component; private String componentPath; /** * @see PageProvider#PageProvider(IRequestablePage) * * @param page * @param componentPath */ public PageAndComponentProvider(IRequestablePage page, String componentPath) { super(page); setComponentPath(componentPath); } /** * @see PageProvider#PageProvider(IRequestablePage) * * @param page * @param component */ public PageAndComponentProvider(IRequestablePage page, IRequestableComponent component) { super(page); Args.notNull(component, "component"); this.component = component; } /** * @see PageProvider#PageProvider(Class, PageParameters) * * @param pageClass * @param pageParameters * @param componentPath */ public PageAndComponentProvider(Class<? extends IRequestablePage> pageClass, PageParameters pageParameters, String componentPath) { super(pageClass, pageParameters); setComponentPath(componentPath); } /** * @see PageProvider#PageProvider(Class) * * @param pageClass * @param componentPath */ public PageAndComponentProvider(Class<? extends IRequestablePage> pageClass, String componentPath) { super(pageClass); setComponentPath(componentPath); } /** * @see PageProvider#PageProvider(Integer, Class, Integer) * * @param pageId * @param pageClass * @param renderCount * @param componentPath */ public PageAndComponentProvider(int pageId, Class<? extends IRequestablePage> pageClass, Integer renderCount, String componentPath) { super(pageId, pageClass, renderCount); setComponentPath(componentPath); } /** * @see PageProvider#PageProvider(int, Class, PageParameters, Integer) * * @param pageId * @param pageClass * @param pageParameters * @param renderCount * @param componentPath */ public PageAndComponentProvider(Integer pageId, Class<? extends IRequestablePage> pageClass, PageParameters pageParameters, Integer renderCount, String componentPath) { super(pageId, pageClass, pageParameters, renderCount); setComponentPath(componentPath); } /** * @see PageProvider#PageProvider(Integer, Integer) * * @param pageId * @param renderCount * @param componentPath */ public PageAndComponentProvider(int pageId, Integer renderCount, String componentPath) { super(pageId, renderCount); setComponentPath(componentPath); } public PageAndComponentProvider(IRequestablePage page, IRequestableComponent component, PageParameters parameters) { super(page); Args.notNull(component, "component"); this.component = component; if (parameters != null) { setPageParameters(parameters); } } /** * @see org.apache.wicket.core.request.handler.IPageAndComponentProvider#getComponent() */ @Override public IRequestableComponent getComponent() { if (component == null) { IRequestablePage page = getPageInstance(); component = page.get(componentPath); if (component == null) { /* * on stateless pages it is possible that the component may not yet exist because it * couldve been created in one of the lifecycle callbacks of this page. Lets invoke * the callbacks to give the page a chance to create the missing component. */ // make sure this page instance was just created so the page can be stateless if (page.isPageStateless()) { Page p = (Page)page; p.internalInitialize(); p.internalPrepareForRender(false); component = page.get(componentPath); } } } if (component == null) { throw new ComponentNotFoundException("Could not find component '" + componentPath + "' on page '" + getPageClass()); } return component; } /** * @see org.apache.wicket.core.request.handler.IPageAndComponentProvider#getComponentPath() */ @Override public String getComponentPath() { if (componentPath != null) { return componentPath; } else { return component.getPageRelativePath(); } } /** * * @param componentPath */ private void setComponentPath(String componentPath) { Args.notNull(componentPath, "componentPath"); this.componentPath = componentPath; } }
wicket-core/src/main/java/org/apache/wicket/core/request/handler/PageAndComponentProvider.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.wicket.core.request.handler; import org.apache.wicket.Page; import org.apache.wicket.request.component.IRequestableComponent; import org.apache.wicket.request.component.IRequestablePage; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.util.lang.Args; /** * Extension of {@link PageProvider} that is also capable of providing a Component belonging to the * page. * * @see PageProvider * * @author Matej Knopp */ public class PageAndComponentProvider extends PageProvider implements IPageAndComponentProvider { private IRequestableComponent component; private String componentPath; /** * @see PageProvider#PageProvider(IRequestablePage) * * @param page * @param componentPath */ public PageAndComponentProvider(IRequestablePage page, String componentPath) { super(page); setComponentPath(componentPath); } /** * @see PageProvider#PageProvider(IRequestablePage) * * @param page * @param component */ public PageAndComponentProvider(IRequestablePage page, IRequestableComponent component) { super(page); Args.notNull(component, "component"); this.component = component; } /** * @see PageProvider#PageProvider(Class, PageParameters) * * @param pageClass * @param pageParameters * @param componentPath */ public PageAndComponentProvider(Class<? extends IRequestablePage> pageClass, PageParameters pageParameters, String componentPath) { super(pageClass, pageParameters); setComponentPath(componentPath); } /** * @see PageProvider#PageProvider(Class) * * @param pageClass * @param componentPath */ public PageAndComponentProvider(Class<? extends IRequestablePage> pageClass, String componentPath) { super(pageClass); setComponentPath(componentPath); } /** * @see PageProvider#PageProvider(int, Class, Integer) * * @param pageId * @param pageClass * @param renderCount * @param componentPath */ public PageAndComponentProvider(int pageId, Class<? extends IRequestablePage> pageClass, Integer renderCount, String componentPath) { super(pageId, pageClass, renderCount); setComponentPath(componentPath); } /** * @see PageProvider#PageProvider(int, Class, PageParameters, Integer) * * @param pageId * @param pageClass * @param pageParameters * @param renderCount * @param componentPath */ public PageAndComponentProvider(Integer pageId, Class<? extends IRequestablePage> pageClass, PageParameters pageParameters, Integer renderCount, String componentPath) { super(pageId, pageClass, pageParameters, renderCount); setComponentPath(componentPath); } /** * @see PageProvider#PageProvider(Integer, Integer) * * @param pageId * @param renderCount * @param componentPath */ public PageAndComponentProvider(int pageId, Integer renderCount, String componentPath) { super(pageId, renderCount); setComponentPath(componentPath); } public PageAndComponentProvider(IRequestablePage page, IRequestableComponent component, PageParameters parameters) { super(page); Args.notNull(component, "component"); this.component = component; if (parameters != null) { setPageParameters(parameters); } } /** * @see org.apache.wicket.core.request.handler.IPageAndComponentProvider#getComponent() */ @Override public IRequestableComponent getComponent() { if (component == null) { IRequestablePage page = getPageInstance(); component = page.get(componentPath); if (component == null) { /* * on stateless pages it is possible that the component may not yet exist because it * couldve been created in one of the lifecycle callbacks of this page. Lets invoke * the callbacks to give the page a chance to create the missing component. */ // make sure this page instance was just created so the page can be stateless if (page.isPageStateless()) { Page p = (Page)page; p.internalInitialize(); p.internalPrepareForRender(false); component = page.get(componentPath); } } } if (component == null) { throw new ComponentNotFoundException("Could not find component '" + componentPath + "' on page '" + getPageClass()); } return component; } /** * @see org.apache.wicket.core.request.handler.IPageAndComponentProvider#getComponentPath() */ @Override public String getComponentPath() { if (componentPath != null) { return componentPath; } else { return component.getPageRelativePath(); } } /** * * @param componentPath */ private void setComponentPath(String componentPath) { Args.notNull(componentPath, "componentPath"); this.componentPath = componentPath; } }
Fix Javadoc error (cherry picked from commit f0eb015745d387f8051b12acf051705eea4e31c9)
wicket-core/src/main/java/org/apache/wicket/core/request/handler/PageAndComponentProvider.java
Fix Javadoc error
<ide><path>icket-core/src/main/java/org/apache/wicket/core/request/handler/PageAndComponentProvider.java <ide> } <ide> <ide> /** <del> * @see PageProvider#PageProvider(int, Class, Integer) <add> * @see PageProvider#PageProvider(Integer, Class, Integer) <ide> * <ide> * @param pageId <ide> * @param pageClass
Java
agpl-3.0
error: pathspec 'src/test/java/ca/nrc/cadc/beacon/web/resources/GroupNameServerResourceTest.java' did not match any file(s) known to git
5e234fc6d607af715b9de153edb9f05449a37759
1
opencadc/vosui,opencadc/cadc-vosui,canfar/vosui,opencadc/cadc-vosui,opencadc/cadc-vosui,opencadc/vosui,canfar/vosui,hjeeves/cadc-vosui,opencadc/vosui,hjeeves/cadc-vosui,opencadc/vosui,opencadc/cadc-vosui,hjeeves/cadc-vosui,hjeeves/cadc-vosui
package ca.nrc.cadc.beacon.web.resources; import ca.nrc.cadc.reg.client.RegistryClient; import ca.nrc.cadc.vos.ContainerNode; import ca.nrc.cadc.vos.LinkNode; import ca.nrc.cadc.vos.VOSURI; import org.json.JSONObject; import org.junit.Test; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Status; import org.restlet.ext.json.JsonRepresentation; import org.restlet.representation.Representation; import javax.servlet.ServletContext; import java.io.IOException; import java.net.URI; import java.security.PrivilegedExceptionAction; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.easymock.EasyMock.*; import static org.easymock.EasyMock.verify; /** * Created by hjeeves on 2017-02-07. */ public class GroupNameServerResourceTest extends AbstractServerResourceTest<GroupNameServerResource> { @Test public void getGroupNames() throws Exception { expect(mockServletContext.getContextPath()).andReturn("/teststorage").once(); // mockResponse.redirectTemporary( // "/servletpath/list/other/dir/my/dir"); // expectLastCall().once(); // // final JSONObject sourceJSON = new JSONObject("{\"link_name\":\"MY_LINK\"," // + "\"link_url\":\"http://gohere.com/to/see\"}"); // final JsonRepresentation payload = new JsonRepresentation(sourceJSON); final Map<String, Object> attributes = new HashMap<>(); // attributes.put(VOSpaceApplication.GMS_SERVICE_PROPERTY_KEY, "curr/dir/MY_LINK"); // mockResponse.setStatus(Status.SUCCESS_CREATED); // expectLastCall().once(); // replay(mockVOSpaceClient, mockServletContext, mockResponse); testSubject = new GroupNameServerResource() { @Override ServletContext getServletContext() { return mockServletContext; } @Override RegistryClient getRegistryClient() { return mockRegistryClient; } /** * Returns the request attributes. * * @return The request attributes. * @see Request#getAttributes() */ @Override public Map<String, Object> getRequestAttributes() { return attributes; } /** * Returns the handled response. * * @return The handled response. */ @Override public Response getResponse() { return mockResponse; } }; // Representation groupNames = testSubject.getGroupNames(); // verify(mockVOSpaceClient, mockServletContext, mockResponse); }; }
src/test/java/ca/nrc/cadc/beacon/web/resources/GroupNameServerResourceTest.java
s2041, t7762 initial commit for browser test
src/test/java/ca/nrc/cadc/beacon/web/resources/GroupNameServerResourceTest.java
s2041, t7762 initial commit for browser test
<ide><path>rc/test/java/ca/nrc/cadc/beacon/web/resources/GroupNameServerResourceTest.java <add>package ca.nrc.cadc.beacon.web.resources; <add> <add>import ca.nrc.cadc.reg.client.RegistryClient; <add>import ca.nrc.cadc.vos.ContainerNode; <add>import ca.nrc.cadc.vos.LinkNode; <add>import ca.nrc.cadc.vos.VOSURI; <add>import org.json.JSONObject; <add>import org.junit.Test; <add>import org.restlet.Request; <add>import org.restlet.Response; <add>import org.restlet.data.Status; <add>import org.restlet.ext.json.JsonRepresentation; <add>import org.restlet.representation.Representation; <add> <add>import javax.servlet.ServletContext; <add>import java.io.IOException; <add>import java.net.URI; <add>import java.security.PrivilegedExceptionAction; <add>import java.util.HashMap; <add>import java.util.List; <add>import java.util.Map; <add> <add>import static org.easymock.EasyMock.*; <add>import static org.easymock.EasyMock.verify; <add> <add>/** <add> * Created by hjeeves on 2017-02-07. <add> */ <add>public class GroupNameServerResourceTest <add> extends AbstractServerResourceTest<GroupNameServerResource> { <add> @Test <add> public void getGroupNames() throws Exception { <add> <add> expect(mockServletContext.getContextPath()).andReturn("/teststorage").once(); <add> <add>// mockResponse.redirectTemporary( <add>// "/servletpath/list/other/dir/my/dir"); <add>// expectLastCall().once(); <add> <add>// <add>// final JSONObject sourceJSON = new JSONObject("{\"link_name\":\"MY_LINK\"," <add>// + "\"link_url\":\"http://gohere.com/to/see\"}"); <add> <add>// final JsonRepresentation payload = new JsonRepresentation(sourceJSON); <add> <add> final Map<String, Object> attributes = new HashMap<>(); <add> <add>// attributes.put(VOSpaceApplication.GMS_SERVICE_PROPERTY_KEY, "curr/dir/MY_LINK"); <add> <add>// mockResponse.setStatus(Status.SUCCESS_CREATED); <add>// expectLastCall().once(); <add> <add>// replay(mockVOSpaceClient, mockServletContext, mockResponse); <add> <add> testSubject = new GroupNameServerResource() { <add> @Override <add> ServletContext getServletContext() { <add> return mockServletContext; <add> } <add> <add> @Override <add> RegistryClient getRegistryClient() { <add> return mockRegistryClient; <add> } <add> <add> /** <add> * Returns the request attributes. <add> * <add> * @return The request attributes. <add> * @see Request#getAttributes() <add> */ <add> @Override <add> public Map<String, Object> getRequestAttributes() <add> { <add> return attributes; <add> } <add> <add> /** <add> * Returns the handled response. <add> * <add> * @return The handled response. <add> */ <add> @Override <add> public Response getResponse() { <add> return mockResponse; <add> } <add> <add> }; <add> <add>// Representation groupNames = testSubject.getGroupNames(); <add> <add>// verify(mockVOSpaceClient, mockServletContext, mockResponse); <add> }; <add>} <add>
Java
apache-2.0
decce3a1209efcaf6eebbd9b8680c4343e6ccaee
0
kidaa/maven-1,mizdebsk/maven,wangyuesong0/maven,gorcz/maven,wangyuesong/maven,vedmishr/demo1,olamy/maven,trajano/maven,stephenc/maven,apache/maven,rogerchina/maven,aheritier/maven,olamy/maven,pkozelka/maven,ChristianSchulte/maven,aheritier/maven,likaiwalkman/maven,cstamas/maven,atanasenko/maven,ChristianSchulte/maven,wangyuesong/maven,mizdebsk/maven,karthikjaps/maven,dsyer/maven,lbndev/maven,stephenc/maven,keith-turner/maven,kidaa/maven-1,runepeter/maven-deploy-plugin-2.8.1,trajano/maven,stephenc/maven,lbndev/maven,apache/maven,skitt/maven,cstamas/maven,karthikjaps/maven,mizdebsk/maven,vedmishr/demo1,wangyuesong0/maven,barthel/maven,changbai1980/maven,Mounika-Chirukuri/maven,skitt/maven,njuneau/maven,Tibor17/maven,olamy/maven,pkozelka/maven,skitt/maven,likaiwalkman/maven,mcculls/maven,karthikjaps/maven,xasx/maven,wangyuesong/maven,Tibor17/maven,dsyer/maven,runepeter/maven-deploy-plugin-2.8.1,Mounika-Chirukuri/maven,Distrotech/maven,Mounika-Chirukuri/maven,keith-turner/maven,josephw/maven,rogerchina/maven,josephw/maven,xasx/maven,pkozelka/maven,kidaa/maven-1,gorcz/maven,mcculls/maven,dsyer/maven,vedmishr/demo1,xasx/maven,Distrotech/maven,changbai1980/maven,changbai1980/maven,barthel/maven,josephw/maven,apache/maven,atanasenko/maven,lbndev/maven,rogerchina/maven,njuneau/maven,atanasenko/maven,wangyuesong0/maven,trajano/maven,gorcz/maven,keith-turner/maven,mcculls/maven,njuneau/maven,barthel/maven,ChristianSchulte/maven,likaiwalkman/maven,cstamas/maven,aheritier/maven
package org.apache.maven.model.merge; /* * 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.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.maven.model.Activation; import org.apache.maven.model.Build; import org.apache.maven.model.BuildBase; import org.apache.maven.model.CiManagement; import org.apache.maven.model.ConfigurationContainer; import org.apache.maven.model.Contributor; import org.apache.maven.model.Dependency; import org.apache.maven.model.DependencyManagement; import org.apache.maven.model.DeploymentRepository; import org.apache.maven.model.Developer; import org.apache.maven.model.DistributionManagement; import org.apache.maven.model.Exclusion; import org.apache.maven.model.Extension; import org.apache.maven.model.FileSet; import org.apache.maven.model.InputLocation; import org.apache.maven.model.IssueManagement; import org.apache.maven.model.License; import org.apache.maven.model.MailingList; import org.apache.maven.model.Model; import org.apache.maven.model.ModelBase; import org.apache.maven.model.Notifier; import org.apache.maven.model.Organization; import org.apache.maven.model.Parent; import org.apache.maven.model.PatternSet; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginConfiguration; import org.apache.maven.model.PluginContainer; import org.apache.maven.model.PluginExecution; import org.apache.maven.model.PluginManagement; import org.apache.maven.model.Prerequisites; import org.apache.maven.model.Profile; import org.apache.maven.model.Relocation; import org.apache.maven.model.ReportPlugin; import org.apache.maven.model.ReportSet; import org.apache.maven.model.Reporting; import org.apache.maven.model.Repository; import org.apache.maven.model.RepositoryBase; import org.apache.maven.model.RepositoryPolicy; import org.apache.maven.model.Resource; import org.apache.maven.model.Scm; import org.apache.maven.model.Site; import org.codehaus.plexus.util.xml.Xpp3Dom; /** * This is a hand-crafted prototype of the default model merger that should eventually be generated by Modello by a new * Java plugin. * * @author Benjamin Bentmann */ public class ModelMerger { /** * Merges the specified source object into the given target object. * * @param target The target object whose existing contents should be merged with the source, must not be * <code>null</code>. * @param source The (read-only) source object that should be merged into the target object, may be * <code>null</code>. * @param sourceDominant A flag indicating whether either the target object or the source object provides the * dominant data. * @param hints A set of key-value pairs that customized merger implementations can use to carry domain-specific * information along, may be <code>null</code>. */ public void merge( Model target, Model source, boolean sourceDominant, Map<?, ?> hints ) { if ( target == null ) { throw new IllegalArgumentException( "target missing" ); } if ( source == null ) { return; } Map<Object, Object> context = new HashMap<Object, Object>(); if ( hints != null ) { context.putAll( hints ); } mergeModel( target, source, sourceDominant, context ); } protected void mergeModel( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { mergeModelBase( target, source, sourceDominant, context ); mergeModel_ModelVersion( target, source, sourceDominant, context ); mergeModel_Parent( target, source, sourceDominant, context ); mergeModel_GroupId( target, source, sourceDominant, context ); mergeModel_ArtifactId( target, source, sourceDominant, context ); mergeModel_Version( target, source, sourceDominant, context ); mergeModel_Packaging( target, source, sourceDominant, context ); mergeModel_Name( target, source, sourceDominant, context ); mergeModel_Description( target, source, sourceDominant, context ); mergeModel_Url( target, source, sourceDominant, context ); mergeModel_InceptionYear( target, source, sourceDominant, context ); mergeModel_Organization( target, source, sourceDominant, context ); mergeModel_Licenses( target, source, sourceDominant, context ); mergeModel_MailingLists( target, source, sourceDominant, context ); mergeModel_Developers( target, source, sourceDominant, context ); mergeModel_Contributors( target, source, sourceDominant, context ); mergeModel_IssueManagement( target, source, sourceDominant, context ); mergeModel_Scm( target, source, sourceDominant, context ); mergeModel_CiManagement( target, source, sourceDominant, context ); mergeModel_Prerequisites( target, source, sourceDominant, context ); mergeModel_Build( target, source, sourceDominant, context ); mergeModel_Profiles( target, source, sourceDominant, context ); } protected void mergeModel_ModelVersion( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getModelVersion(); if ( src != null ) { if ( sourceDominant || target.getModelVersion() == null ) { target.setModelVersion( src ); target.setLocation( "modelVersion", source.getLocation( "modelVersion" ) ); } } } protected void mergeModel_Parent( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { Parent src = source.getParent(); if ( src != null ) { Parent tgt = target.getParent(); if ( tgt == null ) { tgt = new Parent(); tgt.setRelativePath( null ); target.setParent( tgt ); } mergeParent( tgt, src, sourceDominant, context ); } } protected void mergeModel_GroupId( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getGroupId(); if ( src != null ) { if ( sourceDominant || target.getGroupId() == null ) { target.setGroupId( src ); target.setLocation( "groupId", source.getLocation( "groupId" ) ); } } } protected void mergeModel_ArtifactId( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getArtifactId(); if ( src != null ) { if ( sourceDominant || target.getArtifactId() == null ) { target.setArtifactId( src ); target.setLocation( "artifactId", source.getLocation( "artifactId" ) ); } } } protected void mergeModel_Version( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getVersion(); if ( src != null ) { if ( sourceDominant || target.getVersion() == null ) { target.setVersion( src ); target.setLocation( "version", source.getLocation( "version" ) ); } } } protected void mergeModel_Packaging( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getPackaging(); if ( src != null ) { if ( sourceDominant || target.getPackaging() == null ) { target.setPackaging( src ); target.setLocation( "packaging", source.getLocation( "packaging" ) ); } } } protected void mergeModel_Name( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getName(); if ( src != null ) { if ( sourceDominant || target.getName() == null ) { target.setName( src ); target.setLocation( "name", source.getLocation( "name" ) ); } } } protected void mergeModel_Description( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getDescription(); if ( src != null ) { if ( sourceDominant || target.getDescription() == null ) { target.setDescription( src ); target.setLocation( "description", source.getLocation( "description" ) ); } } } protected void mergeModel_Url( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUrl(); if ( src != null ) { if ( sourceDominant || target.getUrl() == null ) { target.setUrl( src ); target.setLocation( "url", source.getLocation( "url" ) ); } } } protected void mergeModel_InceptionYear( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getInceptionYear(); if ( src != null ) { if ( sourceDominant || target.getInceptionYear() == null ) { target.setInceptionYear( src ); target.setLocation( "inceptionYear", source.getLocation( "inceptionYear" ) ); } } } protected void mergeModel_Organization( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { Organization src = source.getOrganization(); if ( src != null ) { Organization tgt = target.getOrganization(); if ( tgt == null ) { tgt = new Organization(); target.setOrganization( tgt ); } mergeOrganization( tgt, src, sourceDominant, context ); } } protected void mergeModel_Licenses( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { List<License> src = source.getLicenses(); if ( !src.isEmpty() ) { List<License> tgt = target.getLicenses(); Map<Object, License> merged = new LinkedHashMap<Object, License>( ( src.size() + tgt.size() ) * 2 ); for ( License element : tgt ) { Object key = getLicenseKey( element ); merged.put( key, element ); } for ( License element : src ) { Object key = getLicenseKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setLicenses( new ArrayList<License>( merged.values() ) ); } } protected void mergeModel_MailingLists( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { List<MailingList> src = source.getMailingLists(); if ( !src.isEmpty() ) { List<MailingList> tgt = target.getMailingLists(); Map<Object, MailingList> merged = new LinkedHashMap<Object, MailingList>( ( src.size() + tgt.size() ) * 2 ); for ( MailingList element : tgt ) { Object key = getMailingListKey( element ); merged.put( key, element ); } for ( MailingList element : src ) { Object key = getMailingListKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setMailingLists( new ArrayList<MailingList>( merged.values() ) ); } } protected void mergeModel_Developers( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { List<Developer> src = source.getDevelopers(); if ( !src.isEmpty() ) { List<Developer> tgt = target.getDevelopers(); Map<Object, Developer> merged = new LinkedHashMap<Object, Developer>( ( src.size() + tgt.size() ) * 2 ); for ( Developer element : tgt ) { Object key = getDeveloperKey( element ); merged.put( key, element ); } for ( Developer element : src ) { Object key = getDeveloperKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setDevelopers( new ArrayList<Developer>( merged.values() ) ); } } protected void mergeModel_Contributors( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { List<Contributor> src = source.getContributors(); if ( !src.isEmpty() ) { List<Contributor> tgt = target.getContributors(); Map<Object, Contributor> merged = new LinkedHashMap<Object, Contributor>( ( src.size() + tgt.size() ) * 2 ); for ( Contributor element : tgt ) { Object key = getContributorKey( element ); merged.put( key, element ); } for ( Contributor element : src ) { Object key = getContributorKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setContributors( new ArrayList<Contributor>( merged.values() ) ); } } protected void mergeModel_IssueManagement( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { IssueManagement src = source.getIssueManagement(); if ( src != null ) { IssueManagement tgt = target.getIssueManagement(); if ( tgt == null ) { tgt = new IssueManagement(); target.setIssueManagement( tgt ); } mergeIssueManagement( tgt, src, sourceDominant, context ); } } protected void mergeModel_Scm( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { Scm src = source.getScm(); if ( src != null ) { Scm tgt = target.getScm(); if ( tgt == null ) { tgt = new Scm(); tgt.setTag( null ); target.setScm( tgt ); } mergeScm( tgt, src, sourceDominant, context ); } } protected void mergeModel_CiManagement( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { CiManagement src = source.getCiManagement(); if ( src != null ) { CiManagement tgt = target.getCiManagement(); if ( tgt == null ) { tgt = new CiManagement(); target.setCiManagement( tgt ); } mergeCiManagement( tgt, src, sourceDominant, context ); } } protected void mergeModel_Prerequisites( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { Prerequisites src = source.getPrerequisites(); if ( src != null ) { Prerequisites tgt = target.getPrerequisites(); if ( tgt == null ) { tgt = new Prerequisites(); tgt.setMaven( null ); target.setPrerequisites( tgt ); } mergePrerequisites( tgt, src, sourceDominant, context ); } } protected void mergeModel_Build( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { Build src = source.getBuild(); if ( src != null ) { Build tgt = target.getBuild(); if ( tgt == null ) { tgt = new Build(); target.setBuild( tgt ); } mergeBuild( tgt, src, sourceDominant, context ); } } protected void mergeModel_Profiles( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { List<Profile> src = source.getProfiles(); if ( !src.isEmpty() ) { List<Profile> tgt = target.getProfiles(); Map<Object, Profile> merged = new LinkedHashMap<Object, Profile>( ( src.size() + tgt.size() ) * 2 ); for ( Profile element : tgt ) { Object key = getProfileKey( element ); merged.put( key, element ); } for ( Profile element : src ) { Object key = getProfileKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setProfiles( new ArrayList<Profile>( merged.values() ) ); } } protected void mergeModelBase( ModelBase target, ModelBase source, boolean sourceDominant, Map<Object, Object> context ) { mergeModelBase_DistributionManagement( target, source, sourceDominant, context ); mergeModelBase_Modules( target, source, sourceDominant, context ); mergeModelBase_Repositories( target, source, sourceDominant, context ); mergeModelBase_PluginRepositories( target, source, sourceDominant, context ); mergeModelBase_Dependencies( target, source, sourceDominant, context ); mergeModelBase_Reporting( target, source, sourceDominant, context ); mergeModelBase_DependencyManagement( target, source, sourceDominant, context ); mergeModelBase_Properties( target, source, sourceDominant, context ); } protected void mergeModelBase_Modules( ModelBase target, ModelBase source, boolean sourceDominant, Map<Object, Object> context ) { List<String> src = source.getModules(); if ( !src.isEmpty() ) { List<String> tgt = target.getModules(); List<String> merged = new ArrayList<String>( tgt.size() + src.size() ); merged.addAll( tgt ); merged.addAll( src ); target.setModules( merged ); } } protected void mergeModelBase_Dependencies( ModelBase target, ModelBase source, boolean sourceDominant, Map<Object, Object> context ) { List<Dependency> src = source.getDependencies(); if ( !src.isEmpty() ) { List<Dependency> tgt = target.getDependencies(); Map<Object, Dependency> merged = new LinkedHashMap<Object, Dependency>( ( src.size() + tgt.size() ) * 2 ); for ( Dependency element : tgt ) { Object key = getDependencyKey( element ); merged.put( key, element ); } for ( Dependency element : src ) { Object key = getDependencyKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setDependencies( new ArrayList<Dependency>( merged.values() ) ); } } protected void mergeModelBase_Repositories( ModelBase target, ModelBase source, boolean sourceDominant, Map<Object, Object> context ) { List<Repository> src = source.getRepositories(); if ( !src.isEmpty() ) { List<Repository> tgt = target.getRepositories(); Map<Object, Repository> merged = new LinkedHashMap<Object, Repository>( ( src.size() + tgt.size() ) * 2 ); for ( Repository element : tgt ) { Object key = getRepositoryKey( element ); merged.put( key, element ); } for ( Repository element : src ) { Object key = getRepositoryKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setRepositories( new ArrayList<Repository>( merged.values() ) ); } } protected void mergeModelBase_PluginRepositories( ModelBase target, ModelBase source, boolean sourceDominant, Map<Object, Object> context ) { List<Repository> src = source.getPluginRepositories(); if ( !src.isEmpty() ) { List<Repository> tgt = target.getPluginRepositories(); Map<Object, Repository> merged = new LinkedHashMap<Object, Repository>( ( src.size() + tgt.size() ) * 2 ); for ( Repository element : tgt ) { Object key = getRepositoryKey( element ); merged.put( key, element ); } for ( Repository element : src ) { Object key = getRepositoryKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setPluginRepositories( new ArrayList<Repository>( merged.values() ) ); } } protected void mergeModelBase_DistributionManagement( ModelBase target, ModelBase source, boolean sourceDominant, Map<Object, Object> context ) { DistributionManagement src = source.getDistributionManagement(); if ( src != null ) { DistributionManagement tgt = target.getDistributionManagement(); if ( tgt == null ) { tgt = new DistributionManagement(); target.setDistributionManagement( tgt ); } mergeDistributionManagement( tgt, src, sourceDominant, context ); } } protected void mergeModelBase_Reporting( ModelBase target, ModelBase source, boolean sourceDominant, Map<Object, Object> context ) { Reporting src = source.getReporting(); if ( src != null ) { Reporting tgt = target.getReporting(); if ( tgt == null ) { tgt = new Reporting(); target.setReporting( tgt ); } mergeReporting( tgt, src, sourceDominant, context ); } } protected void mergeModelBase_DependencyManagement( ModelBase target, ModelBase source, boolean sourceDominant, Map<Object, Object> context ) { DependencyManagement src = source.getDependencyManagement(); if ( src != null ) { DependencyManagement tgt = target.getDependencyManagement(); if ( tgt == null ) { tgt = new DependencyManagement(); target.setDependencyManagement( tgt ); } mergeDependencyManagement( tgt, src, sourceDominant, context ); } } protected void mergeModelBase_Properties( ModelBase target, ModelBase source, boolean sourceDominant, Map<Object, Object> context ) { Properties merged = new Properties(); if ( sourceDominant ) { merged.putAll( target.getProperties() ); merged.putAll( source.getProperties() ); } else { merged.putAll( source.getProperties() ); merged.putAll( target.getProperties() ); } target.setProperties( merged ); target.setLocation( "properties", InputLocation.merge( target.getLocation( "properties" ), source.getLocation( "properties" ), sourceDominant ) ); } protected void mergeDistributionManagement( DistributionManagement target, DistributionManagement source, boolean sourceDominant, Map<Object, Object> context ) { mergeDistributionManagement_Repository( target, source, sourceDominant, context ); mergeDistributionManagement_SnapshotRepository( target, source, sourceDominant, context ); mergeDistributionManagement_Site( target, source, sourceDominant, context ); mergeDistributionManagement_Status( target, source, sourceDominant, context ); mergeDistributionManagement_DownloadUrl( target, source, sourceDominant, context ); } protected void mergeDistributionManagement_Repository( DistributionManagement target, DistributionManagement source, boolean sourceDominant, Map<Object, Object> context ) { DeploymentRepository src = source.getRepository(); if ( src != null ) { DeploymentRepository tgt = target.getRepository(); if ( tgt == null ) { tgt = new DeploymentRepository(); target.setRepository( tgt ); } mergeDeploymentRepository( tgt, src, sourceDominant, context ); } } protected void mergeDistributionManagement_SnapshotRepository( DistributionManagement target, DistributionManagement source, boolean sourceDominant, Map<Object, Object> context ) { DeploymentRepository src = source.getSnapshotRepository(); if ( src != null ) { DeploymentRepository tgt = target.getSnapshotRepository(); if ( tgt == null ) { tgt = new DeploymentRepository(); target.setSnapshotRepository( tgt ); } mergeDeploymentRepository( tgt, src, sourceDominant, context ); } } protected void mergeDistributionManagement_Site( DistributionManagement target, DistributionManagement source, boolean sourceDominant, Map<Object, Object> context ) { Site src = source.getSite(); if ( src != null ) { Site tgt = target.getSite(); if ( tgt == null ) { tgt = new Site(); target.setSite( tgt ); } mergeSite( tgt, src, sourceDominant, context ); } } protected void mergeDistributionManagement_Status( DistributionManagement target, DistributionManagement source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getStatus(); if ( src != null ) { if ( sourceDominant || target.getStatus() == null ) { target.setStatus( src ); target.setLocation( "status", source.getLocation( "status" ) ); } } } protected void mergeDistributionManagement_DownloadUrl( DistributionManagement target, DistributionManagement source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getDownloadUrl(); if ( src != null ) { if ( sourceDominant || target.getDownloadUrl() == null ) { target.setDownloadUrl( src ); target.setLocation( "downloadUrl", source.getLocation( "downloadUrl" ) ); } } } protected void mergeRelocation( Relocation target, Relocation source, boolean sourceDominant, Map<Object, Object> context ) { mergeRelocation_GroupId( target, source, sourceDominant, context ); mergeRelocation_ArtifactId( target, source, sourceDominant, context ); mergeRelocation_Version( target, source, sourceDominant, context ); mergeRelocation_Message( target, source, sourceDominant, context ); } protected void mergeRelocation_GroupId( Relocation target, Relocation source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getGroupId(); if ( src != null ) { if ( sourceDominant || target.getGroupId() == null ) { target.setGroupId( src ); target.setLocation( "groupId", source.getLocation( "groupId" ) ); } } } protected void mergeRelocation_ArtifactId( Relocation target, Relocation source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getArtifactId(); if ( src != null ) { if ( sourceDominant || target.getArtifactId() == null ) { target.setArtifactId( src ); target.setLocation( "artifactId", source.getLocation( "artifactId" ) ); } } } protected void mergeRelocation_Version( Relocation target, Relocation source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getVersion(); if ( src != null ) { if ( sourceDominant || target.getVersion() == null ) { target.setVersion( src ); target.setLocation( "version", source.getLocation( "version" ) ); } } } protected void mergeRelocation_Message( Relocation target, Relocation source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getMessage(); if ( src != null ) { if ( sourceDominant || target.getMessage() == null ) { target.setMessage( src ); target.setLocation( "message", source.getLocation( "message" ) ); } } } protected void mergeDeploymentRepository( DeploymentRepository target, DeploymentRepository source, boolean sourceDominant, Map<Object, Object> context ) { mergeRepository( target, source, sourceDominant, context ); mergeDeploymentRepository_UniqueVersion( target, source, sourceDominant, context ); } protected void mergeDeploymentRepository_UniqueVersion( DeploymentRepository target, DeploymentRepository source, boolean sourceDominant, Map<Object, Object> context ) { if ( sourceDominant ) { target.setUniqueVersion( source.isUniqueVersion() ); target.setLocation( "uniqueVersion", source.getLocation( "uniqueVersion" ) ); } } protected void mergeSite( Site target, Site source, boolean sourceDominant, Map<Object, Object> context ) { mergeSite_Id( target, source, sourceDominant, context ); mergeSite_Name( target, source, sourceDominant, context ); mergeSite_Url( target, source, sourceDominant, context ); } protected void mergeSite_Id( Site target, Site source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getId(); if ( src != null ) { if ( sourceDominant || target.getId() == null ) { target.setId( src ); target.setLocation( "id", source.getLocation( "id" ) ); } } } protected void mergeSite_Name( Site target, Site source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getName(); if ( src != null ) { if ( sourceDominant || target.getName() == null ) { target.setName( src ); target.setLocation( "name", source.getLocation( "name" ) ); } } } protected void mergeSite_Url( Site target, Site source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUrl(); if ( src != null ) { if ( sourceDominant || target.getUrl() == null ) { target.setUrl( src ); target.setLocation( "url", source.getLocation( "url" ) ); } } } protected void mergeRepository( Repository target, Repository source, boolean sourceDominant, Map<Object, Object> context ) { mergeRepositoryBase( target, source, sourceDominant, context ); mergeRepository_Releases( target, source, sourceDominant, context ); mergeRepository_Snapshots( target, source, sourceDominant, context ); } protected void mergeRepository_Releases( Repository target, Repository source, boolean sourceDominant, Map<Object, Object> context ) { RepositoryPolicy src = source.getReleases(); if ( src != null ) { RepositoryPolicy tgt = target.getReleases(); if ( tgt == null ) { tgt = new RepositoryPolicy(); target.setReleases( tgt ); } mergeRepositoryPolicy( tgt, src, sourceDominant, context ); } } protected void mergeRepository_Snapshots( Repository target, Repository source, boolean sourceDominant, Map<Object, Object> context ) { RepositoryPolicy src = source.getSnapshots(); if ( src != null ) { RepositoryPolicy tgt = target.getSnapshots(); if ( tgt == null ) { tgt = new RepositoryPolicy(); target.setSnapshots( tgt ); } mergeRepositoryPolicy( tgt, src, sourceDominant, context ); } } protected void mergeRepositoryBase( RepositoryBase target, RepositoryBase source, boolean sourceDominant, Map<Object, Object> context ) { mergeRepositoryBase_Id( target, source, sourceDominant, context ); mergeRepositoryBase_Name( target, source, sourceDominant, context ); mergeRepositoryBase_Url( target, source, sourceDominant, context ); mergeRepositoryBase_Layout( target, source, sourceDominant, context ); } protected void mergeRepositoryBase_Id( RepositoryBase target, RepositoryBase source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getId(); if ( src != null ) { if ( sourceDominant || target.getId() == null ) { target.setId( src ); target.setLocation( "id", source.getLocation( "id" ) ); } } } protected void mergeRepositoryBase_Url( RepositoryBase target, RepositoryBase source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUrl(); if ( src != null ) { if ( sourceDominant || target.getUrl() == null ) { target.setUrl( src ); target.setLocation( "url", source.getLocation( "url" ) ); } } } protected void mergeRepositoryBase_Name( RepositoryBase target, RepositoryBase source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getName(); if ( src != null ) { if ( sourceDominant || target.getName() == null ) { target.setName( src ); target.setLocation( "name", source.getLocation( "name" ) ); } } } protected void mergeRepositoryBase_Layout( RepositoryBase target, RepositoryBase source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getLayout(); if ( src != null ) { if ( sourceDominant || target.getLayout() == null ) { target.setLayout( src ); target.setLocation( "layout", source.getLocation( "layout" ) ); } } } protected void mergeRepositoryPolicy( RepositoryPolicy target, RepositoryPolicy source, boolean sourceDominant, Map<Object, Object> context ) { mergeRepositoryPolicy_Enabled( target, source, sourceDominant, context ); mergeRepositoryPolicy_UpdatePolicy( target, source, sourceDominant, context ); mergeRepositoryPolicy_ChecksumPolicy( target, source, sourceDominant, context ); } protected void mergeRepositoryPolicy_Enabled( RepositoryPolicy target, RepositoryPolicy source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getEnabled(); if ( src != null ) { if ( sourceDominant || target.getEnabled() == null ) { target.setEnabled( src ); target.setLocation( "enabled", source.getLocation( "enabled" ) ); } } } protected void mergeRepositoryPolicy_UpdatePolicy( RepositoryPolicy target, RepositoryPolicy source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUpdatePolicy(); if ( src != null ) { if ( sourceDominant || target.getUpdatePolicy() == null ) { target.setUpdatePolicy( src ); target.setLocation( "updatePolicy", source.getLocation( "updatePolicy" ) ); } } } protected void mergeRepositoryPolicy_ChecksumPolicy( RepositoryPolicy target, RepositoryPolicy source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getChecksumPolicy(); if ( src != null ) { if ( sourceDominant || target.getChecksumPolicy() == null ) { target.setChecksumPolicy( src ); target.setLocation( "checksumPolicy", source.getLocation( "checksumPolicy" ) ); } } } protected void mergeDependency( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context ) { mergeDependency_GroupId( target, source, sourceDominant, context ); mergeDependency_ArtifactId( target, source, sourceDominant, context ); mergeDependency_Version( target, source, sourceDominant, context ); mergeDependency_Type( target, source, sourceDominant, context ); mergeDependency_Classifier( target, source, sourceDominant, context ); mergeDependency_Scope( target, source, sourceDominant, context ); mergeDependency_SystemPath( target, source, sourceDominant, context ); mergeDependency_Optional( target, source, sourceDominant, context ); mergeDependency_Exclusions( target, source, sourceDominant, context ); } protected void mergeDependency_GroupId( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getGroupId(); if ( src != null ) { if ( sourceDominant || target.getGroupId() == null ) { target.setGroupId( src ); target.setLocation( "groupId", source.getLocation( "groupId" ) ); } } } protected void mergeDependency_ArtifactId( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getArtifactId(); if ( src != null ) { if ( sourceDominant || target.getArtifactId() == null ) { target.setArtifactId( src ); target.setLocation( "artifactId", source.getLocation( "artifactId" ) ); } } } protected void mergeDependency_Version( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getVersion(); if ( src != null ) { if ( sourceDominant || target.getVersion() == null ) { target.setVersion( src ); target.setLocation( "version", source.getLocation( "version" ) ); } } } protected void mergeDependency_Type( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getType(); if ( src != null ) { if ( sourceDominant || target.getType() == null ) { target.setType( src ); target.setLocation( "type", source.getLocation( "type" ) ); } } } protected void mergeDependency_Classifier( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getClassifier(); if ( src != null ) { if ( sourceDominant || target.getClassifier() == null ) { target.setClassifier( src ); target.setLocation( "classifier", source.getLocation( "classifier" ) ); } } } protected void mergeDependency_Scope( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getScope(); if ( src != null ) { if ( sourceDominant || target.getScope() == null ) { target.setScope( src ); target.setLocation( "scope", source.getLocation( "scope" ) ); } } } protected void mergeDependency_SystemPath( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getSystemPath(); if ( src != null ) { if ( sourceDominant || target.getSystemPath() == null ) { target.setSystemPath( src ); target.setLocation( "systemPath", source.getLocation( "systemPath" ) ); } } } protected void mergeDependency_Optional( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getOptional(); if ( src != null ) { if ( sourceDominant || target.getOptional() == null ) { target.setOptional( src ); target.setLocation( "optional", source.getLocation( "optional" ) ); } } } protected void mergeDependency_Exclusions( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context ) { List<Exclusion> src = source.getExclusions(); if ( !src.isEmpty() ) { List<Exclusion> tgt = target.getExclusions(); Map<Object, Exclusion> merged = new LinkedHashMap<Object, Exclusion>( ( src.size() + tgt.size() ) * 2 ); for ( Exclusion element : tgt ) { Object key = getExclusionKey( element ); merged.put( key, element ); } for ( Exclusion element : src ) { Object key = getExclusionKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setExclusions( new ArrayList<Exclusion>( merged.values() ) ); } } protected void mergeExclusion( Exclusion target, Exclusion source, boolean sourceDominant, Map<Object, Object> context ) { mergeExclusion_GroupId( target, source, sourceDominant, context ); mergeExclusion_ArtifactId( target, source, sourceDominant, context ); } protected void mergeExclusion_GroupId( Exclusion target, Exclusion source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getGroupId(); if ( src != null ) { if ( sourceDominant || target.getGroupId() == null ) { target.setGroupId( src ); target.setLocation( "groupId", source.getLocation( "groupId" ) ); } } } protected void mergeExclusion_ArtifactId( Exclusion target, Exclusion source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getArtifactId(); if ( src != null ) { if ( sourceDominant || target.getArtifactId() == null ) { target.setArtifactId( src ); target.setLocation( "artifactId", source.getLocation( "artifactId" ) ); } } } protected void mergeReporting( Reporting target, Reporting source, boolean sourceDominant, Map<Object, Object> context ) { mergeReporting_OutputDirectory( target, source, sourceDominant, context ); mergeReporting_ExcludeDefaults( target, source, sourceDominant, context ); mergeReporting_Plugins( target, source, sourceDominant, context ); } protected void mergeReporting_OutputDirectory( Reporting target, Reporting source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getOutputDirectory(); if ( src != null ) { if ( sourceDominant || target.getOutputDirectory() == null ) { target.setOutputDirectory( src ); target.setLocation( "outputDirectory", source.getLocation( "outputDirectory" ) ); } } } protected void mergeReporting_ExcludeDefaults( Reporting target, Reporting source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getExcludeDefaults(); if ( src != null ) { if ( sourceDominant || target.getExcludeDefaults() == null ) { target.setExcludeDefaults( src ); target.setLocation( "excludeDefaults", source.getLocation( "excludeDefaults" ) ); } } } protected void mergeReporting_Plugins( Reporting target, Reporting source, boolean sourceDominant, Map<Object, Object> context ) { List<ReportPlugin> src = source.getPlugins(); if ( !src.isEmpty() ) { List<ReportPlugin> tgt = target.getPlugins(); Map<Object, ReportPlugin> merged = new LinkedHashMap<Object, ReportPlugin>( ( src.size() + tgt.size() ) * 2 ); for ( ReportPlugin element : tgt ) { Object key = getReportPluginKey( element ); merged.put( key, element ); } for ( ReportPlugin element : src ) { Object key = getReportPluginKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setPlugins( new ArrayList<ReportPlugin>( merged.values() ) ); } } protected void mergeReportPlugin( ReportPlugin target, ReportPlugin source, boolean sourceDominant, Map<Object, Object> context ) { mergeConfigurationContainer( target, source, sourceDominant, context ); mergeReportPlugin_GroupId( target, source, sourceDominant, context ); mergeReportPlugin_ArtifactId( target, source, sourceDominant, context ); mergeReportPlugin_Version( target, source, sourceDominant, context ); mergeReportPlugin_ReportSets( target, source, sourceDominant, context ); } protected void mergeReportPlugin_GroupId( ReportPlugin target, ReportPlugin source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getGroupId(); if ( src != null ) { if ( sourceDominant || target.getGroupId() == null ) { target.setGroupId( src ); target.setLocation( "groupId", source.getLocation( "groupId" ) ); } } } protected void mergeReportPlugin_ArtifactId( ReportPlugin target, ReportPlugin source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getArtifactId(); if ( src != null ) { if ( sourceDominant || target.getArtifactId() == null ) { target.setArtifactId( src ); target.setLocation( "artifactId", source.getLocation( "artifactId" ) ); } } } protected void mergeReportPlugin_Version( ReportPlugin target, ReportPlugin source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getVersion(); if ( src != null ) { if ( sourceDominant || target.getVersion() == null ) { target.setVersion( src ); target.setLocation( "version", source.getLocation( "version" ) ); } } } protected void mergeReportPlugin_ReportSets( ReportPlugin target, ReportPlugin source, boolean sourceDominant, Map<Object, Object> context ) { List<ReportSet> src = source.getReportSets(); if ( !src.isEmpty() ) { List<ReportSet> tgt = target.getReportSets(); Map<Object, ReportSet> merged = new LinkedHashMap<Object, ReportSet>( ( src.size() + tgt.size() ) * 2 ); for ( ReportSet element : tgt ) { Object key = getReportSetKey( element ); merged.put( key, element ); } for ( ReportSet element : src ) { Object key = getReportSetKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setReportSets( new ArrayList<ReportSet>( merged.values() ) ); } } protected void mergeReportSet( ReportSet target, ReportSet source, boolean sourceDominant, Map<Object, Object> context ) { mergeConfigurationContainer( target, source, sourceDominant, context ); mergeReportSet_Id( target, source, sourceDominant, context ); mergeReportSet_Reports( target, source, sourceDominant, context ); } protected void mergeReportSet_Id( ReportSet target, ReportSet source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getId(); if ( src != null ) { if ( sourceDominant || target.getId() == null ) { target.setId( src ); target.setLocation( "id", source.getLocation( "id" ) ); } } } protected void mergeReportSet_Reports( ReportSet target, ReportSet source, boolean sourceDominant, Map<Object, Object> context ) { List<String> src = source.getReports(); if ( !src.isEmpty() ) { List<String> tgt = target.getReports(); List<String> merged = new ArrayList<String>( tgt.size() + src.size() ); merged.addAll( tgt ); merged.addAll( src ); target.setReports( merged ); } } protected void mergeDependencyManagement( DependencyManagement target, DependencyManagement source, boolean sourceDominant, Map<Object, Object> context ) { mergeDependencyManagement_Dependencies( target, source, sourceDominant, context ); } protected void mergeDependencyManagement_Dependencies( DependencyManagement target, DependencyManagement source, boolean sourceDominant, Map<Object, Object> context ) { List<Dependency> src = source.getDependencies(); if ( !src.isEmpty() ) { List<Dependency> tgt = target.getDependencies(); Map<Object, Dependency> merged = new LinkedHashMap<Object, Dependency>( ( src.size() + tgt.size() ) * 2 ); for ( Dependency element : tgt ) { Object key = getDependencyKey( element ); merged.put( key, element ); } for ( Dependency element : src ) { Object key = getDependencyKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setDependencies( new ArrayList<Dependency>( merged.values() ) ); } } protected void mergeParent( Parent target, Parent source, boolean sourceDominant, Map<Object, Object> context ) { mergeParent_GroupId( target, source, sourceDominant, context ); mergeParent_ArtifactId( target, source, sourceDominant, context ); mergeParent_Version( target, source, sourceDominant, context ); mergeParent_RelativePath( target, source, sourceDominant, context ); } protected void mergeParent_GroupId( Parent target, Parent source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getGroupId(); if ( src != null ) { if ( sourceDominant || target.getGroupId() == null ) { target.setGroupId( src ); target.setLocation( "groupId", source.getLocation( "groupId" ) ); } } } protected void mergeParent_ArtifactId( Parent target, Parent source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getArtifactId(); if ( src != null ) { if ( sourceDominant || target.getArtifactId() == null ) { target.setArtifactId( src ); target.setLocation( "artifactId", source.getLocation( "artifactId" ) ); } } } protected void mergeParent_Version( Parent target, Parent source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getVersion(); if ( src != null ) { if ( sourceDominant || target.getVersion() == null ) { target.setVersion( src ); target.setLocation( "version", source.getLocation( "version" ) ); } } } protected void mergeParent_RelativePath( Parent target, Parent source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getRelativePath(); if ( src != null ) { if ( sourceDominant || target.getRelativePath() == null ) { target.setRelativePath( src ); target.setLocation( "relativePath", source.getLocation( "relativePath" ) ); } } } protected void mergeOrganization( Organization target, Organization source, boolean sourceDominant, Map<Object, Object> context ) { mergeOrganization_Name( target, source, sourceDominant, context ); mergeOrganization_Url( target, source, sourceDominant, context ); } protected void mergeOrganization_Name( Organization target, Organization source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getName(); if ( src != null ) { if ( sourceDominant || target.getName() == null ) { target.setName( src ); target.setLocation( "name", source.getLocation( "name" ) ); } } } protected void mergeOrganization_Url( Organization target, Organization source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUrl(); if ( src != null ) { if ( sourceDominant || target.getUrl() == null ) { target.setUrl( src ); target.setLocation( "url", source.getLocation( "url" ) ); } } } protected void mergeLicense( License target, License source, boolean sourceDominant, Map<Object, Object> context ) { mergeLicense_Name( target, source, sourceDominant, context ); mergeLicense_Url( target, source, sourceDominant, context ); mergeLicense_Distribution( target, source, sourceDominant, context ); mergeLicense_Comments( target, source, sourceDominant, context ); } protected void mergeLicense_Name( License target, License source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getName(); if ( src != null ) { if ( sourceDominant || target.getName() == null ) { target.setName( src ); target.setLocation( "name", source.getLocation( "name" ) ); } } } protected void mergeLicense_Url( License target, License source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUrl(); if ( src != null ) { if ( sourceDominant || target.getUrl() == null ) { target.setUrl( src ); target.setLocation( "url", source.getLocation( "url" ) ); } } } protected void mergeLicense_Distribution( License target, License source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getDistribution(); if ( src != null ) { if ( sourceDominant || target.getDistribution() == null ) { target.setDistribution( src ); target.setLocation( "distribution", source.getLocation( "distribution" ) ); } } } protected void mergeLicense_Comments( License target, License source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getComments(); if ( src != null ) { if ( sourceDominant || target.getComments() == null ) { target.setComments( src ); target.setLocation( "comments", source.getLocation( "comments" ) ); } } } protected void mergeMailingList( MailingList target, MailingList source, boolean sourceDominant, Map<Object, Object> context ) { mergeMailingList_Name( target, source, sourceDominant, context ); mergeMailingList_Subscribe( target, source, sourceDominant, context ); mergeMailingList_Unsubscribe( target, source, sourceDominant, context ); mergeMailingList_Post( target, source, sourceDominant, context ); mergeMailingList_OtherArchives( target, source, sourceDominant, context ); } protected void mergeMailingList_Name( MailingList target, MailingList source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getName(); if ( src != null ) { if ( sourceDominant || target.getName() == null ) { target.setName( src ); target.setLocation( "name", source.getLocation( "name" ) ); } } } protected void mergeMailingList_Subscribe( MailingList target, MailingList source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getSubscribe(); if ( src != null ) { if ( sourceDominant || target.getSubscribe() == null ) { target.setSubscribe( src ); target.setLocation( "subscribe", source.getLocation( "subscribe" ) ); } } } protected void mergeMailingList_Unsubscribe( MailingList target, MailingList source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUnsubscribe(); if ( src != null ) { if ( sourceDominant || target.getUnsubscribe() == null ) { target.setUnsubscribe( src ); target.setLocation( "unsubscribe", source.getLocation( "unsubscribe" ) ); } } } protected void mergeMailingList_Post( MailingList target, MailingList source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getPost(); if ( src != null ) { if ( sourceDominant || target.getPost() == null ) { target.setPost( src ); target.setLocation( "post", source.getLocation( "post" ) ); } } } protected void mergeMailingList_Archive( MailingList target, MailingList source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getArchive(); if ( src != null ) { if ( sourceDominant || target.getArchive() == null ) { target.setArchive( src ); target.setLocation( "archive", source.getLocation( "archive" ) ); } } } protected void mergeMailingList_OtherArchives( MailingList target, MailingList source, boolean sourceDominant, Map<Object, Object> context ) { List<String> src = source.getOtherArchives(); if ( !src.isEmpty() ) { List<String> tgt = target.getOtherArchives(); List<String> merged = new ArrayList<String>( tgt.size() + src.size() ); merged.addAll( tgt ); merged.addAll( src ); target.setOtherArchives( merged ); } } protected void mergeDeveloper( Developer target, Developer source, boolean sourceDominant, Map<Object, Object> context ) { mergeContributor( target, source, sourceDominant, context ); mergeDeveloper_Id( target, source, sourceDominant, context ); } protected void mergeDeveloper_Id( Developer target, Developer source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getId(); if ( src != null ) { if ( sourceDominant || target.getId() == null ) { target.setId( src ); target.setLocation( "id", source.getLocation( "id" ) ); } } } protected void mergeContributor( Contributor target, Contributor source, boolean sourceDominant, Map<Object, Object> context ) { mergeContributor_Name( target, source, sourceDominant, context ); mergeContributor_Email( target, source, sourceDominant, context ); mergeContributor_Url( target, source, sourceDominant, context ); mergeContributor_Organization( target, source, sourceDominant, context ); mergeContributor_OrganizationUrl( target, source, sourceDominant, context ); mergeContributor_Timezone( target, source, sourceDominant, context ); mergeContributor_Roles( target, source, sourceDominant, context ); mergeContributor_Properties( target, source, sourceDominant, context ); } protected void mergeContributor_Name( Contributor target, Contributor source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getName(); if ( src != null ) { if ( sourceDominant || target.getName() == null ) { target.setName( src ); target.setLocation( "name", source.getLocation( "name" ) ); } } } protected void mergeContributor_Email( Contributor target, Contributor source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getEmail(); if ( src != null ) { if ( sourceDominant || target.getEmail() == null ) { target.setEmail( src ); target.setLocation( "email", source.getLocation( "email" ) ); } } } protected void mergeContributor_Url( Contributor target, Contributor source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUrl(); if ( src != null ) { if ( sourceDominant || target.getUrl() == null ) { target.setUrl( src ); target.setLocation( "url", source.getLocation( "url" ) ); } } } protected void mergeContributor_Organization( Contributor target, Contributor source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getOrganization(); if ( src != null ) { if ( sourceDominant || target.getOrganization() == null ) { target.setOrganization( src ); target.setLocation( "organization", source.getLocation( "organization" ) ); } } } protected void mergeContributor_OrganizationUrl( Contributor target, Contributor source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getOrganizationUrl(); if ( src != null ) { if ( sourceDominant || target.getOrganizationUrl() == null ) { target.setOrganizationUrl( src ); target.setLocation( "organizationUrl", source.getLocation( "organizationUrl" ) ); } } } protected void mergeContributor_Timezone( Contributor target, Contributor source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getTimezone(); if ( src != null ) { if ( sourceDominant || target.getTimezone() == null ) { target.setTimezone( src ); target.setLocation( "timezone", source.getLocation( "timezone" ) ); } } } protected void mergeContributor_Roles( Contributor target, Contributor source, boolean sourceDominant, Map<Object, Object> context ) { List<String> src = source.getRoles(); if ( !src.isEmpty() ) { List<String> tgt = target.getRoles(); List<String> merged = new ArrayList<String>( tgt.size() + src.size() ); merged.addAll( tgt ); merged.addAll( src ); target.setRoles( merged ); } } protected void mergeContributor_Properties( Contributor target, Contributor source, boolean sourceDominant, Map<Object, Object> context ) { Properties merged = new Properties(); if ( sourceDominant ) { merged.putAll( target.getProperties() ); merged.putAll( source.getProperties() ); } else { merged.putAll( source.getProperties() ); merged.putAll( target.getProperties() ); } target.setProperties( merged ); target.setLocation( "properties", InputLocation.merge( target.getLocation( "properties" ), source.getLocation( "properties" ), sourceDominant ) ); } protected void mergeIssueManagement( IssueManagement target, IssueManagement source, boolean sourceDominant, Map<Object, Object> context ) { mergeIssueManagement_Url( target, source, sourceDominant, context ); mergeIssueManagement_System( target, source, sourceDominant, context ); } protected void mergeIssueManagement_System( IssueManagement target, IssueManagement source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getSystem(); if ( src != null ) { if ( sourceDominant || target.getSystem() == null ) { target.setSystem( src ); target.setLocation( "system", source.getLocation( "system" ) ); } } } protected void mergeIssueManagement_Url( IssueManagement target, IssueManagement source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUrl(); if ( src != null ) { if ( sourceDominant || target.getUrl() == null ) { target.setUrl( src ); target.setLocation( "url", source.getLocation( "url" ) ); } } } protected void mergeScm( Scm target, Scm source, boolean sourceDominant, Map<Object, Object> context ) { mergeScm_Url( target, source, sourceDominant, context ); mergeScm_Connection( target, source, sourceDominant, context ); mergeScm_DeveloperConnection( target, source, sourceDominant, context ); mergeScm_Tag( target, source, sourceDominant, context ); } protected void mergeScm_Url( Scm target, Scm source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUrl(); if ( src != null ) { if ( sourceDominant || target.getUrl() == null ) { target.setUrl( src ); target.setLocation( "url", source.getLocation( "url" ) ); } } } protected void mergeScm_Connection( Scm target, Scm source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getConnection(); if ( src != null ) { if ( sourceDominant || target.getConnection() == null ) { target.setConnection( src ); target.setLocation( "connection", source.getLocation( "connection" ) ); } } } protected void mergeScm_DeveloperConnection( Scm target, Scm source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getDeveloperConnection(); if ( src != null ) { if ( sourceDominant || target.getDeveloperConnection() == null ) { target.setDeveloperConnection( src ); target.setLocation( "developerConnection", source.getLocation( "developerConnection" ) ); } } } protected void mergeScm_Tag( Scm target, Scm source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getTag(); if ( src != null ) { if ( sourceDominant || target.getTag() == null ) { target.setTag( src ); target.setLocation( "tag", source.getLocation( "tag" ) ); } } } protected void mergeCiManagement( CiManagement target, CiManagement source, boolean sourceDominant, Map<Object, Object> context ) { mergeCiManagement_System( target, source, sourceDominant, context ); mergeCiManagement_Url( target, source, sourceDominant, context ); mergeCiManagement_Notifiers( target, source, sourceDominant, context ); } protected void mergeCiManagement_System( CiManagement target, CiManagement source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getSystem(); if ( src != null ) { if ( sourceDominant || target.getSystem() == null ) { target.setSystem( src ); target.setLocation( "system", source.getLocation( "system" ) ); } } } protected void mergeCiManagement_Url( CiManagement target, CiManagement source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUrl(); if ( src != null ) { if ( sourceDominant || target.getUrl() == null ) { target.setUrl( src ); target.setLocation( "url", source.getLocation( "url" ) ); } } } protected void mergeCiManagement_Notifiers( CiManagement target, CiManagement source, boolean sourceDominant, Map<Object, Object> context ) { List<Notifier> src = source.getNotifiers(); if ( !src.isEmpty() ) { List<Notifier> tgt = target.getNotifiers(); Map<Object, Notifier> merged = new LinkedHashMap<Object, Notifier>( ( src.size() + tgt.size() ) * 2 ); for ( Notifier element : tgt ) { Object key = getNotifierKey( element ); merged.put( key, element ); } for ( Notifier element : src ) { Object key = getNotifierKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setNotifiers( new ArrayList<Notifier>( merged.values() ) ); } } protected void mergeNotifier( Notifier target, Notifier source, boolean sourceDominant, Map<Object, Object> context ) { mergeNotifier_Type( target, source, sourceDominant, context ); mergeNotifier_Address( target, source, sourceDominant, context ); mergeNotifier_Configuration( target, source, sourceDominant, context ); mergeNotifier_SendOnError( target, source, sourceDominant, context ); mergeNotifier_SendOnFailure( target, source, sourceDominant, context ); mergeNotifier_SendOnSuccess( target, source, sourceDominant, context ); mergeNotifier_SendOnWarning( target, source, sourceDominant, context ); } protected void mergeNotifier_Type( Notifier target, Notifier source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getType(); if ( src != null ) { if ( sourceDominant || target.getType() == null ) { target.setType( src ); } } } protected void mergeNotifier_Address( Notifier target, Notifier source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getAddress(); if ( src != null ) { if ( sourceDominant || target.getAddress() == null ) { target.setAddress( src ); } } } protected void mergeNotifier_Configuration( Notifier target, Notifier source, boolean sourceDominant, Map<Object, Object> context ) { Properties merged = new Properties(); if ( sourceDominant ) { merged.putAll( target.getConfiguration() ); merged.putAll( source.getConfiguration() ); } else { merged.putAll( source.getConfiguration() ); merged.putAll( target.getConfiguration() ); } target.setConfiguration( merged ); } protected void mergeNotifier_SendOnError( Notifier target, Notifier source, boolean sourceDominant, Map<Object, Object> context ) { if ( sourceDominant ) { target.setSendOnError( source.isSendOnError() ); } } protected void mergeNotifier_SendOnFailure( Notifier target, Notifier source, boolean sourceDominant, Map<Object, Object> context ) { if ( sourceDominant ) { target.setSendOnFailure( source.isSendOnFailure() ); } } protected void mergeNotifier_SendOnSuccess( Notifier target, Notifier source, boolean sourceDominant, Map<Object, Object> context ) { if ( sourceDominant ) { target.setSendOnSuccess( source.isSendOnSuccess() ); } } protected void mergeNotifier_SendOnWarning( Notifier target, Notifier source, boolean sourceDominant, Map<Object, Object> context ) { if ( sourceDominant ) { target.setSendOnWarning( source.isSendOnWarning() ); } } protected void mergePrerequisites( Prerequisites target, Prerequisites source, boolean sourceDominant, Map<Object, Object> context ) { mergePrerequisites_Maven( target, source, sourceDominant, context ); } protected void mergePrerequisites_Maven( Prerequisites target, Prerequisites source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getMaven(); if ( src != null ) { if ( sourceDominant || target.getMaven() == null ) { target.setMaven( src ); target.setLocation( "maven", source.getLocation( "maven" ) ); } } } protected void mergeBuild( Build target, Build source, boolean sourceDominant, Map<Object, Object> context ) { mergeBuildBase( target, source, sourceDominant, context ); mergeBuild_SourceDirectory( target, source, sourceDominant, context ); mergeBuild_ScriptSourceDirectory( target, source, sourceDominant, context ); mergeBuild_TestSourceDirectory( target, source, sourceDominant, context ); mergeBuild_OutputDirectory( target, source, sourceDominant, context ); mergeBuild_TestOutputDirectory( target, source, sourceDominant, context ); mergeBuild_Extensions( target, source, sourceDominant, context ); } protected void mergeBuild_SourceDirectory( Build target, Build source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getSourceDirectory(); if ( src != null ) { if ( sourceDominant || target.getSourceDirectory() == null ) { target.setSourceDirectory( src ); target.setLocation( "sourceDirectory", source.getLocation( "sourceDirectory" ) ); } } } protected void mergeBuild_ScriptSourceDirectory( Build target, Build source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getScriptSourceDirectory(); if ( src != null ) { if ( sourceDominant || target.getScriptSourceDirectory() == null ) { target.setScriptSourceDirectory( src ); target.setLocation( "scriptSourceDirectory", source.getLocation( "scriptSourceDirectory" ) ); } } } protected void mergeBuild_TestSourceDirectory( Build target, Build source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getTestSourceDirectory(); if ( src != null ) { if ( sourceDominant || target.getTestSourceDirectory() == null ) { target.setTestSourceDirectory( src ); target.setLocation( "testSourceDirectory", source.getLocation( "testSourceDirectory" ) ); } } } protected void mergeBuild_OutputDirectory( Build target, Build source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getOutputDirectory(); if ( src != null ) { if ( sourceDominant || target.getOutputDirectory() == null ) { target.setOutputDirectory( src ); target.setLocation( "outputDirectory", source.getLocation( "outputDirectory" ) ); } } } protected void mergeBuild_TestOutputDirectory( Build target, Build source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getTestOutputDirectory(); if ( src != null ) { if ( sourceDominant || target.getTestOutputDirectory() == null ) { target.setTestOutputDirectory( src ); target.setLocation( "testOutputDirectory", source.getLocation( "testOutputDirectory" ) ); } } } protected void mergeBuild_Extensions( Build target, Build source, boolean sourceDominant, Map<Object, Object> context ) { List<Extension> src = source.getExtensions(); if ( !src.isEmpty() ) { List<Extension> tgt = target.getExtensions(); Map<Object, Extension> merged = new LinkedHashMap<Object, Extension>( ( src.size() + tgt.size() ) * 2 ); for ( Extension element : tgt ) { Object key = getExtensionKey( element ); merged.put( key, element ); } for ( Extension element : src ) { Object key = getExtensionKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setExtensions( new ArrayList<Extension>( merged.values() ) ); } } protected void mergeExtension( Extension target, Extension source, boolean sourceDominant, Map<Object, Object> context ) { mergeExtension_GroupId( target, source, sourceDominant, context ); mergeExtension_ArtifactId( target, source, sourceDominant, context ); mergeExtension_Version( target, source, sourceDominant, context ); } protected void mergeExtension_GroupId( Extension target, Extension source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getGroupId(); if ( src != null ) { if ( sourceDominant || target.getGroupId() == null ) { target.setGroupId( src ); target.setLocation( "groupId", source.getLocation( "groupId" ) ); } } } protected void mergeExtension_ArtifactId( Extension target, Extension source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getArtifactId(); if ( src != null ) { if ( sourceDominant || target.getArtifactId() == null ) { target.setArtifactId( src ); target.setLocation( "artifactId", source.getLocation( "artifactId" ) ); } } } protected void mergeExtension_Version( Extension target, Extension source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getVersion(); if ( src != null ) { if ( sourceDominant || target.getVersion() == null ) { target.setVersion( src ); target.setLocation( "version", source.getLocation( "version" ) ); } } } protected void mergeBuildBase( BuildBase target, BuildBase source, boolean sourceDominant, Map<Object, Object> context ) { mergePluginConfiguration( target, source, sourceDominant, context ); mergeBuildBase_DefaultGoal( target, source, sourceDominant, context ); mergeBuildBase_FinalName( target, source, sourceDominant, context ); mergeBuildBase_Directory( target, source, sourceDominant, context ); mergeBuildBase_Resources( target, source, sourceDominant, context ); mergeBuildBase_TestResources( target, source, sourceDominant, context ); mergeBuildBase_Filters( target, source, sourceDominant, context ); } protected void mergeBuildBase_DefaultGoal( BuildBase target, BuildBase source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getDefaultGoal(); if ( src != null ) { if ( sourceDominant || target.getDefaultGoal() == null ) { target.setDefaultGoal( src ); target.setLocation( "defaultGoal", source.getLocation( "defaultGoal" ) ); } } } protected void mergeBuildBase_Directory( BuildBase target, BuildBase source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getDirectory(); if ( src != null ) { if ( sourceDominant || target.getDirectory() == null ) { target.setDirectory( src ); target.setLocation( "directory", source.getLocation( "directory" ) ); } } } protected void mergeBuildBase_FinalName( BuildBase target, BuildBase source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getFinalName(); if ( src != null ) { if ( sourceDominant || target.getFinalName() == null ) { target.setFinalName( src ); target.setLocation( "finalName", source.getLocation( "finalName" ) ); } } } protected void mergeBuildBase_Filters( BuildBase target, BuildBase source, boolean sourceDominant, Map<Object, Object> context ) { List<String> src = source.getFilters(); if ( !src.isEmpty() ) { List<String> tgt = target.getFilters(); List<String> merged = new ArrayList<String>( tgt.size() + src.size() ); merged.addAll( tgt ); merged.addAll( src ); target.setFilters( merged ); } } protected void mergeBuildBase_Resources( BuildBase target, BuildBase source, boolean sourceDominant, Map<Object, Object> context ) { List<Resource> src = source.getResources(); if ( !src.isEmpty() ) { List<Resource> tgt = target.getResources(); Map<Object, Resource> merged = new LinkedHashMap<Object, Resource>( ( src.size() + tgt.size() ) * 2 ); for ( Resource element : tgt ) { Object key = getResourceKey( element ); merged.put( key, element ); } for ( Resource element : src ) { Object key = getResourceKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setResources( new ArrayList<Resource>( merged.values() ) ); } } protected void mergeBuildBase_TestResources( BuildBase target, BuildBase source, boolean sourceDominant, Map<Object, Object> context ) { List<Resource> src = source.getTestResources(); if ( !src.isEmpty() ) { List<Resource> tgt = target.getTestResources(); Map<Object, Resource> merged = new LinkedHashMap<Object, Resource>( ( src.size() + tgt.size() ) * 2 ); for ( Resource element : tgt ) { Object key = getResourceKey( element ); merged.put( key, element ); } for ( Resource element : src ) { Object key = getResourceKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setTestResources( new ArrayList<Resource>( merged.values() ) ); } } protected void mergePluginConfiguration( PluginConfiguration target, PluginConfiguration source, boolean sourceDominant, Map<Object, Object> context ) { mergePluginContainer( target, source, sourceDominant, context ); mergePluginConfiguration_PluginManagement( target, source, sourceDominant, context ); } protected void mergePluginConfiguration_PluginManagement( PluginConfiguration target, PluginConfiguration source, boolean sourceDominant, Map<Object, Object> context ) { PluginManagement src = source.getPluginManagement(); if ( src != null ) { PluginManagement tgt = target.getPluginManagement(); if ( tgt == null ) { tgt = new PluginManagement(); target.setPluginManagement( tgt ); } mergePluginManagement( tgt, src, sourceDominant, context ); } } protected void mergePluginContainer( PluginContainer target, PluginContainer source, boolean sourceDominant, Map<Object, Object> context ) { mergePluginContainer_Plugins( target, source, sourceDominant, context ); } protected void mergePluginContainer_Plugins( PluginContainer target, PluginContainer source, boolean sourceDominant, Map<Object, Object> context ) { List<Plugin> src = source.getPlugins(); if ( !src.isEmpty() ) { List<Plugin> tgt = target.getPlugins(); Map<Object, Plugin> merged = new LinkedHashMap<Object, Plugin>( ( src.size() + tgt.size() ) * 2 ); for ( Plugin element : tgt ) { Object key = getPluginKey( element ); merged.put( key, element ); } for ( Plugin element : src ) { Object key = getPluginKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setPlugins( new ArrayList<Plugin>( merged.values() ) ); } } protected void mergePluginManagement( PluginManagement target, PluginManagement source, boolean sourceDominant, Map<Object, Object> context ) { mergePluginContainer( target, source, sourceDominant, context ); } protected void mergePlugin( Plugin target, Plugin source, boolean sourceDominant, Map<Object, Object> context ) { mergeConfigurationContainer( target, source, sourceDominant, context ); mergePlugin_GroupId( target, source, sourceDominant, context ); mergePlugin_ArtifactId( target, source, sourceDominant, context ); mergePlugin_Version( target, source, sourceDominant, context ); mergePlugin_Extensions( target, source, sourceDominant, context ); mergePlugin_Dependencies( target, source, sourceDominant, context ); mergePlugin_Executions( target, source, sourceDominant, context ); } protected void mergePlugin_GroupId( Plugin target, Plugin source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getGroupId(); if ( src != null ) { if ( sourceDominant || target.getGroupId() == null ) { target.setGroupId( src ); target.setLocation( "groupId", source.getLocation( "groupId" ) ); } } } protected void mergePlugin_ArtifactId( Plugin target, Plugin source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getArtifactId(); if ( src != null ) { if ( sourceDominant || target.getArtifactId() == null ) { target.setArtifactId( src ); target.setLocation( "artifactId", source.getLocation( "artifactId" ) ); } } } protected void mergePlugin_Version( Plugin target, Plugin source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getVersion(); if ( src != null ) { if ( sourceDominant || target.getVersion() == null ) { target.setVersion( src ); target.setLocation( "version", source.getLocation( "version" ) ); } } } protected void mergePlugin_Extensions( Plugin target, Plugin source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getExtensions(); if ( src != null ) { if ( sourceDominant || target.getExtensions() == null ) { target.setExtensions( src ); target.setLocation( "extensions", source.getLocation( "extensions" ) ); } } } protected void mergePlugin_Dependencies( Plugin target, Plugin source, boolean sourceDominant, Map<Object, Object> context ) { List<Dependency> src = source.getDependencies(); if ( !src.isEmpty() ) { List<Dependency> tgt = target.getDependencies(); Map<Object, Dependency> merged = new LinkedHashMap<Object, Dependency>( ( src.size() + tgt.size() ) * 2 ); for ( Dependency element : tgt ) { Object key = getDependencyKey( element ); merged.put( key, element ); } for ( Dependency element : src ) { Object key = getDependencyKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setDependencies( new ArrayList<Dependency>( merged.values() ) ); } } protected void mergePlugin_Executions( Plugin target, Plugin source, boolean sourceDominant, Map<Object, Object> context ) { List<PluginExecution> src = source.getExecutions(); if ( !src.isEmpty() ) { List<PluginExecution> tgt = target.getExecutions(); Map<Object, PluginExecution> merged = new LinkedHashMap<Object, PluginExecution>( ( src.size() + tgt.size() ) * 2 ); for ( PluginExecution element : tgt ) { Object key = getPluginExecutionKey( element ); merged.put( key, element ); } for ( PluginExecution element : src ) { Object key = getPluginExecutionKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setExecutions( new ArrayList<PluginExecution>( merged.values() ) ); } } protected void mergeConfigurationContainer( ConfigurationContainer target, ConfigurationContainer source, boolean sourceDominant, Map<Object, Object> context ) { mergeConfigurationContainer_Inherited( target, source, sourceDominant, context ); mergeConfigurationContainer_Configuration( target, source, sourceDominant, context ); } protected void mergeConfigurationContainer_Inherited( ConfigurationContainer target, ConfigurationContainer source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getInherited(); if ( src != null ) { if ( sourceDominant || target.getInherited() == null ) { target.setInherited( src ); target.setLocation( "inherited", source.getLocation( "inherited" ) ); } } } protected void mergeConfigurationContainer_Configuration( ConfigurationContainer target, ConfigurationContainer source, boolean sourceDominant, Map<Object, Object> context ) { Xpp3Dom src = (Xpp3Dom) source.getConfiguration(); if ( src != null ) { Xpp3Dom tgt = (Xpp3Dom) target.getConfiguration(); if ( sourceDominant || tgt == null ) { tgt = Xpp3Dom.mergeXpp3Dom( new Xpp3Dom( src ), tgt ); } else { tgt = Xpp3Dom.mergeXpp3Dom( tgt, src ); } target.setConfiguration( tgt ); } } protected void mergePluginExecution( PluginExecution target, PluginExecution source, boolean sourceDominant, Map<Object, Object> context ) { mergeConfigurationContainer( target, source, sourceDominant, context ); mergePluginExecution_Id( target, source, sourceDominant, context ); mergePluginExecution_Phase( target, source, sourceDominant, context ); mergePluginExecution_Goals( target, source, sourceDominant, context ); } protected void mergePluginExecution_Id( PluginExecution target, PluginExecution source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getId(); if ( src != null ) { if ( sourceDominant || target.getId() == null ) { target.setId( src ); target.setLocation( "id", source.getLocation( "id" ) ); } } } protected void mergePluginExecution_Phase( PluginExecution target, PluginExecution source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getPhase(); if ( src != null ) { if ( sourceDominant || target.getPhase() == null ) { target.setPhase( src ); target.setLocation( "phase", source.getLocation( "phase" ) ); } } } protected void mergePluginExecution_Goals( PluginExecution target, PluginExecution source, boolean sourceDominant, Map<Object, Object> context ) { List<String> src = source.getGoals(); if ( !src.isEmpty() ) { List<String> tgt = target.getGoals(); List<String> merged = new ArrayList<String>( tgt.size() + src.size() ); merged.addAll( tgt ); merged.addAll( src ); target.setGoals( merged ); } } protected void mergeResource( Resource target, Resource source, boolean sourceDominant, Map<Object, Object> context ) { mergeFileSet( target, source, sourceDominant, context ); mergeResource_TargetPath( target, source, sourceDominant, context ); mergeResource_Filtering( target, source, sourceDominant, context ); mergeResource_MergeId( target, source, sourceDominant, context ); } protected void mergeResource_TargetPath( Resource target, Resource source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getTargetPath(); if ( src != null ) { if ( sourceDominant || target.getTargetPath() == null ) { target.setTargetPath( src ); target.setLocation( "targetPath", source.getLocation( "targetPath" ) ); } } } protected void mergeResource_Filtering( Resource target, Resource source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getFiltering(); if ( src != null ) { if ( sourceDominant || target.getFiltering() == null ) { target.setFiltering( src ); target.setLocation( "filtering", source.getLocation( "filtering" ) ); } } } protected void mergeResource_MergeId( Resource target, Resource source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getMergeId(); if ( src != null ) { if ( sourceDominant || target.getMergeId() == null ) { target.setMergeId( src ); } } } protected void mergeFileSet( FileSet target, FileSet source, boolean sourceDominant, Map<Object, Object> context ) { mergePatternSet( target, source, sourceDominant, context ); mergeFileSet_Directory( target, source, sourceDominant, context ); } protected void mergeFileSet_Directory( FileSet target, FileSet source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getDirectory(); if ( src != null ) { if ( sourceDominant || target.getDirectory() == null ) { target.setDirectory( src ); target.setLocation( "directory", source.getLocation( "directory" ) ); } } } protected void mergePatternSet( PatternSet target, PatternSet source, boolean sourceDominant, Map<Object, Object> context ) { mergePatternSet_Includes( target, source, sourceDominant, context ); mergePatternSet_Excludes( target, source, sourceDominant, context ); } protected void mergePatternSet_Includes( PatternSet target, PatternSet source, boolean sourceDominant, Map<Object, Object> context ) { List<String> src = source.getIncludes(); if ( !src.isEmpty() ) { List<String> tgt = target.getIncludes(); List<String> merged = new ArrayList<String>( tgt.size() + src.size() ); merged.addAll( tgt ); merged.addAll( src ); target.setIncludes( merged ); } } protected void mergePatternSet_Excludes( PatternSet target, PatternSet source, boolean sourceDominant, Map<Object, Object> context ) { List<String> src = source.getExcludes(); if ( !src.isEmpty() ) { List<String> tgt = target.getExcludes(); List<String> merged = new ArrayList<String>( tgt.size() + src.size() ); merged.addAll( tgt ); merged.addAll( src ); target.setExcludes( merged ); } } protected void mergeProfile( Profile target, Profile source, boolean sourceDominant, Map<Object, Object> context ) { mergeModelBase( target, source, sourceDominant, context ); // TODO } protected void mergeActivation( Activation target, Activation source, boolean sourceDominant, Map<Object, Object> context ) { // TODO } protected Object getDependencyKey( Dependency dependency ) { return dependency; } protected Object getPluginKey( Plugin object ) { return object; } protected Object getPluginExecutionKey( PluginExecution object ) { return object; } protected Object getReportPluginKey( ReportPlugin object ) { return object; } protected Object getReportSetKey( ReportSet object ) { return object; } protected Object getLicenseKey( License object ) { return object; } protected Object getMailingListKey( MailingList object ) { return object; } protected Object getDeveloperKey( Developer object ) { return object; } protected Object getContributorKey( Contributor object ) { return object; } protected Object getProfileKey( Profile object ) { return object; } protected Object getRepositoryKey( Repository object ) { return getRepositoryBaseKey( object ); } protected Object getRepositoryBaseKey( RepositoryBase object ) { return object; } protected Object getNotifierKey( Notifier object ) { return object; } protected Object getResourceKey( Resource object ) { return object; } protected Object getExtensionKey( Extension object ) { return object; } protected Object getExclusionKey( Exclusion object ) { return object; } }
maven-model/src/main/java/org/apache/maven/model/merge/ModelMerger.java
package org.apache.maven.model.merge; /* * 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.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.maven.model.Activation; import org.apache.maven.model.Build; import org.apache.maven.model.BuildBase; import org.apache.maven.model.CiManagement; import org.apache.maven.model.ConfigurationContainer; import org.apache.maven.model.Contributor; import org.apache.maven.model.Dependency; import org.apache.maven.model.DependencyManagement; import org.apache.maven.model.DeploymentRepository; import org.apache.maven.model.Developer; import org.apache.maven.model.DistributionManagement; import org.apache.maven.model.Exclusion; import org.apache.maven.model.Extension; import org.apache.maven.model.FileSet; import org.apache.maven.model.InputLocation; import org.apache.maven.model.IssueManagement; import org.apache.maven.model.License; import org.apache.maven.model.MailingList; import org.apache.maven.model.Model; import org.apache.maven.model.ModelBase; import org.apache.maven.model.Notifier; import org.apache.maven.model.Organization; import org.apache.maven.model.Parent; import org.apache.maven.model.PatternSet; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginConfiguration; import org.apache.maven.model.PluginContainer; import org.apache.maven.model.PluginExecution; import org.apache.maven.model.PluginManagement; import org.apache.maven.model.Prerequisites; import org.apache.maven.model.Profile; import org.apache.maven.model.Relocation; import org.apache.maven.model.ReportPlugin; import org.apache.maven.model.ReportSet; import org.apache.maven.model.Reporting; import org.apache.maven.model.Repository; import org.apache.maven.model.RepositoryBase; import org.apache.maven.model.RepositoryPolicy; import org.apache.maven.model.Resource; import org.apache.maven.model.Scm; import org.apache.maven.model.Site; import org.codehaus.plexus.util.xml.Xpp3Dom; /** * This is a hand-crafted prototype of the default model merger that should eventually be generated by Modello by a new * Java plugin. * * @author Benjamin Bentmann */ public class ModelMerger { /** * Merges the specified source object into the given target object. * * @param target The target object whose existing contents should be merged with the source, must not be * <code>null</code>. * @param source The (read-only) source object that should be merged into the target object, may be * <code>null</code>. * @param sourceDominant A flag indicating whether either the target object or the source object provides the * dominant data. * @param hints A set of key-value pairs that customized merger implementations can use to carry domain-specific * information along, may be <code>null</code>. */ public void merge( Model target, Model source, boolean sourceDominant, Map<?, ?> hints ) { if ( target == null ) { throw new IllegalArgumentException( "target missing" ); } if ( source == null ) { return; } Map<Object, Object> context = new HashMap<Object, Object>(); if ( hints != null ) { context.putAll( hints ); } mergeModel( target, source, sourceDominant, context ); } protected void mergeModel( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { mergeModelBase( target, source, sourceDominant, context ); mergeModel_ModelVersion( target, source, sourceDominant, context ); mergeModel_Parent( target, source, sourceDominant, context ); mergeModel_GroupId( target, source, sourceDominant, context ); mergeModel_ArtifactId( target, source, sourceDominant, context ); mergeModel_Version( target, source, sourceDominant, context ); mergeModel_Packaging( target, source, sourceDominant, context ); mergeModel_Name( target, source, sourceDominant, context ); mergeModel_Description( target, source, sourceDominant, context ); mergeModel_Url( target, source, sourceDominant, context ); mergeModel_InceptionYear( target, source, sourceDominant, context ); mergeModel_Organization( target, source, sourceDominant, context ); mergeModel_Licenses( target, source, sourceDominant, context ); mergeModel_MailingLists( target, source, sourceDominant, context ); mergeModel_Developers( target, source, sourceDominant, context ); mergeModel_Contributors( target, source, sourceDominant, context ); mergeModel_IssueManagement( target, source, sourceDominant, context ); mergeModel_Scm( target, source, sourceDominant, context ); mergeModel_CiManagement( target, source, sourceDominant, context ); mergeModel_Prerequisites( target, source, sourceDominant, context ); mergeModel_Build( target, source, sourceDominant, context ); mergeModel_Profiles( target, source, sourceDominant, context ); } protected void mergeModel_ModelVersion( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getModelVersion(); if ( src != null ) { if ( sourceDominant || target.getModelVersion() == null ) { target.setModelVersion( src ); target.setLocation( "modelVersion", source.getLocation( "modelVersion" ) ); } } } protected void mergeModel_Parent( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { Parent src = source.getParent(); if ( src != null ) { Parent tgt = target.getParent(); if ( tgt == null ) { tgt = new Parent(); target.setParent( tgt ); } mergeParent( tgt, src, sourceDominant, context ); } } protected void mergeModel_GroupId( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getGroupId(); if ( src != null ) { if ( sourceDominant || target.getGroupId() == null ) { target.setGroupId( src ); target.setLocation( "groupId", source.getLocation( "groupId" ) ); } } } protected void mergeModel_ArtifactId( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getArtifactId(); if ( src != null ) { if ( sourceDominant || target.getArtifactId() == null ) { target.setArtifactId( src ); target.setLocation( "artifactId", source.getLocation( "artifactId" ) ); } } } protected void mergeModel_Version( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getVersion(); if ( src != null ) { if ( sourceDominant || target.getVersion() == null ) { target.setVersion( src ); target.setLocation( "version", source.getLocation( "version" ) ); } } } protected void mergeModel_Packaging( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getPackaging(); if ( src != null ) { if ( sourceDominant || target.getPackaging() == null ) { target.setPackaging( src ); target.setLocation( "packaging", source.getLocation( "packaging" ) ); } } } protected void mergeModel_Name( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getName(); if ( src != null ) { if ( sourceDominant || target.getName() == null ) { target.setName( src ); target.setLocation( "name", source.getLocation( "name" ) ); } } } protected void mergeModel_Description( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getDescription(); if ( src != null ) { if ( sourceDominant || target.getDescription() == null ) { target.setDescription( src ); target.setLocation( "description", source.getLocation( "description" ) ); } } } protected void mergeModel_Url( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUrl(); if ( src != null ) { if ( sourceDominant || target.getUrl() == null ) { target.setUrl( src ); target.setLocation( "url", source.getLocation( "url" ) ); } } } protected void mergeModel_InceptionYear( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getInceptionYear(); if ( src != null ) { if ( sourceDominant || target.getInceptionYear() == null ) { target.setInceptionYear( src ); target.setLocation( "inceptionYear", source.getLocation( "inceptionYear" ) ); } } } protected void mergeModel_Organization( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { Organization src = source.getOrganization(); if ( src != null ) { Organization tgt = target.getOrganization(); if ( tgt == null ) { tgt = new Organization(); target.setOrganization( tgt ); } mergeOrganization( tgt, src, sourceDominant, context ); } } protected void mergeModel_Licenses( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { List<License> src = source.getLicenses(); if ( !src.isEmpty() ) { List<License> tgt = target.getLicenses(); Map<Object, License> merged = new LinkedHashMap<Object, License>( ( src.size() + tgt.size() ) * 2 ); for ( License element : tgt ) { Object key = getLicenseKey( element ); merged.put( key, element ); } for ( License element : src ) { Object key = getLicenseKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setLicenses( new ArrayList<License>( merged.values() ) ); } } protected void mergeModel_MailingLists( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { List<MailingList> src = source.getMailingLists(); if ( !src.isEmpty() ) { List<MailingList> tgt = target.getMailingLists(); Map<Object, MailingList> merged = new LinkedHashMap<Object, MailingList>( ( src.size() + tgt.size() ) * 2 ); for ( MailingList element : tgt ) { Object key = getMailingListKey( element ); merged.put( key, element ); } for ( MailingList element : src ) { Object key = getMailingListKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setMailingLists( new ArrayList<MailingList>( merged.values() ) ); } } protected void mergeModel_Developers( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { List<Developer> src = source.getDevelopers(); if ( !src.isEmpty() ) { List<Developer> tgt = target.getDevelopers(); Map<Object, Developer> merged = new LinkedHashMap<Object, Developer>( ( src.size() + tgt.size() ) * 2 ); for ( Developer element : tgt ) { Object key = getDeveloperKey( element ); merged.put( key, element ); } for ( Developer element : src ) { Object key = getDeveloperKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setDevelopers( new ArrayList<Developer>( merged.values() ) ); } } protected void mergeModel_Contributors( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { List<Contributor> src = source.getContributors(); if ( !src.isEmpty() ) { List<Contributor> tgt = target.getContributors(); Map<Object, Contributor> merged = new LinkedHashMap<Object, Contributor>( ( src.size() + tgt.size() ) * 2 ); for ( Contributor element : tgt ) { Object key = getContributorKey( element ); merged.put( key, element ); } for ( Contributor element : src ) { Object key = getContributorKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setContributors( new ArrayList<Contributor>( merged.values() ) ); } } protected void mergeModel_IssueManagement( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { IssueManagement src = source.getIssueManagement(); if ( src != null ) { IssueManagement tgt = target.getIssueManagement(); if ( tgt == null ) { tgt = new IssueManagement(); target.setIssueManagement( tgt ); } mergeIssueManagement( tgt, src, sourceDominant, context ); } } protected void mergeModel_Scm( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { Scm src = source.getScm(); if ( src != null ) { Scm tgt = target.getScm(); if ( tgt == null ) { tgt = new Scm(); target.setScm( tgt ); } mergeScm( tgt, src, sourceDominant, context ); } } protected void mergeModel_CiManagement( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { CiManagement src = source.getCiManagement(); if ( src != null ) { CiManagement tgt = target.getCiManagement(); if ( tgt == null ) { tgt = new CiManagement(); target.setCiManagement( tgt ); } mergeCiManagement( tgt, src, sourceDominant, context ); } } protected void mergeModel_Prerequisites( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { Prerequisites src = source.getPrerequisites(); if ( src != null ) { Prerequisites tgt = target.getPrerequisites(); if ( tgt == null ) { tgt = new Prerequisites(); target.setPrerequisites( tgt ); } mergePrerequisites( tgt, src, sourceDominant, context ); } } protected void mergeModel_Build( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { Build src = source.getBuild(); if ( src != null ) { Build tgt = target.getBuild(); if ( tgt == null ) { tgt = new Build(); target.setBuild( tgt ); } mergeBuild( tgt, src, sourceDominant, context ); } } protected void mergeModel_Profiles( Model target, Model source, boolean sourceDominant, Map<Object, Object> context ) { List<Profile> src = source.getProfiles(); if ( !src.isEmpty() ) { List<Profile> tgt = target.getProfiles(); Map<Object, Profile> merged = new LinkedHashMap<Object, Profile>( ( src.size() + tgt.size() ) * 2 ); for ( Profile element : tgt ) { Object key = getProfileKey( element ); merged.put( key, element ); } for ( Profile element : src ) { Object key = getProfileKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setProfiles( new ArrayList<Profile>( merged.values() ) ); } } protected void mergeModelBase( ModelBase target, ModelBase source, boolean sourceDominant, Map<Object, Object> context ) { mergeModelBase_DistributionManagement( target, source, sourceDominant, context ); mergeModelBase_Modules( target, source, sourceDominant, context ); mergeModelBase_Repositories( target, source, sourceDominant, context ); mergeModelBase_PluginRepositories( target, source, sourceDominant, context ); mergeModelBase_Dependencies( target, source, sourceDominant, context ); mergeModelBase_Reporting( target, source, sourceDominant, context ); mergeModelBase_DependencyManagement( target, source, sourceDominant, context ); mergeModelBase_Properties( target, source, sourceDominant, context ); } protected void mergeModelBase_Modules( ModelBase target, ModelBase source, boolean sourceDominant, Map<Object, Object> context ) { List<String> src = source.getModules(); if ( !src.isEmpty() ) { List<String> tgt = target.getModules(); List<String> merged = new ArrayList<String>( tgt.size() + src.size() ); merged.addAll( tgt ); merged.addAll( src ); target.setModules( merged ); } } protected void mergeModelBase_Dependencies( ModelBase target, ModelBase source, boolean sourceDominant, Map<Object, Object> context ) { List<Dependency> src = source.getDependencies(); if ( !src.isEmpty() ) { List<Dependency> tgt = target.getDependencies(); Map<Object, Dependency> merged = new LinkedHashMap<Object, Dependency>( ( src.size() + tgt.size() ) * 2 ); for ( Dependency element : tgt ) { Object key = getDependencyKey( element ); merged.put( key, element ); } for ( Dependency element : src ) { Object key = getDependencyKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setDependencies( new ArrayList<Dependency>( merged.values() ) ); } } protected void mergeModelBase_Repositories( ModelBase target, ModelBase source, boolean sourceDominant, Map<Object, Object> context ) { List<Repository> src = source.getRepositories(); if ( !src.isEmpty() ) { List<Repository> tgt = target.getRepositories(); Map<Object, Repository> merged = new LinkedHashMap<Object, Repository>( ( src.size() + tgt.size() ) * 2 ); for ( Repository element : tgt ) { Object key = getRepositoryKey( element ); merged.put( key, element ); } for ( Repository element : src ) { Object key = getRepositoryKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setRepositories( new ArrayList<Repository>( merged.values() ) ); } } protected void mergeModelBase_PluginRepositories( ModelBase target, ModelBase source, boolean sourceDominant, Map<Object, Object> context ) { List<Repository> src = source.getPluginRepositories(); if ( !src.isEmpty() ) { List<Repository> tgt = target.getPluginRepositories(); Map<Object, Repository> merged = new LinkedHashMap<Object, Repository>( ( src.size() + tgt.size() ) * 2 ); for ( Repository element : tgt ) { Object key = getRepositoryKey( element ); merged.put( key, element ); } for ( Repository element : src ) { Object key = getRepositoryKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setPluginRepositories( new ArrayList<Repository>( merged.values() ) ); } } protected void mergeModelBase_DistributionManagement( ModelBase target, ModelBase source, boolean sourceDominant, Map<Object, Object> context ) { DistributionManagement src = source.getDistributionManagement(); if ( src != null ) { DistributionManagement tgt = target.getDistributionManagement(); if ( tgt == null ) { tgt = new DistributionManagement(); target.setDistributionManagement( tgt ); } mergeDistributionManagement( tgt, src, sourceDominant, context ); } } protected void mergeModelBase_Reporting( ModelBase target, ModelBase source, boolean sourceDominant, Map<Object, Object> context ) { Reporting src = source.getReporting(); if ( src != null ) { Reporting tgt = target.getReporting(); if ( tgt == null ) { tgt = new Reporting(); target.setReporting( tgt ); } mergeReporting( tgt, src, sourceDominant, context ); } } protected void mergeModelBase_DependencyManagement( ModelBase target, ModelBase source, boolean sourceDominant, Map<Object, Object> context ) { DependencyManagement src = source.getDependencyManagement(); if ( src != null ) { DependencyManagement tgt = target.getDependencyManagement(); if ( tgt == null ) { tgt = new DependencyManagement(); target.setDependencyManagement( tgt ); } mergeDependencyManagement( tgt, src, sourceDominant, context ); } } protected void mergeModelBase_Properties( ModelBase target, ModelBase source, boolean sourceDominant, Map<Object, Object> context ) { Properties merged = new Properties(); if ( sourceDominant ) { merged.putAll( target.getProperties() ); merged.putAll( source.getProperties() ); } else { merged.putAll( source.getProperties() ); merged.putAll( target.getProperties() ); } target.setProperties( merged ); target.setLocation( "properties", InputLocation.merge( target.getLocation( "properties" ), source.getLocation( "properties" ), sourceDominant ) ); } protected void mergeDistributionManagement( DistributionManagement target, DistributionManagement source, boolean sourceDominant, Map<Object, Object> context ) { mergeDistributionManagement_Repository( target, source, sourceDominant, context ); mergeDistributionManagement_SnapshotRepository( target, source, sourceDominant, context ); mergeDistributionManagement_Site( target, source, sourceDominant, context ); mergeDistributionManagement_Status( target, source, sourceDominant, context ); mergeDistributionManagement_DownloadUrl( target, source, sourceDominant, context ); } protected void mergeDistributionManagement_Repository( DistributionManagement target, DistributionManagement source, boolean sourceDominant, Map<Object, Object> context ) { DeploymentRepository src = source.getRepository(); if ( src != null ) { DeploymentRepository tgt = target.getRepository(); if ( tgt == null ) { tgt = new DeploymentRepository(); target.setRepository( tgt ); } mergeDeploymentRepository( tgt, src, sourceDominant, context ); } } protected void mergeDistributionManagement_SnapshotRepository( DistributionManagement target, DistributionManagement source, boolean sourceDominant, Map<Object, Object> context ) { DeploymentRepository src = source.getSnapshotRepository(); if ( src != null ) { DeploymentRepository tgt = target.getSnapshotRepository(); if ( tgt == null ) { tgt = new DeploymentRepository(); target.setSnapshotRepository( tgt ); } mergeDeploymentRepository( tgt, src, sourceDominant, context ); } } protected void mergeDistributionManagement_Site( DistributionManagement target, DistributionManagement source, boolean sourceDominant, Map<Object, Object> context ) { Site src = source.getSite(); if ( src != null ) { Site tgt = target.getSite(); if ( tgt == null ) { tgt = new Site(); target.setSite( tgt ); } mergeSite( tgt, src, sourceDominant, context ); } } protected void mergeDistributionManagement_Status( DistributionManagement target, DistributionManagement source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getStatus(); if ( src != null ) { if ( sourceDominant || target.getStatus() == null ) { target.setStatus( src ); target.setLocation( "status", source.getLocation( "status" ) ); } } } protected void mergeDistributionManagement_DownloadUrl( DistributionManagement target, DistributionManagement source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getDownloadUrl(); if ( src != null ) { if ( sourceDominant || target.getDownloadUrl() == null ) { target.setDownloadUrl( src ); target.setLocation( "downloadUrl", source.getLocation( "downloadUrl" ) ); } } } protected void mergeRelocation( Relocation target, Relocation source, boolean sourceDominant, Map<Object, Object> context ) { mergeRelocation_GroupId( target, source, sourceDominant, context ); mergeRelocation_ArtifactId( target, source, sourceDominant, context ); mergeRelocation_Version( target, source, sourceDominant, context ); mergeRelocation_Message( target, source, sourceDominant, context ); } protected void mergeRelocation_GroupId( Relocation target, Relocation source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getGroupId(); if ( src != null ) { if ( sourceDominant || target.getGroupId() == null ) { target.setGroupId( src ); target.setLocation( "groupId", source.getLocation( "groupId" ) ); } } } protected void mergeRelocation_ArtifactId( Relocation target, Relocation source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getArtifactId(); if ( src != null ) { if ( sourceDominant || target.getArtifactId() == null ) { target.setArtifactId( src ); target.setLocation( "artifactId", source.getLocation( "artifactId" ) ); } } } protected void mergeRelocation_Version( Relocation target, Relocation source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getVersion(); if ( src != null ) { if ( sourceDominant || target.getVersion() == null ) { target.setVersion( src ); target.setLocation( "version", source.getLocation( "version" ) ); } } } protected void mergeRelocation_Message( Relocation target, Relocation source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getMessage(); if ( src != null ) { if ( sourceDominant || target.getMessage() == null ) { target.setMessage( src ); target.setLocation( "message", source.getLocation( "message" ) ); } } } protected void mergeDeploymentRepository( DeploymentRepository target, DeploymentRepository source, boolean sourceDominant, Map<Object, Object> context ) { mergeRepository( target, source, sourceDominant, context ); mergeDeploymentRepository_UniqueVersion( target, source, sourceDominant, context ); } protected void mergeDeploymentRepository_UniqueVersion( DeploymentRepository target, DeploymentRepository source, boolean sourceDominant, Map<Object, Object> context ) { if ( sourceDominant ) { target.setUniqueVersion( source.isUniqueVersion() ); target.setLocation( "uniqueVersion", source.getLocation( "uniqueVersion" ) ); } } protected void mergeSite( Site target, Site source, boolean sourceDominant, Map<Object, Object> context ) { mergeSite_Id( target, source, sourceDominant, context ); mergeSite_Name( target, source, sourceDominant, context ); mergeSite_Url( target, source, sourceDominant, context ); } protected void mergeSite_Id( Site target, Site source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getId(); if ( src != null ) { if ( sourceDominant || target.getId() == null ) { target.setId( src ); target.setLocation( "id", source.getLocation( "id" ) ); } } } protected void mergeSite_Name( Site target, Site source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getName(); if ( src != null ) { if ( sourceDominant || target.getName() == null ) { target.setName( src ); target.setLocation( "name", source.getLocation( "name" ) ); } } } protected void mergeSite_Url( Site target, Site source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUrl(); if ( src != null ) { if ( sourceDominant || target.getUrl() == null ) { target.setUrl( src ); target.setLocation( "url", source.getLocation( "url" ) ); } } } protected void mergeRepository( Repository target, Repository source, boolean sourceDominant, Map<Object, Object> context ) { mergeRepositoryBase( target, source, sourceDominant, context ); mergeRepository_Releases( target, source, sourceDominant, context ); mergeRepository_Snapshots( target, source, sourceDominant, context ); } protected void mergeRepository_Releases( Repository target, Repository source, boolean sourceDominant, Map<Object, Object> context ) { RepositoryPolicy src = source.getReleases(); if ( src != null ) { RepositoryPolicy tgt = target.getReleases(); if ( tgt == null ) { tgt = new RepositoryPolicy(); target.setReleases( tgt ); } mergeRepositoryPolicy( tgt, src, sourceDominant, context ); } } protected void mergeRepository_Snapshots( Repository target, Repository source, boolean sourceDominant, Map<Object, Object> context ) { RepositoryPolicy src = source.getSnapshots(); if ( src != null ) { RepositoryPolicy tgt = target.getSnapshots(); if ( tgt == null ) { tgt = new RepositoryPolicy(); target.setSnapshots( tgt ); } mergeRepositoryPolicy( tgt, src, sourceDominant, context ); } } protected void mergeRepositoryBase( RepositoryBase target, RepositoryBase source, boolean sourceDominant, Map<Object, Object> context ) { mergeRepositoryBase_Id( target, source, sourceDominant, context ); mergeRepositoryBase_Name( target, source, sourceDominant, context ); mergeRepositoryBase_Url( target, source, sourceDominant, context ); mergeRepositoryBase_Layout( target, source, sourceDominant, context ); } protected void mergeRepositoryBase_Id( RepositoryBase target, RepositoryBase source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getId(); if ( src != null ) { if ( sourceDominant || target.getId() == null ) { target.setId( src ); target.setLocation( "id", source.getLocation( "id" ) ); } } } protected void mergeRepositoryBase_Url( RepositoryBase target, RepositoryBase source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUrl(); if ( src != null ) { if ( sourceDominant || target.getUrl() == null ) { target.setUrl( src ); target.setLocation( "url", source.getLocation( "url" ) ); } } } protected void mergeRepositoryBase_Name( RepositoryBase target, RepositoryBase source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getName(); if ( src != null ) { if ( sourceDominant || target.getName() == null ) { target.setName( src ); target.setLocation( "name", source.getLocation( "name" ) ); } } } protected void mergeRepositoryBase_Layout( RepositoryBase target, RepositoryBase source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getLayout(); if ( src != null ) { if ( sourceDominant || target.getLayout() == null ) { target.setLayout( src ); target.setLocation( "layout", source.getLocation( "layout" ) ); } } } protected void mergeRepositoryPolicy( RepositoryPolicy target, RepositoryPolicy source, boolean sourceDominant, Map<Object, Object> context ) { mergeRepositoryPolicy_Enabled( target, source, sourceDominant, context ); mergeRepositoryPolicy_UpdatePolicy( target, source, sourceDominant, context ); mergeRepositoryPolicy_ChecksumPolicy( target, source, sourceDominant, context ); } protected void mergeRepositoryPolicy_Enabled( RepositoryPolicy target, RepositoryPolicy source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getEnabled(); if ( src != null ) { if ( sourceDominant || target.getEnabled() == null ) { target.setEnabled( src ); target.setLocation( "enabled", source.getLocation( "enabled" ) ); } } } protected void mergeRepositoryPolicy_UpdatePolicy( RepositoryPolicy target, RepositoryPolicy source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUpdatePolicy(); if ( src != null ) { if ( sourceDominant || target.getUpdatePolicy() == null ) { target.setUpdatePolicy( src ); target.setLocation( "updatePolicy", source.getLocation( "updatePolicy" ) ); } } } protected void mergeRepositoryPolicy_ChecksumPolicy( RepositoryPolicy target, RepositoryPolicy source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getChecksumPolicy(); if ( src != null ) { if ( sourceDominant || target.getChecksumPolicy() == null ) { target.setChecksumPolicy( src ); target.setLocation( "checksumPolicy", source.getLocation( "checksumPolicy" ) ); } } } protected void mergeDependency( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context ) { mergeDependency_GroupId( target, source, sourceDominant, context ); mergeDependency_ArtifactId( target, source, sourceDominant, context ); mergeDependency_Version( target, source, sourceDominant, context ); mergeDependency_Type( target, source, sourceDominant, context ); mergeDependency_Classifier( target, source, sourceDominant, context ); mergeDependency_Scope( target, source, sourceDominant, context ); mergeDependency_SystemPath( target, source, sourceDominant, context ); mergeDependency_Optional( target, source, sourceDominant, context ); mergeDependency_Exclusions( target, source, sourceDominant, context ); } protected void mergeDependency_GroupId( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getGroupId(); if ( src != null ) { if ( sourceDominant || target.getGroupId() == null ) { target.setGroupId( src ); target.setLocation( "groupId", source.getLocation( "groupId" ) ); } } } protected void mergeDependency_ArtifactId( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getArtifactId(); if ( src != null ) { if ( sourceDominant || target.getArtifactId() == null ) { target.setArtifactId( src ); target.setLocation( "artifactId", source.getLocation( "artifactId" ) ); } } } protected void mergeDependency_Version( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getVersion(); if ( src != null ) { if ( sourceDominant || target.getVersion() == null ) { target.setVersion( src ); target.setLocation( "version", source.getLocation( "version" ) ); } } } protected void mergeDependency_Type( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getType(); if ( src != null ) { if ( sourceDominant || target.getType() == null ) { target.setType( src ); target.setLocation( "type", source.getLocation( "type" ) ); } } } protected void mergeDependency_Classifier( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getClassifier(); if ( src != null ) { if ( sourceDominant || target.getClassifier() == null ) { target.setClassifier( src ); target.setLocation( "classifier", source.getLocation( "classifier" ) ); } } } protected void mergeDependency_Scope( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getScope(); if ( src != null ) { if ( sourceDominant || target.getScope() == null ) { target.setScope( src ); target.setLocation( "scope", source.getLocation( "scope" ) ); } } } protected void mergeDependency_SystemPath( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getSystemPath(); if ( src != null ) { if ( sourceDominant || target.getSystemPath() == null ) { target.setSystemPath( src ); target.setLocation( "systemPath", source.getLocation( "systemPath" ) ); } } } protected void mergeDependency_Optional( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getOptional(); if ( src != null ) { if ( sourceDominant || target.getOptional() == null ) { target.setOptional( src ); target.setLocation( "optional", source.getLocation( "optional" ) ); } } } protected void mergeDependency_Exclusions( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context ) { List<Exclusion> src = source.getExclusions(); if ( !src.isEmpty() ) { List<Exclusion> tgt = target.getExclusions(); Map<Object, Exclusion> merged = new LinkedHashMap<Object, Exclusion>( ( src.size() + tgt.size() ) * 2 ); for ( Exclusion element : tgt ) { Object key = getExclusionKey( element ); merged.put( key, element ); } for ( Exclusion element : src ) { Object key = getExclusionKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setExclusions( new ArrayList<Exclusion>( merged.values() ) ); } } protected void mergeExclusion( Exclusion target, Exclusion source, boolean sourceDominant, Map<Object, Object> context ) { mergeExclusion_GroupId( target, source, sourceDominant, context ); mergeExclusion_ArtifactId( target, source, sourceDominant, context ); } protected void mergeExclusion_GroupId( Exclusion target, Exclusion source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getGroupId(); if ( src != null ) { if ( sourceDominant || target.getGroupId() == null ) { target.setGroupId( src ); target.setLocation( "groupId", source.getLocation( "groupId" ) ); } } } protected void mergeExclusion_ArtifactId( Exclusion target, Exclusion source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getArtifactId(); if ( src != null ) { if ( sourceDominant || target.getArtifactId() == null ) { target.setArtifactId( src ); target.setLocation( "artifactId", source.getLocation( "artifactId" ) ); } } } protected void mergeReporting( Reporting target, Reporting source, boolean sourceDominant, Map<Object, Object> context ) { mergeReporting_OutputDirectory( target, source, sourceDominant, context ); mergeReporting_ExcludeDefaults( target, source, sourceDominant, context ); mergeReporting_Plugins( target, source, sourceDominant, context ); } protected void mergeReporting_OutputDirectory( Reporting target, Reporting source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getOutputDirectory(); if ( src != null ) { if ( sourceDominant || target.getOutputDirectory() == null ) { target.setOutputDirectory( src ); target.setLocation( "outputDirectory", source.getLocation( "outputDirectory" ) ); } } } protected void mergeReporting_ExcludeDefaults( Reporting target, Reporting source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getExcludeDefaults(); if ( src != null ) { if ( sourceDominant || target.getExcludeDefaults() == null ) { target.setExcludeDefaults( src ); target.setLocation( "excludeDefaults", source.getLocation( "excludeDefaults" ) ); } } } protected void mergeReporting_Plugins( Reporting target, Reporting source, boolean sourceDominant, Map<Object, Object> context ) { List<ReportPlugin> src = source.getPlugins(); if ( !src.isEmpty() ) { List<ReportPlugin> tgt = target.getPlugins(); Map<Object, ReportPlugin> merged = new LinkedHashMap<Object, ReportPlugin>( ( src.size() + tgt.size() ) * 2 ); for ( ReportPlugin element : tgt ) { Object key = getReportPluginKey( element ); merged.put( key, element ); } for ( ReportPlugin element : src ) { Object key = getReportPluginKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setPlugins( new ArrayList<ReportPlugin>( merged.values() ) ); } } protected void mergeReportPlugin( ReportPlugin target, ReportPlugin source, boolean sourceDominant, Map<Object, Object> context ) { mergeConfigurationContainer( target, source, sourceDominant, context ); mergeReportPlugin_GroupId( target, source, sourceDominant, context ); mergeReportPlugin_ArtifactId( target, source, sourceDominant, context ); mergeReportPlugin_Version( target, source, sourceDominant, context ); mergeReportPlugin_ReportSets( target, source, sourceDominant, context ); } protected void mergeReportPlugin_GroupId( ReportPlugin target, ReportPlugin source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getGroupId(); if ( src != null ) { if ( sourceDominant || target.getGroupId() == null ) { target.setGroupId( src ); target.setLocation( "groupId", source.getLocation( "groupId" ) ); } } } protected void mergeReportPlugin_ArtifactId( ReportPlugin target, ReportPlugin source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getArtifactId(); if ( src != null ) { if ( sourceDominant || target.getArtifactId() == null ) { target.setArtifactId( src ); target.setLocation( "artifactId", source.getLocation( "artifactId" ) ); } } } protected void mergeReportPlugin_Version( ReportPlugin target, ReportPlugin source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getVersion(); if ( src != null ) { if ( sourceDominant || target.getVersion() == null ) { target.setVersion( src ); target.setLocation( "version", source.getLocation( "version" ) ); } } } protected void mergeReportPlugin_ReportSets( ReportPlugin target, ReportPlugin source, boolean sourceDominant, Map<Object, Object> context ) { List<ReportSet> src = source.getReportSets(); if ( !src.isEmpty() ) { List<ReportSet> tgt = target.getReportSets(); Map<Object, ReportSet> merged = new LinkedHashMap<Object, ReportSet>( ( src.size() + tgt.size() ) * 2 ); for ( ReportSet element : tgt ) { Object key = getReportSetKey( element ); merged.put( key, element ); } for ( ReportSet element : src ) { Object key = getReportSetKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setReportSets( new ArrayList<ReportSet>( merged.values() ) ); } } protected void mergeReportSet( ReportSet target, ReportSet source, boolean sourceDominant, Map<Object, Object> context ) { mergeConfigurationContainer( target, source, sourceDominant, context ); mergeReportSet_Id( target, source, sourceDominant, context ); mergeReportSet_Reports( target, source, sourceDominant, context ); } protected void mergeReportSet_Id( ReportSet target, ReportSet source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getId(); if ( src != null ) { if ( sourceDominant || target.getId() == null ) { target.setId( src ); target.setLocation( "id", source.getLocation( "id" ) ); } } } protected void mergeReportSet_Reports( ReportSet target, ReportSet source, boolean sourceDominant, Map<Object, Object> context ) { List<String> src = source.getReports(); if ( !src.isEmpty() ) { List<String> tgt = target.getReports(); List<String> merged = new ArrayList<String>( tgt.size() + src.size() ); merged.addAll( tgt ); merged.addAll( src ); target.setReports( merged ); } } protected void mergeDependencyManagement( DependencyManagement target, DependencyManagement source, boolean sourceDominant, Map<Object, Object> context ) { mergeDependencyManagement_Dependencies( target, source, sourceDominant, context ); } protected void mergeDependencyManagement_Dependencies( DependencyManagement target, DependencyManagement source, boolean sourceDominant, Map<Object, Object> context ) { List<Dependency> src = source.getDependencies(); if ( !src.isEmpty() ) { List<Dependency> tgt = target.getDependencies(); Map<Object, Dependency> merged = new LinkedHashMap<Object, Dependency>( ( src.size() + tgt.size() ) * 2 ); for ( Dependency element : tgt ) { Object key = getDependencyKey( element ); merged.put( key, element ); } for ( Dependency element : src ) { Object key = getDependencyKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setDependencies( new ArrayList<Dependency>( merged.values() ) ); } } protected void mergeParent( Parent target, Parent source, boolean sourceDominant, Map<Object, Object> context ) { mergeParent_GroupId( target, source, sourceDominant, context ); mergeParent_ArtifactId( target, source, sourceDominant, context ); mergeParent_Version( target, source, sourceDominant, context ); mergeParent_RelativePath( target, source, sourceDominant, context ); } protected void mergeParent_GroupId( Parent target, Parent source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getGroupId(); if ( src != null ) { if ( sourceDominant || target.getGroupId() == null ) { target.setGroupId( src ); target.setLocation( "groupId", source.getLocation( "groupId" ) ); } } } protected void mergeParent_ArtifactId( Parent target, Parent source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getArtifactId(); if ( src != null ) { if ( sourceDominant || target.getArtifactId() == null ) { target.setArtifactId( src ); target.setLocation( "artifactId", source.getLocation( "artifactId" ) ); } } } protected void mergeParent_Version( Parent target, Parent source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getVersion(); if ( src != null ) { if ( sourceDominant || target.getVersion() == null ) { target.setVersion( src ); target.setLocation( "version", source.getLocation( "version" ) ); } } } protected void mergeParent_RelativePath( Parent target, Parent source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getRelativePath(); if ( src != null ) { if ( sourceDominant || target.getRelativePath() == null ) { target.setRelativePath( src ); target.setLocation( "relativePath", source.getLocation( "relativePath" ) ); } } } protected void mergeOrganization( Organization target, Organization source, boolean sourceDominant, Map<Object, Object> context ) { mergeOrganization_Name( target, source, sourceDominant, context ); mergeOrganization_Url( target, source, sourceDominant, context ); } protected void mergeOrganization_Name( Organization target, Organization source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getName(); if ( src != null ) { if ( sourceDominant || target.getName() == null ) { target.setName( src ); target.setLocation( "name", source.getLocation( "name" ) ); } } } protected void mergeOrganization_Url( Organization target, Organization source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUrl(); if ( src != null ) { if ( sourceDominant || target.getUrl() == null ) { target.setUrl( src ); target.setLocation( "url", source.getLocation( "url" ) ); } } } protected void mergeLicense( License target, License source, boolean sourceDominant, Map<Object, Object> context ) { mergeLicense_Name( target, source, sourceDominant, context ); mergeLicense_Url( target, source, sourceDominant, context ); mergeLicense_Distribution( target, source, sourceDominant, context ); mergeLicense_Comments( target, source, sourceDominant, context ); } protected void mergeLicense_Name( License target, License source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getName(); if ( src != null ) { if ( sourceDominant || target.getName() == null ) { target.setName( src ); target.setLocation( "name", source.getLocation( "name" ) ); } } } protected void mergeLicense_Url( License target, License source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUrl(); if ( src != null ) { if ( sourceDominant || target.getUrl() == null ) { target.setUrl( src ); target.setLocation( "url", source.getLocation( "url" ) ); } } } protected void mergeLicense_Distribution( License target, License source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getDistribution(); if ( src != null ) { if ( sourceDominant || target.getDistribution() == null ) { target.setDistribution( src ); target.setLocation( "distribution", source.getLocation( "distribution" ) ); } } } protected void mergeLicense_Comments( License target, License source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getComments(); if ( src != null ) { if ( sourceDominant || target.getComments() == null ) { target.setComments( src ); target.setLocation( "comments", source.getLocation( "comments" ) ); } } } protected void mergeMailingList( MailingList target, MailingList source, boolean sourceDominant, Map<Object, Object> context ) { mergeMailingList_Name( target, source, sourceDominant, context ); mergeMailingList_Subscribe( target, source, sourceDominant, context ); mergeMailingList_Unsubscribe( target, source, sourceDominant, context ); mergeMailingList_Post( target, source, sourceDominant, context ); mergeMailingList_OtherArchives( target, source, sourceDominant, context ); } protected void mergeMailingList_Name( MailingList target, MailingList source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getName(); if ( src != null ) { if ( sourceDominant || target.getName() == null ) { target.setName( src ); target.setLocation( "name", source.getLocation( "name" ) ); } } } protected void mergeMailingList_Subscribe( MailingList target, MailingList source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getSubscribe(); if ( src != null ) { if ( sourceDominant || target.getSubscribe() == null ) { target.setSubscribe( src ); target.setLocation( "subscribe", source.getLocation( "subscribe" ) ); } } } protected void mergeMailingList_Unsubscribe( MailingList target, MailingList source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUnsubscribe(); if ( src != null ) { if ( sourceDominant || target.getUnsubscribe() == null ) { target.setUnsubscribe( src ); target.setLocation( "unsubscribe", source.getLocation( "unsubscribe" ) ); } } } protected void mergeMailingList_Post( MailingList target, MailingList source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getPost(); if ( src != null ) { if ( sourceDominant || target.getPost() == null ) { target.setPost( src ); target.setLocation( "post", source.getLocation( "post" ) ); } } } protected void mergeMailingList_Archive( MailingList target, MailingList source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getArchive(); if ( src != null ) { if ( sourceDominant || target.getArchive() == null ) { target.setArchive( src ); target.setLocation( "archive", source.getLocation( "archive" ) ); } } } protected void mergeMailingList_OtherArchives( MailingList target, MailingList source, boolean sourceDominant, Map<Object, Object> context ) { List<String> src = source.getOtherArchives(); if ( !src.isEmpty() ) { List<String> tgt = target.getOtherArchives(); List<String> merged = new ArrayList<String>( tgt.size() + src.size() ); merged.addAll( tgt ); merged.addAll( src ); target.setOtherArchives( merged ); } } protected void mergeDeveloper( Developer target, Developer source, boolean sourceDominant, Map<Object, Object> context ) { mergeContributor( target, source, sourceDominant, context ); mergeDeveloper_Id( target, source, sourceDominant, context ); } protected void mergeDeveloper_Id( Developer target, Developer source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getId(); if ( src != null ) { if ( sourceDominant || target.getId() == null ) { target.setId( src ); target.setLocation( "id", source.getLocation( "id" ) ); } } } protected void mergeContributor( Contributor target, Contributor source, boolean sourceDominant, Map<Object, Object> context ) { mergeContributor_Name( target, source, sourceDominant, context ); mergeContributor_Email( target, source, sourceDominant, context ); mergeContributor_Url( target, source, sourceDominant, context ); mergeContributor_Organization( target, source, sourceDominant, context ); mergeContributor_OrganizationUrl( target, source, sourceDominant, context ); mergeContributor_Timezone( target, source, sourceDominant, context ); mergeContributor_Roles( target, source, sourceDominant, context ); mergeContributor_Properties( target, source, sourceDominant, context ); } protected void mergeContributor_Name( Contributor target, Contributor source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getName(); if ( src != null ) { if ( sourceDominant || target.getName() == null ) { target.setName( src ); target.setLocation( "name", source.getLocation( "name" ) ); } } } protected void mergeContributor_Email( Contributor target, Contributor source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getEmail(); if ( src != null ) { if ( sourceDominant || target.getEmail() == null ) { target.setEmail( src ); target.setLocation( "email", source.getLocation( "email" ) ); } } } protected void mergeContributor_Url( Contributor target, Contributor source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUrl(); if ( src != null ) { if ( sourceDominant || target.getUrl() == null ) { target.setUrl( src ); target.setLocation( "url", source.getLocation( "url" ) ); } } } protected void mergeContributor_Organization( Contributor target, Contributor source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getOrganization(); if ( src != null ) { if ( sourceDominant || target.getOrganization() == null ) { target.setOrganization( src ); target.setLocation( "organization", source.getLocation( "organization" ) ); } } } protected void mergeContributor_OrganizationUrl( Contributor target, Contributor source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getOrganizationUrl(); if ( src != null ) { if ( sourceDominant || target.getOrganizationUrl() == null ) { target.setOrganizationUrl( src ); target.setLocation( "organizationUrl", source.getLocation( "organizationUrl" ) ); } } } protected void mergeContributor_Timezone( Contributor target, Contributor source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getTimezone(); if ( src != null ) { if ( sourceDominant || target.getTimezone() == null ) { target.setTimezone( src ); target.setLocation( "timezone", source.getLocation( "timezone" ) ); } } } protected void mergeContributor_Roles( Contributor target, Contributor source, boolean sourceDominant, Map<Object, Object> context ) { List<String> src = source.getRoles(); if ( !src.isEmpty() ) { List<String> tgt = target.getRoles(); List<String> merged = new ArrayList<String>( tgt.size() + src.size() ); merged.addAll( tgt ); merged.addAll( src ); target.setRoles( merged ); } } protected void mergeContributor_Properties( Contributor target, Contributor source, boolean sourceDominant, Map<Object, Object> context ) { Properties merged = new Properties(); if ( sourceDominant ) { merged.putAll( target.getProperties() ); merged.putAll( source.getProperties() ); } else { merged.putAll( source.getProperties() ); merged.putAll( target.getProperties() ); } target.setProperties( merged ); target.setLocation( "properties", InputLocation.merge( target.getLocation( "properties" ), source.getLocation( "properties" ), sourceDominant ) ); } protected void mergeIssueManagement( IssueManagement target, IssueManagement source, boolean sourceDominant, Map<Object, Object> context ) { mergeIssueManagement_Url( target, source, sourceDominant, context ); mergeIssueManagement_System( target, source, sourceDominant, context ); } protected void mergeIssueManagement_System( IssueManagement target, IssueManagement source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getSystem(); if ( src != null ) { if ( sourceDominant || target.getSystem() == null ) { target.setSystem( src ); target.setLocation( "system", source.getLocation( "system" ) ); } } } protected void mergeIssueManagement_Url( IssueManagement target, IssueManagement source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUrl(); if ( src != null ) { if ( sourceDominant || target.getUrl() == null ) { target.setUrl( src ); target.setLocation( "url", source.getLocation( "url" ) ); } } } protected void mergeScm( Scm target, Scm source, boolean sourceDominant, Map<Object, Object> context ) { mergeScm_Url( target, source, sourceDominant, context ); mergeScm_Connection( target, source, sourceDominant, context ); mergeScm_DeveloperConnection( target, source, sourceDominant, context ); mergeScm_Tag( target, source, sourceDominant, context ); } protected void mergeScm_Url( Scm target, Scm source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUrl(); if ( src != null ) { if ( sourceDominant || target.getUrl() == null ) { target.setUrl( src ); target.setLocation( "url", source.getLocation( "url" ) ); } } } protected void mergeScm_Connection( Scm target, Scm source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getConnection(); if ( src != null ) { if ( sourceDominant || target.getConnection() == null ) { target.setConnection( src ); target.setLocation( "connection", source.getLocation( "connection" ) ); } } } protected void mergeScm_DeveloperConnection( Scm target, Scm source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getDeveloperConnection(); if ( src != null ) { if ( sourceDominant || target.getDeveloperConnection() == null ) { target.setDeveloperConnection( src ); target.setLocation( "developerConnection", source.getLocation( "developerConnection" ) ); } } } protected void mergeScm_Tag( Scm target, Scm source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getTag(); if ( src != null ) { if ( sourceDominant || target.getTag() == null ) { target.setTag( src ); target.setLocation( "tag", source.getLocation( "tag" ) ); } } } protected void mergeCiManagement( CiManagement target, CiManagement source, boolean sourceDominant, Map<Object, Object> context ) { mergeCiManagement_System( target, source, sourceDominant, context ); mergeCiManagement_Url( target, source, sourceDominant, context ); mergeCiManagement_Notifiers( target, source, sourceDominant, context ); } protected void mergeCiManagement_System( CiManagement target, CiManagement source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getSystem(); if ( src != null ) { if ( sourceDominant || target.getSystem() == null ) { target.setSystem( src ); target.setLocation( "system", source.getLocation( "system" ) ); } } } protected void mergeCiManagement_Url( CiManagement target, CiManagement source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getUrl(); if ( src != null ) { if ( sourceDominant || target.getUrl() == null ) { target.setUrl( src ); target.setLocation( "url", source.getLocation( "url" ) ); } } } protected void mergeCiManagement_Notifiers( CiManagement target, CiManagement source, boolean sourceDominant, Map<Object, Object> context ) { List<Notifier> src = source.getNotifiers(); if ( !src.isEmpty() ) { List<Notifier> tgt = target.getNotifiers(); Map<Object, Notifier> merged = new LinkedHashMap<Object, Notifier>( ( src.size() + tgt.size() ) * 2 ); for ( Notifier element : tgt ) { Object key = getNotifierKey( element ); merged.put( key, element ); } for ( Notifier element : src ) { Object key = getNotifierKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setNotifiers( new ArrayList<Notifier>( merged.values() ) ); } } protected void mergeNotifier( Notifier target, Notifier source, boolean sourceDominant, Map<Object, Object> context ) { mergeNotifier_Type( target, source, sourceDominant, context ); mergeNotifier_Address( target, source, sourceDominant, context ); mergeNotifier_Configuration( target, source, sourceDominant, context ); mergeNotifier_SendOnError( target, source, sourceDominant, context ); mergeNotifier_SendOnFailure( target, source, sourceDominant, context ); mergeNotifier_SendOnSuccess( target, source, sourceDominant, context ); mergeNotifier_SendOnWarning( target, source, sourceDominant, context ); } protected void mergeNotifier_Type( Notifier target, Notifier source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getType(); if ( src != null ) { if ( sourceDominant || target.getType() == null ) { target.setType( src ); } } } protected void mergeNotifier_Address( Notifier target, Notifier source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getAddress(); if ( src != null ) { if ( sourceDominant || target.getAddress() == null ) { target.setAddress( src ); } } } protected void mergeNotifier_Configuration( Notifier target, Notifier source, boolean sourceDominant, Map<Object, Object> context ) { Properties merged = new Properties(); if ( sourceDominant ) { merged.putAll( target.getConfiguration() ); merged.putAll( source.getConfiguration() ); } else { merged.putAll( source.getConfiguration() ); merged.putAll( target.getConfiguration() ); } target.setConfiguration( merged ); } protected void mergeNotifier_SendOnError( Notifier target, Notifier source, boolean sourceDominant, Map<Object, Object> context ) { if ( sourceDominant ) { target.setSendOnError( source.isSendOnError() ); } } protected void mergeNotifier_SendOnFailure( Notifier target, Notifier source, boolean sourceDominant, Map<Object, Object> context ) { if ( sourceDominant ) { target.setSendOnFailure( source.isSendOnFailure() ); } } protected void mergeNotifier_SendOnSuccess( Notifier target, Notifier source, boolean sourceDominant, Map<Object, Object> context ) { if ( sourceDominant ) { target.setSendOnSuccess( source.isSendOnSuccess() ); } } protected void mergeNotifier_SendOnWarning( Notifier target, Notifier source, boolean sourceDominant, Map<Object, Object> context ) { if ( sourceDominant ) { target.setSendOnWarning( source.isSendOnWarning() ); } } protected void mergePrerequisites( Prerequisites target, Prerequisites source, boolean sourceDominant, Map<Object, Object> context ) { mergePrerequisites_Maven( target, source, sourceDominant, context ); } protected void mergePrerequisites_Maven( Prerequisites target, Prerequisites source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getMaven(); if ( src != null ) { if ( sourceDominant || target.getMaven() == null ) { target.setMaven( src ); target.setLocation( "maven", source.getLocation( "maven" ) ); } } } protected void mergeBuild( Build target, Build source, boolean sourceDominant, Map<Object, Object> context ) { mergeBuildBase( target, source, sourceDominant, context ); mergeBuild_SourceDirectory( target, source, sourceDominant, context ); mergeBuild_ScriptSourceDirectory( target, source, sourceDominant, context ); mergeBuild_TestSourceDirectory( target, source, sourceDominant, context ); mergeBuild_OutputDirectory( target, source, sourceDominant, context ); mergeBuild_TestOutputDirectory( target, source, sourceDominant, context ); mergeBuild_Extensions( target, source, sourceDominant, context ); } protected void mergeBuild_SourceDirectory( Build target, Build source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getSourceDirectory(); if ( src != null ) { if ( sourceDominant || target.getSourceDirectory() == null ) { target.setSourceDirectory( src ); target.setLocation( "sourceDirectory", source.getLocation( "sourceDirectory" ) ); } } } protected void mergeBuild_ScriptSourceDirectory( Build target, Build source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getScriptSourceDirectory(); if ( src != null ) { if ( sourceDominant || target.getScriptSourceDirectory() == null ) { target.setScriptSourceDirectory( src ); target.setLocation( "scriptSourceDirectory", source.getLocation( "scriptSourceDirectory" ) ); } } } protected void mergeBuild_TestSourceDirectory( Build target, Build source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getTestSourceDirectory(); if ( src != null ) { if ( sourceDominant || target.getTestSourceDirectory() == null ) { target.setTestSourceDirectory( src ); target.setLocation( "testSourceDirectory", source.getLocation( "testSourceDirectory" ) ); } } } protected void mergeBuild_OutputDirectory( Build target, Build source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getOutputDirectory(); if ( src != null ) { if ( sourceDominant || target.getOutputDirectory() == null ) { target.setOutputDirectory( src ); target.setLocation( "outputDirectory", source.getLocation( "outputDirectory" ) ); } } } protected void mergeBuild_TestOutputDirectory( Build target, Build source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getTestOutputDirectory(); if ( src != null ) { if ( sourceDominant || target.getTestOutputDirectory() == null ) { target.setTestOutputDirectory( src ); target.setLocation( "testOutputDirectory", source.getLocation( "testOutputDirectory" ) ); } } } protected void mergeBuild_Extensions( Build target, Build source, boolean sourceDominant, Map<Object, Object> context ) { List<Extension> src = source.getExtensions(); if ( !src.isEmpty() ) { List<Extension> tgt = target.getExtensions(); Map<Object, Extension> merged = new LinkedHashMap<Object, Extension>( ( src.size() + tgt.size() ) * 2 ); for ( Extension element : tgt ) { Object key = getExtensionKey( element ); merged.put( key, element ); } for ( Extension element : src ) { Object key = getExtensionKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setExtensions( new ArrayList<Extension>( merged.values() ) ); } } protected void mergeExtension( Extension target, Extension source, boolean sourceDominant, Map<Object, Object> context ) { mergeExtension_GroupId( target, source, sourceDominant, context ); mergeExtension_ArtifactId( target, source, sourceDominant, context ); mergeExtension_Version( target, source, sourceDominant, context ); } protected void mergeExtension_GroupId( Extension target, Extension source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getGroupId(); if ( src != null ) { if ( sourceDominant || target.getGroupId() == null ) { target.setGroupId( src ); target.setLocation( "groupId", source.getLocation( "groupId" ) ); } } } protected void mergeExtension_ArtifactId( Extension target, Extension source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getArtifactId(); if ( src != null ) { if ( sourceDominant || target.getArtifactId() == null ) { target.setArtifactId( src ); target.setLocation( "artifactId", source.getLocation( "artifactId" ) ); } } } protected void mergeExtension_Version( Extension target, Extension source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getVersion(); if ( src != null ) { if ( sourceDominant || target.getVersion() == null ) { target.setVersion( src ); target.setLocation( "version", source.getLocation( "version" ) ); } } } protected void mergeBuildBase( BuildBase target, BuildBase source, boolean sourceDominant, Map<Object, Object> context ) { mergePluginConfiguration( target, source, sourceDominant, context ); mergeBuildBase_DefaultGoal( target, source, sourceDominant, context ); mergeBuildBase_FinalName( target, source, sourceDominant, context ); mergeBuildBase_Directory( target, source, sourceDominant, context ); mergeBuildBase_Resources( target, source, sourceDominant, context ); mergeBuildBase_TestResources( target, source, sourceDominant, context ); mergeBuildBase_Filters( target, source, sourceDominant, context ); } protected void mergeBuildBase_DefaultGoal( BuildBase target, BuildBase source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getDefaultGoal(); if ( src != null ) { if ( sourceDominant || target.getDefaultGoal() == null ) { target.setDefaultGoal( src ); target.setLocation( "defaultGoal", source.getLocation( "defaultGoal" ) ); } } } protected void mergeBuildBase_Directory( BuildBase target, BuildBase source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getDirectory(); if ( src != null ) { if ( sourceDominant || target.getDirectory() == null ) { target.setDirectory( src ); target.setLocation( "directory", source.getLocation( "directory" ) ); } } } protected void mergeBuildBase_FinalName( BuildBase target, BuildBase source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getFinalName(); if ( src != null ) { if ( sourceDominant || target.getFinalName() == null ) { target.setFinalName( src ); target.setLocation( "finalName", source.getLocation( "finalName" ) ); } } } protected void mergeBuildBase_Filters( BuildBase target, BuildBase source, boolean sourceDominant, Map<Object, Object> context ) { List<String> src = source.getFilters(); if ( !src.isEmpty() ) { List<String> tgt = target.getFilters(); List<String> merged = new ArrayList<String>( tgt.size() + src.size() ); merged.addAll( tgt ); merged.addAll( src ); target.setFilters( merged ); } } protected void mergeBuildBase_Resources( BuildBase target, BuildBase source, boolean sourceDominant, Map<Object, Object> context ) { List<Resource> src = source.getResources(); if ( !src.isEmpty() ) { List<Resource> tgt = target.getResources(); Map<Object, Resource> merged = new LinkedHashMap<Object, Resource>( ( src.size() + tgt.size() ) * 2 ); for ( Resource element : tgt ) { Object key = getResourceKey( element ); merged.put( key, element ); } for ( Resource element : src ) { Object key = getResourceKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setResources( new ArrayList<Resource>( merged.values() ) ); } } protected void mergeBuildBase_TestResources( BuildBase target, BuildBase source, boolean sourceDominant, Map<Object, Object> context ) { List<Resource> src = source.getTestResources(); if ( !src.isEmpty() ) { List<Resource> tgt = target.getTestResources(); Map<Object, Resource> merged = new LinkedHashMap<Object, Resource>( ( src.size() + tgt.size() ) * 2 ); for ( Resource element : tgt ) { Object key = getResourceKey( element ); merged.put( key, element ); } for ( Resource element : src ) { Object key = getResourceKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setTestResources( new ArrayList<Resource>( merged.values() ) ); } } protected void mergePluginConfiguration( PluginConfiguration target, PluginConfiguration source, boolean sourceDominant, Map<Object, Object> context ) { mergePluginContainer( target, source, sourceDominant, context ); mergePluginConfiguration_PluginManagement( target, source, sourceDominant, context ); } protected void mergePluginConfiguration_PluginManagement( PluginConfiguration target, PluginConfiguration source, boolean sourceDominant, Map<Object, Object> context ) { PluginManagement src = source.getPluginManagement(); if ( src != null ) { PluginManagement tgt = target.getPluginManagement(); if ( tgt == null ) { tgt = new PluginManagement(); target.setPluginManagement( tgt ); } mergePluginManagement( tgt, src, sourceDominant, context ); } } protected void mergePluginContainer( PluginContainer target, PluginContainer source, boolean sourceDominant, Map<Object, Object> context ) { mergePluginContainer_Plugins( target, source, sourceDominant, context ); } protected void mergePluginContainer_Plugins( PluginContainer target, PluginContainer source, boolean sourceDominant, Map<Object, Object> context ) { List<Plugin> src = source.getPlugins(); if ( !src.isEmpty() ) { List<Plugin> tgt = target.getPlugins(); Map<Object, Plugin> merged = new LinkedHashMap<Object, Plugin>( ( src.size() + tgt.size() ) * 2 ); for ( Plugin element : tgt ) { Object key = getPluginKey( element ); merged.put( key, element ); } for ( Plugin element : src ) { Object key = getPluginKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setPlugins( new ArrayList<Plugin>( merged.values() ) ); } } protected void mergePluginManagement( PluginManagement target, PluginManagement source, boolean sourceDominant, Map<Object, Object> context ) { mergePluginContainer( target, source, sourceDominant, context ); } protected void mergePlugin( Plugin target, Plugin source, boolean sourceDominant, Map<Object, Object> context ) { mergeConfigurationContainer( target, source, sourceDominant, context ); mergePlugin_GroupId( target, source, sourceDominant, context ); mergePlugin_ArtifactId( target, source, sourceDominant, context ); mergePlugin_Version( target, source, sourceDominant, context ); mergePlugin_Extensions( target, source, sourceDominant, context ); mergePlugin_Dependencies( target, source, sourceDominant, context ); mergePlugin_Executions( target, source, sourceDominant, context ); } protected void mergePlugin_GroupId( Plugin target, Plugin source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getGroupId(); if ( src != null ) { if ( sourceDominant || target.getGroupId() == null ) { target.setGroupId( src ); target.setLocation( "groupId", source.getLocation( "groupId" ) ); } } } protected void mergePlugin_ArtifactId( Plugin target, Plugin source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getArtifactId(); if ( src != null ) { if ( sourceDominant || target.getArtifactId() == null ) { target.setArtifactId( src ); target.setLocation( "artifactId", source.getLocation( "artifactId" ) ); } } } protected void mergePlugin_Version( Plugin target, Plugin source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getVersion(); if ( src != null ) { if ( sourceDominant || target.getVersion() == null ) { target.setVersion( src ); target.setLocation( "version", source.getLocation( "version" ) ); } } } protected void mergePlugin_Extensions( Plugin target, Plugin source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getExtensions(); if ( src != null ) { if ( sourceDominant || target.getExtensions() == null ) { target.setExtensions( src ); target.setLocation( "extensions", source.getLocation( "extensions" ) ); } } } protected void mergePlugin_Dependencies( Plugin target, Plugin source, boolean sourceDominant, Map<Object, Object> context ) { List<Dependency> src = source.getDependencies(); if ( !src.isEmpty() ) { List<Dependency> tgt = target.getDependencies(); Map<Object, Dependency> merged = new LinkedHashMap<Object, Dependency>( ( src.size() + tgt.size() ) * 2 ); for ( Dependency element : tgt ) { Object key = getDependencyKey( element ); merged.put( key, element ); } for ( Dependency element : src ) { Object key = getDependencyKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setDependencies( new ArrayList<Dependency>( merged.values() ) ); } } protected void mergePlugin_Executions( Plugin target, Plugin source, boolean sourceDominant, Map<Object, Object> context ) { List<PluginExecution> src = source.getExecutions(); if ( !src.isEmpty() ) { List<PluginExecution> tgt = target.getExecutions(); Map<Object, PluginExecution> merged = new LinkedHashMap<Object, PluginExecution>( ( src.size() + tgt.size() ) * 2 ); for ( PluginExecution element : tgt ) { Object key = getPluginExecutionKey( element ); merged.put( key, element ); } for ( PluginExecution element : src ) { Object key = getPluginExecutionKey( element ); if ( sourceDominant || !merged.containsKey( key ) ) { merged.put( key, element ); } } target.setExecutions( new ArrayList<PluginExecution>( merged.values() ) ); } } protected void mergeConfigurationContainer( ConfigurationContainer target, ConfigurationContainer source, boolean sourceDominant, Map<Object, Object> context ) { mergeConfigurationContainer_Inherited( target, source, sourceDominant, context ); mergeConfigurationContainer_Configuration( target, source, sourceDominant, context ); } protected void mergeConfigurationContainer_Inherited( ConfigurationContainer target, ConfigurationContainer source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getInherited(); if ( src != null ) { if ( sourceDominant || target.getInherited() == null ) { target.setInherited( src ); target.setLocation( "inherited", source.getLocation( "inherited" ) ); } } } protected void mergeConfigurationContainer_Configuration( ConfigurationContainer target, ConfigurationContainer source, boolean sourceDominant, Map<Object, Object> context ) { Xpp3Dom src = (Xpp3Dom) source.getConfiguration(); if ( src != null ) { Xpp3Dom tgt = (Xpp3Dom) target.getConfiguration(); if ( sourceDominant || tgt == null ) { tgt = Xpp3Dom.mergeXpp3Dom( new Xpp3Dom( src ), tgt ); } else { tgt = Xpp3Dom.mergeXpp3Dom( tgt, src ); } target.setConfiguration( tgt ); } } protected void mergePluginExecution( PluginExecution target, PluginExecution source, boolean sourceDominant, Map<Object, Object> context ) { mergeConfigurationContainer( target, source, sourceDominant, context ); mergePluginExecution_Id( target, source, sourceDominant, context ); mergePluginExecution_Phase( target, source, sourceDominant, context ); mergePluginExecution_Goals( target, source, sourceDominant, context ); } protected void mergePluginExecution_Id( PluginExecution target, PluginExecution source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getId(); if ( src != null ) { if ( sourceDominant || target.getId() == null ) { target.setId( src ); target.setLocation( "id", source.getLocation( "id" ) ); } } } protected void mergePluginExecution_Phase( PluginExecution target, PluginExecution source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getPhase(); if ( src != null ) { if ( sourceDominant || target.getPhase() == null ) { target.setPhase( src ); target.setLocation( "phase", source.getLocation( "phase" ) ); } } } protected void mergePluginExecution_Goals( PluginExecution target, PluginExecution source, boolean sourceDominant, Map<Object, Object> context ) { List<String> src = source.getGoals(); if ( !src.isEmpty() ) { List<String> tgt = target.getGoals(); List<String> merged = new ArrayList<String>( tgt.size() + src.size() ); merged.addAll( tgt ); merged.addAll( src ); target.setGoals( merged ); } } protected void mergeResource( Resource target, Resource source, boolean sourceDominant, Map<Object, Object> context ) { mergeFileSet( target, source, sourceDominant, context ); mergeResource_TargetPath( target, source, sourceDominant, context ); mergeResource_Filtering( target, source, sourceDominant, context ); mergeResource_MergeId( target, source, sourceDominant, context ); } protected void mergeResource_TargetPath( Resource target, Resource source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getTargetPath(); if ( src != null ) { if ( sourceDominant || target.getTargetPath() == null ) { target.setTargetPath( src ); target.setLocation( "targetPath", source.getLocation( "targetPath" ) ); } } } protected void mergeResource_Filtering( Resource target, Resource source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getFiltering(); if ( src != null ) { if ( sourceDominant || target.getFiltering() == null ) { target.setFiltering( src ); target.setLocation( "filtering", source.getLocation( "filtering" ) ); } } } protected void mergeResource_MergeId( Resource target, Resource source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getMergeId(); if ( src != null ) { if ( sourceDominant || target.getMergeId() == null ) { target.setMergeId( src ); } } } protected void mergeFileSet( FileSet target, FileSet source, boolean sourceDominant, Map<Object, Object> context ) { mergePatternSet( target, source, sourceDominant, context ); mergeFileSet_Directory( target, source, sourceDominant, context ); } protected void mergeFileSet_Directory( FileSet target, FileSet source, boolean sourceDominant, Map<Object, Object> context ) { String src = source.getDirectory(); if ( src != null ) { if ( sourceDominant || target.getDirectory() == null ) { target.setDirectory( src ); target.setLocation( "directory", source.getLocation( "directory" ) ); } } } protected void mergePatternSet( PatternSet target, PatternSet source, boolean sourceDominant, Map<Object, Object> context ) { mergePatternSet_Includes( target, source, sourceDominant, context ); mergePatternSet_Excludes( target, source, sourceDominant, context ); } protected void mergePatternSet_Includes( PatternSet target, PatternSet source, boolean sourceDominant, Map<Object, Object> context ) { List<String> src = source.getIncludes(); if ( !src.isEmpty() ) { List<String> tgt = target.getIncludes(); List<String> merged = new ArrayList<String>( tgt.size() + src.size() ); merged.addAll( tgt ); merged.addAll( src ); target.setIncludes( merged ); } } protected void mergePatternSet_Excludes( PatternSet target, PatternSet source, boolean sourceDominant, Map<Object, Object> context ) { List<String> src = source.getExcludes(); if ( !src.isEmpty() ) { List<String> tgt = target.getExcludes(); List<String> merged = new ArrayList<String>( tgt.size() + src.size() ); merged.addAll( tgt ); merged.addAll( src ); target.setExcludes( merged ); } } protected void mergeProfile( Profile target, Profile source, boolean sourceDominant, Map<Object, Object> context ) { mergeModelBase( target, source, sourceDominant, context ); // TODO } protected void mergeActivation( Activation target, Activation source, boolean sourceDominant, Map<Object, Object> context ) { // TODO } protected Object getDependencyKey( Dependency dependency ) { return dependency; } protected Object getPluginKey( Plugin object ) { return object; } protected Object getPluginExecutionKey( PluginExecution object ) { return object; } protected Object getReportPluginKey( ReportPlugin object ) { return object; } protected Object getReportSetKey( ReportSet object ) { return object; } protected Object getLicenseKey( License object ) { return object; } protected Object getMailingListKey( MailingList object ) { return object; } protected Object getDeveloperKey( Developer object ) { return object; } protected Object getContributorKey( Contributor object ) { return object; } protected Object getProfileKey( Profile object ) { return object; } protected Object getRepositoryKey( Repository object ) { return getRepositoryBaseKey( object ); } protected Object getRepositoryBaseKey( RepositoryBase object ) { return object; } protected Object getNotifierKey( Notifier object ) { return object; } protected Object getResourceKey( Resource object ) { return object; } protected Object getExtensionKey( Extension object ) { return object; } protected Object getExclusionKey( Exclusion object ) { return object; } }
[MNG-5153] ModelMerger omits relativ path git-svn-id: d3061b52f177ba403f02f0a296a85518da96c313@1156671 13f79535-47bb-0310-9956-ffa450edef68
maven-model/src/main/java/org/apache/maven/model/merge/ModelMerger.java
[MNG-5153] ModelMerger omits relativ path
<ide><path>aven-model/src/main/java/org/apache/maven/model/merge/ModelMerger.java <ide> if ( tgt == null ) <ide> { <ide> tgt = new Parent(); <add> tgt.setRelativePath( null ); <ide> target.setParent( tgt ); <ide> } <ide> mergeParent( tgt, src, sourceDominant, context ); <ide> if ( tgt == null ) <ide> { <ide> tgt = new Scm(); <add> tgt.setTag( null ); <ide> target.setScm( tgt ); <ide> } <ide> mergeScm( tgt, src, sourceDominant, context ); <ide> if ( tgt == null ) <ide> { <ide> tgt = new Prerequisites(); <add> tgt.setMaven( null ); <ide> target.setPrerequisites( tgt ); <ide> } <ide> mergePrerequisites( tgt, src, sourceDominant, context );
Java
apache-2.0
9453cf508bdc6ce3f629ccaffa045a7fe81b859e
0
blackducksoftware/hub-common,blackducksoftware/hub-common,blackducksoftware/hub-common
/******************************************************************************* * Black Duck Software Suite SDK * Copyright (C) 2016 Black Duck Software, Inc. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *******************************************************************************/ package com.blackducksoftware.integration.hub.exception; import com.blackducksoftware.integration.hub.ValidationExceptionEnum; public class ValidationException extends RuntimeException { private static final long serialVersionUID = 9001308081326471943L; private final ValidationExceptionEnum validationExceptionEnum; public ValidationException(final ValidationExceptionEnum validationExceptionEnum) { this.validationExceptionEnum = validationExceptionEnum; } public ValidationException(final ValidationExceptionEnum validationExceptionEnum, final String message) { super(message); this.validationExceptionEnum = validationExceptionEnum; } public ValidationException(final ValidationExceptionEnum validationExceptionEnum, final Throwable cause) { super(cause); this.validationExceptionEnum = validationExceptionEnum; } public ValidationException(final ValidationExceptionEnum validationExceptionEnum, final String message, final Throwable cause) { super(message, cause); this.validationExceptionEnum = validationExceptionEnum; } public ValidationExceptionEnum getValidationExceptionEnum() { return validationExceptionEnum; } }
src/main/java/com/blackducksoftware/integration/hub/exception/ValidationException.java
/******************************************************************************* * Black Duck Software Suite SDK * Copyright (C) 2016 Black Duck Software, Inc. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *******************************************************************************/ package com.blackducksoftware.integration.hub.exception; import com.blackducksoftware.integration.hub.ValidationExceptionEnum; public class ValidationException extends RuntimeException { private static final long serialVersionUID = 9001308081326471943L; private final ValidationExceptionEnum validationMessageType; public ValidationException(final ValidationExceptionEnum validationMessageType) { this.validationMessageType = validationMessageType; } public ValidationException(final ValidationExceptionEnum validationMessageType, final String message) { super(message); this.validationMessageType = validationMessageType; } public ValidationException(final ValidationExceptionEnum validationMessageType, final Throwable cause) { super(cause); this.validationMessageType = validationMessageType; } public ValidationException(final ValidationExceptionEnum validationMessageType, final String message, final Throwable cause) { super(message, cause); this.validationMessageType = validationMessageType; } public ValidationExceptionEnum getValidationMessage() { return validationMessageType; } }
fixing method names
src/main/java/com/blackducksoftware/integration/hub/exception/ValidationException.java
fixing method names
<ide><path>rc/main/java/com/blackducksoftware/integration/hub/exception/ValidationException.java <ide> public class ValidationException extends RuntimeException { <ide> private static final long serialVersionUID = 9001308081326471943L; <ide> <del> private final ValidationExceptionEnum validationMessageType; <add> private final ValidationExceptionEnum validationExceptionEnum; <ide> <del> public ValidationException(final ValidationExceptionEnum validationMessageType) { <del> this.validationMessageType = validationMessageType; <add> public ValidationException(final ValidationExceptionEnum validationExceptionEnum) { <add> this.validationExceptionEnum = validationExceptionEnum; <ide> } <ide> <del> public ValidationException(final ValidationExceptionEnum validationMessageType, final String message) { <add> public ValidationException(final ValidationExceptionEnum validationExceptionEnum, final String message) { <ide> super(message); <del> this.validationMessageType = validationMessageType; <add> this.validationExceptionEnum = validationExceptionEnum; <ide> } <ide> <del> public ValidationException(final ValidationExceptionEnum validationMessageType, final Throwable cause) { <add> public ValidationException(final ValidationExceptionEnum validationExceptionEnum, final Throwable cause) { <ide> super(cause); <del> this.validationMessageType = validationMessageType; <add> this.validationExceptionEnum = validationExceptionEnum; <ide> } <ide> <del> public ValidationException(final ValidationExceptionEnum validationMessageType, final String message, <add> public ValidationException(final ValidationExceptionEnum validationExceptionEnum, final String message, <ide> final Throwable cause) { <ide> super(message, cause); <del> this.validationMessageType = validationMessageType; <add> this.validationExceptionEnum = validationExceptionEnum; <ide> } <ide> <del> public ValidationExceptionEnum getValidationMessage() { <del> return validationMessageType; <add> public ValidationExceptionEnum getValidationExceptionEnum() { <add> return validationExceptionEnum; <ide> } <ide> <ide> }
Java
apache-2.0
74908667d5cbee07aeaafff4343ddcd7556ed8ae
0
opensingular/singular-core,opensingular/singular-core,opensingular/singular-core,opensingular/singular-core
/* * Copyright (c) 2016, Mirante and/or its affiliates. All rights reserved. * Mirante PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package br.net.mirante.singular.flow.core; import br.net.mirante.singular.commons.base.SingularException; import br.net.mirante.singular.flow.core.builder.ITaskDefinition; import br.net.mirante.singular.flow.core.entity.*; import br.net.mirante.singular.flow.core.service.IPersistenceService; import br.net.mirante.singular.flow.core.variable.ValidationResult; import br.net.mirante.singular.flow.core.variable.VarInstanceMap; import br.net.mirante.singular.flow.core.view.Lnk; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; /** * <p> * Esta é a classe responsável por manter os dados de instância de um * determinado processo. * </p> * * @author Mirante Tecnologia */ @SuppressWarnings({ "serial", "unchecked" }) public class ProcessInstance implements Serializable { private RefProcessDefinition processDefinitionRef; private Integer codEntity; private transient IEntityProcessInstance entity; private transient MTask<?> estadoAtual; private transient ExecutionContext executionContext; private transient VarInstanceMap<?> variables; final void setProcessDefinition(ProcessDefinition<?> processDefinition) { if (processDefinitionRef != null) { throw new SingularException("Erro Interno"); } processDefinitionRef = RefProcessDefinition.of(processDefinition); } /** * <p> * Retorna a definição de processo desta instância. * </p> * * @param <K> o tipo da definição de processo. * @return a definição de processo desta instância. */ public <K extends ProcessDefinition<?>> K getProcessDefinition() { if (processDefinitionRef == null) { throw new SingularException( "A instância não foi inicializada corretamente, pois não tem uma referência a ProcessDefinition! Tente chamar o método newInstance() a partir da definição do processo."); } return (K) processDefinitionRef.get(); } /** * <p> * Inicia esta instância de processo. * </p> * * @return A tarefa atual da instância depois da inicialização. */ public TaskInstance start() { return start(getVariaveis()); } /** * @deprecated Esse método deve ser renomeado pois possui um comportamente * implicito não evidente em comparação à outra versão sobrecarregada do * mesmo: "getPersistedDescription" */ @Deprecated public TaskInstance start(VarInstanceMap<?> varInstanceMap) { getPersistedDescription(); // Força a geração da descrição return FlowEngine.start(this, varInstanceMap); } /** * <p> * Executa a próxima transição desta instância de processo. * </p> */ public void executeTransition() { FlowEngine.executeTransition(this, null, null); } /** * <p> * Executa a transição especificada desta instância de processo. * </p> * * @param transitionName a transição especificada. */ public void executeTransition(String transitionName) { FlowEngine.executeTransition(this, transitionName, null); } /** * <p> * Executa a transição especificada desta instância de processo passando as * variáveis fornecidas. * </p> * * @param transitionName a transição especificada. * @param param as variáveis fornecidas. */ public void executeTransition(String transitionName, VarInstanceMap<?> param) { FlowEngine.executeTransition(this, transitionName, param); } /** * <p> * Realiza a montagem necessária para execução da transição especificada a * partir da tarefa atual desta instância. * </p> * * @param transitionName a transição especificada. * @return a montagem resultante. */ public TransitionCall prepareTransition(String transitionName) { return getCurrentTask().prepareTransition(transitionName); } final IEntityProcessInstance getInternalEntity() { if (entity == null) { if (codEntity != null) { IEntityProcessInstance newfromDB = getPersistenceService().retrieveProcessInstanceByCod(codEntity); if (newfromDB != null) { if (!getProcessDefinition().getEntityProcessDefinition().equals(newfromDB.getProcessVersion().getProcessDefinition())) { throw new SingularException(getProcessDefinition().getName() + " id=" + codEntity + " se refere a definição de processo " + newfromDB.getProcessVersion().getProcessDefinition().getKey() + " mas era esperado que referenciasse " + getProcessDefinition().getEntityProcessDefinition()); } entity = newfromDB; } } if (entity == null) { throw new SingularException( getClass().getName() + " is not binded to a new and neither to a existing database intance process entity."); } } return entity; } private TaskInstance getCurrentTaskOrException() { TaskInstance current = getCurrentTask(); if (current == null) { throw new SingularException(createErrorMsg("Não há um task atual para essa instancia")); } return current; } final void setInternalEntity(IEntityProcessInstance entity) { Objects.requireNonNull(entity); this.entity = entity; this.codEntity = entity.getCod(); } /** * <p> * Configura a instância "pai" desta instância de processo. * </p> * * @param pai a instância "pai". */ public void setParent(ProcessInstance pai) { getPersistenceService().setProcessInstanceParent(getInternalEntity(), pai.getInternalEntity()); } /** * <p> * Retorna a tarefa "pai" desta instância de processo. * </p> * * @return a tarefa "pai". */ public TaskInstance getParentTask() { IEntityTaskInstance dbTaskInstance = getInternalEntity().getParentTask(); return dbTaskInstance == null ? null : Flow.getTaskInstance(dbTaskInstance); } /** * <p> * Retorna o tarefa corrente desta instância de processo. * </p> * * @return a tarefa corrente. */ public MTask<?> getEstado() { if (estadoAtual == null) { TaskInstance current = getCurrentTask(); if (current != null) { estadoAtual = getProcessDefinition().getFlowMap().getTaskBybbreviation(current.getAbbreviation()); } else if (isFinished()) { current = getLatestTask(); if (current != null && current.isFinished()) { estadoAtual = getProcessDefinition().getFlowMap().getTaskBybbreviation(current.getAbbreviation()); } else { throw new SingularException(createErrorMsg( "incossitencia: o estado final está null, mas deveria ter um estado do tipo final por estar finalizado")); } } else { throw new SingularException(createErrorMsg("getEstado() não pode ser invocado para essa instância")); } } return estadoAtual; } /** * <p> * Verifica se esta instância está encerrada. * </p> * * @return {@code true} caso esta instância está encerrada; {@code false} * caso contrário. */ public boolean isFinished() { return getEndDate() != null; } /** * <p> * Retornar o nome da definição de processo desta instância. * </p> * * @return o nome da definição de processo. */ public String getProcessName() { return getProcessDefinition().getName(); } /** * <p> * Retorna o nome da tarefa atual desta instância de processo. * </p> * * @return o nome da tarefa atual; ou {@code null} caso não haja uma tarefa * atual. */ public String getCurrentTaskName() { if (getEstado() != null) { return getEstado().getName(); } TaskInstance tarefaAtual = getCurrentTask(); if (tarefaAtual != null) { // Uma situação legada, que não existe mais no fluxo mapeado return tarefaAtual.getName(); } return null; } /** * <p> * Retorna o <i>link resolver</i> padrão desta instância de processo. * </p> * * @return o <i>link resolver</i> padrão. */ public final Lnk getDefaultHref() { return Flow.getDefaultHrefFor(this); } /** * <p> * Retorna os códigos de usuários com direito de execução da tarefa humana * definida para o processo correspondente a esta instância. * </p> * * @param nomeTarefa o nome da tarefa humana a ser inspecionada. * @return os códigos de usuários com direitos de execução. */ public Set<Integer> getFirstLevelUsersCodWithAccess(String nomeTarefa) { return getProcessDefinition().getFlowMap().getPeopleTaskByAbbreviationOrException(nomeTarefa).getAccessStrategy() .getFirstLevelUsersCodWithAccess(this); } /** * <p> * Verifica de o usuário especificado pode executar a tarefa corrente desta * instância de processo. * </p> * * @param user o usuário especificado. * @return {@code true} caso o usuário possa executar a tarefa corrente; * {@code false} caso contrário. */ public final boolean canExecuteTask(MUser user) { if (getEstado() == null) { return false; } IEntityTaskType tt = getEstado().getTaskType(); if (tt.isPeople() || tt.isWait()) { return (isAllocated(user.getCod())) || (getAccessStrategy() != null && getAccessStrategy().canExecute(this, user)); } return false; } /** * <p> * Verifica de o usuário especificado pode visualizar a tarefa corrente * desta instância de processo. * </p> * * @param user o usuário especificado. * @return {@code true} caso o usuário possa visualizar a tarefa corrente; * {@code false} caso contrário. */ public boolean canVisualize(MUser user) { MTask<?> tt = getLatestTask().getFlowTask(); if (tt.isPeople() || tt.isWait()) { if (hasAllocatedUser() && isAllocated(user.getCod())) { return true; } } return getAccessStrategy() != null && getAccessStrategy().canVisualize(this, user); } /** * <p> * Retorna os códigos de usuários com direito de execução da tarefa corrente * desta instância de processo. * </p> * * @return os códigos de usuários com direitos de execução. */ public Set<Integer> getFirstLevelUsersCodWithAccess() { return getAccessStrategy().getFirstLevelUsersCodWithAccess(this); } /** * <p> * Retorna os usuários com direito de execução da tarefa corrente desta * instância de processo. * </p> * * @return os usuários com direitos de execução. */ public List<MUser> listAllocableUsers() { return getAccessStrategy().listAllocableUsers(this); } /** * <p> * Formata uma mensagem de erro. * </p> * <p> * A formatação da mensagem segue o seguinte padrão: * </p> * * <pre> * getClass().getName() + &quot; - &quot; + getFullId() + &quot; : &quot; + message * </pre> * * @param message a mensagem a ser formatada. * @return a mensagem formatada. * @see #getFullId() */ public final String createErrorMsg(String message) { return getClass().getName() + " - " + getFullId() + " : " + message; } @SuppressWarnings("rawtypes") private TaskAccessStrategy getAccessStrategy() { return getEstado().getAccessStrategy(); } /** * Apenas para uso interno da engine de processo e da persistencia. */ public final void refreshEntity() { getPersistenceService().refreshModel(getInternalEntity()); } /** * Recupera a entidade persistente correspondente a esta instância de * processo. */ public final IEntityProcessInstance getEntity() { if (codEntity == null && getInternalEntity().getCod() == null) { return saveEntity(); } entity = getPersistenceService().retrieveProcessInstanceByCod(codEntity); return entity; } /** * <p> * Retorna o usuário desta instância de processo atribuído ao papel * especificado. * </p> * * @param roleAbbreviation a sigla do papel especificado. * @return o usuário atribuído ao papel. */ public final MUser getUserWithRole(String roleAbbreviation) { final IEntityRoleInstance entityRole = getEntity().getRoleUserByAbbreviation(roleAbbreviation); if (entityRole != null) { return entityRole.getUser(); } return null; } /** * <p> * Recupera a lista de papeis da entidade persistente correspondente a esta * instância. * </p> * * @return os papeis. */ // TODO Daniel deveria retornar um objeto que isolasse da persistência @Deprecated public final List<? extends IEntityRoleInstance> getUserRoles() { return getEntity().getRoles(); } /** * <p> * Recupera a lista de papeis com a sigla especificada da entidade * persistente correspondente a esta instância. * </p> * * @param roleAbbreviation a sigla especificada. * @return os papeis. */ public final IEntityRoleInstance getRoleUserByAbbreviation(String roleAbbreviation) { return getEntity().getRoleUserByAbbreviation(roleAbbreviation); } /** * <p> * Verifica se há papeis definidos. * </p> * * @return {@code true} caso haja pelo menos um papel definido; * {@code false} caso contrário. */ public final boolean hasUserRoles() { return !getEntity().getRoles().isEmpty(); } /** * <p> * Retorna o usuário que criou esta instância de processo. * </p> * * @return o usuário criador. */ public final MUser getUserCreator() { return getInternalEntity().getUserCreator(); } /** * <p> * Altera a descrição desta instância de processo. * </p> * <p> * A descrição será truncada para um tamanho máximo de 250 caracteres. * </p> * * @param descricao a nova descrição. */ public final void setDescription(String descricao) { getInternalEntity().setDescription(StringUtils.left(descricao, 250)); } /** * <p> * Persiste esta instância de processo. * </p> * * @param <K> o tipo da entidade desta instância. * @return a entidade persistida. */ public final <K extends IEntityProcessInstance> K saveEntity() { setInternalEntity(getPersistenceService().saveProcessInstance(getInternalEntity())); return (K) getInternalEntity(); } /** * <p> * Realiza uma transição manual da tarefa atual para a tarefa especificada. * </p> * * @param task a tarefa especificada. */ public final void forceStateUpdate(MTask<?> task) { final TaskInstance tarefaOrigem = getLatestTask(); List<MUser> pessoasAnteriores = getResponsaveisDiretos(); final Date agora = new Date(); TaskInstance tarefaNova = updateState(tarefaOrigem, null, task, agora); if (tarefaOrigem != null) { tarefaOrigem.log("Alteração Manual de Estado", "de '" + tarefaOrigem.getName() + "' para '" + task.getName() + "'", null, Flow.getUserIfAvailable(), agora).sendEmail(pessoasAnteriores); } FlowEngine.initTask(this, task, tarefaNova); ExecutionContext execucaoMTask = new ExecutionContext(this, tarefaNova, null); task.notifyTaskStart(getLatestTask(task), execucaoMTask); if (task.isImmediateExecution()) { executeTransition(); } } /** * <p> * Realiza uma transição da tarefa de origiem para a tarefa alvo * especificadas. * </p> * * @param tarefaOrigem a tarefa de origem. * @param transicaoOrigem a transição disparada. * @param task a tarefa alvo. * @param agora o momento da transição. * @return a tarefa corrente depois da transição. */ protected final TaskInstance updateState(TaskInstance tarefaOrigem, MTransition transicaoOrigem, MTask<?> task, Date agora) { synchronized (this) { if (tarefaOrigem != null) { tarefaOrigem.endLastAllocation(); String transitionName = null; if (transicaoOrigem != null) { transitionName = transicaoOrigem.getAbbreviation(); } getPersistenceService().completeTask(tarefaOrigem.getEntityTaskInstance(), transitionName, Flow.getUserIfAvailable()); } IEntityTaskVersion situacaoNova = getProcessDefinition().getEntityTaskVersion(task); IEntityTaskInstance tarefa = getPersistenceService().addTask(getEntity(), situacaoNova); TaskInstance tarefaNova = getTaskInstance(tarefa); estadoAtual = task; Flow.notifyListeners(n -> n.notifyStateUpdate(ProcessInstance.this)); return tarefaNova; } } /** * Retorna a data inicial desta instância. * * @return nunca null. */ public final Date getBeginDate() { return getInternalEntity().getBeginDate(); } /** * <p> * Retorna a data de encerramento desta instância. * </p> * * @return a data de encerramento. */ public final Date getEndDate() { return getInternalEntity().getEndDate(); } /** * <p> * Retorna o código desta instância. * </p> * * @return o código. */ public final Integer getEntityCod() { return codEntity; } /** * <p> * Retorna o código desta instância como uma {@link String}. * </p> * * @return o código. */ public final String getId() { return getEntityCod().toString(); } /** * <p> * Retorna um novo <b>ID</b> autogerado para esta instância. * </p> * * @return o <b>ID</b> autogerado. */ public final String getFullId() { return Flow.generateID(this); } private TaskInstance getTaskInstance(final IEntityTaskInstance tarefa) { return tarefa != null ? new TaskInstance(this, tarefa) : null; } /** * <p> * O mesmo que {@link #getCompleteDescription()}. * </p> * * @return a descrição completa. */ public String getDescription() { return getCompleteDescription(); } /** * <p> * Retorna o nome do processo seguido da descrição completa. * * @return o nome do processo seguido da descrição completa. */ public final String getExtendedDescription() { String descricao = getDescription(); if (descricao == null) { return getProcessName(); } return getProcessName() + " - " + descricao; } /** * <p> * Retorna a descrição atual desta instância. * </p> * * @return a descrição atual. */ protected final String getPersistedDescription() { String descricao = getInternalEntity().getDescription(); if (descricao == null) { descricao = generateInitialDescription(); if (!StringUtils.isBlank(descricao)) { setDescription(descricao); } } return descricao; } /** * <p> * Cria a descrição que vai gravada no banco de dados. Deve ser sobreescrito * para ter efeito. * </p> * * @return a descrição criada. */ protected String generateInitialDescription() { return null; } /** * <p> * Sobrescreve a descrição da demanda a partir do método * {@link #generateInitialDescription()}. * </p> * * @return {@code true} caso tenha sido alterada a descrição; {@code false} * caso contrário. */ public final boolean regenerateInitialDescription() { String descricao = generateInitialDescription(); if (!StringUtils.isBlank(descricao) && !descricao.equalsIgnoreCase(getInternalEntity().getDescription())) { setDescription(descricao); return true; } return false; } /** * <p> * Cria versão extendida da descrição em relação ao campo descrição no BD. * </p> * <p> * Geralmente são adicionadas informações que não precisam ter cache feito * em banco de dados. * </p> * * @return a descrição atual desta instância. */ protected String getCompleteDescription() { return getPersistedDescription(); } /** * <p> * Retorna os responsáveis diretos. * </p> * * @return os responsáveis diretos. */ public List<MUser> getResponsaveisDiretos() { TaskInstance tarefa = getCurrentTask(); if (tarefa != null) { return tarefa.getDirectlyResponsibles(); } return Collections.emptyList(); } private void addUserRole(MProcessRole mProcessRole, MUser user) { if (getUserWithRole(mProcessRole.getAbbreviation()) == null) { getPersistenceService().setInstanceUserRole(getEntity(), getProcessDefinition().getEntityProcessDefinition().getRole(mProcessRole.getAbbreviation()), user); } } /** * <p> * Atribui ou substitui o usuário para o papel especificado. * </p> * * @param roleAbbreviation o papel especificado. * @param newUser o novo usuário atribuído ao papel. */ public final void addOrReplaceUserRole(final String roleAbbreviation, MUser newUser) { MProcessRole mProcessRole = getProcessDefinition().getFlowMap().getRoleWithAbbreviation(roleAbbreviation); if (mProcessRole == null) { throw new SingularFlowException("Não foi possível encontrar a role: " + roleAbbreviation); } MUser previousUser = getUserWithRole(mProcessRole.getAbbreviation()); if (previousUser == null) { if (newUser != null) { addUserRole(mProcessRole, newUser); getProcessDefinition().getFlowMap().notifyRoleChange(this, mProcessRole, null, newUser); final TaskInstance latestTask = getLatestTask(); if (latestTask != null) { latestTask.log("Papel definido", String.format("%s: %s", mProcessRole.getName(), newUser.getSimpleName())); } } } else if (newUser == null || !previousUser.equals(newUser)) { IEntityProcessInstance entityTmp = getEntity(); getPersistenceService().removeInstanceUserRole(entityTmp, entityTmp.getRoleUserByAbbreviation(mProcessRole.getAbbreviation())); if (newUser != null) { addUserRole(mProcessRole, newUser); } getProcessDefinition().getFlowMap().notifyRoleChange(this, mProcessRole, previousUser, newUser); final TaskInstance latestTask = getLatestTask(); if (latestTask != null) { if (newUser != null) { latestTask.log("Papel alterado", String.format("%s: %s", mProcessRole.getName(), newUser.getSimpleName())); } else { latestTask.log("Papel removido", mProcessRole.getName()); } } } } /** * <p> * Configura o valor variável especificada. * </p> * * @param nomeVariavel o nome da variável especificada. * @param valor o valor a ser configurado. */ public void setVariavel(String nomeVariavel, Object valor) { getVariaveis().setValor(nomeVariavel, valor); } /** * <p> * Retorna o valor da variável do tipo {@link Date} especificada. * </p> * * @param nomeVariavel o nome da variável especificada. * @return o valor da variável. */ public final Date getValorVariavelData(String nomeVariavel) { return getVariaveis().getValorData(nomeVariavel); } /** * <p> * Retorna o valor da variável do tipo {@link Boolean} especificada. * </p> * * @param nomeVariavel o nome da variável especificada. * @return o valor da variável. */ public final Boolean getValorVariavelBoolean(String nomeVariavel) { return getVariaveis().getValorBoolean(nomeVariavel); } /** * <p> * Retorna o valor da variável do tipo {@link String} especificada. * </p> * * @param nomeVariavel o nome da variável especificada. * @return o valor da variável. */ public final String getValorVariavelString(String nomeVariavel) { return getVariaveis().getValorString(nomeVariavel); } /** * <p> * Retorna o valor da variável do tipo {@link Integer} especificada. * </p> * * @param nomeVariavel o nome da variável especificada. * @return o valor da variável. */ public final Integer getValorVariavelInteger(String nomeVariavel) { return getVariaveis().getValorInteger(nomeVariavel); } /** * <p> * Retorna o valor da variável especificada. * </p> * * @param <T> o tipo da variável especificada. * @param nomeVariavel o nome da variável especificada. * @return o valor da variável. */ public final <T> T getValorVariavel(String nomeVariavel) { return getVariaveis().getValor(nomeVariavel); } /** * <p> * Retorna o mapa das variáveis desta instância de processo. * </p> * * @return o mapa das variáveis. */ public final VarInstanceMap<?> getVariaveis() { if (variables == null) { variables = new VarInstanceTableProcess(this); } return variables; } /** * <p> * Valida esta instância de processo. * </p> * * @throws SingularFlowException caso a validação falhe. */ protected void validadeStart() { if (variables == null && !getProcessDefinition().getVariables().hasRequired()) { return; } ValidationResult result = getVariaveis().validar(); if (result.hasErros()) { throw new SingularFlowException(createErrorMsg("Erro ao iniciar processo '" + getProcessName() + "': " + result)); } } /** * <p> * Verifica se há usuário alocado em alguma tarefa desta instância de * processo. * </p> * * @return {@code true} caso haja algum usuário alocado; {@code false} caso * contrário. */ public boolean hasAllocatedUser() { return getEntity().getTasks().stream().anyMatch(tarefa -> tarefa.isActive() && tarefa.getAllocatedUser() != null); } /** * <p> * Retorna os usuários alocados nas tarefas ativas * </p> * * @return a lista de usuários (<i>null safe</i>). */ public Set<MUser> getAllocatedUsers() { return getEntity().getTasks().stream().filter(tarefa -> tarefa.isActive() && tarefa.getAllocatedUser() != null).map(tarefa -> tarefa.getAllocatedUser()).collect(Collectors.toSet()); } /** * <p> * Verifica se o usuário especificado está alocado em alguma tarefa desta * instância de processo. * </p> * * @param codPessoa o código usuário especificado. * @return {@code true} caso o usuário esteja alocado; {@code false} caso * contrário. */ public boolean isAllocated(Integer codPessoa) { return getEntity().getTasks().stream().anyMatch(tarefa -> tarefa.isActive() && tarefa.getAllocatedUser() != null && tarefa.getAllocatedUser().getCod().equals(codPessoa)); } /** * <p> * Retorna a lista de todas as tarefas. Ordena da mais antiga para a mais * nova. * </p> * * @return a lista de tarefas (<i>null safe</i>). */ public List<TaskInstance> getTasks() { IEntityProcessInstance demanda = getEntity(); return demanda.getTasks().stream().map(this::getTaskInstance).collect(Collectors.toList()); } /** * <p> * Retorna a mais nova tarefa que atende a condição informada. * </p> * * @param condicao a condição informada. * @return a tarefa; ou {@code null} caso não encontre a tarefa. */ public TaskInstance getLatestTask(Predicate<TaskInstance> condicao) { List<? extends IEntityTaskInstance> lista = getEntity().getTasks(); for (int i = lista.size() - 1; i != -1; i--) { TaskInstance task = getTaskInstance(lista.get(i)); if (condicao.test(task)) { return task; } } return null; } /** * <p> * Retorna a tarefa atual. * </p> * * @return a tarefa atual. */ public TaskInstance getCurrentTask() { return getLatestTask(t -> t.isActive()); } /** * <p> * Retorna a mais nova tarefa encerrada ou ativa. * </p> * * @return a mais nova tarefa encerrada ou ativa. */ public TaskInstance getLatestTask() { return getLatestTask(t -> true); } private TaskInstance getLatestTask(String abbreviation) { return getLatestTask(t -> t.getAbbreviation().equalsIgnoreCase(abbreviation)); } /** * <p> * Encontra a mais nova tarefa encerrada ou ativa com a sigla da referência. * </p> * * @param taskRef a referência. * @return a tarefa; ou {@code null} caso não encotre a tarefa. */ public TaskInstance getLatestTask(ITaskDefinition taskRef) { return getLatestTask(taskRef.getKey()); } /** * <p> * Encontra a mais nova tarefa encerrada ou ativa do tipo informado. * </p> * * @param tipo o tipo informado. * @return a tarefa; ou {@code null} caso não encotre a tarefa. */ public TaskInstance getLatestTask(MTask<?> tipo) { return getLatestTask(tipo.getAbbreviation()); } private TaskInstance getFinishedTask(String abbreviation) { return getLatestTask(t -> t.isFinished() && t.getAbbreviation().equalsIgnoreCase(abbreviation)); } /** * <p> * Encontra a mais nova tarefa encerrada e com a mesma sigla da referência. * </p> * * @param taskRef a referência. * @return a tarefa; ou {@code null} caso não encotre a tarefa. */ public TaskInstance getFinishedTask(ITaskDefinition taskRef) { return getFinishedTask(taskRef.getKey()); } /** * <p> * Encontra a mais nova tarefa encerrada e com a mesma sigla do tipo. * </p> * * @param tipo o tipo. * @return a tarefa; ou {@code null} caso não encotre a tarefa. */ public TaskInstance getFinishedTask(MTask<?> tipo) { return getFinishedTask(tipo.getAbbreviation()); } protected IPersistenceService<IEntityCategory, IEntityProcessDefinition, IEntityProcessVersion, IEntityProcessInstance, IEntityTaskInstance, IEntityTaskDefinition, IEntityTaskVersion, IEntityVariableInstance, IEntityRoleDefinition, IEntityRoleInstance> getPersistenceService() { return getProcessDefinition().getPersistenceService(); } /** * <p> * Configura o contexto de execução. * </p> * * @param execucaoTask o novo contexto de execução. */ final void setExecutionContext(ExecutionContext execucaoTask) { if (this.executionContext != null && execucaoTask != null) { throw new SingularFlowException(createErrorMsg("A instancia já está com um tarefa em processo de execução")); } this.executionContext = execucaoTask; } }
flow/core/src/main/java/br/net/mirante/singular/flow/core/ProcessInstance.java
/* * Copyright (c) 2016, Mirante and/or its affiliates. All rights reserved. * Mirante PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package br.net.mirante.singular.flow.core; import java.io.Serializable; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import br.net.mirante.singular.commons.base.SingularException; import br.net.mirante.singular.flow.core.builder.ITaskDefinition; import br.net.mirante.singular.flow.core.entity.IEntityCategory; import br.net.mirante.singular.flow.core.entity.IEntityProcessDefinition; import br.net.mirante.singular.flow.core.entity.IEntityProcessInstance; import br.net.mirante.singular.flow.core.entity.IEntityProcessVersion; import br.net.mirante.singular.flow.core.entity.IEntityRoleDefinition; import br.net.mirante.singular.flow.core.entity.IEntityRoleInstance; import br.net.mirante.singular.flow.core.entity.IEntityTaskDefinition; import br.net.mirante.singular.flow.core.entity.IEntityTaskInstance; import br.net.mirante.singular.flow.core.entity.IEntityTaskVersion; import br.net.mirante.singular.flow.core.entity.IEntityVariableInstance; import br.net.mirante.singular.flow.core.service.IPersistenceService; import br.net.mirante.singular.flow.core.variable.ValidationResult; import br.net.mirante.singular.flow.core.variable.VarInstanceMap; import br.net.mirante.singular.flow.core.view.Lnk; /** * <p> * Esta é a classe responsável por manter os dados de instância de um * determinado processo. * </p> * * @author Mirante Tecnologia */ @SuppressWarnings({ "serial", "unchecked" }) public class ProcessInstance implements Serializable { private RefProcessDefinition processDefinitionRef; private Integer codEntity; private transient IEntityProcessInstance entity; private transient MTask<?> estadoAtual; private transient ExecutionContext executionContext; private transient VarInstanceMap<?> variables; final void setProcessDefinition(ProcessDefinition<?> processDefinition) { if (processDefinitionRef != null) { throw new SingularException("Erro Interno"); } processDefinitionRef = RefProcessDefinition.of(processDefinition); } /** * <p> * Retorna a definição de processo desta instância. * </p> * * @param <K> o tipo da definição de processo. * @return a definição de processo desta instância. */ public <K extends ProcessDefinition<?>> K getProcessDefinition() { if (processDefinitionRef == null) { throw new SingularException( "A instância não foi inicializada corretamente, pois não tem uma referência a ProcessDefinition! Tente chamar o método newInstance() a partir da definição do processo."); } return (K) processDefinitionRef.get(); } /** * <p> * Inicia esta instância de processo. * </p> * * @return A tarefa atual da instância depois da inicialização. */ public TaskInstance start() { return start(getVariaveis()); } /** * @deprecated Esse método deve ser renomeado pois possui um comportamente * implicito não evidente em comparação à outra versão sobrecarregada do * mesmo: "getPersistedDescription" */ @Deprecated public TaskInstance start(VarInstanceMap<?> varInstanceMap) { getPersistedDescription(); // Força a geração da descrição return FlowEngine.start(this, varInstanceMap); } /** * <p> * Executa a próxima transição desta instância de processo. * </p> */ public void executeTransition() { FlowEngine.executeTransition(this, null, null); } /** * <p> * Executa a transição especificada desta instância de processo. * </p> * * @param transitionName a transição especificada. */ public void executeTransition(String transitionName) { FlowEngine.executeTransition(this, transitionName, null); } /** * <p> * Executa a transição especificada desta instância de processo passando as * variáveis fornecidas. * </p> * * @param transitionName a transição especificada. * @param param as variáveis fornecidas. */ public void executeTransition(String transitionName, VarInstanceMap<?> param) { FlowEngine.executeTransition(this, transitionName, param); } /** * <p> * Realiza a montagem necessária para execução da transição especificada a * partir da tarefa atual desta instância. * </p> * * @param transitionName a transição especificada. * @return a montagem resultante. */ public TransitionCall prepareTransition(String transitionName) { return getCurrentTask().prepareTransition(transitionName); } final IEntityProcessInstance getInternalEntity() { if (entity == null) { if (codEntity != null) { IEntityProcessInstance newfromDB = getPersistenceService().retrieveProcessInstanceByCod(codEntity); if (newfromDB != null) { if (!getProcessDefinition().getEntityProcessDefinition().equals(newfromDB.getProcessVersion().getProcessDefinition())) { throw new SingularException(getProcessDefinition().getName() + " id=" + codEntity + " se refere a definição de processo " + newfromDB.getProcessVersion().getProcessDefinition().getKey() + " mas era esperado que referenciasse " + getProcessDefinition().getEntityProcessDefinition()); } entity = newfromDB; } } if (entity == null) { throw new SingularException( getClass().getName() + " is not binded to a new and neither to a existing database intance process entity."); } } return entity; } private TaskInstance getCurrentTaskOrException() { TaskInstance current = getCurrentTask(); if (current == null) { throw new SingularException(createErrorMsg("Não há um task atual para essa instancia")); } return current; } final void setInternalEntity(IEntityProcessInstance entity) { Objects.requireNonNull(entity); this.entity = entity; this.codEntity = entity.getCod(); } /** * <p> * Configura a instância "pai" desta instância de processo. * </p> * * @param pai a instância "pai". */ public void setParent(ProcessInstance pai) { getPersistenceService().setProcessInstanceParent(getInternalEntity(), pai.getInternalEntity()); } /** * <p> * Retorna a tarefa "pai" desta instância de processo. * </p> * * @return a tarefa "pai". */ public TaskInstance getParentTask() { IEntityTaskInstance dbTaskInstance = getInternalEntity().getParentTask(); return dbTaskInstance == null ? null : Flow.getTaskInstance(dbTaskInstance); } /** * <p> * Retorna o tarefa corrente desta instância de processo. * </p> * * @return a tarefa corrente. */ public MTask<?> getEstado() { if (estadoAtual == null) { TaskInstance current = getCurrentTask(); if (current != null) { estadoAtual = getProcessDefinition().getFlowMap().getTaskBybbreviation(current.getAbbreviation()); } else if (isFinished()) { current = getLatestTask(); if (current != null && current.isFinished()) { estadoAtual = getProcessDefinition().getFlowMap().getTaskBybbreviation(current.getAbbreviation()); } else { throw new SingularException(createErrorMsg( "incossitencia: o estado final está null, mas deveria ter um estado do tipo final por estar finalizado")); } } else { throw new SingularException(createErrorMsg("getEstado() não pode ser invocado para essa instância")); } } return estadoAtual; } /** * <p> * Verifica se esta instância está encerrada. * </p> * * @return {@code true} caso esta instância está encerrada; {@code false} * caso contrário. */ public boolean isFinished() { return getEndDate() != null; } /** * <p> * Retornar o nome da definição de processo desta instância. * </p> * * @return o nome da definição de processo. */ public String getProcessName() { return getProcessDefinition().getName(); } /** * <p> * Retorna o nome da tarefa atual desta instância de processo. * </p> * * @return o nome da tarefa atual; ou {@code null} caso não haja uma tarefa * atual. */ public String getCurrentTaskName() { if (getEstado() != null) { return getEstado().getName(); } TaskInstance tarefaAtual = getCurrentTask(); if (tarefaAtual != null) { // Uma situação legada, que não existe mais no fluxo mapeado return tarefaAtual.getName(); } return null; } /** * <p> * Retorna o <i>link resolver</i> padrão desta instância de processo. * </p> * * @return o <i>link resolver</i> padrão. */ public final Lnk getDefaultHref() { return Flow.getDefaultHrefFor(this); } /** * <p> * Retorna os códigos de usuários com direito de execução da tarefa humana * definida para o processo correspondente a esta instância. * </p> * * @param nomeTarefa o nome da tarefa humana a ser inspecionada. * @return os códigos de usuários com direitos de execução. */ public Set<Integer> getFirstLevelUsersCodWithAccess(String nomeTarefa) { return getProcessDefinition().getFlowMap().getPeopleTaskByAbbreviationOrException(nomeTarefa).getAccessStrategy() .getFirstLevelUsersCodWithAccess(this); } /** * <p> * Verifica de o usuário especificado pode executar a tarefa corrente desta * instância de processo. * </p> * * @param user o usuário especificado. * @return {@code true} caso o usuário possa executar a tarefa corrente; * {@code false} caso contrário. */ public final boolean canExecuteTask(MUser user) { if (getEstado() == null) { return false; } IEntityTaskType tt = getEstado().getTaskType(); if (tt.isPeople() || tt.isWait()) { return (isAllocated(user.getCod())) || (getAccessStrategy() != null && getAccessStrategy().canExecute(this, user)); } return false; } /** * <p> * Verifica de o usuário especificado pode visualizar a tarefa corrente * desta instância de processo. * </p> * * @param user o usuário especificado. * @return {@code true} caso o usuário possa visualizar a tarefa corrente; * {@code false} caso contrário. */ public boolean canVisualize(MUser user) { MTask<?> tt = getLatestTask().getFlowTask(); if (tt.isPeople() || tt.isWait()) { if (hasAllocatedUser() && isAllocated(user.getCod())) { return true; } } return getAccessStrategy() != null && getAccessStrategy().canVisualize(this, user); } /** * <p> * Retorna os códigos de usuários com direito de execução da tarefa corrente * desta instância de processo. * </p> * * @return os códigos de usuários com direitos de execução. */ public Set<Integer> getFirstLevelUsersCodWithAccess() { return getAccessStrategy().getFirstLevelUsersCodWithAccess(this); } /** * <p> * Retorna os usuários com direito de execução da tarefa corrente desta * instância de processo. * </p> * * @return os usuários com direitos de execução. */ public List<MUser> listAllocableUsers() { return getAccessStrategy().listAllocableUsers(this); } /** * <p> * Formata uma mensagem de erro. * </p> * <p> * A formatação da mensagem segue o seguinte padrão: * </p> * * <pre> * getClass().getName() + &quot; - &quot; + getFullId() + &quot; : &quot; + message * </pre> * * @param message a mensagem a ser formatada. * @return a mensagem formatada. * @see #getFullId() */ public final String createErrorMsg(String message) { return getClass().getName() + " - " + getFullId() + " : " + message; } @SuppressWarnings("rawtypes") private TaskAccessStrategy getAccessStrategy() { return getEstado().getAccessStrategy(); } /** * Apenas para uso interno da engine de processo e da persistencia. */ public final void refreshEntity() { getPersistenceService().refreshModel(getInternalEntity()); } /** * Recupera a entidade persistente correspondente a esta instância de * processo. */ public final IEntityProcessInstance getEntity() { if (codEntity == null && getInternalEntity().getCod() == null) { return saveEntity(); } entity = getPersistenceService().retrieveProcessInstanceByCod(codEntity); return entity; } /** * <p> * Retorna o usuário desta instância de processo atribuído ao papel * especificado. * </p> * * @param roleAbbreviation a sigla do papel especificado. * @return o usuário atribuído ao papel. */ public final MUser getUserWithRole(String roleAbbreviation) { final IEntityRoleInstance entityRole = getEntity().getRoleUserByAbbreviation(roleAbbreviation); if (entityRole != null) { return entityRole.getUser(); } return null; } /** * <p> * Recupera a lista de papeis da entidade persistente correspondente a esta * instância. * </p> * * @return os papeis. */ // TODO Daniel deveria retornar um objeto que isolasse da persistência @Deprecated public final List<? extends IEntityRoleInstance> getUserRoles() { return getEntity().getRoles(); } /** * <p> * Recupera a lista de papeis com a sigla especificada da entidade * persistente correspondente a esta instância. * </p> * * @param roleAbbreviation a sigla especificada. * @return os papeis. */ public final IEntityRoleInstance getRoleUserByAbbreviation(String roleAbbreviation) { return getEntity().getRoleUserByAbbreviation(roleAbbreviation); } /** * <p> * Verifica se há papeis definidos. * </p> * * @return {@code true} caso haja pelo menos um papel definido; * {@code false} caso contrário. */ public final boolean hasUserRoles() { return !getEntity().getRoles().isEmpty(); } /** * <p> * Retorna o usuário que criou esta instância de processo. * </p> * * @return o usuário criador. */ public final MUser getUserCreator() { return getInternalEntity().getUserCreator(); } /** * <p> * Altera a descrição desta instância de processo. * </p> * <p> * A descrição será truncada para um tamanho máximo de 250 caracteres. * </p> * * @param descricao a nova descrição. */ public final void setDescription(String descricao) { getInternalEntity().setDescription(StringUtils.left(descricao, 250)); } /** * <p> * Persiste esta instância de processo. * </p> * * @param <K> o tipo da entidade desta instância. * @return a entidade persistida. */ public final <K extends IEntityProcessInstance> K saveEntity() { setInternalEntity(getPersistenceService().saveProcessInstance(getInternalEntity())); return (K) getInternalEntity(); } /** * <p> * Realiza uma transição manual da tarefa atual para a tarefa especificada. * </p> * * @param task a tarefa especificada. */ public final void forceStateUpdate(MTask<?> task) { final TaskInstance tarefaOrigem = getLatestTask(); List<MUser> pessoasAnteriores = getResponsaveisDiretos(); final Date agora = new Date(); TaskInstance tarefaNova = updateState(tarefaOrigem, null, task, agora); if (tarefaOrigem != null) { tarefaOrigem.log("Alteração Manual de Estado", "de '" + tarefaOrigem.getName() + "' para '" + task.getName() + "'", null, Flow.getUserIfAvailable(), agora).sendEmail(pessoasAnteriores); } FlowEngine.initTask(this, task, tarefaNova); ExecutionContext execucaoMTask = new ExecutionContext(this, tarefaNova, null); task.notifyTaskStart(getLatestTask(task), execucaoMTask); if (task.isImmediateExecution()) { executeTransition(); } } /** * <p> * Realiza uma transição da tarefa de origiem para a tarefa alvo * especificadas. * </p> * * @param tarefaOrigem a tarefa de origem. * @param transicaoOrigem a transição disparada. * @param task a tarefa alvo. * @param agora o momento da transição. * @return a tarefa corrente depois da transição. */ protected final TaskInstance updateState(TaskInstance tarefaOrigem, MTransition transicaoOrigem, MTask<?> task, Date agora) { synchronized (this) { if (tarefaOrigem != null) { tarefaOrigem.endLastAllocation(); String transitionName = null; if (transicaoOrigem != null) { transitionName = transicaoOrigem.getName(); } getPersistenceService().completeTask(tarefaOrigem.getEntityTaskInstance(), transitionName, Flow.getUserIfAvailable()); } IEntityTaskVersion situacaoNova = getProcessDefinition().getEntityTaskVersion(task); IEntityTaskInstance tarefa = getPersistenceService().addTask(getEntity(), situacaoNova); TaskInstance tarefaNova = getTaskInstance(tarefa); estadoAtual = task; Flow.notifyListeners(n -> n.notifyStateUpdate(ProcessInstance.this)); return tarefaNova; } } /** * Retorna a data inicial desta instância. * * @return nunca null. */ public final Date getBeginDate() { return getInternalEntity().getBeginDate(); } /** * <p> * Retorna a data de encerramento desta instância. * </p> * * @return a data de encerramento. */ public final Date getEndDate() { return getInternalEntity().getEndDate(); } /** * <p> * Retorna o código desta instância. * </p> * * @return o código. */ public final Integer getEntityCod() { return codEntity; } /** * <p> * Retorna o código desta instância como uma {@link String}. * </p> * * @return o código. */ public final String getId() { return getEntityCod().toString(); } /** * <p> * Retorna um novo <b>ID</b> autogerado para esta instância. * </p> * * @return o <b>ID</b> autogerado. */ public final String getFullId() { return Flow.generateID(this); } private TaskInstance getTaskInstance(final IEntityTaskInstance tarefa) { return tarefa != null ? new TaskInstance(this, tarefa) : null; } /** * <p> * O mesmo que {@link #getCompleteDescription()}. * </p> * * @return a descrição completa. */ public String getDescription() { return getCompleteDescription(); } /** * <p> * Retorna o nome do processo seguido da descrição completa. * * @return o nome do processo seguido da descrição completa. */ public final String getExtendedDescription() { String descricao = getDescription(); if (descricao == null) { return getProcessName(); } return getProcessName() + " - " + descricao; } /** * <p> * Retorna a descrição atual desta instância. * </p> * * @return a descrição atual. */ protected final String getPersistedDescription() { String descricao = getInternalEntity().getDescription(); if (descricao == null) { descricao = generateInitialDescription(); if (!StringUtils.isBlank(descricao)) { setDescription(descricao); } } return descricao; } /** * <p> * Cria a descrição que vai gravada no banco de dados. Deve ser sobreescrito * para ter efeito. * </p> * * @return a descrição criada. */ protected String generateInitialDescription() { return null; } /** * <p> * Sobrescreve a descrição da demanda a partir do método * {@link #generateInitialDescription()}. * </p> * * @return {@code true} caso tenha sido alterada a descrição; {@code false} * caso contrário. */ public final boolean regenerateInitialDescription() { String descricao = generateInitialDescription(); if (!StringUtils.isBlank(descricao) && !descricao.equalsIgnoreCase(getInternalEntity().getDescription())) { setDescription(descricao); return true; } return false; } /** * <p> * Cria versão extendida da descrição em relação ao campo descrição no BD. * </p> * <p> * Geralmente são adicionadas informações que não precisam ter cache feito * em banco de dados. * </p> * * @return a descrição atual desta instância. */ protected String getCompleteDescription() { return getPersistedDescription(); } /** * <p> * Retorna os responsáveis diretos. * </p> * * @return os responsáveis diretos. */ public List<MUser> getResponsaveisDiretos() { TaskInstance tarefa = getCurrentTask(); if (tarefa != null) { return tarefa.getDirectlyResponsibles(); } return Collections.emptyList(); } private void addUserRole(MProcessRole mProcessRole, MUser user) { if (getUserWithRole(mProcessRole.getAbbreviation()) == null) { getPersistenceService().setInstanceUserRole(getEntity(), getProcessDefinition().getEntityProcessDefinition().getRole(mProcessRole.getAbbreviation()), user); } } /** * <p> * Atribui ou substitui o usuário para o papel especificado. * </p> * * @param roleAbbreviation o papel especificado. * @param newUser o novo usuário atribuído ao papel. */ public final void addOrReplaceUserRole(final String roleAbbreviation, MUser newUser) { MProcessRole mProcessRole = getProcessDefinition().getFlowMap().getRoleWithAbbreviation(roleAbbreviation); if (mProcessRole == null) { throw new SingularFlowException("Não foi possível encontrar a role: " + roleAbbreviation); } MUser previousUser = getUserWithRole(mProcessRole.getAbbreviation()); if (previousUser == null) { if (newUser != null) { addUserRole(mProcessRole, newUser); getProcessDefinition().getFlowMap().notifyRoleChange(this, mProcessRole, null, newUser); final TaskInstance latestTask = getLatestTask(); if (latestTask != null) { latestTask.log("Papel definido", String.format("%s: %s", mProcessRole.getName(), newUser.getSimpleName())); } } } else if (newUser == null || !previousUser.equals(newUser)) { IEntityProcessInstance entityTmp = getEntity(); getPersistenceService().removeInstanceUserRole(entityTmp, entityTmp.getRoleUserByAbbreviation(mProcessRole.getAbbreviation())); if (newUser != null) { addUserRole(mProcessRole, newUser); } getProcessDefinition().getFlowMap().notifyRoleChange(this, mProcessRole, previousUser, newUser); final TaskInstance latestTask = getLatestTask(); if (latestTask != null) { if (newUser != null) { latestTask.log("Papel alterado", String.format("%s: %s", mProcessRole.getName(), newUser.getSimpleName())); } else { latestTask.log("Papel removido", mProcessRole.getName()); } } } } /** * <p> * Configura o valor variável especificada. * </p> * * @param nomeVariavel o nome da variável especificada. * @param valor o valor a ser configurado. */ public void setVariavel(String nomeVariavel, Object valor) { getVariaveis().setValor(nomeVariavel, valor); } /** * <p> * Retorna o valor da variável do tipo {@link Date} especificada. * </p> * * @param nomeVariavel o nome da variável especificada. * @return o valor da variável. */ public final Date getValorVariavelData(String nomeVariavel) { return getVariaveis().getValorData(nomeVariavel); } /** * <p> * Retorna o valor da variável do tipo {@link Boolean} especificada. * </p> * * @param nomeVariavel o nome da variável especificada. * @return o valor da variável. */ public final Boolean getValorVariavelBoolean(String nomeVariavel) { return getVariaveis().getValorBoolean(nomeVariavel); } /** * <p> * Retorna o valor da variável do tipo {@link String} especificada. * </p> * * @param nomeVariavel o nome da variável especificada. * @return o valor da variável. */ public final String getValorVariavelString(String nomeVariavel) { return getVariaveis().getValorString(nomeVariavel); } /** * <p> * Retorna o valor da variável do tipo {@link Integer} especificada. * </p> * * @param nomeVariavel o nome da variável especificada. * @return o valor da variável. */ public final Integer getValorVariavelInteger(String nomeVariavel) { return getVariaveis().getValorInteger(nomeVariavel); } /** * <p> * Retorna o valor da variável especificada. * </p> * * @param <T> o tipo da variável especificada. * @param nomeVariavel o nome da variável especificada. * @return o valor da variável. */ public final <T> T getValorVariavel(String nomeVariavel) { return getVariaveis().getValor(nomeVariavel); } /** * <p> * Retorna o mapa das variáveis desta instância de processo. * </p> * * @return o mapa das variáveis. */ public final VarInstanceMap<?> getVariaveis() { if (variables == null) { variables = new VarInstanceTableProcess(this); } return variables; } /** * <p> * Valida esta instância de processo. * </p> * * @throws SingularFlowException caso a validação falhe. */ protected void validadeStart() { if (variables == null && !getProcessDefinition().getVariables().hasRequired()) { return; } ValidationResult result = getVariaveis().validar(); if (result.hasErros()) { throw new SingularFlowException(createErrorMsg("Erro ao iniciar processo '" + getProcessName() + "': " + result)); } } /** * <p> * Verifica se há usuário alocado em alguma tarefa desta instância de * processo. * </p> * * @return {@code true} caso haja algum usuário alocado; {@code false} caso * contrário. */ public boolean hasAllocatedUser() { return getEntity().getTasks().stream().anyMatch(tarefa -> tarefa.isActive() && tarefa.getAllocatedUser() != null); } /** * <p> * Retorna os usuários alocados nas tarefas ativas * </p> * * @return a lista de usuários (<i>null safe</i>). */ public Set<MUser> getAllocatedUsers() { return getEntity().getTasks().stream().filter(tarefa -> tarefa.isActive() && tarefa.getAllocatedUser() != null).map(tarefa -> tarefa.getAllocatedUser()).collect(Collectors.toSet()); } /** * <p> * Verifica se o usuário especificado está alocado em alguma tarefa desta * instância de processo. * </p> * * @param codPessoa o código usuário especificado. * @return {@code true} caso o usuário esteja alocado; {@code false} caso * contrário. */ public boolean isAllocated(Integer codPessoa) { return getEntity().getTasks().stream().anyMatch(tarefa -> tarefa.isActive() && tarefa.getAllocatedUser() != null && tarefa.getAllocatedUser().getCod().equals(codPessoa)); } /** * <p> * Retorna a lista de todas as tarefas. Ordena da mais antiga para a mais * nova. * </p> * * @return a lista de tarefas (<i>null safe</i>). */ public List<TaskInstance> getTasks() { IEntityProcessInstance demanda = getEntity(); return demanda.getTasks().stream().map(this::getTaskInstance).collect(Collectors.toList()); } /** * <p> * Retorna a mais nova tarefa que atende a condição informada. * </p> * * @param condicao a condição informada. * @return a tarefa; ou {@code null} caso não encontre a tarefa. */ public TaskInstance getLatestTask(Predicate<TaskInstance> condicao) { List<? extends IEntityTaskInstance> lista = getEntity().getTasks(); for (int i = lista.size() - 1; i != -1; i--) { TaskInstance task = getTaskInstance(lista.get(i)); if (condicao.test(task)) { return task; } } return null; } /** * <p> * Retorna a tarefa atual. * </p> * * @return a tarefa atual. */ public TaskInstance getCurrentTask() { return getLatestTask(t -> t.isActive()); } /** * <p> * Retorna a mais nova tarefa encerrada ou ativa. * </p> * * @return a mais nova tarefa encerrada ou ativa. */ public TaskInstance getLatestTask() { return getLatestTask(t -> true); } private TaskInstance getLatestTask(String abbreviation) { return getLatestTask(t -> t.getAbbreviation().equalsIgnoreCase(abbreviation)); } /** * <p> * Encontra a mais nova tarefa encerrada ou ativa com a sigla da referência. * </p> * * @param taskRef a referência. * @return a tarefa; ou {@code null} caso não encotre a tarefa. */ public TaskInstance getLatestTask(ITaskDefinition taskRef) { return getLatestTask(taskRef.getKey()); } /** * <p> * Encontra a mais nova tarefa encerrada ou ativa do tipo informado. * </p> * * @param tipo o tipo informado. * @return a tarefa; ou {@code null} caso não encotre a tarefa. */ public TaskInstance getLatestTask(MTask<?> tipo) { return getLatestTask(tipo.getAbbreviation()); } private TaskInstance getFinishedTask(String abbreviation) { return getLatestTask(t -> t.isFinished() && t.getAbbreviation().equalsIgnoreCase(abbreviation)); } /** * <p> * Encontra a mais nova tarefa encerrada e com a mesma sigla da referência. * </p> * * @param taskRef a referência. * @return a tarefa; ou {@code null} caso não encotre a tarefa. */ public TaskInstance getFinishedTask(ITaskDefinition taskRef) { return getFinishedTask(taskRef.getKey()); } /** * <p> * Encontra a mais nova tarefa encerrada e com a mesma sigla do tipo. * </p> * * @param tipo o tipo. * @return a tarefa; ou {@code null} caso não encotre a tarefa. */ public TaskInstance getFinishedTask(MTask<?> tipo) { return getFinishedTask(tipo.getAbbreviation()); } protected IPersistenceService<IEntityCategory, IEntityProcessDefinition, IEntityProcessVersion, IEntityProcessInstance, IEntityTaskInstance, IEntityTaskDefinition, IEntityTaskVersion, IEntityVariableInstance, IEntityRoleDefinition, IEntityRoleInstance> getPersistenceService() { return getProcessDefinition().getPersistenceService(); } /** * <p> * Configura o contexto de execução. * </p> * * @param execucaoTask o novo contexto de execução. */ final void setExecutionContext(ExecutionContext execucaoTask) { if (this.executionContext != null && execucaoTask != null) { throw new SingularFlowException(createErrorMsg("A instancia já está com um tarefa em processo de execução")); } this.executionContext = execucaoTask; } }
Ajustando persistencia do transição executada
flow/core/src/main/java/br/net/mirante/singular/flow/core/ProcessInstance.java
Ajustando persistencia do transição executada
<ide><path>low/core/src/main/java/br/net/mirante/singular/flow/core/ProcessInstance.java <ide> <ide> package br.net.mirante.singular.flow.core; <ide> <del>import java.io.Serializable; <del>import java.util.Collections; <del>import java.util.Date; <del>import java.util.List; <del>import java.util.Objects; <del>import java.util.Set; <del>import java.util.function.Predicate; <del>import java.util.stream.Collectors; <del> <del>import org.apache.commons.lang3.StringUtils; <del> <ide> import br.net.mirante.singular.commons.base.SingularException; <ide> import br.net.mirante.singular.flow.core.builder.ITaskDefinition; <del>import br.net.mirante.singular.flow.core.entity.IEntityCategory; <del>import br.net.mirante.singular.flow.core.entity.IEntityProcessDefinition; <del>import br.net.mirante.singular.flow.core.entity.IEntityProcessInstance; <del>import br.net.mirante.singular.flow.core.entity.IEntityProcessVersion; <del>import br.net.mirante.singular.flow.core.entity.IEntityRoleDefinition; <del>import br.net.mirante.singular.flow.core.entity.IEntityRoleInstance; <del>import br.net.mirante.singular.flow.core.entity.IEntityTaskDefinition; <del>import br.net.mirante.singular.flow.core.entity.IEntityTaskInstance; <del>import br.net.mirante.singular.flow.core.entity.IEntityTaskVersion; <del>import br.net.mirante.singular.flow.core.entity.IEntityVariableInstance; <add>import br.net.mirante.singular.flow.core.entity.*; <ide> import br.net.mirante.singular.flow.core.service.IPersistenceService; <ide> import br.net.mirante.singular.flow.core.variable.ValidationResult; <ide> import br.net.mirante.singular.flow.core.variable.VarInstanceMap; <ide> import br.net.mirante.singular.flow.core.view.Lnk; <add>import org.apache.commons.lang3.StringUtils; <add> <add>import java.io.Serializable; <add>import java.util.*; <add>import java.util.function.Predicate; <add>import java.util.stream.Collectors; <ide> <ide> /** <ide> * <p> <ide> tarefaOrigem.endLastAllocation(); <ide> String transitionName = null; <ide> if (transicaoOrigem != null) { <del> transitionName = transicaoOrigem.getName(); <add> transitionName = transicaoOrigem.getAbbreviation(); <ide> } <ide> getPersistenceService().completeTask(tarefaOrigem.getEntityTaskInstance(), transitionName, Flow.getUserIfAvailable()); <ide> }
Java
apache-2.0
b8507e699eb656d32e0131e688f3a302d4106e98
0
apache/tomcat,Nickname0806/Test_Q4,apache/tomcat,apache/tomcat,Nickname0806/Test_Q4,apache/tomcat,Nickname0806/Test_Q4,Nickname0806/Test_Q4,apache/tomcat
/* * 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.jasper.compiler; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.Hashtable; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Vector; import javax.el.MethodExpression; import javax.el.ValueExpression; import javax.servlet.jsp.tagext.TagAttributeInfo; import javax.servlet.jsp.tagext.TagInfo; import javax.servlet.jsp.tagext.TagVariableInfo; import javax.servlet.jsp.tagext.VariableInfo; import org.apache.jasper.Constants; import org.apache.jasper.JasperException; import org.apache.jasper.JspCompilationContext; import org.apache.jasper.compiler.Node.NamedAttribute; import org.apache.jasper.runtime.JspRuntimeLibrary; import org.xml.sax.Attributes; /** * Generate Java source from Nodes * * @author Anil K. Vijendran * @author Danno Ferrin * @author Mandar Raje * @author Rajiv Mordani * @author Pierre Delisle * * Tomcat 4.1.x and Tomcat 5: * @author Kin-man Chung * @author Jan Luehe * @author Shawn Bayern * @author Mark Roth * @author Denis Benoit * * Tomcat 6.x * @author Jacob Hookom * @author Remy Maucherat */ class Generator { private static final Class<?>[] OBJECT_CLASS = { Object.class }; private static final String VAR_EXPRESSIONFACTORY = System.getProperty("org.apache.jasper.compiler.Generator.VAR_EXPRESSIONFACTORY", "_el_expressionfactory"); private static final String VAR_INSTANCEMANAGER = System.getProperty("org.apache.jasper.compiler.Generator.VAR_INSTANCEMANAGER", "_jsp_instancemanager"); private ServletWriter out; private ArrayList<GenBuffer> methodsBuffered; private FragmentHelperClass fragmentHelperClass; private ErrorDispatcher err; private BeanRepository beanInfo; private Set<String> varInfoNames; private JspCompilationContext ctxt; private boolean isPoolingEnabled; private boolean breakAtLF; private String jspIdPrefix; private int jspId; private PageInfo pageInfo; private Vector<String> tagHandlerPoolNames; private GenBuffer charArrayBuffer; /** * @param s * the input string * @return quoted and escaped string, per Java rule */ static String quote(String s) { if (s == null) return "null"; return '"' + escape(s) + '"'; } /** * @param s * the input string * @return escaped string, per Java rule */ static String escape(String s) { if (s == null) return ""; StringBuilder b = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '"') b.append('\\').append('"'); else if (c == '\\') b.append('\\').append('\\'); else if (c == '\n') b.append('\\').append('n'); else if (c == '\r') b.append('\\').append('r'); else b.append(c); } return b.toString(); } /** * Single quote and escape a character */ static String quote(char c) { StringBuilder b = new StringBuilder(); b.append('\''); if (c == '\'') b.append('\\').append('\''); else if (c == '\\') b.append('\\').append('\\'); else if (c == '\n') b.append('\\').append('n'); else if (c == '\r') b.append('\\').append('r'); else b.append(c); b.append('\''); return b.toString(); } private String createJspId() { if (this.jspIdPrefix == null) { StringBuilder sb = new StringBuilder(32); String name = ctxt.getServletJavaFileName(); sb.append("jsp_").append(Math.abs(name.hashCode())).append('_'); this.jspIdPrefix = sb.toString(); } return this.jspIdPrefix + (this.jspId++); } /** * Generates declarations. This includes "info" of the page directive, and * scriptlet declarations. */ private void generateDeclarations(Node.Nodes page) throws JasperException { class DeclarationVisitor extends Node.Visitor { private boolean getServletInfoGenerated = false; /* * Generates getServletInfo() method that returns the value of the * page directive's 'info' attribute, if present. * * The Validator has already ensured that if the translation unit * contains more than one page directive with an 'info' attribute, * their values match. */ @Override public void visit(Node.PageDirective n) throws JasperException { if (getServletInfoGenerated) { return; } String info = n.getAttributeValue("info"); if (info == null) return; getServletInfoGenerated = true; out.printil("public String getServletInfo() {"); out.pushIndent(); out.printin("return "); out.print(quote(info)); out.println(";"); out.popIndent(); out.printil("}"); out.println(); } @Override public void visit(Node.Declaration n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); out.printMultiLn(new String(n.getText())); out.println(); n.setEndJavaLine(out.getJavaLine()); } // Custom Tags may contain declarations from tag plugins. @Override public void visit(Node.CustomTag n) throws JasperException { if (n.useTagPlugin()) { if (n.getAtSTag() != null) { n.getAtSTag().visit(this); } visitBody(n); if (n.getAtETag() != null) { n.getAtETag().visit(this); } } else { visitBody(n); } } } out.println(); page.visit(new DeclarationVisitor()); } /** * Compiles list of tag handler pool names. */ private void compileTagHandlerPoolList(Node.Nodes page) throws JasperException { class TagHandlerPoolVisitor extends Node.Visitor { private Vector<String> names; /* * Constructor * * @param v Vector of tag handler pool names to populate */ TagHandlerPoolVisitor(Vector<String> v) { names = v; } /* * Gets the name of the tag handler pool for the given custom tag * and adds it to the list of tag handler pool names unless it is * already contained in it. */ @Override public void visit(Node.CustomTag n) throws JasperException { if (!n.implementsSimpleTag()) { String name = createTagHandlerPoolName(n.getPrefix(), n .getLocalName(), n.getAttributes(), n.getNamedAttributeNodes(), n.hasEmptyBody()); n.setTagHandlerPoolName(name); if (!names.contains(name)) { names.add(name); } } visitBody(n); } /* * Creates the name of the tag handler pool whose tag handlers may * be (re)used to service this action. * * @return The name of the tag handler pool */ private String createTagHandlerPoolName(String prefix, String shortName, Attributes attrs, Node.Nodes namedAttrs, boolean hasEmptyBody) { String poolName = null; poolName = "_jspx_tagPool_" + prefix + "_" + shortName; if (attrs != null) { String[] attrNames = new String[attrs.getLength() + namedAttrs.size()]; for (int i = 0; i < attrNames.length; i++) { attrNames[i] = attrs.getQName(i); } for (int i = 0; i < namedAttrs.size(); i++) { attrNames[attrs.getLength() + i] = ((NamedAttribute) namedAttrs.getNode(i)).getQName(); } Arrays.sort(attrNames, Collections.reverseOrder()); if (attrNames.length > 0) { poolName = poolName + "&"; } for (int i = 0; i < attrNames.length; i++) { poolName = poolName + "_" + attrNames[i]; } } if (hasEmptyBody) { poolName = poolName + "_nobody"; } return JspUtil.makeJavaIdentifier(poolName); } } page.visit(new TagHandlerPoolVisitor(tagHandlerPoolNames)); } private void declareTemporaryScriptingVars(Node.Nodes page) throws JasperException { class ScriptingVarVisitor extends Node.Visitor { private Vector<String> vars; ScriptingVarVisitor() { vars = new Vector<String>(); } @Override public void visit(Node.CustomTag n) throws JasperException { if (n.getCustomNestingLevel() > 0) { TagVariableInfo[] tagVarInfos = n.getTagVariableInfos(); VariableInfo[] varInfos = n.getVariableInfos(); if (varInfos.length > 0) { for (int i = 0; i < varInfos.length; i++) { String varName = varInfos[i].getVarName(); String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); if (!vars.contains(tmpVarName)) { vars.add(tmpVarName); out.printin(varInfos[i].getClassName()); out.print(" "); out.print(tmpVarName); out.print(" = "); out.print(null); out.println(";"); } } } else { for (int i = 0; i < tagVarInfos.length; i++) { String varName = tagVarInfos[i].getNameGiven(); if (varName == null) { varName = n.getTagData().getAttributeString( tagVarInfos[i].getNameFromAttribute()); } else if (tagVarInfos[i].getNameFromAttribute() != null) { // alias continue; } String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); if (!vars.contains(tmpVarName)) { vars.add(tmpVarName); out.printin(tagVarInfos[i].getClassName()); out.print(" "); out.print(tmpVarName); out.print(" = "); out.print(null); out.println(";"); } } } } visitBody(n); } } page.visit(new ScriptingVarVisitor()); } /** * Generates the _jspInit() method for instantiating the tag handler pools. * For tag file, _jspInit has to be invoked manually, and the ServletConfig * object explicitly passed. * * In JSP 2.1, we also instantiate an ExpressionFactory */ private void generateInit() { if (ctxt.isTagFile()) { out.printil("private void _jspInit(ServletConfig config) {"); } else { out.printil("public void _jspInit() {"); } out.pushIndent(); if (isPoolingEnabled) { for (int i = 0; i < tagHandlerPoolNames.size(); i++) { out.printin(tagHandlerPoolNames.elementAt(i)); out.print(" = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool("); if (ctxt.isTagFile()) { out.print("config"); } else { out.print("getServletConfig()"); } out.println(");"); } } out.printin(VAR_EXPRESSIONFACTORY); out.print(" = _jspxFactory.getJspApplicationContext("); if (ctxt.isTagFile()) { out.print("config"); } else { out.print("getServletConfig()"); } out.println(".getServletContext()).getExpressionFactory();"); out.printin(VAR_INSTANCEMANAGER); out.print(" = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager("); if (ctxt.isTagFile()) { out.print("config"); } else { out.print("getServletConfig()"); } out.println(");"); out.popIndent(); out.printil("}"); out.println(); } /** * Generates the _jspDestroy() method which is responsible for calling the * release() method on every tag handler in any of the tag handler pools. */ private void generateDestroy() { out.printil("public void _jspDestroy() {"); out.pushIndent(); if (isPoolingEnabled) { for (int i = 0; i < tagHandlerPoolNames.size(); i++) { out.printin(tagHandlerPoolNames.elementAt(i)); out.println(".release();"); } } out.popIndent(); out.printil("}"); out.println(); } /** * Generate preamble package name (shared by servlet and tag handler * preamble generation) */ private void genPreamblePackage(String packageName) { if (!"".equals(packageName) && packageName != null) { out.printil("package " + packageName + ";"); out.println(); } } /** * Generate preamble imports (shared by servlet and tag handler preamble * generation) */ private void genPreambleImports() { Iterator<String> iter = pageInfo.getImports().iterator(); while (iter.hasNext()) { out.printin("import "); out.print(iter.next()); out.println(";"); } out.println(); } /** * Generation of static initializers in preamble. For example, dependent * list, el function map, prefix map. (shared by servlet and tag handler * preamble generation) */ private void genPreambleStaticInitializers() { out.printil("private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();"); out.println(); // Static data for getDependants() out.printil("private static java.util.List<String> _jspx_dependants;"); out.println(); List<String> dependants = pageInfo.getDependants(); Iterator<String> iter = dependants.iterator(); if (!dependants.isEmpty()) { out.printil("static {"); out.pushIndent(); out.printin("_jspx_dependants = new java.util.ArrayList<String>("); out.print("" + dependants.size()); out.println(");"); while (iter.hasNext()) { out.printin("_jspx_dependants.add(\""); out.print(iter.next()); out.println("\");"); } out.popIndent(); out.printil("}"); out.println(); } } /** * Declare tag handler pools (tags of the same type and with the same * attribute set share the same tag handler pool) (shared by servlet and tag * handler preamble generation) * * In JSP 2.1, we also scope an instance of ExpressionFactory */ private void genPreambleClassVariableDeclarations() { if (isPoolingEnabled && !tagHandlerPoolNames.isEmpty()) { for (int i = 0; i < tagHandlerPoolNames.size(); i++) { out.printil("private org.apache.jasper.runtime.TagHandlerPool " + tagHandlerPoolNames.elementAt(i) + ";"); } out.println(); } out.printin("private javax.el.ExpressionFactory "); out.print(VAR_EXPRESSIONFACTORY); out.println(";"); out.printin("private org.apache.tomcat.InstanceManager "); out.print(VAR_INSTANCEMANAGER); out.println(";"); out.println(); } /** * Declare general-purpose methods (shared by servlet and tag handler * preamble generation) */ private void genPreambleMethods() { // Method used to get compile time file dependencies out.printil("public java.util.List<String> getDependants() {"); out.pushIndent(); out.printil("return _jspx_dependants;"); out.popIndent(); out.printil("}"); out.println(); generateInit(); generateDestroy(); } /** * Generates the beginning of the static portion of the servlet. */ private void generatePreamble(Node.Nodes page) throws JasperException { String servletPackageName = ctxt.getServletPackageName(); String servletClassName = ctxt.getServletClassName(); String serviceMethodName = Constants.SERVICE_METHOD_NAME; // First the package name: genPreamblePackage(servletPackageName); // Generate imports genPreambleImports(); // Generate class declaration out.printin("public final class "); out.print(servletClassName); out.print(" extends "); out.println(pageInfo.getExtends()); out.printin(" implements org.apache.jasper.runtime.JspSourceDependent"); if (!pageInfo.isThreadSafe()) { out.println(","); out.printin(" SingleThreadModel"); } out.println(" {"); out.pushIndent(); // Class body begins here generateDeclarations(page); // Static initializations here genPreambleStaticInitializers(); // Class variable declarations genPreambleClassVariableDeclarations(); // Constructor // generateConstructor(className); // Methods here genPreambleMethods(); // Now the service method out.printin("public void "); out.print(serviceMethodName); out.println("(HttpServletRequest request, HttpServletResponse response)"); out.println(" throws java.io.IOException, ServletException {"); out.pushIndent(); out.println(); // Local variable declarations out.printil("PageContext pageContext = null;"); if (pageInfo.isSession()) out.printil("HttpSession session = null;"); if (pageInfo.isErrorPage()) { out.printil("Throwable exception = org.apache.jasper.runtime.JspRuntimeLibrary.getThrowable(request);"); out.printil("if (exception != null) {"); out.pushIndent(); out.printil("response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);"); out.popIndent(); out.printil("}"); } out.printil("ServletContext application = null;"); out.printil("ServletConfig config = null;"); out.printil("JspWriter out = null;"); out.printil("Object page = this;"); out.printil("JspWriter _jspx_out = null;"); out.printil("PageContext _jspx_page_context = null;"); out.println(); declareTemporaryScriptingVars(page); out.println(); out.printil("try {"); out.pushIndent(); out.printin("response.setContentType("); out.print(quote(pageInfo.getContentType())); out.println(");"); if (ctxt.getOptions().isXpoweredBy()) { out.printil("response.addHeader(\"X-Powered-By\", \"JSP/2.1\");"); } out .printil("pageContext = _jspxFactory.getPageContext(this, request, response,"); out.printin("\t\t\t"); out.print(quote(pageInfo.getErrorPage())); out.print(", " + pageInfo.isSession()); out.print(", " + pageInfo.getBuffer()); out.print(", " + pageInfo.isAutoFlush()); out.println(");"); out.printil("_jspx_page_context = pageContext;"); out.printil("application = pageContext.getServletContext();"); out.printil("config = pageContext.getServletConfig();"); if (pageInfo.isSession()) out.printil("session = pageContext.getSession();"); out.printil("out = pageContext.getOut();"); out.printil("_jspx_out = out;"); out.println(); } /** * Generates an XML Prolog, which includes an XML declaration and an XML * doctype declaration. */ private void generateXmlProlog(Node.Nodes page) { /* * An XML declaration is generated under the following conditions: - * 'omit-xml-declaration' attribute of <jsp:output> action is set to * "no" or "false" - JSP document without a <jsp:root> */ String omitXmlDecl = pageInfo.getOmitXmlDecl(); if ((omitXmlDecl != null && !JspUtil.booleanValue(omitXmlDecl)) || (omitXmlDecl == null && page.getRoot().isXmlSyntax() && !pageInfo.hasJspRoot() && !ctxt.isTagFile())) { String cType = pageInfo.getContentType(); String charSet = cType.substring(cType.indexOf("charset=") + 8); out.printil("out.write(\"<?xml version=\\\"1.0\\\" encoding=\\\"" + charSet + "\\\"?>\\n\");"); } /* * Output a DOCTYPE declaration if the doctype-root-element appears. If * doctype-public appears: <!DOCTYPE name PUBLIC "doctypePublic" * "doctypeSystem"> else <!DOCTYPE name SYSTEM "doctypeSystem" > */ String doctypeName = pageInfo.getDoctypeName(); if (doctypeName != null) { String doctypePublic = pageInfo.getDoctypePublic(); String doctypeSystem = pageInfo.getDoctypeSystem(); out.printin("out.write(\"<!DOCTYPE "); out.print(doctypeName); if (doctypePublic == null) { out.print(" SYSTEM \\\""); } else { out.print(" PUBLIC \\\""); out.print(doctypePublic); out.print("\\\" \\\""); } out.print(doctypeSystem); out.println("\\\">\\n\");"); } } /** * A visitor that generates codes for the elements in the page. */ class GenerateVisitor extends Node.Visitor { /* * Hashtable containing introspection information on tag handlers: * <key>: tag prefix <value>: hashtable containing introspection on tag * handlers: <key>: tag short name <value>: introspection info of tag * handler for <prefix:shortName> tag */ private Hashtable<String,Hashtable<String,TagHandlerInfo>> handlerInfos; private Hashtable<String,Integer> tagVarNumbers; private String parent; private boolean isSimpleTagParent; // Is parent a SimpleTag? private String pushBodyCountVar; private String simpleTagHandlerVar; private boolean isSimpleTagHandler; private boolean isFragment; private boolean isTagFile; private ServletWriter out; private ArrayList<GenBuffer> methodsBuffered; private FragmentHelperClass fragmentHelperClass; private int methodNesting; private int charArrayCount; private HashMap<String,String> textMap; /** * Constructor. */ public GenerateVisitor(boolean isTagFile, ServletWriter out, ArrayList<GenBuffer> methodsBuffered, FragmentHelperClass fragmentHelperClass) { this.isTagFile = isTagFile; this.out = out; this.methodsBuffered = methodsBuffered; this.fragmentHelperClass = fragmentHelperClass; methodNesting = 0; handlerInfos = new Hashtable<String,Hashtable<String,TagHandlerInfo>>(); tagVarNumbers = new Hashtable<String,Integer>(); textMap = new HashMap<String,String>(); } /** * Returns an attribute value, optionally URL encoded. If the value is a * runtime expression, the result is the expression itself, as a string. * If the result is an EL expression, we insert a call to the * interpreter. If the result is a Named Attribute we insert the * generated variable name. Otherwise the result is a string literal, * quoted and escaped. * * @param attr * An JspAttribute object * @param encode * true if to be URL encoded * @param expectedType * the expected type for an EL evaluation (ignored for * attributes that aren't EL expressions) */ private String attributeValue(Node.JspAttribute attr, boolean encode, Class<?> expectedType) { String v = attr.getValue(); if (!attr.isNamedAttribute() && (v == null)) return ""; if (attr.isExpression()) { if (encode) { return "org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode(String.valueOf(" + v + "), request.getCharacterEncoding())"; } return v; } else if (attr.isELInterpreterInput()) { v = attributeValueWithEL(this.isTagFile, v, expectedType, attr.getEL().getMapName()); if (encode) { return "org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode(" + v + ", request.getCharacterEncoding())"; } return v; } else if (attr.isNamedAttribute()) { return attr.getNamedAttributeNode().getTemporaryVariableName(); } else { if (encode) { return "org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode(" + quote(v) + ", request.getCharacterEncoding())"; } return quote(v); } } /* * When interpreting the EL attribute value, literals outside the EL * must not be unescaped but the EL processor will unescape them. * Therefore, make sure only the EL expressions are processed by the EL * processor. */ private String attributeValueWithEL(boolean isTag, String tx, Class<?> expectedType, String mapName) { if (tx==null) return null; Class<?> type = expectedType; int size = tx.length(); StringBuilder output = new StringBuilder(size); boolean el = false; int i = 0; int mark = 0; char ch; while(i < size){ ch = tx.charAt(i); // Start of an EL expression if (!el && i+1 < size && ch == '$' && tx.charAt(i+1)=='{') { if (mark < i) { if (output.length() > 0) { output.append(" + "); // Composite expression - must coerce to String type = String.class; } output.append(quote(tx.substring(mark, i))); } mark = i; el = true; i += 2; } else if (ch=='\\' && i+1 < size && (tx.charAt(i+1)=='$' || tx.charAt(i+1)=='}')) { // Skip an escaped $ or } i += 2; } else if (el && ch=='}') { // End of an EL expression if (output.length() > 0) { output.append(" + "); // Composite expression - must coerce to String type = String.class; } if (i+1 < size) { // Composite expression - must coerce to String type = String.class; } output.append( JspUtil.interpreterCall(isTag, tx.substring(mark, i+1), type, mapName, false)); mark = i + 1; el = false; ++i; } else { // Nothing to see here - move to next character ++i; } } if (!el && mark < i) { if (output.length() > 0) { output.append(" + "); } output.append(quote(tx.substring(mark, i))); } if (expectedType != type && !expectedType.isAssignableFrom(type)) { // Composite expression was evaluated to String // We must coerce it to the expected type. String className = JspUtil.getCanonicalName(expectedType); String methodName = null; if (expectedType.isPrimitive()) { if (expectedType == Boolean.TYPE) { className = "Boolean"; methodName = ".booleanValue()"; } else if (expectedType == Character.TYPE) { className = "Character"; methodName = ".charValue()"; } else if (expectedType == Byte.TYPE) { className = "Byte"; methodName = ".byteValue()"; } else if (expectedType == Short.TYPE) { className = "Short"; methodName = ".shortValue()"; } else if (expectedType == Integer.TYPE) { className = "Integer"; methodName = ".intValue()"; } else if (expectedType == Long.TYPE) { className = "Long"; methodName = ".longValue()"; } else if (expectedType == Float.TYPE) { className = "Float"; methodName = ".floatValue()"; } else if (expectedType == Double.TYPE) { className = "Double"; methodName = ".doubleValue()"; } } output.insert(0, "((" + className + ")org.apache.el.lang.ELSupport.coerceToType("); output.append(",").append(className).append(".class))"); if (methodName != null) { output.insert(0, '('); output.append(methodName).append(')'); } } return output.toString(); } /** * Prints the attribute value specified in the param action, in the form * of name=value string. * * @param n * the parent node for the param action nodes. */ private void printParams(Node n, String pageParam, boolean literal) throws JasperException { class ParamVisitor extends Node.Visitor { String separator; ParamVisitor(String separator) { this.separator = separator; } @Override public void visit(Node.ParamAction n) throws JasperException { out.print(" + "); out.print(separator); out.print(" + "); out.print("org.apache.jasper.runtime.JspRuntimeLibrary." + "URLEncode(" + quote(n.getTextAttribute("name")) + ", request.getCharacterEncoding())"); out.print("+ \"=\" + "); out.print(attributeValue(n.getValue(), true, String.class)); // The separator is '&' after the second use separator = "\"&\""; } } String sep; if (literal) { sep = pageParam.indexOf('?') > 0 ? "\"&\"" : "\"?\""; } else { sep = "((" + pageParam + ").indexOf('?')>0? '&': '?')"; } if (n.getBody() != null) { n.getBody().visit(new ParamVisitor(sep)); } } @Override public void visit(Node.Expression n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); out.printin("out.print("); out.printMultiLn(n.getText()); out.println(");"); n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.Scriptlet n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); out.printMultiLn(n.getText()); out.println(); n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.ELExpression n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); if (!pageInfo.isELIgnored() && (n.getEL() != null)) { out.printil("out.write(" + JspUtil.interpreterCall(this.isTagFile, n.getType() + "{" + new String(n.getText()) + "}", String.class, n.getEL().getMapName(), false) + ");"); } else { out.printil("out.write(" + quote(n.getType() + "{" + new String(n.getText()) + "}") + ");"); } n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.IncludeAction n) throws JasperException { String flush = n.getTextAttribute("flush"); Node.JspAttribute page = n.getPage(); boolean isFlush = false; // default to false; if ("true".equals(flush)) isFlush = true; n.setBeginJavaLine(out.getJavaLine()); String pageParam; if (page.isNamedAttribute()) { // If the page for jsp:include was specified via // jsp:attribute, first generate code to evaluate // that body. pageParam = generateNamedAttributeValue(page .getNamedAttributeNode()); } else { pageParam = attributeValue(page, false, String.class); } // If any of the params have their values specified by // jsp:attribute, prepare those values first. Node jspBody = findJspBody(n); if (jspBody != null) { prepareParams(jspBody); } else { prepareParams(n); } out .printin("org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, " + pageParam); printParams(n, pageParam, page.isLiteral()); out.println(", out, " + isFlush + ");"); n.setEndJavaLine(out.getJavaLine()); } /** * Scans through all child nodes of the given parent for <param> * subelements. For each <param> element, if its value is specified via * a Named Attribute (<jsp:attribute>), generate the code to evaluate * those bodies first. * <p> * If parent is null, simply returns. */ private void prepareParams(Node parent) throws JasperException { if (parent == null) return; Node.Nodes subelements = parent.getBody(); if (subelements != null) { for (int i = 0; i < subelements.size(); i++) { Node n = subelements.getNode(i); if (n instanceof Node.ParamAction) { Node.Nodes paramSubElements = n.getBody(); for (int j = 0; (paramSubElements != null) && (j < paramSubElements.size()); j++) { Node m = paramSubElements.getNode(j); if (m instanceof Node.NamedAttribute) { generateNamedAttributeValue((Node.NamedAttribute) m); } } } } } } /** * Finds the <jsp:body> subelement of the given parent node. If not * found, null is returned. */ private Node.JspBody findJspBody(Node parent) { Node.JspBody result = null; Node.Nodes subelements = parent.getBody(); for (int i = 0; (subelements != null) && (i < subelements.size()); i++) { Node n = subelements.getNode(i); if (n instanceof Node.JspBody) { result = (Node.JspBody) n; break; } } return result; } @Override public void visit(Node.ForwardAction n) throws JasperException { Node.JspAttribute page = n.getPage(); n.setBeginJavaLine(out.getJavaLine()); out.printil("if (true) {"); // So that javac won't complain about out.pushIndent(); // codes after "return" String pageParam; if (page.isNamedAttribute()) { // If the page for jsp:forward was specified via // jsp:attribute, first generate code to evaluate // that body. pageParam = generateNamedAttributeValue(page .getNamedAttributeNode()); } else { pageParam = attributeValue(page, false, String.class); } // If any of the params have their values specified by // jsp:attribute, prepare those values first. Node jspBody = findJspBody(n); if (jspBody != null) { prepareParams(jspBody); } else { prepareParams(n); } out.printin("_jspx_page_context.forward("); out.print(pageParam); printParams(n, pageParam, page.isLiteral()); out.println(");"); if (isTagFile || isFragment) { out.printil("throw new SkipPageException();"); } else { out.printil((methodNesting > 0) ? "return true;" : "return;"); } out.popIndent(); out.printil("}"); n.setEndJavaLine(out.getJavaLine()); // XXX Not sure if we can eliminate dead codes after this. } @Override public void visit(Node.GetProperty n) throws JasperException { String name = n.getTextAttribute("name"); String property = n.getTextAttribute("property"); n.setBeginJavaLine(out.getJavaLine()); if (beanInfo.checkVariable(name)) { // Bean is defined using useBean, introspect at compile time Class<?> bean = beanInfo.getBeanType(name); String beanName = JspUtil.getCanonicalName(bean); java.lang.reflect.Method meth = JspRuntimeLibrary .getReadMethod(bean, property); String methodName = meth.getName(); out .printil("out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString(" + "(((" + beanName + ")_jspx_page_context.findAttribute(" + "\"" + name + "\"))." + methodName + "())));"); } else if (varInfoNames.contains(name)) { // The object is a custom action with an associated // VariableInfo entry for this name. // Get the class name and then introspect at runtime. out .printil("out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString" + "(org.apache.jasper.runtime.JspRuntimeLibrary.handleGetProperty" + "(_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\")));"); } else { StringBuilder msg = new StringBuilder("jsp:getProperty for bean with name '"); msg.append(name); msg.append( "'. Name was not previously introduced as per JSP.5.3"); throw new JasperException(msg.toString()); } n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.SetProperty n) throws JasperException { String name = n.getTextAttribute("name"); String property = n.getTextAttribute("property"); String param = n.getTextAttribute("param"); Node.JspAttribute value = n.getValue(); n.setBeginJavaLine(out.getJavaLine()); if ("*".equals(property)) { out .printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspect(" + "_jspx_page_context.findAttribute(" + "\"" + name + "\"), request);"); } else if (value == null) { if (param == null) param = property; // default to same as property out .printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\", request.getParameter(\"" + param + "\"), " + "request, \"" + param + "\", false);"); } else if (value.isExpression()) { out .printil("org.apache.jasper.runtime.JspRuntimeLibrary.handleSetProperty(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\","); out.print(attributeValue(value, false, null)); out.println(");"); } else if (value.isELInterpreterInput()) { // We've got to resolve the very call to the interpreter // at runtime since we don't know what type to expect // in the general case; we thus can't hard-wire the call // into the generated code. (XXX We could, however, // optimize the case where the bean is exposed with // <jsp:useBean>, much as the code here does for // getProperty.) // The following holds true for the arguments passed to // JspRuntimeLibrary.handleSetPropertyExpression(): // - 'pageContext' is a VariableResolver. // - 'this' (either the generated Servlet or the generated tag // handler for Tag files) is a FunctionMapper. out .printil("org.apache.jasper.runtime.JspRuntimeLibrary.handleSetPropertyExpression(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\", " + quote(value.getValue()) + ", " + "_jspx_page_context, " + value.getEL().getMapName() + ");"); } else if (value.isNamedAttribute()) { // If the value for setProperty was specified via // jsp:attribute, first generate code to evaluate // that body. String valueVarName = generateNamedAttributeValue(value .getNamedAttributeNode()); out .printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\", " + valueVarName + ", null, null, false);"); } else { out .printin("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\", "); out.print(attributeValue(value, false, null)); out.println(", null, null, false);"); } n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.UseBean n) throws JasperException { String name = n.getTextAttribute("id"); String scope = n.getTextAttribute("scope"); String klass = n.getTextAttribute("class"); String type = n.getTextAttribute("type"); Node.JspAttribute beanName = n.getBeanName(); // If "class" is specified, try an instantiation at compile time boolean generateNew = false; String canonicalName = null; // Canonical name for klass if (klass != null) { try { Class<?> bean = ctxt.getClassLoader().loadClass(klass); if (klass.indexOf('$') >= 0) { // Obtain the canonical type name canonicalName = JspUtil.getCanonicalName(bean); } else { canonicalName = klass; } int modifiers = bean.getModifiers(); if (!Modifier.isPublic(modifiers) || Modifier.isInterface(modifiers) || Modifier.isAbstract(modifiers)) { throw new Exception("Invalid bean class modifier"); } // Check that there is a 0 arg constructor bean.getConstructor(new Class[] {}); // At compile time, we have determined that the bean class // exists, with a public zero constructor, new() can be // used for bean instantiation. generateNew = true; } catch (Exception e) { // Cannot instantiate the specified class, either a // compilation error or a runtime error will be raised, // depending on a compiler flag. if (ctxt.getOptions() .getErrorOnUseBeanInvalidClassAttribute()) { err.jspError(n, "jsp.error.invalid.bean", klass); } if (canonicalName == null) { // Doing our best here to get a canonical name // from the binary name, should work 99.99% of time. canonicalName = klass.replace('$', '.'); } } if (type == null) { // if type is unspecified, use "class" as type of bean type = canonicalName; } } String scopename = "PageContext.PAGE_SCOPE"; // Default to page String lock = "_jspx_page_context"; if ("request".equals(scope)) { scopename = "PageContext.REQUEST_SCOPE"; lock = "request"; } else if ("session".equals(scope)) { scopename = "PageContext.SESSION_SCOPE"; lock = "session"; } else if ("application".equals(scope)) { scopename = "PageContext.APPLICATION_SCOPE"; lock = "application"; } n.setBeginJavaLine(out.getJavaLine()); // Declare bean out.printin(type); out.print(' '); out.print(name); out.println(" = null;"); // Lock while getting or creating bean out.printin("synchronized ("); out.print(lock); out.println(") {"); out.pushIndent(); // Locate bean from context out.printin(name); out.print(" = ("); out.print(type); out.print(") _jspx_page_context.getAttribute("); out.print(quote(name)); out.print(", "); out.print(scopename); out.println(");"); // Create bean /* * Check if bean is already there */ out.printin("if ("); out.print(name); out.println(" == null){"); out.pushIndent(); if (klass == null && beanName == null) { /* * If both class name and beanName is not specified, the bean * must be found locally, otherwise it's an error */ out .printin("throw new java.lang.InstantiationException(\"bean "); out.print(name); out.println(" not found within scope\");"); } else { /* * Instantiate the bean if it is not in the specified scope. */ if (!generateNew) { String binaryName; if (beanName != null) { if (beanName.isNamedAttribute()) { // If the value for beanName was specified via // jsp:attribute, first generate code to evaluate // that body. binaryName = generateNamedAttributeValue(beanName .getNamedAttributeNode()); } else { binaryName = attributeValue(beanName, false, String.class); } } else { // Implies klass is not null binaryName = quote(klass); } out.printil("try {"); out.pushIndent(); out.printin(name); out.print(" = ("); out.print(type); out.print(") java.beans.Beans.instantiate("); out.print("this.getClass().getClassLoader(), "); out.print(binaryName); out.println(");"); out.popIndent(); /* * Note: Beans.instantiate throws ClassNotFoundException if * the bean class is abstract. */ out.printil("} catch (ClassNotFoundException exc) {"); out.pushIndent(); out .printil("throw new InstantiationException(exc.getMessage());"); out.popIndent(); out.printil("} catch (Exception exc) {"); out.pushIndent(); out.printin("throw new ServletException("); out.print("\"Cannot create bean of class \" + "); out.print(binaryName); out.println(", exc);"); out.popIndent(); out.printil("}"); // close of try } else { // Implies klass is not null // Generate codes to instantiate the bean class out.printin(name); out.print(" = new "); out.print(canonicalName); out.println("();"); } /* * Set attribute for bean in the specified scope */ out.printin("_jspx_page_context.setAttribute("); out.print(quote(name)); out.print(", "); out.print(name); out.print(", "); out.print(scopename); out.println(");"); // Only visit the body when bean is instantiated visitBody(n); } out.popIndent(); out.printil("}"); // End of lock block out.popIndent(); out.printil("}"); n.setEndJavaLine(out.getJavaLine()); } /** * @return a string for the form 'attr = "value"' */ private String makeAttr(String attr, String value) { if (value == null) return ""; return " " + attr + "=\"" + value + '\"'; } @Override public void visit(Node.PlugIn n) throws JasperException { /** * A visitor to handle <jsp:param> in a plugin */ class ParamVisitor extends Node.Visitor { private boolean ie; ParamVisitor(boolean ie) { this.ie = ie; } @Override public void visit(Node.ParamAction n) throws JasperException { String name = n.getTextAttribute("name"); if (name.equalsIgnoreCase("object")) name = "java_object"; else if (name.equalsIgnoreCase("type")) name = "java_type"; n.setBeginJavaLine(out.getJavaLine()); // XXX - Fixed a bug here - value used to be output // inline, which is only okay if value is not an EL // expression. Also, key/value pairs for the // embed tag were not being generated correctly. // Double check that this is now the correct behavior. if (ie) { // We want something of the form // out.println( "<param name=\"blah\" // value=\"" + ... + "\">" ); out.printil("out.write( \"<param name=\\\"" + escape(name) + "\\\" value=\\\"\" + " + attributeValue(n.getValue(), false, String.class) + " + \"\\\">\" );"); out.printil("out.write(\"\\n\");"); } else { // We want something of the form // out.print( " blah=\"" + ... + "\"" ); out.printil("out.write( \" " + escape(name) + "=\\\"\" + " + attributeValue(n.getValue(), false, String.class) + " + \"\\\"\" );"); } n.setEndJavaLine(out.getJavaLine()); } } String type = n.getTextAttribute("type"); String code = n.getTextAttribute("code"); String name = n.getTextAttribute("name"); Node.JspAttribute height = n.getHeight(); Node.JspAttribute width = n.getWidth(); String hspace = n.getTextAttribute("hspace"); String vspace = n.getTextAttribute("vspace"); String align = n.getTextAttribute("align"); String iepluginurl = n.getTextAttribute("iepluginurl"); String nspluginurl = n.getTextAttribute("nspluginurl"); String codebase = n.getTextAttribute("codebase"); String archive = n.getTextAttribute("archive"); String jreversion = n.getTextAttribute("jreversion"); String widthStr = null; if (width != null) { if (width.isNamedAttribute()) { widthStr = generateNamedAttributeValue(width .getNamedAttributeNode()); } else { widthStr = attributeValue(width, false, String.class); } } String heightStr = null; if (height != null) { if (height.isNamedAttribute()) { heightStr = generateNamedAttributeValue(height .getNamedAttributeNode()); } else { heightStr = attributeValue(height, false, String.class); } } if (iepluginurl == null) iepluginurl = Constants.IE_PLUGIN_URL; if (nspluginurl == null) nspluginurl = Constants.NS_PLUGIN_URL; n.setBeginJavaLine(out.getJavaLine()); // If any of the params have their values specified by // jsp:attribute, prepare those values first. // Look for a params node and prepare its param subelements: Node.JspBody jspBody = findJspBody(n); if (jspBody != null) { Node.Nodes subelements = jspBody.getBody(); if (subelements != null) { for (int i = 0; i < subelements.size(); i++) { Node m = subelements.getNode(i); if (m instanceof Node.ParamsAction) { prepareParams(m); break; } } } } // XXX - Fixed a bug here - width and height can be set // dynamically. Double-check if this generation is correct. // IE style plugin // <object ...> // First compose the runtime output string String s0 = "<object" + makeAttr("classid", ctxt.getOptions().getIeClassId()) + makeAttr("name", name); String s1 = ""; if (width != null) { s1 = " + \" width=\\\"\" + " + widthStr + " + \"\\\"\""; } String s2 = ""; if (height != null) { s2 = " + \" height=\\\"\" + " + heightStr + " + \"\\\"\""; } String s3 = makeAttr("hspace", hspace) + makeAttr("vspace", vspace) + makeAttr("align", align) + makeAttr("codebase", iepluginurl) + '>'; // Then print the output string to the java file out.printil("out.write(" + quote(s0) + s1 + s2 + " + " + quote(s3) + ");"); out.printil("out.write(\"\\n\");"); // <param > for java_code s0 = "<param name=\"java_code\"" + makeAttr("value", code) + '>'; out.printil("out.write(" + quote(s0) + ");"); out.printil("out.write(\"\\n\");"); // <param > for java_codebase if (codebase != null) { s0 = "<param name=\"java_codebase\"" + makeAttr("value", codebase) + '>'; out.printil("out.write(" + quote(s0) + ");"); out.printil("out.write(\"\\n\");"); } // <param > for java_archive if (archive != null) { s0 = "<param name=\"java_archive\"" + makeAttr("value", archive) + '>'; out.printil("out.write(" + quote(s0) + ");"); out.printil("out.write(\"\\n\");"); } // <param > for type s0 = "<param name=\"type\"" + makeAttr("value", "application/x-java-" + type + ((jreversion == null) ? "" : ";version=" + jreversion)) + '>'; out.printil("out.write(" + quote(s0) + ");"); out.printil("out.write(\"\\n\");"); /* * generate a <param> for each <jsp:param> in the plugin body */ if (n.getBody() != null) n.getBody().visit(new ParamVisitor(true)); /* * Netscape style plugin part */ out.printil("out.write(" + quote("<comment>") + ");"); out.printil("out.write(\"\\n\");"); s0 = "<EMBED" + makeAttr("type", "application/x-java-" + type + ((jreversion == null) ? "" : ";version=" + jreversion)) + makeAttr("name", name); // s1 and s2 are the same as before. s3 = makeAttr("hspace", hspace) + makeAttr("vspace", vspace) + makeAttr("align", align) + makeAttr("pluginspage", nspluginurl) + makeAttr("java_code", code) + makeAttr("java_codebase", codebase) + makeAttr("java_archive", archive); out.printil("out.write(" + quote(s0) + s1 + s2 + " + " + quote(s3) + ");"); /* * Generate a 'attr = "value"' for each <jsp:param> in plugin body */ if (n.getBody() != null) n.getBody().visit(new ParamVisitor(false)); out.printil("out.write(" + quote("/>") + ");"); out.printil("out.write(\"\\n\");"); out.printil("out.write(" + quote("<noembed>") + ");"); out.printil("out.write(\"\\n\");"); /* * Fallback */ if (n.getBody() != null) { visitBody(n); out.printil("out.write(\"\\n\");"); } out.printil("out.write(" + quote("</noembed>") + ");"); out.printil("out.write(\"\\n\");"); out.printil("out.write(" + quote("</comment>") + ");"); out.printil("out.write(\"\\n\");"); out.printil("out.write(" + quote("</object>") + ");"); out.printil("out.write(\"\\n\");"); n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.NamedAttribute n) throws JasperException { // Don't visit body of this tag - we already did earlier. } @Override public void visit(Node.CustomTag n) throws JasperException { // Use plugin to generate more efficient code if there is one. if (n.useTagPlugin()) { generateTagPlugin(n); return; } TagHandlerInfo handlerInfo = getTagHandlerInfo(n); // Create variable names String baseVar = createTagVarName(n.getQName(), n.getPrefix(), n .getLocalName()); String tagEvalVar = "_jspx_eval_" + baseVar; String tagHandlerVar = "_jspx_th_" + baseVar; String tagPushBodyCountVar = "_jspx_push_body_count_" + baseVar; // If the tag contains no scripting element, generate its codes // to a method. ServletWriter outSave = null; Node.ChildInfo ci = n.getChildInfo(); if (ci.isScriptless() && !ci.hasScriptingVars()) { // The tag handler and its body code can reside in a separate // method if it is scriptless and does not have any scripting // variable defined. String tagMethod = "_jspx_meth_" + baseVar; // Generate a call to this method out.printin("if ("); out.print(tagMethod); out.print("("); if (parent != null) { out.print(parent); out.print(", "); } out.print("_jspx_page_context"); if (pushBodyCountVar != null) { out.print(", "); out.print(pushBodyCountVar); } out.println("))"); out.pushIndent(); out.printil((methodNesting > 0) ? "return true;" : "return;"); out.popIndent(); // Set up new buffer for the method outSave = out; /* * For fragments, their bodies will be generated in fragment * helper classes, and the Java line adjustments will be done * there, hence they are set to null here to avoid double * adjustments. */ GenBuffer genBuffer = new GenBuffer(n, n.implementsSimpleTag() ? null : n.getBody()); methodsBuffered.add(genBuffer); out = genBuffer.getOut(); methodNesting++; // Generate code for method declaration out.println(); out.pushIndent(); out.printin("private boolean "); out.print(tagMethod); out.print("("); if (parent != null) { out.print("javax.servlet.jsp.tagext.JspTag "); out.print(parent); out.print(", "); } out.print("PageContext _jspx_page_context"); if (pushBodyCountVar != null) { out.print(", int[] "); out.print(pushBodyCountVar); } out.println(")"); out.printil(" throws Throwable {"); out.pushIndent(); // Initialize local variables used in this method. if (!isTagFile) { out .printil("PageContext pageContext = _jspx_page_context;"); } out.printil("JspWriter out = _jspx_page_context.getOut();"); generateLocalVariables(out, n); } // Add the named objects to the list of 'introduced' names to enable // a later test as per JSP.5.3 VariableInfo[] infos = n.getVariableInfos(); if (infos != null && infos.length > 0) { for (int i = 0; i < infos.length; i++) { VariableInfo info = infos[i]; if (info != null && info.getVarName() != null) pageInfo.getVarInfoNames().add(info.getVarName()); } } if (n.implementsSimpleTag()) { generateCustomDoTag(n, handlerInfo, tagHandlerVar); } else { /* * Classic tag handler: Generate code for start element, body, * and end element */ generateCustomStart(n, handlerInfo, tagHandlerVar, tagEvalVar, tagPushBodyCountVar); // visit body String tmpParent = parent; parent = tagHandlerVar; boolean isSimpleTagParentSave = isSimpleTagParent; isSimpleTagParent = false; String tmpPushBodyCountVar = null; if (n.implementsTryCatchFinally()) { tmpPushBodyCountVar = pushBodyCountVar; pushBodyCountVar = tagPushBodyCountVar; } boolean tmpIsSimpleTagHandler = isSimpleTagHandler; isSimpleTagHandler = false; visitBody(n); parent = tmpParent; isSimpleTagParent = isSimpleTagParentSave; if (n.implementsTryCatchFinally()) { pushBodyCountVar = tmpPushBodyCountVar; } isSimpleTagHandler = tmpIsSimpleTagHandler; generateCustomEnd(n, tagHandlerVar, tagEvalVar, tagPushBodyCountVar); } if (ci.isScriptless() && !ci.hasScriptingVars()) { // Generate end of method if (methodNesting > 0) { out.printil("return false;"); } out.popIndent(); out.printil("}"); out.popIndent(); methodNesting--; // restore previous writer out = outSave; } } private static final String DOUBLE_QUOTE = "\\\""; @Override public void visit(Node.UninterpretedTag n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); /* * Write begin tag */ out.printin("out.write(\"<"); out.print(n.getQName()); Attributes attrs = n.getNonTaglibXmlnsAttributes(); int attrsLen = (attrs == null) ? 0 : attrs.getLength(); for (int i = 0; i < attrsLen; i++) { out.print(" "); out.print(attrs.getQName(i)); out.print("="); out.print(DOUBLE_QUOTE); out.print(attrs.getValue(i).replace("\"", "&quot;")); out.print(DOUBLE_QUOTE); } attrs = n.getAttributes(); attrsLen = (attrs == null) ? 0 : attrs.getLength(); Node.JspAttribute[] jspAttrs = n.getJspAttributes(); for (int i = 0; i < attrsLen; i++) { out.print(" "); out.print(attrs.getQName(i)); out.print("="); if (jspAttrs[i].isELInterpreterInput()) { out.print("\\\"\" + "); out.print(attributeValue(jspAttrs[i], false, String.class)); out.print(" + \"\\\""); } else { out.print(DOUBLE_QUOTE); out.print(attrs.getValue(i).replace("\"", "&quot;")); out.print(DOUBLE_QUOTE); } } if (n.getBody() != null) { out.println(">\");"); // Visit tag body visitBody(n); /* * Write end tag */ out.printin("out.write(\"</"); out.print(n.getQName()); out.println(">\");"); } else { out.println("/>\");"); } n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.JspElement n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); // Compute attribute value string for XML-style and named // attributes Hashtable<String,String> map = new Hashtable<String,String>(); Node.JspAttribute[] attrs = n.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { String attrStr = null; if (attrs[i].isNamedAttribute()) { attrStr = generateNamedAttributeValue(attrs[i] .getNamedAttributeNode()); } else { attrStr = attributeValue(attrs[i], false, Object.class); } String s = " + \" " + attrs[i].getName() + "=\\\"\" + " + attrStr + " + \"\\\"\""; map.put(attrs[i].getName(), s); } // Write begin tag, using XML-style 'name' attribute as the // element name String elemName = attributeValue(n.getNameAttribute(), false, String.class); out.printin("out.write(\"<\""); out.print(" + " + elemName); // Write remaining attributes Enumeration<String> enumeration = map.keys(); while (enumeration.hasMoreElements()) { String attrName = enumeration.nextElement(); out.print(map.get(attrName)); } // Does the <jsp:element> have nested tags other than // <jsp:attribute> boolean hasBody = false; Node.Nodes subelements = n.getBody(); if (subelements != null) { for (int i = 0; i < subelements.size(); i++) { Node subelem = subelements.getNode(i); if (!(subelem instanceof Node.NamedAttribute)) { hasBody = true; break; } } } if (hasBody) { out.println(" + \">\");"); // Smap should not include the body n.setEndJavaLine(out.getJavaLine()); // Visit tag body visitBody(n); // Write end tag out.printin("out.write(\"</\""); out.print(" + " + elemName); out.println(" + \">\");"); } else { out.println(" + \"/>\");"); n.setEndJavaLine(out.getJavaLine()); } } @Override public void visit(Node.TemplateText n) throws JasperException { String text = n.getText(); int textSize = text.length(); if (textSize == 0) { return; } if (textSize <= 3) { // Special case small text strings n.setBeginJavaLine(out.getJavaLine()); int lineInc = 0; for (int i = 0; i < textSize; i++) { char ch = text.charAt(i); out.printil("out.write(" + quote(ch) + ");"); if (i > 0) { n.addSmap(lineInc); } if (ch == '\n') { lineInc++; } } n.setEndJavaLine(out.getJavaLine()); return; } if (ctxt.getOptions().genStringAsCharArray()) { // Generate Strings as char arrays, for performance ServletWriter caOut; if (charArrayBuffer == null) { charArrayBuffer = new GenBuffer(); caOut = charArrayBuffer.getOut(); caOut.pushIndent(); textMap = new HashMap<String,String>(); } else { caOut = charArrayBuffer.getOut(); } String charArrayName = textMap.get(text); if (charArrayName == null) { charArrayName = "_jspx_char_array_" + charArrayCount++; textMap.put(text, charArrayName); caOut.printin("static char[] "); caOut.print(charArrayName); caOut.print(" = "); caOut.print(quote(text)); caOut.println(".toCharArray();"); } n.setBeginJavaLine(out.getJavaLine()); out.printil("out.write(" + charArrayName + ");"); n.setEndJavaLine(out.getJavaLine()); return; } n.setBeginJavaLine(out.getJavaLine()); out.printin(); StringBuilder sb = new StringBuilder("out.write(\""); int initLength = sb.length(); int count = JspUtil.CHUNKSIZE; int srcLine = 0; // relative to starting source line for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); --count; switch (ch) { case '"': sb.append('\\').append('\"'); break; case '\\': sb.append('\\').append('\\'); break; case '\r': sb.append('\\').append('r'); break; case '\n': sb.append('\\').append('n'); srcLine++; if (breakAtLF || count < 0) { // Generate an out.write() when see a '\n' in template sb.append("\");"); out.println(sb.toString()); if (i < text.length() - 1) { out.printin(); } sb.setLength(initLength); count = JspUtil.CHUNKSIZE; } // add a Smap for this line n.addSmap(srcLine); break; case '\t': // Not sure we need this sb.append('\\').append('t'); break; default: sb.append(ch); } } if (sb.length() > initLength) { sb.append("\");"); out.println(sb.toString()); } n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.JspBody n) throws JasperException { if (n.getBody() != null) { if (isSimpleTagHandler) { out.printin(simpleTagHandlerVar); out.print(".setJspBody("); generateJspFragment(n, simpleTagHandlerVar); out.println(");"); } else { visitBody(n); } } } @Override public void visit(Node.InvokeAction n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); // Copy virtual page scope of tag file to page scope of invoking // page out.printil("((org.apache.jasper.runtime.JspContextWrapper) this.jspContext).syncBeforeInvoke();"); String varReaderAttr = n.getTextAttribute("varReader"); String varAttr = n.getTextAttribute("var"); if (varReaderAttr != null || varAttr != null) { out.printil("_jspx_sout = new java.io.StringWriter();"); } else { out.printil("_jspx_sout = null;"); } // Invoke fragment, unless fragment is null out.printin("if ("); out.print(toGetterMethod(n.getTextAttribute("fragment"))); out.println(" != null) {"); out.pushIndent(); out.printin(toGetterMethod(n.getTextAttribute("fragment"))); out.println(".invoke(_jspx_sout);"); out.popIndent(); out.printil("}"); // Store varReader in appropriate scope if (varReaderAttr != null || varAttr != null) { String scopeName = n.getTextAttribute("scope"); out.printin("_jspx_page_context.setAttribute("); if (varReaderAttr != null) { out.print(quote(varReaderAttr)); out.print(", new java.io.StringReader(_jspx_sout.toString())"); } else { out.print(quote(varAttr)); out.print(", _jspx_sout.toString()"); } if (scopeName != null) { out.print(", "); out.print(getScopeConstant(scopeName)); } out.println(");"); } // Restore EL context out.printil("jspContext.getELContext().putContext(JspContext.class,getJspContext());"); n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.DoBodyAction n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); // Copy virtual page scope of tag file to page scope of invoking // page out.printil("((org.apache.jasper.runtime.JspContextWrapper) this.jspContext).syncBeforeInvoke();"); // Invoke body String varReaderAttr = n.getTextAttribute("varReader"); String varAttr = n.getTextAttribute("var"); if (varReaderAttr != null || varAttr != null) { out.printil("_jspx_sout = new java.io.StringWriter();"); } else { out.printil("_jspx_sout = null;"); } out.printil("if (getJspBody() != null)"); out.pushIndent(); out.printil("getJspBody().invoke(_jspx_sout);"); out.popIndent(); // Store varReader in appropriate scope if (varReaderAttr != null || varAttr != null) { String scopeName = n.getTextAttribute("scope"); out.printin("_jspx_page_context.setAttribute("); if (varReaderAttr != null) { out.print(quote(varReaderAttr)); out .print(", new java.io.StringReader(_jspx_sout.toString())"); } else { out.print(quote(varAttr)); out.print(", _jspx_sout.toString()"); } if (scopeName != null) { out.print(", "); out.print(getScopeConstant(scopeName)); } out.println(");"); } // Restore EL context out.printil("jspContext.getELContext().putContext(JspContext.class,getJspContext());"); n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.AttributeGenerator n) throws JasperException { Node.CustomTag tag = n.getTag(); Node.JspAttribute[] attrs = tag.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { if (attrs[i].getName().equals(n.getName())) { out.print(evaluateAttribute(getTagHandlerInfo(tag), attrs[i], tag, null)); break; } } } private TagHandlerInfo getTagHandlerInfo(Node.CustomTag n) throws JasperException { Hashtable<String,TagHandlerInfo> handlerInfosByShortName = handlerInfos.get(n.getPrefix()); if (handlerInfosByShortName == null) { handlerInfosByShortName = new Hashtable<String,TagHandlerInfo>(); handlerInfos.put(n.getPrefix(), handlerInfosByShortName); } TagHandlerInfo handlerInfo = handlerInfosByShortName.get(n.getLocalName()); if (handlerInfo == null) { handlerInfo = new TagHandlerInfo(n, n.getTagHandlerClass(), err); handlerInfosByShortName.put(n.getLocalName(), handlerInfo); } return handlerInfo; } private void generateTagPlugin(Node.CustomTag n) throws JasperException { if (n.getAtSTag() != null) { n.getAtSTag().visit(this); } visitBody(n); if (n.getAtETag() != null) { n.getAtETag().visit(this); } } private void generateCustomStart(Node.CustomTag n, TagHandlerInfo handlerInfo, String tagHandlerVar, String tagEvalVar, String tagPushBodyCountVar) throws JasperException { Class<?> tagHandlerClass = handlerInfo.getTagHandlerClass(); out.printin("// "); out.println(n.getQName()); n.setBeginJavaLine(out.getJavaLine()); // Declare AT_BEGIN scripting variables declareScriptingVars(n, VariableInfo.AT_BEGIN); saveScriptingVars(n, VariableInfo.AT_BEGIN); String tagHandlerClassName = JspUtil .getCanonicalName(tagHandlerClass); if (isPoolingEnabled && !(n.implementsJspIdConsumer())) { out.printin(tagHandlerClassName); out.print(" "); out.print(tagHandlerVar); out.print(" = "); out.print("("); out.print(tagHandlerClassName); out.print(") "); out.print(n.getTagHandlerPoolName()); out.print(".get("); out.print(tagHandlerClassName); out.println(".class);"); } else { writeNewInstance(tagHandlerVar, tagHandlerClassName); } // includes setting the context generateSetters(n, tagHandlerVar, handlerInfo, false); // JspIdConsumer (after context has been set) if (n.implementsJspIdConsumer()) { out.printin(tagHandlerVar); out.print(".setJspId(\""); out.print(createJspId()); out.println("\");"); } if (n.implementsTryCatchFinally()) { out.printin("int[] "); out.print(tagPushBodyCountVar); out.println(" = new int[] { 0 };"); out.printil("try {"); out.pushIndent(); } out.printin("int "); out.print(tagEvalVar); out.print(" = "); out.print(tagHandlerVar); out.println(".doStartTag();"); if (!n.implementsBodyTag()) { // Synchronize AT_BEGIN scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); } if (!n.hasEmptyBody()) { out.printin("if ("); out.print(tagEvalVar); out.println(" != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {"); out.pushIndent(); // Declare NESTED scripting variables declareScriptingVars(n, VariableInfo.NESTED); saveScriptingVars(n, VariableInfo.NESTED); if (n.implementsBodyTag()) { out.printin("if ("); out.print(tagEvalVar); out .println(" != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {"); // Assume EVAL_BODY_BUFFERED out.pushIndent(); out.printil("out = _jspx_page_context.pushBody();"); if (n.implementsTryCatchFinally()) { out.printin(tagPushBodyCountVar); out.println("[0]++;"); } else if (pushBodyCountVar != null) { out.printin(pushBodyCountVar); out.println("[0]++;"); } out.printin(tagHandlerVar); out.println(".setBodyContent((javax.servlet.jsp.tagext.BodyContent) out);"); out.printin(tagHandlerVar); out.println(".doInitBody();"); out.popIndent(); out.printil("}"); // Synchronize AT_BEGIN and NESTED scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); syncScriptingVars(n, VariableInfo.NESTED); } else { // Synchronize NESTED scripting variables syncScriptingVars(n, VariableInfo.NESTED); } if (n.implementsIterationTag()) { out.printil("do {"); out.pushIndent(); } } // Map the Java lines that handles start of custom tags to the // JSP line for this tag n.setEndJavaLine(out.getJavaLine()); } private void writeNewInstance(String tagHandlerVar, String tagHandlerClassName) { if (Constants.USE_INSTANCE_MANAGER_FOR_TAGS) { out.printin(tagHandlerClassName); out.print(" "); out.print(tagHandlerVar); out.print(" = ("); out.print(tagHandlerClassName); out.print(")"); out.print(VAR_INSTANCEMANAGER); out.print(".newInstance(\""); out.print(tagHandlerClassName); out.println("\", this.getClass().getClassLoader());"); } else { out.printin(tagHandlerClassName); out.print(" "); out.print(tagHandlerVar); out.print(" = ("); out.print("new "); out.print(tagHandlerClassName); out.println("());"); out.printin(VAR_INSTANCEMANAGER); out.print(".newInstance("); out.print(tagHandlerVar); out.println(");"); } } private void writeDestroyInstance(String tagHandlerVar) { out.printin(VAR_INSTANCEMANAGER); out.print(".destroyInstance("); out.print(tagHandlerVar); out.println(");"); } private void generateCustomEnd(Node.CustomTag n, String tagHandlerVar, String tagEvalVar, String tagPushBodyCountVar) { if (!n.hasEmptyBody()) { if (n.implementsIterationTag()) { out.printin("int evalDoAfterBody = "); out.print(tagHandlerVar); out.println(".doAfterBody();"); // Synchronize AT_BEGIN and NESTED scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); syncScriptingVars(n, VariableInfo.NESTED); out .printil("if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)"); out.pushIndent(); out.printil("break;"); out.popIndent(); out.popIndent(); out.printil("} while (true);"); } restoreScriptingVars(n, VariableInfo.NESTED); if (n.implementsBodyTag()) { out.printin("if ("); out.print(tagEvalVar); out .println(" != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {"); out.pushIndent(); out.printil("out = _jspx_page_context.popBody();"); if (n.implementsTryCatchFinally()) { out.printin(tagPushBodyCountVar); out.println("[0]--;"); } else if (pushBodyCountVar != null) { out.printin(pushBodyCountVar); out.println("[0]--;"); } out.popIndent(); out.printil("}"); } out.popIndent(); // EVAL_BODY out.printil("}"); } out.printin("if ("); out.print(tagHandlerVar); out .println(".doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {"); out.pushIndent(); if (!n.implementsTryCatchFinally()) { if (isPoolingEnabled && !(n.implementsJspIdConsumer())) { out.printin(n.getTagHandlerPoolName()); out.print(".reuse("); out.print(tagHandlerVar); out.println(");"); } else { out.printin(tagHandlerVar); out.println(".release();"); writeDestroyInstance(tagHandlerVar); } } if (isTagFile || isFragment) { out.printil("throw new SkipPageException();"); } else { out.printil((methodNesting > 0) ? "return true;" : "return;"); } out.popIndent(); out.printil("}"); // Synchronize AT_BEGIN scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); // TryCatchFinally if (n.implementsTryCatchFinally()) { out.popIndent(); // try out.printil("} catch (Throwable _jspx_exception) {"); out.pushIndent(); out.printin("while ("); out.print(tagPushBodyCountVar); out.println("[0]-- > 0)"); out.pushIndent(); out.printil("out = _jspx_page_context.popBody();"); out.popIndent(); out.printin(tagHandlerVar); out.println(".doCatch(_jspx_exception);"); out.popIndent(); out.printil("} finally {"); out.pushIndent(); out.printin(tagHandlerVar); out.println(".doFinally();"); } if (isPoolingEnabled && !(n.implementsJspIdConsumer())) { out.printin(n.getTagHandlerPoolName()); out.print(".reuse("); out.print(tagHandlerVar); out.println(");"); } else { out.printin(tagHandlerVar); out.println(".release();"); writeDestroyInstance(tagHandlerVar); } if (n.implementsTryCatchFinally()) { out.popIndent(); out.printil("}"); } // Declare and synchronize AT_END scripting variables (must do this // outside the try/catch/finally block) declareScriptingVars(n, VariableInfo.AT_END); syncScriptingVars(n, VariableInfo.AT_END); restoreScriptingVars(n, VariableInfo.AT_BEGIN); } private void generateCustomDoTag(Node.CustomTag n, TagHandlerInfo handlerInfo, String tagHandlerVar) throws JasperException { Class<?> tagHandlerClass = handlerInfo.getTagHandlerClass(); n.setBeginJavaLine(out.getJavaLine()); out.printin("// "); out.println(n.getQName()); // Declare AT_BEGIN scripting variables declareScriptingVars(n, VariableInfo.AT_BEGIN); saveScriptingVars(n, VariableInfo.AT_BEGIN); String tagHandlerClassName = JspUtil .getCanonicalName(tagHandlerClass); writeNewInstance(tagHandlerVar, tagHandlerClassName); generateSetters(n, tagHandlerVar, handlerInfo, true); // JspIdConsumer (after context has been set) if (n.implementsJspIdConsumer()) { out.printin(tagHandlerVar); out.print(".setJspId(\""); out.print(createJspId()); out.println("\");"); } // Set the body if (findJspBody(n) == null) { /* * Encapsulate body of custom tag invocation in JspFragment and * pass it to tag handler's setJspBody(), unless tag body is * empty */ if (!n.hasEmptyBody()) { out.printin(tagHandlerVar); out.print(".setJspBody("); generateJspFragment(n, tagHandlerVar); out.println(");"); } } else { /* * Body of tag is the body of the <jsp:body> element. The visit * method for that element is going to encapsulate that * element's body in a JspFragment and pass it to the tag * handler's setJspBody() */ String tmpTagHandlerVar = simpleTagHandlerVar; simpleTagHandlerVar = tagHandlerVar; boolean tmpIsSimpleTagHandler = isSimpleTagHandler; isSimpleTagHandler = true; visitBody(n); simpleTagHandlerVar = tmpTagHandlerVar; isSimpleTagHandler = tmpIsSimpleTagHandler; } out.printin(tagHandlerVar); out.println(".doTag();"); restoreScriptingVars(n, VariableInfo.AT_BEGIN); // Synchronize AT_BEGIN scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); // Declare and synchronize AT_END scripting variables declareScriptingVars(n, VariableInfo.AT_END); syncScriptingVars(n, VariableInfo.AT_END); // Resource injection writeDestroyInstance(tagHandlerVar); n.setEndJavaLine(out.getJavaLine()); } private void declareScriptingVars(Node.CustomTag n, int scope) { Vector<Object> vec = n.getScriptingVars(scope); if (vec != null) { for (int i = 0; i < vec.size(); i++) { Object elem = vec.elementAt(i); if (elem instanceof VariableInfo) { VariableInfo varInfo = (VariableInfo) elem; if (varInfo.getDeclare()) { out.printin(varInfo.getClassName()); out.print(" "); out.print(varInfo.getVarName()); out.println(" = null;"); } } else { TagVariableInfo tagVarInfo = (TagVariableInfo) elem; if (tagVarInfo.getDeclare()) { String varName = tagVarInfo.getNameGiven(); if (varName == null) { varName = n.getTagData().getAttributeString( tagVarInfo.getNameFromAttribute()); } else if (tagVarInfo.getNameFromAttribute() != null) { // alias continue; } out.printin(tagVarInfo.getClassName()); out.print(" "); out.print(varName); out.println(" = null;"); } } } } } /* * This method is called as part of the custom tag's start element. * * If the given custom tag has a custom nesting level greater than 0, * save the current values of its scripting variables to temporary * variables, so those values may be restored in the tag's end element. * This way, the scripting variables may be synchronized by the given * tag without affecting their original values. */ private void saveScriptingVars(Node.CustomTag n, int scope) { if (n.getCustomNestingLevel() == 0) { return; } TagVariableInfo[] tagVarInfos = n.getTagVariableInfos(); VariableInfo[] varInfos = n.getVariableInfos(); if ((varInfos.length == 0) && (tagVarInfos.length == 0)) { return; } if (varInfos.length > 0) { for (int i = 0; i < varInfos.length; i++) { if (varInfos[i].getScope() != scope) continue; // If the scripting variable has been declared, skip codes // for saving and restoring it. if (n.getScriptingVars(scope).contains(varInfos[i])) continue; String varName = varInfos[i].getVarName(); String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); out.printin(tmpVarName); out.print(" = "); out.print(varName); out.println(";"); } } else { for (int i = 0; i < tagVarInfos.length; i++) { if (tagVarInfos[i].getScope() != scope) continue; // If the scripting variable has been declared, skip codes // for saving and restoring it. if (n.getScriptingVars(scope).contains(tagVarInfos[i])) continue; String varName = tagVarInfos[i].getNameGiven(); if (varName == null) { varName = n.getTagData().getAttributeString( tagVarInfos[i].getNameFromAttribute()); } else if (tagVarInfos[i].getNameFromAttribute() != null) { // alias continue; } String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); out.printin(tmpVarName); out.print(" = "); out.print(varName); out.println(";"); } } } /* * This method is called as part of the custom tag's end element. * * If the given custom tag has a custom nesting level greater than 0, * restore its scripting variables to their original values that were * saved in the tag's start element. */ private void restoreScriptingVars(Node.CustomTag n, int scope) { if (n.getCustomNestingLevel() == 0) { return; } TagVariableInfo[] tagVarInfos = n.getTagVariableInfos(); VariableInfo[] varInfos = n.getVariableInfos(); if ((varInfos.length == 0) && (tagVarInfos.length == 0)) { return; } if (varInfos.length > 0) { for (int i = 0; i < varInfos.length; i++) { if (varInfos[i].getScope() != scope) continue; // If the scripting variable has been declared, skip codes // for saving and restoring it. if (n.getScriptingVars(scope).contains(varInfos[i])) continue; String varName = varInfos[i].getVarName(); String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); out.printin(varName); out.print(" = "); out.print(tmpVarName); out.println(";"); } } else { for (int i = 0; i < tagVarInfos.length; i++) { if (tagVarInfos[i].getScope() != scope) continue; // If the scripting variable has been declared, skip codes // for saving and restoring it. if (n.getScriptingVars(scope).contains(tagVarInfos[i])) continue; String varName = tagVarInfos[i].getNameGiven(); if (varName == null) { varName = n.getTagData().getAttributeString( tagVarInfos[i].getNameFromAttribute()); } else if (tagVarInfos[i].getNameFromAttribute() != null) { // alias continue; } String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); out.printin(varName); out.print(" = "); out.print(tmpVarName); out.println(";"); } } } /* * Synchronizes the scripting variables of the given custom tag for the * given scope. */ private void syncScriptingVars(Node.CustomTag n, int scope) { TagVariableInfo[] tagVarInfos = n.getTagVariableInfos(); VariableInfo[] varInfos = n.getVariableInfos(); if ((varInfos.length == 0) && (tagVarInfos.length == 0)) { return; } if (varInfos.length > 0) { for (int i = 0; i < varInfos.length; i++) { if (varInfos[i].getScope() == scope) { out.printin(varInfos[i].getVarName()); out.print(" = ("); out.print(varInfos[i].getClassName()); out.print(") _jspx_page_context.findAttribute("); out.print(quote(varInfos[i].getVarName())); out.println(");"); } } } else { for (int i = 0; i < tagVarInfos.length; i++) { if (tagVarInfos[i].getScope() == scope) { String name = tagVarInfos[i].getNameGiven(); if (name == null) { name = n.getTagData().getAttributeString( tagVarInfos[i].getNameFromAttribute()); } else if (tagVarInfos[i].getNameFromAttribute() != null) { // alias continue; } out.printin(name); out.print(" = ("); out.print(tagVarInfos[i].getClassName()); out.print(") _jspx_page_context.findAttribute("); out.print(quote(name)); out.println(");"); } } } } private String getJspContextVar() { if (this.isTagFile) { return "this.getJspContext()"; } return "_jspx_page_context"; } private String getExpressionFactoryVar() { return VAR_EXPRESSIONFACTORY; } /* * Creates a tag variable name by concatenating the given prefix and * shortName and encoded to make the resultant string a valid Java * Identifier. */ private String createTagVarName(String fullName, String prefix, String shortName) { String varName; synchronized (tagVarNumbers) { varName = prefix + "_" + shortName + "_"; if (tagVarNumbers.get(fullName) != null) { Integer i = tagVarNumbers.get(fullName); varName = varName + i.intValue(); tagVarNumbers.put(fullName, new Integer(i.intValue() + 1)); } else { tagVarNumbers.put(fullName, new Integer(1)); varName = varName + "0"; } } return JspUtil.makeJavaIdentifier(varName); } private String evaluateAttribute(TagHandlerInfo handlerInfo, Node.JspAttribute attr, Node.CustomTag n, String tagHandlerVar) throws JasperException { String attrValue = attr.getValue(); if (attrValue == null) { if (attr.isNamedAttribute()) { if (n.checkIfAttributeIsJspFragment(attr.getName())) { // XXX - no need to generate temporary variable here attrValue = generateNamedAttributeJspFragment(attr .getNamedAttributeNode(), tagHandlerVar); } else { attrValue = generateNamedAttributeValue(attr .getNamedAttributeNode()); } } else { return null; } } String localName = attr.getLocalName(); Method m = null; Class<?>[] c = null; if (attr.isDynamic()) { c = OBJECT_CLASS; } else { m = handlerInfo.getSetterMethod(localName); if (m == null) { err.jspError(n, "jsp.error.unable.to_find_method", attr .getName()); } c = m.getParameterTypes(); // XXX assert(c.length > 0) } if (attr.isExpression()) { // Do nothing } else if (attr.isNamedAttribute()) { if (!n.checkIfAttributeIsJspFragment(attr.getName()) && !attr.isDynamic()) { attrValue = convertString(c[0], attrValue, localName, handlerInfo.getPropertyEditorClass(localName), true); } } else if (attr.isELInterpreterInput()) { // results buffer StringBuilder sb = new StringBuilder(64); TagAttributeInfo tai = attr.getTagAttributeInfo(); // generate elContext reference sb.append(getJspContextVar()); sb.append(".getELContext()"); String elContext = sb.toString(); if (attr.getEL() != null && attr.getEL().getMapName() != null) { sb.setLength(0); sb.append("new org.apache.jasper.el.ELContextWrapper("); sb.append(elContext); sb.append(','); sb.append(attr.getEL().getMapName()); sb.append(')'); elContext = sb.toString(); } // reset buffer sb.setLength(0); // create our mark sb.append(n.getStart().toString()); sb.append(" '"); sb.append(attrValue); sb.append('\''); String mark = sb.toString(); // reset buffer sb.setLength(0); // depending on type if (attr.isDeferredInput() || ((tai != null) && ValueExpression.class.getName().equals(tai.getTypeName()))) { sb.append("new org.apache.jasper.el.JspValueExpression("); sb.append(quote(mark)); sb.append(','); sb.append(getExpressionFactoryVar()); sb.append(".createValueExpression("); if (attr.getEL() != null) { // optimize sb.append(elContext); sb.append(','); } sb.append(quote(attrValue)); sb.append(','); sb.append(JspUtil.toJavaSourceTypeFromTld(attr.getExpectedTypeName())); sb.append("))"); // should the expression be evaluated before passing to // the setter? boolean evaluate = false; if (tai.canBeRequestTime()) { evaluate = true; // JSP.2.3.2 } if (attr.isDeferredInput()) { evaluate = false; // JSP.2.3.3 } if (attr.isDeferredInput() && tai.canBeRequestTime()) { evaluate = !attrValue.contains("#{"); // JSP.2.3.5 } if (evaluate) { sb.append(".getValue("); sb.append(getJspContextVar()); sb.append(".getELContext()"); sb.append(")"); } attrValue = sb.toString(); } else if (attr.isDeferredMethodInput() || ((tai != null) && MethodExpression.class.getName().equals(tai.getTypeName()))) { sb.append("new org.apache.jasper.el.JspMethodExpression("); sb.append(quote(mark)); sb.append(','); sb.append(getExpressionFactoryVar()); sb.append(".createMethodExpression("); sb.append(elContext); sb.append(','); sb.append(quote(attrValue)); sb.append(','); sb.append(JspUtil.toJavaSourceTypeFromTld(attr.getExpectedTypeName())); sb.append(','); sb.append("new Class[] {"); String[] p = attr.getParameterTypeNames(); for (int i = 0; i < p.length; i++) { sb.append(JspUtil.toJavaSourceTypeFromTld(p[i])); sb.append(','); } if (p.length > 0) { sb.setLength(sb.length() - 1); } sb.append("}))"); attrValue = sb.toString(); } else { // run attrValue through the expression interpreter String mapName = (attr.getEL() != null) ? attr.getEL() .getMapName() : null; attrValue = attributeValueWithEL(this.isTagFile, attrValue, c[0], mapName); } } else { attrValue = convertString(c[0], attrValue, localName, handlerInfo.getPropertyEditorClass(localName), false); } return attrValue; } /** * Generate code to create a map for the alias variables * * @return the name of the map */ private String generateAliasMap(Node.CustomTag n, String tagHandlerVar) { TagVariableInfo[] tagVars = n.getTagVariableInfos(); String aliasMapVar = null; boolean aliasSeen = false; for (int i = 0; i < tagVars.length; i++) { String nameFrom = tagVars[i].getNameFromAttribute(); if (nameFrom != null) { String aliasedName = n.getAttributeValue(nameFrom); if (aliasedName == null) continue; if (!aliasSeen) { out.printin("java.util.HashMap "); aliasMapVar = tagHandlerVar + "_aliasMap"; out.print(aliasMapVar); out.println(" = new java.util.HashMap();"); aliasSeen = true; } out.printin(aliasMapVar); out.print(".put("); out.print(quote(tagVars[i].getNameGiven())); out.print(", "); out.print(quote(aliasedName)); out.println(");"); } } return aliasMapVar; } private void generateSetters(Node.CustomTag n, String tagHandlerVar, TagHandlerInfo handlerInfo, boolean simpleTag) throws JasperException { // Set context if (simpleTag) { // Generate alias map String aliasMapVar = null; if (n.isTagFile()) { aliasMapVar = generateAliasMap(n, tagHandlerVar); } out.printin(tagHandlerVar); if (aliasMapVar == null) { out.println(".setJspContext(_jspx_page_context);"); } else { out.print(".setJspContext(_jspx_page_context, "); out.print(aliasMapVar); out.println(");"); } } else { out.printin(tagHandlerVar); out.println(".setPageContext(_jspx_page_context);"); } // Set parent if (isTagFile && parent == null) { out.printin(tagHandlerVar); out.print(".setParent("); out.print("new javax.servlet.jsp.tagext.TagAdapter("); out.print("(javax.servlet.jsp.tagext.SimpleTag) this ));"); } else if (!simpleTag) { out.printin(tagHandlerVar); out.print(".setParent("); if (parent != null) { if (isSimpleTagParent) { out.print("new javax.servlet.jsp.tagext.TagAdapter("); out.print("(javax.servlet.jsp.tagext.SimpleTag) "); out.print(parent); out.println("));"); } else { out.print("(javax.servlet.jsp.tagext.Tag) "); out.print(parent); out.println(");"); } } else { out.println("null);"); } } else { // The setParent() method need not be called if the value being // passed is null, since SimpleTag instances are not reused if (parent != null) { out.printin(tagHandlerVar); out.print(".setParent("); out.print(parent); out.println(");"); } } // need to handle deferred values and methods Node.JspAttribute[] attrs = n.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { String attrValue = evaluateAttribute(handlerInfo, attrs[i], n, tagHandlerVar); Mark m = n.getStart(); out.printil("// "+m.getFile()+"("+m.getLineNumber()+","+m.getColumnNumber()+") "+ attrs[i].getTagAttributeInfo()); if (attrs[i].isDynamic()) { out.printin(tagHandlerVar); out.print("."); out.print("setDynamicAttribute("); String uri = attrs[i].getURI(); if ("".equals(uri) || (uri == null)) { out.print("null"); } else { out.print("\"" + attrs[i].getURI() + "\""); } out.print(", \""); out.print(attrs[i].getLocalName()); out.print("\", "); out.print(attrValue); out.println(");"); } else { out.printin(tagHandlerVar); out.print("."); out.print(handlerInfo.getSetterMethod( attrs[i].getLocalName()).getName()); out.print("("); out.print(attrValue); out.println(");"); } } } /* * @param c The target class to which to coerce the given string @param * s The string value @param attrName The name of the attribute whose * value is being supplied @param propEditorClass The property editor * for the given attribute @param isNamedAttribute true if the given * attribute is a named attribute (that is, specified using the * jsp:attribute standard action), and false otherwise */ private String convertString(Class<?> c, String s, String attrName, Class<?> propEditorClass, boolean isNamedAttribute) { String quoted = s; if (!isNamedAttribute) { quoted = quote(s); } if (propEditorClass != null) { String className = JspUtil.getCanonicalName(c); return "(" + className + ")org.apache.jasper.runtime.JspRuntimeLibrary.getValueFromBeanInfoPropertyEditor(" + className + ".class, \"" + attrName + "\", " + quoted + ", " + JspUtil.getCanonicalName(propEditorClass) + ".class)"; } else if (c == String.class) { return quoted; } else if (c == boolean.class) { return JspUtil.coerceToPrimitiveBoolean(s, isNamedAttribute); } else if (c == Boolean.class) { return JspUtil.coerceToBoolean(s, isNamedAttribute); } else if (c == byte.class) { return JspUtil.coerceToPrimitiveByte(s, isNamedAttribute); } else if (c == Byte.class) { return JspUtil.coerceToByte(s, isNamedAttribute); } else if (c == char.class) { return JspUtil.coerceToChar(s, isNamedAttribute); } else if (c == Character.class) { return JspUtil.coerceToCharacter(s, isNamedAttribute); } else if (c == double.class) { return JspUtil.coerceToPrimitiveDouble(s, isNamedAttribute); } else if (c == Double.class) { return JspUtil.coerceToDouble(s, isNamedAttribute); } else if (c == float.class) { return JspUtil.coerceToPrimitiveFloat(s, isNamedAttribute); } else if (c == Float.class) { return JspUtil.coerceToFloat(s, isNamedAttribute); } else if (c == int.class) { return JspUtil.coerceToInt(s, isNamedAttribute); } else if (c == Integer.class) { return JspUtil.coerceToInteger(s, isNamedAttribute); } else if (c == short.class) { return JspUtil.coerceToPrimitiveShort(s, isNamedAttribute); } else if (c == Short.class) { return JspUtil.coerceToShort(s, isNamedAttribute); } else if (c == long.class) { return JspUtil.coerceToPrimitiveLong(s, isNamedAttribute); } else if (c == Long.class) { return JspUtil.coerceToLong(s, isNamedAttribute); } else if (c == Object.class) { return "new String(" + quoted + ")"; } else { String className = JspUtil.getCanonicalName(c); return "(" + className + ")org.apache.jasper.runtime.JspRuntimeLibrary.getValueFromPropertyEditorManager(" + className + ".class, \"" + attrName + "\", " + quoted + ")"; } } /* * Converts the scope string representation, whose possible values are * "page", "request", "session", and "application", to the corresponding * scope constant. */ private String getScopeConstant(String scope) { String scopeName = "PageContext.PAGE_SCOPE"; // Default to page if ("request".equals(scope)) { scopeName = "PageContext.REQUEST_SCOPE"; } else if ("session".equals(scope)) { scopeName = "PageContext.SESSION_SCOPE"; } else if ("application".equals(scope)) { scopeName = "PageContext.APPLICATION_SCOPE"; } return scopeName; } /** * Generates anonymous JspFragment inner class which is passed as an * argument to SimpleTag.setJspBody(). */ private void generateJspFragment(Node n, String tagHandlerVar) throws JasperException { // XXX - A possible optimization here would be to check to see // if the only child of the parent node is TemplateText. If so, // we know there won't be any parameters, etc, so we can // generate a low-overhead JspFragment that just echoes its // body. The implementation of this fragment can come from // the org.apache.jasper.runtime package as a support class. FragmentHelperClass.Fragment fragment = fragmentHelperClass .openFragment(n, methodNesting); ServletWriter outSave = out; out = fragment.getGenBuffer().getOut(); String tmpParent = parent; parent = "_jspx_parent"; boolean isSimpleTagParentSave = isSimpleTagParent; isSimpleTagParent = true; boolean tmpIsFragment = isFragment; isFragment = true; String pushBodyCountVarSave = pushBodyCountVar; if (pushBodyCountVar != null) { // Use a fixed name for push body count, to simplify code gen pushBodyCountVar = "_jspx_push_body_count"; } visitBody(n); out = outSave; parent = tmpParent; isSimpleTagParent = isSimpleTagParentSave; isFragment = tmpIsFragment; pushBodyCountVar = pushBodyCountVarSave; fragmentHelperClass.closeFragment(fragment, methodNesting); // XXX - Need to change pageContext to jspContext if // we're not in a place where pageContext is defined (e.g. // in a fragment or in a tag file. out.print("new " + fragmentHelperClass.getClassName() + "( " + fragment.getId() + ", _jspx_page_context, " + tagHandlerVar + ", " + pushBodyCountVar + ")"); } /** * Generate the code required to obtain the runtime value of the given * named attribute. * * @return The name of the temporary variable the result is stored in. */ public String generateNamedAttributeValue(Node.NamedAttribute n) throws JasperException { String varName = n.getTemporaryVariableName(); // If the only body element for this named attribute node is // template text, we need not generate an extra call to // pushBody and popBody. Maybe we can further optimize // here by getting rid of the temporary variable, but in // reality it looks like javac does this for us. Node.Nodes body = n.getBody(); if (body != null) { boolean templateTextOptimization = false; if (body.size() == 1) { Node bodyElement = body.getNode(0); if (bodyElement instanceof Node.TemplateText) { templateTextOptimization = true; out.printil("String " + varName + " = " + quote(new String( ((Node.TemplateText) bodyElement) .getText())) + ";"); } } // XXX - Another possible optimization would be for // lone EL expressions (no need to pushBody here either). if (!templateTextOptimization) { out.printil("out = _jspx_page_context.pushBody();"); visitBody(n); out.printil("String " + varName + " = " + "((javax.servlet.jsp.tagext.BodyContent)" + "out).getString();"); out.printil("out = _jspx_page_context.popBody();"); } } else { // Empty body must be treated as "" out.printil("String " + varName + " = \"\";"); } return varName; } /** * Similar to generateNamedAttributeValue, but create a JspFragment * instead. * * @param n * The parent node of the named attribute * @param tagHandlerVar * The variable the tag handler is stored in, so the fragment * knows its parent tag. * @return The name of the temporary variable the fragment is stored in. */ public String generateNamedAttributeJspFragment(Node.NamedAttribute n, String tagHandlerVar) throws JasperException { String varName = n.getTemporaryVariableName(); out.printin("javax.servlet.jsp.tagext.JspFragment " + varName + " = "); generateJspFragment(n, tagHandlerVar); out.println(";"); return varName; } } private static void generateLocalVariables(ServletWriter out, Node n) throws JasperException { Node.ChildInfo ci; if (n instanceof Node.CustomTag) { ci = ((Node.CustomTag) n).getChildInfo(); } else if (n instanceof Node.JspBody) { ci = ((Node.JspBody) n).getChildInfo(); } else if (n instanceof Node.NamedAttribute) { ci = ((Node.NamedAttribute) n).getChildInfo(); } else { // Cannot access err since this method is static, but at // least flag an error. throw new JasperException("Unexpected Node Type"); // err.getString( // "jsp.error.internal.unexpected_node_type" ) ); } if (ci.hasUseBean()) { out .printil("HttpSession session = _jspx_page_context.getSession();"); out .printil("ServletContext application = _jspx_page_context.getServletContext();"); } if (ci.hasUseBean() || ci.hasIncludeAction() || ci.hasSetProperty() || ci.hasParamAction()) { out .printil("HttpServletRequest request = (HttpServletRequest)_jspx_page_context.getRequest();"); } if (ci.hasIncludeAction()) { out .printil("HttpServletResponse response = (HttpServletResponse)_jspx_page_context.getResponse();"); } } /** * Common part of postamble, shared by both servlets and tag files. */ private void genCommonPostamble() { // Append any methods that were generated in the buffer. for (int i = 0; i < methodsBuffered.size(); i++) { GenBuffer methodBuffer = methodsBuffered.get(i); methodBuffer.adjustJavaLines(out.getJavaLine() - 1); out.printMultiLn(methodBuffer.toString()); } // Append the helper class if (fragmentHelperClass.isUsed()) { fragmentHelperClass.generatePostamble(); fragmentHelperClass.adjustJavaLines(out.getJavaLine() - 1); out.printMultiLn(fragmentHelperClass.toString()); } // Append char array declarations if (charArrayBuffer != null) { out.printMultiLn(charArrayBuffer.toString()); } // Close the class definition out.popIndent(); out.printil("}"); } /** * Generates the ending part of the static portion of the servlet. */ private void generatePostamble() { out.popIndent(); out.printil("} catch (Throwable t) {"); out.pushIndent(); out.printil("if (!(t instanceof SkipPageException)){"); out.pushIndent(); out.printil("out = _jspx_out;"); out.printil("if (out != null && out.getBufferSize() != 0)"); out.pushIndent(); out.printil("try { out.clearBuffer(); } catch (java.io.IOException e) {}"); out.popIndent(); out .printil("if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);"); out.popIndent(); out.printil("}"); out.popIndent(); out.printil("} finally {"); out.pushIndent(); out .printil("_jspxFactory.releasePageContext(_jspx_page_context);"); out.popIndent(); out.printil("}"); // Close the service method out.popIndent(); out.printil("}"); // Generated methods, helper classes, etc. genCommonPostamble(); } /** * Constructor. */ Generator(ServletWriter out, Compiler compiler) { this.out = out; methodsBuffered = new ArrayList<GenBuffer>(); charArrayBuffer = null; err = compiler.getErrorDispatcher(); ctxt = compiler.getCompilationContext(); fragmentHelperClass = new FragmentHelperClass("Helper"); pageInfo = compiler.getPageInfo(); /* * Temporary hack. If a JSP page uses the "extends" attribute of the * page directive, the _jspInit() method of the generated servlet class * will not be called (it is only called for those generated servlets * that extend HttpJspBase, the default), causing the tag handler pools * not to be initialized and resulting in a NPE. The JSP spec needs to * clarify whether containers can override init() and destroy(). For * now, we just disable tag pooling for pages that use "extends". */ if (pageInfo.getExtends(false) == null) { isPoolingEnabled = ctxt.getOptions().isPoolingEnabled(); } else { isPoolingEnabled = false; } beanInfo = pageInfo.getBeanRepository(); varInfoNames = pageInfo.getVarInfoNames(); breakAtLF = ctxt.getOptions().getMappedFile(); if (isPoolingEnabled) { tagHandlerPoolNames = new Vector<String>(); } } /** * The main entry for Generator. * * @param out * The servlet output writer * @param compiler * The compiler * @param page * The input page */ public static void generate(ServletWriter out, Compiler compiler, Node.Nodes page) throws JasperException { Generator gen = new Generator(out, compiler); if (gen.isPoolingEnabled) { gen.compileTagHandlerPoolList(page); } if (gen.ctxt.isTagFile()) { JasperTagInfo tagInfo = (JasperTagInfo) gen.ctxt.getTagInfo(); gen.generateTagHandlerPreamble(tagInfo, page); if (gen.ctxt.isPrototypeMode()) { return; } gen.generateXmlProlog(page); gen.fragmentHelperClass.generatePreamble(); page.visit(gen.new GenerateVisitor(gen.ctxt.isTagFile(), out, gen.methodsBuffered, gen.fragmentHelperClass)); gen.generateTagHandlerPostamble(tagInfo); } else { gen.generatePreamble(page); gen.generateXmlProlog(page); gen.fragmentHelperClass.generatePreamble(); page.visit(gen.new GenerateVisitor(gen.ctxt.isTagFile(), out, gen.methodsBuffered, gen.fragmentHelperClass)); gen.generatePostamble(); } } /* * Generates tag handler preamble. */ private void generateTagHandlerPreamble(JasperTagInfo tagInfo, Node.Nodes tag) throws JasperException { // Generate package declaration String className = tagInfo.getTagClassName(); int lastIndex = className.lastIndexOf('.'); if (lastIndex != -1) { String pkgName = className.substring(0, lastIndex); genPreamblePackage(pkgName); className = className.substring(lastIndex + 1); } // Generate imports genPreambleImports(); // Generate class declaration out.printin("public final class "); out.println(className); out.printil(" extends javax.servlet.jsp.tagext.SimpleTagSupport"); out.printin(" implements org.apache.jasper.runtime.JspSourceDependent"); if (tagInfo.hasDynamicAttributes()) { out.println(","); out.printin(" javax.servlet.jsp.tagext.DynamicAttributes"); } out.println(" {"); out.println(); out.pushIndent(); /* * Class body begins here */ generateDeclarations(tag); // Static initializations here genPreambleStaticInitializers(); out.printil("private JspContext jspContext;"); // Declare writer used for storing result of fragment/body invocation // if 'varReader' or 'var' attribute is specified out.printil("private java.io.Writer _jspx_sout;"); // Class variable declarations genPreambleClassVariableDeclarations(); generateSetJspContext(tagInfo); // Tag-handler specific declarations generateTagHandlerAttributes(tagInfo); if (tagInfo.hasDynamicAttributes()) generateSetDynamicAttribute(); // Methods here genPreambleMethods(); // Now the doTag() method out.printil("public void doTag() throws JspException, java.io.IOException {"); if (ctxt.isPrototypeMode()) { out.printil("}"); out.popIndent(); out.printil("}"); return; } out.pushIndent(); /* * According to the spec, 'pageContext' must not be made available as an * implicit object in tag files. Declare _jspx_page_context, so we can * share the code generator with JSPs. */ out.printil("PageContext _jspx_page_context = (PageContext)jspContext;"); // Declare implicit objects. out.printil("HttpServletRequest request = " + "(HttpServletRequest) _jspx_page_context.getRequest();"); out.printil("HttpServletResponse response = " + "(HttpServletResponse) _jspx_page_context.getResponse();"); out.printil("HttpSession session = _jspx_page_context.getSession();"); out.printil("ServletContext application = _jspx_page_context.getServletContext();"); out.printil("ServletConfig config = _jspx_page_context.getServletConfig();"); out.printil("JspWriter out = jspContext.getOut();"); out.printil("_jspInit(config);"); // set current JspContext on ELContext out.printil("jspContext.getELContext().putContext(JspContext.class,jspContext);"); generatePageScopedVariables(tagInfo); declareTemporaryScriptingVars(tag); out.println(); out.printil("try {"); out.pushIndent(); } private void generateTagHandlerPostamble(TagInfo tagInfo) { out.popIndent(); // Have to catch Throwable because a classic tag handler // helper method is declared to throw Throwable. out.printil("} catch( Throwable t ) {"); out.pushIndent(); out.printil("if( t instanceof SkipPageException )"); out.printil(" throw (SkipPageException) t;"); out.printil("if( t instanceof java.io.IOException )"); out.printil(" throw (java.io.IOException) t;"); out.printil("if( t instanceof IllegalStateException )"); out.printil(" throw (IllegalStateException) t;"); out.printil("if( t instanceof JspException )"); out.printil(" throw (JspException) t;"); out.printil("throw new JspException(t);"); out.popIndent(); out.printil("} finally {"); out.pushIndent(); // handle restoring VariableMapper TagAttributeInfo[] attrInfos = tagInfo.getAttributes(); for (int i = 0; i < attrInfos.length; i++) { if (attrInfos[i].isDeferredMethod() || attrInfos[i].isDeferredValue()) { out.printin("_el_variablemapper.setVariable("); out.print(quote(attrInfos[i].getName())); out.print(",_el_ve"); out.print(i); out.println(");"); } } // restore nested JspContext on ELContext out.printil("jspContext.getELContext().putContext(JspContext.class,super.getJspContext());"); out.printil("((org.apache.jasper.runtime.JspContextWrapper) jspContext).syncEndTagFile();"); if (isPoolingEnabled && !tagHandlerPoolNames.isEmpty()) { out.printil("_jspDestroy();"); } out.popIndent(); out.printil("}"); // Close the doTag method out.popIndent(); out.printil("}"); // Generated methods, helper classes, etc. genCommonPostamble(); } /** * Generates declarations for tag handler attributes, and defines the getter * and setter methods for each. */ private void generateTagHandlerAttributes(TagInfo tagInfo) { if (tagInfo.hasDynamicAttributes()) { out.printil("private java.util.HashMap _jspx_dynamic_attrs = new java.util.HashMap();"); } // Declare attributes TagAttributeInfo[] attrInfos = tagInfo.getAttributes(); for (int i = 0; i < attrInfos.length; i++) { out.printin("private "); if (attrInfos[i].isFragment()) { out.print("javax.servlet.jsp.tagext.JspFragment "); } else { out.print(JspUtil.toJavaSourceType(attrInfos[i].getTypeName())); out.print(" "); } out.print(attrInfos[i].getName()); out.println(";"); } out.println(); // Define attribute getter and setter methods for (int i = 0; i < attrInfos.length; i++) { // getter method out.printin("public "); if (attrInfos[i].isFragment()) { out.print("javax.servlet.jsp.tagext.JspFragment "); } else { out.print(JspUtil.toJavaSourceType(attrInfos[i] .getTypeName())); out.print(" "); } out.print(toGetterMethod(attrInfos[i].getName())); out.println(" {"); out.pushIndent(); out.printin("return this."); out.print(attrInfos[i].getName()); out.println(";"); out.popIndent(); out.printil("}"); out.println(); // setter method out.printin("public void "); out.print(toSetterMethodName(attrInfos[i].getName())); if (attrInfos[i].isFragment()) { out.print("(javax.servlet.jsp.tagext.JspFragment "); } else { out.print("("); out.print(JspUtil.toJavaSourceType(attrInfos[i] .getTypeName())); out.print(" "); } out.print(attrInfos[i].getName()); out.println(") {"); out.pushIndent(); out.printin("this."); out.print(attrInfos[i].getName()); out.print(" = "); out.print(attrInfos[i].getName()); out.println(";"); if (ctxt.isTagFile()) { // Tag files should also set jspContext attributes out.printin("jspContext.setAttribute(\""); out.print(attrInfos[i].getName()); out.print("\", "); out.print(attrInfos[i].getName()); out.println(");"); } out.popIndent(); out.printil("}"); out.println(); } } /* * Generate setter for JspContext so we can create a wrapper and store both * the original and the wrapper. We need the wrapper to mask the page * context from the tag file and simulate a fresh page context. We need the * original to do things like sync AT_BEGIN and AT_END scripting variables. */ private void generateSetJspContext(TagInfo tagInfo) { boolean nestedSeen = false; boolean atBeginSeen = false; boolean atEndSeen = false; // Determine if there are any aliases boolean aliasSeen = false; TagVariableInfo[] tagVars = tagInfo.getTagVariableInfos(); for (int i = 0; i < tagVars.length; i++) { if (tagVars[i].getNameFromAttribute() != null && tagVars[i].getNameGiven() != null) { aliasSeen = true; break; } } if (aliasSeen) { out .printil("public void setJspContext(JspContext ctx, java.util.Map aliasMap) {"); } else { out.printil("public void setJspContext(JspContext ctx) {"); } out.pushIndent(); out.printil("super.setJspContext(ctx);"); out.printil("java.util.ArrayList _jspx_nested = null;"); out.printil("java.util.ArrayList _jspx_at_begin = null;"); out.printil("java.util.ArrayList _jspx_at_end = null;"); for (int i = 0; i < tagVars.length; i++) { switch (tagVars[i].getScope()) { case VariableInfo.NESTED: if (!nestedSeen) { out.printil("_jspx_nested = new java.util.ArrayList();"); nestedSeen = true; } out.printin("_jspx_nested.add("); break; case VariableInfo.AT_BEGIN: if (!atBeginSeen) { out.printil("_jspx_at_begin = new java.util.ArrayList();"); atBeginSeen = true; } out.printin("_jspx_at_begin.add("); break; case VariableInfo.AT_END: if (!atEndSeen) { out.printil("_jspx_at_end = new java.util.ArrayList();"); atEndSeen = true; } out.printin("_jspx_at_end.add("); break; } // switch out.print(quote(tagVars[i].getNameGiven())); out.println(");"); } if (aliasSeen) { out .printil("this.jspContext = new org.apache.jasper.runtime.JspContextWrapper(ctx, _jspx_nested, _jspx_at_begin, _jspx_at_end, aliasMap);"); } else { out .printil("this.jspContext = new org.apache.jasper.runtime.JspContextWrapper(ctx, _jspx_nested, _jspx_at_begin, _jspx_at_end, null);"); } out.popIndent(); out.printil("}"); out.println(); out.printil("public JspContext getJspContext() {"); out.pushIndent(); out.printil("return this.jspContext;"); out.popIndent(); out.printil("}"); } /* * Generates implementation of * javax.servlet.jsp.tagext.DynamicAttributes.setDynamicAttribute() method, * which saves each dynamic attribute that is passed in so that a scoped * variable can later be created for it. */ public void generateSetDynamicAttribute() { out .printil("public void setDynamicAttribute(String uri, String localName, Object value) throws JspException {"); out.pushIndent(); /* * According to the spec, only dynamic attributes with no uri are to be * present in the Map; all other dynamic attributes are ignored. */ out.printil("if (uri == null)"); out.pushIndent(); out.printil("_jspx_dynamic_attrs.put(localName, value);"); out.popIndent(); out.popIndent(); out.printil("}"); } /* * Creates a page-scoped variable for each declared tag attribute. Also, if * the tag accepts dynamic attributes, a page-scoped variable is made * available for each dynamic attribute that was passed in. */ private void generatePageScopedVariables(JasperTagInfo tagInfo) { // "normal" attributes TagAttributeInfo[] attrInfos = tagInfo.getAttributes(); boolean variableMapperVar = false; for (int i = 0; i < attrInfos.length; i++) { String attrName = attrInfos[i].getName(); // handle assigning deferred vars to VariableMapper, storing // previous values under '_el_ve[i]' for later re-assignment if (attrInfos[i].isDeferredValue() || attrInfos[i].isDeferredMethod()) { // we need to scope the modified VariableMapper for consistency and performance if (!variableMapperVar) { out.printil("javax.el.VariableMapper _el_variablemapper = jspContext.getELContext().getVariableMapper();"); variableMapperVar = true; } out.printin("javax.el.ValueExpression _el_ve"); out.print(i); out.print(" = _el_variablemapper.setVariable("); out.print(quote(attrName)); out.print(','); if (attrInfos[i].isDeferredMethod()) { out.print(VAR_EXPRESSIONFACTORY); out.print(".createValueExpression("); out.print(toGetterMethod(attrName)); out.print(",javax.el.MethodExpression.class)"); } else { out.print(toGetterMethod(attrName)); } out.println(");"); } else { out.printil("if( " + toGetterMethod(attrName) + " != null ) "); out.pushIndent(); out.printin("_jspx_page_context.setAttribute("); out.print(quote(attrName)); out.print(", "); out.print(toGetterMethod(attrName)); out.println(");"); out.popIndent(); } } // Expose the Map containing dynamic attributes as a page-scoped var if (tagInfo.hasDynamicAttributes()) { out.printin("_jspx_page_context.setAttribute(\""); out.print(tagInfo.getDynamicAttributesMapName()); out.print("\", _jspx_dynamic_attrs);"); } } /* * Generates the getter method for the given attribute name. */ private String toGetterMethod(String attrName) { char[] attrChars = attrName.toCharArray(); attrChars[0] = Character.toUpperCase(attrChars[0]); return "get" + new String(attrChars) + "()"; } /* * Generates the setter method name for the given attribute name. */ private String toSetterMethodName(String attrName) { char[] attrChars = attrName.toCharArray(); attrChars[0] = Character.toUpperCase(attrChars[0]); return "set" + new String(attrChars); } /** * Class storing the result of introspecting a custom tag handler. */ private static class TagHandlerInfo { private Hashtable<String, Method> methodMaps; private Hashtable<String, Class<?>> propertyEditorMaps; private Class<?> tagHandlerClass; /** * Constructor. * * @param n * The custom tag whose tag handler class is to be * introspected * @param tagHandlerClass * Tag handler class * @param err * Error dispatcher */ TagHandlerInfo(Node n, Class<?> tagHandlerClass, ErrorDispatcher err) throws JasperException { this.tagHandlerClass = tagHandlerClass; this.methodMaps = new Hashtable<String, Method>(); this.propertyEditorMaps = new Hashtable<String, Class<?>>(); try { BeanInfo tagClassInfo = Introspector .getBeanInfo(tagHandlerClass); PropertyDescriptor[] pd = tagClassInfo.getPropertyDescriptors(); for (int i = 0; i < pd.length; i++) { /* * FIXME: should probably be checking for things like * pageContext, bodyContent, and parent here -akv */ if (pd[i].getWriteMethod() != null) { methodMaps.put(pd[i].getName(), pd[i].getWriteMethod()); } if (pd[i].getPropertyEditorClass() != null) propertyEditorMaps.put(pd[i].getName(), pd[i] .getPropertyEditorClass()); } } catch (IntrospectionException ie) { err.jspError(n, "jsp.error.introspect.taghandler", tagHandlerClass.getName(), ie); } } /** * XXX */ public Method getSetterMethod(String attrName) { return methodMaps.get(attrName); } /** * XXX */ public Class<?> getPropertyEditorClass(String attrName) { return propertyEditorMaps.get(attrName); } /** * XXX */ public Class<?> getTagHandlerClass() { return tagHandlerClass; } } /** * A class for generating codes to a buffer. Included here are some support * for tracking source to Java lines mapping. */ private static class GenBuffer { /* * For a CustomTag, the codes that are generated at the beginning of the * tag may not be in the same buffer as those for the body of the tag. * Two fields are used here to keep this straight. For codes that do not * corresponds to any JSP lines, they should be null. */ private Node node; private Node.Nodes body; private java.io.CharArrayWriter charWriter; protected ServletWriter out; GenBuffer() { this(null, null); } GenBuffer(Node n, Node.Nodes b) { node = n; body = b; if (body != null) { body.setGeneratedInBuffer(true); } charWriter = new java.io.CharArrayWriter(); out = new ServletWriter(new java.io.PrintWriter(charWriter)); } public ServletWriter getOut() { return out; } @Override public String toString() { return charWriter.toString(); } /** * Adjust the Java Lines. This is necessary because the Java lines * stored with the nodes are relative the beginning of this buffer and * need to be adjusted when this buffer is inserted into the source. */ public void adjustJavaLines(final int offset) { if (node != null) { adjustJavaLine(node, offset); } if (body != null) { try { body.visit(new Node.Visitor() { @Override public void doVisit(Node n) { adjustJavaLine(n, offset); } @Override public void visit(Node.CustomTag n) throws JasperException { Node.Nodes b = n.getBody(); if (b != null && !b.isGeneratedInBuffer()) { // Don't adjust lines for the nested tags that // are also generated in buffers, because the // adjustments will be done elsewhere. b.visit(this); } } }); } catch (JasperException ex) { // Ignore } } } private static void adjustJavaLine(Node n, int offset) { if (n.getBeginJavaLine() > 0) { n.setBeginJavaLine(n.getBeginJavaLine() + offset); n.setEndJavaLine(n.getEndJavaLine() + offset); } } } /** * Keeps track of the generated Fragment Helper Class */ private static class FragmentHelperClass { private static class Fragment { private GenBuffer genBuffer; private int id; public Fragment(int id, Node node) { this.id = id; genBuffer = new GenBuffer(null, node.getBody()); } public GenBuffer getGenBuffer() { return this.genBuffer; } public int getId() { return this.id; } } // True if the helper class should be generated. private boolean used = false; private ArrayList<Fragment> fragments = new ArrayList<Fragment>(); private String className; // Buffer for entire helper class private GenBuffer classBuffer = new GenBuffer(); public FragmentHelperClass(String className) { this.className = className; } public String getClassName() { return this.className; } public boolean isUsed() { return this.used; } public void generatePreamble() { ServletWriter out = this.classBuffer.getOut(); out.println(); out.pushIndent(); // Note: cannot be static, as we need to reference things like // _jspx_meth_* out.printil("private class " + className); out.printil(" extends " + "org.apache.jasper.runtime.JspFragmentHelper"); out.printil("{"); out.pushIndent(); out .printil("private javax.servlet.jsp.tagext.JspTag _jspx_parent;"); out.printil("private int[] _jspx_push_body_count;"); out.println(); out.printil("public " + className + "( int discriminator, JspContext jspContext, " + "javax.servlet.jsp.tagext.JspTag _jspx_parent, " + "int[] _jspx_push_body_count ) {"); out.pushIndent(); out.printil("super( discriminator, jspContext, _jspx_parent );"); out.printil("this._jspx_parent = _jspx_parent;"); out.printil("this._jspx_push_body_count = _jspx_push_body_count;"); out.popIndent(); out.printil("}"); } public Fragment openFragment(Node parent, int methodNesting) throws JasperException { Fragment result = new Fragment(fragments.size(), parent); fragments.add(result); this.used = true; parent.setInnerClassName(className); ServletWriter out = result.getGenBuffer().getOut(); out.pushIndent(); out.pushIndent(); // XXX - Returns boolean because if a tag is invoked from // within this fragment, the Generator sometimes might // generate code like "return true". This is ignored for now, // meaning only the fragment is skipped. The JSR-152 // expert group is currently discussing what to do in this case. // See comment in closeFragment() if (methodNesting > 0) { out.printin("public boolean invoke"); } else { out.printin("public void invoke"); } out.println(result.getId() + "( " + "JspWriter out ) "); out.pushIndent(); // Note: Throwable required because methods like _jspx_meth_* // throw Throwable. out.printil("throws Throwable"); out.popIndent(); out.printil("{"); out.pushIndent(); generateLocalVariables(out, parent); return result; } public void closeFragment(Fragment fragment, int methodNesting) { ServletWriter out = fragment.getGenBuffer().getOut(); // XXX - See comment in openFragment() if (methodNesting > 0) { out.printil("return false;"); } else { out.printil("return;"); } out.popIndent(); out.printil("}"); } public void generatePostamble() { ServletWriter out = this.classBuffer.getOut(); // Generate all fragment methods: for (int i = 0; i < fragments.size(); i++) { Fragment fragment = fragments.get(i); fragment.getGenBuffer().adjustJavaLines(out.getJavaLine() - 1); out.printMultiLn(fragment.getGenBuffer().toString()); } // Generate postamble: out.printil("public void invoke( java.io.Writer writer )"); out.pushIndent(); out.printil("throws JspException"); out.popIndent(); out.printil("{"); out.pushIndent(); out.printil("JspWriter out = null;"); out.printil("if( writer != null ) {"); out.pushIndent(); out.printil("out = this.jspContext.pushBody(writer);"); out.popIndent(); out.printil("} else {"); out.pushIndent(); out.printil("out = this.jspContext.getOut();"); out.popIndent(); out.printil("}"); out.printil("try {"); out.pushIndent(); out.printil("this.jspContext.getELContext().putContext(JspContext.class,this.jspContext);"); out.printil("switch( this.discriminator ) {"); out.pushIndent(); for (int i = 0; i < fragments.size(); i++) { out.printil("case " + i + ":"); out.pushIndent(); out.printil("invoke" + i + "( out );"); out.printil("break;"); out.popIndent(); } out.popIndent(); out.printil("}"); // switch out.popIndent(); out.printil("}"); // try out.printil("catch( Throwable e ) {"); out.pushIndent(); out.printil("if (e instanceof SkipPageException)"); out.printil(" throw (SkipPageException) e;"); out.printil("throw new JspException( e );"); out.popIndent(); out.printil("}"); // catch out.printil("finally {"); out.pushIndent(); out.printil("if( writer != null ) {"); out.pushIndent(); out.printil("this.jspContext.popBody();"); out.popIndent(); out.printil("}"); out.popIndent(); out.printil("}"); // finally out.popIndent(); out.printil("}"); // invoke method out.popIndent(); out.printil("}"); // helper class out.popIndent(); } @Override public String toString() { return classBuffer.toString(); } public void adjustJavaLines(int offset) { for (int i = 0; i < fragments.size(); i++) { Fragment fragment = fragments.get(i); fragment.getGenBuffer().adjustJavaLines(offset); } } } }
java/org/apache/jasper/compiler/Generator.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.jasper.compiler; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.Hashtable; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Vector; import javax.el.MethodExpression; import javax.el.ValueExpression; import javax.servlet.jsp.tagext.TagAttributeInfo; import javax.servlet.jsp.tagext.TagInfo; import javax.servlet.jsp.tagext.TagVariableInfo; import javax.servlet.jsp.tagext.VariableInfo; import org.apache.jasper.Constants; import org.apache.jasper.JasperException; import org.apache.jasper.JspCompilationContext; import org.apache.jasper.compiler.Node.NamedAttribute; import org.apache.jasper.runtime.JspRuntimeLibrary; import org.xml.sax.Attributes; /** * Generate Java source from Nodes * * @author Anil K. Vijendran * @author Danno Ferrin * @author Mandar Raje * @author Rajiv Mordani * @author Pierre Delisle * * Tomcat 4.1.x and Tomcat 5: * @author Kin-man Chung * @author Jan Luehe * @author Shawn Bayern * @author Mark Roth * @author Denis Benoit * * Tomcat 6.x * @author Jacob Hookom * @author Remy Maucherat */ class Generator { private static final Class<?>[] OBJECT_CLASS = { Object.class }; private static final String VAR_EXPRESSIONFACTORY = System.getProperty("org.apache.jasper.compiler.Generator.VAR_EXPRESSIONFACTORY", "_el_expressionfactory"); private static final String VAR_INSTANCEMANAGER = System.getProperty("org.apache.jasper.compiler.Generator.VAR_INSTANCEMANAGER", "_jsp_instancemanager"); private ServletWriter out; private ArrayList<GenBuffer> methodsBuffered; private FragmentHelperClass fragmentHelperClass; private ErrorDispatcher err; private BeanRepository beanInfo; private Set<String> varInfoNames; private JspCompilationContext ctxt; private boolean isPoolingEnabled; private boolean breakAtLF; private String jspIdPrefix; private int jspId; private PageInfo pageInfo; private Vector<String> tagHandlerPoolNames; private GenBuffer charArrayBuffer; /** * @param s * the input string * @return quoted and escaped string, per Java rule */ static String quote(String s) { if (s == null) return "null"; return '"' + escape(s) + '"'; } /** * @param s * the input string * @return escaped string, per Java rule */ static String escape(String s) { if (s == null) return ""; StringBuilder b = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '"') b.append('\\').append('"'); else if (c == '\\') b.append('\\').append('\\'); else if (c == '\n') b.append('\\').append('n'); else if (c == '\r') b.append('\\').append('r'); else b.append(c); } return b.toString(); } /** * Single quote and escape a character */ static String quote(char c) { StringBuilder b = new StringBuilder(); b.append('\''); if (c == '\'') b.append('\\').append('\''); else if (c == '\\') b.append('\\').append('\\'); else if (c == '\n') b.append('\\').append('n'); else if (c == '\r') b.append('\\').append('r'); else b.append(c); b.append('\''); return b.toString(); } private String createJspId() { if (this.jspIdPrefix == null) { StringBuilder sb = new StringBuilder(32); String name = ctxt.getServletJavaFileName(); sb.append("jsp_").append(Math.abs(name.hashCode())).append('_'); this.jspIdPrefix = sb.toString(); } return this.jspIdPrefix + (this.jspId++); } /** * Generates declarations. This includes "info" of the page directive, and * scriptlet declarations. */ private void generateDeclarations(Node.Nodes page) throws JasperException { class DeclarationVisitor extends Node.Visitor { private boolean getServletInfoGenerated = false; /* * Generates getServletInfo() method that returns the value of the * page directive's 'info' attribute, if present. * * The Validator has already ensured that if the translation unit * contains more than one page directive with an 'info' attribute, * their values match. */ @Override public void visit(Node.PageDirective n) throws JasperException { if (getServletInfoGenerated) { return; } String info = n.getAttributeValue("info"); if (info == null) return; getServletInfoGenerated = true; out.printil("public String getServletInfo() {"); out.pushIndent(); out.printin("return "); out.print(quote(info)); out.println(";"); out.popIndent(); out.printil("}"); out.println(); } @Override public void visit(Node.Declaration n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); out.printMultiLn(new String(n.getText())); out.println(); n.setEndJavaLine(out.getJavaLine()); } // Custom Tags may contain declarations from tag plugins. @Override public void visit(Node.CustomTag n) throws JasperException { if (n.useTagPlugin()) { if (n.getAtSTag() != null) { n.getAtSTag().visit(this); } visitBody(n); if (n.getAtETag() != null) { n.getAtETag().visit(this); } } else { visitBody(n); } } } out.println(); page.visit(new DeclarationVisitor()); } /** * Compiles list of tag handler pool names. */ private void compileTagHandlerPoolList(Node.Nodes page) throws JasperException { class TagHandlerPoolVisitor extends Node.Visitor { private Vector<String> names; /* * Constructor * * @param v Vector of tag handler pool names to populate */ TagHandlerPoolVisitor(Vector<String> v) { names = v; } /* * Gets the name of the tag handler pool for the given custom tag * and adds it to the list of tag handler pool names unless it is * already contained in it. */ @Override public void visit(Node.CustomTag n) throws JasperException { if (!n.implementsSimpleTag()) { String name = createTagHandlerPoolName(n.getPrefix(), n .getLocalName(), n.getAttributes(), n.getNamedAttributeNodes(), n.hasEmptyBody()); n.setTagHandlerPoolName(name); if (!names.contains(name)) { names.add(name); } } visitBody(n); } /* * Creates the name of the tag handler pool whose tag handlers may * be (re)used to service this action. * * @return The name of the tag handler pool */ private String createTagHandlerPoolName(String prefix, String shortName, Attributes attrs, Node.Nodes namedAttrs, boolean hasEmptyBody) { String poolName = null; poolName = "_jspx_tagPool_" + prefix + "_" + shortName; if (attrs != null) { String[] attrNames = new String[attrs.getLength() + namedAttrs.size()]; for (int i = 0; i < attrNames.length; i++) { attrNames[i] = attrs.getQName(i); } for (int i = 0; i < namedAttrs.size(); i++) { attrNames[attrs.getLength() + i] = ((NamedAttribute) namedAttrs.getNode(i)).getQName(); } Arrays.sort(attrNames, Collections.reverseOrder()); if (attrNames.length > 0) { poolName = poolName + "&"; } for (int i = 0; i < attrNames.length; i++) { poolName = poolName + "_" + attrNames[i]; } } if (hasEmptyBody) { poolName = poolName + "_nobody"; } return JspUtil.makeJavaIdentifier(poolName); } } page.visit(new TagHandlerPoolVisitor(tagHandlerPoolNames)); } private void declareTemporaryScriptingVars(Node.Nodes page) throws JasperException { class ScriptingVarVisitor extends Node.Visitor { private Vector<String> vars; ScriptingVarVisitor() { vars = new Vector<String>(); } @Override public void visit(Node.CustomTag n) throws JasperException { if (n.getCustomNestingLevel() > 0) { TagVariableInfo[] tagVarInfos = n.getTagVariableInfos(); VariableInfo[] varInfos = n.getVariableInfos(); if (varInfos.length > 0) { for (int i = 0; i < varInfos.length; i++) { String varName = varInfos[i].getVarName(); String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); if (!vars.contains(tmpVarName)) { vars.add(tmpVarName); out.printin(varInfos[i].getClassName()); out.print(" "); out.print(tmpVarName); out.print(" = "); out.print(null); out.println(";"); } } } else { for (int i = 0; i < tagVarInfos.length; i++) { String varName = tagVarInfos[i].getNameGiven(); if (varName == null) { varName = n.getTagData().getAttributeString( tagVarInfos[i].getNameFromAttribute()); } else if (tagVarInfos[i].getNameFromAttribute() != null) { // alias continue; } String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); if (!vars.contains(tmpVarName)) { vars.add(tmpVarName); out.printin(tagVarInfos[i].getClassName()); out.print(" "); out.print(tmpVarName); out.print(" = "); out.print(null); out.println(";"); } } } } visitBody(n); } } page.visit(new ScriptingVarVisitor()); } /** * Generates the _jspInit() method for instantiating the tag handler pools. * For tag file, _jspInit has to be invoked manually, and the ServletConfig * object explicitly passed. * * In JSP 2.1, we also instantiate an ExpressionFactory */ private void generateInit() { if (ctxt.isTagFile()) { out.printil("private void _jspInit(ServletConfig config) {"); } else { out.printil("public void _jspInit() {"); } out.pushIndent(); if (isPoolingEnabled) { for (int i = 0; i < tagHandlerPoolNames.size(); i++) { out.printin(tagHandlerPoolNames.elementAt(i)); out.print(" = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool("); if (ctxt.isTagFile()) { out.print("config"); } else { out.print("getServletConfig()"); } out.println(");"); } } out.printin(VAR_EXPRESSIONFACTORY); out.print(" = _jspxFactory.getJspApplicationContext("); if (ctxt.isTagFile()) { out.print("config"); } else { out.print("getServletConfig()"); } out.println(".getServletContext()).getExpressionFactory();"); out.printin(VAR_INSTANCEMANAGER); out.print(" = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager("); if (ctxt.isTagFile()) { out.print("config"); } else { out.print("getServletConfig()"); } out.println(");"); out.popIndent(); out.printil("}"); out.println(); } /** * Generates the _jspDestroy() method which is responsible for calling the * release() method on every tag handler in any of the tag handler pools. */ private void generateDestroy() { out.printil("public void _jspDestroy() {"); out.pushIndent(); if (isPoolingEnabled) { for (int i = 0; i < tagHandlerPoolNames.size(); i++) { out.printin(tagHandlerPoolNames.elementAt(i)); out.println(".release();"); } } out.popIndent(); out.printil("}"); out.println(); } /** * Generate preamble package name (shared by servlet and tag handler * preamble generation) */ private void genPreamblePackage(String packageName) { if (!"".equals(packageName) && packageName != null) { out.printil("package " + packageName + ";"); out.println(); } } /** * Generate preamble imports (shared by servlet and tag handler preamble * generation) */ private void genPreambleImports() { Iterator<String> iter = pageInfo.getImports().iterator(); while (iter.hasNext()) { out.printin("import "); out.print(iter.next()); out.println(";"); } out.println(); } /** * Generation of static initializers in preamble. For example, dependent * list, el function map, prefix map. (shared by servlet and tag handler * preamble generation) */ private void genPreambleStaticInitializers() { out.printil("private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();"); out.println(); // Static data for getDependants() out.printil("private static java.util.List<String> _jspx_dependants;"); out.println(); List<String> dependants = pageInfo.getDependants(); Iterator<String> iter = dependants.iterator(); if (!dependants.isEmpty()) { out.printil("static {"); out.pushIndent(); out.printin("_jspx_dependants = new java.util.ArrayList<String>("); out.print("" + dependants.size()); out.println(");"); while (iter.hasNext()) { out.printin("_jspx_dependants.add(\""); out.print(iter.next()); out.println("\");"); } out.popIndent(); out.printil("}"); out.println(); } } /** * Declare tag handler pools (tags of the same type and with the same * attribute set share the same tag handler pool) (shared by servlet and tag * handler preamble generation) * * In JSP 2.1, we also scope an instance of ExpressionFactory */ private void genPreambleClassVariableDeclarations() { if (isPoolingEnabled && !tagHandlerPoolNames.isEmpty()) { for (int i = 0; i < tagHandlerPoolNames.size(); i++) { out.printil("private org.apache.jasper.runtime.TagHandlerPool " + tagHandlerPoolNames.elementAt(i) + ";"); } out.println(); } out.printin("private javax.el.ExpressionFactory "); out.print(VAR_EXPRESSIONFACTORY); out.println(";"); out.printin("private org.apache.tomcat.InstanceManager "); out.print(VAR_INSTANCEMANAGER); out.println(";"); out.println(); } /** * Declare general-purpose methods (shared by servlet and tag handler * preamble generation) */ private void genPreambleMethods() { // Method used to get compile time file dependencies out.printil("public java.util.List<String> getDependants() {"); out.pushIndent(); out.printil("return _jspx_dependants;"); out.popIndent(); out.printil("}"); out.println(); generateInit(); generateDestroy(); } /** * Generates the beginning of the static portion of the servlet. */ private void generatePreamble(Node.Nodes page) throws JasperException { String servletPackageName = ctxt.getServletPackageName(); String servletClassName = ctxt.getServletClassName(); String serviceMethodName = Constants.SERVICE_METHOD_NAME; // First the package name: genPreamblePackage(servletPackageName); // Generate imports genPreambleImports(); // Generate class declaration out.printin("public final class "); out.print(servletClassName); out.print(" extends "); out.println(pageInfo.getExtends()); out.printin(" implements org.apache.jasper.runtime.JspSourceDependent"); if (!pageInfo.isThreadSafe()) { out.println(","); out.printin(" SingleThreadModel"); } out.println(" {"); out.pushIndent(); // Class body begins here generateDeclarations(page); // Static initializations here genPreambleStaticInitializers(); // Class variable declarations genPreambleClassVariableDeclarations(); // Constructor // generateConstructor(className); // Methods here genPreambleMethods(); // Now the service method out.printin("public void "); out.print(serviceMethodName); out.println("(HttpServletRequest request, HttpServletResponse response)"); out.println(" throws java.io.IOException, ServletException {"); out.pushIndent(); out.println(); // Local variable declarations out.printil("PageContext pageContext = null;"); if (pageInfo.isSession()) out.printil("HttpSession session = null;"); if (pageInfo.isErrorPage()) { out.printil("Throwable exception = org.apache.jasper.runtime.JspRuntimeLibrary.getThrowable(request);"); out.printil("if (exception != null) {"); out.pushIndent(); out.printil("response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);"); out.popIndent(); out.printil("}"); } out.printil("ServletContext application = null;"); out.printil("ServletConfig config = null;"); out.printil("JspWriter out = null;"); out.printil("Object page = this;"); out.printil("JspWriter _jspx_out = null;"); out.printil("PageContext _jspx_page_context = null;"); out.println(); declareTemporaryScriptingVars(page); out.println(); out.printil("try {"); out.pushIndent(); out.printin("response.setContentType("); out.print(quote(pageInfo.getContentType())); out.println(");"); if (ctxt.getOptions().isXpoweredBy()) { out.printil("response.addHeader(\"X-Powered-By\", \"JSP/2.1\");"); } out .printil("pageContext = _jspxFactory.getPageContext(this, request, response,"); out.printin("\t\t\t"); out.print(quote(pageInfo.getErrorPage())); out.print(", " + pageInfo.isSession()); out.print(", " + pageInfo.getBuffer()); out.print(", " + pageInfo.isAutoFlush()); out.println(");"); out.printil("_jspx_page_context = pageContext;"); out.printil("application = pageContext.getServletContext();"); out.printil("config = pageContext.getServletConfig();"); if (pageInfo.isSession()) out.printil("session = pageContext.getSession();"); out.printil("out = pageContext.getOut();"); out.printil("_jspx_out = out;"); out.println(); } /** * Generates an XML Prolog, which includes an XML declaration and an XML * doctype declaration. */ private void generateXmlProlog(Node.Nodes page) { /* * An XML declaration is generated under the following conditions: - * 'omit-xml-declaration' attribute of <jsp:output> action is set to * "no" or "false" - JSP document without a <jsp:root> */ String omitXmlDecl = pageInfo.getOmitXmlDecl(); if ((omitXmlDecl != null && !JspUtil.booleanValue(omitXmlDecl)) || (omitXmlDecl == null && page.getRoot().isXmlSyntax() && !pageInfo.hasJspRoot() && !ctxt.isTagFile())) { String cType = pageInfo.getContentType(); String charSet = cType.substring(cType.indexOf("charset=") + 8); out.printil("out.write(\"<?xml version=\\\"1.0\\\" encoding=\\\"" + charSet + "\\\"?>\\n\");"); } /* * Output a DOCTYPE declaration if the doctype-root-element appears. If * doctype-public appears: <!DOCTYPE name PUBLIC "doctypePublic" * "doctypeSystem"> else <!DOCTYPE name SYSTEM "doctypeSystem" > */ String doctypeName = pageInfo.getDoctypeName(); if (doctypeName != null) { String doctypePublic = pageInfo.getDoctypePublic(); String doctypeSystem = pageInfo.getDoctypeSystem(); out.printin("out.write(\"<!DOCTYPE "); out.print(doctypeName); if (doctypePublic == null) { out.print(" SYSTEM \\\""); } else { out.print(" PUBLIC \\\""); out.print(doctypePublic); out.print("\\\" \\\""); } out.print(doctypeSystem); out.println("\\\">\\n\");"); } } /** * A visitor that generates codes for the elements in the page. */ class GenerateVisitor extends Node.Visitor { /* * Hashtable containing introspection information on tag handlers: * <key>: tag prefix <value>: hashtable containing introspection on tag * handlers: <key>: tag short name <value>: introspection info of tag * handler for <prefix:shortName> tag */ private Hashtable<String,Hashtable<String,TagHandlerInfo>> handlerInfos; private Hashtable<String,Integer> tagVarNumbers; private String parent; private boolean isSimpleTagParent; // Is parent a SimpleTag? private String pushBodyCountVar; private String simpleTagHandlerVar; private boolean isSimpleTagHandler; private boolean isFragment; private boolean isTagFile; private ServletWriter out; private ArrayList<GenBuffer> methodsBuffered; private FragmentHelperClass fragmentHelperClass; private int methodNesting; private int charArrayCount; private HashMap<String,String> textMap; /** * Constructor. */ public GenerateVisitor(boolean isTagFile, ServletWriter out, ArrayList<GenBuffer> methodsBuffered, FragmentHelperClass fragmentHelperClass) { this.isTagFile = isTagFile; this.out = out; this.methodsBuffered = methodsBuffered; this.fragmentHelperClass = fragmentHelperClass; methodNesting = 0; handlerInfos = new Hashtable<String,Hashtable<String,TagHandlerInfo>>(); tagVarNumbers = new Hashtable<String,Integer>(); textMap = new HashMap<String,String>(); } /** * Returns an attribute value, optionally URL encoded. If the value is a * runtime expression, the result is the expression itself, as a string. * If the result is an EL expression, we insert a call to the * interpreter. If the result is a Named Attribute we insert the * generated variable name. Otherwise the result is a string literal, * quoted and escaped. * * @param attr * An JspAttribute object * @param encode * true if to be URL encoded * @param expectedType * the expected type for an EL evaluation (ignored for * attributes that aren't EL expressions) */ private String attributeValue(Node.JspAttribute attr, boolean encode, Class<?> expectedType) { String v = attr.getValue(); if (!attr.isNamedAttribute() && (v == null)) return ""; if (attr.isExpression()) { if (encode) { return "org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode(String.valueOf(" + v + "), request.getCharacterEncoding())"; } return v; } else if (attr.isELInterpreterInput()) { v = attributeValueWithEL(this.isTagFile, v, expectedType, attr.getEL().getMapName()); if (encode) { return "org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode(" + v + ", request.getCharacterEncoding())"; } return v; } else if (attr.isNamedAttribute()) { return attr.getNamedAttributeNode().getTemporaryVariableName(); } else { if (encode) { return "org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode(" + quote(v) + ", request.getCharacterEncoding())"; } return quote(v); } } /* * When interpreting the EL attribute value, literals outside the EL * must not be unescaped but the EL processor will unescape them. * Therefore, make sure only the EL expressions are processed by the EL * processor. */ private String attributeValueWithEL(boolean isTag, String tx, Class<?> expectedType, String mapName) { if (tx==null) return null; Class<?> type = expectedType; int size = tx.length(); StringBuilder output = new StringBuilder(size); boolean el = false; int i = 0; int mark = 0; char ch; while(i < size){ ch = tx.charAt(i); // Start of an EL expression if (!el && i+1 < size && ch == '$' && tx.charAt(i+1)=='{') { if (mark < i) { if (output.length() > 0) { output.append(" + "); // Composite expression - must coerce to String type = String.class; } output.append(quote(tx.substring(mark, i))); } mark = i; el = true; i += 2; } else if (ch=='\\' && i+1 < size && (tx.charAt(i+1)=='$' || tx.charAt(i+1)=='}')) { // Skip an escaped $ or } i += 2; } else if (el && ch=='}') { // End of an EL expression if (output.length() > 0) { output.append(" + "); // Composite expression - must coerce to String type = String.class; } if (i+1 < size) { // Composite expression - must coerce to String type = String.class; } output.append( JspUtil.interpreterCall(isTag, tx.substring(mark, i+1), type, mapName, false)); mark = i + 1; el = false; ++i; } else { // Nothing to see here - move to next character ++i; } } if (!el && mark < i) { if (output.length() > 0) { output.append(" + "); } output.append(quote(tx.substring(mark, i))); } return output.toString(); } /** * Prints the attribute value specified in the param action, in the form * of name=value string. * * @param n * the parent node for the param action nodes. */ private void printParams(Node n, String pageParam, boolean literal) throws JasperException { class ParamVisitor extends Node.Visitor { String separator; ParamVisitor(String separator) { this.separator = separator; } @Override public void visit(Node.ParamAction n) throws JasperException { out.print(" + "); out.print(separator); out.print(" + "); out.print("org.apache.jasper.runtime.JspRuntimeLibrary." + "URLEncode(" + quote(n.getTextAttribute("name")) + ", request.getCharacterEncoding())"); out.print("+ \"=\" + "); out.print(attributeValue(n.getValue(), true, String.class)); // The separator is '&' after the second use separator = "\"&\""; } } String sep; if (literal) { sep = pageParam.indexOf('?') > 0 ? "\"&\"" : "\"?\""; } else { sep = "((" + pageParam + ").indexOf('?')>0? '&': '?')"; } if (n.getBody() != null) { n.getBody().visit(new ParamVisitor(sep)); } } @Override public void visit(Node.Expression n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); out.printin("out.print("); out.printMultiLn(n.getText()); out.println(");"); n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.Scriptlet n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); out.printMultiLn(n.getText()); out.println(); n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.ELExpression n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); if (!pageInfo.isELIgnored() && (n.getEL() != null)) { out.printil("out.write(" + JspUtil.interpreterCall(this.isTagFile, n.getType() + "{" + new String(n.getText()) + "}", String.class, n.getEL().getMapName(), false) + ");"); } else { out.printil("out.write(" + quote(n.getType() + "{" + new String(n.getText()) + "}") + ");"); } n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.IncludeAction n) throws JasperException { String flush = n.getTextAttribute("flush"); Node.JspAttribute page = n.getPage(); boolean isFlush = false; // default to false; if ("true".equals(flush)) isFlush = true; n.setBeginJavaLine(out.getJavaLine()); String pageParam; if (page.isNamedAttribute()) { // If the page for jsp:include was specified via // jsp:attribute, first generate code to evaluate // that body. pageParam = generateNamedAttributeValue(page .getNamedAttributeNode()); } else { pageParam = attributeValue(page, false, String.class); } // If any of the params have their values specified by // jsp:attribute, prepare those values first. Node jspBody = findJspBody(n); if (jspBody != null) { prepareParams(jspBody); } else { prepareParams(n); } out .printin("org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, " + pageParam); printParams(n, pageParam, page.isLiteral()); out.println(", out, " + isFlush + ");"); n.setEndJavaLine(out.getJavaLine()); } /** * Scans through all child nodes of the given parent for <param> * subelements. For each <param> element, if its value is specified via * a Named Attribute (<jsp:attribute>), generate the code to evaluate * those bodies first. * <p> * If parent is null, simply returns. */ private void prepareParams(Node parent) throws JasperException { if (parent == null) return; Node.Nodes subelements = parent.getBody(); if (subelements != null) { for (int i = 0; i < subelements.size(); i++) { Node n = subelements.getNode(i); if (n instanceof Node.ParamAction) { Node.Nodes paramSubElements = n.getBody(); for (int j = 0; (paramSubElements != null) && (j < paramSubElements.size()); j++) { Node m = paramSubElements.getNode(j); if (m instanceof Node.NamedAttribute) { generateNamedAttributeValue((Node.NamedAttribute) m); } } } } } } /** * Finds the <jsp:body> subelement of the given parent node. If not * found, null is returned. */ private Node.JspBody findJspBody(Node parent) { Node.JspBody result = null; Node.Nodes subelements = parent.getBody(); for (int i = 0; (subelements != null) && (i < subelements.size()); i++) { Node n = subelements.getNode(i); if (n instanceof Node.JspBody) { result = (Node.JspBody) n; break; } } return result; } @Override public void visit(Node.ForwardAction n) throws JasperException { Node.JspAttribute page = n.getPage(); n.setBeginJavaLine(out.getJavaLine()); out.printil("if (true) {"); // So that javac won't complain about out.pushIndent(); // codes after "return" String pageParam; if (page.isNamedAttribute()) { // If the page for jsp:forward was specified via // jsp:attribute, first generate code to evaluate // that body. pageParam = generateNamedAttributeValue(page .getNamedAttributeNode()); } else { pageParam = attributeValue(page, false, String.class); } // If any of the params have their values specified by // jsp:attribute, prepare those values first. Node jspBody = findJspBody(n); if (jspBody != null) { prepareParams(jspBody); } else { prepareParams(n); } out.printin("_jspx_page_context.forward("); out.print(pageParam); printParams(n, pageParam, page.isLiteral()); out.println(");"); if (isTagFile || isFragment) { out.printil("throw new SkipPageException();"); } else { out.printil((methodNesting > 0) ? "return true;" : "return;"); } out.popIndent(); out.printil("}"); n.setEndJavaLine(out.getJavaLine()); // XXX Not sure if we can eliminate dead codes after this. } @Override public void visit(Node.GetProperty n) throws JasperException { String name = n.getTextAttribute("name"); String property = n.getTextAttribute("property"); n.setBeginJavaLine(out.getJavaLine()); if (beanInfo.checkVariable(name)) { // Bean is defined using useBean, introspect at compile time Class<?> bean = beanInfo.getBeanType(name); String beanName = JspUtil.getCanonicalName(bean); java.lang.reflect.Method meth = JspRuntimeLibrary .getReadMethod(bean, property); String methodName = meth.getName(); out .printil("out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString(" + "(((" + beanName + ")_jspx_page_context.findAttribute(" + "\"" + name + "\"))." + methodName + "())));"); } else if (varInfoNames.contains(name)) { // The object is a custom action with an associated // VariableInfo entry for this name. // Get the class name and then introspect at runtime. out .printil("out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString" + "(org.apache.jasper.runtime.JspRuntimeLibrary.handleGetProperty" + "(_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\")));"); } else { StringBuilder msg = new StringBuilder("jsp:getProperty for bean with name '"); msg.append(name); msg.append( "'. Name was not previously introduced as per JSP.5.3"); throw new JasperException(msg.toString()); } n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.SetProperty n) throws JasperException { String name = n.getTextAttribute("name"); String property = n.getTextAttribute("property"); String param = n.getTextAttribute("param"); Node.JspAttribute value = n.getValue(); n.setBeginJavaLine(out.getJavaLine()); if ("*".equals(property)) { out .printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspect(" + "_jspx_page_context.findAttribute(" + "\"" + name + "\"), request);"); } else if (value == null) { if (param == null) param = property; // default to same as property out .printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\", request.getParameter(\"" + param + "\"), " + "request, \"" + param + "\", false);"); } else if (value.isExpression()) { out .printil("org.apache.jasper.runtime.JspRuntimeLibrary.handleSetProperty(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\","); out.print(attributeValue(value, false, null)); out.println(");"); } else if (value.isELInterpreterInput()) { // We've got to resolve the very call to the interpreter // at runtime since we don't know what type to expect // in the general case; we thus can't hard-wire the call // into the generated code. (XXX We could, however, // optimize the case where the bean is exposed with // <jsp:useBean>, much as the code here does for // getProperty.) // The following holds true for the arguments passed to // JspRuntimeLibrary.handleSetPropertyExpression(): // - 'pageContext' is a VariableResolver. // - 'this' (either the generated Servlet or the generated tag // handler for Tag files) is a FunctionMapper. out .printil("org.apache.jasper.runtime.JspRuntimeLibrary.handleSetPropertyExpression(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\", " + quote(value.getValue()) + ", " + "_jspx_page_context, " + value.getEL().getMapName() + ");"); } else if (value.isNamedAttribute()) { // If the value for setProperty was specified via // jsp:attribute, first generate code to evaluate // that body. String valueVarName = generateNamedAttributeValue(value .getNamedAttributeNode()); out .printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\", " + valueVarName + ", null, null, false);"); } else { out .printin("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\", "); out.print(attributeValue(value, false, null)); out.println(", null, null, false);"); } n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.UseBean n) throws JasperException { String name = n.getTextAttribute("id"); String scope = n.getTextAttribute("scope"); String klass = n.getTextAttribute("class"); String type = n.getTextAttribute("type"); Node.JspAttribute beanName = n.getBeanName(); // If "class" is specified, try an instantiation at compile time boolean generateNew = false; String canonicalName = null; // Canonical name for klass if (klass != null) { try { Class<?> bean = ctxt.getClassLoader().loadClass(klass); if (klass.indexOf('$') >= 0) { // Obtain the canonical type name canonicalName = JspUtil.getCanonicalName(bean); } else { canonicalName = klass; } int modifiers = bean.getModifiers(); if (!Modifier.isPublic(modifiers) || Modifier.isInterface(modifiers) || Modifier.isAbstract(modifiers)) { throw new Exception("Invalid bean class modifier"); } // Check that there is a 0 arg constructor bean.getConstructor(new Class[] {}); // At compile time, we have determined that the bean class // exists, with a public zero constructor, new() can be // used for bean instantiation. generateNew = true; } catch (Exception e) { // Cannot instantiate the specified class, either a // compilation error or a runtime error will be raised, // depending on a compiler flag. if (ctxt.getOptions() .getErrorOnUseBeanInvalidClassAttribute()) { err.jspError(n, "jsp.error.invalid.bean", klass); } if (canonicalName == null) { // Doing our best here to get a canonical name // from the binary name, should work 99.99% of time. canonicalName = klass.replace('$', '.'); } } if (type == null) { // if type is unspecified, use "class" as type of bean type = canonicalName; } } String scopename = "PageContext.PAGE_SCOPE"; // Default to page String lock = "_jspx_page_context"; if ("request".equals(scope)) { scopename = "PageContext.REQUEST_SCOPE"; lock = "request"; } else if ("session".equals(scope)) { scopename = "PageContext.SESSION_SCOPE"; lock = "session"; } else if ("application".equals(scope)) { scopename = "PageContext.APPLICATION_SCOPE"; lock = "application"; } n.setBeginJavaLine(out.getJavaLine()); // Declare bean out.printin(type); out.print(' '); out.print(name); out.println(" = null;"); // Lock while getting or creating bean out.printin("synchronized ("); out.print(lock); out.println(") {"); out.pushIndent(); // Locate bean from context out.printin(name); out.print(" = ("); out.print(type); out.print(") _jspx_page_context.getAttribute("); out.print(quote(name)); out.print(", "); out.print(scopename); out.println(");"); // Create bean /* * Check if bean is already there */ out.printin("if ("); out.print(name); out.println(" == null){"); out.pushIndent(); if (klass == null && beanName == null) { /* * If both class name and beanName is not specified, the bean * must be found locally, otherwise it's an error */ out .printin("throw new java.lang.InstantiationException(\"bean "); out.print(name); out.println(" not found within scope\");"); } else { /* * Instantiate the bean if it is not in the specified scope. */ if (!generateNew) { String binaryName; if (beanName != null) { if (beanName.isNamedAttribute()) { // If the value for beanName was specified via // jsp:attribute, first generate code to evaluate // that body. binaryName = generateNamedAttributeValue(beanName .getNamedAttributeNode()); } else { binaryName = attributeValue(beanName, false, String.class); } } else { // Implies klass is not null binaryName = quote(klass); } out.printil("try {"); out.pushIndent(); out.printin(name); out.print(" = ("); out.print(type); out.print(") java.beans.Beans.instantiate("); out.print("this.getClass().getClassLoader(), "); out.print(binaryName); out.println(");"); out.popIndent(); /* * Note: Beans.instantiate throws ClassNotFoundException if * the bean class is abstract. */ out.printil("} catch (ClassNotFoundException exc) {"); out.pushIndent(); out .printil("throw new InstantiationException(exc.getMessage());"); out.popIndent(); out.printil("} catch (Exception exc) {"); out.pushIndent(); out.printin("throw new ServletException("); out.print("\"Cannot create bean of class \" + "); out.print(binaryName); out.println(", exc);"); out.popIndent(); out.printil("}"); // close of try } else { // Implies klass is not null // Generate codes to instantiate the bean class out.printin(name); out.print(" = new "); out.print(canonicalName); out.println("();"); } /* * Set attribute for bean in the specified scope */ out.printin("_jspx_page_context.setAttribute("); out.print(quote(name)); out.print(", "); out.print(name); out.print(", "); out.print(scopename); out.println(");"); // Only visit the body when bean is instantiated visitBody(n); } out.popIndent(); out.printil("}"); // End of lock block out.popIndent(); out.printil("}"); n.setEndJavaLine(out.getJavaLine()); } /** * @return a string for the form 'attr = "value"' */ private String makeAttr(String attr, String value) { if (value == null) return ""; return " " + attr + "=\"" + value + '\"'; } @Override public void visit(Node.PlugIn n) throws JasperException { /** * A visitor to handle <jsp:param> in a plugin */ class ParamVisitor extends Node.Visitor { private boolean ie; ParamVisitor(boolean ie) { this.ie = ie; } @Override public void visit(Node.ParamAction n) throws JasperException { String name = n.getTextAttribute("name"); if (name.equalsIgnoreCase("object")) name = "java_object"; else if (name.equalsIgnoreCase("type")) name = "java_type"; n.setBeginJavaLine(out.getJavaLine()); // XXX - Fixed a bug here - value used to be output // inline, which is only okay if value is not an EL // expression. Also, key/value pairs for the // embed tag were not being generated correctly. // Double check that this is now the correct behavior. if (ie) { // We want something of the form // out.println( "<param name=\"blah\" // value=\"" + ... + "\">" ); out.printil("out.write( \"<param name=\\\"" + escape(name) + "\\\" value=\\\"\" + " + attributeValue(n.getValue(), false, String.class) + " + \"\\\">\" );"); out.printil("out.write(\"\\n\");"); } else { // We want something of the form // out.print( " blah=\"" + ... + "\"" ); out.printil("out.write( \" " + escape(name) + "=\\\"\" + " + attributeValue(n.getValue(), false, String.class) + " + \"\\\"\" );"); } n.setEndJavaLine(out.getJavaLine()); } } String type = n.getTextAttribute("type"); String code = n.getTextAttribute("code"); String name = n.getTextAttribute("name"); Node.JspAttribute height = n.getHeight(); Node.JspAttribute width = n.getWidth(); String hspace = n.getTextAttribute("hspace"); String vspace = n.getTextAttribute("vspace"); String align = n.getTextAttribute("align"); String iepluginurl = n.getTextAttribute("iepluginurl"); String nspluginurl = n.getTextAttribute("nspluginurl"); String codebase = n.getTextAttribute("codebase"); String archive = n.getTextAttribute("archive"); String jreversion = n.getTextAttribute("jreversion"); String widthStr = null; if (width != null) { if (width.isNamedAttribute()) { widthStr = generateNamedAttributeValue(width .getNamedAttributeNode()); } else { widthStr = attributeValue(width, false, String.class); } } String heightStr = null; if (height != null) { if (height.isNamedAttribute()) { heightStr = generateNamedAttributeValue(height .getNamedAttributeNode()); } else { heightStr = attributeValue(height, false, String.class); } } if (iepluginurl == null) iepluginurl = Constants.IE_PLUGIN_URL; if (nspluginurl == null) nspluginurl = Constants.NS_PLUGIN_URL; n.setBeginJavaLine(out.getJavaLine()); // If any of the params have their values specified by // jsp:attribute, prepare those values first. // Look for a params node and prepare its param subelements: Node.JspBody jspBody = findJspBody(n); if (jspBody != null) { Node.Nodes subelements = jspBody.getBody(); if (subelements != null) { for (int i = 0; i < subelements.size(); i++) { Node m = subelements.getNode(i); if (m instanceof Node.ParamsAction) { prepareParams(m); break; } } } } // XXX - Fixed a bug here - width and height can be set // dynamically. Double-check if this generation is correct. // IE style plugin // <object ...> // First compose the runtime output string String s0 = "<object" + makeAttr("classid", ctxt.getOptions().getIeClassId()) + makeAttr("name", name); String s1 = ""; if (width != null) { s1 = " + \" width=\\\"\" + " + widthStr + " + \"\\\"\""; } String s2 = ""; if (height != null) { s2 = " + \" height=\\\"\" + " + heightStr + " + \"\\\"\""; } String s3 = makeAttr("hspace", hspace) + makeAttr("vspace", vspace) + makeAttr("align", align) + makeAttr("codebase", iepluginurl) + '>'; // Then print the output string to the java file out.printil("out.write(" + quote(s0) + s1 + s2 + " + " + quote(s3) + ");"); out.printil("out.write(\"\\n\");"); // <param > for java_code s0 = "<param name=\"java_code\"" + makeAttr("value", code) + '>'; out.printil("out.write(" + quote(s0) + ");"); out.printil("out.write(\"\\n\");"); // <param > for java_codebase if (codebase != null) { s0 = "<param name=\"java_codebase\"" + makeAttr("value", codebase) + '>'; out.printil("out.write(" + quote(s0) + ");"); out.printil("out.write(\"\\n\");"); } // <param > for java_archive if (archive != null) { s0 = "<param name=\"java_archive\"" + makeAttr("value", archive) + '>'; out.printil("out.write(" + quote(s0) + ");"); out.printil("out.write(\"\\n\");"); } // <param > for type s0 = "<param name=\"type\"" + makeAttr("value", "application/x-java-" + type + ((jreversion == null) ? "" : ";version=" + jreversion)) + '>'; out.printil("out.write(" + quote(s0) + ");"); out.printil("out.write(\"\\n\");"); /* * generate a <param> for each <jsp:param> in the plugin body */ if (n.getBody() != null) n.getBody().visit(new ParamVisitor(true)); /* * Netscape style plugin part */ out.printil("out.write(" + quote("<comment>") + ");"); out.printil("out.write(\"\\n\");"); s0 = "<EMBED" + makeAttr("type", "application/x-java-" + type + ((jreversion == null) ? "" : ";version=" + jreversion)) + makeAttr("name", name); // s1 and s2 are the same as before. s3 = makeAttr("hspace", hspace) + makeAttr("vspace", vspace) + makeAttr("align", align) + makeAttr("pluginspage", nspluginurl) + makeAttr("java_code", code) + makeAttr("java_codebase", codebase) + makeAttr("java_archive", archive); out.printil("out.write(" + quote(s0) + s1 + s2 + " + " + quote(s3) + ");"); /* * Generate a 'attr = "value"' for each <jsp:param> in plugin body */ if (n.getBody() != null) n.getBody().visit(new ParamVisitor(false)); out.printil("out.write(" + quote("/>") + ");"); out.printil("out.write(\"\\n\");"); out.printil("out.write(" + quote("<noembed>") + ");"); out.printil("out.write(\"\\n\");"); /* * Fallback */ if (n.getBody() != null) { visitBody(n); out.printil("out.write(\"\\n\");"); } out.printil("out.write(" + quote("</noembed>") + ");"); out.printil("out.write(\"\\n\");"); out.printil("out.write(" + quote("</comment>") + ");"); out.printil("out.write(\"\\n\");"); out.printil("out.write(" + quote("</object>") + ");"); out.printil("out.write(\"\\n\");"); n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.NamedAttribute n) throws JasperException { // Don't visit body of this tag - we already did earlier. } @Override public void visit(Node.CustomTag n) throws JasperException { // Use plugin to generate more efficient code if there is one. if (n.useTagPlugin()) { generateTagPlugin(n); return; } TagHandlerInfo handlerInfo = getTagHandlerInfo(n); // Create variable names String baseVar = createTagVarName(n.getQName(), n.getPrefix(), n .getLocalName()); String tagEvalVar = "_jspx_eval_" + baseVar; String tagHandlerVar = "_jspx_th_" + baseVar; String tagPushBodyCountVar = "_jspx_push_body_count_" + baseVar; // If the tag contains no scripting element, generate its codes // to a method. ServletWriter outSave = null; Node.ChildInfo ci = n.getChildInfo(); if (ci.isScriptless() && !ci.hasScriptingVars()) { // The tag handler and its body code can reside in a separate // method if it is scriptless and does not have any scripting // variable defined. String tagMethod = "_jspx_meth_" + baseVar; // Generate a call to this method out.printin("if ("); out.print(tagMethod); out.print("("); if (parent != null) { out.print(parent); out.print(", "); } out.print("_jspx_page_context"); if (pushBodyCountVar != null) { out.print(", "); out.print(pushBodyCountVar); } out.println("))"); out.pushIndent(); out.printil((methodNesting > 0) ? "return true;" : "return;"); out.popIndent(); // Set up new buffer for the method outSave = out; /* * For fragments, their bodies will be generated in fragment * helper classes, and the Java line adjustments will be done * there, hence they are set to null here to avoid double * adjustments. */ GenBuffer genBuffer = new GenBuffer(n, n.implementsSimpleTag() ? null : n.getBody()); methodsBuffered.add(genBuffer); out = genBuffer.getOut(); methodNesting++; // Generate code for method declaration out.println(); out.pushIndent(); out.printin("private boolean "); out.print(tagMethod); out.print("("); if (parent != null) { out.print("javax.servlet.jsp.tagext.JspTag "); out.print(parent); out.print(", "); } out.print("PageContext _jspx_page_context"); if (pushBodyCountVar != null) { out.print(", int[] "); out.print(pushBodyCountVar); } out.println(")"); out.printil(" throws Throwable {"); out.pushIndent(); // Initialize local variables used in this method. if (!isTagFile) { out .printil("PageContext pageContext = _jspx_page_context;"); } out.printil("JspWriter out = _jspx_page_context.getOut();"); generateLocalVariables(out, n); } // Add the named objects to the list of 'introduced' names to enable // a later test as per JSP.5.3 VariableInfo[] infos = n.getVariableInfos(); if (infos != null && infos.length > 0) { for (int i = 0; i < infos.length; i++) { VariableInfo info = infos[i]; if (info != null && info.getVarName() != null) pageInfo.getVarInfoNames().add(info.getVarName()); } } if (n.implementsSimpleTag()) { generateCustomDoTag(n, handlerInfo, tagHandlerVar); } else { /* * Classic tag handler: Generate code for start element, body, * and end element */ generateCustomStart(n, handlerInfo, tagHandlerVar, tagEvalVar, tagPushBodyCountVar); // visit body String tmpParent = parent; parent = tagHandlerVar; boolean isSimpleTagParentSave = isSimpleTagParent; isSimpleTagParent = false; String tmpPushBodyCountVar = null; if (n.implementsTryCatchFinally()) { tmpPushBodyCountVar = pushBodyCountVar; pushBodyCountVar = tagPushBodyCountVar; } boolean tmpIsSimpleTagHandler = isSimpleTagHandler; isSimpleTagHandler = false; visitBody(n); parent = tmpParent; isSimpleTagParent = isSimpleTagParentSave; if (n.implementsTryCatchFinally()) { pushBodyCountVar = tmpPushBodyCountVar; } isSimpleTagHandler = tmpIsSimpleTagHandler; generateCustomEnd(n, tagHandlerVar, tagEvalVar, tagPushBodyCountVar); } if (ci.isScriptless() && !ci.hasScriptingVars()) { // Generate end of method if (methodNesting > 0) { out.printil("return false;"); } out.popIndent(); out.printil("}"); out.popIndent(); methodNesting--; // restore previous writer out = outSave; } } private static final String DOUBLE_QUOTE = "\\\""; @Override public void visit(Node.UninterpretedTag n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); /* * Write begin tag */ out.printin("out.write(\"<"); out.print(n.getQName()); Attributes attrs = n.getNonTaglibXmlnsAttributes(); int attrsLen = (attrs == null) ? 0 : attrs.getLength(); for (int i = 0; i < attrsLen; i++) { out.print(" "); out.print(attrs.getQName(i)); out.print("="); out.print(DOUBLE_QUOTE); out.print(attrs.getValue(i).replace("\"", "&quot;")); out.print(DOUBLE_QUOTE); } attrs = n.getAttributes(); attrsLen = (attrs == null) ? 0 : attrs.getLength(); Node.JspAttribute[] jspAttrs = n.getJspAttributes(); for (int i = 0; i < attrsLen; i++) { out.print(" "); out.print(attrs.getQName(i)); out.print("="); if (jspAttrs[i].isELInterpreterInput()) { out.print("\\\"\" + "); out.print(attributeValue(jspAttrs[i], false, String.class)); out.print(" + \"\\\""); } else { out.print(DOUBLE_QUOTE); out.print(attrs.getValue(i).replace("\"", "&quot;")); out.print(DOUBLE_QUOTE); } } if (n.getBody() != null) { out.println(">\");"); // Visit tag body visitBody(n); /* * Write end tag */ out.printin("out.write(\"</"); out.print(n.getQName()); out.println(">\");"); } else { out.println("/>\");"); } n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.JspElement n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); // Compute attribute value string for XML-style and named // attributes Hashtable<String,String> map = new Hashtable<String,String>(); Node.JspAttribute[] attrs = n.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { String attrStr = null; if (attrs[i].isNamedAttribute()) { attrStr = generateNamedAttributeValue(attrs[i] .getNamedAttributeNode()); } else { attrStr = attributeValue(attrs[i], false, Object.class); } String s = " + \" " + attrs[i].getName() + "=\\\"\" + " + attrStr + " + \"\\\"\""; map.put(attrs[i].getName(), s); } // Write begin tag, using XML-style 'name' attribute as the // element name String elemName = attributeValue(n.getNameAttribute(), false, String.class); out.printin("out.write(\"<\""); out.print(" + " + elemName); // Write remaining attributes Enumeration<String> enumeration = map.keys(); while (enumeration.hasMoreElements()) { String attrName = enumeration.nextElement(); out.print(map.get(attrName)); } // Does the <jsp:element> have nested tags other than // <jsp:attribute> boolean hasBody = false; Node.Nodes subelements = n.getBody(); if (subelements != null) { for (int i = 0; i < subelements.size(); i++) { Node subelem = subelements.getNode(i); if (!(subelem instanceof Node.NamedAttribute)) { hasBody = true; break; } } } if (hasBody) { out.println(" + \">\");"); // Smap should not include the body n.setEndJavaLine(out.getJavaLine()); // Visit tag body visitBody(n); // Write end tag out.printin("out.write(\"</\""); out.print(" + " + elemName); out.println(" + \">\");"); } else { out.println(" + \"/>\");"); n.setEndJavaLine(out.getJavaLine()); } } @Override public void visit(Node.TemplateText n) throws JasperException { String text = n.getText(); int textSize = text.length(); if (textSize == 0) { return; } if (textSize <= 3) { // Special case small text strings n.setBeginJavaLine(out.getJavaLine()); int lineInc = 0; for (int i = 0; i < textSize; i++) { char ch = text.charAt(i); out.printil("out.write(" + quote(ch) + ");"); if (i > 0) { n.addSmap(lineInc); } if (ch == '\n') { lineInc++; } } n.setEndJavaLine(out.getJavaLine()); return; } if (ctxt.getOptions().genStringAsCharArray()) { // Generate Strings as char arrays, for performance ServletWriter caOut; if (charArrayBuffer == null) { charArrayBuffer = new GenBuffer(); caOut = charArrayBuffer.getOut(); caOut.pushIndent(); textMap = new HashMap<String,String>(); } else { caOut = charArrayBuffer.getOut(); } String charArrayName = textMap.get(text); if (charArrayName == null) { charArrayName = "_jspx_char_array_" + charArrayCount++; textMap.put(text, charArrayName); caOut.printin("static char[] "); caOut.print(charArrayName); caOut.print(" = "); caOut.print(quote(text)); caOut.println(".toCharArray();"); } n.setBeginJavaLine(out.getJavaLine()); out.printil("out.write(" + charArrayName + ");"); n.setEndJavaLine(out.getJavaLine()); return; } n.setBeginJavaLine(out.getJavaLine()); out.printin(); StringBuilder sb = new StringBuilder("out.write(\""); int initLength = sb.length(); int count = JspUtil.CHUNKSIZE; int srcLine = 0; // relative to starting source line for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); --count; switch (ch) { case '"': sb.append('\\').append('\"'); break; case '\\': sb.append('\\').append('\\'); break; case '\r': sb.append('\\').append('r'); break; case '\n': sb.append('\\').append('n'); srcLine++; if (breakAtLF || count < 0) { // Generate an out.write() when see a '\n' in template sb.append("\");"); out.println(sb.toString()); if (i < text.length() - 1) { out.printin(); } sb.setLength(initLength); count = JspUtil.CHUNKSIZE; } // add a Smap for this line n.addSmap(srcLine); break; case '\t': // Not sure we need this sb.append('\\').append('t'); break; default: sb.append(ch); } } if (sb.length() > initLength) { sb.append("\");"); out.println(sb.toString()); } n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.JspBody n) throws JasperException { if (n.getBody() != null) { if (isSimpleTagHandler) { out.printin(simpleTagHandlerVar); out.print(".setJspBody("); generateJspFragment(n, simpleTagHandlerVar); out.println(");"); } else { visitBody(n); } } } @Override public void visit(Node.InvokeAction n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); // Copy virtual page scope of tag file to page scope of invoking // page out.printil("((org.apache.jasper.runtime.JspContextWrapper) this.jspContext).syncBeforeInvoke();"); String varReaderAttr = n.getTextAttribute("varReader"); String varAttr = n.getTextAttribute("var"); if (varReaderAttr != null || varAttr != null) { out.printil("_jspx_sout = new java.io.StringWriter();"); } else { out.printil("_jspx_sout = null;"); } // Invoke fragment, unless fragment is null out.printin("if ("); out.print(toGetterMethod(n.getTextAttribute("fragment"))); out.println(" != null) {"); out.pushIndent(); out.printin(toGetterMethod(n.getTextAttribute("fragment"))); out.println(".invoke(_jspx_sout);"); out.popIndent(); out.printil("}"); // Store varReader in appropriate scope if (varReaderAttr != null || varAttr != null) { String scopeName = n.getTextAttribute("scope"); out.printin("_jspx_page_context.setAttribute("); if (varReaderAttr != null) { out.print(quote(varReaderAttr)); out.print(", new java.io.StringReader(_jspx_sout.toString())"); } else { out.print(quote(varAttr)); out.print(", _jspx_sout.toString()"); } if (scopeName != null) { out.print(", "); out.print(getScopeConstant(scopeName)); } out.println(");"); } // Restore EL context out.printil("jspContext.getELContext().putContext(JspContext.class,getJspContext());"); n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.DoBodyAction n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); // Copy virtual page scope of tag file to page scope of invoking // page out.printil("((org.apache.jasper.runtime.JspContextWrapper) this.jspContext).syncBeforeInvoke();"); // Invoke body String varReaderAttr = n.getTextAttribute("varReader"); String varAttr = n.getTextAttribute("var"); if (varReaderAttr != null || varAttr != null) { out.printil("_jspx_sout = new java.io.StringWriter();"); } else { out.printil("_jspx_sout = null;"); } out.printil("if (getJspBody() != null)"); out.pushIndent(); out.printil("getJspBody().invoke(_jspx_sout);"); out.popIndent(); // Store varReader in appropriate scope if (varReaderAttr != null || varAttr != null) { String scopeName = n.getTextAttribute("scope"); out.printin("_jspx_page_context.setAttribute("); if (varReaderAttr != null) { out.print(quote(varReaderAttr)); out .print(", new java.io.StringReader(_jspx_sout.toString())"); } else { out.print(quote(varAttr)); out.print(", _jspx_sout.toString()"); } if (scopeName != null) { out.print(", "); out.print(getScopeConstant(scopeName)); } out.println(");"); } // Restore EL context out.printil("jspContext.getELContext().putContext(JspContext.class,getJspContext());"); n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.AttributeGenerator n) throws JasperException { Node.CustomTag tag = n.getTag(); Node.JspAttribute[] attrs = tag.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { if (attrs[i].getName().equals(n.getName())) { out.print(evaluateAttribute(getTagHandlerInfo(tag), attrs[i], tag, null)); break; } } } private TagHandlerInfo getTagHandlerInfo(Node.CustomTag n) throws JasperException { Hashtable<String,TagHandlerInfo> handlerInfosByShortName = handlerInfos.get(n.getPrefix()); if (handlerInfosByShortName == null) { handlerInfosByShortName = new Hashtable<String,TagHandlerInfo>(); handlerInfos.put(n.getPrefix(), handlerInfosByShortName); } TagHandlerInfo handlerInfo = handlerInfosByShortName.get(n.getLocalName()); if (handlerInfo == null) { handlerInfo = new TagHandlerInfo(n, n.getTagHandlerClass(), err); handlerInfosByShortName.put(n.getLocalName(), handlerInfo); } return handlerInfo; } private void generateTagPlugin(Node.CustomTag n) throws JasperException { if (n.getAtSTag() != null) { n.getAtSTag().visit(this); } visitBody(n); if (n.getAtETag() != null) { n.getAtETag().visit(this); } } private void generateCustomStart(Node.CustomTag n, TagHandlerInfo handlerInfo, String tagHandlerVar, String tagEvalVar, String tagPushBodyCountVar) throws JasperException { Class<?> tagHandlerClass = handlerInfo.getTagHandlerClass(); out.printin("// "); out.println(n.getQName()); n.setBeginJavaLine(out.getJavaLine()); // Declare AT_BEGIN scripting variables declareScriptingVars(n, VariableInfo.AT_BEGIN); saveScriptingVars(n, VariableInfo.AT_BEGIN); String tagHandlerClassName = JspUtil .getCanonicalName(tagHandlerClass); if (isPoolingEnabled && !(n.implementsJspIdConsumer())) { out.printin(tagHandlerClassName); out.print(" "); out.print(tagHandlerVar); out.print(" = "); out.print("("); out.print(tagHandlerClassName); out.print(") "); out.print(n.getTagHandlerPoolName()); out.print(".get("); out.print(tagHandlerClassName); out.println(".class);"); } else { writeNewInstance(tagHandlerVar, tagHandlerClassName); } // includes setting the context generateSetters(n, tagHandlerVar, handlerInfo, false); // JspIdConsumer (after context has been set) if (n.implementsJspIdConsumer()) { out.printin(tagHandlerVar); out.print(".setJspId(\""); out.print(createJspId()); out.println("\");"); } if (n.implementsTryCatchFinally()) { out.printin("int[] "); out.print(tagPushBodyCountVar); out.println(" = new int[] { 0 };"); out.printil("try {"); out.pushIndent(); } out.printin("int "); out.print(tagEvalVar); out.print(" = "); out.print(tagHandlerVar); out.println(".doStartTag();"); if (!n.implementsBodyTag()) { // Synchronize AT_BEGIN scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); } if (!n.hasEmptyBody()) { out.printin("if ("); out.print(tagEvalVar); out.println(" != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {"); out.pushIndent(); // Declare NESTED scripting variables declareScriptingVars(n, VariableInfo.NESTED); saveScriptingVars(n, VariableInfo.NESTED); if (n.implementsBodyTag()) { out.printin("if ("); out.print(tagEvalVar); out .println(" != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {"); // Assume EVAL_BODY_BUFFERED out.pushIndent(); out.printil("out = _jspx_page_context.pushBody();"); if (n.implementsTryCatchFinally()) { out.printin(tagPushBodyCountVar); out.println("[0]++;"); } else if (pushBodyCountVar != null) { out.printin(pushBodyCountVar); out.println("[0]++;"); } out.printin(tagHandlerVar); out.println(".setBodyContent((javax.servlet.jsp.tagext.BodyContent) out);"); out.printin(tagHandlerVar); out.println(".doInitBody();"); out.popIndent(); out.printil("}"); // Synchronize AT_BEGIN and NESTED scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); syncScriptingVars(n, VariableInfo.NESTED); } else { // Synchronize NESTED scripting variables syncScriptingVars(n, VariableInfo.NESTED); } if (n.implementsIterationTag()) { out.printil("do {"); out.pushIndent(); } } // Map the Java lines that handles start of custom tags to the // JSP line for this tag n.setEndJavaLine(out.getJavaLine()); } private void writeNewInstance(String tagHandlerVar, String tagHandlerClassName) { if (Constants.USE_INSTANCE_MANAGER_FOR_TAGS) { out.printin(tagHandlerClassName); out.print(" "); out.print(tagHandlerVar); out.print(" = ("); out.print(tagHandlerClassName); out.print(")"); out.print(VAR_INSTANCEMANAGER); out.print(".newInstance(\""); out.print(tagHandlerClassName); out.println("\", this.getClass().getClassLoader());"); } else { out.printin(tagHandlerClassName); out.print(" "); out.print(tagHandlerVar); out.print(" = ("); out.print("new "); out.print(tagHandlerClassName); out.println("());"); out.printin(VAR_INSTANCEMANAGER); out.print(".newInstance("); out.print(tagHandlerVar); out.println(");"); } } private void writeDestroyInstance(String tagHandlerVar) { out.printin(VAR_INSTANCEMANAGER); out.print(".destroyInstance("); out.print(tagHandlerVar); out.println(");"); } private void generateCustomEnd(Node.CustomTag n, String tagHandlerVar, String tagEvalVar, String tagPushBodyCountVar) { if (!n.hasEmptyBody()) { if (n.implementsIterationTag()) { out.printin("int evalDoAfterBody = "); out.print(tagHandlerVar); out.println(".doAfterBody();"); // Synchronize AT_BEGIN and NESTED scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); syncScriptingVars(n, VariableInfo.NESTED); out .printil("if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)"); out.pushIndent(); out.printil("break;"); out.popIndent(); out.popIndent(); out.printil("} while (true);"); } restoreScriptingVars(n, VariableInfo.NESTED); if (n.implementsBodyTag()) { out.printin("if ("); out.print(tagEvalVar); out .println(" != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {"); out.pushIndent(); out.printil("out = _jspx_page_context.popBody();"); if (n.implementsTryCatchFinally()) { out.printin(tagPushBodyCountVar); out.println("[0]--;"); } else if (pushBodyCountVar != null) { out.printin(pushBodyCountVar); out.println("[0]--;"); } out.popIndent(); out.printil("}"); } out.popIndent(); // EVAL_BODY out.printil("}"); } out.printin("if ("); out.print(tagHandlerVar); out .println(".doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {"); out.pushIndent(); if (!n.implementsTryCatchFinally()) { if (isPoolingEnabled && !(n.implementsJspIdConsumer())) { out.printin(n.getTagHandlerPoolName()); out.print(".reuse("); out.print(tagHandlerVar); out.println(");"); } else { out.printin(tagHandlerVar); out.println(".release();"); writeDestroyInstance(tagHandlerVar); } } if (isTagFile || isFragment) { out.printil("throw new SkipPageException();"); } else { out.printil((methodNesting > 0) ? "return true;" : "return;"); } out.popIndent(); out.printil("}"); // Synchronize AT_BEGIN scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); // TryCatchFinally if (n.implementsTryCatchFinally()) { out.popIndent(); // try out.printil("} catch (Throwable _jspx_exception) {"); out.pushIndent(); out.printin("while ("); out.print(tagPushBodyCountVar); out.println("[0]-- > 0)"); out.pushIndent(); out.printil("out = _jspx_page_context.popBody();"); out.popIndent(); out.printin(tagHandlerVar); out.println(".doCatch(_jspx_exception);"); out.popIndent(); out.printil("} finally {"); out.pushIndent(); out.printin(tagHandlerVar); out.println(".doFinally();"); } if (isPoolingEnabled && !(n.implementsJspIdConsumer())) { out.printin(n.getTagHandlerPoolName()); out.print(".reuse("); out.print(tagHandlerVar); out.println(");"); } else { out.printin(tagHandlerVar); out.println(".release();"); writeDestroyInstance(tagHandlerVar); } if (n.implementsTryCatchFinally()) { out.popIndent(); out.printil("}"); } // Declare and synchronize AT_END scripting variables (must do this // outside the try/catch/finally block) declareScriptingVars(n, VariableInfo.AT_END); syncScriptingVars(n, VariableInfo.AT_END); restoreScriptingVars(n, VariableInfo.AT_BEGIN); } private void generateCustomDoTag(Node.CustomTag n, TagHandlerInfo handlerInfo, String tagHandlerVar) throws JasperException { Class<?> tagHandlerClass = handlerInfo.getTagHandlerClass(); n.setBeginJavaLine(out.getJavaLine()); out.printin("// "); out.println(n.getQName()); // Declare AT_BEGIN scripting variables declareScriptingVars(n, VariableInfo.AT_BEGIN); saveScriptingVars(n, VariableInfo.AT_BEGIN); String tagHandlerClassName = JspUtil .getCanonicalName(tagHandlerClass); writeNewInstance(tagHandlerVar, tagHandlerClassName); generateSetters(n, tagHandlerVar, handlerInfo, true); // JspIdConsumer (after context has been set) if (n.implementsJspIdConsumer()) { out.printin(tagHandlerVar); out.print(".setJspId(\""); out.print(createJspId()); out.println("\");"); } // Set the body if (findJspBody(n) == null) { /* * Encapsulate body of custom tag invocation in JspFragment and * pass it to tag handler's setJspBody(), unless tag body is * empty */ if (!n.hasEmptyBody()) { out.printin(tagHandlerVar); out.print(".setJspBody("); generateJspFragment(n, tagHandlerVar); out.println(");"); } } else { /* * Body of tag is the body of the <jsp:body> element. The visit * method for that element is going to encapsulate that * element's body in a JspFragment and pass it to the tag * handler's setJspBody() */ String tmpTagHandlerVar = simpleTagHandlerVar; simpleTagHandlerVar = tagHandlerVar; boolean tmpIsSimpleTagHandler = isSimpleTagHandler; isSimpleTagHandler = true; visitBody(n); simpleTagHandlerVar = tmpTagHandlerVar; isSimpleTagHandler = tmpIsSimpleTagHandler; } out.printin(tagHandlerVar); out.println(".doTag();"); restoreScriptingVars(n, VariableInfo.AT_BEGIN); // Synchronize AT_BEGIN scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); // Declare and synchronize AT_END scripting variables declareScriptingVars(n, VariableInfo.AT_END); syncScriptingVars(n, VariableInfo.AT_END); // Resource injection writeDestroyInstance(tagHandlerVar); n.setEndJavaLine(out.getJavaLine()); } private void declareScriptingVars(Node.CustomTag n, int scope) { Vector<Object> vec = n.getScriptingVars(scope); if (vec != null) { for (int i = 0; i < vec.size(); i++) { Object elem = vec.elementAt(i); if (elem instanceof VariableInfo) { VariableInfo varInfo = (VariableInfo) elem; if (varInfo.getDeclare()) { out.printin(varInfo.getClassName()); out.print(" "); out.print(varInfo.getVarName()); out.println(" = null;"); } } else { TagVariableInfo tagVarInfo = (TagVariableInfo) elem; if (tagVarInfo.getDeclare()) { String varName = tagVarInfo.getNameGiven(); if (varName == null) { varName = n.getTagData().getAttributeString( tagVarInfo.getNameFromAttribute()); } else if (tagVarInfo.getNameFromAttribute() != null) { // alias continue; } out.printin(tagVarInfo.getClassName()); out.print(" "); out.print(varName); out.println(" = null;"); } } } } } /* * This method is called as part of the custom tag's start element. * * If the given custom tag has a custom nesting level greater than 0, * save the current values of its scripting variables to temporary * variables, so those values may be restored in the tag's end element. * This way, the scripting variables may be synchronized by the given * tag without affecting their original values. */ private void saveScriptingVars(Node.CustomTag n, int scope) { if (n.getCustomNestingLevel() == 0) { return; } TagVariableInfo[] tagVarInfos = n.getTagVariableInfos(); VariableInfo[] varInfos = n.getVariableInfos(); if ((varInfos.length == 0) && (tagVarInfos.length == 0)) { return; } if (varInfos.length > 0) { for (int i = 0; i < varInfos.length; i++) { if (varInfos[i].getScope() != scope) continue; // If the scripting variable has been declared, skip codes // for saving and restoring it. if (n.getScriptingVars(scope).contains(varInfos[i])) continue; String varName = varInfos[i].getVarName(); String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); out.printin(tmpVarName); out.print(" = "); out.print(varName); out.println(";"); } } else { for (int i = 0; i < tagVarInfos.length; i++) { if (tagVarInfos[i].getScope() != scope) continue; // If the scripting variable has been declared, skip codes // for saving and restoring it. if (n.getScriptingVars(scope).contains(tagVarInfos[i])) continue; String varName = tagVarInfos[i].getNameGiven(); if (varName == null) { varName = n.getTagData().getAttributeString( tagVarInfos[i].getNameFromAttribute()); } else if (tagVarInfos[i].getNameFromAttribute() != null) { // alias continue; } String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); out.printin(tmpVarName); out.print(" = "); out.print(varName); out.println(";"); } } } /* * This method is called as part of the custom tag's end element. * * If the given custom tag has a custom nesting level greater than 0, * restore its scripting variables to their original values that were * saved in the tag's start element. */ private void restoreScriptingVars(Node.CustomTag n, int scope) { if (n.getCustomNestingLevel() == 0) { return; } TagVariableInfo[] tagVarInfos = n.getTagVariableInfos(); VariableInfo[] varInfos = n.getVariableInfos(); if ((varInfos.length == 0) && (tagVarInfos.length == 0)) { return; } if (varInfos.length > 0) { for (int i = 0; i < varInfos.length; i++) { if (varInfos[i].getScope() != scope) continue; // If the scripting variable has been declared, skip codes // for saving and restoring it. if (n.getScriptingVars(scope).contains(varInfos[i])) continue; String varName = varInfos[i].getVarName(); String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); out.printin(varName); out.print(" = "); out.print(tmpVarName); out.println(";"); } } else { for (int i = 0; i < tagVarInfos.length; i++) { if (tagVarInfos[i].getScope() != scope) continue; // If the scripting variable has been declared, skip codes // for saving and restoring it. if (n.getScriptingVars(scope).contains(tagVarInfos[i])) continue; String varName = tagVarInfos[i].getNameGiven(); if (varName == null) { varName = n.getTagData().getAttributeString( tagVarInfos[i].getNameFromAttribute()); } else if (tagVarInfos[i].getNameFromAttribute() != null) { // alias continue; } String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); out.printin(varName); out.print(" = "); out.print(tmpVarName); out.println(";"); } } } /* * Synchronizes the scripting variables of the given custom tag for the * given scope. */ private void syncScriptingVars(Node.CustomTag n, int scope) { TagVariableInfo[] tagVarInfos = n.getTagVariableInfos(); VariableInfo[] varInfos = n.getVariableInfos(); if ((varInfos.length == 0) && (tagVarInfos.length == 0)) { return; } if (varInfos.length > 0) { for (int i = 0; i < varInfos.length; i++) { if (varInfos[i].getScope() == scope) { out.printin(varInfos[i].getVarName()); out.print(" = ("); out.print(varInfos[i].getClassName()); out.print(") _jspx_page_context.findAttribute("); out.print(quote(varInfos[i].getVarName())); out.println(");"); } } } else { for (int i = 0; i < tagVarInfos.length; i++) { if (tagVarInfos[i].getScope() == scope) { String name = tagVarInfos[i].getNameGiven(); if (name == null) { name = n.getTagData().getAttributeString( tagVarInfos[i].getNameFromAttribute()); } else if (tagVarInfos[i].getNameFromAttribute() != null) { // alias continue; } out.printin(name); out.print(" = ("); out.print(tagVarInfos[i].getClassName()); out.print(") _jspx_page_context.findAttribute("); out.print(quote(name)); out.println(");"); } } } } private String getJspContextVar() { if (this.isTagFile) { return "this.getJspContext()"; } return "_jspx_page_context"; } private String getExpressionFactoryVar() { return VAR_EXPRESSIONFACTORY; } /* * Creates a tag variable name by concatenating the given prefix and * shortName and encoded to make the resultant string a valid Java * Identifier. */ private String createTagVarName(String fullName, String prefix, String shortName) { String varName; synchronized (tagVarNumbers) { varName = prefix + "_" + shortName + "_"; if (tagVarNumbers.get(fullName) != null) { Integer i = tagVarNumbers.get(fullName); varName = varName + i.intValue(); tagVarNumbers.put(fullName, new Integer(i.intValue() + 1)); } else { tagVarNumbers.put(fullName, new Integer(1)); varName = varName + "0"; } } return JspUtil.makeJavaIdentifier(varName); } private String evaluateAttribute(TagHandlerInfo handlerInfo, Node.JspAttribute attr, Node.CustomTag n, String tagHandlerVar) throws JasperException { String attrValue = attr.getValue(); if (attrValue == null) { if (attr.isNamedAttribute()) { if (n.checkIfAttributeIsJspFragment(attr.getName())) { // XXX - no need to generate temporary variable here attrValue = generateNamedAttributeJspFragment(attr .getNamedAttributeNode(), tagHandlerVar); } else { attrValue = generateNamedAttributeValue(attr .getNamedAttributeNode()); } } else { return null; } } String localName = attr.getLocalName(); Method m = null; Class<?>[] c = null; if (attr.isDynamic()) { c = OBJECT_CLASS; } else { m = handlerInfo.getSetterMethod(localName); if (m == null) { err.jspError(n, "jsp.error.unable.to_find_method", attr .getName()); } c = m.getParameterTypes(); // XXX assert(c.length > 0) } if (attr.isExpression()) { // Do nothing } else if (attr.isNamedAttribute()) { if (!n.checkIfAttributeIsJspFragment(attr.getName()) && !attr.isDynamic()) { attrValue = convertString(c[0], attrValue, localName, handlerInfo.getPropertyEditorClass(localName), true); } } else if (attr.isELInterpreterInput()) { // results buffer StringBuilder sb = new StringBuilder(64); TagAttributeInfo tai = attr.getTagAttributeInfo(); // generate elContext reference sb.append(getJspContextVar()); sb.append(".getELContext()"); String elContext = sb.toString(); if (attr.getEL() != null && attr.getEL().getMapName() != null) { sb.setLength(0); sb.append("new org.apache.jasper.el.ELContextWrapper("); sb.append(elContext); sb.append(','); sb.append(attr.getEL().getMapName()); sb.append(')'); elContext = sb.toString(); } // reset buffer sb.setLength(0); // create our mark sb.append(n.getStart().toString()); sb.append(" '"); sb.append(attrValue); sb.append('\''); String mark = sb.toString(); // reset buffer sb.setLength(0); // depending on type if (attr.isDeferredInput() || ((tai != null) && ValueExpression.class.getName().equals(tai.getTypeName()))) { sb.append("new org.apache.jasper.el.JspValueExpression("); sb.append(quote(mark)); sb.append(','); sb.append(getExpressionFactoryVar()); sb.append(".createValueExpression("); if (attr.getEL() != null) { // optimize sb.append(elContext); sb.append(','); } sb.append(quote(attrValue)); sb.append(','); sb.append(JspUtil.toJavaSourceTypeFromTld(attr.getExpectedTypeName())); sb.append("))"); // should the expression be evaluated before passing to // the setter? boolean evaluate = false; if (tai.canBeRequestTime()) { evaluate = true; // JSP.2.3.2 } if (attr.isDeferredInput()) { evaluate = false; // JSP.2.3.3 } if (attr.isDeferredInput() && tai.canBeRequestTime()) { evaluate = !attrValue.contains("#{"); // JSP.2.3.5 } if (evaluate) { sb.append(".getValue("); sb.append(getJspContextVar()); sb.append(".getELContext()"); sb.append(")"); } attrValue = sb.toString(); } else if (attr.isDeferredMethodInput() || ((tai != null) && MethodExpression.class.getName().equals(tai.getTypeName()))) { sb.append("new org.apache.jasper.el.JspMethodExpression("); sb.append(quote(mark)); sb.append(','); sb.append(getExpressionFactoryVar()); sb.append(".createMethodExpression("); sb.append(elContext); sb.append(','); sb.append(quote(attrValue)); sb.append(','); sb.append(JspUtil.toJavaSourceTypeFromTld(attr.getExpectedTypeName())); sb.append(','); sb.append("new Class[] {"); String[] p = attr.getParameterTypeNames(); for (int i = 0; i < p.length; i++) { sb.append(JspUtil.toJavaSourceTypeFromTld(p[i])); sb.append(','); } if (p.length > 0) { sb.setLength(sb.length() - 1); } sb.append("}))"); attrValue = sb.toString(); } else { // run attrValue through the expression interpreter String mapName = (attr.getEL() != null) ? attr.getEL() .getMapName() : null; attrValue = attributeValueWithEL(this.isTagFile, attrValue, c[0], mapName); } } else { attrValue = convertString(c[0], attrValue, localName, handlerInfo.getPropertyEditorClass(localName), false); } return attrValue; } /** * Generate code to create a map for the alias variables * * @return the name of the map */ private String generateAliasMap(Node.CustomTag n, String tagHandlerVar) { TagVariableInfo[] tagVars = n.getTagVariableInfos(); String aliasMapVar = null; boolean aliasSeen = false; for (int i = 0; i < tagVars.length; i++) { String nameFrom = tagVars[i].getNameFromAttribute(); if (nameFrom != null) { String aliasedName = n.getAttributeValue(nameFrom); if (aliasedName == null) continue; if (!aliasSeen) { out.printin("java.util.HashMap "); aliasMapVar = tagHandlerVar + "_aliasMap"; out.print(aliasMapVar); out.println(" = new java.util.HashMap();"); aliasSeen = true; } out.printin(aliasMapVar); out.print(".put("); out.print(quote(tagVars[i].getNameGiven())); out.print(", "); out.print(quote(aliasedName)); out.println(");"); } } return aliasMapVar; } private void generateSetters(Node.CustomTag n, String tagHandlerVar, TagHandlerInfo handlerInfo, boolean simpleTag) throws JasperException { // Set context if (simpleTag) { // Generate alias map String aliasMapVar = null; if (n.isTagFile()) { aliasMapVar = generateAliasMap(n, tagHandlerVar); } out.printin(tagHandlerVar); if (aliasMapVar == null) { out.println(".setJspContext(_jspx_page_context);"); } else { out.print(".setJspContext(_jspx_page_context, "); out.print(aliasMapVar); out.println(");"); } } else { out.printin(tagHandlerVar); out.println(".setPageContext(_jspx_page_context);"); } // Set parent if (isTagFile && parent == null) { out.printin(tagHandlerVar); out.print(".setParent("); out.print("new javax.servlet.jsp.tagext.TagAdapter("); out.print("(javax.servlet.jsp.tagext.SimpleTag) this ));"); } else if (!simpleTag) { out.printin(tagHandlerVar); out.print(".setParent("); if (parent != null) { if (isSimpleTagParent) { out.print("new javax.servlet.jsp.tagext.TagAdapter("); out.print("(javax.servlet.jsp.tagext.SimpleTag) "); out.print(parent); out.println("));"); } else { out.print("(javax.servlet.jsp.tagext.Tag) "); out.print(parent); out.println(");"); } } else { out.println("null);"); } } else { // The setParent() method need not be called if the value being // passed is null, since SimpleTag instances are not reused if (parent != null) { out.printin(tagHandlerVar); out.print(".setParent("); out.print(parent); out.println(");"); } } // need to handle deferred values and methods Node.JspAttribute[] attrs = n.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { String attrValue = evaluateAttribute(handlerInfo, attrs[i], n, tagHandlerVar); Mark m = n.getStart(); out.printil("// "+m.getFile()+"("+m.getLineNumber()+","+m.getColumnNumber()+") "+ attrs[i].getTagAttributeInfo()); if (attrs[i].isDynamic()) { out.printin(tagHandlerVar); out.print("."); out.print("setDynamicAttribute("); String uri = attrs[i].getURI(); if ("".equals(uri) || (uri == null)) { out.print("null"); } else { out.print("\"" + attrs[i].getURI() + "\""); } out.print(", \""); out.print(attrs[i].getLocalName()); out.print("\", "); out.print(attrValue); out.println(");"); } else { out.printin(tagHandlerVar); out.print("."); out.print(handlerInfo.getSetterMethod( attrs[i].getLocalName()).getName()); out.print("("); out.print(attrValue); out.println(");"); } } } /* * @param c The target class to which to coerce the given string @param * s The string value @param attrName The name of the attribute whose * value is being supplied @param propEditorClass The property editor * for the given attribute @param isNamedAttribute true if the given * attribute is a named attribute (that is, specified using the * jsp:attribute standard action), and false otherwise */ private String convertString(Class<?> c, String s, String attrName, Class<?> propEditorClass, boolean isNamedAttribute) { String quoted = s; if (!isNamedAttribute) { quoted = quote(s); } if (propEditorClass != null) { String className = JspUtil.getCanonicalName(c); return "(" + className + ")org.apache.jasper.runtime.JspRuntimeLibrary.getValueFromBeanInfoPropertyEditor(" + className + ".class, \"" + attrName + "\", " + quoted + ", " + JspUtil.getCanonicalName(propEditorClass) + ".class)"; } else if (c == String.class) { return quoted; } else if (c == boolean.class) { return JspUtil.coerceToPrimitiveBoolean(s, isNamedAttribute); } else if (c == Boolean.class) { return JspUtil.coerceToBoolean(s, isNamedAttribute); } else if (c == byte.class) { return JspUtil.coerceToPrimitiveByte(s, isNamedAttribute); } else if (c == Byte.class) { return JspUtil.coerceToByte(s, isNamedAttribute); } else if (c == char.class) { return JspUtil.coerceToChar(s, isNamedAttribute); } else if (c == Character.class) { return JspUtil.coerceToCharacter(s, isNamedAttribute); } else if (c == double.class) { return JspUtil.coerceToPrimitiveDouble(s, isNamedAttribute); } else if (c == Double.class) { return JspUtil.coerceToDouble(s, isNamedAttribute); } else if (c == float.class) { return JspUtil.coerceToPrimitiveFloat(s, isNamedAttribute); } else if (c == Float.class) { return JspUtil.coerceToFloat(s, isNamedAttribute); } else if (c == int.class) { return JspUtil.coerceToInt(s, isNamedAttribute); } else if (c == Integer.class) { return JspUtil.coerceToInteger(s, isNamedAttribute); } else if (c == short.class) { return JspUtil.coerceToPrimitiveShort(s, isNamedAttribute); } else if (c == Short.class) { return JspUtil.coerceToShort(s, isNamedAttribute); } else if (c == long.class) { return JspUtil.coerceToPrimitiveLong(s, isNamedAttribute); } else if (c == Long.class) { return JspUtil.coerceToLong(s, isNamedAttribute); } else if (c == Object.class) { return "new String(" + quoted + ")"; } else { String className = JspUtil.getCanonicalName(c); return "(" + className + ")org.apache.jasper.runtime.JspRuntimeLibrary.getValueFromPropertyEditorManager(" + className + ".class, \"" + attrName + "\", " + quoted + ")"; } } /* * Converts the scope string representation, whose possible values are * "page", "request", "session", and "application", to the corresponding * scope constant. */ private String getScopeConstant(String scope) { String scopeName = "PageContext.PAGE_SCOPE"; // Default to page if ("request".equals(scope)) { scopeName = "PageContext.REQUEST_SCOPE"; } else if ("session".equals(scope)) { scopeName = "PageContext.SESSION_SCOPE"; } else if ("application".equals(scope)) { scopeName = "PageContext.APPLICATION_SCOPE"; } return scopeName; } /** * Generates anonymous JspFragment inner class which is passed as an * argument to SimpleTag.setJspBody(). */ private void generateJspFragment(Node n, String tagHandlerVar) throws JasperException { // XXX - A possible optimization here would be to check to see // if the only child of the parent node is TemplateText. If so, // we know there won't be any parameters, etc, so we can // generate a low-overhead JspFragment that just echoes its // body. The implementation of this fragment can come from // the org.apache.jasper.runtime package as a support class. FragmentHelperClass.Fragment fragment = fragmentHelperClass .openFragment(n, methodNesting); ServletWriter outSave = out; out = fragment.getGenBuffer().getOut(); String tmpParent = parent; parent = "_jspx_parent"; boolean isSimpleTagParentSave = isSimpleTagParent; isSimpleTagParent = true; boolean tmpIsFragment = isFragment; isFragment = true; String pushBodyCountVarSave = pushBodyCountVar; if (pushBodyCountVar != null) { // Use a fixed name for push body count, to simplify code gen pushBodyCountVar = "_jspx_push_body_count"; } visitBody(n); out = outSave; parent = tmpParent; isSimpleTagParent = isSimpleTagParentSave; isFragment = tmpIsFragment; pushBodyCountVar = pushBodyCountVarSave; fragmentHelperClass.closeFragment(fragment, methodNesting); // XXX - Need to change pageContext to jspContext if // we're not in a place where pageContext is defined (e.g. // in a fragment or in a tag file. out.print("new " + fragmentHelperClass.getClassName() + "( " + fragment.getId() + ", _jspx_page_context, " + tagHandlerVar + ", " + pushBodyCountVar + ")"); } /** * Generate the code required to obtain the runtime value of the given * named attribute. * * @return The name of the temporary variable the result is stored in. */ public String generateNamedAttributeValue(Node.NamedAttribute n) throws JasperException { String varName = n.getTemporaryVariableName(); // If the only body element for this named attribute node is // template text, we need not generate an extra call to // pushBody and popBody. Maybe we can further optimize // here by getting rid of the temporary variable, but in // reality it looks like javac does this for us. Node.Nodes body = n.getBody(); if (body != null) { boolean templateTextOptimization = false; if (body.size() == 1) { Node bodyElement = body.getNode(0); if (bodyElement instanceof Node.TemplateText) { templateTextOptimization = true; out.printil("String " + varName + " = " + quote(new String( ((Node.TemplateText) bodyElement) .getText())) + ";"); } } // XXX - Another possible optimization would be for // lone EL expressions (no need to pushBody here either). if (!templateTextOptimization) { out.printil("out = _jspx_page_context.pushBody();"); visitBody(n); out.printil("String " + varName + " = " + "((javax.servlet.jsp.tagext.BodyContent)" + "out).getString();"); out.printil("out = _jspx_page_context.popBody();"); } } else { // Empty body must be treated as "" out.printil("String " + varName + " = \"\";"); } return varName; } /** * Similar to generateNamedAttributeValue, but create a JspFragment * instead. * * @param n * The parent node of the named attribute * @param tagHandlerVar * The variable the tag handler is stored in, so the fragment * knows its parent tag. * @return The name of the temporary variable the fragment is stored in. */ public String generateNamedAttributeJspFragment(Node.NamedAttribute n, String tagHandlerVar) throws JasperException { String varName = n.getTemporaryVariableName(); out.printin("javax.servlet.jsp.tagext.JspFragment " + varName + " = "); generateJspFragment(n, tagHandlerVar); out.println(";"); return varName; } } private static void generateLocalVariables(ServletWriter out, Node n) throws JasperException { Node.ChildInfo ci; if (n instanceof Node.CustomTag) { ci = ((Node.CustomTag) n).getChildInfo(); } else if (n instanceof Node.JspBody) { ci = ((Node.JspBody) n).getChildInfo(); } else if (n instanceof Node.NamedAttribute) { ci = ((Node.NamedAttribute) n).getChildInfo(); } else { // Cannot access err since this method is static, but at // least flag an error. throw new JasperException("Unexpected Node Type"); // err.getString( // "jsp.error.internal.unexpected_node_type" ) ); } if (ci.hasUseBean()) { out .printil("HttpSession session = _jspx_page_context.getSession();"); out .printil("ServletContext application = _jspx_page_context.getServletContext();"); } if (ci.hasUseBean() || ci.hasIncludeAction() || ci.hasSetProperty() || ci.hasParamAction()) { out .printil("HttpServletRequest request = (HttpServletRequest)_jspx_page_context.getRequest();"); } if (ci.hasIncludeAction()) { out .printil("HttpServletResponse response = (HttpServletResponse)_jspx_page_context.getResponse();"); } } /** * Common part of postamble, shared by both servlets and tag files. */ private void genCommonPostamble() { // Append any methods that were generated in the buffer. for (int i = 0; i < methodsBuffered.size(); i++) { GenBuffer methodBuffer = methodsBuffered.get(i); methodBuffer.adjustJavaLines(out.getJavaLine() - 1); out.printMultiLn(methodBuffer.toString()); } // Append the helper class if (fragmentHelperClass.isUsed()) { fragmentHelperClass.generatePostamble(); fragmentHelperClass.adjustJavaLines(out.getJavaLine() - 1); out.printMultiLn(fragmentHelperClass.toString()); } // Append char array declarations if (charArrayBuffer != null) { out.printMultiLn(charArrayBuffer.toString()); } // Close the class definition out.popIndent(); out.printil("}"); } /** * Generates the ending part of the static portion of the servlet. */ private void generatePostamble() { out.popIndent(); out.printil("} catch (Throwable t) {"); out.pushIndent(); out.printil("if (!(t instanceof SkipPageException)){"); out.pushIndent(); out.printil("out = _jspx_out;"); out.printil("if (out != null && out.getBufferSize() != 0)"); out.pushIndent(); out.printil("try { out.clearBuffer(); } catch (java.io.IOException e) {}"); out.popIndent(); out .printil("if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);"); out.popIndent(); out.printil("}"); out.popIndent(); out.printil("} finally {"); out.pushIndent(); out .printil("_jspxFactory.releasePageContext(_jspx_page_context);"); out.popIndent(); out.printil("}"); // Close the service method out.popIndent(); out.printil("}"); // Generated methods, helper classes, etc. genCommonPostamble(); } /** * Constructor. */ Generator(ServletWriter out, Compiler compiler) { this.out = out; methodsBuffered = new ArrayList<GenBuffer>(); charArrayBuffer = null; err = compiler.getErrorDispatcher(); ctxt = compiler.getCompilationContext(); fragmentHelperClass = new FragmentHelperClass("Helper"); pageInfo = compiler.getPageInfo(); /* * Temporary hack. If a JSP page uses the "extends" attribute of the * page directive, the _jspInit() method of the generated servlet class * will not be called (it is only called for those generated servlets * that extend HttpJspBase, the default), causing the tag handler pools * not to be initialized and resulting in a NPE. The JSP spec needs to * clarify whether containers can override init() and destroy(). For * now, we just disable tag pooling for pages that use "extends". */ if (pageInfo.getExtends(false) == null) { isPoolingEnabled = ctxt.getOptions().isPoolingEnabled(); } else { isPoolingEnabled = false; } beanInfo = pageInfo.getBeanRepository(); varInfoNames = pageInfo.getVarInfoNames(); breakAtLF = ctxt.getOptions().getMappedFile(); if (isPoolingEnabled) { tagHandlerPoolNames = new Vector<String>(); } } /** * The main entry for Generator. * * @param out * The servlet output writer * @param compiler * The compiler * @param page * The input page */ public static void generate(ServletWriter out, Compiler compiler, Node.Nodes page) throws JasperException { Generator gen = new Generator(out, compiler); if (gen.isPoolingEnabled) { gen.compileTagHandlerPoolList(page); } if (gen.ctxt.isTagFile()) { JasperTagInfo tagInfo = (JasperTagInfo) gen.ctxt.getTagInfo(); gen.generateTagHandlerPreamble(tagInfo, page); if (gen.ctxt.isPrototypeMode()) { return; } gen.generateXmlProlog(page); gen.fragmentHelperClass.generatePreamble(); page.visit(gen.new GenerateVisitor(gen.ctxt.isTagFile(), out, gen.methodsBuffered, gen.fragmentHelperClass)); gen.generateTagHandlerPostamble(tagInfo); } else { gen.generatePreamble(page); gen.generateXmlProlog(page); gen.fragmentHelperClass.generatePreamble(); page.visit(gen.new GenerateVisitor(gen.ctxt.isTagFile(), out, gen.methodsBuffered, gen.fragmentHelperClass)); gen.generatePostamble(); } } /* * Generates tag handler preamble. */ private void generateTagHandlerPreamble(JasperTagInfo tagInfo, Node.Nodes tag) throws JasperException { // Generate package declaration String className = tagInfo.getTagClassName(); int lastIndex = className.lastIndexOf('.'); if (lastIndex != -1) { String pkgName = className.substring(0, lastIndex); genPreamblePackage(pkgName); className = className.substring(lastIndex + 1); } // Generate imports genPreambleImports(); // Generate class declaration out.printin("public final class "); out.println(className); out.printil(" extends javax.servlet.jsp.tagext.SimpleTagSupport"); out.printin(" implements org.apache.jasper.runtime.JspSourceDependent"); if (tagInfo.hasDynamicAttributes()) { out.println(","); out.printin(" javax.servlet.jsp.tagext.DynamicAttributes"); } out.println(" {"); out.println(); out.pushIndent(); /* * Class body begins here */ generateDeclarations(tag); // Static initializations here genPreambleStaticInitializers(); out.printil("private JspContext jspContext;"); // Declare writer used for storing result of fragment/body invocation // if 'varReader' or 'var' attribute is specified out.printil("private java.io.Writer _jspx_sout;"); // Class variable declarations genPreambleClassVariableDeclarations(); generateSetJspContext(tagInfo); // Tag-handler specific declarations generateTagHandlerAttributes(tagInfo); if (tagInfo.hasDynamicAttributes()) generateSetDynamicAttribute(); // Methods here genPreambleMethods(); // Now the doTag() method out.printil("public void doTag() throws JspException, java.io.IOException {"); if (ctxt.isPrototypeMode()) { out.printil("}"); out.popIndent(); out.printil("}"); return; } out.pushIndent(); /* * According to the spec, 'pageContext' must not be made available as an * implicit object in tag files. Declare _jspx_page_context, so we can * share the code generator with JSPs. */ out.printil("PageContext _jspx_page_context = (PageContext)jspContext;"); // Declare implicit objects. out.printil("HttpServletRequest request = " + "(HttpServletRequest) _jspx_page_context.getRequest();"); out.printil("HttpServletResponse response = " + "(HttpServletResponse) _jspx_page_context.getResponse();"); out.printil("HttpSession session = _jspx_page_context.getSession();"); out.printil("ServletContext application = _jspx_page_context.getServletContext();"); out.printil("ServletConfig config = _jspx_page_context.getServletConfig();"); out.printil("JspWriter out = jspContext.getOut();"); out.printil("_jspInit(config);"); // set current JspContext on ELContext out.printil("jspContext.getELContext().putContext(JspContext.class,jspContext);"); generatePageScopedVariables(tagInfo); declareTemporaryScriptingVars(tag); out.println(); out.printil("try {"); out.pushIndent(); } private void generateTagHandlerPostamble(TagInfo tagInfo) { out.popIndent(); // Have to catch Throwable because a classic tag handler // helper method is declared to throw Throwable. out.printil("} catch( Throwable t ) {"); out.pushIndent(); out.printil("if( t instanceof SkipPageException )"); out.printil(" throw (SkipPageException) t;"); out.printil("if( t instanceof java.io.IOException )"); out.printil(" throw (java.io.IOException) t;"); out.printil("if( t instanceof IllegalStateException )"); out.printil(" throw (IllegalStateException) t;"); out.printil("if( t instanceof JspException )"); out.printil(" throw (JspException) t;"); out.printil("throw new JspException(t);"); out.popIndent(); out.printil("} finally {"); out.pushIndent(); // handle restoring VariableMapper TagAttributeInfo[] attrInfos = tagInfo.getAttributes(); for (int i = 0; i < attrInfos.length; i++) { if (attrInfos[i].isDeferredMethod() || attrInfos[i].isDeferredValue()) { out.printin("_el_variablemapper.setVariable("); out.print(quote(attrInfos[i].getName())); out.print(",_el_ve"); out.print(i); out.println(");"); } } // restore nested JspContext on ELContext out.printil("jspContext.getELContext().putContext(JspContext.class,super.getJspContext());"); out.printil("((org.apache.jasper.runtime.JspContextWrapper) jspContext).syncEndTagFile();"); if (isPoolingEnabled && !tagHandlerPoolNames.isEmpty()) { out.printil("_jspDestroy();"); } out.popIndent(); out.printil("}"); // Close the doTag method out.popIndent(); out.printil("}"); // Generated methods, helper classes, etc. genCommonPostamble(); } /** * Generates declarations for tag handler attributes, and defines the getter * and setter methods for each. */ private void generateTagHandlerAttributes(TagInfo tagInfo) { if (tagInfo.hasDynamicAttributes()) { out.printil("private java.util.HashMap _jspx_dynamic_attrs = new java.util.HashMap();"); } // Declare attributes TagAttributeInfo[] attrInfos = tagInfo.getAttributes(); for (int i = 0; i < attrInfos.length; i++) { out.printin("private "); if (attrInfos[i].isFragment()) { out.print("javax.servlet.jsp.tagext.JspFragment "); } else { out.print(JspUtil.toJavaSourceType(attrInfos[i].getTypeName())); out.print(" "); } out.print(attrInfos[i].getName()); out.println(";"); } out.println(); // Define attribute getter and setter methods for (int i = 0; i < attrInfos.length; i++) { // getter method out.printin("public "); if (attrInfos[i].isFragment()) { out.print("javax.servlet.jsp.tagext.JspFragment "); } else { out.print(JspUtil.toJavaSourceType(attrInfos[i] .getTypeName())); out.print(" "); } out.print(toGetterMethod(attrInfos[i].getName())); out.println(" {"); out.pushIndent(); out.printin("return this."); out.print(attrInfos[i].getName()); out.println(";"); out.popIndent(); out.printil("}"); out.println(); // setter method out.printin("public void "); out.print(toSetterMethodName(attrInfos[i].getName())); if (attrInfos[i].isFragment()) { out.print("(javax.servlet.jsp.tagext.JspFragment "); } else { out.print("("); out.print(JspUtil.toJavaSourceType(attrInfos[i] .getTypeName())); out.print(" "); } out.print(attrInfos[i].getName()); out.println(") {"); out.pushIndent(); out.printin("this."); out.print(attrInfos[i].getName()); out.print(" = "); out.print(attrInfos[i].getName()); out.println(";"); if (ctxt.isTagFile()) { // Tag files should also set jspContext attributes out.printin("jspContext.setAttribute(\""); out.print(attrInfos[i].getName()); out.print("\", "); out.print(attrInfos[i].getName()); out.println(");"); } out.popIndent(); out.printil("}"); out.println(); } } /* * Generate setter for JspContext so we can create a wrapper and store both * the original and the wrapper. We need the wrapper to mask the page * context from the tag file and simulate a fresh page context. We need the * original to do things like sync AT_BEGIN and AT_END scripting variables. */ private void generateSetJspContext(TagInfo tagInfo) { boolean nestedSeen = false; boolean atBeginSeen = false; boolean atEndSeen = false; // Determine if there are any aliases boolean aliasSeen = false; TagVariableInfo[] tagVars = tagInfo.getTagVariableInfos(); for (int i = 0; i < tagVars.length; i++) { if (tagVars[i].getNameFromAttribute() != null && tagVars[i].getNameGiven() != null) { aliasSeen = true; break; } } if (aliasSeen) { out .printil("public void setJspContext(JspContext ctx, java.util.Map aliasMap) {"); } else { out.printil("public void setJspContext(JspContext ctx) {"); } out.pushIndent(); out.printil("super.setJspContext(ctx);"); out.printil("java.util.ArrayList _jspx_nested = null;"); out.printil("java.util.ArrayList _jspx_at_begin = null;"); out.printil("java.util.ArrayList _jspx_at_end = null;"); for (int i = 0; i < tagVars.length; i++) { switch (tagVars[i].getScope()) { case VariableInfo.NESTED: if (!nestedSeen) { out.printil("_jspx_nested = new java.util.ArrayList();"); nestedSeen = true; } out.printin("_jspx_nested.add("); break; case VariableInfo.AT_BEGIN: if (!atBeginSeen) { out.printil("_jspx_at_begin = new java.util.ArrayList();"); atBeginSeen = true; } out.printin("_jspx_at_begin.add("); break; case VariableInfo.AT_END: if (!atEndSeen) { out.printil("_jspx_at_end = new java.util.ArrayList();"); atEndSeen = true; } out.printin("_jspx_at_end.add("); break; } // switch out.print(quote(tagVars[i].getNameGiven())); out.println(");"); } if (aliasSeen) { out .printil("this.jspContext = new org.apache.jasper.runtime.JspContextWrapper(ctx, _jspx_nested, _jspx_at_begin, _jspx_at_end, aliasMap);"); } else { out .printil("this.jspContext = new org.apache.jasper.runtime.JspContextWrapper(ctx, _jspx_nested, _jspx_at_begin, _jspx_at_end, null);"); } out.popIndent(); out.printil("}"); out.println(); out.printil("public JspContext getJspContext() {"); out.pushIndent(); out.printil("return this.jspContext;"); out.popIndent(); out.printil("}"); } /* * Generates implementation of * javax.servlet.jsp.tagext.DynamicAttributes.setDynamicAttribute() method, * which saves each dynamic attribute that is passed in so that a scoped * variable can later be created for it. */ public void generateSetDynamicAttribute() { out .printil("public void setDynamicAttribute(String uri, String localName, Object value) throws JspException {"); out.pushIndent(); /* * According to the spec, only dynamic attributes with no uri are to be * present in the Map; all other dynamic attributes are ignored. */ out.printil("if (uri == null)"); out.pushIndent(); out.printil("_jspx_dynamic_attrs.put(localName, value);"); out.popIndent(); out.popIndent(); out.printil("}"); } /* * Creates a page-scoped variable for each declared tag attribute. Also, if * the tag accepts dynamic attributes, a page-scoped variable is made * available for each dynamic attribute that was passed in. */ private void generatePageScopedVariables(JasperTagInfo tagInfo) { // "normal" attributes TagAttributeInfo[] attrInfos = tagInfo.getAttributes(); boolean variableMapperVar = false; for (int i = 0; i < attrInfos.length; i++) { String attrName = attrInfos[i].getName(); // handle assigning deferred vars to VariableMapper, storing // previous values under '_el_ve[i]' for later re-assignment if (attrInfos[i].isDeferredValue() || attrInfos[i].isDeferredMethod()) { // we need to scope the modified VariableMapper for consistency and performance if (!variableMapperVar) { out.printil("javax.el.VariableMapper _el_variablemapper = jspContext.getELContext().getVariableMapper();"); variableMapperVar = true; } out.printin("javax.el.ValueExpression _el_ve"); out.print(i); out.print(" = _el_variablemapper.setVariable("); out.print(quote(attrName)); out.print(','); if (attrInfos[i].isDeferredMethod()) { out.print(VAR_EXPRESSIONFACTORY); out.print(".createValueExpression("); out.print(toGetterMethod(attrName)); out.print(",javax.el.MethodExpression.class)"); } else { out.print(toGetterMethod(attrName)); } out.println(");"); } else { out.printil("if( " + toGetterMethod(attrName) + " != null ) "); out.pushIndent(); out.printin("_jspx_page_context.setAttribute("); out.print(quote(attrName)); out.print(", "); out.print(toGetterMethod(attrName)); out.println(");"); out.popIndent(); } } // Expose the Map containing dynamic attributes as a page-scoped var if (tagInfo.hasDynamicAttributes()) { out.printin("_jspx_page_context.setAttribute(\""); out.print(tagInfo.getDynamicAttributesMapName()); out.print("\", _jspx_dynamic_attrs);"); } } /* * Generates the getter method for the given attribute name. */ private String toGetterMethod(String attrName) { char[] attrChars = attrName.toCharArray(); attrChars[0] = Character.toUpperCase(attrChars[0]); return "get" + new String(attrChars) + "()"; } /* * Generates the setter method name for the given attribute name. */ private String toSetterMethodName(String attrName) { char[] attrChars = attrName.toCharArray(); attrChars[0] = Character.toUpperCase(attrChars[0]); return "set" + new String(attrChars); } /** * Class storing the result of introspecting a custom tag handler. */ private static class TagHandlerInfo { private Hashtable<String, Method> methodMaps; private Hashtable<String, Class<?>> propertyEditorMaps; private Class<?> tagHandlerClass; /** * Constructor. * * @param n * The custom tag whose tag handler class is to be * introspected * @param tagHandlerClass * Tag handler class * @param err * Error dispatcher */ TagHandlerInfo(Node n, Class<?> tagHandlerClass, ErrorDispatcher err) throws JasperException { this.tagHandlerClass = tagHandlerClass; this.methodMaps = new Hashtable<String, Method>(); this.propertyEditorMaps = new Hashtable<String, Class<?>>(); try { BeanInfo tagClassInfo = Introspector .getBeanInfo(tagHandlerClass); PropertyDescriptor[] pd = tagClassInfo.getPropertyDescriptors(); for (int i = 0; i < pd.length; i++) { /* * FIXME: should probably be checking for things like * pageContext, bodyContent, and parent here -akv */ if (pd[i].getWriteMethod() != null) { methodMaps.put(pd[i].getName(), pd[i].getWriteMethod()); } if (pd[i].getPropertyEditorClass() != null) propertyEditorMaps.put(pd[i].getName(), pd[i] .getPropertyEditorClass()); } } catch (IntrospectionException ie) { err.jspError(n, "jsp.error.introspect.taghandler", tagHandlerClass.getName(), ie); } } /** * XXX */ public Method getSetterMethod(String attrName) { return methodMaps.get(attrName); } /** * XXX */ public Class<?> getPropertyEditorClass(String attrName) { return propertyEditorMaps.get(attrName); } /** * XXX */ public Class<?> getTagHandlerClass() { return tagHandlerClass; } } /** * A class for generating codes to a buffer. Included here are some support * for tracking source to Java lines mapping. */ private static class GenBuffer { /* * For a CustomTag, the codes that are generated at the beginning of the * tag may not be in the same buffer as those for the body of the tag. * Two fields are used here to keep this straight. For codes that do not * corresponds to any JSP lines, they should be null. */ private Node node; private Node.Nodes body; private java.io.CharArrayWriter charWriter; protected ServletWriter out; GenBuffer() { this(null, null); } GenBuffer(Node n, Node.Nodes b) { node = n; body = b; if (body != null) { body.setGeneratedInBuffer(true); } charWriter = new java.io.CharArrayWriter(); out = new ServletWriter(new java.io.PrintWriter(charWriter)); } public ServletWriter getOut() { return out; } @Override public String toString() { return charWriter.toString(); } /** * Adjust the Java Lines. This is necessary because the Java lines * stored with the nodes are relative the beginning of this buffer and * need to be adjusted when this buffer is inserted into the source. */ public void adjustJavaLines(final int offset) { if (node != null) { adjustJavaLine(node, offset); } if (body != null) { try { body.visit(new Node.Visitor() { @Override public void doVisit(Node n) { adjustJavaLine(n, offset); } @Override public void visit(Node.CustomTag n) throws JasperException { Node.Nodes b = n.getBody(); if (b != null && !b.isGeneratedInBuffer()) { // Don't adjust lines for the nested tags that // are also generated in buffers, because the // adjustments will be done elsewhere. b.visit(this); } } }); } catch (JasperException ex) { // Ignore } } } private static void adjustJavaLine(Node n, int offset) { if (n.getBeginJavaLine() > 0) { n.setBeginJavaLine(n.getBeginJavaLine() + offset); n.setEndJavaLine(n.getEndJavaLine() + offset); } } } /** * Keeps track of the generated Fragment Helper Class */ private static class FragmentHelperClass { private static class Fragment { private GenBuffer genBuffer; private int id; public Fragment(int id, Node node) { this.id = id; genBuffer = new GenBuffer(null, node.getBody()); } public GenBuffer getGenBuffer() { return this.genBuffer; } public int getId() { return this.id; } } // True if the helper class should be generated. private boolean used = false; private ArrayList<Fragment> fragments = new ArrayList<Fragment>(); private String className; // Buffer for entire helper class private GenBuffer classBuffer = new GenBuffer(); public FragmentHelperClass(String className) { this.className = className; } public String getClassName() { return this.className; } public boolean isUsed() { return this.used; } public void generatePreamble() { ServletWriter out = this.classBuffer.getOut(); out.println(); out.pushIndent(); // Note: cannot be static, as we need to reference things like // _jspx_meth_* out.printil("private class " + className); out.printil(" extends " + "org.apache.jasper.runtime.JspFragmentHelper"); out.printil("{"); out.pushIndent(); out .printil("private javax.servlet.jsp.tagext.JspTag _jspx_parent;"); out.printil("private int[] _jspx_push_body_count;"); out.println(); out.printil("public " + className + "( int discriminator, JspContext jspContext, " + "javax.servlet.jsp.tagext.JspTag _jspx_parent, " + "int[] _jspx_push_body_count ) {"); out.pushIndent(); out.printil("super( discriminator, jspContext, _jspx_parent );"); out.printil("this._jspx_parent = _jspx_parent;"); out.printil("this._jspx_push_body_count = _jspx_push_body_count;"); out.popIndent(); out.printil("}"); } public Fragment openFragment(Node parent, int methodNesting) throws JasperException { Fragment result = new Fragment(fragments.size(), parent); fragments.add(result); this.used = true; parent.setInnerClassName(className); ServletWriter out = result.getGenBuffer().getOut(); out.pushIndent(); out.pushIndent(); // XXX - Returns boolean because if a tag is invoked from // within this fragment, the Generator sometimes might // generate code like "return true". This is ignored for now, // meaning only the fragment is skipped. The JSR-152 // expert group is currently discussing what to do in this case. // See comment in closeFragment() if (methodNesting > 0) { out.printin("public boolean invoke"); } else { out.printin("public void invoke"); } out.println(result.getId() + "( " + "JspWriter out ) "); out.pushIndent(); // Note: Throwable required because methods like _jspx_meth_* // throw Throwable. out.printil("throws Throwable"); out.popIndent(); out.printil("{"); out.pushIndent(); generateLocalVariables(out, parent); return result; } public void closeFragment(Fragment fragment, int methodNesting) { ServletWriter out = fragment.getGenBuffer().getOut(); // XXX - See comment in openFragment() if (methodNesting > 0) { out.printil("return false;"); } else { out.printil("return;"); } out.popIndent(); out.printil("}"); } public void generatePostamble() { ServletWriter out = this.classBuffer.getOut(); // Generate all fragment methods: for (int i = 0; i < fragments.size(); i++) { Fragment fragment = fragments.get(i); fragment.getGenBuffer().adjustJavaLines(out.getJavaLine() - 1); out.printMultiLn(fragment.getGenBuffer().toString()); } // Generate postamble: out.printil("public void invoke( java.io.Writer writer )"); out.pushIndent(); out.printil("throws JspException"); out.popIndent(); out.printil("{"); out.pushIndent(); out.printil("JspWriter out = null;"); out.printil("if( writer != null ) {"); out.pushIndent(); out.printil("out = this.jspContext.pushBody(writer);"); out.popIndent(); out.printil("} else {"); out.pushIndent(); out.printil("out = this.jspContext.getOut();"); out.popIndent(); out.printil("}"); out.printil("try {"); out.pushIndent(); out.printil("this.jspContext.getELContext().putContext(JspContext.class,this.jspContext);"); out.printil("switch( this.discriminator ) {"); out.pushIndent(); for (int i = 0; i < fragments.size(); i++) { out.printil("case " + i + ":"); out.pushIndent(); out.printil("invoke" + i + "( out );"); out.printil("break;"); out.popIndent(); } out.popIndent(); out.printil("}"); // switch out.popIndent(); out.printil("}"); // try out.printil("catch( Throwable e ) {"); out.pushIndent(); out.printil("if (e instanceof SkipPageException)"); out.printil(" throw (SkipPageException) e;"); out.printil("throw new JspException( e );"); out.popIndent(); out.printil("}"); // catch out.printil("finally {"); out.pushIndent(); out.printil("if( writer != null ) {"); out.pushIndent(); out.printil("this.jspContext.popBody();"); out.popIndent(); out.printil("}"); out.popIndent(); out.printil("}"); // finally out.popIndent(); out.printil("}"); // invoke method out.popIndent(); out.printil("}"); // helper class out.popIndent(); } @Override public String toString() { return classBuffer.toString(); } public void adjustJavaLines(int offset) { for (int i = 0; i < fragments.size(); i++) { Fragment fragment = fragments.get(i); fragment.getGenBuffer().adjustJavaLines(offset); } } } }
Fix second part of Comment 8 in https://issues.apache.org/bugzilla/show_bug.cgi?id=47413#c8 Coerce result of composite EL expression (${a}${b}) from String to the expected type. git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@893001 13f79535-47bb-0310-9956-ffa450edef68
java/org/apache/jasper/compiler/Generator.java
Fix second part of Comment 8 in https://issues.apache.org/bugzilla/show_bug.cgi?id=47413#c8 Coerce result of composite EL expression (${a}${b}) from String to the expected type.
<ide><path>ava/org/apache/jasper/compiler/Generator.java <ide> output.append(" + "); <ide> } <ide> output.append(quote(tx.substring(mark, i))); <add> } <add> if (expectedType != type && !expectedType.isAssignableFrom(type)) { <add> // Composite expression was evaluated to String <add> // We must coerce it to the expected type. <add> String className = JspUtil.getCanonicalName(expectedType); <add> String methodName = null; <add> if (expectedType.isPrimitive()) { <add> if (expectedType == Boolean.TYPE) { <add> className = "Boolean"; <add> methodName = ".booleanValue()"; <add> } <add> else if (expectedType == Character.TYPE) { <add> className = "Character"; <add> methodName = ".charValue()"; <add> } <add> else if (expectedType == Byte.TYPE) { <add> className = "Byte"; <add> methodName = ".byteValue()"; <add> } <add> else if (expectedType == Short.TYPE) { <add> className = "Short"; <add> methodName = ".shortValue()"; <add> } <add> else if (expectedType == Integer.TYPE) { <add> className = "Integer"; <add> methodName = ".intValue()"; <add> } <add> else if (expectedType == Long.TYPE) { <add> className = "Long"; <add> methodName = ".longValue()"; <add> } <add> else if (expectedType == Float.TYPE) { <add> className = "Float"; <add> methodName = ".floatValue()"; <add> } <add> else if (expectedType == Double.TYPE) { <add> className = "Double"; <add> methodName = ".doubleValue()"; <add> } <add> } <add> output.insert(0, "((" <add> + className <add> + ")org.apache.el.lang.ELSupport.coerceToType("); <add> output.append(",").append(className).append(".class))"); <add> if (methodName != null) { <add> output.insert(0, '('); <add> output.append(methodName).append(')'); <add> } <ide> } <ide> return output.toString(); <ide> }
JavaScript
mit
fed94f1ba3327f5645ebd2e733c394baf342e3a8
0
lepovica/WarCluster-AI
function FuzzyTriangleSet(leftOffset, peakPoint, rightOffset) { return { _peakPoint : peakPoint, _leftOffset : leftOffset, _rightOffset : rightOffset, calculateDOM : function(value) { if( ((rightOffset === 0.0) && (peakPoint === value)) || ((leftOffset === 0.0) && (peakPoint === value)) ) { return 1.0; } if( (value <= peakPoint) && (value >= (peakPoint - leftOffset)) ){ var grad = 1.0 / leftOffset; return grad * (value - (peakPoint - leftOffset)); }else { if( (value > peakPoint) && (value < (peakPoint + rightOffset))) { var grad = 1.0 / -rightOffset; return grad * (value - peakPoint) + 1.0; }else { return 0.0; } } } } }
AI/FuzztTriangleSet.js
function TriangleFuzzySet(leftOffset, peakPoint, rightOffset) { return { _peakPoint : peakPoint, _leftOffset : leftOffset, _rightOffset : rightOffset, calculateDOM : function(value) { if( ((rightOffset === 0.0) && (peakPoint === value)) || ((leftOffset === 0.0) && (peakPoint === value)) ) { return 1.0; } if( (value <= peakPoint) && (value >= (peakPoint - leftOffset)) ){ var grad = 1.0 / leftOffset; return grad * (value - (peakPoint - leftOffset)); }else { if( (value > peakPoint) && (value < (peakPoint + rightOffset))) { var grad = 1.0 / -rightOffset; return grad * (value - peakPoint) + 1.0; }else { return 0.0; } } } } }
change name of function in triangle set
AI/FuzztTriangleSet.js
change name of function in triangle set
<ide><path>I/FuzztTriangleSet.js <del>function TriangleFuzzySet(leftOffset, peakPoint, rightOffset) { <add>function FuzzyTriangleSet(leftOffset, peakPoint, rightOffset) { <ide> return { <ide> _peakPoint : peakPoint, <ide> _leftOffset : leftOffset,
Java
lgpl-2.1
072a83ca27a153e493b40c42a941556bbfc89e70
0
ACS-Community/ACS,csrg-utfsm/acscb,csrg-utfsm/acscb,ACS-Community/ACS,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,ACS-Community/ACS,csrg-utfsm/acscb,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,csrg-utfsm/acscb,csrg-utfsm/acscb,ACS-Community/ACS,jbarriosc/ACSUFRO,ACS-Community/ACS,jbarriosc/ACSUFRO,csrg-utfsm/acscb,csrg-utfsm/acscb,ACS-Community/ACS,ACS-Community/ACS,jbarriosc/ACSUFRO,csrg-utfsm/acscb,ACS-Community/ACS
/* * Created on Aug 29, 2003 by mschilli */ package alma.acs.commandcenter.meta; import java.util.logging.Level; import java.util.logging.Logger; import org.omg.PortableServer.POA; import alma.acs.component.client.ComponentClient; import alma.acs.component.client.AdvancedComponentClient; import alma.acs.container.ContainerServices; import alma.acs.container.corba.AcsCorba; import alma.acs.util.AcsLocations; /** * Helps to bring an application into the Acs environment. * <p> * Usage: When interested in component retrieval: * <ol> * <li>fs = new Firestarter(); * <li>fs.prepareContainerServices(null, null); * <li>fs.giveContainerServices() * </ol> * * When interested in Maci Administration: * <ol> * <li>fs = new Firestarter(); * <li>fs.prepareSupervisorFactory(null) * <li>fs.giveSupervisorFactory() * </ol> * * Eventually, in both cases, you should always call: * <ul> * <li>fs.shutdown(); * </ul> * * </p> * * * @author mschilli */ public class Firestarter { protected String clientName = null; protected AcsCorba acsCorba = null; protected POA rootPoa = null; protected ComponentClient componentClient = null; protected MaciSupervisorFactory maciSupervisorFactory = null; protected Logger firestarterLog = null; protected Logger acscorbaLog = null; protected Integer orbPort = null; protected Integer orbPortSearchRetry = null; // ========================================================== // Firestarter // ========================================================== /** * Creates a Firestarter for a client with the specified name (like "AcsCommandCenter" * or "OMC"). * * @param clientName will be used as namespace prefix for the default-loggers * * @see * @since ACS 5.0 */ public Firestarter (String clientName) { this(clientName, null); } /** * Creates a Firestarter for a client with the specified name (like "AcsCommandCenter" * or "OMC") and the specified Logger. * * @param clientName will be used as namespace prefix for the default-loggers * @param firestarterLog will be used to log messages from this class * * @see * @since ACS 5.0 */ public Firestarter (String clientName, Logger firestarterLog) { if (clientName == null) { throw new NullPointerException("clientName should not be null"); } if (firestarterLog == null) { firestarterLog = Logger.getLogger(clientName + ".Firestarter"); } this.clientName = clientName; this.firestarterLog = firestarterLog; } /** * Should be invoked to clean up the Firestarter. */ public void shutdown () { try { if (componentClient != null) { componentClient.tearDown(); componentClient = null; } } catch (Throwable t) { firestarterLog.log(Level.INFO, "failed to stop componentclient", t); } try { if (maciSupervisorFactory != null) { maciSupervisorFactory.stop(); maciSupervisorFactory = null; } } catch (Throwable t) { firestarterLog.log(Level.INFO, "failed to stop macisupervisor(s)", t); } try { if (acsCorba != null) { new Thread() { public void run () { acsCorba.shutdownORB(false); } }.start(); acsCorba.blockOnORB(); acsCorba = null; rootPoa = null; } } catch (Throwable t) { firestarterLog.log(Level.INFO, "failed to stop orb", t); } } // ========================================================== // ContainerServices // ========================================================== /** * This class is <i>fail-fast</i> in that it tries to set up the remote connectivity * instantly on a call to this method. If this first call goes well, subsequent calls * will succeed (aside from other general errors). * <p> * After the first *successful* execution, it will ignore subsequent invokations. This * means, this method can be called as often as wanted.</p> * <p> * If you don't specify the <code>managerLoc</code>, this will delegate to * {@link alma.acs.util.AcsLocations} to find the manager. </p> * * @param compclientLog use <code>null</code> for default * @param managerLoc use <code>null</code> for default * @throws Exception if construction of {@link Logger} or {@link ComponentClient} fails */ public void prepareContainerServices (Logger compclientLog, String managerLoc) throws Exception { if (componentClient != null) { return; // already prepared } if (compclientLog == null) { compclientLog = Logger.getLogger(clientName + ".ComponentClient"); } if (managerLoc == null) { managerLoc = AcsLocations.figureOutManagerLocation(); } /* the following call may fail with exception. if it succeeds, * we can continue working with acsCorba and rootPoa */ prepareAcsCorba(); this.componentClient = createComponentClient(compclientLog, managerLoc); } /** * Hook for subclasses. This default implementation creates an * <code>AdvancedComponentClient</code>. * * @throws Exception if creation of component client fails */ protected ComponentClient createComponentClient (Logger compclientLog, String managerLoc) throws Exception { AdvancedComponentClient ret; ret = new AdvancedComponentClient(compclientLog, managerLoc, clientName+".ComponentClient", acsCorba); return ret; } /** * Returns the {@link ContainerServices}. Note: {@link #prepareContainerServices()} * must have been executed successfully for this method to work * * @throws IllegalStateException if {@link #prepareContainerServices()} was not yet * executed successfully * @return the {@link ContainerServices} */ public ContainerServices giveContainerServices () { if (componentClient == null) { throw new IllegalStateException("container services not prepared"); } return componentClient.getContainerServices(); } // ========================================================== // MaciSupervisors // ========================================================== /** * This class is <i>fail-fast</i> in that it tries to set up the remote connectivity * instantly on a call to this method. If this first call goes well, subsequent calls * will succeed (aside from other general errors). * * @param factoryLog use <code>null</code> for default * @throws Exception if construction of {@link MaciSupervisor} fails */ public void prepareSupervisorFactory (Logger factoryLog) throws Exception { if (maciSupervisorFactory != null) { return; // already prepared } if (factoryLog == null) { factoryLog = Logger.getLogger(clientName + ".Factory"); } /* the following call may fail with exception. if it succeeds, * we can continue working with acsCorba and acsCorba.getORB() */ prepareAcsCorba(); maciSupervisorFactory = new MaciSupervisorFactory(clientName, factoryLog, acsCorba.getORB()); } /** * Returns a MaciSupervisorFactory. Note: {@link #prepareSupervisorFactory()} must have been executed * successfully for this method to work * * @throws IllegalStateException if {@link #prepareSupervisorFactory()} was not yet executed * successfully * @return a MaciSupervisor */ public MaciSupervisorFactory giveSupervisorFactory () { if (maciSupervisorFactory == null) { throw new IllegalStateException("supervisor factory not prepared"); } return maciSupervisorFactory; } // ========================================================== // AcsCorba // ========================================================== /** * Set AcsCorba's logger and orb-port strategy. * <p> * For a description of the parameters <code>orbPort</code> and * <code>orbPortSearchRetry</code>, see * {@link AcsCorba#setPortOptions(Integer, Integer)}. * </p> * * @param acscorbaLog use <code>null</code> for default * @param orbPort use <code>null</code> for default * @param orbPortSearchRetry use <code>null</code> for default */ public void setAcsCorbaOptions (Logger acscorbaLog, Integer orbPort, Integer orbPortSearchRetry) { this.acscorbaLog = acscorbaLog; this.orbPort = orbPort; this.orbPortSearchRetry = orbPortSearchRetry; } /** * This class is <i>fail-fast</i> in that it tries to create an {@link AcsCorba} * instantly on a call to this method. If this first call goes well, subsequent calls * will succeed (aside from other general errors). * * @throws Exception if construction of {@link AcsCorba} fails */ protected void prepareAcsCorba () throws Exception { if (acsCorba != null && acsCorba.isInitialized()) { return; // already prepared } if (acscorbaLog == null) { acscorbaLog = Logger.getLogger(clientName + ".AcsCorba"); } acsCorba = new AcsCorba(acscorbaLog); acsCorba.setPortOptions(orbPort, orbPortSearchRetry); boolean isAdmin = true; acsCorba.initCorbaForClient(isAdmin); } }
LGPL/CommonSoftware/acscommandcenter/src/alma/acs/commandcenter/meta/Firestarter.java
/* * Created on Aug 29, 2003 by mschilli */ package alma.acs.commandcenter.meta; import java.util.logging.Level; import java.util.logging.Logger; import org.omg.PortableServer.POA; import alma.acs.component.client.AdvancedComponentClient; import alma.acs.container.ContainerServices; import alma.acs.container.corba.AcsCorba; import alma.acs.util.AcsLocations; /** * Helps to bring an application into the Acs environment. * <p> * Usage: When interested in component retrieval: * <ol> * <li>fs = new Firestarter(); * <li>fs.prepareContainerServices(null, null); * <li>fs.giveContainerServices() * </ol> * * When interested in Maci Administration: * <ol> * <li>fs = new Firestarter(); * <li>fs.prepareSupervisorFactory(null) * <li>fs.giveSupervisorFactory() * </ol> * * Eventually, in both cases, you should always call: * <ul> * <li>fs.shutdown(); * </ul> * * </p> * * * @author mschilli */ public class Firestarter { protected String clientName = null; protected AcsCorba acsCorba = null; protected POA rootPoa = null; protected AdvancedComponentClient componentClient = null; protected MaciSupervisorFactory maciSupervisorFactory = null; protected Logger firestarterLog = null; protected Logger acscorbaLog = null; protected Integer orbPort = null; protected Integer orbPortSearchRetry = null; // ========================================================== // Firestarter // ========================================================== /** * Creates a Firestarter for a client with the specified name (like "AcsCommandCenter" * or "OMC"). * * @param clientName will be used as namespace prefix for the default-loggers * * @see * @since ACS 5.0 */ public Firestarter (String clientName) { this(clientName, null); } /** * Creates a Firestarter for a client with the specified name (like "AcsCommandCenter" * or "OMC") and the specified Logger. * * @param clientName will be used as namespace prefix for the default-loggers * @param firestarterLog will be used to log messages from this class * * @see * @since ACS 5.0 */ public Firestarter (String clientName, Logger firestarterLog) { if (clientName == null) { throw new NullPointerException("clientName should not be null"); } if (firestarterLog == null) { firestarterLog = Logger.getLogger(clientName + ".Firestarter"); } this.clientName = clientName; this.firestarterLog = firestarterLog; } /** * Should be invoked to clean up the Firestarter. */ public void shutdown () { try { if (componentClient != null) { componentClient.tearDown(); componentClient = null; } } catch (Throwable t) { firestarterLog.log(Level.INFO, "failed to stop componentclient", t); } try { if (maciSupervisorFactory != null) { maciSupervisorFactory.stop(); maciSupervisorFactory = null; } } catch (Throwable t) { firestarterLog.log(Level.INFO, "failed to stop macisupervisor(s)", t); } try { if (acsCorba != null) { new Thread() { public void run () { acsCorba.shutdownORB(false); } }.start(); acsCorba.blockOnORB(); acsCorba = null; rootPoa = null; } } catch (Throwable t) { firestarterLog.log(Level.INFO, "failed to stop orb", t); } } // ========================================================== // ContainerServices // ========================================================== /** * This class is <i>fail-fast</i> in that it tries to set up the remote connectivity * instantly on a call to this method. If this first call goes well, subsequent calls * will succeed (aside from other general errors). * <p> * After the first *successful* execution, it will ignore subsequent invokations. This * means, this method can be called as often as wanted.</p> * <p> * If you don't specify the <code>managerLoc</code>, this will delegate to * {@link alma.acs.util.AcsLocations} to find the manager. </p> * * @param compclientLog use <code>null</code> for default * @param managerLoc use <code>null</code> for default * @throws Exception if construction of {@link Logger} or {@link ComponentClient} fails */ public void prepareContainerServices (Logger compclientLog, String managerLoc) throws Exception { if (componentClient != null) { return; // already prepared } if (compclientLog == null) { compclientLog = Logger.getLogger(clientName + ".ComponentClient"); } if (managerLoc == null) { managerLoc = AcsLocations.figureOutManagerLocation(); } /* the following call may fail with exception. if it succeeds, * we can continue working with acsCorba and rootPoa */ prepareAcsCorba(); this.componentClient = createComponentClient(compclientLog, managerLoc); } /** * Hook for subclasses * * @throws Exception if creation of component client fails */ protected AdvancedComponentClient createComponentClient (Logger compclientLog, String managerLoc) throws Exception { AdvancedComponentClient ret; ret = new AdvancedComponentClient(compclientLog, managerLoc, clientName+".ComponentClient", acsCorba); return ret; } /** * Returns the {@link ContainerServices}. Note: {@link #prepareContainerServices()} * must have been executed successfully for this method to work * * @throws IllegalStateException if {@link #prepareContainerServices()} was not yet * executed successfully * @return the {@link ContainerServices} */ public ContainerServices giveContainerServices () { if (componentClient == null) { throw new IllegalStateException("container services not prepared"); } return componentClient.getContainerServices(); } // ========================================================== // MaciSupervisors // ========================================================== /** * This class is <i>fail-fast</i> in that it tries to set up the remote connectivity * instantly on a call to this method. If this first call goes well, subsequent calls * will succeed (aside from other general errors). * * @param factoryLog use <code>null</code> for default * @throws Exception if construction of {@link MaciSupervisor} fails */ public void prepareSupervisorFactory (Logger factoryLog) throws Exception { if (maciSupervisorFactory != null) { return; // already prepared } if (factoryLog == null) { factoryLog = Logger.getLogger(clientName + ".Factory"); } /* the following call may fail with exception. if it succeeds, * we can continue working with acsCorba and acsCorba.getORB() */ prepareAcsCorba(); maciSupervisorFactory = new MaciSupervisorFactory(clientName, factoryLog, acsCorba.getORB()); } /** * Returns a MaciSupervisorFactory. Note: {@link #prepareSupervisorFactory()} must have been executed * successfully for this method to work * * @throws IllegalStateException if {@link #prepareSupervisorFactory()} was not yet executed * successfully * @return a MaciSupervisor */ public MaciSupervisorFactory giveSupervisorFactory () { if (maciSupervisorFactory == null) { throw new IllegalStateException("supervisor factory not prepared"); } return maciSupervisorFactory; } // ========================================================== // AcsCorba // ========================================================== /** * Set AcsCorba's logger and orb-port strategy. * <p> * For a description of the parameters <code>orbPort</code> and * <code>orbPortSearchRetry</code>, see * {@link AcsCorba#setPortOptions(Integer, Integer)}. * </p> * * @param acscorbaLog use <code>null</code> for default * @param orbPort use <code>null</code> for default * @param orbPortSearchRetry use <code>null</code> for default */ public void setAcsCorbaOptions (Logger acscorbaLog, Integer orbPort, Integer orbPortSearchRetry) { this.acscorbaLog = acscorbaLog; this.orbPort = orbPort; this.orbPortSearchRetry = orbPortSearchRetry; } /** * This class is <i>fail-fast</i> in that it tries to create an {@link AcsCorba} * instantly on a call to this method. If this first call goes well, subsequent calls * will succeed (aside from other general errors). * * @throws Exception if construction of {@link AcsCorba} fails */ protected void prepareAcsCorba () throws Exception { if (acsCorba != null && acsCorba.isInitialized()) { return; // already prepared } if (acscorbaLog == null) { acscorbaLog = Logger.getLogger(clientName + ".AcsCorba"); } acsCorba = new AcsCorba(acscorbaLog); acsCorba.setPortOptions(orbPort, orbPortSearchRetry); boolean isAdmin = true; acsCorba.initCorbaForClient(isAdmin); } }
reverted method signature of createComponentClient(), so it is backward-compatible with Acs 5.0.3 git-svn-id: afcf11d89342f630bd950d18a70234a9e277d909@56308 523d945c-050c-4681-91ec-863ad3bb968a
LGPL/CommonSoftware/acscommandcenter/src/alma/acs/commandcenter/meta/Firestarter.java
reverted method signature of createComponentClient(), so it is backward-compatible with Acs 5.0.3
<ide><path>GPL/CommonSoftware/acscommandcenter/src/alma/acs/commandcenter/meta/Firestarter.java <ide> <ide> import org.omg.PortableServer.POA; <ide> <add>import alma.acs.component.client.ComponentClient; <ide> import alma.acs.component.client.AdvancedComponentClient; <ide> import alma.acs.container.ContainerServices; <ide> import alma.acs.container.corba.AcsCorba; <ide> <ide> protected AcsCorba acsCorba = null; <ide> protected POA rootPoa = null; <del> protected AdvancedComponentClient componentClient = null; <add> protected ComponentClient componentClient = null; <ide> protected MaciSupervisorFactory maciSupervisorFactory = null; <ide> <ide> protected Logger firestarterLog = null; <ide> <ide> <ide> /** <del> * Hook for subclasses <add> * Hook for subclasses. This default implementation creates an <add> * <code>AdvancedComponentClient</code>. <ide> * <ide> * @throws Exception if creation of component client fails <ide> */ <del> protected AdvancedComponentClient createComponentClient (Logger compclientLog, String managerLoc) throws Exception { <add> protected ComponentClient createComponentClient (Logger compclientLog, String managerLoc) throws Exception { <ide> AdvancedComponentClient ret; <ide> ret = new AdvancedComponentClient(compclientLog, managerLoc, clientName+".ComponentClient", acsCorba); <ide> return ret;
Java
apache-2.0
f7ba27764e8907043040d18c81c41ee057234006
0
chaudharyp/Sunshine
package com.example.android.sunshine.app; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.format.Time; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; 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.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; /** * A placeholder fragment containing a simple view. */ public class ForecastFragment extends Fragment { private ArrayAdapter<String> mForecastAdapter; public ForecastFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); String[] weatherData = { "Mon 6/23 - Sunny - 31/17", "Tue 6/24 - Foggy - 21/8", "Wed 6/25 - Cloudy - 22/17", "Thurs 6/26 - Rainy - 18/11", "Fri 6/27 - Foggy - 21/10", "Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18", "Sun 6/29 - Sunny - 20/7" }; ArrayList<String> weatherList = new ArrayList<>(Arrays.asList(weatherData)); mForecastAdapter = new ArrayAdapter<>(getContext(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weatherList); final ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast); listView.setAdapter(mForecastAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String selectedItemText = parent.getItemAtPosition(position) .toString(); Intent intent = new Intent(getContext(), DetailActivity.class); intent.putExtra(Intent.EXTRA_TEXT, selectedItemText); startActivity(intent); } }); return rootView; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.forecastfragment, menu); } @Override public boolean onOptionsItemSelected(MenuItem menuItem) { int itemId = menuItem.getItemId(); switch (itemId){ case R.id.action_refresh: new FetchWeatherTask().execute("94043"); return true; default: return super.onOptionsItemSelected(menuItem); } } public class FetchWeatherTask extends AsyncTask<String, Void, String[]> { private final String LOG_TAG = FetchWeatherTask.class.getSimpleName(); @Override protected String[] doInBackground(String... params) { if (params == null) { return null; } // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; String mode = "json"; String units = "metric"; int count = 7; // Will contain the raw JSON response as a string. String forecastJsonStr = null; try { final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily"; final String QUERY_PARAM = "q"; final String MODE_PARAM = "mode"; final String UNITS_PARAM = "units"; final String COUNT_PARAM = "cnt"; final String APPID_PARAM = "APPID"; Uri builtUri = Uri.parse(FORECAST_BASE_URL) .buildUpon() .appendQueryParameter(QUERY_PARAM, params[0]) .appendQueryParameter(MODE_PARAM, mode) .appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(COUNT_PARAM, Integer.toString(count)) .appendQueryParameter(APPID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY) .build(); // Construct the URL for the OpenWeatherMap query // Possible parameters are available at OWM's forecast API page, at // http://openweathermap.org/API#forecast URL url = new URL(builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuffer buffer = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } forecastJsonStr = buffer.toString(); String[] forecastArray = getWeatherDataFromJson(forecastJsonStr, 7); return forecastArray; } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the weather data, there's no point in attempting // to parse it. return null; } catch (JSONException 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); } } } } /** * <p>Runs on the UI thread after {@link #doInBackground}. The * specified result is the value returned by {@link #doInBackground}.</p> * <p/> * <p>This method won't be invoked if the task was cancelled.</p> * * @param forecastArray The result of the operation computed by {@link #doInBackground}. * @see #onPreExecute * @see #doInBackground * @see #onCancelled(Object) */ @Override protected void onPostExecute(String[] forecastArray) { if (forecastArray == null) { return; } ArrayList<String> forecastList = new ArrayList<>(Arrays.asList(forecastArray)); mForecastAdapter.clear(); mForecastAdapter.addAll(forecastList); } /* The date/time conversion code is going to be moved outside the asynctask later, * so for convenience we're breaking it out into its own method now. */ private String getReadableDateString(long time){ // Because the API returns a unix timestamp (measured in seconds), // it must be converted to milliseconds in order to be converted to valid date. SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd"); return shortenedDateFormat.format(time); } /** * Prepare the weather high/lows for presentation. */ private String formatHighLows(double high, double low) { // For presentation, assume the user doesn't care about tenths of a degree. long roundedHigh = Math.round(high); long roundedLow = Math.round(low); String highLowStr = roundedHigh + "/" + roundedLow; return highLowStr; } /** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us. */ private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays) throws JSONException { // These are the names of the JSON objects that need to be extracted. final String OWM_LIST = "list"; final String OWM_WEATHER = "weather"; final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_DESCRIPTION = "main"; JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); String[] resultStrs = new String[numDays]; for(int i = 0; i < weatherArray.length(); i++) { // For now, using the format "Day, description, hi/low" String day; String description; String highAndLow; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // The date/time is returned as a long. We need to convert that // into something human-readable, since most people won't read "1400356800" as // "this saturday". long dateTime; // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay+i); day = getReadableDateString(dateTime); // description is in a child array called "weather", which is 1 element long. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); double high = temperatureObject.getDouble(OWM_MAX); double low = temperatureObject.getDouble(OWM_MIN); highAndLow = formatHighLows(high, low); resultStrs[i] = day + " - " + description + " - " + highAndLow; } return resultStrs; } } }
app/src/main/java/com/example/android/sunshine/app/ForecastFragment.java
package com.example.android.sunshine.app; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.format.Time; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; 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.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; /** * A placeholder fragment containing a simple view. */ public class ForecastFragment extends Fragment { private ArrayAdapter<String> mForecastAdapter; public ForecastFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); String[] weatherData = { "Mon 6/23 - Sunny - 31/17", "Tue 6/24 - Foggy - 21/8", "Wed 6/25 - Cloudy - 22/17", "Thurs 6/26 - Rainy - 18/11", "Fri 6/27 - Foggy - 21/10", "Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18", "Sun 6/29 - Sunny - 20/7" }; ArrayList<String> weatherList = new ArrayList<>(Arrays.asList(weatherData)); mForecastAdapter = new ArrayAdapter<>(getContext(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weatherList); final ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast); listView.setAdapter(mForecastAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String selectedItemText = parent.getItemAtPosition(position) .toString(); Toast.makeText(getContext(), selectedItemText, Toast.LENGTH_SHORT) .show(); } }); return rootView; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.forecastfragment, menu); } @Override public boolean onOptionsItemSelected(MenuItem menuItem) { int itemId = menuItem.getItemId(); switch (itemId){ case R.id.action_refresh: new FetchWeatherTask().execute("94043"); return true; default: return super.onOptionsItemSelected(menuItem); } } public class FetchWeatherTask extends AsyncTask<String, Void, String[]> { private final String LOG_TAG = FetchWeatherTask.class.getSimpleName(); @Override protected String[] doInBackground(String... params) { if (params == null) { return null; } // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; String mode = "json"; String units = "metric"; int count = 7; // Will contain the raw JSON response as a string. String forecastJsonStr = null; try { final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily"; final String QUERY_PARAM = "q"; final String MODE_PARAM = "mode"; final String UNITS_PARAM = "units"; final String COUNT_PARAM = "cnt"; final String APPID_PARAM = "APPID"; Uri builtUri = Uri.parse(FORECAST_BASE_URL) .buildUpon() .appendQueryParameter(QUERY_PARAM, params[0]) .appendQueryParameter(MODE_PARAM, mode) .appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(COUNT_PARAM, Integer.toString(count)) .appendQueryParameter(APPID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY) .build(); // Construct the URL for the OpenWeatherMap query // Possible parameters are available at OWM's forecast API page, at // http://openweathermap.org/API#forecast URL url = new URL(builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuffer buffer = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } forecastJsonStr = buffer.toString(); String[] forecastArray = getWeatherDataFromJson(forecastJsonStr, 7); return forecastArray; } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the weather data, there's no point in attempting // to parse it. return null; } catch (JSONException 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); } } } } /** * <p>Runs on the UI thread after {@link #doInBackground}. The * specified result is the value returned by {@link #doInBackground}.</p> * <p/> * <p>This method won't be invoked if the task was cancelled.</p> * * @param forecastArray The result of the operation computed by {@link #doInBackground}. * @see #onPreExecute * @see #doInBackground * @see #onCancelled(Object) */ @Override protected void onPostExecute(String[] forecastArray) { if (forecastArray == null) { return; } ArrayList<String> forecastList = new ArrayList<>(Arrays.asList(forecastArray)); mForecastAdapter.clear(); mForecastAdapter.addAll(forecastList); } /* The date/time conversion code is going to be moved outside the asynctask later, * so for convenience we're breaking it out into its own method now. */ private String getReadableDateString(long time){ // Because the API returns a unix timestamp (measured in seconds), // it must be converted to milliseconds in order to be converted to valid date. SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd"); return shortenedDateFormat.format(time); } /** * Prepare the weather high/lows for presentation. */ private String formatHighLows(double high, double low) { // For presentation, assume the user doesn't care about tenths of a degree. long roundedHigh = Math.round(high); long roundedLow = Math.round(low); String highLowStr = roundedHigh + "/" + roundedLow; return highLowStr; } /** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us. */ private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays) throws JSONException { // These are the names of the JSON objects that need to be extracted. final String OWM_LIST = "list"; final String OWM_WEATHER = "weather"; final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_DESCRIPTION = "main"; JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); String[] resultStrs = new String[numDays]; for(int i = 0; i < weatherArray.length(); i++) { // For now, using the format "Day, description, hi/low" String day; String description; String highAndLow; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // The date/time is returned as a long. We need to convert that // into something human-readable, since most people won't read "1400356800" as // "this saturday". long dateTime; // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay+i); day = getReadableDateString(dateTime); // description is in a child array called "weather", which is 1 element long. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); double high = temperatureObject.getDouble(OWM_MAX); double low = temperatureObject.getDouble(OWM_MIN); highAndLow = formatHighLows(high, low); resultStrs[i] = day + " - " + description + " - " + highAndLow; } return resultStrs; } } }
Launching DetailActivity on list item click.
app/src/main/java/com/example/android/sunshine/app/ForecastFragment.java
Launching DetailActivity on list item click.
<ide><path>pp/src/main/java/com/example/android/sunshine/app/ForecastFragment.java <ide> package com.example.android.sunshine.app; <ide> <add>import android.content.Intent; <ide> import android.net.Uri; <ide> import android.os.AsyncTask; <ide> import android.os.Bundle; <ide> public void onItemClick(AdapterView<?> parent, View view, int position, long id) { <ide> String selectedItemText = parent.getItemAtPosition(position) <ide> .toString(); <del> Toast.makeText(getContext(), selectedItemText, Toast.LENGTH_SHORT) <del> .show(); <add> Intent intent = new Intent(getContext(), DetailActivity.class); <add> intent.putExtra(Intent.EXTRA_TEXT, selectedItemText); <add> startActivity(intent); <ide> } <ide> }); <ide> return rootView;
JavaScript
mit
a92fa0267f6f07a4785090d7d9fce009ac2d59f9
0
WheatonCS/Lexos,WheatonCS/Lexos,WheatonCS/Lexos
$(function(){ // Create the manage table initialize_manage_table("#manage-table", true); // Create the context menu hide callbacks $(window).on("mousedown resize", hide_context_menu); $("#main-section").on("scroll", hide_context_menu); // Create the context menu button callbacks $("#preview-button").mousedown(preview); $("#edit-name-button").mousedown(edit_name); $("#edit-class-button").mousedown(edit_class); $("#delete-button").mousedown(delete_document); $("#merge-selected-button").mousedown(merge_selected); $("#edit-selected-classes-button").mousedown(edit_selected_classes); $("#delete-selected-button").mousedown(delete_selected); $("#select-all-button").mousedown(manage_table_select_all); $("#deselect-all-button").mousedown(manage_table_deselect_all); // Initialize the walkthrough initialize_walkthrough(walkthrough); // Disable the "Active Documents" button $("#active-documents-text").addClass("disabled"); }); /** * Shows a custom context menu. * @param {Event} event: The event that triggered the callback. */ let context_menu_document_id; function show_context_menu(event){ // Prevent the default context menu from appearing event.preventDefault(); // Save the ID of the right-clicked document for use in other functions context_menu_document_id = parseInt($(this).attr("id")); // Set the custom context menu's position to the right-click and make it // visible and clickable let position = get_mouse_position(event); let page_size = get_page_size(); let context_menu_size = get_element_size("#context-menu"); let context_menu_far_position = point_add(position, context_menu_size); if(context_menu_far_position.x > page_size.x) position.x -= context_menu_size.x; if(context_menu_far_position.y > page_size.y) position.y -= context_menu_size.y; $("#context-menu").css({"pointer-events": "auto", "opacity": "1", "left": `${position.x}px`, "top": `${position.y}px`}); } /** * Hides the custom context menu. * @param {Event} event: The event that triggered the callback. */ function hide_context_menu(event){ $("#context-menu").css({"pointer-events": "none", "opacity": "0"}); } /** * Creates a popup containing a preview of the document that was right-clicked. */ function preview(){ // Send a request to get the preview of the document that was right-clicked send_manage_table_request("preview", context_menu_document_id) // If the request is successful create a popup and append the // HTML-escaped document preview to it .done(function(response){ create_popup("Preview"); let preview = $(`<h3 id="document-preview-text"></h3>`) .appendTo("#preview-popup .popup-content"); preview.text(parse_json(response)["preview_text"]); }) // If the request failed, display an error .fail(function(){ error(`Failed to retrieve the document's preview.`); }); } /** * Renames the document that was right-clicked. */ function edit_name(){ // Create a popup containing a text input create_text_input_popup("Document Name"); // Set the popup's initial text input to the existing document name $("#document-name-popup .popup-input").val( get_manage_document(context_menu_document_id).label); // If the popup's "OK" button is clicked $("#document-name-popup .popup-ok-button").click(function(){ // Make a request to set the name of the document that was // right-clicked to the content of the popup's text input field send_manage_table_request("edit-name", [context_menu_document_id, $("#document-name-popup .popup-input").val()]) // If the request was successful, close the popup and recreate the // table .done(function(){ close_popup(); create_manage_table() }) // If the request failed, display an error .fail(function(){ error("Failed to edit the document's name."); }); }); } /** * Sets the class name of the document that was right-clicked. */ function edit_class(){ // Create a popup containing a text input create_text_input_popup("Document Class"); // Set the popup's initial text input to the existing document class $("#document-class-popup .popup-input").val( get_manage_document(context_menu_document_id).class); // When the popup's "OK" button is clicked $("#document-class-popup .popup-ok-button").click(function(){ // Make a request to set the class of the document that was // right-clicked to the content of the popup's text input field send_manage_table_request("set-class", [context_menu_document_id, $("#document-class-popup .popup-input").val()]) // If the request was successful, close the popup and recreate the // table .done(function(){ close_popup(); create_manage_table(); }) // If the request failed, display an error .fail(function(){ error("Failed to set the document's class."); }); }); } /** * Deletes the document that was right-clicked. */ function delete_document(){ // Send a request to delete the document that was right-clicked send_manage_table_request("delete", context_menu_document_id) // If the request was successful, recreate the table .done(function(){ create_manage_table(); }) // If the request failed, display an error .fail(function(){ error("Failed to delete the document."); }); } /** * Merges the selected documents. */ function merge_selected(){ let selected_document_ids = get_selected_document_ids(); let first_selected_document = get_manage_document(selected_document_ids[0]); // Create the popup create_ok_popup("Merge Active"); $(` <h3>Name: </h3> <input id="merge-name-input" value="Merge-${first_selected_document.label}" type="text" spellcheck="false" autocomplete="off"> <br> <label> <input id="merge-milestone-checkbox" name="" type="checkbox"> <span></span> Milestone: <input id="merge-milestone-input" name="" value="#EOF#" type="text" spellcheck="false" autocomplete="off"> </label> `).appendTo("#merge-active-popup .popup-content"); // If the popup's "OK" button is clicked... $("#merge-active-popup .popup-ok-button").click(function(){ // Create the payload let payload = [ selected_document_ids, $("#merge-name-input").val(), first_selected_document.source, $("#merge-milestone-checkbox").is(":checked") ? $("#merge-milestone-input").val() : "" ]; // Send the merge request send_manage_table_request("merge-selected", payload) // If the request was successful, close the popup and recreate the // table .done(function(){ close_popup(); create_manage_table(); }) // If the request failed, display an error .fail(function(){ error("Failed to merge the active documents."); }); }); } /** * Edits the class names of the selected documents. */ function edit_selected_classes(){ // Create a popup containing a text input create_text_input_popup("Document Class"); // If the popup's "OK" button is clicked... $("#document-class-popup .popup-ok-button").click(function(){ // Send a request to set the class names of the selected documents // to the value in the popup's text input send_manage_table_request("edit-selected-classes", [get_selected_document_ids(), $("#document-class-popup .popup-input").val()]) // If the request was successful, close the popup and recreate the // table .done(function(){ close_popup(); create_manage_table(); }) // If the request failed, display an error .fail(function(){ error("Failed to edit the active documents' classes."); }); }); } /** * Deletes the selected documents. */ function delete_selected(){ // Send a request to delete the selected documents send_manage_table_request("delete-selected") // If the request was successful, recreate the table .done(function(){ create_manage_table(); }) // If the request failed, display an error .fail("Failed to delete the active documents"); } /** * Gets the IDs of the currently selected documents. * @returns {Number[]}: The selected document IDs. */ function get_selected_document_ids(){ let id_list = []; $(".manage-table-row").each(function(){ if($(this).hasClass("manage-table-selected-row")) id_list.push(parseInt($(this).attr("id"))); }); return id_list; } /** * Initializes the walkthrough. */ function walkthrough(){ let intro = introJs(); intro.setOptions({steps: [ { intro: `Welcome to the Manage page!`, position: "top", }, { element: "#active", intro: `Active documents will have a blue highlight to them. You can deactivate documents by clicking while holding down "D".`, position: "bottom" }, { element: "#document", intro: `The Document column holds custom document names. You can rename documents by right-clicking.`, position: "bottom" }, { element: "#class", intro: `If you want to group documents together, you may give them a class by right-clicking.`, position: "bottom" }, { element: "#excerpt", intro: `Excerpt will give you a preview of your document.`, position: "bottom" }, { element: "#help-button", intro: `Check our Help section for more advice on the Manage page.`, position: "bottom" }, { element: "#prepare-button", intro: `Once you"re satisfied with your active documents, you can move on to the "Prepare" pages.`, position: "bottom" }, { intro: `This concludes the Manage walkthrough!`, position: "top", } ]}); return intro; }
lexos/static/js/manage.js
$(function(){ // Create the manage table initialize_manage_table("#manage-table", true); // Create the context menu hide callbacks $(window).on("mousedown resize", hide_context_menu); $("#main-section").on("scroll", hide_context_menu); // Create the context menu button callbacks $("#preview-button").mousedown(preview); $("#edit-name-button").mousedown(edit_name); $("#edit-class-button").mousedown(edit_class); $("#delete-button").mousedown(delete_document); $("#merge-selected-button").mousedown(merge_selected); $("#edit-selected-classes-button").mousedown(edit_selected_classes); $("#delete-selected-button").mousedown(delete_selected); $("#select-all-button").mousedown(manage_table_select_all); $("#deselect-all-button").mousedown(manage_table_deselect_all); // Initialize the walkthrough initialize_walkthrough(walkthrough); // Disable the "Active Documents" button $("#active-documents-text").addClass("disabled"); }); /** * Shows a custom context menu. * @param {Event} event: The event that triggered the callback. */ let context_menu_document_id; function show_context_menu(event){ // Prevent the default context menu from appearing event.preventDefault(); // Save the ID of the right-clicked document for use in other functions context_menu_document_id = parseInt($(this).attr("id")); // Set the custom context menu's position to the right-click and make it // visible and clickable let position = get_mouse_position(event); let page_size = get_page_size(); let context_menu_size = get_element_size("#context-menu"); let context_menu_far_position = point_add(position, context_menu_size); if(context_menu_far_position.x > page_size.x) position.x -= context_menu_size.x; if(context_menu_far_position.y > page_size.y) position.y -= context_menu_size.y; $("#context-menu").css({"pointer-events": "auto", "opacity": "1", "left": `${position.x}px`, "top": `${position.y}px`}); } /** * Hides the custom context menu. * @param {Event} event: The event that triggered the callback. */ function hide_context_menu(event){ $("#context-menu").css({"pointer-events": "none", "opacity": "0"}); } /** * Creates a popup containing a preview of the document that was right-clicked. */ function preview(){ // Send a request to get the preview of the document that was right-clicked send_manage_table_request("preview", context_menu_document_id) // If the request is successful create a popup and append the // HTML-escaped document preview to it .done(function(response){ create_popup("Preview"); let preview = $(`<h3 id="document-preview-text"></h3>`) .appendTo("#preview-popup .popup-content"); preview.text(parse_json(response)["preview_text"]); }) // If the request failed, display an error .fail(function(){ error(`Failed to retrieve the document's preview.`); }); } /** * Renames the document that was right-clicked. */ function edit_name(){ // Create a popup containing a text input create_text_input_popup("Document Name"); // Set the popup's initial text input to the existing document name $("#document-name-popup .popup-input").val( get_manage_document(context_menu_document_id).label); // If the popup's "OK" button is clicked $("#document-name-popup .popup-ok-button").click(function(){ // Make a request to set the name of the document that was // right-clicked to the content of the popup's text input field send_manage_table_request("edit-name", [context_menu_document_id, $("#document-name-popup .popup-input").val()]) // If the request was successful, close the popup and recreate the // table .done(function(){ close_popup(); create_manage_table() }) // If the request failed, display an error .fail(function(){ error("Failed to edit the document's name."); }); }); } /** * Sets the class name of the document that was right-clicked. */ function edit_class(){ // Create a popup containing a text input create_text_input_popup("Document Class"); // Set the popup's initial text input to the existing document class $("#document-class-popup .popup-input").val( get_manage_document(context_menu_document_id).class); // When the popup's "OK" button is clicked $("#document-class-popup .popup-ok-button").click(function(){ // Make a request to set the class of the document that was // right-clicked to the content of the popup's text input field send_manage_table_request("set-class", [context_menu_document_id, $("#document-class-popup .popup-input").val()]) // If the request was successful, close the popup and recreate the // table .done(function(){ close_popup(); create_manage_table(); }) // If the request failed, display an error .fail(function(){ error("Failed to set the document's class."); }); }); } /** * Deletes the document that was right-clicked. */ function delete_document(){ // Send a request to delete the document that was right-clicked send_manage_table_request("delete", context_menu_document_id) // If the request was successful, recreate the table .done(function(){ create_manage_table(); }) // If the request failed, display an error .fail(function(){ error("Failed to delete the document."); }); } /** * Merges the selected documents. */ function merge_selected(){ let selected_document_ids = get_selected_document_ids(); let first_selected_document = get_manage_document(selected_document_ids[0]); // Create the popup create_ok_popup("Merge Active"); $(` <h3>Name: </h3> <input id="merge-name-input" value="Merge-${first_selected_document.label}" type="text" spellcheck="false" autocomplete="off"> <br> <label> <input id="merge-milestone-checkbox" name="" type="checkbox"> <span></span> Milestone: <input id="merge-milestone-input" name="" value="#EOF#" type="text" spellcheck="false" autocomplete="off"> </label> `).appendTo("#merge-active-popup .popup-content"); // If the popup's "OK" button is clicked... $("#merge-active-popup .popup-ok-button").click(function(){ // Create the payload let payload = [ selected_document_ids, $("#merge-name-input").val(), first_selected_document.source, $("#merge-milestone-checkbox").is(":checked") ? $("#merge-milestone-input").val() : "" ]; // Send the merge request send_manage_table_request("merge-selected", payload) // If the request was successful, close the popup and recreate the // table .done(function(){ close_popup(); create_manage_table(); }) // If the request failed, display an error .fail(function(){ error("Failed to merge the active documents."); }); }); } /** * Edits the class names of the selected documents. */ function edit_selected_classes(){ // Create a popup containing a text input create_text_input_popup("Document Class"); // If the popup's "OK" button is clicked... $("#document-class-popup .popup-ok-button").click(function(){ // Send a request to set the class names of the selected documents // to the value in the popup's text input send_manage_table_request("edit-selected-classes", [get_selected_document_ids(), $("#document-class-popup .popup-input").val()]) // If the request was successful, close the popup and recreate the // table .done(function(){ close_popup(); create_manage_table(); }) // If the request failed, display an error .fail(function(){ error("Failed to edit the active documents' classes."); }); }); } /** * Deletes the selected documents. */ function delete_selected(){ // Send a request to delete the selected documents send_manage_table_request("delete-selected") // If the request was successful, recreate the table .done(function(){ create_manage_table(); }) // If the request failed, display an error .fail("Failed to delete the active documents"); } /** * Gets the IDs of the currently selected documents. * @returns {Number[]}: The selected document IDs. */ function get_selected_document_ids(){ let id_list = []; $(".manage-table-row").each(function(){ if($(this).hasClass("manage-table-selected-row")) id_list.push(parseInt($(this).attr("id"))); }); return id_list; } /** * Initializes the walkthrough. */ function walkthrough(){ let intro = introJs(); intro.setOptions({steps: [ { intro: `Welcome to the Manage page!`, position: "top", }, { element: "#active", intro: `Active documents will have a blue highlight to them. You can deactivate documents by clicking while holding down "D".`, position: "bottom" }, { element: "#document", intro: `The Document column holds custom document names. You can rename documents by right-clicking.`, position: "bottom" }, { element: "#class", intro: `If you want to group documents together, you may give them a class by right-clicking.`, position: "bottom" }, { element: "#excerpt", intro: `Excerpt will give you a preview of your document.`, position: "bottom" }, { element: "#active-documents-footer", intro: `By clicking Active Documents in any page, you can quickly access a popup where you can toggle documents in-page.`, position: "bottom" }, { element: "#help-button", intro: `Check our Help section for more advice on the Manage page.`, position: "bottom" }, { element: "#prepare-button", intro: `Once you"re satisfied with your active documents, you can move on to the "Prepare" pages.`, position: "bottom" }, { intro: `This concludes the Manage walkthrough!`, position: "top", } ]}); return intro; }
removed a bit
lexos/static/js/manage.js
removed a bit
<ide><path>exos/static/js/manage.js <ide> position: "bottom" <ide> }, <ide> { <del> element: "#active-documents-footer", <del> intro: `By clicking Active Documents in any page, you can quickly <del> access a popup where you can toggle documents in-page.`, <del> position: "bottom" <del> }, <del> { <ide> element: "#help-button", <ide> intro: `Check our Help section for more advice on the Manage <ide> page.`,
JavaScript
apache-2.0
4a6022cd8459b06eec86a676861e2552a3d708e6
0
SmartDeveloperHub/sdh-framework
/* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# This file is part of the Smart Developer Hub Project: http://www.smartdeveloperhub.org/ Center for Open Middleware http://www.centeropenmiddleware.com/ #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# Copyright (C) 2015 Center for Open Middleware. #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# */ (function() { /* ------------------------------- ------ FRAMEWORK GLOBALS ------ ------------------------------- */ //Variable where public methods and variables will be stored var _self = { data: {}, widgets: {}, dashboard: {} }; //Path to the SDH-API server without the trailing slash var _serverUrl; // Array with the information about the different resources of the API var _resourcesInfo; // List of all the parameters that can be used with the API. // It is only for performance purposes while checking input. var _existentParametersList = []; // Storage of the data data var _resourcesStorage = {}; //TODO: multi-level cache var _resourcesContexts = {}; // Contains a list that links user callbacks (given as parameter at the observe methods) with the internal // callbacks. It is need to remove handlers when not used and free memory. var _event_handlers = []; // This is a variable to make the events invisible outside the framework var _eventBox = {}; // Dashboard controller var _dashboardController = null; var _dashboardEnv = {}; // This contains the listeners for each of the events of the dashboard var _dashboardEventListeners = { 'change' : [] }; var _isReady = false; var FRAMEWORK_NAME = "SDHWebFramework"; /* ------------------------------- -- FRAMEWORK PRIVATE METHODS -- ------------------------------- */ /** * Prints a framework error * @param message Message to display. */ var error = function error(message) { console.error("[" + FRAMEWORK_NAME + "] " + message); }; /** * Prints a framework warning * @param message Message to display. */ var warn = function warn(message) { console.warn("[" + FRAMEWORK_NAME + "] " + message); }; var requestJSON = function requestJSON(path, queryParams, callback, maxRetries) { if(typeof maxRetries === 'undefined'){ maxRetries = 2; //So up to 3 times will be requested } $.getJSON( _serverUrl + path, queryParams, callback).fail( function(d, textStatus, e) { error("Framework getJSON request failed\nStatus: " + textStatus + " \nError: "+ (e ? e : '-') + "\nRequested url: '"+ path+"'\nParameters: " + JSON.stringify(queryParams)); //Retry the request if (maxRetries > 0 && textStatus === "timeout") { requestJSON(path, queryParams, callback, --maxRetries); } }); }; /** * Fills _resourcesInfo hashmap with the reources info and the following structure: * { * "{resource-id}": { * path:"yourpath/../sdfsdf", * params: ['param1', 'param2'], * queryParams: ['queryParam1'] * }, * ... * } * @param onReady */ var loadResourcesInfo = function loadResourcesInfo(onReady) { requestJSON("/api/", null, function(data) { //var paths = data['swaggerjson']['paths']; var paths = [{ path :"/metrics", variable: "mid" },{ path :"/tbdata", variable: "tid" }]; var apiPaths = data['swaggerjson']['paths']; //Count number of elements in paths var pathsLength = 0; for(var i in paths) pathsLength++; //Function to check if it has finished and call the callback var pathsProcessed = 0; var pathProcessed = function() { if(++pathsProcessed === pathsLength && 'function' === typeof onReady) { onReady(); } }; //Initialize the _resourcesInfo object _resourcesInfo = {}; //var isMetricList = /\/data\/$/; //var isMetricListWithoutParams = /^((?!\{).)*\/data\/$/; //var isSpecificMetric = /\/\{mid\}$/; //TODO: I dont like this, but till now there is not any other way to get static data... var statInfo = [ // API static Information description { "id" : "userinfo", "path" : "/users/{uid}", params: {'uid': {name: 'uid',in: 'path',required: true}}, "description" : "User Information" }, { "id" : "repoinfo", "path" : "/repositories/{rid}", params: {'rid': {name: 'rid',in: 'path',required: true}}, "description" : "Repository Information" }, { "id" : "orginfo", "path" : "/", "description" : "Organization Information" }, { "id" : "userlist", "path" : "/users/", "description" : "Users List" }, { "id" : "repolist", "path" : "/repositories/", "description" : "Repository List" }, { "id" : "metriclist", "path" : "/metrics/", "description" : "Metrics list" }, { "id" : "tbdlist", "path" : "/tbd/", "description" : "Time-based data list" } ]; for(var i = statInfo.length - 1; i >= 0; --i ) { var info = statInfo[i]; _resourcesInfo[info['id']] = { path: info['path'], requiredParams: (info.params != null ? info.params : {}), //list of url param names optionalParams: {} //list of query params }; } //TODO: END TODO ---------------------------- //Iterate over the path of the api for(var x = paths.length - 1; x >= 0; --x ) { var path = paths[x]['path']; // Make an api request to retrieve all the data requestJSON(path, null, function(p, data) { //Iterate over the resources for(var j = 0, len = data.length; j < len; ++j) { var resourceInfo = data[j]; var resourceId = resourceInfo['id']; var resourcePath = resourceInfo['path']; // Fill the _resourcesInfo array _resourcesInfo[resourceId] = { path: resourcePath, requiredParams: {}, //list of url param names optionalParams: {} //list of query params }; //Get the general resource path info (like /data/{mid}) var generalResourcePath = resourcePath.substring(0, resourcePath.lastIndexOf('/')) + '/{'+paths[p]['variable']+'}'; var generalResourcePathInfo = apiPaths[generalResourcePath]; if(generalResourcePathInfo == null) { error("General resource path ("+generalResourcePathInfo+") does not exist in API path list."); continue; } //Add the url params and query params to the list if(generalResourcePathInfo['get']['parameters'] != null) { var parameters = generalResourcePathInfo['get']['parameters']; //Add all parameters and avoid 'mid' for(var i = 0, len_i = parameters.length; i < len_i; i++) { var paramName = parameters[i]['name']; //Add the parameter in params or queryParams if(paramName === paths[p]['variable']) { //Ignore it } else if (parameters[i]['required'] == true || resourceInfo['params'].indexOf(paramName) !== -1) { _resourcesInfo[resourceId]['requiredParams'][paramName] = { name: paramName, in: parameters[i]['in'], required: true }; } else if(resourceInfo['optional'].indexOf(paramName) !== -1) { _resourcesInfo[resourceId]['optionalParams'][paramName] = { name: paramName, in: parameters[i]['in'], required: false }; } //Add it to the list of possible parameters (cache) if(_existentParametersList.indexOf(parameters[i]['name']) === -1) { _existentParametersList.push(parameters[i]['name']); } } } } pathProcessed(); //Finished processing this path }.bind(null, x)); } }); }; /** * Checks if the resource object has all the information that is needed to request the resource data * @param resource A resource object. At least must have the id. Can have other parameters, like range, userId... * @returns {boolean} */ var resourceCanBeRequested = function resourceCanBeRequested(resource) { if(resource['id'] == null) { return false; } var resourceInfo = _resourcesInfo[resource['id']]; if(resourceInfo == null) { return false; } for(var paramId in resourceInfo['requiredParams']) { var paramValue = resource[paramId]; if(paramValue == null) { return false; } } return true; }; /** * Checks if all the given resources fulfill all the requirements to be requested * @param resources Array of normalized resources * @returns {boolean} */ var allResourcesCanBeRequested = function allResourcesCanBeRequested(resources) { for(var i in resources) { if(!resourceCanBeRequested(resources[i])) { return false; } } return true; }; /** * Request a given resource * @param resourceId */ var makeResourceRequest = function makeResourceRequest(resourceId, params, callback) { var resourceInfo = _resourcesInfo[resourceId]; var queryParams = {}; if(resourceInfo != null) { /* Generate path */ var path = resourceInfo.path; // Replace params in url skeleton for(var paramId in params) { var paramInfo = resourceInfo['requiredParams'][paramId] || resourceInfo['optionalParams'][paramId]; var paramValue = params[paramId]; if(paramValue == null) { //It has no value (ignore it or throw an error) if(paramInfo['required'] === true) { error("Resource '"+ resourceId + "' needs parameter '"+ paramId +"'."); return; } } else if(paramInfo['in'] === 'query') { queryParams[paramId] = paramValue; } else if(paramInfo['in'] === 'path') { path = path.replace('{'+paramId+'}', paramValue); } } /* Make the request */ requestJSON(path, queryParams, callback); } else { error("Resource '"+ resourceId + "' does not exist."); } }; /** * Requests multiple resources * @param resources Normalized resource * @param callback * @param unique Is this is a request that do not depend on any context, so it will be executed only once */ var multipleResourcesRequest = function multipleResourcesRequest(resources, callback, unique) { var completedRequests = 0; var allData = {}; var requests = []; var onResourceReady = function(resourceId, params, data) { if(allData[resourceId] == null) { allData[resourceId] = []; } //Add the framework info to the data received from the api var resUID = resourceHash(resourceId, params); var info = { UID: resUID, request: { params: params } }; allData[resourceId].push({ data: data, info: info }); if(++completedRequests === requests.length) { sendDataEventToCallback(allData, callback, unique); } }; //Send a loading data event to the listener sendLoadingEventToCallback(callback); for(var i in resources) { var resourceId = resources[i].id; var params = {}; var multiparams = []; //Fill the params and multiparams for(var name in resources[i]) { if(_resourcesInfo[resourceId]['optionalParams'][name] != null || _resourcesInfo[resourceId]['requiredParams'][name] != null) { //Is a param //Check if is multi parameter and add it to the list of multi parameters if(resources[i][name] instanceof Array) { multiparams.push(name); } params[name] = resources[i][name]; } } var requestsCombinations = generateResourceRequestParamsCombinations(resourceId, params, multiparams); requests = requests.concat(requestsCombinations); } for(var i in requests) { var resourceId = requests[i]['resourceId']; var params = requests[i]['params']; makeResourceRequest(resourceId, params, onResourceReady.bind(undefined, resourceId, params)); } }; /** * Generates an array of requests combining all the values of the multi parameters (param and queryParam). * @param resourceId * @param params Hash map of param name and values. * @param multiparam List of parameter names that have multiple values. * @returns {Array} Array of requests to execute for one resource */ var generateResourceRequestParamsCombinations = function (resourceId, params, multiparam) { var paramsCombinations = generateParamsCombinations(params, multiparam); var allCombinations = []; //Create the combinations of params and queryParams for(var i = 0, len_i = paramsCombinations.length; i < len_i; ++i) { allCombinations.push({ resourceId: resourceId, params: paramsCombinations[i] }); } return allCombinations; }; /** * Generates all the combinations of multi parameters. * @param params Hash map of param name and values. * @param multiParams List of parameter names that have multiple values. * @returns {Array} Array of parameter combinations. */ var generateParamsCombinations = function generateParamsCombinations(params, multiParams) { //Clone params before modifying them params = clone(params); if(multiParams.length > 0) { var result = []; //Clone function params before modifying them multiParams = clone(multiParams); //Remove the parameter from the list of multi parameters var param = multiParams.pop(); //Save the values of the parameter because it will be modified var values = params[param]; //For each value generate the possible combinations for(var i in values) { var value = values[i]; //Overwrite array with only one value params[param] = value; //Generate the combinations for that value var combinations = generateParamsCombinations(params, multiParams); result = result.concat(combinations); } return result; } else { //End of recursion return [ params ]; } }; /** * Converts the array of resources containing a mixture of strings (for simple resources) and objects (for complex resources) * into an array of objects with at least an id. * @param resources Array of resources containing a mixture of strings (for simple resources) and objects (for complex resources). * It can be modified, so consider cloning it if necessary. * @returns {Array} */ var normalizeResources = function normalizeResources(resources) { var newMetricsParam = []; for(var i in resources) { if('string' === typeof resources[i]) { newMetricsParam.push({id: resources[i]}); } else if('object' === typeof resources[i] && resources[i]['id']) { //Metrics objects must have an id newMetricsParam.push(resources[i]); } else { warn("One of the resources given was not string nor object so it has been ignored."); } } //Remove invalid resources and parameters newMetricsParam = cleanResources(newMetricsParam); return newMetricsParam; }; /** * Cleans an array of resource objects removing the non existent ones and the invalid parameters of them. * @param resources Array of resource objects to clean. */ var cleanResources = function cleanResources(resources) { var newResources = []; for(var i = 0; i < resources.length; ++i) { var resource = resources[i]; var resourceId = resource['id']; var resourceInfo = _resourcesInfo[resourceId]; if(resourceInfo == null) { warn("Resource '"+resourceId+"' does not exist."); } else { //Check its parameters var cleanParameters = {}; for(var paramName in resource) { if(paramName != 'id' && paramName != 'static' && resourceInfo['requiredParams'][paramName] == null && resourceInfo['optionalParams'][paramName] == null) { warn("Parameter '"+paramName+"' is not a valid parameter for resource '"+resourceId+"'."); } else { cleanParameters[paramName] = resource[paramName]; } } if(Object.keys(cleanParameters).length > 0) { newResources.push(cleanParameters); } } } return newResources; }; /** Clone the object * @obj1 Object to clone. * @return {object} */ var clone = function clone(obj1) { var result; if (obj1 == null) { return obj1; } else if (Array.isArray(obj1)) { result = []; } else if (typeof obj1 === 'object') { result = {}; } else { return obj1; } for (var key in obj1) { result[key] = clone(obj1[key]); } return result; }; /** * Deep merge in obj1 object. (Priority obj2) * @param obj1 * @param obj2 * @param mergeArrays If true, combines arrays. Otherwise, if two arrays must be merged, * the obj2's array overwrites the other. Default: true. * @returns {*} */ var mergeObjects = function mergeObjects(obj1, obj2, mergeArrays) { mergeArrays = mergeArrays || true; if (Array.isArray(obj2) && Array.isArray(obj1) && mergeArrays) { // Merge Arrays var i; for (i = 0; i < obj2.length; i++) { if (typeof obj2[i] === 'object' && typeof obj1[i] === 'object') { obj1[i] = mergeObjects(obj1[i], obj2[i], mergeArrays); } else { obj1[i] = obj2[i]; } } } else if (Array.isArray(obj2)) { // Priority obj2 obj1 = obj2; } else { // object case j for (var p in obj2) { if(obj1.hasOwnProperty(p)){ if (typeof obj2[p] === 'object' && typeof obj1[p] === 'object') { obj1[p] = mergeObjects(obj1[p], obj2[p], mergeArrays); } else { obj1[p] = obj2[p]; } } else { obj1[p] = obj2[p]; } } } return obj1; }; /** * Generates a hashcode given an string * @param str * @returns {number} 32 bit integer */ var hashCode = function hashCode(str) { var hash = 0, i, chr, len; if (str.length == 0) return hash; for (i = 0, len = str.length; i < len; i++) { chr = str.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var resourceHash = function resourceHash(resourceId, requestParams){ //TODO: loadResourcesInfo should set the list of hasheable parameters var str = resourceId; var hasheable = ""; for(var i in _resourcesInfo[resourceId]['requiredParams']){ var param = _resourcesInfo[resourceId]['requiredParams'][i]['name']; hasheable += param + requestParams[param] + ";" } if(requestParams['aggr'] != null) { hasheable += 'aggr' + requestParams['aggr'] + ";" } return resourceId + "#" + hashCode(hasheable).toString(16); }; /** * Combines an incomplete resource with a context in order to create a complete resource to make a request with. * @param resources * @param contexts Context ids */ var combineResourcesWithContexts = function combineResourcesWithContexts(resources, contexts) { var newResources = []; var contextsData = []; //Fill the array with data for each context for(var i in contexts) { contextsData.push(_resourcesContexts[contexts[i]]['data']); } //Iterate through the resources and combine them with the contexts for(var i in resources) { //Clone the resource object to avoid modification var resource = clone(resources[i]); //Modify the resource with all the contexts for(var c in contextsData) { //Clean the context var mergeContext = getCleanContextByResource(contextsData[c], resource); resource = mergeObjects(resource, mergeContext, false); } //Add the resource to the returned array newResources.push(resource); } return newResources; }; /** * Initializes the context container for the given contextId * @param contextId */ var initializeContext = function initializeContext(contextId) { _resourcesContexts[contextId] = { updateCounter: 0, data: {} }; }; /** * Gets a new context with only the params and query params accepted by the resource (taking into account the static * params). * @param context Object * @param resource A resource object (only id and static are used). */ var getCleanContextByResource = function getCleanContextByResource(context, resource) { var newContext = {}; var resourceInfo = _resourcesInfo[resource['id']]; var statics; if(resource['static'] != null){ statics = resource['static']; } else { statics = []; } //Add all the params this resource accepts for(var name in resourceInfo['requiredParams']) { if(context[name] !== undefined && statics.indexOf(name) === -1){ newContext[name] = context[name]; } } //Add all the query params this resource accepts for(var name in resourceInfo['optionalParams']) { if(context[name] !== undefined && statics.indexOf(name) === -1){ newContext[name] = context[name]; } } return newContext; }; /** * Checks if the given object is empty * @param o Object to check. * @returns {boolean} True if empty; false otherwise. */ var isObjectEmpty = function isObjectEmpty(o) { for(var i in o) return false; return true; }; /** * Send a data event to the given observer. This means that the data the framework was loading is now ready. * @param data New data. * @param callback * @param unique Is this is a request that do not depend on any context, so it will be executed only once */ var sendDataEventToCallback = function sendDataEventToCallback(data, callback, unique) { if(typeof callback === "function") { var observed = false; if(!unique) { //Check if it still is being observed for (var i in _event_handlers) { if (_event_handlers[i].userCallback === callback) { observed = true; break; } } } else { observed = true; } if(observed) { callback({ event: "data", data: data }); } } }; /** * Send a loading event to the given observer. That means that the framework is loading new data for that observer. * @param callback */ var sendLoadingEventToCallback = function sendLoadingEventToCallback(callback) { callback({ event: "loading" }); }; /* ------------------------------- -- FRAMEWORK PUBLIC METHODS --- ------------------------------- */ /** * * @param resources Array with resources. Each resource can be an String or an Object. The object must have the following * format: { * id: String, * <param1Id>: String, * <paramxId>: String, * } * For example: { * id: "usercommits", * uid: "pepito", * from : new Date(), * max: 0, * static: ["from"] //Static makes this parameter unalterable by the context changes. * //Static parameters must have a value; otherwise, an error will be returned. * } * @param callback Callback that receives an object containing at least an "event" that can be "data" or "loading". * - loading means that the framework is retrieving new data for the observer. * - data means that the new data is ready and can be accessed through the "data" element of the object returned to * the callback. The "data" element of the object is a hashmap using as key the resourceId of the requested resources * and as value an array with data for each of the request done for that resourceId. * @param contextIds Array of context ids. */ _self.data.observe = function observe(resources, callback, contextIds) { if('function' !== typeof callback){ error("Method 'observeData' requires a valid callback function."); return; } if(!Array.isArray(resources) || resources.length === 0 ) { error("Method 'observeData' has received an invalid resources parameter."); return; } if(contextIds != null && !(contextIds instanceof Array) ) { error("Method 'observeData' expects contextIds parameter to be null or an array."); return; } //Normalize the array of resources resources = normalizeResources(resources); if(resources.length === 0) { warn("No resources to observe."); return; } //Check that static parameters have their value defined in the resource for(var i = 0; i < resources.length; ++i) { if(resources[i]['static'] != null && resources[i]['static'].length > 0) { for(var s = 0; s < resources[i]['static'].length; ++s) { var staticParam = resources[i]['static'][s]; if(resources[i][staticParam] == null) { error("Static parameter '"+staticParam+"' must have its value defined."); return; } } } } //Is an Array, verify that it only contains strings if(contextIds instanceof Array) { //We will use it internally, so we need to clone it to prevent the user changing it contextIds = clone(contextIds); //If one of the contexts is not an string, remove it from the array for(var i = 0; i < contextIds.length; ++i) { if(typeof contextIds[i] != 'string') { contextIds.splice(i, 1); } } } else { //Invalid parameter type (or null) contextIds = [] } //Initialize contexts it they are not initialized for(var i = 0; i < contextIds.length; ++i) { if (_resourcesContexts[contextIds[i]] == null) { initializeContext(contextIds[i]); } } //If contexts are defined, combine the resources with the context in order to create more complete resources that could // be requested. if(contextIds.length > 0) { //Combine the resources with the context in order to create more complete resources that could be requested. var resourcesWithContext = combineResourcesWithContexts(resources, contextIds); //Request all the resources if possible if(allResourcesCanBeRequested(resourcesWithContext)) { multipleResourcesRequest(resourcesWithContext, callback, false); } //Create the CONTEXT event handler var contextEventHandler = function(event, contextCounter, contextChanges, contextId) { //If it is not the last context event launched, ignore the data because there is another more recent // event being executed if(contextCounter != _resourcesContexts[contextId]['updateCounter']){ return; } //Check if the changes affect to the resources var affectedResources = []; for(var i in resources) { var cleanContextChanges = getCleanContextByResource(contextChanges, resources[i]); if(!isObjectEmpty(cleanContextChanges)){ affectedResources.push(resources[i]); } } if(affectedResources.length === 0) { return; //The context change did not affect to none the resources } //TODO: when implementing the cache, affectedResources should be used to only request the changed resources. //Currently, as there is no cache, all the data must be requested because it is not stored anywhere. //Update the resources with the context data var resourcesWithContext = combineResourcesWithContexts(resources, contextIds); if(allResourcesCanBeRequested(resourcesWithContext)) { multipleResourcesRequest(resourcesWithContext, callback, false); } }; //Link user callbacks with event handlers _event_handlers.push({ userCallback: callback, contexts: contextIds, contextHandler: contextEventHandler }); // Create the CONTEXT event listener for each of the contexts for(var c in contextIds) { $(_eventBox).on("CONTEXT" + contextIds[c], contextEventHandler); } } else { //No context is set //Request all the resources if(allResourcesCanBeRequested(resources)) { multipleResourcesRequest(resources, callback, true); } else { error("Some of the resources have not information enough for an 'observe' without context or does not exist."); } } }; /** * Cancels observing for an specific callback * @param callback The callback that was given to the observe methods */ _self.data.stopObserve = function stopObserve(callback) { for (var i in _event_handlers) { if(_event_handlers[i].userCallback === callback) { for (var c in _event_handlers[i]['contexts']) { $(_eventBox).off("CONTEXT" + _event_handlers[i]['contexts'][c], _event_handlers[i]['contextHandler']); } _event_handlers.splice(i, 1); } } }; /** * Cancels observing for everything. */ _self.data.stopAllObserves = function stopAllObserves() { //Remove all the event handlers for (var i in _event_handlers) { for (var c in _event_handlers[i]['contexts']) { $(_eventBox).off("CONTEXT" + _event_handlers[i]['contexts'][c], _event_handlers[i]['contextHandler']); } } //Empty the array _event_handlers.splice(0, _event_handlers.length); }; _self.data.clear = function() { //Stop all the observes _self.data.stopAllObserves(); //Clear the resources contexts storage for(var key in _resourcesContexts) { delete _resourcesContexts[key]; } }; /** * Updates the context with the given data. * @param contextId String * @param contextData An object with the params to update. A param value of null means to delete the param from the * context, i.e the following sequence os updateContext with data {uid: 1, max:5, pid: 2} and {pid: 3, max:null} * will result in the following context: {uid: 1, pid:3} */ _self.data.updateContext = function updateContext(contextId, contextData) { if('string' !== typeof contextId) { error("Method 'updateRange' requires a string for contextId param."); return; } if(_resourcesContexts[contextId] == null) { initializeContext(contextId); } //Update values of the context (if null, remove it) var hasChanged = false; var changes = {}; var setChange = function(name, newValue) { hasChanged = true; changes[name] = newValue; }; for(var name in contextData) { //Check if that parameter exists. If not, ignore it if(_existentParametersList.indexOf(name) === -1) { warn("Parameter '" + name + "' given in updateContext does not exist."); continue; } var newValue = contextData[name]; var oldValue = _resourcesContexts[contextId]['data'][name]; // Save the changes if(newValue instanceof Array && oldValue instanceof Array ) { //Check if multiparameter arrays are identical if(newValue.length != oldValue.length) { setChange(name, newValue); } //Check all the values inside the array for(var i = 0; i < newValue.length; ++i) { if(newValue[i] != oldValue[i]){ setChange(name, newValue); break; } } } else if(newValue != oldValue) { setChange(name, newValue); } //Change the context if(newValue != null && newValue != oldValue && (!(newValue instanceof Array) || newValue.length > 0)) { _resourcesContexts[contextId]['data'][name] = newValue; } else if((newValue == null && oldValue != null) || (newValue instanceof Array && newValue.length === 0)) { delete _resourcesContexts[contextId]['data'][name]; } } //Trigger an event to indicate that the context has changed if(hasChanged) { _resourcesContexts[contextId].updateCounter++; $(_eventBox).trigger("CONTEXT" + contextId, [_resourcesContexts[contextId].updateCounter, changes, contextId]); } }; /** * Sets the dashboard controller for the framework. * @param controller */ _self.dashboard.setDashboardController = function setDashboardController(controller) { _dashboardController = controller; }; /** * Registers a new widget in this dashboard * @param newDashboard Widget object. */ _self.dashboard.registerWidget = function registerWidget(widget) { if(_dashboardController != null && _dashboardController.registerWidget != null) { _dashboardController.registerWidget(widget); } else { warn("Dashboard controller has no registerWidget method."); } }; /** * Changes the current dashboard * @param newDashboard Id of the new dashboard to visualize. * @param env Environment object. This contains all the information of the environment that the new dashboard will need. */ _self.dashboard.changeTo = function changeTo(newDashboard, env) { if(_dashboardController != null && _dashboardController.changeTo != null) { //Ask the dashboard controller to change the dashboard _dashboardController.changeTo(newDashboard, function() { //Dashboard controller is now ready to change the dashboard, so we need to change the env _dashboardEnv = ( typeof env === 'object' ? env : {} ); //Execute change listeners for(var i = 0; i < _dashboardEventListeners['change'].length; ++i) { if(typeof _dashboardEventListeners['change'][i] === 'function') { _dashboardEventListeners['change'][i](); } } }); } else { error("Dashboard controller has no changeTo method."); } }; /** * Gets the dashboard environment */ _self.dashboard.getEnv = function getEnv() { return clone(_dashboardEnv) || {}; // TODO: optimize? }; /** * Add events to the dashboard. Event available: * - change: executed when the dashboard is changed. This is also fired with the initial dashboard. * @param event * @param callback */ _self.dashboard.addEventListener = function(event, callback) { if(event === 'change' && typeof callback === 'function') { _dashboardEventListeners['change'].push(callback); } }; /** * Removes an event from the dashboard. * @param event * @param callback */ _self.dashboard.removeEventListener = function(event, callback) { if(event === 'change') { for(var i = _dashboardEventListeners['change'].length - 1; i >= 0; --i) { if(_dashboardEventListeners['change'][i] === callback) { _dashboardEventListeners['change'].splice(i,1); } } } }; /* -------------------------------- --- FRAMEWORK INITIALIZATION --- -------------------------------- */ /** * Method that makes the initial checks to determine if the framework can be initialized * @returns {boolean} */ var frameworkPreCheck = function frameworkPreCheck(){ /* CHECK SHD-API SERVER URL */ if(typeof SDH_API_URL === 'undefined'){ error("SDH_API_URL global variable must be set with the url to the SDH-API server."); return false; } _serverUrl = SDH_API_URL.trim(); if(_serverUrl.length === 0) { error("SDH_API_URL global variable must be set with a valid url to the SDH-API server."); return false; } if(_serverUrl.substr(-1) === '/') { _serverUrl = _serverUrl.substr(0, _serverUrl.length - 1); } /* CHECK JQUERY */ if (typeof jQuery == 'undefined') { error("SDH Framework requires JQuery to work properly."); return false; } return true; }; /** * Add a callback that will be executed when the framework is ready * @param callback */ var frameworkReady = function frameworkReady(callback) { if(!_isReady && typeof callback === 'function') { $(_eventBox).on("FRAMEWORK_READY", function() { $(_eventBox).off("FRAMEWORK_READY"); callback(); }); } else if(typeof callback === 'function') { callback(); } }; var isFrameworkReady = function isFrameworkReady() { return _isReady; }; var frameworkInit = function frameworkInit() { if(frameworkPreCheck()) { loadResourcesInfo(function(){ window.framework.data = _self.data; window.framework.dashboard = _self.dashboard; _isReady = true; $(_eventBox).trigger("FRAMEWORK_READY"); }); window.framework = { data: {}, widgets: {}, dashboard: {}, ready: frameworkReady, /* Method to add a callback that will be executed when the framework is ready */ isReady: isFrameworkReady }; // AMD compliant if ( typeof define === "function" && define.amd) { define( [], function () { return window.framework; } ); } } }; frameworkInit(); })();
framework.js
/* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# This file is part of the Smart Developer Hub Project: http://www.smartdeveloperhub.org/ Center for Open Middleware http://www.centeropenmiddleware.com/ #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# Copyright (C) 2015 Center for Open Middleware. #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# */ (function() { /* ------------------------------- ------ FRAMEWORK GLOBALS ------ ------------------------------- */ //Variable where public methods and variables will be stored var _self = { data: {}, widgets: {}, dashboard: {} }; //Path to the SDH-API server without the trailing slash var _serverUrl; // Array with the information about the different resources of the API var _resourcesInfo; // List of all the parameters that can be used with the API. // It is only for performance purposes while checking input. var _existentParametersList = []; // Storage of the data data var _resourcesStorage = {}; //TODO: multi-level cache var _resourcesContexts = {}; // Contains a list that links user callbacks (given as parameter at the observe methods) with the internal // callbacks. It is need to remove handlers when not used and free memory. var _event_handlers = []; // This is a variable to make the events invisible outside the framework var _eventBox = {}; // Dashboard controller var _dashboardController = null; var _dashboardEnv = {}; // This contains the listeners for each of the events of the dashboard var _dashboardEventListeners = { 'change' : [] }; var _isReady = false; var FRAMEWORK_NAME = "SDHWebFramework"; /* ------------------------------- -- FRAMEWORK PRIVATE METHODS -- ------------------------------- */ /** * Prints a framework error * @param message Message to display. */ var error = function error(message) { console.error("[" + FRAMEWORK_NAME + "] " + message); }; /** * Prints a framework warning * @param message Message to display. */ var warn = function warn(message) { console.warn("[" + FRAMEWORK_NAME + "] " + message); }; var requestJSON = function requestJSON(path, queryParams, callback, maxRetries) { if(typeof maxRetries === 'undefined'){ maxRetries = 2; //So up to 3 times will be requested } $.getJSON( _serverUrl + path, queryParams, callback).fail( function(d, textStatus, e) { error("Framework getJSON request failed\nStatus: " + textStatus + " \nError: "+ (e ? e : '-') + "\nRequested url: '"+ path+"'\nParameters: " + JSON.stringify(queryParams)); //Retry the request if (maxRetries > 0 && textStatus === "timeout") { requestJSON(path, queryParams, callback, --maxRetries); } }); }; /** * Fills _resourcesInfo hashmap with the reources info and the following structure: * { * "{resource-id}": { * path:"yourpath/../sdfsdf", * params: ['param1', 'param2'], * queryParams: ['queryParam1'] * }, * ... * } * @param onReady */ var loadResourcesInfo = function loadResourcesInfo(onReady) { requestJSON("/api/", null, function(data) { //var paths = data['swaggerjson']['paths']; var paths = [{ path :"/metrics", variable: "mid" },{ path :"/tbdata", variable: "tid" }]; var apiPaths = data['swaggerjson']['paths']; //Count number of elements in paths var pathsLength = 0; for(var i in paths) pathsLength++; //Function to check if it has finished and call the callback var pathsProcessed = 0; var pathProcessed = function() { if(++pathsProcessed === pathsLength && 'function' === typeof onReady) { onReady(); } }; //Initialize the _resourcesInfo object _resourcesInfo = {}; //var isMetricList = /\/data\/$/; //var isMetricListWithoutParams = /^((?!\{).)*\/data\/$/; //var isSpecificMetric = /\/\{mid\}$/; //TODO: I dont like this, but till now there is not any other way to get static data... var statInfo = [ // API static Information description { "id" : "userinfo", "path" : "/users/{uid}", params: {'uid': {name: 'uid',in: 'path',required: true}}, "description" : "User Information" }, { "id" : "repoinfo", "path" : "/repositories/{rid}", params: {'rid': {name: 'rid',in: 'path',required: true}}, "description" : "Repository Information" }, { "id" : "orginfo", "path" : "/", "description" : "Organization Information" }, { "id" : "userlist", "path" : "/users/", "description" : "Users List" }, { "id" : "repolist", "path" : "/repositories/", "description" : "Repository List" }, { "id" : "metriclist", "path" : "/metrics/", "description" : "Metrics list" }, { "id" : "tbdlist", "path" : "/tbd/", "description" : "Time-based data list" } ]; for(var i = statInfo.length - 1; i >= 0; --i ) { var info = statInfo[i]; _resourcesInfo[info['id']] = { path: info['path'], requiredParams: (info.params != null ? info.params : {}), //list of url param names optionalParams: {} //list of query params }; } //TODO: END TODO ---------------------------- //Iterate over the path of the api for(var x = paths.length - 1; x >= 0; --x ) { var path = paths[x]['path']; // Make an api request to retrieve all the data requestJSON(path, null, function(p, data) { //Iterate over the resources for(var j = 0, len = data.length; j < len; ++j) { var resourceInfo = data[j]; var resourceId = resourceInfo['id']; var resourcePath = resourceInfo['path']; // Fill the _resourcesInfo array _resourcesInfo[resourceId] = { path: resourcePath, requiredParams: {}, //list of url param names optionalParams: {} //list of query params }; //Get the general resource path info (like /data/{mid}) var generalResourcePath = resourcePath.substring(0, resourcePath.lastIndexOf('/')) + '/{'+paths[p]['variable']+'}'; var generalResourcePathInfo = apiPaths[generalResourcePath]; if(generalResourcePathInfo == null) { error("General resource path ("+generalResourcePathInfo+") does not exist in API path list."); continue; } //Add the url params and query params to the list if(generalResourcePathInfo['get']['parameters'] != null) { var parameters = generalResourcePathInfo['get']['parameters']; //Add all parameters and avoid 'mid' for(var i = 0, len_i = parameters.length; i < len_i; i++) { var paramName = parameters[i]['name']; //Add the parameter in params or queryParams if(paramName === paths[p]['variable']) { //Ignore it } else if (parameters[i]['required'] == true || resourceInfo['params'].indexOf(paramName) !== -1) { _resourcesInfo[resourceId]['requiredParams'][paramName] = { name: paramName, in: parameters[i]['in'], required: true }; } else if(resourceInfo['optional'].indexOf(paramName) !== -1) { _resourcesInfo[resourceId]['optionalParams'][paramName] = { name: paramName, in: parameters[i]['in'], required: false }; } //Add it to the list of possible parameters (cache) if(_existentParametersList.indexOf(parameters[i]['name']) === -1) { _existentParametersList.push(parameters[i]['name']); } } } } pathProcessed(); //Finished processing this path }.bind(null, x)); } }); }; /** * Checks if the resource object has all the information that is needed to request the resource data * @param resource A resource object. At least must have the id. Can have other parameters, like range, userId... * @returns {boolean} */ var resourceCanBeRequested = function resourceCanBeRequested(resource) { if(resource['id'] == null) { return false; } var resourceInfo = _resourcesInfo[resource['id']]; if(resourceInfo == null) { return false; } for(var paramId in resourceInfo['requiredParams']) { var paramValue = resource[paramId]; if(paramValue == null) { return false; } } return true; }; /** * Checks if all the given resources fulfill all the requirements to be requested * @param resources Array of normalized resources * @returns {boolean} */ var allResourcesCanBeRequested = function allResourcesCanBeRequested(resources) { for(var i in resources) { if(!resourceCanBeRequested(resources[i])) { return false; } } return true; }; /** * Request a given resource * @param resourceId */ var makeResourceRequest = function makeResourceRequest(resourceId, params, callback) { var resourceInfo = _resourcesInfo[resourceId]; var queryParams = {}; if(resourceInfo != null) { /* Generate path */ var path = resourceInfo.path; // Replace params in url skeleton for(var paramId in params) { var paramInfo = resourceInfo['requiredParams'][paramId] || resourceInfo['optionalParams'][paramId]; var paramValue = params[paramId]; if(paramValue == null) { //It has no value (ignore it or throw an error) if(paramInfo['required'] === true) { error("Resource '"+ resourceId + "' needs parameter '"+ paramId +"'."); return; } } else if(paramInfo['in'] === 'query') { queryParams[paramId] = paramValue; } else if(paramInfo['in'] === 'path') { path = path.replace('{'+paramId+'}', paramValue); } } /* Make the request */ requestJSON(path, queryParams, callback); } else { error("Resource '"+ resourceId + "' does not exist."); } }; /** * Requests multiple resources * @param resources Normalized resource * @param callback * @param unique Is this is a request that do not depend on any context, so it will be executed only once */ var multipleResourcesRequest = function multipleResourcesRequest(resources, callback, unique) { var completedRequests = 0; var allData = {}; var requests = []; var onResourceReady = function(resourceId, params, data) { if(allData[resourceId] == null) { allData[resourceId] = []; } //Add the framework info to the data received from the api var resUID = resourceHash(resourceId, params); var info = { UID: resUID, request: { params: params } }; allData[resourceId].push({ data: data, info: info }); if(++completedRequests === requests.length) { sendDataEventToCallback(allData, callback, unique); } }; //Send a loading data event to the listener sendLoadingEventToCallback(callback); for(var i in resources) { var resourceId = resources[i].id; var params = {}; var multiparams = []; //Fill the params and multiparams for(var name in resources[i]) { if(_resourcesInfo[resourceId]['optionalParams'][name] != null || _resourcesInfo[resourceId]['requiredParams'][name] != null) { //Is a param //Check if is multi parameter and add it to the list of multi parameters if(resources[i][name] instanceof Array) { multiparams.push(name); } params[name] = resources[i][name]; } } var requestsCombinations = generateResourceRequestParamsCombinations(resourceId, params, multiparams); requests = requests.concat(requestsCombinations); } for(var i in requests) { var resourceId = requests[i]['resourceId']; var params = requests[i]['params']; makeResourceRequest(resourceId, params, onResourceReady.bind(undefined, resourceId, params)); } }; /** * Generates an array of requests combining all the values of the multi parameters (param and queryParam). * @param resourceId * @param params Hash map of param name and values. * @param multiparam List of parameter names that have multiple values. * @returns {Array} Array of requests to execute for one resource */ var generateResourceRequestParamsCombinations = function (resourceId, params, multiparam) { var paramsCombinations = generateParamsCombinations(params, multiparam); var allCombinations = []; //Create the combinations of params and queryParams for(var i = 0, len_i = paramsCombinations.length; i < len_i; ++i) { allCombinations.push({ resourceId: resourceId, params: paramsCombinations[i] }); } return allCombinations; }; /** * Generates all the combinations of multi parameters. * @param params Hash map of param name and values. * @param multiParams List of parameter names that have multiple values. * @returns {Array} Array of parameter combinations. */ var generateParamsCombinations = function generateParamsCombinations(params, multiParams) { //Clone params before modifying them params = clone(params); if(multiParams.length > 0) { var result = []; //Clone function params before modifying them multiParams = clone(multiParams); //Remove the parameter from the list of multi parameters var param = multiParams.pop(); //Save the values of the parameter because it will be modified var values = params[param]; //For each value generate the possible combinations for(var i in values) { var value = values[i]; //Overwrite array with only one value params[param] = value; //Generate the combinations for that value var combinations = generateParamsCombinations(params, multiParams); result = result.concat(combinations); } return result; } else { //End of recursion return [ params ]; } }; /** * Converts the array of resources containing a mixture of strings (for simple resources) and objects (for complex resources) * into an array of objects with at least an id. * @param resources Array of resources containing a mixture of strings (for simple resources) and objects (for complex resources). * It can be modified, so consider cloning it if necessary. * @returns {Array} */ var normalizeResources = function normalizeResources(resources) { var newMetricsParam = []; for(var i in resources) { if('string' === typeof resources[i]) { newMetricsParam.push({id: resources[i]}); } else if('object' === typeof resources[i] && resources[i]['id']) { //Metrics objects must have an id newMetricsParam.push(resources[i]); } else { warn("One of the resources given was not string nor object so it has been ignored."); } } //Remove invalid resources and parameters newMetricsParam = cleanResources(newMetricsParam); return newMetricsParam; }; /** * Cleans an array of resource objects removing the non existent ones and the invalid parameters of them. * @param resources Array of resource objects to clean. */ var cleanResources = function cleanResources(resources) { var newResources = []; for(var i = 0; i < resources.length; ++i) { var resource = resources[i]; var resourceId = resource['id']; var resourceInfo = _resourcesInfo[resourceId]; if(resourceInfo == null) { warn("Resource '"+resourceId+"' does not exist."); } else { //Check its parameters var cleanParameters = {}; for(var paramName in resource) { if(paramName != 'id' && paramName != 'static' && resourceInfo['requiredParams'][paramName] == null && resourceInfo['optionalParams'][paramName] == null) { warn("Parameter '"+paramName+"' is not a valid parameter for resource '"+resourceId+"'."); } else { cleanParameters[paramName] = resource[paramName]; } } if(Object.keys(cleanParameters).length > 0) { newResources.push(cleanParameters); } } } return newResources; }; /** Clone the object * @obj1 Object to clone. * @return {object} */ var clone = function clone(obj1) { var result; if (obj1 == null) { return obj1; } else if (Array.isArray(obj1)) { result = []; } else if (typeof obj1 === 'object') { result = {}; } else { return obj1; } for (var key in obj1) { result[key] = clone(obj1[key]); } return result; }; /** * Deep merge in obj1 object. (Priority obj2) * @param obj1 * @param obj2 * @param mergeArrays If true, combines arrays. Otherwise, if two arrays must be merged, * the obj2's array overwrites the other. Default: true. * @returns {*} */ var mergeObjects = function mergeObjects(obj1, obj2, mergeArrays) { mergeArrays = mergeArrays || true; if (Array.isArray(obj2) && Array.isArray(obj1) && mergeArrays) { // Merge Arrays var i; for (i = 0; i < obj2.length; i++) { if (typeof obj2[i] === 'object' && typeof obj1[i] === 'object') { obj1[i] = mergeObjects(obj1[i], obj2[i], mergeArrays); } else { obj1[i] = obj2[i]; } } } else if (Array.isArray(obj2)) { // Priority obj2 obj1 = obj2; } else { // object case j for (var p in obj2) { if(obj1.hasOwnProperty(p)){ if (typeof obj2[p] === 'object' && typeof obj1[p] === 'object') { obj1[p] = mergeObjects(obj1[p], obj2[p], mergeArrays); } else { obj1[p] = obj2[p]; } } else { obj1[p] = obj2[p]; } } } return obj1; }; /** * Generates a hashcode given an string * @param str * @returns {number} 32 bit integer */ var hashCode = function hashCode(str) { var hash = 0, i, chr, len; if (str.length == 0) return hash; for (i = 0, len = str.length; i < len; i++) { chr = str.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; var resourceHash = function resourceHash(resourceId, requestParams){ var str = resourceId; var hasheable = ""; for(var i in _resourcesInfo[resourceId]['requiredParams']){ var param = _resourcesInfo[resourceId]['requiredParams'][i]['name']; hasheable += param + requestParams[param] + ";" } return resourceId + "#" + hashCode(hasheable).toString(16); }; /** * Combines an incomplete resource with a context in order to create a complete resource to make a request with. * @param resources * @param contexts Context ids */ var combineResourcesWithContexts = function combineResourcesWithContexts(resources, contexts) { var newResources = []; var contextsData = []; //Fill the array with data for each context for(var i in contexts) { contextsData.push(_resourcesContexts[contexts[i]]['data']); } //Iterate through the resources and combine them with the contexts for(var i in resources) { //Clone the resource object to avoid modification var resource = clone(resources[i]); //Modify the resource with all the contexts for(var c in contextsData) { //Clean the context var mergeContext = getCleanContextByResource(contextsData[c], resource); resource = mergeObjects(resource, mergeContext, false); } //Add the resource to the returned array newResources.push(resource); } return newResources; }; /** * Initializes the context container for the given contextId * @param contextId */ var initializeContext = function initializeContext(contextId) { _resourcesContexts[contextId] = { updateCounter: 0, data: {} }; }; /** * Gets a new context with only the params and query params accepted by the resource (taking into account the static * params). * @param context Object * @param resource A resource object (only id and static are used). */ var getCleanContextByResource = function getCleanContextByResource(context, resource) { var newContext = {}; var resourceInfo = _resourcesInfo[resource['id']]; var statics; if(resource['static'] != null){ statics = resource['static']; } else { statics = []; } //Add all the params this resource accepts for(var name in resourceInfo['requiredParams']) { if(context[name] !== undefined && statics.indexOf(name) === -1){ newContext[name] = context[name]; } } //Add all the query params this resource accepts for(var name in resourceInfo['optionalParams']) { if(context[name] !== undefined && statics.indexOf(name) === -1){ newContext[name] = context[name]; } } return newContext; }; /** * Checks if the given object is empty * @param o Object to check. * @returns {boolean} True if empty; false otherwise. */ var isObjectEmpty = function isObjectEmpty(o) { for(var i in o) return false; return true; }; /** * Send a data event to the given observer. This means that the data the framework was loading is now ready. * @param data New data. * @param callback * @param unique Is this is a request that do not depend on any context, so it will be executed only once */ var sendDataEventToCallback = function sendDataEventToCallback(data, callback, unique) { if(typeof callback === "function") { var observed = false; if(!unique) { //Check if it still is being observed for (var i in _event_handlers) { if (_event_handlers[i].userCallback === callback) { observed = true; break; } } } else { observed = true; } if(observed) { callback({ event: "data", data: data }); } } }; /** * Send a loading event to the given observer. That means that the framework is loading new data for that observer. * @param callback */ var sendLoadingEventToCallback = function sendLoadingEventToCallback(callback) { callback({ event: "loading" }); }; /* ------------------------------- -- FRAMEWORK PUBLIC METHODS --- ------------------------------- */ /** * * @param resources Array with resources. Each resource can be an String or an Object. The object must have the following * format: { * id: String, * <param1Id>: String, * <paramxId>: String, * } * For example: { * id: "usercommits", * uid: "pepito", * from : new Date(), * max: 0, * static: ["from"] //Static makes this parameter unalterable by the context changes. * //Static parameters must have a value; otherwise, an error will be returned. * } * @param callback Callback that receives an object containing at least an "event" that can be "data" or "loading". * - loading means that the framework is retrieving new data for the observer. * - data means that the new data is ready and can be accessed through the "data" element of the object returned to * the callback. The "data" element of the object is a hashmap using as key the resourceId of the requested resources * and as value an array with data for each of the request done for that resourceId. * @param contextIds Array of context ids. */ _self.data.observe = function observe(resources, callback, contextIds) { if('function' !== typeof callback){ error("Method 'observeData' requires a valid callback function."); return; } if(!Array.isArray(resources) || resources.length === 0 ) { error("Method 'observeData' has received an invalid resources parameter."); return; } if(contextIds != null && !(contextIds instanceof Array) ) { error("Method 'observeData' expects contextIds parameter to be null or an array."); return; } //Normalize the array of resources resources = normalizeResources(resources); if(resources.length === 0) { warn("No resources to observe."); return; } //Check that static parameters have their value defined in the resource for(var i = 0; i < resources.length; ++i) { if(resources[i]['static'] != null && resources[i]['static'].length > 0) { for(var s = 0; s < resources[i]['static'].length; ++s) { var staticParam = resources[i]['static'][s]; if(resources[i][staticParam] == null) { error("Static parameter '"+staticParam+"' must have its value defined."); return; } } } } //Is an Array, verify that it only contains strings if(contextIds instanceof Array) { //We will use it internally, so we need to clone it to prevent the user changing it contextIds = clone(contextIds); //If one of the contexts is not an string, remove it from the array for(var i = 0; i < contextIds.length; ++i) { if(typeof contextIds[i] != 'string') { contextIds.splice(i, 1); } } } else { //Invalid parameter type (or null) contextIds = [] } //Initialize contexts it they are not initialized for(var i = 0; i < contextIds.length; ++i) { if (_resourcesContexts[contextIds[i]] == null) { initializeContext(contextIds[i]); } } //If contexts are defined, combine the resources with the context in order to create more complete resources that could // be requested. if(contextIds.length > 0) { //Combine the resources with the context in order to create more complete resources that could be requested. var resourcesWithContext = combineResourcesWithContexts(resources, contextIds); //Request all the resources if possible if(allResourcesCanBeRequested(resourcesWithContext)) { multipleResourcesRequest(resourcesWithContext, callback, false); } //Create the CONTEXT event handler var contextEventHandler = function(event, contextCounter, contextChanges, contextId) { //If it is not the last context event launched, ignore the data because there is another more recent // event being executed if(contextCounter != _resourcesContexts[contextId]['updateCounter']){ return; } //Check if the changes affect to the resources var affectedResources = []; for(var i in resources) { var cleanContextChanges = getCleanContextByResource(contextChanges, resources[i]); if(!isObjectEmpty(cleanContextChanges)){ affectedResources.push(resources[i]); } } if(affectedResources.length === 0) { return; //The context change did not affect to none the resources } //TODO: when implementing the cache, affectedResources should be used to only request the changed resources. //Currently, as there is no cache, all the data must be requested because it is not stored anywhere. //Update the resources with the context data var resourcesWithContext = combineResourcesWithContexts(resources, contextIds); if(allResourcesCanBeRequested(resourcesWithContext)) { multipleResourcesRequest(resourcesWithContext, callback, false); } }; //Link user callbacks with event handlers _event_handlers.push({ userCallback: callback, contexts: contextIds, contextHandler: contextEventHandler }); // Create the CONTEXT event listener for each of the contexts for(var c in contextIds) { $(_eventBox).on("CONTEXT" + contextIds[c], contextEventHandler); } } else { //No context is set //Request all the resources if(allResourcesCanBeRequested(resources)) { multipleResourcesRequest(resources, callback, true); } else { error("Some of the resources have not information enough for an 'observe' without context or does not exist."); } } }; /** * Cancels observing for an specific callback * @param callback The callback that was given to the observe methods */ _self.data.stopObserve = function stopObserve(callback) { for (var i in _event_handlers) { if(_event_handlers[i].userCallback === callback) { for (var c in _event_handlers[i]['contexts']) { $(_eventBox).off("CONTEXT" + _event_handlers[i]['contexts'][c], _event_handlers[i]['contextHandler']); } _event_handlers.splice(i, 1); } } }; /** * Cancels observing for everything. */ _self.data.stopAllObserves = function stopAllObserves() { //Remove all the event handlers for (var i in _event_handlers) { for (var c in _event_handlers[i]['contexts']) { $(_eventBox).off("CONTEXT" + _event_handlers[i]['contexts'][c], _event_handlers[i]['contextHandler']); } } //Empty the array _event_handlers.splice(0, _event_handlers.length); }; _self.data.clear = function() { //Stop all the observes _self.data.stopAllObserves(); //Clear the resources contexts storage for(var key in _resourcesContexts) { delete _resourcesContexts[key]; } }; /** * Updates the context with the given data. * @param contextId String * @param contextData An object with the params to update. A param value of null means to delete the param from the * context, i.e the following sequence os updateContext with data {uid: 1, max:5, pid: 2} and {pid: 3, max:null} * will result in the following context: {uid: 1, pid:3} */ _self.data.updateContext = function updateContext(contextId, contextData) { if('string' !== typeof contextId) { error("Method 'updateRange' requires a string for contextId param."); return; } if(_resourcesContexts[contextId] == null) { initializeContext(contextId); } //Update values of the context (if null, remove it) var hasChanged = false; var changes = {}; var setChange = function(name, newValue) { hasChanged = true; changes[name] = newValue; }; for(var name in contextData) { //Check if that parameter exists. If not, ignore it if(_existentParametersList.indexOf(name) === -1) { warn("Parameter '" + name + "' given in updateContext does not exist."); continue; } var newValue = contextData[name]; var oldValue = _resourcesContexts[contextId]['data'][name]; // Save the changes if(newValue instanceof Array && oldValue instanceof Array ) { //Check if multiparameter arrays are identical if(newValue.length != oldValue.length) { setChange(name, newValue); } //Check all the values inside the array for(var i = 0; i < newValue.length; ++i) { if(newValue[i] != oldValue[i]){ setChange(name, newValue); break; } } } else if(newValue != oldValue) { setChange(name, newValue); } //Change the context if(newValue != null && newValue != oldValue && (!(newValue instanceof Array) || newValue.length > 0)) { _resourcesContexts[contextId]['data'][name] = newValue; } else if((newValue == null && oldValue != null) || (newValue instanceof Array && newValue.length === 0)) { delete _resourcesContexts[contextId]['data'][name]; } } //Trigger an event to indicate that the context has changed if(hasChanged) { _resourcesContexts[contextId].updateCounter++; $(_eventBox).trigger("CONTEXT" + contextId, [_resourcesContexts[contextId].updateCounter, changes, contextId]); } }; /** * Sets the dashboard controller for the framework. * @param controller */ _self.dashboard.setDashboardController = function setDashboardController(controller) { _dashboardController = controller; }; /** * Registers a new widget in this dashboard * @param newDashboard Widget object. */ _self.dashboard.registerWidget = function registerWidget(widget) { if(_dashboardController != null && _dashboardController.registerWidget != null) { _dashboardController.registerWidget(widget); } else { warn("Dashboard controller has no registerWidget method."); } }; /** * Changes the current dashboard * @param newDashboard Id of the new dashboard to visualize. * @param env Environment object. This contains all the information of the environment that the new dashboard will need. */ _self.dashboard.changeTo = function changeTo(newDashboard, env) { if(_dashboardController != null && _dashboardController.changeTo != null) { //Ask the dashboard controller to change the dashboard _dashboardController.changeTo(newDashboard, function() { //Dashboard controller is now ready to change the dashboard, so we need to change the env _dashboardEnv = ( typeof env === 'object' ? env : {} ); //Execute change listeners for(var i = 0; i < _dashboardEventListeners['change'].length; ++i) { if(typeof _dashboardEventListeners['change'][i] === 'function') { _dashboardEventListeners['change'][i](); } } }); } else { error("Dashboard controller has no changeTo method."); } }; /** * Gets the dashboard environment */ _self.dashboard.getEnv = function getEnv() { return clone(_dashboardEnv) || {}; // TODO: optimize? }; /** * Add events to the dashboard. Event available: * - change: executed when the dashboard is changed. This is also fired with the initial dashboard. * @param event * @param callback */ _self.dashboard.addEventListener = function(event, callback) { if(event === 'change' && typeof callback === 'function') { _dashboardEventListeners['change'].push(callback); } }; /** * Removes an event from the dashboard. * @param event * @param callback */ _self.dashboard.removeEventListener = function(event, callback) { if(event === 'change') { for(var i = _dashboardEventListeners['change'].length - 1; i >= 0; --i) { if(_dashboardEventListeners['change'][i] === callback) { _dashboardEventListeners['change'].splice(i,1); } } } }; /* -------------------------------- --- FRAMEWORK INITIALIZATION --- -------------------------------- */ /** * Method that makes the initial checks to determine if the framework can be initialized * @returns {boolean} */ var frameworkPreCheck = function frameworkPreCheck(){ /* CHECK SHD-API SERVER URL */ if(typeof SDH_API_URL === 'undefined'){ error("SDH_API_URL global variable must be set with the url to the SDH-API server."); return false; } _serverUrl = SDH_API_URL.trim(); if(_serverUrl.length === 0) { error("SDH_API_URL global variable must be set with a valid url to the SDH-API server."); return false; } if(_serverUrl.substr(-1) === '/') { _serverUrl = _serverUrl.substr(0, _serverUrl.length - 1); } /* CHECK JQUERY */ if (typeof jQuery == 'undefined') { error("SDH Framework requires JQuery to work properly."); return false; } return true; }; /** * Add a callback that will be executed when the framework is ready * @param callback */ var frameworkReady = function frameworkReady(callback) { if(!_isReady && typeof callback === 'function') { $(_eventBox).on("FRAMEWORK_READY", function() { $(_eventBox).off("FRAMEWORK_READY"); callback(); }); } else if(typeof callback === 'function') { callback(); } }; var isFrameworkReady = function isFrameworkReady() { return _isReady; }; var frameworkInit = function frameworkInit() { if(frameworkPreCheck()) { loadResourcesInfo(function(){ window.framework.data = _self.data; window.framework.dashboard = _self.dashboard; _isReady = true; $(_eventBox).trigger("FRAMEWORK_READY"); }); window.framework = { data: {}, widgets: {}, dashboard: {}, ready: frameworkReady, /* Method to add a callback that will be executed when the framework is ready */ isReady: isFrameworkReady }; // AMD compliant if ( typeof define === "function" && define.amd) { define( [], function () { return window.framework; } ); } } }; frameworkInit(); })();
[Framework] Added aggr to the hasheable parameters of the resource
framework.js
[Framework] Added aggr to the hasheable parameters of the resource
<ide><path>ramework.js <ide> <ide> <ide> var resourceHash = function resourceHash(resourceId, requestParams){ <del> <add> //TODO: loadResourcesInfo should set the list of hasheable parameters <ide> var str = resourceId; <ide> var hasheable = ""; <ide> for(var i in _resourcesInfo[resourceId]['requiredParams']){ <ide> var param = _resourcesInfo[resourceId]['requiredParams'][i]['name']; <ide> hasheable += param + requestParams[param] + ";" <add> } <add> <add> if(requestParams['aggr'] != null) { <add> hasheable += 'aggr' + requestParams['aggr'] + ";" <ide> } <ide> <ide> return resourceId + "#" + hashCode(hasheable).toString(16);
Java
apache-2.0
9b3a5095ac8184a8eb2c769ea2e8e97bce044627
0
vrozov/incubator-apex-core,vrozov/apex-core,deepak-narkhede/apex-core,sandeshh/incubator-apex-core,tushargosavi/apex-core,deepak-narkhede/apex-core,tweise/apex-core,andyperlitch/incubator-apex-core,brightchen/incubator-apex-core,brightchen/apex-core,PramodSSImmaneni/incubator-apex-core,brightchen/apex-core,tushargosavi/incubator-apex-core,devtagare/incubator-apex-core,tweise/incubator-apex-core,mattqzhang/apex-core,vrozov/apex-core,simplifi-it/otterx,tweise/apex-core,devtagare/incubator-apex-core,simplifi-it/otterx,amberarrow/incubator-apex-core,mattqzhang/apex-core,vrozov/incubator-apex-core,brightchen/incubator-apex-core,PramodSSImmaneni/apex-core,sandeshh/apex-core,amberarrow/incubator-apex-core,sandeshh/apex-core,tweise/incubator-apex-core,simplifi-it/otterx,apache/incubator-apex-core,tweise/apex-core,tushargosavi/apex-core,mt0803/incubator-apex-core,mattqzhang/apex-core,PramodSSImmaneni/incubator-apex-core,apache/incubator-apex-core,PramodSSImmaneni/incubator-apex-core,MalharJenkins/incubator-apex-core,PramodSSImmaneni/apex-core,tushargosavi/incubator-apex-core,vrozov/apex-core,ishark/incubator-apex-core,sandeshh/incubator-apex-core,devtagare/incubator-apex-core,ishark/incubator-apex-core,sandeshh/apex-core,ishark/incubator-apex-core,MalharJenkins/incubator-apex-core,sandeshh/incubator-apex-core,vrozov/incubator-apex-core,deepak-narkhede/apex-core,PramodSSImmaneni/apex-core,brightchen/apex-core,apache/incubator-apex-core,andyperlitch/incubator-apex-core,aniruddhas/incubator-apex-core,klynchDS/incubator-apex-core,tushargosavi/apex-core,aniruddhas/incubator-apex-core,chinmaykolhatkar/incubator-apex-core,mt0803/incubator-apex-core,klynchDS/incubator-apex-core,chinmaykolhatkar/incubator-apex-core,chinmaykolhatkar/incubator-apex-core,tushargosavi/incubator-apex-core,tweise/incubator-apex-core
/* * Copyright (c) 2012-2013 DataTorrent, Inc. * All Rights Reserved. */ package com.datatorrent.stram; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetSocketAddress; import java.net.URI; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; import static java.lang.Thread.sleep; import javax.xml.bind.annotation.XmlElement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.service.CompositeService; import org.apache.hadoop.yarn.api.ApplicationConstants; import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse; import org.apache.hadoop.yarn.api.protocolrecords.FinishApplicationMasterRequest; import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterResponse; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.client.api.AMRMClient; import org.apache.hadoop.yarn.client.api.AMRMClient.ContainerRequest; import org.apache.hadoop.yarn.client.api.YarnClient; import org.apache.hadoop.yarn.client.api.async.NMClientAsync; import org.apache.hadoop.yarn.client.api.async.impl.NMClientAsyncImpl; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.ConverterUtils; import org.apache.hadoop.yarn.util.Records; import org.apache.hadoop.yarn.util.SystemClock; import org.apache.hadoop.yarn.webapp.WebApp; import org.apache.hadoop.yarn.webapp.WebApps; import com.datatorrent.api.AttributeMap; import com.datatorrent.api.DAGContext; import com.datatorrent.stram.StreamingContainerManager.ContainerResource; import com.datatorrent.stram.api.BaseContext; import com.datatorrent.stram.api.StramEvent; import com.datatorrent.stram.license.License; import com.datatorrent.stram.license.LicensingAgentClient; import com.datatorrent.stram.plan.logical.LogicalPlan; import com.datatorrent.stram.plan.physical.OperatorStatus.PortStatus; import com.datatorrent.stram.plan.physical.PTContainer; import com.datatorrent.stram.plan.physical.PTOperator; import com.datatorrent.stram.security.StramDelegationTokenManager; import com.datatorrent.stram.security.StramWSFilterInitializer; import com.datatorrent.stram.webapp.AppInfo; import com.datatorrent.stram.webapp.StramWebApp; import com.google.common.collect.Maps; /** * Streaming Application Master * * @since 0.3.2 */ public class StramAppMasterService extends CompositeService { private static final Logger LOG = LoggerFactory.getLogger(StramAppMasterService.class); private static final long DELEGATION_KEY_UPDATE_INTERVAL = 24 * 60 * 60 * 1000; private static final long DELEGATION_TOKEN_MAX_LIFETIME = 365 * 24 * 60 * 60 * 1000; private static final long DELEGATION_TOKEN_RENEW_INTERVAL = 365 * 24 * 60 * 60 * 1000; private static final long DELEGATION_TOKEN_REMOVER_SCAN_INTERVAL = 24 * 60 * 60 * 1000; private static final int NUMBER_MISSED_HEARTBEATS = 30; private AMRMClient<ContainerRequest> amRmClient; private NMClientAsync nmClient; private LogicalPlan dag; // Application Attempt Id ( combination of attemptId and fail count ) final private ApplicationAttemptId appAttemptID; // Hostname of the container private final String appMasterHostname = ""; // Tracking url to which app master publishes info for clients to monitor private String appMasterTrackingUrl = ""; // Simple flag to denote whether all works is done private boolean appDone = false; // Counter for completed containers ( complete denotes successful or failed ) private final AtomicInteger numCompletedContainers = new AtomicInteger(); // Containers that the RM has allocated to us private final Map<String, Container> allAllocatedContainers = new HashMap<String, Container>(); // Count of failed containers private final AtomicInteger numFailedContainers = new AtomicInteger(); private final ConcurrentLinkedQueue<Runnable> pendingTasks = new ConcurrentLinkedQueue<Runnable>(); // Launch threads // private final List<Thread> launchThreads = new ArrayList<Thread>(); // child container callback private StreamingContainerParent heartbeatListener; private StreamingContainerManager dnmgr; private final Clock clock = new SystemClock(); private final long startTime = clock.getTime(); private final ClusterAppStats stats = new ClusterAppStats(); private StramDelegationTokenManager delegationTokenManager = null; private LicensingAgentClient licenseClient; public StramAppMasterService(ApplicationAttemptId appAttemptID) { super(StramAppMasterService.class.getName()); this.appAttemptID = appAttemptID; } /** * Overrides getters to pull live info. */ protected class ClusterAppStats extends AppInfo.AppStats { @Override public int getAllocatedContainers() { return allAllocatedContainers.size(); } @Override public int getPlannedContainers() { return dnmgr.getPhysicalPlan().getContainers().size(); } @Override @XmlElement public int getFailedContainers() { return numFailedContainers.get(); } @Override public int getNumOperators() { return dnmgr.getPhysicalPlan().getAllOperators().size(); } @Override public long getCurrentWindowId() { long min = Long.MAX_VALUE; for (Map.Entry<Integer, PTOperator> entry : dnmgr.getPhysicalPlan().getAllOperators().entrySet()) { long windowId = entry.getValue().stats.currentWindowId.get(); if (min > windowId) { min = windowId; } } return StreamingContainerManager.toWsWindowId(min == Long.MAX_VALUE ? 0 : min); } @Override public long getRecoveryWindowId() { return StreamingContainerManager.toWsWindowId(dnmgr.getCommittedWindowId()); } @Override public long getTuplesProcessedPSMA() { long result = 0; for (Map.Entry<Integer, PTOperator> entry : dnmgr.getPhysicalPlan().getAllOperators().entrySet()) { result += entry.getValue().stats.tuplesProcessedPSMA.get(); } return result; } @Override public long getTotalTuplesProcessed() { long result = 0; for (Map.Entry<Integer, PTOperator> entry : dnmgr.getPhysicalPlan().getAllOperators().entrySet()) { result += entry.getValue().stats.totalTuplesProcessed.get(); } return result; } @Override public long getTuplesEmittedPSMA() { long result = 0; for (Map.Entry<Integer, PTOperator> entry : dnmgr.getPhysicalPlan().getAllOperators().entrySet()) { result += entry.getValue().stats.tuplesEmittedPSMA.get(); } return result; } @Override public long getTotalTuplesEmitted() { long result = 0; for (Map.Entry<Integer, PTOperator> entry : dnmgr.getPhysicalPlan().getAllOperators().entrySet()) { result += entry.getValue().stats.totalTuplesEmitted.get(); } return result; } @Override public long getTotalMemoryAllocated() { long result = 0; for (PTContainer c : dnmgr.getPhysicalPlan().getContainers()) { result += c.getAllocatedMemoryMB(); } return result; } @Override public long getTotalBufferServerReadBytesPSMA() { long result = 0; for (Map.Entry<Integer, PTOperator> entry : dnmgr.getPhysicalPlan().getAllOperators().entrySet()) { for (Map.Entry<String, PortStatus> portEntry : entry.getValue().stats.inputPortStatusList.entrySet()) { result += portEntry.getValue().bufferServerBytesPSMA.getAvg(); } } return result; } @Override public long getTotalBufferServerWriteBytesPSMA() { long result = 0; for (Map.Entry<Integer, PTOperator> entry : dnmgr.getPhysicalPlan().getAllOperators().entrySet()) { for (Map.Entry<String, PortStatus> portEntry : entry.getValue().stats.outputPortStatusList.entrySet()) { result += portEntry.getValue().bufferServerBytesPSMA.getAvg(); } } return result; } @Override public List<Integer> getCriticalPath() { StreamingContainerManager.CriticalPathInfo criticalPathInfo = dnmgr.getCriticalPathInfo(); return (criticalPathInfo == null) ? null : criticalPathInfo.path; } @Override public long getLatency() { StreamingContainerManager.CriticalPathInfo criticalPathInfo = dnmgr.getCriticalPathInfo(); return (criticalPathInfo == null) ? 0 : criticalPathInfo.latency; } } private class ClusterAppContextImpl extends BaseContext implements StramAppContext { private ClusterAppContextImpl() { super(null, null); } ClusterAppContextImpl(AttributeMap attributes) { super(attributes, null); } @Override public ApplicationId getApplicationID() { return appAttemptID.getApplicationId(); } @Override public ApplicationAttemptId getApplicationAttemptId() { return appAttemptID; } @Override public String getApplicationName() { return getValue(LogicalPlan.APPLICATION_NAME); } @Override public long getStartTime() { return startTime; } @Override public String getApplicationPath() { return getValue(LogicalPlan.APPLICATION_PATH); } @Override public CharSequence getUser() { return System.getenv(ApplicationConstants.Environment.USER.toString()); } @Override public Clock getClock() { return clock; } @Override public String getAppMasterTrackingUrl() { return appMasterTrackingUrl; } @Override public ClusterAppStats getStats() { return stats; } @Override public String getGatewayAddress() { return getValue(LogicalPlan.GATEWAY_ADDRESS); } @Override public String getLicenseId() { return StramAppMasterService.this.licenseClient.getLicenseId(); } @Override public long getRemainingLicensedMB() { return StramAppMasterService.this.licenseClient.getRemainingLicensedMB(); } @Override public long getTotalLicensedMB() { return StramAppMasterService.this.licenseClient.getTotalLicensedMB(); } @Override public long getAllocatedMB() { return StramAppMasterService.this.licenseClient.getAllocatedMB(); } @Override public long getLicenseInfoLastUpdate() { return StramAppMasterService.this.licenseClient.getLicenseInfoLastUpdate(); } @SuppressWarnings("FieldNameHidesFieldInSuperclass") private static final long serialVersionUID = 201309112304L; } /** * Dump out contents of $CWD and the environment to stdout for debugging */ @SuppressWarnings("UseOfSystemOutOrSystemErr") public void dumpOutDebugInfo() { LOG.info("Dump debug output"); Map<String, String> envs = System.getenv(); LOG.info("\nDumping System Env: begin"); for (Map.Entry<String, String> env : envs.entrySet()) { LOG.info("System env: key=" + env.getKey() + ", val=" + env.getValue()); } LOG.info("Dumping System Env: end"); String cmd = "ls -al"; Runtime run = Runtime.getRuntime(); Process pr; try { pr = run.exec(cmd); pr.waitFor(); BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line; LOG.info("\nDumping files in local dir: begin"); try { while ((line = buf.readLine()) != null) { LOG.info("System CWD content: " + line); } LOG.info("Dumping files in local dir: end"); } finally { buf.close(); } } catch (IOException e) { LOG.debug("Exception", e); } catch (InterruptedException e) { LOG.info("Interrupted", e); } LOG.info("Classpath: {}", System.getProperty("java.class.path")); LOG.info("Config resources: {}", getConfig().toString()); try { // find a better way of logging this using the logger. Configuration.dumpConfiguration(getConfig(), new PrintWriter(System.out)); } catch (Exception e) { LOG.error("Error dumping configuration.", e); } } @Override protected void serviceInit(Configuration conf) throws Exception { LOG.info("Application master" + ", appId=" + appAttemptID.getApplicationId().getId() + ", clustertimestamp=" + appAttemptID.getApplicationId().getClusterTimestamp() + ", attemptId=" + appAttemptID.getAttemptId()); FileInputStream fis = new FileInputStream("./" + LogicalPlan.SER_FILE_NAME); try { this.dag = LogicalPlan.read(fis); } finally { fis.close(); } // "debug" simply dumps all data using LOG.info if (dag.isDebug()) { dumpOutDebugInfo(); } FSRecoveryHandler recoveryHandler = new FSRecoveryHandler(dag.assertAppPath(), conf); this.dnmgr = StreamingContainerManager.getInstance(recoveryHandler, dag, true); dag = this.dnmgr.getLogicalPlan(); LOG.info("Starting application with {} operators in {} containers", dag.getAllOperators().size(), dnmgr.getPhysicalPlan().getContainers().size()); if (UserGroupInformation.isSecurityEnabled()) { // TODO :- Need to perform token renewal delegationTokenManager = new StramDelegationTokenManager(DELEGATION_KEY_UPDATE_INTERVAL, DELEGATION_TOKEN_MAX_LIFETIME, DELEGATION_TOKEN_RENEW_INTERVAL, DELEGATION_TOKEN_REMOVER_SCAN_INTERVAL); } this.nmClient = new NMClientAsyncImpl(new NMCallbackHandler()); addService(nmClient); this.amRmClient = AMRMClient.createAMRMClient(); addService(amRmClient); // start RPC server int rpcListenerCount = dag.getValue(DAGContext.HEARTBEAT_LISTENER_THREAD_COUNT); this.heartbeatListener = new StreamingContainerParent(this.getClass().getName(), dnmgr, delegationTokenManager, rpcListenerCount); addService(heartbeatListener); // get license and prepare for license agent interaction String licenseBase64 = dag.getValue(LogicalPlan.LICENSE); if (licenseBase64 != null) { byte[] licenseBytes = Base64.decodeBase64(licenseBase64); String licenseId = License.getLicenseID(licenseBytes); this.licenseClient = new LicensingAgentClient(appAttemptID.getApplicationId(), licenseId); addService(this.licenseClient); } // initialize all services added above super.serviceInit(conf); } @Override protected void serviceStart() throws Exception { super.serviceStart(); if (delegationTokenManager != null) { delegationTokenManager.startThreads(); } // write the connect address for containers to DFS InetSocketAddress connectAddress = NetUtils.getConnectAddress(this.heartbeatListener.getAddress()); URI connectUri = new URI("stram", null, connectAddress.getHostName(), connectAddress.getPort(), null, null, null); FSRecoveryHandler recoveryHandler = new FSRecoveryHandler(dag.assertAppPath(), getConfig()); recoveryHandler.writeConnectUri(connectUri.toString()); // start web service StramAppContext appContext = new ClusterAppContextImpl(dag.getAttributes()); try { org.mortbay.log.Log.setLog(null); Configuration config = getConfig(); if (UserGroupInformation.isSecurityEnabled()) { config = new Configuration(config); config.set("hadoop.http.filter.initializers", StramWSFilterInitializer.class.getCanonicalName()); } WebApp webApp = WebApps.$for("stram", StramAppContext.class, appContext, "ws").with(config).start(new StramWebApp(this.dnmgr)); LOG.info("Started web service at port: " + webApp.port()); this.appMasterTrackingUrl = NetUtils.getConnectAddress(webApp.getListenerAddress()).getHostName() + ":" + webApp.port(); LOG.info("Setting tracking URL to: " + appMasterTrackingUrl); } catch (Exception e) { LOG.error("Webapps failed to start. Ignoring for now:", e); } } @Override protected void serviceStop() throws Exception { super.serviceStop(); if (delegationTokenManager != null) { delegationTokenManager.stopThreads(); } nmClient.stop(); amRmClient.stop(); dnmgr.teardown(); } public boolean run() throws YarnException { boolean status = true; try { StramChild.eventloop.start(); execute(); } catch (Exception re) { status = false; LOG.error("Caught Exception in execute()", re); if (re.getCause() instanceof YarnException) { throw (YarnException) re.getCause(); } } finally { StramChild.eventloop.stop(); } return status; } /** * Main run function for the application master * * @throws YarnRemoteException */ @SuppressWarnings("SleepWhileInLoop") private void execute() throws YarnException, IOException { LOG.info("Starting ApplicationMaster"); Credentials credentials = UserGroupInformation.getCurrentUser().getCredentials(); LOG.info("number of tokens: {}", credentials.getAllTokens().size()); Iterator<Token<?>> iter = credentials.getAllTokens().iterator(); while (iter.hasNext()) { Token<?> token = iter.next(); LOG.debug("token: " + token); } // Register self with ResourceManager RegisterApplicationMasterResponse response = amRmClient.registerApplicationMaster(appMasterHostname, 0, appMasterTrackingUrl); // Dump out information about cluster capability as seen by the resource manager int maxMem = response.getMaximumResourceCapability().getMemory(); LOG.info("Max mem capabililty of resources in this cluster " + maxMem); int containerMemory = dag.getContainerMemoryMB(); if (containerMemory > maxMem) { LOG.info("Container memory specified above max threshold of cluster. Using max value." + ", specified=" + containerMemory + ", max=" + maxMem); containerMemory = maxMem; } // for locality relaxation fall back Map<StramChildAgent.ContainerStartRequest, Integer> requestedResources = Maps.newHashMap(); // Setup heartbeat emitter // TODO poll RM every now and then with an empty request to let RM know that we are alive // The heartbeat interval after which an AM is timed out by the RM is defined by a config setting: // RM_AM_EXPIRY_INTERVAL_MS with default defined by DEFAULT_RM_AM_EXPIRY_INTERVAL_MS // The allocate calls to the RM count as heartbeat so, for now, this additional heartbeat emitter // is not required. // Setup ask for containers from RM // Send request for containers to RM // Until we get our fully allocated quota, we keep on polling RM for containers // Keep looping until all containers finished processing // ( regardless of success/failure). int loopCounter = -1; List<ContainerId> releasedContainers = new ArrayList<ContainerId>(); int numTotalContainers = 0; // keep track of already requested containers to not request them again while waiting for allocation int numRequestedContainers = 0; int nextRequestPriority = 0; ResourceRequestHandler resourceRequestor = new ResourceRequestHandler(); try { // YARN-435 // we need getClusterNodes to populate the initial node list, // subsequent updates come through the heartbeat response YarnClient clientRMService = YarnClient.createYarnClient(); clientRMService.init(getConfig()); clientRMService.start(); resourceRequestor.updateNodeReports(clientRMService.getNodeReports()); clientRMService.stop(); } catch (Exception e) { throw new RuntimeException("Failed to retrieve cluster nodes report.", e); } // check for previously allocated containers // as of 2.2, containers won't survive AM restart, but this will change in the future - YARN-1490 checkContainerStatus(); int availableLicensedMemory = (licenseClient != null) ? 0 : Integer.MAX_VALUE; while (!appDone) { loopCounter++; Runnable r; while ((r = this.pendingTasks.poll()) != null) { r.run(); } // log current state /* * LOG.info("Current application state: loop=" + loopCounter + ", appDone=" + appDone + ", total=" + * numTotalContainers + ", requested=" + numRequestedContainers + ", completed=" + numCompletedContainers + * ", failed=" + numFailedContainers + ", currentAllocated=" + this.allAllocatedContainers.size()); */ // Sleep before each loop when asking RM for containers // to avoid flooding RM with spurious requests when it // need not have any available containers try { sleep(1000); } catch (InterruptedException e) { LOG.info("Sleep interrupted " + e.getMessage()); } // Setup request to be sent to RM to allocate containers List<ContainerRequest> containerRequests = new ArrayList<ContainerRequest>(); // request containers for pending deploy requests if (!dnmgr.containerStartRequests.isEmpty()) { boolean requestResources = true; if (licenseClient != null) { // ensure enough memory is left to request new container licenseClient.reportAllocatedMemory((int)stats.getTotalMemoryAllocated()); availableLicensedMemory = licenseClient.getRemainingEnforcementMB(); int requiredMemory = dnmgr.containerStartRequests.size() * containerMemory; if (requiredMemory > availableLicensedMemory) { LOG.warn("Insufficient licensed memory to request resources required {}m available {}m", requiredMemory, availableLicensedMemory); requestResources = false; } } if (requestResources) { StramChildAgent.ContainerStartRequest csr; while ((csr = dnmgr.containerStartRequests.poll()) != null) { csr.container.setResourceRequestPriority(nextRequestPriority++); requestedResources.put(csr, loopCounter); containerRequests.add(resourceRequestor.createContainerRequest(csr, containerMemory,true)); numTotalContainers++; numRequestedContainers++; } } } if (!requestedResources.isEmpty()) { //resourceRequestor.clearNodeMapping(); for (Map.Entry<StramChildAgent.ContainerStartRequest, Integer> entry : requestedResources.entrySet()) { if ((loopCounter - entry.getValue()) > NUMBER_MISSED_HEARTBEATS) { entry.setValue(loopCounter); StramChildAgent.ContainerStartRequest csr = entry.getKey(); containerRequests.add(resourceRequestor.createContainerRequest(csr, containerMemory,false)); } } } AllocateResponse amResp = sendContainerAskToRM(containerRequests, releasedContainers); releasedContainers.clear(); // CDH reporting incorrect resources, see SPOI-1846. Workaround for now. //int availableMemory = Math.min(amResp.getAvailableResources().getMemory(), availableLicensedMemory); int availableMemory = availableLicensedMemory; dnmgr.getPhysicalPlan().setAvailableResources(availableMemory); // Retrieve list of allocated containers from the response List<Container> newAllocatedContainers = amResp.getAllocatedContainers(); // LOG.info("Got response from RM for container ask, allocatedCnt=" + newAllocatedContainers.size()); numRequestedContainers -= newAllocatedContainers.size(); long timestamp = System.currentTimeMillis(); for (Container allocatedContainer : newAllocatedContainers) { LOG.info("Got new container." + ", containerId=" + allocatedContainer.getId() + ", containerNode=" + allocatedContainer.getNodeId() + ", containerNodeURI=" + allocatedContainer.getNodeHttpAddress() + ", containerResourceMemory" + allocatedContainer.getResource().getMemory() + ", priority" + allocatedContainer.getPriority()); // + ", containerToken" + allocatedContainer.getContainerToken().getIdentifier().toString()); boolean alreadyAllocated = true; StramChildAgent.ContainerStartRequest csr = null; for (Map.Entry<StramChildAgent.ContainerStartRequest, Integer> entry : requestedResources.entrySet()) { if(entry.getKey().container.getResourceRequestPriority() == allocatedContainer.getPriority().getPriority()){ alreadyAllocated = false; csr = entry.getKey(); break; } } if (alreadyAllocated) { LOG.debug("Releasing {} as resource with priority {} was already assigned", allocatedContainer.getId(), allocatedContainer.getPriority()); releasedContainers.add(allocatedContainer.getId()); continue; } if(csr != null) requestedResources.remove(csr); // allocate resource to container ContainerResource resource = new ContainerResource(allocatedContainer.getPriority().getPriority(), allocatedContainer.getId().toString(), allocatedContainer.getNodeId().toString(), allocatedContainer.getResource().getMemory(), allocatedContainer.getNodeHttpAddress()); StramChildAgent sca = dnmgr.assignContainer(resource, null); { // record container start event StramEvent ev = new StramEvent.StartContainerEvent(allocatedContainer.getId().toString(), allocatedContainer.getNodeId().toString()); ev.setTimestamp(timestamp); dnmgr.recordEventAsync(ev); } if (sca == null) { // allocated container no longer needed, add release request LOG.warn("Container {} allocated but nothing to deploy, going to release this container.", allocatedContainer.getId()); releasedContainers.add(allocatedContainer.getId()); } else { this.allAllocatedContainers.put(allocatedContainer.getId().toString(), allocatedContainer); ByteBuffer tokens = LaunchContainerRunnable.getTokens(delegationTokenManager, heartbeatListener.getAddress()); LaunchContainerRunnable launchContainer = new LaunchContainerRunnable(allocatedContainer, nmClient, dag, tokens); // Thread launchThread = new Thread(runnableLaunchContainer); // launchThreads.add(launchThread); // launchThread.start(); launchContainer.run(); // communication with NMs is now async } } // track node updates for future locality constraint allocations // TODO: it seems 2.0.4-alpha doesn't give us any updates resourceRequestor.updateNodeReports(amResp.getUpdatedNodes()); // Check the completed containers List<ContainerStatus> completedContainers = amResp.getCompletedContainersStatuses(); // LOG.debug("Got response from RM for container ask, completedCnt=" + completedContainers.size()); for (ContainerStatus containerStatus : completedContainers) { LOG.info("Got container status for containerID= " + containerStatus.getContainerId() + ", state=" + containerStatus.getState() + ", exitStatus=" + containerStatus.getExitStatus() + ", diagnostics=" + containerStatus.getDiagnostics()); // non complete containers should not be here assert (containerStatus.getState() == ContainerState.COMPLETE); Container allocatedContainer = allAllocatedContainers.remove(containerStatus.getContainerId().toString()); // increment counters for completed/failed containers int exitStatus = containerStatus.getExitStatus(); LOG.info("Container {} exit status {}.", containerStatus.getContainerId(), exitStatus); if (0 != exitStatus) { if (allocatedContainer != null) { numFailedContainers.incrementAndGet(); } if (exitStatus == 1) { // non-recoverable StramChild failure appDone = true; dnmgr.shutdownDiagnosticsMessage = "Unrecoverable failure " + containerStatus.getContainerId(); LOG.info("Exiting due to: {}", dnmgr.shutdownDiagnosticsMessage); } else { // Recoverable failure or process killed (externally or via stop request by AM) LOG.info("Container {} failed or killed.", containerStatus.getContainerId()); dnmgr.scheduleContainerRestart(containerStatus.getContainerId().toString()); } } else { // container completed successfully numCompletedContainers.incrementAndGet(); LOG.info("Container completed successfully." + ", containerId=" + containerStatus.getContainerId()); } // record operator stop for this container StramChildAgent containerAgent = dnmgr.getContainerAgent(containerStatus.getContainerId().toString()); for (PTOperator oper : containerAgent.container.getOperators()) { StramEvent ev = new StramEvent.StopOperatorEvent(oper.getName(), oper.getId(), containerStatus.getContainerId().toString()); ev.setReason("container exited with status " + exitStatus); dnmgr.recordEventAsync(ev); } // record container stop event StramEvent ev = new StramEvent.StopContainerEvent(containerStatus.getContainerId().toString(), containerStatus.getExitStatus()); dnmgr.recordEventAsync(ev); dnmgr.removeContainerAgent(containerAgent.container.getExternalId()); } if (licenseClient != null) { if (!(amResp.getCompletedContainersStatuses().isEmpty() && amResp.getAllocatedContainers().isEmpty())) { // update license agent on allocated container changes licenseClient.reportAllocatedMemory((int)stats.getTotalMemoryAllocated()); } availableLicensedMemory = licenseClient.getRemainingEnforcementMB(); } if (allAllocatedContainers.isEmpty() && numRequestedContainers == 0 && dnmgr.containerStartRequests.isEmpty()) { LOG.debug("Exiting as no more containers are allocated or requested"); appDone = true; } LOG.debug("Current application state: loop=" + loopCounter + ", appDone=" + appDone + ", total=" + numTotalContainers + ", requested=" + numRequestedContainers + ", completed=" + numCompletedContainers + ", failed=" + numFailedContainers + ", currentAllocated=" + allAllocatedContainers.size()); // monitor child containers dnmgr.monitorHeartbeat(); } LOG.info("Application completed. Signalling finish to RM"); FinishApplicationMasterRequest finishReq = Records.newRecord(FinishApplicationMasterRequest.class); if (numFailedContainers.get() == 0) { finishReq.setFinalApplicationStatus(FinalApplicationStatus.SUCCEEDED); } else { finishReq.setFinalApplicationStatus(FinalApplicationStatus.FAILED); String diagnostics = "Diagnostics." + ", total=" + numTotalContainers + ", completed=" + numCompletedContainers.get() + ", allocated=" + allAllocatedContainers.size() + ", failed=" + numFailedContainers.get(); if (!StringUtils.isEmpty(dnmgr.shutdownDiagnosticsMessage)) { diagnostics += "\n"; diagnostics += dnmgr.shutdownDiagnosticsMessage; } // YARN-208 - as of 2.0.1-alpha dropped by the RM finishReq.setDiagnostics(diagnostics); // expected termination of the master process // application status and diagnostics message are set above } LOG.info("diagnostics: " + finishReq.getDiagnostics()); amRmClient.unregisterApplicationMaster(finishReq.getFinalApplicationStatus(), finishReq.getDiagnostics(), null); } /** * Check for containers that were allocated in a previous attempt. * If the containers are still alive, wait for them to check in via heartbeat. */ private void checkContainerStatus() { Collection<StramChildAgent> containers = this.dnmgr.getContainerAgents(); for (StramChildAgent ca : containers) { ContainerId containerId = ConverterUtils.toContainerId(ca.container.getExternalId()); NodeId nodeId = ConverterUtils.toNodeId(ca.container.host); // put container back into the allocated list org.apache.hadoop.yarn.api.records.Token containerToken = null; Resource resource = Resource.newInstance(ca.container.getAllocatedMemoryMB(), 1); Priority priority = Priority.newInstance(ca.container.getResourceRequestPriority()); Container yarnContainer = Container.newInstance(containerId, nodeId, ca.container.nodeHttpAddress, resource, priority, containerToken); this.allAllocatedContainers.put(containerId.toString(), yarnContainer); // check the status nmClient.getContainerStatusAsync(containerId, nodeId); } } /** * Ask RM to allocate given no. of containers to this Application Master * * @param requestedContainers * Containers to ask for from RM * @return Response from RM to AM with allocated containers * @throws YarnRemoteException */ private AllocateResponse sendContainerAskToRM(List<ContainerRequest> containerRequests, List<ContainerId> releasedContainers) throws YarnException, IOException { if (containerRequests.size() > 0) { LOG.info("Asking RM for containers: " + containerRequests); for (ContainerRequest cr : containerRequests) { LOG.info("Requested container: {}", cr.toString()); amRmClient.addContainerRequest(cr); } } for (ContainerId containerId : releasedContainers) { LOG.info("Released container, id={}", containerId.getId()); amRmClient.releaseAssignedContainer(containerId); } for (String containerIdStr : dnmgr.containerStopRequests.values()) { Container allocatedContainer = this.allAllocatedContainers.get(containerIdStr); if (allocatedContainer != null) { nmClient.stopContainerAsync(allocatedContainer.getId(), allocatedContainer.getNodeId()); LOG.info("Requested stop container {}", containerIdStr); } dnmgr.containerStopRequests.remove(containerIdStr); } return amRmClient.allocate(0); } private class NMCallbackHandler implements NMClientAsync.CallbackHandler { NMCallbackHandler() { } @Override public void onContainerStopped(ContainerId containerId) { if (LOG.isDebugEnabled()) { LOG.debug("Succeeded to stop Container " + containerId); } } @Override public void onContainerStatusReceived(ContainerId containerId, ContainerStatus containerStatus) { LOG.debug("Container Status: id=" + containerId + ", status=" + containerStatus); if (containerStatus.getState() != ContainerState.RUNNING) { recoverContainer(containerId); } } @Override public void onContainerStarted(ContainerId containerId, Map<String, ByteBuffer> allServiceResponse) { if (LOG.isDebugEnabled()) { LOG.debug("Succeeded to start Container " + containerId); } } @Override public void onStartContainerError(ContainerId containerId, Throwable t) { LOG.error("Start container failed for: containerId={}" + containerId, t); } @Override public void onGetContainerStatusError(ContainerId containerId, Throwable t) { LOG.error("Failed to query the status of Container " + containerId, t); // if the NM is not reachable, consider container lost and recover recoverContainer(containerId); } @Override public void onStopContainerError(ContainerId containerId, Throwable t) { LOG.warn("Failed to stop container {}", containerId); // container could not be stopped, we won't receive a stop event from AM heartbeat // short circuit and schedule recovery directly recoverContainer(containerId); } private void recoverContainer(final ContainerId containerId) { pendingTasks.add(new Runnable() { @Override public void run() { LOG.info("Lost container {}", containerId); dnmgr.scheduleContainerRestart(containerId.toString()); }}); } } }
engine/src/main/java/com/datatorrent/stram/StramAppMasterService.java
/* * Copyright (c) 2012-2013 DataTorrent, Inc. * All Rights Reserved. */ package com.datatorrent.stram; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetSocketAddress; import java.net.URI; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; import static java.lang.Thread.sleep; import javax.xml.bind.annotation.XmlElement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.service.CompositeService; import org.apache.hadoop.yarn.api.ApplicationConstants; import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse; import org.apache.hadoop.yarn.api.protocolrecords.FinishApplicationMasterRequest; import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterResponse; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.client.api.AMRMClient; import org.apache.hadoop.yarn.client.api.AMRMClient.ContainerRequest; import org.apache.hadoop.yarn.client.api.YarnClient; import org.apache.hadoop.yarn.client.api.async.NMClientAsync; import org.apache.hadoop.yarn.client.api.async.impl.NMClientAsyncImpl; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.ConverterUtils; import org.apache.hadoop.yarn.util.Records; import org.apache.hadoop.yarn.util.SystemClock; import org.apache.hadoop.yarn.webapp.WebApp; import org.apache.hadoop.yarn.webapp.WebApps; import com.datatorrent.api.AttributeMap; import com.datatorrent.api.DAGContext; import com.datatorrent.stram.StreamingContainerManager.ContainerResource; import com.datatorrent.stram.api.BaseContext; import com.datatorrent.stram.api.StramEvent; import com.datatorrent.stram.license.License; import com.datatorrent.stram.license.LicensingAgentClient; import com.datatorrent.stram.plan.logical.LogicalPlan; import com.datatorrent.stram.plan.physical.OperatorStatus.PortStatus; import com.datatorrent.stram.plan.physical.PTContainer; import com.datatorrent.stram.plan.physical.PTOperator; import com.datatorrent.stram.security.StramDelegationTokenManager; import com.datatorrent.stram.security.StramWSFilterInitializer; import com.datatorrent.stram.webapp.AppInfo; import com.datatorrent.stram.webapp.StramWebApp; import com.google.common.collect.Maps; /** * Streaming Application Master * * @since 0.3.2 */ public class StramAppMasterService extends CompositeService { private static final Logger LOG = LoggerFactory.getLogger(StramAppMasterService.class); private static final long DELEGATION_KEY_UPDATE_INTERVAL = 24 * 60 * 60 * 1000; private static final long DELEGATION_TOKEN_MAX_LIFETIME = 365 * 24 * 60 * 60 * 1000; private static final long DELEGATION_TOKEN_RENEW_INTERVAL = 365 * 24 * 60 * 60 * 1000; private static final long DELEGATION_TOKEN_REMOVER_SCAN_INTERVAL = 24 * 60 * 60 * 1000; private static final int NUMBER_MISSED_HEARTBEATS = 30; private AMRMClient<ContainerRequest> amRmClient; private NMClientAsync nmClient; private LogicalPlan dag; // Application Attempt Id ( combination of attemptId and fail count ) final private ApplicationAttemptId appAttemptID; // Hostname of the container private final String appMasterHostname = ""; // Tracking url to which app master publishes info for clients to monitor private String appMasterTrackingUrl = ""; // Simple flag to denote whether all works is done private boolean appDone = false; // Counter for completed containers ( complete denotes successful or failed ) private final AtomicInteger numCompletedContainers = new AtomicInteger(); // Containers that the RM has allocated to us private final Map<String, Container> allAllocatedContainers = new HashMap<String, Container>(); // Count of failed containers private final AtomicInteger numFailedContainers = new AtomicInteger(); private final ConcurrentLinkedQueue<Runnable> pendingTasks = new ConcurrentLinkedQueue<Runnable>(); // Launch threads // private final List<Thread> launchThreads = new ArrayList<Thread>(); // child container callback private StreamingContainerParent heartbeatListener; private StreamingContainerManager dnmgr; private final Clock clock = new SystemClock(); private final long startTime = clock.getTime(); private final ClusterAppStats stats = new ClusterAppStats(); private StramDelegationTokenManager delegationTokenManager = null; private LicensingAgentClient licenseClient; public StramAppMasterService(ApplicationAttemptId appAttemptID) { super(StramAppMasterService.class.getName()); this.appAttemptID = appAttemptID; } /** * Overrides getters to pull live info. */ protected class ClusterAppStats extends AppInfo.AppStats { @Override public int getAllocatedContainers() { return allAllocatedContainers.size(); } @Override public int getPlannedContainers() { return dnmgr.getPhysicalPlan().getContainers().size(); } @Override @XmlElement public int getFailedContainers() { return numFailedContainers.get(); } @Override public int getNumOperators() { return dnmgr.getPhysicalPlan().getAllOperators().size(); } @Override public long getCurrentWindowId() { long min = Long.MAX_VALUE; for (Map.Entry<Integer, PTOperator> entry : dnmgr.getPhysicalPlan().getAllOperators().entrySet()) { long windowId = entry.getValue().stats.currentWindowId.get(); if (min > windowId) { min = windowId; } } return StreamingContainerManager.toWsWindowId(min == Long.MAX_VALUE ? 0 : min); } @Override public long getRecoveryWindowId() { return StreamingContainerManager.toWsWindowId(dnmgr.getCommittedWindowId()); } @Override public long getTuplesProcessedPSMA() { long result = 0; for (Map.Entry<Integer, PTOperator> entry : dnmgr.getPhysicalPlan().getAllOperators().entrySet()) { result += entry.getValue().stats.tuplesProcessedPSMA.get(); } return result; } @Override public long getTotalTuplesProcessed() { long result = 0; for (Map.Entry<Integer, PTOperator> entry : dnmgr.getPhysicalPlan().getAllOperators().entrySet()) { result += entry.getValue().stats.totalTuplesProcessed.get(); } return result; } @Override public long getTuplesEmittedPSMA() { long result = 0; for (Map.Entry<Integer, PTOperator> entry : dnmgr.getPhysicalPlan().getAllOperators().entrySet()) { result += entry.getValue().stats.tuplesEmittedPSMA.get(); } return result; } @Override public long getTotalTuplesEmitted() { long result = 0; for (Map.Entry<Integer, PTOperator> entry : dnmgr.getPhysicalPlan().getAllOperators().entrySet()) { result += entry.getValue().stats.totalTuplesEmitted.get(); } return result; } @Override public long getTotalMemoryAllocated() { long result = 0; for (PTContainer c : dnmgr.getPhysicalPlan().getContainers()) { result += c.getAllocatedMemoryMB(); } return result; } @Override public long getTotalBufferServerReadBytesPSMA() { long result = 0; for (Map.Entry<Integer, PTOperator> entry : dnmgr.getPhysicalPlan().getAllOperators().entrySet()) { for (Map.Entry<String, PortStatus> portEntry : entry.getValue().stats.inputPortStatusList.entrySet()) { result += portEntry.getValue().bufferServerBytesPSMA.getAvg(); } } return result; } @Override public long getTotalBufferServerWriteBytesPSMA() { long result = 0; for (Map.Entry<Integer, PTOperator> entry : dnmgr.getPhysicalPlan().getAllOperators().entrySet()) { for (Map.Entry<String, PortStatus> portEntry : entry.getValue().stats.outputPortStatusList.entrySet()) { result += portEntry.getValue().bufferServerBytesPSMA.getAvg(); } } return result; } @Override public List<Integer> getCriticalPath() { StreamingContainerManager.CriticalPathInfo criticalPathInfo = dnmgr.getCriticalPathInfo(); return (criticalPathInfo == null) ? null : criticalPathInfo.path; } @Override public long getLatency() { StreamingContainerManager.CriticalPathInfo criticalPathInfo = dnmgr.getCriticalPathInfo(); return (criticalPathInfo == null) ? 0 : criticalPathInfo.latency; } } private class ClusterAppContextImpl extends BaseContext implements StramAppContext { private ClusterAppContextImpl() { super(null, null); } ClusterAppContextImpl(AttributeMap attributes) { super(attributes, null); } @Override public ApplicationId getApplicationID() { return appAttemptID.getApplicationId(); } @Override public ApplicationAttemptId getApplicationAttemptId() { return appAttemptID; } @Override public String getApplicationName() { return getValue(LogicalPlan.APPLICATION_NAME); } @Override public long getStartTime() { return startTime; } @Override public String getApplicationPath() { return getValue(LogicalPlan.APPLICATION_PATH); } @Override public CharSequence getUser() { return System.getenv(ApplicationConstants.Environment.USER.toString()); } @Override public Clock getClock() { return clock; } @Override public String getAppMasterTrackingUrl() { return appMasterTrackingUrl; } @Override public ClusterAppStats getStats() { return stats; } @Override public String getGatewayAddress() { return getValue(LogicalPlan.GATEWAY_ADDRESS); } @Override public String getLicenseId() { return StramAppMasterService.this.licenseClient.getLicenseId(); } @Override public long getRemainingLicensedMB() { return StramAppMasterService.this.licenseClient.getRemainingLicensedMB(); } @Override public long getTotalLicensedMB() { return StramAppMasterService.this.licenseClient.getTotalLicensedMB(); } @Override public long getAllocatedMB() { return StramAppMasterService.this.licenseClient.getAllocatedMB(); } @Override public long getLicenseInfoLastUpdate() { return StramAppMasterService.this.licenseClient.getLicenseInfoLastUpdate(); } @SuppressWarnings("FieldNameHidesFieldInSuperclass") private static final long serialVersionUID = 201309112304L; } /** * Dump out contents of $CWD and the environment to stdout for debugging */ @SuppressWarnings("UseOfSystemOutOrSystemErr") public void dumpOutDebugInfo() { LOG.info("Dump debug output"); Map<String, String> envs = System.getenv(); LOG.info("\nDumping System Env: begin"); for (Map.Entry<String, String> env : envs.entrySet()) { LOG.info("System env: key=" + env.getKey() + ", val=" + env.getValue()); } LOG.info("Dumping System Env: end"); String cmd = "ls -al"; Runtime run = Runtime.getRuntime(); Process pr; try { pr = run.exec(cmd); pr.waitFor(); BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line; LOG.info("\nDumping files in local dir: begin"); try { while ((line = buf.readLine()) != null) { LOG.info("System CWD content: " + line); } LOG.info("Dumping files in local dir: end"); } finally { buf.close(); } } catch (IOException e) { LOG.debug("Exception", e); } catch (InterruptedException e) { LOG.info("Interrupted", e); } LOG.info("Classpath: {}", System.getProperty("java.class.path")); LOG.info("Config resources: {}", getConfig().toString()); try { // find a better way of logging this using the logger. Configuration.dumpConfiguration(getConfig(), new PrintWriter(System.out)); } catch (Exception e) { LOG.error("Error dumping configuration.", e); } } @Override protected void serviceInit(Configuration conf) throws Exception { LOG.info("Application master" + ", appId=" + appAttemptID.getApplicationId().getId() + ", clustertimestamp=" + appAttemptID.getApplicationId().getClusterTimestamp() + ", attemptId=" + appAttemptID.getAttemptId()); FileInputStream fis = new FileInputStream("./" + LogicalPlan.SER_FILE_NAME); try { this.dag = LogicalPlan.read(fis); } finally { fis.close(); } // "debug" simply dumps all data using LOG.info if (dag.isDebug()) { dumpOutDebugInfo(); } FSRecoveryHandler recoveryHandler = new FSRecoveryHandler(dag.assertAppPath(), conf); this.dnmgr = StreamingContainerManager.getInstance(recoveryHandler, dag, true); dag = this.dnmgr.getLogicalPlan(); LOG.info("Starting application with {} operators in {} containers", dag.getAllOperators().size(), dnmgr.getPhysicalPlan().getContainers().size()); if (UserGroupInformation.isSecurityEnabled()) { // TODO :- Need to perform token renewal delegationTokenManager = new StramDelegationTokenManager(DELEGATION_KEY_UPDATE_INTERVAL, DELEGATION_TOKEN_MAX_LIFETIME, DELEGATION_TOKEN_RENEW_INTERVAL, DELEGATION_TOKEN_REMOVER_SCAN_INTERVAL); } this.nmClient = new NMClientAsyncImpl(new NMCallbackHandler()); addService(nmClient); this.amRmClient = AMRMClient.createAMRMClient(); addService(amRmClient); // start RPC server int rpcListenerCount = dag.getValue(DAGContext.HEARTBEAT_LISTENER_THREAD_COUNT); this.heartbeatListener = new StreamingContainerParent(this.getClass().getName(), dnmgr, delegationTokenManager, rpcListenerCount); addService(heartbeatListener); // get license and prepare for license agent interaction String licenseBase64 = dag.getValue(LogicalPlan.LICENSE); if (licenseBase64 != null) { byte[] licenseBytes = Base64.decodeBase64(licenseBase64); String licenseId = License.getLicenseID(licenseBytes); this.licenseClient = new LicensingAgentClient(appAttemptID.getApplicationId(), licenseId); addService(this.licenseClient); } // initialize all services added above super.serviceInit(conf); } @Override protected void serviceStart() throws Exception { super.serviceStart(); if (delegationTokenManager != null) { delegationTokenManager.startThreads(); } // write the connect address for containers to DFS InetSocketAddress connectAddress = NetUtils.getConnectAddress(this.heartbeatListener.getAddress()); URI connectUri = new URI("stram", null, connectAddress.getHostName(), connectAddress.getPort(), null, null, null); FSRecoveryHandler recoveryHandler = new FSRecoveryHandler(dag.assertAppPath(), getConfig()); recoveryHandler.writeConnectUri(connectUri.toString()); // start web service StramAppContext appContext = new ClusterAppContextImpl(dag.getAttributes()); try { org.mortbay.log.Log.setLog(null); Configuration config = getConfig(); if (UserGroupInformation.isSecurityEnabled()) { config = new Configuration(config); config.set("hadoop.http.filter.initializers", StramWSFilterInitializer.class.getCanonicalName()); } WebApp webApp = WebApps.$for("stram", StramAppContext.class, appContext, "ws").with(config).start(new StramWebApp(this.dnmgr)); LOG.info("Started web service at port: " + webApp.port()); this.appMasterTrackingUrl = NetUtils.getConnectAddress(webApp.getListenerAddress()).getHostName() + ":" + webApp.port(); LOG.info("Setting tracking URL to: " + appMasterTrackingUrl); } catch (Exception e) { LOG.error("Webapps failed to start. Ignoring for now:", e); } } @Override protected void serviceStop() throws Exception { super.serviceStop(); if (delegationTokenManager != null) { delegationTokenManager.stopThreads(); } nmClient.stop(); amRmClient.stop(); dnmgr.teardown(); } public boolean run() throws YarnException { boolean status = true; try { StramChild.eventloop.start(); execute(); } catch (Exception re) { status = false; LOG.error("Caught Exception in execute()", re); if (re.getCause() instanceof YarnException) { throw (YarnException) re.getCause(); } } finally { StramChild.eventloop.stop(); } return status; } /** * Main run function for the application master * * @throws YarnRemoteException */ @SuppressWarnings("SleepWhileInLoop") private void execute() throws YarnException, IOException { LOG.info("Starting ApplicationMaster"); Credentials credentials = UserGroupInformation.getCurrentUser().getCredentials(); LOG.info("number of tokens: {}", credentials.getAllTokens().size()); Iterator<Token<?>> iter = credentials.getAllTokens().iterator(); while (iter.hasNext()) { Token<?> token = iter.next(); LOG.debug("token: " + token); } // Register self with ResourceManager RegisterApplicationMasterResponse response = amRmClient.registerApplicationMaster(appMasterHostname, 0, appMasterTrackingUrl); // Dump out information about cluster capability as seen by the resource manager int maxMem = response.getMaximumResourceCapability().getMemory(); LOG.info("Max mem capabililty of resources in this cluster " + maxMem); int containerMemory = dag.getContainerMemoryMB(); if (containerMemory > maxMem) { LOG.info("Container memory specified above max threshold of cluster. Using max value." + ", specified=" + containerMemory + ", max=" + maxMem); containerMemory = maxMem; } // for locality relaxation fall back Map<StramChildAgent.ContainerStartRequest, Integer> requestedResources = Maps.newHashMap(); // Setup heartbeat emitter // TODO poll RM every now and then with an empty request to let RM know that we are alive // The heartbeat interval after which an AM is timed out by the RM is defined by a config setting: // RM_AM_EXPIRY_INTERVAL_MS with default defined by DEFAULT_RM_AM_EXPIRY_INTERVAL_MS // The allocate calls to the RM count as heartbeat so, for now, this additional heartbeat emitter // is not required. // Setup ask for containers from RM // Send request for containers to RM // Until we get our fully allocated quota, we keep on polling RM for containers // Keep looping until all containers finished processing // ( regardless of success/failure). int loopCounter = -1; List<ContainerId> releasedContainers = new ArrayList<ContainerId>(); int numTotalContainers = 0; // keep track of already requested containers to not request them again while waiting for allocation int numRequestedContainers = 0; int nextRequestPriority = 0; ResourceRequestHandler resourceRequestor = new ResourceRequestHandler(); try { // YARN-435 // we need getClusterNodes to populate the initial node list, // subsequent updates come through the heartbeat response YarnClient clientRMService = YarnClient.createYarnClient(); clientRMService.init(getConfig()); clientRMService.start(); resourceRequestor.updateNodeReports(clientRMService.getNodeReports()); clientRMService.stop(); } catch (Exception e) { throw new RuntimeException("Failed to retrieve cluster nodes report.", e); } // check for previously allocated containers // as of 2.2, containers won't survive AM restart, but this will change in the future - YARN-1490 checkContainerStatus(); int availableLicensedMemory = (licenseClient != null) ? 0 : Integer.MAX_VALUE; while (!appDone) { loopCounter++; Runnable r; while ((r = this.pendingTasks.poll()) != null) { r.run(); } // log current state /* * LOG.info("Current application state: loop=" + loopCounter + ", appDone=" + appDone + ", total=" + * numTotalContainers + ", requested=" + numRequestedContainers + ", completed=" + numCompletedContainers + * ", failed=" + numFailedContainers + ", currentAllocated=" + this.allAllocatedContainers.size()); */ // Sleep before each loop when asking RM for containers // to avoid flooding RM with spurious requests when it // need not have any available containers try { sleep(1000); } catch (InterruptedException e) { LOG.info("Sleep interrupted " + e.getMessage()); } // Setup request to be sent to RM to allocate containers List<ContainerRequest> containerRequests = new ArrayList<ContainerRequest>(); // request containers for pending deploy requests if (!dnmgr.containerStartRequests.isEmpty()) { boolean requestResources = true; if (licenseClient != null) { // ensure enough memory is left to request new container licenseClient.reportAllocatedMemory((int)stats.getTotalMemoryAllocated()); availableLicensedMemory = licenseClient.getRemainingEnforcementMB(); int requiredMemory = dnmgr.containerStartRequests.size() * containerMemory; if (requiredMemory > availableLicensedMemory) { LOG.warn("Insufficient licensed memory to request resources required {}m available {}m", requiredMemory, availableLicensedMemory); requestResources = false; } } if (requestResources) { StramChildAgent.ContainerStartRequest csr; while ((csr = dnmgr.containerStartRequests.poll()) != null) { csr.container.setResourceRequestPriority(nextRequestPriority++); requestedResources.put(csr, loopCounter); containerRequests.add(resourceRequestor.createContainerRequest(csr, containerMemory,true)); numTotalContainers++; numRequestedContainers++; } } } if (!requestedResources.isEmpty()) { //resourceRequestor.clearNodeMapping(); for (Map.Entry<StramChildAgent.ContainerStartRequest, Integer> entry : requestedResources.entrySet()) { if ((loopCounter - entry.getValue()) > NUMBER_MISSED_HEARTBEATS) { entry.setValue(loopCounter); StramChildAgent.ContainerStartRequest csr = entry.getKey(); containerRequests.add(resourceRequestor.createContainerRequest(csr, containerMemory,false)); } } } AllocateResponse amResp = sendContainerAskToRM(containerRequests, releasedContainers); releasedContainers.clear(); int availableMemory = Math.min(amResp.getAvailableResources().getMemory(), availableLicensedMemory); dnmgr.getPhysicalPlan().setAvailableResources(availableMemory); // Retrieve list of allocated containers from the response List<Container> newAllocatedContainers = amResp.getAllocatedContainers(); // LOG.info("Got response from RM for container ask, allocatedCnt=" + newAllocatedContainers.size()); numRequestedContainers -= newAllocatedContainers.size(); long timestamp = System.currentTimeMillis(); for (Container allocatedContainer : newAllocatedContainers) { LOG.info("Got new container." + ", containerId=" + allocatedContainer.getId() + ", containerNode=" + allocatedContainer.getNodeId() + ", containerNodeURI=" + allocatedContainer.getNodeHttpAddress() + ", containerResourceMemory" + allocatedContainer.getResource().getMemory() + ", priority" + allocatedContainer.getPriority()); // + ", containerToken" + allocatedContainer.getContainerToken().getIdentifier().toString()); boolean alreadyAllocated = true; StramChildAgent.ContainerStartRequest csr = null; for (Map.Entry<StramChildAgent.ContainerStartRequest, Integer> entry : requestedResources.entrySet()) { if(entry.getKey().container.getResourceRequestPriority() == allocatedContainer.getPriority().getPriority()){ alreadyAllocated = false; csr = entry.getKey(); break; } } if (alreadyAllocated) { LOG.debug("Releasing {} as resource with priority {} was already assigned", allocatedContainer.getId(), allocatedContainer.getPriority()); releasedContainers.add(allocatedContainer.getId()); continue; } if(csr != null) requestedResources.remove(csr); // allocate resource to container ContainerResource resource = new ContainerResource(allocatedContainer.getPriority().getPriority(), allocatedContainer.getId().toString(), allocatedContainer.getNodeId().toString(), allocatedContainer.getResource().getMemory(), allocatedContainer.getNodeHttpAddress()); StramChildAgent sca = dnmgr.assignContainer(resource, null); { // record container start event StramEvent ev = new StramEvent.StartContainerEvent(allocatedContainer.getId().toString(), allocatedContainer.getNodeId().toString()); ev.setTimestamp(timestamp); dnmgr.recordEventAsync(ev); } if (sca == null) { // allocated container no longer needed, add release request LOG.warn("Container {} allocated but nothing to deploy, going to release this container.", allocatedContainer.getId()); releasedContainers.add(allocatedContainer.getId()); } else { this.allAllocatedContainers.put(allocatedContainer.getId().toString(), allocatedContainer); ByteBuffer tokens = LaunchContainerRunnable.getTokens(delegationTokenManager, heartbeatListener.getAddress()); LaunchContainerRunnable launchContainer = new LaunchContainerRunnable(allocatedContainer, nmClient, dag, tokens); // Thread launchThread = new Thread(runnableLaunchContainer); // launchThreads.add(launchThread); // launchThread.start(); launchContainer.run(); // communication with NMs is now async } } // track node updates for future locality constraint allocations // TODO: it seems 2.0.4-alpha doesn't give us any updates resourceRequestor.updateNodeReports(amResp.getUpdatedNodes()); // Check the completed containers List<ContainerStatus> completedContainers = amResp.getCompletedContainersStatuses(); // LOG.debug("Got response from RM for container ask, completedCnt=" + completedContainers.size()); for (ContainerStatus containerStatus : completedContainers) { LOG.info("Got container status for containerID= " + containerStatus.getContainerId() + ", state=" + containerStatus.getState() + ", exitStatus=" + containerStatus.getExitStatus() + ", diagnostics=" + containerStatus.getDiagnostics()); // non complete containers should not be here assert (containerStatus.getState() == ContainerState.COMPLETE); Container allocatedContainer = allAllocatedContainers.remove(containerStatus.getContainerId().toString()); // increment counters for completed/failed containers int exitStatus = containerStatus.getExitStatus(); LOG.info("Container {} exit status {}.", containerStatus.getContainerId(), exitStatus); if (0 != exitStatus) { if (allocatedContainer != null) { numFailedContainers.incrementAndGet(); } if (exitStatus == 1) { // non-recoverable StramChild failure appDone = true; dnmgr.shutdownDiagnosticsMessage = "Unrecoverable failure " + containerStatus.getContainerId(); LOG.info("Exiting due to: {}", dnmgr.shutdownDiagnosticsMessage); } else { // Recoverable failure or process killed (externally or via stop request by AM) LOG.info("Container {} failed or killed.", containerStatus.getContainerId()); dnmgr.scheduleContainerRestart(containerStatus.getContainerId().toString()); } } else { // container completed successfully numCompletedContainers.incrementAndGet(); LOG.info("Container completed successfully." + ", containerId=" + containerStatus.getContainerId()); } // record operator stop for this container StramChildAgent containerAgent = dnmgr.getContainerAgent(containerStatus.getContainerId().toString()); for (PTOperator oper : containerAgent.container.getOperators()) { StramEvent ev = new StramEvent.StopOperatorEvent(oper.getName(), oper.getId(), containerStatus.getContainerId().toString()); ev.setReason("container exited with status " + exitStatus); dnmgr.recordEventAsync(ev); } // record container stop event StramEvent ev = new StramEvent.StopContainerEvent(containerStatus.getContainerId().toString(), containerStatus.getExitStatus()); dnmgr.recordEventAsync(ev); dnmgr.removeContainerAgent(containerAgent.container.getExternalId()); } if (licenseClient != null) { if (!(amResp.getCompletedContainersStatuses().isEmpty() && amResp.getAllocatedContainers().isEmpty())) { // update license agent on allocated container changes licenseClient.reportAllocatedMemory((int)stats.getTotalMemoryAllocated()); availableLicensedMemory = licenseClient.getRemainingEnforcementMB(); } } if (allAllocatedContainers.isEmpty() && numRequestedContainers == 0 && dnmgr.containerStartRequests.isEmpty()) { LOG.debug("Exiting as no more containers are allocated or requested"); appDone = true; } LOG.debug("Current application state: loop=" + loopCounter + ", appDone=" + appDone + ", total=" + numTotalContainers + ", requested=" + numRequestedContainers + ", completed=" + numCompletedContainers + ", failed=" + numFailedContainers + ", currentAllocated=" + allAllocatedContainers.size()); // monitor child containers dnmgr.monitorHeartbeat(); } LOG.info("Application completed. Signalling finish to RM"); FinishApplicationMasterRequest finishReq = Records.newRecord(FinishApplicationMasterRequest.class); if (numFailedContainers.get() == 0) { finishReq.setFinalApplicationStatus(FinalApplicationStatus.SUCCEEDED); } else { finishReq.setFinalApplicationStatus(FinalApplicationStatus.FAILED); String diagnostics = "Diagnostics." + ", total=" + numTotalContainers + ", completed=" + numCompletedContainers.get() + ", allocated=" + allAllocatedContainers.size() + ", failed=" + numFailedContainers.get(); if (!StringUtils.isEmpty(dnmgr.shutdownDiagnosticsMessage)) { diagnostics += "\n"; diagnostics += dnmgr.shutdownDiagnosticsMessage; } // YARN-208 - as of 2.0.1-alpha dropped by the RM finishReq.setDiagnostics(diagnostics); // expected termination of the master process // application status and diagnostics message are set above } LOG.info("diagnostics: " + finishReq.getDiagnostics()); amRmClient.unregisterApplicationMaster(finishReq.getFinalApplicationStatus(), finishReq.getDiagnostics(), null); } /** * Check for containers that were allocated in a previous attempt. * If the containers are still alive, wait for them to check in via heartbeat. */ private void checkContainerStatus() { Collection<StramChildAgent> containers = this.dnmgr.getContainerAgents(); for (StramChildAgent ca : containers) { ContainerId containerId = ConverterUtils.toContainerId(ca.container.getExternalId()); NodeId nodeId = ConverterUtils.toNodeId(ca.container.host); // put container back into the allocated list org.apache.hadoop.yarn.api.records.Token containerToken = null; Resource resource = Resource.newInstance(ca.container.getAllocatedMemoryMB(), 1); Priority priority = Priority.newInstance(ca.container.getResourceRequestPriority()); Container yarnContainer = Container.newInstance(containerId, nodeId, ca.container.nodeHttpAddress, resource, priority, containerToken); this.allAllocatedContainers.put(containerId.toString(), yarnContainer); // check the status nmClient.getContainerStatusAsync(containerId, nodeId); } } /** * Ask RM to allocate given no. of containers to this Application Master * * @param requestedContainers * Containers to ask for from RM * @return Response from RM to AM with allocated containers * @throws YarnRemoteException */ private AllocateResponse sendContainerAskToRM(List<ContainerRequest> containerRequests, List<ContainerId> releasedContainers) throws YarnException, IOException { if (containerRequests.size() > 0) { LOG.info("Asking RM for containers: " + containerRequests); for (ContainerRequest cr : containerRequests) { LOG.info("Requested container: {}", cr.toString()); amRmClient.addContainerRequest(cr); } } for (ContainerId containerId : releasedContainers) { LOG.info("Released container, id={}", containerId.getId()); amRmClient.releaseAssignedContainer(containerId); } for (String containerIdStr : dnmgr.containerStopRequests.values()) { Container allocatedContainer = this.allAllocatedContainers.get(containerIdStr); if (allocatedContainer != null) { nmClient.stopContainerAsync(allocatedContainer.getId(), allocatedContainer.getNodeId()); LOG.info("Requested stop container {}", containerIdStr); } dnmgr.containerStopRequests.remove(containerIdStr); } return amRmClient.allocate(0); } private class NMCallbackHandler implements NMClientAsync.CallbackHandler { NMCallbackHandler() { } @Override public void onContainerStopped(ContainerId containerId) { if (LOG.isDebugEnabled()) { LOG.debug("Succeeded to stop Container " + containerId); } } @Override public void onContainerStatusReceived(ContainerId containerId, ContainerStatus containerStatus) { LOG.debug("Container Status: id=" + containerId + ", status=" + containerStatus); if (containerStatus.getState() != ContainerState.RUNNING) { recoverContainer(containerId); } } @Override public void onContainerStarted(ContainerId containerId, Map<String, ByteBuffer> allServiceResponse) { if (LOG.isDebugEnabled()) { LOG.debug("Succeeded to start Container " + containerId); } } @Override public void onStartContainerError(ContainerId containerId, Throwable t) { LOG.error("Start container failed for: containerId={}" + containerId, t); } @Override public void onGetContainerStatusError(ContainerId containerId, Throwable t) { LOG.error("Failed to query the status of Container " + containerId, t); // if the NM is not reachable, consider container lost and recover recoverContainer(containerId); } @Override public void onStopContainerError(ContainerId containerId, Throwable t) { LOG.warn("Failed to stop container {}", containerId); // container could not be stopped, we won't receive a stop event from AM heartbeat // short circuit and schedule recovery directly recoverContainer(containerId); } private void recoverContainer(final ContainerId containerId) { pendingTasks.add(new Runnable() { @Override public void run() { LOG.info("Lost container {}", containerId); dnmgr.scheduleContainerRestart(containerId.toString()); }}); } } }
Fix for getting up-to-date remaining license memory in the cluster even when there are no plan updates. Workaround for CDH reporting incorrect available cluster resources.
engine/src/main/java/com/datatorrent/stram/StramAppMasterService.java
Fix for getting up-to-date remaining license memory in the cluster even when there are no plan updates. Workaround for CDH reporting incorrect available cluster resources.
<ide><path>ngine/src/main/java/com/datatorrent/stram/StramAppMasterService.java <ide> AllocateResponse amResp = sendContainerAskToRM(containerRequests, releasedContainers); <ide> releasedContainers.clear(); <ide> <del> int availableMemory = Math.min(amResp.getAvailableResources().getMemory(), availableLicensedMemory); <add> // CDH reporting incorrect resources, see SPOI-1846. Workaround for now. <add> //int availableMemory = Math.min(amResp.getAvailableResources().getMemory(), availableLicensedMemory); <add> int availableMemory = availableLicensedMemory; <ide> dnmgr.getPhysicalPlan().setAvailableResources(availableMemory); <ide> <ide> // Retrieve list of allocated containers from the response <ide> if (!(amResp.getCompletedContainersStatuses().isEmpty() && amResp.getAllocatedContainers().isEmpty())) { <ide> // update license agent on allocated container changes <ide> licenseClient.reportAllocatedMemory((int)stats.getTotalMemoryAllocated()); <del> availableLicensedMemory = licenseClient.getRemainingEnforcementMB(); <del> } <add> } <add> availableLicensedMemory = licenseClient.getRemainingEnforcementMB(); <ide> } <ide> <ide> if (allAllocatedContainers.isEmpty() && numRequestedContainers == 0 && dnmgr.containerStartRequests.isEmpty()) {
Java
apache-2.0
aaa308145a2359a8af706939485a366b3df4c4c4
0
kanpol/omni-note
package it.feio.android.omninotes.models; import it.feio.android.omninotes.R; import android.widget.LinearLayout.LayoutParams; import de.keyboardsurfer.android.widget.crouton.Configuration; import de.keyboardsurfer.android.widget.crouton.Style; public class ONStyle { public static final int DURATION_INFINITE = -1; public static final Style ALERT; public static final Style WARN; public static final Style CONFIRM; public static final Style INFO; public static final int AlertRed = R.color.alert; public static final int WarnOrange= R.color.warning; public static final int ConfirmGreen = R.color.confirm; public static final int InfoYellow = R.color.info; private static final int DURATION_SHORT = 1000; private static final int DURATION_MEDIUM = 1800; private static final int DURATION_LONG = 2500; static { ALERT = new Style.Builder() .setBackgroundColor(AlertRed) // .setDuration(DURATION_LONG) .setHeight(LayoutParams.WRAP_CONTENT) .setConfiguration(new Configuration.Builder().setDuration(DURATION_MEDIUM).build()) .build(); WARN = new Style.Builder() // .setDuration(DURATION_MEDIUM) .setBackgroundColor(WarnOrange) .setHeight(LayoutParams.WRAP_CONTENT) .setConfiguration(new Configuration.Builder().setDuration(DURATION_MEDIUM).build()) .build(); CONFIRM = new Style.Builder() // .setDuration(DURATION_MEDIUM) .setBackgroundColor(ConfirmGreen) .setHeight(LayoutParams.WRAP_CONTENT) .setConfiguration(new Configuration.Builder().setDuration(DURATION_MEDIUM).build()) .build(); INFO = new Style.Builder() // .setDuration(DURATION_MEDIUM) .setBackgroundColor(InfoYellow) .setHeight(LayoutParams.WRAP_CONTENT) .setConfiguration(new Configuration.Builder().setDuration(DURATION_MEDIUM).build()) .build(); } }
src/it/feio/android/omninotes/models/ONStyle.java
package it.feio.android.omninotes.models; import it.feio.android.omninotes.R; import android.widget.LinearLayout.LayoutParams; import de.keyboardsurfer.android.widget.crouton.Configuration; import de.keyboardsurfer.android.widget.crouton.Style; public class ONStyle { public static final int DURATION_INFINITE = -1; public static final Style ALERT; public static final Style WARN; public static final Style CONFIRM; public static final Style INFO; public static final int AlertRed = R.color.alert; public static final int WarnOrange= R.color.warning; public static final int ConfirmGreen = R.color.confirm; public static final int InfoYellow = R.color.info; private static final int DURATION_SHORT = 1300; private static final int DURATION_MEDIUM = 2100; private static final int DURATION_LONG = 3000; static { ALERT = new Style.Builder() .setBackgroundColor(AlertRed) // .setDuration(DURATION_LONG) .setHeight(LayoutParams.WRAP_CONTENT) .setConfiguration(new Configuration.Builder().setDuration(DURATION_MEDIUM).build()) .build(); WARN = new Style.Builder() // .setDuration(DURATION_MEDIUM) .setBackgroundColor(WarnOrange) .setHeight(LayoutParams.WRAP_CONTENT) .setConfiguration(new Configuration.Builder().setDuration(DURATION_MEDIUM).build()) .build(); CONFIRM = new Style.Builder() // .setDuration(DURATION_MEDIUM) .setBackgroundColor(ConfirmGreen) .setHeight(LayoutParams.WRAP_CONTENT) .setConfiguration(new Configuration.Builder().setDuration(DURATION_MEDIUM).build()) .build(); INFO = new Style.Builder() // .setDuration(DURATION_MEDIUM) .setBackgroundColor(InfoYellow) .setHeight(LayoutParams.WRAP_CONTENT) .setConfiguration(new Configuration.Builder().setDuration(DURATION_MEDIUM).build()) .build(); } }
Shortened crouton timings
src/it/feio/android/omninotes/models/ONStyle.java
Shortened crouton timings
<ide><path>rc/it/feio/android/omninotes/models/ONStyle.java <ide> public static final int ConfirmGreen = R.color.confirm; <ide> public static final int InfoYellow = R.color.info; <ide> <del>private static final int DURATION_SHORT = 1300; <del>private static final int DURATION_MEDIUM = 2100; <del>private static final int DURATION_LONG = 3000; <add>private static final int DURATION_SHORT = 1000; <add>private static final int DURATION_MEDIUM = 1800; <add>private static final int DURATION_LONG = 2500; <ide> <ide> <ide> static {
Java
apache-2.0
3e9d93631f58fdfe665209afa1a241a0091d8a73
0
romartin/kie-wb-common,droolsjbpm/kie-wb-common,ederign/kie-wb-common,porcelli-forks/kie-wb-common,cristianonicolai/kie-wb-common,romartin/kie-wb-common,scandihealth/kie-wb-common,porcelli-forks/kie-wb-common,manstis/kie-wb-common,ederign/kie-wb-common,porcelli-forks/kie-wb-common,scandihealth/kie-wb-common,dgutierr/kie-wb-common,manstis/kie-wb-common,manstis/kie-wb-common,cristianonicolai/kie-wb-common,jhrcek/kie-wb-common,ederign/kie-wb-common,jhrcek/kie-wb-common,manstis/kie-wb-common,romartin/kie-wb-common,psiroky/kie-wb-common,manstis/kie-wb-common,romartin/kie-wb-common,jhrcek/kie-wb-common,jhrcek/kie-wb-common,ederign/kie-wb-common,droolsjbpm/kie-wb-common,nmirasch/kie-wb-common,porcelli-forks/kie-wb-common,dgutierr/kie-wb-common,romartin/kie-wb-common
package org.kie.workbench.common.screens.projecteditor.client.menu; import java.util.ArrayList; import java.util.List; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Observes; import javax.inject.Inject; import org.guvnor.common.services.project.context.ProjectContext; import org.guvnor.common.services.project.context.ProjectContextChangeEvent; import org.guvnor.common.services.shared.file.CopyService; import org.guvnor.common.services.shared.file.DeleteService; import org.guvnor.common.services.shared.file.RenameService; import org.guvnor.structure.client.file.*; import org.jboss.errai.common.client.api.Caller; import org.kie.workbench.common.screens.projecteditor.client.validation.ProjectNameValidator; import org.kie.workbench.common.services.shared.project.KieProject; import org.kie.workbench.common.services.shared.project.KieProjectService; import org.kie.workbench.common.widgets.client.resources.i18n.ToolsMenuConstants; import org.uberfire.backend.vfs.Path; import org.uberfire.client.mvp.PlaceManager; import org.uberfire.mvp.Command; import org.uberfire.workbench.model.menu.MenuFactory; import org.uberfire.workbench.model.menu.MenuItem; @ApplicationScoped public class ProjectMenu { @Inject private PlaceManager placeManager; @Inject protected Caller<KieProjectService> projectService; @Inject protected Caller<RenameService> renameService; @Inject protected Caller<DeleteService> deleteService; @Inject protected Caller<CopyService> copyService; @Inject protected ProjectContext context; @Inject protected ProjectNameValidator projectNameValidator; private MenuItem projectScreen = MenuFactory.newSimpleItem( ToolsMenuConstants.INSTANCE.ProjectEditor() ).respondsWith( new Command() { @Override public void execute() { placeManager.goTo( "projectScreen" ); } } ).endMenu().build().getItems().get( 0 ); private MenuItem projectStructureScreen = MenuFactory.newSimpleItem( ToolsMenuConstants.INSTANCE.RepositoryStructure() ).respondsWith( new Command() { @Override public void execute() { placeManager.goTo( "repositoryStructureScreen" ); } } ).endMenu().build().getItems().get( 0 ); private MenuItem copyProject = MenuFactory.newSimpleItem( ToolsMenuConstants.INSTANCE.CopyProject() ).respondsWith( new Command() { @Override public void execute() { final Path path = context.getActiveProject().getRootPath(); new CopyPopup( path, projectNameValidator, new CommandWithFileNameAndCommitMessage() { @Override public void execute( FileNameAndCommitMessage payload ) { copyService.call().copy( path, payload.getNewFileName(), payload.getCommitMessage() ); } } ).show(); } } ).endMenu().build().getItems().get( 0 ); private MenuItem renameProject = MenuFactory.newSimpleItem( ToolsMenuConstants.INSTANCE.RenameProject() ).respondsWith( new Command() { @Override public void execute() { final Path path = context.getActiveProject().getRootPath(); new RenamePopup( path, projectNameValidator, new CommandWithFileNameAndCommitMessage() { @Override public void execute( FileNameAndCommitMessage payload ) { renameService.call().rename( path, payload.getNewFileName(), payload.getCommitMessage() ); } } ).show(); } } ).endMenu().build().getItems().get( 0 ); private MenuItem removeProject = MenuFactory.newSimpleItem( ToolsMenuConstants.INSTANCE.RemoveProject() ).respondsWith( new Command() { @Override public void execute() { new DeletePopup( new CommandWithCommitMessage() { @Override public void execute( String payload ) { deleteService.call().delete( context.getActiveProject().getRootPath(), payload ); } } ).show(); } } ).endMenu().build().getItems().get( 0 ); public List<MenuItem> getMenuItems() { ArrayList<MenuItem> menuItems = new ArrayList<MenuItem>(); menuItems.add( projectScreen ); menuItems.add( projectStructureScreen ); // menuItems.add(removeProject); // menuItems.add(renameProject); // menuItems.add(copyProject); return menuItems; } public void onProjectContextChanged( @Observes final ProjectContextChangeEvent event ) { enableToolsMenuItems( (KieProject) event.getProject() ); } private void enableToolsMenuItems( final KieProject project ) { final boolean enabled = ( project != null ); projectScreen.setEnabled( enabled ); } }
kie-wb-common-screens/kie-wb-common-project-editor/kie-wb-common-project-editor-client/src/main/java/org/kie/workbench/common/screens/projecteditor/client/menu/ProjectMenu.java
package org.kie.workbench.common.screens.projecteditor.client.menu; import java.util.ArrayList; import java.util.List; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Observes; import javax.inject.Inject; import org.guvnor.common.services.project.context.ProjectContext; import org.guvnor.common.services.project.context.ProjectContextChangeEvent; import org.guvnor.common.services.shared.file.CopyService; import org.guvnor.common.services.shared.file.DeleteService; import org.guvnor.common.services.shared.file.RenameService; import org.guvnor.structure.client.file.*; import org.jboss.errai.common.client.api.Caller; import org.kie.workbench.common.screens.projecteditor.client.validation.ProjectNameValidator; import org.kie.workbench.common.services.shared.project.KieProject; import org.kie.workbench.common.services.shared.project.KieProjectService; import org.kie.workbench.common.widgets.client.resources.i18n.ToolsMenuConstants; import org.uberfire.backend.vfs.Path; import org.uberfire.client.mvp.PlaceManager; import org.uberfire.mvp.Command; import org.uberfire.workbench.model.menu.MenuFactory; import org.uberfire.workbench.model.menu.MenuItem; @ApplicationScoped public class ProjectMenu { @Inject private PlaceManager placeManager; @Inject protected Caller<KieProjectService> projectService; @Inject protected Caller<RenameService> renameService; @Inject protected Caller<DeleteService> deleteService; @Inject protected Caller<CopyService> copyService; @Inject protected ProjectContext context; @Inject protected ProjectNameValidator projectNameValidator; private MenuItem projectScreen = MenuFactory.newSimpleItem( ToolsMenuConstants.INSTANCE.ProjectEditor() ).respondsWith( new Command() { @Override public void execute() { placeManager.goTo( "projectScreen" ); } } ).endMenu().build().getItems().get( 0 ); private MenuItem projectStructureScreen = MenuFactory.newSimpleItem( ToolsMenuConstants.INSTANCE.RepositoryStructure() ).respondsWith( new Command() { @Override public void execute() { placeManager.goTo( "projectStructureScreen" ); } } ).endMenu().build().getItems().get( 0 ); private MenuItem copyProject = MenuFactory.newSimpleItem( ToolsMenuConstants.INSTANCE.CopyProject() ).respondsWith( new Command() { @Override public void execute() { final Path path = context.getActiveProject().getRootPath(); new CopyPopup( path, projectNameValidator, new CommandWithFileNameAndCommitMessage() { @Override public void execute( FileNameAndCommitMessage payload ) { copyService.call().copy( path, payload.getNewFileName(), payload.getCommitMessage() ); } } ).show(); } } ).endMenu().build().getItems().get( 0 ); private MenuItem renameProject = MenuFactory.newSimpleItem( ToolsMenuConstants.INSTANCE.RenameProject() ).respondsWith( new Command() { @Override public void execute() { final Path path = context.getActiveProject().getRootPath(); new RenamePopup( path, projectNameValidator, new CommandWithFileNameAndCommitMessage() { @Override public void execute( FileNameAndCommitMessage payload ) { renameService.call().rename( path, payload.getNewFileName(), payload.getCommitMessage() ); } } ).show(); } } ).endMenu().build().getItems().get( 0 ); private MenuItem removeProject = MenuFactory.newSimpleItem( ToolsMenuConstants.INSTANCE.RemoveProject() ).respondsWith( new Command() { @Override public void execute() { new DeletePopup( new CommandWithCommitMessage() { @Override public void execute( String payload ) { deleteService.call().delete( context.getActiveProject().getRootPath(), payload ); } } ).show(); } } ).endMenu().build().getItems().get( 0 ); public List<MenuItem> getMenuItems() { ArrayList<MenuItem> menuItems = new ArrayList<MenuItem>(); menuItems.add( projectScreen ); menuItems.add( projectStructureScreen ); // menuItems.add(removeProject); // menuItems.add(renameProject); // menuItems.add(copyProject); return menuItems; } public void onProjectContextChanged( @Observes final ProjectContextChangeEvent event ) { enableToolsMenuItems( (KieProject) event.getProject() ); } private void enableToolsMenuItems( final KieProject project ) { final boolean enabled = ( project != null ); projectScreen.setEnabled( enabled ); } }
Project structure screen renamed to repositoryStructureScreen
kie-wb-common-screens/kie-wb-common-project-editor/kie-wb-common-project-editor-client/src/main/java/org/kie/workbench/common/screens/projecteditor/client/menu/ProjectMenu.java
Project structure screen renamed to repositoryStructureScreen
<ide><path>ie-wb-common-screens/kie-wb-common-project-editor/kie-wb-common-project-editor-client/src/main/java/org/kie/workbench/common/screens/projecteditor/client/menu/ProjectMenu.java <ide> new Command() { <ide> @Override <ide> public void execute() { <del> placeManager.goTo( "projectStructureScreen" ); <add> placeManager.goTo( "repositoryStructureScreen" ); <ide> } <ide> } ).endMenu().build().getItems().get( 0 ); <ide>
Java
epl-1.0
6f93421211874b61ad8f2d9883756805b48089b1
0
blizzy78/egit,paulvi/egit,collaborative-modeling/egit,SmithAndr/egit,collaborative-modeling/egit,wdliu/egit,paulvi/egit,wdliu/egit,SmithAndr/egit
/******************************************************************************* * Copyright (C) 2011, 2012 Bernard Leach <[email protected]> and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.egit.ui.internal.staging; import static org.eclipse.egit.ui.internal.CommonUtils.runCommand; import static org.eclipse.ui.ISources.ACTIVE_MENU_SELECTION_NAME; import static org.eclipse.ui.menus.CommandContributionItem.STYLE_PUSH; import java.io.File; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.eclipse.core.commands.operations.IUndoContext; import org.eclipse.core.expressions.IEvaluationContext; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.preferences.IEclipsePreferences.IPreferenceChangeListener; import org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.egit.core.RepositoryUtil; import org.eclipse.egit.core.internal.indexdiff.IndexDiffCacheEntry; import org.eclipse.egit.core.internal.indexdiff.IndexDiffChangedListener; import org.eclipse.egit.core.internal.indexdiff.IndexDiffData; import org.eclipse.egit.core.op.CommitOperation; import org.eclipse.egit.core.project.RepositoryMapping; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.UIIcons; import org.eclipse.egit.ui.UIPreferences; import org.eclipse.egit.ui.UIText; import org.eclipse.egit.ui.UIUtils; import org.eclipse.egit.ui.internal.EgitUiEditorUtils; import org.eclipse.egit.ui.internal.actions.ActionCommands; import org.eclipse.egit.ui.internal.actions.BooleanPrefAction; import org.eclipse.egit.ui.internal.commit.CommitHelper; import org.eclipse.egit.ui.internal.commit.CommitJob; import org.eclipse.egit.ui.internal.commit.CommitMessageHistory; import org.eclipse.egit.ui.internal.commit.CommitProposalProcessor; import org.eclipse.egit.ui.internal.components.ToggleableWarningLabel; import org.eclipse.egit.ui.internal.decorators.ProblemLabelDecorator; import org.eclipse.egit.ui.internal.dialogs.CommitMessageArea; import org.eclipse.egit.ui.internal.dialogs.CommitMessageComponent; import org.eclipse.egit.ui.internal.dialogs.CommitMessageComponentState; import org.eclipse.egit.ui.internal.dialogs.CommitMessageComponentStateManager; import org.eclipse.egit.ui.internal.dialogs.ICommitMessageComponentNotifications; import org.eclipse.egit.ui.internal.dialogs.SpellcheckableMessageArea; import org.eclipse.egit.ui.internal.operations.DeletePathsOperationUI; import org.eclipse.egit.ui.internal.operations.IgnoreOperationUI; import org.eclipse.egit.ui.internal.repository.tree.RepositoryTreeNode; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.preference.IPersistentPreferenceStore; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.LocalSelectionTransfer; import org.eclipse.jface.viewers.ContentViewer; import org.eclipse.jface.viewers.DecoratingStyledCellLabelProvider; import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider; import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider; import org.eclipse.jface.viewers.IBaseLabelProvider; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jgit.api.AddCommand; import org.eclipse.jgit.api.CheckoutCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.RmCommand; import org.eclipse.jgit.api.errors.NoFilepatternException; import org.eclipse.jgit.dircache.DirCache; import org.eclipse.jgit.dircache.DirCacheEditor; import org.eclipse.jgit.dircache.DirCacheEntry; import org.eclipse.jgit.lib.ConfigConstants; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.RepositoryState; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.VerifyKeyListener; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSourceAdapter; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.DropTargetAdapter; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.ISelectionService; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.forms.IFormColors; import org.eclipse.ui.forms.widgets.ExpandableComposite; import org.eclipse.ui.forms.widgets.Form; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Section; import org.eclipse.ui.handlers.IHandlerService; import org.eclipse.ui.menus.CommandContributionItem; import org.eclipse.ui.menus.CommandContributionItemParameter; import org.eclipse.ui.operations.UndoRedoActionGroup; import org.eclipse.ui.part.IShowInSource; import org.eclipse.ui.part.ShowInContext; import org.eclipse.ui.part.ViewPart; /** * A GitX style staging view with embedded commit dialog. */ public class StagingView extends ViewPart implements IShowInSource { /** * Staging view id */ public static final String VIEW_ID = "org.eclipse.egit.ui.StagingView"; //$NON-NLS-1$ private static final String EMPTY_STRING = ""; //$NON-NLS-1$ private Form form; private Section stagedSection; private Section unstagedSection; private Section commitMessageSection; private TableViewer stagedTableViewer; private TableViewer unstagedTableViewer; private ToggleableWarningLabel warningLabel; private SpellcheckableMessageArea commitMessageText; private Text committerText; private Text authorText; private CommitMessageComponent commitMessageComponent; private boolean reactOnSelection = true; private ISelectionListener selectionChangedListener; private Repository currentRepository; static class StagingViewUpdate { Repository repository; IndexDiffData indexDiff; Collection<String> changedResources; StagingViewUpdate(Repository theRepository, IndexDiffData theIndexDiff, Collection<String> theChanges) { this.repository = theRepository; this.indexDiff = theIndexDiff; this.changedResources = theChanges; } } static class StagingDragListener extends DragSourceAdapter { private ISelectionProvider provider; public StagingDragListener(ISelectionProvider provider) { this.provider = provider; } public void dragStart(DragSourceEvent event) { event.doit = !provider.getSelection().isEmpty(); } public void dragFinished(DragSourceEvent event) { if (LocalSelectionTransfer.getTransfer().isSupportedType( event.dataType)) LocalSelectionTransfer.getTransfer().setSelection(null); } public void dragSetData(DragSourceEvent event) { IStructuredSelection selection = (IStructuredSelection) provider .getSelection(); if (selection.isEmpty()) return; if (LocalSelectionTransfer.getTransfer().isSupportedType( event.dataType)) { LocalSelectionTransfer.getTransfer().setSelection(selection); return; } if (FileTransfer.getInstance().isSupportedType(event.dataType)) { List<String> files = new ArrayList<String>(); for (Object selected : selection.toList()) if (selected instanceof StagingEntry) { StagingEntry entry = (StagingEntry) selected; File file = new File( entry.getRepository().getWorkTree(), entry.getPath()); if (file.exists()) files.add(file.getAbsolutePath()); } if (!files.isEmpty()) { event.data = files.toArray(new String[files.size()]); return; } } } } private final IPreferenceChangeListener prefListener = new IPreferenceChangeListener() { public void preferenceChange(PreferenceChangeEvent event) { if (!RepositoryUtil.PREFS_DIRECTORIES.equals(event.getKey())) return; final Repository repo = currentRepository; if (repo == null) return; if (Activator.getDefault().getRepositoryUtil().contains(repo)) return; reload(null); } }; private Action signedOffByAction; private Action addChangeIdAction; private Action amendPreviousCommitAction; private Action openNewCommitsAction; private Action columnLayoutAction; private Action fileNameModeAction; private Action refreshAction; private SashForm stagingSashForm; private IndexDiffChangedListener myIndexDiffListener = new IndexDiffChangedListener() { public void indexDiffChanged(Repository repository, IndexDiffData indexDiffData) { reload(repository); } }; private IndexDiffCacheEntry cacheEntry; private UndoRedoActionGroup undoRedoActionGroup; private Button commitButton; private Button commitAndPushButton; @Override public void createPartControl(Composite parent) { GridLayoutFactory.fillDefaults().applyTo(parent); final FormToolkit toolkit = new FormToolkit(parent.getDisplay()); parent.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { toolkit.dispose(); } }); form = toolkit.createForm(parent); Image repoImage = UIIcons.REPOSITORY.createImage(); UIUtils.hookDisposal(form, repoImage); form.setImage(repoImage); form.setText(UIText.StagingView_NoSelectionTitle); GridDataFactory.fillDefaults().grab(true, true).applyTo(form); toolkit.decorateFormHeading(form); GridLayoutFactory.swtDefaults().applyTo(form.getBody()); SashForm horizontalSashForm = new SashForm(form.getBody(), SWT.NONE); toolkit.adapt(horizontalSashForm, true, true); GridDataFactory.fillDefaults().grab(true, true) .applyTo(horizontalSashForm); stagingSashForm = new SashForm(horizontalSashForm, getStagingFormOrientation()); toolkit.adapt(stagingSashForm, true, true); GridDataFactory.fillDefaults().grab(true, true) .applyTo(stagingSashForm); unstagedSection = toolkit.createSection(stagingSashForm, ExpandableComposite.TITLE_BAR); Composite unstagedTableComposite = toolkit .createComposite(unstagedSection); toolkit.paintBordersFor(unstagedTableComposite); unstagedSection.setClient(unstagedTableComposite); GridLayoutFactory.fillDefaults().extendedMargins(2, 2, 2, 2) .applyTo(unstagedTableComposite); unstagedTableViewer = new TableViewer(toolkit.createTable( unstagedTableComposite, SWT.FULL_SELECTION | SWT.MULTI)); GridDataFactory.fillDefaults().grab(true, true) .applyTo(unstagedTableViewer.getControl()); unstagedTableViewer.getTable().setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TREE_BORDER); unstagedTableViewer.getTable().setLinesVisible(true); unstagedTableViewer.setLabelProvider(createLabelProvider(unstagedTableViewer)); unstagedTableViewer.setContentProvider(new StagingViewContentProvider( true)); unstagedTableViewer.addDragSupport(DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK, new Transfer[] { LocalSelectionTransfer.getTransfer(), FileTransfer.getInstance() }, new StagingDragListener( unstagedTableViewer)); unstagedTableViewer.addDropSupport(DND.DROP_MOVE, new Transfer[] { LocalSelectionTransfer.getTransfer() }, new DropTargetAdapter() { public void drop(DropTargetEvent event) { if (event.data instanceof IStructuredSelection) { final IStructuredSelection selection = (IStructuredSelection) event.data; if (selection.getFirstElement() instanceof StagingEntry) unstage(selection); } } public void dragOver(DropTargetEvent event) { event.detail = DND.DROP_MOVE; } }); unstagedTableViewer.addOpenListener(new IOpenListener() { public void open(OpenEvent event) { compareWith(event); } }); commitMessageSection = toolkit.createSection( horizontalSashForm, ExpandableComposite.TITLE_BAR); commitMessageSection.setText(UIText.StagingView_CommitMessage); Composite commitMessageComposite = toolkit .createComposite(commitMessageSection); commitMessageSection.setClient(commitMessageComposite); GridLayoutFactory.fillDefaults().numColumns(1) .applyTo(commitMessageComposite); warningLabel = new ToggleableWarningLabel(commitMessageComposite, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).exclude(true) .applyTo(warningLabel); Composite commitMessageTextComposite = toolkit .createComposite(commitMessageComposite); toolkit.paintBordersFor(commitMessageTextComposite); GridDataFactory.fillDefaults().grab(true, true) .applyTo(commitMessageTextComposite); GridLayoutFactory.fillDefaults().numColumns(1) .extendedMargins(2, 2, 2, 2) .applyTo(commitMessageTextComposite); final CommitProposalProcessor commitProposalProcessor = new CommitProposalProcessor() { @Override protected Collection<String> computeFileNameProposals() { return getStagedFileNames(); } @Override protected Collection<String> computeMessageProposals() { return CommitMessageHistory.getCommitHistory(); } }; commitMessageText = new CommitMessageArea(commitMessageTextComposite, EMPTY_STRING, toolkit.getBorderStyle()) { @Override protected CommitProposalProcessor getCommitProposalProcessor() { return commitProposalProcessor; } @Override protected IHandlerService getHandlerService() { return (IHandlerService) getSite().getService(IHandlerService.class); } }; commitMessageText.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); GridDataFactory.fillDefaults().grab(true, true) .applyTo(commitMessageText); UIUtils.addBulbDecorator(commitMessageText.getTextWidget(), UIText.CommitDialog_ContentAssist); Composite composite = toolkit.createComposite(commitMessageComposite); toolkit.paintBordersFor(composite); GridDataFactory.fillDefaults().grab(true, false).applyTo(composite); GridLayoutFactory.swtDefaults().numColumns(2).applyTo(composite); toolkit.createLabel(composite, UIText.StagingView_Author) .setForeground( toolkit.getColors().getColor(IFormColors.TB_TOGGLE)); authorText = toolkit.createText(composite, null); authorText .setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); authorText.setLayoutData(GridDataFactory.fillDefaults() .grab(true, false).create()); toolkit.createLabel(composite, UIText.StagingView_Committer) .setForeground( toolkit.getColors().getColor(IFormColors.TB_TOGGLE)); committerText = toolkit.createText(composite, null); committerText.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); committerText.setLayoutData(GridDataFactory.fillDefaults() .grab(true, false).create()); Composite buttonsContainer = toolkit.createComposite(composite); GridDataFactory.fillDefaults().grab(true, false).span(2,1).indent(0, 8) .applyTo(buttonsContainer); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(buttonsContainer); Label filler = toolkit.createLabel(buttonsContainer, ""); //$NON-NLS-1$ GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(filler); Composite commitButtonsContainer = toolkit.createComposite(buttonsContainer); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER) .applyTo(commitButtonsContainer); GridLayoutFactory.fillDefaults().numColumns(2).equalWidth(true).applyTo(commitButtonsContainer); this.commitAndPushButton = toolkit.createButton(commitButtonsContainer, UIText.StagingView_CommitAndPush, SWT.PUSH); commitAndPushButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { commit(true); } }); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER) .applyTo(commitAndPushButton); this.commitButton = toolkit.createButton(commitButtonsContainer, UIText.StagingView_Commit, SWT.PUSH); commitButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { commit(false); } }); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER) .applyTo(commitButton); stagedSection = toolkit.createSection(stagingSashForm, ExpandableComposite.TITLE_BAR); Composite stagedTableComposite = toolkit.createComposite(stagedSection); toolkit.paintBordersFor(stagedTableComposite); stagedSection.setClient(stagedTableComposite); GridLayoutFactory.fillDefaults().extendedMargins(2, 2, 2, 2) .applyTo(stagedTableComposite); stagedTableViewer = new TableViewer(toolkit.createTable( stagedTableComposite, SWT.FULL_SELECTION | SWT.MULTI)); GridDataFactory.fillDefaults().grab(true, true) .applyTo(stagedTableViewer.getControl()); stagedTableViewer.getTable().setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TREE_BORDER); stagedTableViewer.getTable().setLinesVisible(true); stagedTableViewer.setLabelProvider(createLabelProvider(stagedTableViewer)); stagedTableViewer.setContentProvider(new StagingViewContentProvider( false)); stagedTableViewer.addDragSupport( DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK, new Transfer[] { LocalSelectionTransfer.getTransfer(), FileTransfer.getInstance() }, new StagingDragListener( stagedTableViewer)); stagedTableViewer.addDropSupport(DND.DROP_MOVE, new Transfer[] { LocalSelectionTransfer.getTransfer() }, new DropTargetAdapter() { public void drop(DropTargetEvent event) { if (event.data instanceof IStructuredSelection) { final IStructuredSelection selection = (IStructuredSelection) event.data; if (selection.getFirstElement() instanceof StagingEntry) stage(selection); } } public void dragOver(DropTargetEvent event) { event.detail = DND.DROP_MOVE; } }); stagedTableViewer.addOpenListener(new IOpenListener() { public void open(OpenEvent event) { compareWith(event); } }); selectionChangedListener = new ISelectionListener() { public void selectionChanged(IWorkbenchPart part, ISelection selection) { if (!reactOnSelection || part == getSite().getPart()) return; // this may happen if we switch between editors if (part instanceof IEditorPart) { IEditorInput input = ((IEditorPart) part).getEditorInput(); if (input instanceof IFileEditorInput) reactOnSelection(new StructuredSelection( ((IFileEditorInput) input).getFile())); } else reactOnSelection(selection); } }; IPreferenceStore preferenceStore = getPreferenceStore(); if (preferenceStore.contains(UIPreferences.STAGING_VIEW_SYNC_SELECTION)) reactOnSelection = preferenceStore.getBoolean( UIPreferences.STAGING_VIEW_SYNC_SELECTION); else preferenceStore.setDefault(UIPreferences.STAGING_VIEW_SYNC_SELECTION, true); InstanceScope.INSTANCE.getNode( org.eclipse.egit.core.Activator.getPluginId()) .addPreferenceChangeListener(prefListener); updateSectionText(); updateToolbar(); enableCommitWidgets(false); createPopupMenu(unstagedTableViewer); createPopupMenu(stagedTableViewer); final ICommitMessageComponentNotifications listener = new ICommitMessageComponentNotifications() { public void updateSignedOffToggleSelection(boolean selection) { signedOffByAction.setChecked(selection); } public void updateChangeIdToggleSelection(boolean selection) { addChangeIdAction.setChecked(selection); } }; commitMessageComponent = new CommitMessageComponent(listener); commitMessageComponent.attachControls(commitMessageText, authorText, committerText); // allow to commit with ctrl-enter commitMessageText.getTextWidget().addVerifyKeyListener(new VerifyKeyListener() { public void verifyKey(VerifyEvent event) { if (UIUtils.isSubmitKeyEvent(event)) { event.doit = false; commit(false); } } }); commitMessageText.getTextWidget().addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { // Ctrl+Enter shortcut only works when the focus is on the commit message text String commitButtonTooltip = MessageFormat.format( UIText.StagingView_CommitToolTip, UIUtils.SUBMIT_KEY_STROKE.format()); commitButton.setToolTipText(commitButtonTooltip); } public void focusLost(FocusEvent e) { commitButton.setToolTipText(null); } }); ModifyListener modifyListener = new ModifyListener() { public void modifyText(ModifyEvent e) { updateMessage(); } }; authorText.addModifyListener(modifyListener); committerText.addModifyListener(modifyListener); // react on selection changes IWorkbenchPartSite site = getSite(); ISelectionService srv = (ISelectionService) site .getService(ISelectionService.class); srv.addPostSelectionListener(selectionChangedListener); // Use current selection to populate staging view ISelection selection = srv.getSelection(); if (selection != null && !selection.isEmpty()) { IWorkbenchPart part = site.getPage().getActivePart(); if (part != null) selectionChangedListener.selectionChanged(part, selection); } site.setSelectionProvider(unstagedTableViewer); } public ShowInContext getShowInContext() { if (stagedTableViewer != null && stagedTableViewer.getTable().isFocusControl()) return getShowInContext(stagedTableViewer); else if (unstagedTableViewer != null && unstagedTableViewer.getTable().isFocusControl()) return getShowInContext(unstagedTableViewer); else return null; } private ShowInContext getShowInContext(TableViewer tableViewer) { IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection(); List<IResource> resources = new ArrayList<IResource>(); for (Object element : selection.toList()) { if (element instanceof StagingEntry) { StagingEntry entry = (StagingEntry) element; IFile file = entry.getFile(); if (file != null) resources.add(file); } } return new ShowInContext(null, new StructuredSelection(resources)); } private int getStagingFormOrientation() { boolean columnLayout = Activator.getDefault().getPreferenceStore() .getBoolean(UIPreferences.STAGING_VIEW_COLUMN_LAYOUT); if (columnLayout) return SWT.HORIZONTAL; else return SWT.VERTICAL; } private void enableCommitWidgets(boolean enabled) { if (!enabled) { commitMessageText.setText(""); //$NON-NLS-1$ committerText.setText(""); //$NON-NLS-1$ authorText.setText(""); //$NON-NLS-1$ } commitMessageText.setEnabled(enabled); committerText.setEnabled(enabled); authorText.setEnabled(enabled); refreshAction.setEnabled(enabled); amendPreviousCommitAction.setEnabled(enabled); signedOffByAction.setEnabled(enabled); addChangeIdAction.setEnabled(enabled); commitButton.setEnabled(enabled); commitAndPushButton.setEnabled(enabled); } private void updateToolbar() { IActionBars actionBars = getViewSite().getActionBars(); IToolBarManager toolbar = actionBars.getToolBarManager(); refreshAction = new Action(UIText.StagingView_Refresh, IAction.AS_PUSH_BUTTON) { public void run() { if(cacheEntry != null) cacheEntry.refreshResourcesAndIndexDiff(); } }; refreshAction.setImageDescriptor(UIIcons.ELCL16_REFRESH); toolbar.add(refreshAction); // link with selection Action linkSelectionAction = new BooleanPrefAction( (IPersistentPreferenceStore) getPreferenceStore(), UIPreferences.STAGING_VIEW_SYNC_SELECTION, UIText.StagingView_LinkSelection) { @Override public void apply(boolean value) { reactOnSelection = value; } }; linkSelectionAction.setImageDescriptor(UIIcons.ELCL16_SYNCED); toolbar.add(linkSelectionAction); toolbar.add(new Separator()); amendPreviousCommitAction = new Action( UIText.StagingView_Ammend_Previous_Commit, IAction.AS_CHECK_BOX) { public void run() { commitMessageComponent.setAmendingButtonSelection(isChecked()); updateMessage(); } }; amendPreviousCommitAction.setImageDescriptor(UIIcons.AMEND_COMMIT); toolbar.add(amendPreviousCommitAction); signedOffByAction = new Action(UIText.StagingView_Add_Signed_Off_By, IAction.AS_CHECK_BOX) { public void run() { commitMessageComponent.setSignedOffButtonSelection(isChecked()); } }; signedOffByAction.setImageDescriptor(UIIcons.SIGNED_OFF); toolbar.add(signedOffByAction); addChangeIdAction = new Action(UIText.StagingView_Add_Change_ID, IAction.AS_CHECK_BOX) { public void run() { commitMessageComponent.setChangeIdButtonSelection(isChecked()); } }; addChangeIdAction.setImageDescriptor(UIIcons.GERRIT); toolbar.add(addChangeIdAction); toolbar.add(new Separator()); openNewCommitsAction = new Action(UIText.StagingView_OpenNewCommits, IAction.AS_CHECK_BOX) { public void run() { getPreferenceStore().setValue( UIPreferences.STAGING_VIEW_SHOW_NEW_COMMITS, isChecked()); } }; openNewCommitsAction.setChecked(getPreferenceStore().getBoolean( UIPreferences.STAGING_VIEW_SHOW_NEW_COMMITS)); columnLayoutAction = new Action(UIText.StagingView_ColumnLayout, IAction.AS_CHECK_BOX) { public void run() { getPreferenceStore().setValue( UIPreferences.STAGING_VIEW_COLUMN_LAYOUT, isChecked()); stagingSashForm.setOrientation(isChecked() ? SWT.HORIZONTAL : SWT.VERTICAL); } }; columnLayoutAction.setChecked(getPreferenceStore().getBoolean( UIPreferences.STAGING_VIEW_COLUMN_LAYOUT)); fileNameModeAction = new Action(UIText.StagingView_ShowFileNamesFirst, IAction.AS_CHECK_BOX) { public void run() { final boolean enable = isChecked(); getLabelProvider(stagedTableViewer).setFileNameMode(enable); getLabelProvider(unstagedTableViewer).setFileNameMode(enable); stagedTableViewer.refresh(); unstagedTableViewer.refresh(); getPreferenceStore().setValue( UIPreferences.STAGING_VIEW_FILENAME_MODE, enable); } }; fileNameModeAction.setChecked(getPreferenceStore().getBoolean( UIPreferences.STAGING_VIEW_FILENAME_MODE)); IMenuManager dropdownMenu = actionBars.getMenuManager(); dropdownMenu.add(openNewCommitsAction); dropdownMenu.add(columnLayoutAction); dropdownMenu.add(fileNameModeAction); actionBars.setGlobalActionHandler(ActionFactory.DELETE.getId(), new GlobalDeleteActionHandler()); // For the normal resource undo/redo actions to be active, so that files // deleted via the "Delete" action in the staging view can be restored. IUndoContext workspaceContext = (IUndoContext) ResourcesPlugin.getWorkspace().getAdapter(IUndoContext.class); undoRedoActionGroup = new UndoRedoActionGroup(getViewSite(), workspaceContext, true); undoRedoActionGroup.fillActionBars(actionBars); actionBars.updateActionBars(); } private IBaseLabelProvider createLabelProvider(TableViewer tableViewer) { StagingViewLabelProvider baseProvider = new StagingViewLabelProvider(); baseProvider.setFileNameMode(getPreferenceStore().getBoolean( UIPreferences.STAGING_VIEW_FILENAME_MODE)); ProblemLabelDecorator decorator = new ProblemLabelDecorator(tableViewer); return new DecoratingStyledCellLabelProvider(baseProvider, decorator, null); } private IPreferenceStore getPreferenceStore() { return Activator.getDefault().getPreferenceStore(); } private StagingViewLabelProvider getLabelProvider(ContentViewer viewer) { IBaseLabelProvider base = viewer.getLabelProvider(); IStyledLabelProvider styled = ((DelegatingStyledCellLabelProvider) base) .getStyledStringProvider(); return (StagingViewLabelProvider) styled; } private StagingViewContentProvider getContentProvider(ContentViewer viewer) { return (StagingViewContentProvider) viewer.getContentProvider(); } private void updateSectionText() { Integer stagedCount = Integer.valueOf(stagedTableViewer.getTable() .getItemCount()); stagedSection.setText(MessageFormat.format( UIText.StagingView_StagedChanges, stagedCount)); Integer unstagedCount = Integer.valueOf(unstagedTableViewer.getTable() .getItemCount()); unstagedSection.setText(MessageFormat.format( UIText.StagingView_UnstagedChanges, unstagedCount)); } private void updateMessage() { String message = commitMessageComponent.getStatus().getMessage(); boolean needsRedraw = false; if (message != null) { warningLabel.showMessage(message); needsRedraw = true; } else { needsRedraw = warningLabel.isVisible(); warningLabel.hideMessage(); } // Without this explicit redraw, the ControlDecoration of the // commit message area would not get updated and cause visual // corruption. if (needsRedraw) commitMessageSection.redraw(); } private void compareWith(OpenEvent event) { IStructuredSelection selection = (IStructuredSelection) event .getSelection(); if (selection.isEmpty()) return; StagingEntry stagingEntry = (StagingEntry) selection.getFirstElement(); if (stagingEntry.isSubmodule()) return; switch (stagingEntry.getState()) { case ADDED: case CHANGED: case REMOVED: runCommand(ActionCommands.COMPARE_INDEX_WITH_HEAD_ACTION, selection); break; case MISSING: case MODIFIED: case PARTIALLY_MODIFIED: case CONFLICTING: case UNTRACKED: default: // compare with index runCommand(ActionCommands.COMPARE_WITH_INDEX_ACTION, selection); } } private void createPopupMenu(final TableViewer tableViewer) { final MenuManager menuMgr = new MenuManager(); menuMgr.setRemoveAllWhenShown(true); Control control = tableViewer.getControl(); control.setMenu(menuMgr.createContextMenu(control)); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection(); if (selection.isEmpty()) return; boolean submoduleSelected = false; for (Object item : selection.toArray()) if (((StagingEntry) item).isSubmodule()) { submoduleSelected = true; break; } Action openWorkingTreeVersion = new Action( UIText.CommitFileDiffViewer_OpenWorkingTreeVersionInEditorMenuLabel) { @Override public void run() { openSelectionInEditor(tableViewer.getSelection()); } }; openWorkingTreeVersion.setEnabled(!submoduleSelected); menuMgr.add(openWorkingTreeVersion); Set<StagingEntry.Action> availableActions = getAvailableActions(selection); boolean addReplaceWithFileInGitIndex = availableActions.contains(StagingEntry.Action.REPLACE_WITH_FILE_IN_GIT_INDEX); boolean addReplaceWithHeadRevision = availableActions.contains(StagingEntry.Action.REPLACE_WITH_HEAD_REVISION); boolean addStage = availableActions.contains(StagingEntry.Action.STAGE); boolean addUnstage = availableActions.contains(StagingEntry.Action.UNSTAGE); boolean addDelete = availableActions.contains(StagingEntry.Action.DELETE); boolean addIgnore = availableActions.contains(StagingEntry.Action.IGNORE); boolean addLaunchMergeTool = availableActions.contains(StagingEntry.Action.LAUNCH_MERGE_TOOL); if (addStage) menuMgr.add(new Action(UIText.StagingView_StageItemMenuLabel) { @Override public void run() { stage((IStructuredSelection) tableViewer.getSelection()); } }); if (addUnstage) menuMgr.add(new Action(UIText.StagingView_UnstageItemMenuLabel) { @Override public void run() { unstage((IStructuredSelection) tableViewer.getSelection()); } }); boolean selectionIncludesNonWorkspaceResources = selectionIncludesNonWorkspaceResources(tableViewer.getSelection()); if (addReplaceWithFileInGitIndex) if (selectionIncludesNonWorkspaceResources) menuMgr.add(new ReplaceAction(UIText.StagingView_replaceWithFileInGitIndex, selection, false)); else menuMgr.add(createItem(ActionCommands.DISCARD_CHANGES_ACTION, tableViewer)); // replace with index if (addReplaceWithHeadRevision) if (selectionIncludesNonWorkspaceResources) menuMgr.add(new ReplaceAction(UIText.StagingView_replaceWithHeadRevision, selection, true)); else menuMgr.add(createItem(ActionCommands.REPLACE_WITH_HEAD_ACTION, tableViewer)); if (addIgnore) menuMgr.add(new IgnoreAction(selection)); if (addDelete) menuMgr.add(new DeleteAction(selection)); if (addLaunchMergeTool) menuMgr.add(createItem(ActionCommands.MERGE_TOOL_ACTION, tableViewer)); } }); } private class ReplaceAction extends Action { IStructuredSelection selection; private final boolean headRevision; ReplaceAction(String text, IStructuredSelection selection, boolean headRevision) { super(text); this.selection = selection; this.headRevision = headRevision; } @Override public void run() { boolean performAction = MessageDialog.openConfirm(form.getShell(), UIText.DiscardChangesAction_confirmActionTitle, UIText.DiscardChangesAction_confirmActionMessage); if (!performAction) return ; String[] files = getSelectedFiles(selection); replaceWith(files, headRevision); } } private static class IgnoreAction extends Action { private final IStructuredSelection selection; IgnoreAction(IStructuredSelection selection) { super(UIText.StagingView_IgnoreItemMenuLabel); this.selection = selection; } @Override public void run() { IgnoreOperationUI operation = new IgnoreOperationUI( getSelectedPaths(selection)); operation.run(); } } private class DeleteAction extends Action { private final IStructuredSelection selection; DeleteAction(IStructuredSelection selection) { super(UIText.StagingView_DeleteItemMenuLabel); this.selection = selection; } @Override public void run() { DeletePathsOperationUI operation = new DeletePathsOperationUI( getSelectedPaths(selection), getSite()); operation.run(); } } private class GlobalDeleteActionHandler extends Action { @Override public void run() { DeletePathsOperationUI operation = new DeletePathsOperationUI( getSelectedPaths(getSelection()), getSite()); operation.run(); } @Override public boolean isEnabled() { if (!unstagedTableViewer.getTable().isFocusControl()) return false; IStructuredSelection selection = getSelection(); if (selection.isEmpty()) return false; for (Object element : selection.toList()) { StagingEntry entry = (StagingEntry) element; if (!entry.getAvailableActions().contains(StagingEntry.Action.DELETE)) return false; } return true; } private IStructuredSelection getSelection() { return (IStructuredSelection) unstagedTableViewer.getSelection(); } } private void replaceWith(String[] files, boolean headRevision) { if (files == null || files.length == 0) return; CheckoutCommand checkoutCommand = new Git(currentRepository).checkout(); if (headRevision) checkoutCommand.setStartPoint(Constants.HEAD); for (String path : files) checkoutCommand.addPath(path); try { checkoutCommand.call(); } catch (Exception e) { Activator.handleError(UIText.StagingView_checkoutFailed, e, true); } } private String[] getSelectedFiles(IStructuredSelection selection) { List<String> result = new ArrayList<String>(); Iterator iterator = selection.iterator(); while (iterator.hasNext()) { StagingEntry stagingEntry = (StagingEntry) iterator.next(); result.add(stagingEntry.getPath()); } return result.toArray(new String[result.size()]); } private static List<IPath> getSelectedPaths(IStructuredSelection selection) { List<IPath> paths = new ArrayList<IPath>(); Iterator iterator = selection.iterator(); while (iterator.hasNext()) { StagingEntry stagingEntry = (StagingEntry) iterator.next(); paths.add(stagingEntry.getLocation()); } return paths; } /** * @param selection * @return true if the selection includes a non-workspace resource, false otherwise */ private boolean selectionIncludesNonWorkspaceResources(ISelection selection) { if (!(selection instanceof IStructuredSelection)) return false; IStructuredSelection structuredSelection = (IStructuredSelection) selection; Iterator iterator = structuredSelection.iterator(); while (iterator.hasNext()) { Object selectedObject = iterator.next(); if (!(selectedObject instanceof StagingEntry)) return false; StagingEntry stagingEntry = (StagingEntry) selectedObject; String path = currentRepository.getWorkTree() + "/" + stagingEntry.getPath(); //$NON-NLS-1$ if (getResource(path) == null) return true; } return false; } private IFile getResource(String path) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IFile file = root.getFileForLocation(new Path(path)); if (file == null) return null; if (file.getProject().isAccessible()) return file; return null; } private void openSelectionInEditor(ISelection s) { if (s.isEmpty() || !(s instanceof IStructuredSelection)) return; final IStructuredSelection iss = (IStructuredSelection) s; for (Iterator<StagingEntry> it = iss.iterator(); it.hasNext();) { String relativePath = it.next().getPath(); String path = new Path(currentRepository.getWorkTree() .getAbsolutePath()).append(relativePath) .toOSString(); openFileInEditor(path); } } private void openFileInEditor(String filePath) { IWorkbenchWindow window = PlatformUI.getWorkbench() .getActiveWorkbenchWindow(); File file = new File(filePath); if (!file.exists()) { String message = NLS.bind(UIText.CommitFileDiffViewer_FileDoesNotExist, filePath); Activator.showError(message, null); } IWorkbenchPage page = window.getActivePage(); EgitUiEditorUtils.openEditor(file, page); } private static Set<StagingEntry.Action> getAvailableActions(IStructuredSelection selection) { Set<StagingEntry.Action> availableActions = EnumSet.noneOf(StagingEntry.Action.class); for (Iterator it = selection.iterator(); it.hasNext(); ) { StagingEntry stagingEntry = (StagingEntry) it.next(); if (availableActions.isEmpty()) availableActions.addAll(stagingEntry.getAvailableActions()); else availableActions.retainAll(stagingEntry.getAvailableActions()); } return availableActions; } private CommandContributionItem createItem(String itemAction, final TableViewer tableViewer) { IWorkbench workbench = PlatformUI.getWorkbench(); CommandContributionItemParameter itemParam = new CommandContributionItemParameter( workbench, null, itemAction, STYLE_PUSH); IWorkbenchWindow activeWorkbenchWindow = workbench .getActiveWorkbenchWindow(); IHandlerService hsr = (IHandlerService) activeWorkbenchWindow .getService(IHandlerService.class); IEvaluationContext ctx = hsr.getCurrentState(); ctx.addVariable(ACTIVE_MENU_SELECTION_NAME, tableViewer.getSelection()); return new CommandContributionItem(itemParam); } private void reactOnSelection(ISelection selection) { if (selection instanceof StructuredSelection) { StructuredSelection ssel = (StructuredSelection) selection; if (ssel.size() != 1) return; Object firstElement = ssel.getFirstElement(); if (firstElement instanceof IResource) showResource((IResource) firstElement); else if (firstElement instanceof RepositoryTreeNode) { RepositoryTreeNode repoNode = (RepositoryTreeNode) firstElement; reload(repoNode.getRepository()); } else if (firstElement instanceof IAdaptable) { IResource adapted = (IResource) ((IAdaptable) firstElement).getAdapter(IResource.class); if (adapted != null) showResource(adapted); } } } private void showResource(final IResource resource) { IProject project = resource.getProject(); RepositoryMapping mapping = RepositoryMapping.getMapping(project); if (mapping == null) return; if (mapping.getRepository() != currentRepository) reload(mapping.getRepository()); } private void stage(IStructuredSelection selection) { Git git = new Git(currentRepository); AddCommand add = null; RmCommand rm = null; Iterator iterator = selection.iterator(); while (iterator.hasNext()) { StagingEntry entry = (StagingEntry) iterator.next(); switch (entry.getState()) { case ADDED: case CHANGED: case REMOVED: // already staged break; case CONFLICTING: case MODIFIED: case PARTIALLY_MODIFIED: case UNTRACKED: if (add == null) add = git.add(); add.addFilepattern(entry.getPath()); break; case MISSING: if (rm == null) rm = git.rm(); rm.addFilepattern(entry.getPath()); break; } } if (add != null) try { add.call(); } catch (NoFilepatternException e1) { // cannot happen } catch (Exception e2) { Activator.error(e2.getMessage(), e2); } if (rm != null) try { rm.call(); } catch (NoFilepatternException e) { // cannot happen } catch (Exception e2) { Activator.error(e2.getMessage(), e2); } } private void unstage(IStructuredSelection selection) { if (selection.isEmpty()) return; RevCommit headRev = null; try { final Ref head = currentRepository.getRef(Constants.HEAD); // head.getObjectId() is null if the repository does not contain any // commit if (head.getObjectId() != null) headRev = new RevWalk(currentRepository).parseCommit(head .getObjectId()); } catch (IOException e1) { // TODO fix text MessageDialog.openError(getSite().getShell(), UIText.CommitAction_MergeHeadErrorTitle, UIText.CommitAction_ErrorReadingMergeMsg); return; } final DirCache dirCache; final DirCacheEditor edit; try { dirCache = currentRepository.lockDirCache(); edit = dirCache.editor(); } catch (IOException e) { // TODO fix text MessageDialog.openError(getSite().getShell(), UIText.CommitAction_MergeHeadErrorTitle, UIText.CommitAction_ErrorReadingMergeMsg); return; } try { updateDirCache(selection, headRev, edit); try { edit.commit(); } catch (IOException e) { // TODO fix text MessageDialog.openError(getSite().getShell(), UIText.CommitAction_MergeHeadErrorTitle, UIText.CommitAction_ErrorReadingMergeMsg); } } finally { dirCache.unlock(); } } private void updateDirCache(IStructuredSelection selection, final RevCommit headRev, final DirCacheEditor edit) { Iterator iterator = selection.iterator(); while (iterator.hasNext()) { StagingEntry entry = (StagingEntry) iterator.next(); switch (entry.getState()) { case ADDED: edit.add(new DirCacheEditor.DeletePath(entry.getPath())); break; case CHANGED: case REMOVED: // set the index object id/file mode back to our head revision try { final TreeWalk tw = TreeWalk.forPath(currentRepository, entry.getPath(), headRev.getTree()); if (tw != null) edit.add(new DirCacheEditor.PathEdit(entry.getPath()) { @Override public void apply(DirCacheEntry ent) { ent.setFileMode(tw.getFileMode(0)); ent.setObjectId(tw.getObjectId(0)); // for index & working tree compare ent.setLastModified(0); } }); } catch (IOException e) { // TODO fix text MessageDialog.openError(getSite().getShell(), UIText.CommitAction_MergeHeadErrorTitle, UIText.CommitAction_ErrorReadingMergeMsg); } break; default: // unstaged } } } private boolean isValidRepo(final Repository repository) { return repository != null && !repository.isBare() && repository.getWorkTree().exists() && org.eclipse.egit.core.Activator.getDefault() .getRepositoryUtil().contains(repository); } /** * Clear the view's state. * <p> * This method must be called from the UI-thread */ private void clearRepository() { saveCommitMessageComponentState(); currentRepository = null; StagingViewUpdate update = new StagingViewUpdate(null, null, null); unstagedTableViewer.setInput(update); stagedTableViewer.setInput(update); enableCommitWidgets(false); updateSectionText(); form.setText(UIText.StagingView_NoSelectionTitle); } private void reload(final Repository repository) { if (form.isDisposed()) return; if (repository == null) { asyncExec(new Runnable() { public void run() { clearRepository(); } }); return; } if (!isValidRepo(repository)) return; final boolean repositoryChanged = currentRepository != repository; asyncExec(new Runnable() { public void run() { if (form.isDisposed()) return; final IndexDiffData indexDiff = doReload(repository); boolean indexDiffAvailable = indexDiff != null; final StagingViewUpdate update = new StagingViewUpdate(currentRepository, indexDiff, null); unstagedTableViewer.setInput(update); stagedTableViewer.setInput(update); enableCommitWidgets(indexDiffAvailable); boolean commitEnabled = indexDiffAvailable && repository.getRepositoryState().canCommit(); commitButton.setEnabled(commitEnabled); commitAndPushButton.setEnabled(commitEnabled); form.setText(StagingView.getRepositoryName(repository)); updateCommitMessageComponent(repositoryChanged, indexDiffAvailable); updateSectionText(); } }); } private IndexDiffData doReload(final Repository repository) { currentRepository = repository; IndexDiffCacheEntry entry = org.eclipse.egit.core.Activator.getDefault().getIndexDiffCache().getIndexDiffCacheEntry(currentRepository); if(cacheEntry != null && cacheEntry != entry) cacheEntry.removeIndexDiffChangedListener(myIndexDiffListener); cacheEntry = entry; cacheEntry.addIndexDiffChangedListener(myIndexDiffListener); return cacheEntry.getIndexDiff(); } private void clearCommitMessageToggles() { amendPreviousCommitAction.setChecked(false); addChangeIdAction.setChecked(false); signedOffByAction.setChecked(false); } void updateCommitMessageComponent(boolean repositoryChanged, boolean indexDiffAvailable) { CommitHelper helper = new CommitHelper(currentRepository); CommitMessageComponentState oldState = null; if (repositoryChanged) { if (userEnteredCommmitMessage()) saveCommitMessageComponentState(); else deleteCommitMessageComponentState(); oldState = loadCommitMessageComponentState(); commitMessageComponent.setRepository(currentRepository); if (oldState == null) loadInitialState(helper); else loadExistingState(helper, oldState); } else // repository did not change if (userEnteredCommmitMessage()) { if (!commitMessageComponent.getHeadCommit().equals( helper.getPreviousCommit())) addHeadChangedWarning(commitMessageComponent .getCommitMessage()); } else loadInitialState(helper); amendPreviousCommitAction.setChecked(commitMessageComponent .isAmending()); amendPreviousCommitAction.setEnabled(indexDiffAvailable && helper.amendAllowed()); updateMessage(); } private void loadExistingState(CommitHelper helper, CommitMessageComponentState oldState) { boolean headCommitChanged = !oldState.getHeadCommit().equals( getCommitId(helper.getPreviousCommit())); commitMessageComponent.enableListers(false); commitMessageComponent.setAuthor(oldState.getAuthor()); if (headCommitChanged) addHeadChangedWarning(oldState.getCommitMessage()); else commitMessageComponent .setCommitMessage(oldState.getCommitMessage()); commitMessageComponent.setCommitter(oldState.getCommitter()); commitMessageComponent.setHeadCommit(getCommitId(helper .getPreviousCommit())); commitMessageComponent.setCommitAllowed(helper.canCommit()); commitMessageComponent.setCannotCommitMessage(helper.getCannotCommitMessage()); boolean amendAllowed = helper.amendAllowed(); commitMessageComponent.setAmendAllowed(amendAllowed); if (!amendAllowed) commitMessageComponent.setAmending(false); else if (!headCommitChanged && oldState.getAmend()) commitMessageComponent.setAmending(true); else commitMessageComponent.setAmending(false); commitMessageComponent.updateUIFromState(); commitMessageComponent.updateSignedOffAndChangeIdButton(); commitMessageComponent.enableListers(true); } private void addHeadChangedWarning(String commitMessage) { String message = UIText.StagingView_headCommitChanged + Text.DELIMITER + Text.DELIMITER + commitMessage; commitMessageComponent.setCommitMessage(message); } private void loadInitialState(CommitHelper helper) { commitMessageComponent.enableListers(false); commitMessageComponent.resetState(); commitMessageComponent.setAuthor(helper.getAuthor()); commitMessageComponent.setCommitMessage(helper.getCommitMessage()); commitMessageComponent.setCommitter(helper.getCommitter()); commitMessageComponent.setHeadCommit(getCommitId(helper .getPreviousCommit())); commitMessageComponent.setCommitAllowed(helper.canCommit()); commitMessageComponent.setCannotCommitMessage(helper.getCannotCommitMessage()); commitMessageComponent.setAmendAllowed(helper.amendAllowed()); commitMessageComponent.setAmending(false); // set the defaults for change id and signed off buttons. commitMessageComponent.setDefaults(); commitMessageComponent.updateUI(); commitMessageComponent.enableListers(true); } private boolean userEnteredCommmitMessage() { if (commitMessageComponent.getRepository() == null) return false; String message = commitMessageComponent.getCommitMessage().replace( UIText.StagingView_headCommitChanged, ""); //$NON-NLS-1$ if (message == null || message.trim().length() == 0) return false; String chIdLine = "Change-Id: I" + ObjectId.zeroId().name(); //$NON-NLS-1$ if (currentRepository.getConfig().getBoolean( ConfigConstants.CONFIG_GERRIT_SECTION, ConfigConstants.CONFIG_KEY_CREATECHANGEID, false) && commitMessageComponent.getCreateChangeId()) { if (message.trim().equals(chIdLine)) return false; // change id was added automatically, but ther is more in the // message; strip the id, and check for the signed-off-by tag message = message.replace(chIdLine, ""); //$NON-NLS-1$ } if (org.eclipse.egit.ui.Activator.getDefault().getPreferenceStore() .getBoolean(UIPreferences.COMMIT_DIALOG_SIGNED_OFF_BY) && commitMessageComponent.isSignedOff() && message.trim().equals( Constants.SIGNED_OFF_BY_TAG + commitMessageComponent.getCommitter())) return false; return true; } private ObjectId getCommitId(RevCommit commit) { if (commit == null) return ObjectId.zeroId(); return commit.getId(); } private void saveCommitMessageComponentState() { final Repository repo = commitMessageComponent.getRepository(); if (repo != null) CommitMessageComponentStateManager.persistState(repo, commitMessageComponent.getState()); } private void deleteCommitMessageComponentState() { if (commitMessageComponent.getRepository() != null) CommitMessageComponentStateManager .deleteState(commitMessageComponent.getRepository()); } private CommitMessageComponentState loadCommitMessageComponentState() { return CommitMessageComponentStateManager.loadState(currentRepository); } private static String getRepositoryName(Repository repository) { String repoName = Activator.getDefault().getRepositoryUtil() .getRepositoryName(repository); RepositoryState state = repository.getRepositoryState(); if (state != RepositoryState.SAFE) return repoName + '|' + state.getDescription(); else return repoName; } private Collection<String> getStagedFileNames() { StagingViewContentProvider stagedContentProvider = getContentProvider(stagedTableViewer); StagingEntry[] entries = stagedContentProvider.getStagingEntries(); List<String> files = new ArrayList<String>(); for (StagingEntry entry : entries) files.add(entry.getPath()); return files; } private void commit(boolean pushUpstream) { if (!isCommitWithoutFilesAllowed()) { MessageDialog.openError(getSite().getShell(), UIText.StagingView_committingNotPossible, UIText.StagingView_noStagedFiles); return; } if (!commitMessageComponent.checkCommitInfo()) return; if (!UIUtils.saveAllEditors(currentRepository)) return; String commitMessage = commitMessageComponent.getCommitMessage(); CommitOperation commitOperation = null; try { commitOperation = new CommitOperation(currentRepository, commitMessageComponent.getAuthor(), commitMessageComponent.getCommitter(), commitMessage); } catch (CoreException e) { Activator.handleError(UIText.StagingView_commitFailed, e, true); return; } if (amendPreviousCommitAction.isChecked()) commitOperation.setAmending(true); commitOperation.setComputeChangeId(addChangeIdAction.isChecked()); Job commitJob = new CommitJob(currentRepository, commitOperation) .setOpenCommitEditor(openNewCommitsAction.isChecked()) .setPushUpstream(pushUpstream); commitJob.schedule(); CommitMessageHistory.saveCommitHistory(commitMessage); clearCommitMessageToggles(); commitMessageText.setText(EMPTY_STRING); } private boolean isCommitWithoutFilesAllowed() { if (stagedTableViewer.getTable().getItemCount() > 0) return true; if (amendPreviousCommitAction.isChecked()) return true; return CommitHelper.isCommitWithoutFilesAllowed(currentRepository); } @Override public void setFocus() { unstagedTableViewer.getControl().setFocus(); } @Override public void dispose() { super.dispose(); ISelectionService srv = (ISelectionService) getSite().getService( ISelectionService.class); srv.removePostSelectionListener(selectionChangedListener); if(cacheEntry != null) cacheEntry.removeIndexDiffChangedListener(myIndexDiffListener); if (undoRedoActionGroup != null) undoRedoActionGroup.dispose(); InstanceScope.INSTANCE.getNode( org.eclipse.egit.core.Activator.getPluginId()) .removePreferenceChangeListener(prefListener); } private void asyncExec(Runnable runnable) { PlatformUI.getWorkbench().getDisplay().asyncExec(runnable); } }
org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/staging/StagingView.java
/******************************************************************************* * Copyright (C) 2011, 2012 Bernard Leach <[email protected]> and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.egit.ui.internal.staging; import static org.eclipse.egit.ui.internal.CommonUtils.runCommand; import static org.eclipse.ui.ISources.ACTIVE_MENU_SELECTION_NAME; import static org.eclipse.ui.menus.CommandContributionItem.STYLE_PUSH; import java.io.File; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.eclipse.core.commands.operations.IUndoContext; import org.eclipse.core.expressions.IEvaluationContext; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.preferences.IEclipsePreferences.IPreferenceChangeListener; import org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.egit.core.RepositoryUtil; import org.eclipse.egit.core.internal.indexdiff.IndexDiffCacheEntry; import org.eclipse.egit.core.internal.indexdiff.IndexDiffChangedListener; import org.eclipse.egit.core.internal.indexdiff.IndexDiffData; import org.eclipse.egit.core.op.CommitOperation; import org.eclipse.egit.core.project.RepositoryMapping; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.UIIcons; import org.eclipse.egit.ui.UIPreferences; import org.eclipse.egit.ui.UIText; import org.eclipse.egit.ui.UIUtils; import org.eclipse.egit.ui.internal.EgitUiEditorUtils; import org.eclipse.egit.ui.internal.actions.ActionCommands; import org.eclipse.egit.ui.internal.actions.BooleanPrefAction; import org.eclipse.egit.ui.internal.commit.CommitHelper; import org.eclipse.egit.ui.internal.commit.CommitJob; import org.eclipse.egit.ui.internal.commit.CommitMessageHistory; import org.eclipse.egit.ui.internal.commit.CommitProposalProcessor; import org.eclipse.egit.ui.internal.components.ToggleableWarningLabel; import org.eclipse.egit.ui.internal.decorators.ProblemLabelDecorator; import org.eclipse.egit.ui.internal.dialogs.CommitMessageArea; import org.eclipse.egit.ui.internal.dialogs.CommitMessageComponent; import org.eclipse.egit.ui.internal.dialogs.CommitMessageComponentState; import org.eclipse.egit.ui.internal.dialogs.CommitMessageComponentStateManager; import org.eclipse.egit.ui.internal.dialogs.ICommitMessageComponentNotifications; import org.eclipse.egit.ui.internal.dialogs.SpellcheckableMessageArea; import org.eclipse.egit.ui.internal.operations.DeletePathsOperationUI; import org.eclipse.egit.ui.internal.operations.IgnoreOperationUI; import org.eclipse.egit.ui.internal.repository.tree.RepositoryTreeNode; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.preference.IPersistentPreferenceStore; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.LocalSelectionTransfer; import org.eclipse.jface.viewers.ContentViewer; import org.eclipse.jface.viewers.DecoratingStyledCellLabelProvider; import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider; import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider; import org.eclipse.jface.viewers.IBaseLabelProvider; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jgit.api.AddCommand; import org.eclipse.jgit.api.CheckoutCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.RmCommand; import org.eclipse.jgit.api.errors.NoFilepatternException; import org.eclipse.jgit.dircache.DirCache; import org.eclipse.jgit.dircache.DirCacheEditor; import org.eclipse.jgit.dircache.DirCacheEntry; import org.eclipse.jgit.lib.ConfigConstants; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.RepositoryState; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.VerifyKeyListener; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSourceAdapter; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.DropTargetAdapter; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.ISelectionService; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.forms.IFormColors; import org.eclipse.ui.forms.widgets.ExpandableComposite; import org.eclipse.ui.forms.widgets.Form; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Section; import org.eclipse.ui.handlers.IHandlerService; import org.eclipse.ui.menus.CommandContributionItem; import org.eclipse.ui.menus.CommandContributionItemParameter; import org.eclipse.ui.operations.UndoRedoActionGroup; import org.eclipse.ui.part.ViewPart; /** * A GitX style staging view with embedded commit dialog. */ public class StagingView extends ViewPart { /** * Staging view id */ public static final String VIEW_ID = "org.eclipse.egit.ui.StagingView"; //$NON-NLS-1$ private static final String EMPTY_STRING = ""; //$NON-NLS-1$ private Form form; private Section stagedSection; private Section unstagedSection; private Section commitMessageSection; private TableViewer stagedTableViewer; private TableViewer unstagedTableViewer; private ToggleableWarningLabel warningLabel; private SpellcheckableMessageArea commitMessageText; private Text committerText; private Text authorText; private CommitMessageComponent commitMessageComponent; private boolean reactOnSelection = true; private ISelectionListener selectionChangedListener; private Repository currentRepository; static class StagingViewUpdate { Repository repository; IndexDiffData indexDiff; Collection<String> changedResources; StagingViewUpdate(Repository theRepository, IndexDiffData theIndexDiff, Collection<String> theChanges) { this.repository = theRepository; this.indexDiff = theIndexDiff; this.changedResources = theChanges; } } static class StagingDragListener extends DragSourceAdapter { private ISelectionProvider provider; public StagingDragListener(ISelectionProvider provider) { this.provider = provider; } public void dragStart(DragSourceEvent event) { event.doit = !provider.getSelection().isEmpty(); } public void dragFinished(DragSourceEvent event) { if (LocalSelectionTransfer.getTransfer().isSupportedType( event.dataType)) LocalSelectionTransfer.getTransfer().setSelection(null); } public void dragSetData(DragSourceEvent event) { IStructuredSelection selection = (IStructuredSelection) provider .getSelection(); if (selection.isEmpty()) return; if (LocalSelectionTransfer.getTransfer().isSupportedType( event.dataType)) { LocalSelectionTransfer.getTransfer().setSelection(selection); return; } if (FileTransfer.getInstance().isSupportedType(event.dataType)) { List<String> files = new ArrayList<String>(); for (Object selected : selection.toList()) if (selected instanceof StagingEntry) { StagingEntry entry = (StagingEntry) selected; File file = new File( entry.getRepository().getWorkTree(), entry.getPath()); if (file.exists()) files.add(file.getAbsolutePath()); } if (!files.isEmpty()) { event.data = files.toArray(new String[files.size()]); return; } } } } private final IPreferenceChangeListener prefListener = new IPreferenceChangeListener() { public void preferenceChange(PreferenceChangeEvent event) { if (!RepositoryUtil.PREFS_DIRECTORIES.equals(event.getKey())) return; final Repository repo = currentRepository; if (repo == null) return; if (Activator.getDefault().getRepositoryUtil().contains(repo)) return; reload(null); } }; private Action signedOffByAction; private Action addChangeIdAction; private Action amendPreviousCommitAction; private Action openNewCommitsAction; private Action columnLayoutAction; private Action fileNameModeAction; private Action refreshAction; private SashForm stagingSashForm; private IndexDiffChangedListener myIndexDiffListener = new IndexDiffChangedListener() { public void indexDiffChanged(Repository repository, IndexDiffData indexDiffData) { reload(repository); } }; private IndexDiffCacheEntry cacheEntry; private UndoRedoActionGroup undoRedoActionGroup; private Button commitButton; private Button commitAndPushButton; @Override public void createPartControl(Composite parent) { GridLayoutFactory.fillDefaults().applyTo(parent); final FormToolkit toolkit = new FormToolkit(parent.getDisplay()); parent.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { toolkit.dispose(); } }); form = toolkit.createForm(parent); Image repoImage = UIIcons.REPOSITORY.createImage(); UIUtils.hookDisposal(form, repoImage); form.setImage(repoImage); form.setText(UIText.StagingView_NoSelectionTitle); GridDataFactory.fillDefaults().grab(true, true).applyTo(form); toolkit.decorateFormHeading(form); GridLayoutFactory.swtDefaults().applyTo(form.getBody()); SashForm horizontalSashForm = new SashForm(form.getBody(), SWT.NONE); toolkit.adapt(horizontalSashForm, true, true); GridDataFactory.fillDefaults().grab(true, true) .applyTo(horizontalSashForm); stagingSashForm = new SashForm(horizontalSashForm, getStagingFormOrientation()); toolkit.adapt(stagingSashForm, true, true); GridDataFactory.fillDefaults().grab(true, true) .applyTo(stagingSashForm); unstagedSection = toolkit.createSection(stagingSashForm, ExpandableComposite.TITLE_BAR); Composite unstagedTableComposite = toolkit .createComposite(unstagedSection); toolkit.paintBordersFor(unstagedTableComposite); unstagedSection.setClient(unstagedTableComposite); GridLayoutFactory.fillDefaults().extendedMargins(2, 2, 2, 2) .applyTo(unstagedTableComposite); unstagedTableViewer = new TableViewer(toolkit.createTable( unstagedTableComposite, SWT.FULL_SELECTION | SWT.MULTI)); GridDataFactory.fillDefaults().grab(true, true) .applyTo(unstagedTableViewer.getControl()); unstagedTableViewer.getTable().setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TREE_BORDER); unstagedTableViewer.getTable().setLinesVisible(true); unstagedTableViewer.setLabelProvider(createLabelProvider(unstagedTableViewer)); unstagedTableViewer.setContentProvider(new StagingViewContentProvider( true)); unstagedTableViewer.addDragSupport(DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK, new Transfer[] { LocalSelectionTransfer.getTransfer(), FileTransfer.getInstance() }, new StagingDragListener( unstagedTableViewer)); unstagedTableViewer.addDropSupport(DND.DROP_MOVE, new Transfer[] { LocalSelectionTransfer.getTransfer() }, new DropTargetAdapter() { public void drop(DropTargetEvent event) { if (event.data instanceof IStructuredSelection) { final IStructuredSelection selection = (IStructuredSelection) event.data; if (selection.getFirstElement() instanceof StagingEntry) unstage(selection); } } public void dragOver(DropTargetEvent event) { event.detail = DND.DROP_MOVE; } }); unstagedTableViewer.addOpenListener(new IOpenListener() { public void open(OpenEvent event) { compareWith(event); } }); commitMessageSection = toolkit.createSection( horizontalSashForm, ExpandableComposite.TITLE_BAR); commitMessageSection.setText(UIText.StagingView_CommitMessage); Composite commitMessageComposite = toolkit .createComposite(commitMessageSection); commitMessageSection.setClient(commitMessageComposite); GridLayoutFactory.fillDefaults().numColumns(1) .applyTo(commitMessageComposite); warningLabel = new ToggleableWarningLabel(commitMessageComposite, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).exclude(true) .applyTo(warningLabel); Composite commitMessageTextComposite = toolkit .createComposite(commitMessageComposite); toolkit.paintBordersFor(commitMessageTextComposite); GridDataFactory.fillDefaults().grab(true, true) .applyTo(commitMessageTextComposite); GridLayoutFactory.fillDefaults().numColumns(1) .extendedMargins(2, 2, 2, 2) .applyTo(commitMessageTextComposite); final CommitProposalProcessor commitProposalProcessor = new CommitProposalProcessor() { @Override protected Collection<String> computeFileNameProposals() { return getStagedFileNames(); } @Override protected Collection<String> computeMessageProposals() { return CommitMessageHistory.getCommitHistory(); } }; commitMessageText = new CommitMessageArea(commitMessageTextComposite, EMPTY_STRING, toolkit.getBorderStyle()) { @Override protected CommitProposalProcessor getCommitProposalProcessor() { return commitProposalProcessor; } @Override protected IHandlerService getHandlerService() { return (IHandlerService) getSite().getService(IHandlerService.class); } }; commitMessageText.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); GridDataFactory.fillDefaults().grab(true, true) .applyTo(commitMessageText); UIUtils.addBulbDecorator(commitMessageText.getTextWidget(), UIText.CommitDialog_ContentAssist); Composite composite = toolkit.createComposite(commitMessageComposite); toolkit.paintBordersFor(composite); GridDataFactory.fillDefaults().grab(true, false).applyTo(composite); GridLayoutFactory.swtDefaults().numColumns(2).applyTo(composite); toolkit.createLabel(composite, UIText.StagingView_Author) .setForeground( toolkit.getColors().getColor(IFormColors.TB_TOGGLE)); authorText = toolkit.createText(composite, null); authorText .setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); authorText.setLayoutData(GridDataFactory.fillDefaults() .grab(true, false).create()); toolkit.createLabel(composite, UIText.StagingView_Committer) .setForeground( toolkit.getColors().getColor(IFormColors.TB_TOGGLE)); committerText = toolkit.createText(composite, null); committerText.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); committerText.setLayoutData(GridDataFactory.fillDefaults() .grab(true, false).create()); Composite buttonsContainer = toolkit.createComposite(composite); GridDataFactory.fillDefaults().grab(true, false).span(2,1).indent(0, 8) .applyTo(buttonsContainer); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(buttonsContainer); Label filler = toolkit.createLabel(buttonsContainer, ""); //$NON-NLS-1$ GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(filler); Composite commitButtonsContainer = toolkit.createComposite(buttonsContainer); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER) .applyTo(commitButtonsContainer); GridLayoutFactory.fillDefaults().numColumns(2).equalWidth(true).applyTo(commitButtonsContainer); this.commitAndPushButton = toolkit.createButton(commitButtonsContainer, UIText.StagingView_CommitAndPush, SWT.PUSH); commitAndPushButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { commit(true); } }); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER) .applyTo(commitAndPushButton); this.commitButton = toolkit.createButton(commitButtonsContainer, UIText.StagingView_Commit, SWT.PUSH); commitButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { commit(false); } }); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER) .applyTo(commitButton); stagedSection = toolkit.createSection(stagingSashForm, ExpandableComposite.TITLE_BAR); Composite stagedTableComposite = toolkit.createComposite(stagedSection); toolkit.paintBordersFor(stagedTableComposite); stagedSection.setClient(stagedTableComposite); GridLayoutFactory.fillDefaults().extendedMargins(2, 2, 2, 2) .applyTo(stagedTableComposite); stagedTableViewer = new TableViewer(toolkit.createTable( stagedTableComposite, SWT.FULL_SELECTION | SWT.MULTI)); GridDataFactory.fillDefaults().grab(true, true) .applyTo(stagedTableViewer.getControl()); stagedTableViewer.getTable().setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TREE_BORDER); stagedTableViewer.getTable().setLinesVisible(true); stagedTableViewer.setLabelProvider(createLabelProvider(stagedTableViewer)); stagedTableViewer.setContentProvider(new StagingViewContentProvider( false)); stagedTableViewer.addDragSupport( DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK, new Transfer[] { LocalSelectionTransfer.getTransfer(), FileTransfer.getInstance() }, new StagingDragListener( stagedTableViewer)); stagedTableViewer.addDropSupport(DND.DROP_MOVE, new Transfer[] { LocalSelectionTransfer.getTransfer() }, new DropTargetAdapter() { public void drop(DropTargetEvent event) { if (event.data instanceof IStructuredSelection) { final IStructuredSelection selection = (IStructuredSelection) event.data; if (selection.getFirstElement() instanceof StagingEntry) stage(selection); } } public void dragOver(DropTargetEvent event) { event.detail = DND.DROP_MOVE; } }); stagedTableViewer.addOpenListener(new IOpenListener() { public void open(OpenEvent event) { compareWith(event); } }); selectionChangedListener = new ISelectionListener() { public void selectionChanged(IWorkbenchPart part, ISelection selection) { if (!reactOnSelection || part == getSite().getPart()) return; // this may happen if we switch between editors if (part instanceof IEditorPart) { IEditorInput input = ((IEditorPart) part).getEditorInput(); if (input instanceof IFileEditorInput) reactOnSelection(new StructuredSelection( ((IFileEditorInput) input).getFile())); } else reactOnSelection(selection); } }; IPreferenceStore preferenceStore = getPreferenceStore(); if (preferenceStore.contains(UIPreferences.STAGING_VIEW_SYNC_SELECTION)) reactOnSelection = preferenceStore.getBoolean( UIPreferences.STAGING_VIEW_SYNC_SELECTION); else preferenceStore.setDefault(UIPreferences.STAGING_VIEW_SYNC_SELECTION, true); InstanceScope.INSTANCE.getNode( org.eclipse.egit.core.Activator.getPluginId()) .addPreferenceChangeListener(prefListener); updateSectionText(); updateToolbar(); enableCommitWidgets(false); createPopupMenu(unstagedTableViewer); createPopupMenu(stagedTableViewer); final ICommitMessageComponentNotifications listener = new ICommitMessageComponentNotifications() { public void updateSignedOffToggleSelection(boolean selection) { signedOffByAction.setChecked(selection); } public void updateChangeIdToggleSelection(boolean selection) { addChangeIdAction.setChecked(selection); } }; commitMessageComponent = new CommitMessageComponent(listener); commitMessageComponent.attachControls(commitMessageText, authorText, committerText); // allow to commit with ctrl-enter commitMessageText.getTextWidget().addVerifyKeyListener(new VerifyKeyListener() { public void verifyKey(VerifyEvent event) { if (UIUtils.isSubmitKeyEvent(event)) { event.doit = false; commit(false); } } }); commitMessageText.getTextWidget().addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { // Ctrl+Enter shortcut only works when the focus is on the commit message text String commitButtonTooltip = MessageFormat.format( UIText.StagingView_CommitToolTip, UIUtils.SUBMIT_KEY_STROKE.format()); commitButton.setToolTipText(commitButtonTooltip); } public void focusLost(FocusEvent e) { commitButton.setToolTipText(null); } }); ModifyListener modifyListener = new ModifyListener() { public void modifyText(ModifyEvent e) { updateMessage(); } }; authorText.addModifyListener(modifyListener); committerText.addModifyListener(modifyListener); // react on selection changes IWorkbenchPartSite site = getSite(); ISelectionService srv = (ISelectionService) site .getService(ISelectionService.class); srv.addPostSelectionListener(selectionChangedListener); // Use current selection to populate staging view ISelection selection = srv.getSelection(); if (selection != null && !selection.isEmpty()) { IWorkbenchPart part = site.getPage().getActivePart(); if (part != null) selectionChangedListener.selectionChanged(part, selection); } site.setSelectionProvider(unstagedTableViewer); } private int getStagingFormOrientation() { boolean columnLayout = Activator.getDefault().getPreferenceStore() .getBoolean(UIPreferences.STAGING_VIEW_COLUMN_LAYOUT); if (columnLayout) return SWT.HORIZONTAL; else return SWT.VERTICAL; } private void enableCommitWidgets(boolean enabled) { if (!enabled) { commitMessageText.setText(""); //$NON-NLS-1$ committerText.setText(""); //$NON-NLS-1$ authorText.setText(""); //$NON-NLS-1$ } commitMessageText.setEnabled(enabled); committerText.setEnabled(enabled); authorText.setEnabled(enabled); refreshAction.setEnabled(enabled); amendPreviousCommitAction.setEnabled(enabled); signedOffByAction.setEnabled(enabled); addChangeIdAction.setEnabled(enabled); commitButton.setEnabled(enabled); commitAndPushButton.setEnabled(enabled); } private void updateToolbar() { IActionBars actionBars = getViewSite().getActionBars(); IToolBarManager toolbar = actionBars.getToolBarManager(); refreshAction = new Action(UIText.StagingView_Refresh, IAction.AS_PUSH_BUTTON) { public void run() { if(cacheEntry != null) cacheEntry.refreshResourcesAndIndexDiff(); } }; refreshAction.setImageDescriptor(UIIcons.ELCL16_REFRESH); toolbar.add(refreshAction); // link with selection Action linkSelectionAction = new BooleanPrefAction( (IPersistentPreferenceStore) getPreferenceStore(), UIPreferences.STAGING_VIEW_SYNC_SELECTION, UIText.StagingView_LinkSelection) { @Override public void apply(boolean value) { reactOnSelection = value; } }; linkSelectionAction.setImageDescriptor(UIIcons.ELCL16_SYNCED); toolbar.add(linkSelectionAction); toolbar.add(new Separator()); amendPreviousCommitAction = new Action( UIText.StagingView_Ammend_Previous_Commit, IAction.AS_CHECK_BOX) { public void run() { commitMessageComponent.setAmendingButtonSelection(isChecked()); updateMessage(); } }; amendPreviousCommitAction.setImageDescriptor(UIIcons.AMEND_COMMIT); toolbar.add(amendPreviousCommitAction); signedOffByAction = new Action(UIText.StagingView_Add_Signed_Off_By, IAction.AS_CHECK_BOX) { public void run() { commitMessageComponent.setSignedOffButtonSelection(isChecked()); } }; signedOffByAction.setImageDescriptor(UIIcons.SIGNED_OFF); toolbar.add(signedOffByAction); addChangeIdAction = new Action(UIText.StagingView_Add_Change_ID, IAction.AS_CHECK_BOX) { public void run() { commitMessageComponent.setChangeIdButtonSelection(isChecked()); } }; addChangeIdAction.setImageDescriptor(UIIcons.GERRIT); toolbar.add(addChangeIdAction); toolbar.add(new Separator()); openNewCommitsAction = new Action(UIText.StagingView_OpenNewCommits, IAction.AS_CHECK_BOX) { public void run() { getPreferenceStore().setValue( UIPreferences.STAGING_VIEW_SHOW_NEW_COMMITS, isChecked()); } }; openNewCommitsAction.setChecked(getPreferenceStore().getBoolean( UIPreferences.STAGING_VIEW_SHOW_NEW_COMMITS)); columnLayoutAction = new Action(UIText.StagingView_ColumnLayout, IAction.AS_CHECK_BOX) { public void run() { getPreferenceStore().setValue( UIPreferences.STAGING_VIEW_COLUMN_LAYOUT, isChecked()); stagingSashForm.setOrientation(isChecked() ? SWT.HORIZONTAL : SWT.VERTICAL); } }; columnLayoutAction.setChecked(getPreferenceStore().getBoolean( UIPreferences.STAGING_VIEW_COLUMN_LAYOUT)); fileNameModeAction = new Action(UIText.StagingView_ShowFileNamesFirst, IAction.AS_CHECK_BOX) { public void run() { final boolean enable = isChecked(); getLabelProvider(stagedTableViewer).setFileNameMode(enable); getLabelProvider(unstagedTableViewer).setFileNameMode(enable); stagedTableViewer.refresh(); unstagedTableViewer.refresh(); getPreferenceStore().setValue( UIPreferences.STAGING_VIEW_FILENAME_MODE, enable); } }; fileNameModeAction.setChecked(getPreferenceStore().getBoolean( UIPreferences.STAGING_VIEW_FILENAME_MODE)); IMenuManager dropdownMenu = actionBars.getMenuManager(); dropdownMenu.add(openNewCommitsAction); dropdownMenu.add(columnLayoutAction); dropdownMenu.add(fileNameModeAction); actionBars.setGlobalActionHandler(ActionFactory.DELETE.getId(), new GlobalDeleteActionHandler()); // For the normal resource undo/redo actions to be active, so that files // deleted via the "Delete" action in the staging view can be restored. IUndoContext workspaceContext = (IUndoContext) ResourcesPlugin.getWorkspace().getAdapter(IUndoContext.class); undoRedoActionGroup = new UndoRedoActionGroup(getViewSite(), workspaceContext, true); undoRedoActionGroup.fillActionBars(actionBars); actionBars.updateActionBars(); } private IBaseLabelProvider createLabelProvider(TableViewer tableViewer) { StagingViewLabelProvider baseProvider = new StagingViewLabelProvider(); baseProvider.setFileNameMode(getPreferenceStore().getBoolean( UIPreferences.STAGING_VIEW_FILENAME_MODE)); ProblemLabelDecorator decorator = new ProblemLabelDecorator(tableViewer); return new DecoratingStyledCellLabelProvider(baseProvider, decorator, null); } private IPreferenceStore getPreferenceStore() { return Activator.getDefault().getPreferenceStore(); } private StagingViewLabelProvider getLabelProvider(ContentViewer viewer) { IBaseLabelProvider base = viewer.getLabelProvider(); IStyledLabelProvider styled = ((DelegatingStyledCellLabelProvider) base) .getStyledStringProvider(); return (StagingViewLabelProvider) styled; } private StagingViewContentProvider getContentProvider(ContentViewer viewer) { return (StagingViewContentProvider) viewer.getContentProvider(); } private void updateSectionText() { Integer stagedCount = Integer.valueOf(stagedTableViewer.getTable() .getItemCount()); stagedSection.setText(MessageFormat.format( UIText.StagingView_StagedChanges, stagedCount)); Integer unstagedCount = Integer.valueOf(unstagedTableViewer.getTable() .getItemCount()); unstagedSection.setText(MessageFormat.format( UIText.StagingView_UnstagedChanges, unstagedCount)); } private void updateMessage() { String message = commitMessageComponent.getStatus().getMessage(); boolean needsRedraw = false; if (message != null) { warningLabel.showMessage(message); needsRedraw = true; } else { needsRedraw = warningLabel.isVisible(); warningLabel.hideMessage(); } // Without this explicit redraw, the ControlDecoration of the // commit message area would not get updated and cause visual // corruption. if (needsRedraw) commitMessageSection.redraw(); } private void compareWith(OpenEvent event) { IStructuredSelection selection = (IStructuredSelection) event .getSelection(); if (selection.isEmpty()) return; StagingEntry stagingEntry = (StagingEntry) selection.getFirstElement(); if (stagingEntry.isSubmodule()) return; switch (stagingEntry.getState()) { case ADDED: case CHANGED: case REMOVED: runCommand(ActionCommands.COMPARE_INDEX_WITH_HEAD_ACTION, selection); break; case MISSING: case MODIFIED: case PARTIALLY_MODIFIED: case CONFLICTING: case UNTRACKED: default: // compare with index runCommand(ActionCommands.COMPARE_WITH_INDEX_ACTION, selection); } } private void createPopupMenu(final TableViewer tableViewer) { final MenuManager menuMgr = new MenuManager(); menuMgr.setRemoveAllWhenShown(true); Control control = tableViewer.getControl(); control.setMenu(menuMgr.createContextMenu(control)); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection(); if (selection.isEmpty()) return; boolean submoduleSelected = false; for (Object item : selection.toArray()) if (((StagingEntry) item).isSubmodule()) { submoduleSelected = true; break; } Action openWorkingTreeVersion = new Action( UIText.CommitFileDiffViewer_OpenWorkingTreeVersionInEditorMenuLabel) { @Override public void run() { openSelectionInEditor(tableViewer.getSelection()); } }; openWorkingTreeVersion.setEnabled(!submoduleSelected); menuMgr.add(openWorkingTreeVersion); Set<StagingEntry.Action> availableActions = getAvailableActions(selection); boolean addReplaceWithFileInGitIndex = availableActions.contains(StagingEntry.Action.REPLACE_WITH_FILE_IN_GIT_INDEX); boolean addReplaceWithHeadRevision = availableActions.contains(StagingEntry.Action.REPLACE_WITH_HEAD_REVISION); boolean addStage = availableActions.contains(StagingEntry.Action.STAGE); boolean addUnstage = availableActions.contains(StagingEntry.Action.UNSTAGE); boolean addDelete = availableActions.contains(StagingEntry.Action.DELETE); boolean addIgnore = availableActions.contains(StagingEntry.Action.IGNORE); boolean addLaunchMergeTool = availableActions.contains(StagingEntry.Action.LAUNCH_MERGE_TOOL); if (addStage) menuMgr.add(new Action(UIText.StagingView_StageItemMenuLabel) { @Override public void run() { stage((IStructuredSelection) tableViewer.getSelection()); } }); if (addUnstage) menuMgr.add(new Action(UIText.StagingView_UnstageItemMenuLabel) { @Override public void run() { unstage((IStructuredSelection) tableViewer.getSelection()); } }); boolean selectionIncludesNonWorkspaceResources = selectionIncludesNonWorkspaceResources(tableViewer.getSelection()); if (addReplaceWithFileInGitIndex) if (selectionIncludesNonWorkspaceResources) menuMgr.add(new ReplaceAction(UIText.StagingView_replaceWithFileInGitIndex, selection, false)); else menuMgr.add(createItem(ActionCommands.DISCARD_CHANGES_ACTION, tableViewer)); // replace with index if (addReplaceWithHeadRevision) if (selectionIncludesNonWorkspaceResources) menuMgr.add(new ReplaceAction(UIText.StagingView_replaceWithHeadRevision, selection, true)); else menuMgr.add(createItem(ActionCommands.REPLACE_WITH_HEAD_ACTION, tableViewer)); if (addIgnore) menuMgr.add(new IgnoreAction(selection)); if (addDelete) menuMgr.add(new DeleteAction(selection)); if (addLaunchMergeTool) menuMgr.add(createItem(ActionCommands.MERGE_TOOL_ACTION, tableViewer)); } }); } private class ReplaceAction extends Action { IStructuredSelection selection; private final boolean headRevision; ReplaceAction(String text, IStructuredSelection selection, boolean headRevision) { super(text); this.selection = selection; this.headRevision = headRevision; } @Override public void run() { boolean performAction = MessageDialog.openConfirm(form.getShell(), UIText.DiscardChangesAction_confirmActionTitle, UIText.DiscardChangesAction_confirmActionMessage); if (!performAction) return ; String[] files = getSelectedFiles(selection); replaceWith(files, headRevision); } } private static class IgnoreAction extends Action { private final IStructuredSelection selection; IgnoreAction(IStructuredSelection selection) { super(UIText.StagingView_IgnoreItemMenuLabel); this.selection = selection; } @Override public void run() { IgnoreOperationUI operation = new IgnoreOperationUI( getSelectedPaths(selection)); operation.run(); } } private class DeleteAction extends Action { private final IStructuredSelection selection; DeleteAction(IStructuredSelection selection) { super(UIText.StagingView_DeleteItemMenuLabel); this.selection = selection; } @Override public void run() { DeletePathsOperationUI operation = new DeletePathsOperationUI( getSelectedPaths(selection), getSite()); operation.run(); } } private class GlobalDeleteActionHandler extends Action { @Override public void run() { DeletePathsOperationUI operation = new DeletePathsOperationUI( getSelectedPaths(getSelection()), getSite()); operation.run(); } @Override public boolean isEnabled() { if (!unstagedTableViewer.getTable().isFocusControl()) return false; IStructuredSelection selection = getSelection(); if (selection.isEmpty()) return false; for (Object element : selection.toList()) { StagingEntry entry = (StagingEntry) element; if (!entry.getAvailableActions().contains(StagingEntry.Action.DELETE)) return false; } return true; } private IStructuredSelection getSelection() { return (IStructuredSelection) unstagedTableViewer.getSelection(); } } private void replaceWith(String[] files, boolean headRevision) { if (files == null || files.length == 0) return; CheckoutCommand checkoutCommand = new Git(currentRepository).checkout(); if (headRevision) checkoutCommand.setStartPoint(Constants.HEAD); for (String path : files) checkoutCommand.addPath(path); try { checkoutCommand.call(); } catch (Exception e) { Activator.handleError(UIText.StagingView_checkoutFailed, e, true); } } private String[] getSelectedFiles(IStructuredSelection selection) { List<String> result = new ArrayList<String>(); Iterator iterator = selection.iterator(); while (iterator.hasNext()) { StagingEntry stagingEntry = (StagingEntry) iterator.next(); result.add(stagingEntry.getPath()); } return result.toArray(new String[result.size()]); } private static List<IPath> getSelectedPaths(IStructuredSelection selection) { List<IPath> paths = new ArrayList<IPath>(); Iterator iterator = selection.iterator(); while (iterator.hasNext()) { StagingEntry stagingEntry = (StagingEntry) iterator.next(); paths.add(stagingEntry.getLocation()); } return paths; } /** * @param selection * @return true if the selection includes a non-workspace resource, false otherwise */ private boolean selectionIncludesNonWorkspaceResources(ISelection selection) { if (!(selection instanceof IStructuredSelection)) return false; IStructuredSelection structuredSelection = (IStructuredSelection) selection; Iterator iterator = structuredSelection.iterator(); while (iterator.hasNext()) { Object selectedObject = iterator.next(); if (!(selectedObject instanceof StagingEntry)) return false; StagingEntry stagingEntry = (StagingEntry) selectedObject; String path = currentRepository.getWorkTree() + "/" + stagingEntry.getPath(); //$NON-NLS-1$ if (getResource(path) == null) return true; } return false; } private IFile getResource(String path) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IFile file = root.getFileForLocation(new Path(path)); if (file == null) return null; if (file.getProject().isAccessible()) return file; return null; } private void openSelectionInEditor(ISelection s) { if (s.isEmpty() || !(s instanceof IStructuredSelection)) return; final IStructuredSelection iss = (IStructuredSelection) s; for (Iterator<StagingEntry> it = iss.iterator(); it.hasNext();) { String relativePath = it.next().getPath(); String path = new Path(currentRepository.getWorkTree() .getAbsolutePath()).append(relativePath) .toOSString(); openFileInEditor(path); } } private void openFileInEditor(String filePath) { IWorkbenchWindow window = PlatformUI.getWorkbench() .getActiveWorkbenchWindow(); File file = new File(filePath); if (!file.exists()) { String message = NLS.bind(UIText.CommitFileDiffViewer_FileDoesNotExist, filePath); Activator.showError(message, null); } IWorkbenchPage page = window.getActivePage(); EgitUiEditorUtils.openEditor(file, page); } private static Set<StagingEntry.Action> getAvailableActions(IStructuredSelection selection) { Set<StagingEntry.Action> availableActions = EnumSet.noneOf(StagingEntry.Action.class); for (Iterator it = selection.iterator(); it.hasNext(); ) { StagingEntry stagingEntry = (StagingEntry) it.next(); if (availableActions.isEmpty()) availableActions.addAll(stagingEntry.getAvailableActions()); else availableActions.retainAll(stagingEntry.getAvailableActions()); } return availableActions; } private CommandContributionItem createItem(String itemAction, final TableViewer tableViewer) { IWorkbench workbench = PlatformUI.getWorkbench(); CommandContributionItemParameter itemParam = new CommandContributionItemParameter( workbench, null, itemAction, STYLE_PUSH); IWorkbenchWindow activeWorkbenchWindow = workbench .getActiveWorkbenchWindow(); IHandlerService hsr = (IHandlerService) activeWorkbenchWindow .getService(IHandlerService.class); IEvaluationContext ctx = hsr.getCurrentState(); ctx.addVariable(ACTIVE_MENU_SELECTION_NAME, tableViewer.getSelection()); return new CommandContributionItem(itemParam); } private void reactOnSelection(ISelection selection) { if (selection instanceof StructuredSelection) { StructuredSelection ssel = (StructuredSelection) selection; if (ssel.size() != 1) return; Object firstElement = ssel.getFirstElement(); if (firstElement instanceof IResource) showResource((IResource) firstElement); else if (firstElement instanceof RepositoryTreeNode) { RepositoryTreeNode repoNode = (RepositoryTreeNode) firstElement; reload(repoNode.getRepository()); } else if (firstElement instanceof IAdaptable) { IResource adapted = (IResource) ((IAdaptable) firstElement).getAdapter(IResource.class); if (adapted != null) showResource(adapted); } } } private void showResource(final IResource resource) { IProject project = resource.getProject(); RepositoryMapping mapping = RepositoryMapping.getMapping(project); if (mapping == null) return; if (mapping.getRepository() != currentRepository) reload(mapping.getRepository()); } private void stage(IStructuredSelection selection) { Git git = new Git(currentRepository); AddCommand add = null; RmCommand rm = null; Iterator iterator = selection.iterator(); while (iterator.hasNext()) { StagingEntry entry = (StagingEntry) iterator.next(); switch (entry.getState()) { case ADDED: case CHANGED: case REMOVED: // already staged break; case CONFLICTING: case MODIFIED: case PARTIALLY_MODIFIED: case UNTRACKED: if (add == null) add = git.add(); add.addFilepattern(entry.getPath()); break; case MISSING: if (rm == null) rm = git.rm(); rm.addFilepattern(entry.getPath()); break; } } if (add != null) try { add.call(); } catch (NoFilepatternException e1) { // cannot happen } catch (Exception e2) { Activator.error(e2.getMessage(), e2); } if (rm != null) try { rm.call(); } catch (NoFilepatternException e) { // cannot happen } catch (Exception e2) { Activator.error(e2.getMessage(), e2); } } private void unstage(IStructuredSelection selection) { if (selection.isEmpty()) return; RevCommit headRev = null; try { final Ref head = currentRepository.getRef(Constants.HEAD); // head.getObjectId() is null if the repository does not contain any // commit if (head.getObjectId() != null) headRev = new RevWalk(currentRepository).parseCommit(head .getObjectId()); } catch (IOException e1) { // TODO fix text MessageDialog.openError(getSite().getShell(), UIText.CommitAction_MergeHeadErrorTitle, UIText.CommitAction_ErrorReadingMergeMsg); return; } final DirCache dirCache; final DirCacheEditor edit; try { dirCache = currentRepository.lockDirCache(); edit = dirCache.editor(); } catch (IOException e) { // TODO fix text MessageDialog.openError(getSite().getShell(), UIText.CommitAction_MergeHeadErrorTitle, UIText.CommitAction_ErrorReadingMergeMsg); return; } try { updateDirCache(selection, headRev, edit); try { edit.commit(); } catch (IOException e) { // TODO fix text MessageDialog.openError(getSite().getShell(), UIText.CommitAction_MergeHeadErrorTitle, UIText.CommitAction_ErrorReadingMergeMsg); } } finally { dirCache.unlock(); } } private void updateDirCache(IStructuredSelection selection, final RevCommit headRev, final DirCacheEditor edit) { Iterator iterator = selection.iterator(); while (iterator.hasNext()) { StagingEntry entry = (StagingEntry) iterator.next(); switch (entry.getState()) { case ADDED: edit.add(new DirCacheEditor.DeletePath(entry.getPath())); break; case CHANGED: case REMOVED: // set the index object id/file mode back to our head revision try { final TreeWalk tw = TreeWalk.forPath(currentRepository, entry.getPath(), headRev.getTree()); if (tw != null) edit.add(new DirCacheEditor.PathEdit(entry.getPath()) { @Override public void apply(DirCacheEntry ent) { ent.setFileMode(tw.getFileMode(0)); ent.setObjectId(tw.getObjectId(0)); // for index & working tree compare ent.setLastModified(0); } }); } catch (IOException e) { // TODO fix text MessageDialog.openError(getSite().getShell(), UIText.CommitAction_MergeHeadErrorTitle, UIText.CommitAction_ErrorReadingMergeMsg); } break; default: // unstaged } } } private boolean isValidRepo(final Repository repository) { return repository != null && !repository.isBare() && repository.getWorkTree().exists() && org.eclipse.egit.core.Activator.getDefault() .getRepositoryUtil().contains(repository); } /** * Clear the view's state. * <p> * This method must be called from the UI-thread */ private void clearRepository() { saveCommitMessageComponentState(); currentRepository = null; StagingViewUpdate update = new StagingViewUpdate(null, null, null); unstagedTableViewer.setInput(update); stagedTableViewer.setInput(update); enableCommitWidgets(false); updateSectionText(); form.setText(UIText.StagingView_NoSelectionTitle); } private void reload(final Repository repository) { if (form.isDisposed()) return; if (repository == null) { asyncExec(new Runnable() { public void run() { clearRepository(); } }); return; } if (!isValidRepo(repository)) return; final boolean repositoryChanged = currentRepository != repository; asyncExec(new Runnable() { public void run() { if (form.isDisposed()) return; final IndexDiffData indexDiff = doReload(repository); boolean indexDiffAvailable = indexDiff != null; final StagingViewUpdate update = new StagingViewUpdate(currentRepository, indexDiff, null); unstagedTableViewer.setInput(update); stagedTableViewer.setInput(update); enableCommitWidgets(indexDiffAvailable); boolean commitEnabled = indexDiffAvailable && repository.getRepositoryState().canCommit(); commitButton.setEnabled(commitEnabled); commitAndPushButton.setEnabled(commitEnabled); form.setText(StagingView.getRepositoryName(repository)); updateCommitMessageComponent(repositoryChanged, indexDiffAvailable); updateSectionText(); } }); } private IndexDiffData doReload(final Repository repository) { currentRepository = repository; IndexDiffCacheEntry entry = org.eclipse.egit.core.Activator.getDefault().getIndexDiffCache().getIndexDiffCacheEntry(currentRepository); if(cacheEntry != null && cacheEntry != entry) cacheEntry.removeIndexDiffChangedListener(myIndexDiffListener); cacheEntry = entry; cacheEntry.addIndexDiffChangedListener(myIndexDiffListener); return cacheEntry.getIndexDiff(); } private void clearCommitMessageToggles() { amendPreviousCommitAction.setChecked(false); addChangeIdAction.setChecked(false); signedOffByAction.setChecked(false); } void updateCommitMessageComponent(boolean repositoryChanged, boolean indexDiffAvailable) { CommitHelper helper = new CommitHelper(currentRepository); CommitMessageComponentState oldState = null; if (repositoryChanged) { if (userEnteredCommmitMessage()) saveCommitMessageComponentState(); else deleteCommitMessageComponentState(); oldState = loadCommitMessageComponentState(); commitMessageComponent.setRepository(currentRepository); if (oldState == null) loadInitialState(helper); else loadExistingState(helper, oldState); } else // repository did not change if (userEnteredCommmitMessage()) { if (!commitMessageComponent.getHeadCommit().equals( helper.getPreviousCommit())) addHeadChangedWarning(commitMessageComponent .getCommitMessage()); } else loadInitialState(helper); amendPreviousCommitAction.setChecked(commitMessageComponent .isAmending()); amendPreviousCommitAction.setEnabled(indexDiffAvailable && helper.amendAllowed()); updateMessage(); } private void loadExistingState(CommitHelper helper, CommitMessageComponentState oldState) { boolean headCommitChanged = !oldState.getHeadCommit().equals( getCommitId(helper.getPreviousCommit())); commitMessageComponent.enableListers(false); commitMessageComponent.setAuthor(oldState.getAuthor()); if (headCommitChanged) addHeadChangedWarning(oldState.getCommitMessage()); else commitMessageComponent .setCommitMessage(oldState.getCommitMessage()); commitMessageComponent.setCommitter(oldState.getCommitter()); commitMessageComponent.setHeadCommit(getCommitId(helper .getPreviousCommit())); commitMessageComponent.setCommitAllowed(helper.canCommit()); commitMessageComponent.setCannotCommitMessage(helper.getCannotCommitMessage()); boolean amendAllowed = helper.amendAllowed(); commitMessageComponent.setAmendAllowed(amendAllowed); if (!amendAllowed) commitMessageComponent.setAmending(false); else if (!headCommitChanged && oldState.getAmend()) commitMessageComponent.setAmending(true); else commitMessageComponent.setAmending(false); commitMessageComponent.updateUIFromState(); commitMessageComponent.updateSignedOffAndChangeIdButton(); commitMessageComponent.enableListers(true); } private void addHeadChangedWarning(String commitMessage) { String message = UIText.StagingView_headCommitChanged + Text.DELIMITER + Text.DELIMITER + commitMessage; commitMessageComponent.setCommitMessage(message); } private void loadInitialState(CommitHelper helper) { commitMessageComponent.enableListers(false); commitMessageComponent.resetState(); commitMessageComponent.setAuthor(helper.getAuthor()); commitMessageComponent.setCommitMessage(helper.getCommitMessage()); commitMessageComponent.setCommitter(helper.getCommitter()); commitMessageComponent.setHeadCommit(getCommitId(helper .getPreviousCommit())); commitMessageComponent.setCommitAllowed(helper.canCommit()); commitMessageComponent.setCannotCommitMessage(helper.getCannotCommitMessage()); commitMessageComponent.setAmendAllowed(helper.amendAllowed()); commitMessageComponent.setAmending(false); // set the defaults for change id and signed off buttons. commitMessageComponent.setDefaults(); commitMessageComponent.updateUI(); commitMessageComponent.enableListers(true); } private boolean userEnteredCommmitMessage() { if (commitMessageComponent.getRepository() == null) return false; String message = commitMessageComponent.getCommitMessage().replace( UIText.StagingView_headCommitChanged, ""); //$NON-NLS-1$ if (message == null || message.trim().length() == 0) return false; String chIdLine = "Change-Id: I" + ObjectId.zeroId().name(); //$NON-NLS-1$ if (currentRepository.getConfig().getBoolean( ConfigConstants.CONFIG_GERRIT_SECTION, ConfigConstants.CONFIG_KEY_CREATECHANGEID, false) && commitMessageComponent.getCreateChangeId()) { if (message.trim().equals(chIdLine)) return false; // change id was added automatically, but ther is more in the // message; strip the id, and check for the signed-off-by tag message = message.replace(chIdLine, ""); //$NON-NLS-1$ } if (org.eclipse.egit.ui.Activator.getDefault().getPreferenceStore() .getBoolean(UIPreferences.COMMIT_DIALOG_SIGNED_OFF_BY) && commitMessageComponent.isSignedOff() && message.trim().equals( Constants.SIGNED_OFF_BY_TAG + commitMessageComponent.getCommitter())) return false; return true; } private ObjectId getCommitId(RevCommit commit) { if (commit == null) return ObjectId.zeroId(); return commit.getId(); } private void saveCommitMessageComponentState() { final Repository repo = commitMessageComponent.getRepository(); if (repo != null) CommitMessageComponentStateManager.persistState(repo, commitMessageComponent.getState()); } private void deleteCommitMessageComponentState() { if (commitMessageComponent.getRepository() != null) CommitMessageComponentStateManager .deleteState(commitMessageComponent.getRepository()); } private CommitMessageComponentState loadCommitMessageComponentState() { return CommitMessageComponentStateManager.loadState(currentRepository); } private static String getRepositoryName(Repository repository) { String repoName = Activator.getDefault().getRepositoryUtil() .getRepositoryName(repository); RepositoryState state = repository.getRepositoryState(); if (state != RepositoryState.SAFE) return repoName + '|' + state.getDescription(); else return repoName; } private Collection<String> getStagedFileNames() { StagingViewContentProvider stagedContentProvider = getContentProvider(stagedTableViewer); StagingEntry[] entries = stagedContentProvider.getStagingEntries(); List<String> files = new ArrayList<String>(); for (StagingEntry entry : entries) files.add(entry.getPath()); return files; } private void commit(boolean pushUpstream) { if (!isCommitWithoutFilesAllowed()) { MessageDialog.openError(getSite().getShell(), UIText.StagingView_committingNotPossible, UIText.StagingView_noStagedFiles); return; } if (!commitMessageComponent.checkCommitInfo()) return; if (!UIUtils.saveAllEditors(currentRepository)) return; String commitMessage = commitMessageComponent.getCommitMessage(); CommitOperation commitOperation = null; try { commitOperation = new CommitOperation(currentRepository, commitMessageComponent.getAuthor(), commitMessageComponent.getCommitter(), commitMessage); } catch (CoreException e) { Activator.handleError(UIText.StagingView_commitFailed, e, true); return; } if (amendPreviousCommitAction.isChecked()) commitOperation.setAmending(true); commitOperation.setComputeChangeId(addChangeIdAction.isChecked()); Job commitJob = new CommitJob(currentRepository, commitOperation) .setOpenCommitEditor(openNewCommitsAction.isChecked()) .setPushUpstream(pushUpstream); commitJob.schedule(); CommitMessageHistory.saveCommitHistory(commitMessage); clearCommitMessageToggles(); commitMessageText.setText(EMPTY_STRING); } private boolean isCommitWithoutFilesAllowed() { if (stagedTableViewer.getTable().getItemCount() > 0) return true; if (amendPreviousCommitAction.isChecked()) return true; return CommitHelper.isCommitWithoutFilesAllowed(currentRepository); } @Override public void setFocus() { unstagedTableViewer.getControl().setFocus(); } @Override public void dispose() { super.dispose(); ISelectionService srv = (ISelectionService) getSite().getService( ISelectionService.class); srv.removePostSelectionListener(selectionChangedListener); if(cacheEntry != null) cacheEntry.removeIndexDiffChangedListener(myIndexDiffListener); if (undoRedoActionGroup != null) undoRedoActionGroup.dispose(); InstanceScope.INSTANCE.getNode( org.eclipse.egit.core.Activator.getPluginId()) .removePreferenceChangeListener(prefListener); } private void asyncExec(Runnable runnable) { PlatformUI.getWorkbench().getDisplay().asyncExec(runnable); } }
[stagingView] Add Show In support for unstaged/staged files Bug: 363567 Change-Id: I00bf92b16dcf3887d0596c87a386830770b68e28
org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/staging/StagingView.java
[stagingView] Add Show In support for unstaged/staged files
<ide><path>rg.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/staging/StagingView.java <ide> import org.eclipse.ui.menus.CommandContributionItem; <ide> import org.eclipse.ui.menus.CommandContributionItemParameter; <ide> import org.eclipse.ui.operations.UndoRedoActionGroup; <add>import org.eclipse.ui.part.IShowInSource; <add>import org.eclipse.ui.part.ShowInContext; <ide> import org.eclipse.ui.part.ViewPart; <ide> <ide> /** <ide> * A GitX style staging view with embedded commit dialog. <ide> */ <del>public class StagingView extends ViewPart { <add>public class StagingView extends ViewPart implements IShowInSource { <ide> <ide> /** <ide> * Staging view id <ide> } <ide> <ide> site.setSelectionProvider(unstagedTableViewer); <add> } <add> <add> public ShowInContext getShowInContext() { <add> if (stagedTableViewer != null && stagedTableViewer.getTable().isFocusControl()) <add> return getShowInContext(stagedTableViewer); <add> else if (unstagedTableViewer != null && unstagedTableViewer.getTable().isFocusControl()) <add> return getShowInContext(unstagedTableViewer); <add> else <add> return null; <add> } <add> <add> private ShowInContext getShowInContext(TableViewer tableViewer) { <add> IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection(); <add> List<IResource> resources = new ArrayList<IResource>(); <add> for (Object element : selection.toList()) { <add> if (element instanceof StagingEntry) { <add> StagingEntry entry = (StagingEntry) element; <add> IFile file = entry.getFile(); <add> if (file != null) <add> resources.add(file); <add> } <add> } <add> return new ShowInContext(null, new StructuredSelection(resources)); <ide> } <ide> <ide> private int getStagingFormOrientation() {
JavaScript
mit
cae3c833b4fa5c249e2f188e3abe8196872eedf2
0
mAiNiNfEcTiOn/lighthouse-ci-poc
metrics.js
// Copyright 2016 Google Inc. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE 'use strict'; module.exports = { prepareData }; function prepareData(res) { const audits = res.audits; const resSW = audits['service-worker']; const resFMP = audits['first-meaningful-paint']; const resFMPext = resFMP.extendedInfo; const resTTI = audits['time-to-interactive']; const resTTIext = resTTI && resTTI.extendedInfo; const preparedResults = [ { title: 'Service Worker', name: 'sw', value: resSW && resSW.rawValue }, { title: 'First Contentful Paint', name: 'ttfcp', value: resFMPext && resFMPext.value.timings.fCP }, { title: 'First Meaningful Paint', name: 'ttfmp', value: resFMP && resFMP.rawValue }, { title: 'Time to Interactive', name: 'tti', value: resTTI && resTTI.rawValue }, { title: 'Visually Complete 85%', name: 'vc85', value: resTTIext && parseFloat(resTTIext.value.timings.visuallyReady) } ]; return { preparedResults, generatedTime: res.generatedTime, lighthouseVersion: res.lighthouseVersion, initialUrl: res.initialUrl, url: res.url }; }
Removes the metrics.js file which is not used anymore (though we might use it in the future if necessary)
metrics.js
Removes the metrics.js file which is not used anymore (though we might use it in the future if necessary)
<ide><path>etrics.js <del>// Copyright 2016 Google Inc. All Rights Reserved. <del>// Licensed under the Apache License, Version 2.0. See LICENSE <del>'use strict'; <del> <del>module.exports = { <del> prepareData <del>}; <del> <del>function prepareData(res) { <del> const audits = res.audits; <del> <del> const resSW = audits['service-worker']; <del> <del> const resFMP = audits['first-meaningful-paint']; <del> const resFMPext = resFMP.extendedInfo; <del> <del> const resTTI = audits['time-to-interactive']; <del> const resTTIext = resTTI && resTTI.extendedInfo; <del> <del> const preparedResults = [ <del> { <del> title: 'Service Worker', <del> name: 'sw', <del> value: resSW && resSW.rawValue <del> }, <del> { <del> title: 'First Contentful Paint', <del> name: 'ttfcp', <del> value: resFMPext && resFMPext.value.timings.fCP <del> }, <del> { <del> title: 'First Meaningful Paint', <del> name: 'ttfmp', <del> value: resFMP && resFMP.rawValue <del> }, <del> { <del> title: 'Time to Interactive', <del> name: 'tti', <del> value: resTTI && resTTI.rawValue <del> }, <del> { <del> title: 'Visually Complete 85%', <del> name: 'vc85', <del> value: resTTIext && parseFloat(resTTIext.value.timings.visuallyReady) <del> } <del> ]; <del> <del> return { <del> preparedResults, <del> generatedTime: res.generatedTime, <del> lighthouseVersion: res.lighthouseVersion, <del> initialUrl: res.initialUrl, <del> url: res.url <del> }; <del>}
Java
lgpl-2.1
c89f14b74e2ba22e59b636d8f63dc4c9100b616c
0
serrapos/opencms-core,gallardo/opencms-core,alkacon/opencms-core,serrapos/opencms-core,sbonoc/opencms-core,serrapos/opencms-core,ggiudetti/opencms-core,ggiudetti/opencms-core,ggiudetti/opencms-core,serrapos/opencms-core,sbonoc/opencms-core,mediaworx/opencms-core,it-tavis/opencms-core,victos/opencms-core,ggiudetti/opencms-core,MenZil/opencms-core,mediaworx/opencms-core,it-tavis/opencms-core,gallardo/opencms-core,MenZil/opencms-core,mediaworx/opencms-core,alkacon/opencms-core,alkacon/opencms-core,sbonoc/opencms-core,sbonoc/opencms-core,mediaworx/opencms-core,victos/opencms-core,serrapos/opencms-core,MenZil/opencms-core,serrapos/opencms-core,victos/opencms-core,serrapos/opencms-core,gallardo/opencms-core,it-tavis/opencms-core,gallardo/opencms-core,MenZil/opencms-core,victos/opencms-core,alkacon/opencms-core,it-tavis/opencms-core
/* * File : $Source: /alkacon/cvs/opencms/test/org/opencms/importexport/TestCmsImportExportNonexistentUser.java,v $ * Date : $Date: 2005/04/27 14:25:16 $ * Version: $Revision: 1.3 $ * * This library is part of OpenCms - * the Open Source Content Mananagement System * * Copyright (C) 2002 - 2004 Alkacon Software (http://www.alkacon.com) * * 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. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * 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.opencms.importexport; import org.opencms.file.CmsObject; import org.opencms.file.CmsProject; import org.opencms.file.types.CmsResourceTypePlain; import org.opencms.main.I_CmsConstants; import org.opencms.main.OpenCms; import org.opencms.report.CmsShellReport; import org.opencms.test.OpenCmsTestCase; import org.opencms.test.OpenCmsTestProperties; import java.io.File; import junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestSuite; /** * Tests exporting/import VFS data with nonexistent users.<p> * * @author Thomas Weckert ([email protected]) * @version $Revision: 1.3 $ */ public class TestCmsImportExportNonexistentUser extends OpenCmsTestCase { /** * Default JUnit constructor.<p> * * @param arg0 JUnit parameters */ public TestCmsImportExportNonexistentUser(String arg0) { super(arg0); } /** * Test suite for this test class.<p> * * @return the test suite */ public static Test suite() { OpenCmsTestProperties.initialize(org.opencms.test.AllTests.TEST_PROPERTIES_PATH); TestSuite suite = new TestSuite(); suite.setName(TestCmsImportExport.class.getName()); suite.addTest(new TestCmsImportExportNonexistentUser("testImportExportNonexistentUser")); TestSetup wrapper = new TestSetup(suite) { protected void setUp() { setupOpenCms("simpletest", "/sites/default/"); } protected void tearDown() { removeOpenCms(); } }; return wrapper; } /** * Tests exporting and import of VFS data with a nonexistent/deleted user.<p> * * The username of the deleted user should in the export manifest be replaced * by the name of the Admin user.<p> * * @throws Exception if something goes wrong */ public void testImportExportNonexistentUser() throws Exception { String zipExportFilename = null; CmsObject cms = getCmsObject(); try { String username = "tempuser"; String password = "password"; String filename = "/dummy1.txt"; String contentStr = "This is a comment. I love comments."; zipExportFilename = OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf("packages/testImportExportNonexistentUser.zip"); byte[] content = contentStr.getBytes(); CmsProject offlineProject = cms.getRequestContext().currentProject(); // create a temporary user for this test case cms.createUser(username, password, "Temporary user for import/export test case", null); // add this user to the project managers user group cms.addUserToGroup(username, OpenCms.getDefaultUsers().getGroupProjectmanagers()); // switch to the temporary user, offline project and default site cms.loginUser(username, password); cms.getRequestContext().setSiteRoot("/sites/default/"); cms.getRequestContext().setCurrentProject(offlineProject); // create a dummy plain text file by the temporary user cms.createResource(filename, CmsResourceTypePlain.getStaticTypeId(), content, null); // publish the dummy plain text file cms.unlockResource(filename); cms.publishResource(filename); // switch back to the Admin user, offline project and default site cms.loginUser("Admin", "admin"); cms.getRequestContext().setSiteRoot("/sites/default/"); cms.getRequestContext().setCurrentProject(offlineProject); // delete the temporary user cms.deleteUser(username); // export the dummy plain text file CmsVfsImportExportHandler vfsExportHandler = new CmsVfsImportExportHandler(); vfsExportHandler.setFileName(zipExportFilename); vfsExportHandler.setExportPaths(new String[] {filename}); vfsExportHandler.setExcludeSystem(true); vfsExportHandler.setExcludeUnchanged(false); vfsExportHandler.setExportUserdata(false); OpenCms.getImportExportManager().exportData(cms, vfsExportHandler, new CmsShellReport()); // delete the dummy plain text file cms.lockResource(filename); cms.deleteResource(filename, I_CmsConstants.C_DELETE_OPTION_DELETE_SIBLINGS); // publish the deleted dummy plain text file cms.unlockResource(filename); cms.publishResource(filename); // re-import the exported dummy plain text file OpenCms.getImportExportManager().importData(cms, zipExportFilename, "/", new CmsShellReport()); } catch (Exception e) { fail(e.toString()); } finally { try { if (zipExportFilename != null) { File file = new File(zipExportFilename); if (file.exists()) { file.delete(); } } } catch (Throwable t) { // intentionally left blank } } } }
test/org/opencms/importexport/TestCmsImportExportNonexistentUser.java
/* * File : $Source: /alkacon/cvs/opencms/test/org/opencms/importexport/TestCmsImportExportNonexistentUser.java,v $ * Date : $Date: 2005/04/27 14:20:19 $ * Version: $Revision: 1.2 $ * * This library is part of OpenCms - * the Open Source Content Mananagement System * * Copyright (C) 2002 - 2004 Alkacon Software (http://www.alkacon.com) * * 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. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * 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.opencms.importexport; import org.opencms.file.CmsObject; import org.opencms.file.CmsProject; import org.opencms.file.types.CmsResourceTypePlain; import org.opencms.main.OpenCms; import org.opencms.report.CmsShellReport; import org.opencms.test.OpenCmsTestCase; import org.opencms.test.OpenCmsTestProperties; import java.io.File; import junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestSuite; /** * Tests exporting/import VFS data with nonexistent users.<p> * * @author Thomas Weckert ([email protected]) * @version $Revision: 1.2 $ */ public class TestCmsImportExportNonexistentUser extends OpenCmsTestCase { /** * Default JUnit constructor.<p> * * @param arg0 JUnit parameters */ public TestCmsImportExportNonexistentUser(String arg0) { super(arg0); } /** * Test suite for this test class.<p> * * @return the test suite */ public static Test suite() { OpenCmsTestProperties.initialize(org.opencms.test.AllTests.TEST_PROPERTIES_PATH); TestSuite suite = new TestSuite(); suite.setName(TestCmsImportExport.class.getName()); suite.addTest(new TestCmsImportExportNonexistentUser("testImportExportNonexistentUser")); TestSetup wrapper = new TestSetup(suite) { protected void setUp() { setupOpenCms("simpletest", "/sites/default/"); } protected void tearDown() { removeOpenCms(); } }; return wrapper; } /** * Tests exporting and import of VFS data with a nonexistent/deleted user.<p> * * The username of the deleted user should in the export manifest be replaced * by the name of the Admin user.<p> * * @throws Exception if something goes wrong */ public void testImportExportNonexistentUser() throws Exception { String zipExportFilename = null; CmsObject cms = getCmsObject(); try { String username = "tempuser"; String password = "password"; String filename = "/dummy1.txt"; String contentStr = "This is a comment. I love comments."; zipExportFilename = OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf("packages/testImportExportNonexistentUser.zip"); byte[] content = contentStr.getBytes(); CmsProject offlineProject = cms.getRequestContext().currentProject(); // create a temporary user for this test case cms.createUser(username, password, "Temporary user for import/export test case", null); // add this user to the project managers user group cms.addUserToGroup(username, OpenCms.getDefaultUsers().getGroupProjectmanagers()); // switch to the temporary user, offline project and default site cms.loginUser(username, password); cms.getRequestContext().setSiteRoot("/sites/default/"); cms.getRequestContext().setCurrentProject(offlineProject); // create a dummy plain text file by the temporary user cms.createResource(filename, CmsResourceTypePlain.getStaticTypeId(), content, null); // publish the dummy plain text file cms.unlockResource(filename); cms.publishResource(filename); // switch back to the Admin user cms.loginUser("Admin", "admin"); // delete the temporary user cms.deleteUser(username); // export the dummy plain text file CmsVfsImportExportHandler vfsExportHandler = new CmsVfsImportExportHandler(); vfsExportHandler.setFileName(zipExportFilename); vfsExportHandler.setExportPaths(new String[] {filename}); vfsExportHandler.setExcludeSystem(true); vfsExportHandler.setExcludeUnchanged(false); vfsExportHandler.setExportUserdata(false); OpenCms.getImportExportManager().exportData(cms, vfsExportHandler, new CmsShellReport()); } catch (Exception e) { fail(e.toString()); } finally { try { if (zipExportFilename != null) { File file = new File(zipExportFilename); if (file.exists()) { file.delete(); } } } catch (Throwable t) { // intentionally left blank } } } }
Exported zip archive gets re-imported again.
test/org/opencms/importexport/TestCmsImportExportNonexistentUser.java
Exported zip archive gets re-imported again.
<ide><path>est/org/opencms/importexport/TestCmsImportExportNonexistentUser.java <ide> /* <ide> * File : $Source: /alkacon/cvs/opencms/test/org/opencms/importexport/TestCmsImportExportNonexistentUser.java,v $ <del> * Date : $Date: 2005/04/27 14:20:19 $ <del> * Version: $Revision: 1.2 $ <add> * Date : $Date: 2005/04/27 14:25:16 $ <add> * Version: $Revision: 1.3 $ <ide> * <ide> * This library is part of OpenCms - <ide> * the Open Source Content Mananagement System <ide> import org.opencms.file.CmsObject; <ide> import org.opencms.file.CmsProject; <ide> import org.opencms.file.types.CmsResourceTypePlain; <add>import org.opencms.main.I_CmsConstants; <ide> import org.opencms.main.OpenCms; <ide> import org.opencms.report.CmsShellReport; <ide> import org.opencms.test.OpenCmsTestCase; <ide> * Tests exporting/import VFS data with nonexistent users.<p> <ide> * <ide> * @author Thomas Weckert ([email protected]) <del> * @version $Revision: 1.2 $ <add> * @version $Revision: 1.3 $ <ide> */ <ide> public class TestCmsImportExportNonexistentUser extends OpenCmsTestCase { <ide> <ide> cms.unlockResource(filename); <ide> cms.publishResource(filename); <ide> <del> // switch back to the Admin user <del> cms.loginUser("Admin", "admin"); <add> // switch back to the Admin user, offline project and default site <add> cms.loginUser("Admin", "admin"); <add> cms.getRequestContext().setSiteRoot("/sites/default/"); <add> cms.getRequestContext().setCurrentProject(offlineProject); <ide> // delete the temporary user <ide> cms.deleteUser(username); <ide> <ide> vfsExportHandler.setExcludeUnchanged(false); <ide> vfsExportHandler.setExportUserdata(false); <ide> OpenCms.getImportExportManager().exportData(cms, vfsExportHandler, new CmsShellReport()); <add> <add> // delete the dummy plain text file <add> cms.lockResource(filename); <add> cms.deleteResource(filename, I_CmsConstants.C_DELETE_OPTION_DELETE_SIBLINGS); <add> // publish the deleted dummy plain text file <add> cms.unlockResource(filename); <add> cms.publishResource(filename); <add> <add> // re-import the exported dummy plain text file <add> OpenCms.getImportExportManager().importData(cms, zipExportFilename, "/", new CmsShellReport()); <ide> } catch (Exception e) { <ide> <ide> fail(e.toString());
Java
agpl-3.0
88e2105beae650970a9f056bcc212de09873a74f
0
Silverpeas/Silverpeas-Components,ebonnet/Silverpeas-Components,auroreallibe/Silverpeas-Components,mmoqui/Silverpeas-Components,ebonnet/Silverpeas-Components,SilverTeamWork/Silverpeas-Components,Silverpeas/Silverpeas-Components,mmoqui/Silverpeas-Components,mmoqui/Silverpeas-Components,SilverTeamWork/Silverpeas-Components,ebonnet/Silverpeas-Components,SilverYoCha/Silverpeas-Components,SilverYoCha/Silverpeas-Components,ebonnet/Silverpeas-Components,ebonnet/Silverpeas-Components,auroreallibe/Silverpeas-Components,SilverTeamWork/Silverpeas-Components,auroreallibe/Silverpeas-Components,Silverpeas/Silverpeas-Components,SilverYoCha/Silverpeas-Components,ebonnet/Silverpeas-Components,ebonnet/Silverpeas-Components
/** * Copyright (C) 2000 - 2009 Silverpeas * * 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. * * As a special exception to the terms and conditions of version 3.0 of the GPL, you may * redistribute this Program in connection with Free/Libre Open Source Software ("FLOSS") * applications as described in Silverpeas's FLOSS exception. You should have received a copy of the * text describing the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * 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 com.silverpeas.scheduleevent.control; import com.silverpeas.calendar.CalendarEvent; import com.silverpeas.export.ExportException; import com.silverpeas.export.Exporter; import com.silverpeas.export.ExporterProvider; import com.silverpeas.export.ical.ExportableCalendar; import com.silverpeas.scheduleevent.notification.ScheduleEventUserCallAgainNotification; import com.silverpeas.scheduleevent.notification.ScheduleEventUserNotification; import com.silverpeas.scheduleevent.service.CalendarEventEncoder; import com.silverpeas.scheduleevent.service.ScheduleEventService; import com.silverpeas.scheduleevent.service.ScheduleEventServiceProvider; import com.silverpeas.scheduleevent.service.model.ScheduleEventBean; import com.silverpeas.scheduleevent.service.model.ScheduleEventStatus; import com.silverpeas.scheduleevent.service.model.beans.Contributor; import com.silverpeas.scheduleevent.service.model.beans.DateOption; import com.silverpeas.scheduleevent.service.model.beans.Response; import com.silverpeas.scheduleevent.service.model.beans.ScheduleEvent; import com.silverpeas.scheduleevent.service.model.beans.ScheduleEventComparator; import com.silverpeas.scheduleevent.view.BestTimeVO; import com.silverpeas.scheduleevent.view.DateVO; import com.silverpeas.scheduleevent.view.HalfDayDateVO; import com.silverpeas.scheduleevent.view.HalfDayTime; import com.silverpeas.scheduleevent.view.OptionDateVO; import com.silverpeas.scheduleevent.view.ScheduleEventDetailVO; import com.silverpeas.scheduleevent.view.ScheduleEventVO; import com.silverpeas.scheduleevent.view.TimeVO; import com.silverpeas.usernotification.builder.helper.UserNotificationHelper; import com.stratelia.silverpeas.peasCore.AbstractComponentSessionController; import com.stratelia.silverpeas.peasCore.ComponentContext; import com.stratelia.silverpeas.peasCore.MainSessionController; import com.stratelia.silverpeas.peasCore.URLManager; import com.stratelia.silverpeas.selection.Selection; import com.stratelia.silverpeas.selection.SelectionUsersGroups; import com.stratelia.silverpeas.silvertrace.SilverTrace; import com.stratelia.webactiv.beans.admin.UserDetail; import org.apache.commons.io.FileUtils; import org.silverpeas.util.FileRepositoryManager; import org.silverpeas.util.NotifierUtil; import org.silverpeas.util.Pair; import org.silverpeas.util.ResourceLocator; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import static com.silverpeas.export.ExportDescriptor.withWriter; public class ScheduleEventSessionController extends AbstractComponentSessionController { private Selection sel = null; private ScheduleEvent currentScheduleEvent = null; private static final String ICS_PREFIX = "scheduleevent"; /** * Standard Session Controller Constructeur * @param mainSessionCtrl The user's profile * @param componentContext The component's profile * @see */ public ScheduleEventSessionController(MainSessionController mainSessionCtrl, ComponentContext componentContext) { super(mainSessionCtrl, componentContext, "org.silverpeas.components.scheduleevent.multilang.ScheduleEventBundle", "org.silverpeas.components.scheduleevent.settings.ScheduleEventIcons", "org.silverpeas.components.scheduleevent.settings.ScheduleEventSettings"); sel = getSelection(); } public void setCurrentScheduleEvent(ScheduleEvent currentScheduleEvent) { this.currentScheduleEvent = currentScheduleEvent; } public ScheduleEvent getCurrentScheduleEvent() { return currentScheduleEvent; } public ScheduleEventBean getCurrentScheduleEventVO() { return new ScheduleEventVO(getCurrentScheduleEvent()); } public void resetScheduleEventCreationBuffer() { setCurrentScheduleEvent(null); } private void addContributor(Set<Contributor> contributors, String userId) { Contributor contributor = new Contributor(); contributor.setScheduleEvent(currentScheduleEvent); contributor.setUserId(Integer.parseInt(userId)); contributor.setUserName(getUserDetail(userId).getDisplayedName()); contributors.add(contributor); } public void createCurrentScheduleEvent() { setCurrentScheduleEvent(new ScheduleEvent()); currentScheduleEvent.setAuthor(Integer.parseInt(getUserId())); addContributor(currentScheduleEvent.getContributors(), getUserId()); } public boolean isCurrentScheduleEventDefined() { return getCurrentScheduleEvent() != null; } public String initSelectUsersPanel() { if (isUserOwnerOfEvent(getCurrentScheduleEvent())) { String m_context = ResourceLocator.getGeneralSettingBundle().getString("ApplicationURL"); Pair<String, String> hostComponentName = new Pair<>(getComponentName(), ""); Pair<String, String>[] hostPath = new Pair[1]; hostPath[0] = new Pair<>(getString("scheduleevent.form.selectContributors"), ""); sel.resetAll(); sel.setHostSpaceName(""); sel.setHostComponentName(hostComponentName); sel.setHostPath(hostPath); String[] idUsers = getContributorsUserIds(currentScheduleEvent.getContributors()); sel.setSelectedElements(idUsers); sel.setSelectedSets(new String[0]); // constraints String hostDirection, cancelDirection; if (currentScheduleEvent.getId() == null) { hostDirection = "ConfirmUsers?popupMode=Yes"; cancelDirection = "ConfirmScreen?popupMode=Yes"; } else { hostDirection = "ConfirmModifyUsers?scheduleEventId=" + currentScheduleEvent.getId(); cancelDirection = "Detail?scheduleEventId=" + currentScheduleEvent.getId(); } String hostUrl = m_context + URLManager.getURL(URLManager.CMP_SCHEDULE_EVENT, null, null) + hostDirection; String cancelUrl = m_context + URLManager.getURL(URLManager.CMP_SCHEDULE_EVENT, null, null) + cancelDirection; sel.setGoBackURL(hostUrl); sel.setCancelURL(cancelUrl); sel.setMultiSelect(true); sel.setPopupMode(true); sel.setFirstPage(Selection.FIRST_PAGE_BROWSE); return Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS); } else { SilverTrace.warn("scheduleevent", "ScheduleEventSessionController.initSelectUsersPanel", "Security alert from user " + getUserId()); NotifierUtil.addError(getString("GML.security.access")); return "/admin/jsp/accessForbidden.jsp"; } } private static String[] getContributorsUserIds(Set<Contributor> contributors) { Set<String> result = new HashSet<String>(contributors.size()); for (Contributor subscriber : contributors) { if (subscriber.getUserId() != -1) { result.add(String.valueOf(subscriber.getUserId())); } } return result.toArray(new String[result.size()]); } public void setIdUsersAndGroups() { String[] usersId = SelectionUsersGroups.getDistinctUserIds(sel.getSelectedElements(), sel. getSelectedSets()); if (usersId.length < 1) { return; } Set<Contributor> recordedContributors = currentScheduleEvent.getContributors(); deleteRecordedContributors(usersId, recordedContributors); addContributors(usersId, recordedContributors); } public void addContributors(String[] usersId, Set<Contributor> recordedContributors) { if (usersId.length < 1) { return; } UserDetail[] userDetails = SelectionUsersGroups.getUserDetails(usersId); boolean foundCreator = false; for (UserDetail detail : userDetails) { if (detail.getId().equals(String.valueOf(currentScheduleEvent.getAuthor()))) { foundCreator = true; } boolean foundAlreadyCreated = false; for (Contributor contributor : recordedContributors) { if (detail.getId().equals(String.valueOf(contributor.getUserId()))) { foundAlreadyCreated = true; } } if (!foundAlreadyCreated) { addContributor(recordedContributors, detail.getId()); SilverTrace.debug("scheduleevent", "ScheduleEventSessionController.addContributors()", "Contributor '" + getUserDetail(detail.getId()).getDisplayedName() + "' added to event '" + currentScheduleEvent.getTitle() + "'"); } } if (!foundCreator) { addContributor(recordedContributors, String.valueOf(currentScheduleEvent.getAuthor())); } } private void deleteRecordedContributors(String[] selectedUsersIds, Set<Contributor> recordedContributors) { if (recordedContributors.isEmpty()) { return; } UserDetail[] userDetails = SelectionUsersGroups.getUserDetails(selectedUsersIds); boolean found = false; Iterator<Contributor> recordedContributorIt = recordedContributors.iterator(); while (recordedContributorIt.hasNext()) { Contributor currentContributor = recordedContributorIt.next(); String currentContributorUserId = String.valueOf(currentContributor.getUserId()); if (getUserId().equals(currentContributorUserId)) { continue; } for (final UserDetail userDetail : userDetails) { if (userDetail.getId().equals(currentContributorUserId)) { found = true; } } if (!found) { recordedContributorIt.remove(); SilverTrace.debug("scheduleevent", "ScheduleEventSessionController.deleteRecordedContributors()", "Contributor '" + currentContributor.getUserName() + "' deleted from event '" + currentScheduleEvent.getTitle() + "'"); } } } public void updateIdUsersAndGroups() { String[] usersId = SelectionUsersGroups.getDistinctUserIds(sel.getSelectedElements(), sel. getSelectedSets()); Set<Contributor> recordedContributors = currentScheduleEvent.getContributors(); deleteRecordedContributors(usersId, recordedContributors); addContributors(usersId, recordedContributors); getScheduleEventService().updateScheduleEvent(currentScheduleEvent); } public void save() { // add last info for a complete save currentScheduleEvent.setAuthor(Integer.parseInt(getUserId())); currentScheduleEvent.setStatus(ScheduleEventStatus.OPEN); currentScheduleEvent.setCreationDate(new Date()); // create all dateoption for database // preTreatementForDateOption(); getScheduleEventService().createScheduleEvent(currentScheduleEvent); // notify contributors // initAlertUser(); sendSubscriptionsNotification(); // delete session object after saving it currentScheduleEvent = null; } public void sendSubscriptionsNotification() { try { UserNotificationHelper .buildAndSend(new ScheduleEventUserNotification(currentScheduleEvent, getUserDetail())); } catch (Exception e) { SilverTrace.warn("scheduleevent", "ScheduleEventSessionController.sendSubscriptionsNotification()", "scheduleEvent.EX_IMPOSSIBLE_DALERTER_LES_UTILISATEURS", "", e); } } public void sendCallAgainNotification(String message) { try { UserNotificationHelper .buildAndSend(new ScheduleEventUserCallAgainNotification(currentScheduleEvent, message, getUserDetail())); NotifierUtil.addSuccess(getString("scheduleevent.callagain.ok")); } catch (Exception e) { SilverTrace.warn("scheduleevent", "ScheduleEventSessionController.sendSubscriptionsNotification()", "scheduleEvent.EX_IMPOSSIBLE_DALERTER_LES_UTILISATEURS", "", e); } } private ScheduleEventService getScheduleEventService() { return ScheduleEventServiceProvider.getScheduleEventService(); } public List<ScheduleEvent> getScheduleEventsByUserId() { Set<ScheduleEvent> allEvents = getScheduleEventService().listAllScheduleEventsByUserId( getUserId()); List<ScheduleEvent> results = new ArrayList<ScheduleEvent>(allEvents); Collections.sort(results, new ScheduleEventComparator()); return results; } public ScheduleEvent getDetail(String id) { ScheduleEvent event = getScheduleEventService().findScheduleEvent(id); // update last visited date if (event != null) { if (event.canBeAccessedBy(getUserDetail())) { getScheduleEventService().setLastVisited(event, Integer.valueOf(getUserId())); } else { event = null; } } return event; } public void switchState(String id) { ScheduleEvent event = getScheduleEventService().findScheduleEvent(id); if (isUserOwnerOfEvent(event)) { int actualStatus = event.getStatus(); int newStatus = ScheduleEventStatus.OPEN; if (ScheduleEventStatus.OPEN == actualStatus) { newStatus = ScheduleEventStatus.CLOSED; } getScheduleEventService().updateScheduleEventStatus(id, newStatus); } else { SilverTrace.warn("scheduleevent", "ScheduleEventSessionController.switchState", "Security alert from user " + getUserId()); NotifierUtil.addError(getString("GML.security.access")); } } private boolean isUserOwnerOfEvent(final ScheduleEvent event) { return event.getAuthor() == Integer.parseInt(getUserId()); } public void delete(String scheduleEventId) { ScheduleEvent scheduleEvent = getScheduleEventService().findScheduleEvent(scheduleEventId); if (isUserOwnerOfEvent(scheduleEvent)) { getScheduleEventService().deleteScheduleEvent(scheduleEvent); } else { SilverTrace.warn("scheduleevent", "ScheduleEventSessionController.delete", "Security alert from user " + getUserId()); NotifierUtil.addError(getString("GML.security.access")); } } public void updateUserAvailabilities(ScheduleEvent scheduleEvent) { updateValidationDate(scheduleEvent, getUserId()); getScheduleEventService().updateScheduleEvent(scheduleEvent); } private void updateValidationDate(ScheduleEvent scheduleEvent, String userId) { Contributor contributor = getContributor(scheduleEvent, userId); if (contributor != null) { contributor.setLastValidation(new Date()); } } private Contributor getContributor(ScheduleEvent scheduleEvent, String id) { try { int userId = Integer.parseInt(id); for (Contributor contributor : scheduleEvent.getContributors()) { if (contributor.getUserId() == userId) { return contributor; } } } catch (Exception ignore) { } return null; } public ScheduleEvent purgeOldResponseForUserId(ScheduleEvent scheduleEvent) { return getScheduleEventService().purgeOldResponseForUserId(scheduleEvent, Integer.parseInt(getUserId())); } public Double getSubscribersRateAnswerFor(ScheduleEvent event) { return 0.0; } public Set<OptionDateVO> getCurrentOptionalDateIndexes() throws Exception { return ((ScheduleEventVO) getCurrentScheduleEventVO()).getOptionalDateIndexes(); } public void setCurrentScheduleEventWith(Set<OptionDateVO> optionalDays) { ((ScheduleEventVO) getCurrentScheduleEventVO()).setScheduleEventWith(optionalDays); } public Response makeReponseFor(ScheduleEvent scheduleEvent, String dateId) { // TODO: Can add checks for dateId, scheduleEvent integrity Response result = new Response(); result.setScheduleEvent(scheduleEvent); result.setUserId(Integer.parseInt(getUserId())); result.setOptionId(dateId); NotifierUtil.addSuccess(getString("scheduleevent.form.confirmMessage")); return result; } /** * Converts the specified detailed scheduleevent into a calendar event. * @param event detail. * @param listDateOption of dates. * @return the calendar events corresponding to the schedule event. */ private List<CalendarEvent> asCalendarEvents(final ScheduleEvent event, final List<DateOption> listDateOption) { CalendarEventEncoder encoder = new CalendarEventEncoder(); return encoder.encode(event, listDateOption); } /** * Exports the current ScheduleEvent in iCal format. The iCal file is generated into the temporary * directory. * @return the iCal file name into which is generated the current ScheduleEvent. * @throws Exception */ public String exportToICal(ScheduleEvent event) throws Exception { // construction de la liste des dates retenues de l'événement List<DateOption> listDateOption = new ArrayList<DateOption>(); ScheduleEventDetailVO scheduleEventDetailVO = new ScheduleEventDetailVO(this, event); BestTimeVO bestTimeVO = scheduleEventDetailVO.getBestTimes(); if (bestTimeVO.isBestDateExists()) { List<TimeVO> listTimeVO = bestTimeVO.getTimes(); for (TimeVO timeVO : listTimeVO) { HalfDayTime halfDayTime = (HalfDayTime) timeVO; DateVO dateVO = halfDayTime.getDate(); HalfDayDateVO halfDayDateVO = (HalfDayDateVO) dateVO; Date day = halfDayDateVO.getDate(); DateOption dateOption = new DateOption(); dateOption.setDay(day); String label = halfDayTime.getMultilangLabel(); if ("scheduleevent.form.hour.columnam".equals(label)) { dateOption.setHour(ScheduleEventVO.MORNING_HOUR); } else if ("scheduleevent.form.hour.columnpm".equals(label)) { dateOption.setHour(ScheduleEventVO.AFTERNOON_HOUR); } listDateOption.add(dateOption); } } // transformation des dates en CalendarEvent List<CalendarEvent> eventsToExport = asCalendarEvents(event, listDateOption); // export iCal Exporter<ExportableCalendar> iCalExporter = ExporterProvider.getICalExporter(); String icsFileName = ICS_PREFIX + getUserId() + ".ics"; String icsFilePath = FileRepositoryManager.getTemporaryPath() + icsFileName; FileWriter fileWriter = new FileWriter(icsFilePath); try { iCalExporter.export(withWriter(fileWriter), ExportableCalendar.with(eventsToExport)); } catch (ExportException ex) { File fileToDelete = new File(icsFilePath); if (fileToDelete.exists()) { FileUtils.deleteQuietly(fileToDelete); } throw ex; } return icsFileName; } }
scheduleevent/scheduleevent-war/src/main/java/com/silverpeas/scheduleevent/control/ScheduleEventSessionController.java
/** * Copyright (C) 2000 - 2009 Silverpeas * * 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. * * As a special exception to the terms and conditions of version 3.0 of the GPL, you may * redistribute this Program in connection with Free/Libre Open Source Software ("FLOSS") * applications as described in Silverpeas's FLOSS exception. You should have received a copy of the * text describing the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * 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 com.silverpeas.scheduleevent.control; import com.silverpeas.calendar.CalendarEvent; import com.silverpeas.export.ExportException; import com.silverpeas.export.Exporter; import com.silverpeas.export.ExporterProvider; import com.silverpeas.export.ical.ExportableCalendar; import com.silverpeas.scheduleevent.notification.ScheduleEventUserCallAgainNotification; import com.silverpeas.scheduleevent.notification.ScheduleEventUserNotification; import com.silverpeas.scheduleevent.service.CalendarEventEncoder; import com.silverpeas.scheduleevent.service.ScheduleEventService; import com.silverpeas.scheduleevent.service.ScheduleEventServiceProvider; import com.silverpeas.scheduleevent.service.model.ScheduleEventBean; import com.silverpeas.scheduleevent.service.model.ScheduleEventStatus; import com.silverpeas.scheduleevent.service.model.beans.Contributor; import com.silverpeas.scheduleevent.service.model.beans.DateOption; import com.silverpeas.scheduleevent.service.model.beans.Response; import com.silverpeas.scheduleevent.service.model.beans.ScheduleEvent; import com.silverpeas.scheduleevent.service.model.beans.ScheduleEventComparator; import com.silverpeas.scheduleevent.view.BestTimeVO; import com.silverpeas.scheduleevent.view.DateVO; import com.silverpeas.scheduleevent.view.HalfDayDateVO; import com.silverpeas.scheduleevent.view.HalfDayTime; import com.silverpeas.scheduleevent.view.OptionDateVO; import com.silverpeas.scheduleevent.view.ScheduleEventDetailVO; import com.silverpeas.scheduleevent.view.ScheduleEventVO; import com.silverpeas.scheduleevent.view.TimeVO; import com.silverpeas.usernotification.builder.helper.UserNotificationHelper; import com.stratelia.silverpeas.peasCore.AbstractComponentSessionController; import com.stratelia.silverpeas.peasCore.ComponentContext; import com.stratelia.silverpeas.peasCore.MainSessionController; import com.stratelia.silverpeas.peasCore.URLManager; import com.stratelia.silverpeas.selection.Selection; import com.stratelia.silverpeas.selection.SelectionUsersGroups; import com.stratelia.silverpeas.silvertrace.SilverTrace; import com.stratelia.webactiv.beans.admin.UserDetail; import org.apache.commons.io.FileUtils; import org.silverpeas.util.FileRepositoryManager; import org.silverpeas.util.NotifierUtil; import org.silverpeas.util.Pair; import org.silverpeas.util.ResourceLocator; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import static com.silverpeas.export.ExportDescriptor.withWriter; public class ScheduleEventSessionController extends AbstractComponentSessionController { private Selection sel = null; private ScheduleEvent currentScheduleEvent = null; private static final String ICS_PREFIX = "scheduleevent"; /** * Standard Session Controller Constructeur * @param mainSessionCtrl The user's profile * @param componentContext The component's profile * @see */ public ScheduleEventSessionController(MainSessionController mainSessionCtrl, ComponentContext componentContext) { super(mainSessionCtrl, componentContext, "org.silverpeas.components.scheduleevent.multilang.ScheduleEventBundle", "org.silverpeas.components.scheduleevent.settings.ScheduleEventIcons", "org.silverpeas.components.scheduleevent.settings.ScheduleEventSettings"); sel = getSelection(); } public void setCurrentScheduleEvent(ScheduleEvent currentScheduleEvent) { this.currentScheduleEvent = currentScheduleEvent; } public ScheduleEvent getCurrentScheduleEvent() { return currentScheduleEvent; } public ScheduleEventBean getCurrentScheduleEventVO() { return new ScheduleEventVO(getCurrentScheduleEvent()); } public void resetScheduleEventCreationBuffer() { setCurrentScheduleEvent(null); } private void addContributor(Set<Contributor> contributors, String userId) { Contributor contributor = new Contributor(); contributor.setScheduleEvent(currentScheduleEvent); contributor.setUserId(Integer.parseInt(userId)); contributor.setUserName(getUserDetail(userId).getDisplayedName()); contributors.add(contributor); } public void createCurrentScheduleEvent() { setCurrentScheduleEvent(new ScheduleEvent()); currentScheduleEvent.setAuthor(Integer.parseInt(getUserId())); addContributor(currentScheduleEvent.getContributors(), getUserId()); } public boolean isCurrentScheduleEventDefined() { return getCurrentScheduleEvent() != null; } public String initSelectUsersPanel() { if (getCurrentScheduleEvent().getAuthor() == Integer.parseInt(getUserId())) { String m_context = ResourceLocator.getGeneralSettingBundle().getString("ApplicationURL"); Pair<String, String> hostComponentName = new Pair<>(getComponentName(), ""); Pair<String, String>[] hostPath = new Pair[1]; hostPath[0] = new Pair<>(getString("scheduleevent.form.selectContributors"), ""); sel.resetAll(); sel.setHostSpaceName(""); sel.setHostComponentName(hostComponentName); sel.setHostPath(hostPath); String[] idUsers = getContributorsUserIds(currentScheduleEvent.getContributors()); sel.setSelectedElements(idUsers); sel.setSelectedSets(new String[0]); // constraints String hostDirection, cancelDirection; if (currentScheduleEvent.getId() == null) { hostDirection = "ConfirmUsers?popupMode=Yes"; cancelDirection = "ConfirmScreen?popupMode=Yes"; } else { hostDirection = "ConfirmModifyUsers?scheduleEventId=" + currentScheduleEvent.getId(); cancelDirection = "Detail?scheduleEventId=" + currentScheduleEvent.getId(); } String hostUrl = m_context + URLManager.getURL(URLManager.CMP_SCHEDULE_EVENT, null, null) + hostDirection; String cancelUrl = m_context + URLManager.getURL(URLManager.CMP_SCHEDULE_EVENT, null, null) + cancelDirection; sel.setGoBackURL(hostUrl); sel.setCancelURL(cancelUrl); sel.setMultiSelect(true); sel.setPopupMode(true); sel.setFirstPage(Selection.FIRST_PAGE_BROWSE); return Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS); } else { SilverTrace.warn("scheduleevent", "ScheduleEventSessionController.initSelectUsersPanel", "Security alert from user " + getUserId()); NotifierUtil.addError(getString("GML.security.access")); return "/admin/jsp/accessForbidden.jsp"; } } private static String[] getContributorsUserIds(Set<Contributor> contributors) { Set<String> result = new HashSet<String>(contributors.size()); for (Contributor subscriber : contributors) { if (subscriber.getUserId() != -1) { result.add(String.valueOf(subscriber.getUserId())); } } return result.toArray(new String[result.size()]); } public void setIdUsersAndGroups() { String[] usersId = SelectionUsersGroups.getDistinctUserIds(sel.getSelectedElements(), sel. getSelectedSets()); if (usersId.length < 1) { return; } Set<Contributor> recordedContributors = currentScheduleEvent.getContributors(); deleteRecordedContributors(usersId, recordedContributors); addContributors(usersId, recordedContributors); } public void addContributors(String[] usersId, Set<Contributor> recordedContributors) { if (usersId.length < 1) { return; } UserDetail[] userDetails = SelectionUsersGroups.getUserDetails(usersId); boolean foundCreator = false; for (UserDetail detail : userDetails) { if (detail.getId().equals(String.valueOf(currentScheduleEvent.getAuthor()))) { foundCreator = true; } boolean foundAlreadyCreated = false; for (Contributor contributor : recordedContributors) { if (detail.getId().equals(String.valueOf(contributor.getUserId()))) { foundAlreadyCreated = true; } } if (!foundAlreadyCreated) { addContributor(recordedContributors, detail.getId()); SilverTrace.debug("scheduleevent", "ScheduleEventSessionController.addContributors()", "Contributor '" + getUserDetail(detail.getId()).getDisplayedName() + "' added to event '" + currentScheduleEvent.getTitle() + "'"); } } if (!foundCreator) { addContributor(recordedContributors, String.valueOf(currentScheduleEvent.getAuthor())); } } private void deleteRecordedContributors(String[] selectedUsersIds, Set<Contributor> recordedContributors) { if (recordedContributors.isEmpty()) { return; } UserDetail[] userDetails = SelectionUsersGroups.getUserDetails(selectedUsersIds); boolean found = false; Iterator<Contributor> recordedContributorIt = recordedContributors.iterator(); while (recordedContributorIt.hasNext()) { Contributor currentContributor = recordedContributorIt.next(); String currentContributorUserId = String.valueOf(currentContributor.getUserId()); if (getUserId().equals(currentContributorUserId)) { continue; } for (final UserDetail userDetail : userDetails) { if (userDetail.getId().equals(currentContributorUserId)) { found = true; } } if (!found) { recordedContributorIt.remove(); SilverTrace.debug("scheduleevent", "ScheduleEventSessionController.deleteRecordedContributors()", "Contributor '" + currentContributor.getUserName() + "' deleted from event '" + currentScheduleEvent.getTitle() + "'"); } } } public void updateIdUsersAndGroups() { String[] usersId = SelectionUsersGroups.getDistinctUserIds(sel.getSelectedElements(), sel. getSelectedSets()); Set<Contributor> recordedContributors = currentScheduleEvent.getContributors(); deleteRecordedContributors(usersId, recordedContributors); addContributors(usersId, recordedContributors); getScheduleEventService().updateScheduleEvent(currentScheduleEvent); } public void save() { // add last info for a complete save currentScheduleEvent.setAuthor(Integer.parseInt(getUserId())); currentScheduleEvent.setStatus(ScheduleEventStatus.OPEN); currentScheduleEvent.setCreationDate(new Date()); // create all dateoption for database // preTreatementForDateOption(); getScheduleEventService().createScheduleEvent(currentScheduleEvent); // notify contributors // initAlertUser(); sendSubscriptionsNotification(); // delete session object after saving it currentScheduleEvent = null; } public void sendSubscriptionsNotification() { try { UserNotificationHelper .buildAndSend(new ScheduleEventUserNotification(currentScheduleEvent, getUserDetail())); } catch (Exception e) { SilverTrace.warn("scheduleevent", "ScheduleEventSessionController.sendSubscriptionsNotification()", "scheduleEvent.EX_IMPOSSIBLE_DALERTER_LES_UTILISATEURS", "", e); } } public void sendCallAgainNotification(String message) { try { UserNotificationHelper .buildAndSend(new ScheduleEventUserCallAgainNotification(currentScheduleEvent, message, getUserDetail())); NotifierUtil.addSuccess(getString("scheduleevent.callagain.ok")); } catch (Exception e) { SilverTrace.warn("scheduleevent", "ScheduleEventSessionController.sendSubscriptionsNotification()", "scheduleEvent.EX_IMPOSSIBLE_DALERTER_LES_UTILISATEURS", "", e); } } private ScheduleEventService getScheduleEventService() { return ScheduleEventServiceProvider.getScheduleEventService(); } public List<ScheduleEvent> getScheduleEventsByUserId() { Set<ScheduleEvent> allEvents = getScheduleEventService().listAllScheduleEventsByUserId( getUserId()); List<ScheduleEvent> results = new ArrayList<ScheduleEvent>(allEvents); Collections.sort(results, new ScheduleEventComparator()); return results; } public ScheduleEvent getDetail(String id) { ScheduleEvent event = getScheduleEventService().findScheduleEvent(id); // update last visited date if (event != null) { if (event.canBeAccessedBy(getUserDetail())) { getScheduleEventService().setLastVisited(event, Integer.valueOf(getUserId())); } else { event = null; } } return event; } public void switchState(String id) { ScheduleEvent event = getScheduleEventService().findScheduleEvent(id); if (event.getAuthor() == Integer.parseInt(getUserId())) { int actualStatus = event.getStatus(); int newStatus = ScheduleEventStatus.OPEN; if (ScheduleEventStatus.OPEN == actualStatus) { newStatus = ScheduleEventStatus.CLOSED; } getScheduleEventService().updateScheduleEventStatus(id, newStatus); } else { SilverTrace.warn("scheduleevent", "ScheduleEventSessionController.switchState", "Security alert from user " + getUserId()); NotifierUtil.addError(getString("GML.security.access")); } } public void delete(String scheduleEventId) { ScheduleEvent scheduleEvent = getScheduleEventService().findScheduleEvent(scheduleEventId); if (scheduleEvent.getAuthor() == Integer.parseInt(getUserId())) { getScheduleEventService().deleteScheduleEvent(scheduleEvent); } else { SilverTrace.warn("scheduleevent", "ScheduleEventSessionController.delete", "Security alert from user " + getUserId()); NotifierUtil.addError(getString("GML.security.access")); } } public void updateUserAvailabilities(ScheduleEvent scheduleEvent) { updateValidationDate(scheduleEvent, getUserId()); getScheduleEventService().updateScheduleEvent(scheduleEvent); } private void updateValidationDate(ScheduleEvent scheduleEvent, String userId) { Contributor contributor = getContributor(scheduleEvent, userId); if (contributor != null) { contributor.setLastValidation(new Date()); } } private Contributor getContributor(ScheduleEvent scheduleEvent, String id) { try { int userId = Integer.parseInt(id); for (Contributor contributor : scheduleEvent.getContributors()) { if (contributor.getUserId() == userId) { return contributor; } } } catch (Exception ignore) { } return null; } public ScheduleEvent purgeOldResponseForUserId(ScheduleEvent scheduleEvent) { return getScheduleEventService().purgeOldResponseForUserId(scheduleEvent, Integer.parseInt(getUserId())); } public Double getSubscribersRateAnswerFor(ScheduleEvent event) { return 0.0; } public Set<OptionDateVO> getCurrentOptionalDateIndexes() throws Exception { return ((ScheduleEventVO) getCurrentScheduleEventVO()).getOptionalDateIndexes(); } public void setCurrentScheduleEventWith(Set<OptionDateVO> optionalDays) { ((ScheduleEventVO) getCurrentScheduleEventVO()).setScheduleEventWith(optionalDays); } public Response makeReponseFor(ScheduleEvent scheduleEvent, String dateId) { // TODO: Can add checks for dateId, scheduleEvent integrity Response result = new Response(); result.setScheduleEvent(scheduleEvent); result.setUserId(Integer.parseInt(getUserId())); result.setOptionId(dateId); NotifierUtil.addSuccess(getString("scheduleevent.form.confirmMessage")); return result; } /** * Converts the specified detailed scheduleevent into a calendar event. * @param event detail. * @param listDateOption of dates. * @return the calendar events corresponding to the schedule event. */ private List<CalendarEvent> asCalendarEvents(final ScheduleEvent event, final List<DateOption> listDateOption) { CalendarEventEncoder encoder = new CalendarEventEncoder(); return encoder.encode(event, listDateOption); } /** * Exports the current ScheduleEvent in iCal format. The iCal file is generated into the temporary * directory. * @return the iCal file name into which is generated the current ScheduleEvent. * @throws Exception */ public String exportToICal(ScheduleEvent event) throws Exception { // construction de la liste des dates retenues de l'événement List<DateOption> listDateOption = new ArrayList<DateOption>(); ScheduleEventDetailVO scheduleEventDetailVO = new ScheduleEventDetailVO(this, event); BestTimeVO bestTimeVO = scheduleEventDetailVO.getBestTimes(); if (bestTimeVO.isBestDateExists()) { List<TimeVO> listTimeVO = bestTimeVO.getTimes(); for (TimeVO timeVO : listTimeVO) { HalfDayTime halfDayTime = (HalfDayTime) timeVO; DateVO dateVO = halfDayTime.getDate(); HalfDayDateVO halfDayDateVO = (HalfDayDateVO) dateVO; Date day = halfDayDateVO.getDate(); DateOption dateOption = new DateOption(); dateOption.setDay(day); String label = halfDayTime.getMultilangLabel(); if ("scheduleevent.form.hour.columnam".equals(label)) { dateOption.setHour(ScheduleEventVO.MORNING_HOUR); } else if ("scheduleevent.form.hour.columnpm".equals(label)) { dateOption.setHour(ScheduleEventVO.AFTERNOON_HOUR); } listDateOption.add(dateOption); } } // transformation des dates en CalendarEvent List<CalendarEvent> eventsToExport = asCalendarEvents(event, listDateOption); // export iCal Exporter<ExportableCalendar> iCalExporter = ExporterProvider.getICalExporter(); String icsFileName = ICS_PREFIX + getUserId() + ".ics"; String icsFilePath = FileRepositoryManager.getTemporaryPath() + icsFileName; FileWriter fileWriter = new FileWriter(icsFilePath); try { iCalExporter.export(withWriter(fileWriter), ExportableCalendar.with(eventsToExport)); } catch (ExportException ex) { File fileToDelete = new File(icsFilePath); if (fileToDelete.exists()) { FileUtils.deleteQuietly(fileToDelete); } throw ex; } return icsFileName; } }
improve fix
scheduleevent/scheduleevent-war/src/main/java/com/silverpeas/scheduleevent/control/ScheduleEventSessionController.java
improve fix
<ide><path>cheduleevent/scheduleevent-war/src/main/java/com/silverpeas/scheduleevent/control/ScheduleEventSessionController.java <ide> } <ide> <ide> public String initSelectUsersPanel() { <del> if (getCurrentScheduleEvent().getAuthor() == Integer.parseInt(getUserId())) { <add> if (isUserOwnerOfEvent(getCurrentScheduleEvent())) { <ide> String m_context = ResourceLocator.getGeneralSettingBundle().getString("ApplicationURL"); <ide> Pair<String, String> hostComponentName = new Pair<>(getComponentName(), ""); <ide> Pair<String, String>[] hostPath = new Pair[1]; <ide> <ide> public void switchState(String id) { <ide> ScheduleEvent event = getScheduleEventService().findScheduleEvent(id); <del> if (event.getAuthor() == Integer.parseInt(getUserId())) { <add> if (isUserOwnerOfEvent(event)) { <ide> int actualStatus = event.getStatus(); <ide> int newStatus = ScheduleEventStatus.OPEN; <ide> if (ScheduleEventStatus.OPEN == actualStatus) { <ide> } <ide> } <ide> <add> private boolean isUserOwnerOfEvent(final ScheduleEvent event) { <add> return event.getAuthor() == Integer.parseInt(getUserId()); <add> } <add> <ide> public void delete(String scheduleEventId) { <ide> ScheduleEvent scheduleEvent = getScheduleEventService().findScheduleEvent(scheduleEventId); <del> if (scheduleEvent.getAuthor() == Integer.parseInt(getUserId())) { <add> if (isUserOwnerOfEvent(scheduleEvent)) { <ide> getScheduleEventService().deleteScheduleEvent(scheduleEvent); <ide> } else { <ide> SilverTrace.warn("scheduleevent", "ScheduleEventSessionController.delete",
Java
bsd-3-clause
37a1467e224f7ea78224e70fc1b4a286f09e501b
0
ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus
package org.pocketcampus.plugin.freeroom.data; import static org.pocketcampus.platform.launcher.server.PCServerConfig.PC_SRV_CONFIG; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URISyntaxException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; import java.util.Scanner; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.pocketcampus.platform.sdk.server.database.ConnectionManager; import org.pocketcampus.platform.sdk.server.database.handlers.exceptions.ServerException; import org.pocketcampus.plugin.freeroom.server.FreeRoomServiceImpl; import org.pocketcampus.plugin.freeroom.server.FreeRoomServiceImpl.OCCUPANCY_TYPE; import org.pocketcampus.plugin.freeroom.server.utils.FetchRoomsDetails; import org.pocketcampus.plugin.freeroom.shared.FRPeriod; import org.pocketcampus.plugin.freeroom.shared.utils.FRTimes; public class FetchOccupancyDataJSON { private final String URL_DATA = "https://isatest.epfl.ch/services/timetable/reservations/"; private final String KEY_ALIAS = "name"; private final String KEY_ALIAS_WITHOUT_SPACE = "code"; private final String KEY_DOORCODE = "EPDLCode"; private final String KEY_UID = "sourceId"; private final String KEY_CAPACITY = "capacity"; private final String KEY_CAPACITY_EXTRA = "extraCapacity"; private final String KEY_DINCAT = "typeDIN"; private final String KEY_OCCUPANCY = "meetingType"; private final String KEY_OCCUPANCY_START = "startDateTime"; private final String KEY_OCCUPANCY_LENGTH = "duration"; private final String KEY_OCCUPANCY_ROOMS = "rooms"; private ConnectionManager connMgr = null; private String DB_URL; private String DB_USER; private String DB_PASSWORD; private FreeRoomServiceImpl server = null; public FetchOccupancyDataJSON(String db_url, String username, String passwd, FreeRoomServiceImpl server) { try { connMgr = new ConnectionManager(db_url, username, passwd); DB_URL = db_url; DB_USER = username; DB_PASSWORD = passwd; this.server = server; } catch (ServerException e) { e.printStackTrace(); } } public void fetchAndInsert(long timestamp) { String json = readFromFile("src" + File.separator + "freeroomjson"); extractJSONAndInsert(json); } private void extractJSONAndInsert(String jsonSource) { try { JSONArray sourceArray = new JSONArray(jsonSource); int lengthSourceArray = sourceArray.length(); int countRoom = 0; for (int i = 0; i < lengthSourceArray; ++i) { int countOccupancy = 0; JSONArray subArray = sourceArray.getJSONArray(i); int subArrayLength = subArray.length(); if (subArrayLength == 2) { JSONObject room = subArray.getJSONObject(0); JSONArray occupancy = subArray.getJSONArray(1); String uid = extractAndInsertRoom(room); if (uid != null) { countRoom++; countOccupancy = extractAndInsertOccupancies(occupancy, uid); System.out.println(countOccupancy + " occupancies inserted for room " + uid); } } } System.out.println(countRoom + " rooms inserted"); } catch (JSONException e) { e.printStackTrace(); } } private String extractAndInsertRoom(JSONObject room) { if (room == null) { return null; } try { String uid = null; if (room.has(KEY_UID)) { uid = room.getString(KEY_UID); } else { return null; } // first fetch and insert the room from the other webservice FetchRoomsDetails frd = new FetchRoomsDetails(DB_URL, DB_USER, DB_PASSWORD); if (!frd.fetchRoomDetailInDB(uid)) { return null; } // from this webservice Connection conn = null; conn = connMgr.getConnection(); String reqCapacity = "UPDATE `fr-roomslist` SET capacity = ? WHERE uid = ? AND capacity = 0"; String reqAlias = "UPDATE `fr-roomslist` SET alias = ? WHERE uid = ? AND alias IS NULL"; PreparedStatement queryCapacity; PreparedStatement queryAlias; // first update the capacity queryCapacity = conn.prepareStatement(reqCapacity); int capacity = 0; if (room.has(KEY_CAPACITY)) { capacity = Integer.parseInt(room.getString(KEY_CAPACITY)); } if (capacity == 0 && room.has(KEY_CAPACITY_EXTRA)) { capacity = Integer.parseInt(room.getString(KEY_CAPACITY_EXTRA)); } queryCapacity.setInt(1, capacity); queryCapacity.setString(2, uid); queryCapacity.executeUpdate(); // then update the alias queryAlias = conn.prepareStatement(reqAlias); String alias = null; if (room.has(KEY_ALIAS)) { JSONObject aliasObject = room.getJSONObject(KEY_ALIAS); if (aliasObject.has("fr")) { alias = aliasObject.getString("fr"); } } if (alias == null && room.has(KEY_ALIAS_WITHOUT_SPACE)) { alias = room.getString(KEY_ALIAS_WITHOUT_SPACE); } if (alias != null) { queryAlias.setString(1, alias); queryAlias.setString(2, uid); queryAlias.executeUpdate(); } // if we are there, it means the fetch of the rooms details // succeeded return uid; } catch (SQLException | JSONException e) { e.printStackTrace(); return null; } } private int extractAndInsertOccupancies(JSONArray array, String uid) { if (array == null || uid == null) { return 0; } if (array.length() == 0) { return 0; } try { int nbOccupancy = array.length(); int count = 0; for (int i = 0; i < nbOccupancy; ++i) { JSONObject occupancy = array.getJSONObject(i); long tsStart = 0; long tsEnd = 0; if (occupancy.has(KEY_OCCUPANCY_START)) { tsStart = Long.parseLong(occupancy.getString(KEY_OCCUPANCY_START)); if (occupancy.has(KEY_OCCUPANCY_LENGTH)) { int length = Integer.parseInt(occupancy.getString(KEY_OCCUPANCY_LENGTH)); tsEnd = tsStart + length * FRTimes.ONE_MIN_IN_MS; } } if (tsStart != 0 && tsEnd != 0 && tsStart < tsEnd) { FRPeriod period = new FRPeriod(tsStart, tsEnd, false); if (server.insertOccupancy(period, OCCUPANCY_TYPE.ROOM, uid, null)) { count++; } } } return count; } catch (JSONException e) { e.printStackTrace(); return 0; } } private String readFromFile(String name) { try { Scanner sc = new Scanner(new File(name)); StringBuffer json = new StringBuffer(); while (sc.hasNextLine()) { json.append(sc.nextLine()); } return json.toString(); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } } private String fetch(long timestamp) { String timestampString = FRTimes.convertTimeStampInString(timestamp); System.out.println("Start fetching for ... " + timestampString); DefaultHttpClient client = new DefaultHttpClient(); HttpGet request; try { request = new HttpGet(URL_DATA + timestampString); request.addHeader("Accept", "application/json"); HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); StringBuffer jsonBuffer = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { jsonBuffer.append(line); } System.out.println("Successfully fetched from server"); return jsonBuffer.toString(); } else { System.err.println("Error while fetching ,status " + response.getStatusLine().getStatusCode()); } } catch (URISyntaxException e) { e.printStackTrace(); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }
plugin/freeroom/plugin.freeroom.server/src/org/pocketcampus/plugin/freeroom/data/FetchOccupancyDataJSON.java
package org.pocketcampus.plugin.freeroom.data; import static org.pocketcampus.platform.launcher.server.PCServerConfig.PC_SRV_CONFIG; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URISyntaxException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; import java.util.Scanner; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.pocketcampus.platform.sdk.server.database.ConnectionManager; import org.pocketcampus.platform.sdk.server.database.handlers.exceptions.ServerException; import org.pocketcampus.plugin.freeroom.server.FreeRoomServiceImpl; import org.pocketcampus.plugin.freeroom.server.FreeRoomServiceImpl.OCCUPANCY_TYPE; import org.pocketcampus.plugin.freeroom.server.utils.FetchRoomsDetails; import org.pocketcampus.plugin.freeroom.shared.FRPeriod; import org.pocketcampus.plugin.freeroom.shared.utils.FRTimes; public class FetchOccupancyDataJSON { private final String URL_DATA = "https://isatest.epfl.ch/services/timetable/reservations/"; private final String KEY_ALIAS = "name"; private final String KEY_ALIAS_WITHOUT_SPACE = "code"; private final String KEY_DOORCODE = "EPDLCode"; private final String KEY_UID = "sourceId"; private final String KEY_CAPACITY = "capacity"; private final String KEY_CAPACITY_EXTRA = "extraCapacity"; private final String KEY_DINCAT = "typeDIN"; private final String KEY_OCCUPANCY = "meetingType"; private final String KEY_OCCUPANCY_START = "startDateTime"; private final String KEY_OCCUPANCY_LENGTH = "duration"; private final String KEY_OCCUPANCY_ROOMS = "rooms"; private ConnectionManager connMgr = null; private String DB_URL; private String DB_USER; private String DB_PASSWORD; private FreeRoomServiceImpl server = null; public FetchOccupancyDataJSON(String db_url, String username, String passwd, FreeRoomServiceImpl server) { try { connMgr = new ConnectionManager(db_url, username, passwd); DB_URL = db_url; DB_USER = username; DB_PASSWORD = passwd; this.server = server; } catch (ServerException e) { e.printStackTrace(); } } public void fetchAndInsert(long timestamp) { String json = readFromFile("src" + File.separator + "freeroomjson"); extractJSONAndInsert(json); } private void extractJSONAndInsert(String jsonSource) { try { JSONArray sourceArray = new JSONArray(jsonSource); int lengthSourceArray = sourceArray.length(); int count = 0; for (int i = 0; i < lengthSourceArray; ++i) { JSONArray subArray = sourceArray.getJSONArray(i); int subArrayLength = subArray.length(); if (subArrayLength == 2) { JSONObject room = subArray.getJSONObject(0); JSONArray occupancy = subArray.getJSONArray(1); String uid = extractAndInsertRoom(room); if (uid != null) { count++; extractAndInsertOccupancies(occupancy, uid); } } } System.out.println(count + " rooms inserted"); } catch (JSONException e) { e.printStackTrace(); } } private String extractAndInsertRoom(JSONObject room) { if (room == null) { return null; } try { String uid = null; if (room.has(KEY_UID)) { uid = room.getString(KEY_UID); } else { return null; } // first fetch and insert the room from the other webservice FetchRoomsDetails frd = new FetchRoomsDetails(DB_URL, DB_USER, DB_PASSWORD); if (!frd.fetchRoomDetailInDB(uid)) { return null; } // from this webservice Connection conn = null; conn = connMgr.getConnection(); String reqCapacity = "UPDATE `fr-roomslist` SET capacity = ? WHERE uid = ? AND capacity = 0"; String reqAlias = "UPDATE `fr-roomslist` SET alias = ? WHERE uid = ? AND alias IS NULL"; PreparedStatement queryCapacity; PreparedStatement queryAlias; // first update the capacity queryCapacity = conn.prepareStatement(reqCapacity); int capacity = 0; if (room.has(KEY_CAPACITY)) { capacity = Integer.parseInt(room.getString(KEY_CAPACITY)); } if (capacity == 0 && room.has(KEY_CAPACITY_EXTRA)) { capacity = Integer.parseInt(room.getString(KEY_CAPACITY_EXTRA)); } queryCapacity.setInt(1, capacity); queryCapacity.setString(2, uid); queryCapacity.executeUpdate(); // then update the alias queryAlias = conn.prepareStatement(reqAlias); String alias = null; if (room.has(KEY_ALIAS)) { JSONObject aliasObject = room.getJSONObject(KEY_ALIAS); if (aliasObject.has("fr")) { alias = aliasObject.getString("fr"); } } if (alias == null && room.has(KEY_ALIAS_WITHOUT_SPACE)) { alias = room.getString(KEY_ALIAS_WITHOUT_SPACE); } if (alias != null) { queryAlias.setString(1, alias); queryAlias.setString(2, uid); queryAlias.executeUpdate(); } // if we are there, it means the fetch of the rooms details // succeeded return uid; } catch (SQLException | JSONException e) { e.printStackTrace(); return null; } } private void extractAndInsertOccupancies(JSONArray array, String uid) { if (array == null || uid == null) { return; } if (array.length() == 0) { return; } try { int nbOccupancy = array.length(); for (int i = 0; i < nbOccupancy; ++i) { JSONObject occupancy = array.getJSONObject(i); long tsStart = 0; long tsEnd = 0; if (occupancy.has(KEY_OCCUPANCY_START)) { tsStart = Long.parseLong(occupancy.getString(KEY_OCCUPANCY_START)); if (occupancy.has(KEY_OCCUPANCY_LENGTH)) { int length = Integer.parseInt(occupancy.getString(KEY_OCCUPANCY_LENGTH)); tsEnd = tsStart + length * FRTimes.ONE_MIN_IN_MS; } } if (tsStart != 0 && tsEnd != 0 && tsStart < tsEnd) { FRPeriod period = new FRPeriod(tsStart, tsEnd, false); server.insertOccupancy(period, OCCUPANCY_TYPE.ROOM, uid, null); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private String readFromFile(String name) { try { Scanner sc = new Scanner(new File(name)); StringBuffer json = new StringBuffer(); while (sc.hasNextLine()) { json.append(sc.nextLine()); } return json.toString(); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } } private String fetch(long timestamp) { String timestampString = FRTimes.convertTimeStampInString(timestamp); System.out.println("Start fetching for ... " + timestampString); DefaultHttpClient client = new DefaultHttpClient(); HttpGet request; try { request = new HttpGet(URL_DATA + timestampString); request.addHeader("Accept", "application/json"); HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); StringBuffer jsonBuffer = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { jsonBuffer.append(line); } System.out.println("Successfully fetched from server"); return jsonBuffer.toString(); } else { System.err.println("Error while fetching ,status " + response.getStatusLine().getStatusCode()); } } catch (URISyntaxException e) { e.printStackTrace(); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }
[freeroom.server] Slightly changed of returned value in the process of fetching and extracting occupancies
plugin/freeroom/plugin.freeroom.server/src/org/pocketcampus/plugin/freeroom/data/FetchOccupancyDataJSON.java
[freeroom.server] Slightly changed of returned value in the process of fetching and extracting occupancies
<ide><path>lugin/freeroom/plugin.freeroom.server/src/org/pocketcampus/plugin/freeroom/data/FetchOccupancyDataJSON.java <ide> try { <ide> JSONArray sourceArray = new JSONArray(jsonSource); <ide> int lengthSourceArray = sourceArray.length(); <del> int count = 0; <add> int countRoom = 0; <add> <ide> for (int i = 0; i < lengthSourceArray; ++i) { <add> int countOccupancy = 0; <ide> JSONArray subArray = sourceArray.getJSONArray(i); <ide> int subArrayLength = subArray.length(); <ide> <ide> <ide> String uid = extractAndInsertRoom(room); <ide> if (uid != null) { <del> count++; <del> extractAndInsertOccupancies(occupancy, uid); <add> countRoom++; <add> countOccupancy = extractAndInsertOccupancies(occupancy, uid); <add> System.out.println(countOccupancy + " occupancies inserted for room " + uid); <ide> } <ide> } <ide> <ide> } <del> System.out.println(count + " rooms inserted"); <add> System.out.println(countRoom + " rooms inserted"); <ide> } catch (JSONException e) { <ide> e.printStackTrace(); <ide> } <ide> <ide> } <ide> <del> private void extractAndInsertOccupancies(JSONArray array, String uid) { <add> private int extractAndInsertOccupancies(JSONArray array, String uid) { <ide> if (array == null || uid == null) { <del> return; <add> return 0; <ide> } <ide> <ide> if (array.length() == 0) { <del> return; <add> return 0; <ide> } <ide> try { <ide> int nbOccupancy = array.length(); <del> <add> int count = 0; <ide> for (int i = 0; i < nbOccupancy; ++i) { <ide> JSONObject occupancy = array.getJSONObject(i); <ide> long tsStart = 0; <ide> <ide> if (tsStart != 0 && tsEnd != 0 && tsStart < tsEnd) { <ide> FRPeriod period = new FRPeriod(tsStart, tsEnd, false); <del> server.insertOccupancy(period, OCCUPANCY_TYPE.ROOM, uid, null); <del> } <del> } <add> if (server.insertOccupancy(period, OCCUPANCY_TYPE.ROOM, uid, null)) { <add> count++; <add> } <add> } <add> } <add> return count; <ide> } catch (JSONException e) { <del> // TODO Auto-generated catch block <del> e.printStackTrace(); <add> e.printStackTrace(); <add> return 0; <ide> } <ide> } <ide>
JavaScript
agpl-3.0
f36d91336aba740086b5aadfffc95a6661a53144
0
grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana
define([ 'angular', 'underscore', 'jquery' ], function (angular, _, $) { 'use strict'; // This function needs $inject annotations, update below // when changing arguments to this function function PanelBaseCtrl($scope, $rootScope, $timeout) { var menu = [ { text: 'Edit', configModal: "app/partials/paneleditor.html", condition: !$scope.panelMeta.fullscreenEdit }, { text: 'Edit', click: "toggleFullscreenEdit()", condition: $scope.panelMeta.fullscreenEdit }, { text: "Fullscreen", click: 'toggleFullscreen()', condition: $scope.panelMeta.fullscreenView }, { text: 'Duplicate', click: 'duplicatePanel(panel)', condition: true }, { text: 'Span', submenu: [ { text: '1', click: 'updateColumnSpan(1)' }, { text: '2', click: 'updateColumnSpan(2)' }, { text: '3', click: 'updateColumnSpan(3)' }, { text: '4', click: 'updateColumnSpan(4)' }, { text: '5', click: 'updateColumnSpan(5)' }, { text: '6', click: 'updateColumnSpan(6)' }, { text: '7', click: 'updateColumnSpan(7)' }, { text: '8', click: 'updateColumnSpan(8)' }, { text: '9', click: 'updateColumnSpan(9)' }, { text: '10', click: 'updateColumnSpan(10)' }, { text: '11', click: 'updateColumnSpan(11)' }, { text: '12', click: 'updateColumnSpan(12)' }, ], condition: true }, { text: 'Remove', click: 'remove_panel_from_row(row, panel)', condition: true } ]; $scope.inspector = {}; $scope.panelMeta.menu = _.where(menu, { condition: true }); $scope.updateColumnSpan = function(span) { $scope.panel.span = span; $timeout(function() { $scope.$emit('render'); }); }; $scope.enterFullscreenMode = function(options) { var docHeight = $(window).height(); var editHeight = Math.floor(docHeight * 0.3); var fullscreenHeight = Math.floor(docHeight * 0.7); var oldTimeRange = $scope.range; $scope.height = options.edit ? editHeight : fullscreenHeight; $scope.editMode = options.edit; if (!$scope.fullscreen) { var closeEditMode = $rootScope.$on('panel-fullscreen-exit', function() { $scope.editMode = false; $scope.fullscreen = false; delete $scope.height; closeEditMode(); $timeout(function() { if (oldTimeRange !== $scope.range) { $scope.dashboard.refresh(); } else { $scope.$emit('render'); } }); }); } $(window).scrollTop(0); $scope.fullscreen = true; $rootScope.$emit('panel-fullscreen-enter'); $timeout(function() { $scope.$emit('render'); }); }; $scope.toggleFullscreenEdit = function() { if ($scope.editMode) { $rootScope.$emit('panel-fullscreen-exit'); return; } $scope.enterFullscreenMode({edit: true}); }; $scope.toggleFullscreen = function() { if ($scope.fullscreen && !$scope.editMode) { $rootScope.$emit('panel-fullscreen-exit'); return; } $scope.enterFullscreenMode({ edit: false }); }; } PanelBaseCtrl['$inject'] = ['$scope', '$rootScope', '$timeout']; return PanelBaseCtrl; });
src/app/controllers/panelBaseCtrl.js
define([ 'angular', 'underscore', 'jquery' ], function (angular, _, $) { 'use strict'; function PanelBaseCtrl($scope, $rootScope, $timeout) { var menu = [ { text: 'Edit', configModal: "app/partials/paneleditor.html", condition: !$scope.panelMeta.fullscreenEdit }, { text: 'Edit', click: "toggleFullscreenEdit()", condition: $scope.panelMeta.fullscreenEdit }, { text: "Fullscreen", click: 'toggleFullscreen()', condition: $scope.panelMeta.fullscreenView }, { text: 'Duplicate', click: 'duplicatePanel(panel)', condition: true }, { text: 'Span', submenu: [ { text: '1', click: 'updateColumnSpan(1)' }, { text: '2', click: 'updateColumnSpan(2)' }, { text: '3', click: 'updateColumnSpan(3)' }, { text: '4', click: 'updateColumnSpan(4)' }, { text: '5', click: 'updateColumnSpan(5)' }, { text: '6', click: 'updateColumnSpan(6)' }, { text: '7', click: 'updateColumnSpan(7)' }, { text: '8', click: 'updateColumnSpan(8)' }, { text: '9', click: 'updateColumnSpan(9)' }, { text: '10', click: 'updateColumnSpan(10)' }, { text: '11', click: 'updateColumnSpan(11)' }, { text: '12', click: 'updateColumnSpan(12)' }, ], condition: true }, { text: 'Remove', click: 'remove_panel_from_row(row, panel)', condition: true } ]; $scope.inspector = {}; $scope.panelMeta.menu = _.where(menu, { condition: true }); $scope.updateColumnSpan = function(span) { $scope.panel.span = span; $timeout(function() { $scope.$emit('render'); }); }; $scope.enterFullscreenMode = function(options) { var docHeight = $(window).height(); var editHeight = Math.floor(docHeight * 0.3); var fullscreenHeight = Math.floor(docHeight * 0.7); var oldTimeRange = $scope.range; $scope.height = options.edit ? editHeight : fullscreenHeight; $scope.editMode = options.edit; if (!$scope.fullscreen) { var closeEditMode = $rootScope.$on('panel-fullscreen-exit', function() { $scope.editMode = false; $scope.fullscreen = false; delete $scope.height; closeEditMode(); $timeout(function() { if (oldTimeRange !== $scope.range) { $scope.dashboard.refresh(); } else { $scope.$emit('render'); } }); }); } $(window).scrollTop(0); $scope.fullscreen = true; $rootScope.$emit('panel-fullscreen-enter'); $timeout(function() { $scope.$emit('render'); }); }; $scope.toggleFullscreenEdit = function() { if ($scope.editMode) { $rootScope.$emit('panel-fullscreen-exit'); return; } $scope.enterFullscreenMode({edit: true}); }; $scope.toggleFullscreen = function() { if ($scope.fullscreen && !$scope.editMode) { $rootScope.$emit('panel-fullscreen-exit'); return; } $scope.enterFullscreenMode({ edit: false }); }; } return PanelBaseCtrl; });
Fixes #289, PanelBaseCtrl needs to specify inject dependency annotations as it doesnt follow regular angular controller syntax, ngmin grunt task misses it
src/app/controllers/panelBaseCtrl.js
Fixes #289, PanelBaseCtrl needs to specify inject dependency annotations as it doesnt follow regular angular controller syntax, ngmin grunt task misses it
<ide><path>rc/app/controllers/panelBaseCtrl.js <ide> function (angular, _, $) { <ide> 'use strict'; <ide> <add> // This function needs $inject annotations, update below <add> // when changing arguments to this function <ide> function PanelBaseCtrl($scope, $rootScope, $timeout) { <ide> <ide> var menu = [ <ide> <ide> } <ide> <add> PanelBaseCtrl['$inject'] = ['$scope', '$rootScope', '$timeout']; <add> <ide> return PanelBaseCtrl; <ide> <ide> });
Java
apache-2.0
45a524f54d98310dda9124e4a8534a9f15d2d99a
0
gxa/gxa,gxa/gxa,gxa/gxa,gxa/gxa,gxa/gxa
/** * EBI Microarray Informatics Team (c) 2007-2008 */ package uk.ac.ebi.ae3.indexbuilder; import org.apache.commons.cli2.Argument; import org.apache.commons.cli2.CommandLine; import org.apache.commons.cli2.Group; import org.apache.commons.cli2.builder.ArgumentBuilder; import org.apache.commons.cli2.builder.DefaultOptionBuilder; import org.apache.commons.cli2.builder.GroupBuilder; import org.apache.commons.cli2.commandline.Parser; import org.apache.commons.cli2.option.DefaultOption; import org.apache.commons.cli2.util.HelpFormatter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.dbcp.BasicDataSource; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import uk.ac.ebi.ae3.indexbuilder.service.IndexBuilderService; import uk.ac.ebi.ae3.indexbuilder.service.GeneAtlasIndexBuilder; /** * The main class which contains main method. Create expt lucene index. * Configuration is stored in app-context.xml file * * @author mdylag * */ public class App { /** */ private final HelpFormatter helpFormatter = new HelpFormatter(); private final DefaultOptionBuilder optionBuilder = new DefaultOptionBuilder(); private final ArgumentBuilder argumentBuilder = new ArgumentBuilder(); private final GroupBuilder groupBuilder = new GroupBuilder(); private final Argument pathArgument = argumentBuilder .withName("path") .withMaximum(1) .create(); private final DefaultOption optionProperty = optionBuilder .withLongName( Constants.KEY_PROPERTY) .withRequired( false) .withArgument( pathArgument) .withDescription( "Property file") .create(); private final Argument modeArgument = argumentBuilder .withName("mode") .withMinimum(1) .withMaximum(2) .withDefault("expt") .withSubsequentSeparator(',') .create(); private final DefaultOption optionBuild = optionBuilder .withLongName("build") .withRequired(false) .withArgument(modeArgument) .withDescription("Indexes to build") .create(); private final DefaultOption optionUpdate = optionBuilder .withLongName("update") .withRequired(false) .withDescription("Update mode") .create(); private String propertyFile; private XmlBeanFactory appContext; private static final Log log = LogFactory .getLog(App.class); private boolean buildExpt = false; private boolean buildGene = false; private boolean updateMode = false; public static void main(String[] args) { try { App app = new App(); //TODO: Add exception to parse method if(app.parse(args)) { app.startContext(); app.run(); } } catch (Exception e) { e.printStackTrace(); log.error(e); System.exit(-1); } catch (IndexException e) { e.printStackTrace(); log.error(e); System.exit(-1); } } protected void startContext() { PropertyPlaceholderConfigurer conf = new PropertyPlaceholderConfigurer(); conf.setLocation(propertyFile == null ? new ClassPathResource("indexbuilder.properties") : new FileSystemResource(propertyFile)); appContext = new XmlBeanFactory(new ClassPathResource( "app-context.xml")); conf.postProcessBeanFactory(appContext); } /** * DOCUMENT ME * @throws Exception * @throws IndexException */ protected void run() throws Exception, IndexException { IndexBuilderService indexBuilderService; log.info("Will build indexes: " + (buildExpt ? "experiments " : "") + (buildGene ? "gene" : "") + (updateMode ? " (update mode)" : "")); if(buildExpt) { log.info("Building experiments index"); indexBuilderService = (IndexBuilderService) appContext .getBean(Constants.exptIndexBuilderServiceID); indexBuilderService.setUpdateMode(updateMode); indexBuilderService.buildIndex(); } if(buildGene) { log.info("Building atlas gene index"); indexBuilderService = (IndexBuilderService) appContext .getBean(Constants.geneIndexBuilderServiceID); indexBuilderService.setUpdateMode(updateMode); indexBuilderService.buildIndex(); } } protected boolean parse(String[] args) { Group groupOptions = groupBuilder.withOption(optionProperty) .withOption(optionBuild) .withOption(optionUpdate) .create(); Parser parser = new Parser(); parser.setGroup(groupOptions); parser.setHelpFormatter(helpFormatter); parser.setHelpTrigger("--help"); CommandLine cl = parser.parseAndHelp(args); if (cl == null) { helpFormatter.printException(); return false; } else { propertyFile = cl.hasOption(optionProperty) ? (String) cl.getValue(optionProperty) : null; updateMode = cl.hasOption(optionUpdate); if(cl.hasOption(optionBuild)) { for(Object s: cl.getValues(optionBuild)) { if("expt".equals(s)) buildExpt = true; else if("gene".equals(s)) buildGene = true; } } if(!buildGene && !buildExpt) buildExpt = true; return true; } } public XmlBeanFactory getAppContext() { return appContext; } public void setAppContext(XmlBeanFactory appContext) { this.appContext = appContext; } }
indexbuilder/src/main/java/uk/ac/ebi/ae3/indexbuilder/App.java
/** * EBI Microarray Informatics Team (c) 2007-2008 */ package uk.ac.ebi.ae3.indexbuilder; import org.apache.commons.cli2.Argument; import org.apache.commons.cli2.CommandLine; import org.apache.commons.cli2.Group; import org.apache.commons.cli2.builder.ArgumentBuilder; import org.apache.commons.cli2.builder.DefaultOptionBuilder; import org.apache.commons.cli2.builder.GroupBuilder; import org.apache.commons.cli2.commandline.Parser; import org.apache.commons.cli2.option.DefaultOption; import org.apache.commons.cli2.util.HelpFormatter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.dbcp.BasicDataSource; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import uk.ac.ebi.ae3.indexbuilder.service.IndexBuilderService; import uk.ac.ebi.ae3.indexbuilder.service.GeneAtlasIndexBuilder; /** * The main class which contains main method. Create expt lucene index. * Configuration is stored in app-context.xml file * * @author mdylag * */ public class App { /** */ private final HelpFormatter helpFormatter = new HelpFormatter(); private final DefaultOptionBuilder optionBuilder = new DefaultOptionBuilder(); private final ArgumentBuilder argumentBuilder = new ArgumentBuilder(); private final GroupBuilder groupBuilder = new GroupBuilder(); private final Argument pathArgument = argumentBuilder .withName("path") .withMaximum(1) .create(); private final DefaultOption optionProperty = optionBuilder .withLongName( Constants.KEY_PROPERTY) .withRequired( false) .withArgument( pathArgument) .withDescription( "Property file") .create(); private final Argument modeArgument = argumentBuilder .withName("mode") .withMinimum(1) .withMaximum(2) .withDefault("expt") .withSubsequentSeparator(',') .create(); private final DefaultOption optionBuild = optionBuilder .withLongName("build") .withRequired(false) .withArgument(modeArgument) .withDescription("Indexes to build") .create(); private final DefaultOption optionUpdate = optionBuilder .withLongName("update") .withRequired(false) .withDescription("Update mode") .create(); private String propertyFile; private XmlBeanFactory appContext; private static final Log log = LogFactory .getLog(App.class); private boolean buildExpt = false; private boolean buildGene = false; private boolean updateMode = false; public static void main(String[] args) { try { App app = new App(); //TODO: Add exception to parse method if(app.parse(args)) { app.startContext(); app.run(); } } catch (Exception e) { e.printStackTrace(); log.error(e); System.exit(-1); } catch (IndexException e) { e.printStackTrace(); log.error(e); System.exit(-1); } } protected void startContext() { PropertyPlaceholderConfigurer conf = new PropertyPlaceholderConfigurer(); conf.setLocation(propertyFile == null ? new ClassPathResource("indexbuilder.properties") : new FileSystemResource(propertyFile)); appContext = new XmlBeanFactory(new ClassPathResource( "app-context.xml")); conf.postProcessBeanFactory(appContext); } /** * DOCUMENT ME * @throws Exception * @throws IndexException */ protected void run() throws Exception, IndexException { IndexBuilderService indexBuilderService; log.info("Will build indexes: " + (buildExpt ? "experiments " : "") + (buildGene ? "gene" : "") + (updateMode ? " (update mode)" : "")); if(buildExpt) { log.info("Building experiments index"); indexBuilderService = (IndexBuilderService) appContext .getBean(Constants.exptIndexBuilderServiceID); indexBuilderService.setUpdateMode(updateMode); indexBuilderService.buildIndex(); } if(buildGene) { log.info("Building atlas gene index"); indexBuilderService = (IndexBuilderService) appContext .getBean(Constants.geneIndexBuilderServiceID); indexBuilderService.setUpdateMode(updateMode); indexBuilderService.buildIndex(); } } protected boolean parse(String[] args) { Group groupOptions = groupBuilder.withOption(optionProperty) .withOption(optionBuild) .withOption(optionUpdate) .create(); Parser parser = new Parser(); parser.setGroup(groupOptions); parser.setHelpFormatter(helpFormatter); parser.setHelpTrigger("--help"); CommandLine cl = parser.parseAndHelp(args); if (cl == null) { helpFormatter.printException(); return false; } else { propertyFile = cl.hasOption(optionProperty) ? (String) cl.getValue(optionProperty) : null; updateMode = cl.hasOption(optionUpdate); if(cl.hasOption(optionBuild)) { for(Object s: cl.getValues(optionBuild)) { if("expt".equals(s)) buildExpt = true; else if("gene".equals(s)) buildGene = true; } } return true; } } public XmlBeanFactory getAppContext() { return appContext; } public void setAppContext(XmlBeanFactory appContext) { this.appContext = appContext; } }
Build expt index if none is specified on command line git-svn-id: e91e1122b8e4d8f297534355a8810ed6b723f824@5782 2913f559-6b04-0410-9a09-c530ee9f5186
indexbuilder/src/main/java/uk/ac/ebi/ae3/indexbuilder/App.java
Build expt index if none is specified on command line
<ide><path>ndexbuilder/src/main/java/uk/ac/ebi/ae3/indexbuilder/App.java <ide> buildGene = true; <ide> } <ide> } <add> <add> if(!buildGene && !buildExpt) <add> buildExpt = true; <add> <ide> return true; <ide> } <ide>
Java
mit
fc6cd58bdee2f99885c7406e4510bfadca137fa8
0
InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service
package org.innovateuk.ifs.finance.controller; import org.innovateuk.ifs.MockMvcTest; import org.innovateuk.ifs.finance.resource.cost.FinanceRowType; import org.innovateuk.ifs.finance.resource.totals.FinanceCostTotalResource; import org.innovateuk.ifs.finance.resource.totals.FinanceType; import org.innovateuk.ifs.finance.transactional.CostTotalService; import org.junit.Test; import org.mockito.Mock; import org.springframework.http.MediaType; import java.math.BigDecimal; import java.util.List; import java.util.function.Consumer; import static org.assertj.core.api.Assertions.assertThat; import static org.innovateuk.ifs.LambdaMatcher.createLambdaMatcher; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess; import static org.innovateuk.ifs.finance.builder.FinanceCostTotalResourceBuilder.newFinanceCostTotalResource; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; public class CostTotalControllerTest extends MockMvcTest<CostTotalController> { @Mock private CostTotalService costTotalService; @Override public CostTotalController supplyControllerUnderTest() { return new CostTotalController(costTotalService); } @Test public void addCostTotal() throws Exception { FinanceCostTotalResource financeCostTotalResource = new FinanceCostTotalResource( FinanceType.APPLICATION, FinanceRowType.LABOUR, new BigDecimal("999999999.999999"), 1L ); Consumer<FinanceCostTotalResource> matchesExpectedResource = (resource) -> { assertThat(resource).isEqualToComparingFieldByField(financeCostTotalResource); }; when(costTotalService.saveCostTotal(createLambdaMatcher(matchesExpectedResource))).thenReturn(serviceSuccess()); mockMvc.perform( post("/cost-total") .content(json(financeCostTotalResource)) .contentType(MediaType.APPLICATION_JSON) ) .andExpect(status().isCreated()); verify(costTotalService).saveCostTotal(createLambdaMatcher(matchesExpectedResource)); } @Test public void addCostTotals() throws Exception { List<FinanceCostTotalResource> financeCostTotalResources = newFinanceCostTotalResource() .withFinanceType(FinanceType.APPLICATION) .withFinanceRowType(FinanceRowType.LABOUR, FinanceRowType.MATERIALS) .withFinanceId(1L, 2L) .withTotal(new BigDecimal("999.999999"), new BigDecimal("1999.999999")) .build(2); Consumer<List<FinanceCostTotalResource>> matchesExpectedResources = (resources) -> { assertThat(resources).usingFieldByFieldElementComparator().containsAll(financeCostTotalResources); }; when(costTotalService.saveCostTotals(createLambdaMatcher(matchesExpectedResources))).thenReturn(serviceSuccess()); mockMvc.perform( post("/cost-totals") .content(json(financeCostTotalResources)) .contentType(MediaType.APPLICATION_JSON) ) .andExpect(status().isCreated()); verify(costTotalService).saveCostTotals(createLambdaMatcher(matchesExpectedResources)); } }
ifs-data-layer/ifs-finance-data-service/src/test/java/org/innovateuk/ifs/finance/controller/CostTotalControllerTest.java
package org.innovateuk.ifs.finance.controller; import org.innovateuk.ifs.MockMvcTest; import org.innovateuk.ifs.finance.resource.cost.FinanceRowType; import org.innovateuk.ifs.finance.resource.totals.FinanceCostTotalResource; import org.innovateuk.ifs.finance.resource.totals.FinanceType; import org.innovateuk.ifs.finance.transactional.CostTotalService; import org.junit.Test; import org.mockito.Mock; import org.springframework.http.MediaType; import java.math.BigDecimal; import java.util.List; import java.util.function.Consumer; import static org.assertj.core.api.Assertions.assertThat; import static org.innovateuk.ifs.LambdaMatcher.createLambdaMatcher; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess; import static org.innovateuk.ifs.finance.builder.sync.FinanceCostTotalResourceBuilder.newFinanceCostTotalResource; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; public class CostTotalControllerTest extends MockMvcTest<CostTotalController> { @Mock private CostTotalService costTotalService; @Override public CostTotalController supplyControllerUnderTest() { return new CostTotalController(costTotalService); } @Test public void addCostTotal() throws Exception { FinanceCostTotalResource financeCostTotalResource = new FinanceCostTotalResource( FinanceType.APPLICATION, FinanceRowType.LABOUR, new BigDecimal("999999999.999999"), 1L ); Consumer<FinanceCostTotalResource> matchesExpectedResource = (resource) -> { assertThat(resource).isEqualToComparingFieldByField(financeCostTotalResource); }; when(costTotalService.saveCostTotal(createLambdaMatcher(matchesExpectedResource))).thenReturn(serviceSuccess()); mockMvc.perform( post("/cost-total") .content(json(financeCostTotalResource)) .contentType(MediaType.APPLICATION_JSON) ) .andExpect(status().isCreated()); verify(costTotalService).saveCostTotal(createLambdaMatcher(matchesExpectedResource)); } @Test public void addCostTotals() throws Exception { List<FinanceCostTotalResource> financeCostTotalResources = newFinanceCostTotalResource() .withFinanceType(FinanceType.APPLICATION) .withFinanceRowType(FinanceRowType.LABOUR, FinanceRowType.MATERIALS) .withFinanceId(1L, 2L) .withTotal(new BigDecimal("999.999999"), new BigDecimal("1999.999999")) .build(2); Consumer<List<FinanceCostTotalResource>> matchesExpectedResources = (resources) -> { assertThat(resources).usingFieldByFieldElementComparator().containsAll(financeCostTotalResources); }; when(costTotalService.saveCostTotals(createLambdaMatcher(matchesExpectedResources))).thenReturn(serviceSuccess()); mockMvc.perform( post("/cost-totals") .content(json(financeCostTotalResources)) .contentType(MediaType.APPLICATION_JSON) ) .andExpect(status().isCreated()); verify(costTotalService).saveCostTotals(createLambdaMatcher(matchesExpectedResources)); } }
[IFS-10220] fix
ifs-data-layer/ifs-finance-data-service/src/test/java/org/innovateuk/ifs/finance/controller/CostTotalControllerTest.java
[IFS-10220] fix
<ide><path>fs-data-layer/ifs-finance-data-service/src/test/java/org/innovateuk/ifs/finance/controller/CostTotalControllerTest.java <ide> import static org.assertj.core.api.Assertions.assertThat; <ide> import static org.innovateuk.ifs.LambdaMatcher.createLambdaMatcher; <ide> import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess; <del>import static org.innovateuk.ifs.finance.builder.sync.FinanceCostTotalResourceBuilder.newFinanceCostTotalResource; <add>import static org.innovateuk.ifs.finance.builder.FinanceCostTotalResourceBuilder.newFinanceCostTotalResource; <ide> import static org.mockito.Mockito.verify; <ide> import static org.mockito.Mockito.when; <ide> import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
Java
bsd-3-clause
04ac4b47dbdd59a2e54b46796284a92e2cc3d4c8
0
NCIP/caadapter,NCIP/caadapter,NCIP/caadapter
package gov.nih.nci.cbiit.cdms.formula.gui.view; import java.awt.Graphics; import java.awt.Point; import gov.nih.nci.cbiit.cdms.formula.core.BaseMeta; import gov.nih.nci.cbiit.cdms.formula.core.FormulaMeta; import gov.nih.nci.cbiit.cdms.formula.core.OperationType; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; public class FormulaPanel extends JPanel{ private BaseMeta controlMeta; private JLabel nameLabel; private TermView termView; public FormulaPanel(BaseMeta formula) { super(); controlMeta=formula; if (controlMeta==null) return; if (controlMeta instanceof FormulaMeta) initFormulaUI((FormulaMeta) controlMeta); else { nameLabel=new JLabel("Formula Store:"+controlMeta.getName()); nameLabel.setLocation(this.getX()+this.getWidth()/2, this.getY()+this.getHeight()/2); this.add(nameLabel); } } private void drawDivider(TermView view, int x0, int y0, Graphics g) { g.drawLine(x0,y0, x0+view.getWidth(), y0); } private void drawSquareRoot(TermView view, int x0, int y0, Graphics g) { // p2-----------------p1 // * // * // * // p4* * // * ** // p5* * p3 Point p1=new Point(x0+view.getWidth()-5, y0-10); Point p2=new Point(x0, y0-10); Point p3=new Point(x0-5, y0+view.getHeight()-10); Point p4=new Point(x0-10, y0+view.getHeight()-15); Point p5=new Point(x0-15, y0+view.getHeight()-10); g.drawLine(p1.x,p1.y, p2.x, p2.y); g.drawLine(p2.x,p2.y, p3.x, p3.y); g.drawLine(p3.x,p3.y, p4.x, p4.y); g.drawLine(p4.x,p4.y, p5.x, p5.y); } private void initFormulaUI(FormulaMeta f) { String lbText="No formula is selected"; if (f!=null) lbText=f.getName(); if (f.getExpression().getUnit()!=null &&f.getExpression().getUnit().trim().length()>0) lbText=lbText+"("+f.getExpression().getUnit()+")"; lbText=lbText+" = "; nameLabel=new TermUiComponent(lbText); add(nameLabel); termView=new TermView(f.getExpression(), 0, 0); ViewMouseAdapter mouseListener=new ViewMouseAdapter(); processViewComponents(termView, mouseListener); } @Override protected void paintComponent(Graphics arg0) { // TODO Auto-generated method stub super.paintComponent(arg0); if (nameLabel==null) return; nameLabel.setLocation(TermView.VIEW_COMPONENT_PADDING*4, getHeight()/2); if (termView==null) return; int x0=TermView.VIEW_COMPONENT_PADDING*2 + nameLabel.getX()+(int)nameLabel.getBounds().getWidth(); //y0 is the middle of the left label int y0=this.getHeight()/2+TermView.VIEW_COMPONENT_HEIGHT/2; positionTermUiComponent(termView, x0, calculateViewY(termView,y0), arg0); } private int calculateViewY(TermView view, int yStart) { int y=yStart; if (view.getTerm()==null) return y; if (view.getTerm().getOperation()==null) return y; switch(view.getTerm().getOperation()) { case DIVISION://make the divider line at bottom of the dividend y=yStart-view.getFirtTermView().getHeight(); break; case SQUAREROOT: //make the centers of square root and left label at the same level y=yStart-view.getHeight()/2; break; default : //make the view start is the bottom of left label y=yStart-TermView.VIEW_COMPONENT_HEIGHT/2; break; } return y; } private void positionTermUiComponent(TermView view, int x0, int y0, Graphics g) { if (view==null) return; if (view.getTermUiComponent()!=null) { JComponent viewUi=view.getTermUiComponent(); viewUi.setLocation(x0+view.getX(), y0+view.getY()); } positionTermUiComponent(view.getFirtTermView(), x0, y0, g); if (view.getTermOperatioinComponent()!=null) { if(view.getTerm().getOperation().equals(OperationType.LOGARITHM)) view.getTermOperatioinComponent().setLocation(x0+view.getX(), y0+view.getSecondTermView().getY()); else view.getTermOperatioinComponent().setLocation(x0+view.getX()+view.getFirtTermView().getWidth(), y0+view.getFirtTermView().getY()); } if (view.getTerm().getOperation()==OperationType.DIVISION) drawDivider(view,x0+view.getX(), y0+view.getY()+view.getFirtTermView().getHeight(), g); else if (view.getTerm().getOperation()==OperationType.SQUAREROOT) drawSquareRoot(view, x0+view.getX(), y0+view.getY(), g); int x2=x0; int y2=y0; if (view.getTerm()!=null&&view.getTerm().getOperation()!=null&&view.getTerm().getOperation().equals(OperationType.DIVISION)) { y2=y0+TermView.VIEW_COMPONENT_HEIGHT/2; } positionTermUiComponent(view.getSecondTermView(), x2, y2, g); } /** * use the the mouse listener instance for all TermView UI components * @param view * @param listener */ private void processViewComponents(TermView view, ViewMouseAdapter listener) { if (view==null) return; if (view.getTermUiComponent()!=null) { add(view.getTermUiComponent()); view.getTermUiComponent().addMouseListener(listener); return; } processViewComponents(view.getFirtTermView(), listener); if (view.getTermOperatioinComponent()!=null) { add(view.getTermOperatioinComponent()); view.getTermOperatioinComponent().addMouseListener(listener); } processViewComponents(view.getSecondTermView(), listener); } }
software/cdms/src/gov/nih/nci/cbiit/cdms/formula/gui/view/FormulaPanel.java
package gov.nih.nci.cbiit.cdms.formula.gui.view; import java.awt.Graphics; import java.awt.Point; import gov.nih.nci.cbiit.cdms.formula.core.BaseMeta; import gov.nih.nci.cbiit.cdms.formula.core.FormulaMeta; import gov.nih.nci.cbiit.cdms.formula.core.OperationType; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; public class FormulaPanel extends JPanel{ private BaseMeta controlMeta; private JLabel nameLabel; private TermView termView; public FormulaPanel(BaseMeta formula) { super(); controlMeta=formula; if (controlMeta==null) return; if (controlMeta instanceof FormulaMeta) initFormulaUI((FormulaMeta) controlMeta); else { nameLabel=new JLabel("Formula Store:"+controlMeta.getName()); nameLabel.setLocation(this.getX()+this.getWidth()/2, this.getY()+this.getHeight()/2); this.add(nameLabel); } } private void drawDivider(TermView view, int x0, int y0, Graphics g) { g.drawLine(x0,y0, x0+view.getWidth(), y0); } private void drawSquareRoot(TermView view, int x0, int y0, Graphics g) { // p2-----------------p1 // * // * // * // p4* * // * ** // p5* * p3 Point p1=new Point(x0+view.getWidth()-5, y0-10); Point p2=new Point(x0, y0-10); Point p3=new Point(x0-5, y0+view.getHeight()-10); Point p4=new Point(x0-10, y0+view.getHeight()-15); Point p5=new Point(x0-15, y0+view.getHeight()-10); g.drawLine(p1.x,p1.y, p2.x, p2.y); g.drawLine(p2.x,p2.y, p3.x, p3.y); g.drawLine(p3.x,p3.y, p4.x, p4.y); g.drawLine(p4.x,p4.y, p5.x, p5.y); } private void initFormulaUI(FormulaMeta f) { String lbText="No formula is selected"; if (f!=null) lbText=f.getName(); if (f.getExpression().getUnit()!=null &&f.getExpression().getUnit().trim().length()>0) lbText=lbText+"("+f.getExpression().getUnit()+")"; lbText=lbText+" = "; nameLabel=new TermUiComponent(lbText); add(nameLabel); termView=new TermView(f.getExpression(), 0, 0); ViewMouseAdapter mouseListener=new ViewMouseAdapter(); processViewComponents(termView, mouseListener); } @Override protected void paintComponent(Graphics arg0) { // TODO Auto-generated method stub super.paintComponent(arg0); if (nameLabel==null) return; nameLabel.setLocation(TermView.VIEW_COMPONENT_PADDING*4, getHeight()/2); if (termView==null) return; int x0=TermView.VIEW_COMPONENT_PADDING*2 + nameLabel.getX()+(int)nameLabel.getBounds().getWidth(); //y0 is the middle of the left label int y0=this.getHeight()/2+TermView.VIEW_COMPONENT_HEIGHT/2; positionTermUiComponent(termView, x0, calculateViewY(termView,y0), arg0); } private int calculateViewY(TermView view, int yStart) { int y=yStart; if (view.getTerm()==null) return y; if (view.getTerm().getOperation()==null) return y; switch(view.getTerm().getOperation()) { case DIVISION://make the divider line at bottom of the dividend y=yStart-view.getFirtTermView().getHeight(); break; case SQUAREROOT: //make the centers of square root and left label at the same level y=yStart-view.getHeight()/2; break; default : //make the view start is the bottom of left label y=yStart-TermView.VIEW_COMPONENT_HEIGHT/2; break; } return y; } private void positionTermUiComponent(TermView view, int x0, int y0, Graphics g) { if (view==null) return; if (view.getTermUiComponent()!=null) { JComponent viewUi=view.getTermUiComponent(); viewUi.setLocation(x0+view.getX(), y0+view.getY()); } positionTermUiComponent(view.getFirtTermView(), x0, y0, g); if (view.getTermOperatioinComponent()!=null) { if(view.getTerm().getOperation().equals(OperationType.LOGARITHM)) view.getTermOperatioinComponent().setLocation(x0+view.getX(), y0+view.getSecondTermView().getY()); else view.getTermOperatioinComponent().setLocation(x0+view.getX()+view.getFirtTermView().getWidth(), y0+view.getFirtTermView().getY()); } if (view.getTerm().getOperation()==OperationType.DIVISION) drawDivider(view,x0+view.getX(), y0+view.getY()+view.getFirtTermView().getHeight(), g); else if (view.getTerm().getOperation()==OperationType.SQUAREROOT) drawSquareRoot(view, x0, y0, g); int x2=x0; int y2=y0; if (view.getTerm()!=null&&view.getTerm().getOperation()!=null&&view.getTerm().getOperation().equals(OperationType.DIVISION)) { x2=x0+Math.max(view.getFirtTermView().getWidth(),view.getSecondTermView().getWidth())/2 -view.getSecondTermView().getWidth()/2; y2=y0+TermView.VIEW_COMPONENT_HEIGHT/2; } positionTermUiComponent(view.getSecondTermView(), x2, y2, g); } /** * use the the mouse listener instance for all TermView UI components * @param view * @param listener */ private void processViewComponents(TermView view, ViewMouseAdapter listener) { if (view==null) return; if (view.getTermUiComponent()!=null) { add(view.getTermUiComponent()); view.getTermUiComponent().addMouseListener(listener); return; } processViewComponents(view.getFirtTermView(), listener); if (view.getTermOperatioinComponent()!=null) { add(view.getTermOperatioinComponent()); view.getTermOperatioinComponent().addMouseListener(listener); } processViewComponents(view.getSecondTermView(), listener); } }
set divisor and dividend at the same middle horizontal position SVN-Revision: 3057
software/cdms/src/gov/nih/nci/cbiit/cdms/formula/gui/view/FormulaPanel.java
set divisor and dividend at the same middle horizontal position
<ide><path>oftware/cdms/src/gov/nih/nci/cbiit/cdms/formula/gui/view/FormulaPanel.java <ide> if (view.getTerm().getOperation()==OperationType.DIVISION) <ide> drawDivider(view,x0+view.getX(), y0+view.getY()+view.getFirtTermView().getHeight(), g); <ide> else if (view.getTerm().getOperation()==OperationType.SQUAREROOT) <del> drawSquareRoot(view, x0, y0, g); <add> drawSquareRoot(view, x0+view.getX(), y0+view.getY(), g); <ide> int x2=x0; <ide> int y2=y0; <ide> if (view.getTerm()!=null&&view.getTerm().getOperation()!=null&&view.getTerm().getOperation().equals(OperationType.DIVISION)) <ide> { <del> x2=x0+Math.max(view.getFirtTermView().getWidth(),view.getSecondTermView().getWidth())/2 <del> -view.getSecondTermView().getWidth()/2; <ide> y2=y0+TermView.VIEW_COMPONENT_HEIGHT/2; <ide> } <ide> positionTermUiComponent(view.getSecondTermView(), x2, y2, g);
JavaScript
mit
da71a85fa748ea0a1cd7aa8f6723bedadee8871c
0
xseano/xQube,xseano/xQube,xseano/xQube
var ip = "ws://127.0.0.1:8080"; var obj = this; const id = getRandomInt(1, 65355); var sceneObjId = id + "SceneObj"; const cameraHeight = 55; // Controls FOV on Cube in context of the plane const cameraAngle = 72; // Controls Angle at which camera points towards cube function SceneObj(id) { this.id = id; this.socket = new WebSocket(ip); this.scene = new THREE.Scene(); } obj[sceneObjId] = new SceneObj(id); var ws = obj[sceneObjId].socket; var sceneColor = new THREE.Color("rgb(174, 129, 255)"); function onLoad() { ws.binaryType = "arraybuffer"; ws.onopen = open; ws.onclose = close; ws.onerror = close; //ws.onmessage = message; window.bodyDiv = document.getElementById("bodyDiv"); bodyDiv.innerHTML = '<center><span class="textMsg"> ~ x³ ~ </span><br><br><br><span class="textMsg">xQube is Connecting...</span><br></center>'; if (ws.readyState == 1) { open(); } } function close() { bodyDiv.innerHTML = '<center><span class="textMsg"> ~ x³ ~ </span><br><br><br><span class="textMsg">xQube failed to connect...</span><br></center>'; } function createBuffer(size) { return new DataView(new ArrayBuffer(size)) } function sendBuffer(dataview) { ws.send(dataview.buffer) } function str2ab(str) { var buf = new ArrayBuffer(str.length*2); var bufView = new Uint16Array(buf); for (var i=0, strLen=str.length; i<strLen; i++) { bufView[i] = str.charCodeAt(i); } return buf; } function sendString(str) { var buffer = createBuffer(2); var offset = 0; buffer.setUint8(offset++, 1); buffer.setUint8(offset++, str.charCodeAt(0)); sendBuffer(buffer); } function open() { bodyDiv.innerHTML = ''; sendString('h'); var socketID = obj[sceneObjId].id; var camObjId = socketID + "CamObj"; var cubeObjId = socketID + "CubeObj"; obj[camObjId] = new THREE.PerspectiveCamera(105, window.innerWidth/window.innerHeight, 0.1, 1000); var renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); var scale = 2000; var sections = 200; var baseGrid = new THREE.GridHelper(scale, sections); obj[sceneObjId].scene.add(baseGrid); var cWidth = 5; var cHeight = 5; var cDepth = 5; var cColor = "rgb(174, 129, 255)"; var camZ = 4; var cubeColorRGB = new THREE.Color(cColor); var cubeGeom = new THREE.BoxGeometry(cWidth, cHeight, cDepth); var txtrLder = new THREE.TextureLoader(); var dice1 = txtrLder.load( './resources/images/DiceFace_1.png' ); var dice2 = txtrLder.load( './resources/images/DiceFace_2.png' ); var dice3 = txtrLder.load( './resources/images/DiceFace_3.png' ); var dice4 = txtrLder.load( './resources/images/DiceFace_4.png' ); var dice5 = txtrLder.load( './resources/images/DiceFace_5.png' ); var dice6 = txtrLder.load( './resources/images/DiceFace_6.png' ); var cubeMaterials = [ new THREE.MeshBasicMaterial( { map: dice1 } ), new THREE.MeshBasicMaterial( { map: dice2 } ), new THREE.MeshBasicMaterial( { map: dice3 } ), new THREE.MeshBasicMaterial( { map: dice4 } ), new THREE.MeshBasicMaterial( { map: dice5 } ), new THREE.MeshBasicMaterial( { map: dice6 } ) ]; var cubeFaces = new THREE.MeshFaceMaterial(cubeMaterials); //var cubeColor = new THREE.MeshBasicMaterial({ color: cubeColorRGB, opacity: 0.7, transparent: true }); var group = new THREE.Group(); obj[sceneObjId].scene.add(group); obj[cubeObjId] = new THREE.Mesh(cubeGeom, cubeFaces); obj[cubeObjId].name = socketID; group.add(obj[cubeObjId]); obj[sceneObjId].scene.add(obj[cubeObjId]); obj[cubeObjId].position.set(0, 10, camZ); obj[camObjId].position.y = cameraHeight; obj[camObjId].rotation.x = -(cameraAngle * Math.PI / 180); obj[camObjId].position.x = 0; obj[camObjId].position.z = camZ; var render = function () { requestAnimationFrame(render); renderer.render(obj[sceneObjId].scene, obj[camObjId]); //obj[sceneObjId].socket.emit('getUserList'); }; render(); } function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; }
html/resources/js/main.js
var ip = "ws://127.0.0.1:8080"; var obj = this; var id = getRandomInt(1, 65355); var sceneObjId = id + "SceneObj"; const cameraHeight = 55; // Controls FOV on Cube in context of the plane const cameraAngle = 72; // Controls Angle at which camera points towards cube function SceneObj() { this.socket = new WebSocket(ip); this.scene = new THREE.Scene(); } obj[sceneObjId] = new SceneObj(); var ws = obj[sceneObjId].socket; var sceneColor = new THREE.Color("rgb(174, 129, 255)"); function onLoad() { ws.binaryType = "arraybuffer"; ws.onopen = open; ws.onclose = close; ws.onerror = close; //ws.onmessage = message; window.bodyDiv = document.getElementById("bodyDiv"); bodyDiv.innerHTML = '<center><span class="textMsg"> ~ x³ ~ </span><br><br><br><span class="textMsg">xQube is Connecting...</span><br></center>'; if (ws.readyState == 1) { open(); } } function close() { bodyDiv.innerHTML = '<center><span class="textMsg"> ~ x³ ~ </span><br><br><br><span class="textMsg">xQube failed to connect...</span><br></center>'; } function createBuffer(size) { return new DataView(new ArrayBuffer(size)) } function sendBuffer(dataview) { ws.send(dataview.buffer) } function str2ab(str) { var buf = new ArrayBuffer(str.length*2); var bufView = new Uint16Array(buf); for (var i=0, strLen=str.length; i<strLen; i++) { bufView[i] = str.charCodeAt(i); } return buf; } function sendString(str) { var buffer = createBuffer(2); var offset = 0; buffer.setUint8(offset++, 1); buffer.setUint8(offset++, str.charCodeAt(0)); sendBuffer(buffer); } function open() { bodyDiv.innerHTML = ''; sendString('h'); } function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; }
Started loading scene
html/resources/js/main.js
Started loading scene
<ide><path>tml/resources/js/main.js <ide> var ip = "ws://127.0.0.1:8080"; <ide> <ide> var obj = this; <del>var id = getRandomInt(1, 65355); <add>const id = getRandomInt(1, 65355); <ide> var sceneObjId = id + "SceneObj"; <ide> const cameraHeight = 55; // Controls FOV on Cube in context of the plane <ide> const cameraAngle = 72; // Controls Angle at which camera points towards cube <ide> <del>function SceneObj() { <add>function SceneObj(id) { <add> this.id = id; <ide> this.socket = new WebSocket(ip); <ide> this.scene = new THREE.Scene(); <ide> } <ide> <del>obj[sceneObjId] = new SceneObj(); <add>obj[sceneObjId] = new SceneObj(id); <ide> var ws = obj[sceneObjId].socket; <ide> var sceneColor = new THREE.Color("rgb(174, 129, 255)"); <ide> <ide> function open() { <ide> bodyDiv.innerHTML = ''; <ide> sendString('h'); <add> <add> var socketID = obj[sceneObjId].id; <add> var camObjId = socketID + "CamObj"; <add> var cubeObjId = socketID + "CubeObj"; <add> <add> obj[camObjId] = new THREE.PerspectiveCamera(105, window.innerWidth/window.innerHeight, 0.1, 1000); <add> <add> var renderer = new THREE.WebGLRenderer(); <add> renderer.setSize(window.innerWidth, window.innerHeight); <add> document.body.appendChild(renderer.domElement); <add> <add> var scale = 2000; <add> var sections = 200; <add> var baseGrid = new THREE.GridHelper(scale, sections); <add> obj[sceneObjId].scene.add(baseGrid); <add> <add> var cWidth = 5; <add> var cHeight = 5; <add> var cDepth = 5; <add> var cColor = "rgb(174, 129, 255)"; <add> var camZ = 4; <add> <add> var cubeColorRGB = new THREE.Color(cColor); <add> var cubeGeom = new THREE.BoxGeometry(cWidth, cHeight, cDepth); <add> var txtrLder = new THREE.TextureLoader(); <add> <add> var dice1 = txtrLder.load( './resources/images/DiceFace_1.png' ); <add> var dice2 = txtrLder.load( './resources/images/DiceFace_2.png' ); <add> var dice3 = txtrLder.load( './resources/images/DiceFace_3.png' ); <add> var dice4 = txtrLder.load( './resources/images/DiceFace_4.png' ); <add> var dice5 = txtrLder.load( './resources/images/DiceFace_5.png' ); <add> var dice6 = txtrLder.load( './resources/images/DiceFace_6.png' ); <add> <add> var cubeMaterials = [ <add> new THREE.MeshBasicMaterial( { map: dice1 } ), <add> new THREE.MeshBasicMaterial( { map: dice2 } ), <add> new THREE.MeshBasicMaterial( { map: dice3 } ), <add> new THREE.MeshBasicMaterial( { map: dice4 } ), <add> new THREE.MeshBasicMaterial( { map: dice5 } ), <add> new THREE.MeshBasicMaterial( { map: dice6 } ) <add> ]; <add> <add> var cubeFaces = new THREE.MeshFaceMaterial(cubeMaterials); <add> //var cubeColor = new THREE.MeshBasicMaterial({ color: cubeColorRGB, opacity: 0.7, transparent: true }); <add> var group = new THREE.Group(); <add> obj[sceneObjId].scene.add(group); <add> obj[cubeObjId] = new THREE.Mesh(cubeGeom, cubeFaces); <add> obj[cubeObjId].name = socketID; <add> group.add(obj[cubeObjId]); <add> obj[sceneObjId].scene.add(obj[cubeObjId]); <add> <add> obj[cubeObjId].position.set(0, 10, camZ); <add> obj[camObjId].position.y = cameraHeight; <add> obj[camObjId].rotation.x = -(cameraAngle * Math.PI / 180); <add> obj[camObjId].position.x = 0; <add> obj[camObjId].position.z = camZ; <add> <add> <add> var render = function () { <add> requestAnimationFrame(render); <add> renderer.render(obj[sceneObjId].scene, obj[camObjId]); <add> //obj[sceneObjId].socket.emit('getUserList'); <add> }; <add> <add> render(); <ide> } <ide> <ide> function getRandomInt(min, max) {
Java
apache-2.0
acb21089ea11ac13c522d7616eec3f9aa5bccc1a
0
googleapis/java-pubsub,googleapis/java-pubsub,googleapis/java-pubsub
/* * Copyright 2016 Google LLC * * 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.google.cloud.pubsub.v1; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import com.google.api.core.ApiFunction; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutureCallback; import com.google.api.core.ApiFutures; import com.google.api.core.BetaApi; import com.google.api.core.SettableApiFuture; import com.google.api.gax.batching.BatchingSettings; import com.google.api.gax.core.CredentialsProvider; import com.google.api.gax.core.ExecutorAsBackgroundResource; import com.google.api.gax.core.ExecutorProvider; import com.google.api.gax.core.FixedExecutorProvider; import com.google.api.gax.core.InstantiatingExecutorProvider; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.rpc.HeaderProvider; import com.google.api.gax.rpc.NoHeaderProvider; import com.google.api.gax.rpc.StatusCode; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.pubsub.v1.stub.GrpcPublisherStub; import com.google.cloud.pubsub.v1.stub.PublisherStub; import com.google.cloud.pubsub.v1.stub.PublisherStubSettings; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.pubsub.v1.PublishRequest; import com.google.pubsub.v1.PublishResponse; import com.google.pubsub.v1.PubsubMessage; import com.google.pubsub.v1.TopicName; import com.google.pubsub.v1.TopicNames; import java.io.IOException; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import org.threeten.bp.Duration; /** * A Cloud Pub/Sub <a href="https://cloud.google.com/pubsub/docs/publisher">publisher</a>, that is * associated with a specific topic at creation. * * <p>A {@link Publisher} provides built-in capabilities to automatically handle batching of * messages, controlling memory utilization, and retrying API calls on transient errors. * * <p>With customizable options that control: * * <ul> * <li>Message batching: such as number of messages or max batch byte size. * <li>Retries: such as the maximum duration of retries for a failing batch of messages. * </ul> * * <p>{@link Publisher} will use the credentials set on the channel, which uses application default * credentials through {@link GoogleCredentials#getApplicationDefault} by default. */ public class Publisher { private static final Logger logger = Logger.getLogger(Publisher.class.getName()); private final String topicName; private final BatchingSettings batchingSettings; private final Lock messagesBatchLock; private MessagesBatch messagesBatch; private final AtomicBoolean activeAlarm; private final PublisherStub publisherStub; private final ScheduledExecutorService executor; private final AtomicBoolean shutdown; private final List<AutoCloseable> closeables; private final MessageWaiter messagesWaiter; private ScheduledFuture<?> currentAlarmFuture; private final ApiFunction<PubsubMessage, PubsubMessage> messageTransform; /** The maximum number of messages in one request. Defined by the API. */ public static long getApiMaxRequestElementCount() { return 1000L; } /** The maximum size of one request. Defined by the API. */ public static long getApiMaxRequestBytes() { return 10L * 1000L * 1000L; // 10 megabytes (https://en.wikipedia.org/wiki/Megabyte) } private Publisher(Builder builder) throws IOException { topicName = builder.topicName; this.batchingSettings = builder.batchingSettings; this.messageTransform = builder.messageTransform; messagesBatch = new MessagesBatch(); messagesBatchLock = new ReentrantLock(); activeAlarm = new AtomicBoolean(false); executor = builder.executorProvider.getExecutor(); if (builder.executorProvider.shouldAutoClose()) { closeables = Collections.<AutoCloseable>singletonList(new ExecutorAsBackgroundResource(executor)); } else { closeables = Collections.emptyList(); } // Publisher used to take maxAttempt == 0 to mean infinity, but to GAX it means don't retry. // We post-process this here to keep backward-compatibility. RetrySettings retrySettings = builder.retrySettings; if (retrySettings.getMaxAttempts() == 0) { retrySettings = retrySettings.toBuilder().setMaxAttempts(Integer.MAX_VALUE).build(); } PublisherStubSettings.Builder stubSettings = PublisherStubSettings.newBuilder() .setCredentialsProvider(builder.credentialsProvider) .setExecutorProvider(FixedExecutorProvider.create(executor)) .setTransportChannelProvider(builder.channelProvider); stubSettings .publishSettings() .setRetryableCodes( StatusCode.Code.ABORTED, StatusCode.Code.CANCELLED, StatusCode.Code.DEADLINE_EXCEEDED, StatusCode.Code.INTERNAL, StatusCode.Code.RESOURCE_EXHAUSTED, StatusCode.Code.UNKNOWN, StatusCode.Code.UNAVAILABLE) .setRetrySettings(retrySettings) .setBatchingSettings(BatchingSettings.newBuilder().setIsEnabled(false).build()); this.publisherStub = GrpcPublisherStub.create(stubSettings.build()); shutdown = new AtomicBoolean(false); messagesWaiter = new MessageWaiter(); } /** Topic which the publisher publishes to. */ public TopicName getTopicName() { return TopicNames.parse(topicName); } /** Topic which the publisher publishes to. */ public String getTopicNameString() { return topicName; } /** * Schedules the publishing of a message. The publishing of the message may occur immediately or * be delayed based on the publisher batching options. * * <p>Example of publishing a message. * * <pre>{@code * String message = "my_message"; * ByteString data = ByteString.copyFromUtf8(message); * PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build(); * ApiFuture<String> messageIdFuture = publisher.publish(pubsubMessage); * ApiFutures.addCallback(messageIdFuture, new ApiFutureCallback<String>() { * public void onSuccess(String messageId) { * System.out.println("published with message id: " + messageId); * } * * public void onFailure(Throwable t) { * System.out.println("failed to publish: " + t); * } * }); * }</pre> * * @param message the message to publish. * @return the message ID wrapped in a future. */ public ApiFuture<String> publish(PubsubMessage message) { if (shutdown.get()) { throw new IllegalStateException("Cannot publish on a shut-down publisher."); } message = messageTransform.apply(message); final int messageSize = message.getSerializedSize(); OutstandingBatch batchToSend = null; SettableApiFuture<String> publishResult = SettableApiFuture.<String>create(); final OutstandingPublish outstandingPublish = new OutstandingPublish(publishResult, message); messagesBatchLock.lock(); try { // Check if the next message makes the current batch exceed the max batch byte size. if (!messagesBatch.isEmpty() && hasBatchingBytes() && messagesBatch.getBatchedBytes() + messageSize >= getMaxBatchBytes()) { batchToSend = messagesBatch.popOutstandingBatch(); } // Border case if the message to send is greater or equals to the max batch size then can't // be included in the current batch and instead sent immediately. if (!hasBatchingBytes() || messageSize < getMaxBatchBytes()) { messagesBatch.addMessage(outstandingPublish, messageSize); // If after adding the message we have reached the batch max messages then we have a batch // to send. if (messagesBatch.getMessagesCount() == getBatchingSettings().getElementCountThreshold()) { batchToSend = messagesBatch.popOutstandingBatch(); } } // Setup the next duration based delivery alarm if there are messages batched. setupAlarm(); } finally { messagesBatchLock.unlock(); } messagesWaiter.incrementPendingMessages(1); if (batchToSend != null) { logger.log(Level.FINER, "Scheduling a batch for immediate sending."); final OutstandingBatch finalBatchToSend = batchToSend; executor.execute( new Runnable() { @Override public void run() { publishOutstandingBatch(finalBatchToSend); } }); } // If the message is over the size limit, it was not added to the pending messages and it will // be sent in its own batch immediately. if (hasBatchingBytes() && messageSize >= getMaxBatchBytes()) { logger.log( Level.FINER, "Message exceeds the max batch bytes, scheduling it for immediate send."); executor.execute( new Runnable() { @Override public void run() { publishOutstandingBatch( new OutstandingBatch(ImmutableList.of(outstandingPublish), messageSize)); } }); } return publishResult; } private void setupAlarm() { if (!messagesBatch.isEmpty()) { if (!activeAlarm.getAndSet(true)) { long delayThresholdMs = getBatchingSettings().getDelayThreshold().toMillis(); logger.log(Level.FINER, "Setting up alarm for the next {0} ms.", delayThresholdMs); currentAlarmFuture = executor.schedule( new Runnable() { @Override public void run() { logger.log(Level.FINER, "Sending messages based on schedule."); activeAlarm.getAndSet(false); publishAllOutstanding(); } }, delayThresholdMs, TimeUnit.MILLISECONDS); } } else if (currentAlarmFuture != null) { logger.log(Level.FINER, "Cancelling alarm, no more messages"); if (activeAlarm.getAndSet(false)) { currentAlarmFuture.cancel(false); } } } /** * Publish any outstanding batches if non-empty. This method sends buffered messages, but does not * wait for the send operations to complete. To wait for messages to send, call {@code get} on the * futures returned from {@code publish}. */ public void publishAllOutstanding() { messagesBatchLock.lock(); OutstandingBatch batchToSend; try { if (messagesBatch.isEmpty()) { return; } batchToSend = messagesBatch.popOutstandingBatch(); } finally { messagesBatchLock.unlock(); } publishOutstandingBatch(batchToSend); } private ApiFuture<PublishResponse> publishCall(OutstandingBatch outstandingBatch) { PublishRequest.Builder publishRequest = PublishRequest.newBuilder(); publishRequest.setTopic(topicName); for (OutstandingPublish outstandingPublish : outstandingBatch.outstandingPublishes) { publishRequest.addMessages(outstandingPublish.message); } return publisherStub.publishCallable().futureCall(publishRequest.build()); } private void publishOutstandingBatch(final OutstandingBatch outstandingBatch) { ApiFutureCallback<PublishResponse> futureCallback = new ApiFutureCallback<PublishResponse>() { @Override public void onSuccess(PublishResponse result) { try { if (result.getMessageIdsCount() != outstandingBatch.size()) { Throwable t = new IllegalStateException( String.format( "The publish result count %s does not match " + "the expected %s results. Please contact Cloud Pub/Sub support " + "if this frequently occurs", result.getMessageIdsCount(), outstandingBatch.size())); for (OutstandingPublish oustandingMessage : outstandingBatch.outstandingPublishes) { oustandingMessage.publishResult.setException(t); } return; } Iterator<OutstandingPublish> messagesResultsIt = outstandingBatch.outstandingPublishes.iterator(); for (String messageId : result.getMessageIdsList()) { messagesResultsIt.next().publishResult.set(messageId); } } finally { messagesWaiter.incrementPendingMessages(-outstandingBatch.size()); } } @Override public void onFailure(Throwable t) { try { for (OutstandingPublish outstandingPublish : outstandingBatch.outstandingPublishes) { outstandingPublish.publishResult.setException(t); } } finally { messagesWaiter.incrementPendingMessages(-outstandingBatch.size()); } } }; ApiFutures.addCallback(publishCall(outstandingBatch), futureCallback, directExecutor()); } private static final class OutstandingBatch { final List<OutstandingPublish> outstandingPublishes; final long creationTime; int attempt; int batchSizeBytes; OutstandingBatch(List<OutstandingPublish> outstandingPublishes, int batchSizeBytes) { this.outstandingPublishes = outstandingPublishes; attempt = 1; creationTime = System.currentTimeMillis(); this.batchSizeBytes = batchSizeBytes; } public int getAttempt() { return attempt; } public int size() { return outstandingPublishes.size(); } } private static final class OutstandingPublish { SettableApiFuture<String> publishResult; PubsubMessage message; OutstandingPublish(SettableApiFuture<String> publishResult, PubsubMessage message) { this.publishResult = publishResult; this.message = message; } } /** The batching settings configured on this {@code Publisher}. */ public BatchingSettings getBatchingSettings() { return batchingSettings; } private long getMaxBatchBytes() { return getBatchingSettings().getRequestByteThreshold(); } /** * Schedules immediate publishing of any outstanding messages and waits until all are processed. * * <p>Sends remaining outstanding messages and prevents future calls to publish. This method * should be invoked prior to deleting the {@link Publisher} object in order to ensure that no * pending messages are lost. */ public void shutdown() throws Exception { if (shutdown.getAndSet(true)) { throw new IllegalStateException("Cannot shut down a publisher already shut-down."); } if (currentAlarmFuture != null && activeAlarm.getAndSet(false)) { currentAlarmFuture.cancel(false); } publishAllOutstanding(); messagesWaiter.waitNoMessages(); for (AutoCloseable closeable : closeables) { closeable.close(); } publisherStub.shutdown(); } /** * Wait for all work has completed execution after a {@link #shutdown()} request, or the timeout * occurs, or the current thread is interrupted. * * <p>Call this method to make sure all resources are freed properly. */ public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return publisherStub.awaitTermination(duration, unit); } private boolean hasBatchingBytes() { return getMaxBatchBytes() > 0; } /** * Constructs a new {@link Builder} using the given topic. * * <p>Example of creating a {@code Publisher}. * * <pre>{@code * String projectName = "my_project"; * String topicName = "my_topic"; * ProjectTopicName topic = ProjectTopicName.create(projectName, topicName); * Publisher publisher = Publisher.newBuilder(topic).build(); * try { * // ... * } finally { * // When finished with the publisher, make sure to shutdown to free up resources. * publisher.shutdown(); * publisher.awaitTermination(1, TimeUnit.MINUTES); * } * }</pre> */ public static Builder newBuilder(TopicName topicName) { return newBuilder(topicName.toString()); } /** * Constructs a new {@link Builder} using the given topic. * * <p>Example of creating a {@code Publisher}. * * <pre>{@code * String topic = "projects/my_project/topics/my_topic"; * Publisher publisher = Publisher.newBuilder(topic).build(); * try { * // ... * } finally { * // When finished with the publisher, make sure to shutdown to free up resources. * publisher.shutdown(); * publisher.awaitTermination(1, TimeUnit.MINUTES); * } * }</pre> */ public static Builder newBuilder(String topicName) { return new Builder(topicName); } /** A builder of {@link Publisher}s. */ public static final class Builder { static final Duration MIN_TOTAL_TIMEOUT = Duration.ofSeconds(10); static final Duration MIN_RPC_TIMEOUT = Duration.ofMillis(10); // Meaningful defaults. static final long DEFAULT_ELEMENT_COUNT_THRESHOLD = 100L; static final long DEFAULT_REQUEST_BYTES_THRESHOLD = 1000L; // 1 kB static final Duration DEFAULT_DELAY_THRESHOLD = Duration.ofMillis(1); static final Duration DEFAULT_RPC_TIMEOUT = Duration.ofSeconds(10); static final Duration DEFAULT_TOTAL_TIMEOUT = MIN_TOTAL_TIMEOUT; static final BatchingSettings DEFAULT_BATCHING_SETTINGS = BatchingSettings.newBuilder() .setDelayThreshold(DEFAULT_DELAY_THRESHOLD) .setRequestByteThreshold(DEFAULT_REQUEST_BYTES_THRESHOLD) .setElementCountThreshold(DEFAULT_ELEMENT_COUNT_THRESHOLD) .build(); static final RetrySettings DEFAULT_RETRY_SETTINGS = RetrySettings.newBuilder() .setTotalTimeout(DEFAULT_TOTAL_TIMEOUT) .setInitialRetryDelay(Duration.ofMillis(5)) .setRetryDelayMultiplier(2) .setMaxRetryDelay(Duration.ofMillis(Long.MAX_VALUE)) .setInitialRpcTimeout(DEFAULT_RPC_TIMEOUT) .setRpcTimeoutMultiplier(2) .setMaxRpcTimeout(DEFAULT_RPC_TIMEOUT) .build(); private static final int THREADS_PER_CPU = 5; static final ExecutorProvider DEFAULT_EXECUTOR_PROVIDER = InstantiatingExecutorProvider.newBuilder() .setExecutorThreadCount(THREADS_PER_CPU * Runtime.getRuntime().availableProcessors()) .build(); String topicName; // Batching options BatchingSettings batchingSettings = DEFAULT_BATCHING_SETTINGS; RetrySettings retrySettings = DEFAULT_RETRY_SETTINGS; TransportChannelProvider channelProvider = TopicAdminSettings.defaultGrpcTransportProviderBuilder().setChannelsPerCpu(1).build(); HeaderProvider headerProvider = new NoHeaderProvider(); HeaderProvider internalHeaderProvider = TopicAdminSettings.defaultApiClientHeaderProviderBuilder().build(); ExecutorProvider executorProvider = DEFAULT_EXECUTOR_PROVIDER; CredentialsProvider credentialsProvider = TopicAdminSettings.defaultCredentialsProviderBuilder().build(); ApiFunction<PubsubMessage, PubsubMessage> messageTransform = new ApiFunction<PubsubMessage, PubsubMessage>() { @Override public PubsubMessage apply(PubsubMessage input) { return input; } }; private Builder(String topic) { this.topicName = Preconditions.checkNotNull(topic); } /** * {@code ChannelProvider} to use to create Channels, which must point at Cloud Pub/Sub * endpoint. * * <p>For performance, this client benefits from having multiple underlying connections. See * {@link com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder#setPoolSize(int)}. */ public Builder setChannelProvider(TransportChannelProvider channelProvider) { this.channelProvider = Preconditions.checkNotNull(channelProvider); return this; } /** * Sets the static header provider. The header provider will be called during client * construction only once. The headers returned by the provider will be cached and supplied as * is for each request issued by the constructed client. Some reserved headers can be overridden * (e.g. Content-Type) or merged with the default value (e.g. User-Agent) by the underlying * transport layer. * * @param headerProvider the header provider * @return the builder */ @BetaApi public Builder setHeaderProvider(HeaderProvider headerProvider) { this.headerProvider = Preconditions.checkNotNull(headerProvider); return this; } /** * Sets the static header provider for getting internal (library-defined) headers. The header * provider will be called during client construction only once. The headers returned by the * provider will be cached and supplied as is for each request issued by the constructed client. * Some reserved headers can be overridden (e.g. Content-Type) or merged with the default value * (e.g. User-Agent) by the underlying transport layer. * * @param internalHeaderProvider the internal header provider * @return the builder */ Builder setInternalHeaderProvider(HeaderProvider internalHeaderProvider) { this.internalHeaderProvider = Preconditions.checkNotNull(internalHeaderProvider); return this; } /** {@code CredentialsProvider} to use to create Credentials to authenticate calls. */ public Builder setCredentialsProvider(CredentialsProvider credentialsProvider) { this.credentialsProvider = Preconditions.checkNotNull(credentialsProvider); return this; } // Batching options public Builder setBatchingSettings(BatchingSettings batchingSettings) { Preconditions.checkNotNull(batchingSettings); Preconditions.checkNotNull(batchingSettings.getElementCountThreshold()); Preconditions.checkArgument(batchingSettings.getElementCountThreshold() > 0); Preconditions.checkNotNull(batchingSettings.getRequestByteThreshold()); Preconditions.checkArgument(batchingSettings.getRequestByteThreshold() > 0); Preconditions.checkNotNull(batchingSettings.getDelayThreshold()); Preconditions.checkArgument(batchingSettings.getDelayThreshold().toMillis() > 0); this.batchingSettings = batchingSettings; return this; } /** Configures the Publisher's retry parameters. */ public Builder setRetrySettings(RetrySettings retrySettings) { Preconditions.checkArgument( retrySettings.getTotalTimeout().compareTo(MIN_TOTAL_TIMEOUT) >= 0); Preconditions.checkArgument( retrySettings.getInitialRpcTimeout().compareTo(MIN_RPC_TIMEOUT) >= 0); this.retrySettings = retrySettings; return this; } /** Gives the ability to set a custom executor to be used by the library. */ public Builder setExecutorProvider(ExecutorProvider executorProvider) { this.executorProvider = Preconditions.checkNotNull(executorProvider); return this; } /** * Gives the ability to set an {@link ApiFunction} that will transform the {@link PubsubMessage} * before it is sent */ @BetaApi public Builder setTransform(ApiFunction<PubsubMessage, PubsubMessage> messageTransform) { this.messageTransform = Preconditions.checkNotNull(messageTransform, "The messageTransform cannnot be null."); return this; } public Publisher build() throws IOException { return new Publisher(this); } } private static class MessagesBatch { private List<OutstandingPublish> messages = new LinkedList<>(); private int batchedBytes; private OutstandingBatch popOutstandingBatch() { OutstandingBatch batch = new OutstandingBatch(messages, batchedBytes); reset(); return batch; } private void reset() { messages = new LinkedList<>(); batchedBytes = 0; } private boolean isEmpty() { return messages.isEmpty(); } private int getBatchedBytes() { return batchedBytes; } private void addMessage(OutstandingPublish message, int messageSize) { messages.add(message); batchedBytes += messageSize; } private int getMessagesCount() { return messages.size(); } } }
google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/v1/Publisher.java
/* * Copyright 2016 Google LLC * * 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.google.cloud.pubsub.v1; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import com.google.api.core.ApiFunction; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutureCallback; import com.google.api.core.ApiFutures; import com.google.api.core.BetaApi; import com.google.api.core.SettableApiFuture; import com.google.api.gax.batching.BatchingSettings; import com.google.api.gax.core.CredentialsProvider; import com.google.api.gax.core.ExecutorAsBackgroundResource; import com.google.api.gax.core.ExecutorProvider; import com.google.api.gax.core.FixedExecutorProvider; import com.google.api.gax.core.InstantiatingExecutorProvider; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.rpc.HeaderProvider; import com.google.api.gax.rpc.NoHeaderProvider; import com.google.api.gax.rpc.StatusCode; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.pubsub.v1.stub.GrpcPublisherStub; import com.google.cloud.pubsub.v1.stub.PublisherStub; import com.google.cloud.pubsub.v1.stub.PublisherStubSettings; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.pubsub.v1.PublishRequest; import com.google.pubsub.v1.PublishResponse; import com.google.pubsub.v1.PubsubMessage; import com.google.pubsub.v1.TopicName; import com.google.pubsub.v1.TopicNames; import java.io.IOException; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import org.threeten.bp.Duration; /** * A Cloud Pub/Sub <a href="https://cloud.google.com/pubsub/docs/publisher">publisher</a>, that is * associated with a specific topic at creation. * * <p>A {@link Publisher} provides built-in capabilities to automatically handle batching of * messages, controlling memory utilization, and retrying API calls on transient errors. * * <p>With customizable options that control: * * <ul> * <li>Message batching: such as number of messages or max batch byte size. * <li>Retries: such as the maximum duration of retries for a failing batch of messages. * </ul> * * <p>{@link Publisher} will use the credentials set on the channel, which uses application default * credentials through {@link GoogleCredentials#getApplicationDefault} by default. */ public class Publisher { private static final Logger logger = Logger.getLogger(Publisher.class.getName()); private final String topicName; private final BatchingSettings batchingSettings; private final Lock messagesBatchLock; private MessagesBatch messagesBatch; private final AtomicBoolean activeAlarm; private final PublisherStub publisherStub; private final ScheduledExecutorService executor; private final AtomicBoolean shutdown; private final List<AutoCloseable> closeables; private final MessageWaiter messagesWaiter; private ScheduledFuture<?> currentAlarmFuture; private final ApiFunction<PubsubMessage, PubsubMessage> messageTransform; /** The maximum number of messages in one request. Defined by the API. */ public static long getApiMaxRequestElementCount() { return 1000L; } /** The maximum size of one request. Defined by the API. */ public static long getApiMaxRequestBytes() { return 10L * 1000L * 1000L; // 10 megabytes (https://en.wikipedia.org/wiki/Megabyte) } private Publisher(Builder builder) throws IOException { topicName = builder.topicName; this.batchingSettings = builder.batchingSettings; this.messageTransform = builder.messageTransform; messagesBatch = new MessagesBatch(); messagesBatchLock = new ReentrantLock(); activeAlarm = new AtomicBoolean(false); executor = builder.executorProvider.getExecutor(); if (builder.executorProvider.shouldAutoClose()) { closeables = Collections.<AutoCloseable>singletonList(new ExecutorAsBackgroundResource(executor)); } else { closeables = Collections.emptyList(); } // Publisher used to take maxAttempt == 0 to mean infinity, but to GAX it means don't retry. // We post-process this here to keep backward-compatibility. RetrySettings retrySettings = builder.retrySettings; if (retrySettings.getMaxAttempts() == 0) { retrySettings = retrySettings.toBuilder().setMaxAttempts(Integer.MAX_VALUE).build(); } PublisherStubSettings.Builder stubSettings = PublisherStubSettings.newBuilder() .setCredentialsProvider(builder.credentialsProvider) .setExecutorProvider(FixedExecutorProvider.create(executor)) .setTransportChannelProvider(builder.channelProvider); stubSettings .publishSettings() .setRetryableCodes( StatusCode.Code.ABORTED, StatusCode.Code.CANCELLED, StatusCode.Code.DEADLINE_EXCEEDED, StatusCode.Code.INTERNAL, StatusCode.Code.RESOURCE_EXHAUSTED, StatusCode.Code.UNKNOWN, StatusCode.Code.UNAVAILABLE) .setRetrySettings(retrySettings) .setBatchingSettings(BatchingSettings.newBuilder().setIsEnabled(false).build()); this.publisherStub = GrpcPublisherStub.create(stubSettings.build()); shutdown = new AtomicBoolean(false); messagesWaiter = new MessageWaiter(); } /** Topic which the publisher publishes to. */ public TopicName getTopicName() { return TopicNames.parse(topicName); } /** Topic which the publisher publishes to. */ public String getTopicNameString() { return topicName; } /** * Schedules the publishing of a message. The publishing of the message may occur immediately or * be delayed based on the publisher batching options. * * <p>Example of publishing a message. * * <pre>{@code * String message = "my_message"; * ByteString data = ByteString.copyFromUtf8(message); * PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build(); * ApiFuture<String> messageIdFuture = publisher.publish(pubsubMessage); * ApiFutures.addCallback(messageIdFuture, new ApiFutureCallback<String>() { * public void onSuccess(String messageId) { * System.out.println("published with message id: " + messageId); * } * * public void onFailure(Throwable t) { * System.out.println("failed to publish: " + t); * } * }); * }</pre> * * @param message the message to publish. * @return the message ID wrapped in a future. */ public ApiFuture<String> publish(PubsubMessage message) { if (shutdown.get()) { throw new IllegalStateException("Cannot publish on a shut-down publisher."); } message = messageTransform.apply(message); final int messageSize = message.getSerializedSize(); OutstandingBatch batchToSend = null; SettableApiFuture<String> publishResult = SettableApiFuture.<String>create(); final OutstandingPublish outstandingPublish = new OutstandingPublish(publishResult, message); messagesBatchLock.lock(); try { // Check if the next message makes the current batch exceed the max batch byte size. if (!messagesBatch.isEmpty() && hasBatchingBytes() && messagesBatch.getBatchedBytes() + messageSize >= getMaxBatchBytes()) { batchToSend = messagesBatch.popOutstandingBatch(); } // Border case if the message to send is greater or equals to the max batch size then can't // be included in the current batch and instead sent immediately. if (!hasBatchingBytes() || messageSize < getMaxBatchBytes()) { messagesBatch.addMessage(outstandingPublish, messageSize); // If after adding the message we have reached the batch max messages then we have a batch // to send. if (messagesBatch.getMessagesCount() == getBatchingSettings().getElementCountThreshold()) { batchToSend = messagesBatch.popOutstandingBatch(); } } // Setup the next duration based delivery alarm if there are messages batched. if (!messagesBatch.isEmpty()) { setupDurationBasedPublishAlarm(); } else if (currentAlarmFuture != null) { logger.log(Level.FINER, "Cancelling alarm, no more messages"); if (activeAlarm.getAndSet(false)) { currentAlarmFuture.cancel(false); } } } finally { messagesBatchLock.unlock(); } messagesWaiter.incrementPendingMessages(1); if (batchToSend != null) { logger.log(Level.FINER, "Scheduling a batch for immediate sending."); final OutstandingBatch finalBatchToSend = batchToSend; executor.execute( new Runnable() { @Override public void run() { publishOutstandingBatch(finalBatchToSend); } }); } // If the message is over the size limit, it was not added to the pending messages and it will // be sent in its own batch immediately. if (hasBatchingBytes() && messageSize >= getMaxBatchBytes()) { logger.log( Level.FINER, "Message exceeds the max batch bytes, scheduling it for immediate send."); executor.execute( new Runnable() { @Override public void run() { publishOutstandingBatch( new OutstandingBatch(ImmutableList.of(outstandingPublish), messageSize)); } }); } return publishResult; } private void setupDurationBasedPublishAlarm() { if (!activeAlarm.getAndSet(true)) { long delayThresholdMs = getBatchingSettings().getDelayThreshold().toMillis(); logger.log(Level.FINER, "Setting up alarm for the next {0} ms.", delayThresholdMs); currentAlarmFuture = executor.schedule( new Runnable() { @Override public void run() { logger.log(Level.FINER, "Sending messages based on schedule."); activeAlarm.getAndSet(false); publishAllOutstanding(); } }, delayThresholdMs, TimeUnit.MILLISECONDS); } } /** * Publish any outstanding batches if non-empty. This method sends buffered messages, but does not * wait for the send operations to complete. To wait for messages to send, call {@code get} on the * futures returned from {@code publish}. */ public void publishAllOutstanding() { messagesBatchLock.lock(); OutstandingBatch batchToSend; try { if (messagesBatch.isEmpty()) { return; } batchToSend = messagesBatch.popOutstandingBatch(); } finally { messagesBatchLock.unlock(); } publishOutstandingBatch(batchToSend); } private ApiFuture<PublishResponse> publishCall(OutstandingBatch outstandingBatch) { PublishRequest.Builder publishRequest = PublishRequest.newBuilder(); publishRequest.setTopic(topicName); for (OutstandingPublish outstandingPublish : outstandingBatch.outstandingPublishes) { publishRequest.addMessages(outstandingPublish.message); } return publisherStub.publishCallable().futureCall(publishRequest.build()); } private void publishOutstandingBatch(final OutstandingBatch outstandingBatch) { ApiFutureCallback<PublishResponse> futureCallback = new ApiFutureCallback<PublishResponse>() { @Override public void onSuccess(PublishResponse result) { try { if (result.getMessageIdsCount() != outstandingBatch.size()) { Throwable t = new IllegalStateException( String.format( "The publish result count %s does not match " + "the expected %s results. Please contact Cloud Pub/Sub support " + "if this frequently occurs", result.getMessageIdsCount(), outstandingBatch.size())); for (OutstandingPublish oustandingMessage : outstandingBatch.outstandingPublishes) { oustandingMessage.publishResult.setException(t); } return; } Iterator<OutstandingPublish> messagesResultsIt = outstandingBatch.outstandingPublishes.iterator(); for (String messageId : result.getMessageIdsList()) { messagesResultsIt.next().publishResult.set(messageId); } } finally { messagesWaiter.incrementPendingMessages(-outstandingBatch.size()); } } @Override public void onFailure(Throwable t) { try { for (OutstandingPublish outstandingPublish : outstandingBatch.outstandingPublishes) { outstandingPublish.publishResult.setException(t); } } finally { messagesWaiter.incrementPendingMessages(-outstandingBatch.size()); } } }; ApiFutures.addCallback(publishCall(outstandingBatch), futureCallback, directExecutor()); } private static final class OutstandingBatch { final List<OutstandingPublish> outstandingPublishes; final long creationTime; int attempt; int batchSizeBytes; OutstandingBatch(List<OutstandingPublish> outstandingPublishes, int batchSizeBytes) { this.outstandingPublishes = outstandingPublishes; attempt = 1; creationTime = System.currentTimeMillis(); this.batchSizeBytes = batchSizeBytes; } public int getAttempt() { return attempt; } public int size() { return outstandingPublishes.size(); } } private static final class OutstandingPublish { SettableApiFuture<String> publishResult; PubsubMessage message; OutstandingPublish(SettableApiFuture<String> publishResult, PubsubMessage message) { this.publishResult = publishResult; this.message = message; } } /** The batching settings configured on this {@code Publisher}. */ public BatchingSettings getBatchingSettings() { return batchingSettings; } private long getMaxBatchBytes() { return getBatchingSettings().getRequestByteThreshold(); } /** * Schedules immediate publishing of any outstanding messages and waits until all are processed. * * <p>Sends remaining outstanding messages and prevents future calls to publish. This method * should be invoked prior to deleting the {@link Publisher} object in order to ensure that no * pending messages are lost. */ public void shutdown() throws Exception { if (shutdown.getAndSet(true)) { throw new IllegalStateException("Cannot shut down a publisher already shut-down."); } if (currentAlarmFuture != null && activeAlarm.getAndSet(false)) { currentAlarmFuture.cancel(false); } publishAllOutstanding(); messagesWaiter.waitNoMessages(); for (AutoCloseable closeable : closeables) { closeable.close(); } publisherStub.shutdown(); } /** * Wait for all work has completed execution after a {@link #shutdown()} request, or the timeout * occurs, or the current thread is interrupted. * * <p>Call this method to make sure all resources are freed properly. */ public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return publisherStub.awaitTermination(duration, unit); } private boolean hasBatchingBytes() { return getMaxBatchBytes() > 0; } /** * Constructs a new {@link Builder} using the given topic. * * <p>Example of creating a {@code Publisher}. * * <pre>{@code * String projectName = "my_project"; * String topicName = "my_topic"; * ProjectTopicName topic = ProjectTopicName.create(projectName, topicName); * Publisher publisher = Publisher.newBuilder(topic).build(); * try { * // ... * } finally { * // When finished with the publisher, make sure to shutdown to free up resources. * publisher.shutdown(); * publisher.awaitTermination(1, TimeUnit.MINUTES); * } * }</pre> */ public static Builder newBuilder(TopicName topicName) { return newBuilder(topicName.toString()); } /** * Constructs a new {@link Builder} using the given topic. * * <p>Example of creating a {@code Publisher}. * * <pre>{@code * String topic = "projects/my_project/topics/my_topic"; * Publisher publisher = Publisher.newBuilder(topic).build(); * try { * // ... * } finally { * // When finished with the publisher, make sure to shutdown to free up resources. * publisher.shutdown(); * publisher.awaitTermination(1, TimeUnit.MINUTES); * } * }</pre> */ public static Builder newBuilder(String topicName) { return new Builder(topicName); } /** A builder of {@link Publisher}s. */ public static final class Builder { static final Duration MIN_TOTAL_TIMEOUT = Duration.ofSeconds(10); static final Duration MIN_RPC_TIMEOUT = Duration.ofMillis(10); // Meaningful defaults. static final long DEFAULT_ELEMENT_COUNT_THRESHOLD = 100L; static final long DEFAULT_REQUEST_BYTES_THRESHOLD = 1000L; // 1 kB static final Duration DEFAULT_DELAY_THRESHOLD = Duration.ofMillis(1); static final Duration DEFAULT_RPC_TIMEOUT = Duration.ofSeconds(10); static final Duration DEFAULT_TOTAL_TIMEOUT = MIN_TOTAL_TIMEOUT; static final BatchingSettings DEFAULT_BATCHING_SETTINGS = BatchingSettings.newBuilder() .setDelayThreshold(DEFAULT_DELAY_THRESHOLD) .setRequestByteThreshold(DEFAULT_REQUEST_BYTES_THRESHOLD) .setElementCountThreshold(DEFAULT_ELEMENT_COUNT_THRESHOLD) .build(); static final RetrySettings DEFAULT_RETRY_SETTINGS = RetrySettings.newBuilder() .setTotalTimeout(DEFAULT_TOTAL_TIMEOUT) .setInitialRetryDelay(Duration.ofMillis(5)) .setRetryDelayMultiplier(2) .setMaxRetryDelay(Duration.ofMillis(Long.MAX_VALUE)) .setInitialRpcTimeout(DEFAULT_RPC_TIMEOUT) .setRpcTimeoutMultiplier(2) .setMaxRpcTimeout(DEFAULT_RPC_TIMEOUT) .build(); private static final int THREADS_PER_CPU = 5; static final ExecutorProvider DEFAULT_EXECUTOR_PROVIDER = InstantiatingExecutorProvider.newBuilder() .setExecutorThreadCount(THREADS_PER_CPU * Runtime.getRuntime().availableProcessors()) .build(); String topicName; // Batching options BatchingSettings batchingSettings = DEFAULT_BATCHING_SETTINGS; RetrySettings retrySettings = DEFAULT_RETRY_SETTINGS; TransportChannelProvider channelProvider = TopicAdminSettings.defaultGrpcTransportProviderBuilder().setChannelsPerCpu(1).build(); HeaderProvider headerProvider = new NoHeaderProvider(); HeaderProvider internalHeaderProvider = TopicAdminSettings.defaultApiClientHeaderProviderBuilder().build(); ExecutorProvider executorProvider = DEFAULT_EXECUTOR_PROVIDER; CredentialsProvider credentialsProvider = TopicAdminSettings.defaultCredentialsProviderBuilder().build(); ApiFunction<PubsubMessage, PubsubMessage> messageTransform = new ApiFunction<PubsubMessage, PubsubMessage>() { @Override public PubsubMessage apply(PubsubMessage input) { return input; } }; private Builder(String topic) { this.topicName = Preconditions.checkNotNull(topic); } /** * {@code ChannelProvider} to use to create Channels, which must point at Cloud Pub/Sub * endpoint. * * <p>For performance, this client benefits from having multiple underlying connections. See * {@link com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder#setPoolSize(int)}. */ public Builder setChannelProvider(TransportChannelProvider channelProvider) { this.channelProvider = Preconditions.checkNotNull(channelProvider); return this; } /** * Sets the static header provider. The header provider will be called during client * construction only once. The headers returned by the provider will be cached and supplied as * is for each request issued by the constructed client. Some reserved headers can be overridden * (e.g. Content-Type) or merged with the default value (e.g. User-Agent) by the underlying * transport layer. * * @param headerProvider the header provider * @return the builder */ @BetaApi public Builder setHeaderProvider(HeaderProvider headerProvider) { this.headerProvider = Preconditions.checkNotNull(headerProvider); return this; } /** * Sets the static header provider for getting internal (library-defined) headers. The header * provider will be called during client construction only once. The headers returned by the * provider will be cached and supplied as is for each request issued by the constructed client. * Some reserved headers can be overridden (e.g. Content-Type) or merged with the default value * (e.g. User-Agent) by the underlying transport layer. * * @param internalHeaderProvider the internal header provider * @return the builder */ Builder setInternalHeaderProvider(HeaderProvider internalHeaderProvider) { this.internalHeaderProvider = Preconditions.checkNotNull(internalHeaderProvider); return this; } /** {@code CredentialsProvider} to use to create Credentials to authenticate calls. */ public Builder setCredentialsProvider(CredentialsProvider credentialsProvider) { this.credentialsProvider = Preconditions.checkNotNull(credentialsProvider); return this; } // Batching options public Builder setBatchingSettings(BatchingSettings batchingSettings) { Preconditions.checkNotNull(batchingSettings); Preconditions.checkNotNull(batchingSettings.getElementCountThreshold()); Preconditions.checkArgument(batchingSettings.getElementCountThreshold() > 0); Preconditions.checkNotNull(batchingSettings.getRequestByteThreshold()); Preconditions.checkArgument(batchingSettings.getRequestByteThreshold() > 0); Preconditions.checkNotNull(batchingSettings.getDelayThreshold()); Preconditions.checkArgument(batchingSettings.getDelayThreshold().toMillis() > 0); this.batchingSettings = batchingSettings; return this; } /** Configures the Publisher's retry parameters. */ public Builder setRetrySettings(RetrySettings retrySettings) { Preconditions.checkArgument( retrySettings.getTotalTimeout().compareTo(MIN_TOTAL_TIMEOUT) >= 0); Preconditions.checkArgument( retrySettings.getInitialRpcTimeout().compareTo(MIN_RPC_TIMEOUT) >= 0); this.retrySettings = retrySettings; return this; } /** Gives the ability to set a custom executor to be used by the library. */ public Builder setExecutorProvider(ExecutorProvider executorProvider) { this.executorProvider = Preconditions.checkNotNull(executorProvider); return this; } /** * Gives the ability to set an {@link ApiFunction} that will transform the {@link PubsubMessage} * before it is sent */ @BetaApi public Builder setTransform(ApiFunction<PubsubMessage, PubsubMessage> messageTransform) { this.messageTransform = Preconditions.checkNotNull(messageTransform, "The messageTransform cannnot be null."); return this; } public Publisher build() throws IOException { return new Publisher(this); } } private static class MessagesBatch { private List<OutstandingPublish> messages = new LinkedList<>(); private int batchedBytes; private OutstandingBatch popOutstandingBatch() { OutstandingBatch batch = new OutstandingBatch(messages, batchedBytes); reset(); return batch; } private void reset() { messages = new LinkedList<>(); batchedBytes = 0; } private boolean isEmpty() { return messages.isEmpty(); } private int getBatchedBytes() { return batchedBytes; } private void addMessage(OutstandingPublish message, int messageSize) { messages.add(message); batchedBytes += messageSize; } private int getMessagesCount() { return messages.size(); } } }
PubSub: refactor alarm setup into a single method (#5008) Moving some alarm setup logic from `publish()` and some logic from `setupDurationBasedPublishAlarm` into a new method called `setupAlarm`
google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/v1/Publisher.java
PubSub: refactor alarm setup into a single method (#5008)
<ide><path>oogle-cloud-pubsub/src/main/java/com/google/cloud/pubsub/v1/Publisher.java <ide> } <ide> } <ide> // Setup the next duration based delivery alarm if there are messages batched. <del> if (!messagesBatch.isEmpty()) { <del> setupDurationBasedPublishAlarm(); <del> } else if (currentAlarmFuture != null) { <del> logger.log(Level.FINER, "Cancelling alarm, no more messages"); <del> if (activeAlarm.getAndSet(false)) { <del> currentAlarmFuture.cancel(false); <del> } <del> } <add> setupAlarm(); <ide> } finally { <ide> messagesBatchLock.unlock(); <ide> } <ide> return publishResult; <ide> } <ide> <del> private void setupDurationBasedPublishAlarm() { <del> if (!activeAlarm.getAndSet(true)) { <del> long delayThresholdMs = getBatchingSettings().getDelayThreshold().toMillis(); <del> logger.log(Level.FINER, "Setting up alarm for the next {0} ms.", delayThresholdMs); <del> currentAlarmFuture = <del> executor.schedule( <del> new Runnable() { <del> @Override <del> public void run() { <del> logger.log(Level.FINER, "Sending messages based on schedule."); <del> activeAlarm.getAndSet(false); <del> publishAllOutstanding(); <del> } <del> }, <del> delayThresholdMs, <del> TimeUnit.MILLISECONDS); <add> private void setupAlarm() { <add> if (!messagesBatch.isEmpty()) { <add> if (!activeAlarm.getAndSet(true)) { <add> long delayThresholdMs = getBatchingSettings().getDelayThreshold().toMillis(); <add> logger.log(Level.FINER, "Setting up alarm for the next {0} ms.", delayThresholdMs); <add> currentAlarmFuture = <add> executor.schedule( <add> new Runnable() { <add> @Override <add> public void run() { <add> logger.log(Level.FINER, "Sending messages based on schedule."); <add> activeAlarm.getAndSet(false); <add> publishAllOutstanding(); <add> } <add> }, <add> delayThresholdMs, <add> TimeUnit.MILLISECONDS); <add> } <add> } else if (currentAlarmFuture != null) { <add> logger.log(Level.FINER, "Cancelling alarm, no more messages"); <add> if (activeAlarm.getAndSet(false)) { <add> currentAlarmFuture.cancel(false); <add> } <ide> } <ide> } <ide>
Java
lgpl-2.1
e7c6c9a922068c0dc225555fb71bf5de52079883
0
justincc/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,kimrutherford/intermine,drhee/toxoMine,joshkh/intermine,joshkh/intermine,justincc/intermine,elsiklab/intermine,kimrutherford/intermine,zebrafishmine/intermine,justincc/intermine,kimrutherford/intermine,kimrutherford/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,JoeCarlson/intermine,elsiklab/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,drhee/toxoMine,joshkh/intermine,zebrafishmine/intermine,joshkh/intermine,justincc/intermine,tomck/intermine,zebrafishmine/intermine,tomck/intermine,drhee/toxoMine,tomck/intermine,justincc/intermine,drhee/toxoMine,elsiklab/intermine,justincc/intermine,kimrutherford/intermine,elsiklab/intermine,JoeCarlson/intermine,zebrafishmine/intermine,elsiklab/intermine,drhee/toxoMine,zebrafishmine/intermine,kimrutherford/intermine,tomck/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,kimrutherford/intermine,drhee/toxoMine,joshkh/intermine,zebrafishmine/intermine,kimrutherford/intermine,zebrafishmine/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,tomck/intermine,tomck/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,JoeCarlson/intermine,tomck/intermine,tomck/intermine,JoeCarlson/intermine,joshkh/intermine,kimrutherford/intermine,elsiklab/intermine,drhee/toxoMine,joshkh/intermine,tomck/intermine,drhee/toxoMine,joshkh/intermine
package org.intermine.api.query.codegen; /* * Copyright (C) 2002-2010 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.Collection; import java.util.Map.Entry; import org.intermine.api.template.TemplateQuery; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.pathquery.OrderElement; import org.intermine.pathquery.OuterJoinStatus; import org.intermine.pathquery.PathConstraint; import org.intermine.pathquery.PathConstraintAttribute; import org.intermine.pathquery.PathConstraintBag; import org.intermine.pathquery.PathConstraintIds; import org.intermine.pathquery.PathConstraintLookup; import org.intermine.pathquery.PathConstraintMultiValue; import org.intermine.pathquery.PathConstraintSubclass; import org.intermine.pathquery.PathQuery; import org.intermine.util.TypeUtil; /** * This Class generates source code of web service client for path query and template query * * @author Fengyuan Hu * */ public class WebserviceJavaCodeGenerator implements WebserviceCodeGenerator { protected static final String TEST_STRING = "This is a Java test string..."; protected static final String INVALID_QUERY = "Invalid query. No fields selected for output..."; protected static final String INDENT = " "; protected static final String SPACE = " "; protected static final String ENDL = System.getProperty("line.separator"); /** * This method will generate web service source code in Java from a path query. * * @param query a PathQuery * @return web service source code in a string */ public String generate(PathQuery query) { StringBuffer pac = new StringBuffer(); StringBuffer impJava = new StringBuffer(); StringBuffer impIM = new StringBuffer(); StringBuffer sb = new StringBuffer(); // Add package and import pac.append("package ") .append("your.foo.bar.package.name") .append(";" + ENDL + ENDL); impJava.append("import java.io.IOException;" + ENDL) .append("import java.util.List;" + ENDL); impIM.append("import org.intermine.metadata.Model;" + ENDL) .append("import org.intermine.webservice.client.core.ServiceFactory;" + ENDL) .append("import org.intermine.webservice.client.services.ModelService;" + ENDL) .append("import org.intermine.webservice.client.services.QueryService;" + ENDL) .append("import org.intermine.pathquery.PathQuery;" + ENDL); // Add class comments sb.append("/**" + ENDL) .append(SPACE + "*" + SPACE + "Add some description to the class..." + ENDL) .append(SPACE + "*" + ENDL) .append(SPACE + "*" + SPACE + "@auther auther name" + ENDL) .append(SPACE + "**/" + ENDL); // Add class code sb.append("public class PathQueryClient" + ENDL) .append("{" + ENDL + INDENT) .append("private static String serviceRootUrl " + "= \"http://<your webapp base url>/service\";" + ENDL + ENDL); // Add methods code // Add Main method sb.append(INDENT + "/**" + ENDL) .append(INDENT + SPACE + "*" + SPACE + "@param args command line arguments" + ENDL) .append(INDENT + SPACE + "*" + SPACE + "@throws IOException" + ENDL) .append(INDENT + SPACE + "*/" + ENDL); sb.append(INDENT + "public static void main(String[] args) {" + ENDL) .append(INDENT + INDENT + "QueryService service =" + ENDL) .append(INDENT + INDENT + INDENT + "new ServiceFactory(serviceRootUrl," + " \"QueryService\").getQueryService();" + ENDL) .append(INDENT + INDENT + "Model model = getModel();" + ENDL) .append(INDENT + INDENT + "PathQuery query = new PathQuery(model);" + ENDL + ENDL); // Add views if (query.getView() == null || query.getView().isEmpty()) { return INVALID_QUERY; } else { sb.append(INDENT + INDENT + "// Add views" + ENDL); for (String pathString : query.getView()) { sb.append(INDENT + INDENT + "query.addView(\"" + pathString + "\");" + ENDL); } } sb.append(ENDL); // Add orderby if (query.getOrderBy() != null && !query.getOrderBy().isEmpty()) { impIM.append("import org.intermine.pathquery.OrderDirection;" + ENDL); sb.append(INDENT + INDENT + "// Add orderby" + ENDL); for (OrderElement oe : query.getOrderBy()) { sb.append(INDENT + INDENT + "query.addOrderBy(\"" + oe.getOrderPath() + "\", OrderDirection." + oe.getDirection() + ");" + ENDL); } sb.append(ENDL); } // Add constraints if (query.getConstraints() != null && !query.getConstraints().isEmpty()) { impIM.append("import org.intermine.pathquery.Constraints;" + ENDL); sb.append(INDENT + INDENT + "// Add constraints" + ENDL); if (query.getConstraints().size() == 1) { PathConstraint pc = query.getConstraints().entrySet().iterator().next().getKey(); String className = TypeUtil.unqualifiedName(pc.getClass().toString()); if ("PathConstraintMultiValue".equals(className)) { impJava.append("import java.util.ArrayList;" + ENDL); sb.append(INDENT + INDENT + "List<String> values = new ArrayList<String>();" + ENDL); for (String value : ((PathConstraintMultiValue) pc).getValues()) { sb.append(INDENT + INDENT + "values.add(\"" + value + "\");" + ENDL); } } if ("PathConstraintIds".equals(className)) { impJava.append("import java.util.ArrayList;" + ENDL); sb.append(INDENT + INDENT + "List<String> values = new ArrayList<String>();" + ENDL); for (Integer id : ((PathConstraintIds) pc).getIds()) { sb.append(INDENT + INDENT + "ids.add(" + id + ");" + ENDL); } } if ("PathConstraintBag".equals(className)) { sb.append(INDENT + INDENT + "// Only public lists are supported" + ENDL); } sb.append(INDENT + INDENT + "query.addConstraint(" + pathContraintUtil(pc) + ");" + ENDL); } else { for (Entry<PathConstraint, String> entry : query.getConstraints().entrySet()) { PathConstraint pc = entry.getKey(); String className = TypeUtil.unqualifiedName(pc.getClass().toString()); if ("PathConstraintMultiValue".equals(className)) { impJava.append("import java.util.ArrayList;" + ENDL); sb.append(INDENT + INDENT + "List<String> values = new ArrayList<String>();" + ENDL); for (String value : ((PathConstraintMultiValue) pc).getValues()) { sb.append(INDENT + INDENT + "values.add(\"" + value + "\");" + ENDL); } } if ("PathConstraintIds".equals(className)) { impJava.append("import java.util.ArrayList;" + ENDL); sb.append(INDENT + INDENT + "List<String> values = new ArrayList<String>();" + ENDL); for (Integer id : ((PathConstraintIds) pc).getIds()) { sb.append(INDENT + INDENT + "ids.add(" + id + ");" + ENDL); } } sb.append(INDENT + INDENT + "query.addConstraint(" + pathContraintUtil(pc) + ", \"" + entry.getValue() + "\");" + ENDL); sb.append(ENDL); } // Add constraintLogic if (query.getConstraintLogic() != null && !"".equals(query.getConstraintLogic())) { sb.append(INDENT + INDENT + "// Add constraintLogic" + ENDL); sb.append(INDENT + INDENT + "query.setConstraintLogic(\"" + query.getConstraintLogic() + "\");" + ENDL); } } sb.append(ENDL); } // Add join status if (query.getOuterJoinStatus() != null && !query.getOuterJoinStatus().isEmpty()) { impIM.append("import org.intermine.pathquery.OuterJoinStatus;" + ENDL); sb.append(INDENT + INDENT + "// Add join status" + ENDL); for (Entry<String, OuterJoinStatus> entry : query.getOuterJoinStatus().entrySet()) { sb.append(INDENT + INDENT + "query.setOuterJoinStatus(\"" + entry.getKey() + "\", OuterJoinStatus." + entry.getValue() + ");" + ENDL); } sb.append(ENDL); } // Add description? // Add display results code sb.append(INDENT + INDENT + "// Number of results are fetched" + ENDL) .append(INDENT + INDENT + "int maxCount = 100;" + ENDL) .append(INDENT + INDENT + "List<List<String>> result = service.getResult(query, maxCount);" + ENDL) .append(INDENT + INDENT + "System.out.println(\"Results: \");" + ENDL) .append(INDENT + INDENT + "for (List<String> row : result) {" + ENDL) .append(INDENT + INDENT + INDENT + "for (String cell : row) {" + ENDL) .append(INDENT + INDENT + INDENT + INDENT + "System.out.print(cell + \" \");" + ENDL) .append(INDENT + INDENT + INDENT + "}" + ENDL) .append(INDENT + INDENT + INDENT + "System.out.println();" + ENDL) .append(INDENT + INDENT + "}" + ENDL) .append(INDENT + "}" + ENDL + ENDL); // Add getModel method sb.append(INDENT + "private static Model getModel() {" + ENDL) .append(INDENT + INDENT + "ModelService service = new ServiceFactory(serviceRootUrl," + " \"ModelService\").getModelService();" + ENDL) .append(INDENT + INDENT + "return service.getModel();" + ENDL) .append(INDENT + "}" + ENDL); sb.append("}" + ENDL); if (!"".equals(sb.toString())) { return pac.toString() + impJava.toString() + ENDL + impIM.toString() + ENDL + sb.toString(); } else { return TEST_STRING; } } /** * This method will generate web service source code in Java from a template query. * * @param query a TemplateQuery * @return web service source code in a string */ public String generate(TemplateQuery query) { StringBuffer pac = new StringBuffer(); StringBuffer impJava = new StringBuffer(); StringBuffer impIM = new StringBuffer(); StringBuffer sb = new StringBuffer(); // Add package and import pac.append("package ") .append("your.foo.bar.package.name") .append(";" + ENDL + ENDL); impJava.append("import java.util.ArrayList;" + ENDL) .append("import java.util.List;" + ENDL); impIM.append("import org.intermine.webservice.client.core.ServiceFactory;" + ENDL) .append("import org.intermine.webservice.client.services.TemplateService;" + ENDL) .append("import org.intermine.webservice.client.template.TemplateParameter;" + ENDL); // Add class comments sb.append("/**" + ENDL) .append(SPACE + "*" + SPACE + "Add some description to the class..." + ENDL) .append(SPACE + "*" + ENDL) .append(SPACE + "*" + SPACE + "@auther auther name" + ENDL) .append(SPACE + "**/" + ENDL); // Add class code sb.append("public class TemplateQueryClient" + ENDL) .append("{" + ENDL + INDENT) .append("private static String serviceRootUrl " + "= \"http://<your webapp base url>/service\";" + ENDL + ENDL); // Add methods code // Add Main method sb.append(INDENT + "/**" + ENDL) .append(INDENT + SPACE + "*" + SPACE + "@param args command line arguments" + ENDL) .append(INDENT + SPACE + "*/" + ENDL); sb.append(INDENT + "public static void main(String[] args) {" + ENDL + ENDL) .append(INDENT + INDENT + "TemplateService service =" + "new ServiceFactory(serviceRootUrl," + " \"TemplateService\").getTemplateService();" + ENDL + ENDL) .append(INDENT + INDENT + "List<TemplateParameter> parameters = new ArrayList<TemplateParameter>();" + ENDL + ENDL); for (PathConstraint pc : query.getConstraints().keySet()) { String className = TypeUtil.unqualifiedName(pc.getClass().toString()); if ("PathConstraintBag".equals(className)) { return "This template contains a list constraint, which is currently not supported." + " Remove the list constraint and try again..."; } else { sb.append(INDENT + INDENT + templateConstraintUtil(pc) + ENDL); } } sb.append(ENDL); String templateName = query.getName(); // Add display results code sb.append(INDENT + INDENT + "// Name of a public template, " + "private templates are not supported at the moment" + ENDL) .append(INDENT + INDENT + "String templateName = \"" + templateName + "\";" + ENDL) .append(ENDL + INDENT + INDENT + "// Number of results are fetched" + ENDL) .append(INDENT + INDENT + "int maxCount = 100;" + ENDL) .append(INDENT + INDENT + "List<List<String>> result = " + "service.getResult(templateName, parameters, maxCount);" + ENDL) .append(INDENT + INDENT + "System.out.println(\"Results: \");" + ENDL) .append(INDENT + INDENT + "for (List<String> row : result) {" + ENDL) .append(INDENT + INDENT + INDENT + "for (String cell : row) {" + ENDL) .append(INDENT + INDENT + INDENT + INDENT + "System.out.print(cell + \" \");" + ENDL) .append(INDENT + INDENT + INDENT + "}" + ENDL) .append(INDENT + INDENT + INDENT + "System.out.println();" + ENDL) .append(INDENT + INDENT + "}" + ENDL); sb.append(INDENT + "}" + ENDL) .append("}" + ENDL); if (!"".equals(sb.toString())) { return pac.toString() + impJava.toString() + ENDL + impIM.toString() + ENDL + sb.toString(); } else { return TEST_STRING; } } /** * This method helps to generate constraint source code for PathQuery * @param pc PathConstraint object * @return a string like "Constraints.lessThan(\"Gene.length\", \"1000\")" */ private String pathContraintUtil(PathConstraint pc) { // Generate a string like "Constraints.lessThan(\"Gene.length\", \"1000\")" // Ref to Constraints String className = TypeUtil.unqualifiedName(pc.getClass().toString()); String path = pc.getPath(); ConstraintOp op = pc.getOp(); if ("PathConstraintAttribute".equals(className)) { String value = ((PathConstraintAttribute) pc).getValue(); if (op.equals(ConstraintOp.EQUALS)) { return "Constraints.eq(\"" + path + "\", \"" + value + "\")"; } if (op.equals(ConstraintOp.NOT_EQUALS)) { return "Constraints.neq(\"" + path + "\", \"" + value + "\")"; } if (op.equals(ConstraintOp.MATCHES)) { return "Constraints.like(\"" + path + "\", \"" + value + "\")"; } if (op.equals(ConstraintOp.LESS_THAN)) { return "Constraints.lessThan(\"" + path + "\", \"" + value + "\")"; } if (op.equals(ConstraintOp.LESS_THAN_EQUALS)) { return "Constraints.lessThanEqualTo(\"" + path + "\", \"" + value + "\")"; } if (op.equals(ConstraintOp.GREATER_THAN)) { return "Constraints.greaterThan(\"" + path + "\", \"" + value + "\")"; } if (op.equals(ConstraintOp.GREATER_THAN_EQUALS)) { return "Constraints.greaterThanEqualTo(\"" + path + "\", \"" + value + "\")"; } } if ("PathConstraintLookup".equals(className)) { String value = ((PathConstraintLookup) pc).getValue(); String extraValue = ((PathConstraintLookup) pc).getExtraValue(); return "Constraints.lookup(\"" + path + "\", \"" + value + "\", \"" + extraValue + "\")"; } if ("PathConstraintBag".equals(className)) { String bag = ((PathConstraintBag) pc).getBag(); if (op.equals(ConstraintOp.IN)) { return "Constraints.in(\"" + path + "\", \"" + bag + "\")"; } if (op.equals(ConstraintOp.NOT_IN)) { return "Constraints.notIn(\"" + path + "\", \"" + bag + "\")"; } } if ("PathConstraintIds".equals(className)) { // can not test from webapp if (op.equals(ConstraintOp.IN)) { return "Constraints.inIds(\"" + path + "\", ids)"; } if (op.equals(ConstraintOp.NOT_IN)) { return "Constraints.notInIds(\"" + path + "\", ids)"; } } if ("PathConstraintMultiValue".equals(className)) { if (op.equals(ConstraintOp.ONE_OF)) { return "Constraints.oneOfValues(\"" + path + "\", values)"; } if (op.equals(ConstraintOp.NONE_OF)) { return "Constraints.noneOfValues(\"" + path + "\", values)"; } } if ("PathConstraintNull".equals(className)) { if (op.equals(ConstraintOp.IS_NULL)) { return "Constraints.isNull(\"" + path + "\")"; } if (op.equals(ConstraintOp.IS_NOT_NULL)) { return "Constraints.isNotNull(\"" + path + "\")"; } } if ("PathConstraintSubclass".equals(className)) { // can not test from webapp String type = ((PathConstraintSubclass) pc).getType(); return "Constraints.type(\"" + path + "\", \"" + type + "\")"; } return null; } /** * This method helps to generate Template Parameters (predefined constraints) source code for * TemplateQuery * @param pc PathConstraint object * @return a line of source code */ private String templateConstraintUtil(PathConstraint pc) { String className = TypeUtil.unqualifiedName(pc.getClass().toString()); String path = pc.getPath(); String op = pc.getOp().toString(); if ("PathConstraintAttribute".equals(className)) { String value = ((PathConstraintAttribute) pc).getValue(); if ("=".equals(op)) { op = "eq"; } if ("!=".equals(op)) { op = "ne"; } if ("<".equals(op)) { op = "lt"; } if ("<=".equals(op)) { op = "le"; } if (">".equals(op)) { op = "gt"; } if (">=".equals(op)) { op = "ge"; } return "parameters.add(new TemplateParameter(\"" + path + "\", \"" + op + "\", \"" + value + "\"));"; } if ("PathConstraintLookup".equals(className)) { String value = ((PathConstraintLookup) pc).getValue(); String extraValue = ((PathConstraintLookup) pc).getExtraValue(); return "parameters.add(new TemplateParameter(\"" + path + "\", \"" + op + "\", \"" + value + "\", \"" + extraValue + "\"));"; } if ("PathConstraintBag".equals(className)) { // not supported } if ("PathConstraintIds".equals(className)) { // can not test from webapp Collection<Integer> ids = ((PathConstraintIds) pc).getIds(); StringBuilder idSB = new StringBuilder(); for (Integer id : ids) { idSB.append(id); idSB.append(","); } idSB.deleteCharAt(idSB.lastIndexOf(",")); return "parameters.add(new TemplateParameter(\"" + path + "\", \"" + op + "\", \"" + idSB.toString() + "\"));"; } if ("PathConstraintMultiValue".equals(className)) { Collection<String> values = ((PathConstraintMultiValue) pc).getValues(); StringBuilder multiSB = new StringBuilder(); for (String value : values) { multiSB.append(value); multiSB.append(","); } multiSB.deleteCharAt(multiSB.lastIndexOf(",")); return "parameters.add(new TemplateParameter(\"" + path + "\", \"" + op + "\", \"" + multiSB.toString() + "\"));"; } if ("PathConstraintNull".equals(className)) { return "parameters.add(new TemplateParameter(\"" + path + "\", \"" + op + "\", \"" + op + "\"));"; } if ("PathConstraintSubclass".equals(className)) { // not handled } return null; } }
intermine/api/main/src/org/intermine/api/query/codegen/WebserviceJavaCodeGenerator.java
package org.intermine.api.query.codegen; /* * Copyright (C) 2002-2010 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.Collection; import java.util.Map.Entry; import org.intermine.api.template.TemplateQuery; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.pathquery.OrderElement; import org.intermine.pathquery.OuterJoinStatus; import org.intermine.pathquery.PathConstraint; import org.intermine.pathquery.PathConstraintAttribute; import org.intermine.pathquery.PathConstraintBag; import org.intermine.pathquery.PathConstraintIds; import org.intermine.pathquery.PathConstraintLookup; import org.intermine.pathquery.PathConstraintMultiValue; import org.intermine.pathquery.PathConstraintSubclass; import org.intermine.pathquery.PathQuery; import org.intermine.util.TypeUtil; /** * * @author Fengyuan Hu * */ public class WebserviceJavaCodeGenerator implements WebserviceCodeGenerator { protected static final String TEST_STRING = "This is a Java test string..."; protected static final String INVALID_QUERY = "Invalid query. No fields selected for output..."; protected static final String INDENT = " "; protected static final String SPACE = " "; protected static final String ENDL = System.getProperty("line.separator"); /** * This method will generate web service source code in Java from a path query. * * @param query a PathQuery * @return web service source code in a string */ public String generate(PathQuery query) { StringBuffer pac = new StringBuffer(); StringBuffer impJava = new StringBuffer(); StringBuffer impIM = new StringBuffer(); StringBuffer sb = new StringBuffer(); // Add package and import pac.append("package ") .append("your.foo.bar.package.name") .append(";" + ENDL + ENDL); impJava.append("import java.io.IOException;" + ENDL) .append("import java.util.List;" + ENDL); impIM.append("import org.intermine.metadata.Model;" + ENDL) .append("import org.intermine.webservice.client.core.ServiceFactory;" + ENDL) .append("import org.intermine.webservice.client.services.ModelService;" + ENDL) .append("import org.intermine.webservice.client.services.QueryService;" + ENDL) .append("import org.intermine.pathquery.PathQuery;" + ENDL); // Add class comments sb.append("/**" + ENDL) .append(SPACE + "*" + SPACE + "Add some description to the class..." + ENDL) .append(SPACE + "*" + ENDL) .append(SPACE + "*" + SPACE + "@auther auther name" + ENDL) .append(SPACE + "**/" + ENDL); // Add class code sb.append("public class PathQueryClient" + ENDL) .append("{" + ENDL + INDENT) .append("private static String serviceRootUrl " + "= \"http://<your webapp base url>/service\";" + ENDL + ENDL); // Add methods code // Add Main method sb.append(INDENT + "/**" + ENDL) .append(INDENT + SPACE + "*" + SPACE + "@param args command line arguments" + ENDL) .append(INDENT + SPACE + "*" + SPACE + "@throws IOException" + ENDL) .append(INDENT + SPACE + "*/" + ENDL); sb.append(INDENT + "public static void main(String[] args) {" + ENDL) .append(INDENT + INDENT + "QueryService service =" + ENDL) .append(INDENT + INDENT + INDENT + "new ServiceFactory(serviceRootUrl," + " \"QueryService\").getQueryService();" + ENDL) .append(INDENT + INDENT + "Model model = getModel();" + ENDL) .append(INDENT + INDENT + "PathQuery query = new PathQuery(model);" + ENDL + ENDL); // Add views if (query.getView() == null || query.getView().isEmpty()) { return INVALID_QUERY; } else { sb.append(INDENT + INDENT + "// Add views" + ENDL); for (String pathString : query.getView()) { sb.append(INDENT + INDENT + "query.addView(\"" + pathString + "\");" + ENDL); } } sb.append(ENDL); // Add orderby if (query.getOrderBy() != null && !query.getOrderBy().isEmpty()) { impIM.append("import org.intermine.pathquery.OrderDirection;" + ENDL); sb.append(INDENT + INDENT + "// Add orderby" + ENDL); for (OrderElement oe : query.getOrderBy()) { sb.append(INDENT + INDENT + "query.addOrderBy(\"" + oe.getOrderPath() + "\", OrderDirection." + oe.getDirection() + ");" + ENDL); } sb.append(ENDL); } // Add constraints if (query.getConstraints() != null && !query.getConstraints().isEmpty()) { impIM.append("import org.intermine.pathquery.Constraints;" + ENDL); sb.append(INDENT + INDENT + "// Add constraints" + ENDL); if (query.getConstraints().size() == 1) { PathConstraint pc = query.getConstraints().entrySet().iterator().next().getKey(); String className = TypeUtil.unqualifiedName(pc.getClass().toString()); if ("PathConstraintMultiValue".equals(className)) { impJava.append("import java.util.ArrayList;" + ENDL); sb.append(INDENT + INDENT + "List<String> values = new ArrayList<String>();" + ENDL); for (String value : ((PathConstraintMultiValue) pc).getValues()) { sb.append(INDENT + INDENT + "values.add(\"" + value + "\");" + ENDL); } } if ("PathConstraintIds".equals(className)) { impJava.append("import java.util.ArrayList;" + ENDL); sb.append(INDENT + INDENT + "List<String> values = new ArrayList<String>();" + ENDL); for (Integer id : ((PathConstraintIds) pc).getIds()) { sb.append(INDENT + INDENT + "ids.add(" + id + ");" + ENDL); } } if ("PathConstraintBag".equals(className)) { sb.append(INDENT + INDENT + "// Only public lists are supported" + ENDL); } sb.append(INDENT + INDENT + "query.addConstraint(" + pathContraintUtil(pc) + ");" + ENDL); } else { for (Entry<PathConstraint, String> entry : query.getConstraints().entrySet()) { PathConstraint pc = entry.getKey(); String className = TypeUtil.unqualifiedName(pc.getClass().toString()); if ("PathConstraintMultiValue".equals(className)) { impJava.append("import java.util.ArrayList;" + ENDL); sb.append(INDENT + INDENT + "List<String> values = new ArrayList<String>();" + ENDL); for (String value : ((PathConstraintMultiValue) pc).getValues()) { sb.append(INDENT + INDENT + "values.add(\"" + value + "\");" + ENDL); } } if ("PathConstraintIds".equals(className)) { impJava.append("import java.util.ArrayList;" + ENDL); sb.append(INDENT + INDENT + "List<String> values = new ArrayList<String>();" + ENDL); for (Integer id : ((PathConstraintIds) pc).getIds()) { sb.append(INDENT + INDENT + "ids.add(" + id + ");" + ENDL); } } sb.append(INDENT + INDENT + "query.addConstraint(" + pathContraintUtil(pc) + ", \"" + entry.getValue() + "\");" + ENDL); sb.append(ENDL); } // Add constraintLogic if (query.getConstraintLogic() != null && !query.getConstraintLogic().isEmpty()) { sb.append(INDENT + INDENT + "// Add constraintLogic" + ENDL); sb.append(INDENT + INDENT + "query.setConstraintLogic(\"" + query.getConstraintLogic() + "\");" + ENDL); } } sb.append(ENDL); } // Add join status if (query.getOuterJoinStatus() != null && !query.getOuterJoinStatus().isEmpty()) { impIM.append("import org.intermine.pathquery.OuterJoinStatus;" + ENDL); sb.append(INDENT + INDENT + "// Add join status" + ENDL); for (Entry<String, OuterJoinStatus> entry : query.getOuterJoinStatus().entrySet()) { sb.append(INDENT + INDENT + "query.setOuterJoinStatus(\"" + entry.getKey() + "\", OuterJoinStatus." + entry.getValue() + ");" + ENDL); } sb.append(ENDL); } // Add description? // Add display results code sb.append(INDENT + INDENT + "// Number of results are fetched" + ENDL) .append(INDENT + INDENT + "int maxCount = 100;" + ENDL) .append(INDENT + INDENT + "List<List<String>> result = service.getResult(query, maxCount);" + ENDL) .append(INDENT + INDENT + "System.out.println(\"Results: \");" + ENDL) .append(INDENT + INDENT + "for (List<String> row : result) {" + ENDL) .append(INDENT + INDENT + INDENT + "for (String cell : row) {" + ENDL) .append(INDENT + INDENT + INDENT + INDENT + "System.out.print(cell + \" \");" + ENDL) .append(INDENT + INDENT + INDENT + "}" + ENDL) .append(INDENT + INDENT + INDENT + "System.out.println();" + ENDL) .append(INDENT + INDENT + "}" + ENDL) .append(INDENT + "}" + ENDL + ENDL); // Add getModel method sb.append(INDENT + "private static Model getModel() {" + ENDL) .append(INDENT + INDENT + "ModelService service = new ServiceFactory(serviceRootUrl," + " \"ModelService\").getModelService();" + ENDL) .append(INDENT + INDENT + "return service.getModel();" + ENDL) .append(INDENT + "}" + ENDL); sb.append("}" + ENDL); if (!sb.toString().isEmpty()) { return pac.toString() + impJava.toString() + ENDL + impIM.toString() + ENDL + sb.toString(); } else { return TEST_STRING; } } /** * This method will generate web service source code in Java from a template query. * * @param query a TemplateQuery * @return web service source code in a string */ public String generate(TemplateQuery query) { StringBuffer pac = new StringBuffer(); StringBuffer impJava = new StringBuffer(); StringBuffer impIM = new StringBuffer(); StringBuffer sb = new StringBuffer(); // Add package and import pac.append("package ") .append("your.foo.bar.package.name") .append(";" + ENDL + ENDL); impJava.append("import java.util.ArrayList;" + ENDL) .append("import java.util.List;" + ENDL); impIM.append("import org.intermine.webservice.client.core.ServiceFactory;" + ENDL) .append("import org.intermine.webservice.client.services.TemplateService;" + ENDL) .append("import org.intermine.webservice.client.template.TemplateParameter;" + ENDL); // Add class comments sb.append("/**" + ENDL) .append(SPACE + "*" + SPACE + "Add some description to the class..." + ENDL) .append(SPACE + "*" + ENDL) .append(SPACE + "*" + SPACE + "@auther auther name" + ENDL) .append(SPACE + "**/" + ENDL); // Add class code sb.append("public class TemplateQueryClient" + ENDL) .append("{" + ENDL + INDENT) .append("private static String serviceRootUrl " + "= \"http://<your webapp base url>/service\";" + ENDL + ENDL); // Add methods code // Add Main method sb.append(INDENT + "/**" + ENDL) .append(INDENT + SPACE + "*" + SPACE + "@param args command line arguments" + ENDL) .append(INDENT + SPACE + "*/" + ENDL); sb.append(INDENT + "public static void main(String[] args) {" + ENDL + ENDL) .append(INDENT + INDENT + "TemplateService service =" + "new ServiceFactory(serviceRootUrl," + " \"TemplateService\").getTemplateService();" + ENDL + ENDL) .append(INDENT + INDENT + "List<TemplateParameter> parameters = new ArrayList<TemplateParameter>();" + ENDL + ENDL); for (PathConstraint pc : query.getConstraints().keySet()) { String className = TypeUtil.unqualifiedName(pc.getClass().toString()); if ("PathConstraintBag".equals(className)) { return "This template contains a list constraint, which is currently not supported." + " Remove the list constraint and try again..."; } else { sb.append(INDENT + INDENT + templateConstraintUtil(pc) + ENDL); } } sb.append(ENDL); String templateName = query.getName(); // Add display results code sb.append(INDENT + INDENT + "// Name of a public template, " + "private templates are not supported at the moment" + ENDL) .append(INDENT + INDENT + "String templateName = \"" + templateName + "\";" + ENDL) .append(ENDL + INDENT + INDENT + "// Number of results are fetched" + ENDL) .append(INDENT + INDENT + "int maxCount = 100;" + ENDL) .append(INDENT + INDENT + "List<List<String>> result = " + "service.getResult(templateName, parameters, maxCount);" + ENDL) .append(INDENT + INDENT + "System.out.println(\"Results: \");" + ENDL) .append(INDENT + INDENT + "for (List<String> row : result) {" + ENDL) .append(INDENT + INDENT + INDENT + "for (String cell : row) {" + ENDL) .append(INDENT + INDENT + INDENT + INDENT + "System.out.print(cell + \" \");" + ENDL) .append(INDENT + INDENT + INDENT + "}" + ENDL) .append(INDENT + INDENT + INDENT + "System.out.println();" + ENDL) .append(INDENT + INDENT + "}" + ENDL); sb.append(INDENT + "}" + ENDL) .append("}" + ENDL); if (!sb.toString().isEmpty()) { return pac.toString() + impJava.toString() + ENDL + impIM.toString() + ENDL + sb.toString(); } else { return TEST_STRING; } } /** * Say something??? * @param pc PathConstraint object * @return a string like "Constraints.lessThan(\"Gene.length\", \"1000\")" */ private String pathContraintUtil(PathConstraint pc) { // Generate a string like "Constraints.lessThan(\"Gene.length\", \"1000\")" // Ref to Constraints String className = TypeUtil.unqualifiedName(pc.getClass().toString()); String path = pc.getPath(); ConstraintOp op = pc.getOp(); if ("PathConstraintAttribute".equals(className)) { String value = ((PathConstraintAttribute) pc).getValue(); if (op.equals(ConstraintOp.EQUALS)) { return "Constraints.eq(\"" + path + "\", \"" + value + "\")"; } if (op.equals(ConstraintOp.NOT_EQUALS)) { return "Constraints.neq(\"" + path + "\", \"" + value + "\")"; } if (op.equals(ConstraintOp.MATCHES)) { return "Constraints.like(\"" + path + "\", \"" + value + "\")"; } if (op.equals(ConstraintOp.LESS_THAN)) { return "Constraints.lessThan(\"" + path + "\", \"" + value + "\")"; } if (op.equals(ConstraintOp.LESS_THAN_EQUALS)) { return "Constraints.lessThanEqualTo(\"" + path + "\", \"" + value + "\")"; } if (op.equals(ConstraintOp.GREATER_THAN)) { return "Constraints.greaterThan(\"" + path + "\", \"" + value + "\")"; } if (op.equals(ConstraintOp.GREATER_THAN_EQUALS)) { return "Constraints.greaterThanEqualTo(\"" + path + "\", \"" + value + "\")"; } } if ("PathConstraintLookup".equals(className)) { String value = ((PathConstraintLookup) pc).getValue(); String extraValue = ((PathConstraintLookup) pc).getExtraValue(); return "Constraints.lookup(\"" + path + "\", \"" + value + "\", \"" + extraValue + "\")"; } if ("PathConstraintBag".equals(className)) { String bag = ((PathConstraintBag) pc).getBag(); if (op.equals(ConstraintOp.IN)) { return "Constraints.in(\"" + path + "\", \"" + bag + "\")"; } if (op.equals(ConstraintOp.NOT_IN)) { return "Constraints.notIn(\"" + path + "\", \"" + bag + "\")"; } } if ("PathConstraintIds".equals(className)) { // can not test from webapp if (op.equals(ConstraintOp.IN)) { return "Constraints.inIds(\"" + path + "\", ids)"; } if (op.equals(ConstraintOp.NOT_IN)) { return "Constraints.notInIds(\"" + path + "\", ids)"; } } if ("PathConstraintMultiValue".equals(className)) { if (op.equals(ConstraintOp.ONE_OF)) { return "Constraints.oneOfValues(\"" + path + "\", values)"; } if (op.equals(ConstraintOp.NONE_OF)) { return "Constraints.noneOfValues(\"" + path + "\", values)"; } } if ("PathConstraintNull".equals(className)) { if (op.equals(ConstraintOp.IS_NULL)) { return "Constraints.isNull(\"" + path + "\")"; } if (op.equals(ConstraintOp.IS_NOT_NULL)) { return "Constraints.isNotNull(\"" + path + "\")"; } } if ("PathConstraintSubclass".equals(className)) { // can not test from webapp String type = ((PathConstraintSubclass) pc).getType(); return "Constraints.type(\"" + path + "\", \"" + type + "\")"; } return null; } /** * * @param pc PathConstraint object * @return a line of source code */ private String templateConstraintUtil(PathConstraint pc) { String className = TypeUtil.unqualifiedName(pc.getClass().toString()); String path = pc.getPath(); String op = pc.getOp().toString(); if ("PathConstraintAttribute".equals(className)) { String value = ((PathConstraintAttribute) pc).getValue(); if ("=".equals(op)) { op = "eq"; } if ("!=".equals(op)) { op = "ne"; } if ("<".equals(op)) { op = "lt"; } if ("<=".equals(op)) { op = "le"; } if (">".equals(op)) { op = "gt"; } if (">=".equals(op)) { op = "ge"; } return "parameters.add(new TemplateParameter(\"" + path + "\", \"" + op + "\", \"" + value + "\"));"; } if ("PathConstraintLookup".equals(className)) { String value = ((PathConstraintLookup) pc).getValue(); String extraValue = ((PathConstraintLookup) pc).getExtraValue(); return "parameters.add(new TemplateParameter(\"" + path + "\", \"" + op + "\", \"" + value + "\", \"" + extraValue + "\"));"; } if ("PathConstraintBag".equals(className)) { // not supported } if ("PathConstraintIds".equals(className)) { // can not test from webapp Collection<Integer> ids = ((PathConstraintIds) pc).getIds(); StringBuilder idSB = new StringBuilder(); for (Integer id : ids) { idSB.append(id); idSB.append(","); } idSB.deleteCharAt(idSB.lastIndexOf(",")); return "parameters.add(new TemplateParameter(\"" + path + "\", \"" + op + "\", \"" + idSB.toString() + "\"));"; } if ("PathConstraintMultiValue".equals(className)) { Collection<String> values = ((PathConstraintMultiValue) pc).getValues(); StringBuilder multiSB = new StringBuilder(); for (String value : values) { multiSB.append(value); multiSB.append(","); } multiSB.deleteCharAt(multiSB.lastIndexOf(",")); return "parameters.add(new TemplateParameter(\"" + path + "\", \"" + op + "\", \"" + multiSB.toString() + "\"));"; } if ("PathConstraintNull".equals(className)) { return "parameters.add(new TemplateParameter(\"" + path + "\", \"" + op + "\", \"" + op + "\"));"; } if ("PathConstraintSubclass".equals(className)) { // not handled } return null; } }
Web service API - changed isEmpty() for string to a real empty string as Bruiser gave a error
intermine/api/main/src/org/intermine/api/query/codegen/WebserviceJavaCodeGenerator.java
Web service API - changed isEmpty() for string to a real empty string as Bruiser gave a error
<ide><path>ntermine/api/main/src/org/intermine/api/query/codegen/WebserviceJavaCodeGenerator.java <ide> import org.intermine.util.TypeUtil; <ide> <ide> /** <add> * This Class generates source code of web service client for path query and template query <ide> * <ide> * @author Fengyuan Hu <ide> * <ide> } <ide> <ide> // Add constraintLogic <del> if (query.getConstraintLogic() != null && !query.getConstraintLogic().isEmpty()) { <add> if (query.getConstraintLogic() != null && !"".equals(query.getConstraintLogic())) { <ide> sb.append(INDENT + INDENT + "// Add constraintLogic" + ENDL); <ide> sb.append(INDENT + INDENT + "query.setConstraintLogic(\"" <ide> + query.getConstraintLogic() + "\");" <ide> <ide> sb.append("}" + ENDL); <ide> <del> if (!sb.toString().isEmpty()) { <add> if (!"".equals(sb.toString())) { <ide> return pac.toString() + impJava.toString() + ENDL <ide> + impIM.toString() + ENDL + sb.toString(); <ide> } else { <ide> sb.append(INDENT + "}" + ENDL) <ide> .append("}" + ENDL); <ide> <del> if (!sb.toString().isEmpty()) { <add> if (!"".equals(sb.toString())) { <ide> return pac.toString() + impJava.toString() + ENDL <ide> + impIM.toString() + ENDL + sb.toString(); <ide> } else { <ide> } <ide> <ide> /** <del> * Say something??? <add> * This method helps to generate constraint source code for PathQuery <ide> * @param pc PathConstraint object <ide> * @return a string like "Constraints.lessThan(\"Gene.length\", \"1000\")" <ide> */ <ide> } <ide> <ide> /** <del> * <add> * This method helps to generate Template Parameters (predefined constraints) source code for <add> * TemplateQuery <ide> * @param pc PathConstraint object <ide> * @return a line of source code <ide> */
Java
apache-2.0
5953acc6a64ff7355b5cb830b9fc22f28364953f
0
dpocock/camel,CandleCandle/camel,johnpoth/camel,aaronwalker/camel,snadakuduru/camel,edigrid/camel,Thopap/camel,scranton/camel,salikjan/camel,davidkarlsen/camel,lowwool/camel,duro1/camel,ge0ffrey/camel,isururanawaka/camel,partis/camel,jkorab/camel,rmarting/camel,jlpedrosa/camel,tkopczynski/camel,noelo/camel,tdiesler/camel,woj-i/camel,neoramon/camel,oscerd/camel,rmarting/camel,borcsokj/camel,curso007/camel,aaronwalker/camel,dmvolod/camel,chirino/camel,snurmine/camel,oscerd/camel,dmvolod/camel,gilfernandes/camel,rparree/camel,drsquidop/camel,cunningt/camel,jollygeorge/camel,woj-i/camel,yogamaha/camel,yury-vashchyla/camel,haku/camel,nikvaessen/camel,gautric/camel,woj-i/camel,gilfernandes/camel,snurmine/camel,prashant2402/camel,stalet/camel,edigrid/camel,MrCoder/camel,josefkarasek/camel,yury-vashchyla/camel,ekprayas/camel,cunningt/camel,ssharma/camel,allancth/camel,JYBESSON/camel,brreitme/camel,anton-k11/camel,askannon/camel,dkhanolkar/camel,tkopczynski/camel,lburgazzoli/apache-camel,jonmcewen/camel,bfitzpat/camel,dkhanolkar/camel,Thopap/camel,pax95/camel,chanakaudaya/camel,jamesnetherton/camel,ullgren/camel,anton-k11/camel,scranton/camel,adessaigne/camel,acartapanis/camel,adessaigne/camel,jarst/camel,tkopczynski/camel,DariusX/camel,pmoerenhout/camel,punkhorn/camel-upstream,gilfernandes/camel,FingolfinTEK/camel,tadayosi/camel,trohovsky/camel,DariusX/camel,askannon/camel,bhaveshdt/camel,coderczp/camel,jmandawg/camel,davidwilliams1978/camel,anoordover/camel,NetNow/camel,sirlatrom/camel,pkletsko/camel,nboukhed/camel,gautric/camel,jkorab/camel,tkopczynski/camel,partis/camel,askannon/camel,logzio/camel,joakibj/camel,yogamaha/camel,gnodet/camel,stravag/camel,manuelh9r/camel,jarst/camel,CodeSmell/camel,Thopap/camel,FingolfinTEK/camel,yury-vashchyla/camel,mgyongyosi/camel,coderczp/camel,lburgazzoli/camel,pkletsko/camel,nicolaferraro/camel,gnodet/camel,alvinkwekel/camel,isavin/camel,tdiesler/camel,sverkera/camel,tdiesler/camel,anton-k11/camel,qst-jdc-labs/camel,christophd/camel,acartapanis/camel,ssharma/camel,haku/camel,driseley/camel,NickCis/camel,bgaudaen/camel,oscerd/camel,mcollovati/camel,brreitme/camel,bhaveshdt/camel,punkhorn/camel-upstream,isururanawaka/camel,gyc567/camel,cunningt/camel,borcsokj/camel,Thopap/camel,Fabryprog/camel,brreitme/camel,lburgazzoli/camel,akhettar/camel,sebi-hgdata/camel,pkletsko/camel,jollygeorge/camel,jollygeorge/camel,nikhilvibhav/camel,lowwool/camel,dmvolod/camel,hqstevenson/camel,dmvolod/camel,oscerd/camel,tdiesler/camel,akhettar/camel,lowwool/camel,bhaveshdt/camel,jkorab/camel,edigrid/camel,dmvolod/camel,woj-i/camel,stravag/camel,dsimansk/camel,zregvart/camel,royopa/camel,dsimansk/camel,neoramon/camel,w4tson/camel,davidkarlsen/camel,nboukhed/camel,FingolfinTEK/camel,gilfernandes/camel,pplatek/camel,CandleCandle/camel,eformat/camel,prashant2402/camel,ssharma/camel,mike-kukla/camel,ramonmaruko/camel,JYBESSON/camel,mike-kukla/camel,iweiss/camel,mohanaraosv/camel,stalet/camel,jlpedrosa/camel,isavin/camel,sirlatrom/camel,royopa/camel,edigrid/camel,CandleCandle/camel,drsquidop/camel,aaronwalker/camel,gyc567/camel,lowwool/camel,jonmcewen/camel,jonmcewen/camel,josefkarasek/camel,jpav/camel,bhaveshdt/camel,jameszkw/camel,RohanHart/camel,mnki/camel,pplatek/camel,stravag/camel,jarst/camel,gnodet/camel,oscerd/camel,joakibj/camel,joakibj/camel,bdecoste/camel,atoulme/camel,noelo/camel,igarashitm/camel,bfitzpat/camel,dsimansk/camel,ullgren/camel,ekprayas/camel,dvankleef/camel,oscerd/camel,ullgren/camel,pmoerenhout/camel,jonmcewen/camel,salikjan/camel,sverkera/camel,stalet/camel,oalles/camel,tarilabs/camel,arnaud-deprez/camel,satishgummadelli/camel,trohovsky/camel,bdecoste/camel,apache/camel,drsquidop/camel,apache/camel,manuelh9r/camel,pplatek/camel,christophd/camel,prashant2402/camel,ge0ffrey/camel,YoshikiHigo/camel,rparree/camel,royopa/camel,lasombra/camel,arnaud-deprez/camel,atoulme/camel,allancth/camel,sirlatrom/camel,sabre1041/camel,hqstevenson/camel,ullgren/camel,MrCoder/camel,dvankleef/camel,acartapanis/camel,onders86/camel,NickCis/camel,nicolaferraro/camel,ekprayas/camel,jonmcewen/camel,partis/camel,johnpoth/camel,brreitme/camel,tadayosi/camel,NetNow/camel,chanakaudaya/camel,dvankleef/camel,anoordover/camel,logzio/camel,noelo/camel,adessaigne/camel,iweiss/camel,yogamaha/camel,erwelch/camel,haku/camel,grange74/camel,mnki/camel,gyc567/camel,stravag/camel,mohanaraosv/camel,coderczp/camel,RohanHart/camel,YoshikiHigo/camel,eformat/camel,pplatek/camel,tlehoux/camel,cunningt/camel,maschmid/camel,jmandawg/camel,eformat/camel,nboukhed/camel,kevinearls/camel,sabre1041/camel,jpav/camel,curso007/camel,yuruki/camel,w4tson/camel,ramonmaruko/camel,sebi-hgdata/camel,yuruki/camel,dkhanolkar/camel,scranton/camel,christophd/camel,sebi-hgdata/camel,mohanaraosv/camel,pplatek/camel,w4tson/camel,rmarting/camel,hqstevenson/camel,rmarting/camel,jamesnetherton/camel,koscejev/camel,haku/camel,nikhilvibhav/camel,iweiss/camel,lburgazzoli/apache-camel,pmoerenhout/camel,isavin/camel,pax95/camel,yuruki/camel,skinzer/camel,iweiss/camel,nicolaferraro/camel,curso007/camel,mzapletal/camel,engagepoint/camel,sabre1041/camel,pkletsko/camel,maschmid/camel,prashant2402/camel,ssharma/camel,veithen/camel,duro1/camel,nikvaessen/camel,atoulme/camel,snadakuduru/camel,dvankleef/camel,maschmid/camel,driseley/camel,RohanHart/camel,anton-k11/camel,johnpoth/camel,chirino/camel,dmvolod/camel,anoordover/camel,anoordover/camel,jameszkw/camel,hqstevenson/camel,driseley/camel,dkhanolkar/camel,anoordover/camel,oalles/camel,YoshikiHigo/camel,partis/camel,YoshikiHigo/camel,kevinearls/camel,ramonmaruko/camel,satishgummadelli/camel,jlpedrosa/camel,satishgummadelli/camel,gnodet/camel,lburgazzoli/apache-camel,jollygeorge/camel,noelo/camel,mnki/camel,eformat/camel,jkorab/camel,mike-kukla/camel,nboukhed/camel,tkopczynski/camel,sverkera/camel,manuelh9r/camel,kevinearls/camel,ge0ffrey/camel,akhettar/camel,snurmine/camel,yogamaha/camel,koscejev/camel,maschmid/camel,mzapletal/camel,akhettar/camel,ekprayas/camel,borcsokj/camel,oalles/camel,YMartsynkevych/camel,tarilabs/camel,aaronwalker/camel,josefkarasek/camel,jonmcewen/camel,gautric/camel,chirino/camel,tadayosi/camel,mike-kukla/camel,igarashitm/camel,gilfernandes/camel,noelo/camel,adessaigne/camel,acartapanis/camel,curso007/camel,neoramon/camel,duro1/camel,mzapletal/camel,apache/camel,tkopczynski/camel,akhettar/camel,ramonmaruko/camel,lasombra/camel,sebi-hgdata/camel,w4tson/camel,joakibj/camel,engagepoint/camel,MrCoder/camel,allancth/camel,apache/camel,erwelch/camel,rparree/camel,objectiser/camel,grange74/camel,noelo/camel,dsimansk/camel,Thopap/camel,anton-k11/camel,sirlatrom/camel,erwelch/camel,YMartsynkevych/camel,driseley/camel,partis/camel,punkhorn/camel-upstream,veithen/camel,bgaudaen/camel,mzapletal/camel,duro1/camel,woj-i/camel,YoshikiHigo/camel,ssharma/camel,MohammedHammam/camel,Fabryprog/camel,dkhanolkar/camel,FingolfinTEK/camel,mcollovati/camel,driseley/camel,jpav/camel,lburgazzoli/camel,pax95/camel,snadakuduru/camel,apache/camel,grgrzybek/camel,chanakaudaya/camel,koscejev/camel,ssharma/camel,sverkera/camel,anoordover/camel,duro1/camel,jmandawg/camel,MrCoder/camel,sirlatrom/camel,pax95/camel,curso007/camel,NetNow/camel,aaronwalker/camel,lburgazzoli/apache-camel,isururanawaka/camel,w4tson/camel,mike-kukla/camel,grgrzybek/camel,nikvaessen/camel,askannon/camel,borcsokj/camel,MohammedHammam/camel,ramonmaruko/camel,lowwool/camel,tadayosi/camel,veithen/camel,jpav/camel,dvankleef/camel,bdecoste/camel,NetNow/camel,rparree/camel,davidwilliams1978/camel,trohovsky/camel,maschmid/camel,zregvart/camel,edigrid/camel,MohammedHammam/camel,coderczp/camel,jmandawg/camel,yuruki/camel,sabre1041/camel,askannon/camel,nicolaferraro/camel,mcollovati/camel,YoshikiHigo/camel,veithen/camel,lburgazzoli/apache-camel,pplatek/camel,acartapanis/camel,skinzer/camel,oalles/camel,CodeSmell/camel,MrCoder/camel,jameszkw/camel,JYBESSON/camel,grange74/camel,eformat/camel,alvinkwekel/camel,isururanawaka/camel,tarilabs/camel,aaronwalker/camel,YMartsynkevych/camel,oalles/camel,jarst/camel,yury-vashchyla/camel,erwelch/camel,davidwilliams1978/camel,jlpedrosa/camel,woj-i/camel,haku/camel,drsquidop/camel,qst-jdc-labs/camel,snadakuduru/camel,ge0ffrey/camel,lasombra/camel,davidkarlsen/camel,isavin/camel,askannon/camel,NickCis/camel,davidwilliams1978/camel,johnpoth/camel,JYBESSON/camel,jarst/camel,grange74/camel,gyc567/camel,arnaud-deprez/camel,gyc567/camel,erwelch/camel,partis/camel,NickCis/camel,jkorab/camel,christophd/camel,tlehoux/camel,nikvaessen/camel,edigrid/camel,grgrzybek/camel,chanakaudaya/camel,jlpedrosa/camel,sabre1041/camel,sebi-hgdata/camel,chirino/camel,dpocock/camel,nboukhed/camel,grange74/camel,tdiesler/camel,pmoerenhout/camel,chirino/camel,JYBESSON/camel,gilfernandes/camel,grgrzybek/camel,nikhilvibhav/camel,JYBESSON/camel,borcsokj/camel,veithen/camel,igarashitm/camel,dpocock/camel,FingolfinTEK/camel,zregvart/camel,jameszkw/camel,pmoerenhout/camel,NetNow/camel,onders86/camel,gautric/camel,isavin/camel,arnaud-deprez/camel,onders86/camel,coderczp/camel,pplatek/camel,atoulme/camel,jollygeorge/camel,cunningt/camel,atoulme/camel,objectiser/camel,jkorab/camel,apache/camel,Fabryprog/camel,ekprayas/camel,mgyongyosi/camel,onders86/camel,engagepoint/camel,lburgazzoli/camel,lburgazzoli/apache-camel,yogamaha/camel,lburgazzoli/camel,snurmine/camel,isavin/camel,drsquidop/camel,onders86/camel,brreitme/camel,snadakuduru/camel,hqstevenson/camel,acartapanis/camel,yuruki/camel,trohovsky/camel,CodeSmell/camel,gnodet/camel,brreitme/camel,satishgummadelli/camel,prashant2402/camel,neoramon/camel,satishgummadelli/camel,manuelh9r/camel,jpav/camel,stalet/camel,mgyongyosi/camel,mohanaraosv/camel,skinzer/camel,kevinearls/camel,ekprayas/camel,cunningt/camel,trohovsky/camel,mgyongyosi/camel,DariusX/camel,jpav/camel,drsquidop/camel,adessaigne/camel,MohammedHammam/camel,dvankleef/camel,Thopap/camel,YMartsynkevych/camel,CandleCandle/camel,iweiss/camel,RohanHart/camel,rmarting/camel,mnki/camel,neoramon/camel,coderczp/camel,mike-kukla/camel,tlehoux/camel,allancth/camel,pax95/camel,YMartsynkevych/camel,jameszkw/camel,bgaudaen/camel,qst-jdc-labs/camel,punkhorn/camel-upstream,christophd/camel,kevinearls/camel,bdecoste/camel,josefkarasek/camel,bdecoste/camel,chanakaudaya/camel,sabre1041/camel,isururanawaka/camel,mgyongyosi/camel,bfitzpat/camel,MohammedHammam/camel,manuelh9r/camel,jmandawg/camel,Fabryprog/camel,mgyongyosi/camel,bgaudaen/camel,stalet/camel,bhaveshdt/camel,jmandawg/camel,iweiss/camel,chirino/camel,tdiesler/camel,bgaudaen/camel,gautric/camel,jamesnetherton/camel,ge0ffrey/camel,pkletsko/camel,isururanawaka/camel,tadayosi/camel,yuruki/camel,joakibj/camel,erwelch/camel,lasombra/camel,ge0ffrey/camel,igarashitm/camel,jameszkw/camel,neoramon/camel,ramonmaruko/camel,logzio/camel,logzio/camel,stravag/camel,bfitzpat/camel,josefkarasek/camel,DariusX/camel,engagepoint/camel,dsimansk/camel,tadayosi/camel,jamesnetherton/camel,arnaud-deprez/camel,veithen/camel,oalles/camel,bdecoste/camel,tarilabs/camel,logzio/camel,stravag/camel,FingolfinTEK/camel,lasombra/camel,tarilabs/camel,bhaveshdt/camel,davidwilliams1978/camel,nikvaessen/camel,scranton/camel,hqstevenson/camel,sverkera/camel,haku/camel,dpocock/camel,logzio/camel,skinzer/camel,satishgummadelli/camel,davidkarlsen/camel,CandleCandle/camel,jamesnetherton/camel,scranton/camel,snadakuduru/camel,trohovsky/camel,MrCoder/camel,NetNow/camel,objectiser/camel,royopa/camel,rmarting/camel,sebi-hgdata/camel,atoulme/camel,duro1/camel,onders86/camel,dpocock/camel,dpocock/camel,mzapletal/camel,qst-jdc-labs/camel,alvinkwekel/camel,igarashitm/camel,grgrzybek/camel,jlpedrosa/camel,MohammedHammam/camel,allancth/camel,curso007/camel,pmoerenhout/camel,mnki/camel,borcsokj/camel,lasombra/camel,tlehoux/camel,CodeSmell/camel,lowwool/camel,driseley/camel,yogamaha/camel,mohanaraosv/camel,eformat/camel,NickCis/camel,RohanHart/camel,manuelh9r/camel,nboukhed/camel,bfitzpat/camel,lburgazzoli/camel,bgaudaen/camel,johnpoth/camel,bfitzpat/camel,anton-k11/camel,qst-jdc-labs/camel,engagepoint/camel,joakibj/camel,gyc567/camel,CandleCandle/camel,koscejev/camel,objectiser/camel,grgrzybek/camel,alvinkwekel/camel,davidwilliams1978/camel,prashant2402/camel,igarashitm/camel,mohanaraosv/camel,yury-vashchyla/camel,maschmid/camel,YMartsynkevych/camel,skinzer/camel,logzio/camel,snurmine/camel,dsimansk/camel,scranton/camel,koscejev/camel,josefkarasek/camel,rparree/camel,qst-jdc-labs/camel,kevinearls/camel,christophd/camel,allancth/camel,royopa/camel,w4tson/camel,rparree/camel,pax95/camel,pkletsko/camel,mcollovati/camel,johnpoth/camel,skinzer/camel,adessaigne/camel,grange74/camel,RohanHart/camel,tarilabs/camel,chanakaudaya/camel,jollygeorge/camel,stalet/camel,mzapletal/camel,zregvart/camel,sirlatrom/camel,jamesnetherton/camel,royopa/camel,jarst/camel,arnaud-deprez/camel,koscejev/camel,mnki/camel,nikhilvibhav/camel,sverkera/camel,snurmine/camel,nikvaessen/camel,yury-vashchyla/camel,NickCis/camel,gautric/camel,tlehoux/camel,akhettar/camel,dkhanolkar/camel,tlehoux/camel
/** * 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.camel.component.irc; import java.util.List; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Ignore; import org.junit.Test; /** * @version $Revision$ */ public class IrcRouteTest extends CamelTestSupport { protected MockEndpoint resultEndpoint; protected String body1 = "Message One"; protected String body2 = "Message Two"; private boolean sentMessages; @Ignore @Test public void testIrcMessages() throws Exception { resultEndpoint = (MockEndpoint) context.getEndpoint("mock:result"); resultEndpoint.expectedBodiesReceived(body1, body2); resultEndpoint.assertIsSatisfied(); List<Exchange> list = resultEndpoint.getReceivedExchanges(); for (Exchange exchange : list) { log.info("Received exchange: " + exchange + " headers: " + exchange.getIn().getHeaders()); } } protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() throws Exception { from(fromUri()). choice(). when(header(IrcConstants.IRC_MESSAGE_TYPE).isEqualTo("PRIVMSG")).to("mock:result"). when(header(IrcConstants.IRC_MESSAGE_TYPE).isEqualTo("JOIN")).to("seda:consumerJoined"); from("seda:consumerJoined").process(new Processor() { public void process(Exchange exchange) throws Exception { sendMessages(); } }); } }; } protected String sendUri() { return "irc://[email protected]:6667/#camel-test?nickname=camel-prd"; } protected String fromUri() { return "irc://[email protected]:6667/#camel-test?nickname=camel-con"; } /** * Lets send messages once the consumer has joined */ protected void sendMessages() { if (!sentMessages) { sentMessages = true; // now the consumer has joined, lets send some messages template.sendBody(sendUri(), body1); template.sendBody(sendUri(), body2); } } }
components/camel-irc/src/test/java/org/apache/camel/component/irc/IrcRouteTest.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.camel.component.irc; import java.util.List; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; /** * @version $Revision$ */ public class IrcRouteTest extends CamelTestSupport { protected MockEndpoint resultEndpoint; protected String body1 = "Message One"; protected String body2 = "Message Two"; private boolean sentMessages; @Test public void testIrcMessages() throws Exception { resultEndpoint = (MockEndpoint) context.getEndpoint("mock:result"); resultEndpoint.expectedBodiesReceived(body1, body2); resultEndpoint.assertIsSatisfied(); List<Exchange> list = resultEndpoint.getReceivedExchanges(); for (Exchange exchange : list) { log.info("Received exchange: " + exchange + " headers: " + exchange.getIn().getHeaders()); } } protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() throws Exception { from(fromUri()). choice(). when(header(IrcConstants.IRC_MESSAGE_TYPE).isEqualTo("PRIVMSG")).to("mock:result"). when(header(IrcConstants.IRC_MESSAGE_TYPE).isEqualTo("JOIN")).to("seda:consumerJoined"); from("seda:consumerJoined").process(new Processor() { public void process(Exchange exchange) throws Exception { sendMessages(); } }); } }; } protected String sendUri() { return "irc://[email protected]:6667/#camel-test?nickname=camel-prd"; } protected String fromUri() { return "irc://[email protected]:6667/#camel-test?nickname=camel-con"; } /** * Lets send messages once the consumer has joined */ protected void sendMessages() { if (!sentMessages) { sentMessages = true; // now the consumer has joined, lets send some messages template.sendBody(sendUri(), body1); template.sendBody(sendUri(), body2); } } }
Disabled test that requries online and manual testing. git-svn-id: 11f3c9e1d08a13a4be44fe98a6d63a9c00f6ab23@820901 13f79535-47bb-0310-9956-ffa450edef68
components/camel-irc/src/test/java/org/apache/camel/component/irc/IrcRouteTest.java
Disabled test that requries online and manual testing.
<ide><path>omponents/camel-irc/src/test/java/org/apache/camel/component/irc/IrcRouteTest.java <ide> import org.apache.camel.builder.RouteBuilder; <ide> import org.apache.camel.component.mock.MockEndpoint; <ide> import org.apache.camel.test.junit4.CamelTestSupport; <add>import org.junit.Ignore; <ide> import org.junit.Test; <ide> <ide> /** <ide> protected String body2 = "Message Two"; <ide> private boolean sentMessages; <ide> <add> @Ignore <ide> @Test <ide> public void testIrcMessages() throws Exception { <ide> resultEndpoint = (MockEndpoint) context.getEndpoint("mock:result");
Java
apache-2.0
23d80b3c71065571c5c6ca458626fd681326dc2c
0
chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq
/** * * Copyright 2005-2006 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.activemq.broker; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.activemq.ActiveMQConnectionMetaData; import org.apache.activemq.Service; import org.apache.activemq.advisory.AdvisoryBroker; import org.apache.activemq.broker.ft.MasterConnector; import org.apache.activemq.broker.jmx.BrokerView; import org.apache.activemq.broker.jmx.BrokerViewMBean; import org.apache.activemq.broker.jmx.ConnectorView; import org.apache.activemq.broker.jmx.ConnectorViewMBean; import org.apache.activemq.broker.jmx.FTConnectorView; import org.apache.activemq.broker.jmx.JmsConnectorView; import org.apache.activemq.broker.jmx.ManagedRegionBroker; import org.apache.activemq.broker.jmx.ManagementContext; import org.apache.activemq.broker.jmx.NetworkConnectorView; import org.apache.activemq.broker.jmx.NetworkConnectorViewMBean; import org.apache.activemq.broker.jmx.ProxyConnectorView; import org.apache.activemq.broker.region.RegionBroker; import org.apache.activemq.broker.region.policy.PolicyMap; import org.apache.activemq.command.BrokerId; import org.apache.activemq.memory.UsageManager; import org.apache.activemq.network.ConnectionFilter; import org.apache.activemq.network.DiscoveryNetworkConnector; import org.apache.activemq.network.NetworkConnector; import org.apache.activemq.network.jms.JmsConnector; import org.apache.activemq.proxy.ProxyConnector; import org.apache.activemq.security.MessageAuthorizationPolicy; import org.apache.activemq.store.DefaultPersistenceAdapterFactory; import org.apache.activemq.store.PersistenceAdapter; import org.apache.activemq.store.PersistenceAdapterFactory; import org.apache.activemq.store.memory.MemoryPersistenceAdapter; import org.apache.activemq.thread.TaskRunnerFactory; import org.apache.activemq.transport.TransportFactory; import org.apache.activemq.transport.TransportServer; import org.apache.activemq.transport.vm.VMTransportFactory; import org.apache.activemq.util.IOExceptionSupport; import org.apache.activemq.util.JMXSupport; import org.apache.activemq.util.ServiceStopper; import org.apache.activemq.util.URISupport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import edu.emory.mathcs.backport.java.util.concurrent.CopyOnWriteArrayList; import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicBoolean; /** * Represents a running broker service which consists of a number of transport * connectors, network connectors and a bunch of properties which can be used to * configure the broker as its lazily created. * * @version $Revision: 1.1 $ */ public class BrokerService implements Service { public static final String DEFAULT_PORT = "61616"; private static final Log log = LogFactory.getLog(BrokerService.class); private boolean useJmx = true; private boolean persistent = true; private boolean populateJMSXUserID = false; private boolean useShutdownHook = true; private boolean useLoggingForShutdownErrors = false; private boolean shutdownOnMasterFailure = false; private String brokerName = "localhost"; private File dataDirectory; private Broker broker; private ManagementContext managementContext; private ObjectName brokerObjectName; private TaskRunnerFactory taskRunnerFactory; private UsageManager memoryManager; private PersistenceAdapter persistenceAdapter; private PersistenceAdapterFactory persistenceFactory; private MessageAuthorizationPolicy messageAuthorizationPolicy; private List transportConnectors = new CopyOnWriteArrayList(); private List networkConnectors = new CopyOnWriteArrayList(); private List proxyConnectors = new CopyOnWriteArrayList(); private List registeredMBeanNames = new CopyOnWriteArrayList(); private List jmsConnectors = new CopyOnWriteArrayList(); private MasterConnector masterConnector; private Thread shutdownHook; private String[] transportConnectorURIs; private String[] networkConnectorURIs; private String[] proxyConnectorURIs; private String masterConnectorURI; private JmsConnector[] jmsBridgeConnectors; //these are Jms to Jms bridges to other jms messaging systems private boolean deleteAllMessagesOnStartup; private URI vmConnectorURI; private PolicyMap destinationPolicy; private AtomicBoolean started = new AtomicBoolean(false); private BrokerPlugin[] plugins; private boolean keepDurableSubsActive; private BrokerId brokerId; /** * Adds a new transport connector for the given bind address * * @return the newly created and added transport connector * @throws Exception */ public TransportConnector addConnector(String bindAddress) throws Exception { return addConnector(new URI(bindAddress)); } /** * Adds a new transport connector for the given bind address * * @return the newly created and added transport connector * @throws Exception */ public TransportConnector addConnector(URI bindAddress) throws Exception { return addConnector(createTransportConnector(getBroker(), bindAddress)); } /** * Adds a new transport connector for the given TransportServer transport * * @return the newly created and added transport connector * @throws Exception */ public TransportConnector addConnector(TransportServer transport) throws Exception { return addConnector(new TransportConnector(getBroker(), transport)); } /** * Adds a new transport connector * * @return the transport connector * @throws Exception */ public TransportConnector addConnector(TransportConnector connector) throws Exception { transportConnectors.add(connector); return connector; } /** * Adds a new network connector using the given discovery address * * @return the newly created and added network connector * @throws Exception */ public NetworkConnector addNetworkConnector(String discoveryAddress) throws Exception { return addNetworkConnector(new URI(discoveryAddress)); } /** * Adds a new proxy connector using the given bind address * * @return the newly created and added network connector * @throws Exception */ public ProxyConnector addProxyConnector(String bindAddress) throws Exception { return addProxyConnector(new URI(bindAddress)); } /** * Adds a new network connector using the given discovery address * * @return the newly created and added network connector * @throws Exception */ public NetworkConnector addNetworkConnector(URI discoveryAddress) throws Exception{ NetworkConnector connector=new DiscoveryNetworkConnector(discoveryAddress); return addNetworkConnector(connector); } /** * Adds a new proxy connector using the given bind address * * @return the newly created and added network connector * @throws Exception */ public ProxyConnector addProxyConnector(URI bindAddress) throws Exception{ ProxyConnector connector=new ProxyConnector(); connector.setBind(bindAddress); connector.setRemote(new URI("fanout:multicast://default")); return addProxyConnector(connector); } /** * Adds a new network connector to connect this broker to a federated * network */ public NetworkConnector addNetworkConnector(NetworkConnector connector) throws Exception { URI uri = getVmConnectorURI(); HashMap map = new HashMap(URISupport.parseParamters(uri)); map.put("network", "true"); uri = URISupport.createURIWithQuery(uri, URISupport.createQueryString(map)); connector.setLocalUri(uri); // Set a connection filter so that the connector does not establish loop back connections. connector.setConnectionFilter(new ConnectionFilter() { public boolean connectTo(URI location) { List transportConnectors = getTransportConnectors(); for (Iterator iter = transportConnectors.iterator(); iter.hasNext();) { try { TransportConnector tc = (TransportConnector) iter.next(); if( location.equals(tc.getConnectUri()) ) { return false; } } catch (Throwable e) { } } return true; } }); networkConnectors.add(connector); if (isUseJmx()) { registerNetworkConnectorMBean(connector); } return connector; } public ProxyConnector addProxyConnector(ProxyConnector connector) throws Exception { URI uri = getVmConnectorURI(); connector.setLocalUri(uri); proxyConnectors.add(connector); if (isUseJmx()) { registerProxyConnectorMBean(connector); } return connector; } public JmsConnector addJmsConnector(JmsConnector connector) throws Exception{ connector.setBrokerService(this); jmsConnectors.add(connector); if (isUseJmx()) { registerJmsConnectorMBean(connector); } return connector; } public JmsConnector removeJmsConnector(JmsConnector connector){ if (jmsConnectors.remove(connector)){ return connector; } return null; } public void initializeMasterConnector(URI remoteURI) throws Exception { if (masterConnector != null){ throw new IllegalStateException("Can only be the Slave to one Master"); } URI localURI = getVmConnectorURI(); TransportConnector connector = null; if (!transportConnectors.isEmpty()){ connector = (TransportConnector)transportConnectors.get(0); } masterConnector = new MasterConnector(this,connector); masterConnector.setLocalURI(localURI); masterConnector.setRemoteURI(remoteURI); if (isUseJmx()) { registerFTConnectorMBean(masterConnector); } } /** * @return Returns the masterConnectorURI. */ public String getMasterConnectorURI(){ return masterConnectorURI; } /** * @param masterConnectorURI The masterConnectorURI to set. */ public void setMasterConnectorURI(String masterConnectorURI){ this.masterConnectorURI=masterConnectorURI; } /** * @return true if this Broker is a slave to a Master */ public boolean isSlave(){ return masterConnector != null && masterConnector.isSlave(); } public void masterFailed(){ if (shutdownOnMasterFailure){ log.fatal("The Master has failed ... shutting down"); try { stop(); }catch(Exception e){ log.error("Failed to stop for master failure",e); } }else { log.warn("Master Failed - starting all connectors"); try{ startAllConnectors(); }catch(Exception e){ log.error("Failed to startAllConnectors"); } } } public boolean isStarted() { return started.get(); } // Service interface // ------------------------------------------------------------------------- public void start() throws Exception { if (! started.compareAndSet(false, true)) { // lets just ignore redundant start() calls // as its way too easy to not be completely sure if start() has been // called or not with the gazillion of different configuration mechanisms //throw new IllegalStateException("Allready started."); return; } try { processHelperProperties(); BrokerRegistry.getInstance().bind(getBrokerName(), this); addShutdownHook(); if (deleteAllMessagesOnStartup) { deleteAllMessages(); } if (isUseJmx()) { getManagementContext().start(); } getBroker().start(); if (masterConnectorURI!=null){ initializeMasterConnector(new URI(masterConnectorURI)); if (masterConnector!=null){ masterConnector.start(); } } startAllConnectors(); brokerId = broker.getBrokerId(); log.info("ActiveMQ JMS Message Broker (" + getBrokerName()+", "+brokerId+") started"); } catch (Exception e) { log.error("Failed to start ActiveMQ JMS Message Broker. Reason: " + e, e); throw e; } } public void stop() throws Exception { if (! started.compareAndSet(true, false)) { return; } log.info("ActiveMQ Message Broker (" + getBrokerName()+", "+brokerId+") is shutting down"); BrokerRegistry.getInstance().unbind(getBrokerName()); removeShutdownHook(); ServiceStopper stopper = new ServiceStopper(); if (masterConnector != null){ masterConnector.stop(); } for (Iterator iter = getNetworkConnectors().iterator(); iter.hasNext();) { NetworkConnector connector = (NetworkConnector) iter.next(); stopper.stop(connector); } for (Iterator iter = getProxyConnectors().iterator(); iter.hasNext();) { ProxyConnector connector = (ProxyConnector) iter.next(); stopper.stop(connector); } for (Iterator iter = jmsConnectors.iterator(); iter.hasNext();) { JmsConnector connector = (JmsConnector) iter.next(); stopper.stop(connector); } for (Iterator iter = getTransportConnectors().iterator(); iter.hasNext();) { TransportConnector connector = (TransportConnector) iter.next(); stopper.stop(connector); } //remove any VMTransports connected VMTransportFactory.stopped(getBrokerName()); stopper.stop(persistenceAdapter); if (broker != null) { stopper.stop(broker); } if (isUseJmx()) { MBeanServer mbeanServer = getManagementContext().getMBeanServer(); for (Iterator iter = registeredMBeanNames.iterator(); iter.hasNext();) { ObjectName name = (ObjectName) iter.next(); try { mbeanServer.unregisterMBean(name); } catch (Exception e) { stopper.onException(mbeanServer, e); } } stopper.stop(getManagementContext()); } log.info("ActiveMQ JMS Message Broker (" + getBrokerName()+", "+brokerId+") stopped"); stopper.throwFirstException(); } // Properties // ------------------------------------------------------------------------- public Broker getBroker() throws Exception { if (broker == null) { log.info("ActiveMQ " + ActiveMQConnectionMetaData.PROVIDER_VERSION + " JMS Message Broker (" + getBrokerName() + ") is starting"); log.info("For help or more information please see: http://incubator.apache.org/activemq/"); broker = createBroker(); } return broker; } public String getBrokerName() { return brokerName; } /** * Sets the name of this broker; which must be unique in the network */ public void setBrokerName(String brokerName) { this.brokerName = brokerName; } public PersistenceAdapterFactory getPersistenceFactory() { if (persistenceFactory == null) { persistenceFactory = createPersistenceFactory(); } return persistenceFactory; } public File getDataDirectory() { if (dataDirectory == null) { dataDirectory = new File(new File("activemq-data"), getBrokerName() .replaceAll("[^a-zA-Z0-9\\.\\_\\-]", "_")); } return dataDirectory; } /** * Sets the directory in which the data files will be stored by default for * the JDBC and Journal persistence adaptors. * * @param dataDirectory * the directory to store data files */ public void setDataDirectory(File dataDirectory) { this.dataDirectory = dataDirectory; } public void setPersistenceFactory(PersistenceAdapterFactory persistenceFactory) { this.persistenceFactory = persistenceFactory; } public boolean isPersistent() { return persistent; } /** * Sets whether or not persistence is enabled or disabled. */ public void setPersistent(boolean persistent) { this.persistent = persistent; } public boolean isPopulateJMSXUserID() { return populateJMSXUserID; } /** * Sets whether or not the broker should populate the JMSXUserID header. */ public void setPopulateJMSXUserID(boolean populateJMSXUserID) { this.populateJMSXUserID = populateJMSXUserID; } public UsageManager getMemoryManager() { if (memoryManager == null) { memoryManager = new UsageManager(); memoryManager.setLimit(1024 * 1024 * 20); // Default to 20 Meg // limit } return memoryManager; } public void setMemoryManager(UsageManager memoryManager) { this.memoryManager = memoryManager; } public PersistenceAdapter getPersistenceAdapter() throws IOException { if (persistenceAdapter == null) { persistenceAdapter = createPersistenceAdapter(); } return persistenceAdapter; } /** * Sets the persistence adaptor implementation to use for this broker */ public void setPersistenceAdapter(PersistenceAdapter persistenceAdapter) { this.persistenceAdapter = persistenceAdapter; } public TaskRunnerFactory getTaskRunnerFactory() { if (taskRunnerFactory == null) { taskRunnerFactory = new TaskRunnerFactory(); } return taskRunnerFactory; } public void setTaskRunnerFactory(TaskRunnerFactory taskRunnerFactory) { this.taskRunnerFactory = taskRunnerFactory; } public boolean isUseJmx() { return useJmx; } /** * Sets whether or not the Broker's services should be exposed into JMX or * not. */ public void setUseJmx(boolean useJmx) { this.useJmx = useJmx; } public ObjectName getBrokerObjectName() throws IOException { if (brokerObjectName == null) { brokerObjectName = createBrokerObjectName(); } return brokerObjectName; } /** * Sets the JMX ObjectName for this broker */ public void setBrokerObjectName(ObjectName brokerObjectName) { this.brokerObjectName = brokerObjectName; } public ManagementContext getManagementContext() { if (managementContext == null) { managementContext = new ManagementContext(); } return managementContext; } public void setManagementContext(ManagementContext managementContext) { this.managementContext = managementContext; } public String[] getNetworkConnectorURIs() { return networkConnectorURIs; } public void setNetworkConnectorURIs(String[] networkConnectorURIs) { this.networkConnectorURIs = networkConnectorURIs; } public String[] getTransportConnectorURIs() { return transportConnectorURIs; } public void setTransportConnectorURIs(String[] transportConnectorURIs) { this.transportConnectorURIs = transportConnectorURIs; } /** * @return Returns the jmsBridgeConnectors. */ public JmsConnector[] getJmsBridgeConnectors(){ return jmsBridgeConnectors; } /** * @param jmsBridgeConnectors The jmsBridgeConnectors to set. */ public void setJmsBridgeConnectors(JmsConnector[] jmsConnectors){ this.jmsBridgeConnectors=jmsConnectors; } public boolean isUseLoggingForShutdownErrors() { return useLoggingForShutdownErrors; } /** * Sets whether or not we should use commons-logging when reporting errors * when shutting down the broker */ public void setUseLoggingForShutdownErrors(boolean useLoggingForShutdownErrors) { this.useLoggingForShutdownErrors = useLoggingForShutdownErrors; } public boolean isUseShutdownHook() { return useShutdownHook; } /** * Sets whether or not we should use a shutdown handler to close down the * broker cleanly if the JVM is terminated. It is recommended you leave this * enabled. */ public void setUseShutdownHook(boolean useShutdownHook) { this.useShutdownHook = useShutdownHook; } public List getTransportConnectors() { return new ArrayList(transportConnectors); } /** * Sets the transport connectors which this broker will listen on for new * clients */ public void setTransportConnectors(List transportConnectors) throws Exception { for (Iterator iter = transportConnectors.iterator(); iter.hasNext();) { TransportConnector connector = (TransportConnector) iter.next(); addConnector(connector); } } public List getNetworkConnectors() { return new ArrayList(networkConnectors); } public List getProxyConnectors() { return new ArrayList(proxyConnectors); } /** * Sets the network connectors which this broker will use to connect to * other brokers in a federated network */ public void setNetworkConnectors(List networkConnectors) throws Exception { for (Iterator iter = networkConnectors.iterator(); iter.hasNext();) { NetworkConnector connector = (NetworkConnector) iter.next(); addNetworkConnector(connector); } } /** * Sets the network connectors which this broker will use to connect to * other brokers in a federated network */ public void setProxyConnectors(List proxyConnectors) throws Exception { for (Iterator iter = proxyConnectors.iterator(); iter.hasNext();) { ProxyConnector connector = (ProxyConnector) iter.next(); addProxyConnector(connector); } } public PolicyMap getDestinationPolicy() { return destinationPolicy; } /** * Sets the destination specific policies available either for exact * destinations or for wildcard areas of destinations. */ public void setDestinationPolicy(PolicyMap policyMap) { this.destinationPolicy = policyMap; } public BrokerPlugin[] getPlugins() { return plugins; } /** * Sets a number of broker plugins to install such as for security authentication or authorization */ public void setPlugins(BrokerPlugin[] plugins) { this.plugins = plugins; } public MessageAuthorizationPolicy getMessageAuthorizationPolicy() { return messageAuthorizationPolicy; } /** * Sets the policy used to decide if the current connection is authorized to consume * a given message */ public void setMessageAuthorizationPolicy(MessageAuthorizationPolicy messageAuthorizationPolicy) { this.messageAuthorizationPolicy = messageAuthorizationPolicy; } /** * Delete all messages from the persistent store * @throws IOException */ public void deleteAllMessages() throws IOException{ getPersistenceAdapter().deleteAllMessages(); } // Implementation methods // ------------------------------------------------------------------------- /** * Handles any lazy-creation helper properties which are added to make * things easier to configure inside environments such as Spring * * @throws Exception */ protected void processHelperProperties() throws Exception { if (transportConnectorURIs != null) { for (int i = 0; i < transportConnectorURIs.length; i++) { String uri = transportConnectorURIs[i]; addConnector(uri); } } if (networkConnectorURIs != null) { for (int i = 0; i < networkConnectorURIs.length; i++) { String uri = networkConnectorURIs[i]; addNetworkConnector(uri); } } if (proxyConnectorURIs != null) { for (int i = 0; i < proxyConnectorURIs.length; i++) { String uri = proxyConnectorURIs[i]; addProxyConnector(uri); } } if (jmsBridgeConnectors != null){ for (int i = 0; i < jmsBridgeConnectors.length; i++){ addJmsConnector(jmsBridgeConnectors[i]); } } } protected void registerConnectorMBean(TransportConnector connector) throws IOException, URISyntaxException { MBeanServer mbeanServer = getManagementContext().getMBeanServer(); ConnectorViewMBean view = new ConnectorView(connector); try { ObjectName objectName = new ObjectName( managementContext.getJmxDomainName()+":"+ "BrokerName="+JMXSupport.encodeObjectNamePart(getBrokerName())+","+ "Type=Connector,"+ "ConnectorName="+JMXSupport.encodeObjectNamePart(connector.getName()) ); mbeanServer.registerMBean(view, objectName); registeredMBeanNames.add(objectName); } catch (Throwable e) { throw IOExceptionSupport.create("Broker could not be registered in JMX: " + e.getMessage(), e); } } protected void registerNetworkConnectorMBean(NetworkConnector connector) throws IOException { MBeanServer mbeanServer = getManagementContext().getMBeanServer(); NetworkConnectorViewMBean view = new NetworkConnectorView(connector); try { ObjectName objectName = new ObjectName( managementContext.getJmxDomainName()+":"+ "BrokerName="+JMXSupport.encodeObjectNamePart(getBrokerName())+","+ "Type=NetworkConnector,"+ "NetworkConnectorName="+JMXSupport.encodeObjectNamePart(connector.getName()) ); mbeanServer.registerMBean(view, objectName); registeredMBeanNames.add(objectName); } catch (Throwable e) { throw IOExceptionSupport.create("Broker could not be registered in JMX: " + e.getMessage(), e); } } protected void registerProxyConnectorMBean(ProxyConnector connector) throws IOException { MBeanServer mbeanServer = getManagementContext().getMBeanServer(); ProxyConnectorView view = new ProxyConnectorView(connector); try { ObjectName objectName = new ObjectName( managementContext.getJmxDomainName()+":"+ "BrokerName="+JMXSupport.encodeObjectNamePart(getBrokerName())+","+ "Type=ProxyConnector,"+ "ProxyConnectorName="+JMXSupport.encodeObjectNamePart(connector.getName()) ); mbeanServer.registerMBean(view, objectName); registeredMBeanNames.add(objectName); } catch (Throwable e) { throw IOExceptionSupport.create("Broker could not be registered in JMX: " + e.getMessage(), e); } } protected void registerFTConnectorMBean(MasterConnector connector) throws IOException { MBeanServer mbeanServer = getManagementContext().getMBeanServer(); FTConnectorView view = new FTConnectorView(connector); try { ObjectName objectName = new ObjectName( managementContext.getJmxDomainName()+":"+ "BrokerName="+JMXSupport.encodeObjectNamePart(getBrokerName())+","+ "Type=MasterConnector" ); mbeanServer.registerMBean(view, objectName); registeredMBeanNames.add(objectName); } catch (Throwable e) { throw IOExceptionSupport.create("Broker could not be registered in JMX: " + e.getMessage(), e); } } protected void registerJmsConnectorMBean(JmsConnector connector) throws IOException { MBeanServer mbeanServer = getManagementContext().getMBeanServer(); JmsConnectorView view = new JmsConnectorView(connector); try { ObjectName objectName = new ObjectName( managementContext.getJmxDomainName()+":"+ "BrokerName="+JMXSupport.encodeObjectNamePart(getBrokerName())+","+ "Type=JmsConnector,"+ "JmsConnectorName="+JMXSupport.encodeObjectNamePart(connector.getName()) ); mbeanServer.registerMBean(view, objectName); registeredMBeanNames.add(objectName); } catch (Throwable e) { throw IOExceptionSupport.create("Broker could not be registered in JMX: " + e.getMessage(), e); } } /** * Factory method to create a new broker * * @throws Exception * * @throws * @throws */ protected Broker createBroker() throws Exception { Broker regionBroker = createRegionBroker(); Broker broker = addInterceptors(regionBroker); // Add a filter that will stop access to the broker once stopped broker = new MutableBrokerFilter(broker) { public void stop() throws Exception { super.stop(); setNext(new ErrorBroker("Broker has been stopped: "+this) { // Just ignore additional stop actions. public void stop() throws Exception { } }); } }; if (isUseJmx()) { ManagedRegionBroker managedBroker = (ManagedRegionBroker) regionBroker; managedBroker.setContextBroker(broker); BrokerViewMBean view = new BrokerView(this, managedBroker); MBeanServer mbeanServer = getManagementContext().getMBeanServer(); ObjectName objectName = getBrokerObjectName(); mbeanServer.registerMBean(view, objectName); registeredMBeanNames.add(objectName); } return broker; } /** * Factory method to create the core region broker onto which interceptors * are added * * @throws Exception */ protected Broker createRegionBroker() throws Exception { // we must start the persistence adaptor before we can create the region // broker getPersistenceAdapter().setUsageManager(getMemoryManager()); getPersistenceAdapter().start(); RegionBroker regionBroker = null; if (isUseJmx()) { MBeanServer mbeanServer = getManagementContext().getMBeanServer(); regionBroker = new ManagedRegionBroker(this,mbeanServer, getBrokerObjectName(), getTaskRunnerFactory(), getMemoryManager(), getPersistenceAdapter()); } else { regionBroker = new RegionBroker(this,getTaskRunnerFactory(), getMemoryManager(), getPersistenceAdapter()); } regionBroker.setKeepDurableSubsActive(keepDurableSubsActive); regionBroker.setBrokerName(getBrokerName()); return regionBroker; } /** * Strategy method to add interceptors to the broker * * @throws IOException */ protected Broker addInterceptors(Broker broker) throws Exception { broker = new TransactionBroker(broker, getPersistenceAdapter().createTransactionStore()); broker = new AdvisoryBroker(broker); broker = new CompositeDestinationBroker(broker); if (isPopulateJMSXUserID()) { broker = new UserIDBroker(broker); } if (plugins != null) { for (int i = 0; i < plugins.length; i++) { BrokerPlugin plugin = plugins[i]; broker = plugin.installPlugin(broker); } } return broker; } protected PersistenceAdapter createPersistenceAdapter() throws IOException { if (isPersistent()) { return getPersistenceFactory().createPersistenceAdapter(); } else { return new MemoryPersistenceAdapter(); } } protected DefaultPersistenceAdapterFactory createPersistenceFactory() { DefaultPersistenceAdapterFactory factory = new DefaultPersistenceAdapterFactory(); factory.setDataDirectory(getDataDirectory()); factory.setTaskRunnerFactory(getTaskRunnerFactory()); return factory; } protected ObjectName createBrokerObjectName() throws IOException { try { return new ObjectName( getManagementContext().getJmxDomainName()+":"+ "BrokerName="+JMXSupport.encodeObjectNamePart(getBrokerName())+","+ "Type=Broker" ); } catch (Throwable e) { throw IOExceptionSupport.create("Invalid JMX broker name: " + brokerName, e); } } protected TransportConnector createTransportConnector(Broker broker, URI brokerURI) throws Exception { TransportServer transport = TransportFactory.bind(getBrokerName(),brokerURI); return new TransportConnector(broker, transport); } /** * Extracts the port from the options */ protected Object getPort(Map options) { Object port = options.get("port"); if (port == null) { port = DEFAULT_PORT; log.warn("No port specified so defaulting to: " + port); } return port; } protected void addShutdownHook() { if (useShutdownHook) { shutdownHook = new Thread("ActiveMQ ShutdownHook") { public void run() { containerShutdown(); } }; Runtime.getRuntime().addShutdownHook(shutdownHook); } } protected void removeShutdownHook() { if (shutdownHook != null) { try { Runtime.getRuntime().removeShutdownHook(shutdownHook); } catch (Exception e) { log.debug("Caught exception, must be shutting down: " + e); } } } /** * Causes a clean shutdown of the container when the VM is being shut down */ protected void containerShutdown() { try { stop(); } catch (IOException e) { Throwable linkedException = e.getCause(); if (linkedException != null) { logError("Failed to shut down: " + e + ". Reason: " + linkedException, linkedException); } else { logError("Failed to shut down: " + e, e); } if (!useLoggingForShutdownErrors) { e.printStackTrace(System.err); } } catch (Exception e) { logError("Failed to shut down: " + e, e); } } protected void logError(String message, Throwable e) { if (useLoggingForShutdownErrors) { log.error("Failed to shut down: " + e); } else { System.err.println("Failed to shut down: " + e); } } /** * Start all transport and network connections, proxies and bridges * @throws Exception */ protected void startAllConnectors() throws Exception{ if (!isSlave()){ for (Iterator iter = getTransportConnectors().iterator(); iter.hasNext();) { TransportConnector connector = (TransportConnector) iter.next(); startTransportConnector(connector); } for (Iterator iter = getNetworkConnectors().iterator(); iter.hasNext();) { NetworkConnector connector = (NetworkConnector) iter.next(); connector.setBrokerName(getBrokerName()); connector.setDurableDestinations(getBroker().getDurableDestinations()); connector.start(); } for (Iterator iter = getProxyConnectors().iterator(); iter.hasNext();) { ProxyConnector connector = (ProxyConnector) iter.next(); connector.start(); } for (Iterator iter = jmsConnectors.iterator(); iter.hasNext();) { JmsConnector connector = (JmsConnector) iter.next(); connector.start(); } } } protected void startTransportConnector(TransportConnector connector) throws Exception { connector.setBroker(getBroker()); connector.setBrokerName(getBrokerName()); connector.setTaskRunnerFactory(getTaskRunnerFactory()); MessageAuthorizationPolicy policy = getMessageAuthorizationPolicy(); if (policy != null) { connector.setMessageAuthorizationPolicy(policy); } if (isUseJmx()) { connector = connector.asManagedConnector(getManagementContext().getMBeanServer(), getBrokerObjectName()); registerConnectorMBean(connector); } connector.start(); } public boolean isDeleteAllMessagesOnStartup() { return deleteAllMessagesOnStartup; } /** * Sets whether or not all messages are deleted on startup - mostly only * useful for testing. */ public void setDeleteAllMessagesOnStartup(boolean deletePersistentMessagesOnStartup) { this.deleteAllMessagesOnStartup = deletePersistentMessagesOnStartup; } public URI getVmConnectorURI() { if (vmConnectorURI == null) { try { vmConnectorURI = new URI("vm://" + getBrokerName()); } catch (URISyntaxException e) { } } return vmConnectorURI; } public void setVmConnectorURI(URI vmConnectorURI) { this.vmConnectorURI = vmConnectorURI; } /** * @return Returns the shutdownOnMasterFailure. */ public boolean isShutdownOnMasterFailure(){ return shutdownOnMasterFailure; } /** * @param shutdownOnMasterFailure The shutdownOnMasterFailure to set. */ public void setShutdownOnMasterFailure(boolean shutdownOnMasterFailure){ this.shutdownOnMasterFailure=shutdownOnMasterFailure; } public boolean isKeepDurableSubsActive() { return keepDurableSubsActive; } public void setKeepDurableSubsActive(boolean keepDurableSubsActive) { this.keepDurableSubsActive = keepDurableSubsActive; } }
activemq-core/src/main/java/org/apache/activemq/broker/BrokerService.java
/** * * Copyright 2005-2006 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.activemq.broker; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.activemq.ActiveMQConnectionMetaData; import org.apache.activemq.Service; import org.apache.activemq.advisory.AdvisoryBroker; import org.apache.activemq.broker.ft.MasterConnector; import org.apache.activemq.broker.jmx.BrokerView; import org.apache.activemq.broker.jmx.BrokerViewMBean; import org.apache.activemq.broker.jmx.ConnectorView; import org.apache.activemq.broker.jmx.ConnectorViewMBean; import org.apache.activemq.broker.jmx.FTConnectorView; import org.apache.activemq.broker.jmx.JmsConnectorView; import org.apache.activemq.broker.jmx.ManagedRegionBroker; import org.apache.activemq.broker.jmx.ManagementContext; import org.apache.activemq.broker.jmx.NetworkConnectorView; import org.apache.activemq.broker.jmx.NetworkConnectorViewMBean; import org.apache.activemq.broker.jmx.ProxyConnectorView; import org.apache.activemq.broker.region.RegionBroker; import org.apache.activemq.broker.region.policy.PolicyMap; import org.apache.activemq.memory.UsageManager; import org.apache.activemq.network.ConnectionFilter; import org.apache.activemq.network.DiscoveryNetworkConnector; import org.apache.activemq.network.NetworkConnector; import org.apache.activemq.network.jms.JmsConnector; import org.apache.activemq.proxy.ProxyConnector; import org.apache.activemq.security.MessageAuthorizationPolicy; import org.apache.activemq.store.DefaultPersistenceAdapterFactory; import org.apache.activemq.store.PersistenceAdapter; import org.apache.activemq.store.PersistenceAdapterFactory; import org.apache.activemq.store.memory.MemoryPersistenceAdapter; import org.apache.activemq.thread.TaskRunnerFactory; import org.apache.activemq.transport.TransportFactory; import org.apache.activemq.transport.TransportServer; import org.apache.activemq.transport.vm.VMTransportFactory; import org.apache.activemq.util.IOExceptionSupport; import org.apache.activemq.util.JMXSupport; import org.apache.activemq.util.ServiceStopper; import org.apache.activemq.util.URISupport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import edu.emory.mathcs.backport.java.util.concurrent.CopyOnWriteArrayList; import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicBoolean; /** * Represents a running broker service which consists of a number of transport * connectors, network connectors and a bunch of properties which can be used to * configure the broker as its lazily created. * * @version $Revision: 1.1 $ */ public class BrokerService implements Service { public static final String DEFAULT_PORT = "61616"; private static final Log log = LogFactory.getLog(BrokerService.class); private boolean useJmx = true; private boolean persistent = true; private boolean populateJMSXUserID = false; private boolean useShutdownHook = true; private boolean useLoggingForShutdownErrors = false; private boolean shutdownOnMasterFailure = false; private String brokerName = "localhost"; private File dataDirectory; private Broker broker; private ManagementContext managementContext; private ObjectName brokerObjectName; private TaskRunnerFactory taskRunnerFactory; private UsageManager memoryManager; private PersistenceAdapter persistenceAdapter; private PersistenceAdapterFactory persistenceFactory; private MessageAuthorizationPolicy messageAuthorizationPolicy; private List transportConnectors = new CopyOnWriteArrayList(); private List networkConnectors = new CopyOnWriteArrayList(); private List proxyConnectors = new CopyOnWriteArrayList(); private List registeredMBeanNames = new CopyOnWriteArrayList(); private List jmsConnectors = new CopyOnWriteArrayList(); private MasterConnector masterConnector; private Thread shutdownHook; private String[] transportConnectorURIs; private String[] networkConnectorURIs; private String[] proxyConnectorURIs; private String masterConnectorURI; private JmsConnector[] jmsBridgeConnectors; //these are Jms to Jms bridges to other jms messaging systems private boolean deleteAllMessagesOnStartup; private URI vmConnectorURI; private PolicyMap destinationPolicy; private AtomicBoolean started = new AtomicBoolean(false); private BrokerPlugin[] plugins; private boolean keepDurableSubsActive; /** * Adds a new transport connector for the given bind address * * @return the newly created and added transport connector * @throws Exception */ public TransportConnector addConnector(String bindAddress) throws Exception { return addConnector(new URI(bindAddress)); } /** * Adds a new transport connector for the given bind address * * @return the newly created and added transport connector * @throws Exception */ public TransportConnector addConnector(URI bindAddress) throws Exception { return addConnector(createTransportConnector(getBroker(), bindAddress)); } /** * Adds a new transport connector for the given TransportServer transport * * @return the newly created and added transport connector * @throws Exception */ public TransportConnector addConnector(TransportServer transport) throws Exception { return addConnector(new TransportConnector(getBroker(), transport)); } /** * Adds a new transport connector * * @return the transport connector * @throws Exception */ public TransportConnector addConnector(TransportConnector connector) throws Exception { transportConnectors.add(connector); return connector; } /** * Adds a new network connector using the given discovery address * * @return the newly created and added network connector * @throws Exception */ public NetworkConnector addNetworkConnector(String discoveryAddress) throws Exception { return addNetworkConnector(new URI(discoveryAddress)); } /** * Adds a new proxy connector using the given bind address * * @return the newly created and added network connector * @throws Exception */ public ProxyConnector addProxyConnector(String bindAddress) throws Exception { return addProxyConnector(new URI(bindAddress)); } /** * Adds a new network connector using the given discovery address * * @return the newly created and added network connector * @throws Exception */ public NetworkConnector addNetworkConnector(URI discoveryAddress) throws Exception{ NetworkConnector connector=new DiscoveryNetworkConnector(discoveryAddress); return addNetworkConnector(connector); } /** * Adds a new proxy connector using the given bind address * * @return the newly created and added network connector * @throws Exception */ public ProxyConnector addProxyConnector(URI bindAddress) throws Exception{ ProxyConnector connector=new ProxyConnector(); connector.setBind(bindAddress); connector.setRemote(new URI("fanout:multicast://default")); return addProxyConnector(connector); } /** * Adds a new network connector to connect this broker to a federated * network */ public NetworkConnector addNetworkConnector(NetworkConnector connector) throws Exception { URI uri = getVmConnectorURI(); HashMap map = new HashMap(URISupport.parseParamters(uri)); map.put("network", "true"); uri = URISupport.createURIWithQuery(uri, URISupport.createQueryString(map)); connector.setLocalUri(uri); // Set a connection filter so that the connector does not establish loop back connections. connector.setConnectionFilter(new ConnectionFilter() { public boolean connectTo(URI location) { List transportConnectors = getTransportConnectors(); for (Iterator iter = transportConnectors.iterator(); iter.hasNext();) { try { TransportConnector tc = (TransportConnector) iter.next(); if( location.equals(tc.getConnectUri()) ) { return false; } } catch (Throwable e) { } } return true; } }); networkConnectors.add(connector); if (isUseJmx()) { registerNetworkConnectorMBean(connector); } return connector; } public ProxyConnector addProxyConnector(ProxyConnector connector) throws Exception { URI uri = getVmConnectorURI(); connector.setLocalUri(uri); proxyConnectors.add(connector); if (isUseJmx()) { registerProxyConnectorMBean(connector); } return connector; } public JmsConnector addJmsConnector(JmsConnector connector) throws Exception{ connector.setBrokerService(this); jmsConnectors.add(connector); if (isUseJmx()) { registerJmsConnectorMBean(connector); } return connector; } public JmsConnector removeJmsConnector(JmsConnector connector){ if (jmsConnectors.remove(connector)){ return connector; } return null; } public void initializeMasterConnector(URI remoteURI) throws Exception { if (masterConnector != null){ throw new IllegalStateException("Can only be the Slave to one Master"); } URI localURI = getVmConnectorURI(); TransportConnector connector = null; if (!transportConnectors.isEmpty()){ connector = (TransportConnector)transportConnectors.get(0); } masterConnector = new MasterConnector(this,connector); masterConnector.setLocalURI(localURI); masterConnector.setRemoteURI(remoteURI); if (isUseJmx()) { registerFTConnectorMBean(masterConnector); } } /** * @return Returns the masterConnectorURI. */ public String getMasterConnectorURI(){ return masterConnectorURI; } /** * @param masterConnectorURI The masterConnectorURI to set. */ public void setMasterConnectorURI(String masterConnectorURI){ this.masterConnectorURI=masterConnectorURI; } /** * @return true if this Broker is a slave to a Master */ public boolean isSlave(){ return masterConnector != null && masterConnector.isSlave(); } public void masterFailed(){ if (shutdownOnMasterFailure){ log.fatal("The Master has failed ... shutting down"); try { stop(); }catch(Exception e){ log.error("Failed to stop for master failure",e); } }else { log.warn("Master Failed - starting all connectors"); try{ startAllConnectors(); }catch(Exception e){ log.error("Failed to startAllConnectors"); } } } public boolean isStarted() { return started.get(); } // Service interface // ------------------------------------------------------------------------- public void start() throws Exception { if (! started.compareAndSet(false, true)) { // lets just ignore redundant start() calls // as its way too easy to not be completely sure if start() has been // called or not with the gazillion of different configuration mechanisms //throw new IllegalStateException("Allready started."); return; } try { processHelperProperties(); BrokerRegistry.getInstance().bind(getBrokerName(), this); addShutdownHook(); if (deleteAllMessagesOnStartup) { deleteAllMessages(); } if (isUseJmx()) { getManagementContext().start(); } getBroker().start(); if (masterConnectorURI!=null){ initializeMasterConnector(new URI(masterConnectorURI)); if (masterConnector!=null){ masterConnector.start(); } } startAllConnectors(); log.info("ActiveMQ JMS Message Broker (" + getBrokerName() + ") started"); } catch (Exception e) { log.error("Failed to start ActiveMQ JMS Message Broker. Reason: " + e, e); throw e; } } public void stop() throws Exception { if (! started.compareAndSet(true, false)) { return; } log.info("ActiveMQ Message Broker (" + getBrokerName() + ") is shutting down"); BrokerRegistry.getInstance().unbind(getBrokerName()); removeShutdownHook(); ServiceStopper stopper = new ServiceStopper(); if (masterConnector != null){ masterConnector.stop(); } for (Iterator iter = getNetworkConnectors().iterator(); iter.hasNext();) { NetworkConnector connector = (NetworkConnector) iter.next(); stopper.stop(connector); } for (Iterator iter = getProxyConnectors().iterator(); iter.hasNext();) { ProxyConnector connector = (ProxyConnector) iter.next(); stopper.stop(connector); } for (Iterator iter = jmsConnectors.iterator(); iter.hasNext();) { JmsConnector connector = (JmsConnector) iter.next(); stopper.stop(connector); } for (Iterator iter = getTransportConnectors().iterator(); iter.hasNext();) { TransportConnector connector = (TransportConnector) iter.next(); stopper.stop(connector); } //remove any VMTransports connected VMTransportFactory.stopped(getBrokerName()); stopper.stop(persistenceAdapter); if (broker != null) { stopper.stop(broker); } if (isUseJmx()) { MBeanServer mbeanServer = getManagementContext().getMBeanServer(); for (Iterator iter = registeredMBeanNames.iterator(); iter.hasNext();) { ObjectName name = (ObjectName) iter.next(); try { mbeanServer.unregisterMBean(name); } catch (Exception e) { stopper.onException(mbeanServer, e); } } stopper.stop(getManagementContext()); } log.info("ActiveMQ JMS Message Broker (" + getBrokerName() + ") stopped: "+broker); stopper.throwFirstException(); } // Properties // ------------------------------------------------------------------------- public Broker getBroker() throws Exception { if (broker == null) { log.info("ActiveMQ " + ActiveMQConnectionMetaData.PROVIDER_VERSION + " JMS Message Broker (" + getBrokerName() + ") is starting"); log.info("For help or more information please see: http://incubator.apache.org/activemq/"); broker = createBroker(); } return broker; } public String getBrokerName() { return brokerName; } /** * Sets the name of this broker; which must be unique in the network */ public void setBrokerName(String brokerName) { this.brokerName = brokerName; } public PersistenceAdapterFactory getPersistenceFactory() { if (persistenceFactory == null) { persistenceFactory = createPersistenceFactory(); } return persistenceFactory; } public File getDataDirectory() { if (dataDirectory == null) { dataDirectory = new File(new File("activemq-data"), getBrokerName() .replaceAll("[^a-zA-Z0-9\\.\\_\\-]", "_")); } return dataDirectory; } /** * Sets the directory in which the data files will be stored by default for * the JDBC and Journal persistence adaptors. * * @param dataDirectory * the directory to store data files */ public void setDataDirectory(File dataDirectory) { this.dataDirectory = dataDirectory; } public void setPersistenceFactory(PersistenceAdapterFactory persistenceFactory) { this.persistenceFactory = persistenceFactory; } public boolean isPersistent() { return persistent; } /** * Sets whether or not persistence is enabled or disabled. */ public void setPersistent(boolean persistent) { this.persistent = persistent; } public boolean isPopulateJMSXUserID() { return populateJMSXUserID; } /** * Sets whether or not the broker should populate the JMSXUserID header. */ public void setPopulateJMSXUserID(boolean populateJMSXUserID) { this.populateJMSXUserID = populateJMSXUserID; } public UsageManager getMemoryManager() { if (memoryManager == null) { memoryManager = new UsageManager(); memoryManager.setLimit(1024 * 1024 * 20); // Default to 20 Meg // limit } return memoryManager; } public void setMemoryManager(UsageManager memoryManager) { this.memoryManager = memoryManager; } public PersistenceAdapter getPersistenceAdapter() throws IOException { if (persistenceAdapter == null) { persistenceAdapter = createPersistenceAdapter(); } return persistenceAdapter; } /** * Sets the persistence adaptor implementation to use for this broker */ public void setPersistenceAdapter(PersistenceAdapter persistenceAdapter) { this.persistenceAdapter = persistenceAdapter; } public TaskRunnerFactory getTaskRunnerFactory() { if (taskRunnerFactory == null) { taskRunnerFactory = new TaskRunnerFactory(); } return taskRunnerFactory; } public void setTaskRunnerFactory(TaskRunnerFactory taskRunnerFactory) { this.taskRunnerFactory = taskRunnerFactory; } public boolean isUseJmx() { return useJmx; } /** * Sets whether or not the Broker's services should be exposed into JMX or * not. */ public void setUseJmx(boolean useJmx) { this.useJmx = useJmx; } public ObjectName getBrokerObjectName() throws IOException { if (brokerObjectName == null) { brokerObjectName = createBrokerObjectName(); } return brokerObjectName; } /** * Sets the JMX ObjectName for this broker */ public void setBrokerObjectName(ObjectName brokerObjectName) { this.brokerObjectName = brokerObjectName; } public ManagementContext getManagementContext() { if (managementContext == null) { managementContext = new ManagementContext(); } return managementContext; } public void setManagementContext(ManagementContext managementContext) { this.managementContext = managementContext; } public String[] getNetworkConnectorURIs() { return networkConnectorURIs; } public void setNetworkConnectorURIs(String[] networkConnectorURIs) { this.networkConnectorURIs = networkConnectorURIs; } public String[] getTransportConnectorURIs() { return transportConnectorURIs; } public void setTransportConnectorURIs(String[] transportConnectorURIs) { this.transportConnectorURIs = transportConnectorURIs; } /** * @return Returns the jmsBridgeConnectors. */ public JmsConnector[] getJmsBridgeConnectors(){ return jmsBridgeConnectors; } /** * @param jmsBridgeConnectors The jmsBridgeConnectors to set. */ public void setJmsBridgeConnectors(JmsConnector[] jmsConnectors){ this.jmsBridgeConnectors=jmsConnectors; } public boolean isUseLoggingForShutdownErrors() { return useLoggingForShutdownErrors; } /** * Sets whether or not we should use commons-logging when reporting errors * when shutting down the broker */ public void setUseLoggingForShutdownErrors(boolean useLoggingForShutdownErrors) { this.useLoggingForShutdownErrors = useLoggingForShutdownErrors; } public boolean isUseShutdownHook() { return useShutdownHook; } /** * Sets whether or not we should use a shutdown handler to close down the * broker cleanly if the JVM is terminated. It is recommended you leave this * enabled. */ public void setUseShutdownHook(boolean useShutdownHook) { this.useShutdownHook = useShutdownHook; } public List getTransportConnectors() { return new ArrayList(transportConnectors); } /** * Sets the transport connectors which this broker will listen on for new * clients */ public void setTransportConnectors(List transportConnectors) throws Exception { for (Iterator iter = transportConnectors.iterator(); iter.hasNext();) { TransportConnector connector = (TransportConnector) iter.next(); addConnector(connector); } } public List getNetworkConnectors() { return new ArrayList(networkConnectors); } public List getProxyConnectors() { return new ArrayList(proxyConnectors); } /** * Sets the network connectors which this broker will use to connect to * other brokers in a federated network */ public void setNetworkConnectors(List networkConnectors) throws Exception { for (Iterator iter = networkConnectors.iterator(); iter.hasNext();) { NetworkConnector connector = (NetworkConnector) iter.next(); addNetworkConnector(connector); } } /** * Sets the network connectors which this broker will use to connect to * other brokers in a federated network */ public void setProxyConnectors(List proxyConnectors) throws Exception { for (Iterator iter = proxyConnectors.iterator(); iter.hasNext();) { ProxyConnector connector = (ProxyConnector) iter.next(); addProxyConnector(connector); } } public PolicyMap getDestinationPolicy() { return destinationPolicy; } /** * Sets the destination specific policies available either for exact * destinations or for wildcard areas of destinations. */ public void setDestinationPolicy(PolicyMap policyMap) { this.destinationPolicy = policyMap; } public BrokerPlugin[] getPlugins() { return plugins; } /** * Sets a number of broker plugins to install such as for security authentication or authorization */ public void setPlugins(BrokerPlugin[] plugins) { this.plugins = plugins; } public MessageAuthorizationPolicy getMessageAuthorizationPolicy() { return messageAuthorizationPolicy; } /** * Sets the policy used to decide if the current connection is authorized to consume * a given message */ public void setMessageAuthorizationPolicy(MessageAuthorizationPolicy messageAuthorizationPolicy) { this.messageAuthorizationPolicy = messageAuthorizationPolicy; } /** * Delete all messages from the persistent store * @throws IOException */ public void deleteAllMessages() throws IOException{ getPersistenceAdapter().deleteAllMessages(); } // Implementation methods // ------------------------------------------------------------------------- /** * Handles any lazy-creation helper properties which are added to make * things easier to configure inside environments such as Spring * * @throws Exception */ protected void processHelperProperties() throws Exception { if (transportConnectorURIs != null) { for (int i = 0; i < transportConnectorURIs.length; i++) { String uri = transportConnectorURIs[i]; addConnector(uri); } } if (networkConnectorURIs != null) { for (int i = 0; i < networkConnectorURIs.length; i++) { String uri = networkConnectorURIs[i]; addNetworkConnector(uri); } } if (proxyConnectorURIs != null) { for (int i = 0; i < proxyConnectorURIs.length; i++) { String uri = proxyConnectorURIs[i]; addProxyConnector(uri); } } if (jmsBridgeConnectors != null){ for (int i = 0; i < jmsBridgeConnectors.length; i++){ addJmsConnector(jmsBridgeConnectors[i]); } } } protected void registerConnectorMBean(TransportConnector connector) throws IOException, URISyntaxException { MBeanServer mbeanServer = getManagementContext().getMBeanServer(); ConnectorViewMBean view = new ConnectorView(connector); try { ObjectName objectName = new ObjectName( managementContext.getJmxDomainName()+":"+ "BrokerName="+JMXSupport.encodeObjectNamePart(getBrokerName())+","+ "Type=Connector,"+ "ConnectorName="+JMXSupport.encodeObjectNamePart(connector.getName()) ); mbeanServer.registerMBean(view, objectName); registeredMBeanNames.add(objectName); } catch (Throwable e) { throw IOExceptionSupport.create("Broker could not be registered in JMX: " + e.getMessage(), e); } } protected void registerNetworkConnectorMBean(NetworkConnector connector) throws IOException { MBeanServer mbeanServer = getManagementContext().getMBeanServer(); NetworkConnectorViewMBean view = new NetworkConnectorView(connector); try { ObjectName objectName = new ObjectName( managementContext.getJmxDomainName()+":"+ "BrokerName="+JMXSupport.encodeObjectNamePart(getBrokerName())+","+ "Type=NetworkConnector,"+ "NetworkConnectorName="+JMXSupport.encodeObjectNamePart(connector.getName()) ); mbeanServer.registerMBean(view, objectName); registeredMBeanNames.add(objectName); } catch (Throwable e) { throw IOExceptionSupport.create("Broker could not be registered in JMX: " + e.getMessage(), e); } } protected void registerProxyConnectorMBean(ProxyConnector connector) throws IOException { MBeanServer mbeanServer = getManagementContext().getMBeanServer(); ProxyConnectorView view = new ProxyConnectorView(connector); try { ObjectName objectName = new ObjectName( managementContext.getJmxDomainName()+":"+ "BrokerName="+JMXSupport.encodeObjectNamePart(getBrokerName())+","+ "Type=ProxyConnector,"+ "ProxyConnectorName="+JMXSupport.encodeObjectNamePart(connector.getName()) ); mbeanServer.registerMBean(view, objectName); registeredMBeanNames.add(objectName); } catch (Throwable e) { throw IOExceptionSupport.create("Broker could not be registered in JMX: " + e.getMessage(), e); } } protected void registerFTConnectorMBean(MasterConnector connector) throws IOException { MBeanServer mbeanServer = getManagementContext().getMBeanServer(); FTConnectorView view = new FTConnectorView(connector); try { ObjectName objectName = new ObjectName( managementContext.getJmxDomainName()+":"+ "BrokerName="+JMXSupport.encodeObjectNamePart(getBrokerName())+","+ "Type=MasterConnector" ); mbeanServer.registerMBean(view, objectName); registeredMBeanNames.add(objectName); } catch (Throwable e) { throw IOExceptionSupport.create("Broker could not be registered in JMX: " + e.getMessage(), e); } } protected void registerJmsConnectorMBean(JmsConnector connector) throws IOException { MBeanServer mbeanServer = getManagementContext().getMBeanServer(); JmsConnectorView view = new JmsConnectorView(connector); try { ObjectName objectName = new ObjectName( managementContext.getJmxDomainName()+":"+ "BrokerName="+JMXSupport.encodeObjectNamePart(getBrokerName())+","+ "Type=JmsConnector,"+ "JmsConnectorName="+JMXSupport.encodeObjectNamePart(connector.getName()) ); mbeanServer.registerMBean(view, objectName); registeredMBeanNames.add(objectName); } catch (Throwable e) { throw IOExceptionSupport.create("Broker could not be registered in JMX: " + e.getMessage(), e); } } /** * Factory method to create a new broker * * @throws Exception * * @throws * @throws */ protected Broker createBroker() throws Exception { Broker regionBroker = createRegionBroker(); Broker broker = addInterceptors(regionBroker); // Add a filter that will stop access to the broker once stopped broker = new MutableBrokerFilter(broker) { public void stop() throws Exception { super.stop(); setNext(new ErrorBroker("Broker has been stopped: "+this) { // Just ignore additional stop actions. public void stop() throws Exception { } }); } }; if (isUseJmx()) { ManagedRegionBroker managedBroker = (ManagedRegionBroker) regionBroker; managedBroker.setContextBroker(broker); BrokerViewMBean view = new BrokerView(this, managedBroker); MBeanServer mbeanServer = getManagementContext().getMBeanServer(); ObjectName objectName = getBrokerObjectName(); mbeanServer.registerMBean(view, objectName); registeredMBeanNames.add(objectName); } return broker; } /** * Factory method to create the core region broker onto which interceptors * are added * * @throws Exception */ protected Broker createRegionBroker() throws Exception { // we must start the persistence adaptor before we can create the region // broker getPersistenceAdapter().setUsageManager(getMemoryManager()); getPersistenceAdapter().start(); RegionBroker regionBroker = null; if (isUseJmx()) { MBeanServer mbeanServer = getManagementContext().getMBeanServer(); regionBroker = new ManagedRegionBroker(this,mbeanServer, getBrokerObjectName(), getTaskRunnerFactory(), getMemoryManager(), getPersistenceAdapter()); } else { regionBroker = new RegionBroker(this,getTaskRunnerFactory(), getMemoryManager(), getPersistenceAdapter()); } regionBroker.setKeepDurableSubsActive(keepDurableSubsActive); regionBroker.setBrokerName(getBrokerName()); return regionBroker; } /** * Strategy method to add interceptors to the broker * * @throws IOException */ protected Broker addInterceptors(Broker broker) throws Exception { broker = new TransactionBroker(broker, getPersistenceAdapter().createTransactionStore()); broker = new AdvisoryBroker(broker); broker = new CompositeDestinationBroker(broker); if (isPopulateJMSXUserID()) { broker = new UserIDBroker(broker); } if (plugins != null) { for (int i = 0; i < plugins.length; i++) { BrokerPlugin plugin = plugins[i]; broker = plugin.installPlugin(broker); } } return broker; } protected PersistenceAdapter createPersistenceAdapter() throws IOException { if (isPersistent()) { return getPersistenceFactory().createPersistenceAdapter(); } else { return new MemoryPersistenceAdapter(); } } protected DefaultPersistenceAdapterFactory createPersistenceFactory() { DefaultPersistenceAdapterFactory factory = new DefaultPersistenceAdapterFactory(); factory.setDataDirectory(getDataDirectory()); factory.setTaskRunnerFactory(getTaskRunnerFactory()); return factory; } protected ObjectName createBrokerObjectName() throws IOException { try { return new ObjectName( getManagementContext().getJmxDomainName()+":"+ "BrokerName="+JMXSupport.encodeObjectNamePart(getBrokerName())+","+ "Type=Broker" ); } catch (Throwable e) { throw IOExceptionSupport.create("Invalid JMX broker name: " + brokerName, e); } } protected TransportConnector createTransportConnector(Broker broker, URI brokerURI) throws Exception { TransportServer transport = TransportFactory.bind(getBrokerName(),brokerURI); return new TransportConnector(broker, transport); } /** * Extracts the port from the options */ protected Object getPort(Map options) { Object port = options.get("port"); if (port == null) { port = DEFAULT_PORT; log.warn("No port specified so defaulting to: " + port); } return port; } protected void addShutdownHook() { if (useShutdownHook) { shutdownHook = new Thread("ActiveMQ ShutdownHook") { public void run() { containerShutdown(); } }; Runtime.getRuntime().addShutdownHook(shutdownHook); } } protected void removeShutdownHook() { if (shutdownHook != null) { try { Runtime.getRuntime().removeShutdownHook(shutdownHook); } catch (Exception e) { log.debug("Caught exception, must be shutting down: " + e); } } } /** * Causes a clean shutdown of the container when the VM is being shut down */ protected void containerShutdown() { try { stop(); } catch (IOException e) { Throwable linkedException = e.getCause(); if (linkedException != null) { logError("Failed to shut down: " + e + ". Reason: " + linkedException, linkedException); } else { logError("Failed to shut down: " + e, e); } if (!useLoggingForShutdownErrors) { e.printStackTrace(System.err); } } catch (Exception e) { logError("Failed to shut down: " + e, e); } } protected void logError(String message, Throwable e) { if (useLoggingForShutdownErrors) { log.error("Failed to shut down: " + e); } else { System.err.println("Failed to shut down: " + e); } } /** * Start all transport and network connections, proxies and bridges * @throws Exception */ protected void startAllConnectors() throws Exception{ if (!isSlave()){ for (Iterator iter = getTransportConnectors().iterator(); iter.hasNext();) { TransportConnector connector = (TransportConnector) iter.next(); startTransportConnector(connector); } for (Iterator iter = getNetworkConnectors().iterator(); iter.hasNext();) { NetworkConnector connector = (NetworkConnector) iter.next(); connector.setBrokerName(getBrokerName()); connector.setDurableDestinations(getBroker().getDurableDestinations()); connector.start(); } for (Iterator iter = getProxyConnectors().iterator(); iter.hasNext();) { ProxyConnector connector = (ProxyConnector) iter.next(); connector.start(); } for (Iterator iter = jmsConnectors.iterator(); iter.hasNext();) { JmsConnector connector = (JmsConnector) iter.next(); connector.start(); } } } protected void startTransportConnector(TransportConnector connector) throws Exception { connector.setBroker(getBroker()); connector.setBrokerName(getBrokerName()); connector.setTaskRunnerFactory(getTaskRunnerFactory()); MessageAuthorizationPolicy policy = getMessageAuthorizationPolicy(); if (policy != null) { connector.setMessageAuthorizationPolicy(policy); } if (isUseJmx()) { connector = connector.asManagedConnector(getManagementContext().getMBeanServer(), getBrokerObjectName()); registerConnectorMBean(connector); } connector.start(); } public boolean isDeleteAllMessagesOnStartup() { return deleteAllMessagesOnStartup; } /** * Sets whether or not all messages are deleted on startup - mostly only * useful for testing. */ public void setDeleteAllMessagesOnStartup(boolean deletePersistentMessagesOnStartup) { this.deleteAllMessagesOnStartup = deletePersistentMessagesOnStartup; } public URI getVmConnectorURI() { if (vmConnectorURI == null) { try { vmConnectorURI = new URI("vm://" + getBrokerName()); } catch (URISyntaxException e) { } } return vmConnectorURI; } public void setVmConnectorURI(URI vmConnectorURI) { this.vmConnectorURI = vmConnectorURI; } /** * @return Returns the shutdownOnMasterFailure. */ public boolean isShutdownOnMasterFailure(){ return shutdownOnMasterFailure; } /** * @param shutdownOnMasterFailure The shutdownOnMasterFailure to set. */ public void setShutdownOnMasterFailure(boolean shutdownOnMasterFailure){ this.shutdownOnMasterFailure=shutdownOnMasterFailure; } public boolean isKeepDurableSubsActive() { return keepDurableSubsActive; } public void setKeepDurableSubsActive(boolean keepDurableSubsActive) { this.keepDurableSubsActive = keepDurableSubsActive; } }
List the unique id of the broker when it's started and stopped. git-svn-id: 7f3df76e74c7ad56904d6048df705810748eb1a6@391821 13f79535-47bb-0310-9956-ffa450edef68
activemq-core/src/main/java/org/apache/activemq/broker/BrokerService.java
List the unique id of the broker when it's started and stopped.
<ide><path>ctivemq-core/src/main/java/org/apache/activemq/broker/BrokerService.java <ide> import org.apache.activemq.broker.jmx.ProxyConnectorView; <ide> import org.apache.activemq.broker.region.RegionBroker; <ide> import org.apache.activemq.broker.region.policy.PolicyMap; <add>import org.apache.activemq.command.BrokerId; <ide> import org.apache.activemq.memory.UsageManager; <ide> import org.apache.activemq.network.ConnectionFilter; <ide> import org.apache.activemq.network.DiscoveryNetworkConnector; <ide> <ide> private boolean keepDurableSubsActive; <ide> <add> private BrokerId brokerId; <add> <ide> /** <ide> * Adds a new transport connector for the given bind address <ide> * <ide> <ide> startAllConnectors(); <ide> <del> <del> log.info("ActiveMQ JMS Message Broker (" + getBrokerName() + ") started"); <add> brokerId = broker.getBrokerId(); <add> log.info("ActiveMQ JMS Message Broker (" + getBrokerName()+", "+brokerId+") started"); <ide> } <ide> catch (Exception e) { <ide> log.error("Failed to start ActiveMQ JMS Message Broker. Reason: " + e, e); <ide> if (! started.compareAndSet(true, false)) { <ide> return; <ide> } <del> log.info("ActiveMQ Message Broker (" + getBrokerName() + ") is shutting down"); <add> log.info("ActiveMQ Message Broker (" + getBrokerName()+", "+brokerId+") is shutting down"); <ide> BrokerRegistry.getInstance().unbind(getBrokerName()); <ide> <ide> removeShutdownHook(); <ide> stopper.stop(getManagementContext()); <ide> } <ide> <del> log.info("ActiveMQ JMS Message Broker (" + getBrokerName() + ") stopped: "+broker); <add> log.info("ActiveMQ JMS Message Broker (" + getBrokerName()+", "+brokerId+") stopped"); <ide> <ide> stopper.throwFirstException(); <ide> }
Java
apache-2.0
c83301aef9db302be74480701197c3c0d12eb637
0
cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x
/* * Copyright 2002-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.springframework.aop.config; import java.util.ArrayList; import java.util.List; import org.springframework.aop.aspectj.autoproxy.AspectJInvocationContextExposingAdvisorAutoProxyCreator; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.parsing.BeanComponentDefinition; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.core.Ordered; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; /** * Utility class for handling registration of auto-proxy creators used internally * by the '<code>aop</code>' namespace tags. * * <p>Only a single auto-proxy creator can be registered and multiple tags may wish * to register different concrete implementations. As such this class wraps a simple * escalation protocol, allowing clases to request a particular auto-proxy creator * and know that class, <code>or a subclass thereof</code>, will eventually be resident * in the application context. * * @author Rob Harrop * @author Juergen Hoeller * @since 2.0 */ public abstract class AopNamespaceUtils { /** * The bean name of the internally managed auto-proxy creator. */ public static final String AUTO_PROXY_CREATOR_BEAN_NAME = "org.springframework.aop.config.internalAutoProxyCreator"; /** * The class name of the '<code>AnnotationAwareAspectJAutoProxyCreator</code>' class. * Only available with AspectJ and Java 5. */ public static final String ASPECTJ_AUTO_PROXY_CREATOR_CLASS_NAME = "org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"; /** * Stores the auto proxy creator classes in escalation order. */ private static final List APC_PRIORITY_LIST = new ArrayList(); /** * Setup the escalation list. */ static { APC_PRIORITY_LIST.add(DefaultAdvisorAutoProxyCreator.class.getName()); APC_PRIORITY_LIST.add(AspectJInvocationContextExposingAdvisorAutoProxyCreator.class.getName()); APC_PRIORITY_LIST.add(ASPECTJ_AUTO_PROXY_CREATOR_CLASS_NAME); } public static void registerAutoProxyCreatorIfNecessary(ParserContext parserContext, Object sourceElement) { registryOrEscalateApcAsRequired(DefaultAdvisorAutoProxyCreator.class, parserContext, sourceElement); } public static void registerAspectJAutoProxyCreatorIfNecessary(ParserContext parserContext, Object sourceElement) { registryOrEscalateApcAsRequired( AspectJInvocationContextExposingAdvisorAutoProxyCreator.class, parserContext, sourceElement); } public static void registerAtAspectJAutoProxyCreatorIfNecessary(ParserContext parserContext, Object sourceElement) { Class cls = getAspectJAutoProxyCreatorClassIfPossible(); registryOrEscalateApcAsRequired(cls, parserContext, sourceElement); } private static void registryOrEscalateApcAsRequired(Class cls, ParserContext parserContext, Object sourceElement) { Assert.notNull(parserContext, "ParserContext must not be null"); BeanDefinitionRegistry registry = parserContext.getRegistry(); if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) { BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME); if (cls.getName().equals(apcDefinition.getBeanClassName())) { return; } int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName()); int requiredPriority = findPriorityForClass(cls.getName()); if (currentPriority < requiredPriority) { apcDefinition.setBeanClassName(cls.getName()); } } else { RootBeanDefinition beanDefinition = new RootBeanDefinition(cls); beanDefinition.setSource(parserContext.extractSource(sourceElement)); beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition); beanDefinition.getPropertyValues().addPropertyValue("order", new Integer(Ordered.HIGHEST_PRECEDENCE)); // Notify of bean registration. BeanComponentDefinition componentDefinition = new BeanComponentDefinition(beanDefinition, AUTO_PROXY_CREATOR_BEAN_NAME); parserContext.getReaderContext().fireComponentRegistered(componentDefinition); } } public static void forceAutoProxyCreatorToUseClassProxying(BeanDefinitionRegistry registry) { if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) { BeanDefinition definition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME); definition.getPropertyValues().addPropertyValue("proxyTargetClass", Boolean.TRUE); } } private static Class getAspectJAutoProxyCreatorClassIfPossible() { try { return ClassUtils.forName(ASPECTJ_AUTO_PROXY_CREATOR_CLASS_NAME); } catch (Throwable ex) { throw new IllegalStateException( "Unable to load class [" + ASPECTJ_AUTO_PROXY_CREATOR_CLASS_NAME + "]. Are you running on Java 1.5+? Root cause: " + ex); } } private static final int findPriorityForClass(String className) { Assert.notNull(className, "Class name must not be null"); for (int i = 0; i < APC_PRIORITY_LIST.size(); i++) { String str = (String) APC_PRIORITY_LIST.get(i); if (className.equals(str)) { return i; } } throw new IllegalArgumentException( "Class name [" + className + "] is not a known auto-proxy creator class"); } }
src/org/springframework/aop/config/AopNamespaceUtils.java
/* * Copyright 2002-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.springframework.aop.config; import java.util.ArrayList; import java.util.List; import org.springframework.aop.aspectj.autoproxy.AspectJInvocationContextExposingAdvisorAutoProxyCreator; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.parsing.BeanComponentDefinition; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.core.Ordered; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; /** * Utility class for handling registration of auto-proxy creators used internally * by the '<code>aop</code>' namespace tags. * * <p>Only a single auto-proxy creator can be registered and multiple tags may wish * to register different concrete implementations. As such this class wraps a simple * escalation protocol, allowing clases to request a particular auto-proxy creator * and know that class, <code>or a subclass thereof</code>, will eventually be resident * in the application context. * * @author Rob Harrop * @author Juergen Hoeller * @since 2.0 */ public abstract class AopNamespaceUtils { /** * The bean name of the internally managed auto-proxy creator. */ public static final String AUTO_PROXY_CREATOR_BEAN_NAME = "org.springframework.aop.config.internalAutoProxyCreator"; /** * The class name of the '<code>AnnotationAwareAspectJAutoProxyCreator</code>' class. * Only available with AspectJ and Java 5. */ public static final String ASPECTJ_AUTO_PROXY_CREATOR_CLASS_NAME = "org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"; /** * Stores the auto proxy creator classes in escalation order. */ private static final List APC_PRIORITY_LIST = new ArrayList(); /** * Setup the escalation list. */ static { APC_PRIORITY_LIST.add(DefaultAdvisorAutoProxyCreator.class.getName()); APC_PRIORITY_LIST.add(AspectJInvocationContextExposingAdvisorAutoProxyCreator.class.getName()); APC_PRIORITY_LIST.add(ASPECTJ_AUTO_PROXY_CREATOR_CLASS_NAME); } public static void registerAutoProxyCreatorIfNecessary(ParserContext parserContext, Object sourceElement) { registryOrEscalateApcAsRequired(DefaultAdvisorAutoProxyCreator.class, parserContext, sourceElement); } public static void registerAspectJAutoProxyCreatorIfNecessary(ParserContext parserContext, Object sourceElement) { registryOrEscalateApcAsRequired( AspectJInvocationContextExposingAdvisorAutoProxyCreator.class, parserContext, sourceElement); } public static void registerAtAspectJAutoProxyCreatorIfNecessary(ParserContext parserContext, Object sourceElement) { Class cls = getAspectJAutoProxyCreatorClassIfPossible(); if (cls == null) { throw new IllegalStateException("Unable to register AspectJ AutoProxyCreator. Cannot find class [" + ASPECTJ_AUTO_PROXY_CREATOR_CLASS_NAME + "]. Are you running on Java 5.0+?"); } registryOrEscalateApcAsRequired(cls, parserContext, sourceElement); } private static void registryOrEscalateApcAsRequired(Class cls, ParserContext parserContext, Object sourceElement) { Assert.notNull(parserContext, "ParserContext must not be null"); BeanDefinitionRegistry registry = parserContext.getRegistry(); if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) { BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME); if (cls.getName().equals(apcDefinition.getBeanClassName())) { return; } int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName()); int requiredPriority = findPriorityForClass(cls.getName()); if (currentPriority < requiredPriority) { apcDefinition.setBeanClassName(cls.getName()); } } else { RootBeanDefinition beanDefinition = new RootBeanDefinition(cls); beanDefinition.setSource(parserContext.extractSource(sourceElement)); beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition); beanDefinition.getPropertyValues().addPropertyValue("order", new Integer(Ordered.HIGHEST_PRECEDENCE)); // Notify of bean registration. BeanComponentDefinition componentDefinition = new BeanComponentDefinition(beanDefinition, AUTO_PROXY_CREATOR_BEAN_NAME); parserContext.getReaderContext().fireComponentRegistered(componentDefinition); } } public static void forceAutoProxyCreatorToUseClassProxying(BeanDefinitionRegistry registry) { if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) { BeanDefinition definition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME); definition.getPropertyValues().addPropertyValue("proxyTargetClass", Boolean.TRUE); } } private static Class getAspectJAutoProxyCreatorClassIfPossible() { try { return ClassUtils.forName(ASPECTJ_AUTO_PROXY_CREATOR_CLASS_NAME); } catch (ClassNotFoundException ex) { return null; } } private static final int findPriorityForClass(String className) { Assert.notNull(className, "Class name must not be null"); for (int i = 0; i < APC_PRIORITY_LIST.size(); i++) { String str = (String) APC_PRIORITY_LIST.get(i); if (className.equals(str)) { return i; } } throw new IllegalArgumentException( "Class name [" + className + "] is not a known auto-proxy creator class"); } }
catch Throwable instead of just ClassNotFoundException; consistent exception handling git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@11843 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8
src/org/springframework/aop/config/AopNamespaceUtils.java
catch Throwable instead of just ClassNotFoundException; consistent exception handling
<ide><path>rc/org/springframework/aop/config/AopNamespaceUtils.java <ide> <ide> public static void registerAtAspectJAutoProxyCreatorIfNecessary(ParserContext parserContext, Object sourceElement) { <ide> Class cls = getAspectJAutoProxyCreatorClassIfPossible(); <del> if (cls == null) { <del> throw new IllegalStateException("Unable to register AspectJ AutoProxyCreator. Cannot find class [" + <del> ASPECTJ_AUTO_PROXY_CREATOR_CLASS_NAME + "]. Are you running on Java 5.0+?"); <del> } <ide> registryOrEscalateApcAsRequired(cls, parserContext, sourceElement); <ide> } <ide> <ide> try { <ide> return ClassUtils.forName(ASPECTJ_AUTO_PROXY_CREATOR_CLASS_NAME); <ide> } <del> catch (ClassNotFoundException ex) { <del> return null; <add> catch (Throwable ex) { <add> throw new IllegalStateException( <add> "Unable to load class [" + ASPECTJ_AUTO_PROXY_CREATOR_CLASS_NAME + <add> "]. Are you running on Java 1.5+? Root cause: " + ex); <ide> } <ide> } <ide>
Java
mit
ae2f0b5b8a581d0d555e496b37908b9787856b3f
0
zhangtdavid/SimCity
package city.tests.mock; import utilities.LoggedEvent; import city.Application.BANK_SERVICE; import city.Application.TRANSACTION_TYPE; import city.MockRole; import city.interfaces.BankCustomer; import city.roles.BankTellerRole; public class MockBankCustomer extends MockRole implements BankCustomer { public MockBankCustomer() { // TODO Auto-generated method stub } @Override public void msgDepositCompleted() { log.add(new LoggedEvent("Received msgDeposit completed")); // TODO Auto-generated method stub } @Override public void msgWhatDoYouWant(int boothnumber, BankTellerRole tell) { log.add(new LoggedEvent("Received msgWhatDoYouWant")); // TODO Auto-generated method stub } @Override public void msgAccountCreated(int acct) { log.add(new LoggedEvent("Received msgAccountCreated " + acct)); // TODO Auto-generated method stub } @Override public void msgHereIsWithdrawal(int money) { log.add(new LoggedEvent("Received msgHereIsWithdrawal " + money)); // TODO Auto-generated method stub } @Override public void msgLoanGranted(int loanMoney) { log.add(new LoggedEvent("Received msgLoanGranted " + loanMoney)); // TODO Auto-generated method stub } @Override public void msgTransactionDenied() { log.add(new LoggedEvent("Received msgTransactionDenied")); // TODO Auto-generated method stub } @Override public void setActive(BANK_SERVICE atmdeposit, int i, TRANSACTION_TYPE business) { // TODO Auto-generated method stub } }
src/city/tests/mock/MockBankCustomer.java
package city.tests.mock; import utilities.LoggedEvent; import city.MockRole; import city.interfaces.BankCustomer; import city.roles.BankTellerRole; public class MockBankCustomer extends MockRole implements BankCustomer { public MockBankCustomer() { // TODO Auto-generated method stub } @Override public void msgDepositCompleted() { log.add(new LoggedEvent("Received msgDeposit completed")); // TODO Auto-generated method stub } @Override public void msgWhatDoYouWant(int boothnumber, BankTellerRole tell) { log.add(new LoggedEvent("Received msgWhatDoYouWant")); // TODO Auto-generated method stub } @Override public void msgAccountCreated(int acct) { log.add(new LoggedEvent("Received msgAccountCreated " + acct)); // TODO Auto-generated method stub } @Override public void msgHereIsWithdrawal(int money) { log.add(new LoggedEvent("Received msgHereIsWithdrawal " + money)); // TODO Auto-generated method stub } @Override public void msgLoanGranted(int loanMoney) { log.add(new LoggedEvent("Received msgLoanGranted " + loanMoney)); // TODO Auto-generated method stub } @Override public void msgTransactionDenied() { log.add(new LoggedEvent("Received msgTransactionDenied")); // TODO Auto-generated method stub } }
updated mockbankcustomer to reflect changes in interface
src/city/tests/mock/MockBankCustomer.java
updated mockbankcustomer to reflect changes in interface
<ide><path>rc/city/tests/mock/MockBankCustomer.java <ide> package city.tests.mock; <ide> <ide> import utilities.LoggedEvent; <add>import city.Application.BANK_SERVICE; <add>import city.Application.TRANSACTION_TYPE; <ide> import city.MockRole; <ide> import city.interfaces.BankCustomer; <ide> import city.roles.BankTellerRole; <ide> <ide> } <ide> <add> @Override <add> public void setActive(BANK_SERVICE atmdeposit, int i, <add> TRANSACTION_TYPE business) { <add> // TODO Auto-generated method stub <add> <add> } <add> <ide> }
Java
apache-2.0
23a39263d4b7af5a79d05f8320b34b28632c2330
0
sjwall/MaterialTapTargetPrompt
/* * Copyright (C) 2017 Samuel Wall * * 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 uk.co.samuelwall.materialtaptargetprompt; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PointF; import android.graphics.RectF; public class RectanglePromptBackground extends PromptBackground { private RectF mBounds, mBaseBounds; private Paint mPaint; private int mBaseColourAlpha; private float mRx, mRy; public RectanglePromptBackground() { mPaint = new Paint(); mPaint.setAntiAlias(true); mBounds = new RectF(); mBaseBounds = new RectF(); mRx = mRy = 40; } public void setCornerRadius(final float rx, final float ry) { mRx = rx; mRy = ry; } @Override public void setBackgroundColour(int colour) { mPaint.setColor(colour); mBaseColourAlpha = Color.alpha(colour); mPaint.setAlpha(mBaseColourAlpha); } @Override public void prepare(MaterialTapTargetPrompt prompt, float maxTextWidth) { final PointF focalCentre = prompt.getFocalCentre(); float x1, x2, y1, y2; final float focalRadius = prompt.mBaseFocalRadius + prompt.mTextPadding; if (prompt.mVerticalTextPositionAbove) { y1 = prompt.mView.mPrimaryTextTop - prompt.mTextPadding; y2 = focalCentre.y + focalRadius; } else { y1 = focalCentre.y - focalRadius; y2 = prompt.mView.mPrimaryTextTop + prompt.mView.mPrimaryTextLayout.getHeight(); if (prompt.mView.mSecondaryTextLayout != null) { y2 += prompt.mView.mSecondaryTextLayout.getHeight() + prompt.mView.mTextSeparation; } y2 += prompt.mTextPadding; } x1 = Math.min(prompt.mView.mPrimaryTextLeft - prompt.mTextPadding, focalCentre.x - focalRadius); x2 = Math.max(prompt.mView.mPrimaryTextLeft + maxTextWidth + prompt.mTextPadding, focalCentre.x + focalRadius); mBaseBounds.set(x1, y1, x2, y2); } @Override public void update(MaterialTapTargetPrompt prompt, float revealAmount, float alphaModifier) { mPaint.setAlpha((int) (mBaseColourAlpha * alphaModifier)); mBounds.set(mBaseBounds); } @Override public void draw(Canvas canvas) { canvas.drawRoundRect(mBounds, mRx, mRy, mPaint); } @Override public boolean isPointInShape(float x, float y) { return mBounds.contains(x, y); } }
library/src/main/java/uk/co/samuelwall/materialtaptargetprompt/RectanglePromptBackground.java
/* * Copyright (C) 2017 Samuel Wall * * 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 uk.co.samuelwall.materialtaptargetprompt; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PointF; import android.graphics.RectF; public class RectanglePromptBackground extends PromptBackground { private RectF mBounds, mBaseBounds; private Paint mPaint; private int mBaseColourAlpha; private float rx = 40, ry = 40; public RectanglePromptBackground() { mPaint = new Paint(); mPaint.setAntiAlias(true); mBounds = new RectF(); mBaseBounds = new RectF(); } @Override public void setBackgroundColour(int colour) { mPaint.setColor(colour); mBaseColourAlpha = Color.alpha(colour); mPaint.setAlpha(mBaseColourAlpha); } @Override public void prepare(MaterialTapTargetPrompt prompt, float maxTextWidth) { final PointF focalCentre = prompt.getFocalCentre(); float x1, x2, y1, y2; final float focalRadius = prompt.mBaseFocalRadius + prompt.mTextPadding; if (prompt.mVerticalTextPositionAbove) { y1 = prompt.mView.mPrimaryTextTop - prompt.mTextPadding; y2 = focalCentre.y + focalRadius; } else { y1 = focalCentre.y - focalRadius; y2 = prompt.mView.mPrimaryTextTop + prompt.mView.mPrimaryTextLayout.getHeight(); if (prompt.mView.mSecondaryTextLayout != null) { y2 += prompt.mView.mSecondaryTextLayout.getHeight() + prompt.mView.mTextSeparation; } y2 += prompt.mTextPadding; } x1 = Math.min(prompt.mView.mPrimaryTextLeft - prompt.mTextPadding, focalCentre.x - focalRadius); x2 = Math.max(prompt.mView.mPrimaryTextLeft + maxTextWidth + prompt.mTextPadding, focalCentre.x + focalRadius); mBaseBounds.set(x1, y1, x2, y2); } @Override public void update(MaterialTapTargetPrompt prompt, float revealAmount, float alphaModifier) { mPaint.setAlpha((int) (mBaseColourAlpha * alphaModifier)); mBounds.set(mBaseBounds); } @Override public void draw(Canvas canvas) { canvas.drawRoundRect(mBounds, rx, ry, mPaint); } @Override public boolean isPointInShape(float x, float y) { return mBounds.contains(x, y); } }
Added setter for rectangle prompt background corner radius
library/src/main/java/uk/co/samuelwall/materialtaptargetprompt/RectanglePromptBackground.java
Added setter for rectangle prompt background corner radius
<ide><path>ibrary/src/main/java/uk/co/samuelwall/materialtaptargetprompt/RectanglePromptBackground.java <ide> private RectF mBounds, mBaseBounds; <ide> private Paint mPaint; <ide> private int mBaseColourAlpha; <del> private float rx = 40, ry = 40; <add> private float mRx, mRy; <ide> <ide> public RectanglePromptBackground() <ide> { <ide> mPaint.setAntiAlias(true); <ide> mBounds = new RectF(); <ide> mBaseBounds = new RectF(); <add> mRx = mRy = 40; <add> } <add> <add> public void setCornerRadius(final float rx, final float ry) <add> { <add> mRx = rx; <add> mRy = ry; <ide> } <ide> <ide> @Override <ide> @Override <ide> public void draw(Canvas canvas) <ide> { <del> canvas.drawRoundRect(mBounds, rx, ry, mPaint); <add> canvas.drawRoundRect(mBounds, mRx, mRy, mPaint); <ide> } <ide> <ide> @Override
JavaScript
mit
0f248edd214f1c552bd9b0d2f3cc3636d9d42956
0
t3b/t3b_template,t3b/t3b_template,t3b/t3b_template,t3b/t3b_template,t3b/t3b_template
/** * Grunt-Replace * @description Replace inline patterns with variables. * @docs https://npmjs.org/package/grunt-replace */ var config = require("../Config"), deployStrings = { requireJSLibSourceFile: config.JavaScripts.paths.devDir + "/" + config.JavaScripts.requireJS.libSourceFile + ".js", requireJsAttributeDeploy: "data-main=\"typo3conf/ext/" + config.package.name + "/" + config.JavaScripts.paths.devDir + "/" + config.JavaScripts.requireJS.config + "\"", requireJsAttributeLive: "data-mainJs" }; module.exports = function(grunt) { "use strict"; return { "preInit" : { "src" : [ "bower.json" ], "overwrite" : true, "replacements" : [{ "from" : config.defaultName, "to" : config.package.name }] }, "init" : { "src" : [ "bower.json", "ext_emconf.php", "ext_tables.php", "Configuration/**/*.ts", "Configuration/**/*.txt", "Documentation/Private/Template/index.html", config.paths.private + "/Elements/**/*.html", config.paths.private + "/Layouts/**/*.html", config.paths.private + "/Partials/**/*.html", config.paths.private + "/Templates/**/*.html", config.paths.private + "/Sass/**/*.scss", config.paths.private + "/Sass/styleguide.md" ], "overwrite" : true, "replacements" : [{ "from" : "<!= pkg.name !>", "to" : config.package.name }, { "from" : "<!= pkg.description !>", "to" : config.package.description }, { "from" : "<!= pkg.homepage !>", "to" : config.package.homepage }, { "from" : "<!= pkg.version !>", "to" : config.package.version }, { "from" : "<!= pkg.author.name !>", "to" : config.package.author.name }, { "from" : "<!= pkg.author.email !>", "to" : config.package.author.email }, { "from" : "<!= pkg.author.company !>", "to" : config.package.author.company }, { "from" : "<!= date !>", "to" : grunt.template.today("dd-mm-yyyy hh:MM") }] }, "deploy" : { "src" : [config.paths.private + "/Layouts/*.html"], "overwrite" : true, "replacements" : [{ "from" : config.JavaScripts.modernizr.devSourceFile, "to" : config.JavaScripts.modernizr.buildDistFile }, { "from" : deployStrings.requireJSLibSourceFile, "to" : config.JavaScripts.requireJS.compileDistFile }, { "from" : deployStrings.requireJsAttributeDeploy, "to" : deployStrings.requireJsAttributeLive }] }, "dev" : { "src" : [config.paths.private + "/Layouts/*.html"], "overwrite" : true, "replacements" : [{ "from" : config.JavaScripts.modernizr.buildDistFile, "to" : config.JavaScripts.modernizr.devSourceFile }, { "from" : config.JavaScripts.requireJS.compileDistFile, "to" : deployStrings.requireJSLibSourceFile }, { "from" : deployStrings.requireJsAttributeLive, "to" : deployStrings.requireJsAttributeDeploy }] } }; };
Build/Grunt-Options/replace.js
/** * Grunt-Replace * @description Replace inline patterns with variables. * @docs https://npmjs.org/package/grunt-replace */ var config = require("../Config"), deployStrings = { requireJSLibSourceFile: config.JavaScripts.paths.devDir + "/" + config.JavaScripts.requireJS.libSourceFile + ".js", requireJsAttributeDeploy: "data-main=\"typo3conf/ext/" + config.package.name + "/" + config.JavaScripts.paths.devDir + "/" + config.JavaScripts.requireJS.config + "\"", requireJsAttributeLive: "data-mainJs" }; module.exports = function(grunt) { "use strict"; return { "preInit" : { "src" : [ "bower.json" ], "overwrite" : true, "replacements" : [{ "from" : config.defaultName, "to" : config.package.name }] }, "init" : { "src" : [ "bower.json", "ext_emconf.php", "ext_tables.php", "Configuration/**/*.ts", "Configuration/**/*.txt", config.paths.private + "/Elements/**/*.html", config.paths.private + "/Layouts/**/*.html", config.paths.private + "/Partials/**/*.html", config.paths.private + "/Templates/**/*.html", config.paths.private + "/Sass/**/*.scss", ], "overwrite" : true, "replacements" : [{ "from" : "<!= pkg.name !>", "to" : config.package.name }, { "from" : "<!= pkg.description !>", "to" : config.package.description }, { "from" : "<!= pkg.homepage !>", "to" : config.package.homepage }, { "from" : "<!= pkg.version !>", "to" : config.package.version }, { "from" : "<!= pkg.author.name !>", "to" : config.package.author.name }, { "from" : "<!= pkg.author.email !>", "to" : config.package.author.email }, { "from" : "<!= pkg.author.company !>", "to" : config.package.author.company }, { "from" : "<!= date !>", "to" : grunt.template.today("dd-mm-yyyy hh:MM") }] }, "deploy" : { "src" : [config.paths.private + "/Layouts/*.html"], "overwrite" : true, "replacements" : [{ "from" : config.JavaScripts.modernizr.devSourceFile, "to" : config.JavaScripts.modernizr.buildDistFile }, { "from" : deployStrings.requireJSLibSourceFile, "to" : config.JavaScripts.requireJS.compileDistFile }, { "from" : deployStrings.requireJsAttributeDeploy, "to" : deployStrings.requireJsAttributeLive }] }, "dev" : { "src" : [config.paths.private + "/Layouts/*.html"], "overwrite" : true, "replacements" : [{ "from" : config.JavaScripts.modernizr.buildDistFile, "to" : config.JavaScripts.modernizr.devSourceFile }, { "from" : config.JavaScripts.requireJS.compileDistFile, "to" : deployStrings.requireJSLibSourceFile }, { "from" : deployStrings.requireJsAttributeLive, "to" : deployStrings.requireJsAttributeDeploy }] } }; };
[TASK] Make sure the placeholder strings in the styleguide template gets replaced on 'grunt:init'
Build/Grunt-Options/replace.js
[TASK] Make sure the placeholder strings in the styleguide template gets replaced on 'grunt:init'
<ide><path>uild/Grunt-Options/replace.js <ide> "ext_tables.php", <ide> "Configuration/**/*.ts", <ide> "Configuration/**/*.txt", <add> "Documentation/Private/Template/index.html", <ide> config.paths.private + "/Elements/**/*.html", <ide> config.paths.private + "/Layouts/**/*.html", <ide> config.paths.private + "/Partials/**/*.html", <ide> config.paths.private + "/Templates/**/*.html", <ide> config.paths.private + "/Sass/**/*.scss", <add> config.paths.private + "/Sass/styleguide.md" <ide> ], <ide> "overwrite" : true, <ide> "replacements" : [{
Java
apache-2.0
d4626b4d1825b60ef02c0da9c45cd483d1d98f49
0
lukmajercak/hadoop,wwjiang007/hadoop,plusplusjiajia/hadoop,lukmajercak/hadoop,JingchengDu/hadoop,plusplusjiajia/hadoop,wwjiang007/hadoop,wwjiang007/hadoop,xiao-chen/hadoop,ucare-uchicago/hadoop,apache/hadoop,wwjiang007/hadoop,steveloughran/hadoop,apache/hadoop,lukmajercak/hadoop,littlezhou/hadoop,littlezhou/hadoop,mapr/hadoop-common,JingchengDu/hadoop,apache/hadoop,apurtell/hadoop,nandakumar131/hadoop,lukmajercak/hadoop,xiao-chen/hadoop,apurtell/hadoop,apache/hadoop,steveloughran/hadoop,xiao-chen/hadoop,JingchengDu/hadoop,nandakumar131/hadoop,apache/hadoop,JingchengDu/hadoop,lukmajercak/hadoop,JingchengDu/hadoop,apurtell/hadoop,xiao-chen/hadoop,mapr/hadoop-common,lukmajercak/hadoop,littlezhou/hadoop,nandakumar131/hadoop,ucare-uchicago/hadoop,mapr/hadoop-common,apache/hadoop,ucare-uchicago/hadoop,littlezhou/hadoop,xiao-chen/hadoop,apurtell/hadoop,nandakumar131/hadoop,wwjiang007/hadoop,apurtell/hadoop,littlezhou/hadoop,ucare-uchicago/hadoop,plusplusjiajia/hadoop,xiao-chen/hadoop,JingchengDu/hadoop,wwjiang007/hadoop,steveloughran/hadoop,nandakumar131/hadoop,mapr/hadoop-common,nandakumar131/hadoop,lukmajercak/hadoop,steveloughran/hadoop,steveloughran/hadoop,ucare-uchicago/hadoop,ucare-uchicago/hadoop,mapr/hadoop-common,apurtell/hadoop,JingchengDu/hadoop,xiao-chen/hadoop,plusplusjiajia/hadoop,ucare-uchicago/hadoop,apache/hadoop,littlezhou/hadoop,apurtell/hadoop,mapr/hadoop-common,mapr/hadoop-common,plusplusjiajia/hadoop,nandakumar131/hadoop,wwjiang007/hadoop,littlezhou/hadoop,steveloughran/hadoop,plusplusjiajia/hadoop,plusplusjiajia/hadoop,steveloughran/hadoop
/** * 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.hdfs.server.federation.router; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.fs.QuotaUsage; import org.apache.hadoop.fs.StorageType; import org.apache.hadoop.hdfs.protocol.ClientProtocol; import org.apache.hadoop.hdfs.protocol.HdfsConstants; import org.apache.hadoop.hdfs.server.federation.resolver.RemoteLocation; import org.apache.hadoop.hdfs.server.namenode.NameNode.OperationCategory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; /** * Module that implements the quota relevant RPC calls * {@link ClientProtocol#setQuota(String, long, long, StorageType)} * and * {@link ClientProtocol#getQuotaUsage(String)} * in the {@link RouterRpcServer}. */ public class Quota { private static final Logger LOG = LoggerFactory.getLogger(Quota.class); /** RPC server to receive client calls. */ private final RouterRpcServer rpcServer; /** RPC clients to connect to the Namenodes. */ private final RouterRpcClient rpcClient; /** Router used in RouterRpcServer. */ private final Router router; public Quota(Router router, RouterRpcServer server) { this.router = router; this.rpcServer = server; this.rpcClient = server.getRPCClient(); } /** * Set quota for the federation path. * @param path Federation path. * @param namespaceQuota Name space quota. * @param storagespaceQuota Storage space quota. * @param type StorageType that the space quota is intended to be set on. * @throws IOException If the quota system is disabled. */ public void setQuota(String path, long namespaceQuota, long storagespaceQuota, StorageType type) throws IOException { rpcServer.checkOperation(OperationCategory.WRITE); if (!router.isQuotaEnabled()) { throw new IOException("The quota system is disabled in Router."); } // Set quota for current path and its children mount table path. final List<RemoteLocation> locations = getQuotaRemoteLocations(path); if (LOG.isDebugEnabled()) { for (RemoteLocation loc : locations) { LOG.debug("Set quota for path: nsId: {}, dest: {}.", loc.getNameserviceId(), loc.getDest()); } } RemoteMethod method = new RemoteMethod("setQuota", new Class<?>[] {String.class, long.class, long.class, StorageType.class}, new RemoteParam(), namespaceQuota, storagespaceQuota, type); rpcClient.invokeConcurrent(locations, method, false, false); } /** * Get quota usage for the federation path. * @param path Federation path. * @return Aggregated quota. * @throws IOException If the quota system is disabled. */ public QuotaUsage getQuotaUsage(String path) throws IOException { rpcServer.checkOperation(OperationCategory.READ); if (!router.isQuotaEnabled()) { throw new IOException("The quota system is disabled in Router."); } final List<RemoteLocation> quotaLocs = getValidQuotaLocations(path); RemoteMethod method = new RemoteMethod("getQuotaUsage", new Class<?>[] {String.class}, new RemoteParam()); Map<RemoteLocation, QuotaUsage> results = rpcClient.invokeConcurrent( quotaLocs, method, true, false, QuotaUsage.class); return aggregateQuota(results); } /** * Get valid quota remote locations used in {@link #getQuotaUsage(String)}. * Differentiate the method {@link #getQuotaRemoteLocations(String)}, this * method will do some additional filtering. * @param path Federation path. * @return List of valid quota remote locations. * @throws IOException */ private List<RemoteLocation> getValidQuotaLocations(String path) throws IOException { final List<RemoteLocation> locations = getQuotaRemoteLocations(path); // NameService -> Locations ListMultimap<String, RemoteLocation> validLocations = ArrayListMultimap.create(); for (RemoteLocation loc : locations) { final String nsId = loc.getNameserviceId(); final Collection<RemoteLocation> dests = validLocations.get(nsId); // Ensure the paths in the same nameservice is different. // Do not include parent-child paths. boolean isChildPath = false; for (RemoteLocation d : dests) { if (StringUtils.startsWith(loc.getDest(), d.getDest())) { isChildPath = true; break; } } if (!isChildPath) { validLocations.put(nsId, loc); } } return Collections .unmodifiableList(new ArrayList<>(validLocations.values())); } /** * Aggregate quota that queried from sub-clusters. * @param results Quota query result. * @return Aggregated Quota. */ private QuotaUsage aggregateQuota(Map<RemoteLocation, QuotaUsage> results) { long nsCount = 0; long ssCount = 0; long nsQuota = HdfsConstants.QUOTA_RESET; long ssQuota = HdfsConstants.QUOTA_RESET; boolean hasQuotaUnSet = false; for (Map.Entry<RemoteLocation, QuotaUsage> entry : results.entrySet()) { RemoteLocation loc = entry.getKey(); QuotaUsage usage = entry.getValue(); if (usage != null) { // If quota is not set in real FileSystem, the usage // value will return -1. if (usage.getQuota() == -1 && usage.getSpaceQuota() == -1) { hasQuotaUnSet = true; } nsQuota = usage.getQuota(); ssQuota = usage.getSpaceQuota(); nsCount += usage.getFileAndDirectoryCount(); ssCount += usage.getSpaceConsumed(); LOG.debug( "Get quota usage for path: nsId: {}, dest: {}," + " nsCount: {}, ssCount: {}.", loc.getNameserviceId(), loc.getDest(), usage.getFileAndDirectoryCount(), usage.getSpaceConsumed()); } } QuotaUsage.Builder builder = new QuotaUsage.Builder() .fileAndDirectoryCount(nsCount).spaceConsumed(ssCount); if (hasQuotaUnSet) { builder.quota(HdfsConstants.QUOTA_RESET) .spaceQuota(HdfsConstants.QUOTA_RESET); } else { builder.quota(nsQuota).spaceQuota(ssQuota); } return builder.build(); } /** * Get all quota remote locations across subclusters under given * federation path. * @param path Federation path. * @return List of quota remote locations. * @throws IOException */ private List<RemoteLocation> getQuotaRemoteLocations(String path) throws IOException { List<RemoteLocation> locations = new ArrayList<>(); RouterQuotaManager manager = this.router.getQuotaManager(); if (manager != null) { Set<String> childrenPaths = manager.getPaths(path); for (String childPath : childrenPaths) { locations.addAll(rpcServer.getLocationsForPath(childPath, true, false)); } } return locations; } }
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/router/Quota.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.hdfs.server.federation.router; import java.io.IOException; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.hadoop.fs.QuotaUsage; import org.apache.hadoop.fs.StorageType; import org.apache.hadoop.hdfs.protocol.ClientProtocol; import org.apache.hadoop.hdfs.protocol.HdfsConstants; import org.apache.hadoop.hdfs.server.federation.resolver.RemoteLocation; import org.apache.hadoop.hdfs.server.namenode.NameNode.OperationCategory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Module that implements the quota relevant RPC calls * {@link ClientProtocol#setQuota(String, long, long, StorageType)} * and * {@link ClientProtocol#getQuotaUsage(String)} * in the {@link RouterRpcServer}. */ public class Quota { private static final Logger LOG = LoggerFactory.getLogger(Quota.class); /** RPC server to receive client calls. */ private final RouterRpcServer rpcServer; /** RPC clients to connect to the Namenodes. */ private final RouterRpcClient rpcClient; /** Router used in RouterRpcServer. */ private final Router router; public Quota(Router router, RouterRpcServer server) { this.router = router; this.rpcServer = server; this.rpcClient = server.getRPCClient(); } /** * Set quota for the federation path. * @param path Federation path. * @param namespaceQuota Name space quota. * @param storagespaceQuota Storage space quota. * @param type StorageType that the space quota is intended to be set on. * @throws IOException If the quota system is disabled. */ public void setQuota(String path, long namespaceQuota, long storagespaceQuota, StorageType type) throws IOException { rpcServer.checkOperation(OperationCategory.WRITE); if (!router.isQuotaEnabled()) { throw new IOException("The quota system is disabled in Router."); } // Set quota for current path and its children mount table path. final List<RemoteLocation> locations = getQuotaRemoteLocations(path); if (LOG.isDebugEnabled()) { for (RemoteLocation loc : locations) { LOG.debug("Set quota for path: nsId: {}, dest: {}.", loc.getNameserviceId(), loc.getDest()); } } RemoteMethod method = new RemoteMethod("setQuota", new Class<?>[] {String.class, long.class, long.class, StorageType.class}, new RemoteParam(), namespaceQuota, storagespaceQuota, type); rpcClient.invokeConcurrent(locations, method, false, false); } /** * Get quota usage for the federation path. * @param path Federation path. * @return Aggregated quota. * @throws IOException If the quota system is disabled. */ public QuotaUsage getQuotaUsage(String path) throws IOException { rpcServer.checkOperation(OperationCategory.READ); if (!router.isQuotaEnabled()) { throw new IOException("The quota system is disabled in Router."); } final List<RemoteLocation> quotaLocs = getValidQuotaLocations(path); RemoteMethod method = new RemoteMethod("getQuotaUsage", new Class<?>[] {String.class}, new RemoteParam()); Map<RemoteLocation, QuotaUsage> results = rpcClient.invokeConcurrent( quotaLocs, method, true, false, QuotaUsage.class); return aggregateQuota(results); } /** * Get valid quota remote locations used in {@link #getQuotaUsage(String)}. * Differentiate the method {@link #getQuotaRemoteLocations(String)}, this * method will do some additional filtering. * @param path Federation path. * @return List of valid quota remote locations. * @throws IOException */ private List<RemoteLocation> getValidQuotaLocations(String path) throws IOException { final List<RemoteLocation> locations = getQuotaRemoteLocations(path); // NameService -> Locations Map<String, List<RemoteLocation>> validLocations = new HashMap<>(); for (RemoteLocation loc : locations) { String nsId = loc.getNameserviceId(); List<RemoteLocation> dests = validLocations.get(nsId); if (dests == null) { dests = new LinkedList<>(); dests.add(loc); validLocations.put(nsId, dests); } else { // Ensure the paths in the same nameservice is different. // Don't include parent-child paths. boolean isChildPath = false; for (RemoteLocation d : dests) { if (loc.getDest().startsWith(d.getDest())) { isChildPath = true; break; } } if (!isChildPath) { dests.add(loc); } } } List<RemoteLocation> quotaLocs = new LinkedList<>(); for (List<RemoteLocation> locs : validLocations.values()) { quotaLocs.addAll(locs); } return quotaLocs; } /** * Aggregate quota that queried from sub-clusters. * @param results Quota query result. * @return Aggregated Quota. */ private QuotaUsage aggregateQuota(Map<RemoteLocation, QuotaUsage> results) { long nsCount = 0; long ssCount = 0; long nsQuota = HdfsConstants.QUOTA_RESET; long ssQuota = HdfsConstants.QUOTA_RESET; boolean hasQuotaUnSet = false; for (Map.Entry<RemoteLocation, QuotaUsage> entry : results.entrySet()) { RemoteLocation loc = entry.getKey(); QuotaUsage usage = entry.getValue(); if (usage != null) { // If quota is not set in real FileSystem, the usage // value will return -1. if (usage.getQuota() == -1 && usage.getSpaceQuota() == -1) { hasQuotaUnSet = true; } nsQuota = usage.getQuota(); ssQuota = usage.getSpaceQuota(); nsCount += usage.getFileAndDirectoryCount(); ssCount += usage.getSpaceConsumed(); LOG.debug( "Get quota usage for path: nsId: {}, dest: {}," + " nsCount: {}, ssCount: {}.", loc.getNameserviceId(), loc.getDest(), usage.getFileAndDirectoryCount(), usage.getSpaceConsumed()); } } QuotaUsage.Builder builder = new QuotaUsage.Builder() .fileAndDirectoryCount(nsCount).spaceConsumed(ssCount); if (hasQuotaUnSet) { builder.quota(HdfsConstants.QUOTA_RESET) .spaceQuota(HdfsConstants.QUOTA_RESET); } else { builder.quota(nsQuota).spaceQuota(ssQuota); } return builder.build(); } /** * Get all quota remote locations across subclusters under given * federation path. * @param path Federation path. * @return List of quota remote locations. * @throws IOException */ private List<RemoteLocation> getQuotaRemoteLocations(String path) throws IOException { List<RemoteLocation> locations = new LinkedList<>(); RouterQuotaManager manager = this.router.getQuotaManager(); if (manager != null) { Set<String> childrenPaths = manager.getPaths(path); for (String childPath : childrenPaths) { locations.addAll(rpcServer.getLocationsForPath(childPath, true, false)); } } return locations; } }
HDFS-13967. HDFS Router Quota Class Review. Contributed by BELUGA BEHR.
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/router/Quota.java
HDFS-13967. HDFS Router Quota Class Review. Contributed by BELUGA BEHR.
<ide><path>adoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/router/Quota.java <ide> package org.apache.hadoop.hdfs.server.federation.router; <ide> <ide> import java.io.IOException; <del>import java.util.HashMap; <del>import java.util.LinkedList; <add>import java.util.ArrayList; <add>import java.util.Collection; <add>import java.util.Collections; <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.Set; <ide> <add>import org.apache.commons.lang3.StringUtils; <ide> import org.apache.hadoop.fs.QuotaUsage; <ide> import org.apache.hadoop.fs.StorageType; <ide> import org.apache.hadoop.hdfs.protocol.ClientProtocol; <ide> import org.apache.hadoop.hdfs.server.namenode.NameNode.OperationCategory; <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <add> <add>import com.google.common.collect.ArrayListMultimap; <add>import com.google.common.collect.ListMultimap; <ide> <ide> /** <ide> * Module that implements the quota relevant RPC calls <ide> final List<RemoteLocation> locations = getQuotaRemoteLocations(path); <ide> <ide> // NameService -> Locations <del> Map<String, List<RemoteLocation>> validLocations = new HashMap<>(); <add> ListMultimap<String, RemoteLocation> validLocations = <add> ArrayListMultimap.create(); <add> <ide> for (RemoteLocation loc : locations) { <del> String nsId = loc.getNameserviceId(); <del> List<RemoteLocation> dests = validLocations.get(nsId); <del> if (dests == null) { <del> dests = new LinkedList<>(); <del> dests.add(loc); <del> validLocations.put(nsId, dests); <del> } else { <del> // Ensure the paths in the same nameservice is different. <del> // Don't include parent-child paths. <del> boolean isChildPath = false; <del> for (RemoteLocation d : dests) { <del> if (loc.getDest().startsWith(d.getDest())) { <del> isChildPath = true; <del> break; <del> } <add> final String nsId = loc.getNameserviceId(); <add> final Collection<RemoteLocation> dests = validLocations.get(nsId); <add> <add> // Ensure the paths in the same nameservice is different. <add> // Do not include parent-child paths. <add> boolean isChildPath = false; <add> <add> for (RemoteLocation d : dests) { <add> if (StringUtils.startsWith(loc.getDest(), d.getDest())) { <add> isChildPath = true; <add> break; <ide> } <del> <del> if (!isChildPath) { <del> dests.add(loc); <del> } <del> } <del> } <del> <del> List<RemoteLocation> quotaLocs = new LinkedList<>(); <del> for (List<RemoteLocation> locs : validLocations.values()) { <del> quotaLocs.addAll(locs); <del> } <del> <del> return quotaLocs; <add> } <add> <add> if (!isChildPath) { <add> validLocations.put(nsId, loc); <add> } <add> } <add> <add> return Collections <add> .unmodifiableList(new ArrayList<>(validLocations.values())); <ide> } <ide> <ide> /** <ide> */ <ide> private List<RemoteLocation> getQuotaRemoteLocations(String path) <ide> throws IOException { <del> List<RemoteLocation> locations = new LinkedList<>(); <add> List<RemoteLocation> locations = new ArrayList<>(); <ide> RouterQuotaManager manager = this.router.getQuotaManager(); <ide> if (manager != null) { <ide> Set<String> childrenPaths = manager.getPaths(path); <ide> locations.addAll(rpcServer.getLocationsForPath(childPath, true, false)); <ide> } <ide> } <del> <ide> return locations; <ide> } <ide> }
JavaScript
mit
dcfb5b63d9a6e7fc91fde454687322c213c7b16f
0
phetsims/graphing-quadratics,phetsims/graphing-quadratics,phetsims/graphing-quadratics
// Copyright 2018, University of Colorado Boulder /** * Tool that displays the (x,y) coordinates of a point on the graph. * If it's sufficiently close to a quadratic, it will snap to the quadratic. * * @author Andrea Lin * @author Chris Malley (PixelZoom, Inc.) */ define( require => { 'use strict'; // modules const Circle = require( 'SCENERY/nodes/Circle' ); const GQConstants = require( 'GRAPHING_QUADRATICS/common/GQConstants' ); const graphingQuadratics = require( 'GRAPHING_QUADRATICS/graphingQuadratics' ); const Image = require( 'SCENERY/nodes/Image' ); const Node = require( 'SCENERY/nodes/Node' ); const Path = require( 'SCENERY/nodes/Path' ); const PhetFont = require( 'SCENERY_PHET/PhetFont' ); const Property = require( 'AXON/Property' ); const Rectangle = require( 'SCENERY/nodes/Rectangle' ); const Shape = require( 'KITE/Shape' ); const SimpleDragHandler = require( 'SCENERY/input/SimpleDragHandler' ); const StringUtils = require( 'PHETCOMMON/util/StringUtils' ); const Text = require( 'SCENERY/nodes/Text' ); const Util = require( 'DOT/Util' ); const Vector2 = require( 'DOT/Vector2' ); // strings const coordinateUnknownString = require( 'string!GRAPHING_QUADRATICS/coordinateUnknown' ); const pointXYString = require( 'string!GRAPHING_QUADRATICS/pointXY' ); // images const pointToolLeftImage = require( 'image!GRAPHING_QUADRATICS/point_tool_left.png' ); const pointToolRightImage = require( 'image!GRAPHING_QUADRATICS/point_tool_right.png' ); // constants const VALUE_WINDOW_CENTER_X = 44; // center of the value window, relative to the left edge of pointToolLeftImage class PointToolNode extends Node { /** * @param {PointTool} pointTool * @param {ModelViewTransform2} modelViewTransform * @param {Graph} graph * @param {Property.<Boolean>} graphContentsVisibleProperty * @param {Object} [options] */ constructor( pointTool, modelViewTransform, graph, graphContentsVisibleProperty, options ) { options = _.extend( { cursor: 'pointer', backgroundNormalColor: 'white', foregroundNormalColor: 'black', foregroundHighlightColor: 'white' }, options ); assert && assert( pointTool.orientation === 'left' || pointTool.orientation === 'right', 'unsupported pointTool.orientation: ' + pointTool.orientation ); // use the image file that corresponds to the orientation const bodyImage = ( pointTool.orientation === 'left' ) ? pointToolLeftImage : pointToolRightImage; const bodyNode = new Image( bodyImage, { centerY: 0 } ); const probeNode = new ProbeNode(); //TODO use CoordinatesNode here // displayed coordinates const coordinatesNode = new Text( '?', { font: new PhetFont( 15 ), maxWidth: 60 // constrain width, determined empirically, dependent on bodyNode } ); // background behind the coordinates, sized to the body const backgroundNode = new Rectangle( 0, 0, bodyNode.width - 10, bodyNode.height - 10 ); // put probe on correct side of body if ( pointTool.orientation === 'left' ) { bodyNode.left = probeNode.right; } else { probeNode.setScaleMagnitude( -1, 1 ); // reflect about the y axis bodyNode.right = probeNode.left; } backgroundNode.center = bodyNode.center; options.children = [ backgroundNode, bodyNode, probeNode, coordinatesNode ]; super( options ); Property.multilink( [ pointTool.locationProperty, pointTool.onQuadraticProperty, graphContentsVisibleProperty ], ( location, onQuadratic, graphContentsVisible ) => { // move to location this.translation = modelViewTransform.modelToViewPosition( location ); // is the point tool on the graph? const onGraph = graph.contains( location ); // update coordinates - (x, y) or (?, ?) coordinatesNode.text = StringUtils.fillIn( pointXYString, { x: onGraph ? Util.toFixedNumber( location.x, GQConstants.POINT_TOOL_DECIMALS ) : coordinateUnknownString, y: onGraph ? Util.toFixedNumber( location.y, GQConstants.POINT_TOOL_DECIMALS ) : coordinateUnknownString } ); // center coordinates in window if ( pointTool.orientation === 'left' ) { coordinatesNode.centerX = bodyNode.left + VALUE_WINDOW_CENTER_X; } else { coordinatesNode.centerX = bodyNode.right - VALUE_WINDOW_CENTER_X; } coordinatesNode.centerY = bodyNode.centerY; // updater colors if ( onGraph && onQuadratic && graphContentsVisible ) { coordinatesNode.fill = options.foregroundHighlightColor; backgroundNode.fill = onQuadratic.color; } else { coordinatesNode.fill = options.foregroundNormalColor; backgroundNode.fill = options.backgroundNormalColor; } } ); // interactivity this.addInputListener( new PointToolDragHandler( pointTool, modelViewTransform, graph ) ); } } graphingQuadratics.register( 'PointToolNode', PointToolNode ); class ProbeNode extends Node { /** * Draw in the 'left' orientation, with the probe on the left side of the tool. * @param {Object} [options] */ constructor( options ) { options = _.extend( { radius: 15, color: 'black' }, options ); // circle const circle = new Circle( options.radius, { lineWidth: 3, stroke: options.color, fill: 'rgba( 255, 255, 255, 0.2 )', // transparent white centerX: 0, centerY: 0 } ); // crosshairs const crosshairs = new Path( new Shape() .moveTo( -options.radius, 0 ) .lineTo( options.radius, 0 ) .moveTo( 0, -options.radius ) .lineTo( 0, options.radius ), { stroke: options.color, center: circle.center } ); // shaft that connects the probe to the body const shaft = new Rectangle( 0, 0, 0.5 * options.radius, 4, { fill: 'rgb( 144, 144, 144 )', // matched to bodyImage left: circle.right, centerY: circle.centerY } ); super( { children: [ shaft, crosshairs, circle ], // origin at the center x: 0, y: 0 } ); } } graphingQuadratics.register( 'PointToolNode.ProbeNode', ProbeNode ); class PointToolDragHandler extends SimpleDragHandler { /** * Drag handler for the point tool. * @param {PointTool} pointTool * @param {ModelViewTransform2} modelViewTransform * @param {Graph} graph */ constructor( pointTool, modelViewTransform, graph ) { let startOffset; // where the drag started, relative to the tool's origin, in parent view coordinates super( { allowTouchSnag: true, // note where the drag started start: ( event, trail ) => { // Note the mouse-click offset when dragging starts. let location = modelViewTransform.modelToViewPosition( pointTool.locationProperty.value ); startOffset = event.currentTarget.globalToParentPoint( event.pointer.point ).minus( location ); // Move the tool that we're dragging to the foreground. event.currentTarget.moveToFront(); }, drag: ( event, trail ) => { let parentPoint = event.currentTarget.globalToParentPoint( event.pointer.point ).minus( startOffset ); let location = modelViewTransform.viewToModelPosition( parentPoint ); location = pointTool.dragBounds.closestPointTo( location ); if ( graph.contains( location ) ) { //TODO what's up here? let distance = 1; // empirically chosen for ( let i = 0; i < pointTool.quadratics.length; i++ ) { // snap to quadratic if near const quadratic = pointTool.quadratics.get( i ); const nearestPoint = quadratic.getClosestPoint( location ); if ( nearestPoint.distance( location ) < distance ) { distance = nearestPoint.distance( location ); location = nearestPoint; } } if ( distance === 1 ) { // didn't find a quadratic nearby // snap to the graph's grid location = new Vector2( Util.toFixedNumber( location.x, 0 ), Util.toFixedNumber( location.y, 0 ) ); } } pointTool.locationProperty.value = location; } } ); } } graphingQuadratics.register( 'PointToolNode.PointToolDragHandler', PointToolDragHandler ); return PointToolNode; } );
js/common/view/PointToolNode.js
// Copyright 2018, University of Colorado Boulder /** * Tool that displays the (x,y) coordinates of a point on the graph. * If it's sufficiently close to a quadratic, it will snap to the quadratic. * * @author Andrea Lin * @author Chris Malley (PixelZoom, Inc.) */ define( require => { 'use strict'; // modules const Circle = require( 'SCENERY/nodes/Circle' ); const GQConstants = require( 'GRAPHING_QUADRATICS/common/GQConstants' ); const graphingQuadratics = require( 'GRAPHING_QUADRATICS/graphingQuadratics' ); const Image = require( 'SCENERY/nodes/Image' ); const Node = require( 'SCENERY/nodes/Node' ); const Path = require( 'SCENERY/nodes/Path' ); const PhetFont = require( 'SCENERY_PHET/PhetFont' ); const Property = require( 'AXON/Property' ); const Rectangle = require( 'SCENERY/nodes/Rectangle' ); const Shape = require( 'KITE/Shape' ); const SimpleDragHandler = require( 'SCENERY/input/SimpleDragHandler' ); const StringUtils = require( 'PHETCOMMON/util/StringUtils' ); const Text = require( 'SCENERY/nodes/Text' ); const Util = require( 'DOT/Util' ); const Vector2 = require( 'DOT/Vector2' ); // strings const coordinateUnknownString = require( 'string!GRAPHING_QUADRATICS/coordinateUnknown' ); const pointXYString = require( 'string!GRAPHING_QUADRATICS/pointXY' ); // images const pointToolLeftImage = require( 'image!GRAPHING_QUADRATICS/point_tool_left.png' ); const pointToolRightImage = require( 'image!GRAPHING_QUADRATICS/point_tool_right.png' ); // constants const VALUE_WINDOW_CENTER_X = 44; // center of the value window, relative to the left edge of pointToolLeftImage class PointToolNode extends Node { /** * @param {PointTool} pointTool * @param {ModelViewTransform2} modelViewTransform * @param {Graph} graph * @param {Property.<Boolean>} graphContentsVisibleProperty * @param {Object} [options] */ constructor( pointTool, modelViewTransform, graph, graphContentsVisibleProperty, options ) { options = _.extend( { cursor: 'pointer', backgroundNormalColor: 'white', foregroundNormalColor: 'black', foregroundHighlightColor: 'white' }, options ); assert && assert( pointTool.orientation === 'left' || pointTool.orientation === 'right', 'unsupported pointTool.orientation: ' + pointTool.orientation ); // use the image file that corresponds to the orientation const bodyImage = ( pointTool.orientation === 'left' ) ? pointToolLeftImage : pointToolRightImage; const bodyNode = new Image( bodyImage, { centerY: 0 } ); const probeNode = new ProbeNode(); //TODO use CoordinatesNode here // displayed coordinates const coordinatesNode = new Text( '?', { font: new PhetFont( 15 ), maxWidth: 60 // constrain width, determined empirically, dependent on bodyNode } ); // background behind the coordinates, sized to the body const backgroundNode = new Rectangle( 0, 0, bodyNode.width - 10, bodyNode.height - 10 ); // put probe on correct side of body if ( pointTool.orientation === 'left' ) { bodyNode.left = probeNode.right; } else { probeNode.setScaleMagnitude( -1, 1 ); // reflect about the y axis bodyNode.right = probeNode.left; } backgroundNode.center = bodyNode.center; options.children = [ backgroundNode, bodyNode, probeNode, coordinatesNode ]; super( options ); Property.multilink( [ pointTool.locationProperty, pointTool.onQuadraticProperty, graphContentsVisibleProperty ], ( location, onQuadratic, curvesVisible ) => { // move to location this.translation = modelViewTransform.modelToViewPosition( location ); // update coordinates - (x, y) or (?, ?) const onGraph = graph.contains( location ); coordinatesNode.text = StringUtils.fillIn( pointXYString, { x: onGraph ? Util.toFixedNumber( location.x, GQConstants.POINT_TOOL_DECIMALS ) : coordinateUnknownString, y: onGraph ? Util.toFixedNumber( location.y, GQConstants.POINT_TOOL_DECIMALS ) : coordinateUnknownString } ); // center coordinates in window if ( pointTool.orientation === 'left' ) { coordinatesNode.centerX = bodyNode.left + VALUE_WINDOW_CENTER_X; } else { coordinatesNode.centerX = bodyNode.right - VALUE_WINDOW_CENTER_X; } coordinatesNode.centerY = bodyNode.centerY; // updater colors if ( onGraph && onQuadratic && curvesVisible ) { coordinatesNode.fill = options.foregroundHighlightColor; backgroundNode.fill = onQuadratic.color; } else { coordinatesNode.fill = options.foregroundNormalColor; backgroundNode.fill = options.backgroundNormalColor; } } ); // interactivity this.addInputListener( new PointToolDragHandler( pointTool, modelViewTransform, graph ) ); } } graphingQuadratics.register( 'PointToolNode', PointToolNode ); class ProbeNode extends Node { /** * Draw in the 'left' orientation, with the probe on the left side of the tool. * @param {Object} [options] */ constructor( options ) { options = _.extend( { radius: 15, color: 'black' }, options ); // circle const circle = new Circle( options.radius, { lineWidth: 3, stroke: options.color, fill: 'rgba( 255, 255, 255, 0.2 )', // transparent white centerX: 0, centerY: 0 } ); // crosshairs const crosshairs = new Path( new Shape() .moveTo( -options.radius, 0 ) .lineTo( options.radius, 0 ) .moveTo( 0, -options.radius ) .lineTo( 0, options.radius ), { stroke: options.color, center: circle.center } ); // shaft that connects the probe to the body const shaft = new Rectangle( 0, 0, 0.5 * options.radius, 4, { fill: 'rgb( 144, 144, 144 )', // matched to bodyImage left: circle.right, centerY: circle.centerY } ); super( { children: [ shaft, crosshairs, circle ], // origin at the center x: 0, y: 0 } ); } } graphingQuadratics.register( 'PointToolNode.ProbeNode', ProbeNode ); class PointToolDragHandler extends SimpleDragHandler { /** * Drag handler for the point tool. * @param {PointTool} pointTool * @param {ModelViewTransform2} modelViewTransform * @param {Graph} graph */ constructor( pointTool, modelViewTransform, graph ) { let startOffset; // where the drag started, relative to the tool's origin, in parent view coordinates super( { allowTouchSnag: true, // note where the drag started start: ( event, trail ) => { // Note the mouse-click offset when dragging starts. let location = modelViewTransform.modelToViewPosition( pointTool.locationProperty.value ); startOffset = event.currentTarget.globalToParentPoint( event.pointer.point ).minus( location ); // Move the tool that we're dragging to the foreground. event.currentTarget.moveToFront(); }, drag: ( event, trail ) => { let parentPoint = event.currentTarget.globalToParentPoint( event.pointer.point ).minus( startOffset ); let location = modelViewTransform.viewToModelPosition( parentPoint ); location = pointTool.dragBounds.closestPointTo( location ); if ( graph.contains( location ) ) { //TODO what's up here? let distance = 1; // empirically chosen for ( let i = 0; i < pointTool.quadratics.length; i++ ) { // snap to quadratic if near const quadratic = pointTool.quadratics.get( i ); const nearestPoint = quadratic.getClosestPoint( location ); if ( nearestPoint.distance( location ) < distance ) { distance = nearestPoint.distance( location ); location = nearestPoint; } } if ( distance === 1 ) { // didn't find a quadratic nearby // snap to the graph's grid location = new Vector2( Util.toFixedNumber( location.x, 0 ), Util.toFixedNumber( location.y, 0 ) ); } } pointTool.locationProperty.value = location; } } ); } } graphingQuadratics.register( 'PointToolNode.PointToolDragHandler', PointToolDragHandler ); return PointToolNode; } );
fix graphContentsVisible name Signed-off-by: Chris Malley <[email protected]>
js/common/view/PointToolNode.js
fix graphContentsVisible name
<ide><path>s/common/view/PointToolNode.js <ide> super( options ); <ide> <ide> Property.multilink( [ pointTool.locationProperty, pointTool.onQuadraticProperty, graphContentsVisibleProperty ], <del> ( location, onQuadratic, curvesVisible ) => { <add> ( location, onQuadratic, graphContentsVisible ) => { <ide> <ide> // move to location <ide> this.translation = modelViewTransform.modelToViewPosition( location ); <ide> <add> // is the point tool on the graph? <add> const onGraph = graph.contains( location ); <add> <ide> // update coordinates - (x, y) or (?, ?) <del> const onGraph = graph.contains( location ); <ide> coordinatesNode.text = StringUtils.fillIn( pointXYString, { <ide> x: onGraph ? Util.toFixedNumber( location.x, GQConstants.POINT_TOOL_DECIMALS ) : coordinateUnknownString, <ide> y: onGraph ? Util.toFixedNumber( location.y, GQConstants.POINT_TOOL_DECIMALS ) : coordinateUnknownString <ide> coordinatesNode.centerY = bodyNode.centerY; <ide> <ide> // updater colors <del> if ( onGraph && onQuadratic && curvesVisible ) { <add> if ( onGraph && onQuadratic && graphContentsVisible ) { <ide> coordinatesNode.fill = options.foregroundHighlightColor; <ide> backgroundNode.fill = onQuadratic.color; <ide> }
Java
apache-2.0
f3744f29bd8b92de83d792903f99ca80a3622070
0
dain/presto,dain/presto,losipiuk/presto,martint/presto,hgschmie/presto,martint/presto,ebyhr/presto,smartnews/presto,11xor6/presto,11xor6/presto,electrum/presto,losipiuk/presto,hgschmie/presto,electrum/presto,ebyhr/presto,ebyhr/presto,losipiuk/presto,erichwang/presto,losipiuk/presto,erichwang/presto,dain/presto,smartnews/presto,ebyhr/presto,electrum/presto,hgschmie/presto,Praveen2112/presto,11xor6/presto,Praveen2112/presto,treasure-data/presto,11xor6/presto,11xor6/presto,electrum/presto,martint/presto,smartnews/presto,treasure-data/presto,treasure-data/presto,smartnews/presto,dain/presto,ebyhr/presto,treasure-data/presto,erichwang/presto,erichwang/presto,smartnews/presto,erichwang/presto,Praveen2112/presto,Praveen2112/presto,martint/presto,martint/presto,treasure-data/presto,electrum/presto,losipiuk/presto,dain/presto,treasure-data/presto,hgschmie/presto,Praveen2112/presto,hgschmie/presto
/* * 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.prestosql.operator; import com.google.common.collect.ImmutableList; import com.google.common.primitives.Ints; import io.prestosql.memory.context.LocalMemoryContext; import io.prestosql.operator.BasicWorkProcessorOperatorAdapter.BasicAdapterWorkProcessorOperatorFactory; import io.prestosql.operator.WorkProcessor.Transformation; import io.prestosql.operator.WorkProcessor.TransformationState; import io.prestosql.operator.aggregation.AccumulatorFactory; import io.prestosql.spi.Page; import io.prestosql.spi.PageBuilder; import io.prestosql.spi.block.Block; import io.prestosql.spi.type.Type; import io.prestosql.sql.gen.JoinCompiler; import io.prestosql.sql.planner.plan.AggregationNode.Step; import io.prestosql.sql.planner.plan.PlanNodeId; import javax.annotation.Nullable; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.OptionalInt; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.ImmutableList.toImmutableList; import static io.prestosql.operator.BasicWorkProcessorOperatorAdapter.createAdapterOperatorFactory; import static io.prestosql.operator.WorkProcessor.TransformationState.finished; import static io.prestosql.operator.WorkProcessor.TransformationState.needsMoreData; import static io.prestosql.operator.WorkProcessor.TransformationState.ofResult; import static java.util.Objects.requireNonNull; public class StreamingAggregationOperator implements WorkProcessorOperator { public static OperatorFactory createOperatorFactory( int operatorId, PlanNodeId planNodeId, List<Type> sourceTypes, List<Type> groupByTypes, List<Integer> groupByChannels, Step step, List<AccumulatorFactory> accumulatorFactories, JoinCompiler joinCompiler) { return createAdapterOperatorFactory(new Factory( operatorId, planNodeId, sourceTypes, groupByTypes, groupByChannels, step, accumulatorFactories, joinCompiler)); } private static class Factory implements BasicAdapterWorkProcessorOperatorFactory { private final int operatorId; private final PlanNodeId planNodeId; private final List<Type> sourceTypes; private final List<Type> groupByTypes; private final List<Integer> groupByChannels; private final Step step; private final List<AccumulatorFactory> accumulatorFactories; private final JoinCompiler joinCompiler; private boolean closed; private Factory( int operatorId, PlanNodeId planNodeId, List<Type> sourceTypes, List<Type> groupByTypes, List<Integer> groupByChannels, Step step, List<AccumulatorFactory> accumulatorFactories, JoinCompiler joinCompiler) { this.operatorId = operatorId; this.planNodeId = requireNonNull(planNodeId, "planNodeId is null"); this.sourceTypes = ImmutableList.copyOf(requireNonNull(sourceTypes, "sourceTypes is null")); this.groupByTypes = ImmutableList.copyOf(requireNonNull(groupByTypes, "groupByTypes is null")); this.groupByChannels = ImmutableList.copyOf(requireNonNull(groupByChannels, "groupByChannels is null")); this.step = step; this.accumulatorFactories = ImmutableList.copyOf(requireNonNull(accumulatorFactories, "accumulatorFactories is null")); this.joinCompiler = requireNonNull(joinCompiler, "joinCompiler is null"); } @Override public int getOperatorId() { return operatorId; } @Override public PlanNodeId getPlanNodeId() { return planNodeId; } @Override public String getOperatorType() { return StreamingAggregationOperator.class.getSimpleName(); } @Override public WorkProcessorOperator create(ProcessorContext processorContext, WorkProcessor<Page> sourcePages) { checkState(!closed, "Factory is already closed"); return new StreamingAggregationOperator(processorContext, sourcePages, sourceTypes, groupByTypes, groupByChannels, step, accumulatorFactories, joinCompiler); } @Override public void close() { closed = true; } @Override public Factory duplicate() { return new Factory(operatorId, planNodeId, sourceTypes, groupByTypes, groupByChannels, step, accumulatorFactories, joinCompiler); } } private final WorkProcessor<Page> pages; private StreamingAggregationOperator( ProcessorContext processorContext, WorkProcessor<Page> sourcePages, List<Type> sourceTypes, List<Type> groupByTypes, List<Integer> groupByChannels, Step step, List<AccumulatorFactory> accumulatorFactories, JoinCompiler joinCompiler) { pages = sourcePages .transform(new StreamingAggregation( processorContext, sourceTypes, groupByTypes, groupByChannels, step, accumulatorFactories, joinCompiler)); } @Override public WorkProcessor<Page> getOutputPages() { return pages; } private static class StreamingAggregation implements Transformation<Page, Page> { private final LocalMemoryContext systemMemoryContext; private final LocalMemoryContext userMemoryContext; private final List<Type> groupByTypes; private final int[] groupByChannels; private final List<AccumulatorFactory> accumulatorFactories; private final Step step; private final PagesHashStrategy pagesHashStrategy; private List<Aggregator> aggregates; private final PageBuilder pageBuilder; private final Deque<Page> outputPages = new LinkedList<>(); private Page currentGroup; private StreamingAggregation( ProcessorContext processorContext, List<Type> sourceTypes, List<Type> groupByTypes, List<Integer> groupByChannels, Step step, List<AccumulatorFactory> accumulatorFactories, JoinCompiler joinCompiler) { requireNonNull(processorContext, "processorContext is null"); this.systemMemoryContext = processorContext.getMemoryTrackingContext().localSystemMemoryContext(); this.userMemoryContext = processorContext.getMemoryTrackingContext().localUserMemoryContext(); this.groupByTypes = ImmutableList.copyOf(requireNonNull(groupByTypes, "groupByTypes is null")); this.groupByChannels = Ints.toArray(requireNonNull(groupByChannels, "groupByChannels is null")); this.accumulatorFactories = requireNonNull(accumulatorFactories, "accumulatorFactories is null"); this.step = requireNonNull(step, "step is null"); this.aggregates = setupAggregates(step, accumulatorFactories); this.pageBuilder = new PageBuilder(toTypes(groupByTypes, aggregates)); requireNonNull(joinCompiler, "joinCompiler is null"); requireNonNull(sourceTypes, "sourceTypes is null"); pagesHashStrategy = joinCompiler.compilePagesHashStrategyFactory(sourceTypes, groupByChannels, Optional.empty()) .createPagesHashStrategy( sourceTypes.stream() .map(type -> ImmutableList.<Block>of()) .collect(toImmutableList()), OptionalInt.empty()); } @Override public TransformationState<Page> process(@Nullable Page inputPage) { if (inputPage == null) { if (currentGroup != null) { evaluateAndFlushGroup(currentGroup, 0); currentGroup = null; } if (!pageBuilder.isEmpty()) { outputPages.add(pageBuilder.build()); pageBuilder.reset(); } if (outputPages.isEmpty()) { return finished(); } return ofResult(outputPages.removeFirst(), false); } // flush remaining output pages before requesting next input page // invariant: queued output pages are produced from argument `inputPage` if (!outputPages.isEmpty()) { Page outputPage = outputPages.removeFirst(); return ofResult(outputPage, outputPages.isEmpty()); } processInput(inputPage); updateMemoryUsage(); if (outputPages.isEmpty()) { return needsMoreData(); } Page outputPage = outputPages.removeFirst(); return ofResult(outputPage, outputPages.isEmpty()); } private void updateMemoryUsage() { long memorySize = pageBuilder.getRetainedSizeInBytes(); for (Page output : outputPages) { memorySize += output.getRetainedSizeInBytes(); } for (Aggregator aggregator : aggregates) { memorySize += aggregator.getEstimatedSize(); } if (currentGroup != null) { memorySize += currentGroup.getRetainedSizeInBytes(); } if (step.isOutputPartial()) { systemMemoryContext.setBytes(memorySize); } else { userMemoryContext.setBytes(memorySize); } } private void processInput(Page page) { requireNonNull(page, "page is null"); Page groupByPage = extractColumns(page, groupByChannels); if (currentGroup != null) { if (!pagesHashStrategy.rowEqualsRow(0, extractColumns(currentGroup, groupByChannels), 0, groupByPage)) { // page starts with new group, so flush it evaluateAndFlushGroup(currentGroup, 0); } currentGroup = null; } int startPosition = 0; while (true) { // may be equal to page.getPositionCount() if the end is not found in this page int nextGroupStart = findNextGroupStart(startPosition, groupByPage); addRowsToAggregates(page, startPosition, nextGroupStart - 1); if (nextGroupStart < page.getPositionCount()) { // current group stops somewhere in the middle of the page, so flush it evaluateAndFlushGroup(page, startPosition); startPosition = nextGroupStart; } else { currentGroup = page.getRegion(page.getPositionCount() - 1, 1); return; } } } private static Page extractColumns(Page page, int[] channels) { Block[] newBlocks = new Block[channels.length]; for (int i = 0; i < channels.length; i++) { newBlocks[i] = page.getBlock(channels[i]); } return new Page(page.getPositionCount(), newBlocks); } private void addRowsToAggregates(Page page, int startPosition, int endPosition) { Page region = page.getRegion(startPosition, endPosition - startPosition + 1); for (Aggregator aggregator : aggregates) { aggregator.processPage(region); } } private void evaluateAndFlushGroup(Page page, int position) { pageBuilder.declarePosition(); for (int i = 0; i < groupByTypes.size(); i++) { Block block = page.getBlock(groupByChannels[i]); Type type = groupByTypes.get(i); type.appendTo(block, position, pageBuilder.getBlockBuilder(i)); } int offset = groupByTypes.size(); for (int i = 0; i < aggregates.size(); i++) { aggregates.get(i).evaluate(pageBuilder.getBlockBuilder(offset + i)); } if (pageBuilder.isFull()) { outputPages.add(pageBuilder.build()); pageBuilder.reset(); } aggregates = setupAggregates(step, accumulatorFactories); } private int findNextGroupStart(int startPosition, Page page) { for (int i = startPosition + 1; i < page.getPositionCount(); i++) { if (!pagesHashStrategy.rowEqualsRow(startPosition, page, i, page)) { return i; } } return page.getPositionCount(); } private static List<Aggregator> setupAggregates(Step step, List<AccumulatorFactory> accumulatorFactories) { ImmutableList.Builder<Aggregator> builder = ImmutableList.builder(); for (AccumulatorFactory factory : accumulatorFactories) { builder.add(new Aggregator(factory, step)); } return builder.build(); } private static List<Type> toTypes(List<Type> groupByTypes, List<Aggregator> aggregates) { ImmutableList.Builder<Type> builder = ImmutableList.builder(); builder.addAll(groupByTypes); aggregates.stream() .map(Aggregator::getType) .forEach(builder::add); return builder.build(); } } }
presto-main/src/main/java/io/prestosql/operator/StreamingAggregationOperator.java
/* * 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.prestosql.operator; import com.google.common.collect.ImmutableList; import com.google.common.primitives.Ints; import io.prestosql.memory.context.LocalMemoryContext; import io.prestosql.operator.BasicWorkProcessorOperatorAdapter.BasicAdapterWorkProcessorOperatorFactory; import io.prestosql.operator.WorkProcessor.Transformation; import io.prestosql.operator.WorkProcessor.TransformationState; import io.prestosql.operator.aggregation.AccumulatorFactory; import io.prestosql.spi.Page; import io.prestosql.spi.PageBuilder; import io.prestosql.spi.block.Block; import io.prestosql.spi.type.Type; import io.prestosql.sql.gen.JoinCompiler; import io.prestosql.sql.planner.plan.AggregationNode.Step; import io.prestosql.sql.planner.plan.PlanNodeId; import javax.annotation.Nullable; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.OptionalInt; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.ImmutableList.toImmutableList; import static io.prestosql.operator.BasicWorkProcessorOperatorAdapter.createAdapterOperatorFactory; import static io.prestosql.operator.WorkProcessor.TransformationState.finished; import static io.prestosql.operator.WorkProcessor.TransformationState.needsMoreData; import static io.prestosql.operator.WorkProcessor.TransformationState.ofResult; import static java.util.Objects.requireNonNull; public class StreamingAggregationOperator implements WorkProcessorOperator { public static OperatorFactory createOperatorFactory( int operatorId, PlanNodeId planNodeId, List<Type> sourceTypes, List<Type> groupByTypes, List<Integer> groupByChannels, Step step, List<AccumulatorFactory> accumulatorFactories, JoinCompiler joinCompiler) { return createAdapterOperatorFactory(new Factory( operatorId, planNodeId, sourceTypes, groupByTypes, groupByChannels, step, accumulatorFactories, joinCompiler)); } private static class Factory implements BasicAdapterWorkProcessorOperatorFactory { private final int operatorId; private final PlanNodeId planNodeId; private final List<Type> sourceTypes; private final List<Type> groupByTypes; private final List<Integer> groupByChannels; private final Step step; private final List<AccumulatorFactory> accumulatorFactories; private final JoinCompiler joinCompiler; private boolean closed; private Factory( int operatorId, PlanNodeId planNodeId, List<Type> sourceTypes, List<Type> groupByTypes, List<Integer> groupByChannels, Step step, List<AccumulatorFactory> accumulatorFactories, JoinCompiler joinCompiler) { this.operatorId = operatorId; this.planNodeId = requireNonNull(planNodeId, "planNodeId is null"); this.sourceTypes = ImmutableList.copyOf(requireNonNull(sourceTypes, "sourceTypes is null")); this.groupByTypes = ImmutableList.copyOf(requireNonNull(groupByTypes, "groupByTypes is null")); this.groupByChannels = ImmutableList.copyOf(requireNonNull(groupByChannels, "groupByChannels is null")); this.step = step; this.accumulatorFactories = ImmutableList.copyOf(requireNonNull(accumulatorFactories, "accumulatorFactories is null")); this.joinCompiler = requireNonNull(joinCompiler, "joinCompiler is null"); } @Override public int getOperatorId() { return operatorId; } @Override public PlanNodeId getPlanNodeId() { return planNodeId; } @Override public String getOperatorType() { return StreamingAggregationOperator.class.getSimpleName(); } @Override public WorkProcessorOperator create(ProcessorContext processorContext, WorkProcessor<Page> sourcePages) { checkState(!closed, "Factory is already closed"); return new StreamingAggregationOperator(processorContext, sourcePages, sourceTypes, groupByTypes, groupByChannels, step, accumulatorFactories, joinCompiler); } @Override public void close() { closed = true; } @Override public Factory duplicate() { return new Factory(operatorId, planNodeId, sourceTypes, groupByTypes, groupByChannels, step, accumulatorFactories, joinCompiler); } } private final WorkProcessor<Page> pages; private StreamingAggregationOperator( ProcessorContext processorContext, WorkProcessor<Page> sourcePages, List<Type> sourceTypes, List<Type> groupByTypes, List<Integer> groupByChannels, Step step, List<AccumulatorFactory> accumulatorFactories, JoinCompiler joinCompiler) { pages = sourcePages .transform(new StreamingAggregation( processorContext, sourceTypes, groupByTypes, groupByChannels, step, accumulatorFactories, joinCompiler)); } @Override public WorkProcessor<Page> getOutputPages() { return pages; } private static class StreamingAggregation implements Transformation<Page, Page> { private final LocalMemoryContext systemMemoryContext; private final LocalMemoryContext userMemoryContext; private final List<Type> groupByTypes; private final int[] groupByChannels; private final List<AccumulatorFactory> accumulatorFactories; private final Step step; private final PagesHashStrategy pagesHashStrategy; private List<Aggregator> aggregates; private final PageBuilder pageBuilder; private final Deque<Page> outputPages = new LinkedList<>(); private Page currentGroup; private StreamingAggregation( ProcessorContext processorContext, List<Type> sourceTypes, List<Type> groupByTypes, List<Integer> groupByChannels, Step step, List<AccumulatorFactory> accumulatorFactories, JoinCompiler joinCompiler) { requireNonNull(processorContext, "processorContext is null"); this.systemMemoryContext = processorContext.getMemoryTrackingContext().localSystemMemoryContext(); this.userMemoryContext = processorContext.getMemoryTrackingContext().localUserMemoryContext(); this.groupByTypes = ImmutableList.copyOf(requireNonNull(groupByTypes, "groupByTypes is null")); this.groupByChannels = Ints.toArray(requireNonNull(groupByChannels, "groupByChannels is null")); this.accumulatorFactories = requireNonNull(accumulatorFactories, "accumulatorFactories is null"); this.step = requireNonNull(step, "step is null"); this.aggregates = setupAggregates(step, accumulatorFactories); this.pageBuilder = new PageBuilder(toTypes(groupByTypes, aggregates)); requireNonNull(joinCompiler, "joinCompiler is null"); requireNonNull(sourceTypes, "sourceTypes is null"); pagesHashStrategy = joinCompiler.compilePagesHashStrategyFactory(sourceTypes, groupByChannels, Optional.empty()) .createPagesHashStrategy( sourceTypes.stream() .map(type -> ImmutableList.<Block>of()) .collect(toImmutableList()), OptionalInt.empty()); } @Override public TransformationState<Page> process(@Nullable Page inputPage) { if (inputPage == null) { if (currentGroup != null) { evaluateAndFlushGroup(currentGroup, 0); currentGroup = null; } if (!pageBuilder.isEmpty()) { outputPages.add(pageBuilder.build()); pageBuilder.reset(); } if (outputPages.isEmpty()) { return finished(); } return ofResult(outputPages.removeFirst(), false); } // flush remaining output pages before requesting next input page if (!outputPages.isEmpty()) { Page outputPage = outputPages.removeFirst(); return ofResult(outputPage, outputPages.isEmpty()); } // invariant: next input page is requested only when there are no pending output pages queued processInput(inputPage); updateMemoryUsage(); if (outputPages.isEmpty()) { return needsMoreData(); } Page outputPage = outputPages.removeFirst(); return ofResult(outputPage, outputPages.isEmpty()); } private void updateMemoryUsage() { long memorySize = pageBuilder.getRetainedSizeInBytes(); for (Page output : outputPages) { memorySize += output.getRetainedSizeInBytes(); } for (Aggregator aggregator : aggregates) { memorySize += aggregator.getEstimatedSize(); } if (currentGroup != null) { memorySize += currentGroup.getRetainedSizeInBytes(); } if (step.isOutputPartial()) { systemMemoryContext.setBytes(memorySize); } else { userMemoryContext.setBytes(memorySize); } } private void processInput(Page page) { requireNonNull(page, "page is null"); Page groupByPage = extractColumns(page, groupByChannels); if (currentGroup != null) { if (!pagesHashStrategy.rowEqualsRow(0, extractColumns(currentGroup, groupByChannels), 0, groupByPage)) { // page starts with new group, so flush it evaluateAndFlushGroup(currentGroup, 0); } currentGroup = null; } int startPosition = 0; while (true) { // may be equal to page.getPositionCount() if the end is not found in this page int nextGroupStart = findNextGroupStart(startPosition, groupByPage); addRowsToAggregates(page, startPosition, nextGroupStart - 1); if (nextGroupStart < page.getPositionCount()) { // current group stops somewhere in the middle of the page, so flush it evaluateAndFlushGroup(page, startPosition); startPosition = nextGroupStart; } else { currentGroup = page.getRegion(page.getPositionCount() - 1, 1); return; } } } private static Page extractColumns(Page page, int[] channels) { Block[] newBlocks = new Block[channels.length]; for (int i = 0; i < channels.length; i++) { newBlocks[i] = page.getBlock(channels[i]); } return new Page(page.getPositionCount(), newBlocks); } private void addRowsToAggregates(Page page, int startPosition, int endPosition) { Page region = page.getRegion(startPosition, endPosition - startPosition + 1); for (Aggregator aggregator : aggregates) { aggregator.processPage(region); } } private void evaluateAndFlushGroup(Page page, int position) { pageBuilder.declarePosition(); for (int i = 0; i < groupByTypes.size(); i++) { Block block = page.getBlock(groupByChannels[i]); Type type = groupByTypes.get(i); type.appendTo(block, position, pageBuilder.getBlockBuilder(i)); } int offset = groupByTypes.size(); for (int i = 0; i < aggregates.size(); i++) { aggregates.get(i).evaluate(pageBuilder.getBlockBuilder(offset + i)); } if (pageBuilder.isFull()) { outputPages.add(pageBuilder.build()); pageBuilder.reset(); } aggregates = setupAggregates(step, accumulatorFactories); } private int findNextGroupStart(int startPosition, Page page) { for (int i = startPosition + 1; i < page.getPositionCount(); i++) { if (!pagesHashStrategy.rowEqualsRow(startPosition, page, i, page)) { return i; } } return page.getPositionCount(); } private static List<Aggregator> setupAggregates(Step step, List<AccumulatorFactory> accumulatorFactories) { ImmutableList.Builder<Aggregator> builder = ImmutableList.builder(); for (AccumulatorFactory factory : accumulatorFactories) { builder.add(new Aggregator(factory, step)); } return builder.build(); } private static List<Type> toTypes(List<Type> groupByTypes, List<Aggregator> aggregates) { ImmutableList.Builder<Type> builder = ImmutableList.builder(); builder.addAll(groupByTypes); aggregates.stream() .map(Aggregator::getType) .forEach(builder::add); return builder.build(); } } }
Improve StreamingAggregationOperator invariant comment
presto-main/src/main/java/io/prestosql/operator/StreamingAggregationOperator.java
Improve StreamingAggregationOperator invariant comment
<ide><path>resto-main/src/main/java/io/prestosql/operator/StreamingAggregationOperator.java <ide> } <ide> <ide> // flush remaining output pages before requesting next input page <add> // invariant: queued output pages are produced from argument `inputPage` <ide> if (!outputPages.isEmpty()) { <ide> Page outputPage = outputPages.removeFirst(); <ide> return ofResult(outputPage, outputPages.isEmpty()); <ide> } <ide> <del> // invariant: next input page is requested only when there are no pending output pages queued <ide> processInput(inputPage); <ide> updateMemoryUsage(); <ide>
Java
lgpl-2.1
22f77fe99162c6543e18a91bfe5505c4abc467b0
0
zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform
/* * * * Copyright 2014, 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.zanata.action; import static com.google.common.base.Strings.isNullOrEmpty; import java.util.ArrayList; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.hibernate.Session; import org.hibernate.criterion.NaturalIdentifier; import org.hibernate.criterion.Restrictions; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import org.jboss.seam.faces.FacesManager; import org.zanata.common.DocumentType; import org.zanata.common.EntityStatus; import org.zanata.common.LocaleId; import org.zanata.common.ProjectType; import org.zanata.dao.ProjectDAO; import org.zanata.dao.ProjectIterationDAO; import org.zanata.dao.LocaleDAO; import org.zanata.i18n.Messages; import org.zanata.model.HLocale; import org.zanata.model.HProject; import org.zanata.model.HProjectIteration; import org.zanata.model.validator.SlugValidator; import org.zanata.seam.scope.ConversationScopeMessages; import org.zanata.security.ZanataIdentity; import org.zanata.service.LocaleService; import org.zanata.service.SlugEntityService; import org.zanata.service.ValidationService; import org.zanata.service.impl.LocaleServiceImpl; import org.zanata.ui.faces.FacesMessages; import org.zanata.util.ComparatorUtil; import org.zanata.util.UrlUtil; import org.zanata.webtrans.shared.model.ValidationAction; import org.zanata.webtrans.shared.model.ValidationId; import org.zanata.webtrans.shared.validation.ValidationFactory; import javax.faces.application.FacesMessage; import javax.faces.event.ValueChangeEvent; import javax.persistence.EntityNotFoundException; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.ResourceBundle; @Name("versionHome") @Slf4j public class VersionHome extends SlugHome<HProjectIteration> implements HasLanguageSettings { private static final long serialVersionUID = 1L; /** * This field is set from http parameter which will be the original slug */ @Getter private String slug; /** * This field is set from form input which can differ from original slug */ @Setter @Getter private String inputSlugValue; private Long versionId; @Getter @Setter private String projectSlug; @In("jsfMessages") private FacesMessages facesMessages; @In private ProjectIterationDAO projectIterationDAO; @In private LocaleDAO localeDAO; @In private ConversationScopeMessages conversationScopeMessages; @In private LocaleService localeServiceImpl; @In private ValidationService validationServiceImpl; @In private SlugEntityService slugEntityServiceImpl; @In(create = true) private ProjectDAO projectDAO; @In private Messages msgs; @In private CopyVersionManager copyVersionManager; @In private UrlUtil urlUtil; @In private ZanataIdentity identity; private Map<ValidationId, ValidationAction> availableValidations = Maps .newHashMap(); @Getter @Setter private boolean isNewInstance = false; @Setter @Getter private String selectedProjectType; @Getter @Setter private boolean copyFromVersion = true; @Getter @Setter private String copyFromVersionSlug; private final Function<HProjectIteration, VersionItem> VERSION_ITEM_FN = new Function<HProjectIteration, VersionItem>() { @Override public VersionItem apply(HProjectIteration input) { boolean selected = StringUtils.isNotEmpty( copyFromVersionSlug) && copyFromVersionSlug .equals(input.getSlug()); return new VersionItem(selected, input); } }; private void setDefaultCopyFromVersion() { List<VersionItem> otherVersions = getOtherVersions(); if (!otherVersions.isEmpty() && StringUtils.isEmpty(copyFromVersionSlug)) { this.copyFromVersionSlug = otherVersions.get(0).getVersion().getSlug(); copyFromVersion = true; } else { copyFromVersion = false; } } public void init(boolean isNewInstance) { this.isNewInstance = isNewInstance; if (isNewInstance) { identity.checkPermission(getProject(), "insert"); ProjectType projectType = getProject().getDefaultProjectType(); if (projectType != null) { selectedProjectType = projectType.name(); } if(StringUtils.isEmpty(copyFromVersionSlug)) { setDefaultCopyFromVersion(); } } else { copyFromVersion = false; ProjectType versionProjectType = getInstance().getProjectType(); if (versionProjectType != null) { selectedProjectType = versionProjectType.name(); } copyFromVersionSlug = ""; enteredLocaleAliases.putAll(getLocaleAliases()); } } public HProject getProject() { return projectDAO.getBySlug(projectSlug); } public List<VersionItem> getOtherVersions() { HProject project = getProject(); if (project != null) { List<HProjectIteration> versionList = projectIterationDAO.getByProjectSlug(projectSlug, EntityStatus.ACTIVE, EntityStatus.READONLY); Collections.sort(versionList, ComparatorUtil.VERSION_CREATION_DATE_COMPARATOR); List<VersionItem> versionItems = Lists.transform(versionList, VERSION_ITEM_FN); if (StringUtils.isEmpty(copyFromVersionSlug) && !versionItems.isEmpty()) { versionItems.get(0).setSelected(true); } return versionItems; } return Collections.EMPTY_LIST; } @Getter @Setter @AllArgsConstructor public class VersionItem implements Serializable { private boolean selected; private HProjectIteration version; } @Override protected HProjectIteration loadInstance() { Session session = (Session) getEntityManager().getDelegate(); if (versionId == null) { HProjectIteration iteration = (HProjectIteration) session .byNaturalId(HProjectIteration.class) .using("slug", getSlug()) .using("project", projectDAO.getBySlug(projectSlug)).load(); validateIterationState(iteration); versionId = iteration.getId(); return iteration; } else { HProjectIteration iteration = (HProjectIteration) session.load(HProjectIteration.class, versionId); validateIterationState(iteration); return iteration; } } private void validateIterationState(HProjectIteration iteration) { if (iteration == null || iteration.getStatus() == EntityStatus.OBSOLETE) { log.warn( "Project version [id={}, slug={}], does not exist or is soft deleted: {}", versionId, slug, iteration); throw new EntityNotFoundException(); } } public void updateRequireTranslationReview(String key, boolean checked) { identity.checkPermission(instance, "update"); getInstance().setRequireTranslationReview(checked); update(); if (checked) { conversationScopeMessages.setMessage(FacesMessage.SEVERITY_INFO, msgs.get("jsf.iteration.requireReview.enabled")); } else { conversationScopeMessages .setMessage(FacesMessage.SEVERITY_INFO, msgs.get("jsf.iteration.requireReview.disabled")); } } public List<ValidationAction> getValidationList() { List<ValidationAction> sortedList = Lists.newArrayList(getValidations().values()); Collections.sort(sortedList, ValidationFactory.ValidationActionComparator); return sortedList; } private Map<ValidationId, ValidationAction> getValidations() { if (availableValidations.isEmpty()) { Collection<ValidationAction> validationList = validationServiceImpl.getValidationActions(projectSlug, getInstance().getSlug()); for (ValidationAction validationAction : validationList) { availableValidations.put(validationAction.getId(), validationAction); } } return availableValidations; } public void validateSuppliedId() { getInstance(); // this will raise an EntityNotFound exception // when id is invalid and conversation will not // start } public ProjectType getProjectType() { if (getInstance().getProjectType() == null) { getInstance().setProjectType( getInstance().getProject().getDefaultProjectType()); } return getInstance().getProjectType(); } public void setProjectType(ProjectType projectType) { getInstance().setProjectType(projectType); } public void validateProjectSlug() { if (projectDAO.getBySlug(projectSlug) == null) { throw new EntityNotFoundException("no entity with slug " + projectSlug); } } public void verifySlugAvailable(ValueChangeEvent e) { String slug = (String) e.getNewValue(); validateSlug(slug, e.getComponent().getId()); } public boolean validateSlug(String slug, String componentId) { if (!isSlugAvailable(slug)) { facesMessages.addToControl(componentId, "This Version ID has been used in this project"); return false; } boolean valid = new SlugValidator().isValid(slug, null); if (!valid) { String validationMessages = ResourceBundle.getBundle("ValidationMessages").getString( "javax.validation.constraints.Slug.message"); facesMessages.addToControl(componentId, validationMessages); return false; } return true; } public boolean isSlugAvailable(String slug) { return slugEntityServiceImpl.isProjectIterationSlugAvailable(slug, projectSlug); } public String createVersion() { if (!validateSlug(inputSlugValue, "slug")) return "invalid-slug"; if (copyFromVersion) { copyVersion(); return "copy-version"; } else { return persist(); } } public void copyVersion() { getInstance().setSlug(inputSlugValue); getInstance().setStatus(EntityStatus.READONLY); // create basic version here HProject project = getProject(); project.addIteration(getInstance()); super.persist(); copyVersionManager.startCopyVersion(projectSlug, copyFromVersionSlug, getInstance().getSlug()); conversationScopeMessages .setMessage(FacesMessage.SEVERITY_INFO, msgs. format("jsf.copyVersion.started", getInstance().getSlug(), copyFromVersionSlug)); } public void setSlug(String slug) { this.slug = slug; this.inputSlugValue = slug; } @Override public String persist() { if (!validateSlug(getInputSlugValue(), "slug")) { return null; } getInstance().setSlug(getInputSlugValue()); updateProjectType(); HProject project = getProject(); project.addIteration(getInstance()); // FIXME this looks only to be used when copying a version. // so it should copy the setting for isOverrideLocales, // and all enabled locales and locale alias data if it is // overriding. List<HLocale> projectLocales = localeServiceImpl .getSupportedLanguageByProject(projectSlug); getInstance().getCustomizedLocales().addAll(projectLocales); getInstance().getCustomizedValidations().putAll( project.getCustomizedValidations()); return super.persist(); } @Override public Object getId() { return projectSlug + "/" + slug; } @Override public NaturalIdentifier getNaturalId() { return Restrictions.naturalId().set("slug", slug) .set("project", projectDAO.getBySlug(projectSlug)); } @Override public boolean isIdDefined() { return slug != null && projectSlug != null; } public boolean isValidationsSameAsProject() { Collection<ValidationAction> versionValidations = validationServiceImpl.getValidationActions(projectSlug, slug); Collection<ValidationAction> projectValidations = validationServiceImpl.getValidationActions(projectSlug); return versionValidations.equals(projectValidations); } public void copyValidationFromProject() { getInstance().getCustomizedValidations().clear(); getInstance().getCustomizedValidations().putAll( getInstance().getProject().getCustomizedValidations()); availableValidations.clear(); update(); conversationScopeMessages .setMessage( FacesMessage.SEVERITY_INFO, msgs.get( "jsf.iteration.CopyProjectValidations.message")); } /** * Flush changes to the database, and raise an event to communicate that * the version has been changed. * * @return the String "updated" */ @Override public String update() { identity.checkPermission(instance, "update"); if (!getInputSlugValue().equals(slug) && !validateSlug(getInputSlugValue(), "slug")) { return null; } getInstance().setSlug(getInputSlugValue()); boolean softDeleted = false; if (getInstance().getStatus() == EntityStatus.OBSOLETE) { // if we offer delete in REST, we need to move this to hibernate listener String newSlug = getInstance().changeToDeletedSlug(); getInstance().setSlug(newSlug); softDeleted = true; } String state = super.update(); if (softDeleted) { String url = urlUtil.projectUrl(projectSlug); FacesManager.instance().redirectToExternalURL(url); return state; } if (!slug.equals(getInstance().getSlug())) { slug = getInstance().getSlug(); return "versionSlugUpdated"; } return state; } @Override protected void updatedMessage() { // Disable the default message from Seam } public void updateStatus(char initial) { identity.checkPermission(instance, "update"); String message = msgs.format("jsf.iteration.status.updated", EntityStatus.valueOf(initial)); getInstance().setStatus(EntityStatus.valueOf(initial)); if (getInstance().getStatus() == EntityStatus.OBSOLETE) { message = msgs.get("jsf.iteration.deleted"); } update(); facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, message); } public void deleteSelf() { updateStatus('O'); } public void updateSelectedProjectType(ValueChangeEvent e) { selectedProjectType = (String) e.getNewValue(); updateProjectType(); } public void copyProjectTypeFromProject() { getInstance().setProjectType( getInstance().getProject().getDefaultProjectType()); update(); conversationScopeMessages.setMessage(FacesMessage.SEVERITY_INFO, msgs.get("jsf.iteration.CopyProjectType.message")); } /** * @return comma-separated list of accepted file extensions. May be an empty * string */ public String getAcceptedSourceFileExtensions() { List<String> supportedTypes = Lists.transform(ProjectType .getSupportedSourceFileTypes(getProjectType()), new Function<DocumentType, String>() { @Override public String apply(DocumentType docType) { return Joiner.on(",").join( docType.getSourceExtensions()); } }); return Joiner.on(", ").join(supportedTypes); } public String getAcceptedSourceFile() { List<String> supportedTypes = Lists.transform(ProjectType .getSupportedSourceFileTypes(getProjectType()), new Function<DocumentType, String>() { @Override public String apply(DocumentType docType) { return docType.name() + "[" + Joiner.on(",").join( docType.getSourceExtensions()) + "]"; } }); return Joiner.on(", ").join(supportedTypes); } private void updateProjectType() { if (!StringUtils.isEmpty(selectedProjectType) && !selectedProjectType.equals("null")) { ProjectType projectType = ProjectType.valueOf(selectedProjectType); getInstance().setProjectType(projectType); } else { getInstance().setProjectType(null); } } public List<ValidationAction.State> getValidationStates() { return Arrays.asList(ValidationAction.State.values()); } public void updateValidationOption(String name, String state) { identity.checkPermission(instance, "update"); ValidationId validationId = ValidationId.valueOf(name); for (Map.Entry<ValidationId, ValidationAction> entry : getValidations() .entrySet()) { if (entry.getKey().name().equals(name)) { getValidations().get(validationId).setState( ValidationAction.State.valueOf(state)); getInstance().getCustomizedValidations().put( entry.getKey().name(), entry.getValue().getState().name()); ensureMutualExclusivity(getValidations().get(validationId)); break; } } update(); conversationScopeMessages.setMessage(FacesMessage.SEVERITY_INFO, msgs.format("jsf.validation.updated", validationId.getDisplayName(), state)); } /** * If this action is enabled(Warning or Error), then it's exclusive * validation will be turn off * */ private void ensureMutualExclusivity( ValidationAction selectedValidationAction) { if (selectedValidationAction.getState() != ValidationAction.State.Off) { for (ValidationAction exclusiveValAction : selectedValidationAction .getExclusiveValidations()) { getInstance().getCustomizedValidations().put( exclusiveValAction.getId().name(), ValidationAction.State.Off.name()); getValidations().get(exclusiveValAction.getId()).setState( ValidationAction.State.Off); } } } public List<ProjectType> getProjectTypeList() { List<ProjectType> projectTypes = Arrays.asList(ProjectType.values()); Collections.sort(projectTypes, ComparatorUtil.PROJECT_TYPE_COMPARATOR); return projectTypes; } public boolean isOverrideLocales() { return getInstance().isOverrideLocales(); } public void setOverrideLocales(boolean overrideLocales) { identity.checkPermission(instance, "update"); getInstance().setOverrideLocales(overrideLocales); } public Map<LocaleId, String> getLocaleAliases() { return LocaleServiceImpl.getLocaleAliasesByIteration(getInstance()); } public void removeAllLocaleAliases() { identity.checkPermission(instance, "update"); List<LocaleId> removed = new ArrayList<>(); List<LocaleId> aliasedLocales = new ArrayList<>(getLocaleAliases().keySet()); if (!aliasedLocales.isEmpty()) { ensureOverridingLocales(); for (LocaleId aliasedLocale : aliasedLocales) { boolean hadAlias = removeAliasSilently(aliasedLocale); if (hadAlias) { removed.add(aliasedLocale); } } } // else no locales to remove, nothing to do. showRemovedAliasesMessage(removed); } /** * Ensure that isOverrideLocales is true, and copy data if necessary. */ private void ensureOverridingLocales() { if (!isOverrideLocales()) { startOverridingLocales(); } } /** * Copy locale data from project and set overrideLocales, in preparation for * making customizations to the locales. */ private void startOverridingLocales() { // Copied before setOverrideLocales(true) so that the currently returned // values will be used as the basis for any customization. List<HLocale> enabledLocales = getEnabledLocales(); Map<LocaleId, String> localeAliases = getLocaleAliases(); setOverrideLocales(true); // Replace contents rather than entire collections to avoid confusion // with reference to the collections that are bound before this runs. getInstance().getCustomizedLocales().clear(); getInstance().getCustomizedLocales().addAll(enabledLocales); getInstance().getLocaleAliases().clear(); getInstance().getLocaleAliases().putAll(localeAliases); enteredLocaleAliases.clear(); enteredLocaleAliases.putAll(localeAliases); refreshDisabledLocales(); } /** * Update disabled locales to be consistent with enabled locales. */ private void refreshDisabledLocales() { // will be re-generated with correct values next time it is fetched. disabledLocales = null; } public void removeSelectedLocaleAliases() { identity.checkPermission(instance, "update"); List<LocaleId> removed = new ArrayList<>(); for (Map.Entry<LocaleId, Boolean> entry : getSelectedEnabledLocales().entrySet()) { if (entry.getValue()) { boolean hadAlias = removeAliasSilently(entry.getKey()); if (hadAlias) { removed.add(entry.getKey()); } } } showRemovedAliasesMessage(removed); } /** * Show an appropriate message for the removal of aliases from locales * with the given IDs. * * @param removed ids of locales that had aliases removed */ private void showRemovedAliasesMessage(List<LocaleId> removed) { if (removed.isEmpty()) { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.get("jsf.LocaleAlias.NoAliasesToRemove")); } else if (removed.size() == 1) { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.LocaleAlias.AliasRemoved", removed.get(0))); } else { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.LocaleAlias.AliasesRemoved", StringUtils.join(removed, ", "))); } } private boolean removeAliasSilently(LocaleId localeId) { return setLocaleAliasSilently(localeId, ""); } public String getLocaleAlias(HLocale locale) { return getLocaleAliases().get(locale.getLocaleId()); } public boolean hasLocaleAlias(HLocale locale) { return getLocaleAliases().containsKey(locale.getLocaleId()); } /** * A separate map is used, rather than binding the alias map from the * project directly. This is done so that empty values are not added to the * map in every form submission, and so that a value entered in the field * for a row is not automatically updated when a different row is submitted. */ @Getter @Setter private Map<LocaleId, String> enteredLocaleAliases = Maps.newHashMap(); public void updateToEnteredLocaleAlias(LocaleId localeId) { identity.checkPermission(instance, "update"); String enteredAlias = enteredLocaleAliases.get(localeId); setLocaleAlias(localeId, enteredAlias); } private void setLocaleAlias(LocaleId localeId, String alias) { boolean hadAlias = setLocaleAliasSilently(localeId, alias); if (isNullOrEmpty(alias)) { if (hadAlias) { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.LocaleAlias.AliasRemoved", localeId)); } else { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.LocaleAlias.NoAliasToRemove", localeId)); } } else { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.LocaleAlias.AliasSet", localeId, alias)); } } /** * Set or remove a locale alias without showing any message. * * @param localeId for which to set alias * @param alias new alias to use. Use empty string to remove alias. * @return true if there was already an alias, otherwise false. */ private boolean setLocaleAliasSilently(LocaleId localeId, String alias) { HProjectIteration instance = getInstance(); Map<LocaleId, String> aliases = instance.getLocaleAliases(); boolean hadAlias = aliases.containsKey(localeId); if (isNullOrEmpty(alias)) { if (hadAlias) { ensureOverridingLocales(); aliases.remove(localeId); } } else { final boolean sameAlias = hadAlias && alias.equals(aliases.get(localeId)); if (!sameAlias) { ensureOverridingLocales(); aliases.put(localeId, alias); } } update(); return hadAlias; } public void useDefaultLocales() { identity.checkPermission(instance, "update"); setOverrideLocales(false); refreshDisabledLocales(); } @Getter @Setter private String enabledLocalesFilter = ""; @Getter @Setter private String disabledLocalesFilter; public List<HLocale> getEnabledLocales() { if (StringUtils.isNotEmpty(projectSlug) && StringUtils.isNotEmpty(slug)) { List<HLocale> locales = localeServiceImpl.getSupportedLanguageByProjectIteration( projectSlug, slug); Collections.sort(locales, ComparatorUtil.LOCALE_COMPARATOR); return locales; } return Lists.newArrayList(); } @Getter @Setter private Map<LocaleId, Boolean> selectedEnabledLocales = Maps.newHashMap(); // Not sure if this is necessary, seems to work ok on selected disabled // locales without this. public Map<LocaleId, Boolean> getSelectedEnabledLocales() { if (selectedEnabledLocales == null) { selectedEnabledLocales = Maps.newHashMap(); for (HLocale locale : getEnabledLocales()) { selectedEnabledLocales.put(locale.getLocaleId(), Boolean.FALSE); } } return selectedEnabledLocales; } public void disableSelectedLocales() { identity.checkPermission(instance, "update"); List<LocaleId> toRemove = Lists.newArrayList(); for (Map.Entry<LocaleId, Boolean> entry : getSelectedEnabledLocales().entrySet()) { if (entry.getValue()) { toRemove.add(entry.getKey()); } } List<LocaleId> removed = Lists.newArrayList(); for(LocaleId localeId: toRemove) { boolean wasEnabled = disableLocaleSilently(localeId); if (wasEnabled) { removed.add(localeId); } } if (removed.isEmpty()) { // This should not be possible in the UI, but maybe if multiple users are editing it. } else if (removed.size() == 1) { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.languageSettings.LanguageDisabled", removed.get(0))); } else { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.languageSettings.LanguagesDisabled", StringUtils.join(removed, ", "))); } } private boolean disableLocaleSilently(LocaleId localeId) { HLocale locale = localeServiceImpl.getByLocaleId(localeId); return disableLocaleSilently(locale); } public void disableLocale(HLocale locale) { identity.checkPermission(instance, "update"); boolean wasEnabled = disableLocaleSilently(locale); if (wasEnabled) { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.languageSettings.LanguageDisabled", locale.getLocaleId())); } // TODO consider showing a message like "Locale {0} was already disabled." } /** * Disable a locale without printing any message. * * @param locale to disable * @return true if the locale was enabled before this call, false otherwise. */ private boolean disableLocaleSilently(HLocale locale) { boolean wasEnabled; if (getEnabledLocales().contains(locale)) { ensureOverridingLocales(); wasEnabled = getInstance().getCustomizedLocales().remove(locale); refreshDisabledLocales(); // TODO consider using alias from project as default rather than none. getLocaleAliases().remove(locale.getLocaleId()); getSelectedEnabledLocales().remove(locale.getLocaleId()); update(); } else { wasEnabled = false; } return wasEnabled; } private List<HLocale> disabledLocales; public List<HLocale> getDisabledLocales() { if(disabledLocales == null) { disabledLocales = findActiveNotEnabledLocales(); } return disabledLocales; } /** * Populate the list of available locales after filtering out the locales * already in the project. */ private List<HLocale> findActiveNotEnabledLocales() { Collection<HLocale> filtered = Collections2.filter(localeDAO.findAllActive(), new Predicate<HLocale>() { @Override public boolean apply(HLocale input) { // only include those not already in the project return !getEnabledLocales().contains(input); } }); return Lists.newArrayList(filtered); } @Getter @Setter private Map<LocaleId, Boolean> selectedDisabledLocales = Maps.newHashMap(); public void enableSelectedLocales() { identity.checkPermission(instance, "update"); List<LocaleId> enabled = new ArrayList<>(); for (Map.Entry<LocaleId, Boolean> entry : selectedDisabledLocales .entrySet()) { if (entry.getValue()) { boolean wasDisabled = enableLocaleSilently(entry.getKey()); if (wasDisabled) { enabled.add(entry.getKey()); } } } selectedDisabledLocales.clear(); if (enabled.isEmpty()) { // This should not be possible in the UI, but maybe if multiple users are editing it. } else if (enabled.size() == 1) { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.languageSettings.LanguageEnabled", enabled.get(0))); } else { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.languageSettings.LanguagesEnabled", StringUtils.join(enabled, ", "))); } } public void enableLocale(HLocale locale) { identity.checkPermission(instance, "update"); boolean wasDisabled = enableLocaleSilently(locale); if (wasDisabled) { LocaleId localeId = locale.getLocaleId(); facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.languageSettings.LanguageEnabled", localeId)); } // TODO consider printing message like "Locale {0} was already enabled" } private boolean enableLocaleSilently(LocaleId localeId) { HLocale locale = localeServiceImpl.getByLocaleId(localeId); return enableLocaleSilently(locale); } private boolean enableLocaleSilently(HLocale locale) { final boolean wasDisabled = getDisabledLocales().contains(locale); if (wasDisabled) { ensureOverridingLocales(); getInstance().getCustomizedLocales().add(locale); getSelectedEnabledLocales().put(locale.getLocaleId(), Boolean.FALSE); refreshDisabledLocales(); update(); } // else locale already enabled, nothing to do. return wasDisabled; } }
zanata-war/src/main/java/org/zanata/action/VersionHome.java
/* * * * Copyright 2014, 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.zanata.action; import static com.google.common.base.Strings.isNullOrEmpty; import java.util.ArrayList; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.hibernate.Session; import org.hibernate.criterion.NaturalIdentifier; import org.hibernate.criterion.Restrictions; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import org.jboss.seam.faces.FacesManager; import org.zanata.common.DocumentType; import org.zanata.common.EntityStatus; import org.zanata.common.LocaleId; import org.zanata.common.ProjectType; import org.zanata.dao.ProjectDAO; import org.zanata.dao.ProjectIterationDAO; import org.zanata.dao.LocaleDAO; import org.zanata.i18n.Messages; import org.zanata.model.HLocale; import org.zanata.model.HProject; import org.zanata.model.HProjectIteration; import org.zanata.model.validator.SlugValidator; import org.zanata.seam.scope.ConversationScopeMessages; import org.zanata.security.ZanataIdentity; import org.zanata.service.LocaleService; import org.zanata.service.SlugEntityService; import org.zanata.service.ValidationService; import org.zanata.service.impl.LocaleServiceImpl; import org.zanata.ui.faces.FacesMessages; import org.zanata.util.ComparatorUtil; import org.zanata.util.UrlUtil; import org.zanata.webtrans.shared.model.ValidationAction; import org.zanata.webtrans.shared.model.ValidationId; import org.zanata.webtrans.shared.validation.ValidationFactory; import javax.faces.application.FacesMessage; import javax.faces.event.ValueChangeEvent; import javax.persistence.EntityNotFoundException; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.ResourceBundle; @Name("versionHome") @Slf4j public class VersionHome extends SlugHome<HProjectIteration> implements HasLanguageSettings { private static final long serialVersionUID = 1L; /** * This field is set from http parameter which will be the original slug */ @Getter private String slug; /** * This field is set from form input which can differ from original slug */ @Setter @Getter private String inputSlugValue; private Long versionId; @Getter @Setter private String projectSlug; @In("jsfMessages") private FacesMessages facesMessages; @In private ProjectIterationDAO projectIterationDAO; @In private LocaleDAO localeDAO; @In private ConversationScopeMessages conversationScopeMessages; @In private LocaleService localeServiceImpl; @In private ValidationService validationServiceImpl; @In private SlugEntityService slugEntityServiceImpl; @In(create = true) private ProjectDAO projectDAO; @In private Messages msgs; @In private CopyVersionManager copyVersionManager; @In private UrlUtil urlUtil; @In private ZanataIdentity identity; private Map<ValidationId, ValidationAction> availableValidations = Maps .newHashMap(); @Getter @Setter private boolean isNewInstance = false; @Setter @Getter private String selectedProjectType; @Getter @Setter private boolean copyFromVersion = true; @Getter @Setter private String copyFromVersionSlug; private final Function<HProjectIteration, VersionItem> VERSION_ITEM_FN = new Function<HProjectIteration, VersionItem>() { @Override public VersionItem apply(HProjectIteration input) { boolean selected = StringUtils.isNotEmpty( copyFromVersionSlug) && copyFromVersionSlug .equals(input.getSlug()); return new VersionItem(selected, input); } }; private void setDefaultCopyFromVersion() { List<VersionItem> otherVersions = getOtherVersions(); if (!otherVersions.isEmpty() && StringUtils.isEmpty(copyFromVersionSlug)) { this.copyFromVersionSlug = otherVersions.get(0).getVersion().getSlug(); copyFromVersion = true; } else { copyFromVersion = false; } } public void init(boolean isNewInstance) { this.isNewInstance = isNewInstance; if (isNewInstance) { identity.checkPermission(getProject(), "insert"); ProjectType projectType = getProject().getDefaultProjectType(); if (projectType != null) { selectedProjectType = projectType.name(); } if(StringUtils.isEmpty(copyFromVersionSlug)) { setDefaultCopyFromVersion(); } } else { copyFromVersion = false; ProjectType versionProjectType = getInstance().getProjectType(); if (versionProjectType != null) { selectedProjectType = versionProjectType.name(); } copyFromVersionSlug = ""; enteredLocaleAliases.putAll(getLocaleAliases()); } } public HProject getProject() { return projectDAO.getBySlug(projectSlug); } public List<VersionItem> getOtherVersions() { HProject project = getProject(); if (project != null) { List<HProjectIteration> versionList = projectIterationDAO.getByProjectSlug(projectSlug, EntityStatus.ACTIVE, EntityStatus.READONLY); Collections.sort(versionList, ComparatorUtil.VERSION_CREATION_DATE_COMPARATOR); List<VersionItem> versionItems = Lists.transform(versionList, VERSION_ITEM_FN); if (StringUtils.isEmpty(copyFromVersionSlug) && !versionItems.isEmpty()) { versionItems.get(0).setSelected(true); } return versionItems; } return Collections.EMPTY_LIST; } @Getter @Setter @AllArgsConstructor public class VersionItem implements Serializable { private boolean selected; private HProjectIteration version; } @Override protected HProjectIteration loadInstance() { Session session = (Session) getEntityManager().getDelegate(); if (versionId == null) { HProjectIteration iteration = (HProjectIteration) session .byNaturalId(HProjectIteration.class) .using("slug", getSlug()) .using("project", projectDAO.getBySlug(projectSlug)).load(); validateIterationState(iteration); versionId = iteration.getId(); return iteration; } else { HProjectIteration iteration = (HProjectIteration) session.load(HProjectIteration.class, versionId); validateIterationState(iteration); return iteration; } } private void validateIterationState(HProjectIteration iteration) { if (iteration == null || iteration.getStatus() == EntityStatus.OBSOLETE) { log.warn( "Project version [id={}, slug={}], does not exist or is soft deleted: {}", versionId, slug, iteration); throw new EntityNotFoundException(); } } public void updateRequireTranslationReview(String key, boolean checked) { identity.checkPermission(instance, "update"); getInstance().setRequireTranslationReview(checked); update(); if (checked) { conversationScopeMessages.setMessage(FacesMessage.SEVERITY_INFO, msgs.get("jsf.iteration.requireReview.enabled")); } else { conversationScopeMessages .setMessage(FacesMessage.SEVERITY_INFO, msgs.get("jsf.iteration.requireReview.disabled")); } } public List<ValidationAction> getValidationList() { List<ValidationAction> sortedList = Lists.newArrayList(getValidations().values()); Collections.sort(sortedList, ValidationFactory.ValidationActionComparator); return sortedList; } private Map<ValidationId, ValidationAction> getValidations() { if (availableValidations.isEmpty()) { Collection<ValidationAction> validationList = validationServiceImpl.getValidationActions(projectSlug, getInstance().getSlug()); for (ValidationAction validationAction : validationList) { availableValidations.put(validationAction.getId(), validationAction); } } return availableValidations; } public void validateSuppliedId() { getInstance(); // this will raise an EntityNotFound exception // when id is invalid and conversation will not // start } public ProjectType getProjectType() { if (getInstance().getProjectType() == null) { getInstance().setProjectType( getInstance().getProject().getDefaultProjectType()); } return getInstance().getProjectType(); } public void setProjectType(ProjectType projectType) { getInstance().setProjectType(projectType); } public void validateProjectSlug() { if (projectDAO.getBySlug(projectSlug) == null) { throw new EntityNotFoundException("no entity with slug " + projectSlug); } } public void verifySlugAvailable(ValueChangeEvent e) { String slug = (String) e.getNewValue(); validateSlug(slug, e.getComponent().getId()); } public boolean validateSlug(String slug, String componentId) { if (!isSlugAvailable(slug)) { facesMessages.addToControl(componentId, "This Version ID has been used in this project"); return false; } boolean valid = new SlugValidator().isValid(slug, null); if (!valid) { String validationMessages = ResourceBundle.getBundle("ValidationMessages").getString( "javax.validation.constraints.Slug.message"); facesMessages.addToControl(componentId, validationMessages); return false; } return true; } public boolean isSlugAvailable(String slug) { return slugEntityServiceImpl.isProjectIterationSlugAvailable(slug, projectSlug); } public String createVersion() { if (!validateSlug(inputSlugValue, "slug")) return "invalid-slug"; if (copyFromVersion) { copyVersion(); return "copy-version"; } else { return persist(); } } public void copyVersion() { getInstance().setSlug(inputSlugValue); getInstance().setStatus(EntityStatus.READONLY); // create basic version here HProject project = getProject(); project.addIteration(getInstance()); super.persist(); copyVersionManager.startCopyVersion(projectSlug, copyFromVersionSlug, getInstance().getSlug()); conversationScopeMessages .setMessage(FacesMessage.SEVERITY_INFO, msgs. format("jsf.copyVersion.started", getInstance().getSlug(), copyFromVersionSlug)); } public void setSlug(String slug) { this.slug = slug; this.inputSlugValue = slug; } @Override public String persist() { if (!validateSlug(getInputSlugValue(), "slug")) { return null; } getInstance().setSlug(getInputSlugValue()); updateProjectType(); HProject project = getProject(); project.addIteration(getInstance()); // FIXME this looks only to be used when copying a version. // so it should copy the setting for isOverrideLocales, // and all enabled locales and locale alias data if it is // overriding. List<HLocale> projectLocales = localeServiceImpl .getSupportedLanguageByProject(projectSlug); getInstance().getCustomizedLocales().addAll(projectLocales); getInstance().getCustomizedValidations().putAll( project.getCustomizedValidations()); return super.persist(); } @Override public Object getId() { return projectSlug + "/" + slug; } @Override public NaturalIdentifier getNaturalId() { return Restrictions.naturalId().set("slug", slug) .set("project", projectDAO.getBySlug(projectSlug)); } @Override public boolean isIdDefined() { return slug != null && projectSlug != null; } public boolean isValidationsSameAsProject() { Collection<ValidationAction> versionValidations = validationServiceImpl.getValidationActions(projectSlug, slug); Collection<ValidationAction> projectValidations = validationServiceImpl.getValidationActions(projectSlug); return versionValidations.equals(projectValidations); } public void copyValidationFromProject() { getInstance().getCustomizedValidations().clear(); getInstance().getCustomizedValidations().putAll( getInstance().getProject().getCustomizedValidations()); availableValidations.clear(); update(); conversationScopeMessages .setMessage( FacesMessage.SEVERITY_INFO, msgs.get( "jsf.iteration.CopyProjectValidations.message")); } /** * Flush changes to the database, and raise an event to communicate that * the version has been changed. * * @return the String "updated" */ @Override public String update() { identity.checkPermission(instance, "update"); if (!getInputSlugValue().equals(slug) && !validateSlug(getInputSlugValue(), "slug")) { return null; } getInstance().setSlug(getInputSlugValue()); boolean softDeleted = false; if (getInstance().getStatus() == EntityStatus.OBSOLETE) { // if we offer delete in REST, we need to move this to hibernate listener String newSlug = getInstance().changeToDeletedSlug(); getInstance().setSlug(newSlug); softDeleted = true; } String state = super.update(); if (softDeleted) { String url = urlUtil.projectUrl(projectSlug); FacesManager.instance().redirectToExternalURL(url); return state; } if (!slug.equals(getInstance().getSlug())) { slug = getInstance().getSlug(); return "versionSlugUpdated"; } return state; } @Override protected void updatedMessage() { // Disable the default message from Seam } public void updateStatus(char initial) { identity.checkPermission(instance, "update"); String message = msgs.format("jsf.iteration.status.updated", EntityStatus.valueOf(initial)); getInstance().setStatus(EntityStatus.valueOf(initial)); if (getInstance().getStatus() == EntityStatus.OBSOLETE) { message = msgs.get("jsf.iteration.deleted"); } update(); facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, message); } public void deleteSelf() { updateStatus('O'); } public void updateSelectedProjectType(ValueChangeEvent e) { selectedProjectType = (String) e.getNewValue(); updateProjectType(); } public void copyProjectTypeFromProject() { getInstance().setProjectType( getInstance().getProject().getDefaultProjectType()); update(); conversationScopeMessages.setMessage(FacesMessage.SEVERITY_INFO, msgs.get("jsf.iteration.CopyProjectType.message")); } /** * @return comma-separated list of accepted file extensions. May be an empty * string */ public String getAcceptedSourceFileExtensions() { List<String> supportedTypes = Lists.transform(ProjectType .getSupportedSourceFileTypes(getProjectType()), new Function<DocumentType, String>() { @Override public String apply(DocumentType docType) { return Joiner.on(",").join( docType.getSourceExtensions()); } }); return Joiner.on(", ").join(supportedTypes); } public String getAcceptedSourceFile() { List<String> supportedTypes = Lists.transform(ProjectType .getSupportedSourceFileTypes(getProjectType()), new Function<DocumentType, String>() { @Override public String apply(DocumentType docType) { return docType.name() + "[" + Joiner.on(",").join( docType.getSourceExtensions()) + "]"; } }); return Joiner.on(", ").join(supportedTypes); } private void updateProjectType() { if (!StringUtils.isEmpty(selectedProjectType) && !selectedProjectType.equals("null")) { ProjectType projectType = ProjectType.valueOf(selectedProjectType); getInstance().setProjectType(projectType); } else { getInstance().setProjectType(null); } } public List<ValidationAction.State> getValidationStates() { return Arrays.asList(ValidationAction.State.values()); } public void updateValidationOption(String name, String state) { identity.checkPermission(instance, "update"); ValidationId validationId = ValidationId.valueOf(name); for (Map.Entry<ValidationId, ValidationAction> entry : getValidations() .entrySet()) { if (entry.getKey().name().equals(name)) { getValidations().get(validationId).setState( ValidationAction.State.valueOf(state)); getInstance().getCustomizedValidations().put( entry.getKey().name(), entry.getValue().getState().name()); ensureMutualExclusivity(getValidations().get(validationId)); break; } } update(); conversationScopeMessages.setMessage(FacesMessage.SEVERITY_INFO, msgs.format("jsf.validation.updated", validationId.getDisplayName(), state)); } /** * If this action is enabled(Warning or Error), then it's exclusive * validation will be turn off * */ private void ensureMutualExclusivity( ValidationAction selectedValidationAction) { if (selectedValidationAction.getState() != ValidationAction.State.Off) { for (ValidationAction exclusiveValAction : selectedValidationAction .getExclusiveValidations()) { getInstance().getCustomizedValidations().put( exclusiveValAction.getId().name(), ValidationAction.State.Off.name()); getValidations().get(exclusiveValAction.getId()).setState( ValidationAction.State.Off); } } } public List<ProjectType> getProjectTypeList() { List<ProjectType> projectTypes = Arrays.asList(ProjectType.values()); Collections.sort(projectTypes, ComparatorUtil.PROJECT_TYPE_COMPARATOR); return projectTypes; } public boolean isOverrideLocales() { return getInstance().isOverrideLocales(); } public void setOverrideLocales(boolean overrideLocales) { identity.checkPermission(instance, "update"); getInstance().setOverrideLocales(overrideLocales); } public Map<LocaleId, String> getLocaleAliases() { return LocaleServiceImpl.getLocaleAliasesByIteration(getInstance()); } public void removeAllLocaleAliases() { identity.checkPermission(instance, "update"); List<LocaleId> removed = new ArrayList<>(); List<LocaleId> aliasedLocales = new ArrayList<>(getLocaleAliases().keySet()); if (!aliasedLocales.isEmpty()) { ensureOverridingLocales(); for (LocaleId aliasedLocale : aliasedLocales) { boolean hadAlias = removeAliasSilently(aliasedLocale); if (hadAlias) { removed.add(aliasedLocale); } } } // else no locales to remove, nothing to do. showRemovedAliasesMessage(removed); } /** * Ensure that isOverrideLocales is true, and copy data if necessary. */ private void ensureOverridingLocales() { if (!isOverrideLocales()) { startOverridingLocales(); } } /** * Copy locale data from project and set overrideLocales, in preparation for * making customizations to the locales. */ private void startOverridingLocales() { // Copied before setOverrideLocales(true) so that the currently returned // values will be used as the basis for any customization. List<HLocale> enabledLocales = getEnabledLocales(); Map<LocaleId, String> localeAliases = getLocaleAliases(); setOverrideLocales(true); // Replace contents rather than entire collections to avoid confusion // with reference to the collections that are bound before this runs. getInstance().getCustomizedLocales().clear(); getInstance().getCustomizedLocales().addAll(enabledLocales); getInstance().getLocaleAliases().clear(); getInstance().getLocaleAliases().putAll(localeAliases); enteredLocaleAliases.clear(); enteredLocaleAliases.putAll(localeAliases); refreshDisabledLocales(); } /** * Update disabled locales to be consistent with enabled locales. */ private void refreshDisabledLocales() { // will be re-generated with correct values next time it is fetched. disabledLocales = null; } public void removeSelectedLocaleAliases() { identity.checkPermission(instance, "update"); List<LocaleId> removed = new ArrayList<>(); for (Map.Entry<LocaleId, Boolean> entry : getSelectedEnabledLocales().entrySet()) { if (entry.getValue()) { boolean hadAlias = removeAliasSilently(entry.getKey()); if (hadAlias) { removed.add(entry.getKey()); } } } showRemovedAliasesMessage(removed); } /** * Show an appropriate message for the removal of aliases from locales * with the given IDs. * * @param removed ids of locales that had aliases removed */ private void showRemovedAliasesMessage(List<LocaleId> removed) { if (removed.isEmpty()) { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.get("jsf.LocaleAlias.NoAliasesToRemove")); } else if (removed.size() == 1) { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.LocaleAlias.AliasRemoved", removed.get(0))); } else { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.LocaleAlias.AliasesRemoved", StringUtils.join(removed, ", "))); } } private boolean removeAliasSilently(LocaleId localeId) { return setLocaleAliasSilently(localeId, ""); } public String getLocaleAlias(HLocale locale) { return getLocaleAliases().get(locale.getLocaleId()); } public boolean hasLocaleAlias(HLocale locale) { return getLocaleAliases().containsKey(locale.getLocaleId()); } /** * A separate map is used, rather than binding the alias map from the * project directly. This is done so that empty values are not added to the * map in every form submission, and so that a value entered in the field * for a row is not automatically updated when a different row is submitted. */ @Getter @Setter private Map<LocaleId, String> enteredLocaleAliases = Maps.newHashMap(); public void updateToEnteredLocaleAlias(LocaleId localeId) { identity.checkPermission(instance, "update"); String enteredAlias = enteredLocaleAliases.get(localeId); setLocaleAlias(localeId, enteredAlias); } private void setLocaleAlias(LocaleId localeId, String alias) { boolean hadAlias = setLocaleAliasSilently(localeId, alias); if (isNullOrEmpty(alias)) { if (hadAlias) { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.LocaleAlias.AliasRemoved", localeId)); } else { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.LocaleAlias.NoAliasToRemove", localeId)); } } else { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.LocaleAlias.AliasSet", localeId, alias)); } } /** * Set or remove a locale alias without showing any message. * * @param localeId for which to set alias * @param alias new alias to use. Use empty string to remove alias. * @return true if there was already an alias, otherwise false. */ private boolean setLocaleAliasSilently(LocaleId localeId, String alias) { HProjectIteration instance = getInstance(); Map<LocaleId, String> aliases = instance.getLocaleAliases(); boolean hadAlias = aliases.containsKey(localeId); if (isNullOrEmpty(alias)) { if (hadAlias) { ensureOverridingLocales(); aliases.remove(localeId); } } else { final boolean sameAlias = hadAlias && alias.equals(aliases.get(localeId)); if (!sameAlias) { ensureOverridingLocales(); aliases.put(localeId, alias); } } update(); return hadAlias; } public void useDefaultLocales() { identity.checkPermission(instance, "update"); setOverrideLocales(false); refreshDisabledLocales(); } @Getter @Setter private String enabledLocalesFilter = ""; @Getter @Setter private String disabledLocalesFilter; public List<HLocale> getEnabledLocales() { if (StringUtils.isNotEmpty(projectSlug) && StringUtils.isNotEmpty(slug)) { List<HLocale> locales = localeServiceImpl.getSupportedLanguageByProjectIteration( projectSlug, slug); Collections.sort(locales, ComparatorUtil.LOCALE_COMPARATOR); return locales; } return Lists.newArrayList(); } @Getter @Setter private Map<LocaleId, Boolean> selectedEnabledLocales = Maps.newHashMap(); // Not sure if this is necessary, seems to work ok on selected disabled // locales without this. public Map<LocaleId, Boolean> getSelectedEnabledLocales() { if (selectedEnabledLocales == null) { selectedEnabledLocales = Maps.newHashMap(); for (HLocale locale : getEnabledLocales()) { selectedEnabledLocales.put(locale.getLocaleId(), Boolean.FALSE); } } return selectedEnabledLocales; } public void disableSelectedLocales() { identity.checkPermission(instance, "update"); List<LocaleId> toRemove = Lists.newArrayList(); for (Map.Entry<LocaleId, Boolean> entry : getSelectedEnabledLocales().entrySet()) { if (entry.getValue()) { toRemove.add(entry.getKey()); } } List<LocaleId> removed = Lists.newArrayList(); for(LocaleId localeId: toRemove) { boolean wasEnabled = disableLocaleSilently(localeId); if (wasEnabled) { removed.add(localeId); } } if (removed.isEmpty()) { // This should not be possible in the UI, but maybe if multiple users are editing it. } else if (removed.size() == 1) { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.languageSettings.LanguageDisabled", removed.get(0))); } else { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.languageSettings.LanguagesDisabled", StringUtils.join(removed, ", "))); } } private boolean disableLocaleSilently(LocaleId localeId) { HLocale locale = localeServiceImpl.getByLocaleId(localeId); return disableLocaleSilently(locale); } public void disableLocale(HLocale locale) { identity.checkPermission(instance, "update"); boolean wasEnabled = disableLocaleSilently(locale); if (wasEnabled) { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.languageSettings.LanguageDisabled", locale.getLocaleId())); } // TODO consider showing a message like "Locale {0} was already disabled." } /** * Disable a locale without printing any message. * * @param locale to disable * @return true if the locale was enabled before this call, false otherwise. */ private boolean disableLocaleSilently(HLocale locale) { boolean wasEnabled; if (getEnabledLocales().contains(locale)) { ensureOverridingLocales(); wasEnabled = getInstance().getCustomizedLocales().remove(locale); refreshDisabledLocales(); // TODO consider using alias from project as default rather than none. getLocaleAliases().remove(locale.getLocaleId()); getSelectedEnabledLocales().remove(locale.getLocaleId()); update(); } else { wasEnabled = false; } return wasEnabled; } private List<HLocale> disabledLocales; public List<HLocale> getDisabledLocales() { if(disabledLocales == null) { disabledLocales = findActiveNotEnabledLocales(); } return disabledLocales; } /** * Populate the list of available locales after filtering out the locales * already in the project. */ private List<HLocale> findActiveNotEnabledLocales() { Collection<HLocale> filtered = Collections2.filter(localeDAO.findAllActive(), new Predicate<HLocale>() { @Override public boolean apply(HLocale input) { // only include those not already in the project return !getEnabledLocales().contains(input); } }); return Lists.newArrayList(filtered); } @Getter @Setter private Map<LocaleId, Boolean> selectedDisabledLocales = Maps.newHashMap(); public void enableSelectedLocales() { identity.checkPermission(instance, "update"); List<LocaleId> enabled = new ArrayList<>(); for (Map.Entry<LocaleId, Boolean> entry : selectedDisabledLocales .entrySet()) { if (entry.getValue()) { boolean wasDisabled = enableLocaleSilently(entry.getKey()); if (wasDisabled) { enabled.add(entry.getKey()); } } } selectedDisabledLocales.clear(); if (enabled.isEmpty()) { // This should not be possible in the UI, but maybe if multiple users are editing it. } else if (enabled.size() == 1) { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.languageSettings.LanguageEnabled", enabled.get(0))); } else { facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.languageSettings.LanguagesEnabled", StringUtils.join(enabled, ", "))); } } public void enableLocale(HLocale locale) { identity.checkPermission(instance, "update"); boolean wasDisabled = enableLocaleSilently(locale); if (wasDisabled) { LocaleId localeId = locale.getLocaleId(); facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, msgs.format("jsf.languageSettings.LanguageEnabled", localeId)); } // TODO consider printing message like "Locale {0} was already enabled" } private boolean enableLocaleSilently(LocaleId localeId) { HLocale locale = localeServiceImpl.getByLocaleId(localeId); return enableLocaleSilently(locale); } private boolean enableLocaleSilently(HLocale locale) { final boolean wasDisabled = getDisabledLocales().contains(locale); if (wasDisabled) { ensureOverridingLocales(); getInstance().getCustomizedLocales().add(locale); getSelectedEnabledLocales().put(locale.getLocaleId(), Boolean.FALSE); refreshDisabledLocales(); update(); } // else locale already enabled, nothing to do. return wasDisabled; } }
fix checkstyle
zanata-war/src/main/java/org/zanata/action/VersionHome.java
fix checkstyle
<ide><path>anata-war/src/main/java/org/zanata/action/VersionHome.java <ide> msgs.get("jsf.LocaleAlias.NoAliasesToRemove")); <ide> } else if (removed.size() == 1) { <ide> facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, <del> msgs.format("jsf.LocaleAlias.AliasRemoved", removed.get(0))); <add> msgs.format("jsf.LocaleAlias.AliasRemoved", removed.get(0))); <ide> } else { <ide> facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, <ide> msgs.format("jsf.LocaleAlias.AliasesRemoved", <ide> msgs.format("jsf.LocaleAlias.AliasRemoved", localeId)); <ide> } else { <ide> facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, <del> msgs.format("jsf.LocaleAlias.NoAliasToRemove", localeId)); <add> msgs.format("jsf.LocaleAlias.NoAliasToRemove", localeId)); <ide> } <ide> } else { <ide> facesMessages.addGlobal(FacesMessage.SEVERITY_INFO, <ide> } <ide> <ide> List<LocaleId> removed = Lists.newArrayList(); <del> <ide> for(LocaleId localeId: toRemove) { <ide> boolean wasEnabled = disableLocaleSilently(localeId); <ide> if (wasEnabled) {
Java
apache-2.0
93720cc7ddfa20928229a6dc62e258cf19965323
0
openengsb/openengsb,openengsb/openengsb,openengsb/openengsb,openengsb/openengsb,openengsb/openengsb,openengsb/openengsb
/** * Licensed to the Austrian Association for Software Tool Integration (AASTI) * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. The AASTI 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.openengsb.connector.virtual.filewatcher.internal; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import org.openengsb.connector.virtual.filewatcher.FileSerializer; import org.openengsb.core.api.model.OpenEngSBModelEntry; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import com.google.common.collect.Lists; public class CSVParser<ResultType> implements FileSerializer<ResultType> { private abstract class OpenEngSBModelMixin { @JsonIgnore abstract List<OpenEngSBModelEntry> getOpenEngSBModelTail(); } private Class<ResultType> resultType; public CSVParser(Class<ResultType> resultType) { this.resultType = resultType; } @Override public List<ResultType> readFile(File path) throws IOException { CsvMapper csvMapper = new CsvMapper(); CsvSchema schema = csvMapper.schemaFor(resultType); try { MappingIterator<ResultType> iterator = csvMapper.reader(schema).withType(resultType) .readValues(path); return Lists.newArrayList(iterator); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void writeFile(File path, List<ResultType> models) throws IOException { CsvMapper csvMapper = new CsvMapper(); csvMapper.addMixInAnnotations(resultType, OpenEngSBModelMixin.class); CsvSchema schema = csvMapper.schemaFor(resultType); System.out.println(schema.getColumnDesc()); ObjectWriter writer = csvMapper.writer(schema); // supplying the file directly does not work. // java.lang.UnsupportedOperationException: Generator of type com.fasterxml.jackson.core.json.UTF8JsonGenerator // does not support schema of type 'CSV' writer.writeValue(new FileOutputStream(path), models); } }
connector/filewatcher/src/main/java/org/openengsb/connector/virtual/filewatcher/internal/CSVParser.java
/** * Licensed to the Austrian Association for Software Tool Integration (AASTI) * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. The AASTI 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.openengsb.connector.virtual.filewatcher.internal; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import org.openengsb.connector.virtual.filewatcher.FileSerializer; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import com.google.common.collect.Lists; public class CSVParser<ResultType> implements FileSerializer<ResultType> { private Class<ResultType> resultType; public CSVParser(Class<ResultType> resultType) { this.resultType = resultType; } @Override public List<ResultType> readFile(File path) throws IOException { CsvMapper csvMapper = new CsvMapper(); CsvSchema schema = csvMapper.schemaFor(resultType); try { MappingIterator<ResultType> iterator = csvMapper.reader(schema).withType(resultType) .readValues(path); return Lists.newArrayList(iterator); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void writeFile(File path, List<ResultType> models) throws IOException { CsvMapper csvMapper = new CsvMapper(); CsvSchema schema = csvMapper.schemaFor(resultType); System.out.println(schema.getColumnDesc()); ObjectWriter writer = csvMapper.writer(schema); // supplying the file directly does not work. // java.lang.UnsupportedOperationException: Generator of type com.fasterxml.jackson.core.json.UTF8JsonGenerator // does not support schema of type 'CSV' writer.writeValue(new FileOutputStream(path), models); } }
[OPENENGSB-3375] handle OpenEngSBModel-properties correctly in CSV-parser
connector/filewatcher/src/main/java/org/openengsb/connector/virtual/filewatcher/internal/CSVParser.java
[OPENENGSB-3375] handle OpenEngSBModel-properties correctly in CSV-parser
<ide><path>onnector/filewatcher/src/main/java/org/openengsb/connector/virtual/filewatcher/internal/CSVParser.java <ide> import java.util.List; <ide> <ide> import org.openengsb.connector.virtual.filewatcher.FileSerializer; <add>import org.openengsb.core.api.model.OpenEngSBModelEntry; <ide> <add>import com.fasterxml.jackson.annotation.JsonIgnore; <ide> import com.fasterxml.jackson.databind.MappingIterator; <ide> import com.fasterxml.jackson.databind.ObjectWriter; <ide> import com.fasterxml.jackson.dataformat.csv.CsvMapper; <ide> import com.google.common.collect.Lists; <ide> <ide> public class CSVParser<ResultType> implements FileSerializer<ResultType> { <add> <add> private abstract class OpenEngSBModelMixin { <add> @JsonIgnore <add> abstract List<OpenEngSBModelEntry> getOpenEngSBModelTail(); <add> } <ide> <ide> private Class<ResultType> resultType; <ide> <ide> @Override <ide> public void writeFile(File path, List<ResultType> models) throws IOException { <ide> CsvMapper csvMapper = new CsvMapper(); <add> csvMapper.addMixInAnnotations(resultType, OpenEngSBModelMixin.class); <ide> CsvSchema schema = csvMapper.schemaFor(resultType); <ide> System.out.println(schema.getColumnDesc()); <ide> ObjectWriter writer = csvMapper.writer(schema);
Java
mpl-2.0
8258a4d5abdc4166714091fb6fad5805d8773bfc
0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: InstallData.java,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2007-07-03 11:48:43 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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.openoffice.setup; import org.openoffice.setup.SetupData.PackageDescription; import org.openoffice.setup.Util.Controller; import org.openoffice.setup.Util.SystemManager; import java.io.File; import java.util.HashMap; import java.util.Vector; public class InstallData { public static final String ACTION_TYPICAL = "ActionTypical"; public static final String ACTION_CUSTOM = "ActionCustom"; private static InstallData instance = null; static private boolean isUserInstallation; /* root or user installation? */ static private boolean isRootInstallation; /* root or user installation? */ static private boolean isInstallationMode; /* installation or uninstallation? */ static private boolean isUninstallationMode; /* installation or uninstallation? */ static private boolean isCustomInstallation = false; /* custom or typical? */ static private boolean isTypicalInstallation = true; /* custom or typical? */ static private boolean isSolarisUserInstallation = false; static private boolean isChangeInstallation = false; static private boolean stillRunning = false; static private boolean stillAnalyzing = true; static private boolean databaseAnalyzed = false; /* the database was already analyzed? */ static private boolean moduleSizeSet = false; /* the database was already analyzed? */ static private boolean preInstallDone = false; /* preInstall script already executed? */ static private boolean isAbortedInstallation = false; static private boolean isErrorInstallation = false; static private boolean logModuleStates = false; /* logging the current state of modules */ static private boolean visibleModulesChecked = false; /* checking, if the user selected modules */ static private boolean isMaskedCompleteUninstallation = false; /* checking if all visible modules are uninstalled */ static private boolean typicalSelectionStateSaved = false; static private boolean customSelectionStateSaved = false; static private boolean startSelectionStateSaved = false; static private boolean olderVersionExists = false; static private boolean sameVersionExists = false; static private boolean newerVersionExists = false; static private String installType; /* custom or typical installation */ static private String osType; /* Linux, SunOS, ... */ static private String installDir = null; static private String installRoot = null; /* Root directory for Solaris user installation */ static private String defaultDir = "/opt/OpenOffice.org"; static private String packageFormat = null; static private String packagePath = null; static private String packageSubdir = "packages"; static private String adminFileNameReloc = null; static private String adminFileNameNoReloc = null; static private String databasePath = null; static private String getUidPath = null; static private String installationPrivileges = null; static private String storedInstallationPrivileges = null; /* privileges saved in file */ static private String localTempPath = null; static private String installDirName = "installdata"; static private String uninstallDirName = "uninstalldata"; static private int availableDiscSpace = 0; static private File jarFilePath = null; static private File resourceRoot; static private File infoRoot; static private HashMap shellEnvironment = null; /* Solaris environment for user install */ static private PackageDescription updatePackage = null; static private Vector removeFiles = new Vector(); /* Files to remove, if installation is aborted */ static private Vector installPackages = new Vector(); public static InstallData getInstance() { if (instance == null) { instance = new InstallData(); } return instance; } private InstallData() { installType = ACTION_TYPICAL; // default installation type isUserInstallation = SystemManager.isUserInstallation(); isRootInstallation = !isUserInstallation; setInstallationPrivileges(isUserInstallation); osType = SystemManager.getOSType(); resourceRoot = SystemManager.getResourceRoot(); setInstallationMode(); setSolarisUserInstall(); setHtmlFileExistence(); } public void setInstallationType(String installationtype) { installType = installationtype; if ( installType.equals(this.getCustomActionCommand())) { isCustomInstallation = true; isTypicalInstallation = false; } if ( installType.equals(this.getTypicalActionCommand())) { isCustomInstallation = false; isTypicalInstallation = true; } } private void setInstallationMode() { // Exists a directory "uninstalldata" below the resource root? File uninstallDir = new File(resourceRoot, uninstallDirName); File installDir = new File(resourceRoot, installDirName); if ( SystemManager.exists_directory(uninstallDir.getPath())) { isInstallationMode = false; isUninstallationMode = true; infoRoot = uninstallDir; System.err.println("Mode: uninstallation"); } else if ( SystemManager.exists_directory(installDir.getPath())) { isInstallationMode = true; isUninstallationMode = false; infoRoot = installDir; System.err.println("Mode: installation"); } else { // isInstallationMode = null; // isUninstallationMode = null; infoRoot = null; System.err.println("Error: Did not find info path"); System.err.println("Error: No info about installation or uninstallation"); System.exit(1); } } private void setSolarisUserInstall() { if (( isUserInstallation ) && (osType.equalsIgnoreCase("SunOS"))) { isSolarisUserInstallation = true; if ( isInstallationMode ) { Controller.checkForUidFile(this); } } } private void setHtmlFileExistence() { // After inforoot is determined, the existence of files in subdirectory "html" can be checked File htmlDirectory = getInfoRoot("html"); ResourceManager.checkFileExistence(htmlDirectory); } private void setInstallationPrivileges(boolean isUserInstallation) { if ( isUserInstallation ) { installationPrivileges = "user"; } else { installationPrivileges = "root"; } } public String getInstallationType() { return installType; } public String getCustomActionCommand() { return ACTION_CUSTOM; } public String getTypicalActionCommand() { return ACTION_TYPICAL; } public String getInstallationPrivileges() { return installationPrivileges; } public String getOSType() { return osType; } public File getResourceRoot() { return resourceRoot; } public File getResourceRoot(String subDirectory) { File dir = getResourceRoot(); if (dir != null) { dir = new File(dir, subDirectory); if (!dir.exists()) { dir = null; } } return dir; } public File getInfoRoot() { return infoRoot; } public File getInfoRoot(String subDirectory) { File dir = new File(infoRoot, subDirectory); if (!dir.exists()) { dir = null; } return dir; } public boolean isUserInstallation() { return isUserInstallation; } public boolean isRootInstallation() { return isRootInstallation; } public boolean isInstallationMode() { return isInstallationMode; } public boolean isUninstallationMode() { return isUninstallationMode; } public boolean isSolarisUserInstallation() { return isSolarisUserInstallation; } public String getDefaultDir() { return defaultDir; } public void setDefaultDir(String dir) { defaultDir = dir; } public String getInstallDirName() { return installDirName; } public String getUninstallDirName() { return uninstallDirName; } public String getInstallDir() { return installDir; } public void setInstallDir(String dir) { installDir = dir; } public String getInstallRoot() { return installRoot; } public void setInstallRoot(String dir) { installRoot = dir; } public String getDatabasePath() { return databasePath; } public void setDatabasePath(String path) { databasePath = path; } public String getPackagePath() { if ( packagePath == null ) { packagePath = SystemManager.getPackagePath(packageSubdir); } return packagePath; } public void setPackagePath(String path) { packagePath = path; } public String getPackageSubdir() { return packageSubdir; } public void setPackageSubdir(String dir) { packageSubdir = dir; } public String getPackageFormat() { return packageFormat; } public void setPackageFormat(String format) { packageFormat = format; } public String getLocalTempPath() { return localTempPath; } public void setLocalTempPath(String path) { localTempPath = path; } public int getAvailableDiscSpace() { return availableDiscSpace; } public void setAvailableDiscSpace(int space) { availableDiscSpace = space; } public String getAdminFileNameReloc() { return adminFileNameReloc; } public void setAdminFileNameReloc(String fileName) { adminFileNameReloc = fileName; } public String getAdminFileNameNoReloc() { return adminFileNameNoReloc; } public void setAdminFileNameNoReloc(String fileName) { adminFileNameNoReloc = fileName; } public String getGetUidPath() { return getUidPath; } public void setGetUidPath(String filePath) { getUidPath = filePath; } public String getStoredInstallationPrivileges() { return storedInstallationPrivileges; } public void setStoredInstallationPrivileges(String privileges) { storedInstallationPrivileges = privileges; } public void setStillRunning(boolean running) { stillRunning = running; } public boolean stillRunning() { return stillRunning; } public void setStillAnalyzing(boolean running) { stillAnalyzing = running; } public boolean stillAnalyzing() { return stillAnalyzing; } public void setDatabaseAnalyzed(boolean analyzed) { databaseAnalyzed = analyzed; } public boolean databaseAnalyzed() { return databaseAnalyzed; } public void setModuleSizeSet(boolean set) { moduleSizeSet = set; } public boolean moduleSizeSet() { return moduleSizeSet; } public void setPreInstallDone(boolean done) { preInstallDone = done; } public boolean preInstallDone() { return preInstallDone; } public boolean isChangeInstallation() { return isChangeInstallation; } public void setIsChangeInstallation(boolean changeInstallation) { isChangeInstallation = changeInstallation; } public boolean isTypicalInstallation() { return isTypicalInstallation; } public boolean isCustomInstallation() { return isCustomInstallation; } public boolean isAbortedInstallation() { return isAbortedInstallation; } public void setIsAbortedInstallation(boolean abortedInstallation) { isAbortedInstallation = abortedInstallation; } public boolean isErrorInstallation() { return isErrorInstallation; } public void setIsErrorInstallation(boolean errorInstallation) { isErrorInstallation = errorInstallation; } public boolean logModuleStates() { return logModuleStates; } public void setLogModuleStates(boolean log) { logModuleStates = log; } public boolean visibleModulesChecked() { return visibleModulesChecked; } public void setVisibleModulesChecked(boolean checked) { visibleModulesChecked = checked; } public boolean isMaskedCompleteUninstallation() { return isMaskedCompleteUninstallation; } public void setMaskedCompleteUninstallation(boolean masked) { isMaskedCompleteUninstallation = masked; } public boolean typicalSelectionStateSaved() { return typicalSelectionStateSaved; } public void setTypicalSelectionStateSaved(boolean saved) { typicalSelectionStateSaved = saved; } public boolean customSelectionStateSaved() { return customSelectionStateSaved; } public void setCustomSelectionStateSaved(boolean saved) { customSelectionStateSaved = saved; } public boolean startSelectionStateSaved() { return startSelectionStateSaved; } public void setStartSelectionStateSaved(boolean saved) { startSelectionStateSaved = saved; } public boolean olderVersionExists() { return olderVersionExists; } public void setOlderVersionExists(boolean exists) { olderVersionExists = exists; } public boolean sameVersionExists() { return sameVersionExists; } public void setSameVersionExists(boolean exists) { sameVersionExists = exists; } public boolean newerVersionExists() { return newerVersionExists; } public void setNewerVersionExists(boolean exists) { newerVersionExists = exists; } public PackageDescription getUpdatePackage() { return updatePackage; } public void setUpdatePackage(PackageDescription onePackage) { updatePackage = onePackage; } public HashMap getShellEnvironment() { return shellEnvironment; } public Vector getRemoveFiles() { return removeFiles; } public Vector getInstallPackages() { return installPackages; } public void setInstallPackages(Vector packages) { installPackages = packages; } public void setShellEnvironment(HashMap environment) { shellEnvironment = environment; } public File getJarFilePath() { if ( jarFilePath == null ) { jarFilePath = SystemManager.getJarFilePath(); } return jarFilePath; } }
javainstaller2/src/JavaSetup/org/openoffice/setup/InstallData.java
package org.openoffice.setup; import org.openoffice.setup.SetupData.PackageDescription; import org.openoffice.setup.Util.SystemManager; import java.io.File; import java.util.HashMap; import java.util.Vector; public class InstallData { public static final String ACTION_TYPICAL = "ActionTypical"; public static final String ACTION_CUSTOM = "ActionCustom"; private static InstallData instance = null; static private boolean isUserInstallation; /* root or user installation? */ static private boolean isRootInstallation; /* root or user installation? */ static private boolean isInstallationMode; /* installation or uninstallation? */ static private boolean isUninstallationMode; /* installation or uninstallation? */ static private boolean isCustomInstallation = false; /* custom or typical? */ static private boolean isTypicalInstallation = true; /* custom or typical? */ static private boolean isSolarisUserInstallation = false; static private boolean isChangeInstallation = false; static private boolean stillRunning = false; static private boolean stillAnalyzing = true; static private boolean databaseAnalyzed = false; /* the database was already analyzed? */ static private boolean moduleSizeSet = false; /* the database was already analyzed? */ static private boolean preInstallDone = false; /* preInstall script already executed? */ static private boolean isAbortedInstallation = false; static private boolean isErrorInstallation = false; static private boolean logModuleStates = false; /* logging the current state of modules */ static private boolean visibleModulesChecked = false; /* checking, if the user selected modules */ static private boolean isMaskedCompleteUninstallation = false; /* checking if all visible modules are uninstalled */ static private boolean typicalSelectionStateSaved = false; static private boolean customSelectionStateSaved = false; static private boolean startSelectionStateSaved = false; static private boolean olderVersionExists = false; static private boolean sameVersionExists = false; static private boolean newerVersionExists = false; static private String installType; /* custom or typical installation */ static private String osType; /* Linux, SunOS, ... */ static private String installDir = null; static private String installRoot = null; /* Root directory for Solaris user installation */ static private String defaultDir = "/opt/OpenOffice.org"; static private String packageFormat = null; static private String packagePath = null; static private String packageSubdir = "packages"; static private String adminFileNameReloc = null; static private String adminFileNameNoReloc = null; static private String databasePath = null; static private String getUidPath = null; static private String installationPrivileges = null; static private String storedInstallationPrivileges = null; /* privileges saved in file */ static private String localTempPath = null; static private String installDirName = "installdata"; static private String uninstallDirName = "uninstalldata"; static private int availableDiscSpace = 0; static private File jarFilePath = null; static private File resourceRoot; static private File infoRoot; static private HashMap shellEnvironment = null; /* Solaris environment for user install */ static private PackageDescription updatePackage = null; static private Vector removeFiles = new Vector(); /* Files to remove, if installation is aborted */ static private Vector installPackages = new Vector(); public static InstallData getInstance() { if (instance == null) { instance = new InstallData(); } return instance; } private InstallData() { installType = ACTION_TYPICAL; // default installation type isUserInstallation = SystemManager.isUserInstallation(); isRootInstallation = !isUserInstallation; setInstallationPrivileges(isUserInstallation); osType = SystemManager.getOSType(); resourceRoot = SystemManager.getResourceRoot(); setInstallationMode(); setSolarisUserInstall(); setHtmlFileExistence(); } public void setInstallationType(String installationtype) { installType = installationtype; if ( installType.equals(this.getCustomActionCommand())) { isCustomInstallation = true; isTypicalInstallation = false; } if ( installType.equals(this.getTypicalActionCommand())) { isCustomInstallation = false; isTypicalInstallation = true; } } private void setInstallationMode() { // Exists a directory "uninstalldata" below the resource root? File uninstallDir = new File(resourceRoot, uninstallDirName); File installDir = new File(resourceRoot, installDirName); if ( SystemManager.exists_directory(uninstallDir.getPath())) { isInstallationMode = false; isUninstallationMode = true; infoRoot = uninstallDir; System.err.println("Mode: uninstallation"); } else if ( SystemManager.exists_directory(installDir.getPath())) { isInstallationMode = true; isUninstallationMode = false; infoRoot = installDir; System.err.println("Mode: installation"); } else { // isInstallationMode = null; // isUninstallationMode = null; infoRoot = null; System.err.println("Error: Did not find info path"); System.err.println("Error: No info about installation or uninstallation"); System.exit(1); } } private void setSolarisUserInstall() { if (( isUserInstallation ) && (osType.equalsIgnoreCase("SunOS"))) { isSolarisUserInstallation = true; } } private void setHtmlFileExistence() { // After inforoot is determined, the existence of files in subdirectory "html" can be checked File htmlDirectory = getInfoRoot("html"); ResourceManager.checkFileExistence(htmlDirectory); } private void setInstallationPrivileges(boolean isUserInstallation) { if ( isUserInstallation ) { installationPrivileges = "user"; } else { installationPrivileges = "root"; } } public String getInstallationType() { return installType; } public String getCustomActionCommand() { return ACTION_CUSTOM; } public String getTypicalActionCommand() { return ACTION_TYPICAL; } public String getInstallationPrivileges() { return installationPrivileges; } public String getOSType() { return osType; } public File getResourceRoot() { return resourceRoot; } public File getResourceRoot(String subDirectory) { File dir = getResourceRoot(); if (dir != null) { dir = new File(dir, subDirectory); if (!dir.exists()) { dir = null; } } return dir; } public File getInfoRoot() { return infoRoot; } public File getInfoRoot(String subDirectory) { File dir = new File(infoRoot, subDirectory); if (!dir.exists()) { dir = null; } return dir; } public boolean isUserInstallation() { return isUserInstallation; } public boolean isRootInstallation() { return isRootInstallation; } public boolean isInstallationMode() { return isInstallationMode; } public boolean isUninstallationMode() { return isUninstallationMode; } public boolean isSolarisUserInstallation() { return isSolarisUserInstallation; } public String getDefaultDir() { return defaultDir; } public void setDefaultDir(String dir) { defaultDir = dir; } public String getInstallDirName() { return installDirName; } public String getUninstallDirName() { return uninstallDirName; } public String getInstallDir() { return installDir; } public void setInstallDir(String dir) { installDir = dir; } public String getInstallRoot() { return installRoot; } public void setInstallRoot(String dir) { installRoot = dir; } public String getDatabasePath() { return databasePath; } public void setDatabasePath(String path) { databasePath = path; } public String getPackagePath() { if ( packagePath == null ) { packagePath = SystemManager.getPackagePath(packageSubdir); } return packagePath; } public void setPackagePath(String path) { packagePath = path; } public String getPackageSubdir() { return packageSubdir; } public void setPackageSubdir(String dir) { packageSubdir = dir; } public String getPackageFormat() { return packageFormat; } public void setPackageFormat(String format) { packageFormat = format; } public String getLocalTempPath() { return localTempPath; } public void setLocalTempPath(String path) { localTempPath = path; } public int getAvailableDiscSpace() { return availableDiscSpace; } public void setAvailableDiscSpace(int space) { availableDiscSpace = space; } public String getAdminFileNameReloc() { return adminFileNameReloc; } public void setAdminFileNameReloc(String fileName) { adminFileNameReloc = fileName; } public String getAdminFileNameNoReloc() { return adminFileNameNoReloc; } public void setAdminFileNameNoReloc(String fileName) { adminFileNameNoReloc = fileName; } public String getGetUidPath() { return getUidPath; } public void setGetUidPath(String filePath) { getUidPath = filePath; } public String getStoredInstallationPrivileges() { return storedInstallationPrivileges; } public void setStoredInstallationPrivileges(String privileges) { storedInstallationPrivileges = privileges; } public void setStillRunning(boolean running) { stillRunning = running; } public boolean stillRunning() { return stillRunning; } public void setStillAnalyzing(boolean running) { stillAnalyzing = running; } public boolean stillAnalyzing() { return stillAnalyzing; } public void setDatabaseAnalyzed(boolean analyzed) { databaseAnalyzed = analyzed; } public boolean databaseAnalyzed() { return databaseAnalyzed; } public void setModuleSizeSet(boolean set) { moduleSizeSet = set; } public boolean moduleSizeSet() { return moduleSizeSet; } public void setPreInstallDone(boolean done) { preInstallDone = done; } public boolean preInstallDone() { return preInstallDone; } public boolean isChangeInstallation() { return isChangeInstallation; } public void setIsChangeInstallation(boolean changeInstallation) { isChangeInstallation = changeInstallation; } public boolean isTypicalInstallation() { return isTypicalInstallation; } public boolean isCustomInstallation() { return isCustomInstallation; } public boolean isAbortedInstallation() { return isAbortedInstallation; } public void setIsAbortedInstallation(boolean abortedInstallation) { isAbortedInstallation = abortedInstallation; } public boolean isErrorInstallation() { return isErrorInstallation; } public void setIsErrorInstallation(boolean errorInstallation) { isErrorInstallation = errorInstallation; } public boolean logModuleStates() { return logModuleStates; } public void setLogModuleStates(boolean log) { logModuleStates = log; } public boolean visibleModulesChecked() { return visibleModulesChecked; } public void setVisibleModulesChecked(boolean checked) { visibleModulesChecked = checked; } public boolean isMaskedCompleteUninstallation() { return isMaskedCompleteUninstallation; } public void setMaskedCompleteUninstallation(boolean masked) { isMaskedCompleteUninstallation = masked; } public boolean typicalSelectionStateSaved() { return typicalSelectionStateSaved; } public void setTypicalSelectionStateSaved(boolean saved) { typicalSelectionStateSaved = saved; } public boolean customSelectionStateSaved() { return customSelectionStateSaved; } public void setCustomSelectionStateSaved(boolean saved) { customSelectionStateSaved = saved; } public boolean startSelectionStateSaved() { return startSelectionStateSaved; } public void setStartSelectionStateSaved(boolean saved) { startSelectionStateSaved = saved; } public boolean olderVersionExists() { return olderVersionExists; } public void setOlderVersionExists(boolean exists) { olderVersionExists = exists; } public boolean sameVersionExists() { return sameVersionExists; } public void setSameVersionExists(boolean exists) { sameVersionExists = exists; } public boolean newerVersionExists() { return newerVersionExists; } public void setNewerVersionExists(boolean exists) { newerVersionExists = exists; } public PackageDescription getUpdatePackage() { return updatePackage; } public void setUpdatePackage(PackageDescription onePackage) { updatePackage = onePackage; } public HashMap getShellEnvironment() { return shellEnvironment; } public Vector getRemoveFiles() { return removeFiles; } public Vector getInstallPackages() { return installPackages; } public void setInstallPackages(Vector packages) { installPackages = packages; } public void setShellEnvironment(HashMap environment) { shellEnvironment = environment; } public File getJarFilePath() { if ( jarFilePath == null ) { jarFilePath = SystemManager.getJarFilePath(); } return jarFilePath; } }
INTEGRATION: CWS native87 (1.1.10); FILE MERGED 2007/06/28 15:01:30 is 1.1.10.2: #i78444# earlier check for uid file to avoid race condition 2007/04/24 10:09:18 is 1.1.10.1: #i65425# adding header
javainstaller2/src/JavaSetup/org/openoffice/setup/InstallData.java
INTEGRATION: CWS native87 (1.1.10); FILE MERGED 2007/06/28 15:01:30 is 1.1.10.2: #i78444# earlier check for uid file to avoid race condition 2007/04/24 10:09:18 is 1.1.10.1: #i65425# adding header
<ide><path>avainstaller2/src/JavaSetup/org/openoffice/setup/InstallData.java <add>/************************************************************************* <add> * <add> * OpenOffice.org - a multi-platform office productivity suite <add> * <add> * $RCSfile: InstallData.java,v $ <add> * <add> * $Revision: 1.2 $ <add> * <add> * last change: $Author: rt $ $Date: 2007-07-03 11:48:43 $ <add> * <add> * The Contents of this file are made available subject to <add> * the terms of GNU Lesser General Public License Version 2.1. <add> * <add> * <add> * GNU Lesser General Public License Version 2.1 <add> * ============================================= <add> * Copyright 2005 by Sun Microsystems, Inc. <add> * 901 San Antonio Road, Palo Alto, CA 94303, USA <add> * <add> * This library is free software; you can redistribute it and/or <add> * modify it under the terms of the GNU Lesser General Public <add> * License version 2.1, as published by the Free Software Foundation. <add> * <add> * This library is distributed in the hope that it will be useful, <add> * but WITHOUT ANY WARRANTY; without even the implied warranty of <add> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU <add> * Lesser General Public License for more details. <add> * <add> * You should have received a copy of the GNU Lesser General Public <add> * License along with this library; if not, write to the Free Software <add> * Foundation, Inc., 59 Temple Place, Suite 330, Boston, <add> * MA 02111-1307 USA <add> * <add> ************************************************************************/ <add> <ide> package org.openoffice.setup; <ide> <ide> import org.openoffice.setup.SetupData.PackageDescription; <add>import org.openoffice.setup.Util.Controller; <ide> import org.openoffice.setup.Util.SystemManager; <ide> import java.io.File; <ide> import java.util.HashMap; <ide> private void setSolarisUserInstall() { <ide> if (( isUserInstallation ) && (osType.equalsIgnoreCase("SunOS"))) { <ide> isSolarisUserInstallation = true; <add> if ( isInstallationMode ) { <add> Controller.checkForUidFile(this); <add> } <ide> } <ide> } <ide>
Java
unlicense
9a902278b77849f0e4daf5c4dd0f3953ba001718
0
ZP4RKER/jitters-bot
package me.zp4rker.discord.jitters.util; import me.zp4rker.discord.core.logger.ZLogger; import me.zp4rker.discord.jitters.Jitters; import me.zp4rker.discord.core.exception.ExceptionHandler; import net.dv8tion.jda.core.entities.TextChannel; import org.json.JSONArray; import org.json.JSONObject; import java.io.*; import java.net.URL; import java.nio.charset.Charset; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.TimeUnit; /** * @author ZP4RKER */ public class UpcomingEpisode { private static TextChannel flash, arrow, supergirl, legends; private static JSONObject flashData, arrowData, supergirlData, legendsData; public static void start() { // Initialisation flash = Jitters.jda.getTextChannelById(312574911199576064L); arrow = Jitters.jda.getTextChannelById(312574944137707530L); supergirl = Jitters.jda.getTextChannelById(312575189877653504L); legends = Jitters.jda.getTextChannelById(312574974005346304L); flashData = null; arrowData = null; supergirlData = null; legendsData = null; // Timer new Timer().scheduleAtFixedRate(new TimerTask() { @Override public void run() { updateTopics(); } }, 0, 60000); } private static void updateTopics() { flash.getManager().setTopic(pullFlash()).queue(); arrow.getManager().setTopic(pullArrow()).queue(); supergirl.getManager().setTopic(pullSupergirl()).queue(); legends.getManager().setTopic(pullLegends()).queue(); } private static String pullFlash() { if (flashData == null) return getTopic("the-flash"); else return topicFromData(flashData); } private static String pullArrow() { if (arrowData == null) return getTopic("arrow"); else return topicFromData(arrowData); } private static String pullSupergirl() { if (supergirlData == null) return getTopic("supergirl"); else return topicFromData(supergirlData); } private static String pullLegends() { if (legendsData == null) return getTopic("legends-of-tomorrow"); else return topicFromData(legendsData); } private static String getTopic(String show) { JSONObject episodeData = getLatestEpisode(show); if (episodeData == null) return null; saveData(show, episodeData); startPullTimer(show, episodeData); return topicFromData(episodeData); } private static void startPullTimer(String show, JSONObject episodeData) { try { Instant instant = toInstant(episodeData); long remaining = (instant.getEpochSecond() - Instant.now().getEpochSecond()) * 1000; new Timer().schedule(new TimerTask() { @Override public void run() { try { JSONObject newData = getLatestEpisode(show); Instant newTime = toInstant(newData); if (newTime.getEpochSecond() > instant.getEpochSecond()) saveData(show, newData); updateTopics(); } catch (Exception e) { ExceptionHandler.handleException(e); } } }, remaining + 60000, 600000); } catch (Exception e) { ExceptionHandler.handleException(e); } } private static void saveData(String show, JSONObject episodeData) { switch (show) { case "the-flash": flashData = episodeData; break; case "arrow": arrowData = episodeData; break; case "supergirl": supergirlData = episodeData; break; case "legends-of-tomorrow": legendsData = episodeData; } } private static String topicFromData(JSONObject episodeData) { String title = episodeData.getString("name"); String season = episodeData.getInt("season") + ""; String episode = episodeData.getInt("number") + ""; String[] date = episodeData.getString("airdate").split("-"); String[] time = episodeData.getString("airtime").split(":"); Instant instant; try { instant = toInstant(date, time); } catch (Exception e) { ZLogger.warn("Could not get episode airdate/time!"); return null; } String timeLeft = timeRemaining(instant); String episodeString = "S" + season + "E" + (episode.length() < 2 ? "0" : "") + episode + " - " + title; return "Next episode: In " + timeLeft + " (" + episodeString + ")"; } private static JSONObject getLatestEpisode(String show) { JSONObject showData = readJsonFromUrl("http://api.tvmaze.com/search/shows?q=" + show); if (showData == null) return null; showData = showData.getJSONObject("show"); String episodeUrl = showData.getJSONObject("_links").getJSONObject("nextepisode").getString("href"); return readJsonFromUrl(episodeUrl); } private static Instant toInstant(String[] date, String[] time) throws Exception { int year = Integer.parseInt(date[0]); int month = Integer.parseInt(date[1]); int day = Integer.parseInt(date[2]); int hour = Integer.parseInt(time[0]); int minute = Integer.parseInt(time[1]); return ZonedDateTime.of(LocalDateTime.of(year, month, day, hour, minute), ZoneId.of("GMT+4")).toInstant(); } private static Instant toInstant(JSONObject episodeData) throws Exception { String[] date = episodeData.getString("airdate").split("-"); String[] time = episodeData.getString("airtime").split(":"); return toInstant(date, time); } private static String timeRemaining(Instant instant) { Instant now = Instant.now(); long remaining = instant.getEpochSecond() - now.getEpochSecond(); long days = TimeUnit.SECONDS.toDays(remaining); remaining -= TimeUnit.DAYS.toSeconds(days); long hours = TimeUnit.SECONDS.toHours(remaining); remaining -= TimeUnit.HOURS.toSeconds(hours); long minutes = TimeUnit.SECONDS.toMinutes(remaining); return days + "d " + hours + "h " + minutes + "m"; } private static JSONObject readJsonFromUrl(String url) { InputStream is = null; try { is = new URL(url).openStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); if (jsonText.startsWith("[")) return new JSONArray(jsonText).getJSONObject(0); else return new JSONObject(jsonText); } catch (Exception e) { ZLogger.warn("Could not get JSON from URL!"); ExceptionHandler.handleException(e); return null; } finally { closeInputstream(is); } } private static String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } private static void closeInputstream(InputStream is) { try { is.close(); } catch (Exception e) { ZLogger.warn("Could not close inputstream!"); } } }
src/main/java/me/zp4rker/discord/jitters/util/UpcomingEpisode.java
package me.zp4rker.discord.jitters.util; import me.zp4rker.discord.core.logger.ZLogger; import me.zp4rker.discord.jitters.Jitters; import me.zp4rker.discord.core.exception.ExceptionHandler; import net.dv8tion.jda.core.entities.TextChannel; import org.json.JSONArray; import org.json.JSONObject; import java.io.*; import java.net.URL; import java.nio.charset.Charset; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.TimeUnit; /** * @author ZP4RKER */ public class UpcomingEpisode { private static TextChannel flash, arrow, supergirl, legends; private static JSONObject flashData, arrowData, supergirlData, legendsData; public static void start() { // Initialisation flash = Jitters.jda.getTextChannelById(312574911199576064L); arrow = Jitters.jda.getTextChannelById(312574944137707530L); supergirl = Jitters.jda.getTextChannelById(312575189877653504L); legends = Jitters.jda.getTextChannelById(312574974005346304L); flashData = null; arrowData = null; supergirlData = null; legendsData = null; // Timer new Timer().scheduleAtFixedRate(new TimerTask() { @Override public void run() { updateTopics(); } }, 0, 60000); } private static void updateTopics() { flash.getManager().setTopic(pullFlash()).queue(); arrow.getManager().setTopic(pullArrow()).queue(); supergirl.getManager().setTopic(pullSupergirl()).queue(); legends.getManager().setTopic(pullLegends()).queue(); } private static String pullFlash() { if (flashData == null) return getTopic("the-flash"); else return topicFromData(flashData); } private static String pullArrow() { if (arrowData == null) return getTopic("arrow"); else return topicFromData(arrowData); } private static String pullSupergirl() { if (supergirlData == null) return getTopic("supergirl"); else return topicFromData(supergirlData); } private static String pullLegends() { if (legendsData == null) return getTopic("legends-of-tomorrow"); else return topicFromData(legendsData); } private static String getTopic(String show) { JSONObject episodeData = getLatestEpisode(show); if (episodeData == null) return null; saveData(show, episodeData); startPullTimer(show, episodeData); return topicFromData(episodeData); } private static void startPullTimer(String show, JSONObject episodeData) { try { Instant instant = toInstant(episodeData); long remaining = (instant.getEpochSecond() - Instant.now().getEpochSecond()) * 1000; new Timer().schedule(new TimerTask() { @Override public void run() { try { JSONObject newData = getLatestEpisode(show); Instant newTime = toInstant(newData); if (newTime.getEpochSecond() > instant.getEpochSecond()) saveData(show, newData); updateTopics(); } catch (Exception e) { ExceptionHandler.handleException(e); } } }, remaining + 60000, 600000); } catch (Exception e) { ExceptionHandler.handleException(e); } } private static void saveData(String show, JSONObject episodeData) { switch (show) { case "the-flash": flashData = episodeData; break; case "arrow": arrowData = episodeData; break; case "supergirl": supergirlData = episodeData; break; case "legends-of-tomorrow": legendsData = episodeData; } } private static String topicFromData(JSONObject episodeData) { String title = episodeData.getString("name"); String season = episodeData.getInt("season") + ""; String episode = episodeData.getInt("number") + ""; String[] date = episodeData.getString("airdate").split("-"); String[] time = episodeData.getString("airtime").split(":"); Instant instant; try { instant = toInstant(date, time); } catch (Exception e) { ZLogger.warn("Could not get episode airdate/time!"); return null; } String timeLeft = timeRemaining(instant); String episodeString = "S" + season + "E" + (episode.length() < 2 ? "0" : "") + episode + " - " + title; return "Next episode: In " + timeLeft + " (" + episodeString + ")"; } private static JSONObject getLatestEpisode(String show) { JSONObject showData = readJsonFromUrl("http://api.tvmaze.com/search/shows?q=" + show); if (showData == null) return null; showData = showData.getJSONObject("show"); String episodeUrl = showData.getJSONObject("_links").getJSONObject("nextepisode").getString("href"); return readJsonFromUrl(episodeUrl); } private static Instant toInstant(String[] date, String[] time) throws Exception { int year = Integer.parseInt(date[0]); int month = Integer.parseInt(date[1]); int day = Integer.parseInt(date[2]); int hour = Integer.parseInt(time[0]); int minute = Integer.parseInt(time[1]); return ZonedDateTime.of(LocalDateTime.of(year, month, day, hour, minute), ZoneId.of("GMT")).toInstant(); } private static Instant toInstant(JSONObject episodeData) throws Exception { String[] date = episodeData.getString("airdate").split("-"); String[] time = episodeData.getString("airtime").split(":"); return toInstant(date, time); } private static String timeRemaining(Instant instant) { Instant now = Instant.now(); long remaining = instant.getEpochSecond() - now.getEpochSecond(); long days = TimeUnit.SECONDS.toDays(remaining); remaining -= TimeUnit.DAYS.toSeconds(days); long hours = TimeUnit.SECONDS.toHours(remaining); remaining -= TimeUnit.HOURS.toSeconds(hours); long minutes = TimeUnit.SECONDS.toMinutes(remaining); return days + "d " + hours + "h " + minutes + "m"; } private static JSONObject readJsonFromUrl(String url) { InputStream is = null; try { is = new URL(url).openStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); if (jsonText.startsWith("[")) return new JSONArray(jsonText).getJSONObject(0); else return new JSONObject(jsonText); } catch (Exception e) { ZLogger.warn("Could not get JSON from URL!"); ExceptionHandler.handleException(e); return null; } finally { closeInputstream(is); } } private static String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } private static void closeInputstream(InputStream is) { try { is.close(); } catch (Exception e) { ZLogger.warn("Could not close inputstream!"); } } }
Updated timezone
src/main/java/me/zp4rker/discord/jitters/util/UpcomingEpisode.java
Updated timezone
<ide><path>rc/main/java/me/zp4rker/discord/jitters/util/UpcomingEpisode.java <ide> int hour = Integer.parseInt(time[0]); <ide> int minute = Integer.parseInt(time[1]); <ide> <del> return ZonedDateTime.of(LocalDateTime.of(year, month, day, hour, minute), ZoneId.of("GMT")).toInstant(); <add> return ZonedDateTime.of(LocalDateTime.of(year, month, day, hour, minute), ZoneId.of("GMT+4")).toInstant(); <ide> } <ide> <ide> private static Instant toInstant(JSONObject episodeData) throws Exception {
Java
mit
87dfbedb4b419bcf566ae9ab3912e51908273b90
0
v1v/jenkins,viqueen/jenkins,DanielWeber/jenkins,daniel-beck/jenkins,oleg-nenashev/jenkins,daniel-beck/jenkins,daniel-beck/jenkins,viqueen/jenkins,daniel-beck/jenkins,Vlatombe/jenkins,Jochen-A-Fuerbacher/jenkins,ikedam/jenkins,ikedam/jenkins,jenkinsci/jenkins,daniel-beck/jenkins,Jochen-A-Fuerbacher/jenkins,MarkEWaite/jenkins,damianszczepanik/jenkins,godfath3r/jenkins,rsandell/jenkins,viqueen/jenkins,stephenc/jenkins,pjanouse/jenkins,daniel-beck/jenkins,pjanouse/jenkins,ikedam/jenkins,godfath3r/jenkins,DanielWeber/jenkins,MarkEWaite/jenkins,DanielWeber/jenkins,rsandell/jenkins,oleg-nenashev/jenkins,godfath3r/jenkins,godfath3r/jenkins,daniel-beck/jenkins,MarkEWaite/jenkins,stephenc/jenkins,v1v/jenkins,Vlatombe/jenkins,ikedam/jenkins,godfath3r/jenkins,patbos/jenkins,patbos/jenkins,patbos/jenkins,patbos/jenkins,stephenc/jenkins,stephenc/jenkins,v1v/jenkins,rsandell/jenkins,jenkinsci/jenkins,stephenc/jenkins,ikedam/jenkins,Vlatombe/jenkins,Jochen-A-Fuerbacher/jenkins,pjanouse/jenkins,damianszczepanik/jenkins,recena/jenkins,pjanouse/jenkins,oleg-nenashev/jenkins,recena/jenkins,MarkEWaite/jenkins,damianszczepanik/jenkins,rsandell/jenkins,oleg-nenashev/jenkins,MarkEWaite/jenkins,oleg-nenashev/jenkins,DanielWeber/jenkins,ikedam/jenkins,jenkinsci/jenkins,oleg-nenashev/jenkins,damianszczepanik/jenkins,patbos/jenkins,DanielWeber/jenkins,viqueen/jenkins,viqueen/jenkins,pjanouse/jenkins,jenkinsci/jenkins,v1v/jenkins,recena/jenkins,v1v/jenkins,stephenc/jenkins,Jochen-A-Fuerbacher/jenkins,MarkEWaite/jenkins,godfath3r/jenkins,damianszczepanik/jenkins,Vlatombe/jenkins,recena/jenkins,rsandell/jenkins,rsandell/jenkins,ikedam/jenkins,Vlatombe/jenkins,viqueen/jenkins,recena/jenkins,DanielWeber/jenkins,DanielWeber/jenkins,jenkinsci/jenkins,patbos/jenkins,jenkinsci/jenkins,stephenc/jenkins,Jochen-A-Fuerbacher/jenkins,MarkEWaite/jenkins,v1v/jenkins,recena/jenkins,jenkinsci/jenkins,rsandell/jenkins,Vlatombe/jenkins,daniel-beck/jenkins,viqueen/jenkins,jenkinsci/jenkins,godfath3r/jenkins,pjanouse/jenkins,damianszczepanik/jenkins,pjanouse/jenkins,damianszczepanik/jenkins,oleg-nenashev/jenkins,Jochen-A-Fuerbacher/jenkins,MarkEWaite/jenkins,Vlatombe/jenkins,Jochen-A-Fuerbacher/jenkins,rsandell/jenkins,recena/jenkins,v1v/jenkins,patbos/jenkins,damianszczepanik/jenkins,ikedam/jenkins
/* * The MIT License * * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi, * Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe, * Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc., * Yahoo!, Inc. * * 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 jenkins.model; import antlr.ANTLRException; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.google.inject.Injector; import com.thoughtworks.xstream.XStream; import hudson.*; import hudson.Launcher.LocalLauncher; import jenkins.AgentProtocol; import jenkins.diagnostics.URICheckEncodingMonitor; import jenkins.security.stapler.DoActionFilter; import jenkins.security.stapler.StaplerFilteredActionListener; import jenkins.security.stapler.StaplerDispatchable; import jenkins.security.RedactSecretJsonInErrorMessageSanitizer; import jenkins.security.stapler.TypedFilter; import jenkins.telemetry.impl.java11.CatcherClassLoader; import jenkins.telemetry.impl.java11.MissingClassTelemetry; import jenkins.util.SystemProperties; import hudson.cli.declarative.CLIMethod; import hudson.cli.declarative.CLIResolver; import hudson.init.InitMilestone; import hudson.init.InitStrategy; import hudson.init.TermMilestone; import hudson.init.TerminatorFinder; import hudson.lifecycle.Lifecycle; import hudson.lifecycle.RestartNotSupportedException; import hudson.logging.LogRecorderManager; import hudson.markup.EscapedMarkupFormatter; import hudson.markup.MarkupFormatter; import hudson.model.AbstractCIBase; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.model.AdministrativeMonitor; import hudson.model.AllView; import hudson.model.Api; import hudson.model.Computer; import hudson.model.ComputerSet; import hudson.model.DependencyGraph; import hudson.model.Describable; import hudson.model.Descriptor; import hudson.model.Descriptor.FormException; import hudson.model.DescriptorByNameOwner; import hudson.model.DirectoryBrowserSupport; import hudson.model.Failure; import hudson.model.Fingerprint; import hudson.model.FingerprintCleanupThread; import hudson.model.FingerprintMap; import hudson.model.Hudson; import hudson.model.Item; import hudson.model.ItemGroup; import hudson.model.ItemGroupMixIn; import hudson.model.Items; import hudson.model.JDK; import hudson.model.Job; import hudson.model.JobPropertyDescriptor; import hudson.model.Label; import hudson.model.ListView; import hudson.model.LoadBalancer; import hudson.model.LoadStatistics; import hudson.model.ManagementLink; import hudson.model.Messages; import hudson.model.ModifiableViewGroup; import hudson.model.NoFingerprintMatch; import hudson.model.Node; import hudson.model.OverallLoadStatistics; import hudson.model.PaneStatusProperties; import hudson.model.Project; import hudson.model.Queue; import hudson.model.Queue.FlyweightTask; import hudson.model.RestartListener; import hudson.model.RootAction; import hudson.model.Slave; import hudson.model.TaskListener; import hudson.model.TopLevelItem; import hudson.model.TopLevelItemDescriptor; import hudson.model.UnprotectedRootAction; import hudson.model.UpdateCenter; import hudson.model.User; import hudson.model.View; import hudson.model.ViewGroupMixIn; import hudson.model.WorkspaceCleanupThread; import hudson.model.labels.LabelAtom; import hudson.model.listeners.ItemListener; import hudson.model.listeners.SCMListener; import hudson.model.listeners.SaveableListener; import hudson.remoting.Callable; import hudson.remoting.LocalChannel; import hudson.remoting.VirtualChannel; import hudson.scm.RepositoryBrowser; import hudson.scm.SCM; import hudson.search.CollectionSearchIndex; import hudson.search.SearchIndexBuilder; import hudson.search.SearchItem; import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.security.AuthorizationStrategy; import hudson.security.BasicAuthenticationFilter; import hudson.security.FederatedLoginService; import hudson.security.HudsonFilter; import hudson.security.LegacyAuthorizationStrategy; import hudson.security.LegacySecurityRealm; import hudson.security.Permission; import hudson.security.PermissionGroup; import hudson.security.PermissionScope; import hudson.security.SecurityMode; import hudson.security.SecurityRealm; import hudson.security.csrf.CrumbIssuer; import hudson.slaves.Cloud; import hudson.slaves.ComputerListener; import hudson.slaves.DumbSlave; import hudson.slaves.NodeDescriptor; import hudson.slaves.NodeList; import hudson.slaves.NodeProperty; import hudson.slaves.NodePropertyDescriptor; import hudson.slaves.NodeProvisioner; import hudson.slaves.OfflineCause; import hudson.slaves.RetentionStrategy; import hudson.tasks.BuildWrapper; import hudson.tasks.Builder; import hudson.tasks.Publisher; import hudson.triggers.SafeTimerTask; import hudson.triggers.Trigger; import hudson.triggers.TriggerDescriptor; import hudson.util.AdministrativeError; import hudson.util.CaseInsensitiveComparator; import hudson.util.ClockDifference; import hudson.util.CopyOnWriteList; import hudson.util.CopyOnWriteMap; import hudson.util.DaemonThreadFactory; import hudson.util.DescribableList; import hudson.util.FormApply; import hudson.util.FormValidation; import hudson.util.Futures; import hudson.util.HudsonIsLoading; import hudson.util.HudsonIsRestarting; import hudson.util.Iterators; import hudson.util.JenkinsReloadFailed; import hudson.util.MultipartFormDataParser; import hudson.util.NamingThreadFactory; import hudson.util.PluginServletFilter; import hudson.util.RemotingDiagnostics; import hudson.util.RemotingDiagnostics.HeapDump; import hudson.util.TextFile; import hudson.util.VersionNumber; import hudson.util.XStream2; import hudson.views.DefaultMyViewsTabBar; import hudson.views.DefaultViewsTabBar; import hudson.views.MyViewsTabBar; import hudson.views.ViewsTabBar; import hudson.widgets.Widget; import java.util.Objects; import java.util.TimerTask; import java.util.concurrent.CountDownLatch; import jenkins.ExtensionComponentSet; import jenkins.ExtensionRefreshException; import jenkins.InitReactorRunner; import jenkins.install.InstallState; import jenkins.install.SetupWizard; import jenkins.model.ProjectNamingStrategy.DefaultProjectNamingStrategy; import jenkins.security.ClassFilterImpl; import jenkins.security.ConfidentialKey; import jenkins.security.ConfidentialStore; import jenkins.security.SecurityListener; import jenkins.security.MasterToSlaveCallable; import jenkins.slaves.WorkspaceLocator; import jenkins.util.JenkinsJVM; import jenkins.util.Timer; import jenkins.util.io.FileBoolean; import jenkins.util.io.OnMaster; import jenkins.util.xml.XMLUtils; import net.jcip.annotations.GuardedBy; import net.sf.json.JSONObject; import org.acegisecurity.AccessDeniedException; import org.acegisecurity.AcegiSecurityException; import org.acegisecurity.Authentication; import org.acegisecurity.GrantedAuthority; import org.acegisecurity.GrantedAuthorityImpl; import org.acegisecurity.context.SecurityContextHolder; import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken; import org.acegisecurity.ui.AbstractProcessingFilter; import org.apache.commons.jelly.JellyException; import org.apache.commons.jelly.Script; import org.apache.commons.logging.LogFactory; import org.jvnet.hudson.reactor.Executable; import org.jvnet.hudson.reactor.Milestone; import org.jvnet.hudson.reactor.Reactor; import org.jvnet.hudson.reactor.ReactorException; import org.jvnet.hudson.reactor.ReactorListener; import org.jvnet.hudson.reactor.Task; import org.jvnet.hudson.reactor.TaskBuilder; import org.jvnet.hudson.reactor.TaskGraphBuilder; import org.jvnet.hudson.reactor.TaskGraphBuilder.Handle; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.args4j.Argument; import org.kohsuke.stapler.HttpRedirect; import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.HttpResponses; import org.kohsuke.stapler.MetaClass; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerFallback; import org.kohsuke.stapler.StaplerProxy; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.WebApp; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import org.kohsuke.stapler.framework.adjunct.AdjunctManager; import org.kohsuke.stapler.interceptor.RequirePOST; import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff; import org.kohsuke.stapler.jelly.JellyRequestDispatcher; import org.xml.sax.InputSource; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.crypto.SecretKey; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.BindException; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.Charset; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.stream.Collectors; import static hudson.Util.*; import static hudson.init.InitMilestone.*; import hudson.init.Initializer; import hudson.util.LogTaskListener; import static java.util.logging.Level.*; import javax.annotation.Nonnegative; import static javax.servlet.http.HttpServletResponse.*; import org.kohsuke.stapler.WebMethod; /** * Root object of the system. * * @author Kohsuke Kawaguchi */ @ExportedBean public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLevelItemGroup, StaplerProxy, StaplerFallback, ModifiableViewGroup, AccessControlled, DescriptorByNameOwner, ModelObjectWithContextMenu, ModelObjectWithChildren, OnMaster { private transient final Queue queue; /** * Stores various objects scoped to {@link Jenkins}. */ public transient final Lookup lookup = new Lookup(); /** * We update this field to the current version of Jenkins whenever we save {@code config.xml}. * This can be used to detect when an upgrade happens from one version to next. * * <p> * Since this field is introduced starting 1.301, "1.0" is used to represent every version * up to 1.300. This value may also include non-standard versions like "1.301-SNAPSHOT" or * "?", etc., so parsing needs to be done with a care. * * @since 1.301 */ // this field needs to be at the very top so that other components can look at this value even during unmarshalling private String version = "1.0"; /** * The Jenkins instance startup type i.e. NEW, UPGRADE etc */ private String installStateName; @Deprecated private InstallState installState; /** * If we're in the process of an initial setup, * this will be set */ private transient SetupWizard setupWizard; /** * Number of executors of the master node. */ private int numExecutors = 2; /** * Job allocation strategy. */ private Mode mode = Mode.NORMAL; /** * False to enable anyone to do anything. * Left as a field so that we can still read old data that uses this flag. * * @see #authorizationStrategy * @see #securityRealm */ private Boolean useSecurity; /** * Controls how the * <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a> * is handled in Jenkins. * <p> * This ultimately controls who has access to what. * * Never null. */ private volatile AuthorizationStrategy authorizationStrategy = AuthorizationStrategy.UNSECURED; /** * Controls a part of the * <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a> * handling in Jenkins. * <p> * Intuitively, this corresponds to the user database. * * See {@link HudsonFilter} for the concrete authentication protocol. * * Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to * update this field. * * @see #getSecurity() * @see #setSecurityRealm(SecurityRealm) */ private volatile SecurityRealm securityRealm = SecurityRealm.NO_AUTHENTICATION; /** * Disables the remember me on this computer option in the standard login screen. * * @since 1.534 */ private volatile boolean disableRememberMe; /** * The project naming strategy defines/restricts the names which can be given to a project/job. e.g. does the name have to follow a naming convention? */ private ProjectNamingStrategy projectNamingStrategy = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY; /** * Root directory for the workspaces. * This value will be variable-expanded as per {@link #expandVariablesForDirectory}. * @see #getWorkspaceFor(TopLevelItem) */ private String workspaceDir = OLD_DEFAULT_WORKSPACES_DIR; /** * Root directory for the builds. * This value will be variable-expanded as per {@link #expandVariablesForDirectory}. * @see #getBuildDirFor(Job) */ private String buildsDir = DEFAULT_BUILDS_DIR; /** * Message displayed in the top page. */ private String systemMessage; private MarkupFormatter markupFormatter; /** * Root directory of the system. */ public transient final File root; /** * Where are we in the initialization? */ private transient volatile InitMilestone initLevel = InitMilestone.STARTED; /** * All {@link Item}s keyed by their {@link Item#getName() name}s. */ /*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<>(CaseInsensitiveComparator.INSTANCE); /** * The sole instance. */ private static Jenkins theInstance; private transient volatile boolean isQuietingDown; private transient volatile boolean terminating; @GuardedBy("Jenkins.class") private transient boolean cleanUpStarted; /** * Use this to know during startup if this is a fresh one, aka first-time, startup, or a later one. * A file will be created at the very end of the Jenkins initialization process. * I.e. if the file is present, that means this is *NOT* a fresh startup. * * <code> * STARTUP_MARKER_FILE.get(); // returns false if we are on a fresh startup. True for next startups. * </code> */ private transient static FileBoolean STARTUP_MARKER_FILE; private volatile List<JDK> jdks = new ArrayList<>(); private transient volatile DependencyGraph dependencyGraph; private final transient AtomicBoolean dependencyGraphDirty = new AtomicBoolean(); /** * Currently active Views tab bar. */ private volatile ViewsTabBar viewsTabBar = new DefaultViewsTabBar(); /** * Currently active My Views tab bar. */ private volatile MyViewsTabBar myViewsTabBar = new DefaultMyViewsTabBar(); /** * All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}. */ @SuppressWarnings("rawtypes") private transient final Map<Class, ExtensionList> extensionLists = new ConcurrentHashMap<>(); /** * All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}. */ @SuppressWarnings("rawtypes") private transient final Map<Class, DescriptorExtensionList> descriptorLists = new ConcurrentHashMap<>(); /** * {@link Computer}s in this Jenkins system. Read-only. */ protected transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<>(); /** * Active {@link Cloud}s. */ public final Hudson.CloudList clouds = new Hudson.CloudList(this); public static class CloudList extends DescribableList<Cloud,Descriptor<Cloud>> { public CloudList(Jenkins h) { super(h); } public CloudList() {// needed for XStream deserialization } public Cloud getByName(String name) { for (Cloud c : this) if (c.name.equals(name)) return c; return null; } @Override protected void onModified() throws IOException { super.onModified(); Jenkins.get().trimLabels(); } } /** * Legacy store of the set of installed cluster nodes. * @deprecated in favour of {@link Nodes} */ @Deprecated protected transient volatile NodeList slaves; /** * The holder of the set of installed cluster nodes. * * @since 1.607 */ private transient final Nodes nodes = new Nodes(this); /** * Quiet period. * * This is {@link Integer} so that we can initialize it to '5' for upgrading users. */ /*package*/ Integer quietPeriod; /** * Global default for {@link AbstractProject#getScmCheckoutRetryCount()} */ /*package*/ int scmCheckoutRetryCount; /** * {@link View}s. */ private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<>(); /** * Name of the primary view. * <p> * Start with null, so that we can upgrade pre-1.269 data well. * @since 1.269 */ private volatile String primaryView; private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) { protected List<View> views() { return views; } protected String primaryView() { return primaryView; } protected void primaryView(String name) { primaryView=name; } }; private transient final FingerprintMap fingerprintMap = new FingerprintMap(); /** * Loaded plugins. */ public transient final PluginManager pluginManager; public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener; private transient final Object tcpSlaveAgentListenerLock = new Object(); private transient UDPBroadcastThread udpBroadcastThread; private transient DNSMultiCast dnsMultiCast; /** * List of registered {@link SCMListener}s. */ private transient final CopyOnWriteList<SCMListener> scmListeners = new CopyOnWriteList<>(); /** * TCP agent port. * 0 for random, -1 to disable. */ private int slaveAgentPort = getSlaveAgentPortInitialValue(0); private static int getSlaveAgentPortInitialValue(int def) { return SystemProperties.getInteger(Jenkins.class.getName()+".slaveAgentPort", def); } /** * If -Djenkins.model.Jenkins.slaveAgentPort is defined, enforce it on every start instead of only the first one. */ private static final boolean SLAVE_AGENT_PORT_ENFORCE = SystemProperties.getBoolean(Jenkins.class.getName()+".slaveAgentPortEnforce", false); /** * The TCP agent protocols that are explicitly disabled (we store the disabled ones so that newer protocols * are enabled by default). Will be {@code null} instead of empty to simplify XML format. * * @since 2.16 */ @CheckForNull private List<String> disabledAgentProtocols; /** * @deprecated Just a temporary buffer for XSTream migration code from JENKINS-39465, do not use */ @Deprecated private transient String[] _disabledAgentProtocols; /** * The TCP agent protocols that are {@link AgentProtocol#isOptIn()} and explicitly enabled. * Will be {@code null} instead of empty to simplify XML format. * * @since 2.16 */ @CheckForNull private List<String> enabledAgentProtocols; /** * @deprecated Just a temporary buffer for XSTream migration code from JENKINS-39465, do not use */ @Deprecated private transient String[] _enabledAgentProtocols; /** * The TCP agent protocols that are enabled. Built from {@link #disabledAgentProtocols} and * {@link #enabledAgentProtocols}. * * @since 2.16 * @see #setAgentProtocols(Set) * @see #getAgentProtocols() */ private transient Set<String> agentProtocols; /** * Whitespace-separated labels assigned to the master as a {@link Node}. */ private String label=""; /** * {@link hudson.security.csrf.CrumbIssuer} */ private volatile CrumbIssuer crumbIssuer; /** * All labels known to Jenkins. This allows us to reuse the same label instances * as much as possible, even though that's not a strict requirement. */ private transient final ConcurrentHashMap<String,Label> labels = new ConcurrentHashMap<>(); /** * Load statistics of the entire system. * * This includes every executor and every job in the system. */ @Exported public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics(); /** * Load statistics of the free roaming jobs and agents. * * This includes all executors on {@link hudson.model.Node.Mode#NORMAL} nodes and jobs that do not have any assigned nodes. * * @since 1.467 */ @Exported public transient final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics(); /** * {@link NodeProvisioner} that reacts to {@link #unlabeledLoad}. * @since 1.467 */ public transient final NodeProvisioner unlabeledNodeProvisioner = new NodeProvisioner(null,unlabeledLoad); /** * @deprecated as of 1.467 * Use {@link #unlabeledNodeProvisioner}. * This was broken because it was tracking all the executors in the system, but it was only tracking * free-roaming jobs in the queue. So {@link Cloud} fails to launch nodes when you have some exclusive * agents and free-roaming jobs in the queue. */ @Restricted(NoExternalUse.class) @Deprecated public transient final NodeProvisioner overallNodeProvisioner = unlabeledNodeProvisioner; public transient final ServletContext servletContext; /** * Transient action list. Useful for adding navigation items to the navigation bar * on the left. */ private transient final List<Action> actions = new CopyOnWriteArrayList<>(); /** * List of master node properties */ private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<>(this); /** * List of global properties */ private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<>(this); /** * {@link AdministrativeMonitor}s installed on this system. * * @see AdministrativeMonitor */ public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class); /** * Widgets on Jenkins. */ private transient final List<Widget> widgets = getExtensionList(Widget.class); /** * {@link AdjunctManager} */ private transient final AdjunctManager adjuncts; /** * Code that handles {@link ItemGroup} work. */ private transient final ItemGroupMixIn itemGroupMixIn = new ItemGroupMixIn(this,this) { @Override protected void add(TopLevelItem item) { items.put(item.getName(),item); } @Override protected File getRootDirFor(String name) { return Jenkins.this.getRootDirFor(name); } }; /** * Hook for a test harness to intercept Jenkins.get() * * Do not use in the production code as the signature may change. */ public interface JenkinsHolder { @CheckForNull Jenkins getInstance(); } static JenkinsHolder HOLDER = new JenkinsHolder() { public @CheckForNull Jenkins getInstance() { return theInstance; } }; /** * Gets the {@link Jenkins} singleton. * @return {@link Jenkins} instance * @throws IllegalStateException for the reasons that {@link #getInstanceOrNull} might return null * @since 2.98 */ @Nonnull public static Jenkins get() throws IllegalStateException { Jenkins instance = getInstanceOrNull(); if (instance == null) { throw new IllegalStateException("Jenkins.instance is missing. Read the documentation of Jenkins.getInstanceOrNull to see what you are doing wrong."); } return instance; } /** * @deprecated This is a verbose historical alias for {@link #get}. * @since 1.590 */ @Deprecated @Nonnull public static Jenkins getActiveInstance() throws IllegalStateException { return get(); } /** * Gets the {@link Jenkins} singleton. * {@link #get} is what you normally want. * <p>In certain rare cases you may have code that is intended to run before Jenkins starts or while Jenkins is being shut down. * For those rare cases use this method. * <p>In other cases you may have code that might end up running on a remote JVM and not on the Jenkins master. * For those cases you really should rewrite your code so that when the {@link Callable} is sent over the remoting channel * it can do whatever it needs without ever referring to {@link Jenkins}; * for example, gather any information you need on the master side before constructing the callable. * If you must do a runtime check whether you are in the master or agent, use {@link JenkinsJVM} rather than this method, * as merely loading the {@link Jenkins} class file into an agent JVM can cause linkage errors under some conditions. * @return The instance. Null if the {@link Jenkins} service has not been started, or was already shut down, * or we are running on an unrelated JVM, typically an agent. * @since 1.653 */ @CLIResolver @CheckForNull public static Jenkins getInstanceOrNull() { return HOLDER.getInstance(); } /** * @deprecated This is a historical alias for {@link #getInstanceOrNull} but with ambiguous nullability. Use {@link #get} in typical cases. */ @Nullable @Deprecated public static Jenkins getInstance() { return getInstanceOrNull(); } /** * Secret key generated once and used for a long time, beyond * container start/stop. Persisted outside {@code config.xml} to avoid * accidental exposure. */ private transient final String secretKey; private transient final UpdateCenter updateCenter = UpdateCenter.createUpdateCenter(null); /** * True if the user opted out from the statistics tracking. We'll never send anything if this is true. */ private Boolean noUsageStatistics; /** * HTTP proxy configuration. */ public transient volatile ProxyConfiguration proxy; /** * Bound to "/log". */ private transient final LogRecorderManager log = new LogRecorderManager(); private transient final boolean oldJenkinsJVM; protected Jenkins(File root, ServletContext context) throws IOException, InterruptedException, ReactorException { this(root, context, null); } /** * @param pluginManager * If non-null, use existing plugin manager. create a new one. */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({ "SC_START_IN_CTOR", // bug in FindBugs. It flags UDPBroadcastThread.start() call but that's for another class "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" // Trigger.timer }) protected Jenkins(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException { oldJenkinsJVM = JenkinsJVM.isJenkinsJVM(); // capture to restore in cleanUp() JenkinsJVMAccess._setJenkinsJVM(true); // set it for unit tests as they will not have gone through WebAppMain long start = System.currentTimeMillis(); STARTUP_MARKER_FILE = new FileBoolean(new File(root, ".lastStarted")); // As Jenkins is starting, grant this process full control ACL.impersonate(ACL.SYSTEM); try { this.root = root; this.servletContext = context; computeVersion(context); if(theInstance!=null) throw new IllegalStateException("second instance"); theInstance = this; if (!new File(root,"jobs").exists()) { // if this is a fresh install, use more modern default layout that's consistent with agents workspaceDir = DEFAULT_WORKSPACES_DIR; } // doing this early allows InitStrategy to set environment upfront //Telemetry: add interceptor classloader //These lines allow the catcher to be present on Thread.currentThread().getContextClassLoader() in every plugin which //allow us to detect failures in every plugin loading classes by this way. if (MissingClassTelemetry.enabled() && !(Thread.currentThread().getContextClassLoader() instanceof CatcherClassLoader)) { Thread.currentThread().setContextClassLoader(new CatcherClassLoader(Thread.currentThread().getContextClassLoader())); } final InitStrategy is = InitStrategy.get(Thread.currentThread().getContextClassLoader()); Trigger.timer = new java.util.Timer("Jenkins cron thread"); queue = new Queue(LoadBalancer.CONSISTENT_HASH); try { dependencyGraph = DependencyGraph.EMPTY; } catch (InternalError e) { if(e.getMessage().contains("window server")) { throw new Error("Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option",e); } throw e; } // get or create the secret TextFile secretFile = new TextFile(new File(getRootDir(),"secret.key")); if(secretFile.exists()) { secretKey = secretFile.readTrim(); } else { SecureRandom sr = new SecureRandom(); byte[] random = new byte[32]; sr.nextBytes(random); secretKey = Util.toHexString(random); secretFile.write(secretKey); // this marker indicates that the secret.key is generated by the version of Jenkins post SECURITY-49. // this indicates that there's no need to rewrite secrets on disk new FileBoolean(new File(root,"secret.key.not-so-secret")).on(); } try { proxy = ProxyConfiguration.load(); } catch (IOException e) { LOGGER.log(SEVERE, "Failed to load proxy configuration", e); } if (pluginManager==null) pluginManager = PluginManager.createDefault(this); this.pluginManager = pluginManager; WebApp webApp = WebApp.get(servletContext); //Telemetry: add interceptor classloader //These lines allows the catcher to be present on Thread.currentThread().getContextClassLoader() in every plugin which //allow us to detect failures in every plugin loading classes by this way. // JSON binding needs to be able to see all the classes from all the plugins ClassLoader classLoaderToAssign; if (MissingClassTelemetry.enabled() && !(pluginManager.uberClassLoader instanceof CatcherClassLoader)) { classLoaderToAssign = new CatcherClassLoader(pluginManager.uberClassLoader); } else { classLoaderToAssign = pluginManager.uberClassLoader; } webApp.setClassLoader(classLoaderToAssign); webApp.setJsonInErrorMessageSanitizer(RedactSecretJsonInErrorMessageSanitizer.INSTANCE); TypedFilter typedFilter = new TypedFilter(); webApp.setFilterForGetMethods(typedFilter); webApp.setFilterForFields(typedFilter); webApp.setFilterForDoActions(new DoActionFilter()); StaplerFilteredActionListener actionListener = new StaplerFilteredActionListener(); webApp.setFilteredGetterTriggerListener(actionListener); webApp.setFilteredDoActionTriggerListener(actionListener); webApp.setFilteredFieldTriggerListener(actionListener); //Telemetry: add interceptor classloader //These lines allows the catcher to be present on Thread.currentThread().getContextClassLoader() in every plugin which //allow us to detect failures in every plugin loading classes at this way. adjuncts = new AdjunctManager(servletContext, classLoaderToAssign, "adjuncts/" + SESSION_HASH, TimeUnit.DAYS.toMillis(365)); ClassFilterImpl.register(); // initialization consists of ... executeReactor( is, pluginManager.initTasks(is), // loading and preparing plugins loadTasks(), // load jobs InitMilestone.ordering() // forced ordering among key milestones ); // Ensure we reached the final initialization state. Log the error otherwise if (initLevel != InitMilestone.COMPLETED) { LOGGER.log(SEVERE, "Jenkins initialization has not reached the COMPLETED initialization milestone after the startup. " + "Current state: {0}. " + "It may cause undefined incorrect behavior in Jenkins plugin relying on this state. " + "It is likely an issue with the Initialization task graph. " + "Example: usage of @Initializer(after = InitMilestone.COMPLETED) in a plugin (JENKINS-37759). " + "Please create a bug in Jenkins bugtracker. ", initLevel); } if(KILL_AFTER_LOAD) // TODO cleanUp? System.exit(0); save(); launchTcpSlaveAgentListener(); if (UDPBroadcastThread.PORT != -1) { try { udpBroadcastThread = new UDPBroadcastThread(this); udpBroadcastThread.start(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to broadcast over UDP (use -Dhudson.udp=-1 to disable)", e); } } dnsMultiCast = new DNSMultiCast(this); Timer.get().scheduleAtFixedRate(new SafeTimerTask() { @Override protected void doRun() throws Exception { trimLabels(); } }, TimeUnit.MINUTES.toMillis(5), TimeUnit.MINUTES.toMillis(5), TimeUnit.MILLISECONDS); updateComputerList(); {// master is online now, it's instance must always exist final Computer c = toComputer(); if(c != null) { for (ComputerListener cl : ComputerListener.all()) { try { cl.onOnline(c, new LogTaskListener(LOGGER, INFO)); } catch (Exception e) { // Per Javadoc log exceptions but still go online. // NOTE: this does not include Errors, which indicate a fatal problem LOGGER.log(WARNING, String.format("Exception in onOnline() for the computer listener %s on the Jenkins master node", cl.getClass()), e); } } } } for (ItemListener l : ItemListener.all()) { long itemListenerStart = System.currentTimeMillis(); try { l.onLoaded(); } catch (RuntimeException x) { LOGGER.log(Level.WARNING, null, x); } if (LOG_STARTUP_PERFORMANCE) LOGGER.info(String.format("Took %dms for item listener %s startup", System.currentTimeMillis()-itemListenerStart,l.getClass().getName())); } if (LOG_STARTUP_PERFORMANCE) LOGGER.info(String.format("Took %dms for complete Jenkins startup", System.currentTimeMillis()-start)); STARTUP_MARKER_FILE.on(); } finally { SecurityContextHolder.clearContext(); } } /** * Maintains backwards compatibility. Invoked by XStream when this object is de-serialized. */ @SuppressWarnings({"unused"}) private Object readResolve() { if (jdks == null) { jdks = new ArrayList<>(); } if (SLAVE_AGENT_PORT_ENFORCE) { slaveAgentPort = getSlaveAgentPortInitialValue(slaveAgentPort); } if (disabledAgentProtocols == null && _disabledAgentProtocols != null) { disabledAgentProtocols = Arrays.asList(_disabledAgentProtocols); _disabledAgentProtocols = null; } if (enabledAgentProtocols == null && _enabledAgentProtocols != null) { enabledAgentProtocols = Arrays.asList(_enabledAgentProtocols); _enabledAgentProtocols = null; } // Invalidate the protocols cache after the reload agentProtocols = null; return this; } /** * Get the Jenkins {@link jenkins.install.InstallState install state}. * @return The Jenkins {@link jenkins.install.InstallState install state}. */ @Nonnull public InstallState getInstallState() { if (installState != null) { installStateName = installState.name(); installState = null; } InstallState is = installStateName != null ? InstallState.valueOf(installStateName) : InstallState.UNKNOWN; return is != null ? is : InstallState.UNKNOWN; } /** * Update the current install state. This will invoke state.initializeState() * when the state has been transitioned. */ public void setInstallState(@Nonnull InstallState newState) { String prior = installStateName; installStateName = newState.name(); LOGGER.log(Main.isDevelopmentMode ? Level.INFO : Level.FINE, "Install state transitioning from: {0} to : {1}", new Object[] { prior, installStateName }); if (!installStateName.equals(prior)) { getSetupWizard().onInstallStateUpdate(newState); newState.initializeState(); } saveQuietly(); } /** * Executes a reactor. * * @param is * If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Jenkins. */ private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException { Reactor reactor = new Reactor(builders) { /** * Sets the thread name to the task for better diagnostics. */ @Override protected void runTask(Task task) throws Exception { if (is!=null && is.skipInitTask(task)) return; ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread String taskName = InitReactorRunner.getDisplayName(task); Thread t = Thread.currentThread(); String name = t.getName(); if (taskName !=null) t.setName(taskName); try { long start = System.currentTimeMillis(); super.runTask(task); if(LOG_STARTUP_PERFORMANCE) LOGGER.info(String.format("Took %dms for %s by %s", System.currentTimeMillis()-start, taskName, name)); } catch (Exception | Error x) { if (containsLinkageError(x)) { LOGGER.log(Level.WARNING, taskName + " failed perhaps due to plugin dependency issues", x); } else { throw x; } } finally { t.setName(name); SecurityContextHolder.clearContext(); } } private boolean containsLinkageError(Throwable x) { if (x instanceof LinkageError) { return true; } Throwable x2 = x.getCause(); return x2 != null && containsLinkageError(x2); } }; new InitReactorRunner() { @Override protected void onInitMilestoneAttained(InitMilestone milestone) { initLevel = milestone; if (milestone==PLUGINS_PREPARED) { // set up Guice to enable injection as early as possible // before this milestone, ExtensionList.ensureLoaded() won't actually try to locate instances ExtensionList.lookup(ExtensionFinder.class).getComponents(); } } }.run(reactor); } public TcpSlaveAgentListener getTcpSlaveAgentListener() { return tcpSlaveAgentListener; } /** * Makes {@link AdjunctManager} URL-bound. * The dummy parameter allows us to use different URLs for the same adjunct, * for proper cache handling. */ public AdjunctManager getAdjuncts(String dummy) { return adjuncts; } @Exported public int getSlaveAgentPort() { return slaveAgentPort; } /** * @since 2.24 */ public boolean isSlaveAgentPortEnforced() { return Jenkins.SLAVE_AGENT_PORT_ENFORCE; } /** * @param port * 0 to indicate random available TCP port. -1 to disable this service. */ public void setSlaveAgentPort(int port) throws IOException { if (SLAVE_AGENT_PORT_ENFORCE) { LOGGER.log(Level.WARNING, "setSlaveAgentPort({0}) call ignored because system property {1} is true", new String[] { Integer.toString(port), Jenkins.class.getName()+".slaveAgentPortEnforce" }); } else { forceSetSlaveAgentPort(port); } } private void forceSetSlaveAgentPort(int port) throws IOException { this.slaveAgentPort = port; launchTcpSlaveAgentListener(); } /** * Returns the enabled agent protocols. * * @return the enabled agent protocols. * @since 2.16 */ public Set<String> getAgentProtocols() { if (agentProtocols == null) { // idempotent, so don't care if we do this concurrently, should all get same result Set<String> result = new TreeSet<>(); Set<String> disabled = new TreeSet<>(); for (String p : Util.fixNull(disabledAgentProtocols)) { disabled.add(p.trim()); } Set<String> enabled = new TreeSet<>(); for (String p : Util.fixNull(enabledAgentProtocols)) { enabled.add(p.trim()); } for (AgentProtocol p : AgentProtocol.all()) { String name = p.getName(); if (name != null && (p.isRequired() || (!disabled.contains(name) && (!p.isOptIn() || enabled.contains(name))))) { result.add(name); } } agentProtocols = result; return result; } return agentProtocols; } /** * Sets the enabled agent protocols. * * @param protocols the enabled agent protocols. * @since 2.16 */ public void setAgentProtocols(Set<String> protocols) { Set<String> disabled = new TreeSet<>(); Set<String> enabled = new TreeSet<>(); for (AgentProtocol p : AgentProtocol.all()) { String name = p.getName(); if (name != null && !p.isRequired()) { // we want to record the protocols where the admin has made a conscious decision // thus, if a protocol is opt-in, we record the admin enabling it // if a protocol is opt-out, we record the admin disabling it // We should not transition rapidly from opt-in -> opt-out -> opt-in // the scenario we want to have work is: // 1. We introduce a new protocol, it starts off as opt-in. Some admins decide to test and opt-in // 2. We decide that the protocol is ready for general use. It gets marked as opt-out. Any admins // that took part in early testing now have their config switched to not mention the new protocol // at all when they save their config as the protocol is now opt-out. Any admins that want to // disable it can do so and will have their preference recorded. // 3. We decide that the protocol needs to be retired. It gets switched back to opt-in. At this point // the initial opt-in admins, assuming they visited an upgrade to a master with step 2, will // have the protocol disabled for them. This is what we want. If they didn't upgrade to a master // with step 2, well there is not much we can do to differentiate them from somebody who is upgrading // from a previous step 3 master and had needed to keep the protocol turned on. // // What we should never do is flip-flop: opt-in -> opt-out -> opt-in -> opt-out as that will basically // clear any preference that an admin has set, but this should be ok as we only ever will be // adding new protocols and retiring old ones. if (p.isOptIn()) { if (protocols.contains(name)) { enabled.add(name); } } else { if (!protocols.contains(name)) { disabled.add(name); } } } } disabledAgentProtocols = disabled.isEmpty() ? null : new ArrayList<>(disabled); enabledAgentProtocols = enabled.isEmpty() ? null : new ArrayList<>(enabled); agentProtocols = null; } private void launchTcpSlaveAgentListener() throws IOException { synchronized(tcpSlaveAgentListenerLock) { // shutdown previous agent if the port has changed if (tcpSlaveAgentListener != null && tcpSlaveAgentListener.configuredPort != slaveAgentPort) { tcpSlaveAgentListener.shutdown(); tcpSlaveAgentListener = null; } if (slaveAgentPort != -1 && tcpSlaveAgentListener == null) { final String administrativeMonitorId = getClass().getName() + ".tcpBind"; try { tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); // remove previous monitor in case of previous error AdministrativeMonitor toBeRemoved = null; ExtensionList<AdministrativeMonitor> all = AdministrativeMonitor.all(); for (AdministrativeMonitor am : all) { if (administrativeMonitorId.equals(am.id)) { toBeRemoved = am; break; } } all.remove(toBeRemoved); } catch (BindException e) { LOGGER.log(Level.WARNING, String.format("Failed to listen to incoming agent connections through port %s. Change the port number", slaveAgentPort), e); new AdministrativeError(administrativeMonitorId, "Failed to listen to incoming agent connections", "Failed to listen to incoming agent connections. <a href='configureSecurity'>Change the inbound TCP port number</a> to solve the problem.", e); } } } } @Extension @Restricted(NoExternalUse.class) public static class EnforceSlaveAgentPortAdministrativeMonitor extends AdministrativeMonitor { @Inject Jenkins j; @Override public String getDisplayName() { return jenkins.model.Messages.EnforceSlaveAgentPortAdministrativeMonitor_displayName(); } public String getSystemPropertyName() { return Jenkins.class.getName() + ".slaveAgentPort"; } public int getExpectedPort() { int slaveAgentPort = j.slaveAgentPort; return Jenkins.getSlaveAgentPortInitialValue(slaveAgentPort); } @RequirePOST public void doAct(StaplerRequest req, StaplerResponse rsp) throws IOException { j.forceSetSlaveAgentPort(getExpectedPort()); rsp.sendRedirect2(req.getContextPath() + "/manage"); } @Override public boolean isActivated() { int slaveAgentPort = Jenkins.get().slaveAgentPort; return SLAVE_AGENT_PORT_ENFORCE && slaveAgentPort != Jenkins.getSlaveAgentPortInitialValue(slaveAgentPort); } } public void setNodeName(String name) { throw new UnsupportedOperationException(); // not allowed } public String getNodeDescription() { return Messages.Hudson_NodeDescription(); } @Exported public String getDescription() { return systemMessage; } @Nonnull public PluginManager getPluginManager() { return pluginManager; } public UpdateCenter getUpdateCenter() { return updateCenter; } public boolean isUsageStatisticsCollected() { return noUsageStatistics==null || !noUsageStatistics; } public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException { this.noUsageStatistics = noUsageStatistics; save(); } public View.People getPeople() { return new View.People(this); } /** * @since 1.484 */ public View.AsynchPeople getAsynchPeople() { return new View.AsynchPeople(this); } /** * Does this {@link View} has any associated user information recorded? * @deprecated Potentially very expensive call; do not use from Jelly views. */ @Deprecated public boolean hasPeople() { return View.People.isApplicable(items.values()); } public Api getApi() { return new Api(this); } /** * Returns a secret key that survives across container start/stop. * <p> * This value is useful for implementing some of the security features. * * @deprecated * Due to the past security advisory, this value should not be used any more to protect sensitive information. * See {@link ConfidentialStore} and {@link ConfidentialKey} for how to store secrets. */ @Deprecated public String getSecretKey() { return secretKey; } /** * Gets {@linkplain #getSecretKey() the secret key} as a key for AES-128. * @since 1.308 * @deprecated * See {@link #getSecretKey()}. */ @Deprecated public SecretKey getSecretKeyAsAES128() { return Util.toAes128Key(secretKey); } /** * Returns the unique identifier of this Jenkins that has been historically used to identify * this Jenkins to the outside world. * * <p> * This form of identifier is weak in that it can be impersonated by others. See * https://wiki.jenkins-ci.org/display/JENKINS/Instance+Identity for more modern form of instance ID * that can be challenged and verified. * * @since 1.498 */ @SuppressWarnings("deprecation") public String getLegacyInstanceId() { return Util.getDigestOf(getSecretKey()); } /** * Gets the SCM descriptor by name. Primarily used for making them web-visible. */ public Descriptor<SCM> getScm(String shortClassName) { return findDescriptor(shortClassName, SCM.all()); } /** * Gets the repository browser descriptor by name. Primarily used for making them web-visible. */ public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) { return findDescriptor(shortClassName,RepositoryBrowser.all()); } /** * Gets the builder descriptor by name. Primarily used for making them web-visible. */ public Descriptor<Builder> getBuilder(String shortClassName) { return findDescriptor(shortClassName, Builder.all()); } /** * Gets the build wrapper descriptor by name. Primarily used for making them web-visible. */ public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) { return findDescriptor(shortClassName, BuildWrapper.all()); } /** * Gets the publisher descriptor by name. Primarily used for making them web-visible. */ public Descriptor<Publisher> getPublisher(String shortClassName) { return findDescriptor(shortClassName, Publisher.all()); } /** * Gets the trigger descriptor by name. Primarily used for making them web-visible. */ public TriggerDescriptor getTrigger(String shortClassName) { return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all()); } /** * Gets the retention strategy descriptor by name. Primarily used for making them web-visible. */ public Descriptor<RetentionStrategy<?>> getRetentionStrategy(String shortClassName) { return findDescriptor(shortClassName, RetentionStrategy.all()); } /** * Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible. */ public JobPropertyDescriptor getJobProperty(String shortClassName) { // combining these two lines triggers javac bug. See issue #610. Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all()); return (JobPropertyDescriptor) d; } /** * @deprecated * UI method. Not meant to be used programmatically. */ @Deprecated public ComputerSet getComputer() { return new ComputerSet(); } /** * Exposes {@link Descriptor} by its name to URL. * * After doing all the {@code getXXX(shortClassName)} methods, I finally realized that * this just doesn't scale. * * @param id * Either {@link Descriptor#getId()} (recommended) or the short name of a {@link Describable} subtype (for compatibility) * @throws IllegalArgumentException if a short name was passed which matches multiple IDs (fail fast) */ @SuppressWarnings({"unchecked", "rawtypes"}) // too late to fix public Descriptor getDescriptor(String id) { // legacy descriptors that are registered manually doesn't show up in getExtensionList, so check them explicitly. Iterable<Descriptor> descriptors = Iterators.sequence(getExtensionList(Descriptor.class), DescriptorExtensionList.listLegacyInstances()); for (Descriptor d : descriptors) { if (d.getId().equals(id)) { return d; } } Descriptor candidate = null; for (Descriptor d : descriptors) { String name = d.getId(); if (name.substring(name.lastIndexOf('.') + 1).equals(id)) { if (candidate == null) { candidate = d; } else { throw new IllegalArgumentException(id + " is ambiguous; matches both " + name + " and " + candidate.getId()); } } } return candidate; } /** * Alias for {@link #getDescriptor(String)}. */ public Descriptor getDescriptorByName(String id) { return getDescriptor(id); } /** * Gets the {@link Descriptor} that corresponds to the given {@link Describable} type. * <p> * If you have an instance of {@code type} and call {@link Describable#getDescriptor()}, * you'll get the same instance that this method returns. */ @CheckForNull public Descriptor getDescriptor(Class<? extends Describable> type) { for( Descriptor d : getExtensionList(Descriptor.class) ) if(d.clazz==type) return d; return null; } /** * Works just like {@link #getDescriptor(Class)} but don't take no for an answer. * * @throws AssertionError * If the descriptor is missing. * @since 1.326 */ @Nonnull public Descriptor getDescriptorOrDie(Class<? extends Describable> type) { Descriptor d = getDescriptor(type); if (d==null) throw new AssertionError(type+" is missing its descriptor"); return d; } /** * Gets the {@link Descriptor} instance in the current Jenkins by its type. */ public <T extends Descriptor> T getDescriptorByType(Class<T> type) { for( Descriptor d : getExtensionList(Descriptor.class) ) if(d.getClass()==type) return type.cast(d); return null; } /** * Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible. */ public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) { return findDescriptor(shortClassName, SecurityRealm.all()); } /** * Finds a descriptor that has the specified name. */ private <T extends Describable<T>> Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) { String name = '.'+shortClassName; for (Descriptor<T> d : descriptors) { if(d.clazz.getName().endsWith(name)) return d; } return null; } protected void updateComputerList() { updateComputerList(AUTOMATIC_SLAVE_LAUNCH); } /** @deprecated Use {@link SCMListener#all} instead. */ @Deprecated public CopyOnWriteList<SCMListener> getSCMListeners() { return scmListeners; } /** * Gets the plugin object from its short name. * This allows URL {@code hudson/plugin/ID} to be served by the views * of the plugin class. * @param shortName Short name of the plugin * @return The plugin singleton or {@code null} if for some reason the plugin is not loaded. * The fact the plugin is loaded does not mean it is enabled and fully initialized for the current Jenkins session. * Use {@link Plugin#getWrapper()} and then {@link PluginWrapper#isActive()} to check it. */ @CheckForNull public Plugin getPlugin(String shortName) { PluginWrapper p = pluginManager.getPlugin(shortName); if(p==null) return null; return p.getPlugin(); } /** * Gets the plugin object from its class. * * <p> * This allows easy storage of plugin information in the plugin singleton without * every plugin reimplementing the singleton pattern. * * @param <P> Class of the plugin * @param clazz The plugin class (beware class-loader fun, this will probably only work * from within the jpi that defines the plugin class, it may or may not work in other cases) * @return The plugin singleton or {@code null} if for some reason the plugin is not loaded. * The fact the plugin is loaded does not mean it is enabled and fully initialized for the current Jenkins session. * Use {@link Plugin#getWrapper()} and then {@link PluginWrapper#isActive()} to check it. */ @SuppressWarnings("unchecked") @CheckForNull public <P extends Plugin> P getPlugin(Class<P> clazz) { PluginWrapper p = pluginManager.getPlugin(clazz); if(p==null) return null; return (P) p.getPlugin(); } /** * Gets the plugin objects from their super-class. * * @param clazz The plugin class (beware class-loader fun) * * @return The plugin instances. */ public <P extends Plugin> List<P> getPlugins(Class<P> clazz) { List<P> result = new ArrayList<>(); for (PluginWrapper w: pluginManager.getPlugins(clazz)) { result.add((P)w.getPlugin()); } return Collections.unmodifiableList(result); } /** * Synonym for {@link #getDescription}. */ public String getSystemMessage() { return systemMessage; } /** * Gets the markup formatter used in the system. * * @return * never null. * @since 1.391 */ public @Nonnull MarkupFormatter getMarkupFormatter() { MarkupFormatter f = markupFormatter; return f != null ? f : new EscapedMarkupFormatter(); } /** * Sets the markup formatter used in the system globally. * * @since 1.391 */ public void setMarkupFormatter(MarkupFormatter f) { this.markupFormatter = f; } /** * Sets the system message. */ public void setSystemMessage(String message) throws IOException { this.systemMessage = message; save(); } @StaplerDispatchable public FederatedLoginService getFederatedLoginService(String name) { for (FederatedLoginService fls : FederatedLoginService.all()) { if (fls.getUrlName().equals(name)) return fls; } return null; } public List<FederatedLoginService> getFederatedLoginServices() { return FederatedLoginService.all(); } public Launcher createLauncher(TaskListener listener) { return new LocalLauncher(listener).decorateFor(this); } public String getFullName() { return ""; } public String getFullDisplayName() { return ""; } /** * Returns the transient {@link Action}s associated with the top page. * * <p> * Adding {@link Action} is primarily useful for plugins to contribute * an item to the navigation bar of the top page. See existing {@link Action} * implementation for it affects the GUI. * * <p> * To register an {@link Action}, implement {@link RootAction} extension point, or write code like * {@code Jenkins.get().getActions().add(...)}. * * @return * Live list where the changes can be made. Can be empty but never null. * @since 1.172 */ public List<Action> getActions() { return actions; } /** * Gets just the immediate children of {@link Jenkins}. * * @see #getAllItems(Class) */ @Exported(name="jobs") public List<TopLevelItem> getItems() { List<TopLevelItem> viewableItems = new ArrayList<>(); for (TopLevelItem item : items.values()) { if (item.hasPermission(Item.READ)) viewableItems.add(item); } return viewableItems; } /** * Returns the read-only view of all the {@link TopLevelItem}s keyed by their names. * <p> * This method is efficient, as it doesn't involve any copying. * * @since 1.296 */ public Map<String,TopLevelItem> getItemMap() { return Collections.unmodifiableMap(items); } /** * Gets just the immediate children of {@link Jenkins} but of the given type. */ public <T> List<T> getItems(Class<T> type) { List<T> r = new ArrayList<>(); for (TopLevelItem i : getItems()) if (type.isInstance(i)) r.add(type.cast(i)); return r; } /** * Gets a list of simple top-level projects. * @deprecated This method will ignore Maven and matrix projects, as well as projects inside containers such as folders. * You may prefer to call {@link #getAllItems(Class)} on {@link AbstractProject}, * perhaps also using {@link Util#createSubList} to consider only {@link TopLevelItem}s. * (That will also consider the caller's permissions.) * If you really want to get just {@link Project}s at top level, ignoring permissions, * you can filter the values from {@link #getItemMap} using {@link Util#createSubList}. */ @Deprecated public List<Project> getProjects() { return Util.createSubList(items.values(), Project.class); } /** * Gets the names of all the {@link Job}s. */ public Collection<String> getJobNames() { List<String> names = new ArrayList<>(); for (Job j : allItems(Job.class)) names.add(j.getFullName()); names.sort(String.CASE_INSENSITIVE_ORDER); return names; } public List<Action> getViewActions() { return getActions(); } /** * Gets the names of all the {@link TopLevelItem}s. */ public Collection<String> getTopLevelItemNames() { List<String> names = new ArrayList<>(); for (TopLevelItem j : items.values()) names.add(j.getName()); return names; } /** * Gets a view by the specified name. * The method iterates through {@link hudson.model.ViewGroup}s if required. * @param name Name of the view * @return View instance or {@code null} if it is missing */ @CheckForNull public View getView(@CheckForNull String name) { return viewGroupMixIn.getView(name); } /** * Gets the read-only list of all {@link View}s. */ @Exported public Collection<View> getViews() { return viewGroupMixIn.getViews(); } @Override public void addView(View v) throws IOException { viewGroupMixIn.addView(v); } /** * Completely replaces views. * * <p> * This operation is NOT provided as an atomic operation, but rather * the sole purpose of this is to define a setter for this to help * introspecting code, such as system-config-dsl plugin */ // even if we want to offer this atomic operation, CopyOnWriteArrayList // offers no such operation public void setViews(Collection<View> views) throws IOException { BulkChange bc = new BulkChange(this); try { this.views.clear(); for (View v : views) { addView(v); } } finally { bc.commit(); } } public boolean canDelete(View view) { return viewGroupMixIn.canDelete(view); } public synchronized void deleteView(View view) throws IOException { viewGroupMixIn.deleteView(view); } public void onViewRenamed(View view, String oldName, String newName) { viewGroupMixIn.onViewRenamed(view, oldName, newName); } /** * Returns the primary {@link View} that renders the top-page of Jenkins. */ @Exported public View getPrimaryView() { return viewGroupMixIn.getPrimaryView(); } public void setPrimaryView(@Nonnull View v) { this.primaryView = v.getViewName(); } public ViewsTabBar getViewsTabBar() { return viewsTabBar; } public void setViewsTabBar(ViewsTabBar viewsTabBar) { this.viewsTabBar = viewsTabBar; } public Jenkins getItemGroup() { return this; } public MyViewsTabBar getMyViewsTabBar() { return myViewsTabBar; } public void setMyViewsTabBar(MyViewsTabBar myViewsTabBar) { this.myViewsTabBar = myViewsTabBar; } /** * Returns true if the current running Jenkins is upgraded from a version earlier than the specified version. * * <p> * This method continues to return true until the system configuration is saved, at which point * {@link #version} will be overwritten and Jenkins forgets the upgrade history. * * <p> * To handle SNAPSHOTS correctly, pass in "1.N.*" to test if it's upgrading from the version * equal or younger than N. So say if you implement a feature in 1.301 and you want to check * if the installation upgraded from pre-1.301, pass in "1.300.*" * * @since 1.301 */ public boolean isUpgradedFromBefore(VersionNumber v) { try { return new VersionNumber(version).isOlderThan(v); } catch (IllegalArgumentException e) { // fail to parse this version number return false; } } /** * Gets the read-only list of all {@link Computer}s. */ public Computer[] getComputers() { Computer[] r = computers.values().toArray(new Computer[0]); Arrays.sort(r,new Comparator<Computer>() { @Override public int compare(Computer lhs, Computer rhs) { if(lhs.getNode()==Jenkins.this) return -1; if(rhs.getNode()==Jenkins.this) return 1; return lhs.getName().compareTo(rhs.getName()); } }); return r; } @CLIResolver public @CheckForNull Computer getComputer(@Argument(required=true,metaVar="NAME",usage="Node name") @Nonnull String name) { if(name.equals("(master)")) name = ""; for (Computer c : computers.values()) { if(c.getName().equals(name)) return c; } return null; } /** * Gets the label that exists on this system by the name. * * @return null if name is null. * @see Label#parseExpression(String) (String) */ public Label getLabel(String expr) { if(expr==null) return null; expr = hudson.util.QuotedStringTokenizer.unquote(expr); while(true) { Label l = labels.get(expr); if(l!=null) return l; // non-existent try { labels.putIfAbsent(expr,Label.parseExpression(expr)); } catch (ANTLRException e) { // laxly accept it as a single label atom for backward compatibility return getLabelAtom(expr); } } } /** * Returns the label atom of the given name. * @return non-null iff name is non-null */ public @Nullable LabelAtom getLabelAtom(@CheckForNull String name) { if (name==null) return null; while(true) { Label l = labels.get(name); if(l!=null) return (LabelAtom)l; // non-existent LabelAtom la = new LabelAtom(name); if (labels.putIfAbsent(name, la)==null) la.load(); } } /** * Gets all the active labels in the current system. */ public Set<Label> getLabels() { Set<Label> r = new TreeSet<>(); for (Label l : labels.values()) { if(!l.isEmpty()) r.add(l); } return r; } public Set<LabelAtom> getLabelAtoms() { Set<LabelAtom> r = new TreeSet<>(); for (Label l : labels.values()) { if(!l.isEmpty() && l instanceof LabelAtom) r.add((LabelAtom)l); } return r; } public Queue getQueue() { return queue; } @Override public String getDisplayName() { return Messages.Hudson_DisplayName(); } public List<JDK> getJDKs() { return jdks; } /** * Replaces all JDK installations with those from the given collection. * * Use {@link hudson.model.JDK.DescriptorImpl#setInstallations(JDK...)} to * set JDK installations from external code. */ @Restricted(NoExternalUse.class) public void setJDKs(Collection<? extends JDK> jdks) { this.jdks = new ArrayList<>(jdks); } /** * Gets the JDK installation of the given name, or returns null. */ public JDK getJDK(String name) { if(name==null) { // if only one JDK is configured, "default JDK" should mean that JDK. List<JDK> jdks = getJDKs(); if(jdks.size()==1) return jdks.get(0); return null; } for (JDK j : getJDKs()) { if(j.getName().equals(name)) return j; } return null; } /** * Gets the agent node of the give name, hooked under this Jenkins. */ public @CheckForNull Node getNode(String name) { return nodes.getNode(name); } /** * Gets a {@link Cloud} by {@link Cloud#name its name}, or null. */ public Cloud getCloud(String name) { return clouds.getByName(name); } protected Map<Node,Computer> getComputerMap() { return computers; } /** * Returns all {@link Node}s in the system, excluding {@link Jenkins} instance itself which * represents the master. */ public List<Node> getNodes() { return nodes.getNodes(); } /** * Get the {@link Nodes} object that handles maintaining individual {@link Node}s. * @return The Nodes object. */ @Restricted(NoExternalUse.class) public Nodes getNodesObject() { // TODO replace this with something better when we properly expose Nodes. return nodes; } /** * Adds one more {@link Node} to Jenkins. * If a node of the same name already exists then that node will be replaced. */ public void addNode(Node n) throws IOException { nodes.addNode(n); } /** * Removes a {@link Node} from Jenkins. */ public void removeNode(@Nonnull Node n) throws IOException { nodes.removeNode(n); } /** * Saves an existing {@link Node} on disk, called by {@link Node#save()}. This method is preferred in those cases * where you need to determine atomically that the node being saved is actually in the list of nodes. * * @param n the node to be updated. * @return {@code true}, if the node was updated. {@code false}, if the node was not in the list of nodes. * @throws IOException if the node could not be persisted. * @see Nodes#updateNode * @since 1.634 */ public boolean updateNode(Node n) throws IOException { return nodes.updateNode(n); } public void setNodes(final List<? extends Node> n) throws IOException { nodes.setNodes(n); } public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() { return nodeProperties; } public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getGlobalNodeProperties() { return globalNodeProperties; } /** * Resets all labels and remove invalid ones. * * This should be called when the assumptions behind label cache computation changes, * but we also call this periodically to self-heal any data out-of-sync issue. */ /*package*/ void trimLabels() { for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) { Label l = itr.next(); resetLabel(l); if(l.isEmpty()) itr.remove(); } } /** * Binds {@link AdministrativeMonitor}s to URL. * @param id Monitor ID * @return The requested monitor or {@code null} if it does not exist */ @CheckForNull public AdministrativeMonitor getAdministrativeMonitor(String id) { for (AdministrativeMonitor m : administrativeMonitors) if(m.id.equals(id)) return m; return null; } /** * Returns the enabled and activated administrative monitors. * @since 2.64 */ public List<AdministrativeMonitor> getActiveAdministrativeMonitors() { return administrativeMonitors.stream().filter(m -> { try { return m.isEnabled() && m.isActivated(); } catch (Throwable x) { LOGGER.log(Level.WARNING, null, x); return false; } }).collect(Collectors.toList()); } public NodeDescriptor getDescriptor() { return DescriptorImpl.INSTANCE; } public static final class DescriptorImpl extends NodeDescriptor { @Extension public static final DescriptorImpl INSTANCE = new DescriptorImpl(); @Override public boolean isInstantiable() { return false; } public FormValidation doCheckNumExecutors(@QueryParameter String value) { return FormValidation.validateNonNegativeInteger(value); } // to route /descriptor/FQCN/xxx to getDescriptor(FQCN).xxx public Object getDynamic(String token) { return Jenkins.get().getDescriptor(token); } } /** * Gets the system default quiet period. */ public int getQuietPeriod() { return quietPeriod!=null ? quietPeriod : 5; } /** * Sets the global quiet period. * * @param quietPeriod * null to the default value. */ public void setQuietPeriod(Integer quietPeriod) throws IOException { this.quietPeriod = quietPeriod; save(); } /** * Gets the global SCM check out retry count. */ public int getScmCheckoutRetryCount() { return scmCheckoutRetryCount; } public void setScmCheckoutRetryCount(int scmCheckoutRetryCount) throws IOException { this.scmCheckoutRetryCount = scmCheckoutRetryCount; save(); } @Override public String getSearchUrl() { return ""; } @Override public SearchIndexBuilder makeSearchIndex() { SearchIndexBuilder builder = super.makeSearchIndex(); if (hasPermission(ADMINISTER)) { builder.add("configure", "config", "configure") .add("manage") .add("log"); } builder.add(new CollectionSearchIndex<TopLevelItem>() { protected SearchItem get(String key) { return getItemByFullName(key, TopLevelItem.class); } protected Collection<TopLevelItem> all() { return getAllItems(TopLevelItem.class); } @Nonnull @Override protected Iterable<TopLevelItem> allAsIterable() { return allItems(TopLevelItem.class); } }) .add(getPrimaryView().makeSearchIndex()) .add(new CollectionSearchIndex() {// for computers protected Computer get(String key) { return getComputer(key); } protected Collection<Computer> all() { return computers.values(); } }) .add(new CollectionSearchIndex() {// for users protected User get(String key) { return User.get(key,false); } protected Collection<User> all() { return User.getAll(); } }) .add(new CollectionSearchIndex() {// for views protected View get(String key) { return getView(key); } protected Collection<View> all() { return getAllViews(); } }); return builder; } public String getUrlChildPrefix() { return "job"; } /** * Gets the absolute URL of Jenkins, such as {@code http://localhost/jenkins/}. * * <p> * This method first tries to use the manually configured value, then * fall back to {@link #getRootUrlFromRequest}. * It is done in this order so that it can work correctly even in the face * of a reverse proxy. * * @return {@code null} if this parameter is not configured by the user and the calling thread is not in an HTTP request; * otherwise the returned URL will always have the trailing {@code /} * @throws IllegalStateException {@link JenkinsLocationConfiguration} cannot be retrieved. * Jenkins instance may be not ready, or there is an extension loading glitch. * @since 1.66 * @see <a href="https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML">Hyperlinks in HTML</a> */ public @Nullable String getRootUrl() throws IllegalStateException { final JenkinsLocationConfiguration config = JenkinsLocationConfiguration.get(); if (config == null) { // Try to get standard message if possible final Jenkins j = Jenkins.get(); throw new IllegalStateException("Jenkins instance " + j + " has been successfully initialized, but JenkinsLocationConfiguration is undefined."); } String url = config.getUrl(); if(url!=null) { return Util.ensureEndsWith(url,"/"); } StaplerRequest req = Stapler.getCurrentRequest(); if(req!=null) return getRootUrlFromRequest(); return null; } /** * Is Jenkins running in HTTPS? * * Note that we can't really trust {@link StaplerRequest#isSecure()} because HTTPS might be terminated * in the reverse proxy. */ public boolean isRootUrlSecure() { String url = getRootUrl(); return url!=null && url.startsWith("https"); } /** * Gets the absolute URL of Jenkins top page, such as {@code http://localhost/jenkins/}. * * <p> * Unlike {@link #getRootUrl()}, which uses the manually configured value, * this one uses the current request to reconstruct the URL. The benefit is * that this is immune to the configuration mistake (users often fail to set the root URL * correctly, especially when a migration is involved), but the downside * is that unless you are processing a request, this method doesn't work. * * <p>Please note that this will not work in all cases if Jenkins is running behind a * reverse proxy which has not been fully configured. * Specifically the {@code Host} and {@code X-Forwarded-Proto} headers must be set. * <a href="https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache">Running Jenkins behind Apache</a> * shows some examples of configuration. * @since 1.263 */ public @Nonnull String getRootUrlFromRequest() { StaplerRequest req = Stapler.getCurrentRequest(); if (req == null) { throw new IllegalStateException("cannot call getRootUrlFromRequest from outside a request handling thread"); } StringBuilder buf = new StringBuilder(); String scheme = getXForwardedHeader(req, "X-Forwarded-Proto", req.getScheme()); buf.append(scheme).append("://"); String host = getXForwardedHeader(req, "X-Forwarded-Host", req.getServerName()); int index = host.lastIndexOf(':'); int port = req.getServerPort(); if (index == -1) { // Almost everyone else except Nginx put the host and port in separate headers buf.append(host); } else { if (host.startsWith("[") && host.endsWith("]")) { // support IPv6 address buf.append(host); } else { // Nginx uses the same spec as for the Host header, i.e. hostname:port buf.append(host, 0, index); if (index + 1 < host.length()) { try { port = Integer.parseInt(host.substring(index + 1)); } catch (NumberFormatException e) { // ignore } } // but if a user has configured Nginx with an X-Forwarded-Port, that will win out. } } String forwardedPort = getXForwardedHeader(req, "X-Forwarded-Port", null); if (forwardedPort != null) { try { port = Integer.parseInt(forwardedPort); } catch (NumberFormatException e) { // ignore } } if (port != ("https".equals(scheme) ? 443 : 80)) { buf.append(':').append(port); } buf.append(req.getContextPath()).append('/'); return buf.toString(); } /** * Gets the originating "X-Forwarded-..." header from the request. If there are multiple headers the originating * header is the first header. If the originating header contains a comma separated list, the originating entry * is the first one. * @param req the request * @param header the header name * @param defaultValue the value to return if the header is absent. * @return the originating entry of the header or the default value if the header was not present. */ private static String getXForwardedHeader(StaplerRequest req, String header, String defaultValue) { String value = req.getHeader(header); if (value != null) { int index = value.indexOf(','); return index == -1 ? value.trim() : value.substring(0,index).trim(); } return defaultValue; } public File getRootDir() { return root; } public FilePath getWorkspaceFor(TopLevelItem item) { for (WorkspaceLocator l : WorkspaceLocator.all()) { FilePath workspace = l.locate(item, this); if (workspace != null) { return workspace; } } return new FilePath(expandVariablesForDirectory(workspaceDir, item)); } public File getBuildDirFor(Job job) { return expandVariablesForDirectory(buildsDir, job); } /** * If the configured buildsDir has it's default value or has been changed. * * @return true if default value. */ @Restricted(NoExternalUse.class) public boolean isDefaultBuildDir() { return DEFAULT_BUILDS_DIR.equals(buildsDir); } @Restricted(NoExternalUse.class) boolean isDefaultWorkspaceDir() { return OLD_DEFAULT_WORKSPACES_DIR.equals(workspaceDir) || DEFAULT_WORKSPACES_DIR.equals(workspaceDir); } private File expandVariablesForDirectory(String base, Item item) { return new File(expandVariablesForDirectory(base, item.getFullName(), item.getRootDir().getPath())); } @Restricted(NoExternalUse.class) public static String expandVariablesForDirectory(String base, String itemFullName, String itemRootDir) { return Util.replaceMacro(base, ImmutableMap.of( "JENKINS_HOME", Jenkins.get().getRootDir().getPath(), "ITEM_ROOTDIR", itemRootDir, "ITEM_FULLNAME", itemFullName, // legacy, deprecated "ITEM_FULL_NAME", itemFullName.replace(':','$'))); // safe, see JENKINS-12251 } public String getRawWorkspaceDir() { return workspaceDir; } public String getRawBuildsDir() { return buildsDir; } @Restricted(NoExternalUse.class) public void setRawBuildsDir(String buildsDir) { this.buildsDir = buildsDir; } @Override public @Nonnull FilePath getRootPath() { return new FilePath(getRootDir()); } @Override public FilePath createPath(String absolutePath) { return new FilePath((VirtualChannel)null,absolutePath); } public ClockDifference getClockDifference() { return ClockDifference.ZERO; } @Override public Callable<ClockDifference, IOException> getClockDifferenceCallable() { return new ClockDifferenceCallable(); } private static class ClockDifferenceCallable extends MasterToSlaveCallable<ClockDifference, IOException> { @Override public ClockDifference call() throws IOException { return new ClockDifference(0); } } /** * For binding {@link LogRecorderManager} to "/log". * Everything below here is admin-only, so do the check here. */ public LogRecorderManager getLog() { checkPermission(ADMINISTER); return log; } /** * A convenience method to check if there's some security * restrictions in place. */ @Exported public boolean isUseSecurity() { return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED; } public boolean isUseProjectNamingStrategy(){ return projectNamingStrategy != DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY; } /** * If true, all the POST requests to Jenkins would have to have crumb in it to protect * Jenkins from CSRF vulnerabilities. */ @Exported public boolean isUseCrumbs() { return crumbIssuer!=null; } /** * Returns the constant that captures the three basic security modes in Jenkins. */ public SecurityMode getSecurity() { // fix the variable so that this code works under concurrent modification to securityRealm. SecurityRealm realm = securityRealm; if(realm==SecurityRealm.NO_AUTHENTICATION) return SecurityMode.UNSECURED; if(realm instanceof LegacySecurityRealm) return SecurityMode.LEGACY; return SecurityMode.SECURED; } /** * @return * never null. */ public SecurityRealm getSecurityRealm() { return securityRealm; } public void setSecurityRealm(SecurityRealm securityRealm) { if(securityRealm==null) securityRealm= SecurityRealm.NO_AUTHENTICATION; this.useSecurity = true; IdStrategy oldUserIdStrategy = this.securityRealm == null ? securityRealm.getUserIdStrategy() // don't trigger rekey on Jenkins load : this.securityRealm.getUserIdStrategy(); this.securityRealm = securityRealm; // reset the filters and proxies for the new SecurityRealm try { HudsonFilter filter = HudsonFilter.get(servletContext); if (filter == null) { // Fix for #3069: This filter is not necessarily initialized before the servlets. // when HudsonFilter does come back, it'll initialize itself. LOGGER.fine("HudsonFilter has not yet been initialized: Can't perform security setup for now"); } else { LOGGER.fine("HudsonFilter has been previously initialized: Setting security up"); filter.reset(securityRealm); LOGGER.fine("Security is now fully set up"); } if (!oldUserIdStrategy.equals(this.securityRealm.getUserIdStrategy())) { User.rekey(); } } catch (ServletException e) { // for binary compatibility, this method cannot throw a checked exception throw new AcegiSecurityException("Failed to configure filter",e) {}; } saveQuietly(); } public void setAuthorizationStrategy(AuthorizationStrategy a) { if (a == null) a = AuthorizationStrategy.UNSECURED; useSecurity = true; authorizationStrategy = a; saveQuietly(); } public boolean isDisableRememberMe() { return disableRememberMe; } public void setDisableRememberMe(boolean disableRememberMe) { this.disableRememberMe = disableRememberMe; } public void disableSecurity() { useSecurity = null; setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); authorizationStrategy = AuthorizationStrategy.UNSECURED; } public void setProjectNamingStrategy(ProjectNamingStrategy ns) { if(ns == null){ ns = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY; } projectNamingStrategy = ns; } public Lifecycle getLifecycle() { return Lifecycle.get(); } /** * Gets the dependency injection container that hosts all the extension implementations and other * components in Jenkins. * * @since 1.433 */ public @CheckForNull Injector getInjector() { return lookup(Injector.class); } /** * Returns {@link ExtensionList} that retains the discovered instances for the given extension type. * * @param extensionType * The base type that represents the extension point. Normally {@link ExtensionPoint} subtype * but that's not a hard requirement. * @return * Can be an empty list but never null. * @see ExtensionList#lookup */ @SuppressWarnings({"unchecked"}) public <T> ExtensionList<T> getExtensionList(Class<T> extensionType) { ExtensionList<T> extensionList = extensionLists.get(extensionType); return extensionList != null ? extensionList : extensionLists.computeIfAbsent(extensionType, key -> ExtensionList.create(this, key)); } /** * Used to bind {@link ExtensionList}s to URLs. * * @since 1.349 */ @StaplerDispatchable public ExtensionList getExtensionList(String extensionType) throws ClassNotFoundException { return getExtensionList(pluginManager.uberClassLoader.loadClass(extensionType)); } /** * Returns {@link ExtensionList} that retains the discovered {@link Descriptor} instances for the given * kind of {@link Describable}. * * @return * Can be an empty list but never null. */ @SuppressWarnings({"unchecked"}) public @Nonnull <T extends Describable<T>,D extends Descriptor<T>> DescriptorExtensionList<T,D> getDescriptorList(Class<T> type) { return descriptorLists.computeIfAbsent(type, key -> DescriptorExtensionList.createDescriptorList(this, key)); } /** * Refresh {@link ExtensionList}s by adding all the newly discovered extensions. * * Exposed only for {@link PluginManager#dynamicLoad(File)}. */ public void refreshExtensions() throws ExtensionRefreshException { ExtensionList<ExtensionFinder> finders = getExtensionList(ExtensionFinder.class); for (ExtensionFinder ef : finders) { if (!ef.isRefreshable()) throw new ExtensionRefreshException(ef+" doesn't support refresh"); } List<ExtensionComponentSet> fragments = Lists.newArrayList(); for (ExtensionFinder ef : finders) { fragments.add(ef.refresh()); } ExtensionComponentSet delta = ExtensionComponentSet.union(fragments).filtered(); // if we find a new ExtensionFinder, we need it to list up all the extension points as well List<ExtensionComponent<ExtensionFinder>> newFinders = Lists.newArrayList(delta.find(ExtensionFinder.class)); while (!newFinders.isEmpty()) { ExtensionFinder f = newFinders.remove(newFinders.size()-1).getInstance(); ExtensionComponentSet ecs = ExtensionComponentSet.allOf(f).filtered(); newFinders.addAll(ecs.find(ExtensionFinder.class)); delta = ExtensionComponentSet.union(delta, ecs); } for (ExtensionList el : extensionLists.values()) { el.refresh(delta); } for (ExtensionList el : descriptorLists.values()) { el.refresh(delta); } // TODO: we need some generalization here so that extension points can be notified when a refresh happens? for (ExtensionComponent<RootAction> ea : delta.find(RootAction.class)) { Action a = ea.getInstance(); if (!actions.contains(a)) actions.add(a); } } /** * Returns the root {@link ACL}. * * @see AuthorizationStrategy#getRootACL() */ @Override public ACL getACL() { return authorizationStrategy.getRootACL(); } /** * @return * never null. */ public AuthorizationStrategy getAuthorizationStrategy() { return authorizationStrategy; } /** * The strategy used to check the project names. * @return never <code>null</code> */ public ProjectNamingStrategy getProjectNamingStrategy() { return projectNamingStrategy == null ? ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY : projectNamingStrategy; } /** * Returns true if Jenkins is quieting down. * <p> * No further jobs will be executed unless it * can be finished while other current pending builds * are still in progress. */ @Exported public boolean isQuietingDown() { return isQuietingDown; } /** * Returns true if the container initiated the termination of the web application. */ public boolean isTerminating() { return terminating; } /** * Gets the initialization milestone that we've already reached. * * @return * {@link InitMilestone#STARTED} even if the initialization hasn't been started, so that this method * never returns null. */ public InitMilestone getInitLevel() { return initLevel; } /** * Sets a number of executors. * @param n Number of executors * @throws IOException Failed to save the configuration * @throws IllegalArgumentException Negative value has been passed */ public void setNumExecutors(@Nonnegative int n) throws IOException, IllegalArgumentException { if (n < 0) { throw new IllegalArgumentException("Incorrect field \"# of executors\": " + n +". It should be a non-negative number."); } if (this.numExecutors != n) { this.numExecutors = n; updateComputerList(); save(); } } /** * {@inheritDoc}. * * Note that the look up is case-insensitive. */ @Override public TopLevelItem getItem(String name) throws AccessDeniedException { if (name==null) return null; TopLevelItem item = items.get(name); if (item==null) return null; if (!item.hasPermission(Item.READ)) { if (item.hasPermission(Item.DISCOVER)) { throw new AccessDeniedException("Please login to access job " + name); } return null; } return item; } /** * Gets the item by its path name from the given context * * <h2>Path Names</h2> * <p> * If the name starts from '/', like "/foo/bar/zot", then it's interpreted as absolute. * Otherwise, the name should be something like "foo/bar" and it's interpreted like * relative path name in the file system is, against the given context. * <p>For compatibility, as a fallback when nothing else matches, a simple path * like {@code foo/bar} can also be treated with {@link #getItemByFullName}. * @param context * null is interpreted as {@link Jenkins}. Base 'directory' of the interpretation. * @since 1.406 */ public Item getItem(String pathName, ItemGroup context) { if (context==null) context = this; if (pathName==null) return null; if (pathName.startsWith("/")) // absolute return getItemByFullName(pathName); Object/*Item|ItemGroup*/ ctx = context; StringTokenizer tokens = new StringTokenizer(pathName,"/"); while (tokens.hasMoreTokens()) { String s = tokens.nextToken(); if (s.equals("..")) { if (ctx instanceof Item) { ctx = ((Item)ctx).getParent(); continue; } ctx=null; // can't go up further break; } if (s.equals(".")) { continue; } if (ctx instanceof ItemGroup) { ItemGroup g = (ItemGroup) ctx; Item i = g.getItem(s); if (i==null || !i.hasPermission(Item.READ)) { // TODO consider DISCOVER ctx=null; // can't go up further break; } ctx=i; } else { return null; } } if (ctx instanceof Item) return (Item)ctx; // fall back to the classic interpretation return getItemByFullName(pathName); } public final Item getItem(String pathName, Item context) { return getItem(pathName,context!=null?context.getParent():null); } public final <T extends Item> T getItem(String pathName, ItemGroup context, @Nonnull Class<T> type) { Item r = getItem(pathName, context); if (type.isInstance(r)) return type.cast(r); return null; } public final <T extends Item> T getItem(String pathName, Item context, Class<T> type) { return getItem(pathName,context!=null?context.getParent():null,type); } public File getRootDirFor(TopLevelItem child) { return getRootDirFor(child.getName()); } private File getRootDirFor(String name) { return new File(new File(getRootDir(),"jobs"), name); } /** * Gets the {@link Item} object by its full name. * Full names are like path names, where each name of {@link Item} is * combined by '/'. * * @return * null if either such {@link Item} doesn't exist under the given full name, * or it exists but it's no an instance of the given type. * @throws AccessDeniedException as per {@link ItemGroup#getItem} */ public @CheckForNull <T extends Item> T getItemByFullName(@Nonnull String fullName, Class<T> type) throws AccessDeniedException { StringTokenizer tokens = new StringTokenizer(fullName,"/"); ItemGroup parent = this; if(!tokens.hasMoreTokens()) return null; // for example, empty full name. while(true) { Item item = parent.getItem(tokens.nextToken()); if(!tokens.hasMoreTokens()) { if(type.isInstance(item)) return type.cast(item); else return null; } if(!(item instanceof ItemGroup)) return null; // this item can't have any children if (!item.hasPermission(Item.READ)) return null; // TODO consider DISCOVER parent = (ItemGroup) item; } } public @CheckForNull Item getItemByFullName(String fullName) { return getItemByFullName(fullName,Item.class); } /** * Gets the user of the given name. * * @return the user of the given name (which may or may not be an id), if that person exists; else null * @see User#get(String,boolean) * @see User#getById(String, boolean) */ public @CheckForNull User getUser(String name) { return User.get(name, User.ALLOW_USER_CREATION_VIA_URL && hasPermission(ADMINISTER)); } public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException { return createProject(type, name, true); } public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException { return itemGroupMixIn.createProject(type,name,notify); } /** * Overwrites the existing item by new one. * * <p> * This is a short cut for deleting an existing job and adding a new one. */ public synchronized void putItem(TopLevelItem item) throws IOException, InterruptedException { String name = item.getName(); TopLevelItem old = items.get(name); if (old ==item) return; // noop checkPermission(Item.CREATE); if (old!=null) old.delete(); items.put(name,item); ItemListener.fireOnCreated(item); } /** * Creates a new job. * * <p> * This version infers the descriptor from the type of the top-level item. * * @throws IllegalArgumentException * if the project of the given name already exists. */ public synchronized <T extends TopLevelItem> T createProject( Class<T> type, String name ) throws IOException { return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name)); } /** * Called by {@link Job#renameTo(String)} to update relevant data structure. * assumed to be synchronized on Jenkins by the caller. */ public void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException { items.remove(oldName); items.put(newName,job); // For compatibility with old views: for (View v : views) v.onJobRenamed(job, oldName, newName); } /** * Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)} */ public void onDeleted(TopLevelItem item) throws IOException { ItemListener.fireOnDeleted(item); items.remove(item.getName()); // For compatibility with old views: for (View v : views) v.onJobRenamed(item, item.getName(), null); } @Override public boolean canAdd(TopLevelItem item) { return true; } @Override synchronized public <I extends TopLevelItem> I add(I item, String name) throws IOException, IllegalArgumentException { if (items.containsKey(name)) { throw new IllegalArgumentException("already an item '" + name + "'"); } items.put(name, item); return item; } @Override public void remove(TopLevelItem item) throws IOException, IllegalArgumentException { items.remove(item.getName()); } public FingerprintMap getFingerprintMap() { return fingerprintMap; } // if no finger print matches, display "not found page". @StaplerDispatchable public Object getFingerprint( String md5sum ) throws IOException { Fingerprint r = fingerprintMap.get(md5sum); if(r==null) return new NoFingerprintMatch(md5sum); else return r; } /** * Gets a {@link Fingerprint} object if it exists. * Otherwise null. */ public Fingerprint _getFingerprint( String md5sum ) throws IOException { return fingerprintMap.get(md5sum); } /** * The file we save our configuration. */ private XmlFile getConfigFile() { return new XmlFile(XSTREAM, new File(root,"config.xml")); } public int getNumExecutors() { return numExecutors; } public Mode getMode() { return mode; } public void setMode(Mode m) throws IOException { this.mode = m; save(); } public String getLabelString() { return fixNull(label).trim(); } @Override public void setLabelString(String label) throws IOException { this.label = label; save(); } @Override public LabelAtom getSelfLabel() { return getLabelAtom("master"); } @Override @Nonnull public Computer createComputer() { return new Hudson.MasterComputer(); } private void loadConfig() throws IOException { XmlFile cfg = getConfigFile(); if (cfg.exists()) { // reset some data that may not exist in the disk file // so that we can take a proper compensation action later. primaryView = null; views.clear(); // load from disk cfg.unmarshal(Jenkins.this); } try { checkRawBuildsDir(buildsDir); setBuildsAndWorkspacesDir(); } catch (InvalidBuildsDir invalidBuildsDir) { throw new IOException(invalidBuildsDir); } } private void setBuildsAndWorkspacesDir() throws IOException, InvalidBuildsDir { boolean mustSave = false; String newBuildsDir = SystemProperties.getString(BUILDS_DIR_PROP); boolean freshStartup = STARTUP_MARKER_FILE.isOff(); if (newBuildsDir != null && !buildsDir.equals(newBuildsDir)) { checkRawBuildsDir(newBuildsDir); Level level = freshStartup ? Level.INFO : Level.WARNING; LOGGER.log(level, "Changing builds directories from {0} to {1}. Beware that no automated data migration will occur.", new String[]{buildsDir, newBuildsDir}); buildsDir = newBuildsDir; mustSave = true; } else if (!isDefaultBuildDir()) { LOGGER.log(Level.INFO, "Using non default builds directories: {0}.", buildsDir); } String newWorkspacesDir = SystemProperties.getString(WORKSPACES_DIR_PROP); if (newWorkspacesDir != null && !workspaceDir.equals(newWorkspacesDir)) { Level level = freshStartup ? Level.INFO : Level.WARNING; LOGGER.log(level, "Changing workspaces directories from {0} to {1}. Beware that no automated data migration will occur.", new String[]{workspaceDir, newWorkspacesDir}); workspaceDir = newWorkspacesDir; mustSave = true; } else if (!isDefaultWorkspaceDir()) { LOGGER.log(Level.INFO, "Using non default workspaces directories: {0}.", workspaceDir); } if (mustSave) { save(); } } /** * Checks the correctness of the newBuildsDirValue for use as {@link #buildsDir}. * @param newBuildsDirValue the candidate newBuildsDirValue for updating {@link #buildsDir}. */ @VisibleForTesting /*private*/ static void checkRawBuildsDir(String newBuildsDirValue) throws InvalidBuildsDir { // do essentially what expandVariablesForDirectory does, without an Item String replacedValue = expandVariablesForDirectory(newBuildsDirValue, "doCheckRawBuildsDir-Marker:foo", Jenkins.get().getRootDir().getPath() + "/jobs/doCheckRawBuildsDir-Marker$foo"); File replacedFile = new File(replacedValue); if (!replacedFile.isAbsolute()) { throw new InvalidBuildsDir(newBuildsDirValue + " does not resolve to an absolute path"); } if (!replacedValue.contains("doCheckRawBuildsDir-Marker")) { throw new InvalidBuildsDir(newBuildsDirValue + " does not contain ${ITEM_FULL_NAME} or ${ITEM_ROOTDIR}, cannot distinguish between projects"); } if (replacedValue.contains("doCheckRawBuildsDir-Marker:foo")) { // make sure platform can handle colon try { File tmp = File.createTempFile("Jenkins-doCheckRawBuildsDir", "foo:bar"); tmp.delete(); } catch (IOException e) { throw new InvalidBuildsDir(newBuildsDirValue + " contains ${ITEM_FULLNAME} but your system does not support it (JENKINS-12251). Use ${ITEM_FULL_NAME} instead"); } } File d = new File(replacedValue); if (!d.isDirectory()) { // if dir does not exist (almost guaranteed) need to make sure nearest existing ancestor can be written to d = d.getParentFile(); while (!d.exists()) { d = d.getParentFile(); } if (!d.canWrite()) { throw new InvalidBuildsDir(newBuildsDirValue + " does not exist and probably cannot be created"); } } } private synchronized TaskBuilder loadTasks() throws IOException { File projectsDir = new File(root,"jobs"); if(!projectsDir.getCanonicalFile().isDirectory() && !projectsDir.mkdirs()) { if(projectsDir.exists()) throw new IOException(projectsDir+" is not a directory"); throw new IOException("Unable to create "+projectsDir+"\nPermission issue? Please create this directory manually."); } File[] subdirs = projectsDir.listFiles(); final Set<String> loadedNames = Collections.synchronizedSet(new HashSet<>()); TaskGraphBuilder g = new TaskGraphBuilder(); Handle loadJenkins = g.requires(EXTENSIONS_AUGMENTED).attains(JOB_LOADED).add("Loading global config", new Executable() { public void run(Reactor session) throws Exception { loadConfig(); // if we are loading old data that doesn't have this field if (slaves != null && !slaves.isEmpty() && nodes.isLegacy()) { nodes.setNodes(slaves); slaves = null; } else { nodes.load(); } clouds.setOwner(Jenkins.this); } }); List<Handle> loadJobs = new ArrayList<>(); for (final File subdir : subdirs) { loadJobs.add(g.requires(loadJenkins).attains(JOB_LOADED).notFatal().add("Loading item " + subdir.getName(), new Executable() { public void run(Reactor session) throws Exception { if(!Items.getConfigFile(subdir).exists()) { //Does not have job config file, so it is not a jenkins job hence skip it return; } TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir); items.put(item.getName(), item); loadedNames.add(item.getName()); } })); } g.requires(loadJobs.toArray(new Handle[0])).attains(JOB_LOADED).add("Cleaning up obsolete items deleted from the disk", new Executable() { public void run(Reactor reactor) throws Exception { // anything we didn't load from disk, throw them away. // doing this after loading from disk allows newly loaded items // to inspect what already existed in memory (in case of reloading) // retainAll doesn't work well because of CopyOnWriteMap implementation, so remove one by one // hopefully there shouldn't be too many of them. for (String name : items.keySet()) { if (!loadedNames.contains(name)) items.remove(name); } } }); g.requires(JOB_LOADED).attains(COMPLETED).add("Finalizing set up",new Executable() { public void run(Reactor session) throws Exception { rebuildDependencyGraph(); {// recompute label objects - populates the labels mapping. for (Node slave : nodes.getNodes()) // Note that not all labels are visible until the agents have connected. slave.getAssignedLabels(); getAssignedLabels(); } // initialize views by inserting the default view if necessary // this is both for clean Jenkins and for backward compatibility. if(views.size()==0 || primaryView==null) { View v = new AllView(AllView.DEFAULT_VIEW_NAME); setViewOwner(v); views.add(0,v); primaryView = v.getViewName(); } primaryView = AllView.migrateLegacyPrimaryAllViewLocalizedName(views, primaryView); if (useSecurity!=null && !useSecurity) { // forced reset to the unsecure mode. // this works as an escape hatch for people who locked themselves out. authorizationStrategy = AuthorizationStrategy.UNSECURED; setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); } else { // read in old data that doesn't have the security field set if(authorizationStrategy==null) { if(useSecurity==null) authorizationStrategy = AuthorizationStrategy.UNSECURED; else authorizationStrategy = new LegacyAuthorizationStrategy(); } if(securityRealm==null) { if(useSecurity==null) setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); else setSecurityRealm(new LegacySecurityRealm()); } else { // force the set to proxy setSecurityRealm(securityRealm); } } // Initialize the filter with the crumb issuer setCrumbIssuer(crumbIssuer); // auto register root actions for (Action a : getExtensionList(RootAction.class)) if (!actions.contains(a)) actions.add(a); setupWizard = new SetupWizard(); getInstallState().initializeState(); } }); return g; } /** * Save the settings to a file. */ public synchronized void save() throws IOException { if(BulkChange.contains(this)) return; if (initLevel == InitMilestone.COMPLETED) { LOGGER.log(FINE, "setting version {0} to {1}", new Object[] {version, VERSION}); version = VERSION; } else { LOGGER.log(FINE, "refusing to set version {0} to {1} during {2}", new Object[] {version, VERSION, initLevel}); } getConfigFile().write(this); SaveableListener.fireOnChange(this, getConfigFile()); } private void saveQuietly() { try { save(); } catch (IOException x) { LOGGER.log(Level.WARNING, null, x); } } /** * Called to shut down the system. */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD") public void cleanUp() { if (theInstance != this && theInstance != null) { LOGGER.log(Level.WARNING, "This instance is no longer the singleton, ignoring cleanUp()"); return; } synchronized (Jenkins.class) { if (cleanUpStarted) { LOGGER.log(Level.WARNING, "Jenkins.cleanUp() already started, ignoring repeated cleanUp()"); return; } cleanUpStarted = true; } try { LOGGER.log(Level.INFO, "Stopping Jenkins"); final List<Throwable> errors = new ArrayList<>(); fireBeforeShutdown(errors); _cleanUpRunTerminators(errors); terminating = true; final Set<Future<?>> pending = _cleanUpDisconnectComputers(errors); _cleanUpShutdownUDPBroadcast(errors); _cleanUpCloseDNSMulticast(errors); _cleanUpInterruptReloadThread(errors); _cleanUpShutdownTriggers(errors); _cleanUpShutdownTimer(errors); _cleanUpShutdownTcpSlaveAgent(errors); _cleanUpShutdownPluginManager(errors); _cleanUpPersistQueue(errors); _cleanUpShutdownThreadPoolForLoad(errors); _cleanUpAwaitDisconnects(errors, pending); _cleanUpPluginServletFilters(errors); _cleanUpReleaseAllLoggers(errors); LOGGER.log(Level.INFO, "Jenkins stopped"); if (!errors.isEmpty()) { StringBuilder message = new StringBuilder("Unexpected issues encountered during cleanUp: "); Iterator<Throwable> iterator = errors.iterator(); message.append(iterator.next().getMessage()); while (iterator.hasNext()) { message.append("; "); message.append(iterator.next().getMessage()); } iterator = errors.iterator(); RuntimeException exception = new RuntimeException(message.toString(), iterator.next()); while (iterator.hasNext()) { exception.addSuppressed(iterator.next()); } throw exception; } } finally { theInstance = null; if (JenkinsJVM.isJenkinsJVM()) { JenkinsJVMAccess._setJenkinsJVM(oldJenkinsJVM); } ClassFilterImpl.unregister(); } } private void fireBeforeShutdown(List<Throwable> errors) { LOGGER.log(Level.FINE, "Notifying termination"); for (ItemListener l : ItemListener.all()) { try { l.onBeforeShutdown(); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(Level.WARNING, "ItemListener " + l + ": " + e.getMessage(), e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(Level.WARNING, "ItemListener " + l + ": " + e.getMessage(), e); // save for later errors.add(e); } } } private void _cleanUpRunTerminators(List<Throwable> errors) { try { final TerminatorFinder tf = new TerminatorFinder( pluginManager != null ? pluginManager.uberClassLoader : Thread.currentThread().getContextClassLoader()); new Reactor(tf).execute(new Executor() { @Override public void execute(Runnable command) { command.run(); } }, new ReactorListener() { final Level level = Level.parse(Configuration.getStringConfigParameter("termLogLevel", "FINE")); public void onTaskStarted(Task t) { LOGGER.log(level, "Started {0}", InitReactorRunner.getDisplayName(t)); } public void onTaskCompleted(Task t) { LOGGER.log(level, "Completed {0}", InitReactorRunner.getDisplayName(t)); } public void onTaskFailed(Task t, Throwable err, boolean fatal) { LOGGER.log(SEVERE, "Failed " + InitReactorRunner.getDisplayName(t), err); } public void onAttained(Milestone milestone) { Level lv = level; String s = "Attained " + milestone.toString(); if (milestone instanceof TermMilestone && !Main.isUnitTest) { lv = Level.INFO; // noteworthy milestones --- at least while we debug problems further s = milestone.toString(); } LOGGER.log(lv, s); } }); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to execute termination", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to execute termination", e); // save for later errors.add(e); } } private Set<Future<?>> _cleanUpDisconnectComputers(final List<Throwable> errors) { LOGGER.log(Main.isUnitTest ? Level.FINE : Level.INFO, "Starting node disconnection"); final Set<Future<?>> pending = new HashSet<>(); // JENKINS-28840 we know we will be interrupting all the Computers so get the Queue lock once for all Queue.withLock(new Runnable() { @Override public void run() { for( Computer c : computers.values() ) { try { c.interrupt(); killComputer(c); pending.add(c.disconnect(null)); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(Level.WARNING, "Could not disconnect " + c + ": " + e.getMessage(), e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(Level.WARNING, "Could not disconnect " + c + ": " + e.getMessage(), e); // save for later errors.add(e); } } } }); return pending; } private void _cleanUpShutdownUDPBroadcast(List<Throwable> errors) { if(udpBroadcastThread!=null) { LOGGER.log(Level.FINE, "Shutting down {0}", udpBroadcastThread.getName()); try { udpBroadcastThread.shutdown(); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to shutdown UDP Broadcast Thread", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to shutdown UDP Broadcast Thread", e); // save for later errors.add(e); } } } private void _cleanUpCloseDNSMulticast(List<Throwable> errors) { if(dnsMultiCast!=null) { LOGGER.log(Level.FINE, "Closing DNS Multicast service"); try { dnsMultiCast.close(); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to close DNS Multicast service", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to close DNS Multicast service", e); // save for later errors.add(e); } } } private void _cleanUpInterruptReloadThread(List<Throwable> errors) { LOGGER.log(Level.FINE, "Interrupting reload thread"); try { interruptReloadThread(); } catch (SecurityException e) { LOGGER.log(WARNING, "Not permitted to interrupt reload thread", e); errors.add(e); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to interrupt reload thread", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to interrupt reload thread", e); // save for later errors.add(e); } } private void _cleanUpShutdownTriggers(List<Throwable> errors) { LOGGER.log(Level.FINE, "Shutting down triggers"); try { final java.util.Timer timer = Trigger.timer; if (timer != null) { final CountDownLatch latch = new CountDownLatch(1); timer.schedule(new TimerTask() { @Override public void run() { timer.cancel(); latch.countDown(); } }, 0); if (latch.await(10, TimeUnit.SECONDS)) { LOGGER.log(Level.FINE, "Triggers shut down successfully"); } else { timer.cancel(); LOGGER.log(Level.INFO, "Gave up waiting for triggers to finish running"); } } Trigger.timer = null; } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to shut down triggers", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to shut down triggers", e); // save for later errors.add(e); } } private void _cleanUpShutdownTimer(List<Throwable> errors) { LOGGER.log(Level.FINE, "Shutting down timer"); try { Timer.shutdown(); } catch (SecurityException e) { LOGGER.log(WARNING, "Not permitted to shut down Timer", e); errors.add(e); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to shut down Timer", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to shut down Timer", e); // save for later errors.add(e); } } private void _cleanUpShutdownTcpSlaveAgent(List<Throwable> errors) { if(tcpSlaveAgentListener!=null) { LOGGER.log(FINE, "Shutting down TCP/IP agent listener"); try { tcpSlaveAgentListener.shutdown(); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to shut down TCP/IP agent listener", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to shut down TCP/IP agent listener", e); // save for later errors.add(e); } } } private void _cleanUpShutdownPluginManager(List<Throwable> errors) { if(pluginManager!=null) {// be defensive. there could be some ugly timing related issues LOGGER.log(Main.isUnitTest ? Level.FINE : Level.INFO, "Stopping plugin manager"); try { pluginManager.stop(); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to stop plugin manager", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to stop plugin manager", e); // save for later errors.add(e); } } } private void _cleanUpPersistQueue(List<Throwable> errors) { if(getRootDir().exists()) { // if we are aborting because we failed to create JENKINS_HOME, // don't try to save. Issue #536 LOGGER.log(Main.isUnitTest ? Level.FINE : Level.INFO, "Persisting build queue"); try { getQueue().save(); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to persist build queue", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to persist build queue", e); // save for later errors.add(e); } } } private void _cleanUpShutdownThreadPoolForLoad(List<Throwable> errors) { LOGGER.log(FINE, "Shuting down Jenkins load thread pool"); try { threadPoolForLoad.shutdown(); } catch (SecurityException e) { LOGGER.log(WARNING, "Not permitted to shut down Jenkins load thread pool", e); errors.add(e); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to shut down Jenkins load thread pool", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to shut down Jenkins load thread pool", e); // save for later errors.add(e); } } private void _cleanUpAwaitDisconnects(List<Throwable> errors, Set<Future<?>> pending) { if (!pending.isEmpty()) { LOGGER.log(Main.isUnitTest ? Level.FINE : Level.INFO, "Waiting for node disconnection completion"); } for (Future<?> f : pending) { try { f.get(10, TimeUnit.SECONDS); // if clean up operation didn't complete in time, we fail the test } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; // someone wants us to die now. quick! } catch (ExecutionException e) { LOGGER.log(Level.WARNING, "Failed to shut down remote computer connection cleanly", e); } catch (TimeoutException e) { LOGGER.log(Level.WARNING, "Failed to shut down remote computer connection within 10 seconds", e); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(Level.WARNING, "Failed to shut down remote computer connection", e); } catch (Throwable e) { LOGGER.log(Level.SEVERE, "Unexpected error while waiting for remote computer connection disconnect", e); errors.add(e); } } } private void _cleanUpPluginServletFilters(List<Throwable> errors) { LOGGER.log(Level.FINE, "Stopping filters"); try { PluginServletFilter.cleanUp(); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to stop filters", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to stop filters", e); // save for later errors.add(e); } } private void _cleanUpReleaseAllLoggers(List<Throwable> errors) { LOGGER.log(Level.FINE, "Releasing all loggers"); try { LogFactory.releaseAll(); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to release all loggers", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to release all loggers", e); // save for later errors.add(e); } } public Object getDynamic(String token) { for (Action a : getActions()) { String url = a.getUrlName(); if (url==null) continue; if (url.equals(token) || url.equals('/' + token)) return a; } for (Action a : getManagementLinks()) if (Objects.equals(a.getUrlName(), token)) return a; return null; } // // // actions // // /** * Accepts submission from the configuration page. */ @RequirePOST public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { BulkChange bc = new BulkChange(this); try { checkPermission(ADMINISTER); JSONObject json = req.getSubmittedForm(); systemMessage = Util.nullify(req.getParameter("system_message")); boolean result = true; for (Descriptor<?> d : Functions.getSortedDescriptorsForGlobalConfigUnclassified()) result &= configureDescriptor(req,json,d); save(); updateComputerList(); if(result) FormApply.success(req.getContextPath()+'/').generateResponse(req, rsp, null); else FormApply.success("configure").generateResponse(req, rsp, null); // back to config } finally { bc.commit(); } } /** * Gets the {@link CrumbIssuer} currently in use. * * @return null if none is in use. */ @CheckForNull public CrumbIssuer getCrumbIssuer() { return crumbIssuer; } public void setCrumbIssuer(CrumbIssuer issuer) { crumbIssuer = issuer; } public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { rsp.sendRedirect("foo"); } private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException { // collapse the structure to remain backward compatible with the JSON structure before 1. String name = d.getJsonSafeClassName(); JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object. json.putAll(js); return d.configure(req, js); } /** * Accepts submission from the node configuration page. */ @RequirePOST public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { checkPermission(ADMINISTER); BulkChange bc = new BulkChange(this); try { JSONObject json = req.getSubmittedForm(); ExtensionList.lookupSingleton(MasterBuildConfiguration.class).configure(req,json); getNodeProperties().rebuild(req, json.optJSONObject("nodeProperties"), NodeProperty.all()); } finally { bc.commit(); } updateComputerList(); rsp.sendRedirect(req.getContextPath()+'/'+toComputer().getUrl()); // back to the computer page } /** * Accepts the new description. */ @RequirePOST public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { getPrimaryView().doSubmitDescription(req, rsp); } @RequirePOST public synchronized HttpRedirect doQuietDown() throws IOException { try { return doQuietDown(false,0); } catch (InterruptedException e) { throw new AssertionError(); // impossible } } /** * Quiet down Jenkins - preparation for a restart * * @param block Block until the system really quiets down and no builds are running * @param timeout If non-zero, only block up to the specified number of milliseconds */ @RequirePOST public HttpRedirect doQuietDown(@QueryParameter boolean block, @QueryParameter int timeout) throws InterruptedException, IOException { synchronized (this) { checkPermission(ADMINISTER); isQuietingDown = true; } if (block) { long waitUntil = timeout; if (timeout > 0) waitUntil += System.currentTimeMillis(); while (isQuietingDown && (timeout <= 0 || System.currentTimeMillis() < waitUntil) && !RestartListener.isAllReady()) { Thread.sleep(TimeUnit.SECONDS.toMillis(1)); } } return new HttpRedirect("."); } /** * Cancel previous quiet down Jenkins - preparation for a restart */ @RequirePOST // TODO the cancel link needs to be updated accordingly public synchronized HttpRedirect doCancelQuietDown() { checkPermission(ADMINISTER); isQuietingDown = false; getQueue().scheduleMaintenance(); return new HttpRedirect("."); } public HttpResponse doToggleCollapse() throws ServletException, IOException { final StaplerRequest request = Stapler.getCurrentRequest(); final String paneId = request.getParameter("paneId"); PaneStatusProperties.forCurrentUser().toggleCollapsed(paneId); return HttpResponses.forwardToPreviousPage(); } /** * Backward compatibility. Redirect to the thread dump. */ // TODO annotate @GET once baseline includes Stapler version XXX public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException { rsp.sendRedirect2("threadDump"); } /** * Obtains the thread dump of all agents (including the master.) * * <p> * Since this is for diagnostics, it has a built-in precautionary measure against hang agents. */ public Map<String,Map<String,String>> getAllThreadDumps() throws IOException, InterruptedException { checkPermission(ADMINISTER); // issue the requests all at once Map<String,Future<Map<String,String>>> future = new HashMap<>(); for (Computer c : getComputers()) { try { future.put(c.getName(), RemotingDiagnostics.getThreadDumpAsync(c.getChannel())); } catch(Exception e) { LOGGER.info("Failed to get thread dump for node " + c.getName() + ": " + e.getMessage()); } } if (toComputer() == null) { future.put("master", RemotingDiagnostics.getThreadDumpAsync(FilePath.localChannel)); } // if the result isn't available in 5 sec, ignore that. // this is a precaution against hang nodes long endTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(5); Map<String,Map<String,String>> r = new HashMap<>(); for (Entry<String, Future<Map<String, String>>> e : future.entrySet()) { try { r.put(e.getKey(), e.getValue().get(endTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS)); } catch (Exception x) { r.put(e.getKey(), Collections.singletonMap("Failed to retrieve thread dump", Functions.printThrowable(x))); } } return Collections.unmodifiableSortedMap(new TreeMap<>(r)); } @RequirePOST public synchronized TopLevelItem doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { return itemGroupMixIn.createTopLevelItem(req, rsp); } /** * @since 1.319 */ public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException { return itemGroupMixIn.createProjectFromXML(name, xml); } @SuppressWarnings({"unchecked"}) public <T extends TopLevelItem> T copy(T src, String name) throws IOException { return itemGroupMixIn.copy(src, name); } // a little more convenient overloading that assumes the caller gives us the right type // (or else it will fail with ClassCastException) public <T extends AbstractProject<?,?>> T copy(T src, String name) throws IOException { return (T)copy((TopLevelItem)src,name); } @RequirePOST public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { checkPermission(View.CREATE); addView(View.create(req,rsp, this)); } /** * Check if the given name is suitable as a name * for job, view, etc. * * @throws Failure * if the given name is not good */ public static void checkGoodName(String name) throws Failure { if(name==null || name.length()==0) throw new Failure(Messages.Hudson_NoName()); if(".".equals(name.trim())) throw new Failure(Messages.Jenkins_NotAllowedName(".")); if("..".equals(name.trim())) throw new Failure(Messages.Jenkins_NotAllowedName("..")); for( int i=0; i<name.length(); i++ ) { char ch = name.charAt(i); if(Character.isISOControl(ch)) { throw new Failure(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name))); } if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1) throw new Failure(Messages.Hudson_UnsafeChar(ch)); } // looks good } private static String toPrintableName(String name) { StringBuilder printableName = new StringBuilder(); for( int i=0; i<name.length(); i++ ) { char ch = name.charAt(i); if(Character.isISOControl(ch)) printableName.append("\\u").append((int)ch).append(';'); else printableName.append(ch); } return printableName.toString(); } /** * Checks if the user was successfully authenticated. * * @see BasicAuthenticationFilter */ public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { // TODO fire something in SecurityListener? (seems to be used only for REST calls when LegacySecurityRealm is active) if(req.getUserPrincipal()==null) { // authentication must have failed rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } // the user is now authenticated, so send him back to the target String path = req.getContextPath()+req.getOriginalRestOfPath(); String q = req.getQueryString(); if(q!=null) path += '?'+q; rsp.sendRedirect2(path); } /** * Called once the user logs in. Just forward to the top page. * Used only by {@link LegacySecurityRealm}. */ public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException { if(req.getUserPrincipal()==null) { rsp.sendRedirect2("noPrincipal"); return; } // TODO fire something in SecurityListener? String from = req.getParameter("from"); if(from!=null && from.startsWith("/") && !from.equals("/loginError")) { rsp.sendRedirect2(from); // I'm bit uncomfortable letting users redirected to other sites, make sure the URL falls into this domain return; } String url = AbstractProcessingFilter.obtainFullRequestUrl(req); if(url!=null) { // if the login redirect is initiated by Acegi // this should send the user back to where s/he was from. rsp.sendRedirect2(url); return; } rsp.sendRedirect2("."); } /** * Logs out the user. */ public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { String user = getAuthentication().getName(); securityRealm.doLogout(req, rsp); SecurityListener.fireLoggedOut(user); } /** * Serves jar files for inbound agents. */ public Slave.JnlpJar getJnlpJars(String fileName) { return new Slave.JnlpJar(fileName); } public Slave.JnlpJar doJnlpJars(StaplerRequest req) { return new Slave.JnlpJar(req.getRestOfPath().substring(1)); } /** * Reloads the configuration. */ @RequirePOST public synchronized HttpResponse doReload() throws IOException { checkPermission(ADMINISTER); LOGGER.log(Level.WARNING, "Reloading Jenkins as requested by {0}", getAuthentication().getName()); // engage "loading ..." UI and then run the actual task in a separate thread WebApp.get(servletContext).setApp(new HudsonIsLoading()); new Thread("Jenkins config reload thread") { @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); reload(); } catch (Exception e) { LOGGER.log(SEVERE,"Failed to reload Jenkins config",e); new JenkinsReloadFailed(e).publish(servletContext,root); } } }.start(); return HttpResponses.redirectViaContextPath("/"); } /** * Reloads the configuration synchronously. * Beware that this calls neither {@link ItemListener#onLoaded} nor {@link Initializer}s. */ public void reload() throws IOException, InterruptedException, ReactorException { queue.save(); executeReactor(null, loadTasks()); // Ensure we reached the final initialization state. Log the error otherwise if (initLevel != InitMilestone.COMPLETED) { LOGGER.log(SEVERE, "Jenkins initialization has not reached the COMPLETED initialization milestone after the configuration reload. " + "Current state: {0}. " + "It may cause undefined incorrect behavior in Jenkins plugin relying on this state. " + "It is likely an issue with the Initialization task graph. " + "Example: usage of @Initializer(after = InitMilestone.COMPLETED) in a plugin (JENKINS-37759). " + "Please create a bug in Jenkins bugtracker.", initLevel); } User.reload(); queue.load(); WebApp.get(servletContext).setApp(this); } /** * Do a finger-print check. */ @RequirePOST public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { // Parse the request try (MultipartFormDataParser p = new MultipartFormDataParser(req)) { if (isUseCrumbs() && !getCrumbIssuer().validateCrumb(req, p)) { // TODO investigate whether this check can be removed rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "No crumb found"); } rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+ Util.getDigestOf(p.getFileItem("name").getInputStream())+'/'); } } /** * For debugging. Expose URL to perform GC. */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("DM_GC") @RequirePOST public void doGc(StaplerResponse rsp) throws IOException { checkPermission(Jenkins.ADMINISTER); System.gc(); rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); rsp.getWriter().println("GCed"); } /** * End point that intentionally throws an exception to test the error behaviour. * @since 1.467 */ @StaplerDispatchable public void doException() { throw new RuntimeException(); } public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws IOException, JellyException { ContextMenu menu = new ContextMenu().from(this, request, response); for (MenuItem i : menu.items) { if (i.url.equals(request.getContextPath() + "/manage")) { // add "Manage Jenkins" subitems i.subMenu = new ContextMenu().from(this, request, response, "manage"); } } return menu; } public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception { ContextMenu menu = new ContextMenu(); for (View view : getViews()) { menu.add(view.getViewUrl(),view.getDisplayName()); } return menu; } /** * Obtains the heap dump. */ public HeapDump getHeapDump() throws IOException { return new HeapDump(this,FilePath.localChannel); } /** * Simulates OutOfMemoryError. * Useful to make sure OutOfMemoryHeapDump setting. */ @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") @RequirePOST public void doSimulateOutOfMemory() throws IOException { checkPermission(ADMINISTER); System.out.println("Creating artificial OutOfMemoryError situation"); List<Object> args = new ArrayList<>(); //noinspection InfiniteLoopStatement while (true) args.add(new byte[1024*1024]); } /** * Binds /userContent/... to $JENKINS_HOME/userContent. */ public DirectoryBrowserSupport doUserContent() { return new DirectoryBrowserSupport(this,getRootPath().child("userContent"),"User content","folder.png",true); } /** * Perform a restart of Jenkins, if we can. * * This first replaces "app" to {@link HudsonIsRestarting} */ @CLIMethod(name="restart") public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, RestartNotSupportedException { checkPermission(ADMINISTER); if (req != null && req.getMethod().equals("GET")) { req.getView(this,"_restart.jelly").forward(req,rsp); return; } if (req == null || req.getMethod().equals("POST")) { restart(); } if (rsp != null) { rsp.sendRedirect2("."); } } /** * Queues up a restart of Jenkins for when there are no builds running, if we can. * * This first replaces "app" to {@link HudsonIsRestarting} * * @since 1.332 */ @CLIMethod(name="safe-restart") public HttpResponse doSafeRestart(StaplerRequest req) throws IOException, ServletException, RestartNotSupportedException { checkPermission(ADMINISTER); if (req != null && req.getMethod().equals("GET")) return HttpResponses.forwardToView(this,"_safeRestart.jelly"); if (req == null || req.getMethod().equals("POST")) { safeRestart(); } return HttpResponses.redirectToDot(); } private static Lifecycle restartableLifecycle() throws RestartNotSupportedException { if (Main.isUnitTest) { throw new RestartNotSupportedException("Restarting the master JVM is not supported in JenkinsRule-based tests"); } Lifecycle lifecycle = Lifecycle.get(); lifecycle.verifyRestartable(); return lifecycle; } /** * Performs a restart. */ public void restart() throws RestartNotSupportedException { final Lifecycle lifecycle = restartableLifecycle(); servletContext.setAttribute("app", new HudsonIsRestarting()); new Thread("restart thread") { final String exitUser = getAuthentication().getName(); @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); // give some time for the browser to load the "reloading" page Thread.sleep(TimeUnit.SECONDS.toMillis(5)); LOGGER.info(String.format("Restarting VM as requested by %s",exitUser)); for (RestartListener listener : RestartListener.all()) listener.onRestart(); lifecycle.restart(); } catch (InterruptedException | IOException e) { LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e); } } }.start(); } /** * Queues up a restart to be performed once there are no builds currently running. * @since 1.332 */ public void safeRestart() throws RestartNotSupportedException { final Lifecycle lifecycle = restartableLifecycle(); // Quiet down so that we won't launch new builds. isQuietingDown = true; new Thread("safe-restart thread") { final String exitUser = getAuthentication().getName(); @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); // Wait 'til we have no active executors. doQuietDown(true, 0); // Make sure isQuietingDown is still true. if (isQuietingDown) { servletContext.setAttribute("app",new HudsonIsRestarting()); // give some time for the browser to load the "reloading" page LOGGER.info("Restart in 10 seconds"); Thread.sleep(TimeUnit.SECONDS.toMillis(10)); LOGGER.info(String.format("Restarting VM as requested by %s",exitUser)); for (RestartListener listener : RestartListener.all()) listener.onRestart(); lifecycle.restart(); } else { LOGGER.info("Safe-restart mode cancelled"); } } catch (Throwable e) { LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e); } } }.start(); } @Extension @Restricted(NoExternalUse.class) public static class MasterRestartNotifyier extends RestartListener { @Override public void onRestart() { Computer computer = Jenkins.get().toComputer(); if (computer == null) return; RestartCause cause = new RestartCause(); for (ComputerListener listener: ComputerListener.all()) { listener.onOffline(computer, cause); } } @Override public boolean isReadyToRestart() throws IOException, InterruptedException { return true; } private static class RestartCause extends OfflineCause.SimpleOfflineCause { protected RestartCause() { super(Messages._Jenkins_IsRestarting()); } } } /** * Shutdown the system. * @since 1.161 */ @CLIMethod(name="shutdown") @RequirePOST public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException { checkPermission(ADMINISTER); if (rsp!=null) { rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); try (PrintWriter w = rsp.getWriter()) { w.println("Shutting down"); } } new Thread("exit thread") { @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); LOGGER.info(String.format("Shutting down VM as requested by %s from %s", getAuthentication().getName(), req != null ? req.getRemoteAddr() : "???")); cleanUp(); System.exit(0); } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to shut down Jenkins", e); } } }.start(); } /** * Shutdown the system safely. * @since 1.332 */ @CLIMethod(name="safe-shutdown") @RequirePOST public HttpResponse doSafeExit(StaplerRequest req) throws IOException { checkPermission(ADMINISTER); isQuietingDown = true; final String exitUser = getAuthentication().getName(); final String exitAddr = req!=null ? req.getRemoteAddr() : "unknown"; new Thread("safe-exit thread") { @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); LOGGER.info(String.format("Shutting down VM as requested by %s from %s", exitUser, exitAddr)); // Wait 'til we have no active executors. doQuietDown(true, 0); // Make sure isQuietingDown is still true. if (isQuietingDown) { cleanUp(); System.exit(0); } } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to shut down Jenkins", e); } } }.start(); return HttpResponses.plainText("Shutting down as soon as all jobs are complete"); } /** * Gets the {@link Authentication} object that represents the user * associated with the current request. */ public static @Nonnull Authentication getAuthentication() { Authentication a = SecurityContextHolder.getContext().getAuthentication(); // on Tomcat while serving the login page, this is null despite the fact // that we have filters. Looking at the stack trace, Tomcat doesn't seem to // run the request through filters when this is the login request. // see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html if(a==null) a = ANONYMOUS; return a; } /** * For system diagnostics. * Run arbitrary Groovy script. */ public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { _doScript(req, rsp, req.getView(this, "_script.jelly"), FilePath.localChannel, getACL()); } /** * Run arbitrary Groovy script and return result as plain text. */ public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { _doScript(req, rsp, req.getView(this, "_scriptText.jelly"), FilePath.localChannel, getACL()); } /** * @since 1.509.1 */ public static void _doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view, VirtualChannel channel, ACL acl) throws IOException, ServletException { // ability to run arbitrary script is dangerous acl.checkPermission(RUN_SCRIPTS); String text = req.getParameter("script"); if (text != null) { if (!"POST".equals(req.getMethod())) { throw HttpResponses.error(HttpURLConnection.HTTP_BAD_METHOD, "requires POST"); } if (channel == null) { throw HttpResponses.error(HttpURLConnection.HTTP_NOT_FOUND, "Node is offline"); } try { req.setAttribute("output", RemotingDiagnostics.executeGroovy(text, channel)); } catch (InterruptedException e) { throw new ServletException(e); } } view.forward(req, rsp); } /** * Evaluates the Jelly script submitted by the client. * * This is useful for system administration as well as unit testing. */ @RequirePOST public void doEval(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { checkPermission(RUN_SCRIPTS); try { MetaClass mc = WebApp.getCurrent().getMetaClass(getClass()); Script script = mc.classLoader.loadTearOff(JellyClassLoaderTearOff.class).createContext().compileScript(new InputSource(req.getReader())); new JellyRequestDispatcher(this,script).forward(req,rsp); } catch (JellyException e) { throw new ServletException(e); } } /** * Sign up for the user account. */ public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { if (getSecurityRealm().allowsSignup()) { req.getView(getSecurityRealm(), "signup.jelly").forward(req, rsp); return; } req.getView(SecurityRealm.class, "signup.jelly").forward(req, rsp); } /** * Changes the icon size by changing the cookie */ public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { String qs = req.getQueryString(); if(qs==null) throw new ServletException(); Cookie cookie = new Cookie("iconSize", Functions.validateIconSize(qs)); cookie.setMaxAge(/* ~4 mo. */9999999); // #762 rsp.addCookie(cookie); String ref = req.getHeader("Referer"); if(ref==null) ref="."; rsp.sendRedirect2(ref); } @RequirePOST public void doFingerprintCleanup(StaplerResponse rsp) throws IOException { checkPermission(ADMINISTER); FingerprintCleanupThread.invoke(); rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); rsp.getWriter().println("Invoked"); } @RequirePOST public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException { checkPermission(ADMINISTER); WorkspaceCleanupThread.invoke(); rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); rsp.getWriter().println("Invoked"); } /** * If the user chose the default JDK, make sure we got 'java' in PATH. */ public FormValidation doDefaultJDKCheck(StaplerRequest request, @QueryParameter String value) { if(!JDK.isDefaultName(value)) // assume the user configured named ones properly in system config --- // or else system config should have reported form field validation errors. return FormValidation.ok(); // default JDK selected. Does such java really exist? if(JDK.isDefaultJDKValid(Jenkins.this)) return FormValidation.ok(); else return FormValidation.errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath())); } /** * Checks if a top-level view with the given name exists and * make sure that the name is good as a view name. */ public FormValidation doCheckViewName(@QueryParameter String value) { checkPermission(View.CREATE); String name = fixEmpty(value); if (name == null) return FormValidation.ok(); // already exists? if (getView(name) != null) return FormValidation.error(Messages.Hudson_ViewAlreadyExists(name)); // good view name? try { checkGoodName(name); } catch (Failure e) { return FormValidation.error(e.getMessage()); } return FormValidation.ok(); } /** * Checks if a top-level view with the given name exists. * @deprecated 1.512 */ @Deprecated public FormValidation doViewExistsCheck(@QueryParameter String value) { checkPermission(View.CREATE); String view = fixEmpty(value); if(view==null) return FormValidation.ok(); if(getView(view)==null) return FormValidation.ok(); else return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view)); } /** * Serves static resources placed along with Jelly view files. * <p> * This method can serve a lot of files, so care needs to be taken * to make this method secure. It's not clear to me what's the best * strategy here, though the current implementation is based on * file extensions. */ public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { String path = req.getRestOfPath(); // cut off the "..." portion of /resources/.../path/to/file // as this is only used to make path unique (which in turn // allows us to set a long expiration date path = path.substring(path.indexOf('/',1)+1); int idx = path.lastIndexOf('.'); String extension = path.substring(idx+1); if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) { URL url = pluginManager.uberClassLoader.getResource(path); if(url!=null) { long expires = MetaClass.NO_CACHE ? 0 : TimeUnit.DAYS.toMillis(365); rsp.serveFile(req,url,expires); return; } } rsp.sendError(HttpServletResponse.SC_NOT_FOUND); } /** * Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve. * This set is mutable to allow plugins to add additional extensions. */ public static final Set<String> ALLOWED_RESOURCE_EXTENSIONS = new HashSet<>(Arrays.asList( "js|css|jpeg|jpg|png|gif|html|htm".split("\\|") )); /** * Checks if container uses UTF-8 to decode URLs. See * http://wiki.jenkins-ci.org/display/JENKINS/Tomcat#Tomcat-i18n */ @Restricted(NoExternalUse.class) @RestrictedSince("2.37") @Deprecated public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException { return ExtensionList.lookupSingleton(URICheckEncodingMonitor.class).doCheckURIEncoding(request); } /** * Does not check when system default encoding is "ISO-8859-1". */ @Restricted(NoExternalUse.class) @RestrictedSince("2.37") @Deprecated public static boolean isCheckURIEncodingEnabled() { return ExtensionList.lookupSingleton(URICheckEncodingMonitor.class).isCheckEnabled(); } /** * Rebuilds the dependency map. */ public void rebuildDependencyGraph() { DependencyGraph graph = new DependencyGraph(); graph.build(); // volatile acts a as a memory barrier here and therefore guarantees // that graph is fully build, before it's visible to other threads dependencyGraph = graph; dependencyGraphDirty.set(false); } /** * Rebuilds the dependency map asynchronously. * * <p> * This would keep the UI thread more responsive and helps avoid the deadlocks, * as dependency graph recomputation tends to touch a lot of other things. * * @since 1.522 */ public Future<DependencyGraph> rebuildDependencyGraphAsync() { dependencyGraphDirty.set(true); return Timer.get().schedule(new java.util.concurrent.Callable<DependencyGraph>() { @Override public DependencyGraph call() throws Exception { if (dependencyGraphDirty.get()) { rebuildDependencyGraph(); } return dependencyGraph; } }, 500, TimeUnit.MILLISECONDS); } public DependencyGraph getDependencyGraph() { return dependencyGraph; } // for Jelly public List<ManagementLink> getManagementLinks() { return ManagementLink.all(); } /** * If set, a currently active setup wizard - e.g. installation * * @since 2.0 */ @Restricted(NoExternalUse.class) public SetupWizard getSetupWizard() { return setupWizard; } /** * Exposes the current user to {@code /me} URL. */ public User getMe() { User u = User.current(); if (u == null) throw new AccessDeniedException("/me is not available when not logged in"); return u; } /** * Gets the {@link Widget}s registered on this object. * * <p> * Plugins who wish to contribute boxes on the side panel can add widgets * by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}. */ @StaplerDispatchable // some plugins use this to add views to widgets public List<Widget> getWidgets() { return widgets; } public Object getTarget() { try { checkPermission(READ); } catch (AccessDeniedException e) { if (!isSubjectToMandatoryReadPermissionCheck(Stapler.getCurrentRequest().getRestOfPath())) { return this; } throw e; } return this; } /** * Test a path to see if it is subject to mandatory read permission checks by container-managed security * @param restOfPath the URI, excluding the Jenkins root URI and query string * @return true if the path is subject to mandatory read permission checks * @since 2.37 */ public boolean isSubjectToMandatoryReadPermissionCheck(String restOfPath) { for (String name : ALWAYS_READABLE_PATHS) { if (restOfPath.startsWith(name)) { return false; } } for (String name : getUnprotectedRootActions()) { if (restOfPath.startsWith("/" + name + "/") || restOfPath.equals("/" + name)) { return false; } } // TODO SlaveComputer.doSlaveAgentJnlp; there should be an annotation to request unprotected access if (restOfPath.matches("/computer/[^/]+/slave-agent[.]jnlp") && "true".equals(Stapler.getCurrentRequest().getParameter("encrypt"))) { return false; } return true; } /** * Gets a list of unprotected root actions. * These URL prefixes should be exempted from access control checks by container-managed security. * Ideally would be synchronized with {@link #getTarget}. * @return a list of {@linkplain Action#getUrlName URL names} * @since 1.495 */ public Collection<String> getUnprotectedRootActions() { Set<String> names = new TreeSet<>(); names.add("jnlpJars"); // TODO cleaner to refactor doJnlpJars into a URA (see also JENKINS-44100) // TODO consider caching (expiring cache when actions changes) for (Action a : getActions()) { if (a instanceof UnprotectedRootAction) { String url = a.getUrlName(); if (url == null) continue; names.add(url); } } return names; } /** * Fallback to the primary view. */ public View getStaplerFallback() { return getPrimaryView(); } /** * This method checks all existing jobs to see if displayName is * unique. It does not check the displayName against the displayName of the * job that the user is configuring though to prevent a validation warning * if the user sets the displayName to what it currently is. * @param displayName * @param currentJobName */ boolean isDisplayNameUnique(String displayName, String currentJobName) { Collection<TopLevelItem> itemCollection = items.values(); // if there are a lot of projects, we'll have to store their // display names in a HashSet or something for a quick check for(TopLevelItem item : itemCollection) { if(item.getName().equals(currentJobName)) { // we won't compare the candidate displayName against the current // item. This is to prevent an validation warning if the user // sets the displayName to what the existing display name is continue; } else if(displayName.equals(item.getDisplayName())) { return false; } } return true; } /** * True if there is no item in Jenkins that has this name * @param name The name to test * @param currentJobName The name of the job that the user is configuring */ boolean isNameUnique(String name, String currentJobName) { Item item = getItem(name); if(null==item) { // the candidate name didn't return any items so the name is unique return true; } else if(item.getName().equals(currentJobName)) { // the candidate name returned an item, but the item is the item // that the user is configuring so this is ok return true; } else { // the candidate name returned an item, so it is not unique return false; } } /** * Checks to see if the candidate displayName collides with any * existing display names or project names * @param displayName The display name to test * @param jobName The name of the job the user is configuring */ public FormValidation doCheckDisplayName(@QueryParameter String displayName, @QueryParameter String jobName) { displayName = displayName.trim(); if(LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Current job name is " + jobName); } if(!isNameUnique(displayName, jobName)) { return FormValidation.warning(Messages.Jenkins_CheckDisplayName_NameNotUniqueWarning(displayName)); } else if(!isDisplayNameUnique(displayName, jobName)){ return FormValidation.warning(Messages.Jenkins_CheckDisplayName_DisplayNameNotUniqueWarning(displayName)); } else { return FormValidation.ok(); } } public static class MasterComputer extends Computer { protected MasterComputer() { super(Jenkins.get()); } /** * Returns "" to match with {@link Jenkins#getNodeName()}. */ @Override public String getName() { return ""; } @Override public boolean isConnecting() { return false; } @Override public String getDisplayName() { return Messages.Hudson_Computer_DisplayName(); } @Override public String getCaption() { return Messages.Hudson_Computer_Caption(); } @Override public String getUrl() { return "computer/(master)/"; } public RetentionStrategy getRetentionStrategy() { return RetentionStrategy.NOOP; } /** * Will always keep this guy alive so that it can function as a fallback to * execute {@link FlyweightTask}s. See JENKINS-7291. */ @Override protected boolean isAlive() { return true; } @Override public Boolean isUnix() { return !Functions.isWindows(); } /** * Report an error. */ @Override public HttpResponse doDoDelete() throws IOException { throw HttpResponses.status(SC_BAD_REQUEST); } @Override @RequirePOST public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { Jenkins.get().doConfigExecutorsSubmit(req, rsp); } @WebMethod(name="config.xml") @Override public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { throw HttpResponses.status(SC_BAD_REQUEST); } @Override public boolean hasPermission(Permission permission) { // no one should be allowed to delete the master. // this hides the "delete" link from the /computer/(master) page. if(permission==Computer.DELETE) return false; // Configuration of master node requires ADMINISTER permission return super.hasPermission(permission==Computer.CONFIGURE ? Jenkins.ADMINISTER : permission); } @Override public VirtualChannel getChannel() { return FilePath.localChannel; } @Override public Charset getDefaultCharset() { return Charset.defaultCharset(); } public List<LogRecord> getLogRecords() throws IOException, InterruptedException { return logRecords; } @RequirePOST public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { // this computer never returns null from channel, so // this method shall never be invoked. rsp.sendError(SC_NOT_FOUND); } protected Future<?> _connect(boolean forceReconnect) { return Futures.precomputed(null); } /** * {@link LocalChannel} instance that can be used to execute programs locally. * * @deprecated as of 1.558 * Use {@link FilePath#localChannel} */ @Deprecated public static final LocalChannel localChannel = FilePath.localChannel; } /** * Shortcut for {@code Jenkins.getInstanceOrNull()?.lookup.get(type)} */ public static @CheckForNull <T> T lookup(Class<T> type) { Jenkins j = Jenkins.getInstanceOrNull(); return j != null ? j.lookup.get(type) : null; } /** * Live view of recent {@link LogRecord}s produced by Jenkins. */ public static List<LogRecord> logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE /** * Thread-safe reusable {@link XStream}. */ public static final XStream XSTREAM; /** * Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily. */ public static final XStream2 XSTREAM2; private static final int TWICE_CPU_NUM = Math.max(4, Runtime.getRuntime().availableProcessors() * 2); /** * Thread pool used to load configuration in parallel, to improve the start up time. * <p> * The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers. */ /*package*/ transient final ExecutorService threadPoolForLoad = new ThreadPoolExecutor( TWICE_CPU_NUM, TWICE_CPU_NUM, 5L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new NamingThreadFactory(new DaemonThreadFactory(), "Jenkins load")); private static void computeVersion(ServletContext context) { // set the version Properties props = new Properties(); try (InputStream is = Jenkins.class.getResourceAsStream("jenkins-version.properties")) { if(is!=null) props.load(is); } catch (IOException e) { e.printStackTrace(); // if the version properties is missing, that's OK. } String ver = props.getProperty("version"); if(ver==null) ver = UNCOMPUTED_VERSION; if(Main.isDevelopmentMode && "${project.version}".equals(ver)) { // in dev mode, unable to get version (ahem Eclipse) try { File dir = new File(".").getAbsoluteFile(); while(dir != null) { File pom = new File(dir, "pom.xml"); if (pom.exists() && "pom".equals(XMLUtils.getValue("/project/artifactId", pom))) { pom = pom.getCanonicalFile(); LOGGER.info("Reading version from: " + pom.getAbsolutePath()); ver = XMLUtils.getValue("/project/version", pom); break; } dir = dir.getParentFile(); } LOGGER.info("Jenkins is in dev mode, using version: " + ver); } catch (Exception e) { LOGGER.log(Level.WARNING, "Unable to read Jenkins version: " + e.getMessage(), e); } } VERSION = ver; context.setAttribute("version",ver); VERSION_HASH = Util.getDigestOf(ver).substring(0, 8); SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8); if(ver.equals(UNCOMPUTED_VERSION) || SystemProperties.getBoolean("hudson.script.noCache")) RESOURCE_PATH = ""; else RESOURCE_PATH = "/static/"+SESSION_HASH; VIEW_RESOURCE_PATH = "/resources/"+ SESSION_HASH; } /** * The version number before it is "computed" (by a call to computeVersion()). * @since 2.0 */ @Restricted(NoExternalUse.class) public static final String UNCOMPUTED_VERSION = "?"; /** * Version number of this Jenkins. */ public static String VERSION = UNCOMPUTED_VERSION; /** * Parses {@link #VERSION} into {@link VersionNumber}, or null if it's not parseable as a version number * (such as when Jenkins is run with "mvn hudson-dev:run") */ public @CheckForNull static VersionNumber getVersion() { return toVersion(VERSION); } /** * Get the stored version of Jenkins, as stored by * {@link #doConfigSubmit(org.kohsuke.stapler.StaplerRequest, org.kohsuke.stapler.StaplerResponse)}. * <p> * Parses the version into {@link VersionNumber}, or null if it's not parseable as a version number * (such as when Jenkins is run with "mvn hudson-dev:run") * @since 2.0 */ @Restricted(NoExternalUse.class) public @CheckForNull static VersionNumber getStoredVersion() { return toVersion(Jenkins.getActiveInstance().version); } /** * Parses a version string into {@link VersionNumber}, or null if it's not parseable as a version number * (such as when Jenkins is run with "mvn hudson-dev:run") */ private static @CheckForNull VersionNumber toVersion(@CheckForNull String versionString) { if (versionString == null) { return null; } try { return new VersionNumber(versionString); } catch (NumberFormatException e) { try { // for non-released version of Jenkins, this looks like "1.345 (private-foobar), so try to approximate. int idx = versionString.indexOf(' '); if (idx > 0) { return new VersionNumber(versionString.substring(0,idx)); } } catch (NumberFormatException ignored) { // fall through } // totally unparseable return null; } catch (IllegalArgumentException e) { // totally unparseable return null; } } /** * Hash of {@link #VERSION}. */ public static String VERSION_HASH; /** * Unique random token that identifies the current session. * Used to make {@link #RESOURCE_PATH} unique so that we can set long "Expires" header. * * We used to use {@link #VERSION_HASH}, but making this session local allows us to * reuse the same {@link #RESOURCE_PATH} for static resources in plugins. */ public static String SESSION_HASH; /** * Prefix to static resources like images and javascripts in the war file. * Either "" or strings like "/static/VERSION", which avoids Jenkins to pick up * stale cache when the user upgrades to a different version. * <p> * Value computed in {@link WebAppMain}. */ public static String RESOURCE_PATH = ""; /** * Prefix to resources alongside view scripts. * Strings like "/resources/VERSION", which avoids Jenkins to pick up * stale cache when the user upgrades to a different version. * <p> * Value computed in {@link WebAppMain}. */ public static String VIEW_RESOURCE_PATH = "/resources/TBD"; public static boolean PARALLEL_LOAD = Configuration.getBooleanConfigParameter("parallelLoad", true); public static boolean KILL_AFTER_LOAD = Configuration.getBooleanConfigParameter("killAfterLoad", false); /** * @deprecated No longer used. */ @Deprecated public static boolean FLYWEIGHT_SUPPORT = true; /** * Tentative switch to activate the concurrent build behavior. * When we merge this back to the trunk, this allows us to keep * this feature hidden for a while until we iron out the kinks. * @see AbstractProject#isConcurrentBuild() * @deprecated as of 1.464 * This flag will have no effect. */ @Restricted(NoExternalUse.class) @Deprecated public static boolean CONCURRENT_BUILD = true; /** * Switch to enable people to use a shorter workspace name. */ private static final String WORKSPACE_DIRNAME = Configuration.getStringConfigParameter("workspaceDirName", "workspace"); /** * Default value of job's builds dir. * @see #getRawBuildsDir() */ private static final String DEFAULT_BUILDS_DIR = "${ITEM_ROOTDIR}/builds"; /** * Old layout for workspaces. * @see #DEFAULT_WORKSPACES_DIR */ private static final String OLD_DEFAULT_WORKSPACES_DIR = "${ITEM_ROOTDIR}/" + WORKSPACE_DIRNAME; /** * Default value for the workspace's directories layout. * @see #workspaceDir */ private static final String DEFAULT_WORKSPACES_DIR = "${JENKINS_HOME}/workspace/${ITEM_FULL_NAME}"; /** * System property name to set {@link #buildsDir}. * @see #getRawBuildsDir() */ static final String BUILDS_DIR_PROP = Jenkins.class.getName() + ".buildsDir"; /** * System property name to set {@link #workspaceDir}. * @see #getRawWorkspaceDir() */ static final String WORKSPACES_DIR_PROP = Jenkins.class.getName() + ".workspacesDir"; /** * Automatically try to launch an agent when Jenkins is initialized or a new agent computer is created. */ public static boolean AUTOMATIC_SLAVE_LAUNCH = true; private static final Logger LOGGER = Logger.getLogger(Jenkins.class.getName()); public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS; public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER; public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ,PermissionScope.JENKINS); public static final Permission RUN_SCRIPTS = new Permission(PERMISSIONS, "RunScripts", Messages._Hudson_RunScriptsPermission_Description(),ADMINISTER,PermissionScope.JENKINS); /** * Urls that are always visible without READ permission. * * <p>See also:{@link #getUnprotectedRootActions}. */ private static final ImmutableSet<String> ALWAYS_READABLE_PATHS = ImmutableSet.of( "/login", "/logout", "/accessDenied", "/adjuncts/", "/error", "/oops", "/signup", "/tcpSlaveAgentListener", "/federatedLoginService/", "/securityRealm", "/instance-identity" ); /** * {@link Authentication} object that represents the anonymous user. * Because Acegi creates its own {@link AnonymousAuthenticationToken} instances, the code must not * expect the singleton semantics. This is just a convenient instance. * * @since 1.343 */ public static final Authentication ANONYMOUS; static { try { ANONYMOUS = new AnonymousAuthenticationToken( "anonymous", "anonymous", new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")}); XSTREAM = XSTREAM2 = new XStream2(); XSTREAM.alias("jenkins", Jenkins.class); XSTREAM.alias("slave", DumbSlave.class); XSTREAM.alias("jdk", JDK.class); // for backward compatibility with <1.75, recognize the tag name "view" as well. XSTREAM.alias("view", ListView.class); XSTREAM.alias("listView", ListView.class); XSTREAM.addImplicitArray(Jenkins.class, "_disabledAgentProtocols", "disabledAgentProtocol"); XSTREAM.addImplicitArray(Jenkins.class, "_enabledAgentProtocols", "enabledAgentProtocol"); XSTREAM2.addCriticalField(Jenkins.class, "securityRealm"); XSTREAM2.addCriticalField(Jenkins.class, "authorizationStrategy"); // this seems to be necessary to force registration of converter early enough Mode.class.getEnumConstants(); // double check that initialization order didn't do any harm assert PERMISSIONS != null; assert ADMINISTER != null; } catch (RuntimeException | Error e) { // when loaded on an agent and this fails, subsequent NoClassDefFoundError will fail to chain the cause. // see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8051847 // As we don't know where the first exception will go, let's also send this to logging so that // we have a known place to look at. LOGGER.log(SEVERE, "Failed to load Jenkins.class", e); throw e; } } private static final class JenkinsJVMAccess extends JenkinsJVM { private static void _setJenkinsJVM(boolean jenkinsJVM) { JenkinsJVM.setJenkinsJVM(jenkinsJVM); } } }
core/src/main/java/jenkins/model/Jenkins.java
/* * The MIT License * * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi, * Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe, * Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc., * Yahoo!, Inc. * * 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 jenkins.model; import antlr.ANTLRException; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.google.inject.Injector; import com.thoughtworks.xstream.XStream; import hudson.*; import hudson.Launcher.LocalLauncher; import jenkins.AgentProtocol; import jenkins.diagnostics.URICheckEncodingMonitor; import jenkins.security.stapler.DoActionFilter; import jenkins.security.stapler.StaplerFilteredActionListener; import jenkins.security.stapler.StaplerDispatchable; import jenkins.security.RedactSecretJsonInErrorMessageSanitizer; import jenkins.security.stapler.TypedFilter; import jenkins.telemetry.impl.java11.CatcherClassLoader; import jenkins.telemetry.impl.java11.MissingClassTelemetry; import jenkins.util.SystemProperties; import hudson.cli.declarative.CLIMethod; import hudson.cli.declarative.CLIResolver; import hudson.init.InitMilestone; import hudson.init.InitStrategy; import hudson.init.TermMilestone; import hudson.init.TerminatorFinder; import hudson.lifecycle.Lifecycle; import hudson.lifecycle.RestartNotSupportedException; import hudson.logging.LogRecorderManager; import hudson.markup.EscapedMarkupFormatter; import hudson.markup.MarkupFormatter; import hudson.model.AbstractCIBase; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.model.AdministrativeMonitor; import hudson.model.AllView; import hudson.model.Api; import hudson.model.Computer; import hudson.model.ComputerSet; import hudson.model.DependencyGraph; import hudson.model.Describable; import hudson.model.Descriptor; import hudson.model.Descriptor.FormException; import hudson.model.DescriptorByNameOwner; import hudson.model.DirectoryBrowserSupport; import hudson.model.Failure; import hudson.model.Fingerprint; import hudson.model.FingerprintCleanupThread; import hudson.model.FingerprintMap; import hudson.model.Hudson; import hudson.model.Item; import hudson.model.ItemGroup; import hudson.model.ItemGroupMixIn; import hudson.model.Items; import hudson.model.JDK; import hudson.model.Job; import hudson.model.JobPropertyDescriptor; import hudson.model.Label; import hudson.model.ListView; import hudson.model.LoadBalancer; import hudson.model.LoadStatistics; import hudson.model.ManagementLink; import hudson.model.Messages; import hudson.model.ModifiableViewGroup; import hudson.model.NoFingerprintMatch; import hudson.model.Node; import hudson.model.OverallLoadStatistics; import hudson.model.PaneStatusProperties; import hudson.model.Project; import hudson.model.Queue; import hudson.model.Queue.FlyweightTask; import hudson.model.RestartListener; import hudson.model.RootAction; import hudson.model.Slave; import hudson.model.TaskListener; import hudson.model.TopLevelItem; import hudson.model.TopLevelItemDescriptor; import hudson.model.UnprotectedRootAction; import hudson.model.UpdateCenter; import hudson.model.User; import hudson.model.View; import hudson.model.ViewGroupMixIn; import hudson.model.WorkspaceCleanupThread; import hudson.model.labels.LabelAtom; import hudson.model.listeners.ItemListener; import hudson.model.listeners.SCMListener; import hudson.model.listeners.SaveableListener; import hudson.remoting.Callable; import hudson.remoting.LocalChannel; import hudson.remoting.VirtualChannel; import hudson.scm.RepositoryBrowser; import hudson.scm.SCM; import hudson.search.CollectionSearchIndex; import hudson.search.SearchIndexBuilder; import hudson.search.SearchItem; import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.security.AuthorizationStrategy; import hudson.security.BasicAuthenticationFilter; import hudson.security.FederatedLoginService; import hudson.security.HudsonFilter; import hudson.security.LegacyAuthorizationStrategy; import hudson.security.LegacySecurityRealm; import hudson.security.Permission; import hudson.security.PermissionGroup; import hudson.security.PermissionScope; import hudson.security.SecurityMode; import hudson.security.SecurityRealm; import hudson.security.csrf.CrumbIssuer; import hudson.slaves.Cloud; import hudson.slaves.ComputerListener; import hudson.slaves.DumbSlave; import hudson.slaves.NodeDescriptor; import hudson.slaves.NodeList; import hudson.slaves.NodeProperty; import hudson.slaves.NodePropertyDescriptor; import hudson.slaves.NodeProvisioner; import hudson.slaves.OfflineCause; import hudson.slaves.RetentionStrategy; import hudson.tasks.BuildWrapper; import hudson.tasks.Builder; import hudson.tasks.Publisher; import hudson.triggers.SafeTimerTask; import hudson.triggers.Trigger; import hudson.triggers.TriggerDescriptor; import hudson.util.AdministrativeError; import hudson.util.CaseInsensitiveComparator; import hudson.util.ClockDifference; import hudson.util.CopyOnWriteList; import hudson.util.CopyOnWriteMap; import hudson.util.DaemonThreadFactory; import hudson.util.DescribableList; import hudson.util.FormApply; import hudson.util.FormValidation; import hudson.util.Futures; import hudson.util.HudsonIsLoading; import hudson.util.HudsonIsRestarting; import hudson.util.Iterators; import hudson.util.JenkinsReloadFailed; import hudson.util.MultipartFormDataParser; import hudson.util.NamingThreadFactory; import hudson.util.PluginServletFilter; import hudson.util.RemotingDiagnostics; import hudson.util.RemotingDiagnostics.HeapDump; import hudson.util.TextFile; import hudson.util.VersionNumber; import hudson.util.XStream2; import hudson.views.DefaultMyViewsTabBar; import hudson.views.DefaultViewsTabBar; import hudson.views.MyViewsTabBar; import hudson.views.ViewsTabBar; import hudson.widgets.Widget; import java.util.Objects; import java.util.TimerTask; import java.util.concurrent.CountDownLatch; import jenkins.ExtensionComponentSet; import jenkins.ExtensionRefreshException; import jenkins.InitReactorRunner; import jenkins.install.InstallState; import jenkins.install.SetupWizard; import jenkins.model.ProjectNamingStrategy.DefaultProjectNamingStrategy; import jenkins.security.ClassFilterImpl; import jenkins.security.ConfidentialKey; import jenkins.security.ConfidentialStore; import jenkins.security.SecurityListener; import jenkins.security.MasterToSlaveCallable; import jenkins.slaves.WorkspaceLocator; import jenkins.util.JenkinsJVM; import jenkins.util.Timer; import jenkins.util.io.FileBoolean; import jenkins.util.io.OnMaster; import jenkins.util.xml.XMLUtils; import net.jcip.annotations.GuardedBy; import net.sf.json.JSONObject; import org.acegisecurity.AccessDeniedException; import org.acegisecurity.AcegiSecurityException; import org.acegisecurity.Authentication; import org.acegisecurity.GrantedAuthority; import org.acegisecurity.GrantedAuthorityImpl; import org.acegisecurity.context.SecurityContextHolder; import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken; import org.acegisecurity.ui.AbstractProcessingFilter; import org.apache.commons.jelly.JellyException; import org.apache.commons.jelly.Script; import org.apache.commons.logging.LogFactory; import org.jvnet.hudson.reactor.Executable; import org.jvnet.hudson.reactor.Milestone; import org.jvnet.hudson.reactor.Reactor; import org.jvnet.hudson.reactor.ReactorException; import org.jvnet.hudson.reactor.ReactorListener; import org.jvnet.hudson.reactor.Task; import org.jvnet.hudson.reactor.TaskBuilder; import org.jvnet.hudson.reactor.TaskGraphBuilder; import org.jvnet.hudson.reactor.TaskGraphBuilder.Handle; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.args4j.Argument; import org.kohsuke.stapler.HttpRedirect; import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.HttpResponses; import org.kohsuke.stapler.MetaClass; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerFallback; import org.kohsuke.stapler.StaplerProxy; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.WebApp; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import org.kohsuke.stapler.framework.adjunct.AdjunctManager; import org.kohsuke.stapler.interceptor.RequirePOST; import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff; import org.kohsuke.stapler.jelly.JellyRequestDispatcher; import org.xml.sax.InputSource; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.crypto.SecretKey; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.BindException; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.Charset; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.stream.Collectors; import static hudson.Util.*; import static hudson.init.InitMilestone.*; import hudson.init.Initializer; import hudson.util.LogTaskListener; import static java.util.logging.Level.*; import javax.annotation.Nonnegative; import static javax.servlet.http.HttpServletResponse.*; import org.kohsuke.stapler.WebMethod; /** * Root object of the system. * * @author Kohsuke Kawaguchi */ @ExportedBean public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLevelItemGroup, StaplerProxy, StaplerFallback, ModifiableViewGroup, AccessControlled, DescriptorByNameOwner, ModelObjectWithContextMenu, ModelObjectWithChildren, OnMaster { private transient final Queue queue; /** * Stores various objects scoped to {@link Jenkins}. */ public transient final Lookup lookup = new Lookup(); /** * We update this field to the current version of Jenkins whenever we save {@code config.xml}. * This can be used to detect when an upgrade happens from one version to next. * * <p> * Since this field is introduced starting 1.301, "1.0" is used to represent every version * up to 1.300. This value may also include non-standard versions like "1.301-SNAPSHOT" or * "?", etc., so parsing needs to be done with a care. * * @since 1.301 */ // this field needs to be at the very top so that other components can look at this value even during unmarshalling private String version = "1.0"; /** * The Jenkins instance startup type i.e. NEW, UPGRADE etc */ private String installStateName; @Deprecated private InstallState installState; /** * If we're in the process of an initial setup, * this will be set */ private transient SetupWizard setupWizard; /** * Number of executors of the master node. */ private int numExecutors = 2; /** * Job allocation strategy. */ private Mode mode = Mode.NORMAL; /** * False to enable anyone to do anything. * Left as a field so that we can still read old data that uses this flag. * * @see #authorizationStrategy * @see #securityRealm */ private Boolean useSecurity; /** * Controls how the * <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a> * is handled in Jenkins. * <p> * This ultimately controls who has access to what. * * Never null. */ private volatile AuthorizationStrategy authorizationStrategy = AuthorizationStrategy.UNSECURED; /** * Controls a part of the * <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a> * handling in Jenkins. * <p> * Intuitively, this corresponds to the user database. * * See {@link HudsonFilter} for the concrete authentication protocol. * * Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to * update this field. * * @see #getSecurity() * @see #setSecurityRealm(SecurityRealm) */ private volatile SecurityRealm securityRealm = SecurityRealm.NO_AUTHENTICATION; /** * Disables the remember me on this computer option in the standard login screen. * * @since 1.534 */ private volatile boolean disableRememberMe; /** * The project naming strategy defines/restricts the names which can be given to a project/job. e.g. does the name have to follow a naming convention? */ private ProjectNamingStrategy projectNamingStrategy = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY; /** * Root directory for the workspaces. * This value will be variable-expanded as per {@link #expandVariablesForDirectory}. * @see #getWorkspaceFor(TopLevelItem) */ private String workspaceDir = OLD_DEFAULT_WORKSPACES_DIR; /** * Root directory for the builds. * This value will be variable-expanded as per {@link #expandVariablesForDirectory}. * @see #getBuildDirFor(Job) */ private String buildsDir = DEFAULT_BUILDS_DIR; /** * Message displayed in the top page. */ private String systemMessage; private MarkupFormatter markupFormatter; /** * Root directory of the system. */ public transient final File root; /** * Where are we in the initialization? */ private transient volatile InitMilestone initLevel = InitMilestone.STARTED; /** * All {@link Item}s keyed by their {@link Item#getName() name}s. */ /*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<>(CaseInsensitiveComparator.INSTANCE); /** * The sole instance. */ private static Jenkins theInstance; private transient volatile boolean isQuietingDown; private transient volatile boolean terminating; @GuardedBy("Jenkins.class") private transient boolean cleanUpStarted; /** * Use this to know during startup if this is a fresh one, aka first-time, startup, or a later one. * A file will be created at the very end of the Jenkins initialization process. * I.e. if the file is present, that means this is *NOT* a fresh startup. * * <code> * STARTUP_MARKER_FILE.get(); // returns false if we are on a fresh startup. True for next startups. * </code> */ private transient static FileBoolean STARTUP_MARKER_FILE; private volatile List<JDK> jdks = new ArrayList<>(); private transient volatile DependencyGraph dependencyGraph; private final transient AtomicBoolean dependencyGraphDirty = new AtomicBoolean(); /** * Currently active Views tab bar. */ private volatile ViewsTabBar viewsTabBar = new DefaultViewsTabBar(); /** * Currently active My Views tab bar. */ private volatile MyViewsTabBar myViewsTabBar = new DefaultMyViewsTabBar(); /** * All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}. */ @SuppressWarnings("rawtypes") private transient final Map<Class, ExtensionList> extensionLists = new ConcurrentHashMap<>(); /** * All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}. */ @SuppressWarnings("rawtypes") private transient final Map<Class, DescriptorExtensionList> descriptorLists = new ConcurrentHashMap<>(); /** * {@link Computer}s in this Jenkins system. Read-only. */ protected transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<>(); /** * Active {@link Cloud}s. */ public final Hudson.CloudList clouds = new Hudson.CloudList(this); public static class CloudList extends DescribableList<Cloud,Descriptor<Cloud>> { public CloudList(Jenkins h) { super(h); } public CloudList() {// needed for XStream deserialization } public Cloud getByName(String name) { for (Cloud c : this) if (c.name.equals(name)) return c; return null; } @Override protected void onModified() throws IOException { super.onModified(); Jenkins.get().trimLabels(); } } /** * Legacy store of the set of installed cluster nodes. * @deprecated in favour of {@link Nodes} */ @Deprecated protected transient volatile NodeList slaves; /** * The holder of the set of installed cluster nodes. * * @since 1.607 */ private transient final Nodes nodes = new Nodes(this); /** * Quiet period. * * This is {@link Integer} so that we can initialize it to '5' for upgrading users. */ /*package*/ Integer quietPeriod; /** * Global default for {@link AbstractProject#getScmCheckoutRetryCount()} */ /*package*/ int scmCheckoutRetryCount; /** * {@link View}s. */ private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<>(); /** * Name of the primary view. * <p> * Start with null, so that we can upgrade pre-1.269 data well. * @since 1.269 */ private volatile String primaryView; private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) { protected List<View> views() { return views; } protected String primaryView() { return primaryView; } protected void primaryView(String name) { primaryView=name; } }; private transient final FingerprintMap fingerprintMap = new FingerprintMap(); /** * Loaded plugins. */ public transient final PluginManager pluginManager; public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener; private transient final Object tcpSlaveAgentListenerLock = new Object(); private transient UDPBroadcastThread udpBroadcastThread; private transient DNSMultiCast dnsMultiCast; /** * List of registered {@link SCMListener}s. */ private transient final CopyOnWriteList<SCMListener> scmListeners = new CopyOnWriteList<>(); /** * TCP agent port. * 0 for random, -1 to disable. */ private int slaveAgentPort = getSlaveAgentPortInitialValue(0); private static int getSlaveAgentPortInitialValue(int def) { return SystemProperties.getInteger(Jenkins.class.getName()+".slaveAgentPort", def); } /** * If -Djenkins.model.Jenkins.slaveAgentPort is defined, enforce it on every start instead of only the first one. */ private static final boolean SLAVE_AGENT_PORT_ENFORCE = SystemProperties.getBoolean(Jenkins.class.getName()+".slaveAgentPortEnforce", false); /** * The TCP agent protocols that are explicitly disabled (we store the disabled ones so that newer protocols * are enabled by default). Will be {@code null} instead of empty to simplify XML format. * * @since 2.16 */ @CheckForNull private List<String> disabledAgentProtocols; /** * @deprecated Just a temporary buffer for XSTream migration code from JENKINS-39465, do not use */ @Deprecated private transient String[] _disabledAgentProtocols; /** * The TCP agent protocols that are {@link AgentProtocol#isOptIn()} and explicitly enabled. * Will be {@code null} instead of empty to simplify XML format. * * @since 2.16 */ @CheckForNull private List<String> enabledAgentProtocols; /** * @deprecated Just a temporary buffer for XSTream migration code from JENKINS-39465, do not use */ @Deprecated private transient String[] _enabledAgentProtocols; /** * The TCP agent protocols that are enabled. Built from {@link #disabledAgentProtocols} and * {@link #enabledAgentProtocols}. * * @since 2.16 * @see #setAgentProtocols(Set) * @see #getAgentProtocols() */ private transient Set<String> agentProtocols; /** * Whitespace-separated labels assigned to the master as a {@link Node}. */ private String label=""; /** * {@link hudson.security.csrf.CrumbIssuer} */ private volatile CrumbIssuer crumbIssuer; /** * All labels known to Jenkins. This allows us to reuse the same label instances * as much as possible, even though that's not a strict requirement. */ private transient final ConcurrentHashMap<String,Label> labels = new ConcurrentHashMap<>(); /** * Load statistics of the entire system. * * This includes every executor and every job in the system. */ @Exported public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics(); /** * Load statistics of the free roaming jobs and agents. * * This includes all executors on {@link hudson.model.Node.Mode#NORMAL} nodes and jobs that do not have any assigned nodes. * * @since 1.467 */ @Exported public transient final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics(); /** * {@link NodeProvisioner} that reacts to {@link #unlabeledLoad}. * @since 1.467 */ public transient final NodeProvisioner unlabeledNodeProvisioner = new NodeProvisioner(null,unlabeledLoad); /** * @deprecated as of 1.467 * Use {@link #unlabeledNodeProvisioner}. * This was broken because it was tracking all the executors in the system, but it was only tracking * free-roaming jobs in the queue. So {@link Cloud} fails to launch nodes when you have some exclusive * agents and free-roaming jobs in the queue. */ @Restricted(NoExternalUse.class) @Deprecated public transient final NodeProvisioner overallNodeProvisioner = unlabeledNodeProvisioner; public transient final ServletContext servletContext; /** * Transient action list. Useful for adding navigation items to the navigation bar * on the left. */ private transient final List<Action> actions = new CopyOnWriteArrayList<>(); /** * List of master node properties */ private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<>(this); /** * List of global properties */ private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<>(this); /** * {@link AdministrativeMonitor}s installed on this system. * * @see AdministrativeMonitor */ public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class); /** * Widgets on Jenkins. */ private transient final List<Widget> widgets = getExtensionList(Widget.class); /** * {@link AdjunctManager} */ private transient final AdjunctManager adjuncts; /** * Code that handles {@link ItemGroup} work. */ private transient final ItemGroupMixIn itemGroupMixIn = new ItemGroupMixIn(this,this) { @Override protected void add(TopLevelItem item) { items.put(item.getName(),item); } @Override protected File getRootDirFor(String name) { return Jenkins.this.getRootDirFor(name); } }; /** * Hook for a test harness to intercept Jenkins.get() * * Do not use in the production code as the signature may change. */ public interface JenkinsHolder { @CheckForNull Jenkins getInstance(); } static JenkinsHolder HOLDER = new JenkinsHolder() { public @CheckForNull Jenkins getInstance() { return theInstance; } }; /** * Gets the {@link Jenkins} singleton. * @return {@link Jenkins} instance * @throws IllegalStateException for the reasons that {@link #getInstanceOrNull} might return null * @since 2.98 */ @Nonnull public static Jenkins get() throws IllegalStateException { Jenkins instance = getInstanceOrNull(); if (instance == null) { throw new IllegalStateException("Jenkins.instance is missing. Read the documentation of Jenkins.getInstanceOrNull to see what you are doing wrong."); } return instance; } /** * @deprecated This is a verbose historical alias for {@link #get}. * @since 1.590 */ @Deprecated @Nonnull public static Jenkins getActiveInstance() throws IllegalStateException { return get(); } /** * Gets the {@link Jenkins} singleton. * {@link #get} is what you normally want. * <p>In certain rare cases you may have code that is intended to run before Jenkins starts or while Jenkins is being shut down. * For those rare cases use this method. * <p>In other cases you may have code that might end up running on a remote JVM and not on the Jenkins master. * For those cases you really should rewrite your code so that when the {@link Callable} is sent over the remoting channel * it can do whatever it needs without ever referring to {@link Jenkins}; * for example, gather any information you need on the master side before constructing the callable. * If you must do a runtime check whether you are in the master or agent, use {@link JenkinsJVM} rather than this method, * as merely loading the {@link Jenkins} class file into an agent JVM can cause linkage errors under some conditions. * @return The instance. Null if the {@link Jenkins} service has not been started, or was already shut down, * or we are running on an unrelated JVM, typically an agent. * @since 1.653 */ @CLIResolver @CheckForNull public static Jenkins getInstanceOrNull() { return HOLDER.getInstance(); } /** * @deprecated This is a historical alias for {@link #getInstanceOrNull} but with ambiguous nullability. Use {@link #get} in typical cases. */ @Nullable @Deprecated public static Jenkins getInstance() { return getInstanceOrNull(); } /** * Secret key generated once and used for a long time, beyond * container start/stop. Persisted outside {@code config.xml} to avoid * accidental exposure. */ private transient final String secretKey; private transient final UpdateCenter updateCenter = UpdateCenter.createUpdateCenter(null); /** * True if the user opted out from the statistics tracking. We'll never send anything if this is true. */ private Boolean noUsageStatistics; /** * HTTP proxy configuration. */ public transient volatile ProxyConfiguration proxy; /** * Bound to "/log". */ private transient final LogRecorderManager log = new LogRecorderManager(); private transient final boolean oldJenkinsJVM; protected Jenkins(File root, ServletContext context) throws IOException, InterruptedException, ReactorException { this(root, context, null); } /** * @param pluginManager * If non-null, use existing plugin manager. create a new one. */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({ "SC_START_IN_CTOR", // bug in FindBugs. It flags UDPBroadcastThread.start() call but that's for another class "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" // Trigger.timer }) protected Jenkins(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException { oldJenkinsJVM = JenkinsJVM.isJenkinsJVM(); // capture to restore in cleanUp() JenkinsJVMAccess._setJenkinsJVM(true); // set it for unit tests as they will not have gone through WebAppMain long start = System.currentTimeMillis(); STARTUP_MARKER_FILE = new FileBoolean(new File(root, ".lastStarted")); // As Jenkins is starting, grant this process full control ACL.impersonate(ACL.SYSTEM); try { this.root = root; this.servletContext = context; computeVersion(context); if(theInstance!=null) throw new IllegalStateException("second instance"); theInstance = this; if (!new File(root,"jobs").exists()) { // if this is a fresh install, use more modern default layout that's consistent with agents workspaceDir = DEFAULT_WORKSPACES_DIR; } // doing this early allows InitStrategy to set environment upfront //Telemetry: add interceptor classloader //These lines allow the catcher to be present on Thread.currentThread().getContextClassLoader() in every plugin which //allow us to detect failures in every plugin loading classes by this way. if (MissingClassTelemetry.enabled() && !(Thread.currentThread().getContextClassLoader() instanceof CatcherClassLoader)) { Thread.currentThread().setContextClassLoader(new CatcherClassLoader(Thread.currentThread().getContextClassLoader())); } final InitStrategy is = InitStrategy.get(Thread.currentThread().getContextClassLoader()); Trigger.timer = new java.util.Timer("Jenkins cron thread"); queue = new Queue(LoadBalancer.CONSISTENT_HASH); try { dependencyGraph = DependencyGraph.EMPTY; } catch (InternalError e) { if(e.getMessage().contains("window server")) { throw new Error("Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option",e); } throw e; } // get or create the secret TextFile secretFile = new TextFile(new File(getRootDir(),"secret.key")); if(secretFile.exists()) { secretKey = secretFile.readTrim(); } else { SecureRandom sr = new SecureRandom(); byte[] random = new byte[32]; sr.nextBytes(random); secretKey = Util.toHexString(random); secretFile.write(secretKey); // this marker indicates that the secret.key is generated by the version of Jenkins post SECURITY-49. // this indicates that there's no need to rewrite secrets on disk new FileBoolean(new File(root,"secret.key.not-so-secret")).on(); } try { proxy = ProxyConfiguration.load(); } catch (IOException e) { LOGGER.log(SEVERE, "Failed to load proxy configuration", e); } if (pluginManager==null) pluginManager = PluginManager.createDefault(this); this.pluginManager = pluginManager; WebApp webApp = WebApp.get(servletContext); //Telemetry: add interceptor classloader //These lines allows the catcher to be present on Thread.currentThread().getContextClassLoader() in every plugin which //allow us to detect failures in every plugin loading classes by this way. // JSON binding needs to be able to see all the classes from all the plugins ClassLoader classLoaderToAssign; if (MissingClassTelemetry.enabled() && !(pluginManager.uberClassLoader instanceof CatcherClassLoader)) { classLoaderToAssign = new CatcherClassLoader(pluginManager.uberClassLoader); } else { classLoaderToAssign = pluginManager.uberClassLoader; } webApp.setClassLoader(classLoaderToAssign); webApp.setJsonInErrorMessageSanitizer(RedactSecretJsonInErrorMessageSanitizer.INSTANCE); TypedFilter typedFilter = new TypedFilter(); webApp.setFilterForGetMethods(typedFilter); webApp.setFilterForFields(typedFilter); webApp.setFilterForDoActions(new DoActionFilter()); StaplerFilteredActionListener actionListener = new StaplerFilteredActionListener(); webApp.setFilteredGetterTriggerListener(actionListener); webApp.setFilteredDoActionTriggerListener(actionListener); webApp.setFilteredFieldTriggerListener(actionListener); //Telemetry: add interceptor classloader //These lines allows the catcher to be present on Thread.currentThread().getContextClassLoader() in every plugin which //allow us to detect failures in every plugin loading classes at this way. adjuncts = new AdjunctManager(servletContext, classLoaderToAssign, "adjuncts/" + SESSION_HASH, TimeUnit.DAYS.toMillis(365)); ClassFilterImpl.register(); // initialization consists of ... executeReactor( is, pluginManager.initTasks(is), // loading and preparing plugins loadTasks(), // load jobs InitMilestone.ordering() // forced ordering among key milestones ); // Ensure we reached the final initialization state. Log the error otherwise if (initLevel != InitMilestone.COMPLETED) { LOGGER.log(SEVERE, "Jenkins initialization has not reached the COMPLETED initialization milestone after the startup. " + "Current state: {0}. " + "It may cause undefined incorrect behavior in Jenkins plugin relying on this state. " + "It is likely an issue with the Initialization task graph. " + "Example: usage of @Initializer(after = InitMilestone.COMPLETED) in a plugin (JENKINS-37759). " + "Please create a bug in Jenkins bugtracker. ", initLevel); } if(KILL_AFTER_LOAD) // TODO cleanUp? System.exit(0); save(); launchTcpSlaveAgentListener(); if (UDPBroadcastThread.PORT != -1) { try { udpBroadcastThread = new UDPBroadcastThread(this); udpBroadcastThread.start(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to broadcast over UDP (use -Dhudson.udp=-1 to disable)", e); } } dnsMultiCast = new DNSMultiCast(this); Timer.get().scheduleAtFixedRate(new SafeTimerTask() { @Override protected void doRun() throws Exception { trimLabels(); } }, TimeUnit.MINUTES.toMillis(5), TimeUnit.MINUTES.toMillis(5), TimeUnit.MILLISECONDS); updateComputerList(); {// master is online now, it's instance must always exist final Computer c = toComputer(); if(c != null) { for (ComputerListener cl : ComputerListener.all()) { try { cl.onOnline(c, new LogTaskListener(LOGGER, INFO)); } catch (Exception e) { // Per Javadoc log exceptions but still go online. // NOTE: this does not include Errors, which indicate a fatal problem LOGGER.log(WARNING, String.format("Exception in onOnline() for the computer listener %s on the Jenkins master node", cl.getClass()), e); } } } } for (ItemListener l : ItemListener.all()) { long itemListenerStart = System.currentTimeMillis(); try { l.onLoaded(); } catch (RuntimeException x) { LOGGER.log(Level.WARNING, null, x); } if (LOG_STARTUP_PERFORMANCE) LOGGER.info(String.format("Took %dms for item listener %s startup", System.currentTimeMillis()-itemListenerStart,l.getClass().getName())); } if (LOG_STARTUP_PERFORMANCE) LOGGER.info(String.format("Took %dms for complete Jenkins startup", System.currentTimeMillis()-start)); STARTUP_MARKER_FILE.on(); } finally { SecurityContextHolder.clearContext(); } } /** * Maintains backwards compatibility. Invoked by XStream when this object is de-serialized. */ @SuppressWarnings({"unused"}) private Object readResolve() { if (jdks == null) { jdks = new ArrayList<>(); } if (SLAVE_AGENT_PORT_ENFORCE) { slaveAgentPort = getSlaveAgentPortInitialValue(slaveAgentPort); } if (disabledAgentProtocols == null && _disabledAgentProtocols != null) { disabledAgentProtocols = Arrays.asList(_disabledAgentProtocols); _disabledAgentProtocols = null; } if (enabledAgentProtocols == null && _enabledAgentProtocols != null) { enabledAgentProtocols = Arrays.asList(_enabledAgentProtocols); _enabledAgentProtocols = null; } // Invalidate the protocols cache after the reload agentProtocols = null; return this; } /** * Get the Jenkins {@link jenkins.install.InstallState install state}. * @return The Jenkins {@link jenkins.install.InstallState install state}. */ @Nonnull public InstallState getInstallState() { if (installState != null) { installStateName = installState.name(); installState = null; } InstallState is = installStateName != null ? InstallState.valueOf(installStateName) : InstallState.UNKNOWN; return is != null ? is : InstallState.UNKNOWN; } /** * Update the current install state. This will invoke state.initializeState() * when the state has been transitioned. */ public void setInstallState(@Nonnull InstallState newState) { String prior = installStateName; installStateName = newState.name(); LOGGER.log(Main.isDevelopmentMode ? Level.INFO : Level.FINE, "Install state transitioning from: {0} to : {1}", new Object[] { prior, installStateName }); if (!installStateName.equals(prior)) { getSetupWizard().onInstallStateUpdate(newState); newState.initializeState(); } saveQuietly(); } /** * Executes a reactor. * * @param is * If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Jenkins. */ private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException { Reactor reactor = new Reactor(builders) { /** * Sets the thread name to the task for better diagnostics. */ @Override protected void runTask(Task task) throws Exception { if (is!=null && is.skipInitTask(task)) return; ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread String taskName = InitReactorRunner.getDisplayName(task); Thread t = Thread.currentThread(); String name = t.getName(); if (taskName !=null) t.setName(taskName); try { long start = System.currentTimeMillis(); super.runTask(task); if(LOG_STARTUP_PERFORMANCE) LOGGER.info(String.format("Took %dms for %s by %s", System.currentTimeMillis()-start, taskName, name)); } catch (Exception | Error x) { if (containsLinkageError(x)) { LOGGER.log(Level.WARNING, taskName + " failed perhaps due to plugin dependency issues", x); } else { throw x; } } finally { t.setName(name); SecurityContextHolder.clearContext(); } } private boolean containsLinkageError(Throwable x) { if (x instanceof LinkageError) { return true; } Throwable x2 = x.getCause(); return x2 != null && containsLinkageError(x2); } }; new InitReactorRunner() { @Override protected void onInitMilestoneAttained(InitMilestone milestone) { initLevel = milestone; if (milestone==PLUGINS_PREPARED) { // set up Guice to enable injection as early as possible // before this milestone, ExtensionList.ensureLoaded() won't actually try to locate instances ExtensionList.lookup(ExtensionFinder.class).getComponents(); } } }.run(reactor); } public TcpSlaveAgentListener getTcpSlaveAgentListener() { return tcpSlaveAgentListener; } /** * Makes {@link AdjunctManager} URL-bound. * The dummy parameter allows us to use different URLs for the same adjunct, * for proper cache handling. */ public AdjunctManager getAdjuncts(String dummy) { return adjuncts; } @Exported public int getSlaveAgentPort() { return slaveAgentPort; } /** * @since 2.24 */ public boolean isSlaveAgentPortEnforced() { return Jenkins.SLAVE_AGENT_PORT_ENFORCE; } /** * @param port * 0 to indicate random available TCP port. -1 to disable this service. */ public void setSlaveAgentPort(int port) throws IOException { if (SLAVE_AGENT_PORT_ENFORCE) { LOGGER.log(Level.WARNING, "setSlaveAgentPort({0}) call ignored because system property {1} is true", new String[] { Integer.toString(port), Jenkins.class.getName()+".slaveAgentPortEnforce" }); } else { forceSetSlaveAgentPort(port); } } private void forceSetSlaveAgentPort(int port) throws IOException { this.slaveAgentPort = port; launchTcpSlaveAgentListener(); } /** * Returns the enabled agent protocols. * * @return the enabled agent protocols. * @since 2.16 */ public Set<String> getAgentProtocols() { if (agentProtocols == null) { // idempotent, so don't care if we do this concurrently, should all get same result Set<String> result = new TreeSet<>(); Set<String> disabled = new TreeSet<>(); for (String p : Util.fixNull(disabledAgentProtocols)) { disabled.add(p.trim()); } Set<String> enabled = new TreeSet<>(); for (String p : Util.fixNull(enabledAgentProtocols)) { enabled.add(p.trim()); } for (AgentProtocol p : AgentProtocol.all()) { String name = p.getName(); if (name != null && (p.isRequired() || (!disabled.contains(name) && (!p.isOptIn() || enabled.contains(name))))) { result.add(name); } } agentProtocols = result; return result; } return agentProtocols; } /** * Sets the enabled agent protocols. * * @param protocols the enabled agent protocols. * @since 2.16 */ public void setAgentProtocols(Set<String> protocols) { Set<String> disabled = new TreeSet<>(); Set<String> enabled = new TreeSet<>(); for (AgentProtocol p : AgentProtocol.all()) { String name = p.getName(); if (name != null && !p.isRequired()) { // we want to record the protocols where the admin has made a conscious decision // thus, if a protocol is opt-in, we record the admin enabling it // if a protocol is opt-out, we record the admin disabling it // We should not transition rapidly from opt-in -> opt-out -> opt-in // the scenario we want to have work is: // 1. We introduce a new protocol, it starts off as opt-in. Some admins decide to test and opt-in // 2. We decide that the protocol is ready for general use. It gets marked as opt-out. Any admins // that took part in early testing now have their config switched to not mention the new protocol // at all when they save their config as the protocol is now opt-out. Any admins that want to // disable it can do so and will have their preference recorded. // 3. We decide that the protocol needs to be retired. It gets switched back to opt-in. At this point // the initial opt-in admins, assuming they visited an upgrade to a master with step 2, will // have the protocol disabled for them. This is what we want. If they didn't upgrade to a master // with step 2, well there is not much we can do to differentiate them from somebody who is upgrading // from a previous step 3 master and had needed to keep the protocol turned on. // // What we should never do is flip-flop: opt-in -> opt-out -> opt-in -> opt-out as that will basically // clear any preference that an admin has set, but this should be ok as we only ever will be // adding new protocols and retiring old ones. if (p.isOptIn()) { if (protocols.contains(name)) { enabled.add(name); } } else { if (!protocols.contains(name)) { disabled.add(name); } } } } disabledAgentProtocols = disabled.isEmpty() ? null : new ArrayList<>(disabled); enabledAgentProtocols = enabled.isEmpty() ? null : new ArrayList<>(enabled); agentProtocols = null; } private void launchTcpSlaveAgentListener() throws IOException { synchronized(tcpSlaveAgentListenerLock) { // shutdown previous agent if the port has changed if (tcpSlaveAgentListener != null && tcpSlaveAgentListener.configuredPort != slaveAgentPort) { tcpSlaveAgentListener.shutdown(); tcpSlaveAgentListener = null; } if (slaveAgentPort != -1 && tcpSlaveAgentListener == null) { final String administrativeMonitorId = getClass().getName() + ".tcpBind"; try { tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); // remove previous monitor in case of previous error AdministrativeMonitor toBeRemoved = null; ExtensionList<AdministrativeMonitor> all = AdministrativeMonitor.all(); for (AdministrativeMonitor am : all) { if (administrativeMonitorId.equals(am.id)) { toBeRemoved = am; break; } } all.remove(toBeRemoved); } catch (BindException e) { LOGGER.log(Level.WARNING, String.format("Failed to listen to incoming agent connections through port %s. Change the port number", slaveAgentPort), e); new AdministrativeError(administrativeMonitorId, "Failed to listen to incoming agent connections", "Failed to listen to incoming agent connections. <a href='configureSecurity'>Change the inbound TCP port number</a> to solve the problem.", e); } } } } @Extension @Restricted(NoExternalUse.class) public static class EnforceSlaveAgentPortAdministrativeMonitor extends AdministrativeMonitor { @Inject Jenkins j; @Override public String getDisplayName() { return jenkins.model.Messages.EnforceSlaveAgentPortAdministrativeMonitor_displayName(); } public String getSystemPropertyName() { return Jenkins.class.getName() + ".slaveAgentPort"; } public int getExpectedPort() { int slaveAgentPort = j.slaveAgentPort; return Jenkins.getSlaveAgentPortInitialValue(slaveAgentPort); } @RequirePOST public void doAct(StaplerRequest req, StaplerResponse rsp) throws IOException { j.forceSetSlaveAgentPort(getExpectedPort()); rsp.sendRedirect2(req.getContextPath() + "/manage"); } @Override public boolean isActivated() { int slaveAgentPort = Jenkins.get().slaveAgentPort; return SLAVE_AGENT_PORT_ENFORCE && slaveAgentPort != Jenkins.getSlaveAgentPortInitialValue(slaveAgentPort); } } public void setNodeName(String name) { throw new UnsupportedOperationException(); // not allowed } public String getNodeDescription() { return Messages.Hudson_NodeDescription(); } @Exported public String getDescription() { return systemMessage; } @Nonnull public PluginManager getPluginManager() { return pluginManager; } public UpdateCenter getUpdateCenter() { return updateCenter; } public boolean isUsageStatisticsCollected() { return noUsageStatistics==null || !noUsageStatistics; } public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException { this.noUsageStatistics = noUsageStatistics; save(); } public View.People getPeople() { return new View.People(this); } /** * @since 1.484 */ public View.AsynchPeople getAsynchPeople() { return new View.AsynchPeople(this); } /** * Does this {@link View} has any associated user information recorded? * @deprecated Potentially very expensive call; do not use from Jelly views. */ @Deprecated public boolean hasPeople() { return View.People.isApplicable(items.values()); } public Api getApi() { return new Api(this); } /** * Returns a secret key that survives across container start/stop. * <p> * This value is useful for implementing some of the security features. * * @deprecated * Due to the past security advisory, this value should not be used any more to protect sensitive information. * See {@link ConfidentialStore} and {@link ConfidentialKey} for how to store secrets. */ @Deprecated public String getSecretKey() { return secretKey; } /** * Gets {@linkplain #getSecretKey() the secret key} as a key for AES-128. * @since 1.308 * @deprecated * See {@link #getSecretKey()}. */ @Deprecated public SecretKey getSecretKeyAsAES128() { return Util.toAes128Key(secretKey); } /** * Returns the unique identifier of this Jenkins that has been historically used to identify * this Jenkins to the outside world. * * <p> * This form of identifier is weak in that it can be impersonated by others. See * https://wiki.jenkins-ci.org/display/JENKINS/Instance+Identity for more modern form of instance ID * that can be challenged and verified. * * @since 1.498 */ @SuppressWarnings("deprecation") public String getLegacyInstanceId() { return Util.getDigestOf(getSecretKey()); } /** * Gets the SCM descriptor by name. Primarily used for making them web-visible. */ public Descriptor<SCM> getScm(String shortClassName) { return findDescriptor(shortClassName, SCM.all()); } /** * Gets the repository browser descriptor by name. Primarily used for making them web-visible. */ public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) { return findDescriptor(shortClassName,RepositoryBrowser.all()); } /** * Gets the builder descriptor by name. Primarily used for making them web-visible. */ public Descriptor<Builder> getBuilder(String shortClassName) { return findDescriptor(shortClassName, Builder.all()); } /** * Gets the build wrapper descriptor by name. Primarily used for making them web-visible. */ public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) { return findDescriptor(shortClassName, BuildWrapper.all()); } /** * Gets the publisher descriptor by name. Primarily used for making them web-visible. */ public Descriptor<Publisher> getPublisher(String shortClassName) { return findDescriptor(shortClassName, Publisher.all()); } /** * Gets the trigger descriptor by name. Primarily used for making them web-visible. */ public TriggerDescriptor getTrigger(String shortClassName) { return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all()); } /** * Gets the retention strategy descriptor by name. Primarily used for making them web-visible. */ public Descriptor<RetentionStrategy<?>> getRetentionStrategy(String shortClassName) { return findDescriptor(shortClassName, RetentionStrategy.all()); } /** * Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible. */ public JobPropertyDescriptor getJobProperty(String shortClassName) { // combining these two lines triggers javac bug. See issue #610. Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all()); return (JobPropertyDescriptor) d; } /** * @deprecated * UI method. Not meant to be used programmatically. */ @Deprecated public ComputerSet getComputer() { return new ComputerSet(); } /** * Exposes {@link Descriptor} by its name to URL. * * After doing all the {@code getXXX(shortClassName)} methods, I finally realized that * this just doesn't scale. * * @param id * Either {@link Descriptor#getId()} (recommended) or the short name of a {@link Describable} subtype (for compatibility) * @throws IllegalArgumentException if a short name was passed which matches multiple IDs (fail fast) */ @SuppressWarnings({"unchecked", "rawtypes"}) // too late to fix public Descriptor getDescriptor(String id) { // legacy descriptors that are registered manually doesn't show up in getExtensionList, so check them explicitly. Iterable<Descriptor> descriptors = Iterators.sequence(getExtensionList(Descriptor.class), DescriptorExtensionList.listLegacyInstances()); for (Descriptor d : descriptors) { if (d.getId().equals(id)) { return d; } } Descriptor candidate = null; for (Descriptor d : descriptors) { String name = d.getId(); if (name.substring(name.lastIndexOf('.') + 1).equals(id)) { if (candidate == null) { candidate = d; } else { throw new IllegalArgumentException(id + " is ambiguous; matches both " + name + " and " + candidate.getId()); } } } return candidate; } /** * Alias for {@link #getDescriptor(String)}. */ public Descriptor getDescriptorByName(String id) { return getDescriptor(id); } /** * Gets the {@link Descriptor} that corresponds to the given {@link Describable} type. * <p> * If you have an instance of {@code type} and call {@link Describable#getDescriptor()}, * you'll get the same instance that this method returns. */ @CheckForNull public Descriptor getDescriptor(Class<? extends Describable> type) { for( Descriptor d : getExtensionList(Descriptor.class) ) if(d.clazz==type) return d; return null; } /** * Works just like {@link #getDescriptor(Class)} but don't take no for an answer. * * @throws AssertionError * If the descriptor is missing. * @since 1.326 */ @Nonnull public Descriptor getDescriptorOrDie(Class<? extends Describable> type) { Descriptor d = getDescriptor(type); if (d==null) throw new AssertionError(type+" is missing its descriptor"); return d; } /** * Gets the {@link Descriptor} instance in the current Jenkins by its type. */ public <T extends Descriptor> T getDescriptorByType(Class<T> type) { for( Descriptor d : getExtensionList(Descriptor.class) ) if(d.getClass()==type) return type.cast(d); return null; } /** * Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible. */ public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) { return findDescriptor(shortClassName, SecurityRealm.all()); } /** * Finds a descriptor that has the specified name. */ private <T extends Describable<T>> Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) { String name = '.'+shortClassName; for (Descriptor<T> d : descriptors) { if(d.clazz.getName().endsWith(name)) return d; } return null; } protected void updateComputerList() { updateComputerList(AUTOMATIC_SLAVE_LAUNCH); } /** @deprecated Use {@link SCMListener#all} instead. */ @Deprecated public CopyOnWriteList<SCMListener> getSCMListeners() { return scmListeners; } /** * Gets the plugin object from its short name. * This allows URL {@code hudson/plugin/ID} to be served by the views * of the plugin class. * @param shortName Short name of the plugin * @return The plugin singleton or {@code null} if for some reason the plugin is not loaded. * The fact the plugin is loaded does not mean it is enabled and fully initialized for the current Jenkins session. * Use {@link Plugin#getWrapper()} and then {@link PluginWrapper#isActive()} to check it. */ @CheckForNull public Plugin getPlugin(String shortName) { PluginWrapper p = pluginManager.getPlugin(shortName); if(p==null) return null; return p.getPlugin(); } /** * Gets the plugin object from its class. * * <p> * This allows easy storage of plugin information in the plugin singleton without * every plugin reimplementing the singleton pattern. * * @param <P> Class of the plugin * @param clazz The plugin class (beware class-loader fun, this will probably only work * from within the jpi that defines the plugin class, it may or may not work in other cases) * @return The plugin singleton or {@code null} if for some reason the plugin is not loaded. * The fact the plugin is loaded does not mean it is enabled and fully initialized for the current Jenkins session. * Use {@link Plugin#getWrapper()} and then {@link PluginWrapper#isActive()} to check it. */ @SuppressWarnings("unchecked") @CheckForNull public <P extends Plugin> P getPlugin(Class<P> clazz) { PluginWrapper p = pluginManager.getPlugin(clazz); if(p==null) return null; return (P) p.getPlugin(); } /** * Gets the plugin objects from their super-class. * * @param clazz The plugin class (beware class-loader fun) * * @return The plugin instances. */ public <P extends Plugin> List<P> getPlugins(Class<P> clazz) { List<P> result = new ArrayList<>(); for (PluginWrapper w: pluginManager.getPlugins(clazz)) { result.add((P)w.getPlugin()); } return Collections.unmodifiableList(result); } /** * Synonym for {@link #getDescription}. */ public String getSystemMessage() { return systemMessage; } /** * Gets the markup formatter used in the system. * * @return * never null. * @since 1.391 */ public @Nonnull MarkupFormatter getMarkupFormatter() { MarkupFormatter f = markupFormatter; return f != null ? f : new EscapedMarkupFormatter(); } /** * Sets the markup formatter used in the system globally. * * @since 1.391 */ public void setMarkupFormatter(MarkupFormatter f) { this.markupFormatter = f; } /** * Sets the system message. */ public void setSystemMessage(String message) throws IOException { this.systemMessage = message; save(); } @StaplerDispatchable public FederatedLoginService getFederatedLoginService(String name) { for (FederatedLoginService fls : FederatedLoginService.all()) { if (fls.getUrlName().equals(name)) return fls; } return null; } public List<FederatedLoginService> getFederatedLoginServices() { return FederatedLoginService.all(); } public Launcher createLauncher(TaskListener listener) { return new LocalLauncher(listener).decorateFor(this); } public String getFullName() { return ""; } public String getFullDisplayName() { return ""; } /** * Returns the transient {@link Action}s associated with the top page. * * <p> * Adding {@link Action} is primarily useful for plugins to contribute * an item to the navigation bar of the top page. See existing {@link Action} * implementation for it affects the GUI. * * <p> * To register an {@link Action}, implement {@link RootAction} extension point, or write code like * {@code Jenkins.get().getActions().add(...)}. * * @return * Live list where the changes can be made. Can be empty but never null. * @since 1.172 */ public List<Action> getActions() { return actions; } /** * Gets just the immediate children of {@link Jenkins}. * * @see #getAllItems(Class) */ @Exported(name="jobs") public List<TopLevelItem> getItems() { List<TopLevelItem> viewableItems = new ArrayList<>(); for (TopLevelItem item : items.values()) { if (item.hasPermission(Item.READ)) viewableItems.add(item); } return viewableItems; } /** * Returns the read-only view of all the {@link TopLevelItem}s keyed by their names. * <p> * This method is efficient, as it doesn't involve any copying. * * @since 1.296 */ public Map<String,TopLevelItem> getItemMap() { return Collections.unmodifiableMap(items); } /** * Gets just the immediate children of {@link Jenkins} but of the given type. */ public <T> List<T> getItems(Class<T> type) { List<T> r = new ArrayList<>(); for (TopLevelItem i : getItems()) if (type.isInstance(i)) r.add(type.cast(i)); return r; } /** * Gets a list of simple top-level projects. * @deprecated This method will ignore Maven and matrix projects, as well as projects inside containers such as folders. * You may prefer to call {@link #getAllItems(Class)} on {@link AbstractProject}, * perhaps also using {@link Util#createSubList} to consider only {@link TopLevelItem}s. * (That will also consider the caller's permissions.) * If you really want to get just {@link Project}s at top level, ignoring permissions, * you can filter the values from {@link #getItemMap} using {@link Util#createSubList}. */ @Deprecated public List<Project> getProjects() { return Util.createSubList(items.values(), Project.class); } /** * Gets the names of all the {@link Job}s. */ public Collection<String> getJobNames() { List<String> names = new ArrayList<>(); for (Job j : allItems(Job.class)) names.add(j.getFullName()); names.sort(String.CASE_INSENSITIVE_ORDER); return names; } public List<Action> getViewActions() { return getActions(); } /** * Gets the names of all the {@link TopLevelItem}s. */ public Collection<String> getTopLevelItemNames() { List<String> names = new ArrayList<>(); for (TopLevelItem j : items.values()) names.add(j.getName()); return names; } /** * Gets a view by the specified name. * The method iterates through {@link hudson.model.ViewGroup}s if required. * @param name Name of the view * @return View instance or {@code null} if it is missing */ @CheckForNull public View getView(@CheckForNull String name) { return viewGroupMixIn.getView(name); } /** * Gets the read-only list of all {@link View}s. */ @Exported public Collection<View> getViews() { return viewGroupMixIn.getViews(); } @Override public void addView(View v) throws IOException { viewGroupMixIn.addView(v); } /** * Completely replaces views. * * <p> * This operation is NOT provided as an atomic operation, but rather * the sole purpose of this is to define a setter for this to help * introspecting code, such as system-config-dsl plugin */ // even if we want to offer this atomic operation, CopyOnWriteArrayList // offers no such operation public void setViews(Collection<View> views) throws IOException { BulkChange bc = new BulkChange(this); try { this.views.clear(); for (View v : views) { addView(v); } } finally { bc.commit(); } } public boolean canDelete(View view) { return viewGroupMixIn.canDelete(view); } public synchronized void deleteView(View view) throws IOException { viewGroupMixIn.deleteView(view); } public void onViewRenamed(View view, String oldName, String newName) { viewGroupMixIn.onViewRenamed(view, oldName, newName); } /** * Returns the primary {@link View} that renders the top-page of Jenkins. */ @Exported public View getPrimaryView() { return viewGroupMixIn.getPrimaryView(); } public void setPrimaryView(@Nonnull View v) { this.primaryView = v.getViewName(); } public ViewsTabBar getViewsTabBar() { return viewsTabBar; } public void setViewsTabBar(ViewsTabBar viewsTabBar) { this.viewsTabBar = viewsTabBar; } public Jenkins getItemGroup() { return this; } public MyViewsTabBar getMyViewsTabBar() { return myViewsTabBar; } public void setMyViewsTabBar(MyViewsTabBar myViewsTabBar) { this.myViewsTabBar = myViewsTabBar; } /** * Returns true if the current running Jenkins is upgraded from a version earlier than the specified version. * * <p> * This method continues to return true until the system configuration is saved, at which point * {@link #version} will be overwritten and Jenkins forgets the upgrade history. * * <p> * To handle SNAPSHOTS correctly, pass in "1.N.*" to test if it's upgrading from the version * equal or younger than N. So say if you implement a feature in 1.301 and you want to check * if the installation upgraded from pre-1.301, pass in "1.300.*" * * @since 1.301 */ public boolean isUpgradedFromBefore(VersionNumber v) { try { return new VersionNumber(version).isOlderThan(v); } catch (IllegalArgumentException e) { // fail to parse this version number return false; } } /** * Gets the read-only list of all {@link Computer}s. */ public Computer[] getComputers() { Computer[] r = computers.values().toArray(new Computer[0]); Arrays.sort(r,new Comparator<Computer>() { @Override public int compare(Computer lhs, Computer rhs) { if(lhs.getNode()==Jenkins.this) return -1; if(rhs.getNode()==Jenkins.this) return 1; return lhs.getName().compareTo(rhs.getName()); } }); return r; } @CLIResolver public @CheckForNull Computer getComputer(@Argument(required=true,metaVar="NAME",usage="Node name") @Nonnull String name) { if(name.equals("(master)")) name = ""; for (Computer c : computers.values()) { if(c.getName().equals(name)) return c; } return null; } /** * Gets the label that exists on this system by the name. * * @return null if name is null. * @see Label#parseExpression(String) (String) */ public Label getLabel(String expr) { if(expr==null) return null; expr = hudson.util.QuotedStringTokenizer.unquote(expr); while(true) { Label l = labels.get(expr); if(l!=null) return l; // non-existent try { labels.putIfAbsent(expr,Label.parseExpression(expr)); } catch (ANTLRException e) { // laxly accept it as a single label atom for backward compatibility return getLabelAtom(expr); } } } /** * Returns the label atom of the given name. * @return non-null iff name is non-null */ public @Nullable LabelAtom getLabelAtom(@CheckForNull String name) { if (name==null) return null; while(true) { Label l = labels.get(name); if(l!=null) return (LabelAtom)l; // non-existent LabelAtom la = new LabelAtom(name); if (labels.putIfAbsent(name, la)==null) la.load(); } } /** * Gets all the active labels in the current system. */ public Set<Label> getLabels() { Set<Label> r = new TreeSet<>(); for (Label l : labels.values()) { if(!l.isEmpty()) r.add(l); } return r; } public Set<LabelAtom> getLabelAtoms() { Set<LabelAtom> r = new TreeSet<>(); for (Label l : labels.values()) { if(!l.isEmpty() && l instanceof LabelAtom) r.add((LabelAtom)l); } return r; } public Queue getQueue() { return queue; } @Override public String getDisplayName() { return Messages.Hudson_DisplayName(); } public List<JDK> getJDKs() { return jdks; } /** * Replaces all JDK installations with those from the given collection. * * Use {@link hudson.model.JDK.DescriptorImpl#setInstallations(JDK...)} to * set JDK installations from external code. */ @Restricted(NoExternalUse.class) public void setJDKs(Collection<? extends JDK> jdks) { this.jdks = new ArrayList<>(jdks); } /** * Gets the JDK installation of the given name, or returns null. */ public JDK getJDK(String name) { if(name==null) { // if only one JDK is configured, "default JDK" should mean that JDK. List<JDK> jdks = getJDKs(); if(jdks.size()==1) return jdks.get(0); return null; } for (JDK j : getJDKs()) { if(j.getName().equals(name)) return j; } return null; } /** * Gets the agent node of the give name, hooked under this Jenkins. */ public @CheckForNull Node getNode(String name) { return nodes.getNode(name); } /** * Gets a {@link Cloud} by {@link Cloud#name its name}, or null. */ public Cloud getCloud(String name) { return clouds.getByName(name); } protected Map<Node,Computer> getComputerMap() { return computers; } /** * Returns all {@link Node}s in the system, excluding {@link Jenkins} instance itself which * represents the master. */ public List<Node> getNodes() { return nodes.getNodes(); } /** * Get the {@link Nodes} object that handles maintaining individual {@link Node}s. * @return The Nodes object. */ @Restricted(NoExternalUse.class) public Nodes getNodesObject() { // TODO replace this with something better when we properly expose Nodes. return nodes; } /** * Adds one more {@link Node} to Jenkins. * If a node of the same name already exists then that node will be replaced. */ public void addNode(Node n) throws IOException { nodes.addNode(n); } /** * Removes a {@link Node} from Jenkins. */ public void removeNode(@Nonnull Node n) throws IOException { nodes.removeNode(n); } /** * Saves an existing {@link Node} on disk, called by {@link Node#save()}. This method is preferred in those cases * where you need to determine atomically that the node being saved is actually in the list of nodes. * * @param n the node to be updated. * @return {@code true}, if the node was updated. {@code false}, if the node was not in the list of nodes. * @throws IOException if the node could not be persisted. * @see Nodes#updateNode * @since 1.634 */ public boolean updateNode(Node n) throws IOException { return nodes.updateNode(n); } public void setNodes(final List<? extends Node> n) throws IOException { nodes.setNodes(n); } public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() { return nodeProperties; } public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getGlobalNodeProperties() { return globalNodeProperties; } /** * Resets all labels and remove invalid ones. * * This should be called when the assumptions behind label cache computation changes, * but we also call this periodically to self-heal any data out-of-sync issue. */ /*package*/ void trimLabels() { for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) { Label l = itr.next(); resetLabel(l); if(l.isEmpty()) itr.remove(); } } /** * Binds {@link AdministrativeMonitor}s to URL. * @param id Monitor ID * @return The requested monitor or {@code null} if it does not exist */ @CheckForNull public AdministrativeMonitor getAdministrativeMonitor(String id) { for (AdministrativeMonitor m : administrativeMonitors) if(m.id.equals(id)) return m; return null; } /** * Returns the enabled and activated administrative monitors. * @since 2.64 */ public List<AdministrativeMonitor> getActiveAdministrativeMonitors() { return administrativeMonitors.stream().filter(m -> m.isEnabled() && m.isActivated()).collect(Collectors.toList()); } public NodeDescriptor getDescriptor() { return DescriptorImpl.INSTANCE; } public static final class DescriptorImpl extends NodeDescriptor { @Extension public static final DescriptorImpl INSTANCE = new DescriptorImpl(); @Override public boolean isInstantiable() { return false; } public FormValidation doCheckNumExecutors(@QueryParameter String value) { return FormValidation.validateNonNegativeInteger(value); } // to route /descriptor/FQCN/xxx to getDescriptor(FQCN).xxx public Object getDynamic(String token) { return Jenkins.get().getDescriptor(token); } } /** * Gets the system default quiet period. */ public int getQuietPeriod() { return quietPeriod!=null ? quietPeriod : 5; } /** * Sets the global quiet period. * * @param quietPeriod * null to the default value. */ public void setQuietPeriod(Integer quietPeriod) throws IOException { this.quietPeriod = quietPeriod; save(); } /** * Gets the global SCM check out retry count. */ public int getScmCheckoutRetryCount() { return scmCheckoutRetryCount; } public void setScmCheckoutRetryCount(int scmCheckoutRetryCount) throws IOException { this.scmCheckoutRetryCount = scmCheckoutRetryCount; save(); } @Override public String getSearchUrl() { return ""; } @Override public SearchIndexBuilder makeSearchIndex() { SearchIndexBuilder builder = super.makeSearchIndex(); if (hasPermission(ADMINISTER)) { builder.add("configure", "config", "configure") .add("manage") .add("log"); } builder.add(new CollectionSearchIndex<TopLevelItem>() { protected SearchItem get(String key) { return getItemByFullName(key, TopLevelItem.class); } protected Collection<TopLevelItem> all() { return getAllItems(TopLevelItem.class); } @Nonnull @Override protected Iterable<TopLevelItem> allAsIterable() { return allItems(TopLevelItem.class); } }) .add(getPrimaryView().makeSearchIndex()) .add(new CollectionSearchIndex() {// for computers protected Computer get(String key) { return getComputer(key); } protected Collection<Computer> all() { return computers.values(); } }) .add(new CollectionSearchIndex() {// for users protected User get(String key) { return User.get(key,false); } protected Collection<User> all() { return User.getAll(); } }) .add(new CollectionSearchIndex() {// for views protected View get(String key) { return getView(key); } protected Collection<View> all() { return getAllViews(); } }); return builder; } public String getUrlChildPrefix() { return "job"; } /** * Gets the absolute URL of Jenkins, such as {@code http://localhost/jenkins/}. * * <p> * This method first tries to use the manually configured value, then * fall back to {@link #getRootUrlFromRequest}. * It is done in this order so that it can work correctly even in the face * of a reverse proxy. * * @return {@code null} if this parameter is not configured by the user and the calling thread is not in an HTTP request; * otherwise the returned URL will always have the trailing {@code /} * @throws IllegalStateException {@link JenkinsLocationConfiguration} cannot be retrieved. * Jenkins instance may be not ready, or there is an extension loading glitch. * @since 1.66 * @see <a href="https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML">Hyperlinks in HTML</a> */ public @Nullable String getRootUrl() throws IllegalStateException { final JenkinsLocationConfiguration config = JenkinsLocationConfiguration.get(); if (config == null) { // Try to get standard message if possible final Jenkins j = Jenkins.get(); throw new IllegalStateException("Jenkins instance " + j + " has been successfully initialized, but JenkinsLocationConfiguration is undefined."); } String url = config.getUrl(); if(url!=null) { return Util.ensureEndsWith(url,"/"); } StaplerRequest req = Stapler.getCurrentRequest(); if(req!=null) return getRootUrlFromRequest(); return null; } /** * Is Jenkins running in HTTPS? * * Note that we can't really trust {@link StaplerRequest#isSecure()} because HTTPS might be terminated * in the reverse proxy. */ public boolean isRootUrlSecure() { String url = getRootUrl(); return url!=null && url.startsWith("https"); } /** * Gets the absolute URL of Jenkins top page, such as {@code http://localhost/jenkins/}. * * <p> * Unlike {@link #getRootUrl()}, which uses the manually configured value, * this one uses the current request to reconstruct the URL. The benefit is * that this is immune to the configuration mistake (users often fail to set the root URL * correctly, especially when a migration is involved), but the downside * is that unless you are processing a request, this method doesn't work. * * <p>Please note that this will not work in all cases if Jenkins is running behind a * reverse proxy which has not been fully configured. * Specifically the {@code Host} and {@code X-Forwarded-Proto} headers must be set. * <a href="https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache">Running Jenkins behind Apache</a> * shows some examples of configuration. * @since 1.263 */ public @Nonnull String getRootUrlFromRequest() { StaplerRequest req = Stapler.getCurrentRequest(); if (req == null) { throw new IllegalStateException("cannot call getRootUrlFromRequest from outside a request handling thread"); } StringBuilder buf = new StringBuilder(); String scheme = getXForwardedHeader(req, "X-Forwarded-Proto", req.getScheme()); buf.append(scheme).append("://"); String host = getXForwardedHeader(req, "X-Forwarded-Host", req.getServerName()); int index = host.lastIndexOf(':'); int port = req.getServerPort(); if (index == -1) { // Almost everyone else except Nginx put the host and port in separate headers buf.append(host); } else { if (host.startsWith("[") && host.endsWith("]")) { // support IPv6 address buf.append(host); } else { // Nginx uses the same spec as for the Host header, i.e. hostname:port buf.append(host, 0, index); if (index + 1 < host.length()) { try { port = Integer.parseInt(host.substring(index + 1)); } catch (NumberFormatException e) { // ignore } } // but if a user has configured Nginx with an X-Forwarded-Port, that will win out. } } String forwardedPort = getXForwardedHeader(req, "X-Forwarded-Port", null); if (forwardedPort != null) { try { port = Integer.parseInt(forwardedPort); } catch (NumberFormatException e) { // ignore } } if (port != ("https".equals(scheme) ? 443 : 80)) { buf.append(':').append(port); } buf.append(req.getContextPath()).append('/'); return buf.toString(); } /** * Gets the originating "X-Forwarded-..." header from the request. If there are multiple headers the originating * header is the first header. If the originating header contains a comma separated list, the originating entry * is the first one. * @param req the request * @param header the header name * @param defaultValue the value to return if the header is absent. * @return the originating entry of the header or the default value if the header was not present. */ private static String getXForwardedHeader(StaplerRequest req, String header, String defaultValue) { String value = req.getHeader(header); if (value != null) { int index = value.indexOf(','); return index == -1 ? value.trim() : value.substring(0,index).trim(); } return defaultValue; } public File getRootDir() { return root; } public FilePath getWorkspaceFor(TopLevelItem item) { for (WorkspaceLocator l : WorkspaceLocator.all()) { FilePath workspace = l.locate(item, this); if (workspace != null) { return workspace; } } return new FilePath(expandVariablesForDirectory(workspaceDir, item)); } public File getBuildDirFor(Job job) { return expandVariablesForDirectory(buildsDir, job); } /** * If the configured buildsDir has it's default value or has been changed. * * @return true if default value. */ @Restricted(NoExternalUse.class) public boolean isDefaultBuildDir() { return DEFAULT_BUILDS_DIR.equals(buildsDir); } @Restricted(NoExternalUse.class) boolean isDefaultWorkspaceDir() { return OLD_DEFAULT_WORKSPACES_DIR.equals(workspaceDir) || DEFAULT_WORKSPACES_DIR.equals(workspaceDir); } private File expandVariablesForDirectory(String base, Item item) { return new File(expandVariablesForDirectory(base, item.getFullName(), item.getRootDir().getPath())); } @Restricted(NoExternalUse.class) public static String expandVariablesForDirectory(String base, String itemFullName, String itemRootDir) { return Util.replaceMacro(base, ImmutableMap.of( "JENKINS_HOME", Jenkins.get().getRootDir().getPath(), "ITEM_ROOTDIR", itemRootDir, "ITEM_FULLNAME", itemFullName, // legacy, deprecated "ITEM_FULL_NAME", itemFullName.replace(':','$'))); // safe, see JENKINS-12251 } public String getRawWorkspaceDir() { return workspaceDir; } public String getRawBuildsDir() { return buildsDir; } @Restricted(NoExternalUse.class) public void setRawBuildsDir(String buildsDir) { this.buildsDir = buildsDir; } @Override public @Nonnull FilePath getRootPath() { return new FilePath(getRootDir()); } @Override public FilePath createPath(String absolutePath) { return new FilePath((VirtualChannel)null,absolutePath); } public ClockDifference getClockDifference() { return ClockDifference.ZERO; } @Override public Callable<ClockDifference, IOException> getClockDifferenceCallable() { return new ClockDifferenceCallable(); } private static class ClockDifferenceCallable extends MasterToSlaveCallable<ClockDifference, IOException> { @Override public ClockDifference call() throws IOException { return new ClockDifference(0); } } /** * For binding {@link LogRecorderManager} to "/log". * Everything below here is admin-only, so do the check here. */ public LogRecorderManager getLog() { checkPermission(ADMINISTER); return log; } /** * A convenience method to check if there's some security * restrictions in place. */ @Exported public boolean isUseSecurity() { return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED; } public boolean isUseProjectNamingStrategy(){ return projectNamingStrategy != DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY; } /** * If true, all the POST requests to Jenkins would have to have crumb in it to protect * Jenkins from CSRF vulnerabilities. */ @Exported public boolean isUseCrumbs() { return crumbIssuer!=null; } /** * Returns the constant that captures the three basic security modes in Jenkins. */ public SecurityMode getSecurity() { // fix the variable so that this code works under concurrent modification to securityRealm. SecurityRealm realm = securityRealm; if(realm==SecurityRealm.NO_AUTHENTICATION) return SecurityMode.UNSECURED; if(realm instanceof LegacySecurityRealm) return SecurityMode.LEGACY; return SecurityMode.SECURED; } /** * @return * never null. */ public SecurityRealm getSecurityRealm() { return securityRealm; } public void setSecurityRealm(SecurityRealm securityRealm) { if(securityRealm==null) securityRealm= SecurityRealm.NO_AUTHENTICATION; this.useSecurity = true; IdStrategy oldUserIdStrategy = this.securityRealm == null ? securityRealm.getUserIdStrategy() // don't trigger rekey on Jenkins load : this.securityRealm.getUserIdStrategy(); this.securityRealm = securityRealm; // reset the filters and proxies for the new SecurityRealm try { HudsonFilter filter = HudsonFilter.get(servletContext); if (filter == null) { // Fix for #3069: This filter is not necessarily initialized before the servlets. // when HudsonFilter does come back, it'll initialize itself. LOGGER.fine("HudsonFilter has not yet been initialized: Can't perform security setup for now"); } else { LOGGER.fine("HudsonFilter has been previously initialized: Setting security up"); filter.reset(securityRealm); LOGGER.fine("Security is now fully set up"); } if (!oldUserIdStrategy.equals(this.securityRealm.getUserIdStrategy())) { User.rekey(); } } catch (ServletException e) { // for binary compatibility, this method cannot throw a checked exception throw new AcegiSecurityException("Failed to configure filter",e) {}; } saveQuietly(); } public void setAuthorizationStrategy(AuthorizationStrategy a) { if (a == null) a = AuthorizationStrategy.UNSECURED; useSecurity = true; authorizationStrategy = a; saveQuietly(); } public boolean isDisableRememberMe() { return disableRememberMe; } public void setDisableRememberMe(boolean disableRememberMe) { this.disableRememberMe = disableRememberMe; } public void disableSecurity() { useSecurity = null; setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); authorizationStrategy = AuthorizationStrategy.UNSECURED; } public void setProjectNamingStrategy(ProjectNamingStrategy ns) { if(ns == null){ ns = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY; } projectNamingStrategy = ns; } public Lifecycle getLifecycle() { return Lifecycle.get(); } /** * Gets the dependency injection container that hosts all the extension implementations and other * components in Jenkins. * * @since 1.433 */ public @CheckForNull Injector getInjector() { return lookup(Injector.class); } /** * Returns {@link ExtensionList} that retains the discovered instances for the given extension type. * * @param extensionType * The base type that represents the extension point. Normally {@link ExtensionPoint} subtype * but that's not a hard requirement. * @return * Can be an empty list but never null. * @see ExtensionList#lookup */ @SuppressWarnings({"unchecked"}) public <T> ExtensionList<T> getExtensionList(Class<T> extensionType) { ExtensionList<T> extensionList = extensionLists.get(extensionType); return extensionList != null ? extensionList : extensionLists.computeIfAbsent(extensionType, key -> ExtensionList.create(this, key)); } /** * Used to bind {@link ExtensionList}s to URLs. * * @since 1.349 */ @StaplerDispatchable public ExtensionList getExtensionList(String extensionType) throws ClassNotFoundException { return getExtensionList(pluginManager.uberClassLoader.loadClass(extensionType)); } /** * Returns {@link ExtensionList} that retains the discovered {@link Descriptor} instances for the given * kind of {@link Describable}. * * @return * Can be an empty list but never null. */ @SuppressWarnings({"unchecked"}) public @Nonnull <T extends Describable<T>,D extends Descriptor<T>> DescriptorExtensionList<T,D> getDescriptorList(Class<T> type) { return descriptorLists.computeIfAbsent(type, key -> DescriptorExtensionList.createDescriptorList(this, key)); } /** * Refresh {@link ExtensionList}s by adding all the newly discovered extensions. * * Exposed only for {@link PluginManager#dynamicLoad(File)}. */ public void refreshExtensions() throws ExtensionRefreshException { ExtensionList<ExtensionFinder> finders = getExtensionList(ExtensionFinder.class); for (ExtensionFinder ef : finders) { if (!ef.isRefreshable()) throw new ExtensionRefreshException(ef+" doesn't support refresh"); } List<ExtensionComponentSet> fragments = Lists.newArrayList(); for (ExtensionFinder ef : finders) { fragments.add(ef.refresh()); } ExtensionComponentSet delta = ExtensionComponentSet.union(fragments).filtered(); // if we find a new ExtensionFinder, we need it to list up all the extension points as well List<ExtensionComponent<ExtensionFinder>> newFinders = Lists.newArrayList(delta.find(ExtensionFinder.class)); while (!newFinders.isEmpty()) { ExtensionFinder f = newFinders.remove(newFinders.size()-1).getInstance(); ExtensionComponentSet ecs = ExtensionComponentSet.allOf(f).filtered(); newFinders.addAll(ecs.find(ExtensionFinder.class)); delta = ExtensionComponentSet.union(delta, ecs); } for (ExtensionList el : extensionLists.values()) { el.refresh(delta); } for (ExtensionList el : descriptorLists.values()) { el.refresh(delta); } // TODO: we need some generalization here so that extension points can be notified when a refresh happens? for (ExtensionComponent<RootAction> ea : delta.find(RootAction.class)) { Action a = ea.getInstance(); if (!actions.contains(a)) actions.add(a); } } /** * Returns the root {@link ACL}. * * @see AuthorizationStrategy#getRootACL() */ @Override public ACL getACL() { return authorizationStrategy.getRootACL(); } /** * @return * never null. */ public AuthorizationStrategy getAuthorizationStrategy() { return authorizationStrategy; } /** * The strategy used to check the project names. * @return never <code>null</code> */ public ProjectNamingStrategy getProjectNamingStrategy() { return projectNamingStrategy == null ? ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY : projectNamingStrategy; } /** * Returns true if Jenkins is quieting down. * <p> * No further jobs will be executed unless it * can be finished while other current pending builds * are still in progress. */ @Exported public boolean isQuietingDown() { return isQuietingDown; } /** * Returns true if the container initiated the termination of the web application. */ public boolean isTerminating() { return terminating; } /** * Gets the initialization milestone that we've already reached. * * @return * {@link InitMilestone#STARTED} even if the initialization hasn't been started, so that this method * never returns null. */ public InitMilestone getInitLevel() { return initLevel; } /** * Sets a number of executors. * @param n Number of executors * @throws IOException Failed to save the configuration * @throws IllegalArgumentException Negative value has been passed */ public void setNumExecutors(@Nonnegative int n) throws IOException, IllegalArgumentException { if (n < 0) { throw new IllegalArgumentException("Incorrect field \"# of executors\": " + n +". It should be a non-negative number."); } if (this.numExecutors != n) { this.numExecutors = n; updateComputerList(); save(); } } /** * {@inheritDoc}. * * Note that the look up is case-insensitive. */ @Override public TopLevelItem getItem(String name) throws AccessDeniedException { if (name==null) return null; TopLevelItem item = items.get(name); if (item==null) return null; if (!item.hasPermission(Item.READ)) { if (item.hasPermission(Item.DISCOVER)) { throw new AccessDeniedException("Please login to access job " + name); } return null; } return item; } /** * Gets the item by its path name from the given context * * <h2>Path Names</h2> * <p> * If the name starts from '/', like "/foo/bar/zot", then it's interpreted as absolute. * Otherwise, the name should be something like "foo/bar" and it's interpreted like * relative path name in the file system is, against the given context. * <p>For compatibility, as a fallback when nothing else matches, a simple path * like {@code foo/bar} can also be treated with {@link #getItemByFullName}. * @param context * null is interpreted as {@link Jenkins}. Base 'directory' of the interpretation. * @since 1.406 */ public Item getItem(String pathName, ItemGroup context) { if (context==null) context = this; if (pathName==null) return null; if (pathName.startsWith("/")) // absolute return getItemByFullName(pathName); Object/*Item|ItemGroup*/ ctx = context; StringTokenizer tokens = new StringTokenizer(pathName,"/"); while (tokens.hasMoreTokens()) { String s = tokens.nextToken(); if (s.equals("..")) { if (ctx instanceof Item) { ctx = ((Item)ctx).getParent(); continue; } ctx=null; // can't go up further break; } if (s.equals(".")) { continue; } if (ctx instanceof ItemGroup) { ItemGroup g = (ItemGroup) ctx; Item i = g.getItem(s); if (i==null || !i.hasPermission(Item.READ)) { // TODO consider DISCOVER ctx=null; // can't go up further break; } ctx=i; } else { return null; } } if (ctx instanceof Item) return (Item)ctx; // fall back to the classic interpretation return getItemByFullName(pathName); } public final Item getItem(String pathName, Item context) { return getItem(pathName,context!=null?context.getParent():null); } public final <T extends Item> T getItem(String pathName, ItemGroup context, @Nonnull Class<T> type) { Item r = getItem(pathName, context); if (type.isInstance(r)) return type.cast(r); return null; } public final <T extends Item> T getItem(String pathName, Item context, Class<T> type) { return getItem(pathName,context!=null?context.getParent():null,type); } public File getRootDirFor(TopLevelItem child) { return getRootDirFor(child.getName()); } private File getRootDirFor(String name) { return new File(new File(getRootDir(),"jobs"), name); } /** * Gets the {@link Item} object by its full name. * Full names are like path names, where each name of {@link Item} is * combined by '/'. * * @return * null if either such {@link Item} doesn't exist under the given full name, * or it exists but it's no an instance of the given type. * @throws AccessDeniedException as per {@link ItemGroup#getItem} */ public @CheckForNull <T extends Item> T getItemByFullName(@Nonnull String fullName, Class<T> type) throws AccessDeniedException { StringTokenizer tokens = new StringTokenizer(fullName,"/"); ItemGroup parent = this; if(!tokens.hasMoreTokens()) return null; // for example, empty full name. while(true) { Item item = parent.getItem(tokens.nextToken()); if(!tokens.hasMoreTokens()) { if(type.isInstance(item)) return type.cast(item); else return null; } if(!(item instanceof ItemGroup)) return null; // this item can't have any children if (!item.hasPermission(Item.READ)) return null; // TODO consider DISCOVER parent = (ItemGroup) item; } } public @CheckForNull Item getItemByFullName(String fullName) { return getItemByFullName(fullName,Item.class); } /** * Gets the user of the given name. * * @return the user of the given name (which may or may not be an id), if that person exists; else null * @see User#get(String,boolean) * @see User#getById(String, boolean) */ public @CheckForNull User getUser(String name) { return User.get(name, User.ALLOW_USER_CREATION_VIA_URL && hasPermission(ADMINISTER)); } public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException { return createProject(type, name, true); } public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException { return itemGroupMixIn.createProject(type,name,notify); } /** * Overwrites the existing item by new one. * * <p> * This is a short cut for deleting an existing job and adding a new one. */ public synchronized void putItem(TopLevelItem item) throws IOException, InterruptedException { String name = item.getName(); TopLevelItem old = items.get(name); if (old ==item) return; // noop checkPermission(Item.CREATE); if (old!=null) old.delete(); items.put(name,item); ItemListener.fireOnCreated(item); } /** * Creates a new job. * * <p> * This version infers the descriptor from the type of the top-level item. * * @throws IllegalArgumentException * if the project of the given name already exists. */ public synchronized <T extends TopLevelItem> T createProject( Class<T> type, String name ) throws IOException { return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name)); } /** * Called by {@link Job#renameTo(String)} to update relevant data structure. * assumed to be synchronized on Jenkins by the caller. */ public void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException { items.remove(oldName); items.put(newName,job); // For compatibility with old views: for (View v : views) v.onJobRenamed(job, oldName, newName); } /** * Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)} */ public void onDeleted(TopLevelItem item) throws IOException { ItemListener.fireOnDeleted(item); items.remove(item.getName()); // For compatibility with old views: for (View v : views) v.onJobRenamed(item, item.getName(), null); } @Override public boolean canAdd(TopLevelItem item) { return true; } @Override synchronized public <I extends TopLevelItem> I add(I item, String name) throws IOException, IllegalArgumentException { if (items.containsKey(name)) { throw new IllegalArgumentException("already an item '" + name + "'"); } items.put(name, item); return item; } @Override public void remove(TopLevelItem item) throws IOException, IllegalArgumentException { items.remove(item.getName()); } public FingerprintMap getFingerprintMap() { return fingerprintMap; } // if no finger print matches, display "not found page". @StaplerDispatchable public Object getFingerprint( String md5sum ) throws IOException { Fingerprint r = fingerprintMap.get(md5sum); if(r==null) return new NoFingerprintMatch(md5sum); else return r; } /** * Gets a {@link Fingerprint} object if it exists. * Otherwise null. */ public Fingerprint _getFingerprint( String md5sum ) throws IOException { return fingerprintMap.get(md5sum); } /** * The file we save our configuration. */ private XmlFile getConfigFile() { return new XmlFile(XSTREAM, new File(root,"config.xml")); } public int getNumExecutors() { return numExecutors; } public Mode getMode() { return mode; } public void setMode(Mode m) throws IOException { this.mode = m; save(); } public String getLabelString() { return fixNull(label).trim(); } @Override public void setLabelString(String label) throws IOException { this.label = label; save(); } @Override public LabelAtom getSelfLabel() { return getLabelAtom("master"); } @Override @Nonnull public Computer createComputer() { return new Hudson.MasterComputer(); } private void loadConfig() throws IOException { XmlFile cfg = getConfigFile(); if (cfg.exists()) { // reset some data that may not exist in the disk file // so that we can take a proper compensation action later. primaryView = null; views.clear(); // load from disk cfg.unmarshal(Jenkins.this); } try { checkRawBuildsDir(buildsDir); setBuildsAndWorkspacesDir(); } catch (InvalidBuildsDir invalidBuildsDir) { throw new IOException(invalidBuildsDir); } } private void setBuildsAndWorkspacesDir() throws IOException, InvalidBuildsDir { boolean mustSave = false; String newBuildsDir = SystemProperties.getString(BUILDS_DIR_PROP); boolean freshStartup = STARTUP_MARKER_FILE.isOff(); if (newBuildsDir != null && !buildsDir.equals(newBuildsDir)) { checkRawBuildsDir(newBuildsDir); Level level = freshStartup ? Level.INFO : Level.WARNING; LOGGER.log(level, "Changing builds directories from {0} to {1}. Beware that no automated data migration will occur.", new String[]{buildsDir, newBuildsDir}); buildsDir = newBuildsDir; mustSave = true; } else if (!isDefaultBuildDir()) { LOGGER.log(Level.INFO, "Using non default builds directories: {0}.", buildsDir); } String newWorkspacesDir = SystemProperties.getString(WORKSPACES_DIR_PROP); if (newWorkspacesDir != null && !workspaceDir.equals(newWorkspacesDir)) { Level level = freshStartup ? Level.INFO : Level.WARNING; LOGGER.log(level, "Changing workspaces directories from {0} to {1}. Beware that no automated data migration will occur.", new String[]{workspaceDir, newWorkspacesDir}); workspaceDir = newWorkspacesDir; mustSave = true; } else if (!isDefaultWorkspaceDir()) { LOGGER.log(Level.INFO, "Using non default workspaces directories: {0}.", workspaceDir); } if (mustSave) { save(); } } /** * Checks the correctness of the newBuildsDirValue for use as {@link #buildsDir}. * @param newBuildsDirValue the candidate newBuildsDirValue for updating {@link #buildsDir}. */ @VisibleForTesting /*private*/ static void checkRawBuildsDir(String newBuildsDirValue) throws InvalidBuildsDir { // do essentially what expandVariablesForDirectory does, without an Item String replacedValue = expandVariablesForDirectory(newBuildsDirValue, "doCheckRawBuildsDir-Marker:foo", Jenkins.get().getRootDir().getPath() + "/jobs/doCheckRawBuildsDir-Marker$foo"); File replacedFile = new File(replacedValue); if (!replacedFile.isAbsolute()) { throw new InvalidBuildsDir(newBuildsDirValue + " does not resolve to an absolute path"); } if (!replacedValue.contains("doCheckRawBuildsDir-Marker")) { throw new InvalidBuildsDir(newBuildsDirValue + " does not contain ${ITEM_FULL_NAME} or ${ITEM_ROOTDIR}, cannot distinguish between projects"); } if (replacedValue.contains("doCheckRawBuildsDir-Marker:foo")) { // make sure platform can handle colon try { File tmp = File.createTempFile("Jenkins-doCheckRawBuildsDir", "foo:bar"); tmp.delete(); } catch (IOException e) { throw new InvalidBuildsDir(newBuildsDirValue + " contains ${ITEM_FULLNAME} but your system does not support it (JENKINS-12251). Use ${ITEM_FULL_NAME} instead"); } } File d = new File(replacedValue); if (!d.isDirectory()) { // if dir does not exist (almost guaranteed) need to make sure nearest existing ancestor can be written to d = d.getParentFile(); while (!d.exists()) { d = d.getParentFile(); } if (!d.canWrite()) { throw new InvalidBuildsDir(newBuildsDirValue + " does not exist and probably cannot be created"); } } } private synchronized TaskBuilder loadTasks() throws IOException { File projectsDir = new File(root,"jobs"); if(!projectsDir.getCanonicalFile().isDirectory() && !projectsDir.mkdirs()) { if(projectsDir.exists()) throw new IOException(projectsDir+" is not a directory"); throw new IOException("Unable to create "+projectsDir+"\nPermission issue? Please create this directory manually."); } File[] subdirs = projectsDir.listFiles(); final Set<String> loadedNames = Collections.synchronizedSet(new HashSet<>()); TaskGraphBuilder g = new TaskGraphBuilder(); Handle loadJenkins = g.requires(EXTENSIONS_AUGMENTED).attains(JOB_LOADED).add("Loading global config", new Executable() { public void run(Reactor session) throws Exception { loadConfig(); // if we are loading old data that doesn't have this field if (slaves != null && !slaves.isEmpty() && nodes.isLegacy()) { nodes.setNodes(slaves); slaves = null; } else { nodes.load(); } clouds.setOwner(Jenkins.this); } }); List<Handle> loadJobs = new ArrayList<>(); for (final File subdir : subdirs) { loadJobs.add(g.requires(loadJenkins).attains(JOB_LOADED).notFatal().add("Loading item " + subdir.getName(), new Executable() { public void run(Reactor session) throws Exception { if(!Items.getConfigFile(subdir).exists()) { //Does not have job config file, so it is not a jenkins job hence skip it return; } TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir); items.put(item.getName(), item); loadedNames.add(item.getName()); } })); } g.requires(loadJobs.toArray(new Handle[0])).attains(JOB_LOADED).add("Cleaning up obsolete items deleted from the disk", new Executable() { public void run(Reactor reactor) throws Exception { // anything we didn't load from disk, throw them away. // doing this after loading from disk allows newly loaded items // to inspect what already existed in memory (in case of reloading) // retainAll doesn't work well because of CopyOnWriteMap implementation, so remove one by one // hopefully there shouldn't be too many of them. for (String name : items.keySet()) { if (!loadedNames.contains(name)) items.remove(name); } } }); g.requires(JOB_LOADED).attains(COMPLETED).add("Finalizing set up",new Executable() { public void run(Reactor session) throws Exception { rebuildDependencyGraph(); {// recompute label objects - populates the labels mapping. for (Node slave : nodes.getNodes()) // Note that not all labels are visible until the agents have connected. slave.getAssignedLabels(); getAssignedLabels(); } // initialize views by inserting the default view if necessary // this is both for clean Jenkins and for backward compatibility. if(views.size()==0 || primaryView==null) { View v = new AllView(AllView.DEFAULT_VIEW_NAME); setViewOwner(v); views.add(0,v); primaryView = v.getViewName(); } primaryView = AllView.migrateLegacyPrimaryAllViewLocalizedName(views, primaryView); if (useSecurity!=null && !useSecurity) { // forced reset to the unsecure mode. // this works as an escape hatch for people who locked themselves out. authorizationStrategy = AuthorizationStrategy.UNSECURED; setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); } else { // read in old data that doesn't have the security field set if(authorizationStrategy==null) { if(useSecurity==null) authorizationStrategy = AuthorizationStrategy.UNSECURED; else authorizationStrategy = new LegacyAuthorizationStrategy(); } if(securityRealm==null) { if(useSecurity==null) setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); else setSecurityRealm(new LegacySecurityRealm()); } else { // force the set to proxy setSecurityRealm(securityRealm); } } // Initialize the filter with the crumb issuer setCrumbIssuer(crumbIssuer); // auto register root actions for (Action a : getExtensionList(RootAction.class)) if (!actions.contains(a)) actions.add(a); setupWizard = new SetupWizard(); getInstallState().initializeState(); } }); return g; } /** * Save the settings to a file. */ public synchronized void save() throws IOException { if(BulkChange.contains(this)) return; if (initLevel == InitMilestone.COMPLETED) { LOGGER.log(FINE, "setting version {0} to {1}", new Object[] {version, VERSION}); version = VERSION; } else { LOGGER.log(FINE, "refusing to set version {0} to {1} during {2}", new Object[] {version, VERSION, initLevel}); } getConfigFile().write(this); SaveableListener.fireOnChange(this, getConfigFile()); } private void saveQuietly() { try { save(); } catch (IOException x) { LOGGER.log(Level.WARNING, null, x); } } /** * Called to shut down the system. */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD") public void cleanUp() { if (theInstance != this && theInstance != null) { LOGGER.log(Level.WARNING, "This instance is no longer the singleton, ignoring cleanUp()"); return; } synchronized (Jenkins.class) { if (cleanUpStarted) { LOGGER.log(Level.WARNING, "Jenkins.cleanUp() already started, ignoring repeated cleanUp()"); return; } cleanUpStarted = true; } try { LOGGER.log(Level.INFO, "Stopping Jenkins"); final List<Throwable> errors = new ArrayList<>(); fireBeforeShutdown(errors); _cleanUpRunTerminators(errors); terminating = true; final Set<Future<?>> pending = _cleanUpDisconnectComputers(errors); _cleanUpShutdownUDPBroadcast(errors); _cleanUpCloseDNSMulticast(errors); _cleanUpInterruptReloadThread(errors); _cleanUpShutdownTriggers(errors); _cleanUpShutdownTimer(errors); _cleanUpShutdownTcpSlaveAgent(errors); _cleanUpShutdownPluginManager(errors); _cleanUpPersistQueue(errors); _cleanUpShutdownThreadPoolForLoad(errors); _cleanUpAwaitDisconnects(errors, pending); _cleanUpPluginServletFilters(errors); _cleanUpReleaseAllLoggers(errors); LOGGER.log(Level.INFO, "Jenkins stopped"); if (!errors.isEmpty()) { StringBuilder message = new StringBuilder("Unexpected issues encountered during cleanUp: "); Iterator<Throwable> iterator = errors.iterator(); message.append(iterator.next().getMessage()); while (iterator.hasNext()) { message.append("; "); message.append(iterator.next().getMessage()); } iterator = errors.iterator(); RuntimeException exception = new RuntimeException(message.toString(), iterator.next()); while (iterator.hasNext()) { exception.addSuppressed(iterator.next()); } throw exception; } } finally { theInstance = null; if (JenkinsJVM.isJenkinsJVM()) { JenkinsJVMAccess._setJenkinsJVM(oldJenkinsJVM); } ClassFilterImpl.unregister(); } } private void fireBeforeShutdown(List<Throwable> errors) { LOGGER.log(Level.FINE, "Notifying termination"); for (ItemListener l : ItemListener.all()) { try { l.onBeforeShutdown(); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(Level.WARNING, "ItemListener " + l + ": " + e.getMessage(), e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(Level.WARNING, "ItemListener " + l + ": " + e.getMessage(), e); // save for later errors.add(e); } } } private void _cleanUpRunTerminators(List<Throwable> errors) { try { final TerminatorFinder tf = new TerminatorFinder( pluginManager != null ? pluginManager.uberClassLoader : Thread.currentThread().getContextClassLoader()); new Reactor(tf).execute(new Executor() { @Override public void execute(Runnable command) { command.run(); } }, new ReactorListener() { final Level level = Level.parse(Configuration.getStringConfigParameter("termLogLevel", "FINE")); public void onTaskStarted(Task t) { LOGGER.log(level, "Started {0}", InitReactorRunner.getDisplayName(t)); } public void onTaskCompleted(Task t) { LOGGER.log(level, "Completed {0}", InitReactorRunner.getDisplayName(t)); } public void onTaskFailed(Task t, Throwable err, boolean fatal) { LOGGER.log(SEVERE, "Failed " + InitReactorRunner.getDisplayName(t), err); } public void onAttained(Milestone milestone) { Level lv = level; String s = "Attained " + milestone.toString(); if (milestone instanceof TermMilestone && !Main.isUnitTest) { lv = Level.INFO; // noteworthy milestones --- at least while we debug problems further s = milestone.toString(); } LOGGER.log(lv, s); } }); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to execute termination", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to execute termination", e); // save for later errors.add(e); } } private Set<Future<?>> _cleanUpDisconnectComputers(final List<Throwable> errors) { LOGGER.log(Main.isUnitTest ? Level.FINE : Level.INFO, "Starting node disconnection"); final Set<Future<?>> pending = new HashSet<>(); // JENKINS-28840 we know we will be interrupting all the Computers so get the Queue lock once for all Queue.withLock(new Runnable() { @Override public void run() { for( Computer c : computers.values() ) { try { c.interrupt(); killComputer(c); pending.add(c.disconnect(null)); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(Level.WARNING, "Could not disconnect " + c + ": " + e.getMessage(), e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(Level.WARNING, "Could not disconnect " + c + ": " + e.getMessage(), e); // save for later errors.add(e); } } } }); return pending; } private void _cleanUpShutdownUDPBroadcast(List<Throwable> errors) { if(udpBroadcastThread!=null) { LOGGER.log(Level.FINE, "Shutting down {0}", udpBroadcastThread.getName()); try { udpBroadcastThread.shutdown(); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to shutdown UDP Broadcast Thread", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to shutdown UDP Broadcast Thread", e); // save for later errors.add(e); } } } private void _cleanUpCloseDNSMulticast(List<Throwable> errors) { if(dnsMultiCast!=null) { LOGGER.log(Level.FINE, "Closing DNS Multicast service"); try { dnsMultiCast.close(); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to close DNS Multicast service", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to close DNS Multicast service", e); // save for later errors.add(e); } } } private void _cleanUpInterruptReloadThread(List<Throwable> errors) { LOGGER.log(Level.FINE, "Interrupting reload thread"); try { interruptReloadThread(); } catch (SecurityException e) { LOGGER.log(WARNING, "Not permitted to interrupt reload thread", e); errors.add(e); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to interrupt reload thread", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to interrupt reload thread", e); // save for later errors.add(e); } } private void _cleanUpShutdownTriggers(List<Throwable> errors) { LOGGER.log(Level.FINE, "Shutting down triggers"); try { final java.util.Timer timer = Trigger.timer; if (timer != null) { final CountDownLatch latch = new CountDownLatch(1); timer.schedule(new TimerTask() { @Override public void run() { timer.cancel(); latch.countDown(); } }, 0); if (latch.await(10, TimeUnit.SECONDS)) { LOGGER.log(Level.FINE, "Triggers shut down successfully"); } else { timer.cancel(); LOGGER.log(Level.INFO, "Gave up waiting for triggers to finish running"); } } Trigger.timer = null; } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to shut down triggers", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to shut down triggers", e); // save for later errors.add(e); } } private void _cleanUpShutdownTimer(List<Throwable> errors) { LOGGER.log(Level.FINE, "Shutting down timer"); try { Timer.shutdown(); } catch (SecurityException e) { LOGGER.log(WARNING, "Not permitted to shut down Timer", e); errors.add(e); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to shut down Timer", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to shut down Timer", e); // save for later errors.add(e); } } private void _cleanUpShutdownTcpSlaveAgent(List<Throwable> errors) { if(tcpSlaveAgentListener!=null) { LOGGER.log(FINE, "Shutting down TCP/IP agent listener"); try { tcpSlaveAgentListener.shutdown(); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to shut down TCP/IP agent listener", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to shut down TCP/IP agent listener", e); // save for later errors.add(e); } } } private void _cleanUpShutdownPluginManager(List<Throwable> errors) { if(pluginManager!=null) {// be defensive. there could be some ugly timing related issues LOGGER.log(Main.isUnitTest ? Level.FINE : Level.INFO, "Stopping plugin manager"); try { pluginManager.stop(); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to stop plugin manager", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to stop plugin manager", e); // save for later errors.add(e); } } } private void _cleanUpPersistQueue(List<Throwable> errors) { if(getRootDir().exists()) { // if we are aborting because we failed to create JENKINS_HOME, // don't try to save. Issue #536 LOGGER.log(Main.isUnitTest ? Level.FINE : Level.INFO, "Persisting build queue"); try { getQueue().save(); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to persist build queue", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to persist build queue", e); // save for later errors.add(e); } } } private void _cleanUpShutdownThreadPoolForLoad(List<Throwable> errors) { LOGGER.log(FINE, "Shuting down Jenkins load thread pool"); try { threadPoolForLoad.shutdown(); } catch (SecurityException e) { LOGGER.log(WARNING, "Not permitted to shut down Jenkins load thread pool", e); errors.add(e); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to shut down Jenkins load thread pool", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to shut down Jenkins load thread pool", e); // save for later errors.add(e); } } private void _cleanUpAwaitDisconnects(List<Throwable> errors, Set<Future<?>> pending) { if (!pending.isEmpty()) { LOGGER.log(Main.isUnitTest ? Level.FINE : Level.INFO, "Waiting for node disconnection completion"); } for (Future<?> f : pending) { try { f.get(10, TimeUnit.SECONDS); // if clean up operation didn't complete in time, we fail the test } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; // someone wants us to die now. quick! } catch (ExecutionException e) { LOGGER.log(Level.WARNING, "Failed to shut down remote computer connection cleanly", e); } catch (TimeoutException e) { LOGGER.log(Level.WARNING, "Failed to shut down remote computer connection within 10 seconds", e); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(Level.WARNING, "Failed to shut down remote computer connection", e); } catch (Throwable e) { LOGGER.log(Level.SEVERE, "Unexpected error while waiting for remote computer connection disconnect", e); errors.add(e); } } } private void _cleanUpPluginServletFilters(List<Throwable> errors) { LOGGER.log(Level.FINE, "Stopping filters"); try { PluginServletFilter.cleanUp(); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to stop filters", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to stop filters", e); // save for later errors.add(e); } } private void _cleanUpReleaseAllLoggers(List<Throwable> errors) { LOGGER.log(Level.FINE, "Releasing all loggers"); try { LogFactory.releaseAll(); } catch (OutOfMemoryError e) { // we should just propagate this, no point trying to log throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to release all loggers", e); // safe to ignore and continue for this one } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to release all loggers", e); // save for later errors.add(e); } } public Object getDynamic(String token) { for (Action a : getActions()) { String url = a.getUrlName(); if (url==null) continue; if (url.equals(token) || url.equals('/' + token)) return a; } for (Action a : getManagementLinks()) if (Objects.equals(a.getUrlName(), token)) return a; return null; } // // // actions // // /** * Accepts submission from the configuration page. */ @RequirePOST public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { BulkChange bc = new BulkChange(this); try { checkPermission(ADMINISTER); JSONObject json = req.getSubmittedForm(); systemMessage = Util.nullify(req.getParameter("system_message")); boolean result = true; for (Descriptor<?> d : Functions.getSortedDescriptorsForGlobalConfigUnclassified()) result &= configureDescriptor(req,json,d); save(); updateComputerList(); if(result) FormApply.success(req.getContextPath()+'/').generateResponse(req, rsp, null); else FormApply.success("configure").generateResponse(req, rsp, null); // back to config } finally { bc.commit(); } } /** * Gets the {@link CrumbIssuer} currently in use. * * @return null if none is in use. */ @CheckForNull public CrumbIssuer getCrumbIssuer() { return crumbIssuer; } public void setCrumbIssuer(CrumbIssuer issuer) { crumbIssuer = issuer; } public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { rsp.sendRedirect("foo"); } private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException { // collapse the structure to remain backward compatible with the JSON structure before 1. String name = d.getJsonSafeClassName(); JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object. json.putAll(js); return d.configure(req, js); } /** * Accepts submission from the node configuration page. */ @RequirePOST public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { checkPermission(ADMINISTER); BulkChange bc = new BulkChange(this); try { JSONObject json = req.getSubmittedForm(); ExtensionList.lookupSingleton(MasterBuildConfiguration.class).configure(req,json); getNodeProperties().rebuild(req, json.optJSONObject("nodeProperties"), NodeProperty.all()); } finally { bc.commit(); } updateComputerList(); rsp.sendRedirect(req.getContextPath()+'/'+toComputer().getUrl()); // back to the computer page } /** * Accepts the new description. */ @RequirePOST public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { getPrimaryView().doSubmitDescription(req, rsp); } @RequirePOST public synchronized HttpRedirect doQuietDown() throws IOException { try { return doQuietDown(false,0); } catch (InterruptedException e) { throw new AssertionError(); // impossible } } /** * Quiet down Jenkins - preparation for a restart * * @param block Block until the system really quiets down and no builds are running * @param timeout If non-zero, only block up to the specified number of milliseconds */ @RequirePOST public HttpRedirect doQuietDown(@QueryParameter boolean block, @QueryParameter int timeout) throws InterruptedException, IOException { synchronized (this) { checkPermission(ADMINISTER); isQuietingDown = true; } if (block) { long waitUntil = timeout; if (timeout > 0) waitUntil += System.currentTimeMillis(); while (isQuietingDown && (timeout <= 0 || System.currentTimeMillis() < waitUntil) && !RestartListener.isAllReady()) { Thread.sleep(TimeUnit.SECONDS.toMillis(1)); } } return new HttpRedirect("."); } /** * Cancel previous quiet down Jenkins - preparation for a restart */ @RequirePOST // TODO the cancel link needs to be updated accordingly public synchronized HttpRedirect doCancelQuietDown() { checkPermission(ADMINISTER); isQuietingDown = false; getQueue().scheduleMaintenance(); return new HttpRedirect("."); } public HttpResponse doToggleCollapse() throws ServletException, IOException { final StaplerRequest request = Stapler.getCurrentRequest(); final String paneId = request.getParameter("paneId"); PaneStatusProperties.forCurrentUser().toggleCollapsed(paneId); return HttpResponses.forwardToPreviousPage(); } /** * Backward compatibility. Redirect to the thread dump. */ // TODO annotate @GET once baseline includes Stapler version XXX public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException { rsp.sendRedirect2("threadDump"); } /** * Obtains the thread dump of all agents (including the master.) * * <p> * Since this is for diagnostics, it has a built-in precautionary measure against hang agents. */ public Map<String,Map<String,String>> getAllThreadDumps() throws IOException, InterruptedException { checkPermission(ADMINISTER); // issue the requests all at once Map<String,Future<Map<String,String>>> future = new HashMap<>(); for (Computer c : getComputers()) { try { future.put(c.getName(), RemotingDiagnostics.getThreadDumpAsync(c.getChannel())); } catch(Exception e) { LOGGER.info("Failed to get thread dump for node " + c.getName() + ": " + e.getMessage()); } } if (toComputer() == null) { future.put("master", RemotingDiagnostics.getThreadDumpAsync(FilePath.localChannel)); } // if the result isn't available in 5 sec, ignore that. // this is a precaution against hang nodes long endTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(5); Map<String,Map<String,String>> r = new HashMap<>(); for (Entry<String, Future<Map<String, String>>> e : future.entrySet()) { try { r.put(e.getKey(), e.getValue().get(endTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS)); } catch (Exception x) { r.put(e.getKey(), Collections.singletonMap("Failed to retrieve thread dump", Functions.printThrowable(x))); } } return Collections.unmodifiableSortedMap(new TreeMap<>(r)); } @RequirePOST public synchronized TopLevelItem doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { return itemGroupMixIn.createTopLevelItem(req, rsp); } /** * @since 1.319 */ public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException { return itemGroupMixIn.createProjectFromXML(name, xml); } @SuppressWarnings({"unchecked"}) public <T extends TopLevelItem> T copy(T src, String name) throws IOException { return itemGroupMixIn.copy(src, name); } // a little more convenient overloading that assumes the caller gives us the right type // (or else it will fail with ClassCastException) public <T extends AbstractProject<?,?>> T copy(T src, String name) throws IOException { return (T)copy((TopLevelItem)src,name); } @RequirePOST public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { checkPermission(View.CREATE); addView(View.create(req,rsp, this)); } /** * Check if the given name is suitable as a name * for job, view, etc. * * @throws Failure * if the given name is not good */ public static void checkGoodName(String name) throws Failure { if(name==null || name.length()==0) throw new Failure(Messages.Hudson_NoName()); if(".".equals(name.trim())) throw new Failure(Messages.Jenkins_NotAllowedName(".")); if("..".equals(name.trim())) throw new Failure(Messages.Jenkins_NotAllowedName("..")); for( int i=0; i<name.length(); i++ ) { char ch = name.charAt(i); if(Character.isISOControl(ch)) { throw new Failure(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name))); } if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1) throw new Failure(Messages.Hudson_UnsafeChar(ch)); } // looks good } private static String toPrintableName(String name) { StringBuilder printableName = new StringBuilder(); for( int i=0; i<name.length(); i++ ) { char ch = name.charAt(i); if(Character.isISOControl(ch)) printableName.append("\\u").append((int)ch).append(';'); else printableName.append(ch); } return printableName.toString(); } /** * Checks if the user was successfully authenticated. * * @see BasicAuthenticationFilter */ public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { // TODO fire something in SecurityListener? (seems to be used only for REST calls when LegacySecurityRealm is active) if(req.getUserPrincipal()==null) { // authentication must have failed rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } // the user is now authenticated, so send him back to the target String path = req.getContextPath()+req.getOriginalRestOfPath(); String q = req.getQueryString(); if(q!=null) path += '?'+q; rsp.sendRedirect2(path); } /** * Called once the user logs in. Just forward to the top page. * Used only by {@link LegacySecurityRealm}. */ public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException { if(req.getUserPrincipal()==null) { rsp.sendRedirect2("noPrincipal"); return; } // TODO fire something in SecurityListener? String from = req.getParameter("from"); if(from!=null && from.startsWith("/") && !from.equals("/loginError")) { rsp.sendRedirect2(from); // I'm bit uncomfortable letting users redirected to other sites, make sure the URL falls into this domain return; } String url = AbstractProcessingFilter.obtainFullRequestUrl(req); if(url!=null) { // if the login redirect is initiated by Acegi // this should send the user back to where s/he was from. rsp.sendRedirect2(url); return; } rsp.sendRedirect2("."); } /** * Logs out the user. */ public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { String user = getAuthentication().getName(); securityRealm.doLogout(req, rsp); SecurityListener.fireLoggedOut(user); } /** * Serves jar files for inbound agents. */ public Slave.JnlpJar getJnlpJars(String fileName) { return new Slave.JnlpJar(fileName); } public Slave.JnlpJar doJnlpJars(StaplerRequest req) { return new Slave.JnlpJar(req.getRestOfPath().substring(1)); } /** * Reloads the configuration. */ @RequirePOST public synchronized HttpResponse doReload() throws IOException { checkPermission(ADMINISTER); LOGGER.log(Level.WARNING, "Reloading Jenkins as requested by {0}", getAuthentication().getName()); // engage "loading ..." UI and then run the actual task in a separate thread WebApp.get(servletContext).setApp(new HudsonIsLoading()); new Thread("Jenkins config reload thread") { @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); reload(); } catch (Exception e) { LOGGER.log(SEVERE,"Failed to reload Jenkins config",e); new JenkinsReloadFailed(e).publish(servletContext,root); } } }.start(); return HttpResponses.redirectViaContextPath("/"); } /** * Reloads the configuration synchronously. * Beware that this calls neither {@link ItemListener#onLoaded} nor {@link Initializer}s. */ public void reload() throws IOException, InterruptedException, ReactorException { queue.save(); executeReactor(null, loadTasks()); // Ensure we reached the final initialization state. Log the error otherwise if (initLevel != InitMilestone.COMPLETED) { LOGGER.log(SEVERE, "Jenkins initialization has not reached the COMPLETED initialization milestone after the configuration reload. " + "Current state: {0}. " + "It may cause undefined incorrect behavior in Jenkins plugin relying on this state. " + "It is likely an issue with the Initialization task graph. " + "Example: usage of @Initializer(after = InitMilestone.COMPLETED) in a plugin (JENKINS-37759). " + "Please create a bug in Jenkins bugtracker.", initLevel); } User.reload(); queue.load(); WebApp.get(servletContext).setApp(this); } /** * Do a finger-print check. */ @RequirePOST public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { // Parse the request try (MultipartFormDataParser p = new MultipartFormDataParser(req)) { if (isUseCrumbs() && !getCrumbIssuer().validateCrumb(req, p)) { // TODO investigate whether this check can be removed rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "No crumb found"); } rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+ Util.getDigestOf(p.getFileItem("name").getInputStream())+'/'); } } /** * For debugging. Expose URL to perform GC. */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("DM_GC") @RequirePOST public void doGc(StaplerResponse rsp) throws IOException { checkPermission(Jenkins.ADMINISTER); System.gc(); rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); rsp.getWriter().println("GCed"); } /** * End point that intentionally throws an exception to test the error behaviour. * @since 1.467 */ @StaplerDispatchable public void doException() { throw new RuntimeException(); } public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws IOException, JellyException { ContextMenu menu = new ContextMenu().from(this, request, response); for (MenuItem i : menu.items) { if (i.url.equals(request.getContextPath() + "/manage")) { // add "Manage Jenkins" subitems i.subMenu = new ContextMenu().from(this, request, response, "manage"); } } return menu; } public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception { ContextMenu menu = new ContextMenu(); for (View view : getViews()) { menu.add(view.getViewUrl(),view.getDisplayName()); } return menu; } /** * Obtains the heap dump. */ public HeapDump getHeapDump() throws IOException { return new HeapDump(this,FilePath.localChannel); } /** * Simulates OutOfMemoryError. * Useful to make sure OutOfMemoryHeapDump setting. */ @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") @RequirePOST public void doSimulateOutOfMemory() throws IOException { checkPermission(ADMINISTER); System.out.println("Creating artificial OutOfMemoryError situation"); List<Object> args = new ArrayList<>(); //noinspection InfiniteLoopStatement while (true) args.add(new byte[1024*1024]); } /** * Binds /userContent/... to $JENKINS_HOME/userContent. */ public DirectoryBrowserSupport doUserContent() { return new DirectoryBrowserSupport(this,getRootPath().child("userContent"),"User content","folder.png",true); } /** * Perform a restart of Jenkins, if we can. * * This first replaces "app" to {@link HudsonIsRestarting} */ @CLIMethod(name="restart") public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, RestartNotSupportedException { checkPermission(ADMINISTER); if (req != null && req.getMethod().equals("GET")) { req.getView(this,"_restart.jelly").forward(req,rsp); return; } if (req == null || req.getMethod().equals("POST")) { restart(); } if (rsp != null) { rsp.sendRedirect2("."); } } /** * Queues up a restart of Jenkins for when there are no builds running, if we can. * * This first replaces "app" to {@link HudsonIsRestarting} * * @since 1.332 */ @CLIMethod(name="safe-restart") public HttpResponse doSafeRestart(StaplerRequest req) throws IOException, ServletException, RestartNotSupportedException { checkPermission(ADMINISTER); if (req != null && req.getMethod().equals("GET")) return HttpResponses.forwardToView(this,"_safeRestart.jelly"); if (req == null || req.getMethod().equals("POST")) { safeRestart(); } return HttpResponses.redirectToDot(); } private static Lifecycle restartableLifecycle() throws RestartNotSupportedException { if (Main.isUnitTest) { throw new RestartNotSupportedException("Restarting the master JVM is not supported in JenkinsRule-based tests"); } Lifecycle lifecycle = Lifecycle.get(); lifecycle.verifyRestartable(); return lifecycle; } /** * Performs a restart. */ public void restart() throws RestartNotSupportedException { final Lifecycle lifecycle = restartableLifecycle(); servletContext.setAttribute("app", new HudsonIsRestarting()); new Thread("restart thread") { final String exitUser = getAuthentication().getName(); @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); // give some time for the browser to load the "reloading" page Thread.sleep(TimeUnit.SECONDS.toMillis(5)); LOGGER.info(String.format("Restarting VM as requested by %s",exitUser)); for (RestartListener listener : RestartListener.all()) listener.onRestart(); lifecycle.restart(); } catch (InterruptedException | IOException e) { LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e); } } }.start(); } /** * Queues up a restart to be performed once there are no builds currently running. * @since 1.332 */ public void safeRestart() throws RestartNotSupportedException { final Lifecycle lifecycle = restartableLifecycle(); // Quiet down so that we won't launch new builds. isQuietingDown = true; new Thread("safe-restart thread") { final String exitUser = getAuthentication().getName(); @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); // Wait 'til we have no active executors. doQuietDown(true, 0); // Make sure isQuietingDown is still true. if (isQuietingDown) { servletContext.setAttribute("app",new HudsonIsRestarting()); // give some time for the browser to load the "reloading" page LOGGER.info("Restart in 10 seconds"); Thread.sleep(TimeUnit.SECONDS.toMillis(10)); LOGGER.info(String.format("Restarting VM as requested by %s",exitUser)); for (RestartListener listener : RestartListener.all()) listener.onRestart(); lifecycle.restart(); } else { LOGGER.info("Safe-restart mode cancelled"); } } catch (Throwable e) { LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e); } } }.start(); } @Extension @Restricted(NoExternalUse.class) public static class MasterRestartNotifyier extends RestartListener { @Override public void onRestart() { Computer computer = Jenkins.get().toComputer(); if (computer == null) return; RestartCause cause = new RestartCause(); for (ComputerListener listener: ComputerListener.all()) { listener.onOffline(computer, cause); } } @Override public boolean isReadyToRestart() throws IOException, InterruptedException { return true; } private static class RestartCause extends OfflineCause.SimpleOfflineCause { protected RestartCause() { super(Messages._Jenkins_IsRestarting()); } } } /** * Shutdown the system. * @since 1.161 */ @CLIMethod(name="shutdown") @RequirePOST public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException { checkPermission(ADMINISTER); if (rsp!=null) { rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); try (PrintWriter w = rsp.getWriter()) { w.println("Shutting down"); } } new Thread("exit thread") { @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); LOGGER.info(String.format("Shutting down VM as requested by %s from %s", getAuthentication().getName(), req != null ? req.getRemoteAddr() : "???")); cleanUp(); System.exit(0); } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to shut down Jenkins", e); } } }.start(); } /** * Shutdown the system safely. * @since 1.332 */ @CLIMethod(name="safe-shutdown") @RequirePOST public HttpResponse doSafeExit(StaplerRequest req) throws IOException { checkPermission(ADMINISTER); isQuietingDown = true; final String exitUser = getAuthentication().getName(); final String exitAddr = req!=null ? req.getRemoteAddr() : "unknown"; new Thread("safe-exit thread") { @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); LOGGER.info(String.format("Shutting down VM as requested by %s from %s", exitUser, exitAddr)); // Wait 'til we have no active executors. doQuietDown(true, 0); // Make sure isQuietingDown is still true. if (isQuietingDown) { cleanUp(); System.exit(0); } } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to shut down Jenkins", e); } } }.start(); return HttpResponses.plainText("Shutting down as soon as all jobs are complete"); } /** * Gets the {@link Authentication} object that represents the user * associated with the current request. */ public static @Nonnull Authentication getAuthentication() { Authentication a = SecurityContextHolder.getContext().getAuthentication(); // on Tomcat while serving the login page, this is null despite the fact // that we have filters. Looking at the stack trace, Tomcat doesn't seem to // run the request through filters when this is the login request. // see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html if(a==null) a = ANONYMOUS; return a; } /** * For system diagnostics. * Run arbitrary Groovy script. */ public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { _doScript(req, rsp, req.getView(this, "_script.jelly"), FilePath.localChannel, getACL()); } /** * Run arbitrary Groovy script and return result as plain text. */ public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { _doScript(req, rsp, req.getView(this, "_scriptText.jelly"), FilePath.localChannel, getACL()); } /** * @since 1.509.1 */ public static void _doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view, VirtualChannel channel, ACL acl) throws IOException, ServletException { // ability to run arbitrary script is dangerous acl.checkPermission(RUN_SCRIPTS); String text = req.getParameter("script"); if (text != null) { if (!"POST".equals(req.getMethod())) { throw HttpResponses.error(HttpURLConnection.HTTP_BAD_METHOD, "requires POST"); } if (channel == null) { throw HttpResponses.error(HttpURLConnection.HTTP_NOT_FOUND, "Node is offline"); } try { req.setAttribute("output", RemotingDiagnostics.executeGroovy(text, channel)); } catch (InterruptedException e) { throw new ServletException(e); } } view.forward(req, rsp); } /** * Evaluates the Jelly script submitted by the client. * * This is useful for system administration as well as unit testing. */ @RequirePOST public void doEval(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { checkPermission(RUN_SCRIPTS); try { MetaClass mc = WebApp.getCurrent().getMetaClass(getClass()); Script script = mc.classLoader.loadTearOff(JellyClassLoaderTearOff.class).createContext().compileScript(new InputSource(req.getReader())); new JellyRequestDispatcher(this,script).forward(req,rsp); } catch (JellyException e) { throw new ServletException(e); } } /** * Sign up for the user account. */ public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { if (getSecurityRealm().allowsSignup()) { req.getView(getSecurityRealm(), "signup.jelly").forward(req, rsp); return; } req.getView(SecurityRealm.class, "signup.jelly").forward(req, rsp); } /** * Changes the icon size by changing the cookie */ public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { String qs = req.getQueryString(); if(qs==null) throw new ServletException(); Cookie cookie = new Cookie("iconSize", Functions.validateIconSize(qs)); cookie.setMaxAge(/* ~4 mo. */9999999); // #762 rsp.addCookie(cookie); String ref = req.getHeader("Referer"); if(ref==null) ref="."; rsp.sendRedirect2(ref); } @RequirePOST public void doFingerprintCleanup(StaplerResponse rsp) throws IOException { checkPermission(ADMINISTER); FingerprintCleanupThread.invoke(); rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); rsp.getWriter().println("Invoked"); } @RequirePOST public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException { checkPermission(ADMINISTER); WorkspaceCleanupThread.invoke(); rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); rsp.getWriter().println("Invoked"); } /** * If the user chose the default JDK, make sure we got 'java' in PATH. */ public FormValidation doDefaultJDKCheck(StaplerRequest request, @QueryParameter String value) { if(!JDK.isDefaultName(value)) // assume the user configured named ones properly in system config --- // or else system config should have reported form field validation errors. return FormValidation.ok(); // default JDK selected. Does such java really exist? if(JDK.isDefaultJDKValid(Jenkins.this)) return FormValidation.ok(); else return FormValidation.errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath())); } /** * Checks if a top-level view with the given name exists and * make sure that the name is good as a view name. */ public FormValidation doCheckViewName(@QueryParameter String value) { checkPermission(View.CREATE); String name = fixEmpty(value); if (name == null) return FormValidation.ok(); // already exists? if (getView(name) != null) return FormValidation.error(Messages.Hudson_ViewAlreadyExists(name)); // good view name? try { checkGoodName(name); } catch (Failure e) { return FormValidation.error(e.getMessage()); } return FormValidation.ok(); } /** * Checks if a top-level view with the given name exists. * @deprecated 1.512 */ @Deprecated public FormValidation doViewExistsCheck(@QueryParameter String value) { checkPermission(View.CREATE); String view = fixEmpty(value); if(view==null) return FormValidation.ok(); if(getView(view)==null) return FormValidation.ok(); else return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view)); } /** * Serves static resources placed along with Jelly view files. * <p> * This method can serve a lot of files, so care needs to be taken * to make this method secure. It's not clear to me what's the best * strategy here, though the current implementation is based on * file extensions. */ public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { String path = req.getRestOfPath(); // cut off the "..." portion of /resources/.../path/to/file // as this is only used to make path unique (which in turn // allows us to set a long expiration date path = path.substring(path.indexOf('/',1)+1); int idx = path.lastIndexOf('.'); String extension = path.substring(idx+1); if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) { URL url = pluginManager.uberClassLoader.getResource(path); if(url!=null) { long expires = MetaClass.NO_CACHE ? 0 : TimeUnit.DAYS.toMillis(365); rsp.serveFile(req,url,expires); return; } } rsp.sendError(HttpServletResponse.SC_NOT_FOUND); } /** * Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve. * This set is mutable to allow plugins to add additional extensions. */ public static final Set<String> ALLOWED_RESOURCE_EXTENSIONS = new HashSet<>(Arrays.asList( "js|css|jpeg|jpg|png|gif|html|htm".split("\\|") )); /** * Checks if container uses UTF-8 to decode URLs. See * http://wiki.jenkins-ci.org/display/JENKINS/Tomcat#Tomcat-i18n */ @Restricted(NoExternalUse.class) @RestrictedSince("2.37") @Deprecated public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException { return ExtensionList.lookupSingleton(URICheckEncodingMonitor.class).doCheckURIEncoding(request); } /** * Does not check when system default encoding is "ISO-8859-1". */ @Restricted(NoExternalUse.class) @RestrictedSince("2.37") @Deprecated public static boolean isCheckURIEncodingEnabled() { return ExtensionList.lookupSingleton(URICheckEncodingMonitor.class).isCheckEnabled(); } /** * Rebuilds the dependency map. */ public void rebuildDependencyGraph() { DependencyGraph graph = new DependencyGraph(); graph.build(); // volatile acts a as a memory barrier here and therefore guarantees // that graph is fully build, before it's visible to other threads dependencyGraph = graph; dependencyGraphDirty.set(false); } /** * Rebuilds the dependency map asynchronously. * * <p> * This would keep the UI thread more responsive and helps avoid the deadlocks, * as dependency graph recomputation tends to touch a lot of other things. * * @since 1.522 */ public Future<DependencyGraph> rebuildDependencyGraphAsync() { dependencyGraphDirty.set(true); return Timer.get().schedule(new java.util.concurrent.Callable<DependencyGraph>() { @Override public DependencyGraph call() throws Exception { if (dependencyGraphDirty.get()) { rebuildDependencyGraph(); } return dependencyGraph; } }, 500, TimeUnit.MILLISECONDS); } public DependencyGraph getDependencyGraph() { return dependencyGraph; } // for Jelly public List<ManagementLink> getManagementLinks() { return ManagementLink.all(); } /** * If set, a currently active setup wizard - e.g. installation * * @since 2.0 */ @Restricted(NoExternalUse.class) public SetupWizard getSetupWizard() { return setupWizard; } /** * Exposes the current user to {@code /me} URL. */ public User getMe() { User u = User.current(); if (u == null) throw new AccessDeniedException("/me is not available when not logged in"); return u; } /** * Gets the {@link Widget}s registered on this object. * * <p> * Plugins who wish to contribute boxes on the side panel can add widgets * by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}. */ @StaplerDispatchable // some plugins use this to add views to widgets public List<Widget> getWidgets() { return widgets; } public Object getTarget() { try { checkPermission(READ); } catch (AccessDeniedException e) { if (!isSubjectToMandatoryReadPermissionCheck(Stapler.getCurrentRequest().getRestOfPath())) { return this; } throw e; } return this; } /** * Test a path to see if it is subject to mandatory read permission checks by container-managed security * @param restOfPath the URI, excluding the Jenkins root URI and query string * @return true if the path is subject to mandatory read permission checks * @since 2.37 */ public boolean isSubjectToMandatoryReadPermissionCheck(String restOfPath) { for (String name : ALWAYS_READABLE_PATHS) { if (restOfPath.startsWith(name)) { return false; } } for (String name : getUnprotectedRootActions()) { if (restOfPath.startsWith("/" + name + "/") || restOfPath.equals("/" + name)) { return false; } } // TODO SlaveComputer.doSlaveAgentJnlp; there should be an annotation to request unprotected access if (restOfPath.matches("/computer/[^/]+/slave-agent[.]jnlp") && "true".equals(Stapler.getCurrentRequest().getParameter("encrypt"))) { return false; } return true; } /** * Gets a list of unprotected root actions. * These URL prefixes should be exempted from access control checks by container-managed security. * Ideally would be synchronized with {@link #getTarget}. * @return a list of {@linkplain Action#getUrlName URL names} * @since 1.495 */ public Collection<String> getUnprotectedRootActions() { Set<String> names = new TreeSet<>(); names.add("jnlpJars"); // TODO cleaner to refactor doJnlpJars into a URA (see also JENKINS-44100) // TODO consider caching (expiring cache when actions changes) for (Action a : getActions()) { if (a instanceof UnprotectedRootAction) { String url = a.getUrlName(); if (url == null) continue; names.add(url); } } return names; } /** * Fallback to the primary view. */ public View getStaplerFallback() { return getPrimaryView(); } /** * This method checks all existing jobs to see if displayName is * unique. It does not check the displayName against the displayName of the * job that the user is configuring though to prevent a validation warning * if the user sets the displayName to what it currently is. * @param displayName * @param currentJobName */ boolean isDisplayNameUnique(String displayName, String currentJobName) { Collection<TopLevelItem> itemCollection = items.values(); // if there are a lot of projects, we'll have to store their // display names in a HashSet or something for a quick check for(TopLevelItem item : itemCollection) { if(item.getName().equals(currentJobName)) { // we won't compare the candidate displayName against the current // item. This is to prevent an validation warning if the user // sets the displayName to what the existing display name is continue; } else if(displayName.equals(item.getDisplayName())) { return false; } } return true; } /** * True if there is no item in Jenkins that has this name * @param name The name to test * @param currentJobName The name of the job that the user is configuring */ boolean isNameUnique(String name, String currentJobName) { Item item = getItem(name); if(null==item) { // the candidate name didn't return any items so the name is unique return true; } else if(item.getName().equals(currentJobName)) { // the candidate name returned an item, but the item is the item // that the user is configuring so this is ok return true; } else { // the candidate name returned an item, so it is not unique return false; } } /** * Checks to see if the candidate displayName collides with any * existing display names or project names * @param displayName The display name to test * @param jobName The name of the job the user is configuring */ public FormValidation doCheckDisplayName(@QueryParameter String displayName, @QueryParameter String jobName) { displayName = displayName.trim(); if(LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Current job name is " + jobName); } if(!isNameUnique(displayName, jobName)) { return FormValidation.warning(Messages.Jenkins_CheckDisplayName_NameNotUniqueWarning(displayName)); } else if(!isDisplayNameUnique(displayName, jobName)){ return FormValidation.warning(Messages.Jenkins_CheckDisplayName_DisplayNameNotUniqueWarning(displayName)); } else { return FormValidation.ok(); } } public static class MasterComputer extends Computer { protected MasterComputer() { super(Jenkins.get()); } /** * Returns "" to match with {@link Jenkins#getNodeName()}. */ @Override public String getName() { return ""; } @Override public boolean isConnecting() { return false; } @Override public String getDisplayName() { return Messages.Hudson_Computer_DisplayName(); } @Override public String getCaption() { return Messages.Hudson_Computer_Caption(); } @Override public String getUrl() { return "computer/(master)/"; } public RetentionStrategy getRetentionStrategy() { return RetentionStrategy.NOOP; } /** * Will always keep this guy alive so that it can function as a fallback to * execute {@link FlyweightTask}s. See JENKINS-7291. */ @Override protected boolean isAlive() { return true; } @Override public Boolean isUnix() { return !Functions.isWindows(); } /** * Report an error. */ @Override public HttpResponse doDoDelete() throws IOException { throw HttpResponses.status(SC_BAD_REQUEST); } @Override @RequirePOST public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { Jenkins.get().doConfigExecutorsSubmit(req, rsp); } @WebMethod(name="config.xml") @Override public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { throw HttpResponses.status(SC_BAD_REQUEST); } @Override public boolean hasPermission(Permission permission) { // no one should be allowed to delete the master. // this hides the "delete" link from the /computer/(master) page. if(permission==Computer.DELETE) return false; // Configuration of master node requires ADMINISTER permission return super.hasPermission(permission==Computer.CONFIGURE ? Jenkins.ADMINISTER : permission); } @Override public VirtualChannel getChannel() { return FilePath.localChannel; } @Override public Charset getDefaultCharset() { return Charset.defaultCharset(); } public List<LogRecord> getLogRecords() throws IOException, InterruptedException { return logRecords; } @RequirePOST public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { // this computer never returns null from channel, so // this method shall never be invoked. rsp.sendError(SC_NOT_FOUND); } protected Future<?> _connect(boolean forceReconnect) { return Futures.precomputed(null); } /** * {@link LocalChannel} instance that can be used to execute programs locally. * * @deprecated as of 1.558 * Use {@link FilePath#localChannel} */ @Deprecated public static final LocalChannel localChannel = FilePath.localChannel; } /** * Shortcut for {@code Jenkins.getInstanceOrNull()?.lookup.get(type)} */ public static @CheckForNull <T> T lookup(Class<T> type) { Jenkins j = Jenkins.getInstanceOrNull(); return j != null ? j.lookup.get(type) : null; } /** * Live view of recent {@link LogRecord}s produced by Jenkins. */ public static List<LogRecord> logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE /** * Thread-safe reusable {@link XStream}. */ public static final XStream XSTREAM; /** * Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily. */ public static final XStream2 XSTREAM2; private static final int TWICE_CPU_NUM = Math.max(4, Runtime.getRuntime().availableProcessors() * 2); /** * Thread pool used to load configuration in parallel, to improve the start up time. * <p> * The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers. */ /*package*/ transient final ExecutorService threadPoolForLoad = new ThreadPoolExecutor( TWICE_CPU_NUM, TWICE_CPU_NUM, 5L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new NamingThreadFactory(new DaemonThreadFactory(), "Jenkins load")); private static void computeVersion(ServletContext context) { // set the version Properties props = new Properties(); try (InputStream is = Jenkins.class.getResourceAsStream("jenkins-version.properties")) { if(is!=null) props.load(is); } catch (IOException e) { e.printStackTrace(); // if the version properties is missing, that's OK. } String ver = props.getProperty("version"); if(ver==null) ver = UNCOMPUTED_VERSION; if(Main.isDevelopmentMode && "${project.version}".equals(ver)) { // in dev mode, unable to get version (ahem Eclipse) try { File dir = new File(".").getAbsoluteFile(); while(dir != null) { File pom = new File(dir, "pom.xml"); if (pom.exists() && "pom".equals(XMLUtils.getValue("/project/artifactId", pom))) { pom = pom.getCanonicalFile(); LOGGER.info("Reading version from: " + pom.getAbsolutePath()); ver = XMLUtils.getValue("/project/version", pom); break; } dir = dir.getParentFile(); } LOGGER.info("Jenkins is in dev mode, using version: " + ver); } catch (Exception e) { LOGGER.log(Level.WARNING, "Unable to read Jenkins version: " + e.getMessage(), e); } } VERSION = ver; context.setAttribute("version",ver); VERSION_HASH = Util.getDigestOf(ver).substring(0, 8); SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8); if(ver.equals(UNCOMPUTED_VERSION) || SystemProperties.getBoolean("hudson.script.noCache")) RESOURCE_PATH = ""; else RESOURCE_PATH = "/static/"+SESSION_HASH; VIEW_RESOURCE_PATH = "/resources/"+ SESSION_HASH; } /** * The version number before it is "computed" (by a call to computeVersion()). * @since 2.0 */ @Restricted(NoExternalUse.class) public static final String UNCOMPUTED_VERSION = "?"; /** * Version number of this Jenkins. */ public static String VERSION = UNCOMPUTED_VERSION; /** * Parses {@link #VERSION} into {@link VersionNumber}, or null if it's not parseable as a version number * (such as when Jenkins is run with "mvn hudson-dev:run") */ public @CheckForNull static VersionNumber getVersion() { return toVersion(VERSION); } /** * Get the stored version of Jenkins, as stored by * {@link #doConfigSubmit(org.kohsuke.stapler.StaplerRequest, org.kohsuke.stapler.StaplerResponse)}. * <p> * Parses the version into {@link VersionNumber}, or null if it's not parseable as a version number * (such as when Jenkins is run with "mvn hudson-dev:run") * @since 2.0 */ @Restricted(NoExternalUse.class) public @CheckForNull static VersionNumber getStoredVersion() { return toVersion(Jenkins.getActiveInstance().version); } /** * Parses a version string into {@link VersionNumber}, or null if it's not parseable as a version number * (such as when Jenkins is run with "mvn hudson-dev:run") */ private static @CheckForNull VersionNumber toVersion(@CheckForNull String versionString) { if (versionString == null) { return null; } try { return new VersionNumber(versionString); } catch (NumberFormatException e) { try { // for non-released version of Jenkins, this looks like "1.345 (private-foobar), so try to approximate. int idx = versionString.indexOf(' '); if (idx > 0) { return new VersionNumber(versionString.substring(0,idx)); } } catch (NumberFormatException ignored) { // fall through } // totally unparseable return null; } catch (IllegalArgumentException e) { // totally unparseable return null; } } /** * Hash of {@link #VERSION}. */ public static String VERSION_HASH; /** * Unique random token that identifies the current session. * Used to make {@link #RESOURCE_PATH} unique so that we can set long "Expires" header. * * We used to use {@link #VERSION_HASH}, but making this session local allows us to * reuse the same {@link #RESOURCE_PATH} for static resources in plugins. */ public static String SESSION_HASH; /** * Prefix to static resources like images and javascripts in the war file. * Either "" or strings like "/static/VERSION", which avoids Jenkins to pick up * stale cache when the user upgrades to a different version. * <p> * Value computed in {@link WebAppMain}. */ public static String RESOURCE_PATH = ""; /** * Prefix to resources alongside view scripts. * Strings like "/resources/VERSION", which avoids Jenkins to pick up * stale cache when the user upgrades to a different version. * <p> * Value computed in {@link WebAppMain}. */ public static String VIEW_RESOURCE_PATH = "/resources/TBD"; public static boolean PARALLEL_LOAD = Configuration.getBooleanConfigParameter("parallelLoad", true); public static boolean KILL_AFTER_LOAD = Configuration.getBooleanConfigParameter("killAfterLoad", false); /** * @deprecated No longer used. */ @Deprecated public static boolean FLYWEIGHT_SUPPORT = true; /** * Tentative switch to activate the concurrent build behavior. * When we merge this back to the trunk, this allows us to keep * this feature hidden for a while until we iron out the kinks. * @see AbstractProject#isConcurrentBuild() * @deprecated as of 1.464 * This flag will have no effect. */ @Restricted(NoExternalUse.class) @Deprecated public static boolean CONCURRENT_BUILD = true; /** * Switch to enable people to use a shorter workspace name. */ private static final String WORKSPACE_DIRNAME = Configuration.getStringConfigParameter("workspaceDirName", "workspace"); /** * Default value of job's builds dir. * @see #getRawBuildsDir() */ private static final String DEFAULT_BUILDS_DIR = "${ITEM_ROOTDIR}/builds"; /** * Old layout for workspaces. * @see #DEFAULT_WORKSPACES_DIR */ private static final String OLD_DEFAULT_WORKSPACES_DIR = "${ITEM_ROOTDIR}/" + WORKSPACE_DIRNAME; /** * Default value for the workspace's directories layout. * @see #workspaceDir */ private static final String DEFAULT_WORKSPACES_DIR = "${JENKINS_HOME}/workspace/${ITEM_FULL_NAME}"; /** * System property name to set {@link #buildsDir}. * @see #getRawBuildsDir() */ static final String BUILDS_DIR_PROP = Jenkins.class.getName() + ".buildsDir"; /** * System property name to set {@link #workspaceDir}. * @see #getRawWorkspaceDir() */ static final String WORKSPACES_DIR_PROP = Jenkins.class.getName() + ".workspacesDir"; /** * Automatically try to launch an agent when Jenkins is initialized or a new agent computer is created. */ public static boolean AUTOMATIC_SLAVE_LAUNCH = true; private static final Logger LOGGER = Logger.getLogger(Jenkins.class.getName()); public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS; public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER; public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ,PermissionScope.JENKINS); public static final Permission RUN_SCRIPTS = new Permission(PERMISSIONS, "RunScripts", Messages._Hudson_RunScriptsPermission_Description(),ADMINISTER,PermissionScope.JENKINS); /** * Urls that are always visible without READ permission. * * <p>See also:{@link #getUnprotectedRootActions}. */ private static final ImmutableSet<String> ALWAYS_READABLE_PATHS = ImmutableSet.of( "/login", "/logout", "/accessDenied", "/adjuncts/", "/error", "/oops", "/signup", "/tcpSlaveAgentListener", "/federatedLoginService/", "/securityRealm", "/instance-identity" ); /** * {@link Authentication} object that represents the anonymous user. * Because Acegi creates its own {@link AnonymousAuthenticationToken} instances, the code must not * expect the singleton semantics. This is just a convenient instance. * * @since 1.343 */ public static final Authentication ANONYMOUS; static { try { ANONYMOUS = new AnonymousAuthenticationToken( "anonymous", "anonymous", new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")}); XSTREAM = XSTREAM2 = new XStream2(); XSTREAM.alias("jenkins", Jenkins.class); XSTREAM.alias("slave", DumbSlave.class); XSTREAM.alias("jdk", JDK.class); // for backward compatibility with <1.75, recognize the tag name "view" as well. XSTREAM.alias("view", ListView.class); XSTREAM.alias("listView", ListView.class); XSTREAM.addImplicitArray(Jenkins.class, "_disabledAgentProtocols", "disabledAgentProtocol"); XSTREAM.addImplicitArray(Jenkins.class, "_enabledAgentProtocols", "enabledAgentProtocol"); XSTREAM2.addCriticalField(Jenkins.class, "securityRealm"); XSTREAM2.addCriticalField(Jenkins.class, "authorizationStrategy"); // this seems to be necessary to force registration of converter early enough Mode.class.getEnumConstants(); // double check that initialization order didn't do any harm assert PERMISSIONS != null; assert ADMINISTER != null; } catch (RuntimeException | Error e) { // when loaded on an agent and this fails, subsequent NoClassDefFoundError will fail to chain the cause. // see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8051847 // As we don't know where the first exception will go, let's also send this to logging so that // we have a known place to look at. LOGGER.log(SEVERE, "Failed to load Jenkins.class", e); throw e; } } private static final class JenkinsJVMAccess extends JenkinsJVM { private static void _setJenkinsJVM(boolean jenkinsJVM) { JenkinsJVM.setJenkinsJVM(jenkinsJVM); } } }
Behave robustly in the face of errors from AdministrativeMonitor.isActivated.
core/src/main/java/jenkins/model/Jenkins.java
Behave robustly in the face of errors from AdministrativeMonitor.isActivated.
<ide><path>ore/src/main/java/jenkins/model/Jenkins.java <ide> * @since 2.64 <ide> */ <ide> public List<AdministrativeMonitor> getActiveAdministrativeMonitors() { <del> return administrativeMonitors.stream().filter(m -> m.isEnabled() && m.isActivated()).collect(Collectors.toList()); <add> return administrativeMonitors.stream().filter(m -> { <add> try { <add> return m.isEnabled() && m.isActivated(); <add> } catch (Throwable x) { <add> LOGGER.log(Level.WARNING, null, x); <add> return false; <add> } <add> }).collect(Collectors.toList()); <ide> } <ide> <ide> public NodeDescriptor getDescriptor() {
Java
apache-2.0
80a34cf6b5671126f2f1e95efea852343be0dcea
0
dalmirdasilva/dom-distiller,dalmirdasilva/dom-distiller,dalmirdasilva/dom-distiller,dalmirdasilva/dom-distiller,dalmirdasilva/dom-distiller
// Copyright 2014 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 com.dom_distiller.client; import com.dom_distiller.proto.DomDistillerProtos.TimingEntry; import com.dom_distiller.proto.DomDistillerProtos.TimingInfo; public class LogUtil { // All static fields in this class should be primitives or Strings. Otherwise, a costly (because // it is called many, many times) static initializer method will be created. public static final int DEBUG_LEVEL_NONE = 0; public static final int DEBUG_LEVEL_BOILER_PIPE_PHASES = 1; public static final int DEBUG_LEVEL_VISIBILITY_INFO = 2; public static final int DEBUG_LEVEL_PAGING_INFO = 3; public static final int DEBUG_LEVEL_TIMING_INFO = 4; public static final String kBlack = "\033[0;30m"; public static final String kWhite = "\033[1;37m"; public static final String kDarkGray = "\033[1;30m"; public static final String kLightGray = "\033[0;37m"; public static final String kBlue = "\033[0;34m"; public static final String kLightBlue = "\033[1;34m"; public static final String kGreen = "\033[0;32m"; public static final String kLightGreen = "\033[1;32m"; public static final String kCyan = "\033[0;36m"; public static final String kLightCyan = "\033[1;36m"; public static final String kRed = "\033[0;31m"; public static final String kLightRed = "\033[1;31m"; public static final String kPurple = "\033[0;35m"; public static final String kLightPurple = "\033[1;35m"; public static final String kBrown = "\033[0;33m"; public static final String kYellow = "\033[1;33m"; public static final String kReset = "\033[0m"; private static String sLogBuilder = ""; /** * Debug level requested by the client for logging to include while distilling. */ private static int sDebugLevel = DEBUG_LEVEL_NONE; /** * Whether the log should be included in * {@link com.dom_distiller.proto.DomDistillerProtos.DomDistillerResult}. */ private static boolean sIncludeLog = false; public static boolean isLoggable(int level) { return sDebugLevel >= level; } /** * Log a string to console, first to javascript console, and if it fails, * then to regular system console. */ public static void logToConsole(String str) { if (str == null) { str = ""; } // Try to log to javascript console, which is only available when // running in production mode in browser; otherwise, log to regular // system console. if (str.contains("[0;") || str.contains("[1;")) str += kReset; if (!jsLogToConsole(str)) System.out.println(str); sLogBuilder += str + "\n"; } static int getDebugLevel() { return sDebugLevel; } static void setDebugLevel(int level) { sDebugLevel = level; } static String getAndClearLog() { String log = sLogBuilder; sLogBuilder = ""; return log; } /** * Log a string to the javascript console, if it exists, i.e. if it's defined correctly. * Returns true if logging was successful. * The check is necessary to prevent crash/hang when running "ant test.dev" or "ant test.prod". */ private static native boolean jsLogToConsole(String str) /*-{ if ($wnd.console == null || (typeof($wnd.console.log) != 'function' && typeof($wnd.console.log) != 'object')) { return false; } $wnd.console.log(str); return true; }-*/; public static void addTimingInfo(double startTime, TimingInfo timinginfo, String name) { if (timinginfo != null) { TimingEntry entry = timinginfo.addOtherTimes(); entry.setName(name); entry.setTime(DomUtil.getTime() - startTime); } } }
src/com/dom_distiller/client/LogUtil.java
// Copyright 2014 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 com.dom_distiller.client; import com.dom_distiller.proto.DomDistillerProtos.TimingEntry; import com.dom_distiller.proto.DomDistillerProtos.TimingInfo; public class LogUtil { public static final int DEBUG_LEVEL_NONE = 0; public static final int DEBUG_LEVEL_BOILER_PIPE_PHASES = 1; public static final int DEBUG_LEVEL_VISIBILITY_INFO = 2; public static final int DEBUG_LEVEL_PAGING_INFO = 3; public static final int DEBUG_LEVEL_TIMING_INFO = 4; private static final StringBuilder LOG_BUILDER = new StringBuilder(); /** * Debug level requested by the client for logging to include while distilling. */ private static int sDebugLevel = DEBUG_LEVEL_NONE; /** * Whether the log should be included in * {@link com.dom_distiller.proto.DomDistillerProtos.DomDistillerResult}. */ private static boolean sIncludeLog = false; public static boolean isLoggable(int level) { return sDebugLevel >= level; } /** * Log a string to console, first to javascript console, and if it fails, * then to regular system console. */ public static void logToConsole(String str) { if (str == null) { str = ""; } // Try to log to javascript console, which is only available when // running in production mode in browser; otherwise, log to regular // system console. if (str.contains("[0;") || str.contains("[1;")) str += kReset; if (!jsLogToConsole(str)) System.out.println(str); LOG_BUILDER.append(str).append("\n"); } static int getDebugLevel() { return sDebugLevel; } static void setDebugLevel(int level) { sDebugLevel = level; } static String getAndClearLog() { String log = LOG_BUILDER.toString(); // Clears the log, but re-uses the StringBuilder to reduce amount of copying for next use. LOG_BUILDER.setLength(0); return log; } public static final String kBlack = "\033[0;30m"; public static final String kWhite = "\033[1;37m"; public static final String kDarkGray = "\033[1;30m"; public static final String kLightGray = "\033[0;37m"; public static final String kBlue = "\033[0;34m"; public static final String kLightBlue = "\033[1;34m"; public static final String kGreen = "\033[0;32m"; public static final String kLightGreen = "\033[1;32m"; public static final String kCyan = "\033[0;36m"; public static final String kLightCyan = "\033[1;36m"; public static final String kRed = "\033[0;31m"; public static final String kLightRed = "\033[1;31m"; public static final String kPurple = "\033[0;35m"; public static final String kLightPurple = "\033[1;35m"; public static final String kBrown = "\033[0;33m"; public static final String kYellow = "\033[1;33m"; public static final String kReset = "\033[0m"; /** * Log a string to the javascript console, if it exists, i.e. if it's defined correctly. * Returns true if logging was successful. * The check is necessary to prevent crash/hang when running "ant test.dev" or "ant test.prod". */ private static native boolean jsLogToConsole(String str) /*-{ if ($wnd.console == null || (typeof($wnd.console.log) != 'function' && typeof($wnd.console.log) != 'object')) { return false; } $wnd.console.log(str); return true; }-*/; public static void addTimingInfo(double startTime, TimingInfo timinginfo, String name) { if (timinginfo != null) { TimingEntry entry = timinginfo.addOtherTimes(); entry.setName(name); entry.setTime(DomUtil.getTime() - startTime); } } }
Change LogUtil.LOG_BUILDER to a String A StringBuilder is implemented simply as an object with a javascript string field. With a statically initialized StringBuilder a static initializer method is created and called at the callsite of every function in the class. Since LogUtil is used so broadly, this static initializer is actually rather expensive (even though it doesn't do anything after the first call). Perf impact: ~3% decrease in total time. BUG=440977 [email protected] Review URL: https://codereview.chromium.org/791053008
src/com/dom_distiller/client/LogUtil.java
Change LogUtil.LOG_BUILDER to a String
<ide><path>rc/com/dom_distiller/client/LogUtil.java <ide> import com.dom_distiller.proto.DomDistillerProtos.TimingInfo; <ide> <ide> public class LogUtil { <del> <add> // All static fields in this class should be primitives or Strings. Otherwise, a costly (because <add> // it is called many, many times) static initializer method will be created. <ide> public static final int DEBUG_LEVEL_NONE = 0; <ide> public static final int DEBUG_LEVEL_BOILER_PIPE_PHASES = 1; <ide> public static final int DEBUG_LEVEL_VISIBILITY_INFO = 2; <ide> public static final int DEBUG_LEVEL_PAGING_INFO = 3; <ide> public static final int DEBUG_LEVEL_TIMING_INFO = 4; <ide> <del> private static final StringBuilder LOG_BUILDER = new StringBuilder(); <add> public static final String kBlack = "\033[0;30m"; <add> public static final String kWhite = "\033[1;37m"; <add> <add> public static final String kDarkGray = "\033[1;30m"; <add> public static final String kLightGray = "\033[0;37m"; <add> <add> public static final String kBlue = "\033[0;34m"; <add> public static final String kLightBlue = "\033[1;34m"; <add> <add> public static final String kGreen = "\033[0;32m"; <add> public static final String kLightGreen = "\033[1;32m"; <add> <add> public static final String kCyan = "\033[0;36m"; <add> public static final String kLightCyan = "\033[1;36m"; <add> <add> public static final String kRed = "\033[0;31m"; <add> public static final String kLightRed = "\033[1;31m"; <add> <add> public static final String kPurple = "\033[0;35m"; <add> public static final String kLightPurple = "\033[1;35m"; <add> <add> public static final String kBrown = "\033[0;33m"; <add> public static final String kYellow = "\033[1;33m"; <add> <add> public static final String kReset = "\033[0m"; <add> <add> private static String sLogBuilder = ""; <ide> <ide> /** <ide> * Debug level requested by the client for logging to include while distilling. <ide> if (!jsLogToConsole(str)) <ide> System.out.println(str); <ide> <del> LOG_BUILDER.append(str).append("\n"); <add> sLogBuilder += str + "\n"; <ide> } <ide> <ide> static int getDebugLevel() { <ide> } <ide> <ide> static String getAndClearLog() { <del> String log = LOG_BUILDER.toString(); <del> // Clears the log, but re-uses the StringBuilder to reduce amount of copying for next use. <del> LOG_BUILDER.setLength(0); <add> String log = sLogBuilder; <add> sLogBuilder = ""; <ide> return log; <ide> } <del> <del> public static final String kBlack = "\033[0;30m"; <del> public static final String kWhite = "\033[1;37m"; <del> <del> public static final String kDarkGray = "\033[1;30m"; <del> public static final String kLightGray = "\033[0;37m"; <del> <del> public static final String kBlue = "\033[0;34m"; <del> public static final String kLightBlue = "\033[1;34m"; <del> <del> public static final String kGreen = "\033[0;32m"; <del> public static final String kLightGreen = "\033[1;32m"; <del> <del> public static final String kCyan = "\033[0;36m"; <del> public static final String kLightCyan = "\033[1;36m"; <del> <del> public static final String kRed = "\033[0;31m"; <del> public static final String kLightRed = "\033[1;31m"; <del> <del> public static final String kPurple = "\033[0;35m"; <del> public static final String kLightPurple = "\033[1;35m"; <del> <del> public static final String kBrown = "\033[0;33m"; <del> public static final String kYellow = "\033[1;33m"; <del> <del> public static final String kReset = "\033[0m"; <ide> <ide> /** <ide> * Log a string to the javascript console, if it exists, i.e. if it's defined correctly.
Java
mit
7cb6f4895d290e8f555cb5ce8bd11024975e8ba6
0
sake/bouncycastle-java
package java.security; import java.io.IOException; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.InvalidParameterSpecException; public class AlgorithmParameters extends Object { private AlgorithmParametersSpi spi; private Provider provider; private String algorithm; protected AlgorithmParameters( AlgorithmParametersSpi paramSpi, Provider provider, String algorithm) { this.spi = paramSpi; this.provider = provider; this.algorithm = algorithm; } public final String getAlgorithm() { return algorithm; } public final byte[] getEncoded() throws IOException { return spi.engineGetEncoded(); } public final byte[] getEncoded(String format) throws IOException { return spi.engineGetEncoded(format); } public static AlgorithmParameterGenerator getInstance(String algorithm) throws NoSuchAlgorithmException { try { SecurityUtil.Implementation imp = SecurityUtil.getImplementation("AlgorithmParameters", algorithm, null); if (imp != null) { return new AlgorithmParameterGenerator((AlgorithmParameterGeneratorSpi)imp.getEngine(), imp.getProvider(), algorithm); } throw new NoSuchAlgorithmException("can't find algorithm " + algorithm); } catch (NoSuchProviderException e) { throw new NoSuchAlgorithmException(algorithm + " not found"); } } public static AlgorithmParameterGenerator getInstance(String algorithm, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { SecurityUtil.Implementation imp = SecurityUtil.getImplementation("AlgorithmParameters", algorithm, provider); if (imp != null) { return new AlgorithmParameterGenerator((AlgorithmParameterGeneratorSpi)imp.getEngine(), imp.getProvider(), algorithm); } throw new NoSuchAlgorithmException("can't find algorithm " + algorithm); } public final AlgorithmParameterSpec getParameterSpec(Class paramSpec) throws InvalidParameterSpecException { return spi.engineGetParameterSpec(paramSpec); } public final Provider getProvider() { return provider; } public final void init(AlgorithmParameterSpec paramSpec) throws InvalidParameterSpecException { spi.engineInit(paramSpec); } public final void init(byte[] params) throws IOException { spi.engineInit(params); } public final void init(byte[] params, String format) throws IOException { spi.engineInit(params, format); } public final String toString() { return spi.engineToString(); } }
jdk1.1/java/security/AlgorithmParameters.java
package java.security; import java.io.IOException; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.InvalidParameterSpecException; public class AlgorithmParameters extends Object { private AlgorithmParametersSpi spi; private Provider provider; private String algorithm; protected AlgorithmParameters( AlgorithmParametersSpi paramSpi, Provider provider, String algorithm) { this.spi = paramSpi; this.provider = provider; this.algorithm = algorithm; } public final String getAlgorithm() { return algorithm; } public final byte[] getEncoded() throws IOException { return spi.engineGetEncoded(); } public final byte[] getEncoded(String format) throws IOException { return spi.engineGetEncoded(format); } public static AlgorithmParameters getInstance(String algorithm) throws NoSuchAlgorithmException { return null; } public static AlgorithmParameters getInstance( String algorithm, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { return null; } public final AlgorithmParameterSpec getParameterSpec(Class paramSpec) throws InvalidParameterSpecException { return spi.engineGetParameterSpec(paramSpec); } public final Provider getProvider() { return provider; } public final void init(AlgorithmParameterSpec paramSpec) throws InvalidParameterSpecException { spi.engineInit(paramSpec); } public final void init(byte[] params) throws IOException { spi.engineInit(params); } public final void init(byte[] params, String format) throws IOException { spi.engineInit(params, format); } public final String toString() { return spi.engineToString(); } }
fixed getInstance()
jdk1.1/java/security/AlgorithmParameters.java
fixed getInstance()
<ide><path>dk1.1/java/security/AlgorithmParameters.java <ide> return spi.engineGetEncoded(format); <ide> } <ide> <del> public static AlgorithmParameters getInstance(String algorithm) <del> throws NoSuchAlgorithmException <add> public static AlgorithmParameterGenerator getInstance(String algorithm) <add> throws NoSuchAlgorithmException <ide> { <del> return null; <add> try <add> { <add> SecurityUtil.Implementation imp = SecurityUtil.getImplementation("AlgorithmParameters", algorithm, null); <add> <add> if (imp != null) <add> { <add> return new AlgorithmParameterGenerator((AlgorithmParameterGeneratorSpi)imp.getEngine(), imp.getProvider(), algorithm); <add> } <add> <add> throw new NoSuchAlgorithmException("can't find algorithm " + algorithm); <add> } <add> catch (NoSuchProviderException e) <add> { <add> throw new NoSuchAlgorithmException(algorithm + " not found"); <add> } <ide> } <ide> <del> public static AlgorithmParameters getInstance( <del> String algorithm, <del> String provider) <del> throws NoSuchAlgorithmException, NoSuchProviderException <add> public static AlgorithmParameterGenerator getInstance(String algorithm, String provider) <add> throws NoSuchAlgorithmException, NoSuchProviderException <ide> { <del> return null; <add> SecurityUtil.Implementation imp = SecurityUtil.getImplementation("AlgorithmParameters", algorithm, provider); <add> <add> if (imp != null) <add> { <add> return new AlgorithmParameterGenerator((AlgorithmParameterGeneratorSpi)imp.getEngine(), imp.getProvider(), algorithm); <add> } <add> <add> throw new NoSuchAlgorithmException("can't find algorithm " + algorithm); <ide> } <ide> <ide> public final AlgorithmParameterSpec getParameterSpec(Class paramSpec)
Java
apache-2.0
23ca683fc0c1b218a35a84a4c42d822e954e7e08
0
Stratio/stratio-connector-mongodb,Stratio/stratio-connector-mongodb
/* * Licensed to STRATIO (C) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. The STRATIO (C) 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 com.stratio.connector.mongodb.core.engine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.mongodb.DB; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.stratio.connector.commons.connection.Connection; import com.stratio.connector.commons.engine.CommonsMetadataEngine; import com.stratio.connector.mongodb.core.connection.MongoConnectionHandler; import com.stratio.connector.mongodb.core.engine.metadata.IndexUtils; import com.stratio.connector.mongodb.core.engine.metadata.SelectorOptionsUtils; import com.stratio.connector.mongodb.core.engine.metadata.ShardUtils; import com.stratio.crossdata.common.data.CatalogName; import com.stratio.crossdata.common.data.TableName; import com.stratio.crossdata.common.exceptions.ExecutionException; import com.stratio.crossdata.common.exceptions.UnsupportedException; import com.stratio.crossdata.common.metadata.CatalogMetadata; import com.stratio.crossdata.common.metadata.IndexMetadata; import com.stratio.crossdata.common.metadata.TableMetadata; /** * @author darroyo * */ public class MongoMetadataEngine extends CommonsMetadataEngine<MongoClient> { /** * The Log. */ final private Logger logger = LoggerFactory.getLogger(this.getClass()); /** * @param connectionHandler * the connector handler */ public MongoMetadataEngine(MongoConnectionHandler connectionHandler) { super(connectionHandler); } /** * Create a database in MongoDB. * * @param catalogMetadata * the catalogMetadata. * @param connection * the connection which contains the native connector. * @throws UnsupportedException * if any operation is not supported. * @throws ExecutionException * if an error occur. */ @Override protected void createCatalog(CatalogMetadata catalogMetadata, Connection<MongoClient> connection) throws ExecutionException, UnsupportedException { throw new UnsupportedException("Create catalog is not supported"); } /** * Create a collection in MongoDB. * * @param tableMetadata * the tableMetadata. * @param connection * the connection which contains the native connector. * @throws UnsupportedException * if any operation is not supported. * @throws ExecutionException * if an error occur. */ @Override protected void createTable(TableMetadata tableMetadata, Connection<MongoClient> connection) throws ExecutionException, UnsupportedException { if (tableMetadata == null) { throw new UnsupportedException("the table metadata is required"); } if (tableMetadata.getName() == null) { throw new UnsupportedException("the table name is required"); } if (ShardUtils.collectionIsSharded(SelectorOptionsUtils.processOptions(tableMetadata.getOptions()))) { ShardUtils.shardCollection((MongoClient) connection.getNativeConnection(), tableMetadata); } } /** * Drop a database in MongoDB. * * @param targetCluster * the cluster to be dropped. * @param name * the database name. */ @Override protected void dropCatalog(CatalogName name, Connection<MongoClient> connection) throws ExecutionException { try { connection.getNativeConnection().dropDatabase(name.getName()); } catch (MongoException e) { throw new ExecutionException(e.getMessage(), e); } } /** * Drop a collection in MongoDB. * * @param targetCluster * the cluster to be dropped. * @param name * the database name. */ @Override protected void dropTable(TableName name, Connection<MongoClient> connection) throws ExecutionException { DB db = connection.getNativeConnection().getDB(name.getCatalogName().getName()); try { db.getCollection(name.getName()).drop(); } catch (MongoException e) { throw new ExecutionException(e.getMessage(), e); } } /* * (non-Javadoc) * * @see com.stratio.meta.common.connector.IMetadataEngine#createIndex(com.stratio.meta2.common.data.ClusterName, * com.stratio.meta2.common.metadata.IndexMetadata) */ @Override protected void createIndex(IndexMetadata indexMetadata, Connection<MongoClient> connection) throws ExecutionException, UnsupportedException { DB db = connection.getNativeConnection().getDB( indexMetadata.getName().getTableName().getCatalogName().getName()); DBObject indexDBObject = IndexUtils.getIndexDBObject(indexMetadata); DBObject indexOptionsDBObject = IndexUtils.getCustomOptions(indexMetadata); try { db.getCollection(indexMetadata.getName().getTableName().getName()).createIndex(indexDBObject, indexOptionsDBObject); } catch (MongoException e) { throw new ExecutionException(e.getMessage(), e); } if (logger.isDebugEnabled()) { logger.debug("Index created " + indexDBObject.toString() + indexOptionsDBObject); } } /* * (non-Javadoc) * * @see com.stratio.meta.common.connector.IMetadataEngine#dropIndex(com.stratio.meta2.common.data.ClusterName, * com.stratio.meta2.common.metadata.IndexMetadata) */ @Override protected void dropIndex(IndexMetadata indexMetadata, Connection<MongoClient> connection) throws ExecutionException, UnsupportedException { DB db = connection.getNativeConnection().getDB( indexMetadata.getName().getTableName().getCatalogName().getName()); String indexName = null; if (indexMetadata.getName() != null) { indexName = indexMetadata.getName().getName(); } if (indexName != null) { try { db.getCollection(indexMetadata.getName().getTableName().getName()).dropIndex(indexName); } catch (MongoException e) { throw new ExecutionException(e.getMessage(), e); } } else { IndexUtils.dropIndexWithDefaultName(indexMetadata, db); } } }
connector-mongodb-core/src/main/java/com/stratio/connector/mongodb/core/engine/MongoMetadataEngine.java
/* * Licensed to STRATIO (C) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. The STRATIO (C) 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 com.stratio.connector.mongodb.core.engine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.mongodb.DB; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.stratio.connector.commons.connection.Connection; import com.stratio.connector.commons.engine.CommonsMetadataEngine; import com.stratio.connector.mongodb.core.connection.MongoConnectionHandler; import com.stratio.connector.mongodb.core.engine.metadata.IndexUtils; import com.stratio.connector.mongodb.core.engine.metadata.SelectorOptionsUtils; import com.stratio.connector.mongodb.core.engine.metadata.ShardUtils; import com.stratio.crossdata.common.data.CatalogName; import com.stratio.crossdata.common.data.TableName; import com.stratio.crossdata.common.exceptions.ExecutionException; import com.stratio.crossdata.common.exceptions.UnsupportedException; import com.stratio.crossdata.common.metadata.CatalogMetadata; import com.stratio.crossdata.common.metadata.IndexMetadata; import com.stratio.crossdata.common.metadata.TableMetadata; /** * @author darroyo * */ public class MongoMetadataEngine extends CommonsMetadataEngine<MongoClient> { /** * The Log. */ final private Logger logger = LoggerFactory.getLogger(this.getClass()); /** * @param connectionHandler * the connector handler */ public MongoMetadataEngine(MongoConnectionHandler connectionHandler) { super(connectionHandler); } /** * Create a database in MongoDB. * * @param catalogMetadata * the catalogMetadata. * @param connection * the connection which contains the native connector. * @throws UnsupportedException * if any operation is not supported. * @throws ExecutionException * if an error occur. */ @Override protected void createCatalog(CatalogMetadata catalogMetadata, Connection<MongoClient> connection) throws ExecutionException, UnsupportedException { // throw new UnsupportedException("Create catalog is not supported"); } /** * Create a collection in MongoDB. * * @param tableMetadata * the tableMetadata. * @param connection * the connection which contains the native connector. * @throws UnsupportedException * if any operation is not supported. * @throws ExecutionException * if an error occur. */ @Override protected void createTable(TableMetadata tableMetadata, Connection<MongoClient> connection) throws ExecutionException, UnsupportedException { if (tableMetadata == null) { throw new UnsupportedException("the table metadata is required"); } if (tableMetadata.getName() == null) { throw new UnsupportedException("the table name is required"); } if (ShardUtils.collectionIsSharded(SelectorOptionsUtils.processOptions(tableMetadata.getOptions()))) { ShardUtils.shardCollection((MongoClient) connection.getNativeConnection(), tableMetadata); } } /** * Drop a database in MongoDB. * * @param targetCluster * the cluster to be dropped. * @param name * the database name. */ @Override protected void dropCatalog(CatalogName name, Connection<MongoClient> connection) throws ExecutionException { try { connection.getNativeConnection().dropDatabase(name.getName()); } catch (MongoException e) { throw new ExecutionException(e.getMessage(), e); } } /** * Drop a collection in MongoDB. * * @param targetCluster * the cluster to be dropped. * @param name * the database name. */ @Override protected void dropTable(TableName name, Connection<MongoClient> connection) throws ExecutionException { DB db = connection.getNativeConnection().getDB(name.getCatalogName().getName()); try { db.getCollection(name.getName()).drop(); } catch (MongoException e) { throw new ExecutionException(e.getMessage(), e); } } /* * (non-Javadoc) * * @see com.stratio.meta.common.connector.IMetadataEngine#createIndex(com.stratio.meta2.common.data.ClusterName, * com.stratio.meta2.common.metadata.IndexMetadata) */ @Override protected void createIndex(IndexMetadata indexMetadata, Connection<MongoClient> connection) throws ExecutionException, UnsupportedException { DB db = connection.getNativeConnection().getDB( indexMetadata.getName().getTableName().getCatalogName().getName()); DBObject indexDBObject = IndexUtils.getIndexDBObject(indexMetadata); DBObject indexOptionsDBObject = IndexUtils.getCustomOptions(indexMetadata); try { db.getCollection(indexMetadata.getName().getTableName().getName()).createIndex(indexDBObject, indexOptionsDBObject); } catch (MongoException e) { throw new ExecutionException(e.getMessage(), e); } if (logger.isDebugEnabled()) { logger.debug("Index created " + indexDBObject.toString() + indexOptionsDBObject); } } /* * (non-Javadoc) * * @see com.stratio.meta.common.connector.IMetadataEngine#dropIndex(com.stratio.meta2.common.data.ClusterName, * com.stratio.meta2.common.metadata.IndexMetadata) */ @Override protected void dropIndex(IndexMetadata indexMetadata, Connection<MongoClient> connection) throws ExecutionException, UnsupportedException { DB db = connection.getNativeConnection().getDB( indexMetadata.getName().getTableName().getCatalogName().getName()); String indexName = null; if (indexMetadata.getName() != null) { indexName = indexMetadata.getName().getName(); } if (indexName != null) { try { db.getCollection(indexMetadata.getName().getTableName().getName()).dropIndex(indexName); } catch (MongoException e) { throw new ExecutionException(e.getMessage(), e); } } else { IndexUtils.dropIndexWithDefaultName(indexMetadata, db); } } }
imports reorganized: meta => crossdata
connector-mongodb-core/src/main/java/com/stratio/connector/mongodb/core/engine/MongoMetadataEngine.java
imports reorganized: meta => crossdata
<ide><path>onnector-mongodb-core/src/main/java/com/stratio/connector/mongodb/core/engine/MongoMetadataEngine.java <ide> @Override <ide> protected void createCatalog(CatalogMetadata catalogMetadata, Connection<MongoClient> connection) <ide> throws ExecutionException, UnsupportedException { <del> // throw new UnsupportedException("Create catalog is not supported"); <add> throw new UnsupportedException("Create catalog is not supported"); <ide> } <ide> <ide> /**
Java
apache-2.0
7773367e4fb4366cfb0404928d34f53473c771cb
0
lovemomia/momia,lovemomia/momia,lovemomia/service,lovemomia/service
package cn.momia.service.feed.web.ctrl; import cn.momia.api.feed.dto.FeedDto; import cn.momia.api.feed.dto.FeedTopicDto; import cn.momia.api.product.ProductServiceApi; import cn.momia.api.product.dto.ProductDto; import cn.momia.api.user.dto.ParticipantDto; import cn.momia.common.api.http.MomiaHttpResponse; import cn.momia.common.util.SexUtil; import cn.momia.common.util.TimeUtil; import cn.momia.common.webapp.ctrl.BaseController; import cn.momia.common.api.dto.PagedList; import cn.momia.service.feed.facade.Feed; import cn.momia.service.feed.facade.FeedImage; import cn.momia.service.feed.facade.FeedServiceFacade; import cn.momia.api.user.UserServiceApi; import cn.momia.api.user.dto.UserDto; import cn.momia.service.feed.topic.FeedTopic; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @RestController @RequestMapping("/feed") public class FeedController extends BaseController { private static final Logger LOGGER = LoggerFactory.getLogger(FeedController.class); @Autowired private FeedServiceFacade feedServiceFacade; @RequestMapping(value = "/follow", method = RequestMethod.POST) public MomiaHttpResponse follow(@RequestParam(value = "uid") long userId, @RequestParam(value = "fuid") long followedId) { if (!feedServiceFacade.follow(userId, followedId)) return MomiaHttpResponse.FAILED("关注失败"); return MomiaHttpResponse.SUCCESS; } @RequestMapping(method = RequestMethod.GET) public MomiaHttpResponse list(@RequestParam(value = "uid") long userId, @RequestParam(value = "tid", required = false, defaultValue = "0") long topicId, @RequestParam int start, @RequestParam int count) { if (isInvalidLimit(start, count)) return MomiaHttpResponse.SUCCESS(PagedList.EMPTY); long totalCount = topicId > 0 ? feedServiceFacade.queryCountByTopic(topicId) : feedServiceFacade.queryFollowedCountByUser(userId); List<Feed> feeds = topicId > 0 ? feedServiceFacade.queryByTopic(topicId, start, count) : feedServiceFacade.queryFollowedByUser(userId, start, count); return MomiaHttpResponse.SUCCESS(buildPagedFeedDtos(userId, totalCount, feeds, start, count)); } private PagedList<FeedDto> buildPagedFeedDtos(long userId, long totalCount, List<Feed> feeds, int start, int count) { Set<Long> staredFeedIds = new HashSet<Long>(); if (userId > 0) { Set<Long> feedIds = new HashSet<Long>(); for (Feed feed : feeds) feedIds.add(feed.getId()); staredFeedIds.addAll(feedServiceFacade.queryStaredFeeds(userId, feedIds)); } Set<Long> userIds = new HashSet<Long>(); Set<Long> topicIds = new HashSet<Long>(); for (Feed feed : feeds) { userIds.add(feed.getUserId()); topicIds.add(feed.getTopicId()); } List<UserDto> users = UserServiceApi.USER.list(userIds, UserDto.Type.FULL); Map<Long, UserDto> usersMap = new HashMap<Long, UserDto>(); for (UserDto user : users) usersMap.put(user.getId(), user); List<FeedTopic> topics = feedServiceFacade.list(topicIds); Map<Long, FeedTopic> topicsMap = new HashMap<Long, FeedTopic>(); for (FeedTopic topic : topics) topicsMap.put(topic.getId(), topic); PagedList<FeedDto> pagedFeedDtos = new PagedList(totalCount, start, count); List<FeedDto> feedDtos = new ArrayList<FeedDto>(); for (Feed feed : feeds) { UserDto user = usersMap.get(feed.getUserId()); if (user == null) continue; feedDtos.add(buildFeedDto(feed, user, topicsMap.get(feed.getTopicId()), staredFeedIds.contains(feed.getId()))); } pagedFeedDtos.setList(feedDtos); return pagedFeedDtos; } private FeedDto buildFeedDto(Feed feed, UserDto user, FeedTopic topic, boolean stared) { FeedDto feedDto = new FeedDto(); feedDto.setId(feed.getId()); feedDto.setType(feed.getType()); feedDto.setTopicId(feed.getTopicId()); if (topic != null && topic.exists()) { feedDto.setTopicType(topic.getType()); feedDto.setTopic(topic.getTitle()); feedDto.setRefId(topic.getRefId()); } feedDto.setImgs(getImgs(feed)); feedDto.setContent(feed.getContent()); feedDto.setAddTime(feed.getAddTime()); feedDto.setPoi(feed.getPoi()); feedDto.setCommentCount(feed.getCommentCount()); feedDto.setStarCount(feed.getStarCount()); feedDto.setUserId(user.getId()); feedDto.setAvatar(user.getAvatar()); feedDto.setNickName(user.getNickName()); feedDto.setChildren(getChildren(user)); feedDto.setStared(stared); return feedDto; } private List<String> getImgs(Feed feed) { List<String> imgs = new ArrayList<String>(); for (FeedImage feedImage : feed.getImgs()) imgs.add(feedImage.getUrl()); return imgs; } private List<String> getChildren(UserDto user) { List<String> children = new ArrayList<String>(); if (user.getChildren() != null) { int count = 0; for (ParticipantDto child : user.getChildren()) { if (TimeUtil.isAdult(child.getBirthday())) continue; String ageStr = TimeUtil.formatAge(child.getBirthday()); if (SexUtil.isInvalid(child.getSex())) children.add("孩子" + ageStr); else children.add(child.getSex() + "孩" + ageStr); count++; if (count >= 2) break; } } return children; } @RequestMapping(value = "/topic/{tid}", method = RequestMethod.GET) public MomiaHttpResponse topic(@PathVariable(value = "tid") long topicId) { if (topicId <= 0) return MomiaHttpResponse.BAD_REQUEST; FeedTopic feedTopic = feedServiceFacade.getTopic(topicId); FeedTopicDto feedTopicDto = null; if (feedTopic.getType() == FeedTopic.Type.PRODUCT) { ProductDto product = ProductServiceApi.PRODUCT.get(feedTopic.getRefId(), ProductDto.Type.BASE); feedTopicDto = buildFeedTopicDto(feedTopic, product); } else if (feedTopic.getType() == FeedTopic.Type.COURSE) { // TODO course } return MomiaHttpResponse.SUCCESS(feedTopicDto); } @RequestMapping(value = "/topic", method = RequestMethod.GET) public MomiaHttpResponse listTopic(@RequestParam int type, @RequestParam int start, @RequestParam int count) { if (isInvalidLimit(start, count)) return MomiaHttpResponse.SUCCESS(PagedList.EMPTY); long totalCount = feedServiceFacade.queryTopicCount(type); List<FeedTopic> topics = feedServiceFacade.queryTopic(type, start, count); PagedList<FeedTopicDto> pagedFeedTopicDtos = new PagedList(totalCount, start, count); List<FeedTopicDto> feedTopicDtos = new ArrayList<FeedTopicDto>(); Set<Long> refIds = new HashSet<Long>(); for (FeedTopic feedTopic : topics) refIds.add(feedTopic.getRefId()); if (type == FeedTopic.Type.PRODUCT) { List<ProductDto> products = ProductServiceApi.PRODUCT.list(refIds, ProductDto.Type.BASE); Map<Long, ProductDto> productsMap = new HashMap<Long, ProductDto>(); for (ProductDto product : products) productsMap.put(product.getId(), product); for (FeedTopic feedTopic : topics) { ProductDto product = productsMap.get(feedTopic.getRefId()); if (product != null) feedTopicDtos.add(buildFeedTopicDto(feedTopic, product)); } } else if (type == FeedTopic.Type.COURSE) { // TODO course } pagedFeedTopicDtos.setList(feedTopicDtos); return MomiaHttpResponse.SUCCESS(pagedFeedTopicDtos); } private FeedTopicDto buildFeedTopicDto(FeedTopic feedTopic, ProductDto product) { FeedTopicDto feedTopicDto = new FeedTopicDto(); feedTopicDto.setId(feedTopic.getId()); feedTopicDto.setType(feedTopic.getType()); feedTopicDto.setRefId(feedTopic.getRefId()); feedTopicDto.setTitle(StringUtils.isBlank(feedTopic.getTitle()) ? product.getTitle() : feedTopic.getTitle()); feedTopicDto.setScheduler(product.getScheduler()); feedTopicDto.setRegion(product.getRegion()); return feedTopicDto; } @RequestMapping(method = RequestMethod.POST, consumes = "application/json") public MomiaHttpResponse add(@RequestBody Feed feed) { long feedId = feedServiceFacade.addFeed(feed); if (feedId <= 0) return MomiaHttpResponse.FAILED("发表Feed失败"); try { // TODO 异步推送 List<Long> followedIds = feedServiceFacade.queryFollowedIds(feed.getUserId()); followedIds.add(feed.getUserId()); feedServiceFacade.pushFeed(feedId, followedIds); } catch (Exception e) { LOGGER.error("fail to push feed: {}", feed.getId()); } return MomiaHttpResponse.SUCCESS; } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public MomiaHttpResponse get(@RequestParam(value = "uid", defaultValue = "0") long userId, @PathVariable long id) { Feed feed = feedServiceFacade.getFeed(id); if (!feed.exists()) return MomiaHttpResponse.FAILED("无效的Feed"); UserDto feedUser = UserServiceApi.USER.get(feed.getUserId()); if (!feedUser.exists()) return MomiaHttpResponse.FAILED("无效的Feed"); FeedTopic topic = feed.getTopicId() <= 0 ? FeedTopic.NOT_EXIST_FEED_TOPIC : feedServiceFacade.getTopic(feed.getTopicId()); boolean stared = feedServiceFacade.isStared(userId, id); return MomiaHttpResponse.SUCCESS(buildFeedDto(feed, feedUser, topic, stared)); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public MomiaHttpResponse delete(@RequestParam(value = "uid") long userId, @PathVariable long id) { if (!feedServiceFacade.deleteFeed(userId, id)) return MomiaHttpResponse.FAILED("删除Feed失败"); return MomiaHttpResponse.SUCCESS; } }
feed/service-feed/src/main/java/cn/momia/service/feed/web/ctrl/FeedController.java
package cn.momia.service.feed.web.ctrl; import cn.momia.api.feed.dto.FeedDto; import cn.momia.api.feed.dto.FeedTopicDto; import cn.momia.api.product.ProductServiceApi; import cn.momia.api.product.dto.ProductDto; import cn.momia.api.user.dto.ParticipantDto; import cn.momia.common.api.http.MomiaHttpResponse; import cn.momia.common.util.SexUtil; import cn.momia.common.util.TimeUtil; import cn.momia.common.webapp.ctrl.BaseController; import cn.momia.common.api.dto.PagedList; import cn.momia.service.feed.facade.Feed; import cn.momia.service.feed.facade.FeedImage; import cn.momia.service.feed.facade.FeedServiceFacade; import cn.momia.api.user.UserServiceApi; import cn.momia.api.user.dto.UserDto; import cn.momia.service.feed.topic.FeedTopic; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @RestController @RequestMapping("/feed") public class FeedController extends BaseController { private static final Logger LOGGER = LoggerFactory.getLogger(FeedController.class); @Autowired private FeedServiceFacade feedServiceFacade; @RequestMapping(value = "/follow", method = RequestMethod.POST) public MomiaHttpResponse follow(@RequestParam(value = "uid") long userId, @RequestParam(value = "fuid") long followedId) { if (!feedServiceFacade.follow(userId, followedId)) return MomiaHttpResponse.FAILED("关注失败"); return MomiaHttpResponse.SUCCESS; } @RequestMapping(method = RequestMethod.GET) public MomiaHttpResponse list(@RequestParam(value = "uid") long userId, @RequestParam(value = "tid", required = false, defaultValue = "0") long topicId, @RequestParam int start, @RequestParam int count) { if (isInvalidLimit(start, count)) return MomiaHttpResponse.SUCCESS(PagedList.EMPTY); long totalCount = topicId > 0 ? feedServiceFacade.queryCountByTopic(topicId) : feedServiceFacade.queryFollowedCountByUser(userId); List<Feed> feeds = topicId > 0 ? feedServiceFacade.queryByTopic(topicId, start, count) : feedServiceFacade.queryFollowedByUser(userId, start, count); return MomiaHttpResponse.SUCCESS(buildPagedFeedDtos(userId, totalCount, feeds, start, count)); } private PagedList<FeedDto> buildPagedFeedDtos(long userId, long totalCount, List<Feed> feeds, int start, int count) { Set<Long> staredFeedIds = new HashSet<Long>(); if (userId > 0) { Set<Long> feedIds = new HashSet<Long>(); for (Feed feed : feeds) feedIds.add(feed.getId()); staredFeedIds.addAll(feedServiceFacade.queryStaredFeeds(userId, feedIds)); } Set<Long> userIds = new HashSet<Long>(); Set<Long> topicIds = new HashSet<Long>(); for (Feed feed : feeds) { userIds.add(feed.getUserId()); topicIds.add(feed.getTopicId()); } List<UserDto> users = UserServiceApi.USER.list(userIds, UserDto.Type.FULL); Map<Long, UserDto> usersMap = new HashMap<Long, UserDto>(); for (UserDto user : users) usersMap.put(user.getId(), user); List<FeedTopic> topics = feedServiceFacade.list(topicIds); Map<Long, FeedTopic> topicsMap = new HashMap<Long, FeedTopic>(); for (FeedTopic topic : topics) topicsMap.put(topic.getId(), topic); PagedList<FeedDto> pagedFeedDtos = new PagedList(totalCount, start, count); List<FeedDto> feedDtos = new ArrayList<FeedDto>(); for (Feed feed : feeds) { UserDto user = usersMap.get(feed.getUserId()); if (user == null) continue; feedDtos.add(buildFeedDto(feed, user, topicsMap.get(feed.getTopicId()), staredFeedIds.contains(feed.getId()))); } pagedFeedDtos.setList(feedDtos); return pagedFeedDtos; } private FeedDto buildFeedDto(Feed feed, UserDto user, FeedTopic topic, boolean stared) { FeedDto feedDto = new FeedDto(); feedDto.setId(feed.getId()); feedDto.setType(feed.getType()); feedDto.setTopicId(feed.getTopicId()); if (topic != null && topic.exists()) { feedDto.setTopicType(topic.getType()); feedDto.setTopic(topic.getTitle()); feedDto.setRefId(topic.getRefId()); } feedDto.setImgs(getImgs(feed)); feedDto.setContent(feed.getContent()); feedDto.setAddTime(feed.getAddTime()); feedDto.setPoi(feed.getPoi()); feedDto.setCommentCount(feed.getCommentCount()); feedDto.setStarCount(feed.getStarCount()); feedDto.setUserId(user.getId()); feedDto.setAvatar(user.getAvatar()); feedDto.setNickName(user.getNickName()); feedDto.setChildren(getChildren(user)); feedDto.setStared(stared); return feedDto; } private List<String> getImgs(Feed feed) { List<String> imgs = new ArrayList<String>(); for (FeedImage feedImage : feed.getImgs()) imgs.add(feedImage.getUrl()); return imgs; } public List<String> getChildren(UserDto user) { List<String> children = new ArrayList<String>(); if (user.getChildren() != null) { int count = 0; for (ParticipantDto child : user.getChildren()) { if (TimeUtil.isAdult(child.getBirthday())) continue; String ageStr = TimeUtil.formatAge(child.getBirthday()); if (SexUtil.isInvalid(child.getSex())) children.add("孩子" + ageStr); else children.add(child.getSex() + "孩" + ageStr); count++; if (count >= 2) break; } } return children; } @RequestMapping(value = "/topic/{tid}", method = RequestMethod.GET) public MomiaHttpResponse topic(@PathVariable(value = "tid") long topicId) { if (topicId <= 0) return MomiaHttpResponse.BAD_REQUEST; FeedTopic feedTopic = feedServiceFacade.getTopic(topicId); FeedTopicDto feedTopicDto = null; if (feedTopic.getType() == FeedTopic.Type.PRODUCT) { ProductDto product = ProductServiceApi.PRODUCT.get(feedTopic.getRefId(), ProductDto.Type.BASE); feedTopicDto = buildFeedTopicDto(feedTopic, product); } else if (feedTopic.getType() == FeedTopic.Type.COURSE) { // TODO course } return MomiaHttpResponse.SUCCESS(feedTopicDto); } @RequestMapping(value = "/topic", method = RequestMethod.GET) public MomiaHttpResponse listTopic(@RequestParam int type, @RequestParam int start, @RequestParam int count) { if (isInvalidLimit(start, count)) return MomiaHttpResponse.SUCCESS(PagedList.EMPTY); long totalCount = feedServiceFacade.queryTopicCount(type); List<FeedTopic> topics = feedServiceFacade.queryTopic(type, start, count); PagedList<FeedTopicDto> pagedFeedTopicDtos = new PagedList(totalCount, start, count); List<FeedTopicDto> feedTopicDtos = new ArrayList<FeedTopicDto>(); Set<Long> refIds = new HashSet<Long>(); for (FeedTopic feedTopic : topics) refIds.add(feedTopic.getRefId()); if (type == FeedTopic.Type.PRODUCT) { List<ProductDto> products = ProductServiceApi.PRODUCT.list(refIds, ProductDto.Type.BASE); Map<Long, ProductDto> productsMap = new HashMap<Long, ProductDto>(); for (ProductDto product : products) productsMap.put(product.getId(), product); for (FeedTopic feedTopic : topics) { ProductDto product = productsMap.get(feedTopic.getRefId()); if (product != null) feedTopicDtos.add(buildFeedTopicDto(feedTopic, product)); } } else if (type == FeedTopic.Type.COURSE) { // TODO course } pagedFeedTopicDtos.setList(feedTopicDtos); return MomiaHttpResponse.SUCCESS(pagedFeedTopicDtos); } private FeedTopicDto buildFeedTopicDto(FeedTopic feedTopic, ProductDto product) { FeedTopicDto feedTopicDto = new FeedTopicDto(); feedTopicDto.setId(feedTopic.getId()); feedTopicDto.setType(feedTopic.getType()); feedTopicDto.setRefId(feedTopic.getRefId()); feedTopicDto.setTitle(StringUtils.isBlank(feedTopic.getTitle()) ? product.getTitle() : feedTopic.getTitle()); feedTopicDto.setScheduler(product.getScheduler()); feedTopicDto.setRegion(product.getRegion()); return feedTopicDto; } @RequestMapping(method = RequestMethod.POST, consumes = "application/json") public MomiaHttpResponse add(@RequestBody Feed feed) { long feedId = feedServiceFacade.addFeed(feed); if (feedId <= 0) return MomiaHttpResponse.FAILED("发表Feed失败"); try { // TODO 异步推送 List<Long> followedIds = feedServiceFacade.queryFollowedIds(feed.getUserId()); followedIds.add(feed.getUserId()); feedServiceFacade.pushFeed(feedId, followedIds); } catch (Exception e) { LOGGER.error("fail to push feed: {}", feed.getId()); } return MomiaHttpResponse.SUCCESS; } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public MomiaHttpResponse get(@RequestParam(value = "uid", defaultValue = "0") long userId, @PathVariable long id) { Feed feed = feedServiceFacade.getFeed(id); if (!feed.exists()) return MomiaHttpResponse.FAILED("无效的Feed"); UserDto feedUser = UserServiceApi.USER.get(feed.getUserId()); if (!feedUser.exists()) return MomiaHttpResponse.FAILED("无效的Feed"); FeedTopic topic = feed.getTopicId() <= 0 ? FeedTopic.NOT_EXIST_FEED_TOPIC : feedServiceFacade.getTopic(feed.getTopicId()); boolean stared = feedServiceFacade.isStared(userId, id); return MomiaHttpResponse.SUCCESS(buildFeedDto(feed, feedUser, topic, stared)); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public MomiaHttpResponse delete(@RequestParam(value = "uid") long userId, @PathVariable long id) { if (!feedServiceFacade.deleteFeed(userId, id)) return MomiaHttpResponse.FAILED("删除Feed失败"); return MomiaHttpResponse.SUCCESS; } }
utoken为空返回 TOKEN_EXPIRED
feed/service-feed/src/main/java/cn/momia/service/feed/web/ctrl/FeedController.java
utoken为空返回 TOKEN_EXPIRED
<ide><path>eed/service-feed/src/main/java/cn/momia/service/feed/web/ctrl/FeedController.java <ide> @RequestMapping(value = "/follow", method = RequestMethod.POST) <ide> public MomiaHttpResponse follow(@RequestParam(value = "uid") long userId, @RequestParam(value = "fuid") long followedId) { <ide> if (!feedServiceFacade.follow(userId, followedId)) return MomiaHttpResponse.FAILED("关注失败"); <del> <ide> return MomiaHttpResponse.SUCCESS; <ide> } <ide> <ide> return imgs; <ide> } <ide> <del> public List<String> getChildren(UserDto user) { <add> private List<String> getChildren(UserDto user) { <ide> List<String> children = new ArrayList<String>(); <ide> <ide> if (user.getChildren() != null) { <ide> public MomiaHttpResponse add(@RequestBody Feed feed) { <ide> long feedId = feedServiceFacade.addFeed(feed); <ide> if (feedId <= 0) return MomiaHttpResponse.FAILED("发表Feed失败"); <add> <ide> try { <ide> // TODO 异步推送 <ide> List<Long> followedIds = feedServiceFacade.queryFollowedIds(feed.getUserId());
Java
apache-2.0
39fca00e05fa160efaa2feed627879c0ed4abc94
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-2020 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.util.messages.impl; import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.ExtensionNotApplicableException; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.util.Disposer; import com.intellij.util.ArrayUtil; import com.intellij.util.ConcurrencyUtil; import com.intellij.util.EventDispatcher; import com.intellij.util.containers.ConcurrentFactoryMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import com.intellij.util.lang.CompoundRuntimeException; import com.intellij.util.messages.ListenerDescriptor; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusOwner; import com.intellij.util.messages.Topic; import org.jetbrains.annotations.*; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.*; import java.util.concurrent.ConcurrentMap; public class MessageBusImpl implements MessageBus { private static final Logger LOG = Logger.getInstance(MessageBusImpl.class); private static final Comparator<MessageBusImpl> MESSAGE_BUS_COMPARATOR = (bus1, bus2) -> ArrayUtil.lexicographicCompare(bus1.myOrder, bus2.myOrder); @SuppressWarnings("SSBasedInspection") private final ThreadLocal<Queue<DeliveryJob>> myMessageQueue = createThreadLocalQueue(); /** * Root's order is empty * Child bus's order is its parent order plus one more element, an int that's bigger than that of all sibling buses that come before * Sorting by these vectors lexicographically gives DFS order */ private final int[] myOrder; private final ConcurrentMap<Topic<?>, Object> myPublishers = ContainerUtil.newConcurrentMap(); /** * This bus's subscribers */ private final ConcurrentMap<Topic<?>, List<MessageBusConnectionImpl>> mySubscribers = ContainerUtil.newConcurrentMap(); /** * Caches subscribers for this bus and its children or parent, depending on the topic's broadcast policy */ private final Map<Topic<?>, List<MessageBusConnectionImpl>> mySubscriberCache = ContainerUtil.newConcurrentMap(); private final List<MessageBusImpl> myChildBuses = ContainerUtil.createLockFreeCopyOnWriteList(); @NotNull private volatile Map<String, List<ListenerDescriptor>> myTopicClassToListenerClass = Collections.emptyMap(); private static final Object NA = new Object(); private final MessageBusImpl myParentBus; private final RootBus myRootBus; private final MessageBusOwner myOwner; private boolean myDisposed; private Disposable myConnectionDisposable; private MessageDeliveryListener myMessageDeliveryListener; private final Map<PluginDescriptor, MessageBusConnectionImpl> myLazyConnections; private boolean myIgnoreParentLazyListeners; public MessageBusImpl(@NotNull MessageBusOwner owner, @NotNull MessageBusImpl parentBus) { myOwner = owner; myConnectionDisposable = createConnectionDisposable(owner); myParentBus = parentBus; myRootBus = parentBus.myRootBus; synchronized (parentBus.myChildBuses) { myOrder = parentBus.nextOrder(); parentBus.myChildBuses.add(this); } LOG.assertTrue(parentBus.myChildBuses.contains(this)); myRootBus.clearSubscriberCache(); // only for project myLazyConnections = parentBus.myParentBus == null ? ConcurrentFactoryMap.createMap((key) -> connect()) : null; } @NotNull private static Disposable createConnectionDisposable(@NotNull MessageBusOwner owner) { // separate disposable must be used, because container will dispose bus connections in a separate step return Disposer.newDisposable(owner.toString()); } // root message bus constructor private MessageBusImpl(@NotNull MessageBusOwner owner) { myOwner = owner; myConnectionDisposable = createConnectionDisposable(owner); myOrder = ArrayUtil.EMPTY_INT_ARRAY; myRootBus = (RootBus)this; myLazyConnections = ConcurrentFactoryMap.createMap((key) -> connect()); myParentBus = null; } public void setIgnoreParentLazyListeners(boolean ignoreParentLazyListeners) { myIgnoreParentLazyListeners = ignoreParentLazyListeners; } /** * Must be a concurrent map, because remove operation may be concurrently performed (synchronized only per topic). */ @ApiStatus.Internal public void setLazyListeners(@NotNull ConcurrentMap<String, List<ListenerDescriptor>> map) { if (myTopicClassToListenerClass != Collections.<String, List<ListenerDescriptor>>emptyMap()) { myTopicClassToListenerClass.putAll(map); clearSubscriberCache(); } else { myTopicClassToListenerClass = map; } } @Override public MessageBus getParent() { return myParentBus; } @Override public String toString() { return super.toString() + "; owner=" + myOwner + (isDisposed() ? "; disposed" : ""); } /** * calculates {@link #myOrder} for the given child bus */ private int @NotNull [] nextOrder() { MessageBusImpl lastChild = ContainerUtil.getLastItem(myChildBuses); int lastChildIndex = lastChild == null ? 0 : ArrayUtil.getLastElement(lastChild.myOrder, 0); if (lastChildIndex == Integer.MAX_VALUE) { LOG.error("Too many child buses"); } return ArrayUtil.append(myOrder, lastChildIndex + 1); } private void onChildBusDisposed(@NotNull MessageBusImpl childBus) { boolean removed = myChildBuses.remove(childBus); Map<MessageBusImpl, Integer> map = myRootBus.myWaitingBuses.get(); if (map != null) map.remove(childBus); myRootBus.clearSubscriberCache(); LOG.assertTrue(removed); } private static final class DeliveryJob { DeliveryJob(@NotNull MessageBusConnectionImpl connection, @NotNull Message message) { this.connection = connection; this.message = message; } public final MessageBusConnectionImpl connection; public final Message message; @NonNls @Override public String toString() { return "{ DJob connection:" + connection + "; message: " + message + " }"; } } @Override @NotNull public MessageBusConnectionImpl connect() { return connect(myConnectionDisposable); } @Override @NotNull public MessageBusConnectionImpl connect(@NotNull Disposable parentDisposable) { checkNotDisposed(); MessageBusConnectionImpl connection = new MessageBusConnectionImpl(this); Disposer.register(parentDisposable, connection); return connection; } @Override @NotNull public <L> L syncPublisher(@NotNull Topic<L> topic) { checkNotDisposed(); @SuppressWarnings("unchecked") L publisher = (L)myPublishers.get(topic); if (publisher != null) { return publisher; } Class<L> listenerClass = topic.getListenerClass(); Object newInstance = Proxy.newProxyInstance(listenerClass.getClassLoader(), new Class[]{listenerClass}, createTopicHandler(topic)); Object prev = myPublishers.putIfAbsent(topic, newInstance); //noinspection unchecked return (L)(prev == null ? newInstance : prev); } private <L> void subscribeLazyListeners(@NotNull Topic<L> topic) { List<ListenerDescriptor> listenerDescriptors = myTopicClassToListenerClass.remove(topic.getListenerClass().getName()); if (listenerDescriptors != null) { MultiMap<PluginDescriptor, Object> listenerMap = new MultiMap<>(); for (ListenerDescriptor listenerDescriptor : listenerDescriptors) { try { listenerMap.putValue(listenerDescriptor.pluginDescriptor, myOwner.createListener(listenerDescriptor)); } catch (ExtensionNotApplicableException ignore) { } catch (ProcessCanceledException e) { throw e; } catch (Throwable e) { LOG.error("Cannot create listener", e); } } if (!listenerMap.isEmpty()) { for (Map.Entry<PluginDescriptor, Collection<Object>> entry : listenerMap.entrySet()) { myLazyConnections.get(entry.getKey()).subscribe(topic, entry.getValue()); } } } } @ApiStatus.Internal public void unsubscribePluginListeners(PluginDescriptor pluginDescriptor) { MessageBusConnectionImpl connection = myLazyConnections.remove(pluginDescriptor); if (connection != null) { Disposer.dispose(connection); } } @NotNull private <L> InvocationHandler createTopicHandler(@NotNull Topic<L> topic) { return (proxy, method, args) -> { if (method.getDeclaringClass().getName().equals("java.lang.Object")) { return EventDispatcher.handleObjectMethod(proxy, args, method.getName()); } sendMessage(new Message(topic, method, args)); return NA; }; } public final void disposeConnectionChildren() { Disposer.disposeChildren(myConnectionDisposable); } public final void disposeConnection() { Disposer.dispose(myConnectionDisposable); myConnectionDisposable = null; } @Override public final void dispose() { if (myDisposed) { LOG.error("Already disposed: " + this); } myDisposed = true; for (MessageBusImpl childBus : myChildBuses) { Disposer.dispose(childBus); } if (myConnectionDisposable != null) { Disposer.dispose(myConnectionDisposable); } Queue<DeliveryJob> jobs = myMessageQueue.get(); if (!jobs.isEmpty()) { LOG.error("Not delivered events in the queue: " + jobs); } myMessageQueue.remove(); if (myParentBus != null) { myParentBus.onChildBusDisposed(this); } else { myRootBus.myWaitingBuses.remove(); } } @Override public boolean isDisposed() { return myDisposed || myOwner.isDisposed(); } @Override public boolean hasUndeliveredEvents(@NotNull Topic<?> topic) { if (isDisposed() || !isDispatchingAnything()) { return false; } for (MessageBusConnectionImpl connection : getTopicSubscribers(topic)) { if (connection.containsMessage(topic)) { return true; } } return false; } private boolean isDispatchingAnything() { Map<MessageBusImpl, Integer> waitingBuses = myRootBus.myWaitingBuses.get(); return waitingBuses != null && !waitingBuses.isEmpty(); } private void checkNotDisposed() { if (isDisposed()) { LOG.error("Already disposed: " + this); } } @NotNull @TestOnly String getOwner() { return myOwner.toString(); } private void calcSubscribers(@NotNull Topic<?> topic, @NotNull List<? super MessageBusConnectionImpl> result, boolean subscribeLazyListeners) { if (subscribeLazyListeners) { subscribeLazyListeners(topic); } final List<MessageBusConnectionImpl> topicSubscribers = mySubscribers.get(topic); if (topicSubscribers != null) { result.addAll(topicSubscribers); } Topic.BroadcastDirection direction = topic.getBroadcastDirection(); if (direction == Topic.BroadcastDirection.TO_CHILDREN) { for (MessageBusImpl childBus : myChildBuses) { if (!childBus.isDisposed()) { childBus.calcSubscribers(topic, result, !childBus.myIgnoreParentLazyListeners); } } } if (direction == Topic.BroadcastDirection.TO_PARENT && myParentBus != null) { myParentBus.calcSubscribers(topic, result, true); } } private static void postMessage(@NotNull Message message, @NotNull List<MessageBusConnectionImpl> topicSubscribers) { for (MessageBusConnectionImpl subscriber : topicSubscribers) { MessageBusImpl bus = subscriber.getBus(); // maybe temporarily disposed (light test project) if (bus.isDisposed()) { continue; } bus.myMessageQueue.get().offer(new DeliveryJob(subscriber, message)); bus.notifyPendingJobChange(1); subscriber.scheduleMessageDelivery(message); } } @NotNull private List<MessageBusConnectionImpl> getTopicSubscribers(@NotNull Topic<?> topic) { List<MessageBusConnectionImpl> topicSubscribers = mySubscriberCache.get(topic); if (topicSubscribers == null) { topicSubscribers = new ArrayList<>(); calcSubscribers(topic, topicSubscribers, true); mySubscriberCache.put(topic, topicSubscribers); myRootBus.myClearedSubscribersCache = false; } return topicSubscribers; } private void notifyPendingJobChange(int delta) { ThreadLocal<SortedMap<MessageBusImpl, Integer>> ref = myRootBus.myWaitingBuses; SortedMap<MessageBusImpl, Integer> map = ref.get(); if (map == null) { ref.set(map = new TreeMap<>(MESSAGE_BUS_COMPARATOR)); } Integer countObject = map.get(this); int count = countObject == null ? 0 : countObject; int newCount = count + delta; if (newCount > 0) { checkNotDisposed(); map.put(this, newCount); } else if (newCount == 0) { map.remove(this); } else { LOG.error("Negative job count: " + this); } } private void sendMessage(@NotNull Message message) { pumpMessages(); List<MessageBusConnectionImpl> subscribers = getTopicSubscribers(message.getTopic()); if (!subscribers.isEmpty()) { postMessage(message, subscribers); pumpMessages(); } } private void pumpMessages() { checkNotDisposed(); Map<MessageBusImpl, Integer> map = myRootBus.myWaitingBuses.get(); if (map != null && !map.isEmpty()) { List<MessageBusImpl> liveBuses = new ArrayList<>(map.size()); for (MessageBusImpl bus : map.keySet()) { if (ensureAlive(map, bus)) { liveBuses.add(bus); } } if (!liveBuses.isEmpty()) { pumpWaitingBuses(liveBuses); } } } private static void pumpWaitingBuses(@NotNull List<? extends MessageBusImpl> buses) { List<Throwable> exceptions = null; for (MessageBusImpl bus : buses) { if (bus.isDisposed()) { continue; } exceptions = appendExceptions(exceptions, bus.doPumpMessages()); } rethrowExceptions(exceptions); } private static List<Throwable> appendExceptions(@Nullable List<Throwable> exceptions, @NotNull List<? extends Throwable> busExceptions) { if (!busExceptions.isEmpty()) { if (exceptions == null) exceptions = new ArrayList<>(busExceptions.size()); exceptions.addAll(busExceptions); } return exceptions; } private static void rethrowExceptions(@Nullable List<? extends Throwable> exceptions) { if (exceptions == null) return; ProcessCanceledException pce = ContainerUtil.findInstance(exceptions, ProcessCanceledException.class); if (pce != null) throw pce; CompoundRuntimeException.throwIfNotEmpty(exceptions); } private static boolean ensureAlive(@NotNull Map<MessageBusImpl, Integer> map, @NotNull MessageBusImpl bus) { if (bus.isDisposed()) { map.remove(bus); LOG.error("Accessing disposed message bus " + bus); return false; } return true; } @NotNull private List<Throwable> doPumpMessages() { Queue<DeliveryJob> queue = myMessageQueue.get(); List<Throwable> exceptions = Collections.emptyList(); do { DeliveryJob job = queue.poll(); if (job == null) break; notifyPendingJobChange(-1); try { job.connection.deliverMessage(job.message); } catch (Throwable e) { if (exceptions == Collections.<Throwable>emptyList()) { exceptions = new ArrayList<>(); } exceptions.add(e); } } while (true); return exceptions; } void notifyOnSubscription(@NotNull MessageBusConnectionImpl connection, @NotNull Topic<?> topic) { checkNotDisposed(); List<MessageBusConnectionImpl> topicSubscribers = mySubscribers.get(topic); if (topicSubscribers == null) { topicSubscribers = ContainerUtil.createLockFreeCopyOnWriteList(); topicSubscribers = ConcurrencyUtil.cacheOrGet(mySubscribers, topic, topicSubscribers); } topicSubscribers.add(connection); myRootBus.clearSubscriberCache(); } void clearSubscriberCache() { mySubscriberCache.clear(); for (MessageBusImpl bus : myChildBuses) { bus.clearSubscriberCache(); } } void notifyConnectionTerminated(@NotNull MessageBusConnectionImpl connection) { for (List<MessageBusConnectionImpl> topicSubscribers : mySubscribers.values()) { topicSubscribers.remove(connection); } if (isDisposed()) { return; } myRootBus.clearSubscriberCache(); final Iterator<DeliveryJob> i = myMessageQueue.get().iterator(); while (i.hasNext()) { final DeliveryJob job = i.next(); if (job.connection == connection) { i.remove(); notifyPendingJobChange(-1); } } } void deliverSingleMessage() { checkNotDisposed(); final DeliveryJob job = myMessageQueue.get().poll(); if (job == null) return; notifyPendingJobChange(-1); job.connection.deliverMessage(job.message); } @NotNull static <T> ThreadLocal<Queue<T>> createThreadLocalQueue() { return ThreadLocal.withInitial(ArrayDeque::new); } @ApiStatus.Internal public void setMessageDeliveryListener(@Nullable MessageDeliveryListener listener) { if (myMessageDeliveryListener != null && listener != null) { throw new IllegalStateException("Already set: " + myMessageDeliveryListener); } myMessageDeliveryListener = listener; } void invokeListener(@NotNull Message message, Object handler) throws IllegalAccessException, InvocationTargetException { Method method = message.getListenerMethod(); MessageDeliveryListener listener = myMessageDeliveryListener; if (listener == null) { method.invoke(handler, message.getArgs()); return; } long startTime = System.nanoTime(); method.invoke(handler, message.getArgs()); listener.messageDelivered(message.getTopic(), method.getName(), handler, System.nanoTime() - startTime); } static final class RootBus extends MessageBusImpl { /** * Holds the counts of pending messages for all message buses in the hierarchy * This field is null for non-root buses * The map's keys are sorted by {@link #myOrder} * <p> * Used to avoid traversing the whole hierarchy when there are no messages to be sent in most of it */ private final ThreadLocal<SortedMap<MessageBusImpl, Integer>> myWaitingBuses = new ThreadLocal<>(); private volatile boolean myClearedSubscribersCache; @Override void clearSubscriberCache() { if (myClearedSubscribersCache) return; super.clearSubscriberCache(); myClearedSubscribersCache = true; } RootBus(@NotNull MessageBusOwner owner) { super(owner); } } }
platform/core-api/src/com/intellij/util/messages/impl/MessageBusImpl.java
// Copyright 2000-2020 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.util.messages.impl; import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.ExtensionNotApplicableException; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.util.Disposer; import com.intellij.util.ArrayUtil; import com.intellij.util.ConcurrencyUtil; import com.intellij.util.EventDispatcher; import com.intellij.util.containers.ConcurrentFactoryMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import com.intellij.util.lang.CompoundRuntimeException; import com.intellij.util.messages.ListenerDescriptor; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusOwner; import com.intellij.util.messages.Topic; import org.jetbrains.annotations.*; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.*; import java.util.concurrent.ConcurrentMap; public class MessageBusImpl implements MessageBus { private static final Logger LOG = Logger.getInstance(MessageBusImpl.class); private static final Comparator<MessageBusImpl> MESSAGE_BUS_COMPARATOR = (bus1, bus2) -> ArrayUtil.lexicographicCompare(bus1.myOrder, bus2.myOrder); @SuppressWarnings("SSBasedInspection") private final ThreadLocal<Queue<DeliveryJob>> myMessageQueue = createThreadLocalQueue(); /** * Root's order is empty * Child bus's order is its parent order plus one more element, an int that's bigger than that of all sibling buses that come before * Sorting by these vectors lexicographically gives DFS order */ private final int[] myOrder; private final ConcurrentMap<Topic<?>, Object> myPublishers = ContainerUtil.newConcurrentMap(); /** * This bus's subscribers */ private final ConcurrentMap<Topic<?>, List<MessageBusConnectionImpl>> mySubscribers = ContainerUtil.newConcurrentMap(); /** * Caches subscribers for this bus and its children or parent, depending on the topic's broadcast policy */ private final Map<Topic<?>, List<MessageBusConnectionImpl>> mySubscriberCache = ContainerUtil.newConcurrentMap(); private final List<MessageBusImpl> myChildBuses = ContainerUtil.createLockFreeCopyOnWriteList(); @NotNull private volatile Map<String, List<ListenerDescriptor>> myTopicClassToListenerClass = Collections.emptyMap(); private static final Object NA = new Object(); private final MessageBusImpl myParentBus; private final RootBus myRootBus; private final MessageBusOwner myOwner; private boolean myDisposed; private Disposable myConnectionDisposable; private MessageDeliveryListener myMessageDeliveryListener; private final Map<PluginDescriptor, MessageBusConnectionImpl> myLazyConnections; private boolean myIgnoreParentLazyListeners; public MessageBusImpl(@NotNull MessageBusOwner owner, @NotNull MessageBusImpl parentBus) { myOwner = owner; myConnectionDisposable = createConnectionDisposable(owner); myParentBus = parentBus; myRootBus = parentBus.myRootBus; synchronized (parentBus.myChildBuses) { myOrder = parentBus.nextOrder(); parentBus.myChildBuses.add(this); } LOG.assertTrue(parentBus.myChildBuses.contains(this)); myRootBus.clearSubscriberCache(); // only for project myLazyConnections = parentBus.myParentBus == null ? ConcurrentFactoryMap.createMap((key) -> connect()) : null; } @NotNull private static Disposable createConnectionDisposable(@NotNull MessageBusOwner owner) { // separate disposable must be used, because container will dispose bus connections in a separate step return Disposer.newDisposable(owner.toString()); } // root message bus constructor private MessageBusImpl(@NotNull MessageBusOwner owner) { myOwner = owner; myConnectionDisposable = createConnectionDisposable(owner); myOrder = ArrayUtil.EMPTY_INT_ARRAY; myRootBus = (RootBus)this; myLazyConnections = ConcurrentFactoryMap.createMap((key) -> connect()); myParentBus = null; } public void setIgnoreParentLazyListeners(boolean ignoreParentLazyListeners) { myIgnoreParentLazyListeners = ignoreParentLazyListeners; } /** * Must be a concurrent map, because remove operation may be concurrently performed (synchronized only per topic). */ @ApiStatus.Internal public void setLazyListeners(@NotNull ConcurrentMap<String, List<ListenerDescriptor>> map) { if (myTopicClassToListenerClass != Collections.<String, List<ListenerDescriptor>>emptyMap()) { myTopicClassToListenerClass.putAll(map); clearSubscriberCache(); } else { myTopicClassToListenerClass = map; } } @Override public MessageBus getParent() { return myParentBus; } @Override public String toString() { return super.toString() + "; owner=" + myOwner + (isDisposed() ? "; disposed" : ""); } /** * calculates {@link #myOrder} for the given child bus */ private int @NotNull [] nextOrder() { MessageBusImpl lastChild = ContainerUtil.getLastItem(myChildBuses); int lastChildIndex = lastChild == null ? 0 : ArrayUtil.getLastElement(lastChild.myOrder, 0); if (lastChildIndex == Integer.MAX_VALUE) { LOG.error("Too many child buses"); } return ArrayUtil.append(myOrder, lastChildIndex + 1); } private void onChildBusDisposed(@NotNull MessageBusImpl childBus) { boolean removed = myChildBuses.remove(childBus); Map<MessageBusImpl, Integer> map = myRootBus.myWaitingBuses.get(); if (map != null) map.remove(childBus); myRootBus.clearSubscriberCache(); LOG.assertTrue(removed); } private static final class DeliveryJob { DeliveryJob(@NotNull MessageBusConnectionImpl connection, @NotNull Message message) { this.connection = connection; this.message = message; } public final MessageBusConnectionImpl connection; public final Message message; @NonNls @Override public String toString() { return "{ DJob connection:" + connection + "; message: " + message + " }"; } } @Override @NotNull public MessageBusConnectionImpl connect() { return connect(myConnectionDisposable); } @Override @NotNull public MessageBusConnectionImpl connect(@NotNull Disposable parentDisposable) { checkNotDisposed(); MessageBusConnectionImpl connection = new MessageBusConnectionImpl(this); Disposer.register(parentDisposable, connection); return connection; } @Override @NotNull public <L> L syncPublisher(@NotNull Topic<L> topic) { checkNotDisposed(); @SuppressWarnings("unchecked") L publisher = (L)myPublishers.get(topic); if (publisher != null) { return publisher; } Class<L> listenerClass = topic.getListenerClass(); Object newInstance = Proxy.newProxyInstance(listenerClass.getClassLoader(), new Class[]{listenerClass}, createTopicHandler(topic)); Object prev = myPublishers.putIfAbsent(topic, newInstance); //noinspection unchecked return (L)(prev == null ? newInstance : prev); } private <L> void subscribeLazyListeners(@NotNull Topic<L> topic) { List<ListenerDescriptor> listenerDescriptors = myTopicClassToListenerClass.remove(topic.getListenerClass().getName()); if (listenerDescriptors != null) { MultiMap<PluginDescriptor, Object> listenerMap = new MultiMap<>(); for (ListenerDescriptor listenerDescriptor : listenerDescriptors) { try { listenerMap.putValue(listenerDescriptor.pluginDescriptor, myOwner.createListener(listenerDescriptor)); } catch (ExtensionNotApplicableException ignore) { } catch (ProcessCanceledException e) { throw e; } catch (Throwable e) { LOG.error("Cannot create listener", e); } } if (!listenerMap.isEmpty()) { for (Map.Entry<PluginDescriptor, Collection<Object>> entry : listenerMap.entrySet()) { myLazyConnections.get(entry.getKey()).subscribe(topic, entry.getValue()); } } } } @ApiStatus.Internal public void unsubscribePluginListeners(PluginDescriptor pluginDescriptor) { MessageBusConnectionImpl connection = myLazyConnections.remove(pluginDescriptor); if (connection != null) { Disposer.dispose(connection); } } @NotNull private <L> InvocationHandler createTopicHandler(@NotNull Topic<L> topic) { return (proxy, method, args) -> { if (method.getDeclaringClass().getName().equals("java.lang.Object")) { return EventDispatcher.handleObjectMethod(proxy, args, method.getName()); } sendMessage(new Message(topic, method, args)); return NA; }; } public final void disposeConnectionChildren() { Disposer.disposeChildren(myConnectionDisposable); } public final void disposeConnection() { Disposer.dispose(myConnectionDisposable); myConnectionDisposable = null; } @Override public final void dispose() { if (myDisposed) { LOG.error("Already disposed: " + this); } myDisposed = true; for (MessageBusImpl childBus : myChildBuses) { Disposer.dispose(childBus); } if (myConnectionDisposable != null) { Disposer.dispose(myConnectionDisposable); } Queue<DeliveryJob> jobs = myMessageQueue.get(); if (!jobs.isEmpty()) { LOG.error("Not delivered events in the queue: " + jobs); } myMessageQueue.remove(); if (myParentBus != null) { myParentBus.onChildBusDisposed(this); } else { myRootBus.myWaitingBuses.remove(); } } @Override public boolean isDisposed() { return myDisposed || myOwner.isDisposed(); } @Override public boolean hasUndeliveredEvents(@NotNull Topic<?> topic) { if (isDisposed() || !isDispatchingAnything()) { return false; } for (MessageBusConnectionImpl connection : getTopicSubscribers(topic)) { if (connection.containsMessage(topic)) { return true; } } return false; } private boolean isDispatchingAnything() { Map<MessageBusImpl, Integer> waitingBuses = myRootBus.myWaitingBuses.get(); return waitingBuses != null && !waitingBuses.isEmpty(); } private void checkNotDisposed() { if (isDisposed()) { LOG.error("Already disposed: " + this); } } @NotNull @TestOnly String getOwner() { return myOwner.toString(); } private void calcSubscribers(@NotNull Topic<?> topic, @NotNull List<? super MessageBusConnectionImpl> result, boolean subscribeLazyListeners) { if (subscribeLazyListeners) { subscribeLazyListeners(topic); } final List<MessageBusConnectionImpl> topicSubscribers = mySubscribers.get(topic); if (topicSubscribers != null) { result.addAll(topicSubscribers); } Topic.BroadcastDirection direction = topic.getBroadcastDirection(); if (direction == Topic.BroadcastDirection.TO_CHILDREN) { for (MessageBusImpl childBus : myChildBuses) { if (!childBus.isDisposed()) { childBus.calcSubscribers(topic, result, !childBus.myIgnoreParentLazyListeners); } } } if (direction == Topic.BroadcastDirection.TO_PARENT && myParentBus != null) { myParentBus.calcSubscribers(topic, result, true); } } private void postMessage(@NotNull Message message) { checkNotDisposed(); List<MessageBusConnectionImpl> topicSubscribers = getTopicSubscribers(message.getTopic()); if (topicSubscribers.isEmpty()) { return; } for (MessageBusConnectionImpl subscriber : topicSubscribers) { MessageBusImpl bus = subscriber.getBus(); // maybe temporarily disposed (light test project) if (bus.isDisposed()) { continue; } bus.myMessageQueue.get().offer(new DeliveryJob(subscriber, message)); bus.notifyPendingJobChange(1); subscriber.scheduleMessageDelivery(message); } } @NotNull private List<MessageBusConnectionImpl> getTopicSubscribers(@NotNull Topic<?> topic) { List<MessageBusConnectionImpl> topicSubscribers = mySubscriberCache.get(topic); if (topicSubscribers == null) { topicSubscribers = new ArrayList<>(); calcSubscribers(topic, topicSubscribers, true); mySubscriberCache.put(topic, topicSubscribers); myRootBus.myClearedSubscribersCache = false; } return topicSubscribers; } private void notifyPendingJobChange(int delta) { ThreadLocal<SortedMap<MessageBusImpl, Integer>> ref = myRootBus.myWaitingBuses; SortedMap<MessageBusImpl, Integer> map = ref.get(); if (map == null) { ref.set(map = new TreeMap<>(MESSAGE_BUS_COMPARATOR)); } Integer countObject = map.get(this); int count = countObject == null ? 0 : countObject; int newCount = count + delta; if (newCount > 0) { checkNotDisposed(); map.put(this, newCount); } else if (newCount == 0) { map.remove(this); } else { LOG.error("Negative job count: " + this); } } private void sendMessage(@NotNull Message message) { pumpMessages(); postMessage(message); pumpMessages(); } private void pumpMessages() { checkNotDisposed(); Map<MessageBusImpl, Integer> map = myRootBus.myWaitingBuses.get(); if (map != null && !map.isEmpty()) { List<MessageBusImpl> liveBuses = new ArrayList<>(map.size()); for (MessageBusImpl bus : map.keySet()) { if (ensureAlive(map, bus)) { liveBuses.add(bus); } } if (!liveBuses.isEmpty()) { pumpWaitingBuses(liveBuses); } } } private static void pumpWaitingBuses(@NotNull List<? extends MessageBusImpl> buses) { List<Throwable> exceptions = null; for (MessageBusImpl bus : buses) { if (bus.isDisposed()) { continue; } exceptions = appendExceptions(exceptions, bus.doPumpMessages()); } rethrowExceptions(exceptions); } private static List<Throwable> appendExceptions(@Nullable List<Throwable> exceptions, @NotNull List<? extends Throwable> busExceptions) { if (!busExceptions.isEmpty()) { if (exceptions == null) exceptions = new ArrayList<>(busExceptions.size()); exceptions.addAll(busExceptions); } return exceptions; } private static void rethrowExceptions(@Nullable List<? extends Throwable> exceptions) { if (exceptions == null) return; ProcessCanceledException pce = ContainerUtil.findInstance(exceptions, ProcessCanceledException.class); if (pce != null) throw pce; CompoundRuntimeException.throwIfNotEmpty(exceptions); } private static boolean ensureAlive(@NotNull Map<MessageBusImpl, Integer> map, @NotNull MessageBusImpl bus) { if (bus.isDisposed()) { map.remove(bus); LOG.error("Accessing disposed message bus " + bus); return false; } return true; } @NotNull private List<Throwable> doPumpMessages() { Queue<DeliveryJob> queue = myMessageQueue.get(); List<Throwable> exceptions = Collections.emptyList(); do { DeliveryJob job = queue.poll(); if (job == null) break; notifyPendingJobChange(-1); try { job.connection.deliverMessage(job.message); } catch (Throwable e) { if (exceptions == Collections.<Throwable>emptyList()) { exceptions = new ArrayList<>(); } exceptions.add(e); } } while (true); return exceptions; } void notifyOnSubscription(@NotNull MessageBusConnectionImpl connection, @NotNull Topic<?> topic) { checkNotDisposed(); List<MessageBusConnectionImpl> topicSubscribers = mySubscribers.get(topic); if (topicSubscribers == null) { topicSubscribers = ContainerUtil.createLockFreeCopyOnWriteList(); topicSubscribers = ConcurrencyUtil.cacheOrGet(mySubscribers, topic, topicSubscribers); } topicSubscribers.add(connection); myRootBus.clearSubscriberCache(); } void clearSubscriberCache() { mySubscriberCache.clear(); for (MessageBusImpl bus : myChildBuses) { bus.clearSubscriberCache(); } } void notifyConnectionTerminated(@NotNull MessageBusConnectionImpl connection) { for (List<MessageBusConnectionImpl> topicSubscribers : mySubscribers.values()) { topicSubscribers.remove(connection); } if (isDisposed()) { return; } myRootBus.clearSubscriberCache(); final Iterator<DeliveryJob> i = myMessageQueue.get().iterator(); while (i.hasNext()) { final DeliveryJob job = i.next(); if (job.connection == connection) { i.remove(); notifyPendingJobChange(-1); } } } void deliverSingleMessage() { checkNotDisposed(); final DeliveryJob job = myMessageQueue.get().poll(); if (job == null) return; notifyPendingJobChange(-1); job.connection.deliverMessage(job.message); } @NotNull static <T> ThreadLocal<Queue<T>> createThreadLocalQueue() { return ThreadLocal.withInitial(ArrayDeque::new); } @ApiStatus.Internal public void setMessageDeliveryListener(@Nullable MessageDeliveryListener listener) { if (myMessageDeliveryListener != null && listener != null) { throw new IllegalStateException("Already set: " + myMessageDeliveryListener); } myMessageDeliveryListener = listener; } void invokeListener(@NotNull Message message, Object handler) throws IllegalAccessException, InvocationTargetException { Method method = message.getListenerMethod(); MessageDeliveryListener listener = myMessageDeliveryListener; if (listener == null) { method.invoke(handler, message.getArgs()); return; } long startTime = System.nanoTime(); method.invoke(handler, message.getArgs()); listener.messageDelivered(message.getTopic(), method.getName(), handler, System.nanoTime() - startTime); } static final class RootBus extends MessageBusImpl { /** * Holds the counts of pending messages for all message buses in the hierarchy * This field is null for non-root buses * The map's keys are sorted by {@link #myOrder} * <p> * Used to avoid traversing the whole hierarchy when there are no messages to be sent in most of it */ private final ThreadLocal<SortedMap<MessageBusImpl, Integer>> myWaitingBuses = new ThreadLocal<>(); private volatile boolean myClearedSubscribersCache; @Override void clearSubscriberCache() { if (myClearedSubscribersCache) return; super.clearSubscriberCache(); myClearedSubscribersCache = true; } RootBus(@NotNull MessageBusOwner owner) { super(owner); } } }
MessageBusImpl: reduce the invocation counts of postMessage/pumpMessages for JIT-friendliness (IDEA-233084) GitOrigin-RevId: e596ace8b532686c961def1688fc92abd649adba
platform/core-api/src/com/intellij/util/messages/impl/MessageBusImpl.java
MessageBusImpl: reduce the invocation counts of postMessage/pumpMessages for JIT-friendliness (IDEA-233084)
<ide><path>latform/core-api/src/com/intellij/util/messages/impl/MessageBusImpl.java <ide> } <ide> } <ide> <del> private void postMessage(@NotNull Message message) { <del> checkNotDisposed(); <del> List<MessageBusConnectionImpl> topicSubscribers = getTopicSubscribers(message.getTopic()); <del> if (topicSubscribers.isEmpty()) { <del> return; <del> } <del> <add> private static void postMessage(@NotNull Message message, @NotNull List<MessageBusConnectionImpl> topicSubscribers) { <ide> for (MessageBusConnectionImpl subscriber : topicSubscribers) { <ide> MessageBusImpl bus = subscriber.getBus(); <ide> // maybe temporarily disposed (light test project) <ide> <ide> private void sendMessage(@NotNull Message message) { <ide> pumpMessages(); <del> postMessage(message); <del> pumpMessages(); <add> <add> List<MessageBusConnectionImpl> subscribers = getTopicSubscribers(message.getTopic()); <add> if (!subscribers.isEmpty()) { <add> postMessage(message, subscribers); <add> pumpMessages(); <add> } <ide> } <ide> <ide> private void pumpMessages() {
JavaScript
isc
79b1cf1468cb66c713d9410d9231f72b124de548
0
AntonKhorev/crnx-ode-properties,AntonKhorev/crnx-ode-properties
'use strict' const TheadLayout=require('./thead-layout') const data=require('./data') $(function(){ $('.crnx-ode-properties').each(function(){ const $container=$(this) const dag={}, idag={} const selectedNodes={} for (let id in data) { selectedNodes[id]=true dag[id]=data[id].parents idag[id]={} } for (let id in data) { for (let pid in dag[id]) { idag[pid][id]=true } } let theadLayout=new TheadLayout(dag,selectedNodes) const breadthWalk=(graph,id)=>{ const result=[] const visited={} const queue=[id] while (queue.length>0) { id=queue.shift() if (visited[id]) { continue } visited[id]=true if (!selectedNodes[id]) { result.push(id) } queue.push(...Object.keys(graph[id]).sort()) } return result } const writeButton=(text,tip)=>{ const $button=$(`<button type='button'><span>${text}</span></button>`) if (tip!==undefined) { $button.attr('title',tip) } return $button } const writeTable=()=>{ let $attachedMenu, $attachedToButton, attachedDirection, attachTimeoutId const deleteNode=id=>{ delete selectedNodes[id] theadLayout=new TheadLayout(dag,selectedNodes) writeTable() } const addNode=id=>{ selectedNodes[id]=true theadLayout=new TheadLayout(dag,selectedNodes) writeTable() } const setCellClasses=($cell,cell)=>{ ;['b','t','bt','rl','rt','bl'].forEach(dir=>{ if (cell[dir]) { $cell.addClass(dir) } }) } const writeTheadButton=($cell,text,tip,dir,nodes)=>{ const keyCodeEnter=13 const keyCodeSpace=32 const keyCodeUp=38 const keyCodeDown=40 const $button=writeButton(text,tip).addClass(dir).click(function(){ const removeAttachedMenu=()=>{ $attachedToButton.removeClass('attached-t attached-b') $attachedMenu.remove() clearTimeout(attachTimeoutId) $attachedToButton=undefined $attachedMenu=undefined attachedDirection=undefined attachTimeoutId=undefined } const startAttachingMenu=()=>{ $attachedToButton=$button $attachedMenu=$("<ul>").append(nodes.map( id=>$("<li tabindex='0'>"+data[id].name+"</li>").click(function(){ addNode(id) }).keydown(function(ev){ if (!attachedDirection) return // not yet decided on attach direction (this can't happen) if (ev.keyCode==keyCodeUp) { const $toFocus=$(this).prev() if ($toFocus.length) { $toFocus.focus() } else if (attachedDirection=='b') { $button.focus() } } else if (ev.keyCode==keyCodeDown) { const $toFocus=$(this).next() if ($toFocus.length) { $toFocus.focus() } else if (attachedDirection=='t') { $button.focus() } } else if (ev.keyCode==keyCodeEnter || ev.keyCode==keyCodeSpace) { addNode(id) } }) )) $cell.append($attachedMenu) attachTimeoutId=setTimeout(()=>{ // can calculate height only after it's displayed const mh=$attachedMenu.outerHeight() const mo=$attachedMenu.offset() const bh=$button.outerHeight() const bo=$button.offset() let t=bo.top-mh+1 if (dir!='t' || t<0) { // want below or doesn't fit to screen above the button t=bo.top+bh-1 attachedDirection='b' } else { $attachedMenu.insertBefore($button) attachedDirection='t' } $attachedMenu.offset({ top: t, left: mo.left, }) $attachedMenu.addClass('attached') $button.addClass('attached-'+attachedDirection) },0) } if (!$button.is($attachedToButton)) { if ($attachedToButton) { removeAttachedMenu() // close menu opened elsewhere } startAttachingMenu() } else { removeAttachedMenu() // close menu here } }).keydown(function(ev){ if ($button.is($attachedToButton)) { if (ev.keyCode==keyCodeUp && attachedDirection=='t') { $attachedMenu.children().last().focus() } else if (ev.keyCode==keyCodeDown && attachedDirection=='b') { $attachedMenu.children().first().focus() } } }) return $button } const writeTheadCell=cell=>{ const $cell=$("<th>") setCellClasses($cell,cell) if (cell.node!==undefined) { $cell.append(data[cell.node].name) const parents=breadthWalk(dag,cell.node).reverse() let $parents if (parents.length>0) { $cell.append( " ", writeTheadButton($cell,"Add parent","Add one of parents of this node",'t',parents) ) } const children=breadthWalk(idag,cell.node) if (children.length>0) { $cell.append( " ", writeTheadButton($cell,"Add child","Add one of children of this node",'b',children) ) } } return $cell } const writeThead=()=>{ const $thead=$("<thead>") for (let i=0;i<theadLayout.nodeLayers.length;i++) { $thead.append( $("<tr class='nodes'>").append( theadLayout.nodeLayers[i].map(writeTheadCell) ) ) if (i<theadLayout.arcLayers.length) { $thead.append( theadLayout.arcLayers[i].map(row=>$("<tr class='arcs'>").append( row.map(cell=>{ const $cell=$("<th>") setCellClasses($cell,cell) return $cell }) )) ) } } return $thead } const writeTfoot=()=>{ if (theadLayout.columns.length<=1) { return $() } return $("<tfoot>").append( $("<tr>").append( theadLayout.columns.map(id=>$("<td>").append( writeButton("Delete","Delete this node").click(function(){ deleteNode(id) }) )) ) ) } $container.empty().append( $("<table>").append( writeThead(), writeTfoot(), $("<tbody>").append( $("<tr>").append( theadLayout.columns.map(id=>"<td>$$"+data[id].equation+"$$</td>") ) ) ) ) MathJax.Hub.Queue(["Typeset",MathJax.Hub]); } writeTable() }) })
src/main.js
'use strict' const TheadLayout=require('./thead-layout') const data=require('./data') $(function(){ $('.crnx-ode-properties').each(function(){ const $container=$(this) const dag={}, idag={} const selectedNodes={} for (let id in data) { selectedNodes[id]=true dag[id]=data[id].parents idag[id]={} } for (let id in data) { for (let pid in dag[id]) { idag[pid][id]=true } } let theadLayout=new TheadLayout(dag,selectedNodes) const breadthWalk=(graph,id)=>{ const result=[] const visited={} const queue=[id] while (queue.length>0) { id=queue.shift() if (visited[id]) { continue } visited[id]=true if (!selectedNodes[id]) { result.push(id) } queue.push(...Object.keys(graph[id]).sort()) } return result } const writeButton=(text,tip)=>{ const $button=$(`<button type='button'><span>${text}</span></button>`) if (tip!==undefined) { $button.attr('title',tip) } return $button } const writeTable=()=>{ const deleteNode=id=>{ delete selectedNodes[id] theadLayout=new TheadLayout(dag,selectedNodes) writeTable() } const addNode=id=>{ selectedNodes[id]=true theadLayout=new TheadLayout(dag,selectedNodes) writeTable() } const setCellClasses=($cell,cell)=>{ ;['b','t','bt','rl','rt','bl'].forEach(dir=>{ if (cell[dir]) { $cell.addClass(dir) } }) } const writeTheadButton=($cell,text,tip,dir,nodes)=>{ const keyCodeEnter=13 const keyCodeSpace=32 const keyCodeUp=38 const keyCodeDown=40 let $nodes let attached const $button=writeButton(text,tip).addClass(dir).click(function(){ if (!$nodes) { $nodes=$("<ul>").append(nodes.map( id=>$("<li tabindex='0'>"+data[id].name+"</li>").click(function(){ addNode(id) }).keydown(function(ev){ if (!attached) return if (ev.keyCode==keyCodeUp) { const $toFocus=$(this).prev() if ($toFocus.length) { $toFocus.focus() } else if (attached=='b') { $button.focus() } } else if (ev.keyCode==keyCodeDown) { const $toFocus=$(this).next() if ($toFocus.length) { $toFocus.focus() } else if (attached=='t') { $button.focus() } } else if (ev.keyCode==keyCodeEnter || ev.keyCode==keyCodeSpace) { addNode(id) } }) )) $cell.append($nodes) setTimeout(()=>{ // can calculate height only after it's displayed const nh=$nodes.outerHeight() const no=$nodes.offset() const bh=$button.outerHeight() const bo=$button.offset() let t=bo.top-nh+1 if (dir!='t' || t<0) { // want below or doesn't fit to screen above the button t=bo.top+bh-1 attached='b' } else { $nodes.insertBefore($button) attached='t' } $nodes.offset({ top: t, left: no.left, }) $nodes.addClass('attached') $button.addClass('attached-'+attached) },0) } else { $button.removeClass('attached-'+attached) $nodes.remove() $nodes=undefined attached=undefined } }).keydown(function(ev){ if (!attached) return if (ev.keyCode==keyCodeUp && attached=='t') { $nodes.children().last().focus() } else if (ev.keyCode==keyCodeDown && attached=='b') { $nodes.children().first().focus() } }) return $button } const writeTheadCell=cell=>{ const $cell=$("<th>") setCellClasses($cell,cell) if (cell.node!==undefined) { $cell.append(data[cell.node].name) const parents=breadthWalk(dag,cell.node).reverse() let $parents if (parents.length>0) { $cell.append( " ", writeTheadButton($cell,"Add parent","Add one of parents of this node",'t',parents) ) } const children=breadthWalk(idag,cell.node) if (children.length>0) { $cell.append( " ", writeTheadButton($cell,"Add child","Add one of children of this node",'b',children) ) } } return $cell } const writeThead=()=>{ const $thead=$("<thead>") for (let i=0;i<theadLayout.nodeLayers.length;i++) { $thead.append( $("<tr class='nodes'>").append( theadLayout.nodeLayers[i].map(writeTheadCell) ) ) if (i<theadLayout.arcLayers.length) { $thead.append( theadLayout.arcLayers[i].map(row=>$("<tr class='arcs'>").append( row.map(cell=>{ const $cell=$("<th>") setCellClasses($cell,cell) return $cell }) )) ) } } return $thead } const writeTfoot=()=>{ if (theadLayout.columns.length<=1) { return $() } return $("<tfoot>").append( $("<tr>").append( theadLayout.columns.map(id=>$("<td>").append( writeButton("Delete","Delete this node").click(function(){ deleteNode(id) }) )) ) ) } $container.empty().append( $("<table>").append( writeThead(), writeTfoot(), $("<tbody>").append( $("<tr>").append( theadLayout.columns.map(id=>"<td>$$"+data[id].equation+"$$</td>") ) ) ) ) MathJax.Hub.Queue(["Typeset",MathJax.Hub]); } writeTable() }) })
allow only one child/parent menu to be opened
src/main.js
allow only one child/parent menu to be opened
<ide><path>rc/main.js <ide> return $button <ide> } <ide> const writeTable=()=>{ <add> let $attachedMenu, $attachedToButton, attachedDirection, attachTimeoutId <ide> const deleteNode=id=>{ <ide> delete selectedNodes[id] <ide> theadLayout=new TheadLayout(dag,selectedNodes) <ide> const keyCodeSpace=32 <ide> const keyCodeUp=38 <ide> const keyCodeDown=40 <del> let $nodes <del> let attached <ide> const $button=writeButton(text,tip).addClass(dir).click(function(){ <del> if (!$nodes) { <del> $nodes=$("<ul>").append(nodes.map( <add> const removeAttachedMenu=()=>{ <add> $attachedToButton.removeClass('attached-t attached-b') <add> $attachedMenu.remove() <add> clearTimeout(attachTimeoutId) <add> $attachedToButton=undefined <add> $attachedMenu=undefined <add> attachedDirection=undefined <add> attachTimeoutId=undefined <add> } <add> const startAttachingMenu=()=>{ <add> $attachedToButton=$button <add> $attachedMenu=$("<ul>").append(nodes.map( <ide> id=>$("<li tabindex='0'>"+data[id].name+"</li>").click(function(){ <ide> addNode(id) <ide> }).keydown(function(ev){ <del> if (!attached) return <add> if (!attachedDirection) return // not yet decided on attach direction (this can't happen) <ide> if (ev.keyCode==keyCodeUp) { <ide> const $toFocus=$(this).prev() <ide> if ($toFocus.length) { <ide> $toFocus.focus() <del> } else if (attached=='b') { <add> } else if (attachedDirection=='b') { <ide> $button.focus() <ide> } <ide> } else if (ev.keyCode==keyCodeDown) { <ide> const $toFocus=$(this).next() <ide> if ($toFocus.length) { <ide> $toFocus.focus() <del> } else if (attached=='t') { <add> } else if (attachedDirection=='t') { <ide> $button.focus() <ide> } <ide> } else if (ev.keyCode==keyCodeEnter || ev.keyCode==keyCodeSpace) { <ide> } <ide> }) <ide> )) <del> $cell.append($nodes) <del> setTimeout(()=>{ // can calculate height only after it's displayed <del> const nh=$nodes.outerHeight() <del> const no=$nodes.offset() <add> $cell.append($attachedMenu) <add> attachTimeoutId=setTimeout(()=>{ // can calculate height only after it's displayed <add> const mh=$attachedMenu.outerHeight() <add> const mo=$attachedMenu.offset() <ide> const bh=$button.outerHeight() <ide> const bo=$button.offset() <del> let t=bo.top-nh+1 <add> let t=bo.top-mh+1 <ide> if (dir!='t' || t<0) { // want below or doesn't fit to screen above the button <ide> t=bo.top+bh-1 <del> attached='b' <add> attachedDirection='b' <ide> } else { <del> $nodes.insertBefore($button) <del> attached='t' <add> $attachedMenu.insertBefore($button) <add> attachedDirection='t' <ide> } <del> $nodes.offset({ <add> $attachedMenu.offset({ <ide> top: t, <del> left: no.left, <add> left: mo.left, <ide> }) <del> $nodes.addClass('attached') <del> $button.addClass('attached-'+attached) <add> $attachedMenu.addClass('attached') <add> $button.addClass('attached-'+attachedDirection) <ide> },0) <add> } <add> if (!$button.is($attachedToButton)) { <add> if ($attachedToButton) { <add> removeAttachedMenu() // close menu opened elsewhere <add> } <add> startAttachingMenu() <ide> } else { <del> $button.removeClass('attached-'+attached) <del> $nodes.remove() <del> $nodes=undefined <del> attached=undefined <add> removeAttachedMenu() // close menu here <ide> } <ide> }).keydown(function(ev){ <del> if (!attached) return <del> if (ev.keyCode==keyCodeUp && attached=='t') { <del> $nodes.children().last().focus() <del> } else if (ev.keyCode==keyCodeDown && attached=='b') { <del> $nodes.children().first().focus() <add> if ($button.is($attachedToButton)) { <add> if (ev.keyCode==keyCodeUp && attachedDirection=='t') { <add> $attachedMenu.children().last().focus() <add> } else if (ev.keyCode==keyCodeDown && attachedDirection=='b') { <add> $attachedMenu.children().first().focus() <add> } <ide> } <ide> }) <ide> return $button
Java
mit
06678924c332dcf40f9f5a03ae5f98fc122f1969
0
Innovimax-SARL/mix-them
package innovimax.mixthem.operation; import innovimax.mixthem.MixException; import java.util.List; interface ILineOperation extends IOperation { /** * Processes operation and set new result in the LineResult parameter. * @param lineRange The range of lines to mix * @param result The previous operation result * @return The result of the operation (maybe null) * @throws MixException - If an mixing error occurs * @see innovimax.mixthem.operation.LineResult */ void process(List<String> lineRange, LineResult result) throws MixException; /** * Is mixing operation is possible on line range? * @param lineRange The range of lines to mix * @return True if mixing operation is possible */ boolean mixable(List<String> lineRange); }
src/main/java/innovimax/mixthem/operation/ILineOperation.java
package innovimax.mixthem.operation; import innovimax.mixthem.MixException; import java.util.List; interface ILineOperation extends IOperation { /** * Processes operation and set new result in the LineResult parameter. * @param lineRange The range of lines to mix * @param result The previous operation result * @return The result of the operation (maybe null) * @throws MixException - If an mixing error occurs * @see innovimax.mixthem.operation.LineResult */ void process(List<String> lineRange, LineResult result) throws MixException; /** * Is mixing oparation is possible on line range? * @param lineRange The range of lines to mix * @return True if mixing operation is possible */ boolean mixable(List<String> lineRange); }
Update ILineOperation.java
src/main/java/innovimax/mixthem/operation/ILineOperation.java
Update ILineOperation.java
<ide><path>rc/main/java/innovimax/mixthem/operation/ILineOperation.java <ide> */ <ide> void process(List<String> lineRange, LineResult result) throws MixException; <ide> /** <del> * Is mixing oparation is possible on line range? <add> * Is mixing operation is possible on line range? <ide> * @param lineRange The range of lines to mix <ide> * @return True if mixing operation is possible <ide> */
Java
apache-2.0
407d46b5671674c4b0c5ad49a6885b616763e27a
0
NativeScript/android-upload-service,NativeScript/android-upload-service,alexbbb/android-upload-service,alexbbb/android-upload-service,gotev/android-upload-service,gotev/android-upload-service,NativeScript/android-upload-service
package net.gotev.uploadservice.ftp; import android.content.Intent; import net.gotev.uploadservice.Logger; import net.gotev.uploadservice.UploadFile; import net.gotev.uploadservice.UploadService; import net.gotev.uploadservice.UploadTask; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; import org.apache.commons.net.io.CopyStreamEvent; import org.apache.commons.net.io.CopyStreamListener; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; /** * Implements the FTP upload logic. * @author Aleksandar Gotev */ public class FTPUploadTask extends UploadTask implements CopyStreamListener { private static final String LOG_TAG = FTPUploadTask.class.getSimpleName(); // properties associated to each file protected static final String PARAM_REMOTE_PATH = "ftpRemotePath"; protected static final String PARAM_PERMISSIONS = "ftpPermissions"; private FTPUploadTaskParameters ftpParams = null; private FTPClient ftpClient = null; @Override protected void init(UploadService service, Intent intent) throws IOException { super.init(service, intent); this.ftpParams = intent.getParcelableExtra(FTPUploadTaskParameters.PARAM_FTP_TASK_PARAMETERS); } @Override protected void upload() throws Exception { try { ftpClient = new FTPClient(); ftpClient.setBufferSize(UploadService.BUFFER_SIZE); ftpClient.setCopyStreamListener(this); ftpClient.setDefaultTimeout(ftpParams.getConnectTimeout()); ftpClient.setConnectTimeout(ftpParams.getConnectTimeout()); ftpClient.setAutodetectUTF8(true); Logger.debug(LOG_TAG, "Connect timeout set to " + ftpParams.getConnectTimeout() + "ms"); Logger.debug(LOG_TAG, "Connecting to " + params.getServerUrl() + ":" + ftpParams.getPort() + " as " + ftpParams.getUsername()); ftpClient.connect(params.getServerUrl(), ftpParams.getPort()); if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { throw new Exception("Can't connect to " + params.getServerUrl() + ":" + ftpParams.getPort() + ". The server response is: " + ftpClient.getReplyString()); } if (!ftpClient.login(ftpParams.getUsername(), ftpParams.getPassword())) { throw new Exception("Error while performing login on " + params.getServerUrl() + ":" + ftpParams.getPort() + " with username: " + ftpParams.getUsername() + ". Check your credentials and try again."); } // to prevent the socket timeout on the control socket during file transfer, // set the control keep alive timeout to a half of the socket timeout int controlKeepAliveTimeout = ftpParams.getSocketTimeout() / 2 / 1000; ftpClient.setSoTimeout(ftpParams.getSocketTimeout()); ftpClient.setControlKeepAliveTimeout(controlKeepAliveTimeout); ftpClient.setControlKeepAliveReplyTimeout(controlKeepAliveTimeout * 1000); Logger.debug(LOG_TAG, "Socket timeout set to " + ftpParams.getSocketTimeout() + "ms. Enabled control keep alive every " + controlKeepAliveTimeout + "s"); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.setFileTransferMode(ftpParams.isCompressedFileTransfer() ? FTP.COMPRESSED_TRANSFER_MODE : FTP.STREAM_TRANSFER_MODE); // this is needed to calculate the total bytes and the uploaded bytes, because if the // request fails, the upload method will be called again // (until max retries is reached) to retry the upload, so it's necessary to // know at which status we left, to be able to properly notify firther progress. calculateUploadedAndTotalBytes(); String baseWorkingDir = ftpClient.printWorkingDirectory(); Logger.debug(LOG_TAG, "FTP default working directory is: " + baseWorkingDir); Iterator<UploadFile> iterator = params.getFiles().iterator(); while (iterator.hasNext()) { UploadFile file = iterator.next(); if (!shouldContinue) break; uploadFile(baseWorkingDir, file); addSuccessfullyUploadedFile(file.getAbsolutePath()); iterator.remove(); } // Broadcast completion only if the user has not cancelled the operation. if (shouldContinue) { broadcastCompleted(UploadTask.TASK_COMPLETED_SUCCESSFULLY, UploadTask.EMPTY_RESPONSE, null); } } finally { if (ftpClient.isConnected()) { try { Logger.debug(LOG_TAG, "Logout and disconnect from FTP server: " + params.getServerUrl() + ":" + ftpParams.getPort()); ftpClient.logout(); ftpClient.disconnect(); } catch (Exception exc) { Logger.error(LOG_TAG, "Error while closing FTP connection to: " + params.getServerUrl() + ":" + ftpParams.getPort(), exc); } } ftpClient = null; } } /** * Calculates the total bytes of this upload task. * This the sum of all the lengths of the successfully uploaded files and also the pending * ones. */ private void calculateUploadedAndTotalBytes() { uploadedBytes = 0; for (String filePath : getSuccessfullyUploadedFiles()) { uploadedBytes += new File(filePath).length(); } totalBytes = uploadedBytes; for (UploadFile file : params.getFiles()) { totalBytes += file.length(); } } private void uploadFile(String baseWorkingDir, UploadFile file) throws IOException { Logger.debug(LOG_TAG, "Starting FTP upload of: " + file.getAbsolutePath() + " to: " + file.getProperty(PARAM_REMOTE_PATH)); String remoteDestination = file.getProperty(PARAM_REMOTE_PATH); if (remoteDestination.startsWith(baseWorkingDir)) { remoteDestination = remoteDestination.replace(baseWorkingDir, ""); } makeDirectories(remoteDestination, ftpParams.getCreatedDirectoriesPermissions()); InputStream localStream = file.getStream(); try { String remoteFileName = getRemoteFileName(file); if (!ftpClient.storeFile(remoteFileName, localStream)) { throw new IOException("Error while uploading: " + file.getAbsolutePath() + " to: " + file.getProperty(PARAM_REMOTE_PATH)); } setPermission(remoteFileName, file.getProperty(PARAM_PERMISSIONS)); } finally { localStream.close(); } // get back to base working directory if (!ftpClient.changeWorkingDirectory(baseWorkingDir)) { Logger.info(LOG_TAG, "Can't change working directory to: " + baseWorkingDir); } } private void setPermission(String remoteFileName, String permissions) { if (permissions == null || "".equals(permissions)) return; // http://stackoverflow.com/questions/12741938/how-can-i-change-permissions-of-a-file-on-a-ftp-server-using-apache-commons-net try { if (ftpClient.sendSiteCommand("chmod " + permissions + " " + remoteFileName)) { Logger.error(LOG_TAG, "Error while setting permissions for: " + remoteFileName + " to: " + permissions + ". Check if your FTP user can set file permissions!"); } else { Logger.debug(LOG_TAG, "Permissions for: " + remoteFileName + " set to: " + permissions); } } catch (IOException exc) { Logger.error(LOG_TAG, "Error while setting permissions for: " + remoteFileName + " to: " + permissions + ". Check if your FTP user can set file permissions!", exc); } } @Override public void bytesTransferred(CopyStreamEvent event) { } @Override public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) { uploadedBytes += bytesTransferred; broadcastProgress(uploadedBytes, totalBytes); if (!shouldContinue) { try { ftpClient.disconnect(); } catch (Exception exc) { Logger.error(LOG_TAG, "Failed to abort current file transfer", exc); } } } /** * Creates a nested directory structure on a FTP server and enters into it. * @param dirPath Path of the directory, i.e /projects/java/ftp/demo * @param permissions UNIX permissions to apply to created directories. If null, the FTP * server defaults will be applied, because no UNIX permissions will be * explicitly set * @throws IOException if any error occurred during client-server communication */ private void makeDirectories(String dirPath, String permissions) throws IOException { if (!dirPath.contains("/")) return; String[] pathElements = dirPath.split("/"); if (pathElements.length == 1) return; // if the string ends with / it means that the dir path contains only directories, // otherwise if it does not contain /, the last element of the path is the file name, // so it must be ignored when creating the directory structure int lastElement = dirPath.endsWith("/") ? pathElements.length : pathElements.length - 1; for (int i = 0; i < lastElement; i++) { String singleDir = pathElements[i]; if (singleDir.isEmpty()) continue; if (!ftpClient.changeWorkingDirectory(singleDir)) { if (ftpClient.makeDirectory(singleDir)) { Logger.debug(LOG_TAG, "Created remote directory: " + singleDir); if (permissions != null) { setPermission(singleDir, permissions); } ftpClient.changeWorkingDirectory(singleDir); } else { throw new IOException("Unable to create remote directory: " + singleDir); } } } } /** * Checks if the remote file path contains also the remote file name. If it's not specified, * the name of the local file will be used. * @param file file to upload * @return remote file name */ private String getRemoteFileName(UploadFile file) { // if the remote path ends with / // it means that the remote path specifies only the directory structure, so // get the remote file name from the local file if (file.getProperty(PARAM_REMOTE_PATH).endsWith("/")) { return new File(file.getAbsolutePath()).getName(); } // if the remote path contains /, but it's not the last character // it means that I have something like: /path/to/myfilename // so the remote file name is the last path element (myfilename in this example) if (file.getProperty(PARAM_REMOTE_PATH).contains("/")) { String[] tmp = file.getProperty(PARAM_REMOTE_PATH).split("/"); return tmp[tmp.length - 1]; } // if the remote path does not contain /, it means that it specifies only // the remote file name return file.getProperty(PARAM_REMOTE_PATH); } }
uploadservice-ftp/src/main/java/net/gotev/uploadservice/ftp/FTPUploadTask.java
package net.gotev.uploadservice.ftp; import android.content.Intent; import net.gotev.uploadservice.Logger; import net.gotev.uploadservice.UploadFile; import net.gotev.uploadservice.UploadService; import net.gotev.uploadservice.UploadTask; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; import org.apache.commons.net.io.CopyStreamEvent; import org.apache.commons.net.io.CopyStreamListener; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; /** * Implements the FTP upload logic. * @author Aleksandar Gotev */ public class FTPUploadTask extends UploadTask implements CopyStreamListener { private static final String LOG_TAG = FTPUploadTask.class.getSimpleName(); // properties associated to each file protected static final String PARAM_REMOTE_PATH = "ftpRemotePath"; protected static final String PARAM_PERMISSIONS = "ftpPermissions"; private FTPUploadTaskParameters ftpParams = null; private FTPClient ftpClient = null; @Override protected void init(UploadService service, Intent intent) throws IOException { super.init(service, intent); this.ftpParams = intent.getParcelableExtra(FTPUploadTaskParameters.PARAM_FTP_TASK_PARAMETERS); } @Override protected void upload() throws Exception { try { ftpClient = new FTPClient(); ftpClient.setBufferSize(UploadService.BUFFER_SIZE); ftpClient.setCopyStreamListener(this); ftpClient.setDefaultTimeout(ftpParams.getConnectTimeout()); ftpClient.setConnectTimeout(ftpParams.getConnectTimeout()); Logger.debug(LOG_TAG, "Connect timeout set to " + ftpParams.getConnectTimeout() + "ms"); Logger.debug(LOG_TAG, "Connecting to " + params.getServerUrl() + ":" + ftpParams.getPort() + " as " + ftpParams.getUsername()); ftpClient.connect(params.getServerUrl(), ftpParams.getPort()); if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { throw new Exception("Can't connect to " + params.getServerUrl() + ":" + ftpParams.getPort() + ". The server response is: " + ftpClient.getReplyString()); } if (!ftpClient.login(ftpParams.getUsername(), ftpParams.getPassword())) { throw new Exception("Error while performing login on " + params.getServerUrl() + ":" + ftpParams.getPort() + " with username: " + ftpParams.getUsername() + ". Check your credentials and try again."); } // to prevent the socket timeout on the control socket during file transfer, // set the control keep alive timeout to a half of the socket timeout int controlKeepAliveTimeout = ftpParams.getSocketTimeout() / 2 / 1000; ftpClient.setSoTimeout(ftpParams.getSocketTimeout()); ftpClient.setControlKeepAliveTimeout(controlKeepAliveTimeout); ftpClient.setControlKeepAliveReplyTimeout(controlKeepAliveTimeout * 1000); Logger.debug(LOG_TAG, "Socket timeout set to " + ftpParams.getSocketTimeout() + "ms. Enabled control keep alive every " + controlKeepAliveTimeout + "s"); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.setFileTransferMode(ftpParams.isCompressedFileTransfer() ? FTP.COMPRESSED_TRANSFER_MODE : FTP.STREAM_TRANSFER_MODE); // this is needed to calculate the total bytes and the uploaded bytes, because if the // request fails, the upload method will be called again // (until max retries is reached) to retry the upload, so it's necessary to // know at which status we left, to be able to properly notify firther progress. calculateUploadedAndTotalBytes(); String baseWorkingDir = ftpClient.printWorkingDirectory(); Logger.debug(LOG_TAG, "FTP default working directory is: " + baseWorkingDir); Iterator<UploadFile> iterator = params.getFiles().iterator(); while (iterator.hasNext()) { UploadFile file = iterator.next(); if (!shouldContinue) break; uploadFile(baseWorkingDir, file); addSuccessfullyUploadedFile(file.getAbsolutePath()); iterator.remove(); } // Broadcast completion only if the user has not cancelled the operation. if (shouldContinue) { broadcastCompleted(UploadTask.TASK_COMPLETED_SUCCESSFULLY, UploadTask.EMPTY_RESPONSE, null); } } finally { if (ftpClient.isConnected()) { try { Logger.debug(LOG_TAG, "Logout and disconnect from FTP server: " + params.getServerUrl() + ":" + ftpParams.getPort()); ftpClient.logout(); ftpClient.disconnect(); } catch (Exception exc) { Logger.error(LOG_TAG, "Error while closing FTP connection to: " + params.getServerUrl() + ":" + ftpParams.getPort(), exc); } } ftpClient = null; } } /** * Calculates the total bytes of this upload task. * This the sum of all the lengths of the successfully uploaded files and also the pending * ones. */ private void calculateUploadedAndTotalBytes() { uploadedBytes = 0; for (String filePath : getSuccessfullyUploadedFiles()) { uploadedBytes += new File(filePath).length(); } totalBytes = uploadedBytes; for (UploadFile file : params.getFiles()) { totalBytes += file.length(); } } private void uploadFile(String baseWorkingDir, UploadFile file) throws IOException { Logger.debug(LOG_TAG, "Starting FTP upload of: " + file.getAbsolutePath() + " to: " + file.getProperty(PARAM_REMOTE_PATH)); String remoteDestination = file.getProperty(PARAM_REMOTE_PATH); if (remoteDestination.startsWith(baseWorkingDir)) { remoteDestination = remoteDestination.replace(baseWorkingDir, ""); } makeDirectories(remoteDestination, ftpParams.getCreatedDirectoriesPermissions()); InputStream localStream = file.getStream(); try { String remoteFileName = getRemoteFileName(file); if (!ftpClient.storeFile(remoteFileName, localStream)) { throw new IOException("Error while uploading: " + file.getAbsolutePath() + " to: " + file.getProperty(PARAM_REMOTE_PATH)); } setPermission(remoteFileName, file.getProperty(PARAM_PERMISSIONS)); } finally { localStream.close(); } // get back to base working directory if (!ftpClient.changeWorkingDirectory(baseWorkingDir)) { Logger.info(LOG_TAG, "Can't change working directory to: " + baseWorkingDir); } } private void setPermission(String remoteFileName, String permissions) { if (permissions == null || "".equals(permissions)) return; // http://stackoverflow.com/questions/12741938/how-can-i-change-permissions-of-a-file-on-a-ftp-server-using-apache-commons-net try { if (ftpClient.sendSiteCommand("chmod " + permissions + " " + remoteFileName)) { Logger.error(LOG_TAG, "Error while setting permissions for: " + remoteFileName + " to: " + permissions + ". Check if your FTP user can set file permissions!"); } else { Logger.debug(LOG_TAG, "Permissions for: " + remoteFileName + " set to: " + permissions); } } catch (IOException exc) { Logger.error(LOG_TAG, "Error while setting permissions for: " + remoteFileName + " to: " + permissions + ". Check if your FTP user can set file permissions!", exc); } } @Override public void bytesTransferred(CopyStreamEvent event) { } @Override public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) { uploadedBytes += bytesTransferred; broadcastProgress(uploadedBytes, totalBytes); if (!shouldContinue) { try { ftpClient.disconnect(); } catch (Exception exc) { Logger.error(LOG_TAG, "Failed to abort current file transfer", exc); } } } /** * Creates a nested directory structure on a FTP server and enters into it. * @param dirPath Path of the directory, i.e /projects/java/ftp/demo * @param permissions UNIX permissions to apply to created directories. If null, the FTP * server defaults will be applied, because no UNIX permissions will be * explicitly set * @throws IOException if any error occurred during client-server communication */ private void makeDirectories(String dirPath, String permissions) throws IOException { if (!dirPath.contains("/")) return; String[] pathElements = dirPath.split("/"); if (pathElements.length == 1) return; // if the string ends with / it means that the dir path contains only directories, // otherwise if it does not contain /, the last element of the path is the file name, // so it must be ignored when creating the directory structure int lastElement = dirPath.endsWith("/") ? pathElements.length : pathElements.length - 1; for (int i = 0; i < lastElement; i++) { String singleDir = pathElements[i]; if (singleDir.isEmpty()) continue; if (!ftpClient.changeWorkingDirectory(singleDir)) { if (ftpClient.makeDirectory(singleDir)) { Logger.debug(LOG_TAG, "Created remote directory: " + singleDir); if (permissions != null) { setPermission(singleDir, permissions); } ftpClient.changeWorkingDirectory(singleDir); } else { throw new IOException("Unable to create remote directory: " + singleDir); } } } } /** * Checks if the remote file path contains also the remote file name. If it's not specified, * the name of the local file will be used. * @param file file to upload * @return remote file name */ private String getRemoteFileName(UploadFile file) { // if the remote path ends with / // it means that the remote path specifies only the directory structure, so // get the remote file name from the local file if (file.getProperty(PARAM_REMOTE_PATH).endsWith("/")) { return new File(file.getAbsolutePath()).getName(); } // if the remote path contains /, but it's not the last character // it means that I have something like: /path/to/myfilename // so the remote file name is the last path element (myfilename in this example) if (file.getProperty(PARAM_REMOTE_PATH).contains("/")) { String[] tmp = file.getProperty(PARAM_REMOTE_PATH).split("/"); return tmp[tmp.length - 1]; } // if the remote path does not contain /, it means that it specifies only // the remote file name return file.getProperty(PARAM_REMOTE_PATH); } }
#192 enable FTP UTF-8 auto detection
uploadservice-ftp/src/main/java/net/gotev/uploadservice/ftp/FTPUploadTask.java
#192 enable FTP UTF-8 auto detection
<ide><path>ploadservice-ftp/src/main/java/net/gotev/uploadservice/ftp/FTPUploadTask.java <ide> ftpClient.setCopyStreamListener(this); <ide> ftpClient.setDefaultTimeout(ftpParams.getConnectTimeout()); <ide> ftpClient.setConnectTimeout(ftpParams.getConnectTimeout()); <add> ftpClient.setAutodetectUTF8(true); <ide> <ide> Logger.debug(LOG_TAG, "Connect timeout set to " + ftpParams.getConnectTimeout() + "ms"); <ide>
Java
apache-2.0
0dff2ef46b953c3549170679dd186d4312d77ebb
0
sankarh/hive,lirui-apache/hive,sankarh/hive,alanfgates/hive,nishantmonu51/hive,vergilchiu/hive,alanfgates/hive,jcamachor/hive,lirui-apache/hive,vergilchiu/hive,nishantmonu51/hive,vineetgarg02/hive,alanfgates/hive,jcamachor/hive,vergilchiu/hive,vineetgarg02/hive,anishek/hive,anishek/hive,anishek/hive,vineetgarg02/hive,vineetgarg02/hive,nishantmonu51/hive,vergilchiu/hive,vineetgarg02/hive,alanfgates/hive,anishek/hive,jcamachor/hive,lirui-apache/hive,lirui-apache/hive,lirui-apache/hive,alanfgates/hive,b-slim/hive,b-slim/hive,anishek/hive,anishek/hive,lirui-apache/hive,alanfgates/hive,sankarh/hive,jcamachor/hive,jcamachor/hive,b-slim/hive,alanfgates/hive,vineetgarg02/hive,lirui-apache/hive,vergilchiu/hive,vineetgarg02/hive,b-slim/hive,b-slim/hive,b-slim/hive,lirui-apache/hive,jcamachor/hive,vergilchiu/hive,nishantmonu51/hive,vergilchiu/hive,sankarh/hive,nishantmonu51/hive,jcamachor/hive,nishantmonu51/hive,nishantmonu51/hive,b-slim/hive,sankarh/hive,alanfgates/hive,sankarh/hive,vineetgarg02/hive,vineetgarg02/hive,jcamachor/hive,sankarh/hive,alanfgates/hive,anishek/hive,sankarh/hive,vergilchiu/hive,nishantmonu51/hive,lirui-apache/hive,anishek/hive,jcamachor/hive,b-slim/hive,b-slim/hive,sankarh/hive,vergilchiu/hive,nishantmonu51/hive,anishek/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.exec.tez; import static org.apache.tez.dag.api.client.DAGStatus.State.RUNNING; import static org.fusesource.jansi.Ansi.ansi; import static org.fusesource.jansi.internal.CLibrary.STDOUT_FILENO; import static org.fusesource.jansi.internal.CLibrary.STDERR_FILENO; import static org.fusesource.jansi.internal.CLibrary.isatty; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.ql.exec.FileSinkOperator; import org.apache.hadoop.hive.ql.exec.Heartbeater; import org.apache.hadoop.hive.ql.exec.MapOperator; import org.apache.hadoop.hive.ql.exec.ReduceSinkOperator; import org.apache.hadoop.hive.ql.lockmgr.HiveTxnManager; import org.apache.hadoop.hive.ql.log.PerfLogger; import org.apache.hadoop.hive.ql.plan.BaseWork; import org.apache.hadoop.hive.ql.session.SessionState; import org.apache.hadoop.hive.ql.session.SessionState.LogHelper; import org.apache.tez.common.counters.TaskCounter; import org.apache.tez.common.counters.TezCounter; import org.apache.tez.common.counters.TezCounters; import org.apache.tez.dag.api.DAG; import org.apache.tez.dag.api.TezException; import org.apache.tez.dag.api.Vertex; import org.apache.tez.dag.api.client.DAGClient; import org.apache.tez.dag.api.client.DAGStatus; import org.apache.tez.dag.api.client.Progress; import org.apache.tez.dag.api.client.StatusGetOpts; import org.apache.tez.dag.api.client.VertexStatus; import org.fusesource.jansi.Ansi; import com.google.common.base.Preconditions; import java.io.IOException; import java.io.PrintStream; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import jline.TerminalFactory; /** * TezJobMonitor keeps track of a tez job while it's being executed. It will * print status to the console and retrieve final status of the job after * completion. */ public class TezJobMonitor { private static final String CLASS_NAME = TezJobMonitor.class.getName(); private static final int MIN_TERMINAL_WIDTH = 89; private static final int COLUMN_1_WIDTH = 16; private static final int SEPARATOR_WIDTH = MIN_TERMINAL_WIDTH; // keep this within 80 chars width. If more columns needs to be added then update min terminal // width requirement and separator width accordingly private static final String HEADER_FORMAT = "%16s%11s %9s %5s %9s %7s %7s %6s %6s"; private static final String VERTEX_FORMAT = "%-16s%11s %9s %5s %9s %7s %7s %6s %6s"; private static final String FOOTER_FORMAT = "%-15s %-30s %-4s %-25s"; private static final String HEADER = String.format(HEADER_FORMAT, "VERTICES", "EXECUTOR", "STATUS", "TOTAL", "COMPLETED", "RUNNING", "PENDING", "FAILED", "KILLED"); // method and dag summary format private static final String SUMMARY_HEADER_FORMAT = "%-16s %-12s %-12s %-12s %-19s %-19s %-15s %-15s %-15s"; private static final String SUMMARY_VERTEX_FORMAT = "%-16s %11s %16s %12s %16s %18s %18s %14s %16s"; private static final String SUMMARY_HEADER = String.format(SUMMARY_HEADER_FORMAT, "VERTICES", "TOTAL_TASKS", "FAILED_ATTEMPTS", "KILLED_TASKS", "DURATION_SECONDS", "CPU_TIME_MILLIS", "GC_TIME_MILLIS", "INPUT_RECORDS", "OUTPUT_RECORDS"); private static final String TOTAL_PREP_TIME = "TotalPrepTime"; private static final String METHOD = "METHOD"; private static final String DURATION = "DURATION(ms)"; // in-place progress update related variables private int lines; private PrintStream out; private String separator; private transient LogHelper console; private final PerfLogger perfLogger = PerfLogger.getPerfLogger(); private final int checkInterval = 200; private final int maxRetryInterval = 2500; private final int printInterval = 3000; private final int progressBarChars = 30; private long lastPrintTime; private Set<String> completed; /* Pretty print the values */ private final NumberFormat secondsFormat; private final NumberFormat commaFormat; private static final List<DAGClient> shutdownList; private Map<String, BaseWork> workMap; static { shutdownList = Collections.synchronizedList(new LinkedList<DAGClient>()); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { for (DAGClient c: shutdownList) { TezJobMonitor.killRunningJobs(); } try { for (TezSessionState s: TezSessionState.getOpenSessions()) { System.err.println("Shutting down tez session."); TezSessionPoolManager.getInstance().close(s, false); } } catch (Exception e) { // ignore } } }); } public static void initShutdownHook() { Preconditions.checkNotNull(shutdownList, "Shutdown hook was not properly initialized"); } public TezJobMonitor(Map<String, BaseWork> workMap) { this.workMap = workMap; console = SessionState.getConsole(); secondsFormat = new DecimalFormat("#0.00"); commaFormat = NumberFormat.getNumberInstance(Locale.US); // all progress updates are written to info stream and log file. In-place updates can only be // done to info stream (console) out = console.getInfoStream(); separator = ""; for (int i = 0; i < SEPARATOR_WIDTH; i++) { separator += "-"; } } private static boolean isUnixTerminal() { String os = System.getProperty("os.name"); if (os.startsWith("Windows")) { // we do not support Windows, we will revisit this if we really need it for windows. return false; } // We must be on some unix variant.. // check if standard out is a terminal try { // isatty system call will return 1 if the file descriptor is terminal else 0 if (isatty(STDOUT_FILENO) == 0) { return false; } if (isatty(STDERR_FILENO) == 0) { return false; } } catch (NoClassDefFoundError ignore) { // These errors happen if the JNI lib is not available for your platform. return false; } catch (UnsatisfiedLinkError ignore) { // These errors happen if the JNI lib is not available for your platform. return false; } return true; } /** * NOTE: Use this method only if isUnixTerminal is true. * Erases the current line and prints the given line. * @param line - line to print */ public void reprintLine(String line) { out.print(ansi().eraseLine(Ansi.Erase.ALL).a(line).a('\n').toString()); out.flush(); lines++; } /** * NOTE: Use this method only if isUnixTerminal is true. * Erases the current line and prints the given line with the specified color. * @param line - line to print * @param color - color for the line */ public void reprintLineWithColorAsBold(String line, Ansi.Color color) { out.print(ansi().eraseLine(Ansi.Erase.ALL).fg(color).bold().a(line).a('\n').boldOff().reset() .toString()); out.flush(); lines++; } /** * NOTE: Use this method only if isUnixTerminal is true. * Erases the current line and prints the given multiline. Make sure the specified line is not * terminated by linebreak. * @param line - line to print */ public void reprintMultiLine(String line) { int numLines = line.split("\r\n|\r|\n").length; out.print(ansi().eraseLine(Ansi.Erase.ALL).a(line).a('\n').toString()); out.flush(); lines += numLines; } /** * NOTE: Use this method only if isUnixTerminal is true. * Repositions the cursor back to line 0. */ public void repositionCursor() { if (lines > 0) { out.print(ansi().cursorUp(lines).toString()); out.flush(); lines = 0; } } /** * NOTE: Use this method only if isUnixTerminal is true. * Gets the width of the terminal * @return - width of terminal */ public int getTerminalWidth() { return TerminalFactory.get().getWidth(); } /** * monitorExecution handles status printing, failures during execution and final status retrieval. * * @param dagClient client that was used to kick off the job * @param txnMgr transaction manager for this operation * @param conf configuration file for this operation * @return int 0 - success, 1 - killed, 2 - failed */ public int monitorExecution(final DAGClient dagClient, HiveTxnManager txnMgr, HiveConf conf, DAG dag) throws InterruptedException { DAGStatus status = null; completed = new HashSet<String>(); boolean running = false; boolean done = false; int failedCounter = 0; int rc = 0; DAGStatus.State lastState = null; String lastReport = null; Set<StatusGetOpts> opts = new HashSet<StatusGetOpts>(); Heartbeater heartbeater = new Heartbeater(txnMgr, conf); long startTime = 0; boolean isProfileEnabled = conf.getBoolVar(conf, HiveConf.ConfVars.TEZ_EXEC_SUMMARY); boolean inPlaceUpdates = conf.getBoolVar(conf, HiveConf.ConfVars.TEZ_EXEC_INPLACE_PROGRESS); boolean wideTerminal = false; boolean isTerminal = inPlaceUpdates == true ? isUnixTerminal() : false; // we need at least 80 chars wide terminal to display in-place updates properly if (isTerminal) { if (getTerminalWidth() >= MIN_TERMINAL_WIDTH) { wideTerminal = true; } } boolean inPlaceEligible = false; if (inPlaceUpdates && isTerminal && wideTerminal && !console.getIsSilent()) { inPlaceEligible = true; } shutdownList.add(dagClient); console.printInfo("\n"); perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.TEZ_RUN_DAG); perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.TEZ_SUBMIT_TO_RUNNING); while (true) { try { status = dagClient.getDAGStatus(opts); Map<String, Progress> progressMap = status.getVertexProgress(); DAGStatus.State state = status.getState(); heartbeater.heartbeat(); if (state != lastState || state == RUNNING) { lastState = state; switch (state) { case SUBMITTED: console.printInfo("Status: Submitted"); break; case INITING: console.printInfo("Status: Initializing"); startTime = System.currentTimeMillis(); break; case RUNNING: if (!running) { perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.TEZ_SUBMIT_TO_RUNNING); console.printInfo("Status: Running (" + dagClient.getExecutionContext() + ")\n"); startTime = System.currentTimeMillis(); running = true; } if (inPlaceEligible) { printStatusInPlace(progressMap, startTime, false, dagClient); // log the progress report to log file as well lastReport = logStatus(progressMap, lastReport, console); } else { lastReport = printStatus(progressMap, lastReport, console); } break; case SUCCEEDED: if (inPlaceEligible) { printStatusInPlace(progressMap, startTime, false, dagClient); // log the progress report to log file as well lastReport = logStatus(progressMap, lastReport, console); } else { lastReport = printStatus(progressMap, lastReport, console); } /* Profile info is collected anyways, isProfileEnabled * decides if it gets printed or not */ if (isProfileEnabled) { double duration = (System.currentTimeMillis() - startTime) / 1000.0; console.printInfo("Status: DAG finished successfully in " + String.format("%.2f seconds", duration)); console.printInfo("\n"); printMethodsSummary(); printDagSummary(progressMap, console, dagClient, conf, dag); } running = false; done = true; break; case KILLED: if (inPlaceEligible) { printStatusInPlace(progressMap, startTime, true, dagClient); // log the progress report to log file as well lastReport = logStatus(progressMap, lastReport, console); } console.printInfo("Status: Killed"); running = false; done = true; rc = 1; break; case FAILED: case ERROR: if (inPlaceEligible) { printStatusInPlace(progressMap, startTime, true, dagClient); // log the progress report to log file as well lastReport = logStatus(progressMap, lastReport, console); } console.printError("Status: Failed"); running = false; done = true; rc = 2; break; } } if (!done) { Thread.sleep(checkInterval); } } catch (Exception e) { console.printInfo("Exception: " + e.getMessage()); if (++failedCounter % maxRetryInterval / checkInterval == 0 || e instanceof InterruptedException) { try { console.printInfo("Killing DAG..."); dagClient.tryKillDAG(); } catch (IOException io) { // best effort } catch (TezException te) { // best effort } e.printStackTrace(); console.printError("Execution has failed."); rc = 1; done = true; } else { console.printInfo("Retrying..."); } } finally { if (done) { if (rc != 0 && status != null) { for (String diag : status.getDiagnostics()) { console.printError(diag); } } shutdownList.remove(dagClient); break; } } } perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.TEZ_RUN_DAG); return rc; } /** * killRunningJobs tries to terminate execution of all * currently running tez queries. No guarantees, best effort only. */ public static void killRunningJobs() { for (DAGClient c: shutdownList) { try { System.err.println("Trying to shutdown DAG"); c.tryKillDAG(); } catch (Exception e) { // ignore } } } private static long getCounterValueByGroupName(TezCounters vertexCounters, String groupNamePattern, String counterName) { TezCounter tezCounter = vertexCounters.getGroup(groupNamePattern).findCounter(counterName); return (tezCounter == null) ? 0 : tezCounter.getValue(); } private void printMethodsSummary() { long totalInPrepTime = 0; String[] perfLoggerReportMethods = { (PerfLogger.PARSE), (PerfLogger.ANALYZE), (PerfLogger.TEZ_BUILD_DAG), (PerfLogger.TEZ_SUBMIT_TO_RUNNING) }; /* Build the method summary header */ String methodBreakdownHeader = String.format("%-30s %-13s", METHOD, DURATION); console.printInfo(methodBreakdownHeader); for (String method : perfLoggerReportMethods) { long duration = perfLogger.getDuration(method); totalInPrepTime += duration; console.printInfo(String.format("%-30s %11s", method, commaFormat.format(duration))); } /* * The counters list above don't capture the total time from TimeToSubmit.startTime till * TezRunDag.startTime, so calculate the duration and print it. */ totalInPrepTime = perfLogger.getStartTime(PerfLogger.TEZ_RUN_DAG) - perfLogger.getStartTime(PerfLogger.TIME_TO_SUBMIT); console.printInfo(String.format("%-30s %11s\n", TOTAL_PREP_TIME, commaFormat.format( totalInPrepTime))); } private void printDagSummary(Map<String, Progress> progressMap, LogHelper console, DAGClient dagClient, HiveConf conf, DAG dag) { /* Strings for headers and counters */ String hiveCountersGroup = conf.getVar(conf, HiveConf.ConfVars.HIVECOUNTERGROUP); Set<StatusGetOpts> statusGetOpts = EnumSet.of(StatusGetOpts.GET_COUNTERS); TezCounters hiveCounters = null; try { hiveCounters = dagClient.getDAGStatus(statusGetOpts).getDAGCounters(); } catch (IOException e) { // best attempt, shouldn't really kill DAG for this } catch (TezException e) { // best attempt, shouldn't really kill DAG for this } /* If the counters are missing there is no point trying to print progress */ if (hiveCounters == null) { return; } /* Print the per Vertex summary */ console.printInfo(SUMMARY_HEADER); SortedSet<String> keys = new TreeSet<String>(progressMap.keySet()); Set<StatusGetOpts> statusOptions = new HashSet<StatusGetOpts>(1); statusOptions.add(StatusGetOpts.GET_COUNTERS); for (String vertexName : keys) { Progress progress = progressMap.get(vertexName); if (progress != null) { final int totalTasks = progress.getTotalTaskCount(); final int failedTaskAttempts = progress.getFailedTaskAttemptCount(); final int killedTasks = progress.getKilledTaskCount(); final double duration = perfLogger.getDuration(PerfLogger.TEZ_RUN_VERTEX + vertexName) / 1000.0; VertexStatus vertexStatus = null; try { vertexStatus = dagClient.getVertexStatus(vertexName, statusOptions); } catch (IOException e) { // best attempt, shouldn't really kill DAG for this } catch (TezException e) { // best attempt, shouldn't really kill DAG for this } if (vertexStatus == null) { continue; } Vertex currentVertex = dag.getVertex(vertexName); List<Vertex> inputVerticesList = currentVertex.getInputVertices(); long hiveInputRecordsFromOtherVertices = 0; if (inputVerticesList.size() > 0) { for (Vertex inputVertex : inputVerticesList) { String inputVertexName = inputVertex.getName(); hiveInputRecordsFromOtherVertices += getCounterValueByGroupName(hiveCounters, hiveCountersGroup, String.format("%s_", ReduceSinkOperator.Counter.RECORDS_OUT_INTERMEDIATE.toString()) + inputVertexName.replace(" ", "_")); hiveInputRecordsFromOtherVertices += getCounterValueByGroupName(hiveCounters, hiveCountersGroup, String.format("%s_", FileSinkOperator.Counter.RECORDS_OUT.toString()) + inputVertexName.replace(" ", "_")); } } /* * Get the CPU & GC * * counters org.apache.tez.common.counters.TaskCounter * GC_TIME_MILLIS=37712 * CPU_MILLISECONDS=2774230 */ final TezCounters vertexCounters = vertexStatus.getVertexCounters(); final double cpuTimeMillis = getCounterValueByGroupName(vertexCounters, TaskCounter.class.getName(), TaskCounter.CPU_MILLISECONDS.name()); final double gcTimeMillis = getCounterValueByGroupName(vertexCounters, TaskCounter.class.getName(), TaskCounter.GC_TIME_MILLIS.name()); /* * Get the HIVE counters * * HIVE * CREATED_FILES=1 * DESERIALIZE_ERRORS=0 * RECORDS_IN_Map_1=550076554 * RECORDS_OUT_INTERMEDIATE_Map_1=854987 * RECORDS_OUT_Reducer_2=1 */ final long hiveInputRecords = getCounterValueByGroupName( hiveCounters, hiveCountersGroup, String.format("%s_", MapOperator.Counter.RECORDS_IN.toString()) + vertexName.replace(" ", "_")) + hiveInputRecordsFromOtherVertices; final long hiveOutputIntermediateRecords = getCounterValueByGroupName( hiveCounters, hiveCountersGroup, String.format("%s_", ReduceSinkOperator.Counter.RECORDS_OUT_INTERMEDIATE.toString()) + vertexName.replace(" ", "_")); final long hiveOutputRecords = getCounterValueByGroupName( hiveCounters, hiveCountersGroup, String.format("%s_", FileSinkOperator.Counter.RECORDS_OUT.toString()) + vertexName.replace(" ", "_")) + hiveOutputIntermediateRecords; String vertexExecutionStats = String.format(SUMMARY_VERTEX_FORMAT, vertexName, totalTasks, failedTaskAttempts, killedTasks, secondsFormat.format((duration)), commaFormat.format(cpuTimeMillis), commaFormat.format(gcTimeMillis), commaFormat.format(hiveInputRecords), commaFormat.format(hiveOutputRecords)); console.printInfo(vertexExecutionStats); } } } private void printStatusInPlace(Map<String, Progress> progressMap, long startTime, boolean vextexStatusFromAM, DAGClient dagClient) { StringBuffer reportBuffer = new StringBuffer(); int sumComplete = 0; int sumTotal = 0; // position the cursor to line 0 repositionCursor(); // print header // ------------------------------------------------------------------------------- // VERTICES STATUS TOTAL COMPLETED RUNNING PENDING FAILED KILLED // ------------------------------------------------------------------------------- reprintLine(separator); reprintLineWithColorAsBold(HEADER, Ansi.Color.CYAN); reprintLine(separator); SortedSet<String> keys = new TreeSet<String>(progressMap.keySet()); int idx = 0; int maxKeys = keys.size(); for (String s : keys) { idx++; Progress progress = progressMap.get(s); final int complete = progress.getSucceededTaskCount(); final int total = progress.getTotalTaskCount(); final int running = progress.getRunningTaskCount(); final int failed = progress.getFailedTaskAttemptCount(); final int pending = progress.getTotalTaskCount() - progress.getSucceededTaskCount() - progress.getRunningTaskCount(); final int killed = progress.getKilledTaskCount(); // To get vertex status we can use DAGClient.getVertexStatus(), but it will be expensive to // get status from AM for every refresh of the UI. Lets infer the state from task counts. // Only if DAG is FAILED or KILLED the vertex status is fetched from AM. VertexStatus.State vertexState = VertexStatus.State.INITIALIZING; // INITED state if (total > 0) { vertexState = VertexStatus.State.INITED; sumComplete += complete; sumTotal += total; } // RUNNING state if (complete < total && (complete > 0 || running > 0 || failed > 0)) { vertexState = VertexStatus.State.RUNNING; if (!perfLogger.startTimeHasMethod(PerfLogger.TEZ_RUN_VERTEX + s)) { perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.TEZ_RUN_VERTEX + s); } } // SUCCEEDED state if (complete == total) { vertexState = VertexStatus.State.SUCCEEDED; if (!completed.contains(s)) { completed.add(s); /* We may have missed the start of the vertex * due to the 3 seconds interval */ if (!perfLogger.startTimeHasMethod(PerfLogger.TEZ_RUN_VERTEX + s)) { perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.TEZ_RUN_VERTEX + s); } perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.TEZ_RUN_VERTEX + s); } } // DAG might have been killed, lets try to get vertex state from AM before dying // KILLED or FAILED state if (vextexStatusFromAM) { VertexStatus vertexStatus = null; try { vertexStatus = dagClient.getVertexStatus(s, null); } catch (IOException e) { // best attempt, shouldn't really kill DAG for this } catch (TezException e) { // best attempt, shouldn't really kill DAG for this } if (vertexStatus != null) { vertexState = vertexStatus.getState(); } } // Map 1 .......... container SUCCEEDED 7 7 0 0 0 0 String nameWithProgress = getNameWithProgress(s, complete, total); String mode = getMode(s, workMap); String vertexStr = String.format(VERTEX_FORMAT, nameWithProgress, mode, vertexState.toString(), total, complete, running, pending, failed, killed); reportBuffer.append(vertexStr); if (idx != maxKeys) { reportBuffer.append("\n"); } } reprintMultiLine(reportBuffer.toString()); // ------------------------------------------------------------------------------- // VERTICES: 03/04 [=================>>-----] 86% ELAPSED TIME: 1.71 s // ------------------------------------------------------------------------------- reprintLine(separator); final float progress = (sumTotal == 0) ? 0.0f : (float) sumComplete / (float) sumTotal; String footer = getFooter(keys.size(), completed.size(), progress, startTime); reprintLineWithColorAsBold(footer, Ansi.Color.RED); reprintLine(separator); } private String getMode(String name, Map<String, BaseWork> workMap) { String mode = "container"; BaseWork work = workMap.get(name); if (work != null) { // uber > llap > container if (work.getUberMode()) { mode = "uber"; } else if (work.getLlapMode()) { mode = "llap"; } else { mode = "container"; } } return mode; } // Map 1 .......... private String getNameWithProgress(String s, int complete, int total) { String result = ""; if (s != null) { float percent = total == 0 ? 0.0f : (float) complete / (float) total; // lets use the remaining space in column 1 as progress bar int spaceRemaining = COLUMN_1_WIDTH - s.length() - 1; String trimmedVName = s; // if the vertex name is longer than column 1 width, trim it down // "Tez Merge File Work" will become "Tez Merge File.." if (s.length() > COLUMN_1_WIDTH) { trimmedVName = s.substring(0, COLUMN_1_WIDTH - 1); trimmedVName = trimmedVName + ".."; } result = trimmedVName + " "; int toFill = (int) (spaceRemaining * percent); for (int i = 0; i < toFill; i++) { result += "."; } } return result; } // VERTICES: 03/04 [==================>>-----] 86% ELAPSED TIME: 1.71 s private String getFooter(int keySize, int completedSize, float progress, long startTime) { String verticesSummary = String.format("VERTICES: %02d/%02d", completedSize, keySize); String progressBar = getInPlaceProgressBar(progress); final int progressPercent = (int) (progress * 100); String progressStr = "" + progressPercent + "%"; float et = (float) (System.currentTimeMillis() - startTime) / (float) 1000; String elapsedTime = "ELAPSED TIME: " + secondsFormat.format(et) + " s"; String footer = String.format(FOOTER_FORMAT, verticesSummary, progressBar, progressStr, elapsedTime); return footer; } // [==================>>-----] private String getInPlaceProgressBar(float percent) { StringBuilder bar = new StringBuilder("["); int remainingChars = progressBarChars - 4; int completed = (int) (remainingChars * percent); int pending = remainingChars - completed; for (int i = 0; i < completed; i++) { bar.append("="); } bar.append(">>"); for (int i = 0; i < pending; i++) { bar.append("-"); } bar.append("]"); return bar.toString(); } private String printStatus(Map<String, Progress> progressMap, String lastReport, LogHelper console) { String report = getReport(progressMap); if (!report.equals(lastReport) || System.currentTimeMillis() >= lastPrintTime + printInterval) { console.printInfo(report); lastPrintTime = System.currentTimeMillis(); } return report; } private String logStatus(Map<String, Progress> progressMap, String lastReport, LogHelper console) { String report = getReport(progressMap); if (!report.equals(lastReport) || System.currentTimeMillis() >= lastPrintTime + printInterval) { console.logInfo(report); lastPrintTime = System.currentTimeMillis(); } return report; } private String getReport(Map<String, Progress> progressMap) { StringBuffer reportBuffer = new StringBuffer(); SortedSet<String> keys = new TreeSet<String>(progressMap.keySet()); for (String s: keys) { Progress progress = progressMap.get(s); final int complete = progress.getSucceededTaskCount(); final int total = progress.getTotalTaskCount(); final int running = progress.getRunningTaskCount(); final int failed = progress.getFailedTaskAttemptCount(); if (total <= 0) { reportBuffer.append(String.format("%s: -/-\t", s)); } else { if (complete == total && !completed.contains(s)) { completed.add(s); /* * We may have missed the start of the vertex due to the 3 seconds interval */ if (!perfLogger.startTimeHasMethod(PerfLogger.TEZ_RUN_VERTEX + s)) { perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.TEZ_RUN_VERTEX + s); } perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.TEZ_RUN_VERTEX + s); } if(complete < total && (complete > 0 || running > 0 || failed > 0)) { if (!perfLogger.startTimeHasMethod(PerfLogger.TEZ_RUN_VERTEX + s)) { perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.TEZ_RUN_VERTEX + s); } /* vertex is started, but not complete */ if (failed > 0) { reportBuffer.append(String.format("%s: %d(+%d,-%d)/%d\t", s, complete, running, failed, total)); } else { reportBuffer.append(String.format("%s: %d(+%d)/%d\t", s, complete, running, total)); } } else { /* vertex is waiting for input/slots or complete */ if (failed > 0) { /* tasks finished but some failed */ reportBuffer.append(String.format("%s: %d(-%d)/%d\t", s, complete, failed, total)); } else { reportBuffer.append(String.format("%s: %d/%d\t", s, complete, total)); } } } } return reportBuffer.toString(); } }
ql/src/java/org/apache/hadoop/hive/ql/exec/tez/TezJobMonitor.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.exec.tez; import static org.apache.tez.dag.api.client.DAGStatus.State.RUNNING; import static org.fusesource.jansi.Ansi.ansi; import static org.fusesource.jansi.internal.CLibrary.STDOUT_FILENO; import static org.fusesource.jansi.internal.CLibrary.STDERR_FILENO; import static org.fusesource.jansi.internal.CLibrary.isatty; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.ql.exec.FileSinkOperator; import org.apache.hadoop.hive.ql.exec.Heartbeater; import org.apache.hadoop.hive.ql.exec.MapOperator; import org.apache.hadoop.hive.ql.exec.ReduceSinkOperator; import org.apache.hadoop.hive.ql.lockmgr.HiveTxnManager; import org.apache.hadoop.hive.ql.log.PerfLogger; import org.apache.hadoop.hive.ql.plan.BaseWork; import org.apache.hadoop.hive.ql.session.SessionState; import org.apache.hadoop.hive.ql.session.SessionState.LogHelper; import org.apache.tez.common.counters.TaskCounter; import org.apache.tez.common.counters.TezCounter; import org.apache.tez.common.counters.TezCounters; import org.apache.tez.dag.api.DAG; import org.apache.tez.dag.api.TezException; import org.apache.tez.dag.api.Vertex; import org.apache.tez.dag.api.client.DAGClient; import org.apache.tez.dag.api.client.DAGStatus; import org.apache.tez.dag.api.client.Progress; import org.apache.tez.dag.api.client.StatusGetOpts; import org.apache.tez.dag.api.client.VertexStatus; import org.fusesource.jansi.Ansi; import com.google.common.base.Preconditions; import java.io.IOException; import java.io.PrintStream; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import jline.TerminalFactory; /** * TezJobMonitor keeps track of a tez job while it's being executed. It will * print status to the console and retrieve final status of the job after * completion. */ public class TezJobMonitor { private static final String CLASS_NAME = TezJobMonitor.class.getName(); private static final int MIN_TERMINAL_WIDTH = 89; private static final int COLUMN_1_WIDTH = 16; private static final int SEPARATOR_WIDTH = MIN_TERMINAL_WIDTH; // keep this within 80 chars width. If more columns needs to be added then update min terminal // width requirement and separator width accordingly private static final String HEADER_FORMAT = "%16s%11s %9s %5s %9s %7s %7s %6s %6s"; private static final String VERTEX_FORMAT = "%-16s%11s %9s %5s %9s %7s %7s %6s %6s"; private static final String FOOTER_FORMAT = "%-15s %-30s %-4s %-25s"; private static final String HEADER = String.format(HEADER_FORMAT, "VERTICES", "EXECUTOR", "STATUS", "TOTAL", "COMPLETED", "RUNNING", "PENDING", "FAILED", "KILLED"); // method and dag summary format private static final String SUMMARY_HEADER_FORMAT = "%-16s %-12s %-12s %-12s %-19s %-19s %-15s %-15s %-15s"; private static final String SUMMARY_VERTEX_FORMAT = "%-16s %11s %16s %12s %16s %18s %18s %14s %16s"; private static final String SUMMARY_HEADER = String.format(SUMMARY_HEADER_FORMAT, "VERTICES", "TOTAL_TASKS", "FAILED_ATTEMPTS", "KILLED_TASKS", "DURATION_SECONDS", "CPU_TIME_MILLIS", "GC_TIME_MILLIS", "INPUT_RECORDS", "OUTPUT_RECORDS"); private static final String TOTAL_PREP_TIME = "TotalPrepTime"; private static final String METHOD = "METHOD"; private static final String DURATION = "DURATION(ms)"; // in-place progress update related variables private int lines; private PrintStream out; private String separator; private transient LogHelper console; private final PerfLogger perfLogger = PerfLogger.getPerfLogger(); private final int checkInterval = 200; private final int maxRetryInterval = 2500; private final int printInterval = 3000; private final int progressBarChars = 30; private long lastPrintTime; private Set<String> completed; /* Pretty print the values */ private final NumberFormat secondsFormat; private final NumberFormat commaFormat; private static final List<DAGClient> shutdownList; private Map<String, BaseWork> workMap; static { shutdownList = Collections.synchronizedList(new LinkedList<DAGClient>()); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { for (DAGClient c: shutdownList) { TezJobMonitor.killRunningJobs(); } try { for (TezSessionState s: TezSessionState.getOpenSessions()) { System.err.println("Shutting down tez session."); TezSessionPoolManager.getInstance().close(s, false); } } catch (Exception e) { // ignore } } }); } public static void initShutdownHook() { Preconditions.checkNotNull(shutdownList, "Shutdown hook was not properly initialized"); } public TezJobMonitor(Map<String, BaseWork> workMap) { this.workMap = workMap; console = SessionState.getConsole(); secondsFormat = new DecimalFormat("#0.00"); commaFormat = NumberFormat.getNumberInstance(Locale.US); // all progress updates are written to info stream and log file. In-place updates can only be // done to info stream (console) out = console.getInfoStream(); separator = ""; for (int i = 0; i < SEPARATOR_WIDTH; i++) { separator += "-"; } } private static boolean isUnixTerminal() { String os = System.getProperty("os.name"); if (os.startsWith("Windows")) { // we do not support Windows, we will revisit this if we really need it for windows. return false; } // We must be on some unix variant.. // check if standard out is a terminal try { // isatty system call will return 1 if the file descriptor is terminal else 0 if (isatty(STDOUT_FILENO) == 0) { return false; } if (isatty(STDERR_FILENO) == 0) { return false; } } catch (NoClassDefFoundError ignore) { // These errors happen if the JNI lib is not available for your platform. return false; } catch (UnsatisfiedLinkError ignore) { // These errors happen if the JNI lib is not available for your platform. return false; } return true; } /** * NOTE: Use this method only if isUnixTerminal is true. * Erases the current line and prints the given line. * @param line - line to print */ public void reprintLine(String line) { out.print(ansi().eraseLine(Ansi.Erase.ALL).a(line).a('\n').toString()); out.flush(); lines++; } /** * NOTE: Use this method only if isUnixTerminal is true. * Erases the current line and prints the given line with the specified color. * @param line - line to print * @param color - color for the line */ public void reprintLineWithColorAsBold(String line, Ansi.Color color) { out.print(ansi().eraseLine(Ansi.Erase.ALL).fg(color).bold().a(line).a('\n').boldOff().reset() .toString()); out.flush(); lines++; } /** * NOTE: Use this method only if isUnixTerminal is true. * Erases the current line and prints the given multiline. Make sure the specified line is not * terminated by linebreak. * @param line - line to print */ public void reprintMultiLine(String line) { int numLines = line.split("\r\n|\r|\n").length; out.print(ansi().eraseLine(Ansi.Erase.ALL).a(line).a('\n').toString()); out.flush(); lines += numLines; } /** * NOTE: Use this method only if isUnixTerminal is true. * Repositions the cursor back to line 0. */ public void repositionCursor() { if (lines > 0) { out.print(ansi().cursorUp(lines).toString()); out.flush(); lines = 0; } } /** * NOTE: Use this method only if isUnixTerminal is true. * Gets the width of the terminal * @return - width of terminal */ public int getTerminalWidth() { return TerminalFactory.get().getWidth(); } /** * monitorExecution handles status printing, failures during execution and final status retrieval. * * @param dagClient client that was used to kick off the job * @param txnMgr transaction manager for this operation * @param conf configuration file for this operation * @return int 0 - success, 1 - killed, 2 - failed */ public int monitorExecution(final DAGClient dagClient, HiveTxnManager txnMgr, HiveConf conf, DAG dag) throws InterruptedException { DAGStatus status = null; completed = new HashSet<String>(); boolean running = false; boolean done = false; int failedCounter = 0; int rc = 0; DAGStatus.State lastState = null; String lastReport = null; Set<StatusGetOpts> opts = new HashSet<StatusGetOpts>(); Heartbeater heartbeater = new Heartbeater(txnMgr, conf); long startTime = 0; boolean isProfileEnabled = conf.getBoolVar(conf, HiveConf.ConfVars.TEZ_EXEC_SUMMARY); boolean inPlaceUpdates = conf.getBoolVar(conf, HiveConf.ConfVars.TEZ_EXEC_INPLACE_PROGRESS); boolean wideTerminal = false; boolean isTerminal = inPlaceUpdates == true ? isUnixTerminal() : false; // we need at least 80 chars wide terminal to display in-place updates properly if (isTerminal) { if (getTerminalWidth() >= MIN_TERMINAL_WIDTH) { wideTerminal = true; } } boolean inPlaceEligible = false; if (inPlaceUpdates && isTerminal && wideTerminal && !console.getIsSilent()) { inPlaceEligible = true; } shutdownList.add(dagClient); console.printInfo("\n"); perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.TEZ_RUN_DAG); perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.TEZ_SUBMIT_TO_RUNNING); while (true) { try { status = dagClient.getDAGStatus(opts); Map<String, Progress> progressMap = status.getVertexProgress(); DAGStatus.State state = status.getState(); heartbeater.heartbeat(); if (state != lastState || state == RUNNING) { lastState = state; switch (state) { case SUBMITTED: console.printInfo("Status: Submitted"); break; case INITING: console.printInfo("Status: Initializing"); startTime = System.currentTimeMillis(); break; case RUNNING: if (!running) { perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.TEZ_SUBMIT_TO_RUNNING); console.printInfo("Status: Running (" + dagClient.getExecutionContext() + ")\n"); startTime = System.currentTimeMillis(); running = true; } if (inPlaceEligible) { printStatusInPlace(progressMap, startTime, false, dagClient); // log the progress report to log file as well lastReport = logStatus(progressMap, lastReport, console); } else { lastReport = printStatus(progressMap, lastReport, console); } break; case SUCCEEDED: if (inPlaceEligible) { printStatusInPlace(progressMap, startTime, false, dagClient); // log the progress report to log file as well lastReport = logStatus(progressMap, lastReport, console); } else { lastReport = printStatus(progressMap, lastReport, console); } /* Profile info is collected anyways, isProfileEnabled * decides if it gets printed or not */ if (isProfileEnabled) { double duration = (System.currentTimeMillis() - startTime) / 1000.0; console.printInfo("Status: DAG finished successfully in " + String.format("%.2f seconds", duration)); console.printInfo("\n"); printMethodsSummary(); printDagSummary(progressMap, console, dagClient, conf, dag); } running = false; done = true; break; case KILLED: if (inPlaceEligible) { printStatusInPlace(progressMap, startTime, true, dagClient); // log the progress report to log file as well lastReport = logStatus(progressMap, lastReport, console); } console.printInfo("Status: Killed"); running = false; done = true; rc = 1; break; case FAILED: case ERROR: if (inPlaceEligible) { printStatusInPlace(progressMap, startTime, true, dagClient); // log the progress report to log file as well lastReport = logStatus(progressMap, lastReport, console); } console.printError("Status: Failed"); running = false; done = true; rc = 2; break; } } if (!done) { Thread.sleep(checkInterval); } } catch (Exception e) { console.printInfo("Exception: " + e.getMessage()); if (++failedCounter % maxRetryInterval / checkInterval == 0 || e instanceof InterruptedException) { try { console.printInfo("Killing DAG..."); dagClient.tryKillDAG(); } catch (IOException io) { // best effort } catch (TezException te) { // best effort } e.printStackTrace(); console.printError("Execution has failed."); rc = 1; done = true; } else { console.printInfo("Retrying..."); } } finally { if (done) { if (rc != 0 && status != null) { for (String diag : status.getDiagnostics()) { console.printError(diag); } } shutdownList.remove(dagClient); break; } } } perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.TEZ_RUN_DAG); return rc; } /** * killRunningJobs tries to terminate execution of all * currently running tez queries. No guarantees, best effort only. */ public static void killRunningJobs() { for (DAGClient c: shutdownList) { try { System.err.println("Trying to shutdown DAG"); c.tryKillDAG(); } catch (Exception e) { // ignore } } } private static long getCounterValueByGroupName(TezCounters vertexCounters, String groupNamePattern, String counterName) { TezCounter tezCounter = vertexCounters.getGroup(groupNamePattern).findCounter(counterName); return (tezCounter == null) ? 0 : tezCounter.getValue(); } private void printMethodsSummary() { long totalInPrepTime = 0; String[] perfLoggerReportMethods = { (PerfLogger.PARSE), (PerfLogger.ANALYZE), (PerfLogger.TEZ_BUILD_DAG), (PerfLogger.TEZ_SUBMIT_TO_RUNNING) }; /* Build the method summary header */ String methodBreakdownHeader = String.format("%-30s %-13s", METHOD, DURATION); console.printInfo(methodBreakdownHeader); for (String method : perfLoggerReportMethods) { long duration = perfLogger.getDuration(method); totalInPrepTime += duration; console.printInfo(String.format("%-30s %11s", method, commaFormat.format(duration))); } /* * The counters list above don't capture the total time from TimeToSubmit.startTime till * TezRunDag.startTime, so calculate the duration and print it. */ totalInPrepTime = perfLogger.getStartTime(PerfLogger.TEZ_RUN_DAG) - perfLogger.getStartTime(PerfLogger.TIME_TO_SUBMIT); console.printInfo(String.format("%-30s %11s\n", TOTAL_PREP_TIME, commaFormat.format( totalInPrepTime))); } private void printDagSummary(Map<String, Progress> progressMap, LogHelper console, DAGClient dagClient, HiveConf conf, DAG dag) { /* Strings for headers and counters */ String hiveCountersGroup = conf.getVar(conf, HiveConf.ConfVars.HIVECOUNTERGROUP); Set<StatusGetOpts> statusGetOpts = EnumSet.of(StatusGetOpts.GET_COUNTERS); TezCounters hiveCounters = null; try { hiveCounters = dagClient.getDAGStatus(statusGetOpts).getDAGCounters(); } catch (IOException e) { // best attempt, shouldn't really kill DAG for this } catch (TezException e) { // best attempt, shouldn't really kill DAG for this } /* If the counters are missing there is no point trying to print progress */ if (hiveCounters == null) { return; } /* Print the per Vertex summary */ console.printInfo(SUMMARY_HEADER); SortedSet<String> keys = new TreeSet<String>(progressMap.keySet()); Set<StatusGetOpts> statusOptions = new HashSet<StatusGetOpts>(1); statusOptions.add(StatusGetOpts.GET_COUNTERS); for (String vertexName : keys) { Progress progress = progressMap.get(vertexName); if (progress != null) { final int totalTasks = progress.getTotalTaskCount(); final int failedTaskAttempts = progress.getFailedTaskAttemptCount(); final int killedTasks = progress.getKilledTaskCount(); final double duration = perfLogger.getDuration(PerfLogger.TEZ_RUN_VERTEX + vertexName) / 1000.0; VertexStatus vertexStatus = null; try { vertexStatus = dagClient.getVertexStatus(vertexName, statusOptions); } catch (IOException e) { // best attempt, shouldn't really kill DAG for this } catch (TezException e) { // best attempt, shouldn't really kill DAG for this } if (vertexStatus == null) { continue; } Vertex currentVertex = dag.getVertex(vertexName); List<Vertex> inputVerticesList = currentVertex.getInputVertices(); long hiveInputRecordsFromOtherVertices = 0; if (inputVerticesList.size() > 0) { for (Vertex inputVertex : inputVerticesList) { String inputVertexName = inputVertex.getName(); hiveInputRecordsFromOtherVertices += getCounterValueByGroupName(hiveCounters, hiveCountersGroup, String.format("%s_", ReduceSinkOperator.Counter.RECORDS_OUT_INTERMEDIATE.toString()) + inputVertexName.replace(" ", "_")); hiveInputRecordsFromOtherVertices += getCounterValueByGroupName(hiveCounters, hiveCountersGroup, String.format("%s_", FileSinkOperator.Counter.RECORDS_OUT.toString()) + inputVertexName.replace(" ", "_")); } } /* * Get the CPU & GC * * counters org.apache.tez.common.counters.TaskCounter * GC_TIME_MILLIS=37712 * CPU_MILLISECONDS=2774230 */ final TezCounters vertexCounters = vertexStatus.getVertexCounters(); final double cpuTimeMillis = getCounterValueByGroupName(vertexCounters, TaskCounter.class.getName(), TaskCounter.CPU_MILLISECONDS.name()); final double gcTimeMillis = getCounterValueByGroupName(vertexCounters, TaskCounter.class.getName(), TaskCounter.GC_TIME_MILLIS.name()); /* * Get the HIVE counters * * HIVE * CREATED_FILES=1 * DESERIALIZE_ERRORS=0 * RECORDS_IN_Map_1=550076554 * RECORDS_OUT_INTERMEDIATE_Map_1=854987 * RECORDS_OUT_Reducer_2=1 */ final long hiveInputRecords = getCounterValueByGroupName( hiveCounters, hiveCountersGroup, String.format("%s_", MapOperator.Counter.RECORDS_IN.toString()) + vertexName.replace(" ", "_")) + hiveInputRecordsFromOtherVertices; final long hiveOutputIntermediateRecords = getCounterValueByGroupName( hiveCounters, hiveCountersGroup, String.format("%s_", ReduceSinkOperator.Counter.RECORDS_OUT_INTERMEDIATE.toString()) + vertexName.replace(" ", "_")); final long hiveOutputRecords = getCounterValueByGroupName( hiveCounters, hiveCountersGroup, String.format("%s_", FileSinkOperator.Counter.RECORDS_OUT.toString()) + vertexName.replace(" ", "_")) + hiveOutputIntermediateRecords; String vertexExecutionStats = String.format(SUMMARY_VERTEX_FORMAT, vertexName, totalTasks, failedTaskAttempts, killedTasks, secondsFormat.format((duration)), commaFormat.format(cpuTimeMillis), commaFormat.format(gcTimeMillis), commaFormat.format(hiveInputRecords), commaFormat.format(hiveOutputRecords)); console.printInfo(vertexExecutionStats); } } } private void printStatusInPlace(Map<String, Progress> progressMap, long startTime, boolean vextexStatusFromAM, DAGClient dagClient) { StringBuffer reportBuffer = new StringBuffer(); int sumComplete = 0; int sumTotal = 0; // position the cursor to line 0 repositionCursor(); // print header // ------------------------------------------------------------------------------- // VERTICES STATUS TOTAL COMPLETED RUNNING PENDING FAILED KILLED // ------------------------------------------------------------------------------- reprintLine(separator); reprintLineWithColorAsBold(HEADER, Ansi.Color.CYAN); reprintLine(separator); SortedSet<String> keys = new TreeSet<String>(progressMap.keySet()); int idx = 0; int maxKeys = keys.size(); for (String s : keys) { idx++; Progress progress = progressMap.get(s); final int complete = progress.getSucceededTaskCount(); final int total = progress.getTotalTaskCount(); final int running = progress.getRunningTaskCount(); final int failed = progress.getFailedTaskAttemptCount(); final int pending = progress.getTotalTaskCount() - progress.getSucceededTaskCount() - progress.getRunningTaskCount(); final int killed = progress.getKilledTaskCount(); // To get vertex status we can use DAGClient.getVertexStatus(), but it will be expensive to // get status from AM for every refresh of the UI. Lets infer the state from task counts. // Only if DAG is FAILED or KILLED the vertex status is fetched from AM. VertexStatus.State vertexState = VertexStatus.State.INITIALIZING; // INITED state if (total > 0) { vertexState = VertexStatus.State.INITED; sumComplete += complete; sumTotal += total; } // RUNNING state if (complete < total && (complete > 0 || running > 0 || failed > 0)) { vertexState = VertexStatus.State.RUNNING; if (!perfLogger.startTimeHasMethod(PerfLogger.TEZ_RUN_VERTEX + s)) { perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.TEZ_RUN_VERTEX + s); } } // SUCCEEDED state if (complete == total) { vertexState = VertexStatus.State.SUCCEEDED; if (!completed.contains(s)) { completed.add(s); /* We may have missed the start of the vertex * due to the 3 seconds interval */ if (!perfLogger.startTimeHasMethod(PerfLogger.TEZ_RUN_VERTEX + s)) { perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.TEZ_RUN_VERTEX + s); } perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.TEZ_RUN_VERTEX + s); } } // DAG might have been killed, lets try to get vertex state from AM before dying // KILLED or FAILED state if (vextexStatusFromAM) { VertexStatus vertexStatus = null; try { vertexStatus = dagClient.getVertexStatus(s, null); } catch (IOException e) { // best attempt, shouldn't really kill DAG for this } catch (TezException e) { // best attempt, shouldn't really kill DAG for this } if (vertexStatus != null) { vertexState = vertexStatus.getState(); } } // Map 1 .......... container SUCCEEDED 7 7 0 0 0 0 String nameWithProgress = getNameWithProgress(s, complete, total); String mode = getMode(s, workMap); String vertexStr = String.format(VERTEX_FORMAT, nameWithProgress, mode, vertexState.toString(), total, complete, running, pending, failed, killed); reportBuffer.append(vertexStr); if (idx != maxKeys) { reportBuffer.append("\n"); } } reprintMultiLine(reportBuffer.toString()); // ------------------------------------------------------------------------------- // VERTICES: 03/04 [=================>>-----] 86% ELAPSED TIME: 1.71 s // ------------------------------------------------------------------------------- reprintLine(separator); final float progress = (sumTotal == 0) ? 0.0f : (float) sumComplete / (float) sumTotal; String footer = getFooter(keys.size(), completed.size(), progress, startTime); reprintLineWithColorAsBold(footer, Ansi.Color.RED); reprintLine(separator); } private String getMode(String name, Map<String, BaseWork> workMap) { String mode = "container"; BaseWork work = workMap.get(name); if (work != null) { if (work.getLlapMode()) { mode = "llap"; } else if (work.getUberMode()) { mode = "uber"; } else { mode = "container"; } } return mode; } // Map 1 .......... private String getNameWithProgress(String s, int complete, int total) { String result = ""; if (s != null) { float percent = total == 0 ? 0.0f : (float) complete / (float) total; // lets use the remaining space in column 1 as progress bar int spaceRemaining = COLUMN_1_WIDTH - s.length() - 1; String trimmedVName = s; // if the vertex name is longer than column 1 width, trim it down // "Tez Merge File Work" will become "Tez Merge File.." if (s.length() > COLUMN_1_WIDTH) { trimmedVName = s.substring(0, COLUMN_1_WIDTH - 1); trimmedVName = trimmedVName + ".."; } result = trimmedVName + " "; int toFill = (int) (spaceRemaining * percent); for (int i = 0; i < toFill; i++) { result += "."; } } return result; } // VERTICES: 03/04 [==================>>-----] 86% ELAPSED TIME: 1.71 s private String getFooter(int keySize, int completedSize, float progress, long startTime) { String verticesSummary = String.format("VERTICES: %02d/%02d", completedSize, keySize); String progressBar = getInPlaceProgressBar(progress); final int progressPercent = (int) (progress * 100); String progressStr = "" + progressPercent + "%"; float et = (float) (System.currentTimeMillis() - startTime) / (float) 1000; String elapsedTime = "ELAPSED TIME: " + secondsFormat.format(et) + " s"; String footer = String.format(FOOTER_FORMAT, verticesSummary, progressBar, progressStr, elapsedTime); return footer; } // [==================>>-----] private String getInPlaceProgressBar(float percent) { StringBuilder bar = new StringBuilder("["); int remainingChars = progressBarChars - 4; int completed = (int) (remainingChars * percent); int pending = remainingChars - completed; for (int i = 0; i < completed; i++) { bar.append("="); } bar.append(">>"); for (int i = 0; i < pending; i++) { bar.append("-"); } bar.append("]"); return bar.toString(); } private String printStatus(Map<String, Progress> progressMap, String lastReport, LogHelper console) { String report = getReport(progressMap); if (!report.equals(lastReport) || System.currentTimeMillis() >= lastPrintTime + printInterval) { console.printInfo(report); lastPrintTime = System.currentTimeMillis(); } return report; } private String logStatus(Map<String, Progress> progressMap, String lastReport, LogHelper console) { String report = getReport(progressMap); if (!report.equals(lastReport) || System.currentTimeMillis() >= lastPrintTime + printInterval) { console.logInfo(report); lastPrintTime = System.currentTimeMillis(); } return report; } private String getReport(Map<String, Progress> progressMap) { StringBuffer reportBuffer = new StringBuffer(); SortedSet<String> keys = new TreeSet<String>(progressMap.keySet()); for (String s: keys) { Progress progress = progressMap.get(s); final int complete = progress.getSucceededTaskCount(); final int total = progress.getTotalTaskCount(); final int running = progress.getRunningTaskCount(); final int failed = progress.getFailedTaskAttemptCount(); if (total <= 0) { reportBuffer.append(String.format("%s: -/-\t", s)); } else { if (complete == total && !completed.contains(s)) { completed.add(s); /* * We may have missed the start of the vertex due to the 3 seconds interval */ if (!perfLogger.startTimeHasMethod(PerfLogger.TEZ_RUN_VERTEX + s)) { perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.TEZ_RUN_VERTEX + s); } perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.TEZ_RUN_VERTEX + s); } if(complete < total && (complete > 0 || running > 0 || failed > 0)) { if (!perfLogger.startTimeHasMethod(PerfLogger.TEZ_RUN_VERTEX + s)) { perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.TEZ_RUN_VERTEX + s); } /* vertex is started, but not complete */ if (failed > 0) { reportBuffer.append(String.format("%s: %d(+%d,-%d)/%d\t", s, complete, running, failed, total)); } else { reportBuffer.append(String.format("%s: %d(+%d)/%d\t", s, complete, running, total)); } } else { /* vertex is waiting for input/slots or complete */ if (failed > 0) { /* tasks finished but some failed */ reportBuffer.append(String.format("%s: %d(-%d)/%d\t", s, complete, failed, total)); } else { reportBuffer.append(String.format("%s: %d/%d\t", s, complete, total)); } } } } return reportBuffer.toString(); } }
HIVE-10129: LLAP: Fix ordering of execution modes git-svn-id: 5b3ec70fd98a55cad8bf91b276c6694e6bfee275@1669722 13f79535-47bb-0310-9956-ffa450edef68
ql/src/java/org/apache/hadoop/hive/ql/exec/tez/TezJobMonitor.java
HIVE-10129: LLAP: Fix ordering of execution modes
<ide><path>l/src/java/org/apache/hadoop/hive/ql/exec/tez/TezJobMonitor.java <ide> String mode = "container"; <ide> BaseWork work = workMap.get(name); <ide> if (work != null) { <del> if (work.getLlapMode()) { <add> // uber > llap > container <add> if (work.getUberMode()) { <add> mode = "uber"; <add> } else if (work.getLlapMode()) { <ide> mode = "llap"; <del> } else if (work.getUberMode()) { <del> mode = "uber"; <ide> } else { <ide> mode = "container"; <ide> }
JavaScript
mit
5532f65f7bb902135e418e31c3a4205f76c968f4
0
Kashomon/gpub,Kashomon/gpub,Kashomon/gpub
/** * Default options for GPub API. */ gpub.defaultOptions = { /** * Array of SGF (strings). No default is specified here: Must be explicitly * passed in every time. */ // sgfs: [], /** * The format of the 'book' output that is produced by GPub. * See gpub.outputFormat. */ outputFormat: 'LATEX', /** * What is the purpose for the book? I.e., Commentary, Problem book, * Combination-book. * See gpub.bookPurpose. */ bookPurpose: 'GAME_COMMENTARY', /** * Default board region for cropping purposes. * See glift.enums.boardRegions. */ // TODO(kashomon): Should this even be here? boardRegion: 'AUTO', /** * The type of diagrams produced by GPub. * * Ideally you would be able to use any diagramType in an outputFormat, but * that is not currently the case. Moreover, some output formats (e.g., * glift, smartgo) take charge of generating the diagrams. * * However, there are some types that are output format independent: * - ASCII, * - PDF, * - EPS * * See gpub.diagrams.diagramType. */ diagramType: 'GNOS', /** * The size of the page. Element of gpub.book.page.type. */ pageSize: 'LETTER', /** Skip the first N diagrams. Allows users to generate parts of a book. */ skipDiagrams: 0, /** * Maximum diagrams generated -- allows users to specify a section of the * book. 0 indicates that all subsequent diagrams are generated. */ maxDiagrams: 0, /** * Override the default template. * A false-y template will result in using the default template. */ template: null, /** * Whether or not to perform box-cropping on variations. */ autoBoxCropOnVariation: false, /** * List of autocropping preferences. Each element in the array should be a * member of glift.enums.boardRegions. * * Note: this may change if we ever support minimal/close-cropping. */ regionRestrictions: [], //////////////////////////// // DiagramSpecificOptions // //////////////////////////// /** Size of the gnos font */ // TODO(kashomon): Make this diagram-agnostic. gnosFontSize: '12', /** * Whether or not to generate PDF/X-1a compatibile PDFs. Note: this only * applies to output formats that generate PDFs (latex). */ pdfx1a: false, /** * An option only for PDF/X-1a. For this spceification, you must specify a * color profile file (e.g., ISOcoated_v2_300_eci.icc). */ colorProfileFilePath: null, ////////////////// // Book Options // ////////////////// /** Options specifically for book processors */ bookOptions: { /** * init: Any additional setup that needs to be done in the header. I.e., * for diagram packages. */ init: '', title: 'My Book', subtitle: null, publisher: 'GPub', authors: [ // 'Created by GPub' ], year: null, /** * Frontmatter is text supporting the bulk of the the work that comes * before/after the mainmatter of the book. * * Note: It's expected that the frontmatter (except for the copyright page) * will be specified as a markdown-string. * * Not all of these will be supported by all the book-generators. For those * that do support the relevant sections, the frontmatter and backmatter are * dumped into the book options. */ frontmatter: { // copyright: null, // AKA Colophon Page // epigraph: null, // AKA Quote Page foreward: null, // Author or unrelated person preface: null, // Author acknowledgements: null, introduction: null, /** Generate the Table of Contents or just 'Contents'. */ generateToc: true, /** * Generates the copyright page. Copyright should be an object with the * format listed below: * * { * "publisher": "Foo Publisher", * "license": "All rights reserved.", * "publishYear": 2015, * "firstEditionYear": 2015, * "isbn": "1-1-123-123456-1", * "issn": "1-123-12345-1", * "addressLines": [ * "PO #1111", * "1111 Mainville Road Rd, Ste 120", * "Fooville", * "CA 90001", * "www.fooblar.com" * ], * "showPermanenceOfPaper": true, * "printingRunNum": 1 * } */ copyright: null } }, /** * Whether or not debug information should be displayed. */ debug: false }; /** * The type general type of the book. Specifes roughly how we generate the * Glift spec. */ gpub.bookPurpose = { /** Game with commentary. */ GAME_COMMENTARY: 'GAME_COMMENTARY', /** Set of problems and, optionally, anwsers. */ PROBLEM_SET: 'PROBLEM_SET', /** A set of problems processed specifically for book consumption. */ PROBLEM_BOOK: 'PROBLEM_BOOK' }; /** * The format for gpub output. */ gpub.outputFormat = { /** Construct a book with a LaTeX format. */ LATEX: 'LATEX', /** Constructs a full HTML page. This is often useful for testing. */ HTMLPAGE: 'HTMLPAGE', /** Construct a book in ASCII format. */ ASCII: 'ASCII' /** Construct a book in Smart Go format. */ // SMART_GO: 'SMART_GO' // Future Work: // - ONLY_DIAGRAMS // - ASCII // - SmartGo Books }; /** * Process the incoming options and set any missing values. */ gpub.processOptions = function(options) { var newo = {}; var options = options || {}; var simpleTemplate = function(target, base, template) { for (var key in template) { if (key === 'sgfs') { // We don't want to be duplicating the SGFs, so we assume that the SGFs // have been extracted at this point. continue; } if (newo[key] !== undefined) { // We've already copied this key continue; } var val = base[key]; // Note: we treat null and empty string as intentionally falsey values, // thus we only rely on default behavior in the case of if (val !== undefined) { target[key] = base[key]; } else { target[key] = template[key]; } } return target; }; var bookOptions = options.bookOptions || {}; var frontmatter = bookOptions.frontmatter || {}; var t = gpub.defaultOptions; simpleTemplate( newo, options, t); simpleTemplate( newo.bookOptions, bookOptions, t.bookOptions); simpleTemplate( newo.bookOptions.frontmatter, frontmatter, t.bookOptions.frontmatter); if (newo.skipDiagrams < 0) { throw new Error('skipDiagrams cannot be less than 0'); } if (newo.maxDiagrams < 0) { throw new Error('maxDiagrams cannot be less than 0'); } gpub.validateOptions(newo); return newo; }; /** * Validate the options and return the passed-in obj. */ gpub.validateOptions = function(newo) { var keys = [ 'outputFormat', 'bookPurpose', 'boardRegion', 'diagramType', 'pageSize' ]; var parentObjs = [ gpub.outputFormat, gpub.bookPurpose, glift.enums.boardRegions, gpub.diagrams.diagramType, gpub.book.page.type ]; if (keys.length !== parentObjs.length) { throw new Error('Programming error! Keys and parent objs not same length'); } for (var i = 0; i < keys.length; i++) { var k = keys[i]; var value = newo[k]; if (!parentObjs[i].hasOwnProperty(value)) { throw new Error('Value: ' + value + ' for property ' + k + ' unrecognized'); } } return newo; };
src/api/options.js
/** * Default options for GPub API. */ gpub.defaultOptions = { /** * Array of SGF (strings). No default is specified here: Must be explicitly * passed in every time. */ // sgfs: [], /** * The format of the 'book' output that is produced by GPub. * See gpub.outputFormat. */ outputFormat: 'LATEX', /** * What is the purpose for the book? I.e., Commentary, Problem book, * Combination-book. * See gpub.bookPurpose. */ bookPurpose: 'GAME_COMMENTARY', /** * Default board region for cropping purposes. * See glift.enums.boardRegions. */ // TODO(kashomon): Should this even be here? boardRegion: 'AUTO', /** * The type of diagrams produced by GPub. * * Ideally you would be able to use any diagramType in an outputFormat, but * that is not currently the case. Moreover, some output formats (e.g., * glift, smartgo) take charge of generating the diagrams. * * However, there are some types that are output format independent: * - ASCII, * - PDF, * - EPS * * See gpub.diagrams.diagramType. */ diagramType: 'GNOS', /** * The size of the page. Element of gpub.book.page.type. */ pageSize: 'LETTER', /** Skip the first N diagrams. Allows users to generate parts of a book. */ skipDiagrams: 0, /** * Maximum diagrams generated -- allows users to specify a section of the * book. 0 indicates that all subsequent diagrams are generated. */ maxDiagrams: 0, /** * Override the default template. * A false-y template will result in using the default template. */ template: null, /** * Whether or not to perform box-cropping on variations. */ autoBoxCropOnVariation: false, /** * List of autocropping preferences. Each element in the array should be a * member of glift.enums.boardRegions. * * Note: this may change if we ever support minimal/close-cropping. */ regionRestrictions: [], //////////////////////////// // DiagramSpecificOptions // //////////////////////////// /** Size of the gnos font */ gnosFontSize: '12', /** * Whether or not to generate PDF/X-1a compatibile PDFs. Note: this only * applies to output formats that generate PDFs (latex). */ pdfx1a: false, /** * An option only for PDF/X-1a. For this spceification, you must specify a * color profile file (e.g., ISOcoated_v2_300_eci.icc). */ colorProfileFilePath: null, ////////////////// // Book Options // ////////////////// /** Options specifically for book processors */ bookOptions: { /** * init: Any additional setup that needs to be done in the header. I.e., * for diagram packages. */ init: '', title: 'My Book', subtitle: null, publisher: 'GPub', authors: [ // 'Created by GPub' ], year: null, /** * Frontmatter is text supporting the bulk of the the work that comes * before/after the mainmatter of the book. * * Note: It's expected that the frontmatter (except for the copyright page) * will be specified as a markdown-string. * * Not all of these will be supported by all the book-generators. For those * that do support the relevant sections, the frontmatter and backmatter are * dumped into the book options. */ frontmatter: { // copyright: null, // AKA Colophon Page // epigraph: null, // AKA Quote Page foreward: null, // Author or unrelated person preface: null, // Author acknowledgements: null, introduction: null, /** Generate the Table of Contents or just 'Contents'. */ generateToc: true, /** * Generates the copyright page. Copyright should be an object with the * format listed below: * * { * "publisher": "Foo Publisher", * "license": "All rights reserved.", * "publishYear": 2015, * "firstEditionYear": 2015, * "isbn": "1-1-123-123456-1", * "issn": "1-123-12345-1", * "addressLines": [ * "PO #1111", * "1111 Mainville Road Rd, Ste 120", * "Fooville", * "CA 90001", * "www.fooblar.com" * ], * "showPermanenceOfPaper": true, * "printingRunNum": 1 * } */ copyright: null } }, /** * Whether or not debug information should be displayed. */ debug: false }; /** * The type general type of the book. Specifes roughly how we generate the * Glift spec. */ gpub.bookPurpose = { /** Game with commentary. */ GAME_COMMENTARY: 'GAME_COMMENTARY', /** Set of problems and, optionally, anwsers. */ PROBLEM_SET: 'PROBLEM_SET', /** A set of problems processed specifically for book consumption. */ PROBLEM_BOOK: 'PROBLEM_BOOK' }; /** * The format for gpub output. */ gpub.outputFormat = { /** Construct a book with a LaTeX format. */ LATEX: 'LATEX', /** Constructs a full HTML page. This is often useful for testing. */ HTMLPAGE: 'HTMLPAGE', /** Construct a book in ASCII format. */ ASCII: 'ASCII' /** Construct a book in Smart Go format. */ // SMART_GO: 'SMART_GO' // Future Work: // - ONLY_DIAGRAMS // - ASCII // - SmartGo Books }; /** * Process the incoming options and set any missing values. */ gpub.processOptions = function(options) { var newo = {}; var options = options || {}; var simpleTemplate = function(target, base, template) { for (var key in template) { if (key === 'sgfs') { // We don't want to be duplicating the SGFs, so we assume that the SGFs // have been extracted at this point. continue; } if (newo[key] !== undefined) { // We've already copied this key continue; } var val = base[key]; // Note: we treat null and empty string as intentionally falsey values, // thus we only rely on default behavior in the case of if (val !== undefined) { target[key] = base[key]; } else { target[key] = template[key]; } } return target; }; var bookOptions = options.bookOptions || {}; var frontmatter = bookOptions.frontmatter || {}; var t = gpub.defaultOptions; simpleTemplate( newo, options, t); simpleTemplate( newo.bookOptions, bookOptions, t.bookOptions); simpleTemplate( newo.bookOptions.frontmatter, frontmatter, t.bookOptions.frontmatter); if (newo.skipDiagrams < 0) { throw new Error('skipDiagrams cannot be less than 0'); } if (newo.maxDiagrams < 0) { throw new Error('maxDiagrams cannot be less than 0'); } gpub.validateOptions(newo); return newo; }; /** * Validate the options and return the passed-in obj. */ gpub.validateOptions = function(newo) { var keys = [ 'outputFormat', 'bookPurpose', 'boardRegion', 'diagramType', 'pageSize' ]; var parentObjs = [ gpub.outputFormat, gpub.bookPurpose, glift.enums.boardRegions, gpub.diagrams.diagramType, gpub.book.page.type ]; if (keys.length !== parentObjs.length) { throw new Error('Programming error! Keys and parent objs not same length'); } for (var i = 0; i < keys.length; i++) { var k = keys[i]; var value = newo[k]; if (!parentObjs[i].hasOwnProperty(value)) { throw new Error('Value: ' + value + ' for property ' + k + ' unrecognized'); } } return newo; };
Note about fontsize.
src/api/options.js
Note about fontsize.
<ide><path>rc/api/options.js <ide> //////////////////////////// <ide> <ide> /** Size of the gnos font */ <add> // TODO(kashomon): Make this diagram-agnostic. <ide> gnosFontSize: '12', <ide> <ide> /**
JavaScript
mit
2e196c9b614431f973e0e6d4a8b0e2478c047ee7
0
ezfe/tellraw,ezfe/tellraw,ezfe/tellraw
var chars = [1,2,3,4,5,6,7,8,9,0,'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']; var matchLength = 0; var version = 3; var tos_version = 1; var notice = { "show": false, "id": 8, "message": { "title": "Updated...", "text": "Hi", "type": "info" } }; var jobject = []; var selectedHover; var selectedClick; var selectedHover_edit; var selectedClick_edit; var downButton; var upButton; var extraTextFormat = 'raw'; var lang = {"status":"init"}; var currentEdit; var hasAlertedTranslationObjects = false; var webLangRelations; var editing = false; var issueLog = []; var bookPage = 1; var topPage = 1; var embed = false; var lsm = {}; lsm.enabled = false; lsm.storage = {}; lsm.setItem = function(key, value) { try { localStorage.setItem(key, value); } catch(e) { lsm.enabled = true; lsm.storage[key] = value; } } lsm.getItem = function(key) { if (lsm.enabled) { return lsm.storage[key]; } else { return localStorage.getItem(key); } } lsm.clear = function() { if (lsm.enabled) { lsm.storage = {}; } else { localStorage.clear(); } } lsm.removeItem = function(key) { if (lsm.enabled) { delete lsm.storage[key]; } else { localStorage.removeItem(key); } } /* http://stackoverflow.com/a/728694/2059595 */ function clone(obj) { var copy; // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { copy = []; for (var i = 0, len = obj.length; i < len; i++) { copy[i] = clone(obj[i]); } return copy; } // Handle Object if (obj instanceof Object) { copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); } function alert(message) { return swal(message); } function reportAnIssue(ptitle) { var title = ""; var body = ""; if (ptitle != undefined) { title = "Issue Report - " + ptitle; body = 'Please enter steps to reproduce the issue below, as well as any other information you want to include%0A%0A%0A%0A%0A%0A Provided Data - Do not modify below this line%0A%0A```%0A' + JSON.stringify(jobject) + '%0A```'; } var win = window.open('http://github.com/ezfe/tellraw/issues/new?body=' + body + '&title=' + title, '_blank'); win.focus(); } function getLanguageName(langCode) { var name = lang[langCode].language.name; if (name == "English" && langCode != "en-US") { return langCode } else { return name } } function showIssue() { swal(issueLog[issueLog.length - 1].name,issueLog[issueLog.length - 1].data,'error'); } function logIssue(name,data,critical) { issueLog.push({"name":name,"data":data}); if (critical) { swal(name,data,'error'); } } function showView(viewname,suppressAnimation,hideOthers,hideMenubar) { var hideMenubarOriginal = hideMenubar; if (embed) { hideMenubar = true; } var toHide = $('.view-container').not('.view-container[view="' + viewname + '"]'); if (!hideMenubar) { toHide = toHide.not('.view-container[view="pageheader"]'); } var toShow = $('.view-container[view="' + viewname + '"]'); if (!hideMenubar) { $($('.view-container[view="pageheader"]')).show(); } if (hideOthers === false) { toHide = $(''); } if (suppressAnimation) { toHide.hide(); toShow.show(); } else { toHide.slideUp(); toShow.slideDown(); } if (viewname != "loading" && viewname != "pageheader" && viewname != "issue") { lsm.setItem('jview',JSON.stringify({"viewname":viewname,"suppressAnimation":suppressAnimation,"hideOthers":hideOthers,"hideMenubar":hideMenubar})); } if (toShow.length == 0) { logIssue('Missing View',viewname,true); showView('tellraw'); } } function getURL(url){ return $.ajax({ type: "GET", url: url, cache: false, async: false }).responseText; } function verify_jobject_format(jdata) { var resetError = JSON.stringify({"title": "Object Verification Failed", "text": "An error occured and the page has been reset", "type": "error"}); if (get_type(jdata) == "[object Object]") { if (get_type(jdata.extra) == "[object Array]") { jdata = jdata.extra; } else { sessionStorage.setItem('nextTimeAlert',resetError); lsm.clear(); location.reload(); return; } } if (get_type(jdata) != "[object Array]") { sessionStorage.setItem('nextTimeAlert',resetError); lsm.clear(); location.reload(); return; } if (jdata.text != '' && get_type(jdata) != "[object Array]") { jdata.unshift(new Object()); jdata[0].text = jdata.text; jdata[0].color = jdata.color; delete(jdata.color); jdata[0].bold = jdata.bold; delete(jdata.bold); jdata[0].italic = jdata.italic; delete(jdata.italic); jdata[0].underlined = jdata.underlined; delete(jdata.underline); jdata[0].strikethrough = jdata.strikethrough; delete(jdata.strikethrough); jdata[0].obfuscated = jdata.obfuscated; delete(jdata.obfuscated); jdata.text = ''; } //Tracks changes for "true" --> true var booleanUpdateCount = 0; for (var i = 0; i < jdata.length; i++) { //Convert show_text to structured format if (jdata[i].hoverEvent != undefined) { if (jdata[i].hoverEvent.action == "show_text") { if (typeof jdata[i].hoverEvent.value == "object") { if (jdata[i].hoverEvent.value.text != "") { jdata[i].hoverEvent.value = {"text":"", "extra":[jdata[i].hoverEvent.value]}; } } else if (typeof jdata[i].hoverEvent.value == "string") { jdata[i].hoverEvent.value = {"text":"", "extra":[{"text":jdata[i].hoverEvent.value}]}; } } } if (jdata[i].bold == "true") { jdata[i].bold = true; booleanUpdateCount++; } else if (jdata[i].bold !== true) { delete jdata[i].bold; } if (jdata[i].italic == "true") { jdata[i].italic = true; booleanUpdateCount++; } else if (jdata[i].italic !== true) { delete jdata[i].italic; } if (jdata[i].underlined == "true") { jdata[i].underlined = true; booleanUpdateCount++; } else if (jdata[i].underlined !== true) { delete jdata[i].underlined; } if (jdata[i].strikethrough == "true") { jdata[i].strikethrough = true; booleanUpdateCount++; } else if (jdata[i].strikethrough !== true) { delete jdata[i].strikethrough; } if (jdata[i].obfuscated == "true") { jdata[i].obfuscated = true; booleanUpdateCount++; } else if (jdata[i].obfuscated !== true) { delete jdata[i].obfuscated; } } if (booleanUpdateCount > 0) { swal({"title": "Udated!", "text": "All strings representing boolean values have been updated to true/false values (" + booleanUpdateCount + " change" + (booleanUpdateCount == 1 ? "" : "s") + ")", "type": "success"}); } return jdata; } function strictifyItem(job,index) { var joi = job[index]; if (index == 0 || job[index - 1].NEW_ITERATE_FLAG || job[index].NEW_ITERATE_FLAG) { return joi; } var prejoi = job[index - 1]; for (var i = 0; i < Object.keys(prejoi).length; i++) { var key = Object.keys(prejoi)[i]; var doNotCheckKeys = ["text", "score", "selector", "color", "clickEvent", "hoverEvent", "insertion"] if (doNotCheckKeys.indexOf(key) == -1) { if (prejoi[key] === true && joi[key] === undefined) { joi[key] = false; } } else { if (key == "color") { if (joi["color"] === undefined) { joi["color"] = noneName(); } }/* else if (key == "hoverEvent" || key == "clickEvent") { if (joi[key] == undefined) { // DO SOMETHING } }*/ continue; } } return joi; } function strictifyJObject(job) { for (var x = 0; x < job.length; x++) { job[x] = strictifyItem(job,x); } return job; } function formatJObjectList(d) { data = strictifyJObject(clone(d)); if (data.length == 0) { return []; } var ret_val = []; var currentDataToPlug = [""]; for (var i = 0; i < data.length; i++) { if (data[i].NEW_ITERATE_FLAG) { ret_val.push(JSON.stringify(currentDataToPlug)); currentDataToPlug = [""]; } else { currentDataToPlug.push(data[i]); } } if (!data[data.length - 1].NEW_ITERATE_FLAG) { ret_val.push(JSON.stringify(currentDataToPlug)); } return ret_val; } function closeExport() { $('#exporter').remove(); } function isScrolledIntoView(elem) { elem = '#' + elem; var docViewTop = $(window).scrollTop(); var docViewBottom = docViewTop + $(window).height(); var elemTop = $(elem).offset().top; var elemBottom = elemTop + $(elem).height(); return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)); } function goToByScroll(id){ if (!isScrolledIntoView(id)) { $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow'); } } var templates = { "tellraw": { "command": "/tellraw @p %s", "version": "1.7", "formatType": "standardjson", "mouseActionOptions": true }, "execute_tellraw": { "command": "/execute @a ~ ~ ~ tellraw @p %s", "version": "1.8", "formatType": "standardjson", "mouseActionOptions": true }, "title": { "command": "/title @a title %s", "version": "1.8", "formatType": "standardjson", "mouseActionOptions": false }, "subtitle": { "command": "/title @a subtitle %s", "version": "1.8", "formatType": "standardjson", "mouseActionOptions": false }, "sign_item": { "command": "/give @p sign 1 0 {BlockEntityTag:{%s,id:\"Sign\"}}", "version": "1.8", "formatType": "signset", "mouseActionOptions": false }, "sign_block": { "command": "/blockdata [x] [y] [z] {%s}", "version": "1.8", "formatType": "signset", "mouseActionOptions": false }, "book": { "command": "/give @p written_book 1 0 {pages:%s,title:Book,author:TellrawGenerator}", "version": "1.8", "formatType": "bookarray", "mouseActionOptions": true } } /* (c) 2012 Steven Levithan <http://slevithan.com/> MIT license */ if (!String.prototype.codePointAt) { String.prototype.codePointAt = function (pos) { pos = isNaN(pos) ? 0 : pos; var str = String(this), code = str.charCodeAt(pos), next = str.charCodeAt(pos + 1); // If a surrogate pair if (0xD800 <= code && code <= 0xDBFF && 0xDC00 <= next && next <= 0xDFFF) { return ((code - 0xD800) * 0x400) + (next - 0xDC00) + 0x10000; } return code; }; } function setObfuscatedString(string) { var output = ""; for (var i = string.length - 1; i >= 0; i--) { string[i] output = output + chars[Math.floor(Math.random() * chars.length)]; }; return output; } function saveJObject() { swal({ title: "Please enter a save name.", text: "If you enter an existing one, it will overwrite it.", type: "input", showCancelButton: true, closeOnConfirm: false }, function(inputValue) { inputValue = inputValue.replace(' ','_'); if (inputValue == '' || inputValue == undefined || new RegExp('[^a-zA-Z0-9_]').test(inputValue)) { swal('Invalid Save Name!','Please omit special characters','error'); } else { var saveTo = inputValue var saveSlot = 'saveSlot_' + saveTo; var overwrite = false; if (lsm.getItem(saveSlot) != undefined) { overwrite = true; } lsm.setItem('currentSaveSlot',saveTo); lsm.setItem(saveSlot, JSON.stringify({"command": $('#command').val(), "jobject": jobject})); if (overwrite) { swal({ title: 'Saved your current revision to <code>' + saveTo.replace('_', ' ') + '</code>, overwriting your previous save to that slot', html: true }); } else { swal({ title: 'Saved your current revision to <code>' + saveTo.replace('_', ' ') + '</code>, which created a new saveSlot', html: true }); } refreshSavesList(); refreshOutput(); } }); } function loadJObject(saveName) { var saveItem = getJObject(saveName); jobject = saveItem.jobject; $('#command').val(saveItem.command); swal('Loaded save `' + saveName + '`','','success'); refreshSavesList(); refreshOutput(); } function doesJObjectExist(saveName) { var saveSlot = 'saveSlot_' + saveName; return lsm.getItem(saveSlot) != undefined; } function getJObject(saveName) { var saveSlot = 'saveSlot_' + saveName; return JSON.parse(lsm.getItem(saveSlot)); } function deleteAll() { swal({ "title": getLanguageString('settings.deleteall.heading',lsm.getItem('langCode')), "text": getLanguageString('settings.deleteall.body',lsm.getItem('langCode')), "cancelButtonText": getLanguageString('settings.deleteall.no',lsm.getItem('langCode')), "confirmButtonText": getLanguageString('settings.deleteall.yes',lsm.getItem('langCode')), "showCancelButton": true, "closeOnConfirm": false, "type": "warning" },function(isConfirm){ if (isConfirm) { jobject = []; $('.templateButton[template=tellraw]').click(); refreshOutput(); swal('Deleted!','Your current thing was deleted', 'success'); } }); } function clearJObjectSaves() { swal({ "title": getLanguageString('saves.deleteall.heading',lsm.getItem('langCode')), "text": getLanguageString('saves.deleteall.body',lsm.getItem('langCode')), "cancelButtonText": getLanguageString('saves.deleteall.no',lsm.getItem('langCode')), "confirmButtonText": getLanguageString('saves.deleteall.yes',lsm.getItem('langCode')), "showCancelButton": true, "closeOnConfirm": false, "type": "warning" },function(isConfirm){ if (isConfirm) { for (var x = 0; x < Object.keys(lsm).length; x++) { for (var i = 0; i < Object.keys(lsm).length; i++) { var key = Object.keys(lsm)[i]; if (key.indexOf('saveSlot_') != -1) { lsm.removeItem(key); } } } refreshSavesList(); swal('Deleted!','Your saves were deleted', 'success'); } }); } function obfuscationPreviewHandler() { $('.jsonPreviewObfuscated').html(setObfuscatedString($('.jsonPreviewObfuscated').html())); if ($('.jsonPreviewObfuscated').length > 0) { setTimeout(obfuscationPreviewHandler, 20); } } function currentTemplate() { return templates[lsm.getItem('jtemplate')]; } function noneHex() { if (currentTemplate().formatType == 'bookarray' || currentTemplate().formatType == 'signset') { return '#000000'; } else { return '#FFFFFF' } } function noneName() { return 'none'; /* I think none is the proper name */ // if (currentTemplate().formatType == 'bookarray' || currentTemplate().formatType == 'signset') { // return 'black'; // } else { // return 'white' // } } function getCSSHEXFromWord(w) { if (w == "black") return("#000000"); if (w == "dark_blue") return("#0000B2"); if (w == "dark_green") return("#14AB00"); if (w == "dark_aqua") return("#13AAAB"); if (w == "dark_red") return("#A90400"); if (w == "dark_purple") return("#A900B2"); if (w == "gold") return("#FEAC00"); if (w == "gray") return("#AAAAAA"); if (w == "dark_gray") return("#555555"); if (w == "blue") return("#544CFF"); if (w == "green") return("#5CFF00"); if (w == "aqua") return("#5BFFFF"); if (w == "red") return("#FD5650"); if (w == "light_purple") return("#FD4DFF"); if (w == "yellow") return("#FFFF00"); if (w == "white") return("#FFFFFF"); if (w == "none") return(noneHex()); return noneHex(); } function removeWhiteSpace(s) { return s; //BROKEN return s.replace(/ /g, ''); } function deleteIndex(index) { jobject.splice(index, 1); refreshOutput(); } function moveUp(index) { jobject.splice(index+1, 0, jobject.splice(index, 1)[0]); refreshOutput(); } function getSelected(object) { if ($('#'+object).length != 0) { var e = document.getElementById(object); return e.options[e.selectedIndex].value; } else { return false; } } function getSelectedIndex(object) { var e = document.getElementById(object); return e.selectedIndex; } function getChecked(id) { return document.getElementById(id).checked; } function clearExtra() { $('#fmtExtraRaw').click(); $("#clickEventText").val(""); $("#hoverEventText").val(""); $("#hoverEventValue").val(""); $("#hoverEventTextSnippet").val(""); $("#snippetcolor").val("none"); $('#snippetcolor').change(); $("#text_extra").val(""); $("#color_extra").val("none"); $("#clickEvent").val('none'); $("#hoverEvent").val('none'); $("#insertion_text").val(''); $("#bold_text_extra").prop("checked",false); $("#italic_text_extra").prop("checked",false); $("#underlined_text_extra").prop("checked",false); $("#strikethrough_text_extra").prop("checked",false); $("#obfuscated_text_extra").prop("checked",false); $('#hoverEventEntityName').val(''); $('#hoverEventEntityID').val(''); $('#hoverEventEntityType').val(''); $('#textsnippets_add').html(getLanguageString('textsnippets.addsnippet'),lsm.getItem('langCode')); $('#textsnippets-add-button').addClass('btn-default'); $('#textsnippets-add-button').removeClass('btn-danger'); $('#obj_player').val(''); $('#obj_score').val(''); $('#text_extra_container').removeClass('has-error'); refreshOutput(); } function editExtra(index) { editing = true; $('#snippetsWell').hide(); $('#editModalData').show(); currentEdit = index; if (jobject[index].text != undefined) { $('#obj_extra_container_edit').hide(); $('#text_extra_container_edit').show(); $('#translate_selector_container_edit').hide(); $('#selector_extra_container_edit').hide(); $('#text_extra_edit').val(jobject[index].text); } else if (jobject[index].selector != undefined) { $('#obj_extra_container_edit').hide(); $('#selector_extra_container_edit').show(); $('#text_extra_container_edit').hide(); $('#translate_selector_container_edit').hide(); $('#selector_edit').val(jobject[index].selector); } else if (jobject[index].translate != undefined) { $('#obj_extra_container_edit').hide(); $('#text_extra_container_edit').hide(); $('#selector_extra_container_edit').hide(); $('#translate_selector_container_edit').show(); if (!hasAlertedTranslationObjects) { swal('Translation objects are currently broken and may crash your game.','Please test your translation before publishing it.','warning'); hasAlertedTranslationObjects = true; } } else if (jobject[index].score != undefined) { $('#obj_extra_container_edit').show(); $('#text_extra_container_edit').hide(); $('#translate_selector_container_edit').hide(); $('#selector_extra_container_edit').hide(); $('#obj_player_edit').val(jobject[index].score.name); $('#obj_score_edit').val(jobject[index].score.objective); } refreshLanguage(); $('#colorPreviewColor_edit').css('background-color',getCSSHEXFromWord(jobject[index].color)); if (jobject[index].color != undefined) { $("#color_extra_edit").val(jobject[index].color); } else { $("#color_extra_edit").val('none'); } if (jobject[index].bold != undefined) { $('#bold_text_extra_edit').prop('checked',true); } else { $('#bold_text_extra_edit').prop('checked',false); } if (jobject[index].italic != undefined) { $('#italic_text_extra_edit').prop('checked',true); } else { $('#italic_text_extra_edit').prop('checked',false); } if (jobject[index].underlined != undefined) { $('#underlined_text_extra_edit').prop('checked',true); } else { $('#underlined_text_extra_edit').prop('checked',false); } if (jobject[index].strikethrough != undefined) { $('#strikethrough_text_extra_edit').prop('checked',true); } else { $('#strikethrough_text_extra_edit').prop('checked',false); } if (jobject[index].obfuscated != undefined) { $('#obfuscated_text_extra_edit').prop('checked',true); } else { $('#obfuscated_text_extra_edit').prop('checked',false); } if (jobject[index].clickEvent != undefined) { $('#clickEvent_edit').val(jobject[index].clickEvent.action); $('#clickEventText_edit').val(jobject[index].clickEvent.value); } else { $('#clickEvent_edit').val('none'); $('#clickEventText_edit').val(''); } if (jobject[index].hoverEvent != undefined) { $('#hoverEvent_edit').val(jobject[index].hoverEvent.action); if ($('#hoverEvent_edit').val() != 'show_entity') { if (jobject[index].hoverEvent.action == 'show_text') { $('#hoverEventText_edit').val(JSON.stringify(jobject[index].hoverEvent.value)); } else { $('#hoverEventText_edit').val(jobject[index].hoverEvent.value); } } else { $('#hoverEventEntityID_edit').val(jobject[index].hoverEvent.value.match(/id:([a-zA-Z0-9]+)/g )[0].replace('id:','')); $('#hoverEventEntityName_edit').val(jobject[index].hoverEvent.value.match(/name:([a-zA-Z0-9]+)/g )[0].replace('name:','')); $('#hoverEventEntityType_edit').val(jobject[index].hoverEvent.value.match(/type:([a-zA-Z0-9]+)/g )[0].replace('type:','')); } } else { $('#hoverEvent_edit').val('none'); $('#hoverEventText_edit').val(''); } if (jobject[index].insertion != undefined) { $('#insertion_text_edit').val(jobject[index].insertion); } refreshOutput(); } function cancelExtraEdit() { $('#editModalData').hide(); $('#snippetsWell').show(); } function saveExtraEdit() { editing = false; extraIndex = currentEdit; jobject[extraIndex].color = getSelected("color_extra_edit"); if (jobject[extraIndex].color == 'none') { delete jobject[extraIndex].color; } if ($('#obj_extra_container_edit').is(":visible")) { jobject[extraIndex].score = new Object; jobject[extraIndex].score.name = $('#obj_player_edit').val(); jobject[extraIndex].score.objective = $('#obj_score_edit').val(); } else if ($('#text_extra_container_edit').is(":visible")) { jobject[extraIndex].text = $('#text_extra_edit').val(); } else if ($('#selector_extra_container_edit').is(":visible")) { jobject[extraIndex].selector = $('#selector_edit').val(); } else if ($('#translate_selector_container_edit').is(":visible")) { jobject[extraIndex].translate = $('#translate_input_edit').val(); if (matchLength != 0) { if (get_type(jobject.with) != "[object Array]") { jobject[extraIndex].with = new Array(); } for (var i = 0; i < matchLength; i++) { jobject[extraIndex].with[i] = $('#extraTranslationParameter'+i+'_edit').val(); }; } } else { swal('An unexpected error occured.'); } delete jobject[extraIndex].bold; delete jobject[extraIndex].italic; delete jobject[extraIndex].underlined; delete jobject[extraIndex].strikethrough; delete jobject[extraIndex].obfuscated; if (getChecked("bold_text_extra_edit")) { jobject[extraIndex].bold = true; } if (getChecked("italic_text_extra_edit")) { jobject[extraIndex].italic = true; } if (getChecked("underlined_text_extra_edit")) { jobject[extraIndex].underlined = true; } if (getChecked("strikethrough_text_extra_edit")) { jobject[extraIndex].strikethrough = true; } if (getChecked("obfuscated_text_extra_edit")) { jobject[extraIndex].obfuscated = true; } delete jobject[extraIndex].clickEvent; delete jobject[extraIndex].hoverEvent; var clickEventType_edit = $("#clickEvent_edit").val(); var hoverEventType_edit = $("#hoverEvent_edit").val(); if (clickEventType_edit != "none") { jobject[extraIndex].clickEvent = new Object(); jobject[extraIndex].clickEvent.action = clickEventType_edit; jobject[extraIndex].clickEvent.value = $('#clickEventText_edit').val(); if (clickEventType_edit == "run_command" || clickEventType_edit == "suggest_command") { if ($('#clickEventText_edit').val().length > 90) { swal('Commands cannot be longer than 90 characters!','You should edit the length of your command before using this in game.','error'); } } } if (hoverEventType_edit != "none") { jobject[extraIndex].hoverEvent = new Object(); jobject[extraIndex].hoverEvent.action = hoverEventType_edit; if (hoverEventType_edit == 'show_text') { try { jobject[extraIndex].hoverEvent.value = JSON.parse($('#hoverEventText_edit').val()); } catch(err) { jobject[extraIndex].hoverEvent.value = {"text":"","extra":[{"text":$('#hoverEventText_edit').val()}]}; } } else { jobject[extraIndex].hoverEvent.value = $('#hoverEventText_edit').val(); } } if (hoverEventType_edit == "show_entity") { if ($('#hoverEventEntityID_edit').val() == '') { $('#hoverEventEntityID_edit').val('(ID)') } if ($('#hoverEventEntityName_edit').val() == '') { $('#hoverEventEntityName_edit').val('(Name)') } if ($('#hoverEventEntityType_edit').val() == '') { $('#hoverEventEntityType_edit').val('(Type)') } jobject[extraIndex].hoverEvent.value = '{id:'+removeWhiteSpace($('#hoverEventEntityID_edit').val())+',name:'+removeWhiteSpace($('#hoverEventEntityName_edit').val())+',type:'+removeWhiteSpace($('#hoverEventEntityType_edit').val())+'}'; } if ($('#insertion_text_edit').val() != '') { jobject[extraIndex].insertion = $('#insertion_text_edit').val(); } else { delete jobject[extraIndex].insertion; } $('#editModalData').hide(); $('#snippetsWell').show(); refreshOutput(); } function clearExtraText() { delete jobject; refreshOutput(); } function get_type(thing){ if (thing===null) { return "[object Null]"; } return Object.prototype.toString.call(thing); } function modifyExtraText(index,text) { if (text != "" && text != null) { jobject[index].text = text; } refreshOutput(); } function cancelAddExtra() { showView('tellraw'); clearExtra(); } function addExtra() { editing = false; if (extraTextFormat == 'raw' && $('#text_extra').val() == '') { $('#text_extra_container').addClass('has-error'); $('#text_extra').focus(); $('#textsnippets-add-button').removeClass('btn-default'); $('#textsnippets-add-button').addClass('btn-danger'); return false; } else if ($("#hoverEvent").val() == 'show_text' && $('#hoverEventTextSnippet').val() != '') { swal('You entered text, but never added it!'); $('#hoverEventTextSnippet').focus(); $('#textsnippets-add-button').removeClass('btn-default'); $('#textsnippets-add-button').addClass('btn-danger'); return false; } else { showView('tellraw'); } if (get_type(jobject) != "[object Array]") { jobject = []; } if (extraTextFormat == 'NEW_ITERATE_FLAG') { jobject.push({"NEW_ITERATE_FLAG":true}); } else { var clickEventType = $("#clickEvent").val(); var hoverEventType = $("#hoverEvent").val(); jobject.push(new Object()); var extraIndex = jobject.length - 1; if (extraTextFormat == 'trn') { jobject[extraIndex].translate = $('#translate_input').val(); if (matchLength != 0) { if (get_type(jobject.with) != "[object Array]") { jobject[extraIndex].with = new Array(); } for (var i = 0; i < matchLength; i++) { jobject[extraIndex].with[i] = $('#extraTranslationParameter'+i).val(); }; } } else if (extraTextFormat == 'raw') { jobject[extraIndex].text = $('#text_extra').val(); } else if (extraTextFormat == 'obj') { jobject[extraIndex].score = new Object; jobject[extraIndex].score.name = $('#obj_player').val(); jobject[extraIndex].score.objective = $('#obj_score').val(); } else if (extraTextFormat == 'sel') { jobject[extraIndex].selector = $('#selector').val(); } jobject[extraIndex].color = getSelected("color_extra"); if (jobject[extraIndex].color == 'none') { delete jobject[extraIndex].color; } if (getChecked("bold_text_extra")) { jobject[extraIndex].bold = true; } if (getChecked("italic_text_extra")) { jobject[extraIndex].italic = true; } if (getChecked("underlined_text_extra")) { jobject[extraIndex].underlined = true; } if (getChecked("strikethrough_text_extra")) { jobject[extraIndex].strikethrough = true; } if (getChecked("obfuscated_text_extra")) { jobject[extraIndex].obfuscated = true; } if (clickEventType != "none") { jobject[extraIndex].clickEvent = new Object(); jobject[extraIndex].clickEvent.action = clickEventType; jobject[extraIndex].clickEvent.value = $('#clickEventText').val(); if (clickEventType == "run_command" || clickEventType == "suggest_command") { if ($('#clickEventText').val().length > 90) { swal('Commands cannot be longer than 90 characters!','You should edit the length of your command before using this in game.','error'); } } } if (hoverEventType != "none") { jobject[extraIndex].hoverEvent = new Object(); jobject[extraIndex].hoverEvent.action = hoverEventType; if (hoverEventType == 'show_text') { jobject[extraIndex].hoverEvent.value = JSON.parse($('#hoverEventText').val()); if ($('#color_hover').val() != 'none') { jobject[extraIndex].hoverEvent.value.color = $('#color_hover').val(); } } else { jobject[extraIndex].hoverEvent.value = $('#hoverEventValue').val(); } } if (hoverEventType == "show_entity") { if ($('#hoverEventEntityID').val() == '') { $('#hoverEventEntityID').val('(ID)') } if ($('#hoverEventEntityName').val() == '') { $('#hoverEventEntityName').val('(Name)') } if ($('#hoverEventEntityType').val() == '') { $('#hoverEventEntityType').val('(Type)') } jobject[extraIndex].hoverEvent.value = '{id:'+removeWhiteSpace($('#hoverEventEntityID').val())+',name:'+removeWhiteSpace($('#hoverEventEntityName').val())+',type:'+removeWhiteSpace($('#hoverEventEntityType').val())+'}'; } if ($('#insertion_text').val() != '') jobject[extraIndex].insertion = $('#insertion_text').val(); } clearExtra(); refreshOutput(); } function refreshSavesList() { $('.savesContainer').html(''); for (var i = 0; i < Object.keys(lsm).length; i++) { var key = Object.keys(lsm)[i]; if (key.indexOf('saveSlot_') != -1) { $('.savesContainer').append('<div class="row" saveKey="' + key.substring('9') + '"><div class="col-xs-3"><a href="#" onclick="loadJObject(\'' + key.substring('9') + '\')">Load ' + key.substring('9').replace('_', ' ') + '</a></div><div class="col-xs-6">' + lsm.getItem(key).substring(0,90) + ' ...</div><div class="div class="col-xs-3"><a href="#" onclick="deleteJObjectSave(\'' + key.substring('9') + '\')">Delete ' + key.substring('9') + '</a></div></div>') } }; if ($('.savesContainer').html() == '') { $('.savesContainer').html('<div class="row"><div class="col-xs-12"><h4 lang="saves.nosaves"></h4></div></div>'); } refreshLanguage(); } function deleteJObjectSave(saveName) { var saveSlot = 'saveSlot_' + saveName; swal({ title: "Are you sure?", text: "Are you sure you want to delete " + saveName + "?", type: "warning", showCancelButton: true, confirmButtonText: "Yes, delete it!", closeOnConfirm: false }, function(){ lsm.removeItem(saveSlot); refreshSavesList(); swal("Deleted!", saveName + ' was deleted.', "success"); }); refreshSavesList(); } function showFixerView() { showView('escaping-issue',true,false,true); } function refreshOutput(input) { /*VERIFY CONTENTS*/ jobject = verify_jobject_format(jobject); if ($('#command').val().indexOf('%s') == -1) { $('#command').val('/tellraw @p %s'); lsm.setItem('jtemplate','tellraw'); } if ($('#command').val().indexOf('/tellraw') != -1 && templates[lsm.getItem('jtemplate')].formatType != 'standardjson' && lsm.getItem('dontShowQuoteFixer') != "true" && jobject.length > 0) { setTimeout(showFixerView,4000); } refreshSavesList(); /*LANGUAGE SELECTIONS*/ $('.langSelect').removeClass('label label-success'); $('.' + lsm.getItem('langCode')).addClass('label label-success'); /*EXTRA MODAL COLOR PREVIEW MANAGER*/ $('#colorPreviewColor').css({ 'background-color': getCSSHEXFromWord(getSelected('color_extra')) }); /*EXTRA VIEWER MANAGER*/ $('#textsnippets_header').html(getLanguageString('textsnippets.header',lsm.getItem('langCode'))); if (input != 'previewLineChange') { if (get_type(jobject) == "[object Array]") { var extraOutputPreview = ""; $('.extraContainer div.extraRow').remove(); $('.extraContainer').html(''); for (var i = 0; i <= jobject.length - 1; i++) { if (jobject.length-1 > i) { downButton = '<i onclick="moveUp(' + i + ')" class="fa fa-arrow-circle-down"></i> '; } else { downButton = ""; } if (i > 0) { upButton = '<i onclick="moveUp(' + (i-1) + ')" class="fa fa-arrow-circle-up"></i> '; } else { upButton = ""; } if (jobject[i].NEW_ITERATE_FLAG) { if (templates[lsm.getItem('jtemplate')].formatType != 'bookarray' && templates[lsm.getItem('jtemplate')].formatType != 'signset') { var tempJSON = '<span style="color:gray;text-decoration:line-through;" lang="textsnippets.NEW_ITERATE_FLAG.buttontext"></span>'; } else { var tempJSON = '<span lang="textsnippets.NEW_ITERATE_FLAG.buttontext"></span>'; } var saveButton = ''; } else { if (get_type(jobject[i].text) != "[object Undefined]") { var tempJSON = '<input id="previewLine'+i+'" onkeyup="jobject['+i+'].text = $(\'#previewLine'+i+'\').val(); refreshOutput(\'previewLineChange\')" type="text" class="form-control previewLine" value="'+jobject[i].text+'">'; var saveButton = ''; } else if (get_type(jobject[i].translate) != "[object Undefined]") { var tempJSON = '<input type="text" class="form-control previewLine" disabled value="'+jobject[i].translate+'">'; var saveButton = ''; } else if (get_type(jobject[i].score) != "[object Undefined]") { var tempJSON = '<input type="text" class="form-control previewLine" disabled value="'+jobject[i].score.name+'\'s '+jobject[i].score.objective+' score">'; var saveButton = ''; } else if (get_type(jobject[i].selector) != "[object Undefined]") { var tempJSON = '<input type="text" class="form-control previewLine" disabled value="Selector: '+jobject[i].selector+'">'; var saveButton = ''; } if (input == 'noEditIfMatches' && jobject[i].text != $('#previewLine'+matchTo).val()) { var blah = 'blah'; /* wtf */ } else { tempJSON = '<div class="row"><div class="col-xs-10 col-md-11">'+tempJSON+'</div><div class="col-xs-2 col-md-1"><div class="colorPreview"><div class="colorPreviewColor" style="background-color:'+getCSSHEXFromWord(jobject[i].color)+'"></div></div></div></div>'; } } var deleteButton = '<i id="'+i+'RowEditButton" onclick="editExtra('+i+');" class="fa fa-pencil"></i> <i onclick="deleteIndex('+ i +');" class="fa fa-times-circle"></i> '; if (jobject[i].NEW_ITERATE_FLAG) { deleteButton = '<i style="color:gray;" class="fa fa-pencil"></i> <i onclick="deleteIndex('+ i +');" class="fa fa-times-circle"></i> '; } $('.extraContainer').append('<div class="row extraRow row-margin-top row-margin-bottom mover-row RowIndex' + i + '"><div class="col-xs-4 col-sm-2 col-lg-1">'+deleteButton+downButton+upButton+'</div><div class="col-xs-8 col-sm-10 col-lg-11" style="padding:none;">'+tempJSON+'</div></div>'); } if (jobject.length == 0) { delete jobject; $('.extraContainer').html('<br><br>'); refreshLanguage(); } } else { $('.extraContainer div.extraRow').remove(); $('.extraContainer').html('<div class="row"><div class="col-xs-12"><h4>'+getLanguageString('textsnippets.nosnippets',lsm.getItem('langCode'))+'</h4></div></div>'); } refreshLanguage(); } /* SHOW MOUSE ACTION OPTIONS FOR JSON TEMPLATES WITH THAT FLAG */ if (templates[lsm.getItem('jtemplate')].mouseActionOptions) { $('.hoverEventContainer_edit').show(); $('.clickEventContainer_edit').show(); $('.insertionContainer_edit').show(); $('.hoverEventContainer').show(); $('.clickEventContainer').show(); $('.insertionContainer').show(); } else { $('.hoverEventContainer_edit').hide(); $('.clickEventContainer_edit').hide(); $('.insertionContainer_edit').hide(); $('.hoverEventContainer').hide(); $('.clickEventContainer').hide(); $('.insertionContainer').hide(); } if (templates[lsm.getItem('jtemplate')].formatType == 'signset') { $('.clickEventDisabledSigns').show(); $('.hoverEventDisabledSigns').show(); } else { $('.clickEventDisabledSigns').hide(); $('.hoverEventDisabledSigns').hide(); } /*EXTRA TRANSLATE STRING MANAGER*/ if (extraTextFormat == "trn") { $('#obj_extra_container').hide(); $('#text_extra_container').hide(); $('#selector_extra_container').hide(); $('#translate_selector_container').show(); if (!hasAlertedTranslationObjects) { swal('Translation objects are currently broken and may crash your game.','Please test your translation before publishing it.','warning'); hasAlertedTranslationObjects = true; } } else if (extraTextFormat == "obj") { $('#text_extra_container').hide(); $('#translate_selector_container').hide(); $('#selector_extra_container').hide(); $('#obj_extra_container').show(); } else if (extraTextFormat == "sel") { $('#text_extra_container').hide(); $('#translate_selector_container').hide(); $('#selector_extra_container').show(); $('#obj_extra_container').hide(); } else if (extraTextFormat == "raw") { $('#text_extra_container').show(); $('#obj_extra_container').hide(); $('#translate_selector_container').hide(); $('#selector_extra_container').hide(); $('.extraTranslationParameterRow').hide(); } if (extraTextFormat == 'NEW_ITERATE_FLAG') { if (templates[lsm.getItem('jtemplate')].formatType != 'bookarray' && templates[lsm.getItem('jtemplate')].formatType != 'signset') { var swalObject = { title: getLanguageString('textsnippets.NEW_ITERATE_FLAG.incorrect_template.primary.header',lsm.getItem('langCode')), text: getLanguageString('textsnippets.NEW_ITERATE_FLAG.incorrect_template.primary.description',lsm.getItem('langCode')), showCancelButton: true, confirmButtonText: getLanguageString('textsnippets.NEW_ITERATE_FLAG.incorrect_template.primary.yes',lsm.getItem('langCode')), cancelButtonText: getLanguageString('textsnippets.NEW_ITERATE_FLAG.incorrect_template.primary.no',lsm.getItem('langCode')), closeOnConfirm: false, closeOnCancel: true }; var swalCallback = function(isConfirm) { var template = undefined; if (isConfirm) { template = "book"; } else { template = "sign_item"; } $('.templateButton').removeClass('btn-success').removeClass('btn-default').addClass('btn-default'); $('.templateButton[template=' + template + ']').addClass('btn-success').removeClass('btn-default'); lsm.setItem('jtemplate',template); $('#command').val(templates[lsm.getItem('jtemplate')]['command']); refreshOutput(); swal(getLanguageString('textsnippets.NEW_ITERATE_FLAG.incorrect_template.tertiary.header',lsm.getItem('langCode')), getLanguageString('textsnippets.NEW_ITERATE_FLAG.incorrect_template.tertiary.description',lsm.getItem('langCode')).replace('%c', getLanguageString('template.' + template,lsm.getItem('langCode'))), "success"); } swal(swalObject, function(isConfirm){ if (isConfirm) { swal({ title: getLanguageString('textsnippets.NEW_ITERATE_FLAG.incorrect_template.secondary.header',lsm.getItem('langCode')), text: getLanguageString('textsnippets.NEW_ITERATE_FLAG.incorrect_template.secondary.description',lsm.getItem('langCode')), type: "info", showCancelButton: true, confirmButtonText: getLanguageString('textsnippets.NEW_ITERATE_FLAG.incorrect_template.secondary.book',lsm.getItem('langCode')), cancelButtonText: getLanguageString('textsnippets.NEW_ITERATE_FLAG.incorrect_template.secondary.sign',lsm.getItem('langCode')), closeOnConfirm: false, closeOnCancel: false }, swalCallback); } }); $('#fmtExtraRaw').click(); } $('.NEW_ITERATE_FLAG_not_container').hide(); } else { $('.NEW_ITERATE_FLAG_not_container').show(); } /*COMMAND MANAGER*/ if ($("#command").val() == "") $("#command").val(templates[lsm.getItem('jtemplate')]['command']); /*HOVEREVENT SUGGESTION MANAGER*/ $('#hoverEventValue').removeAttr('disabled'); selectedHover = getSelected("hoverEvent"); if (selectedHover == "show_achievement") { $('#hoverEventValue').autocomplete({ source: achievements }); } else if (selectedHover == "show_item") { $('#hoverEventValue').autocomplete({ source: [] }); } else if (selectedHover == "show_entity") { $('.hovertext_default').hide(); $('.hovertext_entity').show(); } else if (selectedHover == "none") { $('#hoverEventValue').attr('disabled','true'); $('#hoverEventValue').autocomplete({ source: [] }); } if (selectedHover != "show_entity") { $('.hovertext_default').show(); $('.hovertext_entity').hide(); } if (selectedHover == "show_text") { $('.hovertext_default').hide(); $('.hovertext_text').show(); $('#hoverEventText').val(JSON.stringify({"text":"","extra":[]})); } else { $('.hovertext_text').hide(); } /*HOVEREVENT EDIT SUGGESTION MANAGER*/ $('#hoverEventText_edit').removeAttr('disabled'); selectedHover_edit = getSelected('hoverEvent_edit'); if (selectedHover_edit == "show_achievement") { $('#hoverEventText_edit').autocomplete({ source: achievements }); } else if (selectedHover_edit == "show_item") { $('#hoverEventText_edit').autocomplete({ source: [] }); } else if (selectedHover_edit == "show_entity") { $('.hovertext_default_edit').hide(); $('.hovertext_entity_edit').show(); } else if (selectedHover_edit == "none") { $('#hoverEventText_edit').attr('disabled','true'); $('#hoverEventText_edit').autocomplete({ source: [] }); } if (selectedHover_edit != "show_entity") { $('.hovertext_default_edit').show(); $('.hovertext_entity_edit').hide(); } if (selectedHover_edit != "show_text") { $('.hovertext_text_edit').hide(); } else { $('.hovertext_text_edit').show(); } /*CLICKEVENT SUGGESTION MANAGER*/ $('#clickEventText').removeAttr('disabled'); selectedClick = getSelected("clickEvent"); if (selectedClick == "run_command" || selectedClick == "suggest_command") { $('#clickEventText').autocomplete({ source: commands }); } else if (selectedClick == "open_url") { $('#clickEventText').autocomplete({ source: ["https://", "http://", "http://apple.com", "https://minecraft.net", "https://mojang.com", "http://ezekielelin.com", "https://reddit.com"] }); } else if (selectedClick == "none") { $('#clickEventText').attr('disabled','true'); $('#clickEventText').autocomplete({ source: [] }); } /*CLICKEVENT EDIT SUGGESTION MANAGER*/ $('#clickEventText_edit').removeAttr('disabled'); selectedClick_edit = getSelected('clickEvent_edit'); if (selectedClick_edit == "run_command" || selectedClick_edit == "suggest_command") { $('#clickEventText_edit').autocomplete({ source: commands }); } else if (selectedClick_edit == "open_url") { $('#clickEventText_edit').autocomplete({ source: ["http://apple.com", "https://minecraft.net", "https://mojang.com", "http://ezekielelin.com", "https://", "https://reddit.com", "http://"] }); } else if (selectedClick_edit == "none") { $('#clickEventText_edit').attr('disabled','true'); $('#clickEventText_edit').autocomplete({ source: [] }); } /*PREPARING OUTPUT*/ var commandString = $('#command').val(); var JSONOutputString = ''; var EscapedJSONOutputString = ''; var formattedJObject = formatJObjectList(jobject); var newLineExpressions = { "bookarray": /\\\\\\\\n/g, "standardjson": /\\\\n/g, "signset": /\\\\\\\\n/g } if (!formattedJObject.length > 0) { JSONOutputString = '[]'; } else { if (templates[lsm.getItem('jtemplate')].formatType == 'bookarray') { JSONOutputString = JSON.stringify(formattedJObject); JSONOutputString = JSONOutputString.replace(newLineExpressions.bookarray,'\\n'); } else if (templates[lsm.getItem('jtemplate')].formatType == 'standardjson') { JSONOutputString = formattedJObject[0]; JSONOutputString = JSONOutputString.replace(newLineExpressions.standardjson,'\\n'); } else if (templates[lsm.getItem('jtemplate')].formatType == 'signset') { JSONOutputString = 'Text1:' + JSON.stringify(formattedJObject[0]); if (formattedJObject.length > 1) { JSONOutputString += ',Text2:' + JSON.stringify(formattedJObject[1]) } if (formattedJObject.length > 2) { JSONOutputString += ',Text3:' + JSON.stringify(formattedJObject[2]) } if (formattedJObject.length > 3) { JSONOutputString += ',Text4:' + JSON.stringify(formattedJObject[3]) } JSONOutputString = JSONOutputString.replace(newLineExpressions.signset,'\\n'); } } commandString = commandString.replace('%s',JSONOutputString); outputString = commandString; $('#outputtextfield').val(outputString); if ($('#showNiceLookingOutput').is(':checked')) { lsm.setItem('nlOutput','yes'); $('#nicelookingoutput').show().html(JSON.stringify(jobject, null, 4).replace(newLineExpressions.standardjson,'\\n')); } else { lsm.setItem('nlOutput','no'); $('#nicelookingoutput').hide(); } jsonParse(); /*COMMAND BLOCK WARNING*/ if ($('#outputtextfield').val().length > 90) { $('#commandblock').show(); } else { $('#commandblock').hide(); } /*SAVE VARIABLES*/ lsm.setItem('jobject',JSON.stringify(jobject)); lsm.setItem('jcommand', $('#command').val()); /*RERUN*/ if (input != 'noLoop' && input != 'previewLineChange') { refreshOutput('noLoop'); } } function jsonParse() { $('#jsonPreview').css('background-color','#'+$('#previewcolor').val()); $('#jsonPreview').css('font-size',$('#previewFontSize').val() + 'px'); lsm.setItem("color",$('#previewcolor').val()); $('#jsonPreview').html(''); if (templates[lsm.getItem('jtemplate')].formatType == 'bookarray') { $('#jsonPreview').addClass('bookPreview'); $('#previewBack').show(); $('#previewForwards').show(); $('#previewPage').show(); } else { $('#jsonPreview').removeClass('bookPreview'); $('#previewBack').hide(); $('#previewForwards').hide(); $('#previewPage').hide(); } if (get_type(jobject) == "[object Array]") { var pageHash = {}; var counter = 1; for (var i = 0; i < jobject.length; i++) { if (jobject[i].NEW_ITERATE_FLAG) { counter++; } else { pageHash['index.' + i] = counter; topPage = counter; } } if (jobject.length == 0) { topPage = 1; } if (bookPage > topPage) { bookPage = topPage; } //console.log(pageHash); $('#previewPage').html('Page ' + bookPage + ' of ' + topPage); for (var i = 0; i < jobject.length; i++) { if (jobject[i].NEW_ITERATE_FLAG) { if (/*templates[lsm.getItem('jtemplate')].formatType == 'bookarray' || */templates[lsm.getItem('jtemplate')].formatType == 'signset') { $('#jsonPreview').append('<span id="jsonPreviewSpanElement'+ i +'"><hr></span>'); } } else if (pageHash['index.' + i] == bookPage || templates[lsm.getItem('jtemplate')].formatType != 'bookarray') { var doClickEvent = false; var doHoverEvent = false; var popoverTitle = ""; var popoverContentClick = ""; var popoverContentHover = ""; var hoverEventType = ""; var hoverEventValue = ""; var clickEventType = ""; var clickEventValue = ""; $('#jsonPreview').append('<span id="jsonPreviewSpanElement'+ i +'"></span>'); if (jobject[i].text) { $('#jsonPreviewSpanElement'+i).html(jobject[i].text.replace(/\\\\n/g,'<br>').replace(/\\n/g,'<br>')); } else if (jobject[i].score) { $('#jsonPreviewSpanElement'+i).html('<span class="label label-info">' + jobject[i].score.name + ':' + jobject[i].score.objective + '</span>'); } else if (jobject[i].translate) { $('#jsonPreviewSpanElement'+i).html('<span class="label label-warning">Translation</span>'); } else if (jobject[i].selector) { $('#jsonPreviewSpanElement'+i).html('<span class="label label-primary">' + jobject[i].selector + '</span>'); } else { $('#jsonPreviewSpanElement'+i).html('<span class="label label-danger">Unknown Element</span>'); } if (jobject[i].bold == true) { $('#jsonPreviewSpanElement'+i).addClass('bold'); } if (jobject[i].italic == true) { $('#jsonPreviewSpanElement'+i).addClass('italic'); } if (jobject[i].underlined == true) { $('#jsonPreviewSpanElement'+i).addClass('underlined'); } if (jobject[i].strikethrough == true) { if ($('#jsonPreviewSpanElement'+i).hasClass('underlined')) { $('#jsonPreviewSpanElement'+i).removeClass('underlined'); $('#jsonPreviewSpanElement'+i).addClass('strikethroughunderlined'); } else { $('#jsonPreviewSpanElement'+i).addClass('strikethrough'); } } if (jobject[i].obfuscated == true) { $('#jsonPreviewSpanElement'+i).addClass('jsonPreviewObfuscated'); } /*COLORS*/ $('#jsonPreviewSpanElement'+i).css('color',getCSSHEXFromWord(jobject[i].color)); /*CLICK & HOVER EVENTS*/ if (get_type(jobject[i].clickEvent) != "[object Undefined]" || get_type(jobject[i].hoverEvent) != "[object Undefined]") { if (get_type(jobject[i].clickEvent) != "[object Undefined]") doClickEvent = true; if (get_type(jobject[i].hoverEvent) != "[object Undefined]") doHoverEvent = true; if (doHoverEvent && doClickEvent) { popoverTitle = getLanguageString('textsnippets.hoverevent.header',lsm.getItem('langCode')) + ' and ' + getLanguageString('textsnippets.clickevent.header',lsm.getItem('langCode')); hoverEventType = jobject[i].hoverEvent.action; hoverEventValue = jobject[i].hoverEvent.value; clickEventType = jobject[i].clickEvent.action; clickEventValue = jobject[i].clickEvent.value; } if (doHoverEvent && !doClickEvent) { popoverTitle = getLanguageString('textsnippets.hoverevent.header',lsm.getItem('langCode')); hoverEventType = jobject[i].hoverEvent.action; hoverEventValue = jobject[i].hoverEvent.value; } if (!doHoverEvent && doClickEvent) { popoverTitle = getLanguageString('textsnippets.clickevent.header',lsm.getItem('langCode')); clickEventType = jobject[i].clickEvent.action; clickEventValue = jobject[i].clickEvent.value; } if (doClickEvent) { if (clickEventType == "open_url") { popoverContentClick = clickEventType+':<a href="'+clickEventValue+'">'+clickEventValue+'</a>'; } else { popoverContentClick = clickEventType+':'+clickEventValue; } } if (doHoverEvent) { if (hoverEventType == 'show_text') { hoverEventValue = JSON.stringify(hoverEventValue); } popoverContentHover = hoverEventType+':'+hoverEventValue; } if (doHoverEvent && doClickEvent) { popoverContentClick = popoverContentClick + '<br>'; } $('#jsonPreviewSpanElement'+i).attr('rel','popover'); } $('#jsonPreviewSpanElement'+ i).popover({ title: popoverTitle, content: popoverContentClick+popoverContentHover, html:true}); } } } else { $('#jsonPreview').html(getLanguageString('output.nothing',lsm.getItem('langCode'))); $('#jsonPreview').css('color','white'); } if ($('.jsonPreviewObfuscated').length > 0) { setTimeout(obfuscationPreviewHandler, 20); } } function refreshLanguage(dropdownSelection) { if (lang[lsm.getItem('langCode')]) { $('*').refreshLanguage(lsm.getItem('langCode')); } else { lsm.setItem('langCode','en-US') } $('*').each(function(){ //if ($(this).attr('version') != undefined && (lsm.getItem('versionIndicators') == "true" || lsm.getItem('versionIndicators') == undefined)) { if (false) { var labelLevel = 'success'; if ($(this).attr('version') == '1.9') { labelLevel = 'danger'; } if ($(this).prop('tagName') == 'OPTION') { $(this).prepend('('+$(this).attr('version')+') '); } else { $(this).append(' <span class="label label-'+labelLevel+'">'+$(this).attr('version')+'</span>'); } } }); } function initialize() { if (lsm.getItem('initialTimestamp') == undefined) { lsm.setItem('initialTimestamp',new Date().getTime()) } if (lsm.getItem('langCode') == undefined) { if (lang[navigator.language.toLowerCase()] != undefined) { lsm.setItem('langCode',navigator.language.toLowerCase()); } else { if (webLangRelations[navigator.language.toLowerCase()] != undefined) { lsm.setItem('langCode',webLangRelations[navigator.language.toLowerCase()]); } } } if (lsm.getItem('langCode') == undefined) { lsm.setItem('langCode','en_US'); } if (lsm.getItem('jformat') != version && lsm.getItem('jformat') != undefined) { swal({ title: "Your cookie format is old!", text: "This may cause issues. Would you like to reset them? You won't be asked again until the next time the format changes.", showCancelButton: true, confirmButtonText: "Reset Cookies", cancelButtonText: "Don't Reset", closeOnCancel: false },function(isConfirm){ if (isConfirm) { sessionStorage.setItem('nextTimeAlert',JSON.stringify({'title': 'All Done', 'text': 'Your cookies have successfully been reset.\n\nCookies are reset when the format changes drastically, or when a mistake causes the cookies to break the website.', 'type': 'success'})); lsm.clear(); location.reload(); } else { swal('Nothing was reset','You won\'t be asked again until the cookie format changes. If you experience an issue, please clear your coookies for this website', 'info'); } }); } else { /*check if alert isn't correctly set. Do not show the alert is jformat isn't set – that means the user hasn't been here before*/ if (lsm.getItem('jalert') != notice.id && lsm.getItem('jformat') != undefined && notice.show) { swal(notice.message); } lsm.setItem('jalert',notice.id); } lsm.setItem('jformat',version); if (sessionStorage.getItem('nextTimeAlert')) { swal(JSON.parse(sessionStorage.getItem('nextTimeAlert'))); sessionStorage.removeItem('nextTimeAlert'); } if (lsm.getItem('nextTimeAlert')) { swal(JSON.parse(lsm.getItem('nextTimeAlert'))); lsm.removeItem('nextTimeAlert'); } if (lsm.getItem('donateAlert') != "shown" && lsm.getItem('donateAlert') != "not-shown") { lsm.setItem('donateAlert','not-shown') } else { if (lsm.getItem('donateAlert') == 'not-shown' && false) { swal({ "title": "Please Consider Donating", "text": "Donations help support my developement of these programs!\n\nDonations can be done through a variety of services, it's up to you.", "confirmButtonText": "I want to donate", "cancelButtonText": "I have already or don't want to donate", "showCancelButton": true, "closeOnConfirm": false, "closeOnCancel": false }, function(want){ if (want) { var swalCallback = function(amount){ if (amount > 25 && amount < 40) { var swalMessage = { "title": "Overcast Network", "text": "That amount fits nicely with an upgrade to my <a href=\"http://oc.tc/ezfe\">Overcast Network</a> account", "html": true, "confirmButtonText": "Ok, show me the page", "cancelButtonText": "I'd rather just send the money", "showCancelButton": true, "closeOnConfirm": false, "closeOnCancel": false }; var swalCallback = function(shouldGoToOvercast){ if (shouldGoToOvercast) { swal({ "title": "Almost done...", "text": "When you arrive, enter the username <i>ezfe</i>", "html": true, },function(){ lsm.setItem('nextTimeAlert',JSON.stringify({"title": "Thanks!", "text": "I'm assuming you donated, in which case thanks! Otherwise, perhaps later?", "type": "success"})); location.href = "https://oc.tc/shop"; }); } else { var swalMessage = { "title": "Ok, that's fine", "text": "Right now, I only offer PayPal, because my web payment system is broken.\n\nYou can find my email address at the bottom of the page!", "status": "success" }; swal(swalMessage); } } swal(swalMessage,swalCallback); } else { var swalMessage = { "title": "Great!", "text": "Right now, I only offer PayPal, because my web payment system is broken.\n\nYou can find my email address at the bottom of the page!", "status": "success" }; swal(swalMessage); } } swal({ "title": "Awesome", "text": "How much do you want to donate?\n(Please enter a number, like 3 or 11. Don't enter the $ symbol)", "type": "input", "closeOnConfirm": false },swalCallback); } else { swal('Awe...','I won\'t bother you again, so long as you don\'t reset your cookies.\n\nI can\'t remember things if you do that.'); } }); lsm.setItem('donateAlert','shown'); } } for (var i = 0; i < Object.keys(templates).length; i++) { var key = Object.keys(templates)[i] if (key == lsm.getItem('jtemplate')) { var classString = 'btn-success'; } else { var classString = 'btn-default'; } $('#templateButtons').append('<button class="btn btn-xs ' + classString + ' templateButton" lang="template.' + key + '" version="' + templates[key]['version'] + '" template="'+ key +'"></button> '); } if (lsm.getItem('jtemplate') == undefined) { lsm.setItem('jtemplate', 'tellraw'); } if (lang[lsm.getItem('langCode')]) { errorString = getLanguageName(lsm.getItem('langCode')) + '<br><br>'; } else { errorString = '&lt;language unknown&gt;<br><br>'; } /*var enCount = JSON.stringify(lang['en_US']).length;*/ for (var i = 0; i < Object.keys(lang).length; i++) { /*var langKey = Object.keys(lang)[i]; var currentCount = JSON.stringify(lang[langKey]).length; var currentPercentage = Math.round(currentCount/enCount*100); console.log(currentPercentage);*/ $('#language_keys').append('<li><a onclick="errorString = \''+ getLanguageName(Object.keys(lang)[i]) +'<br><br>\'; lsm.setItem(\'langCode\',\''+Object.keys(lang)[i]+'\'); refreshLanguage(true); refreshOutput();"><span class="' + Object.keys(lang)[i] + ' langSelect" id="language_select_'+Object.keys(lang)[i]+'">'+ getLanguageName(Object.keys(lang)[i]) +'</span></a></li>'); }; $('#language_keys').append('<li class="divider"></li>'); $('#language_keys').append('<li><a href="http://translate.minecraftjson.com"><span class="language_area" lang="language.translate"></span></a></li>'); $('.extraTranslationParameterRow').hide(); if (lsm.getItem('color') != undefined) { $('#previewcolor').val(lsm.getItem("color")); } else { $('#previewcolor').val('617A80'); } $('#previewcolor').css('background-color','#'+$('#previewcolor').val()); jsonParse(); if (lsm.getItem('jobject') != undefined) { jobject = verify_jobject_format(JSON.parse(lsm.getItem("jobject"))); } if (lsm.getItem('nlOutput') == undefined) { lsm.setItem('nlOutput','no'); } if (lsm.getItem('nlOutput') == 'no') { $('#showNiceLookingOutput').prop('checked', false); } else { $('#showNiceLookingOutput').prop('checked', true); } showView('pageheader',true,false); //JSON.stringify({"viewname":viewname,"suppressAnimation":suppressAnimation,"hideOthers":hideOthers,"hideMenubar":hideMenubar}) if (lsm.getItem('jview') != undefined/* && typeof JSON.stringify(lsm.getItem('jview')) != "string"*/) { var viewObject = JSON.parse(lsm.getItem('jview')); showView(viewObject.viewname,viewObject.suppressAnimation,viewObject.hideOthers,viewObject.hideMenubar); } else { showView('tellraw') } if (lsm.getItem('jtosaccept') == undefined || lsm.getItem('jtosaccept') != tos_version) { //showView('tos-header',true,false,true); } $('.templateButton').click(function(){ $('.templateButton').removeClass('btn-success').removeClass('btn-default').addClass('btn-default'); $(this).addClass('btn-success').removeClass('btn-default'); var template = $(this).attr('template'); lsm.setItem('jtemplate',template); $('#command').val(templates[lsm.getItem('jtemplate')]['command']); refreshOutput(); }); $('#command').val(lsm.getItem('jcommand')); $('#command').change(function(){refreshOutput()}); $('#import').click(function() { swal({ "title": "Import", "text": getLanguageString('settings.importtext.exported.description',lsm.getItem('langCode')), "type": "input", "closeOnConfirm": false },function(oinpt){ var inpt = undefined try { inpt = JSON.parse(oinpt); } catch(err) { logIssue(getLanguageString('settings.importtext.exported.failed.header',lsm.getItem('langCode')),getLanguageString('settings.importtext.exported.failed.description',lsm.getItem('langCode')) + ': ' + oinpt,true) } jobject = inpt['jobject']; if (inpt['jtemplate']) { lsm.setItem('jtemplate',inpt['jtemplate']) } $('#command').val(inpt['command']); swal("Imported", "Your command has been imported", "success"); refreshOutput(); }) }); $('#export').click(function(){ $('#exporter').remove(); $('.alerts').append('<div id="exporter" class="alert alert-info"><h4 lang="export.heading"></h4><p><textarea readonly id="exportText">' + JSON.stringify({"command":$('#command').val(),"jobject":jobject,"jtemplate":lsm.getItem('jtemplate')}) + '</textarea></p><p><button type="button" onclick="closeExport()" class="btn btn-default" lang="export.close"></button></p></div>'); $exportText = $('#exportText'); $exportText.select(); $exportText.height('1px'); $exportText.height(exportText.scrollHeight + "px"); $exportText.click(function(){ this.select(); }); goToByScroll('exporter'); refreshLanguage(); }); refreshLanguage(); refreshOutput(); $('.fmtExtra').on('click', function(){ extraTextFormat = $(this).attr('tellrawType'); $('.fmtExtra').removeClass('active'); $(this).addClass('active'); refreshOutput(); }); $('#addHoverTextText').on('click',function(){ textobj = JSON.parse($('#hoverEventText').val()); snipobj = {"text":$('#hoverEventTextSnippet').val()}; if ($('#snippetcolor').val() != 'none') { snipobj.color = $('#snippetcolor').val(); } $('#hoverEventTextSnippet').val(''); textobj.extra.push(snipobj) $('#hoverEventText').val(JSON.stringify(textobj)); }); $('#removeHoverTextText').on('click',function(){ textobj = JSON.parse($('#hoverEventText').val()); textobj.extra.splice(-1,1) $('#hoverEventText').val(JSON.stringify(textobj)); }); $('#addExtraButton').on('click',function(){ showView('add-extra') editing = true; }); $('#show-saves').on('click',function(){ showView('saves'); }); $('#hide-saves').on('click',function(){ showView('tellraw'); }); $('#lang_request').on('click',function(){ showView('lang-request'); $('#lang-request-errorstring').html(errorString); }); $('#helptoggle').click(function(){ $('.help-box').toggle(); }); $('#enable_dark_mode').on('click',function(){ lsm.setItem('darkMode','true'); $('body').addClass('black-theme'); $(this).hide(); $('#disable_dark_mode').show(); }); $('#disable_dark_mode').on('click',function(){ lsm.setItem('darkMode','false'); $('body').removeClass('black-theme'); $(this).hide(); $('#enable_dark_mode').show(); }); $('.report-issue').on('click',function(){ $('.view-container[view="report-issue"]').children().not('.cancel-issue-row').hide(); $('#issue-workflow-r1').show(); showView('report-issue'); }); $('#previewBack').click(function(){ if (bookPage != 1) bookPage--; refreshOutput(); }); $('#previewForwards').click(function(){ if (bookPage < topPage) bookPage++; refreshOutput(); }); $('.issue-button').click(function(){ var parentRow = $(this).parent().parent(); parentRow.hide(); var id = $(this).attr('id'); if (id == "translation-issue-button") { $('#issue-workflow-r2-translation').fadeIn(); } else if (id == "output-issue-button") { $('#issue-workflow-r2-output').fadeIn(); } else if (id == "translation-current-issue-button") { reportAnIssue('Translation Issue (' + lsm.getItem('langCode') + ')'); showView('tellraw'); } else if (id == "translation-other-issue-button") { reportAnIssue('Translation Issue (Other)'); showView('tellraw'); } else if (id == "output-quotes-issue-button") { $('.templateButton[template=tellraw]').click(); swal('The issue should be fixed.','If it is not, please report as Output > Other, and note this event in your report..','info'); showView('tellraw'); } else if (id == "output-other-issue-button") { reportAnIssue('Output Issue (Other)'); showView('tellraw'); } else if (id == "cancel-issue-button") { showView('tellraw'); parentRow.show(); } else { showView('tellraw'); reportAnIssue(); } }); // Beta tooltip $('#dropdown-list-a').tooltip({"title":"<i style=\"color: #F8814C;\" class=\"fa fa-exclamation-circle\"></i> " + getLanguageString('headerbar.dropdown.hover',lsm.getItem('langCode')),"html":true,"placement":"bottom"}); if (lsm.getItem('beta-tooltip-a-shown') != "yes") { $('#dropdown-list-a').tooltip('show'); } lsm.setItem('beta-tooltip-a-shown',"yes"); //Dark Mode if (lsm.getItem('darkMode') && lsm.getItem('darkMode') == 'true') { $('#enable_dark_mode').click(); //Finish setting up dark mode after handlers exist } } $(document).ready(function(){ if (lsm.getItem('darkMode') && lsm.getItem('darkMode') == 'true') { $('body').addClass('black-theme'); //Rest of "dark mode" is handled later, color scheme handled early for appearance } else if (lsm.getItem('darkMode') == undefined) { $('body').addClass('black-theme'); lsm.setItem('darkMode','true'); } $('.view-container').hide(); showView('loading',true,true,true); $('#loadingtxt').html('Loading Assets'); try { data = getURL('resources.json'); } catch(err) { swal({ "title": "Error!", "text": "An error occured loading page assets. Please try again later.", "type": "error" },function(){ $('html').html('Please try again later'); }); } if (typeof data == 'string') { try { data = JSON.parse(data); } catch(err) { swal({ "title": "Error!", "text": "An error occured loading page assets. Please try again later.", "type": "error" },function(){ $('html').html('Please try again later'); }); } } if (location.hash == "#embed") { $('.view-container[view="tellraw"]').children().filter('br').remove(); embed = true; } else { embed = false; } webLangRelations = data['web_language_relations']; achievements = data['achievements']; commands = data['commands']; for (var i = 0; i < data['web_language_urls'].length; i++) { try { var urlFetch = getURL('lang/' + data['web_language_urls'][i] + '.json'); } catch(err) { if (data['web_language_urls'][i] == 'en_US') { var urlFetch = {"language":{"name":"English"}}; } else { continue; } } if (typeof urlFetch == 'string') { try { urlFetch = JSON.parse(urlFetch); } catch(err) { if (data['web_language_urls'][i] == 'en_US') { var urlFetch = {"language":{"name":"English"}}; } else { continue; } } } lang[data['web_language_urls'][i]] = urlFetch; } delete lang.status; setTimeout(initialize,500); });
js/tellraw.js
var chars = [1,2,3,4,5,6,7,8,9,0,'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']; var matchLength = 0; var version = 3; var tos_version = 1; var notice = { "show": false, "id": 8, "message": { "title": "Updated...", "text": "Hi", "type": "info" } }; var jobject = []; var selectedHover; var selectedClick; var selectedHover_edit; var selectedClick_edit; var downButton; var upButton; var extraTextFormat = 'raw'; var lang = {"status":"init"}; var translationStrings; var currentEdit; var hasAlertedTranslationObjects = false; var webLangRelations; var editing = false; var issueLog = []; var bookPage = 1; var topPage = 1; var embed = false; var lsm = {}; lsm.enabled = false; lsm.storage = {}; lsm.setItem = function(key, value) { try { localStorage.setItem(key, value); } catch(e) { lsm.enabled = true; lsm.storage[key] = value; } } lsm.getItem = function(key) { if (lsm.enabled) { return lsm.storage[key]; } else { return localStorage.getItem(key); } } lsm.clear = function() { if (lsm.enabled) { lsm.storage = {}; } else { localStorage.clear(); } } lsm.removeItem = function(key) { if (lsm.enabled) { delete lsm.storage[key]; } else { localStorage.removeItem(key); } } /* http://stackoverflow.com/a/728694/2059595 */ function clone(obj) { var copy; // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { copy = []; for (var i = 0, len = obj.length; i < len; i++) { copy[i] = clone(obj[i]); } return copy; } // Handle Object if (obj instanceof Object) { copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); } function alert(message) { return swal(message); } function reportAnIssue(ptitle) { var title = ""; var body = ""; if (ptitle != undefined) { title = "Issue Report - " + ptitle; body = 'Please enter steps to reproduce the issue below, as well as any other information you want to include%0A%0A%0A%0A%0A%0A Provided Data - Do not modify below this line%0A%0A```%0A' + JSON.stringify(jobject) + '%0A```'; } var win = window.open('http://github.com/ezfe/tellraw/issues/new?body=' + body + '&title=' + title, '_blank'); win.focus(); } function getLanguageName(langCode) { var name = lang[langCode].language.name; if (name == "English" && langCode != "en-US") { return langCode } else { return name } } function showIssue() { swal(issueLog[issueLog.length - 1].name,issueLog[issueLog.length - 1].data,'error'); } function logIssue(name,data,critical) { issueLog.push({"name":name,"data":data}); if (critical) { swal(name,data,'error'); } } function showView(viewname,suppressAnimation,hideOthers,hideMenubar) { var hideMenubarOriginal = hideMenubar; if (embed) { hideMenubar = true; } var toHide = $('.view-container').not('.view-container[view="' + viewname + '"]'); if (!hideMenubar) { toHide = toHide.not('.view-container[view="pageheader"]'); } var toShow = $('.view-container[view="' + viewname + '"]'); if (!hideMenubar) { $($('.view-container[view="pageheader"]')).show(); } if (hideOthers === false) { toHide = $(''); } if (suppressAnimation) { toHide.hide(); toShow.show(); } else { toHide.slideUp(); toShow.slideDown(); } if (viewname != "loading" && viewname != "pageheader" && viewname != "issue") { lsm.setItem('jview',JSON.stringify({"viewname":viewname,"suppressAnimation":suppressAnimation,"hideOthers":hideOthers,"hideMenubar":hideMenubar})); } if (toShow.length == 0) { logIssue('Missing View',viewname,true); showView('tellraw'); } } function getURL(url){ return $.ajax({ type: "GET", url: url, cache: false, async: false }).responseText; } function verify_jobject_format(jdata) { var resetError = JSON.stringify({"title": "Object Verification Failed", "text": "An error occured and the page has been reset", "type": "error"}); if (get_type(jdata) == "[object Object]") { if (get_type(jdata.extra) == "[object Array]") { jdata = jdata.extra; } else { sessionStorage.setItem('nextTimeAlert',resetError); lsm.clear(); location.reload(); return; } } if (get_type(jdata) != "[object Array]") { sessionStorage.setItem('nextTimeAlert',resetError); lsm.clear(); location.reload(); return; } if (jdata.text != '' && get_type(jdata) != "[object Array]") { jdata.unshift(new Object()); jdata[0].text = jdata.text; jdata[0].color = jdata.color; delete(jdata.color); jdata[0].bold = jdata.bold; delete(jdata.bold); jdata[0].italic = jdata.italic; delete(jdata.italic); jdata[0].underlined = jdata.underlined; delete(jdata.underline); jdata[0].strikethrough = jdata.strikethrough; delete(jdata.strikethrough); jdata[0].obfuscated = jdata.obfuscated; delete(jdata.obfuscated); jdata.text = ''; } //Tracks changes for "true" --> true var booleanUpdateCount = 0; for (var i = 0; i < jdata.length; i++) { //Convert show_text to structured format if (jdata[i].hoverEvent != undefined) { if (jdata[i].hoverEvent.action == "show_text") { if (typeof jdata[i].hoverEvent.value == "object") { if (jdata[i].hoverEvent.value.text != "") { jdata[i].hoverEvent.value = {"text":"", "extra":[jdata[i].hoverEvent.value]}; } } else if (typeof jdata[i].hoverEvent.value == "string") { jdata[i].hoverEvent.value = {"text":"", "extra":[{"text":jdata[i].hoverEvent.value}]}; } } } if (jdata[i].bold == "true") { jdata[i].bold = true; booleanUpdateCount++; } else if (jdata[i].bold !== true) { delete jdata[i].bold; } if (jdata[i].italic == "true") { jdata[i].italic = true; booleanUpdateCount++; } else if (jdata[i].italic !== true) { delete jdata[i].italic; } if (jdata[i].underlined == "true") { jdata[i].underlined = true; booleanUpdateCount++; } else if (jdata[i].underlined !== true) { delete jdata[i].underlined; } if (jdata[i].strikethrough == "true") { jdata[i].strikethrough = true; booleanUpdateCount++; } else if (jdata[i].strikethrough !== true) { delete jdata[i].strikethrough; } if (jdata[i].obfuscated == "true") { jdata[i].obfuscated = true; booleanUpdateCount++; } else if (jdata[i].obfuscated !== true) { delete jdata[i].obfuscated; } } if (booleanUpdateCount > 0) { swal({"title": "Udated!", "text": "All strings representing boolean values have been updated to true/false values (" + booleanUpdateCount + " change" + (booleanUpdateCount == 1 ? "" : "s") + ")", "type": "success"}); } return jdata; } function strictifyItem(job,index) { var joi = job[index]; if (index == 0 || job[index - 1].NEW_ITERATE_FLAG || job[index].NEW_ITERATE_FLAG) { return joi; } var prejoi = job[index - 1]; for (var i = 0; i < Object.keys(prejoi).length; i++) { var key = Object.keys(prejoi)[i]; var doNotCheckKeys = ["text", "score", "selector", "color", "clickEvent", "hoverEvent", "insertion"] if (doNotCheckKeys.indexOf(key) == -1) { if (prejoi[key] === true && joi[key] === undefined) { joi[key] = false; } } else { if (key == "color") { if (joi["color"] === undefined) { joi["color"] = noneName(); } }/* else if (key == "hoverEvent" || key == "clickEvent") { if (joi[key] == undefined) { // DO SOMETHING } }*/ continue; } } return joi; } function strictifyJObject(job) { for (var x = 0; x < job.length; x++) { job[x] = strictifyItem(job,x); } return job; } function formatJObjectList(d) { data = strictifyJObject(clone(d)); if (data.length == 0) { return []; } var ret_val = []; var currentDataToPlug = [""]; for (var i = 0; i < data.length; i++) { if (data[i].NEW_ITERATE_FLAG) { ret_val.push(JSON.stringify(currentDataToPlug)); currentDataToPlug = [""]; } else { currentDataToPlug.push(data[i]); } } if (!data[data.length - 1].NEW_ITERATE_FLAG) { ret_val.push(JSON.stringify(currentDataToPlug)); } return ret_val; } function closeExport() { $('#exporter').remove(); } function isScrolledIntoView(elem) { elem = '#' + elem; var docViewTop = $(window).scrollTop(); var docViewBottom = docViewTop + $(window).height(); var elemTop = $(elem).offset().top; var elemBottom = elemTop + $(elem).height(); return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)); } function goToByScroll(id){ if (!isScrolledIntoView(id)) { $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow'); } } var templates = { "tellraw": { "command": "/tellraw @p %s", "version": "1.7", "formatType": "standardjson", "mouseActionOptions": true }, "execute_tellraw": { "command": "/execute @a ~ ~ ~ tellraw @p %s", "version": "1.8", "formatType": "standardjson", "mouseActionOptions": true }, "title": { "command": "/title @a title %s", "version": "1.8", "formatType": "standardjson", "mouseActionOptions": false }, "subtitle": { "command": "/title @a subtitle %s", "version": "1.8", "formatType": "standardjson", "mouseActionOptions": false }, "sign_item": { "command": "/give @p sign 1 0 {BlockEntityTag:{%s,id:\"Sign\"}}", "version": "1.8", "formatType": "signset", "mouseActionOptions": false }, "sign_block": { "command": "/blockdata [x] [y] [z] {%s}", "version": "1.8", "formatType": "signset", "mouseActionOptions": false }, "book": { "command": "/give @p written_book 1 0 {pages:%s,title:Book,author:TellrawGenerator}", "version": "1.8", "formatType": "bookarray", "mouseActionOptions": true } } /* (c) 2012 Steven Levithan <http://slevithan.com/> MIT license */ if (!String.prototype.codePointAt) { String.prototype.codePointAt = function (pos) { pos = isNaN(pos) ? 0 : pos; var str = String(this), code = str.charCodeAt(pos), next = str.charCodeAt(pos + 1); // If a surrogate pair if (0xD800 <= code && code <= 0xDBFF && 0xDC00 <= next && next <= 0xDFFF) { return ((code - 0xD800) * 0x400) + (next - 0xDC00) + 0x10000; } return code; }; } function setObfuscatedString(string) { var output = ""; for (var i = string.length - 1; i >= 0; i--) { string[i] output = output + chars[Math.floor(Math.random() * chars.length)]; }; return output; } function saveJObject() { swal({ title: "Please enter a save name.", text: "If you enter an existing one, it will overwrite it.", type: "input", showCancelButton: true, closeOnConfirm: false }, function(inputValue) { inputValue = inputValue.replace(' ','_'); if (inputValue == '' || inputValue == undefined || new RegExp('[^a-zA-Z0-9_]').test(inputValue)) { swal('Invalid Save Name!','Please omit special characters','error'); } else { var saveTo = inputValue var saveSlot = 'saveSlot_' + saveTo; var overwrite = false; if (lsm.getItem(saveSlot) != undefined) { overwrite = true; } lsm.setItem('currentSaveSlot',saveTo); lsm.setItem(saveSlot, JSON.stringify({"command": $('#command').val(), "jobject": jobject})); if (overwrite) { swal({ title: 'Saved your current revision to <code>' + saveTo.replace('_', ' ') + '</code>, overwriting your previous save to that slot', html: true }); } else { swal({ title: 'Saved your current revision to <code>' + saveTo.replace('_', ' ') + '</code>, which created a new saveSlot', html: true }); } refreshSavesList(); refreshOutput(); } }); } function loadJObject(saveName) { var saveItem = getJObject(saveName); jobject = saveItem.jobject; $('#command').val(saveItem.command); swal('Loaded save `' + saveName + '`','','success'); refreshSavesList(); refreshOutput(); } function doesJObjectExist(saveName) { var saveSlot = 'saveSlot_' + saveName; return lsm.getItem(saveSlot) != undefined; } function getJObject(saveName) { var saveSlot = 'saveSlot_' + saveName; return JSON.parse(lsm.getItem(saveSlot)); } function deleteAll() { swal({ "title": getLanguageString('settings.deleteall.heading',lsm.getItem('langCode')), "text": getLanguageString('settings.deleteall.body',lsm.getItem('langCode')), "cancelButtonText": getLanguageString('settings.deleteall.no',lsm.getItem('langCode')), "confirmButtonText": getLanguageString('settings.deleteall.yes',lsm.getItem('langCode')), "showCancelButton": true, "closeOnConfirm": false, "type": "warning" },function(isConfirm){ if (isConfirm) { jobject = []; $('.templateButton[template=tellraw]').click(); refreshOutput(); swal('Deleted!','Your current thing was deleted', 'success'); } }); } function clearJObjectSaves() { swal({ "title": getLanguageString('saves.deleteall.heading',lsm.getItem('langCode')), "text": getLanguageString('saves.deleteall.body',lsm.getItem('langCode')), "cancelButtonText": getLanguageString('saves.deleteall.no',lsm.getItem('langCode')), "confirmButtonText": getLanguageString('saves.deleteall.yes',lsm.getItem('langCode')), "showCancelButton": true, "closeOnConfirm": false, "type": "warning" },function(isConfirm){ if (isConfirm) { for (var x = 0; x < Object.keys(lsm).length; x++) { for (var i = 0; i < Object.keys(lsm).length; i++) { var key = Object.keys(lsm)[i]; if (key.indexOf('saveSlot_') != -1) { lsm.removeItem(key); } } } refreshSavesList(); swal('Deleted!','Your saves were deleted', 'success'); } }); } function obfuscationPreviewHandler() { $('.jsonPreviewObfuscated').html(setObfuscatedString($('.jsonPreviewObfuscated').html())); if ($('.jsonPreviewObfuscated').length > 0) { setTimeout(obfuscationPreviewHandler, 20); } } function currentTemplate() { return templates[lsm.getItem('jtemplate')]; } function noneHex() { if (currentTemplate().formatType == 'bookarray' || currentTemplate().formatType == 'signset') { return '#000000'; } else { return '#FFFFFF' } } function noneName() { return 'none'; /* I think none is the proper name */ // if (currentTemplate().formatType == 'bookarray' || currentTemplate().formatType == 'signset') { // return 'black'; // } else { // return 'white' // } } function getCSSHEXFromWord(w) { if (w == "black") return("#000000"); if (w == "dark_blue") return("#0000B2"); if (w == "dark_green") return("#14AB00"); if (w == "dark_aqua") return("#13AAAB"); if (w == "dark_red") return("#A90400"); if (w == "dark_purple") return("#A900B2"); if (w == "gold") return("#FEAC00"); if (w == "gray") return("#AAAAAA"); if (w == "dark_gray") return("#555555"); if (w == "blue") return("#544CFF"); if (w == "green") return("#5CFF00"); if (w == "aqua") return("#5BFFFF"); if (w == "red") return("#FD5650"); if (w == "light_purple") return("#FD4DFF"); if (w == "yellow") return("#FFFF00"); if (w == "white") return("#FFFFFF"); if (w == "none") return(noneHex()); return noneHex(); } function removeWhiteSpace(s) { return s; //BROKEN return s.replace(/ /g, ''); } function deleteIndex(index) { jobject.splice(index, 1); refreshOutput(); } function moveUp(index) { jobject.splice(index+1, 0, jobject.splice(index, 1)[0]); refreshOutput(); } function getSelected(object) { if ($('#'+object).length != 0) { var e = document.getElementById(object); return e.options[e.selectedIndex].value; } else { return false; } } function getSelectedIndex(object) { var e = document.getElementById(object); return e.selectedIndex; } function getChecked(id) { return document.getElementById(id).checked; } function clearExtra() { $('#fmtExtraRaw').click(); $("#clickEventText").val(""); $("#hoverEventText").val(""); $("#hoverEventValue").val(""); $("#hoverEventTextSnippet").val(""); $("#snippetcolor").val("none"); $('#snippetcolor').change(); $("#text_extra").val(""); $("#color_extra").val("none"); $("#clickEvent").val('none'); $("#hoverEvent").val('none'); $("#insertion_text").val(''); $("#bold_text_extra").prop("checked",false); $("#italic_text_extra").prop("checked",false); $("#underlined_text_extra").prop("checked",false); $("#strikethrough_text_extra").prop("checked",false); $("#obfuscated_text_extra").prop("checked",false); $('#hoverEventEntityName').val(''); $('#hoverEventEntityID').val(''); $('#hoverEventEntityType').val(''); $('#textsnippets_add').html(getLanguageString('textsnippets.addsnippet'),lsm.getItem('langCode')); $('#textsnippets-add-button').addClass('btn-default'); $('#textsnippets-add-button').removeClass('btn-danger'); $('#obj_player').val(''); $('#obj_score').val(''); $('#text_extra_container').removeClass('has-error'); refreshOutput(); } function editExtra(index) { editing = true; $('#snippetsWell').hide(); $('#editModalData').show(); currentEdit = index; if (jobject[index].text != undefined) { $('#obj_extra_container_edit').hide(); $('#text_extra_container_edit').show(); $('#translate_selector_container_edit').hide(); $('#selector_extra_container_edit').hide(); $('#text_extra_edit').val(jobject[index].text); } else if (jobject[index].selector != undefined) { $('#obj_extra_container_edit').hide(); $('#selector_extra_container_edit').show(); $('#text_extra_container_edit').hide(); $('#translate_selector_container_edit').hide(); $('#selector_edit').val(jobject[index].selector); } else if (jobject[index].translate != undefined) { $('#obj_extra_container_edit').hide(); $('#text_extra_container_edit').hide(); $('#selector_extra_container_edit').hide(); $('#translate_selector_container_edit').show(); if (!hasAlertedTranslationObjects) { swal('Translation objects are currently broken and may crash your game.','Please test your translation before publishing it.','warning'); hasAlertedTranslationObjects = true; } } else if (jobject[index].score != undefined) { $('#obj_extra_container_edit').show(); $('#text_extra_container_edit').hide(); $('#translate_selector_container_edit').hide(); $('#selector_extra_container_edit').hide(); $('#obj_player_edit').val(jobject[index].score.name); $('#obj_score_edit').val(jobject[index].score.objective); } refreshLanguage(); $('#colorPreviewColor_edit').css('background-color',getCSSHEXFromWord(jobject[index].color)); if (jobject[index].color != undefined) { $("#color_extra_edit").val(jobject[index].color); } else { $("#color_extra_edit").val('none'); } if (jobject[index].bold != undefined) { $('#bold_text_extra_edit').prop('checked',true); } else { $('#bold_text_extra_edit').prop('checked',false); } if (jobject[index].italic != undefined) { $('#italic_text_extra_edit').prop('checked',true); } else { $('#italic_text_extra_edit').prop('checked',false); } if (jobject[index].underlined != undefined) { $('#underlined_text_extra_edit').prop('checked',true); } else { $('#underlined_text_extra_edit').prop('checked',false); } if (jobject[index].strikethrough != undefined) { $('#strikethrough_text_extra_edit').prop('checked',true); } else { $('#strikethrough_text_extra_edit').prop('checked',false); } if (jobject[index].obfuscated != undefined) { $('#obfuscated_text_extra_edit').prop('checked',true); } else { $('#obfuscated_text_extra_edit').prop('checked',false); } if (jobject[index].clickEvent != undefined) { $('#clickEvent_edit').val(jobject[index].clickEvent.action); $('#clickEventText_edit').val(jobject[index].clickEvent.value); } else { $('#clickEvent_edit').val('none'); $('#clickEventText_edit').val(''); } if (jobject[index].hoverEvent != undefined) { $('#hoverEvent_edit').val(jobject[index].hoverEvent.action); if ($('#hoverEvent_edit').val() != 'show_entity') { if (jobject[index].hoverEvent.action == 'show_text') { $('#hoverEventText_edit').val(JSON.stringify(jobject[index].hoverEvent.value)); } else { $('#hoverEventText_edit').val(jobject[index].hoverEvent.value); } } else { $('#hoverEventEntityID_edit').val(jobject[index].hoverEvent.value.match(/id:([a-zA-Z0-9]+)/g )[0].replace('id:','')); $('#hoverEventEntityName_edit').val(jobject[index].hoverEvent.value.match(/name:([a-zA-Z0-9]+)/g )[0].replace('name:','')); $('#hoverEventEntityType_edit').val(jobject[index].hoverEvent.value.match(/type:([a-zA-Z0-9]+)/g )[0].replace('type:','')); } } else { $('#hoverEvent_edit').val('none'); $('#hoverEventText_edit').val(''); } if (jobject[index].insertion != undefined) { $('#insertion_text_edit').val(jobject[index].insertion); } refreshOutput(); } function cancelExtraEdit() { $('#editModalData').hide(); $('#snippetsWell').show(); } function saveExtraEdit() { editing = false; extraIndex = currentEdit; jobject[extraIndex].color = getSelected("color_extra_edit"); if (jobject[extraIndex].color == 'none') { delete jobject[extraIndex].color; } if ($('#obj_extra_container_edit').is(":visible")) { jobject[extraIndex].score = new Object; jobject[extraIndex].score.name = $('#obj_player_edit').val(); jobject[extraIndex].score.objective = $('#obj_score_edit').val(); } else if ($('#text_extra_container_edit').is(":visible")) { jobject[extraIndex].text = $('#text_extra_edit').val(); } else if ($('#selector_extra_container_edit').is(":visible")) { jobject[extraIndex].selector = $('#selector_edit').val(); } else if ($('#translate_selector_container_edit').is(":visible")) { jobject[extraIndex].translate = $('#translate_input_edit').val(); if (matchLength != 0) { if (get_type(jobject.with) != "[object Array]") { jobject[extraIndex].with = new Array(); } for (var i = 0; i < matchLength; i++) { jobject[extraIndex].with[i] = $('#extraTranslationParameter'+i+'_edit').val(); }; } } else { swal('An unexpected error occured.'); } delete jobject[extraIndex].bold; delete jobject[extraIndex].italic; delete jobject[extraIndex].underlined; delete jobject[extraIndex].strikethrough; delete jobject[extraIndex].obfuscated; if (getChecked("bold_text_extra_edit")) { jobject[extraIndex].bold = true; } if (getChecked("italic_text_extra_edit")) { jobject[extraIndex].italic = true; } if (getChecked("underlined_text_extra_edit")) { jobject[extraIndex].underlined = true; } if (getChecked("strikethrough_text_extra_edit")) { jobject[extraIndex].strikethrough = true; } if (getChecked("obfuscated_text_extra_edit")) { jobject[extraIndex].obfuscated = true; } delete jobject[extraIndex].clickEvent; delete jobject[extraIndex].hoverEvent; var clickEventType_edit = $("#clickEvent_edit").val(); var hoverEventType_edit = $("#hoverEvent_edit").val(); if (clickEventType_edit != "none") { jobject[extraIndex].clickEvent = new Object(); jobject[extraIndex].clickEvent.action = clickEventType_edit; jobject[extraIndex].clickEvent.value = $('#clickEventText_edit').val(); if (clickEventType_edit == "run_command" || clickEventType_edit == "suggest_command") { if ($('#clickEventText_edit').val().length > 90) { swal('Commands cannot be longer than 90 characters!','You should edit the length of your command before using this in game.','error'); } } } if (hoverEventType_edit != "none") { jobject[extraIndex].hoverEvent = new Object(); jobject[extraIndex].hoverEvent.action = hoverEventType_edit; if (hoverEventType_edit == 'show_text') { try { jobject[extraIndex].hoverEvent.value = JSON.parse($('#hoverEventText_edit').val()); } catch(err) { jobject[extraIndex].hoverEvent.value = {"text":"","extra":[{"text":$('#hoverEventText_edit').val()}]}; } } else { jobject[extraIndex].hoverEvent.value = $('#hoverEventText_edit').val(); } } if (hoverEventType_edit == "show_entity") { if ($('#hoverEventEntityID_edit').val() == '') { $('#hoverEventEntityID_edit').val('(ID)') } if ($('#hoverEventEntityName_edit').val() == '') { $('#hoverEventEntityName_edit').val('(Name)') } if ($('#hoverEventEntityType_edit').val() == '') { $('#hoverEventEntityType_edit').val('(Type)') } jobject[extraIndex].hoverEvent.value = '{id:'+removeWhiteSpace($('#hoverEventEntityID_edit').val())+',name:'+removeWhiteSpace($('#hoverEventEntityName_edit').val())+',type:'+removeWhiteSpace($('#hoverEventEntityType_edit').val())+'}'; } if ($('#insertion_text_edit').val() != '') { jobject[extraIndex].insertion = $('#insertion_text_edit').val(); } else { delete jobject[extraIndex].insertion; } $('#editModalData').hide(); $('#snippetsWell').show(); refreshOutput(); } function clearExtraText() { delete jobject; refreshOutput(); } function get_type(thing){ if (thing===null) { return "[object Null]"; } return Object.prototype.toString.call(thing); } function modifyExtraText(index,text) { if (text != "" && text != null) { jobject[index].text = text; } refreshOutput(); } function cancelAddExtra() { showView('tellraw'); clearExtra(); } function addExtra() { editing = false; if (extraTextFormat == 'raw' && $('#text_extra').val() == '') { $('#text_extra_container').addClass('has-error'); $('#text_extra').focus(); $('#textsnippets-add-button').removeClass('btn-default'); $('#textsnippets-add-button').addClass('btn-danger'); return false; } else if ($("#hoverEvent").val() == 'show_text' && $('#hoverEventTextSnippet').val() != '') { swal('You entered text, but never added it!'); $('#hoverEventTextSnippet').focus(); $('#textsnippets-add-button').removeClass('btn-default'); $('#textsnippets-add-button').addClass('btn-danger'); return false; } else { showView('tellraw'); } if (get_type(jobject) != "[object Array]") { jobject = []; } if (extraTextFormat == 'NEW_ITERATE_FLAG') { jobject.push({"NEW_ITERATE_FLAG":true}); } else { var clickEventType = $("#clickEvent").val(); var hoverEventType = $("#hoverEvent").val(); jobject.push(new Object()); var extraIndex = jobject.length - 1; if (extraTextFormat == 'trn') { jobject[extraIndex].translate = $('#translate_input').val(); if (matchLength != 0) { if (get_type(jobject.with) != "[object Array]") { jobject[extraIndex].with = new Array(); } for (var i = 0; i < matchLength; i++) { jobject[extraIndex].with[i] = $('#extraTranslationParameter'+i).val(); }; } } else if (extraTextFormat == 'raw') { jobject[extraIndex].text = $('#text_extra').val(); } else if (extraTextFormat == 'obj') { jobject[extraIndex].score = new Object; jobject[extraIndex].score.name = $('#obj_player').val(); jobject[extraIndex].score.objective = $('#obj_score').val(); } else if (extraTextFormat == 'sel') { jobject[extraIndex].selector = $('#selector').val(); } jobject[extraIndex].color = getSelected("color_extra"); if (jobject[extraIndex].color == 'none') { delete jobject[extraIndex].color; } if (getChecked("bold_text_extra")) { jobject[extraIndex].bold = true; } if (getChecked("italic_text_extra")) { jobject[extraIndex].italic = true; } if (getChecked("underlined_text_extra")) { jobject[extraIndex].underlined = true; } if (getChecked("strikethrough_text_extra")) { jobject[extraIndex].strikethrough = true; } if (getChecked("obfuscated_text_extra")) { jobject[extraIndex].obfuscated = true; } if (clickEventType != "none") { jobject[extraIndex].clickEvent = new Object(); jobject[extraIndex].clickEvent.action = clickEventType; jobject[extraIndex].clickEvent.value = $('#clickEventText').val(); if (clickEventType == "run_command" || clickEventType == "suggest_command") { if ($('#clickEventText').val().length > 90) { swal('Commands cannot be longer than 90 characters!','You should edit the length of your command before using this in game.','error'); } } } if (hoverEventType != "none") { jobject[extraIndex].hoverEvent = new Object(); jobject[extraIndex].hoverEvent.action = hoverEventType; if (hoverEventType == 'show_text') { jobject[extraIndex].hoverEvent.value = JSON.parse($('#hoverEventText').val()); if ($('#color_hover').val() != 'none') { jobject[extraIndex].hoverEvent.value.color = $('#color_hover').val(); } } else { jobject[extraIndex].hoverEvent.value = $('#hoverEventValue').val(); } } if (hoverEventType == "show_entity") { if ($('#hoverEventEntityID').val() == '') { $('#hoverEventEntityID').val('(ID)') } if ($('#hoverEventEntityName').val() == '') { $('#hoverEventEntityName').val('(Name)') } if ($('#hoverEventEntityType').val() == '') { $('#hoverEventEntityType').val('(Type)') } jobject[extraIndex].hoverEvent.value = '{id:'+removeWhiteSpace($('#hoverEventEntityID').val())+',name:'+removeWhiteSpace($('#hoverEventEntityName').val())+',type:'+removeWhiteSpace($('#hoverEventEntityType').val())+'}'; } if ($('#insertion_text').val() != '') jobject[extraIndex].insertion = $('#insertion_text').val(); } clearExtra(); refreshOutput(); } function refreshSavesList() { $('.savesContainer').html(''); for (var i = 0; i < Object.keys(lsm).length; i++) { var key = Object.keys(lsm)[i]; if (key.indexOf('saveSlot_') != -1) { $('.savesContainer').append('<div class="row" saveKey="' + key.substring('9') + '"><div class="col-xs-3"><a href="#" onclick="loadJObject(\'' + key.substring('9') + '\')">Load ' + key.substring('9').replace('_', ' ') + '</a></div><div class="col-xs-6">' + lsm.getItem(key).substring(0,90) + ' ...</div><div class="div class="col-xs-3"><a href="#" onclick="deleteJObjectSave(\'' + key.substring('9') + '\')">Delete ' + key.substring('9') + '</a></div></div>') } }; if ($('.savesContainer').html() == '') { $('.savesContainer').html('<div class="row"><div class="col-xs-12"><h4 lang="saves.nosaves"></h4></div></div>'); } refreshLanguage(); } function deleteJObjectSave(saveName) { var saveSlot = 'saveSlot_' + saveName; swal({ title: "Are you sure?", text: "Are you sure you want to delete " + saveName + "?", type: "warning", showCancelButton: true, confirmButtonText: "Yes, delete it!", closeOnConfirm: false }, function(){ lsm.removeItem(saveSlot); refreshSavesList(); swal("Deleted!", saveName + ' was deleted.', "success"); }); refreshSavesList(); } function showFixerView() { showView('escaping-issue',true,false,true); } function refreshOutput(input) { /*VERIFY CONTENTS*/ jobject = verify_jobject_format(jobject); if ($('#command').val().indexOf('%s') == -1) { $('#command').val('/tellraw @p %s'); lsm.setItem('jtemplate','tellraw'); } if ($('#command').val().indexOf('/tellraw') != -1 && templates[lsm.getItem('jtemplate')].formatType != 'standardjson' && lsm.getItem('dontShowQuoteFixer') != "true" && jobject.length > 0) { setTimeout(showFixerView,4000); } refreshSavesList(); /*LANGUAGE SELECTIONS*/ $('.langSelect').removeClass('label label-success'); $('.' + lsm.getItem('langCode')).addClass('label label-success'); /*EXTRA MODAL COLOR PREVIEW MANAGER*/ $('#colorPreviewColor').css({ 'background-color': getCSSHEXFromWord(getSelected('color_extra')) }); /*EXTRA VIEWER MANAGER*/ $('#textsnippets_header').html(getLanguageString('textsnippets.header',lsm.getItem('langCode'))); if (input != 'previewLineChange') { if (get_type(jobject) == "[object Array]") { var extraOutputPreview = ""; $('.extraContainer div.extraRow').remove(); $('.extraContainer').html(''); for (var i = 0; i <= jobject.length - 1; i++) { if (jobject.length-1 > i) { downButton = '<i onclick="moveUp(' + i + ')" class="fa fa-arrow-circle-down"></i> '; } else { downButton = ""; } if (i > 0) { upButton = '<i onclick="moveUp(' + (i-1) + ')" class="fa fa-arrow-circle-up"></i> '; } else { upButton = ""; } if (jobject[i].NEW_ITERATE_FLAG) { if (templates[lsm.getItem('jtemplate')].formatType != 'bookarray' && templates[lsm.getItem('jtemplate')].formatType != 'signset') { var tempJSON = '<span style="color:gray;text-decoration:line-through;" lang="textsnippets.NEW_ITERATE_FLAG.buttontext"></span>'; } else { var tempJSON = '<span lang="textsnippets.NEW_ITERATE_FLAG.buttontext"></span>'; } var saveButton = ''; } else { if (get_type(jobject[i].text) != "[object Undefined]") { var tempJSON = '<input id="previewLine'+i+'" onkeyup="jobject['+i+'].text = $(\'#previewLine'+i+'\').val(); refreshOutput(\'previewLineChange\')" type="text" class="form-control previewLine" value="'+jobject[i].text+'">'; var saveButton = ''; } else if (get_type(jobject[i].translate) != "[object Undefined]") { var tempJSON = '<input type="text" class="form-control previewLine" disabled value="'+jobject[i].translate+'">'; var saveButton = ''; } else if (get_type(jobject[i].score) != "[object Undefined]") { var tempJSON = '<input type="text" class="form-control previewLine" disabled value="'+jobject[i].score.name+'\'s '+jobject[i].score.objective+' score">'; var saveButton = ''; } else if (get_type(jobject[i].selector) != "[object Undefined]") { var tempJSON = '<input type="text" class="form-control previewLine" disabled value="Selector: '+jobject[i].selector+'">'; var saveButton = ''; } if (input == 'noEditIfMatches' && jobject[i].text != $('#previewLine'+matchTo).val()) { var blah = 'blah'; /* wtf */ } else { tempJSON = '<div class="row"><div class="col-xs-10 col-md-11">'+tempJSON+'</div><div class="col-xs-2 col-md-1"><div class="colorPreview"><div class="colorPreviewColor" style="background-color:'+getCSSHEXFromWord(jobject[i].color)+'"></div></div></div></div>'; } } var deleteButton = '<i id="'+i+'RowEditButton" onclick="editExtra('+i+');" class="fa fa-pencil"></i> <i onclick="deleteIndex('+ i +');" class="fa fa-times-circle"></i> '; if (jobject[i].NEW_ITERATE_FLAG) { deleteButton = '<i style="color:gray;" class="fa fa-pencil"></i> <i onclick="deleteIndex('+ i +');" class="fa fa-times-circle"></i> '; } $('.extraContainer').append('<div class="row extraRow row-margin-top row-margin-bottom mover-row RowIndex' + i + '"><div class="col-xs-4 col-sm-2 col-lg-1">'+deleteButton+downButton+upButton+'</div><div class="col-xs-8 col-sm-10 col-lg-11" style="padding:none;">'+tempJSON+'</div></div>'); } if (jobject.length == 0) { delete jobject; $('.extraContainer').html('<br><br>'); refreshLanguage(); } } else { $('.extraContainer div.extraRow').remove(); $('.extraContainer').html('<div class="row"><div class="col-xs-12"><h4>'+getLanguageString('textsnippets.nosnippets',lsm.getItem('langCode'))+'</h4></div></div>'); } refreshLanguage(); } /* SHOW MOUSE ACTION OPTIONS FOR JSON TEMPLATES WITH THAT FLAG */ if (templates[lsm.getItem('jtemplate')].mouseActionOptions) { $('.hoverEventContainer_edit').show(); $('.clickEventContainer_edit').show(); $('.insertionContainer_edit').show(); $('.hoverEventContainer').show(); $('.clickEventContainer').show(); $('.insertionContainer').show(); } else { $('.hoverEventContainer_edit').hide(); $('.clickEventContainer_edit').hide(); $('.insertionContainer_edit').hide(); $('.hoverEventContainer').hide(); $('.clickEventContainer').hide(); $('.insertionContainer').hide(); } if (templates[lsm.getItem('jtemplate')].formatType == 'signset') { $('.clickEventDisabledSigns').show(); $('.hoverEventDisabledSigns').show(); } else { $('.clickEventDisabledSigns').hide(); $('.hoverEventDisabledSigns').hide(); } /*EXTRA TRANSLATE STRING MANAGER*/ if (extraTextFormat == "trn") { $('#obj_extra_container').hide(); $('#text_extra_container').hide(); $('#selector_extra_container').hide(); $('#translate_selector_container').show(); if (!hasAlertedTranslationObjects) { swal('Translation objects are currently broken and may crash your game.','Please test your translation before publishing it.','warning'); hasAlertedTranslationObjects = true; } } else if (extraTextFormat == "obj") { $('#text_extra_container').hide(); $('#translate_selector_container').hide(); $('#selector_extra_container').hide(); $('#obj_extra_container').show(); } else if (extraTextFormat == "sel") { $('#text_extra_container').hide(); $('#translate_selector_container').hide(); $('#selector_extra_container').show(); $('#obj_extra_container').hide(); } else if (extraTextFormat == "raw") { $('#text_extra_container').show(); $('#obj_extra_container').hide(); $('#translate_selector_container').hide(); $('#selector_extra_container').hide(); $('.extraTranslationParameterRow').hide(); } if (extraTextFormat == 'NEW_ITERATE_FLAG') { if (templates[lsm.getItem('jtemplate')].formatType != 'bookarray' && templates[lsm.getItem('jtemplate')].formatType != 'signset') { var swalObject = { title: getLanguageString('textsnippets.NEW_ITERATE_FLAG.incorrect_template.primary.header',lsm.getItem('langCode')), text: getLanguageString('textsnippets.NEW_ITERATE_FLAG.incorrect_template.primary.description',lsm.getItem('langCode')), showCancelButton: true, confirmButtonText: getLanguageString('textsnippets.NEW_ITERATE_FLAG.incorrect_template.primary.yes',lsm.getItem('langCode')), cancelButtonText: getLanguageString('textsnippets.NEW_ITERATE_FLAG.incorrect_template.primary.no',lsm.getItem('langCode')), closeOnConfirm: false, closeOnCancel: true }; var swalCallback = function(isConfirm) { var template = undefined; if (isConfirm) { template = "book"; } else { template = "sign_item"; } $('.templateButton').removeClass('btn-success').removeClass('btn-default').addClass('btn-default'); $('.templateButton[template=' + template + ']').addClass('btn-success').removeClass('btn-default'); lsm.setItem('jtemplate',template); $('#command').val(templates[lsm.getItem('jtemplate')]['command']); refreshOutput(); swal(getLanguageString('textsnippets.NEW_ITERATE_FLAG.incorrect_template.tertiary.header',lsm.getItem('langCode')), getLanguageString('textsnippets.NEW_ITERATE_FLAG.incorrect_template.tertiary.description',lsm.getItem('langCode')).replace('%c', getLanguageString('template.' + template,lsm.getItem('langCode'))), "success"); } swal(swalObject, function(isConfirm){ if (isConfirm) { swal({ title: getLanguageString('textsnippets.NEW_ITERATE_FLAG.incorrect_template.secondary.header',lsm.getItem('langCode')), text: getLanguageString('textsnippets.NEW_ITERATE_FLAG.incorrect_template.secondary.description',lsm.getItem('langCode')), type: "info", showCancelButton: true, confirmButtonText: getLanguageString('textsnippets.NEW_ITERATE_FLAG.incorrect_template.secondary.book',lsm.getItem('langCode')), cancelButtonText: getLanguageString('textsnippets.NEW_ITERATE_FLAG.incorrect_template.secondary.sign',lsm.getItem('langCode')), closeOnConfirm: false, closeOnCancel: false }, swalCallback); } }); $('#fmtExtraRaw').click(); } $('.NEW_ITERATE_FLAG_not_container').hide(); } else { $('.NEW_ITERATE_FLAG_not_container').show(); } /*COMMAND MANAGER*/ if ($("#command").val() == "") $("#command").val(templates[lsm.getItem('jtemplate')]['command']); /*HOVEREVENT SUGGESTION MANAGER*/ $('#hoverEventValue').removeAttr('disabled'); selectedHover = getSelected("hoverEvent"); if (selectedHover == "show_achievement") { $('#hoverEventValue').autocomplete({ source: achievements }); } else if (selectedHover == "show_item") { $('#hoverEventValue').autocomplete({ source: [] }); } else if (selectedHover == "show_entity") { $('.hovertext_default').hide(); $('.hovertext_entity').show(); } else if (selectedHover == "none") { $('#hoverEventValue').attr('disabled','true'); $('#hoverEventValue').autocomplete({ source: [] }); } if (selectedHover != "show_entity") { $('.hovertext_default').show(); $('.hovertext_entity').hide(); } if (selectedHover == "show_text") { $('.hovertext_default').hide(); $('.hovertext_text').show(); $('#hoverEventText').val(JSON.stringify({"text":"","extra":[]})); } else { $('.hovertext_text').hide(); } /*HOVEREVENT EDIT SUGGESTION MANAGER*/ $('#hoverEventText_edit').removeAttr('disabled'); selectedHover_edit = getSelected('hoverEvent_edit'); if (selectedHover_edit == "show_achievement") { $('#hoverEventText_edit').autocomplete({ source: achievements }); } else if (selectedHover_edit == "show_item") { $('#hoverEventText_edit').autocomplete({ source: [] }); } else if (selectedHover_edit == "show_entity") { $('.hovertext_default_edit').hide(); $('.hovertext_entity_edit').show(); } else if (selectedHover_edit == "none") { $('#hoverEventText_edit').attr('disabled','true'); $('#hoverEventText_edit').autocomplete({ source: [] }); } if (selectedHover_edit != "show_entity") { $('.hovertext_default_edit').show(); $('.hovertext_entity_edit').hide(); } if (selectedHover_edit != "show_text") { $('.hovertext_text_edit').hide(); } else { $('.hovertext_text_edit').show(); } /*CLICKEVENT SUGGESTION MANAGER*/ $('#clickEventText').removeAttr('disabled'); selectedClick = getSelected("clickEvent"); if (selectedClick == "run_command" || selectedClick == "suggest_command") { $('#clickEventText').autocomplete({ source: commands }); } else if (selectedClick == "open_url") { $('#clickEventText').autocomplete({ source: ["https://", "http://", "http://apple.com", "https://minecraft.net", "https://mojang.com", "http://ezekielelin.com", "https://reddit.com"] }); } else if (selectedClick == "none") { $('#clickEventText').attr('disabled','true'); $('#clickEventText').autocomplete({ source: [] }); } /*CLICKEVENT EDIT SUGGESTION MANAGER*/ $('#clickEventText_edit').removeAttr('disabled'); selectedClick_edit = getSelected('clickEvent_edit'); if (selectedClick_edit == "run_command" || selectedClick_edit == "suggest_command") { $('#clickEventText_edit').autocomplete({ source: commands }); } else if (selectedClick_edit == "open_url") { $('#clickEventText_edit').autocomplete({ source: ["http://apple.com", "https://minecraft.net", "https://mojang.com", "http://ezekielelin.com", "https://", "https://reddit.com", "http://"] }); } else if (selectedClick_edit == "none") { $('#clickEventText_edit').attr('disabled','true'); $('#clickEventText_edit').autocomplete({ source: [] }); } /*PREPARING OUTPUT*/ var commandString = $('#command').val(); var JSONOutputString = ''; var EscapedJSONOutputString = ''; var formattedJObject = formatJObjectList(jobject); var newLineExpressions = { "bookarray": /\\\\\\\\n/g, "standardjson": /\\\\n/g, "signset": /\\\\\\\\n/g } if (!formattedJObject.length > 0) { JSONOutputString = '[]'; } else { if (templates[lsm.getItem('jtemplate')].formatType == 'bookarray') { JSONOutputString = JSON.stringify(formattedJObject); JSONOutputString = JSONOutputString.replace(newLineExpressions.bookarray,'\\n'); } else if (templates[lsm.getItem('jtemplate')].formatType == 'standardjson') { JSONOutputString = formattedJObject[0]; JSONOutputString = JSONOutputString.replace(newLineExpressions.standardjson,'\\n'); } else if (templates[lsm.getItem('jtemplate')].formatType == 'signset') { JSONOutputString = 'Text1:' + JSON.stringify(formattedJObject[0]); if (formattedJObject.length > 1) { JSONOutputString += ',Text2:' + JSON.stringify(formattedJObject[1]) } if (formattedJObject.length > 2) { JSONOutputString += ',Text3:' + JSON.stringify(formattedJObject[2]) } if (formattedJObject.length > 3) { JSONOutputString += ',Text4:' + JSON.stringify(formattedJObject[3]) } JSONOutputString = JSONOutputString.replace(newLineExpressions.signset,'\\n'); } } commandString = commandString.replace('%s',JSONOutputString); outputString = commandString; $('#outputtextfield').val(outputString); if ($('#showNiceLookingOutput').is(':checked')) { lsm.setItem('nlOutput','yes'); $('#nicelookingoutput').show().html(JSON.stringify(jobject, null, 4).replace(newLineExpressions.standardjson,'\\n')); } else { lsm.setItem('nlOutput','no'); $('#nicelookingoutput').hide(); } jsonParse(); /*COMMAND BLOCK WARNING*/ if ($('#outputtextfield').val().length > 90) { $('#commandblock').show(); } else { $('#commandblock').hide(); } /*SAVE VARIABLES*/ lsm.setItem('jobject',JSON.stringify(jobject)); lsm.setItem('jcommand', $('#command').val()); /*RERUN*/ if (input != 'noLoop' && input != 'previewLineChange') { refreshOutput('noLoop'); } } function jsonParse() { $('#jsonPreview').css('background-color','#'+$('#previewcolor').val()); $('#jsonPreview').css('font-size',$('#previewFontSize').val() + 'px'); lsm.setItem("color",$('#previewcolor').val()); $('#jsonPreview').html(''); if (templates[lsm.getItem('jtemplate')].formatType == 'bookarray') { $('#jsonPreview').addClass('bookPreview'); $('#previewBack').show(); $('#previewForwards').show(); $('#previewPage').show(); } else { $('#jsonPreview').removeClass('bookPreview'); $('#previewBack').hide(); $('#previewForwards').hide(); $('#previewPage').hide(); } if (get_type(jobject) == "[object Array]") { var pageHash = {}; var counter = 1; for (var i = 0; i < jobject.length; i++) { if (jobject[i].NEW_ITERATE_FLAG) { counter++; } else { pageHash['index.' + i] = counter; topPage = counter; } } if (jobject.length == 0) { topPage = 1; } if (bookPage > topPage) { bookPage = topPage; } //console.log(pageHash); $('#previewPage').html('Page ' + bookPage + ' of ' + topPage); for (var i = 0; i < jobject.length; i++) { if (jobject[i].NEW_ITERATE_FLAG) { if (/*templates[lsm.getItem('jtemplate')].formatType == 'bookarray' || */templates[lsm.getItem('jtemplate')].formatType == 'signset') { $('#jsonPreview').append('<span id="jsonPreviewSpanElement'+ i +'"><hr></span>'); } } else if (pageHash['index.' + i] == bookPage || templates[lsm.getItem('jtemplate')].formatType != 'bookarray') { var doClickEvent = false; var doHoverEvent = false; var popoverTitle = ""; var popoverContentClick = ""; var popoverContentHover = ""; var hoverEventType = ""; var hoverEventValue = ""; var clickEventType = ""; var clickEventValue = ""; $('#jsonPreview').append('<span id="jsonPreviewSpanElement'+ i +'"></span>'); if (jobject[i].text) { $('#jsonPreviewSpanElement'+i).html(jobject[i].text.replace(/\\\\n/g,'<br>').replace(/\\n/g,'<br>')); } else if (jobject[i].score) { $('#jsonPreviewSpanElement'+i).html('<span class="label label-info">' + jobject[i].score.name + ':' + jobject[i].score.objective + '</span>'); } else if (jobject[i].translate) { $('#jsonPreviewSpanElement'+i).html('<span class="label label-warning">Translation</span>'); } else if (jobject[i].selector) { $('#jsonPreviewSpanElement'+i).html('<span class="label label-primary">' + jobject[i].selector + '</span>'); } else { $('#jsonPreviewSpanElement'+i).html('<span class="label label-danger">Unknown Element</span>'); } if (jobject[i].bold == true) { $('#jsonPreviewSpanElement'+i).addClass('bold'); } if (jobject[i].italic == true) { $('#jsonPreviewSpanElement'+i).addClass('italic'); } if (jobject[i].underlined == true) { $('#jsonPreviewSpanElement'+i).addClass('underlined'); } if (jobject[i].strikethrough == true) { if ($('#jsonPreviewSpanElement'+i).hasClass('underlined')) { $('#jsonPreviewSpanElement'+i).removeClass('underlined'); $('#jsonPreviewSpanElement'+i).addClass('strikethroughunderlined'); } else { $('#jsonPreviewSpanElement'+i).addClass('strikethrough'); } } if (jobject[i].obfuscated == true) { $('#jsonPreviewSpanElement'+i).addClass('jsonPreviewObfuscated'); } /*COLORS*/ $('#jsonPreviewSpanElement'+i).css('color',getCSSHEXFromWord(jobject[i].color)); /*CLICK & HOVER EVENTS*/ if (get_type(jobject[i].clickEvent) != "[object Undefined]" || get_type(jobject[i].hoverEvent) != "[object Undefined]") { if (get_type(jobject[i].clickEvent) != "[object Undefined]") doClickEvent = true; if (get_type(jobject[i].hoverEvent) != "[object Undefined]") doHoverEvent = true; if (doHoverEvent && doClickEvent) { popoverTitle = getLanguageString('textsnippets.hoverevent.header',lsm.getItem('langCode')) + ' and ' + getLanguageString('textsnippets.clickevent.header',lsm.getItem('langCode')); hoverEventType = jobject[i].hoverEvent.action; hoverEventValue = jobject[i].hoverEvent.value; clickEventType = jobject[i].clickEvent.action; clickEventValue = jobject[i].clickEvent.value; } if (doHoverEvent && !doClickEvent) { popoverTitle = getLanguageString('textsnippets.hoverevent.header',lsm.getItem('langCode')); hoverEventType = jobject[i].hoverEvent.action; hoverEventValue = jobject[i].hoverEvent.value; } if (!doHoverEvent && doClickEvent) { popoverTitle = getLanguageString('textsnippets.clickevent.header',lsm.getItem('langCode')); clickEventType = jobject[i].clickEvent.action; clickEventValue = jobject[i].clickEvent.value; } if (doClickEvent) { if (clickEventType == "open_url") { popoverContentClick = clickEventType+':<a href="'+clickEventValue+'">'+clickEventValue+'</a>'; } else { popoverContentClick = clickEventType+':'+clickEventValue; } } if (doHoverEvent) { if (hoverEventType == 'show_text') { hoverEventValue = JSON.stringify(hoverEventValue); } popoverContentHover = hoverEventType+':'+hoverEventValue; } if (doHoverEvent && doClickEvent) { popoverContentClick = popoverContentClick + '<br>'; } $('#jsonPreviewSpanElement'+i).attr('rel','popover'); } $('#jsonPreviewSpanElement'+ i).popover({ title: popoverTitle, content: popoverContentClick+popoverContentHover, html:true}); } } } else { $('#jsonPreview').html(getLanguageString('output.nothing',lsm.getItem('langCode'))); $('#jsonPreview').css('color','white'); } if ($('.jsonPreviewObfuscated').length > 0) { setTimeout(obfuscationPreviewHandler, 20); } } function refreshLanguage(dropdownSelection) { if (lang[lsm.getItem('langCode')]) { $('*').refreshLanguage(lsm.getItem('langCode')); } else { lsm.setItem('langCode','en-US') } $('*').each(function(){ //if ($(this).attr('version') != undefined && (lsm.getItem('versionIndicators') == "true" || lsm.getItem('versionIndicators') == undefined)) { if (false) { var labelLevel = 'success'; if ($(this).attr('version') == '1.9') { labelLevel = 'danger'; } if ($(this).prop('tagName') == 'OPTION') { $(this).prepend('('+$(this).attr('version')+') '); } else { $(this).append(' <span class="label label-'+labelLevel+'">'+$(this).attr('version')+'</span>'); } } }); } function initialize() { if (lsm.getItem('initialTimestamp') == undefined) { lsm.setItem('initialTimestamp',new Date().getTime()) } if (lsm.getItem('langCode') == undefined) { if (lang[navigator.language.toLowerCase()] != undefined) { lsm.setItem('langCode',navigator.language.toLowerCase()); } else { if (webLangRelations[navigator.language.toLowerCase()] != undefined) { lsm.setItem('langCode',webLangRelations[navigator.language.toLowerCase()]); } } } if (lsm.getItem('langCode') == undefined) { lsm.setItem('langCode','en_US'); } if (lsm.getItem('jformat') != version && lsm.getItem('jformat') != undefined) { swal({ title: "Your cookie format is old!", text: "This may cause issues. Would you like to reset them? You won't be asked again until the next time the format changes.", showCancelButton: true, confirmButtonText: "Reset Cookies", cancelButtonText: "Don't Reset", closeOnCancel: false },function(isConfirm){ if (isConfirm) { sessionStorage.setItem('nextTimeAlert',JSON.stringify({'title': 'All Done', 'text': 'Your cookies have successfully been reset.\n\nCookies are reset when the format changes drastically, or when a mistake causes the cookies to break the website.', 'type': 'success'})); lsm.clear(); location.reload(); } else { swal('Nothing was reset','You won\'t be asked again until the cookie format changes. If you experience an issue, please clear your coookies for this website', 'info'); } }); } else { /*check if alert isn't correctly set. Do not show the alert is jformat isn't set – that means the user hasn't been here before*/ if (lsm.getItem('jalert') != notice.id && lsm.getItem('jformat') != undefined && notice.show) { swal(notice.message); } lsm.setItem('jalert',notice.id); } lsm.setItem('jformat',version); if (sessionStorage.getItem('nextTimeAlert')) { swal(JSON.parse(sessionStorage.getItem('nextTimeAlert'))); sessionStorage.removeItem('nextTimeAlert'); } if (lsm.getItem('nextTimeAlert')) { swal(JSON.parse(lsm.getItem('nextTimeAlert'))); lsm.removeItem('nextTimeAlert'); } if (lsm.getItem('donateAlert') != "shown" && lsm.getItem('donateAlert') != "not-shown") { lsm.setItem('donateAlert','not-shown') } else { if (lsm.getItem('donateAlert') == 'not-shown' && false) { swal({ "title": "Please Consider Donating", "text": "Donations help support my developement of these programs!\n\nDonations can be done through a variety of services, it's up to you.", "confirmButtonText": "I want to donate", "cancelButtonText": "I have already or don't want to donate", "showCancelButton": true, "closeOnConfirm": false, "closeOnCancel": false }, function(want){ if (want) { var swalCallback = function(amount){ if (amount > 25 && amount < 40) { var swalMessage = { "title": "Overcast Network", "text": "That amount fits nicely with an upgrade to my <a href=\"http://oc.tc/ezfe\">Overcast Network</a> account", "html": true, "confirmButtonText": "Ok, show me the page", "cancelButtonText": "I'd rather just send the money", "showCancelButton": true, "closeOnConfirm": false, "closeOnCancel": false }; var swalCallback = function(shouldGoToOvercast){ if (shouldGoToOvercast) { swal({ "title": "Almost done...", "text": "When you arrive, enter the username <i>ezfe</i>", "html": true, },function(){ lsm.setItem('nextTimeAlert',JSON.stringify({"title": "Thanks!", "text": "I'm assuming you donated, in which case thanks! Otherwise, perhaps later?", "type": "success"})); location.href = "https://oc.tc/shop"; }); } else { var swalMessage = { "title": "Ok, that's fine", "text": "Right now, I only offer PayPal, because my web payment system is broken.\n\nYou can find my email address at the bottom of the page!", "status": "success" }; swal(swalMessage); } } swal(swalMessage,swalCallback); } else { var swalMessage = { "title": "Great!", "text": "Right now, I only offer PayPal, because my web payment system is broken.\n\nYou can find my email address at the bottom of the page!", "status": "success" }; swal(swalMessage); } } swal({ "title": "Awesome", "text": "How much do you want to donate?\n(Please enter a number, like 3 or 11. Don't enter the $ symbol)", "type": "input", "closeOnConfirm": false },swalCallback); } else { swal('Awe...','I won\'t bother you again, so long as you don\'t reset your cookies.\n\nI can\'t remember things if you do that.'); } }); lsm.setItem('donateAlert','shown'); } } for (var i = 0; i < Object.keys(templates).length; i++) { var key = Object.keys(templates)[i] if (key == lsm.getItem('jtemplate')) { var classString = 'btn-success'; } else { var classString = 'btn-default'; } $('#templateButtons').append('<button class="btn btn-xs ' + classString + ' templateButton" lang="template.' + key + '" version="' + templates[key]['version'] + '" template="'+ key +'"></button> '); } if (lsm.getItem('jtemplate') == undefined) { lsm.setItem('jtemplate', 'tellraw'); } if (lang[lsm.getItem('langCode')]) { errorString = getLanguageName(lsm.getItem('langCode')) + '<br><br>'; } else { errorString = '&lt;language unknown&gt;<br><br>'; } /*var enCount = JSON.stringify(lang['en_US']).length;*/ for (var i = 0; i < Object.keys(lang).length; i++) { /*var langKey = Object.keys(lang)[i]; var currentCount = JSON.stringify(lang[langKey]).length; var currentPercentage = Math.round(currentCount/enCount*100); console.log(currentPercentage);*/ $('#language_keys').append('<li><a onclick="errorString = \''+ getLanguageName(Object.keys(lang)[i]) +'<br><br>\'; lsm.setItem(\'langCode\',\''+Object.keys(lang)[i]+'\'); refreshLanguage(true); refreshOutput();"><span class="' + Object.keys(lang)[i] + ' langSelect" id="language_select_'+Object.keys(lang)[i]+'">'+ getLanguageName(Object.keys(lang)[i]) +'</span></a></li>'); }; $('#language_keys').append('<li class="divider"></li>'); $('#language_keys').append('<li><a href="http://translate.minecraftjson.com"><span class="language_area" lang="language.translate"></span></a></li>'); $('.extraTranslationParameterRow').hide(); if (lsm.getItem('color') != undefined) { $('#previewcolor').val(lsm.getItem("color")); } else { $('#previewcolor').val('617A80'); } $('#previewcolor').css('background-color','#'+$('#previewcolor').val()); jsonParse(); if (lsm.getItem('jobject') != undefined) { jobject = verify_jobject_format(JSON.parse(lsm.getItem("jobject"))); } if (lsm.getItem('nlOutput') == undefined) { lsm.setItem('nlOutput','no'); } if (lsm.getItem('nlOutput') == 'no') { $('#showNiceLookingOutput').prop('checked', false); } else { $('#showNiceLookingOutput').prop('checked', true); } showView('pageheader',true,false); //JSON.stringify({"viewname":viewname,"suppressAnimation":suppressAnimation,"hideOthers":hideOthers,"hideMenubar":hideMenubar}) if (lsm.getItem('jview') != undefined/* && typeof JSON.stringify(lsm.getItem('jview')) != "string"*/) { var viewObject = JSON.parse(lsm.getItem('jview')); showView(viewObject.viewname,viewObject.suppressAnimation,viewObject.hideOthers,viewObject.hideMenubar); } else { showView('tellraw') } if (lsm.getItem('jtosaccept') == undefined || lsm.getItem('jtosaccept') != tos_version) { //showView('tos-header',true,false,true); } $('.templateButton').click(function(){ $('.templateButton').removeClass('btn-success').removeClass('btn-default').addClass('btn-default'); $(this).addClass('btn-success').removeClass('btn-default'); var template = $(this).attr('template'); lsm.setItem('jtemplate',template); $('#command').val(templates[lsm.getItem('jtemplate')]['command']); refreshOutput(); }); $('#command').val(lsm.getItem('jcommand')); $('#command').change(function(){refreshOutput()}); $('#import').click(function() { swal({ "title": "Import", "text": getLanguageString('settings.importtext.exported.description',lsm.getItem('langCode')), "type": "input", "closeOnConfirm": false },function(oinpt){ var inpt = undefined try { inpt = JSON.parse(oinpt); } catch(err) { logIssue(getLanguageString('settings.importtext.exported.failed.header',lsm.getItem('langCode')),getLanguageString('settings.importtext.exported.failed.description',lsm.getItem('langCode')) + ': ' + oinpt,true) } jobject = inpt['jobject']; if (inpt['jtemplate']) { lsm.setItem('jtemplate',inpt['jtemplate']) } $('#command').val(inpt['command']); swal("Imported", "Your command has been imported", "success"); refreshOutput(); }) }); $('#export').click(function(){ $('#exporter').remove(); $('.alerts').append('<div id="exporter" class="alert alert-info"><h4 lang="export.heading"></h4><p><textarea readonly id="exportText">' + JSON.stringify({"command":$('#command').val(),"jobject":jobject,"jtemplate":lsm.getItem('jtemplate')}) + '</textarea></p><p><button type="button" onclick="closeExport()" class="btn btn-default" lang="export.close"></button></p></div>'); $exportText = $('#exportText'); $exportText.select(); $exportText.height('1px'); $exportText.height(exportText.scrollHeight + "px"); $exportText.click(function(){ this.select(); }); goToByScroll('exporter'); refreshLanguage(); }); $('#translate_input').change(function(){ var val = translationStrings[$('#translate_input').val()]; var match = val.match(/%./g); matchLength = match.length var c = getSelected('translate_selector'); $('.extraTranslationParameterRow').hide(); $('.extraTranslationParameterRow').val(''); if (match != null) { for (var i = matchLength - 1; i >= 0; i--) { if (matchLength > 5) { swal('An unexpected error has occured.','EID-more than 5 matches','error'); } for (var i = matchLength - 1; i >= 0; i--) { $('#parameter'+i+'row').show(); }; }; } }); refreshLanguage(); refreshOutput(); $('.fmtExtra').on('click', function(){ extraTextFormat = $(this).attr('tellrawType'); $('.fmtExtra').removeClass('active'); $(this).addClass('active'); refreshOutput(); }); $('#addHoverTextText').on('click',function(){ textobj = JSON.parse($('#hoverEventText').val()); snipobj = {"text":$('#hoverEventTextSnippet').val()}; if ($('#snippetcolor').val() != 'none') { snipobj.color = $('#snippetcolor').val(); } $('#hoverEventTextSnippet').val(''); textobj.extra.push(snipobj) $('#hoverEventText').val(JSON.stringify(textobj)); }); $('#removeHoverTextText').on('click',function(){ textobj = JSON.parse($('#hoverEventText').val()); textobj.extra.splice(-1,1) $('#hoverEventText').val(JSON.stringify(textobj)); }); $('#addExtraButton').on('click',function(){ showView('add-extra') editing = true; }); $( "#translate_input" ).autocomplete({ //source: Object.keys(translationStrings) }); $( "#translate_input_edit" ).autocomplete({ //source: Object.keys(translationStrings) }); $('#show-saves').on('click',function(){ showView('saves'); }); $('#hide-saves').on('click',function(){ showView('tellraw'); }); $('#lang_request').on('click',function(){ showView('lang-request'); $('#lang-request-errorstring').html(errorString); }); $('#helptoggle').click(function(){ $('.help-box').toggle(); }); $('#enable_dark_mode').on('click',function(){ lsm.setItem('darkMode','true'); $('body').addClass('black-theme'); $(this).hide(); $('#disable_dark_mode').show(); }); $('#disable_dark_mode').on('click',function(){ lsm.setItem('darkMode','false'); $('body').removeClass('black-theme'); $(this).hide(); $('#enable_dark_mode').show(); }); $('.report-issue').on('click',function(){ $('.view-container[view="report-issue"]').children().not('.cancel-issue-row').hide(); $('#issue-workflow-r1').show(); showView('report-issue'); }); $('#previewBack').click(function(){ if (bookPage != 1) bookPage--; refreshOutput(); }); $('#previewForwards').click(function(){ if (bookPage < topPage) bookPage++; refreshOutput(); }); $('.issue-button').click(function(){ var parentRow = $(this).parent().parent(); parentRow.hide(); var id = $(this).attr('id'); if (id == "translation-issue-button") { $('#issue-workflow-r2-translation').fadeIn(); } else if (id == "output-issue-button") { $('#issue-workflow-r2-output').fadeIn(); } else if (id == "translation-current-issue-button") { reportAnIssue('Translation Issue (' + lsm.getItem('langCode') + ')'); showView('tellraw'); } else if (id == "translation-other-issue-button") { reportAnIssue('Translation Issue (Other)'); showView('tellraw'); } else if (id == "output-quotes-issue-button") { $('.templateButton[template=tellraw]').click(); swal('The issue should be fixed.','If it is not, please report as Output > Other, and note this event in your report..','info'); showView('tellraw'); } else if (id == "output-other-issue-button") { reportAnIssue('Output Issue (Other)'); showView('tellraw'); } else if (id == "cancel-issue-button") { showView('tellraw'); parentRow.show(); } else { showView('tellraw'); reportAnIssue(); } }); // Beta tooltip $('#dropdown-list-a').tooltip({"title":"<i style=\"color: #F8814C;\" class=\"fa fa-exclamation-circle\"></i> " + getLanguageString('headerbar.dropdown.hover',lsm.getItem('langCode')),"html":true,"placement":"bottom"}); if (lsm.getItem('beta-tooltip-a-shown') != "yes") { $('#dropdown-list-a').tooltip('show'); } lsm.setItem('beta-tooltip-a-shown',"yes"); //Dark Mode if (lsm.getItem('darkMode') && lsm.getItem('darkMode') == 'true') { $('#enable_dark_mode').click(); //Finish setting up dark mode after handlers exist } } $(document).ready(function(){ if (lsm.getItem('darkMode') && lsm.getItem('darkMode') == 'true') { $('body').addClass('black-theme'); //Rest of "dark mode" is handled later, color scheme handled early for appearance } else if (lsm.getItem('darkMode') == undefined) { $('body').addClass('black-theme'); lsm.setItem('darkMode','true'); } $('.view-container').hide(); showView('loading',true,true,true); $('#loadingtxt').html('Loading Assets'); try { data = getURL('resources.json'); } catch(err) { swal({ "title": "Error!", "text": "An error occured loading page assets. Please try again later.", "type": "error" },function(){ $('html').html('Please try again later'); }); } if (typeof data == 'string') { try { data = JSON.parse(data); } catch(err) { swal({ "title": "Error!", "text": "An error occured loading page assets. Please try again later.", "type": "error" },function(){ $('html').html('Please try again later'); }); } } if (location.hash == "#embed") { $('.view-container[view="tellraw"]').children().filter('br').remove(); embed = true; } else { embed = false; } translationStrings = data['minecraft_language_strings']['en_US']; webLangRelations = data['web_language_relations']; achievements = data['achievements']; commands = data['commands']; for (var i = 0; i < data['web_language_urls'].length; i++) { try { var urlFetch = getURL('lang/' + data['web_language_urls'][i] + '.json'); } catch(err) { if (data['web_language_urls'][i] == 'en_US') { var urlFetch = {"language":{"name":"English"}}; } else { continue; } } if (typeof urlFetch == 'string') { try { urlFetch = JSON.parse(urlFetch); } catch(err) { if (data['web_language_urls'][i] == 'en_US') { var urlFetch = {"language":{"name":"English"}}; } else { continue; } } } lang[data['web_language_urls'][i]] = urlFetch; } delete lang.status; setTimeout(initialize,500); });
Started removing more translation stuff for rewrite #12
js/tellraw.js
Started removing more translation stuff for rewrite
<ide><path>s/tellraw.js <ide> var upButton; <ide> var extraTextFormat = 'raw'; <ide> var lang = {"status":"init"}; <del>var translationStrings; <ide> var currentEdit; <ide> var hasAlertedTranslationObjects = false; <ide> var webLangRelations; <ide> goToByScroll('exporter'); <ide> refreshLanguage(); <ide> }); <del> $('#translate_input').change(function(){ <del> var val = translationStrings[$('#translate_input').val()]; <del> var match = val.match(/%./g); <del> matchLength = match.length <del> var c = getSelected('translate_selector'); <del> $('.extraTranslationParameterRow').hide(); <del> $('.extraTranslationParameterRow').val(''); <del> if (match != null) { <del> for (var i = matchLength - 1; i >= 0; i--) { <del> if (matchLength > 5) { <del> swal('An unexpected error has occured.','EID-more than 5 matches','error'); <del> } <del> for (var i = matchLength - 1; i >= 0; i--) { <del> $('#parameter'+i+'row').show(); <del> }; <del> }; <del> } <del> }); <ide> refreshLanguage(); <ide> refreshOutput(); <ide> $('.fmtExtra').on('click', function(){ <ide> $('#addExtraButton').on('click',function(){ <ide> showView('add-extra') <ide> editing = true; <del> }); <del> $( "#translate_input" ).autocomplete({ <del> //source: Object.keys(translationStrings) <del> }); <del> $( "#translate_input_edit" ).autocomplete({ <del> //source: Object.keys(translationStrings) <ide> }); <ide> $('#show-saves').on('click',function(){ <ide> showView('saves'); <ide> } else { <ide> embed = false; <ide> } <del> translationStrings = data['minecraft_language_strings']['en_US']; <ide> webLangRelations = data['web_language_relations']; <ide> achievements = data['achievements']; <ide> commands = data['commands'];
Java
mpl-2.0
b9d7eaed85224ad37e601c5012e9431f3eb057a9
0
jonalmeida/focus-android,ekager/focus-android,ekager/focus-android,jonalmeida/focus-android,jonalmeida/focus-android,ekager/focus-android,mozilla-mobile/focus-android,mozilla-mobile/focus-android,ekager/focus-android,ekager/focus-android,mozilla-mobile/focus-android,jonalmeida/focus-android,mozilla-mobile/focus-android,jonalmeida/focus-android,jonalmeida/focus-android,mozilla-mobile/focus-android,ekager/focus-android,mozilla-mobile/focus-android
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.AttributeSet; import android.view.View; import android.view.WindowManager; import org.mozilla.focus.R; import org.mozilla.focus.architecture.NonNullObserver; import org.mozilla.focus.fragment.BrowserFragment; import org.mozilla.focus.fragment.FirstrunFragment; import org.mozilla.focus.fragment.UrlInputFragment; import org.mozilla.focus.locale.LocaleAwareAppCompatActivity; import org.mozilla.focus.session.Session; import org.mozilla.focus.session.SessionManager; import org.mozilla.focus.session.ui.SessionsSheetFragment; import org.mozilla.focus.telemetry.TelemetryWrapper; import org.mozilla.focus.utils.Settings; import org.mozilla.focus.utils.ViewUtils; import org.mozilla.focus.web.IWebView; import org.mozilla.focus.web.WebViewProvider; import java.util.List; import mozilla.components.support.utils.SafeIntent; public class MainActivity extends LocaleAwareAppCompatActivity { public static final String ACTION_ERASE = "erase"; public static final String ACTION_OPEN = "open"; public static final String EXTRA_TEXT_SELECTION = "text_selection"; public static final String EXTRA_NOTIFICATION = "notification"; private static final String EXTRA_SHORTCUT = "shortcut"; private final SessionManager sessionManager; public MainActivity() { sessionManager = SessionManager.getInstance(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Settings.getInstance(this).shouldUseSecureMode()) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); } getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); setContentView(R.layout.activity_main); final SafeIntent intent = new SafeIntent(getIntent()); if (intent.isLauncherIntent()) { TelemetryWrapper.openFromIconEvent(); } sessionManager.handleIntent(this, intent, savedInstanceState); registerSessionObserver(); WebViewProvider.preload(this); } private void registerSessionObserver() { (isCustomTabMode() ? sessionManager.getCustomTabSessions() : sessionManager.getSessions() ).observe(this, new NonNullObserver<List<Session>>() { private boolean wasSessionsEmpty = false; @Override public void onValueChanged(@NonNull List<Session> sessions) { if (sessions.isEmpty()) { // There's no active session. Show the URL input screen so that the user can // start a new session. showUrlInputScreen(); wasSessionsEmpty = true; } else { // This happens when we move from 0 to 1 sessions: either on startup or after an erase. if (wasSessionsEmpty) { WebViewProvider.performNewBrowserSessionCleanup(); wasSessionsEmpty = false; } // We have at least one session. Show a fragment for the current session. showBrowserScreenForCurrentSession(); } // If needed show the first run tour on top of the browser or url input fragment. if (Settings.getInstance(MainActivity.this).shouldShowFirstrun()) { showFirstrun(); } } }); } protected boolean isCustomTabMode() { return false; } @Override public void applyLocale() { // We don't care here: all our fragments update themselves as appropriate } @Override protected void onResume() { super.onResume(); TelemetryWrapper.startSession(); if (Settings.getInstance(this).shouldUseSecureMode()) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); } else { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE); } } @Override protected void onPause() { if (isFinishing()) { WebViewProvider.performCleanup(this); } super.onPause(); TelemetryWrapper.stopSession(); } @Override protected void onStop() { super.onStop(); TelemetryWrapper.stopMainActivity(); } @Override protected void onNewIntent(Intent unsafeIntent) { final SafeIntent intent = new SafeIntent(unsafeIntent); sessionManager.handleNewIntent(this, intent); final String action = intent.getAction(); if (ACTION_OPEN.equals(action)) { TelemetryWrapper.openNotificationActionEvent(); } if (ACTION_ERASE.equals(action)) { processEraseAction(intent); } if (intent.isLauncherIntent()) { TelemetryWrapper.resumeFromIconEvent(); } } private void processEraseAction(final SafeIntent intent) { final boolean fromShortcut = intent.getBooleanExtra(EXTRA_SHORTCUT, false); final boolean fromNotification = intent.getBooleanExtra(EXTRA_NOTIFICATION, false); SessionManager.getInstance().removeAllSessions(); if (fromShortcut) { TelemetryWrapper.eraseShortcutEvent(); } else if (fromNotification) { TelemetryWrapper.eraseAndOpenNotificationActionEvent(); } } private void showUrlInputScreen() { final FragmentManager fragmentManager = getSupportFragmentManager(); final BrowserFragment browserFragment = (BrowserFragment) fragmentManager.findFragmentByTag(BrowserFragment.FRAGMENT_TAG); final boolean isShowingBrowser = browserFragment != null; if (isShowingBrowser) { ViewUtils.showBrandedSnackbar(findViewById(android.R.id.content), R.string.feedback_erase, getResources().getInteger(R.integer.erase_snackbar_delay)); } // We add the url input fragment to the layout if it doesn't exist yet. final FragmentTransaction transaction = fragmentManager .beginTransaction(); // We only want to play the animation if a browser fragment is added and resumed. // If it is not resumed then the application is currently in the process of resuming // and the session was removed while the app was in the background (e.g. via the // notification). In this case we do not want to show the content and remove the // browser fragment immediately. boolean shouldAnimate = isShowingBrowser && browserFragment.isResumed(); if (shouldAnimate) { transaction.setCustomAnimations(0, R.anim.erase_animation); } transaction .replace(R.id.container, UrlInputFragment.createWithoutSession(), UrlInputFragment.FRAGMENT_TAG) .commit(); } private void showFirstrun() { getSupportFragmentManager() .beginTransaction() .add(R.id.container, FirstrunFragment.create(), FirstrunFragment.FRAGMENT_TAG) .commit(); } protected Session getCurrentSessionForActivity() { return sessionManager.getCurrentSession(); } protected void showBrowserScreenForCurrentSession() { final Session currentSession = getCurrentSessionForActivity(); final FragmentManager fragmentManager = getSupportFragmentManager(); final BrowserFragment fragment = (BrowserFragment) fragmentManager.findFragmentByTag(BrowserFragment.FRAGMENT_TAG); if (fragment != null && fragment.getSession().isSameAs(currentSession)) { // There's already a BrowserFragment displaying this session. return; } fragmentManager .beginTransaction() .replace(R.id.container, BrowserFragment.createForSession(currentSession), BrowserFragment.FRAGMENT_TAG) .commit(); } @Override public View onCreateView(String name, Context context, AttributeSet attrs) { if (name.equals(IWebView.class.getName())) { // Inject our implementation of IWebView from the WebViewProvider. return WebViewProvider.create(this, attrs); } return super.onCreateView(name, context, attrs); } @Override public void onBackPressed() { final FragmentManager fragmentManager = getSupportFragmentManager(); final SessionsSheetFragment sessionsSheetFragment = (SessionsSheetFragment) fragmentManager.findFragmentByTag(SessionsSheetFragment.FRAGMENT_TAG); if (sessionsSheetFragment != null && sessionsSheetFragment.isVisible() && sessionsSheetFragment.onBackPressed()) { // SessionsSheetFragment handles back presses itself (custom animations). return; } final UrlInputFragment urlInputFragment = (UrlInputFragment) fragmentManager.findFragmentByTag(UrlInputFragment.FRAGMENT_TAG); if (urlInputFragment != null && urlInputFragment.isVisible() && urlInputFragment.onBackPressed()) { // The URL input fragment has handled the back press. It does its own animations so // we do not try to remove it from outside. return; } final BrowserFragment browserFragment = (BrowserFragment) fragmentManager.findFragmentByTag(BrowserFragment.FRAGMENT_TAG); if (browserFragment != null && browserFragment.isVisible() && browserFragment.onBackPressed()) { // The Browser fragment handles back presses on its own because it might just go back // in the browsing history. return; } super.onBackPressed(); } }
app/src/main/java/org/mozilla/focus/activity/MainActivity.java
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.AttributeSet; import android.view.View; import android.view.WindowManager; import org.mozilla.focus.R; import org.mozilla.focus.architecture.NonNullObserver; import org.mozilla.focus.fragment.BrowserFragment; import org.mozilla.focus.fragment.FirstrunFragment; import org.mozilla.focus.fragment.UrlInputFragment; import org.mozilla.focus.locale.LocaleAwareAppCompatActivity; import org.mozilla.focus.session.Session; import org.mozilla.focus.session.SessionManager; import org.mozilla.focus.session.ui.SessionsSheetFragment; import org.mozilla.focus.telemetry.SentryWrapper; import org.mozilla.focus.telemetry.TelemetryWrapper; import org.mozilla.focus.utils.Settings; import org.mozilla.focus.utils.ViewUtils; import org.mozilla.focus.web.IWebView; import org.mozilla.focus.web.WebViewProvider; import java.util.List; import mozilla.components.support.utils.SafeIntent; public class MainActivity extends LocaleAwareAppCompatActivity { public static final String ACTION_ERASE = "erase"; public static final String ACTION_OPEN = "open"; public static final String EXTRA_TEXT_SELECTION = "text_selection"; public static final String EXTRA_NOTIFICATION = "notification"; private static final String EXTRA_SHORTCUT = "shortcut"; private final SessionManager sessionManager; public MainActivity() { sessionManager = SessionManager.getInstance(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SentryWrapper.INSTANCE.init(this); if (Settings.getInstance(this).shouldUseSecureMode()) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); } getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); setContentView(R.layout.activity_main); final SafeIntent intent = new SafeIntent(getIntent()); if (intent.isLauncherIntent()) { TelemetryWrapper.openFromIconEvent(); } sessionManager.handleIntent(this, intent, savedInstanceState); registerSessionObserver(); WebViewProvider.preload(this); } private void registerSessionObserver() { (isCustomTabMode() ? sessionManager.getCustomTabSessions() : sessionManager.getSessions() ).observe(this, new NonNullObserver<List<Session>>() { private boolean wasSessionsEmpty = false; @Override public void onValueChanged(@NonNull List<Session> sessions) { if (sessions.isEmpty()) { // There's no active session. Show the URL input screen so that the user can // start a new session. showUrlInputScreen(); wasSessionsEmpty = true; } else { // This happens when we move from 0 to 1 sessions: either on startup or after an erase. if (wasSessionsEmpty) { WebViewProvider.performNewBrowserSessionCleanup(); wasSessionsEmpty = false; } // We have at least one session. Show a fragment for the current session. showBrowserScreenForCurrentSession(); } // If needed show the first run tour on top of the browser or url input fragment. if (Settings.getInstance(MainActivity.this).shouldShowFirstrun()) { showFirstrun(); } } }); } protected boolean isCustomTabMode() { return false; } @Override public void applyLocale() { // We don't care here: all our fragments update themselves as appropriate } @Override protected void onResume() { super.onResume(); TelemetryWrapper.startSession(); if (Settings.getInstance(this).shouldUseSecureMode()) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); } else { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE); } } @Override protected void onPause() { if (isFinishing()) { WebViewProvider.performCleanup(this); } super.onPause(); TelemetryWrapper.stopSession(); } @Override protected void onStop() { super.onStop(); TelemetryWrapper.stopMainActivity(); } @Override protected void onNewIntent(Intent unsafeIntent) { final SafeIntent intent = new SafeIntent(unsafeIntent); sessionManager.handleNewIntent(this, intent); final String action = intent.getAction(); if (ACTION_OPEN.equals(action)) { TelemetryWrapper.openNotificationActionEvent(); } if (ACTION_ERASE.equals(action)) { processEraseAction(intent); } if (intent.isLauncherIntent()) { TelemetryWrapper.resumeFromIconEvent(); } } private void processEraseAction(final SafeIntent intent) { final boolean fromShortcut = intent.getBooleanExtra(EXTRA_SHORTCUT, false); final boolean fromNotification = intent.getBooleanExtra(EXTRA_NOTIFICATION, false); SessionManager.getInstance().removeAllSessions(); if (fromShortcut) { TelemetryWrapper.eraseShortcutEvent(); } else if (fromNotification) { TelemetryWrapper.eraseAndOpenNotificationActionEvent(); } } private void showUrlInputScreen() { final FragmentManager fragmentManager = getSupportFragmentManager(); final BrowserFragment browserFragment = (BrowserFragment) fragmentManager.findFragmentByTag(BrowserFragment.FRAGMENT_TAG); final boolean isShowingBrowser = browserFragment != null; if (isShowingBrowser) { ViewUtils.showBrandedSnackbar(findViewById(android.R.id.content), R.string.feedback_erase, getResources().getInteger(R.integer.erase_snackbar_delay)); } // We add the url input fragment to the layout if it doesn't exist yet. final FragmentTransaction transaction = fragmentManager .beginTransaction(); // We only want to play the animation if a browser fragment is added and resumed. // If it is not resumed then the application is currently in the process of resuming // and the session was removed while the app was in the background (e.g. via the // notification). In this case we do not want to show the content and remove the // browser fragment immediately. boolean shouldAnimate = isShowingBrowser && browserFragment.isResumed(); if (shouldAnimate) { transaction.setCustomAnimations(0, R.anim.erase_animation); } transaction .replace(R.id.container, UrlInputFragment.createWithoutSession(), UrlInputFragment.FRAGMENT_TAG) .commit(); } private void showFirstrun() { getSupportFragmentManager() .beginTransaction() .add(R.id.container, FirstrunFragment.create(), FirstrunFragment.FRAGMENT_TAG) .commit(); } protected Session getCurrentSessionForActivity() { return sessionManager.getCurrentSession(); } protected void showBrowserScreenForCurrentSession() { final Session currentSession = getCurrentSessionForActivity(); final FragmentManager fragmentManager = getSupportFragmentManager(); final BrowserFragment fragment = (BrowserFragment) fragmentManager.findFragmentByTag(BrowserFragment.FRAGMENT_TAG); if (fragment != null && fragment.getSession().isSameAs(currentSession)) { // There's already a BrowserFragment displaying this session. return; } fragmentManager .beginTransaction() .replace(R.id.container, BrowserFragment.createForSession(currentSession), BrowserFragment.FRAGMENT_TAG) .commit(); } @Override public View onCreateView(String name, Context context, AttributeSet attrs) { if (name.equals(IWebView.class.getName())) { // Inject our implementation of IWebView from the WebViewProvider. return WebViewProvider.create(this, attrs); } return super.onCreateView(name, context, attrs); } @Override public void onBackPressed() { final FragmentManager fragmentManager = getSupportFragmentManager(); final SessionsSheetFragment sessionsSheetFragment = (SessionsSheetFragment) fragmentManager.findFragmentByTag(SessionsSheetFragment.FRAGMENT_TAG); if (sessionsSheetFragment != null && sessionsSheetFragment.isVisible() && sessionsSheetFragment.onBackPressed()) { // SessionsSheetFragment handles back presses itself (custom animations). return; } final UrlInputFragment urlInputFragment = (UrlInputFragment) fragmentManager.findFragmentByTag(UrlInputFragment.FRAGMENT_TAG); if (urlInputFragment != null && urlInputFragment.isVisible() && urlInputFragment.onBackPressed()) { // The URL input fragment has handled the back press. It does its own animations so // we do not try to remove it from outside. return; } final BrowserFragment browserFragment = (BrowserFragment) fragmentManager.findFragmentByTag(BrowserFragment.FRAGMENT_TAG); if (browserFragment != null && browserFragment.isVisible() && browserFragment.onBackPressed()) { // The Browser fragment handles back presses on its own because it might just go back // in the browsing history. return; } super.onBackPressed(); } }
No Issue - Disables Sentry
app/src/main/java/org/mozilla/focus/activity/MainActivity.java
No Issue - Disables Sentry
<ide><path>pp/src/main/java/org/mozilla/focus/activity/MainActivity.java <ide> import org.mozilla.focus.session.Session; <ide> import org.mozilla.focus.session.SessionManager; <ide> import org.mozilla.focus.session.ui.SessionsSheetFragment; <del>import org.mozilla.focus.telemetry.SentryWrapper; <ide> import org.mozilla.focus.telemetry.TelemetryWrapper; <ide> import org.mozilla.focus.utils.Settings; <ide> import org.mozilla.focus.utils.ViewUtils; <ide> @Override <ide> protected void onCreate(Bundle savedInstanceState) { <ide> super.onCreate(savedInstanceState); <del> <del> SentryWrapper.INSTANCE.init(this); <ide> <ide> if (Settings.getInstance(this).shouldUseSecureMode()) { <ide> getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
Java
apache-2.0
4d8b85fa78677eddba7c765c94e9ffcfdda6de1d
0
candyam5522/eureka,candyam5522/eureka,jsons/eureka,candyam5522/eureka
package edu.emory.cci.aiw.cvrg.eureka.services.config; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.servlet.ServletContextEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.persist.PersistService; import com.google.inject.persist.jpa.JpaPersistModule; import com.google.inject.servlet.GuiceServletContextListener; import edu.emory.cci.aiw.cvrg.eureka.services.thread.JobUpdateTask; /** * Set up the Guice dependency injection engine. Uses two modules: * {@link ServletModule} for web related configuration, and {@link AppModule} * for non-web related configuration. * * @author hrathod * */ public class ConfigListener extends GuiceServletContextListener { /** * A timer scheduler to run the job update task. */ private final ScheduledExecutorService executorService = Executors .newSingleThreadScheduledExecutor(); /** * Make sure we always use the same injector */ private final Injector injector = Guice.createInjector(new ServletModule(), new AppModule(), new JpaPersistModule("services-jpa-unit")); /** * The persistence service for the application. */ private PersistService persistService = null; @Override protected Injector getInjector() { return this.injector; } /** * The class level logger. */ private static final Logger LOGGER = LoggerFactory .getLogger(ConfigListener.class); /* * @see * com.google.inject.servlet.GuiceServletContextListener#contextInitialized * (javax.servlet.ServletContextEvent) */ @Override public void contextInitialized(ServletContextEvent inServletContextEvent) { super.contextInitialized(inServletContextEvent); this.persistService = this.getInjector().getInstance( PersistService.class); this.persistService.start(); // Bootstrap bootstrap = this.getInjector().getInstance(Bootstrap.class); // try { // bootstrap.configure(); // } catch (NoSuchAlgorithmException e1) { // LOGGER.error(e1.getMessage(), e1); // } try { ApplicationProperties applicationProperties = this.getInjector() .getInstance(ApplicationProperties.class); JobUpdateTask jobUpdateTask = new JobUpdateTask( applicationProperties.getEtlJobUpdateUrl()); this.executorService.scheduleWithFixedDelay(jobUpdateTask, 0, 10, TimeUnit.SECONDS); } catch (KeyManagementException e) { LOGGER.error(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { LOGGER.error(e.getMessage(), e); } } /* * @see * com.google.inject.servlet.GuiceServletContextListener#contextDestroyed * (javax.servlet.ServletContextEvent) */ @Override public void contextDestroyed(ServletContextEvent inServletContextEvent) { super.contextDestroyed(inServletContextEvent); this.persistService.stop(); this.executorService.shutdown(); try { this.executorService.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); } } }
eureka-services/src/main/java/edu/emory/cci/aiw/cvrg/eureka/services/config/ConfigListener.java
package edu.emory.cci.aiw.cvrg.eureka.services.config; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.servlet.ServletContextEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.persist.PersistService; import com.google.inject.persist.jpa.JpaPersistModule; import com.google.inject.servlet.GuiceServletContextListener; import edu.emory.cci.aiw.cvrg.eureka.services.thread.JobUpdateTask; /** * Set up the Guice dependency injection engine. Uses two modules: * {@link ServletModule} for web related configuration, and {@link AppModule} * for non-web related configuration. * * @author hrathod * */ public class ConfigListener extends GuiceServletContextListener { /** * A timer scheduler to run the job update task. */ ScheduledExecutorService executorService = Executors .newSingleThreadScheduledExecutor(); /** * Make sure we always use the same injector */ private final Injector injector = Guice.createInjector(new ServletModule(), new AppModule(), new JpaPersistModule("services-jpa-unit")); /** * The persistence service for the application. */ private PersistService persistService = null; @Override protected Injector getInjector() { return this.injector; } /** * The class level logger. */ private static final Logger LOGGER = LoggerFactory .getLogger(ConfigListener.class); /* * @see * com.google.inject.servlet.GuiceServletContextListener#contextInitialized * (javax.servlet.ServletContextEvent) */ @Override public void contextInitialized(ServletContextEvent inServletContextEvent) { super.contextInitialized(inServletContextEvent); this.persistService = this.getInjector().getInstance( PersistService.class); this.persistService.start(); // Bootstrap bootstrap = this.getInjector().getInstance(Bootstrap.class); // try { // bootstrap.configure(); // } catch (NoSuchAlgorithmException e1) { // LOGGER.error(e1.getMessage(), e1); // } try { ApplicationProperties applicationProperties = this.getInjector() .getInstance(ApplicationProperties.class); JobUpdateTask jobUpdateTask = new JobUpdateTask( applicationProperties.getEtlJobUpdateUrl()); this.executorService.scheduleWithFixedDelay(jobUpdateTask, 0, 10, TimeUnit.SECONDS); } catch (KeyManagementException e) { LOGGER.error(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { LOGGER.error(e.getMessage(), e); } } /* * @see * com.google.inject.servlet.GuiceServletContextListener#contextDestroyed * (javax.servlet.ServletContextEvent) */ @Override public void contextDestroyed(ServletContextEvent inServletContextEvent) { super.contextDestroyed(inServletContextEvent); this.persistService.stop(); this.executorService.shutdown(); try { this.executorService.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); } } }
Made the executorService field private and final.
eureka-services/src/main/java/edu/emory/cci/aiw/cvrg/eureka/services/config/ConfigListener.java
Made the executorService field private and final.
<ide><path>ureka-services/src/main/java/edu/emory/cci/aiw/cvrg/eureka/services/config/ConfigListener.java <ide> /** <ide> * A timer scheduler to run the job update task. <ide> */ <del> ScheduledExecutorService executorService = Executors <add> private final ScheduledExecutorService executorService = Executors <ide> .newSingleThreadScheduledExecutor(); <ide> /** <ide> * Make sure we always use the same injector
Java
apache-2.0
e0a505a87431307ea352fc6e6f31c3df28fde9dd
0
asterd/BootsFaces-OSP,mtvweb/BootsFaces-OSP,chongma/BootsFaces-OSP,TheCoder4eu/BootsFaces-OSP,jepsar/BootsFaces-OSP,jepsar/BootsFaces-OSP,chongma/BootsFaces-OSP,TheCoder4eu/BootsFaces-OSP,asterd/BootsFaces-OSP,mtvweb/BootsFaces-OSP
/** * Copyright 2014 Riccardo Massera (TheCoder4.Eu) * * This file is part of BootsFaces. * * BootsFaces 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 3 of the License, or * (at your option) any later version. * * BootsFaces 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 BootsFaces. If not, see <http://www.gnu.org/licenses/>. */ package net.bootsfaces.component; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Set; import javax.faces.application.ResourceDependencies; import javax.faces.application.ResourceDependency; import javax.faces.component.FacesComponent; import javax.faces.component.UIComponent; import javax.faces.component.behavior.ClientBehavior; import javax.faces.component.behavior.ClientBehaviorContext; import javax.faces.component.behavior.ClientBehaviorHolder; import javax.faces.component.html.HtmlInputText; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import net.bootsfaces.C; import net.bootsfaces.render.A; import net.bootsfaces.render.H; import net.bootsfaces.render.R; /** * * @author thecoder4.eu */ @ResourceDependencies({ @ResourceDependency(library="bsf", name="css/core.css", target="head"), @ResourceDependency(library="bsf", name="css/bsf.css", target="head") }) @FacesComponent(C.INPUTTEXT_COMPONENT_TYPE) public class InputText extends HtmlInputText { /** * <p>The standard component type for this component.</p> */ public static final String COMPONENT_TYPE =C.INPUTTEXT_COMPONENT_TYPE; /** * <p>The component family for this component.</p> */ public static final String COMPONENT_FAMILY = C.BSFCOMPONENT; public static final String ADDON="input-group-addon"; public InputText() { setRendererType(null); // this component renders itself } @Override public void decode(FacesContext context) { InputText inputText = (InputText) this; if(inputText.isDisabled() || inputText.isReadonly()) { return; } decodeBehaviors(context, inputText); String clientId = inputText.getClientId(context); String submittedValue = (String) context.getExternalContext().getRequestParameterMap().get(clientId); if(submittedValue != null) { inputText.setSubmittedValue(submittedValue); //this.setValid(true); } } @Override public void encodeBegin(FacesContext context) throws IOException { /* * */ Map<String, Object> attrs = getAttributes(); ResponseWriter rw = context.getResponseWriter(); String clientId = getClientId(context); //Map<String, Object> attrs = getAttributes(); //"Prepend" facet UIComponent prep = getFacet(C.PREPEND); //"Append" facet UIComponent app = getFacet(C.APPEND); boolean prepend = (prep!=null); boolean append = (app!=null); // If the facet contains only one component, getChildCount()=0 and the Facet is the UIComponent if(prepend) { R.addClass2FacetComponent(prep, "OutputText", ADDON); }//(prep.getChildren(), "OutputText", S.ADDON); } if(append) { R.addClass2FacetComponent(app, "OutputText", ADDON); } String l = A.asString(attrs.get(A.LABEL)); // Define TYPE ( if null set default = text ) String t = A.asString(attrs.get(A.TYPE)); if (t == null) t = H.TEXT; rw.startElement(H.DIV, this); rw.writeAttribute(H.CLASS, "form-group", H.CLASS); if(l!=null) { rw.startElement(H.LABEL, this); rw.writeAttribute(A.FOR, clientId, A.FOR); rw.writeText(l, null); rw.endElement(H.LABEL); } if(append||prepend) { rw.startElement(H.DIV, this); rw.writeAttribute(H.CLASS, "input-group", H.CLASS); } int span = A.toInt(attrs.get(A.SPAN)); if(span>0) { rw.startElement(H.DIV, this); rw.writeAttribute(H.CLASS, "col-md-"+span, H.CLASS); } if(prepend) { if(prep.getClass().getName().endsWith("Button")||(prep.getChildCount()>0 && prep.getChildren().get(0).getClass().getName().endsWith("Button")) ){ rw.startElement(H.DIV, this); rw.writeAttribute(H.CLASS, "input-group-btn", H.CLASS); prep.encodeAll(context); rw.endElement(H.DIV); } else { prep.encodeAll(context); } } //Input rw.startElement(H.INPUT, this); rw.writeAttribute(H.ID, clientId, null); rw.writeAttribute(H.NAME, clientId, null); rw.writeAttribute(H.TYPE, t, null); StringBuilder sb; String s; sb = new StringBuilder(20); //optimize int sb.append("form-control"); String fsize=A.asString(attrs.get(A.FIELDSIZE)); if(fsize!=null) {sb.append(" input-").append(fsize); } //styleClass and class support String sclass=A.asString(attrs.get(H.STYLECLASS)); if(sclass!=null) {sb.append(" ").append(sclass); } s=sb.toString().trim(); if(s!=null && s.length()>0) { rw.writeAttribute(H.CLASS, s, H.CLASS); } String ph=A.asString(attrs.get(A.PHOLDER)); if(ph!=null) { rw.writeAttribute(H.PHOLDER, ph, null); } if(A.toBool(attrs.get(A.DISABLED))) { rw.writeAttribute(A.DISABLED, A.DISABLED, null); } if(A.toBool(attrs.get(A.READONLY))) { rw.writeAttribute(A.READONLY, A.READONLY, null); } //Encode attributes (HTML 4 pass-through + DHTML) R.encodeHTML4DHTMLAttrs(rw, attrs, A.INPUT_TEXT_ATTRS); if( (A.asString(attrs.get("autocomplete"))!=null) && (A.asString(attrs.get("autocomplete")).equals("off")) ) { rw.writeAttribute("autocomplete", "off", null); } //Render Value String v=R.getValue2Render(context, this); rw.writeAttribute(H.VALUE, v, null); // Render Ajax Capabilities Map<String,List<ClientBehavior>> clientBehaviors = this.getClientBehaviors(); Set<String> keysClientBehavior = clientBehaviors.keySet(); for (String keyClientBehavior : keysClientBehavior){ List<ClientBehavior> behaviors = clientBehaviors.get(keyClientBehavior); for (ClientBehavior cb : behaviors){ ClientBehaviorContext behaviorContext = ClientBehaviorContext.createClientBehaviorContext(context,this,keyClientBehavior, null, null); rw.writeAttribute("on" + keyClientBehavior, cb.getScript(behaviorContext), null); } } rw.endElement(H.INPUT); if(append) { if(app.getClass().getName().endsWith("Button")||(app.getChildCount()>0 && app.getChildren().get(0).getClass().getName().endsWith("Button"))){ rw.startElement(H.DIV, this); rw.writeAttribute(H.CLASS, "input-group-btn", H.CLASS); app.encodeAll(context); rw.endElement(H.DIV); } else { app.encodeAll(context); } } if(append||prepend) {rw.endElement(H.DIV);} //input-group rw.endElement(H.DIV); //form-group if(span>0) { rw.endElement(H.DIV); //span //rw.endElement(H.DIV); //row NO } } @Override public String getFamily() { return COMPONENT_FAMILY; } protected void decodeBehaviors(FacesContext context, UIComponent component) { if(!(component instanceof ClientBehaviorHolder)) { return; } Map<String, List<ClientBehavior>> behaviors = ((ClientBehaviorHolder) component).getClientBehaviors(); if(behaviors.isEmpty()) { return; } Map<String, String> params = context.getExternalContext().getRequestParameterMap(); String behaviorEvent = params.get("javax.faces.behavior.event"); if(null != behaviorEvent) { List<ClientBehavior> behaviorsForEvent = behaviors.get(behaviorEvent); if(behaviorsForEvent != null && !behaviorsForEvent.isEmpty()) { String behaviorSource = params.get("javax.faces.source"); String clientId = component.getClientId(); if(behaviorSource != null && clientId.equals(behaviorSource)) { for(ClientBehavior behavior: behaviorsForEvent) { behavior.decode(context, component); } } } } } }
src/net/bootsfaces/component/InputText.java
/** * Copyright 2014 Riccardo Massera (TheCoder4.Eu) * * This file is part of BootsFaces. * * BootsFaces 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 3 of the License, or * (at your option) any later version. * * BootsFaces 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 BootsFaces. If not, see <http://www.gnu.org/licenses/>. */ package net.bootsfaces.component; import java.io.IOException; import java.util.Map; import javax.faces.application.ResourceDependencies; import javax.faces.application.ResourceDependency; import javax.faces.component.FacesComponent; import javax.faces.component.UIComponent; import javax.faces.component.html.HtmlInputText; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import net.bootsfaces.render.A; import net.bootsfaces.C; import net.bootsfaces.render.H; import net.bootsfaces.render.R; /** * * @author thecoder4.eu */ @ResourceDependencies({ @ResourceDependency(library="bsf", name="css/core.css", target="head"), @ResourceDependency(library="bsf", name="css/bsf.css", target="head") }) @FacesComponent(C.INPUTTEXT_COMPONENT_TYPE) public class InputText extends HtmlInputText { /** * <p>The standard component type for this component.</p> */ public static final String COMPONENT_TYPE =C.INPUTTEXT_COMPONENT_TYPE; /** * <p>The component family for this component.</p> */ public static final String COMPONENT_FAMILY = C.BSFCOMPONENT; public static final String ADDON="input-group-addon"; public InputText() { setRendererType(null); // this component renders itself } @Override public void decode(FacesContext context) { String subVal = (String) context.getExternalContext().getRequestParameterMap().get(getClientId(context)); if(subVal != null) { this.setSubmittedValue(subVal);this.setValid(true); } } @Override public void encodeBegin(FacesContext context) throws IOException { /* * */ Map<String, Object> attrs = getAttributes(); ResponseWriter rw = context.getResponseWriter(); String clientId = getClientId(context); //Map<String, Object> attrs = getAttributes(); //"Prepend" facet UIComponent prep = getFacet(C.PREPEND); //"Append" facet UIComponent app = getFacet(C.APPEND); boolean prepend = (prep!=null); boolean append = (app!=null); // If the facet contains only one component, getChildCount()=0 and the Facet is the UIComponent if(prepend) { R.addClass2FacetComponent(prep, "OutputText", ADDON); }//(prep.getChildren(), "OutputText", S.ADDON); } if(append) { R.addClass2FacetComponent(app, "OutputText", ADDON); } String l = A.asString(attrs.get(A.LABEL)); // Define TYPE ( if null set default = text ) String t = A.asString(attrs.get(A.TYPE)); if (t == null) t = H.TEXT; rw.startElement(H.DIV, this); rw.writeAttribute(H.CLASS, "form-group", H.CLASS); if(l!=null) { rw.startElement(H.LABEL, this); rw.writeAttribute(A.FOR, clientId, A.FOR); rw.writeText(l, null); rw.endElement(H.LABEL); } if(append||prepend) { rw.startElement(H.DIV, this); rw.writeAttribute(H.CLASS, "input-group", H.CLASS); } int span = A.toInt(attrs.get(A.SPAN)); if(span>0) { rw.startElement(H.DIV, this); rw.writeAttribute(H.CLASS, "col-md-"+span, H.CLASS); } if(prepend) { if(prep.getClass().getName().endsWith("Button")||(prep.getChildCount()>0 && prep.getChildren().get(0).getClass().getName().endsWith("Button")) ){ rw.startElement(H.DIV, this); rw.writeAttribute(H.CLASS, "input-group-btn", H.CLASS); prep.encodeAll(context); rw.endElement(H.DIV); } else { prep.encodeAll(context); } } //Input rw.startElement(H.INPUT, this); rw.writeAttribute(H.ID, clientId, null); rw.writeAttribute(H.NAME, clientId, null); rw.writeAttribute(H.TYPE, t, null); StringBuilder sb; String s; sb = new StringBuilder(20); //optimize int sb.append("form-control"); String fsize=A.asString(attrs.get(A.FIELDSIZE)); if(fsize!=null) {sb.append(" input-").append(fsize); } //styleClass and class support String sclass=A.asString(attrs.get(H.STYLECLASS)); if(sclass!=null) {sb.append(" ").append(sclass); } s=sb.toString().trim(); if(s!=null && s.length()>0) { rw.writeAttribute(H.CLASS, s, H.CLASS); } String ph=A.asString(attrs.get(A.PHOLDER)); if(ph!=null) { rw.writeAttribute(H.PHOLDER, ph, null); } if(A.toBool(attrs.get(A.DISABLED))) { rw.writeAttribute(A.DISABLED, A.DISABLED, null); } if(A.toBool(attrs.get(A.READONLY))) { rw.writeAttribute(A.READONLY, A.READONLY, null); } //Encode attributes (HTML 4 pass-through + DHTML) R.encodeHTML4DHTMLAttrs(rw, attrs, A.INPUT_TEXT_ATTRS); if( (A.asString(attrs.get("autocomplete"))!=null) && (A.asString(attrs.get("autocomplete")).equals("off")) ) { rw.writeAttribute("autocomplete", "off", null); } //Render Value String v=R.getValue2Render(context, this); rw.writeAttribute(H.VALUE, v, null); rw.endElement(H.INPUT); if(append) { if(app.getClass().getName().endsWith("Button")||(app.getChildCount()>0 && app.getChildren().get(0).getClass().getName().endsWith("Button"))){ rw.startElement(H.DIV, this); rw.writeAttribute(H.CLASS, "input-group-btn", H.CLASS); app.encodeAll(context); rw.endElement(H.DIV); } else { app.encodeAll(context); } } if(append||prepend) {rw.endElement(H.DIV);} //input-group rw.endElement(H.DIV); //form-group if(span>0) { rw.endElement(H.DIV); //span //rw.endElement(H.DIV); //row NO } } @Override public String getFamily() { return COMPONENT_FAMILY; } }
Fix Issue #8
src/net/bootsfaces/component/InputText.java
Fix Issue #8
<ide><path>rc/net/bootsfaces/component/InputText.java <ide> package net.bootsfaces.component; <ide> <ide> import java.io.IOException; <add>import java.util.List; <ide> import java.util.Map; <add>import java.util.Set; <add> <ide> import javax.faces.application.ResourceDependencies; <ide> import javax.faces.application.ResourceDependency; <ide> import javax.faces.component.FacesComponent; <ide> import javax.faces.component.UIComponent; <add>import javax.faces.component.behavior.ClientBehavior; <add>import javax.faces.component.behavior.ClientBehaviorContext; <add>import javax.faces.component.behavior.ClientBehaviorHolder; <ide> import javax.faces.component.html.HtmlInputText; <ide> import javax.faces.context.FacesContext; <ide> import javax.faces.context.ResponseWriter; <add> <add>import net.bootsfaces.C; <ide> import net.bootsfaces.render.A; <del>import net.bootsfaces.C; <ide> import net.bootsfaces.render.H; <ide> import net.bootsfaces.render.R; <ide> <ide> <ide> @Override <ide> public void decode(FacesContext context) { <del> String subVal = (String) context.getExternalContext().getRequestParameterMap().get(getClientId(context)); <del> <del> if(subVal != null) { <del> this.setSubmittedValue(subVal);this.setValid(true); <del> } <del> } <del> <add> InputText inputText = (InputText) this; <add> <add> if(inputText.isDisabled() || inputText.isReadonly()) { <add> return; <add> } <add> <add> decodeBehaviors(context, inputText); <add> <add> String clientId = inputText.getClientId(context); <add> String submittedValue = (String) context.getExternalContext().getRequestParameterMap().get(clientId); <add> <add> if(submittedValue != null) { <add> inputText.setSubmittedValue(submittedValue); <add> //this.setValid(true); <add> } <add> } <add> <add> <add> <ide> @Override <ide> public void encodeBegin(FacesContext context) throws IOException { <ide> /* <ide> String clientId = getClientId(context); <ide> <ide> //Map<String, Object> attrs = getAttributes(); <del> <ide> //"Prepend" facet <ide> UIComponent prep = getFacet(C.PREPEND); <ide> //"Append" facet <ide> rw.writeAttribute(H.NAME, clientId, null); <ide> rw.writeAttribute(H.TYPE, t, null); <ide> <add> <ide> StringBuilder sb; String s; <ide> sb = new StringBuilder(20); //optimize int <ide> sb.append("form-control"); <ide> //Render Value <ide> String v=R.getValue2Render(context, this); <ide> rw.writeAttribute(H.VALUE, v, null); <add> <add> // Render Ajax Capabilities <add> Map<String,List<ClientBehavior>> clientBehaviors = this.getClientBehaviors(); <add> Set<String> keysClientBehavior = clientBehaviors.keySet(); <add> for (String keyClientBehavior : keysClientBehavior){ <add> List<ClientBehavior> behaviors = clientBehaviors.get(keyClientBehavior); <add> for (ClientBehavior cb : behaviors){ <add> ClientBehaviorContext behaviorContext = ClientBehaviorContext.createClientBehaviorContext(context,this,keyClientBehavior, null, null); <add> rw.writeAttribute("on" + keyClientBehavior, cb.getScript(behaviorContext), null); <add> } <add> <add> } <add> <ide> rw.endElement(H.INPUT); <ide> if(append) { <ide> if(app.getClass().getName().endsWith("Button")||(app.getChildCount()>0 && app.getChildren().get(0).getClass().getName().endsWith("Button"))){ <ide> return COMPONENT_FAMILY; <ide> } <ide> <add> protected void decodeBehaviors(FacesContext context, UIComponent component) { <add> if(!(component instanceof ClientBehaviorHolder)) { <add> return; <add> } <add> <add> Map<String, List<ClientBehavior>> behaviors = ((ClientBehaviorHolder) component).getClientBehaviors(); <add> if(behaviors.isEmpty()) { <add> return; <add> } <add> <add> Map<String, String> params = context.getExternalContext().getRequestParameterMap(); <add> String behaviorEvent = params.get("javax.faces.behavior.event"); <add> <add> if(null != behaviorEvent) { <add> List<ClientBehavior> behaviorsForEvent = behaviors.get(behaviorEvent); <add> <add> if(behaviorsForEvent != null && !behaviorsForEvent.isEmpty()) { <add> String behaviorSource = params.get("javax.faces.source"); <add> String clientId = component.getClientId(); <add> <add> if(behaviorSource != null && clientId.equals(behaviorSource)) { <add> for(ClientBehavior behavior: behaviorsForEvent) { <add> behavior.decode(context, component); <add> } <add> } <add> } <add> } <add> } <ide> <ide> }
Java
apache-2.0
5faa820737d54464b8fad8f2a8db3c57f66d84ef
0
DagensNyheter/helios,DagensNyheter/helios,skinzer/helios,stewnorriss/helios,molindo/helios,stewnorriss/helios,mbruggmann/helios,skinzer/helios,gtonic/helios,udomsak/helios,dflemstr/helios,spotify/helios,mavenraven/helios,kidaa/helios,mbruggmann/helios,molindo/helios,kidaa/helios,gtonic/helios,mattnworb/helios,mavenraven/helios,mavenraven/helios,udomsak/helios,mattnworb/helios,gtonic/helios,molindo/helios,mbruggmann/helios,skinzer/helios,spotify/helios,dflemstr/helios,stewnorriss/helios,DagensNyheter/helios,kidaa/helios,dflemstr/helios,spotify/helios,mattnworb/helios,udomsak/helios
/* * Copyright (c) 2014 Spotify AB. * * 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 com.spotify.helios.cli.command; import com.google.common.base.Optional; import com.google.common.base.Strings; import com.google.common.collect.FluentIterable; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.util.concurrent.ListenableFuture; import com.spotify.helios.cli.Table; import com.spotify.helios.client.HeliosClient; import com.spotify.helios.common.Json; import com.spotify.helios.common.descriptors.DockerVersion; import com.spotify.helios.common.descriptors.HostInfo; import com.spotify.helios.common.descriptors.HostStatus; import com.spotify.helios.common.descriptors.JobId; import com.spotify.helios.common.descriptors.TaskStatus; import net.sourceforge.argparse4j.inf.Argument; import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Subparser; import java.io.PrintStream; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import static com.google.common.base.Predicates.containsPattern; import static com.google.common.collect.Ordering.natural; import static com.spotify.helios.cli.Output.humanDuration; import static com.spotify.helios.cli.Output.table; import static com.spotify.helios.cli.Utils.allAsMap; import static com.spotify.helios.common.descriptors.HostStatus.Status.UP; import static java.lang.String.format; import static java.lang.System.currentTimeMillis; import static net.sourceforge.argparse4j.impl.Arguments.storeTrue; public class HostListCommand extends ControlCommand { private final Argument quietArg; private final Argument patternArg; public HostListCommand(final Subparser parser) { super(parser); parser.help("list hosts"); patternArg = parser.addArgument("pattern") .nargs("?") .setDefault("") .help("Pattern to filter hosts with"); quietArg = parser.addArgument("-q") .action(storeTrue()) .help("only print host names"); } @Override int run(Namespace options, HeliosClient client, PrintStream out, final boolean json) throws ExecutionException, InterruptedException { final String pattern = options.getString(patternArg.getDest()); final List<String> hosts = FluentIterable .from(client.listHosts().get()) .filter(containsPattern(pattern)) .toList(); if (!Strings.isNullOrEmpty(pattern) && hosts.isEmpty()) { out.printf("host pattern %s matched no hosts%n", pattern); return 1; } final List<String> sortedHosts = natural().sortedCopy(hosts); final boolean quiet = options.getBoolean(quietArg.getDest()); if (quiet) { if (json) { out.println(Json.asPrettyStringUnchecked(sortedHosts)); } else { for (final String host : sortedHosts) { out.println(host); } } } else { final Map<String, ListenableFuture<HostStatus>> statuses = Maps.newTreeMap(); for (final String host : hosts) { statuses.put(host, client.hostStatus(host)); } if (json) { final Map<String, HostStatus> sorted = Maps.newTreeMap(); sorted.putAll(allAsMap(statuses)); out.println(Json.asPrettyStringUnchecked(sorted)); } else { final Table table = table(out); table.row("HOST", "STATUS", "DEPLOYED", "RUNNING", "CPUS", "MEM", "LOAD AVG", "MEM USAGE", "OS", "VERSION", "DOCKER"); for (final Map.Entry<String, ListenableFuture<HostStatus>> e : statuses.entrySet()) { final String host = e.getKey(); final HostStatus s = e.getValue().get(); if (s == null) { continue; } final Set<TaskStatus> runningDeployedJobs = Sets.newHashSet(); for (final JobId jobId : s.getJobs().keySet()) { final TaskStatus taskStatus = s.getStatuses().get(jobId); if (taskStatus == null) { continue; } if (taskStatus.getState() == TaskStatus.State.RUNNING) { runningDeployedJobs.add(taskStatus); } } final HostInfo hi = s.getHostInfo(); final String memUsage; final String cpus; final String mem; final String loadAvg; final String os; final String docker; if (hi != null) { final long free = hi.getMemoryFreeBytes(); final long total = hi.getMemoryTotalBytes(); memUsage = format("%.2f", (float) (total - free) / total); cpus = String.valueOf(hi.getCpus()); mem = hi.getMemoryTotalBytes() / (1024 * 1024 * 1024) + " gb"; loadAvg = format("%.2f", hi.getLoadAvg()); os = hi.getOsName() + " " + hi.getOsVersion(); final DockerVersion dv = hi.getDockerVersion(); docker = format("%s (%s)", dv, dv.getApiVersion()); } else { memUsage = cpus = mem = loadAvg = os = docker = ""; } final String version; if (s.getAgentInfo() != null) { version = Optional.fromNullable(s.getAgentInfo().getVersion()).or(""); } else { version = ""; } String status = s.getStatus() == UP ? "Up" : "Down"; if (s.getAgentInfo() != null) { final long startTime = s.getAgentInfo().getStartTime(); final long upTime = s.getAgentInfo().getUptime(); if (s.getStatus() == UP) { status += " " + humanDuration(currentTimeMillis() - startTime); } else { status += " " + humanDuration(currentTimeMillis() - startTime - upTime); } } table.row(host, status, s.getJobs().size(), runningDeployedJobs.size(), cpus, mem, loadAvg, memUsage, os, version, docker); } table.print(); } } return 0; } }
helios-tools/src/main/java/com/spotify/helios/cli/command/HostListCommand.java
/* * Copyright (c) 2014 Spotify AB. * * 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 com.spotify.helios.cli.command; import com.google.common.base.Optional; import com.google.common.base.Strings; import com.google.common.collect.FluentIterable; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.util.concurrent.ListenableFuture; import com.spotify.helios.cli.Table; import com.spotify.helios.client.HeliosClient; import com.spotify.helios.common.Json; import com.spotify.helios.common.descriptors.HostInfo; import com.spotify.helios.common.descriptors.HostStatus; import com.spotify.helios.common.descriptors.JobId; import com.spotify.helios.common.descriptors.TaskStatus; import net.sourceforge.argparse4j.inf.Argument; import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Subparser; import java.io.PrintStream; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import static com.google.common.base.Predicates.containsPattern; import static com.google.common.collect.Ordering.natural; import static com.spotify.helios.cli.Output.humanDuration; import static com.spotify.helios.cli.Output.table; import static com.spotify.helios.cli.Utils.allAsMap; import static com.spotify.helios.common.descriptors.HostStatus.Status.UP; import static java.lang.String.format; import static java.lang.System.currentTimeMillis; import static net.sourceforge.argparse4j.impl.Arguments.storeTrue; public class HostListCommand extends ControlCommand { private final Argument quietArg; private final Argument patternArg; public HostListCommand(final Subparser parser) { super(parser); parser.help("list hosts"); patternArg = parser.addArgument("pattern") .nargs("?") .setDefault("") .help("Pattern to filter hosts with"); quietArg = parser.addArgument("-q") .action(storeTrue()) .help("only print host names"); } @Override int run(Namespace options, HeliosClient client, PrintStream out, final boolean json) throws ExecutionException, InterruptedException { final String pattern = options.getString(patternArg.getDest()); final List<String> hosts = FluentIterable .from(client.listHosts().get()) .filter(containsPattern(pattern)) .toList(); if (!Strings.isNullOrEmpty(pattern) && hosts.isEmpty()) { out.printf("host pattern %s matched no hosts%n", pattern); return 1; } final List<String> sortedHosts = natural().sortedCopy(hosts); final boolean quiet = options.getBoolean(quietArg.getDest()); if (quiet) { if (json) { out.println(Json.asPrettyStringUnchecked(sortedHosts)); } else { for (final String host : sortedHosts) { out.println(host); } } } else { final Map<String, ListenableFuture<HostStatus>> statuses = Maps.newTreeMap(); for (final String host : hosts) { statuses.put(host, client.hostStatus(host)); } if (json) { final Map<String, HostStatus> sorted = Maps.newTreeMap(); sorted.putAll(allAsMap(statuses)); out.println(Json.asPrettyStringUnchecked(sorted)); } else { final Table table = table(out); table.row("HOST", "STATUS", "DEPLOYED", "RUNNING", "CPUS", "MEM", "LOAD AVG", "MEM USAGE", "OS", "VERSION"); for (final Map.Entry<String, ListenableFuture<HostStatus>> e : statuses.entrySet()) { final String host = e.getKey(); final HostStatus s = e.getValue().get(); if (s == null) { continue; } final Set<TaskStatus> runningDeployedJobs = Sets.newHashSet(); for (final JobId jobId : s.getJobs().keySet()) { final TaskStatus taskStatus = s.getStatuses().get(jobId); if (taskStatus == null) { continue; } if (taskStatus.getState() == TaskStatus.State.RUNNING) { runningDeployedJobs.add(taskStatus); } } final HostInfo hi = s.getHostInfo(); final String memUsage; final String cpus; final String mem; final String loadAvg; final String os; if (hi != null) { final long free = hi.getMemoryFreeBytes(); final long total = hi.getMemoryTotalBytes(); memUsage = format("%.2f", (float) (total - free) / total); cpus = String.valueOf(hi.getCpus()); mem = hi.getMemoryTotalBytes() / (1024 * 1024 * 1024) + " gb"; loadAvg = format("%.2f", hi.getLoadAvg()); os = hi.getOsName() + " " + hi.getOsVersion(); } else { memUsage = cpus = mem = loadAvg = os = ""; } final String version; if (s.getAgentInfo() != null) { version = Optional.fromNullable(s.getAgentInfo().getVersion()).or(""); } else { version = ""; } String status = s.getStatus() == UP ? "Up" : "Down"; if (s.getAgentInfo() != null) { final long startTime = s.getAgentInfo().getStartTime(); final long upTime = s.getAgentInfo().getUptime(); if (s.getStatus() == UP) { status += " " + humanDuration(currentTimeMillis() - startTime); } else { status += " " + humanDuration(currentTimeMillis() - startTime - upTime); } } table.row(host, status, s.getJobs().size(), runningDeployedJobs.size(), cpus, mem, loadAvg, memUsage, os, version); } table.print(); } } return 0; } }
cli: hosts: print docker version
helios-tools/src/main/java/com/spotify/helios/cli/command/HostListCommand.java
cli: hosts: print docker version
<ide><path>elios-tools/src/main/java/com/spotify/helios/cli/command/HostListCommand.java <ide> import com.spotify.helios.cli.Table; <ide> import com.spotify.helios.client.HeliosClient; <ide> import com.spotify.helios.common.Json; <add>import com.spotify.helios.common.descriptors.DockerVersion; <ide> import com.spotify.helios.common.descriptors.HostInfo; <ide> import com.spotify.helios.common.descriptors.HostStatus; <ide> import com.spotify.helios.common.descriptors.JobId; <ide> } else { <ide> final Table table = table(out); <ide> table.row("HOST", "STATUS", "DEPLOYED", "RUNNING", <del> "CPUS", "MEM", "LOAD AVG", "MEM USAGE", "OS", "VERSION"); <add> "CPUS", "MEM", "LOAD AVG", "MEM USAGE", "OS", "VERSION", "DOCKER"); <ide> <ide> for (final Map.Entry<String, ListenableFuture<HostStatus>> e : statuses.entrySet()) { <ide> <ide> final String mem; <ide> final String loadAvg; <ide> final String os; <add> final String docker; <ide> if (hi != null) { <ide> final long free = hi.getMemoryFreeBytes(); <ide> final long total = hi.getMemoryTotalBytes(); <ide> mem = hi.getMemoryTotalBytes() / (1024 * 1024 * 1024) + " gb"; <ide> loadAvg = format("%.2f", hi.getLoadAvg()); <ide> os = hi.getOsName() + " " + hi.getOsVersion(); <add> final DockerVersion dv = hi.getDockerVersion(); <add> docker = format("%s (%s)", dv, dv.getApiVersion()); <ide> } else { <del> memUsage = cpus = mem = loadAvg = os = ""; <add> memUsage = cpus = mem = loadAvg = os = docker = ""; <ide> } <ide> <ide> final String version; <ide> } <ide> <ide> table.row(host, status, s.getJobs().size(), runningDeployedJobs.size(), <del> cpus, mem, loadAvg, memUsage, os, version); <add> cpus, mem, loadAvg, memUsage, os, version, docker); <ide> } <ide> <ide> table.print();
Java
apache-2.0
error: pathspec 'android/AndroidUtilDump/src/couk/doridori/android/lib/io/ConnectivityReceiver.java' did not match any file(s) known to git
8cdd143186b680ee3222eb12fb6f7e2af8417357
1
abdyer/AndroidUtilDump
package couk.doridori.android.lib.io; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; /** * A receiver for checking network status changes. * * User: doriancussen * Date: 31/10/2012 */ public class ConnectivityReceiver extends BroadcastReceiver{ private final ConnectivityListener mConnectivityListener; public ConnectivityReceiver(ConnectivityListener connectivityListener){ mConnectivityListener = connectivityListener; } @Override public void onReceive(Context context, Intent intent) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); final boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); if (isConnected) { mConnectivityListener.onConnectionAvailable(); }else{ mConnectivityListener.onConnectionUnavailable(); } } public void register(Context context){ context.registerReceiver(this, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } public void unregister(Context context){ context.unregisterReceiver(this); } public interface ConnectivityListener { /** * Called when a data connection has been established. Can use to * trigger any waiting behaviour */ public void onConnectionAvailable(); public void onConnectionUnavailable(); } }
android/AndroidUtilDump/src/couk/doridori/android/lib/io/ConnectivityReceiver.java
Connection receiver added
android/AndroidUtilDump/src/couk/doridori/android/lib/io/ConnectivityReceiver.java
Connection receiver added
<ide><path>ndroid/AndroidUtilDump/src/couk/doridori/android/lib/io/ConnectivityReceiver.java <add>package couk.doridori.android.lib.io; <add> <add>import android.content.BroadcastReceiver; <add>import android.content.Context; <add>import android.content.Intent; <add>import android.content.IntentFilter; <add>import android.net.ConnectivityManager; <add>import android.net.NetworkInfo; <add> <add>/** <add> * A receiver for checking network status changes. <add> * <add> * User: doriancussen <add> * Date: 31/10/2012 <add> */ <add>public class ConnectivityReceiver extends BroadcastReceiver{ <add> <add> private final ConnectivityListener mConnectivityListener; <add> <add> public ConnectivityReceiver(ConnectivityListener connectivityListener){ <add> mConnectivityListener = connectivityListener; <add> } <add> <add> @Override <add> public void onReceive(Context context, Intent intent) { <add> ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); <add> NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); <add> final boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); <add> <add> if (isConnected) { <add> mConnectivityListener.onConnectionAvailable(); <add> }else{ <add> mConnectivityListener.onConnectionUnavailable(); <add> } <add> } <add> <add> public void register(Context context){ <add> context.registerReceiver(this, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); <add> } <add> <add> public void unregister(Context context){ <add> context.unregisterReceiver(this); <add> } <add> <add> public interface ConnectivityListener { <add> <add> /** <add> * Called when a data connection has been established. Can use to <add> * trigger any waiting behaviour <add> */ <add> public void onConnectionAvailable(); <add> public void onConnectionUnavailable(); <add> } <add>}
Java
apache-2.0
94d8f543575e2ff42d69e66578c6e7afe4c4448c
0
JunkerStudio/StatLogic,JunkerStudio/StatLogic
/** * Copyright 2014 Peter "Felix" Nguyen * * 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 pfnguyen.statlogic.gui; import java.awt.Color; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.math.BigDecimal; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.border.TitledBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; import pfnguyen.statlogic.options.CalculatorOptions.Hypothesis; import pfnguyen.statlogic.options.CalculatorOptions.Option; import pfnguyen.statlogic.ttest.TLoader; @SuppressWarnings("serial") public class TTestPanel extends JPanel { // Primary components private JLabel h0 = new JLabel("H0: \u03BC = ? "); private JLabel h1 = new JLabel("H1: \u03BC \u2260 ? "); private JRadioButton jrbLowerTail = new JRadioButton("Lower Tail"); private JRadioButton jrbUpperTail = new JRadioButton("Upper Tail"); private JRadioButton jrbTwoTail = new JRadioButton("Two Tail"); private JRadioButton jrbProvideXBar = new JRadioButton( "Provide " + "X\u0305" + ", \u03C3\u0302"); private JRadioButton jrbEnterData = new JRadioButton( "Enter data"); private JRadioButton jrbImportData = new JRadioButton( "Import data"); private JLabel jlblTestValue = new JLabel("Test Value"); private JTextField jtfTestValue = new JTextField(8); private JTextField jtfAlpha = new JTextField(4); private JButton jbtCalc = new JButton("Calculate"); // Button groups private ButtonGroup tailBtnGroup = new ButtonGroup(); private ButtonGroup xBarBtnGroup = new ButtonGroup(); // Rows for layout private FlowPanel row1 = new FlowPanel(); private FlowPanel row2 = new FlowPanel(); private FlowPanel row3 = new FlowPanel(); private FlowPanel row4 = new FlowPanel(); private FlowPanel row5 = new FlowPanel(); // Calculator private TLoader tLoader; // Input for Method 3 private Hypothesis hypothesis = Hypothesis.NOT_EQUAL; private BigDecimal testValue; private BigDecimal stdDev; private double significance; // Input for Method 1 private BigDecimal xBar; private int sampleSize; // Layout Container private JPanel layoutContainer = new JPanel(new GridLayout(5, 1)); // Chooser private String[] calcName = { "Hypothesis Test", "Confidence Interval", "Both Options"}; private JComboBox<String> jcboCalcOptions = new JComboBox<String>(calcName); public TTestPanel(final JTextArea jtaOutput, final JLabel statusBar, final StringBuilder outputString) { tLoader = new TLoader(jtaOutput, statusBar, outputString); // Styling setBorder(new TitledBorder("1-Sample t")); setLayout(new FlowLayout(FlowLayout.LEADING)); // Components add(layoutContainer); layoutContainer.add(row1); layoutContainer.add(row2); layoutContainer.add(row3); layoutContainer.add(row4); layoutContainer.add(row5); row1.add(h0); row1.add(h1); row2.add(jrbLowerTail); row2.add(jrbUpperTail); row2.add(jrbTwoTail); row3.add(jrbProvideXBar); row3.add(jrbEnterData); row3.add(jrbImportData); row4.add(jlblTestValue); row4.add(jtfTestValue); row4.add(new JLabel("alpha \u03b1")); row4.add(jtfAlpha); row5.add(jbtCalc); row5.add(jcboCalcOptions); // Component configuration jrbTwoTail.setSelected(true); jrbEnterData.setSelected(true); jcboCalcOptions.setSelectedIndex(2); // Grouping tailBtnGroup.add(jrbLowerTail); tailBtnGroup.add(jrbUpperTail); tailBtnGroup.add(jrbTwoTail); xBarBtnGroup.add(jrbProvideXBar); xBarBtnGroup.add(jrbEnterData); xBarBtnGroup.add(jrbImportData); // Listeners jrbLowerTail.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setLowerTail(); hypothesis = Hypothesis.LESS_THAN; } }); jrbUpperTail.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setUpperTail(); hypothesis = Hypothesis.GREATER_THAN; } }); jrbTwoTail.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { hypothesis = Hypothesis.NOT_EQUAL; setTwoTail(); } }); // Listen for changes in the text jtfTestValue.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { setTail(); } @Override public void removeUpdate(DocumentEvent e) { setTail(); } @Override public void insertUpdate(DocumentEvent e) { setTail(); } }); jtfAlpha.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { try { double temp = new Double(jtfAlpha.getText()); if (temp <= 0 || temp >= 1) { jtfAlpha.setBackground(Color.RED); } else { jtfAlpha.setBackground(Color.WHITE); } } catch (NumberFormatException ex) { if (jtfAlpha.getText().length() != 0) { jtfAlpha.setBackground(Color.RED); } else { jtfAlpha.setBackground(Color.WHITE); } } } @Override public void removeUpdate(DocumentEvent e) { try { double temp = new Double(jtfAlpha.getText()); if (temp <= 0 || temp >= 1) { jtfAlpha.setBackground(Color.RED); } else { jtfAlpha.setBackground(Color.WHITE); } } catch (NumberFormatException ex) { if (jtfAlpha.getText().length() != 0) { jtfAlpha.setBackground(Color.RED); } else { jtfAlpha.setBackground(Color.WHITE); } } } @Override public void changedUpdate(DocumentEvent e) { } }); jbtCalc.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { if ((new Double(jtfAlpha.getText()) > 0.0) && (new Double(jtfAlpha.getText()) < 1.0)) { if (jrbProvideXBar.isSelected()) { JTextField jtfXBar = new JTextField(); JTextField jtfSampleSize = new JTextField(); JTextField jtfStdDev = new JTextField(); if (xBar != null) { jtfXBar.setText(xBar.toString()); } // Should provide error handling if sampleSize <= 1 jtfSampleSize.setText(Integer.toString(sampleSize)); if (jtfSampleSize.getText().contains("0")) { jtfSampleSize.setText(""); } else { jtfSampleSize.setText(Integer.toString(sampleSize)); } if (stdDev != null) { jtfStdDev.setText(stdDev.toString()); } Object[] message = { "X\u0305: ", jtfXBar, "Sample Size: ", jtfSampleSize, "\u03C3\u0302", jtfStdDev}; int selected = JOptionPane.showConfirmDialog( jbtCalc.getParent(), message, "Sample Mean", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (selected != JOptionPane.CANCEL_OPTION) { significance = new Double(jtfAlpha.getText()); xBar = new BigDecimal(jtfXBar.getText()); sampleSize = new Integer(jtfSampleSize.getText()); stdDev = new BigDecimal(jtfStdDev.getText()); if (jcboCalcOptions.getSelectedIndex() == 0 || jcboCalcOptions.getSelectedIndex() == 2) { testValue = new BigDecimal(jtfTestValue.getText()); tLoader.loadXIntoCalc(hypothesis, testValue, xBar, stdDev, sampleSize, significance, Option.TEST_HYPOTHESIS); } if (jcboCalcOptions.getSelectedIndex() == 1 || jcboCalcOptions.getSelectedIndex() == 2) { testValue = BigDecimal.ONE; tLoader.loadXIntoCalc(hypothesis, testValue, xBar, stdDev, sampleSize, significance, Option.CONFIDENCE_INTERVAl); } } } else if (jrbEnterData.isSelected()) { JTextArea jtaValues = new JTextArea(20, 20); jtaValues.setLineWrap(true); jtaValues.setWrapStyleWord(true); BoxPanel calcXBarPanel = new BoxPanel(); calcXBarPanel.add(new JLabel( "Enter values to calculate Sample Mean")); calcXBarPanel.add(new JScrollPane(jtaValues)); int selected = JOptionPane.showConfirmDialog( null, calcXBarPanel, "1-Sample t", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (selected != JOptionPane.CANCEL_OPTION) { significance = new Double(jtfAlpha.getText()); if (jcboCalcOptions.getSelectedIndex() == 0 || jcboCalcOptions.getSelectedIndex() == 2) { testValue = new BigDecimal(jtfTestValue.getText()); tLoader.stringToBigDecimalArray( jtaValues.getText(),hypothesis, testValue, significance, Option.TEST_HYPOTHESIS); } if (jcboCalcOptions.getSelectedIndex() == 1 || jcboCalcOptions.getSelectedIndex() == 2) { testValue = BigDecimal.ONE; // is there a way around this? tLoader.stringToBigDecimalArray( jtaValues.getText(), hypothesis, testValue, significance, Option.CONFIDENCE_INTERVAl); } } } else if (jrbImportData.isSelected()) { try { testValue = new BigDecimal(jtfTestValue.getText()); significance = new Double(jtfAlpha.getText()); if (jcboCalcOptions.getSelectedIndex() == 0) { tLoader.loadFileIntoArray(hypothesis, testValue, significance, Option.TEST_HYPOTHESIS); } else if (jcboCalcOptions.getSelectedIndex() == 1) { tLoader.loadFileIntoArray(hypothesis, testValue, significance, Option.CONFIDENCE_INTERVAl); } else if (jcboCalcOptions.getSelectedIndex() == 2) { tLoader.loadFileIntoArray(hypothesis, testValue, significance, Option.BOTH); } } catch (IOException ex) { System.out.println("Import Failed"); } } } else { JOptionPane.showMessageDialog(null, "Signifiance level must be between 0 and 1 (exclusive)"); } } catch (NumberFormatException ex){ JOptionPane.showMessageDialog(null, "Something is wrong, invalid values"); } } }); jcboCalcOptions.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (jcboCalcOptions.getSelectedIndex() == 1) { h0.setEnabled(false); h1.setEnabled(false); jrbLowerTail.setEnabled(false); jrbUpperTail.setEnabled(false); jrbTwoTail.setEnabled(false); jlblTestValue.setEnabled(false); jtfTestValue.setEnabled(false); } else { h0.setEnabled(true); h1.setEnabled(true); jrbLowerTail.setEnabled(true); jrbUpperTail.setEnabled(true); jrbTwoTail.setEnabled(true); jlblTestValue.setEnabled(true); jtfTestValue.setEnabled(true); } } }); } private void setTail() { if (jrbLowerTail.isSelected()) setLowerTail(); else if (jrbUpperTail.isSelected()) setUpperTail(); else setTwoTail(); } private void setLowerTail() { if (jtfTestValue.getText().length() == 0) { h0.setText("H0: \u03BC = ? "); h1.setText("H1: \u03BC < ?"); h0.setToolTipText(h0.getText()); h1.setToolTipText(h1.getText()); } else if (jtfTestValue.getText().length() < 10) { h0.setText("H0: \u03BC = " + jtfTestValue.getText() + " "); h1.setText("H1: \u03BC < " + jtfTestValue.getText()); h0.setToolTipText("H0: \u03BC = " + jtfTestValue.getText()); h1.setToolTipText(h1.getText()); } else { try { h0.setText("H0: \u03BC = " + jtfTestValue.getText(0, 9) + "... "); h1.setText("H1: \u03BC < " + jtfTestValue.getText(0, 9) + "..."); h0.setToolTipText("H0: \u03BC = " + jtfTestValue.getText()); h1.setToolTipText("H1: \u03BC < " + jtfTestValue.getText()); } catch (BadLocationException e1) { e1.printStackTrace(); } } } private void setUpperTail() { if (jtfTestValue.getText().length() == 0) { h0.setText("H0: \u03BC = ? "); h1.setText("H1: \u03BC > ?"); h0.setToolTipText(h0.getText()); h1.setToolTipText(h1.getText()); } else if (jtfTestValue.getText().length() < 10) { h0.setText("H0: \u03BC = " + jtfTestValue.getText() + " "); h1.setText("H1: \u03BC > " + jtfTestValue.getText()); h0.setToolTipText("H0: \u03BC = " + jtfTestValue.getText()); h1.setToolTipText(h1.getText()); } else { try { h0.setText("H0: \u03BC = " + jtfTestValue.getText(0, 9) + "... "); h1.setText("H1: \u03BC > " + jtfTestValue.getText(0, 9) + "..."); h0.setToolTipText("H0: \u03BC = " + jtfTestValue.getText()); h1.setToolTipText("H1: \u03BC > " + jtfTestValue.getText()); } catch (BadLocationException e1) { e1.printStackTrace(); } } } private void setTwoTail() { if (jtfTestValue.getText().length() == 0) { h0.setText("H0: \u03BC = ? "); h1.setText("H1: \u03BC \u2260 ?"); h0.setToolTipText(h0.getText()); h1.setToolTipText(h1.getText()); } else if (jtfTestValue.getText().length() < 10) { h0.setText("H0: \u03BC = " + jtfTestValue.getText() + " "); h1.setText("H1: \u03BC \u2260 " + jtfTestValue.getText()); h0.setToolTipText("H0: \u03BC = " + jtfTestValue.getText()); h1.setToolTipText(h1.getText()); } else { try { h0.setText("H0: \u03BC = " + jtfTestValue.getText(0, 9) + "... "); h1.setText("H1: \u03BC \u2260 " + jtfTestValue.getText(0, 9) + "..."); h0.setToolTipText("H0: \u03BC = " + jtfTestValue.getText()); h1.setToolTipText("H1: \u03BC \u2260 " + jtfTestValue.getText()); } catch (BadLocationException e1) { e1.printStackTrace(); } } } }
src/pfnguyen/statlogic/gui/TTestPanel.java
/** * Copyright 2014 Peter "Felix" Nguyen * * 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 pfnguyen.statlogic.gui; import java.awt.Color; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.math.BigDecimal; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.border.TitledBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; import pfnguyen.statlogic.options.CalculatorOptions.Hypothesis; import pfnguyen.statlogic.options.CalculatorOptions.Option; import pfnguyen.statlogic.ttest.TLoader; @SuppressWarnings("serial") public class TTestPanel extends JPanel { // Primary components private JLabel h0 = new JLabel("H0: \u03BC = ? "); private JLabel h1 = new JLabel("H1: \u03BC \u2260 ? "); private JRadioButton jrbLowerTail = new JRadioButton("Lower Tail"); private JRadioButton jrbUpperTail = new JRadioButton("Upper Tail"); private JRadioButton jrbTwoTail = new JRadioButton("Two Tail"); private JRadioButton jrbProvideXBar = new JRadioButton( "Provide " + "X\u0305" + ", \u03C3\u0302"); private JRadioButton jrbEnterData = new JRadioButton( "Enter data"); private JRadioButton jrbImportData = new JRadioButton( "Import data"); private JLabel jlblTestValue = new JLabel("Test Value"); private JTextField jtfTestValue = new JTextField(8); private JTextField jtfAlpha = new JTextField(4); private JButton jbtCalculate = new JButton("Calculate"); // Button groups private ButtonGroup tailBtnGroup = new ButtonGroup(); private ButtonGroup xBarBtnGroup = new ButtonGroup(); // Rows for layout private FlowPanel row1 = new FlowPanel(); private FlowPanel row2 = new FlowPanel(); private FlowPanel row3 = new FlowPanel(); private FlowPanel row4 = new FlowPanel(); private FlowPanel row5 = new FlowPanel(); // Calculator private TLoader tLoader; // Input for Method 3 private Hypothesis hypothesis = Hypothesis.NOT_EQUAL; private BigDecimal testValue; private BigDecimal stdDev; private double significance; // Input for Method 1 private BigDecimal xBar; private int sampleSize; // Layout Container private JPanel layoutContainer = new JPanel(new GridLayout(5, 1)); // Chooser private String[] calcName = { "Hypothesis Test", "Confidence Interval", "Both Options"}; private JComboBox<String> jcboCalcOptions = new JComboBox<String>(calcName); public TTestPanel(final JTextArea jtaOutput, final JLabel statusBar, final StringBuilder outputString) { tLoader = new TLoader(jtaOutput, statusBar, outputString); // Styling setBorder(new TitledBorder("1-Sample t")); setLayout(new FlowLayout(FlowLayout.LEADING)); // Components add(layoutContainer); layoutContainer.add(row1); layoutContainer.add(row2); layoutContainer.add(row3); layoutContainer.add(row4); layoutContainer.add(row5); row1.add(h0); row1.add(h1); row2.add(jrbLowerTail); row2.add(jrbUpperTail); row2.add(jrbTwoTail); row3.add(jrbProvideXBar); row3.add(jrbEnterData); row3.add(jrbImportData); row4.add(jlblTestValue); row4.add(jtfTestValue); row4.add(new JLabel("alpha \u03b1")); row4.add(jtfAlpha); row5.add(jbtCalculate); row5.add(jcboCalcOptions); // Component configuration jrbTwoTail.setSelected(true); jrbEnterData.setSelected(true); jcboCalcOptions.setSelectedIndex(2); // Grouping tailBtnGroup.add(jrbLowerTail); tailBtnGroup.add(jrbUpperTail); tailBtnGroup.add(jrbTwoTail); xBarBtnGroup.add(jrbProvideXBar); xBarBtnGroup.add(jrbEnterData); xBarBtnGroup.add(jrbImportData); // Listeners jrbLowerTail.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setLowerTail(); hypothesis = Hypothesis.LESS_THAN; } }); jrbUpperTail.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setUpperTail(); hypothesis = Hypothesis.GREATER_THAN; } }); jrbTwoTail.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { hypothesis = Hypothesis.NOT_EQUAL; setTwoTail(); } }); // Listen for changes in the text jtfTestValue.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { setTail(); } @Override public void removeUpdate(DocumentEvent e) { setTail(); } @Override public void insertUpdate(DocumentEvent e) { setTail(); } }); jtfAlpha.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { try { double temp = new Double(jtfAlpha.getText()); if (temp <= 0 || temp >= 1) { jtfAlpha.setBackground(Color.RED); } else { jtfAlpha.setBackground(Color.WHITE); } } catch (NumberFormatException ex) { if (jtfAlpha.getText().length() != 0) { jtfAlpha.setBackground(Color.RED); } else { jtfAlpha.setBackground(Color.WHITE); } } } @Override public void removeUpdate(DocumentEvent e) { try { double temp = new Double(jtfAlpha.getText()); if (temp <= 0 || temp >= 1) { jtfAlpha.setBackground(Color.RED); } else { jtfAlpha.setBackground(Color.WHITE); } } catch (NumberFormatException ex) { if (jtfAlpha.getText().length() != 0) { jtfAlpha.setBackground(Color.RED); } else { jtfAlpha.setBackground(Color.WHITE); } } } @Override public void changedUpdate(DocumentEvent e) { } }); jbtCalculate.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { if ((new Double(jtfAlpha.getText()) > 0.0) && (new Double(jtfAlpha.getText()) < 1.0)) { if (jrbProvideXBar.isSelected()) { JTextField jtfXBar = new JTextField(); JTextField jtfSampleSize = new JTextField(); JTextField jtfStdDev = new JTextField(); if (xBar != null) { jtfXBar.setText(xBar.toString()); } // Should provide error handling if sampleSize <= 1 jtfSampleSize.setText(Integer.toString(sampleSize)); if (jtfSampleSize.getText().contains("0")) { jtfSampleSize.setText(""); } else { jtfSampleSize.setText(Integer.toString(sampleSize)); } if (stdDev != null) { jtfStdDev.setText(stdDev.toString()); } Object[] message = { "X\u0305: ", jtfXBar, "Sample Size: ", jtfSampleSize, "\u03C3\u0302", jtfStdDev}; int selected = JOptionPane.showConfirmDialog( jbtCalculate.getParent(), message, "Sample Mean", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (selected != JOptionPane.CANCEL_OPTION) { significance = new Double(jtfAlpha.getText()); xBar = new BigDecimal(jtfXBar.getText()); sampleSize = new Integer(jtfSampleSize.getText()); stdDev = new BigDecimal(jtfStdDev.getText()); if (jcboCalcOptions.getSelectedIndex() == 0 || jcboCalcOptions.getSelectedIndex() == 2) { testValue = new BigDecimal(jtfTestValue.getText()); tLoader.loadXIntoCalc(hypothesis, testValue, xBar, stdDev, sampleSize, significance, Option.TEST_HYPOTHESIS); } if (jcboCalcOptions.getSelectedIndex() == 1 || jcboCalcOptions.getSelectedIndex() == 2) { testValue = BigDecimal.ONE; tLoader.loadXIntoCalc(hypothesis, testValue, xBar, stdDev, sampleSize, significance, Option.CONFIDENCE_INTERVAl); } } } else if (jrbEnterData.isSelected()) { JTextArea jtaValues = new JTextArea(20, 20); jtaValues.setLineWrap(true); jtaValues.setWrapStyleWord(true); BoxPanel calcXBarPanel = new BoxPanel(); calcXBarPanel.add(new JLabel( "Enter values to calculate Sample Mean")); calcXBarPanel.add(new JScrollPane(jtaValues)); int selected = JOptionPane.showConfirmDialog( null, calcXBarPanel, "1-Sample t", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (selected != JOptionPane.CANCEL_OPTION) { significance = new Double(jtfAlpha.getText()); if (jcboCalcOptions.getSelectedIndex() == 0 || jcboCalcOptions.getSelectedIndex() == 2) { testValue = new BigDecimal(jtfTestValue.getText()); tLoader.stringToBigDecimalArray( jtaValues.getText(),hypothesis, testValue, significance, Option.TEST_HYPOTHESIS); } if (jcboCalcOptions.getSelectedIndex() == 1 || jcboCalcOptions.getSelectedIndex() == 2) { testValue = BigDecimal.ONE; tLoader.stringToBigDecimalArray( jtaValues.getText(), hypothesis, testValue, significance, Option.CONFIDENCE_INTERVAl); } } } else if (jrbImportData.isSelected()) { try { testValue = new BigDecimal(jtfTestValue.getText()); significance = new Double(jtfAlpha.getText()); tLoader.loadFileIntoArray(hypothesis, testValue, significance); } catch (IOException e1) { e1.printStackTrace(); } } } else { JOptionPane.showMessageDialog(null, "Signifiance level must be between 0 and 1 (exclusive)"); } } catch (NumberFormatException ex){ JOptionPane.showMessageDialog(null, "Something is wrong, invalid values"); } } }); jcboCalcOptions.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (jcboCalcOptions.getSelectedIndex() == 1) { h0.setEnabled(false); h1.setEnabled(false); jrbLowerTail.setEnabled(false); jrbUpperTail.setEnabled(false); jrbTwoTail.setEnabled(false); jlblTestValue.setEnabled(false); jtfTestValue.setEnabled(false); } else { h0.setEnabled(true); h1.setEnabled(true); jrbLowerTail.setEnabled(true); jrbUpperTail.setEnabled(true); jrbTwoTail.setEnabled(true); jlblTestValue.setEnabled(true); jtfTestValue.setEnabled(true); } } }); } private void setTail() { if (jrbLowerTail.isSelected()) setLowerTail(); else if (jrbUpperTail.isSelected()) setUpperTail(); else setTwoTail(); } private void setLowerTail() { if (jtfTestValue.getText().length() == 0) { h0.setText("H0: \u03BC = ? "); h1.setText("H1: \u03BC < ?"); h0.setToolTipText(h0.getText()); h1.setToolTipText(h1.getText()); } else if (jtfTestValue.getText().length() < 10) { h0.setText("H0: \u03BC = " + jtfTestValue.getText() + " "); h1.setText("H1: \u03BC < " + jtfTestValue.getText()); h0.setToolTipText("H0: \u03BC = " + jtfTestValue.getText()); h1.setToolTipText(h1.getText()); } else { try { h0.setText("H0: \u03BC = " + jtfTestValue.getText(0, 9) + "... "); h1.setText("H1: \u03BC < " + jtfTestValue.getText(0, 9) + "..."); h0.setToolTipText("H0: \u03BC = " + jtfTestValue.getText()); h1.setToolTipText("H1: \u03BC < " + jtfTestValue.getText()); } catch (BadLocationException e1) { e1.printStackTrace(); } } } private void setUpperTail() { if (jtfTestValue.getText().length() == 0) { h0.setText("H0: \u03BC = ? "); h1.setText("H1: \u03BC > ?"); h0.setToolTipText(h0.getText()); h1.setToolTipText(h1.getText()); } else if (jtfTestValue.getText().length() < 10) { h0.setText("H0: \u03BC = " + jtfTestValue.getText() + " "); h1.setText("H1: \u03BC > " + jtfTestValue.getText()); h0.setToolTipText("H0: \u03BC = " + jtfTestValue.getText()); h1.setToolTipText(h1.getText()); } else { try { h0.setText("H0: \u03BC = " + jtfTestValue.getText(0, 9) + "... "); h1.setText("H1: \u03BC > " + jtfTestValue.getText(0, 9) + "..."); h0.setToolTipText("H0: \u03BC = " + jtfTestValue.getText()); h1.setToolTipText("H1: \u03BC > " + jtfTestValue.getText()); } catch (BadLocationException e1) { e1.printStackTrace(); } } } private void setTwoTail() { if (jtfTestValue.getText().length() == 0) { h0.setText("H0: \u03BC = ? "); h1.setText("H1: \u03BC \u2260 ?"); h0.setToolTipText(h0.getText()); h1.setToolTipText(h1.getText()); } else if (jtfTestValue.getText().length() < 10) { h0.setText("H0: \u03BC = " + jtfTestValue.getText() + " "); h1.setText("H1: \u03BC \u2260 " + jtfTestValue.getText()); h0.setToolTipText("H0: \u03BC = " + jtfTestValue.getText()); h1.setToolTipText(h1.getText()); } else { try { h0.setText("H0: \u03BC = " + jtfTestValue.getText(0, 9) + "... "); h1.setText("H1: \u03BC \u2260 " + jtfTestValue.getText(0, 9) + "..."); h0.setToolTipText("H0: \u03BC = " + jtfTestValue.getText()); h1.setToolTipText("H1: \u03BC \u2260 " + jtfTestValue.getText()); } catch (BadLocationException e1) { e1.printStackTrace(); } } } }
Refactored JButton. Added functionality to "Import Data" button.
src/pfnguyen/statlogic/gui/TTestPanel.java
Refactored JButton. Added functionality to "Import Data" button.
<ide><path>rc/pfnguyen/statlogic/gui/TTestPanel.java <ide> private JLabel jlblTestValue = new JLabel("Test Value"); <ide> private JTextField jtfTestValue = new JTextField(8); <ide> private JTextField jtfAlpha = new JTextField(4); <del> private JButton jbtCalculate = new JButton("Calculate"); <add> private JButton jbtCalc = new JButton("Calculate"); <ide> // Button groups <ide> private ButtonGroup tailBtnGroup = new ButtonGroup(); <ide> private ButtonGroup xBarBtnGroup = new ButtonGroup(); <ide> row4.add(jtfTestValue); <ide> row4.add(new JLabel("alpha \u03b1")); <ide> row4.add(jtfAlpha); <del> row5.add(jbtCalculate); <add> row5.add(jbtCalc); <ide> row5.add(jcboCalcOptions); <ide> // Component configuration <ide> jrbTwoTail.setSelected(true); <ide> <ide> }); <ide> <del> jbtCalculate.addActionListener(new ActionListener() { <add> jbtCalc.addActionListener(new ActionListener() { <ide> @Override <ide> public void actionPerformed(ActionEvent e) { <ide> try { <ide> "\u03C3\u0302", jtfStdDev}; <ide> <ide> int selected = JOptionPane.showConfirmDialog( <del> jbtCalculate.getParent(), message, <add> jbtCalc.getParent(), message, <ide> "Sample Mean", JOptionPane.OK_CANCEL_OPTION, <ide> JOptionPane.PLAIN_MESSAGE); <ide> <ide> } <ide> if (jcboCalcOptions.getSelectedIndex() == 1 || <ide> jcboCalcOptions.getSelectedIndex() == 2) { <del> testValue = BigDecimal.ONE; <add> testValue = BigDecimal.ONE; // is there a way around this? <ide> tLoader.stringToBigDecimalArray( <ide> jtaValues.getText(), hypothesis, <ide> testValue, significance, <ide> try { <ide> testValue = new BigDecimal(jtfTestValue.getText()); <ide> significance = new Double(jtfAlpha.getText()); <del> tLoader.loadFileIntoArray(hypothesis, testValue, significance); <del> } catch (IOException e1) { <del> e1.printStackTrace(); <add> if (jcboCalcOptions.getSelectedIndex() == 0) { <add> tLoader.loadFileIntoArray(hypothesis, testValue, <add> significance, Option.TEST_HYPOTHESIS); <add> } <add> else if (jcboCalcOptions.getSelectedIndex() == 1) { <add> tLoader.loadFileIntoArray(hypothesis, testValue, <add> significance, Option.CONFIDENCE_INTERVAl); <add> } <add> else if (jcboCalcOptions.getSelectedIndex() == 2) { <add> tLoader.loadFileIntoArray(hypothesis, testValue, <add> significance, Option.BOTH); <add> } <add> } <add> catch (IOException ex) { <add> System.out.println("Import Failed"); <ide> } <ide> } <ide> }
Java
bsd-3-clause
343abf4861c34711c25963ae763fd4c80b316699
0
joakimeriksson/mspsim,ransford/mspsim,ransford/mspsim,joakimeriksson/mspsim,contiki-os/mspsim,contiki-os/mspsim,nfi/mspsim,mspsim/mspsim,fvdnabee/mspsim,fvdnabee/mspsim,cmorty/mspsim,cmorty/mspsim,nfi/mspsim,mspsim/mspsim
/** * Copyright (c) 2007, Swedish Institute of Computer Science. * 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 the Institute 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 INSTITUTE 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 INSTITUTE 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. * * This file is part of MSPSim. * * $Id: MSP430Constants.java,v 1.3 2007/10/21 21:17:34 nfi Exp $ * * ----------------------------------------------------------------- * * MSP430Constants * * Author : Joakim Eriksson * Created : Sun Oct 21 22:00:00 2007 * Updated : $Date: 2007/10/21 21:17:34 $ * $Revision: 1.3 $ */ package se.sics.mspsim.core; public interface MSP430Constants { public static final String VERSION = "0.85"; public static final int CLK_ACLK = 1; public static final int CLK_SMCLK = 2; // Instructions (full length) public static final int RRC = 0x1000; public static final int SWPB = 0x1080; public static final int RRA = 0x1100; public static final int SXT = 0x1180; public static final int PUSH = 0x1200; public static final int CALL = 0x1280; public static final int RETI = 0x1300; // Conditional Jumps [ public static final int JNE = 0x2000; public static final int JEQ = 0x2400; public static final int JNC = 0x2800; public static final int JC = 0x2C00; // Conditional Jumps & jumps... public static final int JN = 0x3000; public static final int JGE = 0x3400; public static final int JL = 0x3800; public static final int JMP = 0x3C00; // Short ones... public static final int MOV = 0x4; public static final int ADD = 0x5; public static final int ADDC = 0x6; public static final int SUBC = 0x7; public static final int SUB = 0x8; public static final int CMP = 0x9; public static final int DADD = 0xa; public static final int BIT = 0xb; public static final int BIC = 0xc; public static final int BIS = 0xd; public static final int XOR = 0xe; public static final int AND = 0xf; public static final String[] TWO_OPS = { "-","-","-","-","MOV", "ADD", "ADDC", "SUBC", "SUB", "CMP", "DADD", "BIT", "BIC", "BIS", "XOR", "AND" }; public static final String[] REGISTER_NAMES = { "PC", "SP", "SR", "CG1", "CG2" }; public static final int PC = 0; public static final int SP = 1; public static final int SR = 2; public static final int CG1 = 2; public static final int CG2 = 3; public static final int[][] CREG_VALUES = new int[][]{ {0, 0, 4, 8}, {0, 1, 2, 0xffff} }; public static final int CARRY_B = 0; public static final int ZERO_B = 1; public static final int NEGATIVE_B = 2; public static final int OVERFLOW_B = 8; public static final int GIE_B = 3; public static final int CARRY = 1; public static final int ZERO = 2; public static final int NEGATIVE = 4; public static final int OVERFLOW = 1 << OVERFLOW_B; public static final int GIE = 1 << GIE_B; /* For the LPM management */ public static final int CPUOFF = 0x0010; public static final int OSCOFF = 0x0020; public static final int SCG0 = 0x0040; public static final int SCG1 = 0x0080; // #define C 0x0001 // #define Z 0x0002 // #define N 0x0004 // #define V 0x0100 // #define GIE 0x0008 // #define CPUOFF 0x0010 // #define OSCOFF 0x0020 // #define SCG0 0x0040 // #define SCG1 0x0080 public static final int AM_REG = 0; public static final int AM_INDEX = 1; public static final int AM_IND_REG = 2; public static final int AM_IND_AUTOINC = 3; public static final int CLKCAPTURE_NONE = 0; public static final int CLKCAPTURE_UP = 1; public static final int CLKCAPTURE_DWN = 2; public static final int CLKCAPTURE_BOTH = 3; public static final int DEBUGGING_LEVEL = 0; }
se/sics/mspsim/core/MSP430Constants.java
/** * Copyright (c) 2007, Swedish Institute of Computer Science. * 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 the Institute 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 INSTITUTE 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 INSTITUTE 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. * * This file is part of MSPSim. * * $Id: MSP430Constants.java,v 1.3 2007/10/21 21:17:34 nfi Exp $ * * ----------------------------------------------------------------- * * MSP430Constants * * Author : Joakim Eriksson * Created : Sun Oct 21 22:00:00 2007 * Updated : $Date: 2007/10/21 21:17:34 $ * $Revision: 1.3 $ */ package se.sics.mspsim.core; public interface MSP430Constants { public static final String VERSION = "0.85 jag ha"; public static final int CLK_ACLK = 1; public static final int CLK_SMCLK = 2; // Instructions (full length) public static final int RRC = 0x1000; public static final int SWPB = 0x1080; public static final int RRA = 0x1100; public static final int SXT = 0x1180; public static final int PUSH = 0x1200; public static final int CALL = 0x1280; public static final int RETI = 0x1300; // Conditional Jumps [ public static final int JNE = 0x2000; public static final int JEQ = 0x2400; public static final int JNC = 0x2800; public static final int JC = 0x2C00; // Conditional Jumps & jumps... public static final int JN = 0x3000; public static final int JGE = 0x3400; public static final int JL = 0x3800; public static final int JMP = 0x3C00; // Short ones... public static final int MOV = 0x4; public static final int ADD = 0x5; public static final int ADDC = 0x6; public static final int SUBC = 0x7; public static final int SUB = 0x8; public static final int CMP = 0x9; public static final int DADD = 0xa; public static final int BIT = 0xb; public static final int BIC = 0xc; public static final int BIS = 0xd; public static final int XOR = 0xe; public static final int AND = 0xf; public static final String[] TWO_OPS = { "-","-","-","-","MOV", "ADD", "ADDC", "SUBC", "SUB", "CMP", "DADD", "BIT", "BIC", "BIS", "XOR", "AND" }; public static final int PC = 0; public static final int SP = 1; public static final int SR = 2; public static final int CG1 = 2; public static final int CG2 = 3; public static final int[][] CREG_VALUES = new int[][]{ {0, 0, 4, 8}, {0, 1, 2, 0xffff} }; public static final int CARRY_B = 0; public static final int ZERO_B = 1; public static final int NEGATIVE_B = 2; public static final int OVERFLOW_B = 8; public static final int GIE_B = 3; public static final int CARRY = 1; public static final int ZERO = 2; public static final int NEGATIVE = 4; public static final int OVERFLOW = 1 << OVERFLOW_B; public static final int GIE = 1 << GIE_B; /* For the LPM management */ public static final int CPUOFF = 0x0010; public static final int OSCOFF = 0x0020; public static final int SCG0 = 0x0040; public static final int SCG1 = 0x0080; // #define C 0x0001 // #define Z 0x0002 // #define N 0x0004 // #define V 0x0100 // #define GIE 0x0008 // #define CPUOFF 0x0010 // #define OSCOFF 0x0020 // #define SCG0 0x0040 // #define SCG1 0x0080 public static final int AM_REG = 0; public static final int AM_INDEX = 1; public static final int AM_IND_REG = 2; public static final int AM_IND_AUTOINC = 3; public static final int CLKCAPTURE_NONE = 0; public static final int CLKCAPTURE_UP = 1; public static final int CLKCAPTURE_DWN = 2; public static final int CLKCAPTURE_BOTH = 3; public static final int DEBUGGING_LEVEL = 0; }
added REGISTER_NAMES git-svn-id: b6c13a3f01c183418960c1e4d1e6a42a97ce9376@172 23d1a52b-0c3c-0410-b72d-8f29ab48fe35
se/sics/mspsim/core/MSP430Constants.java
added REGISTER_NAMES
<ide><path>e/sics/mspsim/core/MSP430Constants.java <ide> <ide> public interface MSP430Constants { <ide> <del> public static final String VERSION = "0.85 jag ha"; <add> public static final String VERSION = "0.85"; <ide> <ide> public static final int CLK_ACLK = 1; <ide> public static final int CLK_SMCLK = 2; <ide> public static final String[] TWO_OPS = { <ide> "-","-","-","-","MOV", "ADD", "ADDC", "SUBC", "SUB", <ide> "CMP", "DADD", "BIT", "BIC", "BIS", "XOR", "AND" <add> }; <add> <add> public static final String[] REGISTER_NAMES = { <add> "PC", "SP", "SR", "CG1", "CG2" <ide> }; <ide> <ide> public static final int PC = 0;
Java
apache-2.0
67e2008c0ee6878e6a95a361e41d02734fba4ad1
0
apache/beam,apache/beam,apache/beam,apache/beam,apache/beam,apache/beam,apache/beam,apache/beam,apache/beam,apache/beam,apache/beam
/* * 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.beam.sdk.io.common; import static org.junit.Assert.assertEquals; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import javax.sql.DataSource; import org.apache.beam.sdk.util.BackOff; import org.apache.beam.sdk.util.BackOffUtils; import org.apache.beam.sdk.util.FluentBackoff; import org.apache.beam.sdk.util.Sleeper; import org.apache.beam.sdk.values.KV; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Lists; import org.joda.time.Duration; import org.postgresql.ds.PGSimpleDataSource; import org.testcontainers.containers.JdbcDatabaseContainer; /** This class contains helper methods to ease database usage in tests. */ public class DatabaseTestHelper { private static Map<String, DataSource> hikariSources = new HashMap<>(); public static ResultSet performQuery(JdbcDatabaseContainer<?> container, String sql) throws SQLException { DataSource ds = getDataSourceForContainer(container); Statement statement = ds.getConnection().createStatement(); statement.execute(sql); ResultSet resultSet = statement.getResultSet(); resultSet.next(); return resultSet; } public static DataSource getDataSourceForContainer(JdbcDatabaseContainer<?> container) { if (hikariSources.get(container.getJdbcUrl()) != null) { return hikariSources.get(container.getJdbcUrl()); } HikariConfig hikariConfig = new HikariConfig(); // Keeping a small connection pool to a testContainer to avoid overwhelming it. hikariConfig.setMaximumPoolSize(2); hikariConfig.setJdbcUrl(container.getJdbcUrl()); hikariConfig.setUsername(container.getUsername()); hikariConfig.setPassword(container.getPassword()); hikariConfig.setDriverClassName(container.getDriverClassName()); return hikariSources.put(container.getJdbcUrl(), new HikariDataSource(hikariConfig)); } public static PGSimpleDataSource getPostgresDataSource(PostgresIOTestPipelineOptions options) { PGSimpleDataSource dataSource = new PGSimpleDataSource(); dataSource.setDatabaseName(options.getPostgresDatabaseName()); dataSource.setServerName(options.getPostgresServerName()); dataSource.setPortNumber(options.getPostgresPort()); dataSource.setUser(options.getPostgresUsername()); dataSource.setPassword(options.getPostgresPassword()); dataSource.setSsl(options.getPostgresSsl()); return dataSource; } public static void createTable( DataSource dataSource, String tableName, List<KV<String, String>> fieldsAndTypes) throws SQLException { String fieldsList = fieldsAndTypes.stream() .map(kv -> kv.getKey() + " " + kv.getValue()) .collect(Collectors.joining(", ")); SQLException exception = null; Sleeper sleeper = Sleeper.DEFAULT; BackOff backoff = FluentBackoff.DEFAULT .withInitialBackoff(Duration.standardSeconds(1)) .withMaxCumulativeBackoff(Duration.standardMinutes(5)) .withMaxRetries(4) .backoff(); while (true) { // This is not implemented as try-with-resources because it appears that try-with-resources is // not correctly catching the PSQLException thrown by dataSource.getConnection() Connection connection = null; try { connection = dataSource.getConnection(); try (Statement statement = connection.createStatement()) { statement.execute(String.format("create table %s (%s)", tableName, fieldsList)); return; } } catch (SQLException e) { exception = e; } finally { if (connection != null) { connection.close(); } } boolean hasNext; try { hasNext = BackOffUtils.next(sleeper, backoff); } catch (Exception e) { throw new RuntimeException(e); } if (!hasNext) { // we tried the max number of times throw exception; } } } public static void createTable(DataSource dataSource, String tableName) throws SQLException { createTable( dataSource, tableName, Lists.newArrayList(KV.of("id", "INT"), KV.of("name", "VARCHAR(500)"))); } public static void deleteTable(DataSource dataSource, String tableName) throws SQLException { if (tableName != null) { try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { statement.executeUpdate(String.format("drop table %s", tableName)); } } } public static String getTestTableName(String testIdentifier) { SimpleDateFormat formatter = new SimpleDateFormat(); formatter.applyPattern("yyyy_MM_dd_HH_mm_ss_S"); return String.format("BEAMTEST_%s_%s", testIdentifier, formatter.format(new Date())); } public static String getPostgresDBUrl(PostgresIOTestPipelineOptions options) { return String.format( "jdbc:postgresql://%s:%s/%s", options.getPostgresServerName(), options.getPostgresPort(), options.getPostgresDatabaseName()); } public static Optional<Long> getPostgresTableSize(DataSource dataSource, String tableName) { try (Connection connection = dataSource.getConnection()) { try (Statement statement = connection.createStatement()) { ResultSet resultSet = statement.executeQuery(String.format("select pg_relation_size('%s')", tableName)); if (resultSet.next()) { return Optional.of(resultSet.getLong(1)); } } } catch (SQLException e) { return Optional.empty(); } return Optional.empty(); } public static void createTableWithStatement(DataSource dataSource, String stmt) throws SQLException { try (Connection connection = dataSource.getConnection()) { try (Statement statement = connection.createStatement()) { statement.execute(stmt); } } } public static ArrayList<KV<Integer, String>> getTestDataToWrite(long rowsToAdd) { ArrayList<KV<Integer, String>> data = new ArrayList<>(); for (int i = 0; i < rowsToAdd; i++) { KV<Integer, String> kv = KV.of(i, TestRow.getNameForSeed(i)); data.add(kv); } return data; } public static void assertRowCount(DataSource dataSource, String tableName, int expectedRowCount) throws SQLException { try (Connection connection = dataSource.getConnection()) { try (Statement statement = connection.createStatement()) { try (ResultSet resultSet = statement.executeQuery("select count(*) from " + tableName)) { resultSet.next(); int count = resultSet.getInt(1); assertEquals(expectedRowCount, count); } } } } }
sdks/java/io/common/src/test/java/org/apache/beam/sdk/io/common/DatabaseTestHelper.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.beam.sdk.io.common; import static org.junit.Assert.assertEquals; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import javax.sql.DataSource; import org.apache.beam.sdk.values.KV; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Lists; import org.postgresql.ds.PGSimpleDataSource; import org.testcontainers.containers.JdbcDatabaseContainer; /** This class contains helper methods to ease database usage in tests. */ public class DatabaseTestHelper { private static Map<String, DataSource> hikariSources = new HashMap<>(); public static ResultSet performQuery(JdbcDatabaseContainer<?> container, String sql) throws SQLException { DataSource ds = getDataSourceForContainer(container); Statement statement = ds.getConnection().createStatement(); statement.execute(sql); ResultSet resultSet = statement.getResultSet(); resultSet.next(); return resultSet; } public static DataSource getDataSourceForContainer(JdbcDatabaseContainer<?> container) { if (hikariSources.get(container.getJdbcUrl()) != null) { return hikariSources.get(container.getJdbcUrl()); } HikariConfig hikariConfig = new HikariConfig(); // Keeping a small connection pool to a testContainer to avoid overwhelming it. hikariConfig.setMaximumPoolSize(2); hikariConfig.setJdbcUrl(container.getJdbcUrl()); hikariConfig.setUsername(container.getUsername()); hikariConfig.setPassword(container.getPassword()); hikariConfig.setDriverClassName(container.getDriverClassName()); return hikariSources.put(container.getJdbcUrl(), new HikariDataSource(hikariConfig)); } public static PGSimpleDataSource getPostgresDataSource(PostgresIOTestPipelineOptions options) { PGSimpleDataSource dataSource = new PGSimpleDataSource(); dataSource.setDatabaseName(options.getPostgresDatabaseName()); dataSource.setServerName(options.getPostgresServerName()); dataSource.setPortNumber(options.getPostgresPort()); dataSource.setUser(options.getPostgresUsername()); dataSource.setPassword(options.getPostgresPassword()); dataSource.setSsl(options.getPostgresSsl()); return dataSource; } public static void createTable( DataSource dataSource, String tableName, List<KV<String, String>> fieldsAndTypes) throws SQLException { String fieldsList = fieldsAndTypes.stream() .map(kv -> kv.getKey() + " " + kv.getValue()) .collect(Collectors.joining(", ")); try (Connection connection = dataSource.getConnection()) { try (Statement statement = connection.createStatement()) { statement.execute(String.format("create table %s (%s)", tableName, fieldsList)); } } } public static void createTable(DataSource dataSource, String tableName) throws SQLException { createTable( dataSource, tableName, Lists.newArrayList(KV.of("id", "INT"), KV.of("name", "VARCHAR(500)"))); } public static void deleteTable(DataSource dataSource, String tableName) throws SQLException { if (tableName != null) { try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { statement.executeUpdate(String.format("drop table %s", tableName)); } } } public static String getTestTableName(String testIdentifier) { SimpleDateFormat formatter = new SimpleDateFormat(); formatter.applyPattern("yyyy_MM_dd_HH_mm_ss_S"); return String.format("BEAMTEST_%s_%s", testIdentifier, formatter.format(new Date())); } public static String getPostgresDBUrl(PostgresIOTestPipelineOptions options) { return String.format( "jdbc:postgresql://%s:%s/%s", options.getPostgresServerName(), options.getPostgresPort(), options.getPostgresDatabaseName()); } public static Optional<Long> getPostgresTableSize(DataSource dataSource, String tableName) { try (Connection connection = dataSource.getConnection()) { try (Statement statement = connection.createStatement()) { ResultSet resultSet = statement.executeQuery(String.format("select pg_relation_size('%s')", tableName)); if (resultSet.next()) { return Optional.of(resultSet.getLong(1)); } } } catch (SQLException e) { return Optional.empty(); } return Optional.empty(); } public static void createTableWithStatement(DataSource dataSource, String stmt) throws SQLException { try (Connection connection = dataSource.getConnection()) { try (Statement statement = connection.createStatement()) { statement.execute(stmt); } } } public static ArrayList<KV<Integer, String>> getTestDataToWrite(long rowsToAdd) { ArrayList<KV<Integer, String>> data = new ArrayList<>(); for (int i = 0; i < rowsToAdd; i++) { KV<Integer, String> kv = KV.of(i, TestRow.getNameForSeed(i)); data.add(kv); } return data; } public static void assertRowCount(DataSource dataSource, String tableName, int expectedRowCount) throws SQLException { try (Connection connection = dataSource.getConnection()) { try (Statement statement = connection.createStatement()) { try (ResultSet resultSet = statement.executeQuery("select count(*) from " + tableName)) { resultSet.next(); int count = resultSet.getInt(1); assertEquals(expectedRowCount, count); } } } } }
Add retry to test connections (#23757) * Move connection setup logic for JDBCIO WriteFn to @startBundle to limit parallel calls to datasource.getConnection() * move connection setup logic back to processElement. Put a retry into the DatabaseTestHelper * run spotless * use fluent backoff instead of manual implementation * refactor to manual resource management * run spotless
sdks/java/io/common/src/test/java/org/apache/beam/sdk/io/common/DatabaseTestHelper.java
Add retry to test connections (#23757)
<ide><path>dks/java/io/common/src/test/java/org/apache/beam/sdk/io/common/DatabaseTestHelper.java <ide> import java.util.Optional; <ide> import java.util.stream.Collectors; <ide> import javax.sql.DataSource; <add>import org.apache.beam.sdk.util.BackOff; <add>import org.apache.beam.sdk.util.BackOffUtils; <add>import org.apache.beam.sdk.util.FluentBackoff; <add>import org.apache.beam.sdk.util.Sleeper; <ide> import org.apache.beam.sdk.values.KV; <ide> import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Lists; <add>import org.joda.time.Duration; <ide> import org.postgresql.ds.PGSimpleDataSource; <ide> import org.testcontainers.containers.JdbcDatabaseContainer; <ide> <ide> fieldsAndTypes.stream() <ide> .map(kv -> kv.getKey() + " " + kv.getValue()) <ide> .collect(Collectors.joining(", ")); <del> try (Connection connection = dataSource.getConnection()) { <del> try (Statement statement = connection.createStatement()) { <del> statement.execute(String.format("create table %s (%s)", tableName, fieldsList)); <add> SQLException exception = null; <add> Sleeper sleeper = Sleeper.DEFAULT; <add> BackOff backoff = <add> FluentBackoff.DEFAULT <add> .withInitialBackoff(Duration.standardSeconds(1)) <add> .withMaxCumulativeBackoff(Duration.standardMinutes(5)) <add> .withMaxRetries(4) <add> .backoff(); <add> while (true) { <add> // This is not implemented as try-with-resources because it appears that try-with-resources is <add> // not correctly catching the PSQLException thrown by dataSource.getConnection() <add> Connection connection = null; <add> try { <add> connection = dataSource.getConnection(); <add> try (Statement statement = connection.createStatement()) { <add> statement.execute(String.format("create table %s (%s)", tableName, fieldsList)); <add> return; <add> } <add> } catch (SQLException e) { <add> exception = e; <add> } finally { <add> if (connection != null) { <add> connection.close(); <add> } <add> } <add> boolean hasNext; <add> try { <add> hasNext = BackOffUtils.next(sleeper, backoff); <add> } catch (Exception e) { <add> throw new RuntimeException(e); <add> } <add> if (!hasNext) { <add> // we tried the max number of times <add> throw exception; <ide> } <ide> } <ide> }
JavaScript
apache-2.0
3613fbb09a29ee6e81a9d0eac306b5b625dea2de
0
jiayinjx/angularjs-portal,UW-Madison-DoIT/angularjs-portal,nblair/angularjs-portal,apetro/angularjs-portal,apetro/angularjs-portal,UW-Madison-DoIT/angularjs-portal,nblair/angularjs-portal,jiayinjx/angularjs-portal,nblair/angularjs-portal,UW-Madison-DoIT/angularjs-portal,paulerickson/angularjs-portal,jiayinjx/angularjs-portal,UW-Madison-DoIT/angularjs-portal,paulerickson/angularjs-portal,davidmsibley/angularjs-portal,apetro/angularjs-portal,jiayinjx/angularjs-portal,paulerickson/angularjs-portal,timlevett/angularjs-portal,nblair/angularjs-portal,davidmsibley/angularjs-portal,davidmsibley/angularjs-portal,timlevett/angularjs-portal,davidmsibley/angularjs-portal,paulerickson/angularjs-portal
'use strict'; (function() { var app = angular.module('portal.main.controllers', []); app.controller('MainController', [ '$http', 'miscService', function($http, miscService) { miscService.pushPageview(); var store = this; store.data = []; $http.get('/portal/api/layoutDoc?tab=UW Bucky Home').then( function(result) { store.data = result.data; } , function(reason){ miscService.redirectUser(reason.status, 'layoutDoc call'); } ); this.directToPortlet = function directToPortlet(url) { $location.path(url); } this.removePortlet = function removePortletFunction(nodeId) { $.ajax({ url: "/portal/api/layout?action=removeElement&elementID=" + nodeId, type: "POST", data: null, dataType: "json", async: true, success: function (request, text){ $('#portlet-id-'+ nodeId).parent().fadeOut(); $('#portlet-id-'+ nodeId).parent().remove(); }, error: function(request, text, error) { } }); }; } ]); /* Username */ app.controller('SessionCheckController', [ 'mainService', function(mainService) { var that = this; that.user = []; mainService.getUser().then(function(result){ that.user = result.data.person; }); }]); /* Search */ app.controller('SearchController', [ '$scope', '$location', 'marketplaceService', function($scope, $location, marketplaceService) { $scope.submit = function(){ if($scope.initialFilter != "") { marketplaceService.initialFilter($scope.initialFilter); $location.path("/marketplace/search/"+ $scope.initialFilter); $scope.initialFilter = ""; } }; } ]); app.controller('HeaderController', [ '$scope', function($scope) { $scope.showSearch = false; }]); })();
js/main/main-controllers.js
'use strict'; (function() { var app = angular.module('portal.main.controllers', []); app.controller('MainController', [ '$http', 'miscService', function($http, miscService) { miscService.pushPageview(); var store = this; store.data = []; $http.get('/portal/api/layoutDoc?tab=UW Bucky Home').then( function(result) { store.data = result.data; } , function(reason){ miscService.redirectUser(reason.status, 'layoutDoc call'); } ); this.directToPortlet = function directToPortlet(url) { $location.path(url); } this.removePortlet = function removePortletFunction(nodeId) { $.ajax({ url: "/portal/api/layout?action=removeElement&elementID=" + nodeId, type: "POST", data: null, dataType: "json", async: true, success: function (request, text){ $('#portlet-id-'+ nodeId).parent().fadeOut(); $('#portlet-id-'+ nodeId).parent().remove(); }, error: function(request, text, error) { } }); }; } ]); /* Username */ app.controller('SessionCheckController', [ 'mainService', function(mainService) { var that = this; that.user = []; mainService.getUser().then(function(result){ that.user = result.data.person; }); }]); /* Search */ app.controller('SearchController', [ '$scope', '$location', 'marketplaceService', function($scope, $location, marketplaceService) { $scope.submit = function(){ if($scope.initialFilter != "") { marketplaceService.initialFilter($scope.initialFilter); $location.path("/marketplace/search/"+ $scope.initialFilter); $scope.initialFilter = ""; } }; } ]); app.controller('HeaderController', [ '$scope', function($scope) { $scope.showSearch = false; }]) })();
minor merge fix
js/main/main-controllers.js
minor merge fix
<ide><path>s/main/main-controllers.js <ide> <ide> app.controller('HeaderController', [ '$scope', function($scope) { <ide> $scope.showSearch = false; <del> }]) <add> }]); <ide> <ide> <ide>
Java
mit
d58a2b88c09f7e84dac8ed90eae1867d0118865f
0
Valakor/CS201-Coursework,brandonsbarber/CS201-Course-Work
package cs201.gui.transit; import java.awt.Color; import java.awt.Graphics2D; import cs201.agents.transit.VehicleAgent; import cs201.agents.transit.BusAgent; import cs201.gui.CityPanel; public class BusGui extends VehicleGui { public BusGui(VehicleAgent vehicle,CityPanel city, int x, int y) { super(vehicle,city,x,y); } @Override public void draw(Graphics2D g) { g.setColor(Color.YELLOW); g.fillRect(getX(),getY(),CityPanel.GRID_SIZE,CityPanel.GRID_SIZE); g.setColor(Color.BLACK); g.drawString(""+getVehicle().getClass(),getX(),getY()); g.drawString(""+((BusAgent)getVehicle()).getNumPassengers(),getX(),getY()+CityPanel.GRID_SIZE); } }
src/cs201/gui/transit/BusGui.java
package cs201.gui.transit; import java.awt.Color; import java.awt.Graphics2D; import cs201.agents.transit.VehicleAgent; import cs201.agents.transit.BusAgent; import cs201.gui.CityPanel; public class BusGui extends VehicleGui { public BusGui(VehicleAgent vehicle,CityPanel city, int x, int y) { super(vehicle,city,x,y); } @Override public void draw(Graphics2D g) { g.setColor(Color.YELLOW); g.fillRect(getX(),getY(),CityPanel.GRID_SIZE,CityPanel.GRID_SIZE); g.setColor(Color.BLACK); g.drawString(""+getVehicle().getClass(),getX(),getY()); g.drawString(""+((BusAgent)getVehicle()).getNumPassengers(),getX()+CityPanel.GRID_SIZE,getY()+CityPanel.GRID_SIZE); } }
Fixed BusGui so that passenger count displays within box
src/cs201/gui/transit/BusGui.java
Fixed BusGui so that passenger count displays within box
<ide><path>rc/cs201/gui/transit/BusGui.java <ide> g.setColor(Color.BLACK); <ide> g.drawString(""+getVehicle().getClass(),getX(),getY()); <ide> <del> g.drawString(""+((BusAgent)getVehicle()).getNumPassengers(),getX()+CityPanel.GRID_SIZE,getY()+CityPanel.GRID_SIZE); <add> g.drawString(""+((BusAgent)getVehicle()).getNumPassengers(),getX(),getY()+CityPanel.GRID_SIZE); <ide> } <ide> }
JavaScript
apache-2.0
567963ba24d5ee230eb760cfff8a14cd00f90182
0
stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib
'use strict'; // MODULES // var isNonNegativeInteger = require( '@stdlib/math/base/utils/is-nonnegative-integer' ); var betainc = require( '@stdlib/math/base/special/betainc' ); var isnan = require( '@stdlib/math/base/utils/is-nan' ); var floor = require( '@stdlib/math/base/special/floor' ); var PINF = require( '@stdlib/math/constants/float64-pinf' ); // MAIN // /** * Evaluates the cumulative distribution function (CDF) for a binomial distribution with number of trials `n` and success probability `p` at a value `x`. * * @param {number} x - input value * @param {NonNegativeInteger} n - number of trials * @param {Probability} p - success probability * @returns {Probability} evaluated CDF * * @example * var y = cdf( 3.0, 20, 0.2 ); * // returns ~0.411 * @example * var y = cdf( 21.0, 20, 0.2 ); * // returns 1.0 * @example * var y = cdf( 5.0, 10, 0.4 ) * // returns ~0.834 * @example * var y = cdf( 0.0, 10, 0.4 ) * // returns ~0.06 * @example * var y = cdf( NaN, 20, 0.5 ); * // returns NaN * @example * var y = cdf( 0.0, NaN, 0.5 ); * // returns NaN * @example * var y = cdf( 0.0, 20, NaN ); * // returns NaN * @example * var y = cdf( 2.0, 1.5, 0.5 ); * // returns NaN * @example * var y = cdf( 2.0, -2.0, 0.5 ); * // returns NaN * @example * var y = cdf( 2.0, 20, -1.0 ); * // returns NaN * @example * var y = cdf( 2.0, 20, 1.5 ); * // returns NaN */ function cdf( x, n, p ) { if ( isnan( x ) || isnan( n ) || isnan( p ) || p < 0.0 || p > 1.0 || !isNonNegativeInteger( n ) || n === PINF ) { return NaN; } if ( x < 0.0 ) { return 0.0; } if ( x >= n ) { return 1.0; } x = floor( x + 1.0e-7 ); return betainc( p, x + 1.0, n - x, true, true ); } // end FUNCTION cdf() // EXPORTS // module.exports = cdf;
lib/node_modules/@stdlib/math/base/dist/binomial/cdf/lib/cdf.js
'use strict'; // MODULES // var isNonNegativeInteger = require( '@stdlib/math/base/utils/is-nonnegative-integer' ); var betainc = require( '@stdlib/math/base/special/betainc' ); var isnan = require( '@stdlib/math/base/utils/is-nan' ); var floor = require( '@stdlib/math/base/special/floor' ); var PINF = require( '@stdlib/math/constants/float64-pinf' ); // MAIN // /** * Evaluates the cumulative distribution function (CDF) for a binomial distribution with number of trials `n` and success probability `p` at a value `x`. * * @param {number} x - input value * @param {NonNegativeInteger} n - number of trials * @param {Probability} p - success probability * @returns {Probability} evaluated CDF * * @example * var y = cdf( 3.0, 20, 0.2 ); * // returns ~0.411 * @example * var y = cdf( 21.0, 20, 0.2 ); * // returns 1.0 * @example * var y = cdf( 5.0, 10, 0.4 ) * // returns ~0.834 * @example * var y = cdf( 0.0, 10, 0.4 ) * // returns ~0.06 * @example * var y = cdf( NaN, 20, 0.5 ); * // returns NaN * @example * var y = cdf( 0.0, NaN, 0.5 ); * // returns NaN * @example * var y = cdf( 0.0, 20, NaN ); * // returns NaN * @example * var y = cdf( 2.0, 1.5, 0.5 ); * // returns NaN * @example * var y = cdf( 2.0, -2.0, 0.5 ); * // returns NaN * @example * var y = cdf( 2.0, 20, -1.0 ); * // returns NaN * @example * var y = cdf( 2.0, 20, 1.5 ); * // returns NaN */ function cdf( x, n, p ) { if ( isnan( x ) || isnan( n ) || isnan( p ) || p < 0.0 || p > 1.0 || !isNonNegativeInteger( n ) || n === PINF ) { return NaN; } if ( x < 0.0 ) { return 0.0; } if ( x >= n ) { return 1.0; } x = floor( x + 1e-7 ); return betainc( p, x + 1.0, n - x, true, true ); } // end FUNCTION cdf() // EXPORTS // module.exports = cdf;
Add decimal
lib/node_modules/@stdlib/math/base/dist/binomial/cdf/lib/cdf.js
Add decimal
<ide><path>ib/node_modules/@stdlib/math/base/dist/binomial/cdf/lib/cdf.js <ide> if ( x >= n ) { <ide> return 1.0; <ide> } <del> x = floor( x + 1e-7 ); <add> x = floor( x + 1.0e-7 ); <ide> return betainc( p, x + 1.0, n - x, true, true ); <ide> } // end FUNCTION cdf() <ide>
Java
apache-2.0
5357d9ed88fbc6608e67b8870d9a1910dbf25e50
0
darshanasbg/identity-inbound-auth-oauth,chirankavinda123/identity-inbound-auth-oauth,darshanasbg/identity-inbound-auth-oauth,chirankavinda123/identity-inbound-auth-oauth,IsuraD/identity-inbound-auth-oauth,wso2-extensions/identity-inbound-auth-oauth,IsuraD/identity-inbound-auth-oauth,wso2-extensions/identity-inbound-auth-oauth
/* * Copyright (c) 2013, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.oauth2.dao; public class SQLQueries { public static final String STORE_AUTHORIZATION_CODE = "INSERT INTO IDN_OAUTH2_AUTHORIZATION_CODE " + "(CODE_ID, AUTHORIZATION_CODE, CONSUMER_KEY_ID, CALLBACK_URL, SCOPE, AUTHZ_USER, USER_DOMAIN, TENANT_ID, " + "TIME_CREATED, VALIDITY_PERIOD, SUBJECT_IDENTIFIER) SELECT ?,?,ID,?,?,?,?,?,?,?,? FROM " + "IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY=?"; public static final String STORE_AUTHORIZATION_CODE_WITH_PKCE = "INSERT INTO IDN_OAUTH2_AUTHORIZATION_CODE " + "(CODE_ID, AUTHORIZATION_CODE, CONSUMER_KEY_ID, CALLBACK_URL, SCOPE, AUTHZ_USER, USER_DOMAIN, TENANT_ID, " + "TIME_CREATED, VALIDITY_PERIOD, SUBJECT_IDENTIFIER, PKCE_CODE_CHALLENGE, PKCE_CODE_CHALLENGE_METHOD) SELECT ?,?,ID,?,?,?,?,?,?,?,?,?,? FROM " + "IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY=?"; public static final String VALIDATE_AUTHZ_CODE = "SELECT AUTHZ_USER, USER_DOMAIN, TENANT_ID, SCOPE, " + "CALLBACK_URL, TIME_CREATED,VALIDITY_PERIOD, STATE, TOKEN_ID, AUTHORIZATION_CODE, CODE_ID, SUBJECT_IDENTIFIER, " + "FROM IDN_OAUTH2_AUTHORIZATION_CODE WHERE " + "CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHORIZATION_CODE = ?"; public static final String VALIDATE_AUTHZ_CODE_WITH_PKCE = "SELECT AUTHZ_USER, USER_DOMAIN, TENANT_ID, SCOPE, " + "CALLBACK_URL, TIME_CREATED,VALIDITY_PERIOD, STATE, TOKEN_ID, AUTHORIZATION_CODE, CODE_ID, SUBJECT_IDENTIFIER, " + "PKCE_CODE_CHALLENGE, PKCE_CODE_CHALLENGE_METHOD FROM IDN_OAUTH2_AUTHORIZATION_CODE WHERE " + "CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHORIZATION_CODE = ?"; public static final String RETRIEVE_CODE_ID_BY_AUTHORIZATION_CODE = "SELECT CODE_ID FROM " + "IDN_OAUTH2_AUTHORIZATION_CODE WHERE AUTHORIZATION_CODE = ?"; public static final String RETRIEVE_AUTHZ_CODE_BY_CODE_ID = "SELECT AUTHORIZATION_CODE FROM " + "IDN_OAUTH2_AUTHORIZATION_CODE WHERE CODE_ID = ?"; public static final String RETRIEVE_TOKEN_ID_BY_TOKEN = "SELECT TOKEN_ID FROM " + "IDN_OAUTH2_ACCESS_TOKEN WHERE ACCESS_TOKEN = ?"; public static final String RETRIEVE_TOKEN_BY_TOKEN_ID = "SELECT ACCESS_TOKEN FROM " + "IDN_OAUTH2_ACCESS_TOKEN WHERE TOKEN_ID = ?"; public static final String UPDATE_TOKEN_AGAINST_AUTHZ_CODE = "UPDATE IDN_OAUTH2_AUTHORIZATION_CODE SET " + "TOKEN_ID=? WHERE AUTHORIZATION_CODE=?"; public static final String GET_ACCESS_TOKEN_BY_AUTHZ_CODE = "SELECT AUTHORIZATION_CODE FROM " + "IDN_OAUTH2_AUTHORIZATION_CODE WHERE " + "TOKEN_ID=?"; public static final String UPDATE_NEW_TOKEN_AGAINST_AUTHZ_CODE = "UPDATE IDN_OAUTH2_AUTHORIZATION_CODE SET " + "TOKEN_ID=? WHERE TOKEN_ID=?"; public static final String DEACTIVATE_AUTHZ_CODE = "UPDATE IDN_OAUTH2_AUTHORIZATION_CODE SET " + "STATE='INACTIVE' WHERE AUTHORIZATION_CODE= ?"; public static final String EXPIRE_AUTHZ_CODE = "UPDATE IDN_OAUTH2_AUTHORIZATION_CODE SET " + "STATE='EXPIRED' WHERE AUTHORIZATION_CODE= ?"; public static final String DEACTIVATE_AUTHZ_CODE_AND_INSERT_CURRENT_TOKEN = "UPDATE IDN_OAUTH2_AUTHORIZATION_CODE SET " + "STATE='INACTIVE', TOKEN_ID=?" + " WHERE AUTHORIZATION_CODE= ?"; public static final String RETRIEVE_LATEST_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_ORACLE = "SELECT * FROM (SELECT " + "ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD,TOKEN_STATE, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN WHERE " + "CONSUMER_KEY_ID=(SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=? AND " + "TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? ORDER BY TIME_CREATED DESC) WHERE ROWNUM < 2 "; public static final String RETRIEVE_LATEST_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_MYSQL = "SELECT ACCESS_TOKEN, " + "REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD," + " TOKEN_STATE, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN WHERE CONSUMER_KEY_ID = (SELECT ID FROM " + "IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=? AND TENANT_ID=? AND USER_DOMAIN=? AND " + "TOKEN_SCOPE_HASH=? ORDER BY TIME_CREATED DESC LIMIT 1"; public static final String RETRIEVE_LATEST_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_DB2SQL = "SELECT ACCESS_TOKEN, " + "REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD," + " TOKEN_STATE, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN WHERE CONSUMER_KEY_ID= (SELECT ID FROM " + "IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=? AND TENANT_ID=? AND USER_DOMAIN=? AND" + " TOKEN_SCOPE_HASH=? ORDER BY TIME_CREATED DESC FETCH FIRST 1 ROWS ONLY"; public static final String RETRIEVE_LATEST_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_MSSQL = "SELECT TOP 1 " + "ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, TOKEN_STATE, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM " + "IDN_OAUTH2_ACCESS_TOKEN WITH (NOLOCK) WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS " + "WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=? AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? ORDER " + "BY TIME_CREATED DESC"; public static final String RETRIEVE_LATEST_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_POSTGRESQL = "SELECT * FROM " + "(SELECT ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, TOKEN_STATE, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN WHERE " + "CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=? AND " + "TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? ORDER BY TIME_CREATED DESC) TOKEN LIMIT 1 "; public static final String RETRIEVE_LATEST_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_INFORMIX = "SELECT FIRST 1 * FROM" + " (SELECT ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, TOKEN_STATE, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN WHERE " + "CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=? AND " + "TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? ORDER BY TIME_CREATED DESC) TOKEN "; public static final String RETRIEVE_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER = "SELECT ACCESS_TOKEN, REFRESH_TOKEN, " + "TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, " + "TOKEN_SCOPE, ACCESS_TOKEN_TABLE.TOKEN_ID, SUBJECT_IDENTIFIER FROM (SELECT TOKEN_ID, ACCESS_TOKEN, REFRESH_TOKEN, " + "TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, SUBJECT_IDENTIFIER FROM" + " IDN_OAUTH2_ACCESS_TOKEN WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE " + "CONSUMER_KEY = ?) AND AUTHZ_USER=? AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_STATE='ACTIVE') " + "ACCESS_TOKEN_TABLE LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON ACCESS_TOKEN_TABLE.TOKEN_ID = " + "IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String RETRIEVE_ACTIVE_EXPIRED_ACCESS_TOKEN_BY_CLIENT_ID_USER = "SELECT ACCESS_TOKEN, REFRESH_TOKEN, " + "TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, " + "TOKEN_SCOPE, ACCESS_TOKEN_TABLE.TOKEN_ID, SUBJECT_IDENTIFIER FROM (SELECT TOKEN_ID, ACCESS_TOKEN, REFRESH_TOKEN, " + "TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, SUBJECT_IDENTIFIER FROM" + " IDN_OAUTH2_ACCESS_TOKEN WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE " + "CONSUMER_KEY = ?) AND AUTHZ_USER=? AND TENANT_ID=? AND USER_DOMAIN=? AND (TOKEN_STATE='ACTIVE' OR " + "TOKEN_STATE='EXPIRED')) ACCESS_TOKEN_TABLE LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON ACCESS_TOKEN_TABLE" + ".TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String RETRIEVE_ACTIVE_ACCESS_TOKEN = "SELECT CONSUMER_KEY, AUTHZ_USER, ACCESS_TOKEN_TABLE.TENANT_ID, " + "USER_DOMAIN, TOKEN_SCOPE, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, REFRESH_TOKEN, ACCESS_TOKEN_TABLE.TOKEN_ID, GRANT_TYPE, " + "SUBJECT_IDENTIFIER FROM (SELECT TOKEN_ID, CONSUMER_KEY, AUTHZ_USER, IDN_OAUTH2_ACCESS_TOKEN.TENANT_ID AS TENANT_ID, " + "IDN_OAUTH2_ACCESS_TOKEN.USER_DOMAIN AS USER_DOMAIN,TIME_CREATED," + "REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, REFRESH_TOKEN, IDN_OAUTH2_ACCESS_TOKEN.GRANT_TYPE AS GRANT_TYPE," + "SUBJECT_IDENTIFIER FROM (SELECT * FROM IDN_OAUTH2_ACCESS_TOKEN WHERE ACCESS_TOKEN=? AND TOKEN_STATE='ACTIVE') IDN_OAUTH2_ACCESS_TOKEN " +"JOIN IDN_OAUTH_CONSUMER_APPS ON CONSUMER_KEY_ID = ID) ACCESS_TOKEN_TABLE" +" LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON ACCESS_TOKEN_TABLE.TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; // public static final String RETRIEVE_ACTIVE_ACCESS_TOKEN = "SELECT CONSUMER_KEY, AUTHZ_USER, ACCESS_TOKEN_TABLE" + // ".TENANT_ID, USER_DOMAIN, TOKEN_SCOPE, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + // "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, REFRESH_TOKEN, ACCESS_TOKEN_TABLE.TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM (SELECT " + // "TOKEN_ID, CONSUMER_KEY, AUTHZ_USER, IDN_OAUTH2_ACCESS_TOKEN.TENANT_ID, IDN_OAUTH2_ACCESS_TOKEN.USER_DOMAIN, TIME_CREATED, " + // "REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, REFRESH_TOKEN, " + // "IDN_OAUTH2_ACCESS_TOKEN.GRANT_TYPE, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN JOIN IDN_OAUTH_CONSUMER_APPS ON " // + "CONSUMER_KEY_ID = ID " + // "WHERE ACCESS_TOKEN=? AND TOKEN_STATE='ACTIVE') ACCESS_TOKEN_TABLE LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE " + // "ON ACCESS_TOKEN_TABLE.TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String RETRIEVE_ACTIVE_EXPIRED_ACCESS_TOKEN = "SELECT CONSUMER_KEY, AUTHZ_USER, " + "ACCESS_TOKEN_TABLE.TENANT_ID, USER_DOMAIN, TOKEN_SCOPE, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, " + "VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, REFRESH_TOKEN, ACCESS_TOKEN_TABLE.TOKEN_ID, " + "GRANT_TYPE, SUBJECT_IDENTIFIER " + "FROM (SELECT TOKEN_ID, CONSUMER_KEY, AUTHZ_USER, IDN_OAUTH2_ACCESS_TOKEN.TENANT_ID, " + "IDN_OAUTH2_ACCESS_TOKEN.USER_DOMAIN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, REFRESH_TOKEN, IDN_OAUTH2_ACCESS_TOKEN.GRANT_TYPE, SUBJECT_IDENTIFIER " + "FROM IDN_OAUTH2_ACCESS_TOKEN JOIN IDN_OAUTH_CONSUMER_APPS ON CONSUMER_KEY_ID = ID " + "WHERE ACCESS_TOKEN=? AND (TOKEN_STATE='ACTIVE' OR TOKEN_STATE='EXPIRED')) ACCESS_TOKEN_TABLE LEFT " + "JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON ACCESS_TOKEN_TABLE.TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String UPDATE_TOKE_STATE = "UPDATE IDN_OAUTH2_ACCESS_TOKEN SET TOKEN_STATE=?, " + "TOKEN_STATE_ID=? WHERE TOKEN_ID=?"; public static final String REVOKE_ACCESS_TOKEN_BY_TOKEN_ID = "UPDATE IDN_OAUTH2_ACCESS_TOKEN SET TOKEN_STATE=?, " + "TOKEN_STATE_ID=? WHERE TOKEN_ID=?"; public static final String REVOKE_ACCESS_TOKEN = "UPDATE IDN_OAUTH2_ACCESS_TOKEN SET TOKEN_STATE=?, " + "TOKEN_STATE_ID=? WHERE ACCESS_TOKEN=?"; public static final String REVOKE_APP_ACCESS_TOKEN = "UPDATE IDN_OAUTH2_ACCESS_TOKEN SET TOKEN_STATE=?, " + "TOKEN_STATE_ID=? WHERE CONSUMER_KEY_ID = (SELECT ID FROM " + "IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND TOKEN_STATE=?"; public static final String REVOKE_REFRESH_TOKEN = "UPDATE IDN_OAUTH2_ACCESS_TOKEN SET TOKEN_STATE=?, " + "TOKEN_STATE_ID=? WHERE REFRESH_TOKEN=?"; public static final String GET_ACCESS_TOKEN_BY_AUTHZUSER = "SELECT DISTINCT ACCESS_TOKEN " + "FROM IDN_OAUTH2_ACCESS_TOKEN WHERE AUTHZ_USER=? AND TENANT_ID=? AND TOKEN_STATE=? AND USER_DOMAIN=?"; public static final String GET_ACCESS_TOKENS_FOR_CONSUMER_KEY = "SELECT ACCESS_TOKEN FROM IDN_OAUTH2_ACCESS_TOKEN" + " WHERE CONSUMER_KEY_ID IN (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ? ) AND " + "TOKEN_STATE=?"; public static final String GET_ACTIVE_DETAILS_FOR_CONSUMER_KEY = "SELECT IDN_OAUTH2_ACCESS_TOKEN.AUTHZ_USER, " + "IDN_OAUTH2_ACCESS_TOKEN.ACCESS_TOKEN, IDN_OAUTH2_ACCESS_TOKEN.TENANT_ID, IDN_OAUTH2_ACCESS_TOKEN.USER_DOMAIN," + " IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_SCOPE FROM IDN_OAUTH2_ACCESS_TOKEN LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE" + " ON IDN_OAUTH2_ACCESS_TOKEN.TOKEN_ID=IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID WHERE " + "CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY=?) AND TOKEN_STATE=?"; public static final String GET_AUTHORIZATION_CODES_FOR_CONSUMER_KEY = "SELECT AUTHORIZATION_CODE FROM " + "IDN_OAUTH2_AUTHORIZATION_CODE WHERE CONSUMER_KEY_ID IN (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE " + "CONSUMER_KEY = ?) "; public static final String GET_ACTIVE_AUTHORIZATION_CODES_FOR_CONSUMER_KEY = "SELECT AUTHORIZATION_CODE FROM " + "IDN_OAUTH2_AUTHORIZATION_CODE WHERE CONSUMER_KEY_ID IN (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE " + "CONSUMER_KEY = ?) AND STATE = ?"; public static final String UPDATE_AUTHORIZATION_CODE_STATE = "UPDATE IDN_OAUTH2_AUTHORIZATION_CODE SET STATE=? " + "WHERE AUTHORIZATION_CODE=?"; public static final String GET_AUTHORIZATION_CODES_BY_AUTHZUSER = "SELECT DISTINCT AUTHORIZATION_CODE" + " FROM IDN_OAUTH2_AUTHORIZATION_CODE WHERE AUTHZ_USER=? AND TENANT_ID=? AND USER_DOMAIN=? AND STATE=?"; public static final String GET_DISTINCT_APPS_AUTHORIZED_BY_USER_ALL_TIME = "SELECT DISTINCT CONSUMER_KEY FROM " + "IDN_OAUTH2_ACCESS_TOKEN JOIN IDN_OAUTH_CONSUMER_APPS ON CONSUMER_KEY_ID = " + "ID WHERE AUTHZ_USER=? AND IDN_OAUTH2_ACCESS_TOKEN.TENANT_ID=? AND IDN_OAUTH2_ACCESS_TOKEN.USER_DOMAIN=? " + "AND (TOKEN_STATE='ACTIVE' OR TOKEN_STATE='EXPIRED')"; public static final String RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_MYSQL = "SELECT ACCESS_TOKEN, AUTHZ_USER, " + "ACCESS_TOKEN_SELECTED.TENANT_ID, USER_DOMAIN, TOKEN_SCOPE, TOKEN_STATE, REFRESH_TOKEN_TIME_CREATED, " + "REFRESH_TOKEN_VALIDITY_PERIOD, ACCESS_TOKEN_SELECTED.TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM ( " + "SELECT ACCESS_TOKEN, AUTHZ_USER, TENANT_ID, USER_DOMAIN, TOKEN_STATE, REFRESH_TOKEN_TIME_CREATED, " + "REFRESH_TOKEN_VALIDITY_PERIOD, TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM $accessTokenStoreTable " + "WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND " + "REFRESH_TOKEN = ? ORDER BY TIME_CREATED DESC LIMIT 1) ACCESS_TOKEN_SELECTED LEFT JOIN " + "IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON ACCESS_TOKEN_SELECTED.TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_DB2SQL = "SELECT ACCESS_TOKEN, AUTHZ_USER, " + "ACCESS_TOKEN_SELECTED.TENANT_ID, USER_DOMAIN, TOKEN_SCOPE, TOKEN_STATE, REFRESH_TOKEN_TIME_CREATED, " + "REFRESH_TOKEN_VALIDITY_PERIOD, ACCESS_TOKEN_SELECTED.TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM ( " + "SELECT ACCESS_TOKEN, AUTHZ_USER, TOKEN_STATE, REFRESH_TOKEN_TIME_CREATED, REFRESH_TOKEN_VALIDITY_PERIOD," + " TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM $accessTokenStoreTable WHERE CONSUMER_KEY_ID = (SELECT ID" + " FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND REFRESH_TOKEN = ? ORDER BY TIME_CREATED DESC " + "FETCH FIRST 1 ROWS ONLY) ACCESS_TOKEN_SELECTED LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON " + "ACCESS_TOKEN_SELECTED.TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_ORACLE = "SELECT ACCESS_TOKEN, AUTHZ_USER, " + "ACCESS_TOKEN_SELECTED.TENANT_ID, USER_DOMAIN, TOKEN_SCOPE, TOKEN_STATE, REFRESH_TOKEN_TIME_CREATED, " + "REFRESH_TOKEN_VALIDITY_PERIOD, ACCESS_TOKEN_SELECTED.TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM ( " + "SELECT * FROM (SELECT ACCESS_TOKEN, AUTHZ_USER, TENANT_ID, USER_DOMAIN, TOKEN_STATE, " + "REFRESH_TOKEN_TIME_CREATED, REFRESH_TOKEN_VALIDITY_PERIOD, TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM" + " $accessTokenStoreTable WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE " + "CONSUMER_KEY = ?) AND REFRESH_TOKEN = ? ORDER BY TIME_CREATED DESC) WHERE ROWNUM < 2 ) " + "ACCESS_TOKEN_SELECTED LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON ACCESS_TOKEN_SELECTED.TOKEN_ID = " + "IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_MSSQL = "SELECT ACCESS_TOKEN, AUTHZ_USER, " + "ACCESS_TOKEN_SELECTED.TENANT_ID, USER_DOMAIN, TOKEN_SCOPE, TOKEN_STATE, REFRESH_TOKEN_TIME_CREATED, " + "REFRESH_TOKEN_VALIDITY_PERIOD, ACCESS_TOKEN_SELECTED.TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM " + "(SELECT TOP 1 ACCESS_TOKEN, AUTHZ_USER, TENANT_ID, USER_DOMAIN, TOKEN_STATE, " + "REFRESH_TOKEN_TIME_CREATED, REFRESH_TOKEN_VALIDITY_PERIOD, TOKEN_ID, GRANT_TYPE, " + "SUBJECT_IDENTIFIER FROM $accessTokenStoreTable WHERE CONSUMER_KEY_ID = (SELECT ID FROM " + "IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND REFRESH_TOKEN = ? ORDER BY TIME_CREATED DESC) " + "ACCESS_TOKEN_SELECTED LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON ACCESS_TOKEN_SELECTED" + ".TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_POSTGRESQL = "SELECT ACCESS_TOKEN, AUTHZ_USER, " + "ACCESS_TOKEN_SELECTED.TENANT_ID, USER_DOMAIN, TOKEN_SCOPE, TOKEN_STATE, REFRESH_TOKEN_TIME_CREATED," + " REFRESH_TOKEN_VALIDITY_PERIOD, ACCESS_TOKEN_SELECTED.TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM " + "(SELECT ACCESS_TOKEN, AUTHZ_USER, TENANT_ID, USER_DOMAIN, TOKEN_STATE, REFRESH_TOKEN_TIME_CREATED, " + "REFRESH_TOKEN_VALIDITY_PERIOD, TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM $accessTokenStoreTable " + "WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND " + "REFRESH_TOKEN = ? ORDER BY TIME_CREATED DESC LIMIT 1) ACCESS_TOKEN_SELECTED LEFT JOIN " + "IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON ACCESS_TOKEN_SELECTED.TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_INFORMIX = "SELECT ACCESS_TOKEN, AUTHZ_USER, " + "ACCESS_TOKEN_SELECTED.TENANT_ID, USER_DOMAIN, TOKEN_SCOPE, TOKEN_STATE, REFRESH_TOKEN_TIME_CREATED, " + "REFRESH_TOKEN_VALIDITY_PERIOD, ACCESS_TOKEN_SELECTED.TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM ( " + "SELECT FIRST 1 ACCESS_TOKEN, AUTHZ_USER, TENANT_ID, USER_DOMAIN, TOKEN_STATE, REFRESH_TOKEN_TIME_CREATED, " + "REFRESH_TOKEN_VALIDITY_PERIOD, TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM $accessTokenStoreTable " + "WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND REFRESH_TOKEN = ? " + "ORDER BY TIME_CREATED DESC) ACCESS_TOKEN_SELECTED LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON " + "ACCESS_TOKEN_SELECTED.TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String INSERT_OAUTH2_ACCESS_TOKEN = "INSERT INTO $accessTokenStoreTable (ACCESS_TOKEN, " + "REFRESH_TOKEN, CONSUMER_KEY_ID, AUTHZ_USER, TENANT_ID, USER_DOMAIN, TIME_CREATED, " + "REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, TOKEN_SCOPE_HASH, " + "TOKEN_STATE, USER_TYPE, TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER) SELECT ?,?,ID,?,?,?,?,?,?,?,?,?,?,?,?," + "? FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY=?"; public static final String INSERT_OAUTH2_TOKEN_SCOPE = "INSERT INTO IDN_OAUTH2_ACCESS_TOKEN_SCOPE (TOKEN_ID, " + "TOKEN_SCOPE, TENANT_ID) VALUES (?,?,?)"; public static final String DELETE_ACCESS_TOKEN = "DELETE FROM $accessTokenStoreTable WHERE ACCESS_TOKEN = ? "; public static final String RETRIEVE_IOS_SCOPE_KEY = "SELECT IOS.SCOPE_KEY FROM IDN_OAUTH2_SCOPE IOS, " + "IDN_OAUTH2_RESOURCE_SCOPE IORS WHERE RESOURCE_PATH = ? AND IORS.SCOPE_ID = IOS.SCOPE_ID"; public static final String DELETE_USER_RPS = "DELETE FROM IDN_OPENID_USER_RPS WHERE USER_NAME = ? AND " + "RP_URL = ?"; public static final String DELETE_USER_RPS_IN_TENANT = "DELETE FROM IDN_OPENID_USER_RPS WHERE USER_NAME = ? AND " + "TENANT_ID=? AND RP_URL = ?"; public static final String UPDATE_TRUSTED_ALWAYS_IDN_OPENID_USER_RPS = "UPDATE IDN_OPENID_USER_RPS SET TRUSTED_ALWAYS=? " + "WHERE USER_NAME = ? AND TENANT_ID=? AND RP_URL = ?"; public static final String RENAME_USER_STORE_IN_ACCESS_TOKENS_TABLE = "UPDATE IDN_OAUTH2_ACCESS_TOKEN SET " + "USER_DOMAIN=? WHERE TENANT_ID=? AND USER_DOMAIN=?"; public static final String RENAME_USER_STORE_IN_AUTHORIZATION_CODES_TABLE = "UPDATE IDN_OAUTH2_AUTHORIZATION_CODE" + " SET USER_DOMAIN=? WHERE TENANT_ID=? AND USER_DOMAIN=?"; public static final String LIST_ALL_TOKENS_IN_TENANT = "SELECT ACCESS_TOKEN, REFRESH_TOKEN, " + "TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, " + "TOKEN_SCOPE, ACCESS_TOKEN_TABLE.TOKEN_ID, AUTHZ_USER, USER_DOMAIN, CONSUMER_KEY FROM (SELECT AUTHZ_USER," + " USER_DOMAIN, CONSUMER_KEY_ID, TOKEN_ID, ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, " + "REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE FROM " + "IDN_OAUTH2_ACCESS_TOKEN WHERE TENANT_ID=? AND (TOKEN_STATE='ACTIVE' OR TOKEN_STATE='EXPIRED')) " + "ACCESS_TOKEN_TABLE JOIN IDN_OAUTH_CONSUMER_APPS ON ID = CONSUMER_KEY_ID LEFT JOIN " + "IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON ACCESS_TOKEN_TABLE.TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String LIST_ALL_TOKENS_IN_USER_STORE = "SELECT ACCESS_TOKEN, REFRESH_TOKEN, " + "TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, " + "TOKEN_SCOPE, ACCESS_TOKEN_TABLE.TOKEN_ID, AUTHZ_USER, CONSUMER_KEY FROM (SELECT AUTHZ_USER, " + "CONSUMER_KEY_ID, TOKEN_ID, ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, " + "VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE FROM IDN_OAUTH2_ACCESS_TOKEN WHERE TENANT_ID=?" + " AND USER_DOMAIN=? AND (TOKEN_STATE='ACTIVE' OR TOKEN_STATE='EXPIRED')) ACCESS_TOKEN_TABLE JOIN " + "IDN_OAUTH_CONSUMER_APPS ON ID = CONSUMER_KEY_ID LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON " + "ACCESS_TOKEN_TABLE.TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String LIST_LATEST_AUTHZ_CODES_IN_USER_DOMAIN = "SELECT CODE_ID, AUTHORIZATION_CODE, " + "CONSUMER_KEY, IDN_OAUTH2_AUTHORIZATION_CODE.AUTHZ_USER, IDN_OAUTH2_AUTHORIZATION_CODE.SCOPE, " + "TIME_CREATED, VALIDITY_PERIOD, IDN_OAUTH2_AUTHORIZATION_CODE.CALLBACK_URL FROM (SELECT " + "AUTHZ_USER, CONSUMER_KEY_ID, SCOPE, MAX(TIME_CREATED) TIMES FROM IDN_OAUTH2_AUTHORIZATION_CODE WHERE " + "TENANT_ID=? AND USER_DOMAIN=? group by AUTHZ_USER, CONSUMER_KEY_ID, SCOPE) AUTHZ_SELECTED JOIN " + "IDN_OAUTH2_AUTHORIZATION_CODE ON AUTHZ_SELECTED.AUTHZ_USER=IDN_OAUTH2_AUTHORIZATION_CODE.AUTHZ_USER " + "AND AUTHZ_SELECTED.CONSUMER_KEY_ID=IDN_OAUTH2_AUTHORIZATION_CODE.CONSUMER_KEY_ID AND AUTHZ_SELECTED" + ".TIMES=IDN_OAUTH2_AUTHORIZATION_CODE.TIME_CREATED AND AUTHZ_SELECTED.SCOPE=IDN_OAUTH2_AUTHORIZATION_CODE" + ".SCOPE JOIN IDN_OAUTH_CONSUMER_APPS ON IDN_OAUTH2_AUTHORIZATION_CODE.CONSUMER_KEY_ID = ID WHERE " + "STATE='ACTIVE'"; public static final String LIST_LATEST_AUTHZ_CODES_IN_TENANT = "SELECT CODE_ID, AUTHORIZATION_CODE, " + "CONSUMER_KEY, IDN_OAUTH2_AUTHORIZATION_CODE.AUTHZ_USER, IDN_OAUTH2_AUTHORIZATION_CODE.SCOPE, " + "TIME_CREATED, VALIDITY_PERIOD, IDN_OAUTH2_AUTHORIZATION_CODE.CALLBACK_URL, IDN_OAUTH2_AUTHORIZATION_CODE" + ".USER_DOMAIN FROM (SELECT AUTHZ_USER, USER_DOMAIN, CONSUMER_KEY_ID, SCOPE, MAX(TIME_CREATED) TIMES " + "FROM IDN_OAUTH2_AUTHORIZATION_CODE WHERE TENANT_ID=? group by AUTHZ_USER, " + "USER_DOMAIN, CONSUMER_KEY_ID, SCOPE) AUTHZ_SELECTED JOIN IDN_OAUTH2_AUTHORIZATION_CODE ON " + "AUTHZ_SELECTED.AUTHZ_USER=IDN_OAUTH2_AUTHORIZATION_CODE.AUTHZ_USER AND AUTHZ_SELECTED" + ".CONSUMER_KEY_ID=IDN_OAUTH2_AUTHORIZATION_CODE.CONSUMER_KEY_ID AND AUTHZ_SELECTED" + ".TIMES=IDN_OAUTH2_AUTHORIZATION_CODE.TIME_CREATED AND AUTHZ_SELECTED" + ".USER_DOMAIN=IDN_OAUTH2_AUTHORIZATION_CODE.USER_DOMAIN AND AUTHZ_SELECTED" + ".SCOPE=IDN_OAUTH2_AUTHORIZATION_CODE.SCOPE JOIN IDN_OAUTH_CONSUMER_APPS ON IDN_OAUTH2_AUTHORIZATION_CODE" + ".CONSUMER_KEY_ID = ID WHERE STATE='ACTIVE'"; public static final String RETRIEVE_ROLES_OF_SCOPE = "SELECT IOS.ROLES FROM IDN_OAUTH2_SCOPE IOS WHERE SCOPE_KEY" + " = ?"; public static final String RETRIEVE_PKCE_TABLE_MYSQL = "SELECT PKCE_MANDATORY, PKCE_SUPPORT_PLAIN FROM " + "IDN_OAUTH_CONSUMER_APPS LIMIT 1"; public static final String RETRIEVE_PKCE_TABLE_DB2SQL = "SELECT PKCE_MANDATORY, PKCE_SUPPORT_PLAIN FROM " + "IDN_OAUTH_CONSUMER_APPS FETCH FIRST 1 ROWS ONLY"; public static final String RETRIEVE_PKCE_TABLE_MSSQL = "SELECT TOP 1 PKCE_MANDATORY, PKCE_SUPPORT_PLAIN FROM " + "IDN_OAUTH_CONSUMER_APPS"; public static final String RETRIEVE_PKCE_TABLE_INFORMIX = "SELECT FIRST 1 PKCE_MANDATORY, PKCE_SUPPORT_PLAIN FROM " + "IDN_OAUTH_CONSUMER_APPS"; public static final String RETRIEVE_PKCE_TABLE_ORACLE = "SELECT PKCE_MANDATORY, PKCE_SUPPORT_PLAIN FROM " + "IDN_OAUTH_CONSUMER_APPS WHERE ROWNUM < 2"; //Retrieve latest active token public static final String RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_MYSQL = "SELECT " + "ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN " + "WHERE CONSUMER_KEY_ID =(SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=? " + "AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND TOKEN_STATE='ACTIVE' ORDER BY TIME_CREATED " + "DESC LIMIT 1"; public static final String RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_ORACLE = "SELECT * FROM " + "(SELECT ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM " + "IDN_OAUTH2_ACCESS_TOKEN WHERE CONSUMER_KEY_ID=(SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY" + " = ?) AND AUTHZ_USER=? AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND TOKEN_STATE='ACTIVE'" + " ORDER BY TIME_CREATED DESC) WHERE ROWNUM < 2 "; public static final String RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_DB2SQL = "SELECT " + "ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN " + "WHERE CONSUMER_KEY_ID= (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=? " + "AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND TOKEN_STATE='ACTIVE' ORDER BY TIME_CREATED " + "DESC FETCH FIRST 1 ROWS ONLY"; public static final String RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_MSSQL = "SELECT TOP 1 " + "ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN " + "WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=?" + " AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND TOKEN_STATE='ACTIVE' ORDER BY TIME_CREATED" + " DESC"; public static final String RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_POSTGRESQL = "SELECT * " + "FROM (SELECT ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN " + "WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=?" + " AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND TOKEN_STATE='ACTIVE' ORDER BY TIME_CREATED" + " DESC) TOKEN LIMIT 1 "; public static final String RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_INFORMIX = "SELECT FIRST 1" + " * FROM (SELECT ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM " + "IDN_OAUTH2_ACCESS_TOKEN WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE " + "CONSUMER_KEY = ?) AND AUTHZ_USER=? AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND " + "TOKEN_STATE='ACTIVE' ORDER BY TIME_CREATED DESC) TOKEN "; //Retrieve latest non-active token public static final String RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_MYSQL = "SELECT " + "ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN " + "WHERE CONSUMER_KEY_ID =(SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=? " + "AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND TOKEN_STATE!='ACTIVE' ORDER BY TIME_CREATED" + " DESC LIMIT 1"; public static final String RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_ORACLE = "SELECT * FROM " + "(SELECT ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM " + "IDN_OAUTH2_ACCESS_TOKEN WHERE CONSUMER_KEY_ID=(SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY" + " = ?) AND AUTHZ_USER=? AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND " + "TOKEN_STATE!='ACTIVE' ORDER BY TIME_CREATED DESC) WHERE ROWNUM < 2 "; public static final String RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_DB2SQL = "SELECT " + "ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN " + "WHERE CONSUMER_KEY_ID= (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=? " + "AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND TOKEN_STATE!='ACTIVE' ORDER BY TIME_CREATED" + " DESC FETCH FIRST 1 ROWS ONLY"; public static final String RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_MSSQL = "SELECT TOP 1 " + "ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN " + "WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=?" + " AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND TOKEN_STATE!='ACTIVE' ORDER BY " + "TIME_CREATED DESC"; public static final String RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_POSTGRESQL = "SELECT * " + "FROM (SELECT ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN " + "WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=?" + " AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND TOKEN_STATE!='ACTIVE' ORDER BY " + "TIME_CREATED DESC) TOKEN LIMIT 1 "; public static final String RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_INFORMIX = "SELECT FIRST 1" + " * FROM (SELECT ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM " + "IDN_OAUTH2_ACCESS_TOKEN WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE " + "CONSUMER_KEY = ?) AND AUTHZ_USER=? AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND " + "TOKEN_STATE!='ACTIVE' ORDER BY TIME_CREATED DESC) TOKEN "; private SQLQueries() { } }
components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/dao/SQLQueries.java
/* * Copyright (c) 2013, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.oauth2.dao; public class SQLQueries { public static final String STORE_AUTHORIZATION_CODE = "INSERT INTO IDN_OAUTH2_AUTHORIZATION_CODE " + "(CODE_ID, AUTHORIZATION_CODE, CONSUMER_KEY_ID, CALLBACK_URL, SCOPE, AUTHZ_USER, USER_DOMAIN, TENANT_ID, " + "TIME_CREATED, VALIDITY_PERIOD, SUBJECT_IDENTIFIER) SELECT ?,?,ID,?,?,?,?,?,?,?,? FROM " + "IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY=?"; public static final String STORE_AUTHORIZATION_CODE_WITH_PKCE = "INSERT INTO IDN_OAUTH2_AUTHORIZATION_CODE " + "(CODE_ID, AUTHORIZATION_CODE, CONSUMER_KEY_ID, CALLBACK_URL, SCOPE, AUTHZ_USER, USER_DOMAIN, TENANT_ID, " + "TIME_CREATED, VALIDITY_PERIOD, SUBJECT_IDENTIFIER, PKCE_CODE_CHALLENGE, PKCE_CODE_CHALLENGE_METHOD) SELECT ?,?,ID,?,?,?,?,?,?,?,?,?,? FROM " + "IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY=?"; public static final String VALIDATE_AUTHZ_CODE = "SELECT AUTHZ_USER, USER_DOMAIN, TENANT_ID, SCOPE, " + "CALLBACK_URL, TIME_CREATED,VALIDITY_PERIOD, STATE, TOKEN_ID, AUTHORIZATION_CODE, CODE_ID, SUBJECT_IDENTIFIER, " + "FROM IDN_OAUTH2_AUTHORIZATION_CODE WHERE " + "CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHORIZATION_CODE = ?"; public static final String VALIDATE_AUTHZ_CODE_WITH_PKCE = "SELECT AUTHZ_USER, USER_DOMAIN, TENANT_ID, SCOPE, " + "CALLBACK_URL, TIME_CREATED,VALIDITY_PERIOD, STATE, TOKEN_ID, AUTHORIZATION_CODE, CODE_ID, SUBJECT_IDENTIFIER, " + "PKCE_CODE_CHALLENGE, PKCE_CODE_CHALLENGE_METHOD FROM IDN_OAUTH2_AUTHORIZATION_CODE WHERE " + "CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHORIZATION_CODE = ?"; public static final String RETRIEVE_CODE_ID_BY_AUTHORIZATION_CODE = "SELECT CODE_ID FROM " + "IDN_OAUTH2_AUTHORIZATION_CODE WHERE AUTHORIZATION_CODE = ?"; public static final String RETRIEVE_AUTHZ_CODE_BY_CODE_ID = "SELECT AUTHORIZATION_CODE FROM " + "IDN_OAUTH2_AUTHORIZATION_CODE WHERE CODE_ID = ?"; public static final String RETRIEVE_TOKEN_ID_BY_TOKEN = "SELECT TOKEN_ID FROM " + "IDN_OAUTH2_ACCESS_TOKEN WHERE ACCESS_TOKEN = ?"; public static final String RETRIEVE_TOKEN_BY_TOKEN_ID = "SELECT ACCESS_TOKEN FROM " + "IDN_OAUTH2_ACCESS_TOKEN WHERE TOKEN_ID = ?"; public static final String UPDATE_TOKEN_AGAINST_AUTHZ_CODE = "UPDATE IDN_OAUTH2_AUTHORIZATION_CODE SET " + "TOKEN_ID=? WHERE AUTHORIZATION_CODE=?"; public static final String GET_ACCESS_TOKEN_BY_AUTHZ_CODE = "SELECT AUTHORIZATION_CODE FROM " + "IDN_OAUTH2_AUTHORIZATION_CODE WHERE " + "TOKEN_ID=?"; public static final String UPDATE_NEW_TOKEN_AGAINST_AUTHZ_CODE = "UPDATE IDN_OAUTH2_AUTHORIZATION_CODE SET " + "TOKEN_ID=? WHERE TOKEN_ID=?"; public static final String DEACTIVATE_AUTHZ_CODE = "UPDATE IDN_OAUTH2_AUTHORIZATION_CODE SET " + "STATE='INACTIVE' WHERE AUTHORIZATION_CODE= ?"; public static final String EXPIRE_AUTHZ_CODE = "UPDATE IDN_OAUTH2_AUTHORIZATION_CODE SET " + "STATE='EXPIRED' WHERE AUTHORIZATION_CODE= ?"; public static final String DEACTIVATE_AUTHZ_CODE_AND_INSERT_CURRENT_TOKEN = "UPDATE IDN_OAUTH2_AUTHORIZATION_CODE SET " + "STATE='INACTIVE', TOKEN_ID=?" + " WHERE AUTHORIZATION_CODE= ?"; public static final String RETRIEVE_LATEST_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_ORACLE = "SELECT * FROM (SELECT " + "ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD,TOKEN_STATE, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN WHERE " + "CONSUMER_KEY_ID=(SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=? AND " + "TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? ORDER BY TIME_CREATED DESC) WHERE ROWNUM < 2 "; public static final String RETRIEVE_LATEST_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_MYSQL = "SELECT ACCESS_TOKEN, " + "REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD," + " TOKEN_STATE, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN WHERE CONSUMER_KEY_ID = (SELECT ID FROM " + "IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=? AND TENANT_ID=? AND USER_DOMAIN=? AND " + "TOKEN_SCOPE_HASH=? ORDER BY TIME_CREATED DESC LIMIT 1"; public static final String RETRIEVE_LATEST_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_DB2SQL = "SELECT ACCESS_TOKEN, " + "REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD," + " TOKEN_STATE, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN WHERE CONSUMER_KEY_ID= (SELECT ID FROM " + "IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=? AND TENANT_ID=? AND USER_DOMAIN=? AND" + " TOKEN_SCOPE_HASH=? ORDER BY TIME_CREATED DESC FETCH FIRST 1 ROWS ONLY"; public static final String RETRIEVE_LATEST_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_MSSQL = "SELECT TOP 1 " + "ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, TOKEN_STATE, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM " + "IDN_OAUTH2_ACCESS_TOKEN WITH (NOLOCK) WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS " + "WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=? AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? ORDER " + "BY TIME_CREATED DESC"; public static final String RETRIEVE_LATEST_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_POSTGRESQL = "SELECT * FROM " + "(SELECT ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, TOKEN_STATE, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN WHERE " + "CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=? AND " + "TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? ORDER BY TIME_CREATED DESC) TOKEN LIMIT 1 "; public static final String RETRIEVE_LATEST_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_INFORMIX = "SELECT FIRST 1 * FROM" + " (SELECT ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, TOKEN_STATE, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN WHERE " + "CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=? AND " + "TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? ORDER BY TIME_CREATED DESC) TOKEN "; public static final String RETRIEVE_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER = "SELECT ACCESS_TOKEN, REFRESH_TOKEN, " + "TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, " + "TOKEN_SCOPE, ACCESS_TOKEN_TABLE.TOKEN_ID, SUBJECT_IDENTIFIER FROM (SELECT TOKEN_ID, ACCESS_TOKEN, REFRESH_TOKEN, " + "TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, SUBJECT_IDENTIFIER FROM" + " IDN_OAUTH2_ACCESS_TOKEN WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE " + "CONSUMER_KEY = ?) AND AUTHZ_USER=? AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_STATE='ACTIVE') " + "ACCESS_TOKEN_TABLE LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON ACCESS_TOKEN_TABLE.TOKEN_ID = " + "IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String RETRIEVE_ACTIVE_EXPIRED_ACCESS_TOKEN_BY_CLIENT_ID_USER = "SELECT ACCESS_TOKEN, REFRESH_TOKEN, " + "TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, " + "TOKEN_SCOPE, ACCESS_TOKEN_TABLE.TOKEN_ID, SUBJECT_IDENTIFIER FROM (SELECT TOKEN_ID, ACCESS_TOKEN, REFRESH_TOKEN, " + "TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, SUBJECT_IDENTIFIER FROM" + " IDN_OAUTH2_ACCESS_TOKEN WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE " + "CONSUMER_KEY = ?) AND AUTHZ_USER=? AND TENANT_ID=? AND USER_DOMAIN=? AND (TOKEN_STATE='ACTIVE' OR " + "TOKEN_STATE='EXPIRED')) ACCESS_TOKEN_TABLE LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON ACCESS_TOKEN_TABLE" + ".TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String RETRIEVE_ACTIVE_ACCESS_TOKEN = "SELECT CONSUMER_KEY, AUTHZ_USER, ACCESS_TOKEN_TABLE.TENANT_ID, " + "USER_DOMAIN, TOKEN_SCOPE, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, REFRESH_TOKEN, ACCESS_TOKEN_TABLE.TOKEN_ID, GRANT_TYPE, " + "SUBJECT_IDENTIFIER FROM (SELECT TOKEN_ID, CONSUMER_KEY, AUTHZ_USER, IDN_OAUTH2_ACCESS_TOKEN.TENANT_ID AS TENANT_ID, " + "IDN_OAUTH2_ACCESS_TOKEN.USER_DOMAIN AS USER_DOMAIN,TIME_CREATED," + "REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, REFRESH_TOKEN, IDN_OAUTH2_ACCESS_TOKEN.GRANT_TYPE AS GRANT_TYPE," + "SUBJECT_IDENTIFIER FROM (SELECT * FROM IDN_OAUTH2_ACCESS_TOKEN WHERE ACCESS_TOKEN=? AND TOKEN_STATE='ACTIVE') AS IDN_OAUTH2_ACCESS_TOKEN " +"JOIN IDN_OAUTH_CONSUMER_APPS ON CONSUMER_KEY_ID = ID) AS ACCESS_TOKEN_TABLE" +" LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON ACCESS_TOKEN_TABLE.TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; // public static final String RETRIEVE_ACTIVE_ACCESS_TOKEN = "SELECT CONSUMER_KEY, AUTHZ_USER, ACCESS_TOKEN_TABLE" + // ".TENANT_ID, USER_DOMAIN, TOKEN_SCOPE, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + // "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, REFRESH_TOKEN, ACCESS_TOKEN_TABLE.TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM (SELECT " + // "TOKEN_ID, CONSUMER_KEY, AUTHZ_USER, IDN_OAUTH2_ACCESS_TOKEN.TENANT_ID, IDN_OAUTH2_ACCESS_TOKEN.USER_DOMAIN, TIME_CREATED, " + // "REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, REFRESH_TOKEN, " + // "IDN_OAUTH2_ACCESS_TOKEN.GRANT_TYPE, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN JOIN IDN_OAUTH_CONSUMER_APPS ON " // + "CONSUMER_KEY_ID = ID " + // "WHERE ACCESS_TOKEN=? AND TOKEN_STATE='ACTIVE') ACCESS_TOKEN_TABLE LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE " + // "ON ACCESS_TOKEN_TABLE.TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String RETRIEVE_ACTIVE_EXPIRED_ACCESS_TOKEN = "SELECT CONSUMER_KEY, AUTHZ_USER, " + "ACCESS_TOKEN_TABLE.TENANT_ID, USER_DOMAIN, TOKEN_SCOPE, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, " + "VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, REFRESH_TOKEN, ACCESS_TOKEN_TABLE.TOKEN_ID, " + "GRANT_TYPE, SUBJECT_IDENTIFIER " + "FROM (SELECT TOKEN_ID, CONSUMER_KEY, AUTHZ_USER, IDN_OAUTH2_ACCESS_TOKEN.TENANT_ID, " + "IDN_OAUTH2_ACCESS_TOKEN.USER_DOMAIN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, REFRESH_TOKEN, IDN_OAUTH2_ACCESS_TOKEN.GRANT_TYPE, SUBJECT_IDENTIFIER " + "FROM IDN_OAUTH2_ACCESS_TOKEN JOIN IDN_OAUTH_CONSUMER_APPS ON CONSUMER_KEY_ID = ID " + "WHERE ACCESS_TOKEN=? AND (TOKEN_STATE='ACTIVE' OR TOKEN_STATE='EXPIRED')) ACCESS_TOKEN_TABLE LEFT " + "JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON ACCESS_TOKEN_TABLE.TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String UPDATE_TOKE_STATE = "UPDATE IDN_OAUTH2_ACCESS_TOKEN SET TOKEN_STATE=?, " + "TOKEN_STATE_ID=? WHERE TOKEN_ID=?"; public static final String REVOKE_ACCESS_TOKEN_BY_TOKEN_ID = "UPDATE IDN_OAUTH2_ACCESS_TOKEN SET TOKEN_STATE=?, " + "TOKEN_STATE_ID=? WHERE TOKEN_ID=?"; public static final String REVOKE_ACCESS_TOKEN = "UPDATE IDN_OAUTH2_ACCESS_TOKEN SET TOKEN_STATE=?, " + "TOKEN_STATE_ID=? WHERE ACCESS_TOKEN=?"; public static final String REVOKE_APP_ACCESS_TOKEN = "UPDATE IDN_OAUTH2_ACCESS_TOKEN SET TOKEN_STATE=?, " + "TOKEN_STATE_ID=? WHERE CONSUMER_KEY_ID = (SELECT ID FROM " + "IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND TOKEN_STATE=?"; public static final String REVOKE_REFRESH_TOKEN = "UPDATE IDN_OAUTH2_ACCESS_TOKEN SET TOKEN_STATE=?, " + "TOKEN_STATE_ID=? WHERE REFRESH_TOKEN=?"; public static final String GET_ACCESS_TOKEN_BY_AUTHZUSER = "SELECT DISTINCT ACCESS_TOKEN " + "FROM IDN_OAUTH2_ACCESS_TOKEN WHERE AUTHZ_USER=? AND TENANT_ID=? AND TOKEN_STATE=? AND USER_DOMAIN=?"; public static final String GET_ACCESS_TOKENS_FOR_CONSUMER_KEY = "SELECT ACCESS_TOKEN FROM IDN_OAUTH2_ACCESS_TOKEN" + " WHERE CONSUMER_KEY_ID IN (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ? ) AND " + "TOKEN_STATE=?"; public static final String GET_ACTIVE_DETAILS_FOR_CONSUMER_KEY = "SELECT IDN_OAUTH2_ACCESS_TOKEN.AUTHZ_USER, " + "IDN_OAUTH2_ACCESS_TOKEN.ACCESS_TOKEN, IDN_OAUTH2_ACCESS_TOKEN.TENANT_ID, IDN_OAUTH2_ACCESS_TOKEN.USER_DOMAIN," + " IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_SCOPE FROM IDN_OAUTH2_ACCESS_TOKEN LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE" + " ON IDN_OAUTH2_ACCESS_TOKEN.TOKEN_ID=IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID WHERE " + "CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY=?) AND TOKEN_STATE=?"; public static final String GET_AUTHORIZATION_CODES_FOR_CONSUMER_KEY = "SELECT AUTHORIZATION_CODE FROM " + "IDN_OAUTH2_AUTHORIZATION_CODE WHERE CONSUMER_KEY_ID IN (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE " + "CONSUMER_KEY = ?) "; public static final String GET_ACTIVE_AUTHORIZATION_CODES_FOR_CONSUMER_KEY = "SELECT AUTHORIZATION_CODE FROM " + "IDN_OAUTH2_AUTHORIZATION_CODE WHERE CONSUMER_KEY_ID IN (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE " + "CONSUMER_KEY = ?) AND STATE = ?"; public static final String UPDATE_AUTHORIZATION_CODE_STATE = "UPDATE IDN_OAUTH2_AUTHORIZATION_CODE SET STATE=? " + "WHERE AUTHORIZATION_CODE=?"; public static final String GET_AUTHORIZATION_CODES_BY_AUTHZUSER = "SELECT DISTINCT AUTHORIZATION_CODE" + " FROM IDN_OAUTH2_AUTHORIZATION_CODE WHERE AUTHZ_USER=? AND TENANT_ID=? AND USER_DOMAIN=? AND STATE=?"; public static final String GET_DISTINCT_APPS_AUTHORIZED_BY_USER_ALL_TIME = "SELECT DISTINCT CONSUMER_KEY FROM " + "IDN_OAUTH2_ACCESS_TOKEN JOIN IDN_OAUTH_CONSUMER_APPS ON CONSUMER_KEY_ID = " + "ID WHERE AUTHZ_USER=? AND IDN_OAUTH2_ACCESS_TOKEN.TENANT_ID=? AND IDN_OAUTH2_ACCESS_TOKEN.USER_DOMAIN=? " + "AND (TOKEN_STATE='ACTIVE' OR TOKEN_STATE='EXPIRED')"; public static final String RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_MYSQL = "SELECT ACCESS_TOKEN, AUTHZ_USER, " + "ACCESS_TOKEN_SELECTED.TENANT_ID, USER_DOMAIN, TOKEN_SCOPE, TOKEN_STATE, REFRESH_TOKEN_TIME_CREATED, " + "REFRESH_TOKEN_VALIDITY_PERIOD, ACCESS_TOKEN_SELECTED.TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM ( " + "SELECT ACCESS_TOKEN, AUTHZ_USER, TENANT_ID, USER_DOMAIN, TOKEN_STATE, REFRESH_TOKEN_TIME_CREATED, " + "REFRESH_TOKEN_VALIDITY_PERIOD, TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM $accessTokenStoreTable " + "WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND " + "REFRESH_TOKEN = ? ORDER BY TIME_CREATED DESC LIMIT 1) ACCESS_TOKEN_SELECTED LEFT JOIN " + "IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON ACCESS_TOKEN_SELECTED.TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_DB2SQL = "SELECT ACCESS_TOKEN, AUTHZ_USER, " + "ACCESS_TOKEN_SELECTED.TENANT_ID, USER_DOMAIN, TOKEN_SCOPE, TOKEN_STATE, REFRESH_TOKEN_TIME_CREATED, " + "REFRESH_TOKEN_VALIDITY_PERIOD, ACCESS_TOKEN_SELECTED.TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM ( " + "SELECT ACCESS_TOKEN, AUTHZ_USER, TOKEN_STATE, REFRESH_TOKEN_TIME_CREATED, REFRESH_TOKEN_VALIDITY_PERIOD," + " TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM $accessTokenStoreTable WHERE CONSUMER_KEY_ID = (SELECT ID" + " FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND REFRESH_TOKEN = ? ORDER BY TIME_CREATED DESC " + "FETCH FIRST 1 ROWS ONLY) ACCESS_TOKEN_SELECTED LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON " + "ACCESS_TOKEN_SELECTED.TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_ORACLE = "SELECT ACCESS_TOKEN, AUTHZ_USER, " + "ACCESS_TOKEN_SELECTED.TENANT_ID, USER_DOMAIN, TOKEN_SCOPE, TOKEN_STATE, REFRESH_TOKEN_TIME_CREATED, " + "REFRESH_TOKEN_VALIDITY_PERIOD, ACCESS_TOKEN_SELECTED.TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM ( " + "SELECT * FROM (SELECT ACCESS_TOKEN, AUTHZ_USER, TENANT_ID, USER_DOMAIN, TOKEN_STATE, " + "REFRESH_TOKEN_TIME_CREATED, REFRESH_TOKEN_VALIDITY_PERIOD, TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM" + " $accessTokenStoreTable WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE " + "CONSUMER_KEY = ?) AND REFRESH_TOKEN = ? ORDER BY TIME_CREATED DESC) WHERE ROWNUM < 2 ) " + "ACCESS_TOKEN_SELECTED LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON ACCESS_TOKEN_SELECTED.TOKEN_ID = " + "IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_MSSQL = "SELECT ACCESS_TOKEN, AUTHZ_USER, " + "ACCESS_TOKEN_SELECTED.TENANT_ID, USER_DOMAIN, TOKEN_SCOPE, TOKEN_STATE, REFRESH_TOKEN_TIME_CREATED, " + "REFRESH_TOKEN_VALIDITY_PERIOD, ACCESS_TOKEN_SELECTED.TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM " + "(SELECT TOP 1 ACCESS_TOKEN, AUTHZ_USER, TENANT_ID, USER_DOMAIN, TOKEN_STATE, " + "REFRESH_TOKEN_TIME_CREATED, REFRESH_TOKEN_VALIDITY_PERIOD, TOKEN_ID, GRANT_TYPE, " + "SUBJECT_IDENTIFIER FROM $accessTokenStoreTable WHERE CONSUMER_KEY_ID = (SELECT ID FROM " + "IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND REFRESH_TOKEN = ? ORDER BY TIME_CREATED DESC) " + "ACCESS_TOKEN_SELECTED LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON ACCESS_TOKEN_SELECTED" + ".TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_POSTGRESQL = "SELECT ACCESS_TOKEN, AUTHZ_USER, " + "ACCESS_TOKEN_SELECTED.TENANT_ID, USER_DOMAIN, TOKEN_SCOPE, TOKEN_STATE, REFRESH_TOKEN_TIME_CREATED," + " REFRESH_TOKEN_VALIDITY_PERIOD, ACCESS_TOKEN_SELECTED.TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM " + "(SELECT ACCESS_TOKEN, AUTHZ_USER, TENANT_ID, USER_DOMAIN, TOKEN_STATE, REFRESH_TOKEN_TIME_CREATED, " + "REFRESH_TOKEN_VALIDITY_PERIOD, TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM $accessTokenStoreTable " + "WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND " + "REFRESH_TOKEN = ? ORDER BY TIME_CREATED DESC LIMIT 1) ACCESS_TOKEN_SELECTED LEFT JOIN " + "IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON ACCESS_TOKEN_SELECTED.TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String RETRIEVE_ACCESS_TOKEN_VALIDATION_DATA_INFORMIX = "SELECT ACCESS_TOKEN, AUTHZ_USER, " + "ACCESS_TOKEN_SELECTED.TENANT_ID, USER_DOMAIN, TOKEN_SCOPE, TOKEN_STATE, REFRESH_TOKEN_TIME_CREATED, " + "REFRESH_TOKEN_VALIDITY_PERIOD, ACCESS_TOKEN_SELECTED.TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM ( " + "SELECT FIRST 1 ACCESS_TOKEN, AUTHZ_USER, TENANT_ID, USER_DOMAIN, TOKEN_STATE, REFRESH_TOKEN_TIME_CREATED, " + "REFRESH_TOKEN_VALIDITY_PERIOD, TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER FROM $accessTokenStoreTable " + "WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND REFRESH_TOKEN = ? " + "ORDER BY TIME_CREATED DESC) ACCESS_TOKEN_SELECTED LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON " + "ACCESS_TOKEN_SELECTED.TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String INSERT_OAUTH2_ACCESS_TOKEN = "INSERT INTO $accessTokenStoreTable (ACCESS_TOKEN, " + "REFRESH_TOKEN, CONSUMER_KEY_ID, AUTHZ_USER, TENANT_ID, USER_DOMAIN, TIME_CREATED, " + "REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, TOKEN_SCOPE_HASH, " + "TOKEN_STATE, USER_TYPE, TOKEN_ID, GRANT_TYPE, SUBJECT_IDENTIFIER) SELECT ?,?,ID,?,?,?,?,?,?,?,?,?,?,?,?," + "? FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY=?"; public static final String INSERT_OAUTH2_TOKEN_SCOPE = "INSERT INTO IDN_OAUTH2_ACCESS_TOKEN_SCOPE (TOKEN_ID, " + "TOKEN_SCOPE, TENANT_ID) VALUES (?,?,?)"; public static final String DELETE_ACCESS_TOKEN = "DELETE FROM $accessTokenStoreTable WHERE ACCESS_TOKEN = ? "; public static final String RETRIEVE_IOS_SCOPE_KEY = "SELECT IOS.SCOPE_KEY FROM IDN_OAUTH2_SCOPE IOS, " + "IDN_OAUTH2_RESOURCE_SCOPE IORS WHERE RESOURCE_PATH = ? AND IORS.SCOPE_ID = IOS.SCOPE_ID"; public static final String DELETE_USER_RPS = "DELETE FROM IDN_OPENID_USER_RPS WHERE USER_NAME = ? AND " + "RP_URL = ?"; public static final String DELETE_USER_RPS_IN_TENANT = "DELETE FROM IDN_OPENID_USER_RPS WHERE USER_NAME = ? AND " + "TENANT_ID=? AND RP_URL = ?"; public static final String UPDATE_TRUSTED_ALWAYS_IDN_OPENID_USER_RPS = "UPDATE IDN_OPENID_USER_RPS SET TRUSTED_ALWAYS=? " + "WHERE USER_NAME = ? AND TENANT_ID=? AND RP_URL = ?"; public static final String RENAME_USER_STORE_IN_ACCESS_TOKENS_TABLE = "UPDATE IDN_OAUTH2_ACCESS_TOKEN SET " + "USER_DOMAIN=? WHERE TENANT_ID=? AND USER_DOMAIN=?"; public static final String RENAME_USER_STORE_IN_AUTHORIZATION_CODES_TABLE = "UPDATE IDN_OAUTH2_AUTHORIZATION_CODE" + " SET USER_DOMAIN=? WHERE TENANT_ID=? AND USER_DOMAIN=?"; public static final String LIST_ALL_TOKENS_IN_TENANT = "SELECT ACCESS_TOKEN, REFRESH_TOKEN, " + "TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, " + "TOKEN_SCOPE, ACCESS_TOKEN_TABLE.TOKEN_ID, AUTHZ_USER, USER_DOMAIN, CONSUMER_KEY FROM (SELECT AUTHZ_USER," + " USER_DOMAIN, CONSUMER_KEY_ID, TOKEN_ID, ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, " + "REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE FROM " + "IDN_OAUTH2_ACCESS_TOKEN WHERE TENANT_ID=? AND (TOKEN_STATE='ACTIVE' OR TOKEN_STATE='EXPIRED')) " + "ACCESS_TOKEN_TABLE JOIN IDN_OAUTH_CONSUMER_APPS ON ID = CONSUMER_KEY_ID LEFT JOIN " + "IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON ACCESS_TOKEN_TABLE.TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String LIST_ALL_TOKENS_IN_USER_STORE = "SELECT ACCESS_TOKEN, REFRESH_TOKEN, " + "TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, " + "TOKEN_SCOPE, ACCESS_TOKEN_TABLE.TOKEN_ID, AUTHZ_USER, CONSUMER_KEY FROM (SELECT AUTHZ_USER, " + "CONSUMER_KEY_ID, TOKEN_ID, ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, " + "VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE FROM IDN_OAUTH2_ACCESS_TOKEN WHERE TENANT_ID=?" + " AND USER_DOMAIN=? AND (TOKEN_STATE='ACTIVE' OR TOKEN_STATE='EXPIRED')) ACCESS_TOKEN_TABLE JOIN " + "IDN_OAUTH_CONSUMER_APPS ON ID = CONSUMER_KEY_ID LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON " + "ACCESS_TOKEN_TABLE.TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; public static final String LIST_LATEST_AUTHZ_CODES_IN_USER_DOMAIN = "SELECT CODE_ID, AUTHORIZATION_CODE, " + "CONSUMER_KEY, IDN_OAUTH2_AUTHORIZATION_CODE.AUTHZ_USER, IDN_OAUTH2_AUTHORIZATION_CODE.SCOPE, " + "TIME_CREATED, VALIDITY_PERIOD, IDN_OAUTH2_AUTHORIZATION_CODE.CALLBACK_URL FROM (SELECT " + "AUTHZ_USER, CONSUMER_KEY_ID, SCOPE, MAX(TIME_CREATED) TIMES FROM IDN_OAUTH2_AUTHORIZATION_CODE WHERE " + "TENANT_ID=? AND USER_DOMAIN=? group by AUTHZ_USER, CONSUMER_KEY_ID, SCOPE) AUTHZ_SELECTED JOIN " + "IDN_OAUTH2_AUTHORIZATION_CODE ON AUTHZ_SELECTED.AUTHZ_USER=IDN_OAUTH2_AUTHORIZATION_CODE.AUTHZ_USER " + "AND AUTHZ_SELECTED.CONSUMER_KEY_ID=IDN_OAUTH2_AUTHORIZATION_CODE.CONSUMER_KEY_ID AND AUTHZ_SELECTED" + ".TIMES=IDN_OAUTH2_AUTHORIZATION_CODE.TIME_CREATED AND AUTHZ_SELECTED.SCOPE=IDN_OAUTH2_AUTHORIZATION_CODE" + ".SCOPE JOIN IDN_OAUTH_CONSUMER_APPS ON IDN_OAUTH2_AUTHORIZATION_CODE.CONSUMER_KEY_ID = ID WHERE " + "STATE='ACTIVE'"; public static final String LIST_LATEST_AUTHZ_CODES_IN_TENANT = "SELECT CODE_ID, AUTHORIZATION_CODE, " + "CONSUMER_KEY, IDN_OAUTH2_AUTHORIZATION_CODE.AUTHZ_USER, IDN_OAUTH2_AUTHORIZATION_CODE.SCOPE, " + "TIME_CREATED, VALIDITY_PERIOD, IDN_OAUTH2_AUTHORIZATION_CODE.CALLBACK_URL, IDN_OAUTH2_AUTHORIZATION_CODE" + ".USER_DOMAIN FROM (SELECT AUTHZ_USER, USER_DOMAIN, CONSUMER_KEY_ID, SCOPE, MAX(TIME_CREATED) TIMES " + "FROM IDN_OAUTH2_AUTHORIZATION_CODE WHERE TENANT_ID=? group by AUTHZ_USER, " + "USER_DOMAIN, CONSUMER_KEY_ID, SCOPE) AUTHZ_SELECTED JOIN IDN_OAUTH2_AUTHORIZATION_CODE ON " + "AUTHZ_SELECTED.AUTHZ_USER=IDN_OAUTH2_AUTHORIZATION_CODE.AUTHZ_USER AND AUTHZ_SELECTED" + ".CONSUMER_KEY_ID=IDN_OAUTH2_AUTHORIZATION_CODE.CONSUMER_KEY_ID AND AUTHZ_SELECTED" + ".TIMES=IDN_OAUTH2_AUTHORIZATION_CODE.TIME_CREATED AND AUTHZ_SELECTED" + ".USER_DOMAIN=IDN_OAUTH2_AUTHORIZATION_CODE.USER_DOMAIN AND AUTHZ_SELECTED" + ".SCOPE=IDN_OAUTH2_AUTHORIZATION_CODE.SCOPE JOIN IDN_OAUTH_CONSUMER_APPS ON IDN_OAUTH2_AUTHORIZATION_CODE" + ".CONSUMER_KEY_ID = ID WHERE STATE='ACTIVE'"; public static final String RETRIEVE_ROLES_OF_SCOPE = "SELECT IOS.ROLES FROM IDN_OAUTH2_SCOPE IOS WHERE SCOPE_KEY" + " = ?"; public static final String RETRIEVE_PKCE_TABLE_MYSQL = "SELECT PKCE_MANDATORY, PKCE_SUPPORT_PLAIN FROM " + "IDN_OAUTH_CONSUMER_APPS LIMIT 1"; public static final String RETRIEVE_PKCE_TABLE_DB2SQL = "SELECT PKCE_MANDATORY, PKCE_SUPPORT_PLAIN FROM " + "IDN_OAUTH_CONSUMER_APPS FETCH FIRST 1 ROWS ONLY"; public static final String RETRIEVE_PKCE_TABLE_MSSQL = "SELECT TOP 1 PKCE_MANDATORY, PKCE_SUPPORT_PLAIN FROM " + "IDN_OAUTH_CONSUMER_APPS"; public static final String RETRIEVE_PKCE_TABLE_INFORMIX = "SELECT FIRST 1 PKCE_MANDATORY, PKCE_SUPPORT_PLAIN FROM " + "IDN_OAUTH_CONSUMER_APPS"; public static final String RETRIEVE_PKCE_TABLE_ORACLE = "SELECT PKCE_MANDATORY, PKCE_SUPPORT_PLAIN FROM " + "IDN_OAUTH_CONSUMER_APPS WHERE ROWNUM < 2"; //Retrieve latest active token public static final String RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_MYSQL = "SELECT " + "ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN " + "WHERE CONSUMER_KEY_ID =(SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=? " + "AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND TOKEN_STATE='ACTIVE' ORDER BY TIME_CREATED " + "DESC LIMIT 1"; public static final String RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_ORACLE = "SELECT * FROM " + "(SELECT ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM " + "IDN_OAUTH2_ACCESS_TOKEN WHERE CONSUMER_KEY_ID=(SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY" + " = ?) AND AUTHZ_USER=? AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND TOKEN_STATE='ACTIVE'" + " ORDER BY TIME_CREATED DESC) WHERE ROWNUM < 2 "; public static final String RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_DB2SQL = "SELECT " + "ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN " + "WHERE CONSUMER_KEY_ID= (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=? " + "AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND TOKEN_STATE='ACTIVE' ORDER BY TIME_CREATED " + "DESC FETCH FIRST 1 ROWS ONLY"; public static final String RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_MSSQL = "SELECT TOP 1 " + "ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN " + "WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=?" + " AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND TOKEN_STATE='ACTIVE' ORDER BY TIME_CREATED" + " DESC"; public static final String RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_POSTGRESQL = "SELECT * " + "FROM (SELECT ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN " + "WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=?" + " AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND TOKEN_STATE='ACTIVE' ORDER BY TIME_CREATED" + " DESC) TOKEN LIMIT 1 "; public static final String RETRIEVE_LATEST_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_INFORMIX = "SELECT FIRST 1" + " * FROM (SELECT ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM " + "IDN_OAUTH2_ACCESS_TOKEN WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE " + "CONSUMER_KEY = ?) AND AUTHZ_USER=? AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND " + "TOKEN_STATE='ACTIVE' ORDER BY TIME_CREATED DESC) TOKEN "; //Retrieve latest non-active token public static final String RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_MYSQL = "SELECT " + "ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN " + "WHERE CONSUMER_KEY_ID =(SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=? " + "AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND TOKEN_STATE!='ACTIVE' ORDER BY TIME_CREATED" + " DESC LIMIT 1"; public static final String RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_ORACLE = "SELECT * FROM " + "(SELECT ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM " + "IDN_OAUTH2_ACCESS_TOKEN WHERE CONSUMER_KEY_ID=(SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY" + " = ?) AND AUTHZ_USER=? AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND " + "TOKEN_STATE!='ACTIVE' ORDER BY TIME_CREATED DESC) WHERE ROWNUM < 2 "; public static final String RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_DB2SQL = "SELECT " + "ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN " + "WHERE CONSUMER_KEY_ID= (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=? " + "AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND TOKEN_STATE!='ACTIVE' ORDER BY TIME_CREATED" + " DESC FETCH FIRST 1 ROWS ONLY"; public static final String RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_MSSQL = "SELECT TOP 1 " + "ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN " + "WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=?" + " AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND TOKEN_STATE!='ACTIVE' ORDER BY " + "TIME_CREATED DESC"; public static final String RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_POSTGRESQL = "SELECT * " + "FROM (SELECT ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM IDN_OAUTH2_ACCESS_TOKEN " + "WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE CONSUMER_KEY = ?) AND AUTHZ_USER=?" + " AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND TOKEN_STATE!='ACTIVE' ORDER BY " + "TIME_CREATED DESC) TOKEN LIMIT 1 "; public static final String RETRIEVE_LATEST_NON_ACTIVE_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_INFORMIX = "SELECT FIRST 1" + " * FROM (SELECT ACCESS_TOKEN, REFRESH_TOKEN, TIME_CREATED, REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, " + "REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, TOKEN_ID, SUBJECT_IDENTIFIER FROM " + "IDN_OAUTH2_ACCESS_TOKEN WHERE CONSUMER_KEY_ID = (SELECT ID FROM IDN_OAUTH_CONSUMER_APPS WHERE " + "CONSUMER_KEY = ?) AND AUTHZ_USER=? AND TENANT_ID=? AND USER_DOMAIN=? AND TOKEN_SCOPE_HASH=? AND " + "TOKEN_STATE!='ACTIVE' ORDER BY TIME_CREATED DESC) TOKEN "; private SQLQueries() { } }
IDENTITY-5552: Error while getting the oath2 open-id access token with oracle db
components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/dao/SQLQueries.java
IDENTITY-5552: Error while getting the oath2 open-id access token with oracle db
<ide><path>omponents/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/dao/SQLQueries.java <ide> + "SUBJECT_IDENTIFIER FROM (SELECT TOKEN_ID, CONSUMER_KEY, AUTHZ_USER, IDN_OAUTH2_ACCESS_TOKEN.TENANT_ID AS TENANT_ID, " <ide> + "IDN_OAUTH2_ACCESS_TOKEN.USER_DOMAIN AS USER_DOMAIN,TIME_CREATED," <ide> + "REFRESH_TOKEN_TIME_CREATED, VALIDITY_PERIOD, REFRESH_TOKEN_VALIDITY_PERIOD, USER_TYPE, REFRESH_TOKEN, IDN_OAUTH2_ACCESS_TOKEN.GRANT_TYPE AS GRANT_TYPE," <del> + "SUBJECT_IDENTIFIER FROM (SELECT * FROM IDN_OAUTH2_ACCESS_TOKEN WHERE ACCESS_TOKEN=? AND TOKEN_STATE='ACTIVE') AS IDN_OAUTH2_ACCESS_TOKEN " <del> +"JOIN IDN_OAUTH_CONSUMER_APPS ON CONSUMER_KEY_ID = ID) AS ACCESS_TOKEN_TABLE" <add> + "SUBJECT_IDENTIFIER FROM (SELECT * FROM IDN_OAUTH2_ACCESS_TOKEN WHERE ACCESS_TOKEN=? AND TOKEN_STATE='ACTIVE') IDN_OAUTH2_ACCESS_TOKEN " <add> +"JOIN IDN_OAUTH_CONSUMER_APPS ON CONSUMER_KEY_ID = ID) ACCESS_TOKEN_TABLE" <ide> +" LEFT JOIN IDN_OAUTH2_ACCESS_TOKEN_SCOPE ON ACCESS_TOKEN_TABLE.TOKEN_ID = IDN_OAUTH2_ACCESS_TOKEN_SCOPE.TOKEN_ID"; <ide> <ide> // public static final String RETRIEVE_ACTIVE_ACCESS_TOKEN = "SELECT CONSUMER_KEY, AUTHZ_USER, ACCESS_TOKEN_TABLE" +
Java
lgpl-2.1
0848e2b0b78789a988e424e818acfba0048f044d
0
pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * 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.xwiki.rendering.internal.macro.velocity; import java.io.StringWriter; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.apache.commons.lang3.StringUtils; import org.apache.velocity.VelocityContext; import org.slf4j.Logger; import org.xwiki.component.annotation.Component; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.rendering.macro.MacroExecutionException; import org.xwiki.rendering.macro.descriptor.DefaultContentDescriptor; import org.xwiki.rendering.macro.script.AbstractScriptMacro; import org.xwiki.rendering.macro.velocity.VelocityMacroConfiguration; import org.xwiki.rendering.macro.velocity.VelocityMacroParameters; import org.xwiki.rendering.macro.velocity.filter.VelocityMacroFilter; import org.xwiki.rendering.transformation.MacroTransformationContext; import org.xwiki.velocity.VelocityManager; import org.xwiki.velocity.XWikiVelocityException; /** * Executes <a href="http://velocity.apache.org/">Velocity</a> on the content of this macro and optionally parse the * resulting content with a wiki syntax parser. * * @version $Id$ * @since 1.5M2 */ @Component @Named("velocity") @Singleton public class VelocityMacro extends AbstractScriptMacro<VelocityMacroParameters> { /** * The description of the macro. */ private static final String DESCRIPTION = "Executes a Velocity script."; /** * The description of the macro content. */ private static final String CONTENT_DESCRIPTION = "the velocity script to execute"; /** * Used to get the Velocity Engine and Velocity Context to use to evaluate the passed Velocity script. */ @Inject private VelocityManager velocityManager; /** * The velocity macro configuration. */ @Inject private VelocityMacroConfiguration configuration; /** * The logger to log. */ @Inject private Logger logger; /** * Default constructor. */ public VelocityMacro() { super("Velocity", DESCRIPTION, new DefaultContentDescriptor(CONTENT_DESCRIPTION), VelocityMacroParameters.class); } @Override public boolean supportsInlineMode() { return true; } @Override protected String evaluateString(VelocityMacroParameters parameters, String content, MacroTransformationContext context) throws MacroExecutionException { String result = ""; try { VelocityContext velocityContext = this.velocityManager.getVelocityContext(); VelocityMacroFilter filter = getFilter(parameters); String cleanedContent = content; if (filter != null) { cleanedContent = filter.before(cleanedContent, velocityContext); } StringWriter writer = new StringWriter(); // Use the Transformation id as the name passed to the Velocity Engine. This name is used internally // by Velocity as a cache index key for caching macros. String key = context.getTransformationContext().getId(); if (key == null) { key = "unknown namespace"; } this.velocityManager.getVelocityEngine().evaluate(velocityContext, writer, key, cleanedContent); result = writer.toString(); if (filter != null) { result = filter.after(result, velocityContext); } } catch (XWikiVelocityException e) { throw new MacroExecutionException("Failed to evaluate Velocity Macro for content [" + content + "]", e); } return result; } /** * @param parameters the velocity macros parameters * @return the velocity content filter * @since 2.0M1 */ private VelocityMacroFilter getFilter(VelocityMacroParameters parameters) { String filterName = parameters.getFilter(); if (StringUtils.isEmpty(filterName)) { filterName = this.configuration.getFilter(); if (StringUtils.isEmpty(filterName)) { filterName = null; } } VelocityMacroFilter filter = null; if (filterName != null) { try { filter = getComponentManager().getInstance(VelocityMacroFilter.class, filterName); } catch (ComponentLookupException e) { this.logger.error("Can't find velocity macro filter", e); } } return filter; } }
xwiki-platform-core/xwiki-platform-rendering/xwiki-platform-rendering-macros/xwiki-platform-rendering-macro-velocity/src/main/java/org/xwiki/rendering/internal/macro/velocity/VelocityMacro.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * 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.xwiki.rendering.internal.macro.velocity; import java.io.StringWriter; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.apache.commons.lang3.StringUtils; import org.apache.velocity.VelocityContext; import org.slf4j.Logger; import org.xwiki.component.annotation.Component; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.rendering.macro.MacroExecutionException; import org.xwiki.rendering.macro.descriptor.DefaultContentDescriptor; import org.xwiki.rendering.macro.script.AbstractScriptMacro; import org.xwiki.rendering.macro.velocity.VelocityMacroConfiguration; import org.xwiki.rendering.macro.velocity.VelocityMacroParameters; import org.xwiki.rendering.macro.velocity.filter.VelocityMacroFilter; import org.xwiki.rendering.transformation.MacroTransformationContext; import org.xwiki.velocity.VelocityManager; import org.xwiki.velocity.XWikiVelocityException; /** * Executes <a href="http://velocity.apache.org/">Velocity</a> on the content of this macro and optionally parse the * resulting content with a wiki syntax parser. * * @version $Id$ * @since 1.5M2 */ @Component @Named("velocity") @Singleton public class VelocityMacro extends AbstractScriptMacro<VelocityMacroParameters> { /** * The description of the macro. */ private static final String DESCRIPTION = "Executes a Velocity script."; /** * The description of the macro content. */ private static final String CONTENT_DESCRIPTION = "the velocity script to execute"; /** * Used to get the Velocity Engine and Velocity Context to use to evaluate the passed Velocity script. */ @Inject private VelocityManager velocityManager; /** * The velocity macro configuration. */ @Inject private VelocityMacroConfiguration configuration; /** * The logger to log. */ @Inject private Logger logger; /** * Default constructor. */ public VelocityMacro() { super("Velocity", DESCRIPTION, new DefaultContentDescriptor(CONTENT_DESCRIPTION), VelocityMacroParameters.class); } @Override public boolean supportsInlineMode() { return true; } @Override protected String evaluateString(VelocityMacroParameters parameters, String content, MacroTransformationContext context) throws MacroExecutionException { String result = ""; try { VelocityContext velocityContext = this.velocityManager.getVelocityContext(); VelocityMacroFilter filter = getFilter(parameters); String cleanedContent = content; if (filter != null) { cleanedContent = filter.before(cleanedContent, velocityContext); } StringWriter writer = new StringWriter(); // Use the Transformation id as the name passed to the Velocity Engine. This name is used internally // by Velocity as a cache index key for caching macros. String key = context.getTransformationContext().getId(); if (key == null) { key = "unknown namespace"; } this.velocityManager.getVelocityEngine().evaluate(velocityContext, writer, key, cleanedContent); result = writer.toString(); if (filter != null) { result = filter.after(result, velocityContext); } } catch (XWikiVelocityException e) { throw new MacroExecutionException("Failed to evaluate Velocity Macro for content [" + content + "]", e); } return result; } /** * @param parameters the velocity macros parameters * @return the velocity content filter * @since 2.0M1 */ private VelocityMacroFilter getFilter(VelocityMacroParameters parameters) { String filterName = parameters.getFilter(); if (StringUtils.isEmpty(filterName)) { filterName = this.configuration.getFilter(); if (StringUtils.isEmpty(filterName)) { filterName = null; } } VelocityMacroFilter filter = null; if (filterName != null) { try { filter = getComponentManager().getInstance(VelocityMacroFilter.class, filterName); } catch (ComponentLookupException e) { this.logger.error("Can't find velocity maco cleaner", e); } } return filter; } }
[misc] Fix typo
xwiki-platform-core/xwiki-platform-rendering/xwiki-platform-rendering-macros/xwiki-platform-rendering-macro-velocity/src/main/java/org/xwiki/rendering/internal/macro/velocity/VelocityMacro.java
[misc] Fix typo
<ide><path>wiki-platform-core/xwiki-platform-rendering/xwiki-platform-rendering-macros/xwiki-platform-rendering-macro-velocity/src/main/java/org/xwiki/rendering/internal/macro/velocity/VelocityMacro.java <ide> try { <ide> filter = getComponentManager().getInstance(VelocityMacroFilter.class, filterName); <ide> } catch (ComponentLookupException e) { <del> this.logger.error("Can't find velocity maco cleaner", e); <add> this.logger.error("Can't find velocity macro filter", e); <ide> } <ide> } <ide>
Java
apache-2.0
a95ca717eb45aae68f5e5f62d542d63151cc972a
0
pushyamig/sakai,duke-compsci290-spring2016/sakai,kingmook/sakai,frasese/sakai,udayg/sakai,rodriguezdevera/sakai,pushyamig/sakai,hackbuteer59/sakai,duke-compsci290-spring2016/sakai,wfuedu/sakai,colczr/sakai,ktakacs/sakai,clhedrick/sakai,wfuedu/sakai,zqian/sakai,whumph/sakai,udayg/sakai,Fudan-University/sakai,lorenamgUMU/sakai,tl-its-umich-edu/sakai,ouit0408/sakai,joserabal/sakai,wfuedu/sakai,lorenamgUMU/sakai,whumph/sakai,udayg/sakai,Fudan-University/sakai,Fudan-University/sakai,conder/sakai,OpenCollabZA/sakai,hackbuteer59/sakai,noondaysun/sakai,wfuedu/sakai,kwedoff1/sakai,wfuedu/sakai,colczr/sakai,noondaysun/sakai,whumph/sakai,frasese/sakai,whumph/sakai,rodriguezdevera/sakai,kingmook/sakai,bzhouduke123/sakai,noondaysun/sakai,duke-compsci290-spring2016/sakai,hackbuteer59/sakai,willkara/sakai,bzhouduke123/sakai,introp-software/sakai,ouit0408/sakai,conder/sakai,conder/sakai,udayg/sakai,clhedrick/sakai,willkara/sakai,frasese/sakai,willkara/sakai,puramshetty/sakai,Fudan-University/sakai,tl-its-umich-edu/sakai,wfuedu/sakai,wfuedu/sakai,pushyamig/sakai,rodriguezdevera/sakai,liubo404/sakai,ouit0408/sakai,buckett/sakai-gitflow,joserabal/sakai,ktakacs/sakai,kwedoff1/sakai,liubo404/sakai,surya-janani/sakai,noondaysun/sakai,bzhouduke123/sakai,kwedoff1/sakai,ktakacs/sakai,zqian/sakai,noondaysun/sakai,puramshetty/sakai,clhedrick/sakai,pushyamig/sakai,kwedoff1/sakai,pushyamig/sakai,Fudan-University/sakai,tl-its-umich-edu/sakai,udayg/sakai,ouit0408/sakai,lorenamgUMU/sakai,clhedrick/sakai,pushyamig/sakai,conder/sakai,frasese/sakai,ouit0408/sakai,hackbuteer59/sakai,joserabal/sakai,rodriguezdevera/sakai,OpenCollabZA/sakai,clhedrick/sakai,willkara/sakai,colczr/sakai,colczr/sakai,udayg/sakai,bzhouduke123/sakai,buckett/sakai-gitflow,pushyamig/sakai,puramshetty/sakai,liubo404/sakai,joserabal/sakai,OpenCollabZA/sakai,bkirschn/sakai,Fudan-University/sakai,OpenCollabZA/sakai,duke-compsci290-spring2016/sakai,duke-compsci290-spring2016/sakai,noondaysun/sakai,whumph/sakai,frasese/sakai,willkara/sakai,conder/sakai,duke-compsci290-spring2016/sakai,surya-janani/sakai,conder/sakai,tl-its-umich-edu/sakai,puramshetty/sakai,zqian/sakai,willkara/sakai,liubo404/sakai,conder/sakai,willkara/sakai,rodriguezdevera/sakai,puramshetty/sakai,bzhouduke123/sakai,kwedoff1/sakai,lorenamgUMU/sakai,ouit0408/sakai,ktakacs/sakai,zqian/sakai,liubo404/sakai,introp-software/sakai,zqian/sakai,noondaysun/sakai,hackbuteer59/sakai,bzhouduke123/sakai,surya-janani/sakai,rodriguezdevera/sakai,tl-its-umich-edu/sakai,introp-software/sakai,bkirschn/sakai,kwedoff1/sakai,bkirschn/sakai,surya-janani/sakai,ktakacs/sakai,tl-its-umich-edu/sakai,colczr/sakai,puramshetty/sakai,clhedrick/sakai,buckett/sakai-gitflow,pushyamig/sakai,liubo404/sakai,kingmook/sakai,surya-janani/sakai,bzhouduke123/sakai,introp-software/sakai,kwedoff1/sakai,introp-software/sakai,colczr/sakai,rodriguezdevera/sakai,ouit0408/sakai,colczr/sakai,frasese/sakai,kingmook/sakai,OpenCollabZA/sakai,zqian/sakai,hackbuteer59/sakai,colczr/sakai,kingmook/sakai,OpenCollabZA/sakai,ouit0408/sakai,buckett/sakai-gitflow,whumph/sakai,buckett/sakai-gitflow,OpenCollabZA/sakai,udayg/sakai,tl-its-umich-edu/sakai,willkara/sakai,bkirschn/sakai,zqian/sakai,rodriguezdevera/sakai,introp-software/sakai,joserabal/sakai,frasese/sakai,udayg/sakai,surya-janani/sakai,puramshetty/sakai,lorenamgUMU/sakai,ktakacs/sakai,lorenamgUMU/sakai,introp-software/sakai,wfuedu/sakai,whumph/sakai,liubo404/sakai,duke-compsci290-spring2016/sakai,buckett/sakai-gitflow,kingmook/sakai,Fudan-University/sakai,joserabal/sakai,frasese/sakai,clhedrick/sakai,noondaysun/sakai,Fudan-University/sakai,kwedoff1/sakai,lorenamgUMU/sakai,lorenamgUMU/sakai,introp-software/sakai,bkirschn/sakai,hackbuteer59/sakai,hackbuteer59/sakai,puramshetty/sakai,kingmook/sakai,OpenCollabZA/sakai,surya-janani/sakai,whumph/sakai,duke-compsci290-spring2016/sakai,ktakacs/sakai,joserabal/sakai,bkirschn/sakai,surya-janani/sakai,bkirschn/sakai,conder/sakai,buckett/sakai-gitflow,ktakacs/sakai,joserabal/sakai,buckett/sakai-gitflow,tl-its-umich-edu/sakai,bkirschn/sakai,zqian/sakai,liubo404/sakai,kingmook/sakai,bzhouduke123/sakai,clhedrick/sakai
/********************************************************************************** * $URL: https://source.sakaiproject.org/svn/sam/trunk/component/src/java/org/sakaiproject/tool/assessment/integration/helper/integrated/SectionAwareServiceHelperImpl.java $ * $Id: SectionAwareServiceHelperImpl.java 9273 2006-05-10 22:34:28Z [email protected] $ *********************************************************************************** * * Copyright (c) 2004, 2005, 2006, 2008, 2009 The Sakai 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.osedu.org/licenses/ECL-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.sakaiproject.tool.assessment.integration.helper.integrated; import java.util.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.section.api.SectionAwareness; import org.sakaiproject.section.api.coursemanagement.CourseSection; import org.sakaiproject.section.api.coursemanagement.EnrollmentRecord; import org.sakaiproject.section.api.facade.Role; import org.sakaiproject.site.api.Group; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.cover.SiteService; import org.sakaiproject.tool.assessment.facade.AgentFacade; import org.sakaiproject.tool.assessment.integration.helper.ifc.SectionAwareServiceHelper; import org.sakaiproject.tool.assessment.integration.helper.integrated.FacadeUtils; import org.sakaiproject.tool.assessment.services.PersistenceService; /** * An implementation of Samigo-specific authorization (based on Gradebook's) needs based * on the shared Section Awareness API. */ public class SectionAwareServiceHelperImpl extends AbstractSectionsImpl implements SectionAwareServiceHelper { private static final Log log = LogFactory.getLog(SectionAwareServiceHelperImpl.class); public boolean isUserAbleToGrade(String siteid, String userUid) { return (getSectionAwareness().isSiteMemberInRole(siteid, userUid, Role.INSTRUCTOR) || getSectionAwareness().isSiteMemberInRole(siteid, userUid, Role.TA)); } public boolean isUserAbleToGradeAll(String siteid, String userUid) { return getSectionAwareness().isSiteMemberInRole(siteid, userUid, Role.INSTRUCTOR); } public boolean isUserAbleToGradeSection(String sectionUid, String userUid) { return getSectionAwareness().isSectionMemberInRole(sectionUid, userUid, Role.TA); } public boolean isUserAbleToEdit(String siteid, String userUid) { return getSectionAwareness().isSiteMemberInRole(siteid, userUid, Role.INSTRUCTOR); } public boolean isUserGradable(String siteid, String userUid) { return getSectionAwareness().isSiteMemberInRole(siteid, userUid, Role.STUDENT); } /** */ public List getAvailableEnrollments(String siteid, String userUid) { List enrollments; if ("-1".equals(userUid) || isUserAbleToGradeAll(siteid, userUid)) { enrollments = getSectionAwareness().getSiteMembersInRole(siteid, Role.STUDENT); } else { // We use a map because we may have duplicate students among the section // participation records. Map enrollmentMap = new HashMap(); List sections = getAvailableSections(siteid, userUid); for (Iterator iter = sections.iterator(); iter.hasNext(); ) { CourseSection section = (CourseSection)iter.next(); List sectionEnrollments = getSectionEnrollmentsTrusted(section.getUuid(), userUid); for (Iterator eIter = sectionEnrollments.iterator(); eIter.hasNext(); ) { EnrollmentRecord enr = (EnrollmentRecord)eIter.next(); enrollmentMap.put(enr.getUser().getUserUid(), enr); } } enrollments = new ArrayList(enrollmentMap.values()); } return enrollments; } /** * added by gopalrc - Jan 2008 * @param siteid * @param userUid * @return */ public List getGroupReleaseEnrollments(String siteid, String userUid, String publishedAssessmentId) { List availEnrollments = getAvailableEnrollments(siteid, userUid); List enrollments = new ArrayList(); HashSet<String> membersInReleaseGroups = new HashSet<String>(0); try { Set<String> availableEnrollments = new HashSet<String>(availEnrollments); Site site = siteService.getInstance().getSite(siteid); // this follows the way the service is already written but it is a bad practice membersInReleaseGroups = new HashSet<String>( site.getMembersInGroups(availableEnrollments) ); } catch (IdUnusedException ex) { // no site found, just log a warning log.warn("Unable to find a site with id ("+siteid+") in order to get the enrollments, will return 0 enrollments"); } for (Iterator eIter = availEnrollments.iterator(); eIter.hasNext(); ) { EnrollmentRecord enr = (EnrollmentRecord)eIter.next(); if (membersInReleaseGroups.contains( enr.getUser().getUserUid())) { enrollments.add(enr); } } return enrollments; } /** * added by gopalrc - Jan 2008 */ private SiteService siteService; public void setSiteService(SiteService siteService) { this.siteService = siteService; } /** * added by gopalrc - Jan 2008 * @param userId * @param siteId * @return */ private boolean isUserInReleaseGroup(String userId, String siteId, String publishedAssessmentId) { //String functionName="assessment.takeAssessment"; Collection siteGroups = null; try { siteGroups = siteService.getSite(siteId).getGroupsWithMember(userId); } catch (IdUnusedException ex) { // no site found } List releaseGroupIds = PersistenceService.getInstance() .getPublishedAssessmentFacadeQueries() .getReleaseToGroupIdsForPublishedAssessment(publishedAssessmentId); if (siteGroups == null) { return false; } Iterator groupsIter = siteGroups.iterator(); while (groupsIter.hasNext()) { Group group = (Group) groupsIter.next(); for (Iterator releaseGroupIdsIter = releaseGroupIds.iterator(); releaseGroupIdsIter.hasNext();) { //if this group is a release group if (group.getId().equals((String)releaseGroupIdsIter.next())) { return true; } } } return false; } public List getAvailableSections(String siteid, String userUid) { List availableSections = new ArrayList(); SectionAwareness sectionAwareness = getSectionAwareness(); if (sectionAwareness ==null) { } else { // Get the list of sections. For now, just use whatever default // sorting we get from the Section Awareness component. /* List sectionCategories = sectionAwareness.getSectionCategories(siteid); for (Iterator catIter = sectionCategories.iterator(); catIter.hasNext(); ) { String category = (String)catIter.next(); List sections = sectionAwareness.getSectionsInCategory(siteid, category); for (Iterator iter = sections.iterator(); iter.hasNext(); ) { CourseSection section = (CourseSection)iter.next(); if (isUserAbleToGradeAll(siteid, userUid) || isUserAbleToGradeSection(section.getUuid(), userUid)) { availableSections.add(section); } } } */ List sections = sectionAwareness.getSections(siteid); for (Iterator iter = sections.iterator(); iter.hasNext(); ) { CourseSection section = (CourseSection)iter.next(); // if (isUserAbleToGradeAll(gradebookUid) || isUserAbleToGradeSection(section.getUuid())) { if (isUserAbleToGradeAll(siteid, userUid) || isUserAbleToGradeSection(section.getUuid(), userUid)) { availableSections.add(section); } } } return availableSections; } public List getSectionEnrollmentsTrusted(String sectionUid) { return getSectionEnrollmentsTrusted(sectionUid, null); } private List getSectionEnrollmentsTrusted(String sectionUid, String userUid) { return getSectionAwareness().getSectionMembersInRole(sectionUid, Role.STUDENT); } public List getSectionEnrollments(String siteid, String sectionUid, String userUid) { List enrollments; if (isUserAbleToGradeAll(siteid, userUid) || isUserAbleToGradeSection(sectionUid, userUid)) { enrollments = getSectionEnrollmentsTrusted(sectionUid, userUid); } else { enrollments = new ArrayList(); log.warn("getSectionEnrollments for sectionUid=" + sectionUid + " called by unauthorized userUid=" + userUid); } return enrollments; } public List findMatchingEnrollments(String siteid, String searchString, String optionalSectionUid, String userUid) { List enrollments; List allEnrollmentsFilteredBySearch = getSectionAwareness().findSiteMembersInRole(siteid, Role.STUDENT, searchString); if (allEnrollmentsFilteredBySearch.isEmpty() || ((optionalSectionUid == null) && isUserAbleToGradeAll(siteid, userUid))) { enrollments = allEnrollmentsFilteredBySearch; } else { if (optionalSectionUid == null) { enrollments = getAvailableEnrollments(siteid, userUid); } else { // The user has selected a particular section. enrollments = getSectionEnrollments(siteid, optionalSectionUid, userUid); } Set availableStudentUids = FacadeUtils.getStudentUids(enrollments); enrollments = new ArrayList(); for (Iterator iter = allEnrollmentsFilteredBySearch.iterator(); iter.hasNext(); ) { EnrollmentRecord enr = (EnrollmentRecord)iter.next(); if (availableStudentUids.contains(enr.getUser().getUserUid())) { enrollments.add(enr); } } } return enrollments; } public boolean isSectionMemberInRoleStudent(String sectionId, String studentId) { return getSectionAwareness().isSectionMemberInRole(sectionId, studentId, Role.STUDENT); } }
samigo/samigo-services/src/java/org/sakaiproject/tool/assessment/integration/helper/integrated/SectionAwareServiceHelperImpl.java
/********************************************************************************** * $URL: https://source.sakaiproject.org/svn/sam/trunk/component/src/java/org/sakaiproject/tool/assessment/integration/helper/integrated/SectionAwareServiceHelperImpl.java $ * $Id: SectionAwareServiceHelperImpl.java 9273 2006-05-10 22:34:28Z [email protected] $ *********************************************************************************** * * Copyright (c) 2004, 2005, 2006, 2008, 2009 The Sakai 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.osedu.org/licenses/ECL-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.sakaiproject.tool.assessment.integration.helper.integrated; import java.util.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.authz.cover.SecurityService; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.section.api.SectionAwareness; import org.sakaiproject.section.api.coursemanagement.CourseSection; import org.sakaiproject.section.api.coursemanagement.EnrollmentRecord; import org.sakaiproject.section.api.facade.Role; import org.sakaiproject.site.api.Group; import org.sakaiproject.site.cover.SiteService; import org.sakaiproject.tool.assessment.facade.AgentFacade; import org.sakaiproject.tool.assessment.integration.helper.ifc.SectionAwareServiceHelper; import org.sakaiproject.tool.assessment.integration.helper.integrated.FacadeUtils; import org.sakaiproject.tool.assessment.services.PersistenceService; /** * An implementation of Samigo-specific authorization (based on Gradebook's) needs based * on the shared Section Awareness API. */ public class SectionAwareServiceHelperImpl extends AbstractSectionsImpl implements SectionAwareServiceHelper { private static final Log log = LogFactory.getLog(SectionAwareServiceHelperImpl.class); public boolean isUserAbleToGrade(String siteid, String userUid) { return (getSectionAwareness().isSiteMemberInRole(siteid, userUid, Role.INSTRUCTOR) || getSectionAwareness().isSiteMemberInRole(siteid, userUid, Role.TA)); } public boolean isUserAbleToGradeAll(String siteid, String userUid) { return getSectionAwareness().isSiteMemberInRole(siteid, userUid, Role.INSTRUCTOR); } public boolean isUserAbleToGradeSection(String sectionUid, String userUid) { return getSectionAwareness().isSectionMemberInRole(sectionUid, userUid, Role.TA); } public boolean isUserAbleToEdit(String siteid, String userUid) { return getSectionAwareness().isSiteMemberInRole(siteid, userUid, Role.INSTRUCTOR); } public boolean isUserGradable(String siteid, String userUid) { return getSectionAwareness().isSiteMemberInRole(siteid, userUid, Role.STUDENT); } /** */ public List getAvailableEnrollments(String siteid, String userUid) { List enrollments; if ("-1".equals(userUid) || isUserAbleToGradeAll(siteid, userUid)) { enrollments = getSectionAwareness().getSiteMembersInRole(siteid, Role.STUDENT); } else { // We use a map because we may have duplicate students among the section // participation records. Map enrollmentMap = new HashMap(); List sections = getAvailableSections(siteid, userUid); for (Iterator iter = sections.iterator(); iter.hasNext(); ) { CourseSection section = (CourseSection)iter.next(); List sectionEnrollments = getSectionEnrollmentsTrusted(section.getUuid(), userUid); for (Iterator eIter = sectionEnrollments.iterator(); eIter.hasNext(); ) { EnrollmentRecord enr = (EnrollmentRecord)eIter.next(); enrollmentMap.put(enr.getUser().getUserUid(), enr); } } enrollments = new ArrayList(enrollmentMap.values()); } return enrollments; } /** * added by gopalrc - Jan 2008 * @param siteid * @param userUid * @return */ public List getGroupReleaseEnrollments(String siteid, String userUid, String publishedAssessmentId) { List availEnrollments = getAvailableEnrollments(siteid, userUid); List enrollments = new ArrayList(); for (Iterator eIter = availEnrollments.iterator(); eIter.hasNext(); ) { EnrollmentRecord enr = (EnrollmentRecord)eIter.next(); if (isUserInReleaseGroup(enr.getUser().getUserUid(), AgentFacade.getCurrentSiteId(), publishedAssessmentId)) { enrollments.add(enr); } } return enrollments; } /** * added by gopalrc - Jan 2008 */ private SiteService siteService; public void setSiteService(SiteService siteService) { this.siteService = siteService; } /** * added by gopalrc - Jan 2008 * @param userId * @param siteId * @return */ private boolean isUserInReleaseGroup(String userId, String siteId, String publishedAssessmentId) { //String functionName="assessment.takeAssessment"; Collection siteGroups = null; try { siteGroups = siteService.getSite(siteId).getGroupsWithMember(userId); } catch (IdUnusedException ex) { // no site found } List releaseGroupIds = PersistenceService.getInstance() .getPublishedAssessmentFacadeQueries() .getReleaseToGroupIdsForPublishedAssessment(publishedAssessmentId); if (siteGroups == null) { return false; } Iterator groupsIter = siteGroups.iterator(); while (groupsIter.hasNext()) { Group group = (Group) groupsIter.next(); for (Iterator releaseGroupIdsIter = releaseGroupIds.iterator(); releaseGroupIdsIter.hasNext();) { //if this group is a release group if (group.getId().equals((String)releaseGroupIdsIter.next())) { return true; } } } return false; } public List getAvailableSections(String siteid, String userUid) { List availableSections = new ArrayList(); SectionAwareness sectionAwareness = getSectionAwareness(); if (sectionAwareness ==null) { } else { // Get the list of sections. For now, just use whatever default // sorting we get from the Section Awareness component. /* List sectionCategories = sectionAwareness.getSectionCategories(siteid); for (Iterator catIter = sectionCategories.iterator(); catIter.hasNext(); ) { String category = (String)catIter.next(); List sections = sectionAwareness.getSectionsInCategory(siteid, category); for (Iterator iter = sections.iterator(); iter.hasNext(); ) { CourseSection section = (CourseSection)iter.next(); if (isUserAbleToGradeAll(siteid, userUid) || isUserAbleToGradeSection(section.getUuid(), userUid)) { availableSections.add(section); } } } */ List sections = sectionAwareness.getSections(siteid); for (Iterator iter = sections.iterator(); iter.hasNext(); ) { CourseSection section = (CourseSection)iter.next(); // if (isUserAbleToGradeAll(gradebookUid) || isUserAbleToGradeSection(section.getUuid())) { if (isUserAbleToGradeAll(siteid, userUid) || isUserAbleToGradeSection(section.getUuid(), userUid)) { availableSections.add(section); } } } return availableSections; } public List getSectionEnrollmentsTrusted(String sectionUid) { return getSectionEnrollmentsTrusted(sectionUid, null); } private List getSectionEnrollmentsTrusted(String sectionUid, String userUid) { return getSectionAwareness().getSectionMembersInRole(sectionUid, Role.STUDENT); } public List getSectionEnrollments(String siteid, String sectionUid, String userUid) { List enrollments; if (isUserAbleToGradeAll(siteid, userUid) || isUserAbleToGradeSection(sectionUid, userUid)) { enrollments = getSectionEnrollmentsTrusted(sectionUid, userUid); } else { enrollments = new ArrayList(); log.warn("getSectionEnrollments for sectionUid=" + sectionUid + " called by unauthorized userUid=" + userUid); } return enrollments; } public List findMatchingEnrollments(String siteid, String searchString, String optionalSectionUid, String userUid) { List enrollments; List allEnrollmentsFilteredBySearch = getSectionAwareness().findSiteMembersInRole(siteid, Role.STUDENT, searchString); if (allEnrollmentsFilteredBySearch.isEmpty() || ((optionalSectionUid == null) && isUserAbleToGradeAll(siteid, userUid))) { enrollments = allEnrollmentsFilteredBySearch; } else { if (optionalSectionUid == null) { enrollments = getAvailableEnrollments(siteid, userUid); } else { // The user has selected a particular section. enrollments = getSectionEnrollments(siteid, optionalSectionUid, userUid); } Set availableStudentUids = FacadeUtils.getStudentUids(enrollments); enrollments = new ArrayList(); for (Iterator iter = allEnrollmentsFilteredBySearch.iterator(); iter.hasNext(); ) { EnrollmentRecord enr = (EnrollmentRecord)iter.next(); if (availableStudentUids.contains(enr.getUser().getUserUid())) { enrollments.add(enr); } } } return enrollments; } public boolean isSectionMemberInRoleStudent(String sectionId, String studentId) { return getSectionAwareness().isSectionMemberInRole(sectionId, studentId, Role.STUDENT); } }
SAM-1472 Scores page load times excessive for large sites with assessments released to groups - adding rewrite of fix based on a dayton patch concept git-svn-id: 574bb14f304dbe16c01253ed6697ea749724087f@103545 66ffb92e-73f9-0310-93c1-f5514f145a0a
samigo/samigo-services/src/java/org/sakaiproject/tool/assessment/integration/helper/integrated/SectionAwareServiceHelperImpl.java
SAM-1472 Scores page load times excessive for large sites with assessments released to groups - adding rewrite of fix based on a dayton patch concept
<ide><path>amigo/samigo-services/src/java/org/sakaiproject/tool/assessment/integration/helper/integrated/SectionAwareServiceHelperImpl.java <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> <del>import org.sakaiproject.authz.cover.SecurityService; <ide> import org.sakaiproject.exception.IdUnusedException; <ide> import org.sakaiproject.section.api.SectionAwareness; <ide> import org.sakaiproject.section.api.coursemanagement.CourseSection; <ide> import org.sakaiproject.section.api.coursemanagement.EnrollmentRecord; <ide> import org.sakaiproject.section.api.facade.Role; <ide> import org.sakaiproject.site.api.Group; <add>import org.sakaiproject.site.api.Site; <ide> import org.sakaiproject.site.cover.SiteService; <ide> import org.sakaiproject.tool.assessment.facade.AgentFacade; <ide> import org.sakaiproject.tool.assessment.integration.helper.ifc.SectionAwareServiceHelper; <ide> public List getGroupReleaseEnrollments(String siteid, String userUid, String publishedAssessmentId) { <ide> List availEnrollments = getAvailableEnrollments(siteid, userUid); <ide> List enrollments = new ArrayList(); <add> <add> HashSet<String> membersInReleaseGroups = new HashSet<String>(0); <add> try { <add> Set<String> availableEnrollments = new HashSet<String>(availEnrollments); <add> Site site = siteService.getInstance().getSite(siteid); // this follows the way the service is already written but it is a bad practice <add> membersInReleaseGroups = new HashSet<String>( site.getMembersInGroups(availableEnrollments) ); <add> } catch (IdUnusedException ex) { <add> // no site found, just log a warning <add> log.warn("Unable to find a site with id ("+siteid+") in order to get the enrollments, will return 0 enrollments"); <add> } <add> <ide> for (Iterator eIter = availEnrollments.iterator(); eIter.hasNext(); ) { <ide> EnrollmentRecord enr = (EnrollmentRecord)eIter.next(); <del> if (isUserInReleaseGroup(enr.getUser().getUserUid(), AgentFacade.getCurrentSiteId(), publishedAssessmentId)) { <add> if (membersInReleaseGroups.contains( enr.getUser().getUserUid())) { <ide> enrollments.add(enr); <ide> } <ide> } <add> <ide> return enrollments; <ide> } <ide>
Java
apache-2.0
35c270eb5de2c1a30efd7790371bbae30e9f1acb
0
mittop/vaadin,oalles/vaadin,udayinfy/vaadin,mittop/vaadin,sitexa/vaadin,magi42/vaadin,synes/vaadin,kironapublic/vaadin,carrchang/vaadin,sitexa/vaadin,Darsstar/framework,shahrzadmn/vaadin,magi42/vaadin,Darsstar/framework,travisfw/vaadin,travisfw/vaadin,oalles/vaadin,fireflyc/vaadin,Flamenco/vaadin,fireflyc/vaadin,sitexa/vaadin,Scarlethue/vaadin,jdahlstrom/vaadin.react,peterl1084/framework,asashour/framework,travisfw/vaadin,oalles/vaadin,oalles/vaadin,Peppe/vaadin,udayinfy/vaadin,jdahlstrom/vaadin.react,synes/vaadin,peterl1084/framework,magi42/vaadin,mstahv/framework,magi42/vaadin,cbmeeks/vaadin,synes/vaadin,jdahlstrom/vaadin.react,Darsstar/framework,udayinfy/vaadin,bmitc/vaadin,Peppe/vaadin,sitexa/vaadin,peterl1084/framework,Legioth/vaadin,carrchang/vaadin,sitexa/vaadin,Peppe/vaadin,Legioth/vaadin,mittop/vaadin,shahrzadmn/vaadin,Scarlethue/vaadin,mstahv/framework,travisfw/vaadin,peterl1084/framework,oalles/vaadin,jdahlstrom/vaadin.react,Peppe/vaadin,kironapublic/vaadin,travisfw/vaadin,mstahv/framework,udayinfy/vaadin,Darsstar/framework,bmitc/vaadin,Scarlethue/vaadin,carrchang/vaadin,synes/vaadin,cbmeeks/vaadin,Legioth/vaadin,asashour/framework,Darsstar/framework,bmitc/vaadin,fireflyc/vaadin,bmitc/vaadin,shahrzadmn/vaadin,shahrzadmn/vaadin,carrchang/vaadin,Scarlethue/vaadin,Flamenco/vaadin,cbmeeks/vaadin,udayinfy/vaadin,asashour/framework,Legioth/vaadin,synes/vaadin,asashour/framework,mstahv/framework,Legioth/vaadin,kironapublic/vaadin,asashour/framework,peterl1084/framework,cbmeeks/vaadin,fireflyc/vaadin,Scarlethue/vaadin,shahrzadmn/vaadin,magi42/vaadin,Flamenco/vaadin,kironapublic/vaadin,Flamenco/vaadin,mittop/vaadin,Peppe/vaadin,kironapublic/vaadin,fireflyc/vaadin,mstahv/framework,jdahlstrom/vaadin.react
/* * Copyright 2000-2013 Vaadin Ltd. * * 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.vaadin.ui; import java.io.Serializable; import java.lang.reflect.Method; import org.json.JSONException; import com.vaadin.event.Action; import com.vaadin.event.FieldEvents; import com.vaadin.event.FieldEvents.BlurEvent; import com.vaadin.event.FieldEvents.BlurListener; import com.vaadin.event.FieldEvents.FocusAndBlurServerRpcImpl; import com.vaadin.event.FieldEvents.FocusEvent; import com.vaadin.event.FieldEvents.FocusListener; import com.vaadin.event.ShortcutAction; import com.vaadin.event.ShortcutAction.KeyCode; import com.vaadin.event.ShortcutAction.ModifierKey; import com.vaadin.event.ShortcutListener; import com.vaadin.server.Resource; import com.vaadin.shared.MouseEventDetails; import com.vaadin.shared.ui.button.ButtonServerRpc; import com.vaadin.shared.ui.button.ButtonState; import com.vaadin.ui.Component.Focusable; import com.vaadin.util.ReflectTools; /** * A generic button component. * * @author Vaadin Ltd. * @since 3.0 */ @SuppressWarnings("serial") public class Button extends AbstractComponent implements FieldEvents.BlurNotifier, FieldEvents.FocusNotifier, Focusable, Action.ShortcutNotifier { private ButtonServerRpc rpc = new ButtonServerRpc() { @Override public void click(MouseEventDetails mouseEventDetails) { fireClick(mouseEventDetails); } @Override public void disableOnClick() throws RuntimeException { setEnabled(false); // Makes sure the enabled=false state is noticed at once - otherwise // a following setEnabled(true) call might have no effect. see // ticket #10030 try { getUI().getConnectorTracker().getDiffState(Button.this) .put("enabled", false); } catch (JSONException e) { throw new RuntimeException(e); } } }; FocusAndBlurServerRpcImpl focusBlurRpc = new FocusAndBlurServerRpcImpl(this) { @Override protected void fireEvent(Event event) { Button.this.fireEvent(event); } }; /** * Creates a new push button. */ public Button() { registerRpc(rpc); registerRpc(focusBlurRpc); } /** * Creates a new push button with the given caption. * * @param caption * the Button caption. */ public Button(String caption) { this(); setCaption(caption); } /** * Creates a new push button with the given icon. * * @param icon * the icon */ public Button(Resource icon) { this(); setIcon(icon); } /** * Creates a new push button with the given caption and icon. * * @param caption * the caption * @param icon * the icon */ public Button(String caption, Resource icon) { this(); setCaption(caption); setIcon(icon); } /** * Creates a new push button with a click listener. * * @param caption * the Button caption. * @param listener * the Button click listener. */ public Button(String caption, ClickListener listener) { this(caption); addListener(listener); } /** * Click event. This event is thrown, when the button is clicked. * * @author Vaadin Ltd. * @since 3.0 */ public static class ClickEvent extends Component.Event { private final MouseEventDetails details; /** * New instance of text change event. * * @param source * the Source of the event. */ public ClickEvent(Component source) { super(source); details = null; } /** * Constructor with mouse details * * @param source * The source where the click took place * @param details * Details about the mouse click */ public ClickEvent(Component source, MouseEventDetails details) { super(source); this.details = details; } /** * Gets the Button where the event occurred. * * @return the Source of the event. */ public Button getButton() { return (Button) getSource(); } /** * Returns the mouse position (x coordinate) when the click took place. * The position is relative to the browser client area. * * @return The mouse cursor x position or -1 if unknown */ public int getClientX() { if (null != details) { return details.getClientX(); } else { return -1; } } /** * Returns the mouse position (y coordinate) when the click took place. * The position is relative to the browser client area. * * @return The mouse cursor y position or -1 if unknown */ public int getClientY() { if (null != details) { return details.getClientY(); } else { return -1; } } /** * Returns the relative mouse position (x coordinate) when the click * took place. The position is relative to the clicked component. * * @return The mouse cursor x position relative to the clicked layout * component or -1 if no x coordinate available */ public int getRelativeX() { if (null != details) { return details.getRelativeX(); } else { return -1; } } /** * Returns the relative mouse position (y coordinate) when the click * took place. The position is relative to the clicked component. * * @return The mouse cursor y position relative to the clicked layout * component or -1 if no y coordinate available */ public int getRelativeY() { if (null != details) { return details.getRelativeY(); } else { return -1; } } /** * Checks if the Alt key was down when the mouse event took place. * * @return true if Alt was down when the event occured, false otherwise * or if unknown */ public boolean isAltKey() { if (null != details) { return details.isAltKey(); } else { return false; } } /** * Checks if the Ctrl key was down when the mouse event took place. * * @return true if Ctrl was pressed when the event occured, false * otherwise or if unknown */ public boolean isCtrlKey() { if (null != details) { return details.isCtrlKey(); } else { return false; } } /** * Checks if the Meta key was down when the mouse event took place. * * @return true if Meta was pressed when the event occured, false * otherwise or if unknown */ public boolean isMetaKey() { if (null != details) { return details.isMetaKey(); } else { return false; } } /** * Checks if the Shift key was down when the mouse event took place. * * @return true if Shift was pressed when the event occured, false * otherwise or if unknown */ public boolean isShiftKey() { if (null != details) { return details.isShiftKey(); } else { return false; } } } /** * Interface for listening for a {@link ClickEvent} fired by a * {@link Component}. * * @author Vaadin Ltd. * @since 3.0 */ public interface ClickListener extends Serializable { public static final Method BUTTON_CLICK_METHOD = ReflectTools .findMethod(ClickListener.class, "buttonClick", ClickEvent.class); /** * Called when a {@link Button} has been clicked. A reference to the * button is given by {@link ClickEvent#getButton()}. * * @param event * An event containing information about the click. */ public void buttonClick(ClickEvent event); } /** * Adds the button click listener. * * @param listener * the Listener to be added. */ public void addClickListener(ClickListener listener) { addListener(ClickEvent.class, listener, ClickListener.BUTTON_CLICK_METHOD); } /** * @deprecated As of 7.0, replaced by * {@link #addClickListener(ClickListener)} **/ @Deprecated public void addListener(ClickListener listener) { addClickListener(listener); } /** * Removes the button click listener. * * @param listener * the Listener to be removed. */ public void removeClickListener(ClickListener listener) { removeListener(ClickEvent.class, listener, ClickListener.BUTTON_CLICK_METHOD); } /** * @deprecated As of 7.0, replaced by * {@link #removeClickListener(ClickListener)} **/ @Deprecated public void removeListener(ClickListener listener) { removeClickListener(listener); } /** * Simulates a button click, notifying all server-side listeners. * * No action is taken is the button is disabled. */ public void click() { if (isEnabled() && !isReadOnly()) { fireClick(); } } /** * Fires a click event to all listeners without any event details. * * In subclasses, override {@link #fireClick(MouseEventDetails)} instead of * this method. */ protected void fireClick() { fireEvent(new Button.ClickEvent(this)); } /** * Fires a click event to all listeners. * * @param details * MouseEventDetails from which keyboard modifiers and other * information about the mouse click can be obtained. If the * button was clicked by a keyboard event, some of the fields may * be empty/undefined. */ protected void fireClick(MouseEventDetails details) { fireEvent(new Button.ClickEvent(this, details)); } @Override public void addBlurListener(BlurListener listener) { addListener(BlurEvent.EVENT_ID, BlurEvent.class, listener, BlurListener.blurMethod); } /** * @deprecated As of 7.0, replaced by {@link #addBlurListener(BlurListener)} **/ @Override @Deprecated public void addListener(BlurListener listener) { addBlurListener(listener); } @Override public void removeBlurListener(BlurListener listener) { removeListener(BlurEvent.EVENT_ID, BlurEvent.class, listener); } /** * @deprecated As of 7.0, replaced by * {@link #removeBlurListener(BlurListener)} **/ @Override @Deprecated public void removeListener(BlurListener listener) { removeBlurListener(listener); } @Override public void addFocusListener(FocusListener listener) { addListener(FocusEvent.EVENT_ID, FocusEvent.class, listener, FocusListener.focusMethod); } /** * @deprecated As of 7.0, replaced by * {@link #addFocusListener(FocusListener)} **/ @Override @Deprecated public void addListener(FocusListener listener) { addFocusListener(listener); } @Override public void removeFocusListener(FocusListener listener) { removeListener(FocusEvent.EVENT_ID, FocusEvent.class, listener); } /** * @deprecated As of 7.0, replaced by * {@link #removeFocusListener(FocusListener)} **/ @Override @Deprecated public void removeListener(FocusListener listener) { removeFocusListener(listener); } /* * Actions */ protected ClickShortcut clickShortcut; /** * Makes it possible to invoke a click on this button by pressing the given * {@link KeyCode} and (optional) {@link ModifierKey}s.<br/> * The shortcut is global (bound to the containing Window). * * @param keyCode * the keycode for invoking the shortcut * @param modifiers * the (optional) modifiers for invoking the shortcut, null for * none */ public void setClickShortcut(int keyCode, int... modifiers) { if (clickShortcut != null) { removeShortcutListener(clickShortcut); } clickShortcut = new ClickShortcut(this, keyCode, modifiers); addShortcutListener(clickShortcut); getState().clickShortcutKeyCode = clickShortcut.getKeyCode(); } /** * Removes the keyboard shortcut previously set with * {@link #setClickShortcut(int, int...)}. */ public void removeClickShortcut() { if (clickShortcut != null) { removeShortcutListener(clickShortcut); clickShortcut = null; getState().clickShortcutKeyCode = 0; } } /** * A {@link ShortcutListener} specifically made to define a keyboard * shortcut that invokes a click on the given button. * */ public static class ClickShortcut extends ShortcutListener { protected Button button; /** * Creates a keyboard shortcut for clicking the given button using the * shorthand notation defined in {@link ShortcutAction}. * * @param button * to be clicked when the shortcut is invoked * @param shorthandCaption * the caption with shortcut keycode and modifiers indicated */ public ClickShortcut(Button button, String shorthandCaption) { super(shorthandCaption); this.button = button; } /** * Creates a keyboard shortcut for clicking the given button using the * given {@link KeyCode} and {@link ModifierKey}s. * * @param button * to be clicked when the shortcut is invoked * @param keyCode * KeyCode to react to * @param modifiers * optional modifiers for shortcut */ public ClickShortcut(Button button, int keyCode, int... modifiers) { super(null, keyCode, modifiers); this.button = button; } /** * Creates a keyboard shortcut for clicking the given button using the * given {@link KeyCode}. * * @param button * to be clicked when the shortcut is invoked * @param keyCode * KeyCode to react to */ public ClickShortcut(Button button, int keyCode) { this(button, keyCode, null); } @Override public void handleAction(Object sender, Object target) { button.click(); } } /** * Determines if a button is automatically disabled when clicked. See * {@link #setDisableOnClick(boolean)} for details. * * @return true if the button is disabled when clicked, false otherwise */ public boolean isDisableOnClick() { return getState().disableOnClick; } /** * Determines if a button is automatically disabled when clicked. If this is * set to true the button will be automatically disabled when clicked, * typically to prevent (accidental) extra clicks on a button. * <p> * Note that this is only used when the click comes from the user, not when * calling {@link #click()}. * </p> * * @param disableOnClick * true to disable button when it is clicked, false otherwise */ public void setDisableOnClick(boolean disableOnClick) { getState().disableOnClick = disableOnClick; } /* * (non-Javadoc) * * @see com.vaadin.ui.Component.Focusable#getTabIndex() */ @Override public int getTabIndex() { return getState().tabIndex; } /* * (non-Javadoc) * * @see com.vaadin.ui.Component.Focusable#setTabIndex(int) */ @Override public void setTabIndex(int tabIndex) { getState().tabIndex = tabIndex; } @Override public void focus() { // Overridden only to make public super.focus(); } @Override protected ButtonState getState() { return (ButtonState) super.getState(); } /** * Sets the component's icon and alt text. * * An alt text is shown when an image could not be loaded, and read by * assisitve devices. * * @param icon * the icon to be shown with the component's caption. * @param iconAltText * String to use as alt text */ public void setIcon(Resource icon, String iconAltText) { super.setIcon(icon); getState().iconAltText = iconAltText == null ? "" : iconAltText; } /** * Returns the icon's alt text. * * @return String with the alt text */ public String getIconAlternateText() { return getState().iconAltText; } public void setIconAlternateText(String iconAltText) { getState().iconAltText = iconAltText; } /** * Set whether the caption text is rendered as HTML or not. You might need * to retheme button to allow higher content than the original text style. * * If set to true, the captions are passed to the browser as html and the * developer is responsible for ensuring no harmful html is used. If set to * false, the content is passed to the browser as plain text. * * @param htmlContentAllowed * <code>true</code> if caption is rendered as HTML, * <code>false</code> otherwise */ public void setHtmlContentAllowed(boolean htmlContentAllowed) { getState().htmlContentAllowed = htmlContentAllowed; } /** * Return HTML rendering setting * * @return <code>true</code> if the caption text is to be rendered as HTML, * <code>false</code> otherwise */ public boolean isHtmlContentAllowed() { return getState().htmlContentAllowed; } }
server/src/com/vaadin/ui/Button.java
/* * Copyright 2000-2013 Vaadin Ltd. * * 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.vaadin.ui; import java.io.Serializable; import java.lang.reflect.Method; import org.json.JSONException; import com.vaadin.event.Action; import com.vaadin.event.FieldEvents; import com.vaadin.event.FieldEvents.BlurEvent; import com.vaadin.event.FieldEvents.BlurListener; import com.vaadin.event.FieldEvents.FocusAndBlurServerRpcImpl; import com.vaadin.event.FieldEvents.FocusEvent; import com.vaadin.event.FieldEvents.FocusListener; import com.vaadin.event.ShortcutAction; import com.vaadin.event.ShortcutAction.KeyCode; import com.vaadin.event.ShortcutAction.ModifierKey; import com.vaadin.event.ShortcutListener; import com.vaadin.server.Resource; import com.vaadin.shared.MouseEventDetails; import com.vaadin.shared.ui.button.ButtonServerRpc; import com.vaadin.shared.ui.button.ButtonState; import com.vaadin.ui.Component.Focusable; import com.vaadin.util.ReflectTools; /** * A generic button component. * * @author Vaadin Ltd. * @since 3.0 */ @SuppressWarnings("serial") public class Button extends AbstractComponent implements FieldEvents.BlurNotifier, FieldEvents.FocusNotifier, Focusable, Action.ShortcutNotifier { private ButtonServerRpc rpc = new ButtonServerRpc() { @Override public void click(MouseEventDetails mouseEventDetails) { fireClick(mouseEventDetails); } @Override public void disableOnClick() throws RuntimeException { setEnabled(false); // Makes sure the enabled=false state is noticed at once - otherwise // a following setEnabled(true) call might have no effect. see // ticket #10030 try { getUI().getConnectorTracker().getDiffState(Button.this) .put("enabled", false); } catch (JSONException e) { throw new RuntimeException(e); } } }; FocusAndBlurServerRpcImpl focusBlurRpc = new FocusAndBlurServerRpcImpl(this) { @Override protected void fireEvent(Event event) { Button.this.fireEvent(event); } }; /** * Creates a new push button. */ public Button() { registerRpc(rpc); registerRpc(focusBlurRpc); } /** * Creates a new push button with the given caption. * * @param caption * the Button caption. */ public Button(String caption) { this(); setCaption(caption); } /** * Creates a new push button with a click listener. * * @param caption * the Button caption. * @param listener * the Button click listener. */ public Button(String caption, ClickListener listener) { this(caption); addListener(listener); } /** * Click event. This event is thrown, when the button is clicked. * * @author Vaadin Ltd. * @since 3.0 */ public static class ClickEvent extends Component.Event { private final MouseEventDetails details; /** * New instance of text change event. * * @param source * the Source of the event. */ public ClickEvent(Component source) { super(source); details = null; } /** * Constructor with mouse details * * @param source * The source where the click took place * @param details * Details about the mouse click */ public ClickEvent(Component source, MouseEventDetails details) { super(source); this.details = details; } /** * Gets the Button where the event occurred. * * @return the Source of the event. */ public Button getButton() { return (Button) getSource(); } /** * Returns the mouse position (x coordinate) when the click took place. * The position is relative to the browser client area. * * @return The mouse cursor x position or -1 if unknown */ public int getClientX() { if (null != details) { return details.getClientX(); } else { return -1; } } /** * Returns the mouse position (y coordinate) when the click took place. * The position is relative to the browser client area. * * @return The mouse cursor y position or -1 if unknown */ public int getClientY() { if (null != details) { return details.getClientY(); } else { return -1; } } /** * Returns the relative mouse position (x coordinate) when the click * took place. The position is relative to the clicked component. * * @return The mouse cursor x position relative to the clicked layout * component or -1 if no x coordinate available */ public int getRelativeX() { if (null != details) { return details.getRelativeX(); } else { return -1; } } /** * Returns the relative mouse position (y coordinate) when the click * took place. The position is relative to the clicked component. * * @return The mouse cursor y position relative to the clicked layout * component or -1 if no y coordinate available */ public int getRelativeY() { if (null != details) { return details.getRelativeY(); } else { return -1; } } /** * Checks if the Alt key was down when the mouse event took place. * * @return true if Alt was down when the event occured, false otherwise * or if unknown */ public boolean isAltKey() { if (null != details) { return details.isAltKey(); } else { return false; } } /** * Checks if the Ctrl key was down when the mouse event took place. * * @return true if Ctrl was pressed when the event occured, false * otherwise or if unknown */ public boolean isCtrlKey() { if (null != details) { return details.isCtrlKey(); } else { return false; } } /** * Checks if the Meta key was down when the mouse event took place. * * @return true if Meta was pressed when the event occured, false * otherwise or if unknown */ public boolean isMetaKey() { if (null != details) { return details.isMetaKey(); } else { return false; } } /** * Checks if the Shift key was down when the mouse event took place. * * @return true if Shift was pressed when the event occured, false * otherwise or if unknown */ public boolean isShiftKey() { if (null != details) { return details.isShiftKey(); } else { return false; } } } /** * Interface for listening for a {@link ClickEvent} fired by a * {@link Component}. * * @author Vaadin Ltd. * @since 3.0 */ public interface ClickListener extends Serializable { public static final Method BUTTON_CLICK_METHOD = ReflectTools .findMethod(ClickListener.class, "buttonClick", ClickEvent.class); /** * Called when a {@link Button} has been clicked. A reference to the * button is given by {@link ClickEvent#getButton()}. * * @param event * An event containing information about the click. */ public void buttonClick(ClickEvent event); } /** * Adds the button click listener. * * @param listener * the Listener to be added. */ public void addClickListener(ClickListener listener) { addListener(ClickEvent.class, listener, ClickListener.BUTTON_CLICK_METHOD); } /** * @deprecated As of 7.0, replaced by * {@link #addClickListener(ClickListener)} **/ @Deprecated public void addListener(ClickListener listener) { addClickListener(listener); } /** * Removes the button click listener. * * @param listener * the Listener to be removed. */ public void removeClickListener(ClickListener listener) { removeListener(ClickEvent.class, listener, ClickListener.BUTTON_CLICK_METHOD); } /** * @deprecated As of 7.0, replaced by * {@link #removeClickListener(ClickListener)} **/ @Deprecated public void removeListener(ClickListener listener) { removeClickListener(listener); } /** * Simulates a button click, notifying all server-side listeners. * * No action is taken is the button is disabled. */ public void click() { if (isEnabled() && !isReadOnly()) { fireClick(); } } /** * Fires a click event to all listeners without any event details. * * In subclasses, override {@link #fireClick(MouseEventDetails)} instead of * this method. */ protected void fireClick() { fireEvent(new Button.ClickEvent(this)); } /** * Fires a click event to all listeners. * * @param details * MouseEventDetails from which keyboard modifiers and other * information about the mouse click can be obtained. If the * button was clicked by a keyboard event, some of the fields may * be empty/undefined. */ protected void fireClick(MouseEventDetails details) { fireEvent(new Button.ClickEvent(this, details)); } @Override public void addBlurListener(BlurListener listener) { addListener(BlurEvent.EVENT_ID, BlurEvent.class, listener, BlurListener.blurMethod); } /** * @deprecated As of 7.0, replaced by {@link #addBlurListener(BlurListener)} **/ @Override @Deprecated public void addListener(BlurListener listener) { addBlurListener(listener); } @Override public void removeBlurListener(BlurListener listener) { removeListener(BlurEvent.EVENT_ID, BlurEvent.class, listener); } /** * @deprecated As of 7.0, replaced by * {@link #removeBlurListener(BlurListener)} **/ @Override @Deprecated public void removeListener(BlurListener listener) { removeBlurListener(listener); } @Override public void addFocusListener(FocusListener listener) { addListener(FocusEvent.EVENT_ID, FocusEvent.class, listener, FocusListener.focusMethod); } /** * @deprecated As of 7.0, replaced by * {@link #addFocusListener(FocusListener)} **/ @Override @Deprecated public void addListener(FocusListener listener) { addFocusListener(listener); } @Override public void removeFocusListener(FocusListener listener) { removeListener(FocusEvent.EVENT_ID, FocusEvent.class, listener); } /** * @deprecated As of 7.0, replaced by * {@link #removeFocusListener(FocusListener)} **/ @Override @Deprecated public void removeListener(FocusListener listener) { removeFocusListener(listener); } /* * Actions */ protected ClickShortcut clickShortcut; /** * Makes it possible to invoke a click on this button by pressing the given * {@link KeyCode} and (optional) {@link ModifierKey}s.<br/> * The shortcut is global (bound to the containing Window). * * @param keyCode * the keycode for invoking the shortcut * @param modifiers * the (optional) modifiers for invoking the shortcut, null for * none */ public void setClickShortcut(int keyCode, int... modifiers) { if (clickShortcut != null) { removeShortcutListener(clickShortcut); } clickShortcut = new ClickShortcut(this, keyCode, modifiers); addShortcutListener(clickShortcut); getState().clickShortcutKeyCode = clickShortcut.getKeyCode(); } /** * Removes the keyboard shortcut previously set with * {@link #setClickShortcut(int, int...)}. */ public void removeClickShortcut() { if (clickShortcut != null) { removeShortcutListener(clickShortcut); clickShortcut = null; getState().clickShortcutKeyCode = 0; } } /** * A {@link ShortcutListener} specifically made to define a keyboard * shortcut that invokes a click on the given button. * */ public static class ClickShortcut extends ShortcutListener { protected Button button; /** * Creates a keyboard shortcut for clicking the given button using the * shorthand notation defined in {@link ShortcutAction}. * * @param button * to be clicked when the shortcut is invoked * @param shorthandCaption * the caption with shortcut keycode and modifiers indicated */ public ClickShortcut(Button button, String shorthandCaption) { super(shorthandCaption); this.button = button; } /** * Creates a keyboard shortcut for clicking the given button using the * given {@link KeyCode} and {@link ModifierKey}s. * * @param button * to be clicked when the shortcut is invoked * @param keyCode * KeyCode to react to * @param modifiers * optional modifiers for shortcut */ public ClickShortcut(Button button, int keyCode, int... modifiers) { super(null, keyCode, modifiers); this.button = button; } /** * Creates a keyboard shortcut for clicking the given button using the * given {@link KeyCode}. * * @param button * to be clicked when the shortcut is invoked * @param keyCode * KeyCode to react to */ public ClickShortcut(Button button, int keyCode) { this(button, keyCode, null); } @Override public void handleAction(Object sender, Object target) { button.click(); } } /** * Determines if a button is automatically disabled when clicked. See * {@link #setDisableOnClick(boolean)} for details. * * @return true if the button is disabled when clicked, false otherwise */ public boolean isDisableOnClick() { return getState().disableOnClick; } /** * Determines if a button is automatically disabled when clicked. If this is * set to true the button will be automatically disabled when clicked, * typically to prevent (accidental) extra clicks on a button. * <p> * Note that this is only used when the click comes from the user, not when * calling {@link #click()}. * </p> * * @param disableOnClick * true to disable button when it is clicked, false otherwise */ public void setDisableOnClick(boolean disableOnClick) { getState().disableOnClick = disableOnClick; } /* * (non-Javadoc) * * @see com.vaadin.ui.Component.Focusable#getTabIndex() */ @Override public int getTabIndex() { return getState().tabIndex; } /* * (non-Javadoc) * * @see com.vaadin.ui.Component.Focusable#setTabIndex(int) */ @Override public void setTabIndex(int tabIndex) { getState().tabIndex = tabIndex; } @Override public void focus() { // Overridden only to make public super.focus(); } @Override protected ButtonState getState() { return (ButtonState) super.getState(); } /** * Sets the component's icon and alt text. * * An alt text is shown when an image could not be loaded, and read by * assisitve devices. * * @param icon * the icon to be shown with the component's caption. * @param iconAltText * String to use as alt text */ public void setIcon(Resource icon, String iconAltText) { super.setIcon(icon); getState().iconAltText = iconAltText == null ? "" : iconAltText; } /** * Returns the icon's alt text. * * @return String with the alt text */ public String getIconAlternateText() { return getState().iconAltText; } public void setIconAlternateText(String iconAltText) { getState().iconAltText = iconAltText; } /** * Set whether the caption text is rendered as HTML or not. You might need * to retheme button to allow higher content than the original text style. * * If set to true, the captions are passed to the browser as html and the * developer is responsible for ensuring no harmful html is used. If set to * false, the content is passed to the browser as plain text. * * @param htmlContentAllowed * <code>true</code> if caption is rendered as HTML, * <code>false</code> otherwise */ public void setHtmlContentAllowed(boolean htmlContentAllowed) { getState().htmlContentAllowed = htmlContentAllowed; } /** * Return HTML rendering setting * * @return <code>true</code> if the caption text is to be rendered as HTML, * <code>false</code> otherwise */ public boolean isHtmlContentAllowed() { return getState().htmlContentAllowed; } }
Resource constructors for Button (#13446) Change-Id: I9e8409660f38e35c01adde69158c34e85cff3c43
server/src/com/vaadin/ui/Button.java
Resource constructors for Button (#13446)
<ide><path>erver/src/com/vaadin/ui/Button.java <ide> } <ide> <ide> /** <add> * Creates a new push button with the given icon. <add> * <add> * @param icon <add> * the icon <add> */ <add> public Button(Resource icon) { <add> this(); <add> setIcon(icon); <add> } <add> <add> /** <add> * Creates a new push button with the given caption and icon. <add> * <add> * @param caption <add> * the caption <add> * @param icon <add> * the icon <add> */ <add> public Button(String caption, Resource icon) { <add> this(); <add> setCaption(caption); <add> setIcon(icon); <add> } <add> <add> /** <ide> * Creates a new push button with a click listener. <ide> * <ide> * @param caption
JavaScript
agpl-3.0
5c519d2f3eebffc87dd6903751eba23b5492e5bd
0
matsuu/mwEmbed,safarijv/mwEmbed,kaltura/mwEmbed,omridevk/mwEmbed,alexmilk/mwEmbed,vladm3/mwEmbed,safarijv/mwEmbed,slash851/mwEmbed,alexmilk/mwEmbed,bordar/mwEmbed,safarijv/mwEmbed,omridevk/mwEmbed,slash851/mwEmbed,bordar/mwEmbed,kaltura/mwEmbed,SVSG/mwEmbed,SVSG/mwEmbed,slash851/mwEmbed,joanpuigsanz/mwEmbed,vladm3/mwEmbed,joanpuigsanz/mwEmbed,abaylis/mwEmbed,omridevk/mwEmbed,abaylis/mwEmbed,tanyaLibatter/mwEmbed,DBezemer/mwEmbed,matsuu/mwEmbed,FlixMaster/mwEmbed,DBezemer/mwEmbed,vladm3/mwEmbed,abaylis/mwEmbed,slash851/mwEmbed,omridevk/mwEmbed,panda-os/mwEmbed,matsuu/mwEmbed,DBezemer/mwEmbed,joanpuigsanz/mwEmbed,FlixMaster/mwEmbed,panda-os/mwEmbed,tanyaLibatter/mwEmbed,bordar/mwEmbed,SVSG/mwEmbed,SVSG/mwEmbed,panda-os/mwEmbed,matsuu/mwEmbed,tanyaLibatter/mwEmbed,tanyaLibatter/mwEmbed,FlixMaster/mwEmbed,kaltura/mwEmbed,vladm3/mwEmbed,joanpuigsanz/mwEmbed,bordar/mwEmbed,DBezemer/mwEmbed,abaylis/mwEmbed,alexmilk/mwEmbed,safarijv/mwEmbed,panda-os/mwEmbed,alexmilk/mwEmbed,kaltura/mwEmbed,FlixMaster/mwEmbed
// Add a jQuery plugin for pretty kaltura docs (function( $ ){ $.fn.prettyKalturaConfig = function( pluginName, flashVars, flashvarCallback ){ var manifestData = {}; return this.each(function() { /** * Init */ // Setup _this pointer var _this = this; // setup master id for ( this ) var id = $(this).attr('id'); // set the target to loading while documentation is loaded $( this ).html('Loading <span class="blink">...</span>'); var _this = this; /** * get a var object from plugin style location or from top level var */ function getVarObj( attrName ){ // Check for plugin config: if( manifestData[pluginName] && manifestData[pluginName].attributes && manifestData[pluginName].attributes[ attrName ] ) { return manifestData[pluginName].attributes[ attrName ]; } // Check other plugins for( var pid in manifestData ){ if( manifestData[ pid ] && manifestData[ pid ].attributes && manifestData[ pid ].attributes[ attrName ] ) { return manifestData[ pid ].attributes[ attrName ]; } } // Check for raw value object: if( manifestData[attrName] ){ return manifestData[attrName]; } return {}; } /** * Set an attr value */ function setAttrValue( attrName, attrValue ){ if( manifestData[pluginName] && manifestData[pluginName].attributes && manifestData[pluginName].attributes[ attrName ] ){ manifestData[pluginName].attributes[ attrName ].value = attrValue; // refresh the value manifestData[pluginName].attributes[ attrName ].$editVal.getEditValue( attrName ); } else if( manifestData[attrName] ){ manifestData[attrName].value = attrValue; // refresh the value manifestData[attrName].$editVal.getEditValue( attrName ); } else { // look for other plugins with this property: for( var pid in manifestData ){ if( manifestData[pid].attributes ){ for( var pAttrName in manifestData[pid].attributes ){ if( pAttrName == attrName ){ manifestData[pid].attributes[ attrName ].value = attrValue; // refresh the value manifestData[pid].attributes[ attrName ].$editVal.getEditValue( attrName ); } } } } } }; /** * Local getter methods */ function getJsonQuoteValue( attrName ){ var val = getAttrValue( attrName ) if( val === 'true' || val == 'false' ){ return val } return '"' + val + '"'; } function getAttrValue( attrName ){ var attrValue = ( typeof getVarObj( attrName ).value != 'undefined' ) ? getVarObj( attrName ).value : null; if( attrValue === true ) attrValue = 'true'; if( attrValue === false ) attrValue = 'false'; return attrValue; } function getAttrType( attrName ){ return getVarObj( attrName )['type'] || 'string'; } // jQuery method to support editing attributes $.fn.getEditValue = function( attrName ){ // switch on edit types: switch( getAttrType( attrName ) ){ case 'boolean': $( this ).html( $('<div class="btn-group" />').append( $('<a class="btn dropdown-toggle" data-toggle="dropdown" href="#" />' ).append( getAttrValue( attrName ) + ' ' + '<span class="caret"></span>' ), $('<ul class="dropdown-menu" />').append( $('<li />').append( $('<a href="#">true</a>').click(function(){ // activate button $('#btn-update-player-' + id ).removeClass('disabled'); setAttrValue(attrName, 'true' ); }) ), $('<li />').append( $('<a href="#">false</a>').click(function(){ // activate button $('#btn-update-player-' + id ).removeClass('disabled'); setAttrValue(attrName, 'false' ); }) ) ) ) ) $( this ).find('a').dropdown(); break; case 'enum': var $enumUlList = $('<ul class="dropdown-menu" />'); var valueObj = getVarObj( attrName ); var enumList = valueObj['enum']; $.each( enumList, function( inx, eVal ){ $enumUlList.append( $('<a href="#" />') .text( eVal ) .click(function(){ // activate button $('#btn-update-player-' + id ).removeClass('disabled'); setAttrValue( attrName, eVal ); }) ) }); $( this ).html( $('<div class="btn-group" />').append( $('<a class="btn dropdown-toggle" data-toggle="dropdown" href="#" />' ).append( getAttrValue( attrName ) + ' ' + '<span class="caret"></span>' ), $enumUlList ) ); $( this ).find('a').dropdown(); break; case 'color': var getHtmlColor = function(){ return getAttrValue( attrName ).replace('0x', '#' ); } var $colorSelector = $('<div />') .css({ 'width': '20px', 'height': '20px', 'border': 'solid thin black', 'backgroundColor' : getHtmlColor(), 'float' : 'left' }) .addClass('colorSelector') $( this ).empty().append( $colorSelector, $('<span />') .css( 'margin-left', '10px' ) .text( getHtmlColor() ) ) $colorSelector.ColorPicker({ color: getHtmlColor(), onShow: function ( colpkr ) { $( colpkr ).fadeIn( 500 ); return false; }, onHide: function (colpkr) { $( colpkr ).fadeOut( 500 ); return false; }, onChange: function (hsb, hex, rgb) { $colorSelector.css('backgroundColor', '#' + hex); // activate button $('#btn-update-player-' + id ).removeClass('disabled'); setAttrValue( attrName, '0x' + hex ); } }); break; case 'string': default: var activeEdit = false; var editHolder = this; var getValueDispaly = function( attrName ){ var attrValue = getAttrValue( attrName ) || '<i>null</i>'; if( getAttrType( attrName ) == 'url' && getAttrValue( attrName ) !== null ){ attrValue = $('<span />').append( $('<a />').attr({ 'href': getAttrValue( attrName ), 'target' : "_new" }).append( $('<i />').addClass('icon-share') ), attrValue ) } return attrValue } $( this ).css('overflow-x', 'hidden').html( getValueDispaly( attrName ) ).click(function(){ if( activeEdit ){ return ; } activeEdit = true; $( this ).html( $('<input type="text" style="width:100px" />').val( getAttrValue( attrName ) ) ); $( this ).find('input').focus() .bind('keyup', function(e){ // de-blur on enter: if( e.keyCode == '13' ){ $(this).blur(); } }) .blur( function() { // activate button $('#btn-update-player-' + id ).removeClass('disabled'); setAttrValue( attrName, $(this).val() ); $( editHolder ).html( getValueDispaly( attrName ) ); activeEdit = false; } ); }); break; } return $( this ); }; // end $.fn.getEditValue plugin function getAttrDesc( attrName ){ if( getVarObj( attrName )[ 'doc' ] ){ return getVarObj( attrName )[ 'doc' ]; } } function getAttrEdit(){ var $tableHead = $('<thead />').append( $('<tr><th style="width:140px">Attribute</th><th style="width:160px">Value</th><th>Description</th></tr>') ); var $mainPlugin = ''; var $tbody = $('<tbody />'); // for each setting get config if( manifestData[pluginName] ){ $.each( manifestData[pluginName].attributes, function( attrName, attr){ // only list "editable" attributes: if( !attr.hideEdit ){ // setup local pointer to $editVal: attr.$editVal = $('<div />').getEditValue( attrName ) ; $tbody.append( $('<tr />').append( $('<td />').text( attrName ), $('<td />').addClass('tdValue').append( attr.$editVal ), $('<td />').html( getAttrDesc( attrName ) ) ) ) } }); // add to main plugin: $mainPlugin = $('<table />') .addClass('table table-bordered table-striped') .append( $tableHead, $tbody ); } var $otherPlugins = $( '<div />' ); // Check for secondary plugins: $.each( manifestData, function( otherPluginId, pluginObject ){ if( pluginObject.attributes && pluginName != otherPluginId ){ $otherPlugins.append( $('<span />').text( pluginObject.description ) ); var $otherPluginTB = $('<tbody />'); $.each( pluginObject.attributes, function( attrName, attr ){ // for secondary plugins we only ad stuff for which we have fv // setup local pointer to $editVal: if( !attr.hideEdit && flashVars[ otherPluginId ][ attrName ] ){ attr.$editVal = $('<div />').getEditValue( attrName ) ; $otherPluginTB.append( $('<tr />').append( $('<td />').text( attrName ), $('<td />').addClass('tdValue').append( attr.$editVal ), $('<td />').html( getAttrDesc( attrName ) ) ) ) } }); $otherPlugins.append( $('<table />') .addClass('table table-bordered table-striped') .append( $tableHead.clone(), $otherPluginTB ) ); } }); // Check for flashvars: var $fvBody = ''; var $fvTbody = $('<tbody />'); $.each( manifestData, function( attrName, attr){ // check if we should skip the plugin if( attrName == pluginName || attr.attributes || attr.hideEdit ){ return true; } if( $fvBody == '' ){ $fvBody = $('<div />').append( $( '<b />').text( 'flashvars / uiConf vars:' ) ); } attr.$editVal = $('<div />').getEditValue( attrName ); $fvTbody.append( $('<tr />').append( $('<td />').text( attrName ), $('<td class="tdValue" />').append( attr.$editVal ), $('<td />').html( getAttrDesc( attrName ) ) ) ); }); if( $fvBody != '' ){ $fvBody.append( $('<table />') .addClass('table table-bordered table-striped') .append( $tableHead.clone(), $fvTbody ) ) } else { $fvBody = $(); } // Check for flashvar callback; var $updatePlayerBtn = flashvarCallback ? $( '<a id="btn-update-player-' + id +'" class="btn disabled">' ) .addClass('kdocUpdatePlayer') .text( 'Update player' ) .click( function(){ var flashvars = {}; $.each( manifestData, function( pName, attr ){ if( pName == pluginName || attr.attributes ){ $.each( manifestData[pName].attributes, function( attrName, attr ){ if( ! flashvars[ pName ] ){ flashvars[ pName ] = {}; } flashvars[ pName ] [ attrName ] = getAttrValue( attrName ); } ) } else { flashvars[ pName ] = attr.value; } }); flashvarCallback( flashvars ); // restore disabled class ( now that the player is up-to-date ) $( this ).addClass( 'disabled') } ): $(); return $('<div />').append( $mainPlugin, $otherPlugins, $fvBody, $updatePlayerBtn, $('<p>&nbsp;</p>') ) } function getFlashvarConfig(){ var fvText = "flashvars: {\n"; var mCount =0; $.each( manifestData, function( pName, attr ){ mCount++; }); var inx = 0; $.each( manifestData, function( pName, attr ){ var coma = ','; inx++; if( inx == mCount ){ coma = ''; } if( pName == pluginName ){ fvText+="\t\"" + pluginName +'": {' + "\n"; var aCount =0; $.each( manifestData[ pluginName].attributes, function( attrName, attr ){ if( !attr.hideEdit && getAttrValue( attrName) !== null ){ aCount++; } }); var aInx =0; $.each( manifestData[ pluginName].attributes, function( attrName, attr ){ if( !attr.hideEdit && getAttrValue( attrName) !== null ){ var aComa = ','; aInx++; if( aInx == aCount ){ aComa = ''; } fvText += "\t\t\"" + attrName + '\" : ' + getJsonQuoteValue( attrName ) + aComa +"\n"; } }) fvText+= "\t}" + coma + "\n"; } else { fvText += "\t\"" + pName + "\" : " + getJsonQuoteValue( pName ) + coma +"\n"; } }); fvText+="}\n"; return $('<div />').append( $('<pre class="prettyprint linenums" />').text( fvText ), $('<span>Flashvar JSON can be used with <a target="top" href="../../../docs/index.php?path=Embeding#kwidget">kWidget.embed</a>:</span>') ); } function getUiConfConfig(){ var uiText = ''; if( manifestData[ pluginName ] && manifestData[ pluginName ].attributes ){ uiText += '<Plugin id="' + pluginName + '" '; $.each( manifestData[ pluginName].attributes, function( attrName, attr){ if( attrName != 'plugin' && getAttrValue( attrName) !== null ){ uiText+= "\n\t" + attrName + '="' + getAttrValue( attrName ) + '" '; } }); // should be moved and or check for override uiText +="\n/>"; } // add uiConf vars $.each( manifestData, function( pAttrName, attr ){ if( pAttrName == pluginName ){ return true; } uiText += "\n" + '<var key="' + pAttrName + '" value="' + getAttrValue( pAttrName ) +'" />'; }); return $('<div />').append( $('<pre class="prettyprint linenums" />').text( uiText ), $('<span>UiConf XML can be inserted via <a target="top" href="http://www.kaltura.org/modifying-kdp-editing-uiconf-xml">KMC api</a>:</span>') ); } function getPlayerStudioLine(){ var plText =''; var and = ''; if( manifestData[ pluginName] ){ $.each( manifestData[ pluginName].attributes, function( attrName, attr){ // only for override ( only included edit attr ): if( !attr.hideEdit ){ plText += and + pluginName + '.' + attrName + '=' + getAttrValue( attrName ); and ='&'; } }) } // add top level flash vars: $.each( manifestData, function( pAttrName, attr ){ if( pAttrName == pluginName ){ return true; } plText += and + pAttrName + '=' + getAttrValue( pAttrName ); and ='&'; }); return $('<div />').append( $('<pre />').text( plText ), $( '<span>Can be used with the player studio <i>"additional paramaters"</i> plug-in line</span>') ) } // build the list of basevars var baseVarsList = ''; $.each( flashVars, function( fvKey, fvValue ){ baseVarsList+= fvKey + ','; }) // get the attributes from the manifest for this plugin: // testing files always ../../ from test var request = window.kDocPath + 'configManifest.php?plugin_id=' + pluginName + '&vars=' + baseVarsList; $.getJSON( request, function( data ){ // check for error: if( data.error ){ $( _this ).html( data.error ); return ; } manifestData = data; // merge in player config values into manifestData $.each( flashVars, function( fvKey, fvValue ){ if( fvKey == pluginName ){ for( var pk in fvValue ){ if( ! manifestData[ pluginName ].attributes[ pk ] ){ manifestData[ pluginName ].attributes[ pk ] = {}; } manifestData[ pluginName ].attributes[ pk ].value = fvValue[pk]; } // continue return true; } // Check for prefixed vars ( pluginName.varKey ) if( fvKey.indexOf( pluginName ) === 0 ){ var fvParts = fvKey.split('.'); manifestData[ pluginName ].attributes[ fvParts[1] ] = fvValue; // continue return true; } if( typeof fvValue == 'object' ){ for( var pk in fvValue ){ if( ! manifestData[ fvKey ].attributes[ pk ] ){ manifestData[ fvKey ].attributes[ pk ] = {}; } manifestData[ fvKey ].attributes[ pk ].value = fvValue[pk]; } } else { if( !manifestData[ fvKey ] ){ manifestData[ fvKey ] = {}; } manifestData[ fvKey ].value = fvValue; } }); $textDesc = ''; if( manifestData[ pluginName ] && manifestData[ pluginName ]['description'] ){ $textDesc = $('<div />').html( manifestData[ pluginName ]['description'] ); } function getEditTabs(){ // output tabs: return $('<div class="tabbable tabs-left" />') .css('width', '800px') .append( $('<ul class="nav nav-tabs" />').append( '<li><a data-getter="getAttrEdit" href="#tab-docs-' + id +'" data-toggle="tab">edit</a></li>' + '<li><a data-getter="getFlashvarConfig" href="#tab-flashvars-' + id +'" data-toggle="tab">flashvars</a></li>' + '<li><a data-getter="getUiConfConfig" href="#tab-uiconf-' + id + '" data-toggle="tab">uiConf</a></li>' + '<li><a data-getter="getPlayerStudioLine" href="#tab-pstudio-'+ id +'" data-toggle="tab">player studio line</a></li>' ), $('<div class="tab-content" />').append( $('<div class="tab-pane active" id="tab-docs-' + id + '" />'), $('<div class="tab-pane active" id="tab-flashvars-' + id + '" />'), $('<div class="tab-pane active" id="tab-uiconf-' + id + '" />'), $('<div class="tab-pane active" id="tab-pstudio-' + id + '" />') ) ) } /** * outputs the settings file */ function getSettings(){ $('#tab-settings-' + id ).text('settings'); } var once = false; function showEditTab(){ if( !once ){ $( _this ).find( 'a[data-getter="getAttrEdit"]' ).click(); } once = true; } $( _this ).empty().append( $('<div />') .css({ 'width': '800px', 'margin-bottom': '10px' }) .append( $('<ul class="nav nav-tabs" />').append( '<li><a href="#tab-desc-' + id +'" data-toggle="tab">Description</a></li>' + '<li><a data-getter="showEditTab" href="#tab-edit-' + id +'" data-toggle="tab">Integrate</a></li>' + '<li><a data-getter="getSettings" href="#tab-settings-' + id +'" data-toggle="tab">Settings</a></li>' ), $('<div class="tab-content" />').append( $('<div class="tab-pane active" id="tab-desc-' + id + '" />').append( $textDesc ), $('<div class="tab-pane active" id="tab-edit-' + id + '" />').append( getEditTabs() ), $('<div class="tab-pane active" id="tab-settings-' + id + '" />') ) ) ); // setup show bindings $( _this ).find('a[data-toggle="tab"]').on('show', function( e ){ // check for data-getter: if( $( this ).attr( 'data-getter' ) ){ $( $( this ).attr( 'href' ) ).html( eval( $( this ).attr( 'data-getter' ) + '()' ) ) } // make the code pretty window.prettyPrint && prettyPrint(); // make sure ( if in an iframe ) the content size is insync: if( parent && parent['sycnIframeContentHeight'] ) { parent.sycnIframeContentHeight(); } }); // show the first tab: $( _this ).find('.nav-tabs a:first').tab('show'); }); }); // each plugin closure } })( jQuery );
docs/js/jquery.prettyKalturaConfig.js
// Add a jQuery plugin for pretty kaltura docs (function( $ ){ $.fn.prettyKalturaConfig = function( pluginName, flashVars, flashvarCallback ){ var manifestData = {}; return this.each(function() { /** * Init */ // Setup _this pointer var _this = this; // setup master id for ( this ) var id = $(this).attr('id'); // set the target to loading while documentation is loaded $( this ).html('Loading <span class="blink">...</span>'); var _this = this; /** * get a var object from plugin style location or from top level var */ function getVarObj( attrName ){ // Check for plugin config: if( manifestData[pluginName] && manifestData[pluginName].attributes && manifestData[pluginName].attributes[ attrName ] ) { return manifestData[pluginName].attributes[ attrName ]; } // Check other plugins for( var pid in manifestData ){ if( manifestData[ pid ] && manifestData[ pid ].attributes && manifestData[ pid ].attributes[ attrName ] ) { return manifestData[ pid ].attributes[ attrName ]; } } // Check for raw value object: if( manifestData[attrName] ){ return manifestData[attrName]; } return {}; } /** * Set an attr value */ function setAttrValue( attrName, attrValue ){ if( manifestData[pluginName] && manifestData[pluginName].attributes && manifestData[pluginName].attributes[ attrName ] ){ manifestData[pluginName].attributes[ attrName ].value = attrValue; // refresh the value manifestData[pluginName].attributes[ attrName ].$editVal.getEditValue( attrName ); } else if( manifestData[attrName] ){ manifestData[attrName].value = attrValue; // refresh the value manifestData[attrName].$editVal.getEditValue( attrName ); } else { // look for other plugins with this property: for( var pid in manifestData ){ if( manifestData[pid].attributes ){ for( var pAttrName in manifestData[pid].attributes ){ if( pAttrName == attrName ){ manifestData[pid].attributes[ attrName ].value = attrValue; // refresh the value manifestData[pid].attributes[ attrName ].$editVal.getEditValue( attrName ); } } } } } }; /** * Local getter methods */ function getJsonQuoteValue( attrName ){ var val = getAttrValue( attrName ) if( val === 'true' || val == 'false' ){ return val } return '"' + val + '"'; } function getAttrValue( attrName ){ var attrValue = ( typeof getVarObj( attrName ).value != 'undefined' ) ? getVarObj( attrName ).value : null; if( attrValue === true ) attrValue = 'true'; if( attrValue === false ) attrValue = 'false'; return attrValue; } function getAttrType( attrName ){ return getVarObj( attrName )['type'] || 'string'; } // jQuery method to support editing attributes $.fn.getEditValue = function( attrName ){ // switch on edit types: switch( getAttrType( attrName ) ){ case 'boolean': $( this ).html( $('<div class="btn-group" />').append( $('<a class="btn dropdown-toggle" data-toggle="dropdown" href="#" />' ).append( getAttrValue( attrName ) + ' ' + '<span class="caret"></span>' ), $('<ul class="dropdown-menu" />').append( $('<li />').append( $('<a href="#">true</a>').click(function(){ // activate button $('#btn-update-player-' + id ).removeClass('disabled'); setAttrValue(attrName, 'true' ); }) ), $('<li />').append( $('<a href="#">false</a>').click(function(){ // activate button $('#btn-update-player-' + id ).removeClass('disabled'); setAttrValue(attrName, 'false' ); }) ) ) ) ) $( this ).find('a').dropdown(); break; case 'enum': var $enumUlList = $('<ul class="dropdown-menu" />'); var valueObj = getVarObj( attrName ); var enumList = valueObj['enum']; $.each( enumList, function( inx, eVal ){ $enumUlList.append( $('<a href="#" />') .text( eVal ) .click(function(){ // activate button $('#btn-update-player-' + id ).removeClass('disabled'); setAttrValue( attrName, eVal ); }) ) }); $( this ).html( $('<div class="btn-group" />').append( $('<a class="btn dropdown-toggle" data-toggle="dropdown" href="#" />' ).append( getAttrValue( attrName ) + ' ' + '<span class="caret"></span>' ), $enumUlList ) ); $( this ).find('a').dropdown(); break; case 'color': var getHtmlColor = function(){ return getAttrValue( attrName ).replace('0x', '#' ); } var $colorSelector = $('<div />') .css({ 'width': '20px', 'height': '20px', 'border': 'solid thin black', 'backgroundColor' : getHtmlColor(), 'float' : 'left' }) .addClass('colorSelector') $( this ).empty().append( $colorSelector, $('<span />') .css( 'margin-left', '10px' ) .text( getHtmlColor() ) ) $colorSelector.ColorPicker({ color: getHtmlColor(), onShow: function ( colpkr ) { $( colpkr ).fadeIn( 500 ); return false; }, onHide: function (colpkr) { $( colpkr ).fadeOut( 500 ); return false; }, onChange: function (hsb, hex, rgb) { $colorSelector.css('backgroundColor', '#' + hex); // activate button $('#btn-update-player-' + id ).removeClass('disabled'); setAttrValue( attrName, '0x' + hex ); } }); break; case 'string': default: var activeEdit = false; var editHolder = this; var getValueDispaly = function( attrName ){ var attrValue = getAttrValue( attrName ) || '<i>null</i>'; if( getAttrType( attrName ) == 'url' && getAttrValue( attrName ) !== null ){ attrValue = $('<span />').append( $('<a />').attr({ 'href': getAttrValue( attrName ), 'target' : "_new" }).append( $('<i />').addClass('icon-share') ), attrValue ) } return attrValue } $( this ).css('overflow-x', 'hidden').html( getValueDispaly( attrName ) ).click(function(){ if( activeEdit ){ return ; } activeEdit = true; $( this ).html( $('<input type="text" style="width:100px" />').val( getAttrValue( attrName ) ) ); $( this ).find('input').focus() .bind('keyup', function(e){ // de-blur on enter: if( e.keyCode == '13' ){ $(this).blur(); } }) .blur( function() { // activate button $('#btn-update-player-' + id ).removeClass('disabled'); setAttrValue( attrName, $(this).val() ); $( editHolder ).html( getValueDispaly( attrName ) ); activeEdit = false; } ); }); break; } return $( this ); }; // end $.fn.getEditValue plugin function getAttrDesc( attrName ){ if( getVarObj( attrName )[ 'doc' ] ){ return getVarObj( attrName )[ 'doc' ]; } } function getAttrEdit(){ var $tableHead = $('<thead />').append( $('<tr><th style="width:140px">Attribute</th><th style="width:160px">Value</th><th>Description</th></tr>') ); var $mainPlugin = ''; var $tbody = $('<tbody />'); // for each setting get config if( manifestData[pluginName] ){ $.each( manifestData[pluginName].attributes, function( attrName, attr){ // only list "editable" attributes: if( !attr.hideEdit ){ // setup local pointer to $editVal: attr.$editVal = $('<div />').getEditValue( attrName ) ; $tbody.append( $('<tr />').append( $('<td />').text( attrName ), $('<td />').addClass('tdValue').append( attr.$editVal ), $('<td />').html( getAttrDesc( attrName ) ) ) ) } }); // add to main plugin: $mainPlugin = $('<table />') .addClass('table table-bordered table-striped') .append( $tableHead, $tbody ); } var $otherPlugins = $( '<div />' ); // Check for secondary plugins: $.each( manifestData, function( otherPluginId, pluginObject ){ if( pluginObject.attributes && pluginName != otherPluginId ){ $otherPlugins.append( $('<span />').text( pluginObject.description ) ); var $otherPluginTB = $('<tbody />'); $.each( pluginObject.attributes, function( attrName, attr ){ // for secondary plugins we only ad stuff for which we have fv // setup local pointer to $editVal: if( !attr.hideEdit && flashVars[ otherPluginId ][ attrName ] ){ attr.$editVal = $('<div />').getEditValue( attrName ) ; $otherPluginTB.append( $('<tr />').append( $('<td />').text( attrName ), $('<td />').addClass('tdValue').append( attr.$editVal ), $('<td />').html( getAttrDesc( attrName ) ) ) ) } }); $otherPlugins.append( $('<table />') .addClass('table table-bordered table-striped') .append( $tableHead.clone(), $otherPluginTB ) ); } }); // Check for flashvars: var $fvBody = ''; var $fvTbody = $('<tbody />'); $.each( manifestData, function( attrName, attr){ // check if we should skip the plugin if( attrName == pluginName || attr.attributes || attr.hideEdit ){ return true; } if( $fvBody == '' ){ $fvBody = $('<div />').append( $( '<b />').text( 'flashvars / uiConf vars:' ) ); } attr.$editVal = $('<div />').getEditValue( attrName ); $fvTbody.append( $('<tr />').append( $('<td />').text( attrName ), $('<td class="tdValue" />').append( attr.$editVal ), $('<td />').html( getAttrDesc( attrName ) ) ) ); }); if( $fvBody != '' ){ $fvBody.append( $('<table />') .addClass('table table-bordered table-striped') .append( $tableHead.clone(), $fvTbody ) ) } else { $fvBody = $(); } // Check for flashvar callback; var $updatePlayerBtn = flashvarCallback ? $( '<a id="btn-update-player-' + id +'" class="btn disabled">' ) .addClass('kdocUpdatePlayer') .text( 'Update player' ) .click( function(){ var flashvars = {}; $.each( manifestData, function( pName, attr ){ if( pName == pluginName || attr.attributes ){ $.each( manifestData[pName].attributes, function( attrName, attr ){ if( ! flashvars[ pName ] ){ flashvars[ pName ] = {}; } flashvars[ pName ] [ attrName ] = getAttrValue( attrName ); } ) } else { flashvars[ pName ] = attr.value; } }); flashvarCallback( flashvars ); // restore disabled class ( now that the player is up-to-date ) $( this ).addClass( 'disabled') } ): $(); return $('<div />').append( $mainPlugin, $otherPlugins, $fvBody, $updatePlayerBtn, $('<p>&nbsp;</p>') ) } function getFlashvarConfig(){ var fvText = "flashvars: {\n"; var mCount =0; $.each( manifestData, function( pName, attr ){ mCount++; }); var inx = 0; $.each( manifestData, function( pName, attr ){ var coma = ','; inx++; if( inx == mCount ){ coma = ''; } if( pName == pluginName ){ fvText+="\t\"" + pluginName +'": {' + "\n"; var aCount =0; $.each( manifestData[ pluginName].attributes, function( attrName, attr ){ if( !attr.hideEdit && getAttrValue( attrName) !== null ){ aCount++; } }); var aInx =0; $.each( manifestData[ pluginName].attributes, function( attrName, attr ){ if( !attr.hideEdit && getAttrValue( attrName) !== null ){ var aComa = ','; aInx++; if( aInx == aCount ){ aComa = ''; } fvText += "\t\t\"" + attrName + '\" : ' + getJsonQuoteValue( attrName ) + aComa +"\n"; } }) fvText+= "\t}" + coma + "\n"; } else { fvText += "\t\"" + pName + "\" : " + getJsonQuoteValue( pName ) + coma +"\n"; } }); fvText+="}\n"; return $('<div />').append( $('<pre class="prettyprint linenums" />').text( fvText ), $('<span>Flashvar JSON can be used with <a target="top" href="../../../docs/index.php?path=Embeding#kwidget">kWidget.embed</a>:</span>') ); } function getUiConfConfig(){ var uiText = ''; if( manifestData[ pluginName ] && manifestData[ pluginName ].attributes ){ uiText += '<Plugin id="' + pluginName + '" '; $.each( manifestData[ pluginName].attributes, function( attrName, attr){ if( attrName != 'plugin' && getAttrValue( attrName) !== null ){ uiText+= "\n\t" + attrName + '="' + getAttrValue( attrName ) + '" '; } }); // should be moved and or check for override uiText +="\n/>"; } // add uiConf vars $.each( manifestData, function( pAttrName, attr ){ if( pAttrName == pluginName ){ return true; } uiText += "\n" + '<var key="' + pAttrName + '" value="' + getAttrValue( pAttrName ) +'" />'; }); return $('<div />').append( $('<pre class="prettyprint linenums" />').text( uiText ), $('<span>UiConf XML can be inserted via <a target="top" href="http://www.kaltura.org/modifying-kdp-editing-uiconf-xml">KMC api</a>:</span>') ); } function getPlayerStudioLine(){ var plText =''; var and = ''; if( manifestData[ pluginName] ){ $.each( manifestData[ pluginName].attributes, function( attrName, attr){ // only for override ( only included edit attr ): if( !attr.hideEdit ){ plText += and + pluginName + '.' + attrName + '=' + getAttrValue( attrName ); and ='&'; } }) } // add top level flash vars: $.each( manifestData, function( pAttrName, attr ){ if( pAttrName == pluginName ){ return true; } plText += and + pAttrName + '=' + getAttrValue( pAttrName ); and ='&'; }); return $('<div />').append( $('<pre />').text( plText ), $( '<span>Can be used with the player studio <i>"additional paramaters"</i> plug-in line</span>') ) } /** * outputs the settings file */ function getSettings(){ } // build the list of basevars var baseVarsList = ''; $.each( flashVars, function( fvKey, fvValue ){ baseVarsList+= fvKey + ','; }) // get the attributes from the manifest for this plugin: // testing files always ../../ from test var request = window.kDocPath + 'configManifest.php?plugin_id=' + pluginName + '&vars=' + baseVarsList; $.getJSON( request, function( data ){ // check for error: if( data.error ){ $( _this ).html( data.error ); return ; } manifestData = data; // merge in player config values into manifestData $.each( flashVars, function( fvKey, fvValue ){ if( fvKey == pluginName ){ for( var pk in fvValue ){ if( ! manifestData[ pluginName ].attributes[ pk ] ){ manifestData[ pluginName ].attributes[ pk ] = {}; } manifestData[ pluginName ].attributes[ pk ].value = fvValue[pk]; } // continue return true; } // Check for prefixed vars ( pluginName.varKey ) if( fvKey.indexOf( pluginName ) === 0 ){ var fvParts = fvKey.split('.'); manifestData[ pluginName ].attributes[ fvParts[1] ] = fvValue; // continue return true; } if( typeof fvValue == 'object' ){ for( var pk in fvValue ){ if( ! manifestData[ fvKey ].attributes[ pk ] ){ manifestData[ fvKey ].attributes[ pk ] = {}; } manifestData[ fvKey ].attributes[ pk ].value = fvValue[pk]; } } else { if( !manifestData[ fvKey ] ){ manifestData[ fvKey ] = {}; } manifestData[ fvKey ].value = fvValue; } }); $textDesc = ''; if( manifestData[ pluginName ] && manifestData[ pluginName ]['description'] ){ $textDesc = $('<div />').html( manifestData[ pluginName ]['description'] ); } function getEditTabs(){ // output tabs: return $('<div class="tabbable tabs-left" />') .css('width', '800px') .append( $('<ul class="nav nav-tabs" />').append( '<li><a data-getter="getAttrEdit" href="#tab-docs-' + id +'" data-toggle="tab">edit</a></li>' + '<li><a data-getter="getFlashvarConfig" href="#tab-flashvars-' + id +'" data-toggle="tab">flashvars</a></li>' + '<li><a data-getter="getUiConfConfig" href="#tab-uiconf-' + id + '" data-toggle="tab">uiConf</a></li>' + '<li><a data-getter="getPlayerStudioLine" href="#tab-pstudio-'+ id +'" data-toggle="tab">player studio line</a></li>' ), $('<div class="tab-content" />').append( $('<div class="tab-pane active" id="tab-docs-' + id + '" />'), $('<div class="tab-pane active" id="tab-flashvars-' + id + '" />'), $('<div class="tab-pane active" id="tab-uiconf-' + id + '" />'), $('<div class="tab-pane active" id="tab-pstudio-' + id + '" />') ) ) } var once = false; function showEditTab(){ if( !once ){ $( _this ).find( 'a[data-getter="getAttrEdit"]' ).click(); } once = true; } $( _this ).empty().append( $('<div />') .css({ 'width': '800px', 'margin-bottom': '10px' }) .append( $('<ul class="nav nav-tabs" />').append( '<li><a href="#tab-desc-' + id +'" data-toggle="tab">Description</a></li>' + '<li><a data-getter="showEditTab" href="#tab-edit-' + id +'" data-toggle="tab">Edit</a></li>' + '<li><a href="#tab-settings-' + id +'" data-toggle="tab">Settings</a></li>' ), $('<div class="tab-content" />').append( $('<div class="tab-pane active" id="tab-desc-' + id + '" />').append( $textDesc ), $('<div class="tab-pane active" id="tab-edit-' + id + '" />').append( getEditTabs() ), $('<div data-getter="getSettings" class="tab-pane active" id="tab-settings-' + id + '" />') ) ) ); // setup show bindings $( _this ).find('a[data-toggle="tab"]').on('show', function( e ){ // check for data-getter: if( $( this ).attr( 'data-getter' ) ){ $( $( this ).attr( 'href' ) ).html( eval( $( this ).attr( 'data-getter' ) + '()' ) ) } // make the code pretty window.prettyPrint && prettyPrint(); // make sure ( if in an iframe ) the content size is insync: if( parent && parent['sycnIframeContentHeight'] ) { parent.sycnIframeContentHeight(); } }); // show the first tab: $( _this ).find('.nav-tabs a:first').tab('show'); }); }); // each plugin closure } })( jQuery );
adds support for settings tab
docs/js/jquery.prettyKalturaConfig.js
adds support for settings tab
<ide><path>ocs/js/jquery.prettyKalturaConfig.js <ide> ) <ide> } <ide> <del> /** <del> * outputs the settings file <del> */ <del> function getSettings(){ <del> <del> } <del> <ide> <ide> // build the list of basevars <ide> var baseVarsList = ''; <ide> ) <ide> ) <ide> } <add> /** <add> * outputs the settings file <add> */ <add> function getSettings(){ <add> $('#tab-settings-' + id ).text('settings'); <add> } <add> <ide> var once = false; <ide> function showEditTab(){ <ide> if( !once ){ <ide> .append( <ide> $('<ul class="nav nav-tabs" />').append( <ide> '<li><a href="#tab-desc-' + id +'" data-toggle="tab">Description</a></li>' + <del> '<li><a data-getter="showEditTab" href="#tab-edit-' + id +'" data-toggle="tab">Edit</a></li>' + <del> '<li><a href="#tab-settings-' + id +'" data-toggle="tab">Settings</a></li>' <add> '<li><a data-getter="showEditTab" href="#tab-edit-' + id +'" data-toggle="tab">Integrate</a></li>' + <add> '<li><a data-getter="getSettings" href="#tab-settings-' + id +'" data-toggle="tab">Settings</a></li>' <ide> ), <ide> $('<div class="tab-content" />').append( <ide> $('<div class="tab-pane active" id="tab-desc-' + id + '" />').append( $textDesc ), <ide> $('<div class="tab-pane active" id="tab-edit-' + id + '" />').append( getEditTabs() ), <del> $('<div data-getter="getSettings" class="tab-pane active" id="tab-settings-' + id + '" />') <add> $('<div class="tab-pane active" id="tab-settings-' + id + '" />') <ide> ) <ide> ) <ide>
Java
mpl-2.0
d3953f3b17efd07fe5c59a25cdd9664f9bd9b2bb
0
amagdenko/oiosaml.java,amagdenko/oiosaml.java,amagdenko/oiosaml.java,amagdenko/oiosaml.java
/* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express * or implied. See the License for the specific language governing * rights and limitations under the License. * * * The Original Code is OIOSAML Trust Client. * * The Initial Developer of the Original Code is Trifork A/S. Portions * created by Trifork A/S are Copyright (C) 2008 Danish National IT * and Telecom Agency (http://www.itst.dk). All Rights Reserved. * * Contributor(s): * Joakim Recht <[email protected]> * */ package dk.itst.oiosaml.trust; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.xml.crypto.MarshalException; import javax.xml.crypto.dom.DOMStructure; import javax.xml.crypto.dsig.CanonicalizationMethod; import javax.xml.crypto.dsig.DigestMethod; import javax.xml.crypto.dsig.Reference; import javax.xml.crypto.dsig.SignatureMethod; import javax.xml.crypto.dsig.SignedInfo; import javax.xml.crypto.dsig.Transform; import javax.xml.crypto.dsig.XMLSignature; import javax.xml.crypto.dsig.XMLSignatureException; import javax.xml.crypto.dsig.XMLSignatureFactory; import javax.xml.crypto.dsig.dom.DOMSignContext; import javax.xml.crypto.dsig.keyinfo.KeyInfo; import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; import javax.xml.crypto.dsig.keyinfo.X509Data; import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec; import javax.xml.crypto.dsig.spec.ExcC14NParameterSpec; import javax.xml.crypto.dsig.spec.TransformParameterSpec; import javax.xml.namespace.QName; import org.apache.log4j.Logger; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.core.Assertion; import org.opensaml.ws.soap.soap11.Body; import org.opensaml.ws.soap.soap11.Envelope; import org.opensaml.ws.soap.soap11.Header; import org.opensaml.ws.wsaddressing.Action; import org.opensaml.ws.wsaddressing.Address; import org.opensaml.ws.wsaddressing.MessageID; import org.opensaml.ws.wsaddressing.ReplyTo; import org.opensaml.ws.wsaddressing.To; import org.opensaml.ws.wssecurity.Created; import org.opensaml.ws.wssecurity.Expires; import org.opensaml.ws.wssecurity.KeyIdentifier; import org.opensaml.ws.wssecurity.Security; import org.opensaml.ws.wssecurity.SecurityTokenReference; import org.opensaml.ws.wssecurity.Timestamp; import org.opensaml.ws.wssecurity.WSSecurityConstants; import org.opensaml.xml.AttributeExtensibleXMLObject; import org.opensaml.xml.XMLObject; import org.opensaml.xml.schema.XSAny; import org.opensaml.xml.schema.XSBooleanValue; import org.opensaml.xml.schema.impl.XSAnyBuilder; import org.opensaml.xml.security.x509.X509Credential; import org.opensaml.xml.signature.Signature; import org.opensaml.xml.util.XMLHelper; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import dk.itst.oiosaml.common.SAMLUtil; import dk.itst.oiosaml.sp.model.OIOSamlObject; import dk.itst.oiosaml.sp.service.util.Utils; import dk.itst.oiosaml.trust.internal.SignatureFactory; /** * Wrap a generic SOAP envelope. * * This class adds some behavior to generic soap envelopes. Use this class to handle signatures, header elements, and other common operations. * * @author recht * */ public class OIOSoapEnvelope { private static final Logger log = Logger.getLogger(OIOSoapEnvelope.class); private Map<XMLObject, String> references = new HashMap<XMLObject, String>(); private final Envelope envelope; private Security security; private Body body; private XMLSignatureFactory xsf; private Assertion securityToken; private SecurityTokenReference securityTokenReference; public OIOSoapEnvelope(Envelope envelope) { this(envelope, false); } /** * Wrap an existing envelope. * * @param envelope * @param signHeaderElements If <code>true</code>, all the header elements in the envelope are marked for signature. */ public OIOSoapEnvelope(Envelope envelope, boolean signHeaderElements) { if (envelope == null) throw new IllegalArgumentException("Envelope cannot be null"); this.envelope = envelope; xsf = SignatureFactory.getInstance(); security = SAMLUtil.getFirstElement(envelope.getHeader(), Security.class); if (signHeaderElements) { if (security == null) { security = SAMLUtil.buildXMLObject(Security.class); security.setMustUnderstand(new XSBooleanValue(true, true)); envelope.getHeader().getUnknownXMLObjects().add(security); } for (XMLObject o : envelope.getHeader().getUnknownXMLObjects()) { if (o instanceof AttributeExtensibleXMLObject) { if (o instanceof Security) continue; addSignatureElement((AttributeExtensibleXMLObject) o); } } } } private OIOSoapEnvelope(Envelope envelope, MessageID msgId, XSAny framework) { this(envelope); addSignatureElement(msgId); addSignatureElement(framework); } /** * Build a new soap envelope with standard OIO headers. * * Standard headers include sbf:Framework, wsa:MessageID, and an empty Security header. */ public static OIOSoapEnvelope buildEnvelope() { Envelope env = SAMLUtil.buildXMLObject(Envelope.class); Header header = SAMLUtil.buildXMLObject(Header.class); env.setHeader(header); MessageID msgId = SAMLUtil.buildXMLObject(MessageID.class); msgId.setValue(UUID.randomUUID().toString()); header.getUnknownXMLObjects().add(msgId); XSAny framework = new XSAnyBuilder().buildObject("urn:liberty:sb:2006-08", "Framework", "sbf"); framework.getUnknownAttributes().put(new QName("version"), "2.0"); framework.getUnknownAttributes().put(new QName("urn:liberty:sb:eGovprofile", "profile"), "urn:liberty:sb:profile:basicegovsimple"); header.getUnknownXMLObjects().add(framework); Security security = SAMLUtil.buildXMLObject(Security.class); security.setMustUnderstand(new XSBooleanValue(true, true)); header.getUnknownXMLObjects().add(security); return new OIOSoapEnvelope(env, msgId, framework); } public void setBody(XMLObject request) { body = SAMLUtil.buildXMLObject(Body.class); body.getUnknownXMLObjects().add(request); addSignatureElement(body); envelope.setBody(body); } public void setAction(String action) { Action a = SAMLUtil.buildXMLObject(Action.class); a.setValue(action); envelope.getHeader().getUnknownXMLObjects().add(a); addSignatureElement(a); } public void addSecurityToken(Assertion token) { security.getUnknownXMLObjects().add(token); } /** * Insert a token and a SecurityTokenReference pointing to the token. */ public void addSecurityTokenReference(Assertion token) { if (token == null) return; token.detach(); securityToken = token; addSecurityToken(token); securityTokenReference = createSecurityTokenReference(token); security.getUnknownXMLObjects().add(securityTokenReference); } private SecurityTokenReference createSecurityTokenReference(Assertion token) { SecurityTokenReference str = SAMLUtil.buildXMLObject(SecurityTokenReference.class); str.setTokenType(WSSecurityConstants.WSSE11_SAML_TOKEN_PROFILE_NS + "#SAMLV2.0"); str.setId(Utils.generateUUID()); KeyIdentifier keyIdentifier = SAMLUtil.buildXMLObject(KeyIdentifier.class); keyIdentifier.setValueType(WSSecurityConstants.WSSE11_SAML_TOKEN_PROFILE_NS + "#SAMLID"); keyIdentifier.setValue(token.getID()); str.setKeyIdentifier(keyIdentifier); return str; } /** * Check if this envelope relates to a specific message id. */ public boolean relatesTo(String messageId) { if (envelope.getHeader() == null) return false; List<XMLObject> objects = envelope.getHeader().getUnknownXMLObjects(TrustConstants.WSA_RELATES_TO); if (objects.isEmpty()) return false; XMLObject object = objects.get(0); String relatesTo; if (object instanceof XSAny) { relatesTo = ((XSAny)object).getTextContent(); } else { Element e = SAMLUtil.marshallObject(object); relatesTo = e.getTextContent().trim(); } return messageId.equals(relatesTo); } /** * Add a timestamp to the Security header. * @param timestampSkew How many minutes before the message should expire. */ public void setTimestamp(int timestampSkew) { DateTime now = new DateTime().toDateTime(DateTimeZone.UTC); Timestamp timestamp = SAMLUtil.buildXMLObject(Timestamp.class); Created created = SAMLUtil.buildXMLObject(Created.class); created.setDateTime(now.minusMinutes(timestampSkew)); timestamp.setCreated(created); Expires exp = SAMLUtil.buildXMLObject(Expires.class); exp.setDateTime(now.plusMinutes(timestampSkew)); timestamp.setExpires(exp); security.getUnknownXMLObjects().add(timestamp); addSignatureElement(timestamp); } /** * Get the first element of the envelope body. */ public XMLObject getBody() { return envelope.getBody().getUnknownXMLObjects().get(0); } /** * Sign the SOAP envelope and return the signed DOM element. * * @param credential Credentials to use for signing. * @return The signed dom element. * @throws NoSuchAlgorithmException * @throws InvalidAlgorithmParameterException * @throws MarshalException * @throws XMLSignatureException */ public Element sign(X509Credential credential) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException { CanonicalizationMethod canonicalizationMethod = xsf.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); SignatureMethod signatureMethod = xsf.newSignatureMethod(SignatureMethod.RSA_SHA1, null); List<Reference> refs = new ArrayList<Reference>(); DigestMethod digestMethod = xsf.newDigestMethod(DigestMethod.SHA1, null); List<Transform> transforms = new ArrayList<Transform>(2); transforms.add(xsf.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#",new ExcC14NParameterSpec(Collections.singletonList("xsd")))); for (Map.Entry<XMLObject, String> ref : references.entrySet()) { Reference r = xsf.newReference("#"+ref.getValue(), digestMethod, transforms, null, null); refs.add(r); } SAMLUtil.marshallObject(envelope); if (securityTokenReference != null) { transforms = new ArrayList<Transform>(); Document doc = envelope.getDOM().getOwnerDocument(); Element tp = XMLHelper.constructElement(doc, WSSecurityConstants.WSSE_NS, "TransformationParameters", WSSecurityConstants.WSSE_PREFIX); Element cm = XMLHelper.constructElement(doc, XMLSignature.XMLNS, "CanonicalizationMethod", "ds"); tp.appendChild(cm); cm.setAttribute("Algorithm", "http://www.w3.org/2001/10/xml-exc-c14n#"); transforms.add(SignatureFactory.getInstance().newTransform("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#STR-Transform", new DOMStructure(tp))); Reference r = xsf.newReference("#"+securityTokenReference.getId(), digestMethod, transforms, null, null); refs.add(r); } // Create the SignedInfo SignedInfo signedInfo = xsf.newSignedInfo(canonicalizationMethod, signatureMethod, refs); KeyInfoFactory keyInfoFactory = xsf.getKeyInfoFactory(); KeyInfo ki; if (isHolderOfKey()) { DOMStructure info = new DOMStructure(SAMLUtil.marshallObject(createSecurityTokenReference(securityToken))); ki = keyInfoFactory.newKeyInfo(Collections.singletonList(info)); } else { X509Data x509Data = keyInfoFactory.newX509Data(Collections.singletonList(credential.getEntityCertificate())); ki = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data)); } XMLSignature signature = xsf.newXMLSignature(signedInfo, ki); String xml = XMLHelper.nodeToString(envelope.getDOM()); log.debug("Signing envelope: " + xml); Element element = SAMLUtil.loadElementFromString(xml); Node security = element.getElementsByTagNameNS(WSSecurityConstants.WSSE_NS, "Security").item(0); DOMSignContext signContext = new DOMSignContext(credential.getPrivateKey(), security); signContext.putNamespacePrefix(SAMLConstants.XMLSIG_NS, SAMLConstants.XMLSIG_PREFIX); signContext.putNamespacePrefix(SAMLConstants.XMLENC_NS, SAMLConstants.XMLENC_PREFIX); for (XMLObject o : references.keySet()) { NodeList nl = element.getElementsByTagNameNS(o.getDOM().getNamespaceURI(), o.getDOM().getLocalName()); for (int i = 0; i < nl.getLength(); i++) { Element e = (Element) nl.item(i); if (e.hasAttributeNS(WSSecurityConstants.WSU_NS, "Id")) { signContext.setIdAttributeNS(e, WSSecurityConstants.WSU_NS, "Id"); e.setIdAttributeNS(WSSecurityConstants.WSU_NS, "Id", true); } } } if (securityTokenReference != null) { NodeList nl = element.getElementsByTagNameNS(SecurityTokenReference.ELEMENT_NAME.getNamespaceURI(), SecurityTokenReference.ELEMENT_LOCAL_NAME); for (int i = 0; i < nl.getLength(); i++) { Element e = (Element) nl.item(i); e.setIdAttributeNS(WSSecurityConstants.WSU_NS, "Id", true); } nl = element.getElementsByTagNameNS(securityToken.getElementQName().getNamespaceURI(), securityToken.getElementQName().getLocalPart()); for (int i = 0; i < nl.getLength(); i++) { Element e = (Element) nl.item(i); if (e.hasAttribute("ID")) { e.setIdAttributeNS(null, "ID", true); } if (e.hasAttributeNS(WSSecurityConstants.WSU_NS, "Id")) { e.setIdAttributeNS(WSSecurityConstants.WSU_NS, "Id", true); } } } // Marshal, generate (and sign) the detached XMLSignature. The DOM // Document will contain the XML Signature if this method returns // successfully. // HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not allow children of the type of the newChild node, or if the node to insert is one of this node's ancestors. signature.sign(signContext); return element; } public XMLObject getXMLObject() { return envelope; } /** * Check if the envelope is signed. This does not validate the signature, it only checks for presence. */ public boolean isSigned() { boolean signed = SAMLUtil.getFirstElement(security, Signature.class) != null; log.debug("Envelope signed: " + signed); return signed; } public void setTo(String endpoint) { To to = SAMLUtil.buildXMLObject(To.class); to.setValue(endpoint); envelope.getHeader().getUnknownXMLObjects().add(to); addSignatureElement(to); } public void setReplyTo(String replyTo) { ReplyTo reply = SAMLUtil.buildXMLObject(ReplyTo.class); Address addr = SAMLUtil.buildXMLObject(Address.class); addr.setValue(replyTo); reply.setAddress(addr); envelope.getHeader().getUnknownXMLObjects().add(reply); addSignatureElement(reply); } /** * Get an XML representation of the object. */ public String toXML() { Element e = SAMLUtil.marshallObject(envelope); return XMLHelper.nodeToString(e); } /** * Get a header element of a specific type. * @param type The header type. * @return The header element, or <code>null</code> if no header of the given type was found. */ public <T extends XMLObject> T getHeaderElement(Class<T> type) { return SAMLUtil.getFirstElement(envelope.getHeader(), type); } /** * Verify the envelope signature. */ public boolean verifySignature(PublicKey key) { if (!isSigned()) return false; return new OIOSamlObject(security).verifySignature(key); } public boolean isHolderOfKey() { if (securityToken == null) return false; if (securityToken.getSubject() == null) return false; if (securityToken.getSubject().getSubjectConfirmations().isEmpty()) return false; return TrustConstants.CONFIRMATION_METHOD_HOK.equals(securityToken.getSubject().getSubjectConfirmations().get(0).getMethod()); } public String getMessageID() { MessageID mid = SAMLUtil.getFirstElement(envelope.getHeader(), MessageID.class); if (mid == null) return null; return mid.getValue(); } public void setUserInteraction(UserInteraction interaction, boolean redirect) { dk.itst.oiosaml.liberty.UserInteraction ui = SAMLUtil.getFirstElement(envelope.getHeader(), dk.itst.oiosaml.liberty.UserInteraction.class); if (ui != null) { ui.detach(); envelope.getHeader().getUnknownXMLObjects().remove(ui); } if (interaction == UserInteraction.NONE) { return; } ui = SAMLUtil.buildXMLObject(dk.itst.oiosaml.liberty.UserInteraction.class); ui.setInteract(interaction.getValue()); ui.setRedirect(redirect); envelope.getHeader().getUnknownXMLObjects().add(ui); addSignatureElement(ui); } // private XMLSignatureFactory getXMLSignature() { // // First, create a DOM XMLSignatureFactory that will be used to // // generate the XMLSignature and marshal it to DOM. // String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI"); // try { // XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance()); // return xmlSignatureFactory; // } catch (Exception e) { // throw new RuntimeException(e); // } // // } private String addSignatureElement(AttributeExtensibleXMLObject obj) { if (obj == null) return null; String id = Utils.generateUUID(); obj.getUnknownAttributes().put(TrustConstants.WSU_ID, id); references.put(obj, id); return id; } public static class STRTransformParameterSpec implements TransformParameterSpec { private CanonicalizationMethod c14nMethod; public STRTransformParameterSpec(CanonicalizationMethod c14nMethod) { this.c14nMethod = c14nMethod; } public CanonicalizationMethod getCanonicalizationMethod() { return c14nMethod; } } }
trust/trunk/src/dk/itst/oiosaml/trust/OIOSoapEnvelope.java
/* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express * or implied. See the License for the specific language governing * rights and limitations under the License. * * * The Original Code is OIOSAML Trust Client. * * The Initial Developer of the Original Code is Trifork A/S. Portions * created by Trifork A/S are Copyright (C) 2008 Danish National IT * and Telecom Agency (http://www.itst.dk). All Rights Reserved. * * Contributor(s): * Joakim Recht <[email protected]> * */ package dk.itst.oiosaml.trust; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.PublicKey; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.xml.crypto.MarshalException; import javax.xml.crypto.dom.DOMStructure; import javax.xml.crypto.dsig.CanonicalizationMethod; import javax.xml.crypto.dsig.DigestMethod; import javax.xml.crypto.dsig.Reference; import javax.xml.crypto.dsig.SignatureMethod; import javax.xml.crypto.dsig.SignedInfo; import javax.xml.crypto.dsig.Transform; import javax.xml.crypto.dsig.XMLSignature; import javax.xml.crypto.dsig.XMLSignatureException; import javax.xml.crypto.dsig.XMLSignatureFactory; import javax.xml.crypto.dsig.dom.DOMSignContext; import javax.xml.crypto.dsig.keyinfo.KeyInfo; import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; import javax.xml.crypto.dsig.keyinfo.X509Data; import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec; import javax.xml.crypto.dsig.spec.ExcC14NParameterSpec; import javax.xml.crypto.dsig.spec.TransformParameterSpec; import javax.xml.namespace.QName; import org.apache.log4j.Logger; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.core.Assertion; import org.opensaml.ws.soap.soap11.Body; import org.opensaml.ws.soap.soap11.Envelope; import org.opensaml.ws.soap.soap11.Header; import org.opensaml.ws.wsaddressing.Action; import org.opensaml.ws.wsaddressing.Address; import org.opensaml.ws.wsaddressing.MessageID; import org.opensaml.ws.wsaddressing.ReplyTo; import org.opensaml.ws.wsaddressing.To; import org.opensaml.ws.wssecurity.Created; import org.opensaml.ws.wssecurity.Expires; import org.opensaml.ws.wssecurity.KeyIdentifier; import org.opensaml.ws.wssecurity.Security; import org.opensaml.ws.wssecurity.SecurityTokenReference; import org.opensaml.ws.wssecurity.Timestamp; import org.opensaml.ws.wssecurity.WSSecurityConstants; import org.opensaml.xml.AttributeExtensibleXMLObject; import org.opensaml.xml.XMLObject; import org.opensaml.xml.schema.XSAny; import org.opensaml.xml.schema.XSBooleanValue; import org.opensaml.xml.schema.impl.XSAnyBuilder; import org.opensaml.xml.security.x509.X509Credential; import org.opensaml.xml.signature.Signature; import org.opensaml.xml.util.XMLHelper; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import dk.itst.oiosaml.common.SAMLUtil; import dk.itst.oiosaml.sp.model.OIOSamlObject; import dk.itst.oiosaml.sp.service.util.Utils; import dk.itst.oiosaml.trust.internal.SignatureFactory; /** * Wrap a generic SOAP envelope. * * This class adds some behavior to generic soap envelopes. Use this class to handle signatures, header elements, and other common operations. * * @author recht * */ public class OIOSoapEnvelope { private static final Logger log = Logger.getLogger(OIOSoapEnvelope.class); private Map<XMLObject, String> references = new HashMap<XMLObject, String>(); private final Envelope envelope; private Security security; private Body body; private XMLSignatureFactory xsf; private Assertion securityToken; private SecurityTokenReference securityTokenReference; public OIOSoapEnvelope(Envelope envelope) { this(envelope, false); } /** * Wrap an existing envelope. * * @param envelope * @param signHeaderElements If <code>true</code>, all the header elements in the envelope are marked for signature. */ public OIOSoapEnvelope(Envelope envelope, boolean signHeaderElements) { if (envelope == null) throw new IllegalArgumentException("Envelope cannot be null"); this.envelope = envelope; xsf = SignatureFactory.getInstance(); security = SAMLUtil.getFirstElement(envelope.getHeader(), Security.class); if (signHeaderElements) { if (security == null) { security = SAMLUtil.buildXMLObject(Security.class); security.setMustUnderstand(new XSBooleanValue(true, true)); envelope.getHeader().getUnknownXMLObjects().add(security); } for (XMLObject o : envelope.getHeader().getUnknownXMLObjects()) { if (o instanceof AttributeExtensibleXMLObject) { if (o instanceof Security) continue; addSignatureElement((AttributeExtensibleXMLObject) o); } } } } private OIOSoapEnvelope(Envelope envelope, MessageID msgId, XSAny framework) { this(envelope); addSignatureElement(msgId); addSignatureElement(framework); } /** * Build a new soap envelope with standard OIO headers. * * Standard headers include sbf:Framework, wsa:MessageID, and an empty Security header. */ public static OIOSoapEnvelope buildEnvelope() { Envelope env = SAMLUtil.buildXMLObject(Envelope.class); Header header = SAMLUtil.buildXMLObject(Header.class); env.setHeader(header); MessageID msgId = SAMLUtil.buildXMLObject(MessageID.class); msgId.setValue(UUID.randomUUID().toString()); header.getUnknownXMLObjects().add(msgId); XSAny framework = new XSAnyBuilder().buildObject("urn:liberty:sb:2006-08", "Framework", "sbf"); framework.getUnknownAttributes().put(new QName("version"), "2.0"); framework.getUnknownAttributes().put(new QName("urn:liberty:sb:eGovprofile", "profile"), "urn:liberty:sb:profile:basicegovsimple"); header.getUnknownXMLObjects().add(framework); Security security = SAMLUtil.buildXMLObject(Security.class); security.setMustUnderstand(new XSBooleanValue(true, true)); header.getUnknownXMLObjects().add(security); return new OIOSoapEnvelope(env, msgId, framework); } public void setBody(XMLObject request) { body = SAMLUtil.buildXMLObject(Body.class); body.getUnknownXMLObjects().add(request); addSignatureElement(body); envelope.setBody(body); } public void setAction(String action) { Action a = SAMLUtil.buildXMLObject(Action.class); a.setValue(action); envelope.getHeader().getUnknownXMLObjects().add(a); addSignatureElement(a); } public void addSecurityToken(Assertion token) { security.getUnknownXMLObjects().add(token); } /** * Insert a token and a SecurityTokenReference pointing to the token. */ public void addSecurityTokenReference(Assertion token) { if (token == null) return; token.detach(); securityToken = token; addSecurityToken(token); securityTokenReference = createSecurityTokenReference(token); security.getUnknownXMLObjects().add(securityTokenReference); } private SecurityTokenReference createSecurityTokenReference(Assertion token) { SecurityTokenReference str = SAMLUtil.buildXMLObject(SecurityTokenReference.class); str.setTokenType(WSSecurityConstants.WSSE11_SAML_TOKEN_PROFILE_NS + "#SAMLV2.0"); str.setId(Utils.generateUUID()); KeyIdentifier keyIdentifier = SAMLUtil.buildXMLObject(KeyIdentifier.class); keyIdentifier.setValueType(WSSecurityConstants.WSSE11_SAML_TOKEN_PROFILE_NS + "#SAMLID"); keyIdentifier.setValue(token.getID()); str.setKeyIdentifier(keyIdentifier); return str; } /** * Check if this envelope relates to a specific message id. */ public boolean relatesTo(String messageId) { if (envelope.getHeader() == null) return false; List<XMLObject> objects = envelope.getHeader().getUnknownXMLObjects(TrustConstants.WSA_RELATES_TO); if (objects.isEmpty()) return false; XMLObject object = objects.get(0); String relatesTo; if (object instanceof XSAny) { relatesTo = ((XSAny)object).getTextContent(); } else { Element e = SAMLUtil.marshallObject(object); relatesTo = e.getTextContent().trim(); } return messageId.equals(relatesTo); } /** * Add a timestamp to the Security header. * @param timestampSkew How many minutes before the message should expire. */ public void setTimestamp(int timestampSkew) { DateTime now = new DateTime().toDateTime(DateTimeZone.UTC); Timestamp timestamp = SAMLUtil.buildXMLObject(Timestamp.class); Created created = SAMLUtil.buildXMLObject(Created.class); created.setDateTime(now.minusMinutes(timestampSkew)); timestamp.setCreated(created); Expires exp = SAMLUtil.buildXMLObject(Expires.class); exp.setDateTime(now.plusMinutes(timestampSkew)); timestamp.setExpires(exp); security.getUnknownXMLObjects().add(timestamp); addSignatureElement(timestamp); } /** * Get the first element of the envelope body. */ public XMLObject getBody() { return envelope.getBody().getUnknownXMLObjects().get(0); } /** * Sign the SOAP envelope and return the signed DOM element. * * @param credential Credentials to use for signing. * @return The signed dom element. * @throws NoSuchAlgorithmException * @throws InvalidAlgorithmParameterException * @throws MarshalException * @throws XMLSignatureException */ public Element sign(X509Credential credential) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException { CanonicalizationMethod canonicalizationMethod = xsf.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); SignatureMethod signatureMethod = xsf.newSignatureMethod(SignatureMethod.RSA_SHA1, null); List<Reference> refs = new ArrayList<Reference>(); DigestMethod digestMethod = xsf.newDigestMethod(DigestMethod.SHA1, null); List<Transform> transforms = new ArrayList<Transform>(2); transforms.add(xsf.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#",new ExcC14NParameterSpec(Collections.singletonList("xsd")))); for (Map.Entry<XMLObject, String> ref : references.entrySet()) { Reference r = xsf.newReference("#"+ref.getValue(), digestMethod, transforms, null, null); refs.add(r); } SAMLUtil.marshallObject(envelope); if (securityTokenReference != null) { transforms = new ArrayList<Transform>(); Document doc = envelope.getDOM().getOwnerDocument(); Element tp = XMLHelper.constructElement(doc, WSSecurityConstants.WSSE_NS, "TransformationParameters", WSSecurityConstants.WSSE_PREFIX); Element cm = XMLHelper.constructElement(doc, XMLSignature.XMLNS, "CanonicalizationMethod", "ds"); tp.appendChild(cm); cm.setAttribute("Algorithm", "http://www.w3.org/2001/10/xml-exc-c14n#"); transforms.add(SignatureFactory.getInstance().newTransform("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#STR-Transform", new DOMStructure(tp))); Reference r = xsf.newReference("#"+securityTokenReference.getId(), digestMethod, transforms, null, null); refs.add(r); } // Create the SignedInfo SignedInfo signedInfo = xsf.newSignedInfo(canonicalizationMethod, signatureMethod, refs); KeyInfoFactory keyInfoFactory = xsf.getKeyInfoFactory(); KeyInfo ki; if (isHolderOfKey()) { DOMStructure info = new DOMStructure(SAMLUtil.marshallObject(createSecurityTokenReference(securityToken))); ki = keyInfoFactory.newKeyInfo(Collections.singletonList(info)); } else { X509Data x509Data = keyInfoFactory.newX509Data(Collections.singletonList(credential.getEntityCertificate())); ki = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data)); } XMLSignature signature = xsf.newXMLSignature(signedInfo, ki); String xml = XMLHelper.nodeToString(envelope.getDOM()); log.debug("Signing envelope: " + xml); Element element = SAMLUtil.loadElementFromString(xml); Node security = element.getElementsByTagNameNS(WSSecurityConstants.WSSE_NS, "Security").item(0); DOMSignContext signContext = new DOMSignContext(credential.getPrivateKey(), security); signContext.putNamespacePrefix(SAMLConstants.XMLSIG_NS, SAMLConstants.XMLSIG_PREFIX); signContext.putNamespacePrefix(SAMLConstants.XMLENC_NS, SAMLConstants.XMLENC_PREFIX); for (XMLObject o : references.keySet()) { NodeList nl = element.getElementsByTagNameNS(o.getDOM().getNamespaceURI(), o.getDOM().getLocalName()); for (int i = 0; i < nl.getLength(); i++) { Element e = (Element) nl.item(i); if (e.hasAttributeNS(WSSecurityConstants.WSU_NS, "Id")) { signContext.setIdAttributeNS(e, WSSecurityConstants.WSU_NS, "Id"); e.setIdAttributeNS(WSSecurityConstants.WSU_NS, "Id", true); } } } if (securityTokenReference != null) { NodeList nl = element.getElementsByTagNameNS(SecurityTokenReference.ELEMENT_NAME.getNamespaceURI(), SecurityTokenReference.ELEMENT_LOCAL_NAME); for (int i = 0; i < nl.getLength(); i++) { Element e = (Element) nl.item(i); e.setIdAttributeNS(WSSecurityConstants.WSU_NS, "Id", true); } nl = element.getElementsByTagNameNS(securityToken.getElementQName().getNamespaceURI(), securityToken.getElementQName().getLocalPart()); for (int i = 0; i < nl.getLength(); i++) { Element e = (Element) nl.item(i); if (e.hasAttribute("ID")) { e.setIdAttributeNS(null, "ID", true); } if (e.hasAttributeNS(WSSecurityConstants.WSU_NS, "Id")) { e.setIdAttributeNS(WSSecurityConstants.WSU_NS, "Id", true); } } } // Marshal, generate (and sign) the detached XMLSignature. The DOM // Document will contain the XML Signature if this method returns // successfully. // HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not allow children of the type of the newChild node, or if the node to insert is one of this node's ancestors. signature.sign(signContext); return element; } public XMLObject getXMLObject() { return envelope; } /** * Check if the envelope is signed. This does not validate the signature, it only checks for presence. */ public boolean isSigned() { boolean signed = SAMLUtil.getFirstElement(security, Signature.class) != null; log.debug("Envelope signed: " + signed); return signed; } public void setTo(String endpoint) { To to = SAMLUtil.buildXMLObject(To.class); to.setValue(endpoint); envelope.getHeader().getUnknownXMLObjects().add(to); addSignatureElement(to); } public void setReplyTo(String replyTo) { ReplyTo reply = SAMLUtil.buildXMLObject(ReplyTo.class); Address addr = SAMLUtil.buildXMLObject(Address.class); addr.setValue(replyTo); reply.setAddress(addr); envelope.getHeader().getUnknownXMLObjects().add(reply); addSignatureElement(reply); } /** * Get an XML representation of the object. */ public String toXML() { Element e = SAMLUtil.marshallObject(envelope); return XMLHelper.nodeToString(e); } /** * Get a header element of a specific type. * @param type The header type. * @return The header element, or <code>null</code> if no header of the given type was found. */ public <T extends XMLObject> T getHeaderElement(Class<T> type) { return SAMLUtil.getFirstElement(envelope.getHeader(), type); } /** * Verify the envelope signature. */ public boolean verifySignature(PublicKey key) { if (!isSigned()) return false; return new OIOSamlObject(security).verifySignature(key); } public boolean isHolderOfKey() { if (securityToken == null) return false; if (securityToken.getSubject() == null) return false; if (securityToken.getSubject().getSubjectConfirmations().isEmpty()) return false; return TrustConstants.CONFIRMATION_METHOD_HOK.equals(securityToken.getSubject().getSubjectConfirmations().get(0).getMethod()); } public String getMessageID() { MessageID mid = SAMLUtil.getFirstElement(envelope.getHeader(), MessageID.class); if (mid == null) return null; return mid.getValue(); } public void setUserInteraction(UserInteraction interaction, boolean redirect) { dk.itst.oiosaml.liberty.UserInteraction ui = SAMLUtil.getFirstElement(envelope.getHeader(), dk.itst.oiosaml.liberty.UserInteraction.class); if (ui != null) { ui.detach(); envelope.getHeader().getUnknownXMLObjects().remove(ui); } if (interaction == UserInteraction.NONE) { return; } ui = SAMLUtil.buildXMLObject(dk.itst.oiosaml.liberty.UserInteraction.class); ui.setInteract(interaction.getValue()); ui.setRedirect(redirect); envelope.getHeader().getUnknownXMLObjects().add(ui); addSignatureElement(ui); } // private XMLSignatureFactory getXMLSignature() { // // First, create a DOM XMLSignatureFactory that will be used to // // generate the XMLSignature and marshal it to DOM. // String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI"); // try { // XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance()); // return xmlSignatureFactory; // } catch (Exception e) { // throw new RuntimeException(e); // } // // } private String addSignatureElement(AttributeExtensibleXMLObject obj) { if (obj == null) return null; String id = Utils.generateUUID(); obj.getUnknownAttributes().put(TrustConstants.WSU_ID, id); references.put(obj, id); return id; } public static class STRTransformParameterSpec implements TransformParameterSpec { private CanonicalizationMethod c14nMethod; public STRTransformParameterSpec(CanonicalizationMethod c14nMethod) { this.c14nMethod = c14nMethod; } public CanonicalizationMethod getCanonicalizationMethod() { return c14nMethod; } } }
remove import
trust/trunk/src/dk/itst/oiosaml/trust/OIOSoapEnvelope.java
remove import
<ide><path>rust/trunk/src/dk/itst/oiosaml/trust/OIOSoapEnvelope.java <ide> <ide> import java.security.InvalidAlgorithmParameterException; <ide> import java.security.NoSuchAlgorithmException; <del>import java.security.Provider; <ide> import java.security.PublicKey; <ide> import java.util.ArrayList; <ide> import java.util.Collections;
Java
mit
e96a6b7db74b231aa566959bbcd8f063392a56b9
0
k0kubun/githubranking,k0kubun/github-ranking,k0kubun/githubranking,k0kubun/githubranking,k0kubun/github-ranking,k0kubun/githubranking,k0kubun/github-ranking,k0kubun/githubranking,k0kubun/github-ranking,k0kubun/github-ranking
package com.github.k0kubun.github_ranking.repository.dao; import com.github.k0kubun.github_ranking.model.User; import java.util.List; import java.sql.ResultSet; import java.sql.SQLException; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.customizers.Mapper; import org.skife.jdbi.v2.tweak.ResultSetMapper; public interface UserDao { @SqlQuery("select id, login, type from users where id = :id") @Mapper(UserMapper.class) User find(@Bind("id") Integer id); // This query does not update updated_at because updating it will show "Up to date" before updating repositories. @SqlUpdate("update users set login = :login where id = :id") long updateLogin(@Bind("id") Integer id, @Bind("login") String login); @SqlUpdate("update users set stargazers_count = :stargazersCount, updated_at = current_timestamp() where id = :id") long updateStars(@Bind("id") Integer id, @Bind("stargazersCount") Integer stargazersCount); @SqlQuery("select id, login, type, stargazers_count from users where type = 'User' order by stargazers_count desc, id desc limit :limit") @Mapper(UserStarMapper.class) List<User> starsDescFirstUsers(@Bind("limit") Integer limit); @SqlQuery("select id, login, type, stargazers_count from users where type = 'User' and " + "(stargazers_count, id) < (:stargazersCount, :id) order by stargazers_count desc, id desc limit :limit") @Mapper(UserStarMapper.class) List<User> starsDescUsersAfter(@Bind("stargazersCount") Integer stargazersCount, @Bind("id") Integer id, @Bind("limit") Integer limit); @SqlQuery("select count(1) from users where type = 'User'") int countUsers(); @SqlQuery("select count(1) from users where type = 'User' and stargazers_count = :stargazersCount") int countUsersHavingStars(@Bind("stargazersCount") int stargazersCount); @SqlUpdate("delete from users where id = :id") long delete(@Bind("id") Integer id); class UserMapper implements ResultSetMapper<User> { @Override public User map(int index, ResultSet r, StatementContext ctx) throws SQLException { User user = new User(r.getInt("id"), r.getString("type")); user.setLogin(r.getString("login")); return user; } } class UserStarMapper implements ResultSetMapper<User> { @Override public User map(int index, ResultSet r, StatementContext ctx) throws SQLException { User user = new User(r.getInt("id"), r.getString("type")); user.setLogin(r.getString("login")); user.setStargazersCount(r.getInt("stargazers_count")); return user; } } }
worker/src/main/java/com/github/k0kubun/github_ranking/repository/dao/UserDao.java
package com.github.k0kubun.github_ranking.repository.dao; import com.github.k0kubun.github_ranking.model.User; import java.util.List; import java.sql.ResultSet; import java.sql.SQLException; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.customizers.Mapper; import org.skife.jdbi.v2.tweak.ResultSetMapper; public interface UserDao { @SqlQuery("select id, login, type from users where id = :id") @Mapper(UserMapper.class) User find(@Bind("id") Integer id); // This query does not update updated_at because updating it will show "Up to date" before updating repositories. @SqlUpdate("update users set login = :login where id = :id") long updateLogin(@Bind("id") Integer id, @Bind("login") String login); @SqlUpdate("update users set stargazers_count = :stargazersCount, updated_at = current_timestamp() where id = :id") long updateStars(@Bind("id") Integer id, @Bind("stargazersCount") Integer stargazersCount); @SqlQuery("select id, login, type, stargazers_count from users where type = 'User' order by stargazers_count desc, id desc limit :limit") @Mapper(UserMapper.class) List<User> starsDescFirstUsers(@Bind("limit") Integer limit); @SqlQuery("select id, login, type, stargazers_count from users where type = 'User' and " + "(stargazers_count, id) < (:stargazersCount, :id) order by stargazers_count desc, id desc limit :limit") @Mapper(UserMapper.class) List<User> starsDescUsersAfter(@Bind("stargazersCount") Integer stargazersCount, @Bind("id") Integer id, @Bind("limit") Integer limit); @SqlQuery("select count(1) from users where type = 'User'") int countUsers(); @SqlQuery("select count(1) from users where type = 'User' and stargazers_count = :stargazersCount") int countUsersHavingStars(@Bind("stargazersCount") int stargazersCount); @SqlUpdate("delete from users where id = :id") long delete(@Bind("id") Integer id); class UserMapper implements ResultSetMapper<User> { @Override public User map(int index, ResultSet r, StatementContext ctx) throws SQLException { User user = new User(r.getInt("id"), r.getString("type")); user.setLogin(r.getString("login")); return user; } } }
Fix user ranking object mapper
worker/src/main/java/com/github/k0kubun/github_ranking/repository/dao/UserDao.java
Fix user ranking object mapper
<ide><path>orker/src/main/java/com/github/k0kubun/github_ranking/repository/dao/UserDao.java <ide> long updateStars(@Bind("id") Integer id, @Bind("stargazersCount") Integer stargazersCount); <ide> <ide> @SqlQuery("select id, login, type, stargazers_count from users where type = 'User' order by stargazers_count desc, id desc limit :limit") <del> @Mapper(UserMapper.class) <add> @Mapper(UserStarMapper.class) <ide> List<User> starsDescFirstUsers(@Bind("limit") Integer limit); <ide> <ide> @SqlQuery("select id, login, type, stargazers_count from users where type = 'User' and " + <ide> "(stargazers_count, id) < (:stargazersCount, :id) order by stargazers_count desc, id desc limit :limit") <del> @Mapper(UserMapper.class) <add> @Mapper(UserStarMapper.class) <ide> List<User> starsDescUsersAfter(@Bind("stargazersCount") Integer stargazersCount, @Bind("id") Integer id, @Bind("limit") Integer limit); <ide> <ide> @SqlQuery("select count(1) from users where type = 'User'") <ide> return user; <ide> } <ide> } <add> <add> class UserStarMapper <add> implements ResultSetMapper<User> <add> { <add> @Override <add> public User map(int index, ResultSet r, StatementContext ctx) <add> throws SQLException <add> { <add> User user = new User(r.getInt("id"), r.getString("type")); <add> user.setLogin(r.getString("login")); <add> user.setStargazersCount(r.getInt("stargazers_count")); <add> return user; <add> } <add> } <ide> }
JavaScript
mit
ec6b5ef58a35fac695a6087f4dfee50c71e84ebd
0
yuanchuan/css-doodle
import { cache_image, is_safari } from './utils/index'; const NS = 'http://www.w3.org/2000/svg'; const NSXLink = 'http://www.w3.org/1999/xlink'; export function create_svg_url(svg, id) { let encoded = encodeURIComponent(svg) + (id ? `#${ id }` : ''); return `url("data:image/svg+xml;utf8,${ encoded }")`; } export function normalize_svg(input) { const xmlns = `xmlns="${ NS }"`; const xmlnsXLink = `xmlns:xlink="${ NSXLink }"`; if (!input.includes('<svg')) { input = `<svg ${ xmlns } ${ xmlnsXLink }>${ input }</svg>`; } if (!input.includes('xmlns')) { input = input.replace(/<svg([\s>])/, `<svg ${ xmlns } ${ xmlnsXLink }$1`); } return input; } export function svg_to_png(svg, width, height, scale) { return new Promise((resolve, reject) => { let source = `data:image/svg+xml;utf8,${ encodeURIComponent(svg) }`; function action() { let img = new Image(); img.crossOrigin = 'anonymous'; img.src = source; img.onload = () => { let canvas = document.createElement('canvas'); let ctx = canvas.getContext('2d'); let dpr = window.devicePixelRatio || 1; /* scale with devicePixelRatio only when the scale equals 1 */ if (scale != 1) { dpr = 1; } canvas.width = width * dpr; canvas.height = height * dpr; ctx.drawImage(img, 0, 0, canvas.width, canvas.height); try { canvas.toBlob(blob => { resolve({ blob, source, url: URL.createObjectURL(blob) }); }); } catch (e) { reject(e); } } } if (is_safari()) { cache_image(source, action, 200); } else { action(); } }); } export function generate_svg(token, element, parent) { if (!element) { element = document.createDocumentFragment(); } if (token.type === 'block') { try { let el = document.createElementNS(NS, token.name); if (el) { token.value.forEach(t => { generate_svg(t, el, token); }); element.appendChild(el); } } catch (e) {} } if (token.type === 'statement') { if (parent && parent.name == 'text' && token.name === 'content') { element.textContent = token.value; } else { try { let ns = token.name.startsWith('xlink:') ? NSXLink : NS; element.setAttributeNS(ns, token.name, token.value); } catch (e) {} } } if (!parent) { let child = element.childNodes[0]; return child && child.outerHTML || ''; } return element; }
src/svg.js
import { cache_image, is_safari } from './utils/index'; const NS = 'http://www.w3.org/2000/svg'; export function create_svg_url(svg, id) { let encoded = encodeURIComponent(svg) + (id ? `#${ id }` : ''); return `url("data:image/svg+xml;utf8,${ encoded }")`; } export function normalize_svg(input) { const xmlns = `xmlns="${ NS }"`; if (!input.includes('<svg')) { input = `<svg ${ xmlns }>${ input }</svg>`; } if (!input.includes('xmlns')) { input = input.replace(/<svg([\s>])/, `<svg ${ xmlns }$1`); } return input; } export function svg_to_png(svg, width, height, scale) { return new Promise((resolve, reject) => { let source = `data:image/svg+xml;utf8,${ encodeURIComponent(svg) }`; function action() { let img = new Image(); img.crossOrigin = 'anonymous'; img.src = source; img.onload = () => { let canvas = document.createElement('canvas'); let ctx = canvas.getContext('2d'); let dpr = window.devicePixelRatio || 1; /* scale with devicePixelRatio only when the scale equals 1 */ if (scale != 1) { dpr = 1; } canvas.width = width * dpr; canvas.height = height * dpr; ctx.drawImage(img, 0, 0, canvas.width, canvas.height); try { canvas.toBlob(blob => { resolve({ blob, source, url: URL.createObjectURL(blob) }); }); } catch (e) { reject(e); } } } if (is_safari()) { cache_image(source, action, 200); } else { action(); } }); } export function generate_svg(token, element, parent) { if (!element) { element = document.createDocumentFragment(); } if (token.type === 'block') { try { let el = document.createElementNS(NS, token.name); if (el) { token.value.forEach(t => { generate_svg(t, el, token); }); element.appendChild(el); } } catch (e) {} } if (token.type === 'statement') { if (parent && parent.name == 'text' && token.name === 'content') { element.textContent = token.value; } else { try { element.setAttributeNS(NS, token.name, token.value); } catch (e) {} } } if (!parent) { let child = element.childNodes[0]; return child && child.outerHTML || ''; } return element; }
Add `xlink` namespace declaration
src/svg.js
Add `xlink` namespace declaration
<ide><path>rc/svg.js <ide> import { cache_image, is_safari } from './utils/index'; <ide> <ide> const NS = 'http://www.w3.org/2000/svg'; <add>const NSXLink = 'http://www.w3.org/1999/xlink'; <ide> <ide> export function create_svg_url(svg, id) { <ide> let encoded = encodeURIComponent(svg) + (id ? `#${ id }` : ''); <ide> <ide> export function normalize_svg(input) { <ide> const xmlns = `xmlns="${ NS }"`; <add> const xmlnsXLink = `xmlns:xlink="${ NSXLink }"`; <ide> if (!input.includes('<svg')) { <del> input = `<svg ${ xmlns }>${ input }</svg>`; <add> input = `<svg ${ xmlns } ${ xmlnsXLink }>${ input }</svg>`; <ide> } <ide> if (!input.includes('xmlns')) { <del> input = input.replace(/<svg([\s>])/, `<svg ${ xmlns }$1`); <add> input = input.replace(/<svg([\s>])/, `<svg ${ xmlns } ${ xmlnsXLink }$1`); <ide> } <ide> return input; <ide> } <ide> element.textContent = token.value; <ide> } else { <ide> try { <del> element.setAttributeNS(NS, token.name, token.value); <add> let ns = token.name.startsWith('xlink:') ? NSXLink : NS; <add> element.setAttributeNS(ns, token.name, token.value); <ide> } catch (e) {} <ide> } <ide> }
Java
apache-2.0
47b3242ae2711f0feb23e50fbbf40113fc6872f0
0
webanno/webanno,webanno/webanno,webanno/webanno,webanno/webanno
/******************************************************************************* * Copyright 2015 * Ubiquitous Knowledge Processing (UKP) Lab and FG Language Technology * Technische Universität Darmstadt * * 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.tudarmstadt.ukp.clarin.webanno.brat.annotation.component; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.getAddr; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.getFeature; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.getLastSentenceAddressInDisplayWindow; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.getNextSentenceAddress; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.getSentenceBeginAddress; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.getSentenceNumber; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.isSame; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.selectAt; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.selectByAddr; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.selectSentenceAt; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.setFeature; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.TypeUtil.getAdapter; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.persistence.NoResultException; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.uima.UIMAException; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASRuntimeException; import org.apache.uima.cas.Feature; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.Type; import org.apache.uima.cas.text.AnnotationFS; import org.apache.uima.fit.util.CasUtil; import org.apache.uima.jcas.JCas; import org.apache.wicket.Component; import org.apache.wicket.MarkupContainer; import org.apache.wicket.ajax.AjaxEventBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.attributes.AjaxCallListener; import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; import org.apache.wicket.ajax.attributes.IAjaxCallListener; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.ajax.form.AjaxFormValidatingBehavior; import org.apache.wicket.ajax.markup.html.form.AjaxButton; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.AbstractTextComponent; import org.apache.wicket.markup.html.form.CheckBox; import org.apache.wicket.markup.html.form.ChoiceRenderer; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.markup.html.panel.Fragment; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.markup.repeater.RefreshingView; import org.apache.wicket.markup.repeater.util.ModelIteratorAdapter; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.request.Request; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.spring.injection.annot.SpringBean; import org.codehaus.plexus.util.StringUtils; import com.googlecode.wicket.jquery.core.Options; import com.googlecode.wicket.jquery.core.template.IJQueryTemplate; import com.googlecode.wicket.jquery.ui.widget.tooltip.TooltipBehavior; import com.googlecode.wicket.kendo.ui.form.NumberTextField; import com.googlecode.wicket.kendo.ui.form.TextField; import com.googlecode.wicket.kendo.ui.form.combobox.ComboBox; import de.tudarmstadt.ukp.clarin.webanno.api.AnnotationService; import de.tudarmstadt.ukp.clarin.webanno.api.RepositoryService; import de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst; import de.tudarmstadt.ukp.clarin.webanno.brat.annotation.BratAnnotatorModel; import de.tudarmstadt.ukp.clarin.webanno.brat.annotation.command.Selection; import de.tudarmstadt.ukp.clarin.webanno.brat.controller.ArcAdapter; import de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil; import de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAnnotationException; import de.tudarmstadt.ukp.clarin.webanno.brat.controller.ChainAdapter; import de.tudarmstadt.ukp.clarin.webanno.brat.controller.SpanAdapter; import de.tudarmstadt.ukp.clarin.webanno.brat.controller.TypeAdapter; import de.tudarmstadt.ukp.clarin.webanno.brat.controller.TypeUtil; import de.tudarmstadt.ukp.clarin.webanno.brat.display.model.VID; import de.tudarmstadt.ukp.clarin.webanno.brat.util.JavascriptUtils; import de.tudarmstadt.ukp.clarin.webanno.constraints.evaluator.Evaluator; import de.tudarmstadt.ukp.clarin.webanno.constraints.evaluator.PossibleValue; import de.tudarmstadt.ukp.clarin.webanno.constraints.evaluator.RulesIndicator; import de.tudarmstadt.ukp.clarin.webanno.constraints.evaluator.ValuesGenerator; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationDocumentState; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationFeature; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationLayer; import de.tudarmstadt.ukp.clarin.webanno.model.Mode; import de.tudarmstadt.ukp.clarin.webanno.model.MultiValueMode; import de.tudarmstadt.ukp.clarin.webanno.model.SourceDocumentState; import de.tudarmstadt.ukp.clarin.webanno.model.Tag; import de.tudarmstadt.ukp.clarin.webanno.model.TagSet; import de.tudarmstadt.ukp.clarin.webanno.support.DefaultFocusBehavior; import de.tudarmstadt.ukp.clarin.webanno.support.DefaultFocusBehavior2; import de.tudarmstadt.ukp.clarin.webanno.support.DescriptionTooltipBehavior; import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.POS; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token; import de.tudarmstadt.ukp.dkpro.core.api.syntax.type.dependency.Dependency; /** * Annotation Detail Editor Panel. * */ public class AnnotationDetailEditorPanel extends Panel { private static final long serialVersionUID = 7324241992353693848L; private static final Log LOG = LogFactory.getLog(AnnotationDetailEditorPanel.class); @SpringBean(name = "documentRepository") private RepositoryService repository; @SpringBean(name = "annotationService") private AnnotationService annotationService; private AnnotationFeatureForm annotationFeatureForm; private Label selectedTextLabel; private CheckBox forwardAnnotationCheck; private RefreshingView<FeatureModel> featureValues; private AjaxButton deleteButton; private AjaxButton reverseButton; private LayerSelector layer; private TextField<String> forwardAnnotationText; private Label selectedAnnotationLayer; private ModalWindow deleteModal; private List<AnnotationLayer> annotationLayers = new ArrayList<AnnotationLayer>(); private List<FeatureModel> featureModels; private BratAnnotatorModel bModel; private String selectedTag = ""; /** *Function to return tooltip using jquery *Docs for the JQuery tooltip widget that we configure below: *https://api.jqueryui.com/tooltip/ */ private final String functionForTooltip = "function() { return " + "'<div class=\"tooltip-title\">'+($(this).text() " + "? $(this).text() : 'no title')+'</div>" + "<div class=\"tooltip-content tooltip-pre\">'+($(this).attr('title') " + "? $(this).attr('title') : 'no description' )+'</div>' }"; public AnnotationDetailEditorPanel(String id, IModel<BratAnnotatorModel> aModel) { super(id, aModel); bModel = aModel.getObject(); annotationFeatureForm = new AnnotationFeatureForm("annotationFeatureForm", aModel.getObject()) { private static final long serialVersionUID = 8081614428845920047L; @Override protected void onConfigure() { super.onConfigure(); // Avoid reversing in read-only layers setEnabled(bModel.getDocument() != null && !isAnnotationFinished()); } }; annotationFeatureForm.setOutputMarkupId(true); annotationFeatureForm.add(new AjaxFormValidatingBehavior(annotationFeatureForm, "onsubmit") { private static final long serialVersionUID = -5642108496844056023L; @Override protected void onSubmit(AjaxRequestTarget aTarget) { try { actionAnnotate(aTarget, bModel, false); } catch (UIMAException | ClassNotFoundException | IOException | BratAnnotationException e) { error(e.getMessage()); } } }); add(annotationFeatureForm); } public boolean isAnnotationFinished() { if (bModel.getMode().equals(Mode.CURATION)) { return bModel.getDocument().getState().equals(SourceDocumentState.CURATION_FINISHED); } else { return repository.getAnnotationDocument(bModel.getDocument(), bModel.getUser()) .getState().equals(AnnotationDocumentState.FINISHED); } } private class AnnotationFeatureForm extends Form<BratAnnotatorModel> { private static final long serialVersionUID = 3635145598405490893L; private WebMarkupContainer featureEditorsContainer; public AnnotationFeatureForm(String id, BratAnnotatorModel aBModel) { super(id, new CompoundPropertyModel<BratAnnotatorModel>(aBModel)); featureModels = new ArrayList<>(); add(forwardAnnotationCheck = new CheckBox("forwardAnnotation") { private static final long serialVersionUID = 8908304272310098353L; @Override protected void onConfigure() { super.onConfigure(); setEnabled(isForwardable()); updateForwardAnnotation(bModel); } }); forwardAnnotationCheck.add(new AjaxFormComponentUpdatingBehavior("onchange") { private static final long serialVersionUID = 5179816588460867471L; @Override protected void onUpdate(AjaxRequestTarget aTarget) { updateForwardAnnotation(getModelObject()); if(bModel.isForwardAnnotation()){ aTarget.appendJavaScript(JavascriptUtils.getFocusScript(forwardAnnotationText)); selectedTag = ""; } } }); forwardAnnotationCheck.setOutputMarkupId(true); add(new Label("noAnnotationWarning", "No Annotation selected!"){ private static final long serialVersionUID = -6046409838139863541L; @Override protected void onConfigure() { super.onConfigure(); setVisible(!bModel.getSelection().getAnnotation().isSet()); } }); add(deleteButton = new AjaxButton("delete") { private static final long serialVersionUID = 1L; @Override protected void onConfigure() { super.onConfigure(); setVisible(bModel.getSelection().getAnnotation().isSet()); // Avoid deleting in read-only layers setEnabled(bModel.getSelectedAnnotationLayer() != null && !bModel.getSelectedAnnotationLayer().isReadonly()); } @Override public void onSubmit(AjaxRequestTarget aTarget, Form<?> aForm) { try { JCas jCas = getCas(bModel); AnnotationFS fs = selectByAddr(jCas, bModel.getSelection().getAnnotation().getId()); AnnotationLayer layer = bModel.getSelectedAnnotationLayer(); TypeAdapter adapter = getAdapter(annotationService, layer); if (adapter instanceof SpanAdapter && getAttachedRels(jCas, fs, layer).size() > 0) { deleteModal.setTitle("Are you sure you like to delete all attached relations to this span annotation?"); deleteModal.setContent(new DeleteOrReplaceAnnotationModalPanel( deleteModal.getContentId(), bModel, deleteModal, AnnotationDetailEditorPanel.this, bModel.getSelectedAnnotationLayer(), false)); deleteModal.show(aTarget); } else { actionDelete(aTarget, bModel); } } catch (UIMAException | ClassNotFoundException | IOException | CASRuntimeException | BratAnnotationException e) { error(e.getMessage()); } } }); add(reverseButton = new AjaxButton("reverse") { private static final long serialVersionUID = 1L; @Override protected void onConfigure() { super.onConfigure(); setVisible(bModel.getSelection().isRelationAnno() && bModel.getSelection().getAnnotation().isSet() && bModel.getSelectedAnnotationLayer().getType() .equals(WebAnnoConst.RELATION_TYPE)); // Avoid reversing in read-only layers setEnabled(bModel.getSelectedAnnotationLayer() != null && !bModel.getSelectedAnnotationLayer().isReadonly()); } @Override public void onSubmit(AjaxRequestTarget aTarget, Form<?> aForm) { aTarget.addChildren(getPage(), FeedbackPanel.class); try { actionReverse(aTarget, bModel); } catch (BratAnnotationException e) { aTarget.prependJavaScript("alert('" + e.getMessage() + "')"); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } catch (UIMAException e) { error(ExceptionUtils.getRootCauseMessage(e)); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } catch (Exception e) { error(e.getMessage()); LOG.error(e.getMessage(), e); } } }); reverseButton.setOutputMarkupPlaceholderTag(true); add(new AjaxButton("clear") { private static final long serialVersionUID = 1L; @Override protected void onConfigure() { super.onConfigure(); setVisible(bModel.getSelection().getAnnotation().isSet()); } @Override public void onSubmit(AjaxRequestTarget aTarget, Form<?> aForm) { aTarget.addChildren(getPage(), FeedbackPanel.class); try { actionClear(aTarget, bModel); } catch (UIMAException e) { error(ExceptionUtils.getRootCauseMessage(e)); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } catch (Exception e) { error(e.getMessage()); LOG.error(e.getMessage(), e); } } }); add(layer = new LayerSelector("defaultAnnotationLayer", annotationLayers)); featureValues = new FeatureEditorPanelContent( "featureValues"); featureEditorsContainer = new WebMarkupContainer("featureEditorsContainer") { private static final long serialVersionUID = 8908304272310098353L; @Override protected void onConfigure() { super.onConfigure(); setVisible(!featureModels.isEmpty() && bModel.getSelection().getAnnotation().isSet()); } }; // Add placeholder since wmc might start out invisible. Without the placeholder we // cannot make it visible in an AJAX call featureEditorsContainer.setOutputMarkupPlaceholderTag(true); featureEditorsContainer.setOutputMarkupId(true); forwardAnnotationText = new TextField<String>("forwardAnno"); forwardAnnotationText.setOutputMarkupId(true); forwardAnnotationText.add(new AjaxFormComponentUpdatingBehavior("onkeyup") { private static final long serialVersionUID = 4554834769861958396L; @Override protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { super.updateAjaxAttributes(attributes); IAjaxCallListener listener = new AjaxCallListener(){ private static final long serialVersionUID = -7968540662654079601L; @Override public CharSequence getPrecondition(Component component) { return "var keycode = Wicket.Event.keyCode(attrs.event);" + " return true;" ; } }; attributes.getAjaxCallListeners().add(listener); attributes.getDynamicExtraParameters() .add("var eventKeycode = Wicket.Event.keyCode(attrs.event);" + "return {keycode: eventKeycode};"); attributes.setAllowDefault(true); } @Override protected void onUpdate(AjaxRequestTarget aTarget) { final Request request = RequestCycle.get().getRequest(); final String jsKeycode = request.getRequestParameters() .getParameterValue("keycode").toString(""); if (jsKeycode.equals("32")){ try { actionAnnotate(aTarget, aBModel, false); selectedTag =""; } catch (UIMAException | ClassNotFoundException | IOException | BratAnnotationException e) { error(e); } return; } if (jsKeycode.equals("13")){ selectedTag =""; return; } selectedTag = (forwardAnnotationText.getModelObject() == null ? "" : forwardAnnotationText.getModelObject().charAt(0)) + selectedTag; featureModels.get(0).value = getKeyBindValue(selectedTag, getBindTags()); aTarget.add(forwardAnnotationText); aTarget.add(featureValues.get(0)); } }); forwardAnnotationText.setOutputMarkupId(true); forwardAnnotationText.add(new AttributeAppender("style", "opacity:0", ";")); // forwardAnno.add(new AttributeAppender("style", "filter:alpha(opacity=0)", ";")); featureEditorsContainer.add(forwardAnnotationText); featureEditorsContainer.add(featureValues); // the selected text for annotationa selectedTextLabel = new Label("selectedText", PropertyModel.of(getModelObject(), "selection.text")); selectedTextLabel.setOutputMarkupId(true); featureEditorsContainer.add(selectedTextLabel); featureEditorsContainer.add(new Label("layerName","Layer"){ private static final long serialVersionUID = 6084341323607243784L; @Override protected void onConfigure() { super.onConfigure(); setVisible(bModel.getPreferences().isBrushMode()); } }); featureEditorsContainer.setOutputMarkupId(true); // the annotation layer for the selected annotation selectedAnnotationLayer = new Label("selectedAnnotationLayer", new Model<String>()) { private static final long serialVersionUID = 4059460390544343324L; @Override protected void onConfigure() { super.onConfigure(); setVisible(bModel.getPreferences().isBrushMode()); } }; selectedAnnotationLayer.setOutputMarkupId(true); featureEditorsContainer.add(selectedAnnotationLayer); add(featureEditorsContainer); add(deleteModal = new ModalWindow("yesNoModal")); deleteModal.setOutputMarkupId(true); deleteModal.setInitialWidth(600); deleteModal.setInitialHeight(50); deleteModal.setResizable(true); deleteModal.setWidthUnit("px"); deleteModal.setHeightUnit("px"); deleteModal.setTitle("Are you sure you want to delete the existing annotation?"); } } public void actionAnnotate(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel, boolean aIsForwarded) throws UIMAException, ClassNotFoundException, IOException, BratAnnotationException { if (isAnnotationFinished()) { throw new BratAnnotationException( "This document is already closed. Please ask your project manager to re-open it via the Monitoring page"); } // If there is no annotation yet, create one. During creation, the adapter // may notice that it would create a duplicate and return the address of // an existing annotation instead of a new one. JCas jCas = getCas(aBModel); actionAnnotate(aTarget, aBModel, jCas, aIsForwarded); } public void actionAnnotate(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel, JCas jCas, boolean aIsForwarded) throws UIMAException, ClassNotFoundException, IOException, BratAnnotationException { if (aBModel.getSelectedAnnotationLayer() == null) { error("No layer is selected. First select a layer."); aTarget.addChildren(getPage(), FeedbackPanel.class); return; } if (aBModel.getSelectedAnnotationLayer().isReadonly()) { error("Layer is not editable."); aTarget.addChildren(getPage(), FeedbackPanel.class); return; } // Verify if input is valid according to tagset for (int i = 0; i < featureModels.size(); i++) { AnnotationFeature feature = featureModels.get(i).feature; if (CAS.TYPE_NAME_STRING.equals(feature.getType())) { String value = (String) featureModels.get(i).value; // Check if tag is necessary, set, and correct if ( value != null && feature.getTagset() != null && !feature.getTagset().isCreateTag() && !annotationService.existsTag(value, feature.getTagset()) ) { error("[" + value + "] is not in the tag list. Please choose from the existing tags"); return; } } } //aTarget.add(annotationFeatureForm); -- THIS CAUSES THE FOCUS TO BE ALWAYS TO THE FIRST ITEM #243 TypeAdapter adapter = getAdapter(annotationService, aBModel.getSelectedAnnotationLayer()); Selection selection = aBModel.getSelection(); if (selection.getAnnotation().isNotSet()) { if (bModel.getSelection().isRelationAnno()) { AnnotationFS originFs = selectByAddr(jCas, selection.getOrigin()); AnnotationFS targetFs = selectByAddr(jCas, selection.getTarget()); if (adapter instanceof SpanAdapter) { error("Layer do not support arc annotation."); aTarget.addChildren(getPage(), FeedbackPanel.class); return; } if (adapter instanceof ArcAdapter) { Sentence sentence = selectSentenceAt(jCas, bModel.getSentenceBeginOffset(), bModel.getSentenceEndOffset()); int start = sentence.getBegin(); int end = selectByAddr(jCas, Sentence.class, getLastSentenceAddressInDisplayWindow(jCas, getAddr(sentence), bModel.getPreferences().getWindowSize())).getEnd(); AnnotationFS arc = ((ArcAdapter) adapter).add(originFs, targetFs, jCas, start, end, null, null); selection.setAnnotation(new VID(getAddr(arc))); } else { selection.setAnnotation( new VID(((ChainAdapter) adapter).addArc(jCas, originFs, targetFs, null, null))); } selection.setBegin(originFs.getBegin()); } else if (adapter instanceof SpanAdapter) { for (FeatureModel fm : featureModels) { Serializable spanValue = ((SpanAdapter) adapter).getSpan(jCas, selection.getBegin(), selection.getEnd(), fm.feature, null); if (spanValue != null) { // allow modification for forward annotation if (aBModel.isForwardAnnotation()) { fm.value = spanValue; featureModels.get(0).value = spanValue; selectedTag = getBindTags().entrySet().stream().filter(e -> e.getValue().equals(spanValue)) .map(Map.Entry::getKey).findFirst().orElse(null); } else { actionClear(aTarget, bModel); throw new BratAnnotationException("Cannot create another annotation of layer [" + "" + bModel.getSelectedAnnotationLayer().getUiName() + " ] at this" + " location - stacking is not enabled for this layer."); } } } Integer annoId = ((SpanAdapter) adapter).add(jCas, selection.getBegin(), selection.getEnd(), null, null); selection.setAnnotation(new VID(annoId)); AnnotationFS annoFs = BratAjaxCasUtil.selectByAddr(jCas, annoId); selection.set(jCas, annoFs.getBegin(), annoFs.getEnd()); } else { for (FeatureModel fm : featureModels) { Serializable spanValue = ((ChainAdapter) adapter).getSpan(jCas, selection.getBegin(), selection.getEnd(), fm.feature, null); if (spanValue != null) { // allow modification for forward annotation if (aBModel.isForwardAnnotation()) { fm.value = spanValue; featureModels.get(0).value = spanValue; selectedTag = getBindTags().entrySet().stream().filter(e -> e.getValue().equals(spanValue)) .map(Map.Entry::getKey).findFirst().orElse(null); } } } selection.setAnnotation(new VID( ((ChainAdapter) adapter).addSpan(jCas, selection.getBegin(), selection.getEnd(), null, null))); } } // Set feature values List<AnnotationFeature> features = new ArrayList<AnnotationFeature>(); for (FeatureModel fm : featureModels) { features.add(fm.feature); // For string features with extensible tagsets, extend the tagset if (CAS.TYPE_NAME_STRING.equals(fm.feature.getType())) { String value = (String) fm.value; if ( value != null && fm.feature.getTagset() != null && fm.feature.getTagset().isCreateTag() && !annotationService.existsTag(value, fm.feature.getTagset()) ) { Tag selectedTag = new Tag(); selectedTag.setName(value); selectedTag.setTagSet(fm.feature.getTagset()); annotationService.createTag(selectedTag, aBModel.getUser()); } } adapter.updateFeature(jCas, fm.feature, aBModel.getSelection().getAnnotation().getId(), fm.value); } // Update progress information int sentenceNumber = getSentenceNumber(jCas, aBModel.getSelection().getBegin()); aBModel.setSentenceNumber(sentenceNumber); aBModel.getDocument().setSentenceAccessed(sentenceNumber); // persist changes repository.writeCas(aBModel.getMode(), aBModel.getDocument(), aBModel.getUser(), jCas); if (bModel.getSelection().isRelationAnno()) { aBModel.setRememberedArcLayer(aBModel.getSelectedAnnotationLayer()); aBModel.setRememberedArcFeatures(featureModels); } else { aBModel.setRememberedSpanLayer(aBModel.getSelectedAnnotationLayer()); aBModel.setRememberedSpanFeatures(featureModels); } aBModel.getSelection().setAnnotate(true); if (aBModel.getSelection().getAnnotation().isSet()) { String bratLabelText = TypeUtil.getBratLabelText(adapter, selectByAddr(jCas, aBModel.getSelection().getAnnotation().getId()), features); info(generateMessage(aBModel.getSelectedAnnotationLayer(), bratLabelText, false)); } onAnnotate(aTarget, aBModel); if (aBModel.isForwardAnnotation() && !aIsForwarded && featureModels.get(0).value != null) { if (aBModel.getSelection().getEnd() >= aBModel.getSentenceEndOffset()) { autoForwardScroll(jCas, aBModel); } onAutoForward(aTarget, aBModel); } else if (aBModel.getPreferences().isScrollPage()) { autoScroll(jCas, aBModel); } forwardAnnotationText.setModelObject(null); onChange(aTarget, aBModel); if (aBModel.isForwardAnnotation() && featureModels.get(0).value != null) { reload(aTarget); } } public void actionDelete(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel) throws IOException, UIMAException, ClassNotFoundException, CASRuntimeException, BratAnnotationException { JCas jCas = getCas(aBModel); AnnotationFS fs = selectByAddr(jCas, aBModel.getSelection().getAnnotation().getId()); // TODO We assume here that the selected annotation layer corresponds to the type of the // FS to be deleted. It would be more robust if we could get the layer from the FS itself. AnnotationLayer layer = aBModel.getSelectedAnnotationLayer(); TypeAdapter adapter = getAdapter(annotationService, layer); // == DELETE ATTACHED RELATIONS == // If the deleted FS is a span, we must delete all relations that // point to it directly or indirectly via the attachFeature. // // NOTE: It is important that this happens before UNATTACH SPANS since the attach feature // is no longer set after UNATTACH SPANS! if (adapter instanceof SpanAdapter) { for (AnnotationFS attachedFs : getAttachedRels(jCas, fs, layer)) { jCas.getCas().removeFsFromIndexes(attachedFs); info("The attached annotation for relation type [" + annotationService .getLayer(attachedFs.getType().getName(), bModel.getProject()).getUiName() + "] is deleted"); } } // == DELETE ATTACHED SPANS == // This case is currently not implemented because WebAnno currently does not allow to // create spans that attach to other spans. The only span type for which this is relevant // is the Token type which cannot be deleted. // == UNATTACH SPANS == // If the deleted FS is a span that is attached to another span, the // attachFeature in the other span must be set to null. Typical example: POS is deleted, so // the pos feature of Token must be set to null. This is a quick case, because we only need // to look at span annotations that have the same offsets as the FS to be deleted. if (adapter instanceof SpanAdapter && layer.getAttachType() != null) { Type spanType = CasUtil.getType(jCas.getCas(), layer.getAttachType().getName()); Feature attachFeature = spanType.getFeatureByBaseName(layer.getAttachFeature() .getName()); for (AnnotationFS attachedFs : selectAt(jCas.getCas(), spanType, fs.getBegin(), fs.getEnd())) { if (isSame(attachedFs.getFeatureValue(attachFeature), fs)) { attachedFs.setFeatureValue(attachFeature, null); LOG.debug("Unattached [" + attachFeature.getShortName() + "] on annotation [" + getAddr(attachedFs) + "]"); } } } // == CLEAN UP LINK FEATURES == // If the deleted FS is a span that is the target of a link feature, we must unset that // link and delete the slot if it is a multi-valued link. Here, we have to scan all // annotations from layers that have link features that could point to the FS // to be deleted: the link feature must be the type of the FS or it must be generic. if (adapter instanceof SpanAdapter) { for (AnnotationFeature linkFeature : annotationService.listAttachedLinkFeatures(layer)) { Type linkType = CasUtil.getType(jCas.getCas(), linkFeature.getLayer().getName()); for (AnnotationFS linkFS : CasUtil.select(jCas.getCas(), linkType)) { List<LinkWithRoleModel> links = getFeature(linkFS, linkFeature); Iterator<LinkWithRoleModel> i = links.iterator(); boolean modified = false; while (i.hasNext()) { LinkWithRoleModel link = i.next(); if (link.targetAddr == getAddr(fs)) { i.remove(); LOG.debug("Cleared slot [" + link.role + "] in feature [" + linkFeature.getName() + "] on annotation [" + getAddr(linkFS) + "]"); modified = true; } } if (modified) { setFeature(linkFS, linkFeature, links); } } } } // If the deleted FS is a relation, we don't have to do anything. Nothing can point to a // relation. if (adapter instanceof ArcAdapter) { // Do nothing ;) } // Actually delete annotation adapter.delete(jCas, aBModel.getSelection().getAnnotation()); // Store CAS again repository.writeCas(aBModel.getMode(), aBModel.getDocument(), aBModel.getUser(), jCas); // Update progress information int sentenceNumber = getSentenceNumber(jCas, aBModel.getSelection().getBegin()); aBModel.setSentenceNumber(sentenceNumber); aBModel.getDocument().setSentenceAccessed(sentenceNumber); // Auto-scroll if (aBModel.getPreferences().isScrollPage()) { autoScroll(jCas, aBModel); } aBModel.setRememberedSpanLayer(aBModel.getSelectedAnnotationLayer()); aBModel.getSelection().setAnnotate(false); info(generateMessage(aBModel.getSelectedAnnotationLayer(), null, true)); // A hack to remember the visual DropDown display value aBModel.setRememberedSpanLayer(aBModel.getSelectedAnnotationLayer()); aBModel.setRememberedSpanFeatures(featureModels); aBModel.getSelection().clear(); // after delete will follow annotation bModel.getSelection().setAnnotate(true); aTarget.add(annotationFeatureForm); aTarget.add(deleteButton); aTarget.add(reverseButton); onChange(aTarget, aBModel); onDelete(aTarget, aBModel, fs); } private void actionReverse(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel) throws IOException, UIMAException, ClassNotFoundException, BratAnnotationException { JCas jCas; jCas = getCas(aBModel); AnnotationFS idFs = selectByAddr(jCas, aBModel.getSelection().getAnnotation().getId()); jCas.removeFsFromIndexes(idFs); AnnotationFS originFs = selectByAddr(jCas, aBModel.getSelection().getOrigin()); AnnotationFS targetFs = selectByAddr(jCas, aBModel.getSelection().getTarget()); TypeAdapter adapter = getAdapter(annotationService, aBModel.getSelectedAnnotationLayer()); Sentence sentence = selectSentenceAt(jCas, bModel.getSentenceBeginOffset(), bModel.getSentenceEndOffset()); int start = sentence.getBegin(); int end = selectByAddr(jCas, Sentence.class, getLastSentenceAddressInDisplayWindow(jCas, getAddr(sentence), bModel.getPreferences().getWindowSize())) .getEnd(); if (adapter instanceof ArcAdapter) { if(featureModels.size()==0){ //If no features, still create arc #256 AnnotationFS arc = ((ArcAdapter) adapter).add(targetFs, originFs, jCas, start, end, null, null); aBModel.getSelection().setAnnotation(new VID(getAddr(arc))); } else{ for (FeatureModel fm : featureModels) { AnnotationFS arc = ((ArcAdapter) adapter).add(targetFs, originFs, jCas, start, end, fm.feature, fm.value); aBModel.getSelection().setAnnotation(new VID(getAddr(arc))); } } } else { error("chains cannot be reversed"); return; } // persist changes repository.writeCas(aBModel.getMode(), aBModel.getDocument(), aBModel.getUser(), jCas); int sentenceNumber = getSentenceNumber(jCas, originFs.getBegin()); aBModel.setSentenceNumber(sentenceNumber); aBModel.getDocument().setSentenceAccessed(sentenceNumber); if (aBModel.getPreferences().isScrollPage()) { autoScroll(jCas, aBModel); } info("The arc has been reversed"); aBModel.setRememberedArcLayer(aBModel.getSelectedAnnotationLayer()); aBModel.setRememberedArcFeatures(featureModels); // in case the user re-reverse it int temp = aBModel.getSelection().getOrigin(); aBModel.getSelection().setOrigin(aBModel.getSelection().getTarget()); aBModel.getSelection().setTarget(temp); onChange(aTarget, aBModel); } public void actionClear(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel) throws IOException, UIMAException, ClassNotFoundException, BratAnnotationException { aBModel.getSelection().clear(); aTarget.add(annotationFeatureForm); onChange(aTarget, aBModel); } public JCas getCas(BratAnnotatorModel aBModel) throws UIMAException, IOException, ClassNotFoundException { if (aBModel.getMode().equals(Mode.ANNOTATION) || aBModel.getMode().equals(Mode.AUTOMATION) || aBModel.getMode().equals(Mode.CORRECTION) || aBModel.getMode().equals(Mode.CORRECTION_MERGE)) { return repository.readAnnotationCas(aBModel.getDocument(), aBModel.getUser()); } else { return repository.readCurationCas(aBModel.getDocument()); } } private void autoScroll(JCas jCas, BratAnnotatorModel aBModel) { int address = getAddr(selectSentenceAt(jCas, aBModel.getSentenceBeginOffset(), aBModel.getSentenceEndOffset())); aBModel.setSentenceAddress(getSentenceBeginAddress(jCas, address, aBModel.getSelection() .getBegin(), aBModel.getProject(), aBModel.getDocument(), aBModel.getPreferences() .getWindowSize())); Sentence sentence = selectByAddr(jCas, Sentence.class, aBModel.getSentenceAddress()); aBModel.setSentenceBeginOffset(sentence.getBegin()); aBModel.setSentenceEndOffset(sentence.getEnd()); Sentence firstSentence = selectSentenceAt(jCas, aBModel.getSentenceBeginOffset(), aBModel.getSentenceEndOffset()); int lastAddressInPage = getLastSentenceAddressInDisplayWindow(jCas, getAddr(firstSentence), aBModel.getPreferences().getWindowSize()); // the last sentence address in the display window Sentence lastSentenceInPage = (Sentence) selectByAddr(jCas, FeatureStructure.class, lastAddressInPage); aBModel.setFSN(BratAjaxCasUtil.getSentenceNumber(jCas, firstSentence.getBegin())); aBModel.setLSN(BratAjaxCasUtil.getSentenceNumber(jCas, lastSentenceInPage.getBegin())); } private void autoForwardScroll(JCas jCas, BratAnnotatorModel aBModel) { int address = getNextSentenceAddress(jCas, selectByAddr(jCas, Sentence.class, aBModel.getSentenceAddress())); aBModel.setSentenceAddress(address); Sentence sentence = selectByAddr(jCas, Sentence.class, aBModel.getSentenceAddress()); aBModel.setSentenceBeginOffset(sentence.getBegin()); aBModel.setSentenceEndOffset(sentence.getEnd()); Sentence firstSentence = selectSentenceAt(jCas, aBModel.getSentenceBeginOffset(), aBModel.getSentenceEndOffset()); int lastAddressInPage = getLastSentenceAddressInDisplayWindow(jCas, getAddr(firstSentence), aBModel.getPreferences().getWindowSize()); // the last sentence address in the display window Sentence lastSentenceInPage = (Sentence) selectByAddr(jCas, FeatureStructure.class, lastAddressInPage); aBModel.setFSN(BratAjaxCasUtil.getSentenceNumber(jCas, firstSentence.getBegin())); aBModel.setLSN(BratAjaxCasUtil.getSentenceNumber(jCas, lastSentenceInPage.getBegin())); } @SuppressWarnings("unchecked") public void setSlot(AjaxRequestTarget aTarget, JCas aJCas, final BratAnnotatorModel aBModel, int aAnnotationId) { // Set an armed slot if (!bModel.getSelection().isRelationAnno() && aBModel.isSlotArmed()) { List<LinkWithRoleModel> links = (List<LinkWithRoleModel>) getFeatureModel(aBModel .getArmedFeature()).value; LinkWithRoleModel link = links.get(aBModel.getArmedSlot()); link.targetAddr = aAnnotationId; link.label = selectByAddr(aJCas, aAnnotationId).getCoveredText(); aBModel.clearArmedSlot(); } // Auto-commit if working on existing annotation if (bModel.getSelection().getAnnotation().isSet()) { try { actionAnnotate(aTarget, bModel, aJCas, false); } catch (BratAnnotationException e) { error(e.getMessage()); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } catch (Exception e) { error(ExceptionUtils.getRootCauseMessage(e)); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } } } private void setLayerAndFeatureModels(AjaxRequestTarget aTarget, JCas aJCas, final BratAnnotatorModel aBModel) throws BratAnnotationException { if (aBModel.getSelection().isRelationAnno()) { long layerId = TypeUtil.getLayerId(aBModel.getSelection().getOriginType()); AnnotationLayer spanLayer = annotationService.getLayer(layerId); if (aBModel.getPreferences().isBrushMode() && !aBModel.getDefaultAnnotationLayer().equals(spanLayer)) { throw new BratAnnotationException("No relation annotation allowed on the " + "selected span layer"); } // If we drag an arc between POS annotations, then the relation must be a dependency // relation. // FIXME - Actually this case should be covered by the last case - the database lookup! if (spanLayer.isBuiltIn() && spanLayer.getName().equals(POS.class.getName())) { AnnotationLayer depLayer = annotationService.getLayer(Dependency.class.getName(), aBModel.getProject()); if (aBModel.getAnnotationLayers().contains(depLayer)) { aBModel.setSelectedAnnotationLayer(depLayer); } else { aBModel.setSelectedAnnotationLayer(null); } } // If we drag an arc in a chain layer, then the arc is of the same layer as the span // Chain layers consist of arcs and spans else if (spanLayer.getType().equals(WebAnnoConst.CHAIN_TYPE)) { // one layer both for the span and arc annotation aBModel.setSelectedAnnotationLayer(spanLayer); } // Otherwise, look up the possible relation layer(s) in the database. else { for (AnnotationLayer layer : annotationService.listAnnotationLayer(aBModel .getProject())) { if (layer.getAttachType() != null && layer.getAttachType().equals(spanLayer)) { if (aBModel.getAnnotationLayers().contains(layer)) { aBModel.setSelectedAnnotationLayer(layer); } else { aBModel.setSelectedAnnotationLayer(null); } break; } } } // populate feature value if (aBModel.getSelection().getAnnotation().isSet()) { AnnotationFS annoFs = selectByAddr(aJCas, aBModel.getSelection().getAnnotation() .getId()); populateFeatures(annoFs); } // Avoid creation of arcs on locked layers else if (aBModel.getSelectedAnnotationLayer() != null && aBModel.getSelectedAnnotationLayer().isReadonly()) { aBModel.setSelectedAnnotationLayer(new AnnotationLayer()); } aBModel.setDefaultAnnotationLayer(spanLayer); } else if (aBModel.getSelection().getAnnotation().isSet()) { AnnotationFS annoFs = selectByAddr(aJCas, aBModel.getSelection().getAnnotation() .getId()); String type = annoFs.getType().getName(); // Might have been reset if we didn't find the layer above. Btw. this can happen if // somebody imports a CAS that has subtypes of layers, e.g. DKPro Core pipelines // like to produce subtypes of POS for individual postags. We do not support such // "elevated types" in WebAnno at this time. if (aBModel.getSelection().getAnnotation().isSet()) { if (type.endsWith(ChainAdapter.CHAIN)) { type = type.substring(0, type.length() - ChainAdapter.CHAIN.length()); } else if (type.endsWith(ChainAdapter.LINK)) { type = type.substring(0, type.length() - ChainAdapter.LINK.length()); } try { aBModel.setSelectedAnnotationLayer(annotationService.getLayer(type, aBModel.getProject())); } catch (NoResultException e) { reset(aTarget); throw new IllegalStateException("Unknown layer [" + type + "]", e); } // populate feature value for (AnnotationFeature feature : annotationService .listAnnotationFeature(aBModel.getSelectedAnnotationLayer())) { if (!feature.isEnabled()) { continue; } if (WebAnnoConst.CHAIN_TYPE.equals(feature.getLayer().getType())) { if (WebAnnoConst.COREFERENCE_TYPE_FEATURE.equals(feature.getName())) { featureModels.add(new FeatureModel(feature, (Serializable) BratAjaxCasUtil.getFeature(annoFs, feature))); } } else { featureModels.add(new FeatureModel(feature, (Serializable) BratAjaxCasUtil.getFeature(annoFs, feature))); } } } } } protected void onChange(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel) { // Overriden in BratAnnotator } protected void onAutoForward(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel) { // Overriden in BratAnnotator } public void onAnnotate(AjaxRequestTarget aTarget, BratAnnotatorModel aModel) { // Overriden in AutomationPage } public void onDelete(AjaxRequestTarget aTarget, BratAnnotatorModel aModel, AnnotationFS aFs) { // Overriden in AutomationPage } public void setAnnotationLayers(BratAnnotatorModel aBModel) { setInitSpanLayers(aBModel); if (annotationLayers.size() == 0) { aBModel.setSelectedAnnotationLayer(new AnnotationLayer()); } else if (aBModel.getSelectedAnnotationLayer() == null) { if (aBModel.getRememberedSpanLayer() == null) { aBModel.setSelectedAnnotationLayer(annotationLayers.get(0)); } else { aBModel.setSelectedAnnotationLayer(aBModel.getRememberedSpanLayer()); } } populateFeatures(null); updateBrushMode(); } private void setInitSpanLayers(BratAnnotatorModel aBModel) { annotationLayers.clear(); AnnotationLayer l = null; for (AnnotationLayer layer : aBModel.getAnnotationLayers()) { if (!layer.isEnabled() || layer.isReadonly() || layer.getName().equals(Token.class.getName())) { continue; } if (layer.getType().equals(WebAnnoConst.SPAN_TYPE)) { annotationLayers.add(layer); l = layer; } // manage chain type else if (layer.getType().equals(WebAnnoConst.CHAIN_TYPE)) { for (AnnotationFeature feature : annotationService.listAnnotationFeature(layer)) { if (!feature.isEnabled()) { continue; } if (feature.getName().equals(WebAnnoConst.COREFERENCE_TYPE_FEATURE)) { annotationLayers.add(layer); } } } // chain } if (bModel.getDefaultAnnotationLayer() != null) { bModel.setSelectedAnnotationLayer(bModel.getDefaultAnnotationLayer()); } else if (l != null) { bModel.setSelectedAnnotationLayer(l); } } public class FeatureEditorPanelContent extends RefreshingView<FeatureModel> { private static final long serialVersionUID = -8359786805333207043L; public FeatureEditorPanelContent(String aId) { super(aId); setOutputMarkupId(true); } @SuppressWarnings("rawtypes") @Override protected void populateItem(final Item<FeatureModel> item) { // Feature editors that allow multiple values may want to update themselves, // e.g. to add another slot. item.setOutputMarkupId(true); final FeatureModel fm = item.getModelObject(); final FeatureEditor frag; switch (fm.feature.getMultiValueMode()) { case NONE: { switch (fm.feature.getType()) { case CAS.TYPE_NAME_INTEGER: { frag = new NumberFeatureEditor("editor", "numberFeatureEditor", item, fm); break; } case CAS.TYPE_NAME_FLOAT: { frag = new NumberFeatureEditor("editor", "numberFeatureEditor", item, fm); break; } case CAS.TYPE_NAME_BOOLEAN: { frag = new BooleanFeatureEditor("editor", "booleanFeatureEditor", item, fm); break; } case CAS.TYPE_NAME_STRING: { frag = new TextFeatureEditor("editor", "textFeatureEditor", item, fm); break; } default: throw new IllegalArgumentException("Unsupported type [" + fm.feature.getType() + "] on feature [" + fm.feature.getName() + "]"); } break; } case ARRAY: { switch (fm.feature.getLinkMode()) { case WITH_ROLE: { // If it is none of the primitive types, it must be a link feature frag = new LinkFeatureEditor("editor", "linkFeatureEditor", item, fm); break; } default: throw new IllegalArgumentException("Unsupported link mode [" + fm.feature.getLinkMode() + "] on feature [" + fm.feature.getName() + "]"); } break; } default: throw new IllegalArgumentException("Unsupported multi-value mode [" + fm.feature.getMultiValueMode() + "] on feature [" + fm.feature.getName() + "]"); } item.add(frag); /* if (bModel.isForwardAnnotation()) { forwardAnnotationText.add(new DefaultFocusBehavior2()); } else { // Disabled for Github Issue #243 // Put focus on first feature // if (item.getIndex() == item.size() - 1) { // frag.getFocusComponent().add(new DefaultFocusBehavior()); // } }*/ if (!fm.feature.getLayer().isReadonly()) { // whenever it is updating an annotation, it updates automatically when a component // for the feature lost focus - but updating is for every component edited // LinkFeatureEditors must be excluded because the auto-update will break the // ability to add slots. Adding a slot is NOT an annotation action. // TODO annotate every time except when position is at (0,0) if (bModel.getSelection().getAnnotation().isSet() && !(frag instanceof LinkFeatureEditor)) { if (frag.isDropOrchoice()) { addAnnotateActionBehavior(frag, "onchange"); } else { addAnnotateActionBehavior(frag, "onblur"); } } else if (!(frag instanceof LinkFeatureEditor)) { if (frag.isDropOrchoice()) { storeFeatureValue(frag, "onchange"); } else { storeFeatureValue(frag, "onblur"); } } if (bModel.isForwardAnnotation()) { forwardAnnotationText.add(new DefaultFocusBehavior2()); } else if (item.getIndex() == 0) { // Put focus on first feature frag.getFocusComponent().add(new DefaultFocusBehavior()); } // Add tooltip on label StringBuilder tooltipTitle = new StringBuilder(); tooltipTitle.append(fm.feature.getUiName()); if (fm.feature.getTagset() != null) { tooltipTitle.append(" ("); tooltipTitle.append(fm.feature.getTagset().getName()); tooltipTitle.append(')'); } Component labelComponent = frag.getLabelComponent(); labelComponent.add(new AttributeAppender("style", "cursor: help", ";")); labelComponent.add(new DescriptionTooltipBehavior(tooltipTitle.toString(), fm.feature.getDescription())); } else { frag.getFocusComponent().setEnabled(false); } } private void storeFeatureValue(final FeatureEditor aFrag, String aEvent) { aFrag.getFocusComponent().add(new AjaxFormComponentUpdatingBehavior(aEvent) { private static final long serialVersionUID = 5179816588460867471L; @Override protected void onUpdate(AjaxRequestTarget aTarget) { aTarget.add(annotationFeatureForm); } }); } private void addAnnotateActionBehavior(final FeatureEditor aFrag, String aEvent) { aFrag.getFocusComponent().add(new AjaxFormComponentUpdatingBehavior(aEvent) { private static final long serialVersionUID = 5179816588460867471L; @Override protected void onUpdate(AjaxRequestTarget aTarget) { try { if (bModel.getConstraints() != null) { // Make sure we update the feature editor panel because due to // constraints the contents may have to be re-rendered aTarget.add(annotationFeatureForm); } actionAnnotate(aTarget, bModel, false); } catch (BratAnnotationException e) { error(ExceptionUtils.getRootCauseMessage(e)); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } catch (Exception e) { error(ExceptionUtils.getRootCauseMessage(e)); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } } }); } @Override protected Iterator<IModel<FeatureModel>> getItemModels() { ModelIteratorAdapter<FeatureModel> i = new ModelIteratorAdapter<FeatureModel>( featureModels) { @Override protected IModel<FeatureModel> model(FeatureModel aObject) { return Model.of(aObject); } }; return i; } } public static abstract class FeatureEditor extends Fragment { private static final long serialVersionUID = -7275181609671919722L; public FeatureEditor(String aId, String aMarkupId, MarkupContainer aMarkupProvider, IModel<?> aModel) { super(aId, aMarkupId, aMarkupProvider, aModel); } public Component getLabelComponent() { return get("feature"); } abstract public Component getFocusComponent(); abstract public boolean isDropOrchoice(); } public static class NumberFeatureEditor<T extends Number> extends FeatureEditor { private static final long serialVersionUID = -2426303638953208057L; @SuppressWarnings("rawtypes") private final NumberTextField field; public NumberFeatureEditor(String aId, String aMarkupId, MarkupContainer aMarkupProvider, FeatureModel aModel) { super(aId, aMarkupId, aMarkupProvider, new CompoundPropertyModel<FeatureModel>(aModel)); add(new Label("feature", aModel.feature.getUiName())); switch (aModel.feature.getType()) { case CAS.TYPE_NAME_INTEGER: { field = new NumberTextField<Integer>("value", Integer.class); add(field); break; } case CAS.TYPE_NAME_FLOAT: { field = new NumberTextField<Float>("value", Float.class); add(field); break; } default: throw new IllegalArgumentException("Type [" + aModel.feature.getType() + "] cannot be rendered as a numeric input field"); } } @SuppressWarnings("rawtypes") @Override public NumberTextField getFocusComponent() { return field; } @Override public boolean isDropOrchoice() { return false; } }; public static class BooleanFeatureEditor extends FeatureEditor { private static final long serialVersionUID = 5104979547245171152L; private final CheckBox field; public BooleanFeatureEditor(String aId, String aMarkupId, MarkupContainer aMarkupProvider, FeatureModel aModel) { super(aId, aMarkupId, aMarkupProvider, new CompoundPropertyModel<FeatureModel>(aModel)); add(new Label("feature", aModel.feature.getUiName())); field = new CheckBox("value"); add(field); } @Override public Component getFocusComponent() { return field; } @Override public boolean isDropOrchoice() { return true; } }; public class TextFeatureEditor extends FeatureEditor { private static final long serialVersionUID = 7763348613632105600L; @SuppressWarnings("rawtypes") private final AbstractTextComponent field; private boolean isDrop; //For showing the status of Constraints rules kicking in. private RulesIndicator indicator = new RulesIndicator(); private boolean hideUnconstraintFeature; /** * Hides feature if "Hide un-constraint feature" is enabled * and constraint rules are applied and feature doesn't match any constraint rule */ @Override public boolean isVisible() { if (hideUnconstraintFeature) { //if enabled and constraints rule execution returns anything other than green if (indicator.isAffected() && !indicator.getStatusColor().equals("green")) { return false; } } return true; } public TextFeatureEditor(String aId, String aMarkupId, MarkupContainer aMarkupProvider, FeatureModel aModel) { super(aId, aMarkupId, aMarkupProvider, new CompoundPropertyModel<FeatureModel>(aModel)); //Checks whether hide un-constraint feature is enabled or not hideUnconstraintFeature = aModel.feature.isHideUnconstraintFeature(); add(new Label("feature", aModel.feature.getUiName())); indicator.reset(); //reset the indicator if (aModel.feature.getTagset() != null) { List<Tag> tagset = null; BratAnnotatorModel model = bModel; // verification to check whether constraints exist for this project or NOT if (model.getConstraints() != null && model.getSelection().getAnnotation().isSet()) { // indicator.setRulesExist(true); tagset = populateTagsBasedOnRules(model, aModel); } else { // indicator.setRulesExist(false); // Earlier behavior, tagset = annotationService.listTags(aModel.feature.getTagset()); } field = new StyledComboBox<Tag>("value", tagset); field.setOutputMarkupId(true); // Must add behavior to editor, not to combobox to ensure proper order of the // initializing JS header items: first combo box, then tooltip. Options options = new Options(DescriptionTooltipBehavior.makeTooltipOptions()); options.set("content", functionForTooltip); add(new TooltipBehavior("#"+field.getMarkupId()+"_listbox *[title]", options)); isDrop = true; } else { field = new TextField<String>("value"); } //Shows whether constraints are triggered or not //also shows state of constraints use. Component constraintsInUseIndicator = new WebMarkupContainer("textIndicator"){ private static final long serialVersionUID = 4346767114287766710L; @Override public boolean isVisible() { return indicator.isAffected(); } }.add(new AttributeAppender("class", new Model<String>(){ private static final long serialVersionUID = -7683195283137223296L; @Override public String getObject() { //adds symbol to indicator return indicator.getStatusSymbol(); } })) .add(new AttributeAppender("style", new Model<String>(){ private static final long serialVersionUID = -5255873539738210137L; @Override public String getObject() { //adds color to indicator return "; color: " + indicator.getStatusColor(); } })); add(constraintsInUseIndicator); add(field); } /** * Adds and sorts tags based on Constraints rules */ private List<Tag> populateTagsBasedOnRules(BratAnnotatorModel model, FeatureModel aModel) { // Add values from rules String restrictionFeaturePath; switch (aModel.feature.getLinkMode()) { case WITH_ROLE: restrictionFeaturePath = aModel.feature.getName() + "." + aModel.feature.getLinkTypeRoleFeatureName(); break; case NONE: restrictionFeaturePath = aModel.feature.getName(); break; default: throw new IllegalArgumentException("Unsupported link mode [" + aModel.feature.getLinkMode() + "] on feature [" + aModel.feature.getName() + "]"); } List<Tag> valuesFromTagset = annotationService.listTags(aModel.feature.getTagset()); try { JCas jCas = getCas(model); FeatureStructure featureStructure = selectByAddr(jCas, model.getSelection() .getAnnotation().getId()); Evaluator evaluator = new ValuesGenerator(); //Only show indicator if this feature can be affected by Constraint rules! indicator.setAffected(evaluator.isThisAffectedByConstraintRules(featureStructure, restrictionFeaturePath, model.getConstraints())); List<PossibleValue> possibleValues; try { possibleValues = evaluator.generatePossibleValues( featureStructure, restrictionFeaturePath, model.getConstraints()); LOG.debug("Possible values for [" + featureStructure.getType().getName() + "] [" + restrictionFeaturePath + "]: " + possibleValues); } catch (Exception e) { error("Unable to evaluate constraints: " + ExceptionUtils.getRootCauseMessage(e)); LOG.error("Unable to evaluate constraints: " + e.getMessage(), e); possibleValues = new ArrayList<>(); } // only adds tags which are suggested by rules and exist in tagset. List<Tag> tagset = compareSortAndAdd(possibleValues, valuesFromTagset, indicator); // add remaining tags addRemainingTags(tagset, valuesFromTagset); return tagset; } catch (IOException | ClassNotFoundException | UIMAException e) { error(ExceptionUtils.getRootCauseMessage(e)); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } return valuesFromTagset; } @Override public Component getFocusComponent() { return field; } @Override public boolean isDropOrchoice() { return isDrop; } }; public class LinkFeatureEditor extends FeatureEditor { private static final long serialVersionUID = 7469241620229001983L; private WebMarkupContainer content; //For showing the status of Constraints rules kicking in. private RulesIndicator indicator = new RulesIndicator(); @SuppressWarnings("rawtypes") private final AbstractTextComponent newRole; private boolean isDrop; private boolean hideUnconstraintFeature; /** * Hides feature if "Hide un-constraint feature" is enabled * and constraint rules are applied and feature doesn't match any constraint rule */ @Override public boolean isVisible() { if (hideUnconstraintFeature) { //if enabled and constraints rule execution returns anything other than green if (indicator.isAffected() && !indicator.getStatusColor().equals("green")) { return false; } } return true; } @SuppressWarnings("unchecked") public LinkFeatureEditor(String aId, String aMarkupId, MarkupContainer aMarkupProvider, final FeatureModel aModel) { super(aId, aMarkupId, aMarkupProvider, new CompoundPropertyModel<FeatureModel>(aModel)); //Checks whether hide un-constraint feature is enabled or not hideUnconstraintFeature = aModel.feature.isHideUnconstraintFeature(); add(new Label("feature", aModel.feature.getUiName())); // Most of the content is inside this container such that we can refresh it independently // from the rest of the form content = new WebMarkupContainer("content"); content.setOutputMarkupId(true); add(content); content.add(new RefreshingView<LinkWithRoleModel>("slots", Model.of((List<LinkWithRoleModel>) aModel.value)) { private static final long serialVersionUID = 5475284956525780698L; @Override protected Iterator<IModel<LinkWithRoleModel>> getItemModels() { ModelIteratorAdapter<LinkWithRoleModel> i = new ModelIteratorAdapter<LinkWithRoleModel>( (List<LinkWithRoleModel>) LinkFeatureEditor.this.getModelObject().value) { @Override protected IModel<LinkWithRoleModel> model(LinkWithRoleModel aObject) { return Model.of(aObject); } }; return i; } @Override protected void populateItem(final Item<LinkWithRoleModel> aItem) { aItem.setModel(new CompoundPropertyModel<LinkWithRoleModel>(aItem .getModelObject())); Label role = new Label("role"); aItem.add(role); final Label label; if (aItem.getModelObject().targetAddr == -1 && bModel.isArmedSlot(aModel.feature, aItem.getIndex())) { label = new Label("label", "<Select to fill>"); } else { label = new Label("label"); } label.add(new AjaxEventBehavior("click") { private static final long serialVersionUID = 7633309278417475424L; @Override protected void onEvent(AjaxRequestTarget aTarget) { if (bModel.isArmedSlot(aModel.feature, aItem.getIndex())) { bModel.clearArmedSlot(); aTarget.add(content); } else { bModel.setArmedSlot(aModel.feature, aItem.getIndex()); // Need to re-render the whole form because a slot in another // link editor might get unarmed aTarget.add(annotationFeatureForm); } } }); label.add(new AttributeAppender("style", new Model<String>() { private static final long serialVersionUID = 1L; @Override public String getObject() { BratAnnotatorModel model = bModel; if (model.isArmedSlot(aModel.feature, aItem.getIndex())) { return "; background: orange"; } else { return ""; } } })); aItem.add(label); } }); if (aModel.feature.getTagset() != null) { List<Tag> tagset = null; //reset the indicator indicator.reset(); if (bModel.getConstraints() != null && bModel.getSelection().getAnnotation().isSet()) { // indicator.setRulesExist(true); //Constraint rules exist! tagset = addTagsBasedOnRules(bModel, aModel); } else { // indicator.setRulesExist(false); //No constraint rules. // add tagsets only, earlier behavior tagset = annotationService.listTags(aModel.feature.getTagset()); } newRole = new StyledComboBox<Tag>("newRole", Model.of(""), tagset) { private static final long serialVersionUID = 1L; @Override protected void onInitialize() { super.onInitialize(); // Ensure proper order of the initializing JS header items: first combo box // behavior (in super.onInitialize()), then tooltip. Options options = new Options(DescriptionTooltipBehavior.makeTooltipOptions()); options.set("content", functionForTooltip); add(new TooltipBehavior("#"+newRole.getMarkupId()+"_listbox *[title]", options)); } @Override protected void onConfigure() { super.onConfigure(); if (bModel.isSlotArmed() && aModel.feature.equals(bModel.getArmedFeature())) { List<LinkWithRoleModel> links = (List<LinkWithRoleModel>) LinkFeatureEditor.this .getModelObject().value; setModelObject(links.get(bModel.getArmedSlot()).role); } else { setModelObject(""); } } }; newRole.setOutputMarkupId(true); content.add(newRole); isDrop = true; } else { content.add(newRole = new TextField<String>("newRole", Model.of("")) { private static final long serialVersionUID = 1L; @Override protected void onConfigure() { super.onConfigure(); if (bModel.isSlotArmed() && aModel.feature.equals(bModel.getArmedFeature())) { List<LinkWithRoleModel> links = (List<LinkWithRoleModel>) LinkFeatureEditor.this .getModelObject().value; setModelObject(links.get(bModel.getArmedSlot()).role); } else { setModelObject(""); } } }); } //Shows whether constraints are triggered or not //also shows state of constraints use. Component constraintsInUseIndicator = new WebMarkupContainer("linkIndicator"){ private static final long serialVersionUID = 4346767114287766710L; @Override public boolean isVisible() { return indicator.isAffected(); } }.add(new AttributeAppender("class", new Model<String>(){ private static final long serialVersionUID = -7683195283137223296L; @Override public String getObject() { //adds symbol to indicator return indicator.getStatusSymbol(); } })) .add(new AttributeAppender("style", new Model<String>(){ private static final long serialVersionUID = -5255873539738210137L; @Override public String getObject() { //adds color to indicator return "; color: " + indicator.getStatusColor(); } })); add(constraintsInUseIndicator); // Add a new empty slot with the specified role content.add(new AjaxButton("add") { private static final long serialVersionUID = 1L; @Override protected void onConfigure(){ BratAnnotatorModel model = bModel; setVisible(!(model.isSlotArmed() && aModel.feature.equals(model.getArmedFeature()))); // setEnabled(!(model.isSlotArmed() // && aModel.feature.equals(model.getArmedFeature()))); } @Override protected void onSubmit(AjaxRequestTarget aTarget, Form<?> aForm) { if (StringUtils.isBlank((String) newRole.getModelObject())) { error("Must set slot label before adding!"); aTarget.addChildren(getPage(), FeedbackPanel.class); } else { List<LinkWithRoleModel> links = (List<LinkWithRoleModel>) LinkFeatureEditor.this .getModelObject().value; LinkWithRoleModel m = new LinkWithRoleModel(); m.role = (String) newRole.getModelObject(); links.add(m); bModel.setArmedSlot(LinkFeatureEditor.this.getModelObject().feature, links.size() - 1); // Need to re-render the whole form because a slot in another // link editor might get unarmed aTarget.add(annotationFeatureForm); } } }); // Allows user to update slot content.add(new AjaxButton("set"){ private static final long serialVersionUID = 7923695373085126646L; @Override protected void onConfigure(){ BratAnnotatorModel model = bModel; setVisible(model.isSlotArmed() && aModel.feature.equals(model.getArmedFeature())); // setEnabled(model.isSlotArmed() // && aModel.feature.equals(model.getArmedFeature())); } @Override protected void onSubmit(AjaxRequestTarget aTarget, Form<?> aForm) { List<LinkWithRoleModel> links = (List<LinkWithRoleModel>) LinkFeatureEditor.this .getModelObject().value; BratAnnotatorModel model = bModel; //Update the slot LinkWithRoleModel m = new LinkWithRoleModel(); m = links.get(model.getArmedSlot()); m.role = (String) newRole.getModelObject(); // int index = model.getArmedSlot(); //retain index // links.remove(model.getArmedSlot()); // model.clearArmedSlot(); // links.add(m); links.set(model.getArmedSlot(), m); //avoid reordering aTarget.add(content); try { actionAnnotate(aTarget, bModel, false); } catch(BratAnnotationException e){ error(ExceptionUtils.getRootCauseMessage(e)); LOG.error(ExceptionUtils.getRootCause(e),e); } catch (Exception e) { error(e.getMessage()); LOG.error(ExceptionUtils.getRootCause(e),e); } } }); // Add a new empty slot with the specified role content.add(new AjaxButton("del") { private static final long serialVersionUID = 1L; @Override protected void onConfigure() { BratAnnotatorModel model = bModel; setVisible(model.isSlotArmed() && aModel.feature.equals(model.getArmedFeature())); // setEnabled(model.isSlotArmed() // && aModel.feature.equals(model.getArmedFeature())); } @Override protected void onSubmit(AjaxRequestTarget aTarget, Form<?> aForm) { List<LinkWithRoleModel> links = (List<LinkWithRoleModel>) LinkFeatureEditor.this .getModelObject().value; BratAnnotatorModel model = bModel; links.remove(model.getArmedSlot()); model.clearArmedSlot(); aTarget.add(content); // Auto-commit if working on existing annotation if (bModel.getSelection().getAnnotation().isSet()) { try { actionAnnotate(aTarget, bModel, false); } catch (BratAnnotationException e) { error(ExceptionUtils.getRootCauseMessage(e)); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } catch (Exception e) { error(ExceptionUtils.getRootCauseMessage(e)); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } } } }); } /** * Adds tagset based on Constraints rules, auto-adds tags which are marked important. * * @return List containing tags which exist in tagset and also suggested by rules, followed * by the remaining tags in tagset. */ private List<Tag> addTagsBasedOnRules(BratAnnotatorModel model, final FeatureModel aModel) { String restrictionFeaturePath = aModel.feature.getName() + "." + aModel.feature.getLinkTypeRoleFeatureName(); List<Tag> valuesFromTagset = annotationService.listTags(aModel.feature.getTagset()); try { JCas jCas = getCas(model); FeatureStructure featureStructure = selectByAddr(jCas, model.getSelection() .getAnnotation().getId()); Evaluator evaluator = new ValuesGenerator(); //Only show indicator if this feature can be affected by Constraint rules! indicator.setAffected(evaluator.isThisAffectedByConstraintRules(featureStructure, restrictionFeaturePath, model.getConstraints())); List<PossibleValue> possibleValues; try { possibleValues = evaluator.generatePossibleValues( featureStructure, restrictionFeaturePath, model.getConstraints()); LOG.debug("Possible values for [" + featureStructure.getType().getName() + "] [" + restrictionFeaturePath + "]: " + possibleValues); } catch (Exception e) { error("Unable to evaluate constraints: " + ExceptionUtils.getRootCauseMessage(e)); LOG.error("Unable to evaluate constraints: " + ExceptionUtils.getRootCauseMessage(e), e); possibleValues = new ArrayList<>(); } // Only adds tags which are suggested by rules and exist in tagset. List<Tag> tagset = compareSortAndAdd(possibleValues, valuesFromTagset, indicator); removeAutomaticallyAddedUnusedEntries(); // Create entries for important tags. autoAddImportantTags(tagset, possibleValues); // Add remaining tags. addRemainingTags(tagset, valuesFromTagset); return tagset; } catch (ClassNotFoundException | UIMAException | IOException e) { error(ExceptionUtils.getRootCauseMessage(e)); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } return valuesFromTagset; } private void removeAutomaticallyAddedUnusedEntries() { // Remove unused (but auto-added) tags. @SuppressWarnings("unchecked") List<LinkWithRoleModel> list = (List<LinkWithRoleModel>) LinkFeatureEditor.this .getModelObject().value; Iterator<LinkWithRoleModel> existingLinks = list.iterator(); while (existingLinks.hasNext()) { LinkWithRoleModel link = existingLinks.next(); if (link.autoCreated && link.targetAddr == -1) { // remove it existingLinks.remove(); } } } private void autoAddImportantTags(List<Tag> aTagset, List<PossibleValue> possibleValues) { // Construct a quick index for tags Set<String> tagset = new HashSet<String>(); for (Tag t : aTagset) { tagset.add(t.getName()); } // Get links list and build role index @SuppressWarnings("unchecked") List<LinkWithRoleModel> links = (List<LinkWithRoleModel>) LinkFeatureEditor.this .getModelObject().value; Set<String> roles = new HashSet<String>(); for (LinkWithRoleModel l : links) { roles.add(l.role); } // Loop over values to see which of the tags are important and add them. for (PossibleValue value : possibleValues) { if (!value.isImportant() || !tagset.contains(value.getValue())) { continue; } // Check if there is already a slot with the given name if (roles.contains(value.getValue())) { continue; } // Add empty slot in UI with that name. LinkWithRoleModel m = new LinkWithRoleModel(); m.role = value.getValue(); // Marking so that can be ignored later. m.autoCreated = true; links.add(m); // NOT arming the slot here! } } public void setModelObject(FeatureModel aModel) { setDefaultModelObject(aModel); } public FeatureModel getModelObject() { return (FeatureModel) getDefaultModelObject(); } @Override public Component getFocusComponent() { return newRole; } @Override public boolean isDropOrchoice() { return isDrop; } }; public void populateFeatures(FeatureStructure aFS) { featureModels = new ArrayList<>(); if (aFS != null) { // Populate from feature structure for (AnnotationFeature feature : annotationService .listAnnotationFeature(bModel.getSelectedAnnotationLayer())) { if (!feature.isEnabled()) { continue; } if (WebAnnoConst.CHAIN_TYPE.equals(feature.getLayer().getType())) { if (bModel.getSelection().isRelationAnno()) { if (feature.getLayer().isLinkedListBehavior() && WebAnnoConst.COREFERENCE_RELATION_FEATURE.equals(feature .getName())) { featureModels.add(new FeatureModel(feature, (Serializable) BratAjaxCasUtil.getFeature(aFS, feature))); } } else { if (WebAnnoConst.COREFERENCE_TYPE_FEATURE.equals(feature.getName())) { featureModels.add(new FeatureModel(feature, (Serializable) BratAjaxCasUtil.getFeature(aFS, feature))); } } } else { featureModels.add(new FeatureModel(feature, (Serializable) BratAjaxCasUtil.getFeature(aFS, feature))); } } } else if (!bModel.getSelection().isRelationAnno() && bModel.getRememberedSpanFeatures() != null) { // Populate from remembered values for (AnnotationFeature feature : annotationService .listAnnotationFeature(bModel.getSelectedAnnotationLayer())) { if (!feature.isEnabled()) { continue; } if (WebAnnoConst.CHAIN_TYPE.equals(feature.getLayer().getType())) { if (WebAnnoConst.COREFERENCE_TYPE_FEATURE.equals(feature.getName())) { featureModels.add(new FeatureModel(feature, bModel.getRememberedSpanFeatures().get(feature))); } } else { featureModels.add(new FeatureModel(feature, bModel.getRememberedSpanFeatures().get(feature))); } } } else if (bModel.getSelection().isRelationAnno() && bModel.getRememberedArcFeatures() != null) { // Populate from remembered values for (AnnotationFeature feature : annotationService .listAnnotationFeature(bModel.getSelectedAnnotationLayer())) { if (!feature.isEnabled()) { continue; } if (WebAnnoConst.CHAIN_TYPE.equals(feature.getLayer().getType())) { if (feature.getLayer().isLinkedListBehavior() && WebAnnoConst.COREFERENCE_RELATION_FEATURE.equals(feature.getName())) { featureModels.add(new FeatureModel(feature, bModel .getRememberedArcFeatures().get(feature))); } } else { featureModels.add(new FeatureModel(feature, bModel.getRememberedArcFeatures().get(feature))); } } } } public void addRemainingTags(List<Tag> tagset, List<Tag> valuesFromTagset) { // adding the remaining part of tagset. for (Tag remainingTag : valuesFromTagset) { if (!tagset.contains(remainingTag)) { tagset.add(remainingTag); } } } /* * Compares existing tagset with possible values resulted from rule evaluation Adds only which * exist in tagset and is suggested by rules. The remaining values from tagset are added * afterwards. */ private static List<Tag> compareSortAndAdd(List<PossibleValue> possibleValues, List<Tag> valuesFromTagset, RulesIndicator rulesIndicator) { //if no possible values, means didn't satisfy conditions if(possibleValues.isEmpty()) { rulesIndicator.didntMatchAnyRule(); } List<Tag> returnList = new ArrayList<Tag>(); // Sorting based on important flag // possibleValues.sort(null); // Comparing to check which values suggested by rules exists in existing // tagset and adding them first in list. for (PossibleValue value : possibleValues) { for (Tag tag : valuesFromTagset) { if (value.getValue().equalsIgnoreCase(tag.getName())) { //Matching values found in tagset and shown in dropdown rulesIndicator.rulesApplied(); // HACK BEGIN tag.setReordered(true); // HACK END //Avoid duplicate entries if(!returnList.contains(tag)){ returnList.add(tag); } } } } //If no matching tags found if(returnList.isEmpty()){ rulesIndicator.didntMatchAnyTag(); } return returnList; } public class LayerSelector extends DropDownChoice<AnnotationLayer> { private static final long serialVersionUID = 2233133653137312264L; public LayerSelector(String aId, List<? extends AnnotationLayer> aChoices) { super(aId, aChoices); setOutputMarkupId(true); setChoiceRenderer(new ChoiceRenderer<AnnotationLayer>("uiName")); add(new AjaxFormComponentUpdatingBehavior("onchange") { private static final long serialVersionUID = 5179816588460867471L; @Override protected void onUpdate(AjaxRequestTarget aTarget) { if (!bModel.getSelectedAnnotationLayer().equals(getModelObject()) && bModel.getSelection().getAnnotation().isSet()) { if (bModel.getSelection().isRelationAnno()) { try { actionClear(aTarget, bModel); } catch (UIMAException | ClassNotFoundException | IOException | BratAnnotationException e) { error(e.getMessage()); } } else { deleteModal.setContent(new DeleteOrReplaceAnnotationModalPanel( deleteModal.getContentId(), bModel, deleteModal, AnnotationDetailEditorPanel.this, getModelObject(), true)); deleteModal .setWindowClosedCallback(new ModalWindow.WindowClosedCallback() { private static final long serialVersionUID = 4364820331676014559L; @Override public void onClose(AjaxRequestTarget target) { target.add(annotationFeatureForm); } }); deleteModal.show(aTarget); } } else { bModel.setSelectedAnnotationLayer(getModelObject()); selectedAnnotationLayer.setDefaultModelObject(getModelObject().getUiName()); aTarget.add(selectedAnnotationLayer); populateFeatures(null); aTarget.add(annotationFeatureForm); } } }); } } private FeatureModel getFeatureModel(AnnotationFeature aFeature) { for (FeatureModel f : featureModels) { if (f.feature.getId() == aFeature.getId()) { return f; } } return null; } /** * Represents a link with a role in the UI. */ public static class LinkWithRoleModel implements Serializable { private static final long serialVersionUID = 2027345278696308900L; public static final String CLICK_HINT = "<Click to activate>"; public String role; public String label = CLICK_HINT; public int targetAddr = -1; public boolean autoCreated; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((label == null) ? 0 : label.hashCode()); result = prime * result + ((role == null) ? 0 : role.hashCode()); result = prime * result + targetAddr; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } LinkWithRoleModel other = (LinkWithRoleModel) obj; if (label == null) { if (other.label != null) { return false; } } else if (!label.equals(other.label)) { return false; } if (role == null) { if (other.role != null) { return false; } } else if (!role.equals(other.role)) { return false; } if (targetAddr != other.targetAddr) { return false; } return true; } } private void updateForwardAnnotation(BratAnnotatorModel aBModel) { if (aBModel.getSelectedAnnotationLayer() != null && !aBModel.getSelectedAnnotationLayer().isLockToTokenOffset()) { aBModel.setForwardAnnotation(false);// no forwarding for // sub-/multitoken annotation } else { aBModel.setForwardAnnotation(aBModel.isForwardAnnotation()); } } public static class FeatureModel implements Serializable { private static final long serialVersionUID = 3512979848975446735L; public final AnnotationFeature feature; public Serializable value; public FeatureModel(AnnotationFeature aFeature, Serializable aValue) { feature = aFeature; value = aValue; // Avoid having null here because otherwise we have to handle null in zillion places! if (value == null && MultiValueMode.ARRAY.equals(aFeature.getMultiValueMode())) { value = new ArrayList<>(); } } } private Map<String, String> getBindTags() { AnnotationFeature f = annotationService.listAnnotationFeature(bModel.getSelectedAnnotationLayer()).get(0); TagSet tagSet = f.getTagset(); Map<Character, String> tagNames = new LinkedHashMap<>(); Map<String, String> bindTag2Key = new LinkedHashMap<>(); for (Tag tag : annotationService.listTags(tagSet)) { if (tagNames.containsKey(tag.getName().toLowerCase().charAt(0))) { String oldBinding = tagNames.get(tag.getName().toLowerCase().charAt(0)); String newBinding = oldBinding + tag.getName().toLowerCase().charAt(0); tagNames.put(tag.getName().toLowerCase().charAt(0), newBinding); bindTag2Key.put(newBinding, tag.getName()); } else { tagNames.put(tag.getName().toLowerCase().charAt(0), tag.getName().toLowerCase().substring(0, 1)); bindTag2Key.put(tag.getName().toLowerCase().substring(0, 1), tag.getName()); } } return bindTag2Key; } private String getKeyBindValue(String aKey, Map<String, String> aBindTags){ // check if all the key pressed are the same character // if not, just check a Tag for the last char pressed if(aKey.isEmpty()){ return aBindTags.get(aBindTags.keySet().iterator().next()); } char prevC = aKey.charAt(0); for(char ch:aKey.toCharArray()){ if(ch!=prevC){ break; } } if (aBindTags.get(aKey)!=null){ return aBindTags.get(aKey); } // re-cycle suggestions if(aBindTags.containsKey(aKey.substring(0,1))){ selectedTag = aKey.substring(0,1); return aBindTags.get(aKey.substring(0,1)); } // set it to the first in the tag list , when arbitrary key is pressed return aBindTags.get(aBindTags.keySet().iterator().next()); } public void reload(AjaxRequestTarget aTarget) { aTarget.add(annotationFeatureForm); } public void reset(AjaxRequestTarget aTarget) { bModel.getSelection().clear(); bModel.getSelection().setBegin(0); bModel.getSelection().setEnd(0); featureModels = new ArrayList<>(); aTarget.add(annotationFeatureForm); } public void reloadLayer(AjaxRequestTarget aTarget) throws BratAnnotationException { try { featureModels = new ArrayList<>(); if (!bModel.getSelection().isRelationAnno()) { setInitSpanLayers(bModel); } setLayerAndFeatureModels(aTarget, getCas(bModel), bModel); if (featureModels.size() == 0) { populateFeatures(null); } else if (isFeatureModelChanged(bModel.getSelectedAnnotationLayer())) { populateFeatures(null); } updateBrushMode(); aTarget.add(annotationFeatureForm); } catch (UIMAException | ClassNotFoundException | IOException e) { error(e.getMessage()); } } private void updateBrushMode() { if (bModel.getPreferences().isBrushMode()) { if (bModel.getDefaultAnnotationLayer() == null) { bModel.setDefaultAnnotationLayer(bModel.getSelectedAnnotationLayer()); } } else if (!bModel.getSelection().isRelationAnno()) { bModel.setDefaultAnnotationLayer(bModel.getSelectedAnnotationLayer()); } // if no layer is selected in Settings if (bModel.getSelectedAnnotationLayer() != null) { selectedAnnotationLayer.setDefaultModelObject(bModel.getSelectedAnnotationLayer().getUiName()); } } /** * remove this model, if new annotation is to be created */ public void clearArmedSlotModel() { for (FeatureModel fm : featureModels) { if (StringUtils.isNotBlank(fm.feature.getLinkTypeName())) { fm.value = new ArrayList<>(); } } } private Set<AnnotationFS> getAttachedRels(JCas aJCas, AnnotationFS aFs, AnnotationLayer aLayer) throws UIMAException, ClassNotFoundException, IOException{ Set<AnnotationFS> toBeDeleted = new HashSet<AnnotationFS>(); for (AnnotationLayer relationLayer : annotationService .listAttachedRelationLayers(aLayer)) { ArcAdapter relationAdapter = (ArcAdapter) getAdapter(annotationService, relationLayer); Type relationType = CasUtil.getType(aJCas.getCas(), relationLayer.getName()); Feature sourceFeature = relationType.getFeatureByBaseName(relationAdapter .getSourceFeatureName()); Feature targetFeature = relationType.getFeatureByBaseName(relationAdapter .getTargetFeatureName()); // This code is already prepared for the day that relations can go between // different layers and may have different attach features for the source and // target layers. Feature relationSourceAttachFeature = null; Feature relationTargetAttachFeature = null; if (relationAdapter.getAttachFeatureName() != null) { relationSourceAttachFeature = sourceFeature.getRange().getFeatureByBaseName( relationAdapter.getAttachFeatureName()); relationTargetAttachFeature = targetFeature.getRange().getFeatureByBaseName( relationAdapter.getAttachFeatureName()); } for (AnnotationFS relationFS : CasUtil.select(aJCas.getCas(), relationType)) { // Here we get the annotations that the relation is pointing to in the UI FeatureStructure sourceFS; if (relationSourceAttachFeature != null) { sourceFS = relationFS.getFeatureValue(sourceFeature).getFeatureValue( relationSourceAttachFeature); } else { sourceFS = relationFS.getFeatureValue(sourceFeature); } FeatureStructure targetFS; if (relationTargetAttachFeature != null) { targetFS = relationFS.getFeatureValue(targetFeature).getFeatureValue( relationTargetAttachFeature); } else { targetFS = relationFS.getFeatureValue(targetFeature); } if (isSame(sourceFS, aFs) || isSame(targetFS, aFs)) { toBeDeleted.add(relationFS); LOG.debug("Deleted relation [" + getAddr(relationFS) + "] from layer [" + relationLayer.getName() + "]"); } } } return toBeDeleted; } public AnnotationFeatureForm getAnnotationFeatureForm() { return annotationFeatureForm; } public Label getSelectedAnnotationLayer() { return selectedAnnotationLayer; } private boolean isFeatureModelChanged(AnnotationLayer aLayer){ for(FeatureModel fM: featureModels){ if(!annotationService.listAnnotationFeature(aLayer).contains(fM.feature)){ return true; } } return false; } private boolean isForwardable() { if (bModel.getSelectedAnnotationLayer() == null) { return false; } if (bModel.getSelectedAnnotationLayer().getId() <= 0) { return false; } if (!bModel.getSelectedAnnotationLayer().getType().equals(WebAnnoConst.SPAN_TYPE)) { return false; } if (!bModel.getSelectedAnnotationLayer().isLockToTokenOffset()) { return false; } // no forward annotation for multifeature layers. if(annotationService.listAnnotationFeature(bModel.getSelectedAnnotationLayer()).size()>1){ return false; } // if there are no features at all, no forward annotation if(annotationService.listAnnotationFeature(bModel.getSelectedAnnotationLayer()).isEmpty()){ return false; } // we allow forward annotation only for a feature with a tagset if(annotationService.listAnnotationFeature(bModel.getSelectedAnnotationLayer()).get(0).getTagset()==null){ return false; } TagSet tagSet = annotationService.listAnnotationFeature(bModel.getSelectedAnnotationLayer()).get(0).getTagset(); // there should be at least one tag in the tagset if(annotationService.listTags(tagSet).size()==0){ return false; } return true; } private static String generateMessage(AnnotationLayer aLayer, String aLabel, boolean aDeleted) { String action = aDeleted ? "deleted" : "created/updated"; String msg = "The [" + aLayer.getUiName() + "] annotation has been " + action + "."; if (StringUtils.isNotBlank(aLabel)) { msg += " Label: [" + aLabel + "]"; } return msg; } class StyledComboBox<T> extends ComboBox<T> { public StyledComboBox(String id, IModel<String> model, List<T> choices) { super(id, model, choices); } public StyledComboBox(String string, List<T> choices) { super(string, choices); } private static final long serialVersionUID = 1L; @Override protected IJQueryTemplate newTemplate() { return new IJQueryTemplate() { private static final long serialVersionUID = 1L; /** * Marks the reordered entries in bold. * Same as text feature editor. */ @Override public String getText() { // Some docs on how the templates work in Kendo, in case we need // more fancy dropdowns // http://docs.telerik.com/kendo-ui/framework/templates/overview StringBuilder sb = new StringBuilder(); sb.append("# if (data.reordered == 'true') { #"); sb.append("<div title=\"#: data.description #\"><b>#: data.name #</b></div>\n"); sb.append("# } else { #"); sb.append("<div title=\"#: data.description #\">#: data.name #</div>\n"); sb.append("# } #"); return sb.toString(); } @Override public List<String> getTextProperties() { return Arrays.asList("name", "description", "reordered"); } }; } } }
webanno-brat/src/main/java/de/tudarmstadt/ukp/clarin/webanno/brat/annotation/component/AnnotationDetailEditorPanel.java
/******************************************************************************* * Copyright 2015 * Ubiquitous Knowledge Processing (UKP) Lab and FG Language Technology * Technische Universität Darmstadt * * 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.tudarmstadt.ukp.clarin.webanno.brat.annotation.component; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.getAddr; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.getFeature; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.getLastSentenceAddressInDisplayWindow; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.getNextSentenceAddress; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.getSentenceBeginAddress; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.getSentenceNumber; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.isSame; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.selectAt; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.selectByAddr; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.selectSentenceAt; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.setFeature; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.TypeUtil.getAdapter; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.persistence.NoResultException; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.uima.UIMAException; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASRuntimeException; import org.apache.uima.cas.Feature; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.Type; import org.apache.uima.cas.text.AnnotationFS; import org.apache.uima.fit.util.CasUtil; import org.apache.uima.jcas.JCas; import org.apache.wicket.Component; import org.apache.wicket.MarkupContainer; import org.apache.wicket.ajax.AjaxEventBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.attributes.AjaxCallListener; import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; import org.apache.wicket.ajax.attributes.IAjaxCallListener; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.ajax.form.AjaxFormValidatingBehavior; import org.apache.wicket.ajax.markup.html.form.AjaxButton; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.AbstractTextComponent; import org.apache.wicket.markup.html.form.CheckBox; import org.apache.wicket.markup.html.form.ChoiceRenderer; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.markup.html.panel.Fragment; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.markup.repeater.RefreshingView; import org.apache.wicket.markup.repeater.util.ModelIteratorAdapter; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.request.Request; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.spring.injection.annot.SpringBean; import org.codehaus.plexus.util.StringUtils; import com.googlecode.wicket.jquery.core.Options; import com.googlecode.wicket.jquery.core.template.IJQueryTemplate; import com.googlecode.wicket.jquery.ui.widget.tooltip.TooltipBehavior; import com.googlecode.wicket.kendo.ui.form.NumberTextField; import com.googlecode.wicket.kendo.ui.form.TextField; import com.googlecode.wicket.kendo.ui.form.combobox.ComboBox; import de.tudarmstadt.ukp.clarin.webanno.api.AnnotationService; import de.tudarmstadt.ukp.clarin.webanno.api.RepositoryService; import de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst; import de.tudarmstadt.ukp.clarin.webanno.brat.annotation.BratAnnotatorModel; import de.tudarmstadt.ukp.clarin.webanno.brat.annotation.command.Selection; import de.tudarmstadt.ukp.clarin.webanno.brat.controller.ArcAdapter; import de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil; import de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAnnotationException; import de.tudarmstadt.ukp.clarin.webanno.brat.controller.ChainAdapter; import de.tudarmstadt.ukp.clarin.webanno.brat.controller.SpanAdapter; import de.tudarmstadt.ukp.clarin.webanno.brat.controller.TypeAdapter; import de.tudarmstadt.ukp.clarin.webanno.brat.controller.TypeUtil; import de.tudarmstadt.ukp.clarin.webanno.brat.display.model.VID; import de.tudarmstadt.ukp.clarin.webanno.brat.util.JavascriptUtils; import de.tudarmstadt.ukp.clarin.webanno.constraints.evaluator.Evaluator; import de.tudarmstadt.ukp.clarin.webanno.constraints.evaluator.PossibleValue; import de.tudarmstadt.ukp.clarin.webanno.constraints.evaluator.RulesIndicator; import de.tudarmstadt.ukp.clarin.webanno.constraints.evaluator.ValuesGenerator; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationDocumentState; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationFeature; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationLayer; import de.tudarmstadt.ukp.clarin.webanno.model.Mode; import de.tudarmstadt.ukp.clarin.webanno.model.MultiValueMode; import de.tudarmstadt.ukp.clarin.webanno.model.SourceDocumentState; import de.tudarmstadt.ukp.clarin.webanno.model.Tag; import de.tudarmstadt.ukp.clarin.webanno.model.TagSet; import de.tudarmstadt.ukp.clarin.webanno.support.DefaultFocusBehavior2; import de.tudarmstadt.ukp.clarin.webanno.support.DescriptionTooltipBehavior; import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.POS; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token; import de.tudarmstadt.ukp.dkpro.core.api.syntax.type.dependency.Dependency; /** * Annotation Detail Editor Panel. * */ public class AnnotationDetailEditorPanel extends Panel { private static final long serialVersionUID = 7324241992353693848L; private static final Log LOG = LogFactory.getLog(AnnotationDetailEditorPanel.class); @SpringBean(name = "documentRepository") private RepositoryService repository; @SpringBean(name = "annotationService") private AnnotationService annotationService; private AnnotationFeatureForm annotationFeatureForm; private Label selectedTextLabel; private CheckBox forwardAnnotationCheck; RefreshingView<FeatureModel> featureValues; private AjaxButton deleteButton; private AjaxButton reverseButton; private LayerSelector layer; private TextField<String> forwardAnnotationText; private Label selectedAnnotationLayer; private ModalWindow deleteModal; private List<AnnotationLayer> annotationLayers = new ArrayList<AnnotationLayer>(); private List<FeatureModel> featureModels; private BratAnnotatorModel bModel; private String selectedTag = ""; /** *Function to return tooltip using jquery *Docs for the JQuery tooltip widget that we configure below: *https://api.jqueryui.com/tooltip/ */ private final String functionForTooltip = "function() { return " + "'<div class=\"tooltip-title\">'+($(this).text() " + "? $(this).text() : 'no title')+'</div>" + "<div class=\"tooltip-content tooltip-pre\">'+($(this).attr('title') " + "? $(this).attr('title') : 'no description' )+'</div>' }"; public AnnotationDetailEditorPanel(String id, IModel<BratAnnotatorModel> aModel) { super(id, aModel); bModel = aModel.getObject(); annotationFeatureForm = new AnnotationFeatureForm("annotationFeatureForm", aModel.getObject()) { private static final long serialVersionUID = 8081614428845920047L; @Override protected void onConfigure() { super.onConfigure(); // Avoid reversing in read-only layers setEnabled(bModel.getDocument() != null && !isAnnotationFinished()); } }; annotationFeatureForm.setOutputMarkupId(true); annotationFeatureForm.add(new AjaxFormValidatingBehavior(annotationFeatureForm, "onsubmit") { private static final long serialVersionUID = -5642108496844056023L; @Override protected void onSubmit(AjaxRequestTarget aTarget) { try { actionAnnotate(aTarget, bModel, false); } catch (UIMAException | ClassNotFoundException | IOException | BratAnnotationException e) { error(e.getMessage()); } } }); add(annotationFeatureForm); } public boolean isAnnotationFinished() { if (bModel.getMode().equals(Mode.CURATION)) { return bModel.getDocument().getState().equals(SourceDocumentState.CURATION_FINISHED); } else { return repository.getAnnotationDocument(bModel.getDocument(), bModel.getUser()) .getState().equals(AnnotationDocumentState.FINISHED); } } private class AnnotationFeatureForm extends Form<BratAnnotatorModel> { private static final long serialVersionUID = 3635145598405490893L; private WebMarkupContainer featureEditorsContainer; public AnnotationFeatureForm(String id, BratAnnotatorModel aBModel) { super(id, new CompoundPropertyModel<BratAnnotatorModel>(aBModel)); featureModels = new ArrayList<>(); add(forwardAnnotationCheck = new CheckBox("forwardAnnotation") { private static final long serialVersionUID = 8908304272310098353L; @Override protected void onConfigure() { super.onConfigure(); setEnabled(isForwardable()); updateForwardAnnotation(bModel); } }); forwardAnnotationCheck.add(new AjaxFormComponentUpdatingBehavior("onchange") { private static final long serialVersionUID = 5179816588460867471L; @Override protected void onUpdate(AjaxRequestTarget aTarget) { updateForwardAnnotation(getModelObject()); if(bModel.isForwardAnnotation()){ aTarget.appendJavaScript(JavascriptUtils.getFocusScript(forwardAnnotationText)); selectedTag = ""; } } }); forwardAnnotationCheck.setOutputMarkupId(true); add(new Label("noAnnotationWarning", "No Annotation selected!"){ private static final long serialVersionUID = -6046409838139863541L; @Override protected void onConfigure() { super.onConfigure(); setVisible(!bModel.getSelection().getAnnotation().isSet()); } }); add(deleteButton = new AjaxButton("delete") { private static final long serialVersionUID = 1L; @Override protected void onConfigure() { super.onConfigure(); setVisible(bModel.getSelection().getAnnotation().isSet()); // Avoid deleting in read-only layers setEnabled(bModel.getSelectedAnnotationLayer() != null && !bModel.getSelectedAnnotationLayer().isReadonly()); } @Override public void onSubmit(AjaxRequestTarget aTarget, Form<?> aForm) { try { JCas jCas = getCas(bModel); AnnotationFS fs = selectByAddr(jCas, bModel.getSelection().getAnnotation().getId()); AnnotationLayer layer = bModel.getSelectedAnnotationLayer(); TypeAdapter adapter = getAdapter(annotationService, layer); if (adapter instanceof SpanAdapter && getAttachedRels(jCas, fs, layer).size() > 0) { deleteModal.setTitle("Are you sure you like to delete all attached relations to this span annotation?"); deleteModal.setContent(new DeleteOrReplaceAnnotationModalPanel( deleteModal.getContentId(), bModel, deleteModal, AnnotationDetailEditorPanel.this, bModel.getSelectedAnnotationLayer(), false)); deleteModal.show(aTarget); } else { actionDelete(aTarget, bModel); } } catch (UIMAException | ClassNotFoundException | IOException | CASRuntimeException | BratAnnotationException e) { error(e.getMessage()); } } }); add(reverseButton = new AjaxButton("reverse") { private static final long serialVersionUID = 1L; @Override protected void onConfigure() { super.onConfigure(); setVisible(bModel.getSelection().isRelationAnno() && bModel.getSelection().getAnnotation().isSet() && bModel.getSelectedAnnotationLayer().getType() .equals(WebAnnoConst.RELATION_TYPE)); // Avoid reversing in read-only layers setEnabled(bModel.getSelectedAnnotationLayer() != null && !bModel.getSelectedAnnotationLayer().isReadonly()); } @Override public void onSubmit(AjaxRequestTarget aTarget, Form<?> aForm) { aTarget.addChildren(getPage(), FeedbackPanel.class); try { actionReverse(aTarget, bModel); } catch (BratAnnotationException e) { aTarget.prependJavaScript("alert('" + e.getMessage() + "')"); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } catch (UIMAException e) { error(ExceptionUtils.getRootCauseMessage(e)); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } catch (Exception e) { error(e.getMessage()); LOG.error(e.getMessage(), e); } } }); reverseButton.setOutputMarkupPlaceholderTag(true); add(new AjaxButton("clear") { private static final long serialVersionUID = 1L; @Override protected void onConfigure() { super.onConfigure(); setVisible(bModel.getSelection().getAnnotation().isSet()); } @Override public void onSubmit(AjaxRequestTarget aTarget, Form<?> aForm) { aTarget.addChildren(getPage(), FeedbackPanel.class); try { actionClear(aTarget, bModel); } catch (UIMAException e) { error(ExceptionUtils.getRootCauseMessage(e)); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } catch (Exception e) { error(e.getMessage()); LOG.error(e.getMessage(), e); } } }); add(layer = new LayerSelector("defaultAnnotationLayer", annotationLayers)); featureValues = new FeatureEditorPanelContent( "featureValues"); featureEditorsContainer = new WebMarkupContainer("featureEditorsContainer") { private static final long serialVersionUID = 8908304272310098353L; @Override protected void onConfigure() { super.onConfigure(); setVisible(!featureModels.isEmpty() && bModel.getSelection().getAnnotation().isSet()); } }; // Add placeholder since wmc might start out invisible. Without the placeholder we // cannot make it visible in an AJAX call featureEditorsContainer.setOutputMarkupPlaceholderTag(true); featureEditorsContainer.setOutputMarkupId(true); forwardAnnotationText = new TextField<String>("forwardAnno"); forwardAnnotationText.setOutputMarkupId(true); forwardAnnotationText.add(new AjaxFormComponentUpdatingBehavior("onkeyup") { private static final long serialVersionUID = 4554834769861958396L; @Override protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { super.updateAjaxAttributes(attributes); IAjaxCallListener listener = new AjaxCallListener(){ private static final long serialVersionUID = -7968540662654079601L; @Override public CharSequence getPrecondition(Component component) { return "var keycode = Wicket.Event.keyCode(attrs.event);" + " return true;" ; } }; attributes.getAjaxCallListeners().add(listener); attributes.getDynamicExtraParameters() .add("var eventKeycode = Wicket.Event.keyCode(attrs.event);" + "return {keycode: eventKeycode};"); attributes.setAllowDefault(true); } @Override protected void onUpdate(AjaxRequestTarget aTarget) { final Request request = RequestCycle.get().getRequest(); final String jsKeycode = request.getRequestParameters() .getParameterValue("keycode").toString(""); if (jsKeycode.equals("32")){ try { actionAnnotate(aTarget, aBModel, false); selectedTag =""; } catch (UIMAException | ClassNotFoundException | IOException | BratAnnotationException e) { error(e); } return; } if (jsKeycode.equals("13")){ selectedTag =""; return; } selectedTag = (forwardAnnotationText.getModelObject() == null ? "" : forwardAnnotationText.getModelObject().charAt(0)) + selectedTag; featureModels.get(0).value = getKeyBindValue(selectedTag, getBindTags()); aTarget.add(forwardAnnotationText); aTarget.add(featureValues.get(0)); } }); forwardAnnotationText.setOutputMarkupId(true); forwardAnnotationText.add(new AttributeAppender("style", "opacity:0", ";")); // forwardAnno.add(new AttributeAppender("style", "filter:alpha(opacity=0)", ";")); featureEditorsContainer.add(forwardAnnotationText); featureEditorsContainer.add(featureValues); // the selected text for annotationa selectedTextLabel = new Label("selectedText", PropertyModel.of(getModelObject(), "selection.text")); selectedTextLabel.setOutputMarkupId(true); featureEditorsContainer.add(selectedTextLabel); featureEditorsContainer.add(new Label("layerName","Layer"){ private static final long serialVersionUID = 6084341323607243784L; @Override protected void onConfigure() { super.onConfigure(); setVisible(bModel.getPreferences().isBrushMode()); } }); featureEditorsContainer.setOutputMarkupId(true); // the annotation layer for the selected annotation selectedAnnotationLayer = new Label("selectedAnnotationLayer", new Model<String>()) { private static final long serialVersionUID = 4059460390544343324L; @Override protected void onConfigure() { super.onConfigure(); setVisible(bModel.getPreferences().isBrushMode()); } }; selectedAnnotationLayer.setOutputMarkupId(true); featureEditorsContainer.add(selectedAnnotationLayer); add(featureEditorsContainer); add(deleteModal = new ModalWindow("yesNoModal")); deleteModal.setOutputMarkupId(true); deleteModal.setInitialWidth(600); deleteModal.setInitialHeight(50); deleteModal.setResizable(true); deleteModal.setWidthUnit("px"); deleteModal.setHeightUnit("px"); deleteModal.setTitle("Are you sure you want to delete the existing annotation?"); } } public void actionAnnotate(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel, boolean aIsForwarded) throws UIMAException, ClassNotFoundException, IOException, BratAnnotationException { if (isAnnotationFinished()) { throw new BratAnnotationException( "This document is already closed. Please ask your project manager to re-open it via the Monitoring page"); } // If there is no annotation yet, create one. During creation, the adapter // may notice that it would create a duplicate and return the address of // an existing annotation instead of a new one. JCas jCas = getCas(aBModel); actionAnnotate(aTarget, aBModel, jCas, aIsForwarded); } public void actionAnnotate(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel, JCas jCas, boolean aIsForwarded) throws UIMAException, ClassNotFoundException, IOException, BratAnnotationException { if (aBModel.getSelectedAnnotationLayer() == null) { error("No layer is selected. First select a layer."); aTarget.addChildren(getPage(), FeedbackPanel.class); return; } if (aBModel.getSelectedAnnotationLayer().isReadonly()) { error("Layer is not editable."); aTarget.addChildren(getPage(), FeedbackPanel.class); return; } // Verify if input is valid according to tagset for (int i = 0; i < featureModels.size(); i++) { AnnotationFeature feature = featureModels.get(i).feature; if (CAS.TYPE_NAME_STRING.equals(feature.getType())) { String value = (String) featureModels.get(i).value; // Check if tag is necessary, set, and correct if ( value != null && feature.getTagset() != null && !feature.getTagset().isCreateTag() && !annotationService.existsTag(value, feature.getTagset()) ) { error("[" + value + "] is not in the tag list. Please choose from the existing tags"); return; } } } aTarget.add(annotationFeatureForm); TypeAdapter adapter = getAdapter(annotationService, aBModel.getSelectedAnnotationLayer()); Selection selection = aBModel.getSelection(); if (selection.getAnnotation().isNotSet()) { if (bModel.getSelection().isRelationAnno()) { AnnotationFS originFs = selectByAddr(jCas, selection.getOrigin()); AnnotationFS targetFs = selectByAddr(jCas, selection.getTarget()); if (adapter instanceof SpanAdapter) { error("Layer do not support arc annotation."); aTarget.addChildren(getPage(), FeedbackPanel.class); return; } if (adapter instanceof ArcAdapter) { Sentence sentence = selectSentenceAt(jCas, bModel.getSentenceBeginOffset(), bModel.getSentenceEndOffset()); int start = sentence.getBegin(); int end = selectByAddr(jCas, Sentence.class, getLastSentenceAddressInDisplayWindow(jCas, getAddr(sentence), bModel.getPreferences().getWindowSize())).getEnd(); AnnotationFS arc = ((ArcAdapter) adapter).add(originFs, targetFs, jCas, start, end, null, null); selection.setAnnotation(new VID(getAddr(arc))); } else { selection.setAnnotation( new VID(((ChainAdapter) adapter).addArc(jCas, originFs, targetFs, null, null))); } selection.setBegin(originFs.getBegin()); } else if (adapter instanceof SpanAdapter) { for (FeatureModel fm : featureModels) { Serializable spanValue = ((SpanAdapter) adapter).getSpan(jCas, selection.getBegin(), selection.getEnd(), fm.feature, null); if (spanValue != null) { // allow modification for forward annotation if (aBModel.isForwardAnnotation()) { fm.value = spanValue; featureModels.get(0).value = spanValue; selectedTag = getBindTags().entrySet().stream().filter(e -> e.getValue().equals(spanValue)) .map(Map.Entry::getKey).findFirst().orElse(null); } else { actionClear(aTarget, bModel); throw new BratAnnotationException("Cannot create another annotation of layer [" + "" + bModel.getSelectedAnnotationLayer().getUiName() + " ] at this" + " location - stacking is not enabled for this layer."); } } } Integer annoId = ((SpanAdapter) adapter).add(jCas, selection.getBegin(), selection.getEnd(), null, null); selection.setAnnotation(new VID(annoId)); AnnotationFS annoFs = BratAjaxCasUtil.selectByAddr(jCas, annoId); selection.set(jCas, annoFs.getBegin(), annoFs.getEnd()); } else { for (FeatureModel fm : featureModels) { Serializable spanValue = ((ChainAdapter) adapter).getSpan(jCas, selection.getBegin(), selection.getEnd(), fm.feature, null); if (spanValue != null) { // allow modification for forward annotation if (aBModel.isForwardAnnotation()) { fm.value = spanValue; featureModels.get(0).value = spanValue; selectedTag = getBindTags().entrySet().stream().filter(e -> e.getValue().equals(spanValue)) .map(Map.Entry::getKey).findFirst().orElse(null); } } } selection.setAnnotation(new VID( ((ChainAdapter) adapter).addSpan(jCas, selection.getBegin(), selection.getEnd(), null, null))); } } // Set feature values List<AnnotationFeature> features = new ArrayList<AnnotationFeature>(); for (FeatureModel fm : featureModels) { features.add(fm.feature); // For string features with extensible tagsets, extend the tagset if (CAS.TYPE_NAME_STRING.equals(fm.feature.getType())) { String value = (String) fm.value; if ( value != null && fm.feature.getTagset() != null && fm.feature.getTagset().isCreateTag() && !annotationService.existsTag(value, fm.feature.getTagset()) ) { Tag selectedTag = new Tag(); selectedTag.setName(value); selectedTag.setTagSet(fm.feature.getTagset()); annotationService.createTag(selectedTag, aBModel.getUser()); } } adapter.updateFeature(jCas, fm.feature, aBModel.getSelection().getAnnotation().getId(), fm.value); } // Update progress information int sentenceNumber = getSentenceNumber(jCas, aBModel.getSelection().getBegin()); aBModel.setSentenceNumber(sentenceNumber); aBModel.getDocument().setSentenceAccessed(sentenceNumber); // persist changes repository.writeCas(aBModel.getMode(), aBModel.getDocument(), aBModel.getUser(), jCas); if (bModel.getSelection().isRelationAnno()) { aBModel.setRememberedArcLayer(aBModel.getSelectedAnnotationLayer()); aBModel.setRememberedArcFeatures(featureModels); } else { aBModel.setRememberedSpanLayer(aBModel.getSelectedAnnotationLayer()); aBModel.setRememberedSpanFeatures(featureModels); } aBModel.getSelection().setAnnotate(true); if (aBModel.getSelection().getAnnotation().isSet()) { String bratLabelText = TypeUtil.getBratLabelText(adapter, selectByAddr(jCas, aBModel.getSelection().getAnnotation().getId()), features); info(generateMessage(aBModel.getSelectedAnnotationLayer(), bratLabelText, false)); } onAnnotate(aTarget, aBModel); if (aBModel.isForwardAnnotation() && !aIsForwarded && featureModels.get(0).value != null) { if (aBModel.getSelection().getEnd() >= aBModel.getSentenceEndOffset()) { autoForwardScroll(jCas, aBModel); } onAutoForward(aTarget, aBModel); } else if (aBModel.getPreferences().isScrollPage()) { autoScroll(jCas, aBModel); } forwardAnnotationText.setModelObject(null); onChange(aTarget, aBModel); if (aBModel.isForwardAnnotation() && featureModels.get(0).value != null) { reload(aTarget); } } public void actionDelete(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel) throws IOException, UIMAException, ClassNotFoundException, CASRuntimeException, BratAnnotationException { JCas jCas = getCas(aBModel); AnnotationFS fs = selectByAddr(jCas, aBModel.getSelection().getAnnotation().getId()); // TODO We assume here that the selected annotation layer corresponds to the type of the // FS to be deleted. It would be more robust if we could get the layer from the FS itself. AnnotationLayer layer = aBModel.getSelectedAnnotationLayer(); TypeAdapter adapter = getAdapter(annotationService, layer); // == DELETE ATTACHED RELATIONS == // If the deleted FS is a span, we must delete all relations that // point to it directly or indirectly via the attachFeature. // // NOTE: It is important that this happens before UNATTACH SPANS since the attach feature // is no longer set after UNATTACH SPANS! if (adapter instanceof SpanAdapter) { for (AnnotationFS attachedFs : getAttachedRels(jCas, fs, layer)) { jCas.getCas().removeFsFromIndexes(attachedFs); info("The attached annotation for relation type [" + annotationService .getLayer(attachedFs.getType().getName(), bModel.getProject()).getUiName() + "] is deleted"); } } // == DELETE ATTACHED SPANS == // This case is currently not implemented because WebAnno currently does not allow to // create spans that attach to other spans. The only span type for which this is relevant // is the Token type which cannot be deleted. // == UNATTACH SPANS == // If the deleted FS is a span that is attached to another span, the // attachFeature in the other span must be set to null. Typical example: POS is deleted, so // the pos feature of Token must be set to null. This is a quick case, because we only need // to look at span annotations that have the same offsets as the FS to be deleted. if (adapter instanceof SpanAdapter && layer.getAttachType() != null) { Type spanType = CasUtil.getType(jCas.getCas(), layer.getAttachType().getName()); Feature attachFeature = spanType.getFeatureByBaseName(layer.getAttachFeature() .getName()); for (AnnotationFS attachedFs : selectAt(jCas.getCas(), spanType, fs.getBegin(), fs.getEnd())) { if (isSame(attachedFs.getFeatureValue(attachFeature), fs)) { attachedFs.setFeatureValue(attachFeature, null); LOG.debug("Unattached [" + attachFeature.getShortName() + "] on annotation [" + getAddr(attachedFs) + "]"); } } } // == CLEAN UP LINK FEATURES == // If the deleted FS is a span that is the target of a link feature, we must unset that // link and delete the slot if it is a multi-valued link. Here, we have to scan all // annotations from layers that have link features that could point to the FS // to be deleted: the link feature must be the type of the FS or it must be generic. if (adapter instanceof SpanAdapter) { for (AnnotationFeature linkFeature : annotationService.listAttachedLinkFeatures(layer)) { Type linkType = CasUtil.getType(jCas.getCas(), linkFeature.getLayer().getName()); for (AnnotationFS linkFS : CasUtil.select(jCas.getCas(), linkType)) { List<LinkWithRoleModel> links = getFeature(linkFS, linkFeature); Iterator<LinkWithRoleModel> i = links.iterator(); boolean modified = false; while (i.hasNext()) { LinkWithRoleModel link = i.next(); if (link.targetAddr == getAddr(fs)) { i.remove(); LOG.debug("Cleared slot [" + link.role + "] in feature [" + linkFeature.getName() + "] on annotation [" + getAddr(linkFS) + "]"); modified = true; } } if (modified) { setFeature(linkFS, linkFeature, links); } } } } // If the deleted FS is a relation, we don't have to do anything. Nothing can point to a // relation. if (adapter instanceof ArcAdapter) { // Do nothing ;) } // Actually delete annotation adapter.delete(jCas, aBModel.getSelection().getAnnotation()); // Store CAS again repository.writeCas(aBModel.getMode(), aBModel.getDocument(), aBModel.getUser(), jCas); // Update progress information int sentenceNumber = getSentenceNumber(jCas, aBModel.getSelection().getBegin()); aBModel.setSentenceNumber(sentenceNumber); aBModel.getDocument().setSentenceAccessed(sentenceNumber); // Auto-scroll if (aBModel.getPreferences().isScrollPage()) { autoScroll(jCas, aBModel); } aBModel.setRememberedSpanLayer(aBModel.getSelectedAnnotationLayer()); aBModel.getSelection().setAnnotate(false); info(generateMessage(aBModel.getSelectedAnnotationLayer(), null, true)); // A hack to remember the visual DropDown display value aBModel.setRememberedSpanLayer(aBModel.getSelectedAnnotationLayer()); aBModel.setRememberedSpanFeatures(featureModels); aBModel.getSelection().clear(); // after delete will follow annotation bModel.getSelection().setAnnotate(true); aTarget.add(annotationFeatureForm); aTarget.add(deleteButton); aTarget.add(reverseButton); onChange(aTarget, aBModel); onDelete(aTarget, aBModel, fs); } private void actionReverse(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel) throws IOException, UIMAException, ClassNotFoundException, BratAnnotationException { JCas jCas; jCas = getCas(aBModel); AnnotationFS idFs = selectByAddr(jCas, aBModel.getSelection().getAnnotation().getId()); jCas.removeFsFromIndexes(idFs); AnnotationFS originFs = selectByAddr(jCas, aBModel.getSelection().getOrigin()); AnnotationFS targetFs = selectByAddr(jCas, aBModel.getSelection().getTarget()); TypeAdapter adapter = getAdapter(annotationService, aBModel.getSelectedAnnotationLayer()); Sentence sentence = selectSentenceAt(jCas, bModel.getSentenceBeginOffset(), bModel.getSentenceEndOffset()); int start = sentence.getBegin(); int end = selectByAddr(jCas, Sentence.class, getLastSentenceAddressInDisplayWindow(jCas, getAddr(sentence), bModel.getPreferences().getWindowSize())) .getEnd(); if (adapter instanceof ArcAdapter) { if(featureModels.size()==0){ //If no features, still create arc #256 AnnotationFS arc = ((ArcAdapter) adapter).add(targetFs, originFs, jCas, start, end, null, null); aBModel.getSelection().setAnnotation(new VID(getAddr(arc))); } else{ for (FeatureModel fm : featureModels) { AnnotationFS arc = ((ArcAdapter) adapter).add(targetFs, originFs, jCas, start, end, fm.feature, fm.value); aBModel.getSelection().setAnnotation(new VID(getAddr(arc))); } } } else { error("chains cannot be reversed"); return; } // persist changes repository.writeCas(aBModel.getMode(), aBModel.getDocument(), aBModel.getUser(), jCas); int sentenceNumber = getSentenceNumber(jCas, originFs.getBegin()); aBModel.setSentenceNumber(sentenceNumber); aBModel.getDocument().setSentenceAccessed(sentenceNumber); if (aBModel.getPreferences().isScrollPage()) { autoScroll(jCas, aBModel); } info("The arc has been reversed"); aBModel.setRememberedArcLayer(aBModel.getSelectedAnnotationLayer()); aBModel.setRememberedArcFeatures(featureModels); // in case the user re-reverse it int temp = aBModel.getSelection().getOrigin(); aBModel.getSelection().setOrigin(aBModel.getSelection().getTarget()); aBModel.getSelection().setTarget(temp); onChange(aTarget, aBModel); } public void actionClear(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel) throws IOException, UIMAException, ClassNotFoundException, BratAnnotationException { aBModel.getSelection().clear(); aTarget.add(annotationFeatureForm); onChange(aTarget, aBModel); } public JCas getCas(BratAnnotatorModel aBModel) throws UIMAException, IOException, ClassNotFoundException { if (aBModel.getMode().equals(Mode.ANNOTATION) || aBModel.getMode().equals(Mode.AUTOMATION) || aBModel.getMode().equals(Mode.CORRECTION) || aBModel.getMode().equals(Mode.CORRECTION_MERGE)) { return repository.readAnnotationCas(aBModel.getDocument(), aBModel.getUser()); } else { return repository.readCurationCas(aBModel.getDocument()); } } private void autoScroll(JCas jCas, BratAnnotatorModel aBModel) { int address = getAddr(selectSentenceAt(jCas, aBModel.getSentenceBeginOffset(), aBModel.getSentenceEndOffset())); aBModel.setSentenceAddress(getSentenceBeginAddress(jCas, address, aBModel.getSelection() .getBegin(), aBModel.getProject(), aBModel.getDocument(), aBModel.getPreferences() .getWindowSize())); Sentence sentence = selectByAddr(jCas, Sentence.class, aBModel.getSentenceAddress()); aBModel.setSentenceBeginOffset(sentence.getBegin()); aBModel.setSentenceEndOffset(sentence.getEnd()); Sentence firstSentence = selectSentenceAt(jCas, aBModel.getSentenceBeginOffset(), aBModel.getSentenceEndOffset()); int lastAddressInPage = getLastSentenceAddressInDisplayWindow(jCas, getAddr(firstSentence), aBModel.getPreferences().getWindowSize()); // the last sentence address in the display window Sentence lastSentenceInPage = (Sentence) selectByAddr(jCas, FeatureStructure.class, lastAddressInPage); aBModel.setFSN(BratAjaxCasUtil.getSentenceNumber(jCas, firstSentence.getBegin())); aBModel.setLSN(BratAjaxCasUtil.getSentenceNumber(jCas, lastSentenceInPage.getBegin())); } private void autoForwardScroll(JCas jCas, BratAnnotatorModel aBModel) { int address = getNextSentenceAddress(jCas, selectByAddr(jCas, Sentence.class, aBModel.getSentenceAddress())); aBModel.setSentenceAddress(address); Sentence sentence = selectByAddr(jCas, Sentence.class, aBModel.getSentenceAddress()); aBModel.setSentenceBeginOffset(sentence.getBegin()); aBModel.setSentenceEndOffset(sentence.getEnd()); Sentence firstSentence = selectSentenceAt(jCas, aBModel.getSentenceBeginOffset(), aBModel.getSentenceEndOffset()); int lastAddressInPage = getLastSentenceAddressInDisplayWindow(jCas, getAddr(firstSentence), aBModel.getPreferences().getWindowSize()); // the last sentence address in the display window Sentence lastSentenceInPage = (Sentence) selectByAddr(jCas, FeatureStructure.class, lastAddressInPage); aBModel.setFSN(BratAjaxCasUtil.getSentenceNumber(jCas, firstSentence.getBegin())); aBModel.setLSN(BratAjaxCasUtil.getSentenceNumber(jCas, lastSentenceInPage.getBegin())); } @SuppressWarnings("unchecked") public void setSlot(AjaxRequestTarget aTarget, JCas aJCas, final BratAnnotatorModel aBModel, int aAnnotationId) { // Set an armed slot if (!bModel.getSelection().isRelationAnno() && aBModel.isSlotArmed()) { List<LinkWithRoleModel> links = (List<LinkWithRoleModel>) getFeatureModel(aBModel .getArmedFeature()).value; LinkWithRoleModel link = links.get(aBModel.getArmedSlot()); link.targetAddr = aAnnotationId; link.label = selectByAddr(aJCas, aAnnotationId).getCoveredText(); aBModel.clearArmedSlot(); } // Auto-commit if working on existing annotation if (bModel.getSelection().getAnnotation().isSet()) { try { actionAnnotate(aTarget, bModel, aJCas, false); } catch (BratAnnotationException e) { error(e.getMessage()); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } catch (Exception e) { error(ExceptionUtils.getRootCauseMessage(e)); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } } } private void setLayerAndFeatureModels(AjaxRequestTarget aTarget, JCas aJCas, final BratAnnotatorModel aBModel) throws BratAnnotationException { if (aBModel.getSelection().isRelationAnno()) { long layerId = TypeUtil.getLayerId(aBModel.getSelection().getOriginType()); AnnotationLayer spanLayer = annotationService.getLayer(layerId); if (aBModel.getPreferences().isBrushMode() && !aBModel.getDefaultAnnotationLayer().equals(spanLayer)) { throw new BratAnnotationException("No relation annotation allowed on the " + "selected span layer"); } // If we drag an arc between POS annotations, then the relation must be a dependency // relation. // FIXME - Actually this case should be covered by the last case - the database lookup! if (spanLayer.isBuiltIn() && spanLayer.getName().equals(POS.class.getName())) { AnnotationLayer depLayer = annotationService.getLayer(Dependency.class.getName(), aBModel.getProject()); if (aBModel.getAnnotationLayers().contains(depLayer)) { aBModel.setSelectedAnnotationLayer(depLayer); } else { aBModel.setSelectedAnnotationLayer(null); } } // If we drag an arc in a chain layer, then the arc is of the same layer as the span // Chain layers consist of arcs and spans else if (spanLayer.getType().equals(WebAnnoConst.CHAIN_TYPE)) { // one layer both for the span and arc annotation aBModel.setSelectedAnnotationLayer(spanLayer); } // Otherwise, look up the possible relation layer(s) in the database. else { for (AnnotationLayer layer : annotationService.listAnnotationLayer(aBModel .getProject())) { if (layer.getAttachType() != null && layer.getAttachType().equals(spanLayer)) { if (aBModel.getAnnotationLayers().contains(layer)) { aBModel.setSelectedAnnotationLayer(layer); } else { aBModel.setSelectedAnnotationLayer(null); } break; } } } // populate feature value if (aBModel.getSelection().getAnnotation().isSet()) { AnnotationFS annoFs = selectByAddr(aJCas, aBModel.getSelection().getAnnotation() .getId()); populateFeatures(annoFs); } // Avoid creation of arcs on locked layers else if (aBModel.getSelectedAnnotationLayer() != null && aBModel.getSelectedAnnotationLayer().isReadonly()) { aBModel.setSelectedAnnotationLayer(new AnnotationLayer()); } aBModel.setDefaultAnnotationLayer(spanLayer); } else if (aBModel.getSelection().getAnnotation().isSet()) { AnnotationFS annoFs = selectByAddr(aJCas, aBModel.getSelection().getAnnotation() .getId()); String type = annoFs.getType().getName(); // Might have been reset if we didn't find the layer above. Btw. this can happen if // somebody imports a CAS that has subtypes of layers, e.g. DKPro Core pipelines // like to produce subtypes of POS for individual postags. We do not support such // "elevated types" in WebAnno at this time. if (aBModel.getSelection().getAnnotation().isSet()) { if (type.endsWith(ChainAdapter.CHAIN)) { type = type.substring(0, type.length() - ChainAdapter.CHAIN.length()); } else if (type.endsWith(ChainAdapter.LINK)) { type = type.substring(0, type.length() - ChainAdapter.LINK.length()); } try { aBModel.setSelectedAnnotationLayer(annotationService.getLayer(type, aBModel.getProject())); } catch (NoResultException e) { reset(aTarget); throw new IllegalStateException("Unknown layer [" + type + "]", e); } // populate feature value for (AnnotationFeature feature : annotationService .listAnnotationFeature(aBModel.getSelectedAnnotationLayer())) { if (!feature.isEnabled()) { continue; } if (WebAnnoConst.CHAIN_TYPE.equals(feature.getLayer().getType())) { if (WebAnnoConst.COREFERENCE_TYPE_FEATURE.equals(feature.getName())) { featureModels.add(new FeatureModel(feature, (Serializable) BratAjaxCasUtil.getFeature(annoFs, feature))); } } else { featureModels.add(new FeatureModel(feature, (Serializable) BratAjaxCasUtil.getFeature(annoFs, feature))); } } } } } protected void onChange(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel) { // Overriden in BratAnnotator } protected void onAutoForward(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel) { // Overriden in BratAnnotator } public void onAnnotate(AjaxRequestTarget aTarget, BratAnnotatorModel aModel) { // Overriden in AutomationPage } public void onDelete(AjaxRequestTarget aTarget, BratAnnotatorModel aModel, AnnotationFS aFs) { // Overriden in AutomationPage } public void setAnnotationLayers(BratAnnotatorModel aBModel) { setInitSpanLayers(aBModel); if (annotationLayers.size() == 0) { aBModel.setSelectedAnnotationLayer(new AnnotationLayer()); } else if (aBModel.getSelectedAnnotationLayer() == null) { if (aBModel.getRememberedSpanLayer() == null) { aBModel.setSelectedAnnotationLayer(annotationLayers.get(0)); } else { aBModel.setSelectedAnnotationLayer(aBModel.getRememberedSpanLayer()); } } populateFeatures(null); updateBrushMode(); } private void setInitSpanLayers(BratAnnotatorModel aBModel) { annotationLayers.clear(); AnnotationLayer l = null; for (AnnotationLayer layer : aBModel.getAnnotationLayers()) { if (!layer.isEnabled() || layer.isReadonly() || layer.getName().equals(Token.class.getName())) { continue; } if (layer.getType().equals(WebAnnoConst.SPAN_TYPE)) { annotationLayers.add(layer); l = layer; } // manage chain type else if (layer.getType().equals(WebAnnoConst.CHAIN_TYPE)) { for (AnnotationFeature feature : annotationService.listAnnotationFeature(layer)) { if (!feature.isEnabled()) { continue; } if (feature.getName().equals(WebAnnoConst.COREFERENCE_TYPE_FEATURE)) { annotationLayers.add(layer); } } } // chain } if (bModel.getDefaultAnnotationLayer() != null) { bModel.setSelectedAnnotationLayer(bModel.getDefaultAnnotationLayer()); } else if (l != null) { bModel.setSelectedAnnotationLayer(l); } } public class FeatureEditorPanelContent extends RefreshingView<FeatureModel> { private static final long serialVersionUID = -8359786805333207043L; public FeatureEditorPanelContent(String aId) { super(aId); setOutputMarkupId(true); } @SuppressWarnings("rawtypes") @Override protected void populateItem(final Item<FeatureModel> item) { // Feature editors that allow multiple values may want to update themselves, // e.g. to add another slot. item.setOutputMarkupId(true); final FeatureModel fm = item.getModelObject(); final FeatureEditor frag; switch (fm.feature.getMultiValueMode()) { case NONE: { switch (fm.feature.getType()) { case CAS.TYPE_NAME_INTEGER: { frag = new NumberFeatureEditor("editor", "numberFeatureEditor", item, fm); break; } case CAS.TYPE_NAME_FLOAT: { frag = new NumberFeatureEditor("editor", "numberFeatureEditor", item, fm); break; } case CAS.TYPE_NAME_BOOLEAN: { frag = new BooleanFeatureEditor("editor", "booleanFeatureEditor", item, fm); break; } case CAS.TYPE_NAME_STRING: { frag = new TextFeatureEditor("editor", "textFeatureEditor", item, fm); break; } default: throw new IllegalArgumentException("Unsupported type [" + fm.feature.getType() + "] on feature [" + fm.feature.getName() + "]"); } break; } case ARRAY: { switch (fm.feature.getLinkMode()) { case WITH_ROLE: { // If it is none of the primitive types, it must be a link feature frag = new LinkFeatureEditor("editor", "linkFeatureEditor", item, fm); break; } default: throw new IllegalArgumentException("Unsupported link mode [" + fm.feature.getLinkMode() + "] on feature [" + fm.feature.getName() + "]"); } break; } default: throw new IllegalArgumentException("Unsupported multi-value mode [" + fm.feature.getMultiValueMode() + "] on feature [" + fm.feature.getName() + "]"); } item.add(frag); if (bModel.isForwardAnnotation()) { forwardAnnotationText.add(new DefaultFocusBehavior2()); } else { // Disabled for Github Issue #243 // Put focus on first feature // if (item.getIndex() == item.size() - 1) { // frag.getFocusComponent().add(new DefaultFocusBehavior()); // } } if (!fm.feature.getLayer().isReadonly()) { // whenever it is updating an annotation, it updates automatically when a component // for the feature lost focus - but updating is for every component edited // LinkFeatureEditors must be excluded because the auto-update will break the // ability to add slots. Adding a slot is NOT an annotation action. // TODO annotate every time except when position is at (0,0) if (bModel.getSelection().getAnnotation().isSet() && !(frag instanceof LinkFeatureEditor)) { if (frag.isDropOrchoice()) { addAnnotateActionBehavior(frag, "onchange"); } else { addAnnotateActionBehavior(frag, "onblur"); } } else if (!(frag instanceof LinkFeatureEditor)) { if (frag.isDropOrchoice()) { storeFeatureValue(frag, "onchange"); } else { storeFeatureValue(frag, "onblur"); } } /* * if (item.getIndex() == 0) { // Put focus on first feature * frag.getFocusComponent().add(new DefaultFocusBehavior()); } */ // Add tooltip on label StringBuilder tooltipTitle = new StringBuilder(); tooltipTitle.append(fm.feature.getUiName()); if (fm.feature.getTagset() != null) { tooltipTitle.append(" ("); tooltipTitle.append(fm.feature.getTagset().getName()); tooltipTitle.append(')'); } Component labelComponent = frag.getLabelComponent(); labelComponent.add(new AttributeAppender("style", "cursor: help", ";")); labelComponent.add(new DescriptionTooltipBehavior(tooltipTitle.toString(), fm.feature.getDescription())); } else { frag.getFocusComponent().setEnabled(false); } } private void storeFeatureValue(final FeatureEditor aFrag, String aEvent) { aFrag.getFocusComponent().add(new AjaxFormComponentUpdatingBehavior(aEvent) { private static final long serialVersionUID = 5179816588460867471L; @Override protected void onUpdate(AjaxRequestTarget aTarget) { aTarget.add(annotationFeatureForm); } }); } private void addAnnotateActionBehavior(final FeatureEditor aFrag, String aEvent) { aFrag.getFocusComponent().add(new AjaxFormComponentUpdatingBehavior(aEvent) { private static final long serialVersionUID = 5179816588460867471L; @Override protected void onUpdate(AjaxRequestTarget aTarget) { try { if (bModel.getConstraints() != null) { // Make sure we update the feature editor panel because due to // constraints the contents may have to be re-rendered aTarget.add(annotationFeatureForm); } actionAnnotate(aTarget, bModel, false); } catch (BratAnnotationException e) { error(ExceptionUtils.getRootCauseMessage(e)); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } catch (Exception e) { error(ExceptionUtils.getRootCauseMessage(e)); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } } }); } @Override protected Iterator<IModel<FeatureModel>> getItemModels() { ModelIteratorAdapter<FeatureModel> i = new ModelIteratorAdapter<FeatureModel>( featureModels) { @Override protected IModel<FeatureModel> model(FeatureModel aObject) { return Model.of(aObject); } }; return i; } } public static abstract class FeatureEditor extends Fragment { private static final long serialVersionUID = -7275181609671919722L; public FeatureEditor(String aId, String aMarkupId, MarkupContainer aMarkupProvider, IModel<?> aModel) { super(aId, aMarkupId, aMarkupProvider, aModel); } public Component getLabelComponent() { return get("feature"); } abstract public Component getFocusComponent(); abstract public boolean isDropOrchoice(); } public static class NumberFeatureEditor<T extends Number> extends FeatureEditor { private static final long serialVersionUID = -2426303638953208057L; @SuppressWarnings("rawtypes") private final NumberTextField field; public NumberFeatureEditor(String aId, String aMarkupId, MarkupContainer aMarkupProvider, FeatureModel aModel) { super(aId, aMarkupId, aMarkupProvider, new CompoundPropertyModel<FeatureModel>(aModel)); add(new Label("feature", aModel.feature.getUiName())); switch (aModel.feature.getType()) { case CAS.TYPE_NAME_INTEGER: { field = new NumberTextField<Integer>("value", Integer.class); add(field); break; } case CAS.TYPE_NAME_FLOAT: { field = new NumberTextField<Float>("value", Float.class); add(field); break; } default: throw new IllegalArgumentException("Type [" + aModel.feature.getType() + "] cannot be rendered as a numeric input field"); } } @SuppressWarnings("rawtypes") @Override public NumberTextField getFocusComponent() { return field; } @Override public boolean isDropOrchoice() { return false; } }; public static class BooleanFeatureEditor extends FeatureEditor { private static final long serialVersionUID = 5104979547245171152L; private final CheckBox field; public BooleanFeatureEditor(String aId, String aMarkupId, MarkupContainer aMarkupProvider, FeatureModel aModel) { super(aId, aMarkupId, aMarkupProvider, new CompoundPropertyModel<FeatureModel>(aModel)); add(new Label("feature", aModel.feature.getUiName())); field = new CheckBox("value"); add(field); } @Override public Component getFocusComponent() { return field; } @Override public boolean isDropOrchoice() { return true; } }; public class TextFeatureEditor extends FeatureEditor { private static final long serialVersionUID = 7763348613632105600L; @SuppressWarnings("rawtypes") private final AbstractTextComponent field; private boolean isDrop; //For showing the status of Constraints rules kicking in. private RulesIndicator indicator = new RulesIndicator(); private boolean hideUnconstraintFeature; /** * Hides feature if "Hide un-constraint feature" is enabled * and constraint rules are applied and feature doesn't match any constraint rule */ @Override public boolean isVisible() { if (hideUnconstraintFeature) { //if enabled and constraints rule execution returns anything other than green if (indicator.isAffected() && !indicator.getStatusColor().equals("green")) { return false; } } return true; } public TextFeatureEditor(String aId, String aMarkupId, MarkupContainer aMarkupProvider, FeatureModel aModel) { super(aId, aMarkupId, aMarkupProvider, new CompoundPropertyModel<FeatureModel>(aModel)); //Checks whether hide un-constraint feature is enabled or not hideUnconstraintFeature = aModel.feature.isHideUnconstraintFeature(); add(new Label("feature", aModel.feature.getUiName())); indicator.reset(); //reset the indicator if (aModel.feature.getTagset() != null) { List<Tag> tagset = null; BratAnnotatorModel model = bModel; // verification to check whether constraints exist for this project or NOT if (model.getConstraints() != null && model.getSelection().getAnnotation().isSet()) { // indicator.setRulesExist(true); tagset = populateTagsBasedOnRules(model, aModel); } else { // indicator.setRulesExist(false); // Earlier behavior, tagset = annotationService.listTags(aModel.feature.getTagset()); } field = new StyledComboBox<Tag>("value", tagset); field.setOutputMarkupId(true); // Must add behavior to editor, not to combobox to ensure proper order of the // initializing JS header items: first combo box, then tooltip. Options options = new Options(DescriptionTooltipBehavior.makeTooltipOptions()); options.set("content", functionForTooltip); add(new TooltipBehavior("#"+field.getMarkupId()+"_listbox *[title]", options)); isDrop = true; } else { field = new TextField<String>("value"); } //Shows whether constraints are triggered or not //also shows state of constraints use. Component constraintsInUseIndicator = new WebMarkupContainer("textIndicator"){ private static final long serialVersionUID = 4346767114287766710L; @Override public boolean isVisible() { return indicator.isAffected(); } }.add(new AttributeAppender("class", new Model<String>(){ private static final long serialVersionUID = -7683195283137223296L; @Override public String getObject() { //adds symbol to indicator return indicator.getStatusSymbol(); } })) .add(new AttributeAppender("style", new Model<String>(){ private static final long serialVersionUID = -5255873539738210137L; @Override public String getObject() { //adds color to indicator return "; color: " + indicator.getStatusColor(); } })); add(constraintsInUseIndicator); add(field); } /** * Adds and sorts tags based on Constraints rules */ private List<Tag> populateTagsBasedOnRules(BratAnnotatorModel model, FeatureModel aModel) { // Add values from rules String restrictionFeaturePath; switch (aModel.feature.getLinkMode()) { case WITH_ROLE: restrictionFeaturePath = aModel.feature.getName() + "." + aModel.feature.getLinkTypeRoleFeatureName(); break; case NONE: restrictionFeaturePath = aModel.feature.getName(); break; default: throw new IllegalArgumentException("Unsupported link mode [" + aModel.feature.getLinkMode() + "] on feature [" + aModel.feature.getName() + "]"); } List<Tag> valuesFromTagset = annotationService.listTags(aModel.feature.getTagset()); try { JCas jCas = getCas(model); FeatureStructure featureStructure = selectByAddr(jCas, model.getSelection() .getAnnotation().getId()); Evaluator evaluator = new ValuesGenerator(); //Only show indicator if this feature can be affected by Constraint rules! indicator.setAffected(evaluator.isThisAffectedByConstraintRules(featureStructure, restrictionFeaturePath, model.getConstraints())); List<PossibleValue> possibleValues; try { possibleValues = evaluator.generatePossibleValues( featureStructure, restrictionFeaturePath, model.getConstraints()); LOG.debug("Possible values for [" + featureStructure.getType().getName() + "] [" + restrictionFeaturePath + "]: " + possibleValues); } catch (Exception e) { error("Unable to evaluate constraints: " + ExceptionUtils.getRootCauseMessage(e)); LOG.error("Unable to evaluate constraints: " + e.getMessage(), e); possibleValues = new ArrayList<>(); } // only adds tags which are suggested by rules and exist in tagset. List<Tag> tagset = compareSortAndAdd(possibleValues, valuesFromTagset, indicator); // add remaining tags addRemainingTags(tagset, valuesFromTagset); return tagset; } catch (IOException | ClassNotFoundException | UIMAException e) { error(ExceptionUtils.getRootCauseMessage(e)); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } return valuesFromTagset; } @Override public Component getFocusComponent() { return field; } @Override public boolean isDropOrchoice() { return isDrop; } }; public class LinkFeatureEditor extends FeatureEditor { private static final long serialVersionUID = 7469241620229001983L; private WebMarkupContainer content; //For showing the status of Constraints rules kicking in. private RulesIndicator indicator = new RulesIndicator(); @SuppressWarnings("rawtypes") private final AbstractTextComponent newRole; private boolean isDrop; private boolean hideUnconstraintFeature; /** * Hides feature if "Hide un-constraint feature" is enabled * and constraint rules are applied and feature doesn't match any constraint rule */ @Override public boolean isVisible() { if (hideUnconstraintFeature) { //if enabled and constraints rule execution returns anything other than green if (indicator.isAffected() && !indicator.getStatusColor().equals("green")) { return false; } } return true; } @SuppressWarnings("unchecked") public LinkFeatureEditor(String aId, String aMarkupId, MarkupContainer aMarkupProvider, final FeatureModel aModel) { super(aId, aMarkupId, aMarkupProvider, new CompoundPropertyModel<FeatureModel>(aModel)); //Checks whether hide un-constraint feature is enabled or not hideUnconstraintFeature = aModel.feature.isHideUnconstraintFeature(); add(new Label("feature", aModel.feature.getUiName())); // Most of the content is inside this container such that we can refresh it independently // from the rest of the form content = new WebMarkupContainer("content"); content.setOutputMarkupId(true); add(content); content.add(new RefreshingView<LinkWithRoleModel>("slots", Model.of((List<LinkWithRoleModel>) aModel.value)) { private static final long serialVersionUID = 5475284956525780698L; @Override protected Iterator<IModel<LinkWithRoleModel>> getItemModels() { ModelIteratorAdapter<LinkWithRoleModel> i = new ModelIteratorAdapter<LinkWithRoleModel>( (List<LinkWithRoleModel>) LinkFeatureEditor.this.getModelObject().value) { @Override protected IModel<LinkWithRoleModel> model(LinkWithRoleModel aObject) { return Model.of(aObject); } }; return i; } @Override protected void populateItem(final Item<LinkWithRoleModel> aItem) { aItem.setModel(new CompoundPropertyModel<LinkWithRoleModel>(aItem .getModelObject())); Label role = new Label("role"); aItem.add(role); final Label label; if (aItem.getModelObject().targetAddr == -1 && bModel.isArmedSlot(aModel.feature, aItem.getIndex())) { label = new Label("label", "<Select to fill>"); } else { label = new Label("label"); } label.add(new AjaxEventBehavior("click") { private static final long serialVersionUID = 7633309278417475424L; @Override protected void onEvent(AjaxRequestTarget aTarget) { if (bModel.isArmedSlot(aModel.feature, aItem.getIndex())) { bModel.clearArmedSlot(); aTarget.add(content); } else { bModel.setArmedSlot(aModel.feature, aItem.getIndex()); // Need to re-render the whole form because a slot in another // link editor might get unarmed aTarget.add(annotationFeatureForm); } } }); label.add(new AttributeAppender("style", new Model<String>() { private static final long serialVersionUID = 1L; @Override public String getObject() { BratAnnotatorModel model = bModel; if (model.isArmedSlot(aModel.feature, aItem.getIndex())) { return "; background: orange"; } else { return ""; } } })); aItem.add(label); } }); if (aModel.feature.getTagset() != null) { List<Tag> tagset = null; //reset the indicator indicator.reset(); if (bModel.getConstraints() != null && bModel.getSelection().getAnnotation().isSet()) { // indicator.setRulesExist(true); //Constraint rules exist! tagset = addTagsBasedOnRules(bModel, aModel); } else { // indicator.setRulesExist(false); //No constraint rules. // add tagsets only, earlier behavior tagset = annotationService.listTags(aModel.feature.getTagset()); } newRole = new StyledComboBox<Tag>("newRole", Model.of(""), tagset) { private static final long serialVersionUID = 1L; @Override protected void onInitialize() { super.onInitialize(); // Ensure proper order of the initializing JS header items: first combo box // behavior (in super.onInitialize()), then tooltip. Options options = new Options(DescriptionTooltipBehavior.makeTooltipOptions()); options.set("content", functionForTooltip); add(new TooltipBehavior("#"+newRole.getMarkupId()+"_listbox *[title]", options)); } @Override protected void onConfigure() { super.onConfigure(); if (bModel.isSlotArmed() && aModel.feature.equals(bModel.getArmedFeature())) { List<LinkWithRoleModel> links = (List<LinkWithRoleModel>) LinkFeatureEditor.this .getModelObject().value; setModelObject(links.get(bModel.getArmedSlot()).role); } else { setModelObject(""); } } }; newRole.setOutputMarkupId(true); content.add(newRole); isDrop = true; } else { content.add(newRole = new TextField<String>("newRole", Model.of("")) { private static final long serialVersionUID = 1L; @Override protected void onConfigure() { super.onConfigure(); if (bModel.isSlotArmed() && aModel.feature.equals(bModel.getArmedFeature())) { List<LinkWithRoleModel> links = (List<LinkWithRoleModel>) LinkFeatureEditor.this .getModelObject().value; setModelObject(links.get(bModel.getArmedSlot()).role); } else { setModelObject(""); } } }); } //Shows whether constraints are triggered or not //also shows state of constraints use. Component constraintsInUseIndicator = new WebMarkupContainer("linkIndicator"){ private static final long serialVersionUID = 4346767114287766710L; @Override public boolean isVisible() { return indicator.isAffected(); } }.add(new AttributeAppender("class", new Model<String>(){ private static final long serialVersionUID = -7683195283137223296L; @Override public String getObject() { //adds symbol to indicator return indicator.getStatusSymbol(); } })) .add(new AttributeAppender("style", new Model<String>(){ private static final long serialVersionUID = -5255873539738210137L; @Override public String getObject() { //adds color to indicator return "; color: " + indicator.getStatusColor(); } })); add(constraintsInUseIndicator); // Add a new empty slot with the specified role content.add(new AjaxButton("add") { private static final long serialVersionUID = 1L; @Override protected void onConfigure(){ BratAnnotatorModel model = bModel; setVisible(!(model.isSlotArmed() && aModel.feature.equals(model.getArmedFeature()))); // setEnabled(!(model.isSlotArmed() // && aModel.feature.equals(model.getArmedFeature()))); } @Override protected void onSubmit(AjaxRequestTarget aTarget, Form<?> aForm) { if (StringUtils.isBlank((String) newRole.getModelObject())) { error("Must set slot label before adding!"); aTarget.addChildren(getPage(), FeedbackPanel.class); } else { List<LinkWithRoleModel> links = (List<LinkWithRoleModel>) LinkFeatureEditor.this .getModelObject().value; LinkWithRoleModel m = new LinkWithRoleModel(); m.role = (String) newRole.getModelObject(); links.add(m); bModel.setArmedSlot(LinkFeatureEditor.this.getModelObject().feature, links.size() - 1); // Need to re-render the whole form because a slot in another // link editor might get unarmed aTarget.add(annotationFeatureForm); } } }); // Allows user to update slot content.add(new AjaxButton("set"){ private static final long serialVersionUID = 7923695373085126646L; @Override protected void onConfigure(){ BratAnnotatorModel model = bModel; setVisible(model.isSlotArmed() && aModel.feature.equals(model.getArmedFeature())); // setEnabled(model.isSlotArmed() // && aModel.feature.equals(model.getArmedFeature())); } @Override protected void onSubmit(AjaxRequestTarget aTarget, Form<?> aForm) { List<LinkWithRoleModel> links = (List<LinkWithRoleModel>) LinkFeatureEditor.this .getModelObject().value; BratAnnotatorModel model = bModel; //Update the slot LinkWithRoleModel m = new LinkWithRoleModel(); m = links.get(model.getArmedSlot()); m.role = (String) newRole.getModelObject(); // int index = model.getArmedSlot(); //retain index // links.remove(model.getArmedSlot()); // model.clearArmedSlot(); // links.add(m); links.set(model.getArmedSlot(), m); //avoid reordering aTarget.add(content); try { actionAnnotate(aTarget, bModel, false); } catch(BratAnnotationException e){ error(ExceptionUtils.getRootCauseMessage(e)); LOG.error(ExceptionUtils.getRootCause(e),e); } catch (Exception e) { error(e.getMessage()); LOG.error(ExceptionUtils.getRootCause(e),e); } } }); // Add a new empty slot with the specified role content.add(new AjaxButton("del") { private static final long serialVersionUID = 1L; @Override protected void onConfigure() { BratAnnotatorModel model = bModel; setVisible(model.isSlotArmed() && aModel.feature.equals(model.getArmedFeature())); // setEnabled(model.isSlotArmed() // && aModel.feature.equals(model.getArmedFeature())); } @Override protected void onSubmit(AjaxRequestTarget aTarget, Form<?> aForm) { List<LinkWithRoleModel> links = (List<LinkWithRoleModel>) LinkFeatureEditor.this .getModelObject().value; BratAnnotatorModel model = bModel; links.remove(model.getArmedSlot()); model.clearArmedSlot(); aTarget.add(content); // Auto-commit if working on existing annotation if (bModel.getSelection().getAnnotation().isSet()) { try { actionAnnotate(aTarget, bModel, false); } catch (BratAnnotationException e) { error(ExceptionUtils.getRootCauseMessage(e)); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } catch (Exception e) { error(ExceptionUtils.getRootCauseMessage(e)); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } } } }); } /** * Adds tagset based on Constraints rules, auto-adds tags which are marked important. * * @return List containing tags which exist in tagset and also suggested by rules, followed * by the remaining tags in tagset. */ private List<Tag> addTagsBasedOnRules(BratAnnotatorModel model, final FeatureModel aModel) { String restrictionFeaturePath = aModel.feature.getName() + "." + aModel.feature.getLinkTypeRoleFeatureName(); List<Tag> valuesFromTagset = annotationService.listTags(aModel.feature.getTagset()); try { JCas jCas = getCas(model); FeatureStructure featureStructure = selectByAddr(jCas, model.getSelection() .getAnnotation().getId()); Evaluator evaluator = new ValuesGenerator(); //Only show indicator if this feature can be affected by Constraint rules! indicator.setAffected(evaluator.isThisAffectedByConstraintRules(featureStructure, restrictionFeaturePath, model.getConstraints())); List<PossibleValue> possibleValues; try { possibleValues = evaluator.generatePossibleValues( featureStructure, restrictionFeaturePath, model.getConstraints()); LOG.debug("Possible values for [" + featureStructure.getType().getName() + "] [" + restrictionFeaturePath + "]: " + possibleValues); } catch (Exception e) { error("Unable to evaluate constraints: " + ExceptionUtils.getRootCauseMessage(e)); LOG.error("Unable to evaluate constraints: " + ExceptionUtils.getRootCauseMessage(e), e); possibleValues = new ArrayList<>(); } // Only adds tags which are suggested by rules and exist in tagset. List<Tag> tagset = compareSortAndAdd(possibleValues, valuesFromTagset, indicator); removeAutomaticallyAddedUnusedEntries(); // Create entries for important tags. autoAddImportantTags(tagset, possibleValues); // Add remaining tags. addRemainingTags(tagset, valuesFromTagset); return tagset; } catch (ClassNotFoundException | UIMAException | IOException e) { error(ExceptionUtils.getRootCauseMessage(e)); LOG.error(ExceptionUtils.getRootCauseMessage(e), e); } return valuesFromTagset; } private void removeAutomaticallyAddedUnusedEntries() { // Remove unused (but auto-added) tags. @SuppressWarnings("unchecked") List<LinkWithRoleModel> list = (List<LinkWithRoleModel>) LinkFeatureEditor.this .getModelObject().value; Iterator<LinkWithRoleModel> existingLinks = list.iterator(); while (existingLinks.hasNext()) { LinkWithRoleModel link = existingLinks.next(); if (link.autoCreated && link.targetAddr == -1) { // remove it existingLinks.remove(); } } } private void autoAddImportantTags(List<Tag> aTagset, List<PossibleValue> possibleValues) { // Construct a quick index for tags Set<String> tagset = new HashSet<String>(); for (Tag t : aTagset) { tagset.add(t.getName()); } // Get links list and build role index @SuppressWarnings("unchecked") List<LinkWithRoleModel> links = (List<LinkWithRoleModel>) LinkFeatureEditor.this .getModelObject().value; Set<String> roles = new HashSet<String>(); for (LinkWithRoleModel l : links) { roles.add(l.role); } // Loop over values to see which of the tags are important and add them. for (PossibleValue value : possibleValues) { if (!value.isImportant() || !tagset.contains(value.getValue())) { continue; } // Check if there is already a slot with the given name if (roles.contains(value.getValue())) { continue; } // Add empty slot in UI with that name. LinkWithRoleModel m = new LinkWithRoleModel(); m.role = value.getValue(); // Marking so that can be ignored later. m.autoCreated = true; links.add(m); // NOT arming the slot here! } } public void setModelObject(FeatureModel aModel) { setDefaultModelObject(aModel); } public FeatureModel getModelObject() { return (FeatureModel) getDefaultModelObject(); } @Override public Component getFocusComponent() { return newRole; } @Override public boolean isDropOrchoice() { return isDrop; } }; public void populateFeatures(FeatureStructure aFS) { featureModels = new ArrayList<>(); if (aFS != null) { // Populate from feature structure for (AnnotationFeature feature : annotationService .listAnnotationFeature(bModel.getSelectedAnnotationLayer())) { if (!feature.isEnabled()) { continue; } if (WebAnnoConst.CHAIN_TYPE.equals(feature.getLayer().getType())) { if (bModel.getSelection().isRelationAnno()) { if (feature.getLayer().isLinkedListBehavior() && WebAnnoConst.COREFERENCE_RELATION_FEATURE.equals(feature .getName())) { featureModels.add(new FeatureModel(feature, (Serializable) BratAjaxCasUtil.getFeature(aFS, feature))); } } else { if (WebAnnoConst.COREFERENCE_TYPE_FEATURE.equals(feature.getName())) { featureModels.add(new FeatureModel(feature, (Serializable) BratAjaxCasUtil.getFeature(aFS, feature))); } } } else { featureModels.add(new FeatureModel(feature, (Serializable) BratAjaxCasUtil.getFeature(aFS, feature))); } } } else if (!bModel.getSelection().isRelationAnno() && bModel.getRememberedSpanFeatures() != null) { // Populate from remembered values for (AnnotationFeature feature : annotationService .listAnnotationFeature(bModel.getSelectedAnnotationLayer())) { if (!feature.isEnabled()) { continue; } if (WebAnnoConst.CHAIN_TYPE.equals(feature.getLayer().getType())) { if (WebAnnoConst.COREFERENCE_TYPE_FEATURE.equals(feature.getName())) { featureModels.add(new FeatureModel(feature, bModel.getRememberedSpanFeatures().get(feature))); } } else { featureModels.add(new FeatureModel(feature, bModel.getRememberedSpanFeatures().get(feature))); } } } else if (bModel.getSelection().isRelationAnno() && bModel.getRememberedArcFeatures() != null) { // Populate from remembered values for (AnnotationFeature feature : annotationService .listAnnotationFeature(bModel.getSelectedAnnotationLayer())) { if (!feature.isEnabled()) { continue; } if (WebAnnoConst.CHAIN_TYPE.equals(feature.getLayer().getType())) { if (feature.getLayer().isLinkedListBehavior() && WebAnnoConst.COREFERENCE_RELATION_FEATURE.equals(feature.getName())) { featureModels.add(new FeatureModel(feature, bModel .getRememberedArcFeatures().get(feature))); } } else { featureModels.add(new FeatureModel(feature, bModel.getRememberedArcFeatures().get(feature))); } } } } public void addRemainingTags(List<Tag> tagset, List<Tag> valuesFromTagset) { // adding the remaining part of tagset. for (Tag remainingTag : valuesFromTagset) { if (!tagset.contains(remainingTag)) { tagset.add(remainingTag); } } } /* * Compares existing tagset with possible values resulted from rule evaluation Adds only which * exist in tagset and is suggested by rules. The remaining values from tagset are added * afterwards. */ private static List<Tag> compareSortAndAdd(List<PossibleValue> possibleValues, List<Tag> valuesFromTagset, RulesIndicator rulesIndicator) { //if no possible values, means didn't satisfy conditions if(possibleValues.isEmpty()) { rulesIndicator.didntMatchAnyRule(); } List<Tag> returnList = new ArrayList<Tag>(); // Sorting based on important flag // possibleValues.sort(null); // Comparing to check which values suggested by rules exists in existing // tagset and adding them first in list. for (PossibleValue value : possibleValues) { for (Tag tag : valuesFromTagset) { if (value.getValue().equalsIgnoreCase(tag.getName())) { //Matching values found in tagset and shown in dropdown rulesIndicator.rulesApplied(); // HACK BEGIN tag.setReordered(true); // HACK END //Avoid duplicate entries if(!returnList.contains(tag)){ returnList.add(tag); } } } } //If no matching tags found if(returnList.isEmpty()){ rulesIndicator.didntMatchAnyTag(); } return returnList; } public class LayerSelector extends DropDownChoice<AnnotationLayer> { private static final long serialVersionUID = 2233133653137312264L; public LayerSelector(String aId, List<? extends AnnotationLayer> aChoices) { super(aId, aChoices); setOutputMarkupId(true); setChoiceRenderer(new ChoiceRenderer<AnnotationLayer>("uiName")); add(new AjaxFormComponentUpdatingBehavior("onchange") { private static final long serialVersionUID = 5179816588460867471L; @Override protected void onUpdate(AjaxRequestTarget aTarget) { if (!bModel.getSelectedAnnotationLayer().equals(getModelObject()) && bModel.getSelection().getAnnotation().isSet()) { if (bModel.getSelection().isRelationAnno()) { try { actionClear(aTarget, bModel); } catch (UIMAException | ClassNotFoundException | IOException | BratAnnotationException e) { error(e.getMessage()); } } else { deleteModal.setContent(new DeleteOrReplaceAnnotationModalPanel( deleteModal.getContentId(), bModel, deleteModal, AnnotationDetailEditorPanel.this, getModelObject(), true)); deleteModal .setWindowClosedCallback(new ModalWindow.WindowClosedCallback() { private static final long serialVersionUID = 4364820331676014559L; @Override public void onClose(AjaxRequestTarget target) { target.add(annotationFeatureForm); } }); deleteModal.show(aTarget); } } else { bModel.setSelectedAnnotationLayer(getModelObject()); selectedAnnotationLayer.setDefaultModelObject(getModelObject().getUiName()); aTarget.add(selectedAnnotationLayer); populateFeatures(null); aTarget.add(annotationFeatureForm); } } }); } } private FeatureModel getFeatureModel(AnnotationFeature aFeature) { for (FeatureModel f : featureModels) { if (f.feature.getId() == aFeature.getId()) { return f; } } return null; } /** * Represents a link with a role in the UI. */ public static class LinkWithRoleModel implements Serializable { private static final long serialVersionUID = 2027345278696308900L; public static final String CLICK_HINT = "<Click to activate>"; public String role; public String label = CLICK_HINT; public int targetAddr = -1; public boolean autoCreated; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((label == null) ? 0 : label.hashCode()); result = prime * result + ((role == null) ? 0 : role.hashCode()); result = prime * result + targetAddr; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } LinkWithRoleModel other = (LinkWithRoleModel) obj; if (label == null) { if (other.label != null) { return false; } } else if (!label.equals(other.label)) { return false; } if (role == null) { if (other.role != null) { return false; } } else if (!role.equals(other.role)) { return false; } if (targetAddr != other.targetAddr) { return false; } return true; } } private void updateForwardAnnotation(BratAnnotatorModel aBModel) { if (aBModel.getSelectedAnnotationLayer() != null && !aBModel.getSelectedAnnotationLayer().isLockToTokenOffset()) { aBModel.setForwardAnnotation(false);// no forwarding for // sub-/multitoken annotation } else { aBModel.setForwardAnnotation(aBModel.isForwardAnnotation()); } } public static class FeatureModel implements Serializable { private static final long serialVersionUID = 3512979848975446735L; public final AnnotationFeature feature; public Serializable value; public FeatureModel(AnnotationFeature aFeature, Serializable aValue) { feature = aFeature; value = aValue; // Avoid having null here because otherwise we have to handle null in zillion places! if (value == null && MultiValueMode.ARRAY.equals(aFeature.getMultiValueMode())) { value = new ArrayList<>(); } } } private Map<String, String> getBindTags() { AnnotationFeature f = annotationService.listAnnotationFeature(bModel.getSelectedAnnotationLayer()).get(0); TagSet tagSet = f.getTagset(); Map<Character, String> tagNames = new LinkedHashMap<>(); Map<String, String> bindTag2Key = new LinkedHashMap<>(); for (Tag tag : annotationService.listTags(tagSet)) { if (tagNames.containsKey(tag.getName().toLowerCase().charAt(0))) { String oldBinding = tagNames.get(tag.getName().toLowerCase().charAt(0)); String newBinding = oldBinding + tag.getName().toLowerCase().charAt(0); tagNames.put(tag.getName().toLowerCase().charAt(0), newBinding); bindTag2Key.put(newBinding, tag.getName()); } else { tagNames.put(tag.getName().toLowerCase().charAt(0), tag.getName().toLowerCase().substring(0, 1)); bindTag2Key.put(tag.getName().toLowerCase().substring(0, 1), tag.getName()); } } return bindTag2Key; } private String getKeyBindValue(String aKey, Map<String, String> aBindTags){ // check if all the key pressed are the same character // if not, just check a Tag for the last char pressed if(aKey.isEmpty()){ return aBindTags.get(aBindTags.keySet().iterator().next()); } char prevC = aKey.charAt(0); for(char ch:aKey.toCharArray()){ if(ch!=prevC){ break; } } if (aBindTags.get(aKey)!=null){ return aBindTags.get(aKey); } // re-cycle suggestions if(aBindTags.containsKey(aKey.substring(0,1))){ selectedTag = aKey.substring(0,1); return aBindTags.get(aKey.substring(0,1)); } // set it to the first in the tag list , when arbitrary key is pressed return aBindTags.get(aBindTags.keySet().iterator().next()); } public void reload(AjaxRequestTarget aTarget) { aTarget.add(annotationFeatureForm); } public void reset(AjaxRequestTarget aTarget) { bModel.getSelection().clear(); bModel.getSelection().setBegin(0); bModel.getSelection().setEnd(0); featureModels = new ArrayList<>(); aTarget.add(annotationFeatureForm); } public void reloadLayer(AjaxRequestTarget aTarget) throws BratAnnotationException { try { featureModels = new ArrayList<>(); if (!bModel.getSelection().isRelationAnno()) { setInitSpanLayers(bModel); } setLayerAndFeatureModels(aTarget, getCas(bModel), bModel); if (featureModels.size() == 0) { populateFeatures(null); } else if (isFeatureModelChanged(bModel.getSelectedAnnotationLayer())) { populateFeatures(null); } updateBrushMode(); aTarget.add(annotationFeatureForm); } catch (UIMAException | ClassNotFoundException | IOException e) { error(e.getMessage()); } } private void updateBrushMode() { if (bModel.getPreferences().isBrushMode()) { if (bModel.getDefaultAnnotationLayer() == null) { bModel.setDefaultAnnotationLayer(bModel.getSelectedAnnotationLayer()); } } else if (!bModel.getSelection().isRelationAnno()) { bModel.setDefaultAnnotationLayer(bModel.getSelectedAnnotationLayer()); } // if no layer is selected in Settings if (bModel.getSelectedAnnotationLayer() != null) { selectedAnnotationLayer.setDefaultModelObject(bModel.getSelectedAnnotationLayer().getUiName()); } } /** * remove this model, if new annotation is to be created */ public void clearArmedSlotModel() { for (FeatureModel fm : featureModels) { if (StringUtils.isNotBlank(fm.feature.getLinkTypeName())) { fm.value = new ArrayList<>(); } } } private Set<AnnotationFS> getAttachedRels(JCas aJCas, AnnotationFS aFs, AnnotationLayer aLayer) throws UIMAException, ClassNotFoundException, IOException{ Set<AnnotationFS> toBeDeleted = new HashSet<AnnotationFS>(); for (AnnotationLayer relationLayer : annotationService .listAttachedRelationLayers(aLayer)) { ArcAdapter relationAdapter = (ArcAdapter) getAdapter(annotationService, relationLayer); Type relationType = CasUtil.getType(aJCas.getCas(), relationLayer.getName()); Feature sourceFeature = relationType.getFeatureByBaseName(relationAdapter .getSourceFeatureName()); Feature targetFeature = relationType.getFeatureByBaseName(relationAdapter .getTargetFeatureName()); // This code is already prepared for the day that relations can go between // different layers and may have different attach features for the source and // target layers. Feature relationSourceAttachFeature = null; Feature relationTargetAttachFeature = null; if (relationAdapter.getAttachFeatureName() != null) { relationSourceAttachFeature = sourceFeature.getRange().getFeatureByBaseName( relationAdapter.getAttachFeatureName()); relationTargetAttachFeature = targetFeature.getRange().getFeatureByBaseName( relationAdapter.getAttachFeatureName()); } for (AnnotationFS relationFS : CasUtil.select(aJCas.getCas(), relationType)) { // Here we get the annotations that the relation is pointing to in the UI FeatureStructure sourceFS; if (relationSourceAttachFeature != null) { sourceFS = relationFS.getFeatureValue(sourceFeature).getFeatureValue( relationSourceAttachFeature); } else { sourceFS = relationFS.getFeatureValue(sourceFeature); } FeatureStructure targetFS; if (relationTargetAttachFeature != null) { targetFS = relationFS.getFeatureValue(targetFeature).getFeatureValue( relationTargetAttachFeature); } else { targetFS = relationFS.getFeatureValue(targetFeature); } if (isSame(sourceFS, aFs) || isSame(targetFS, aFs)) { toBeDeleted.add(relationFS); LOG.debug("Deleted relation [" + getAddr(relationFS) + "] from layer [" + relationLayer.getName() + "]"); } } } return toBeDeleted; } public AnnotationFeatureForm getAnnotationFeatureForm() { return annotationFeatureForm; } public Label getSelectedAnnotationLayer() { return selectedAnnotationLayer; } private boolean isFeatureModelChanged(AnnotationLayer aLayer){ for(FeatureModel fM: featureModels){ if(!annotationService.listAnnotationFeature(aLayer).contains(fM.feature)){ return true; } } return false; } private boolean isForwardable() { if (bModel.getSelectedAnnotationLayer() == null) { return false; } if (bModel.getSelectedAnnotationLayer().getId() <= 0) { return false; } if (!bModel.getSelectedAnnotationLayer().getType().equals(WebAnnoConst.SPAN_TYPE)) { return false; } if (!bModel.getSelectedAnnotationLayer().isLockToTokenOffset()) { return false; } // no forward annotation for multifeature layers. if(annotationService.listAnnotationFeature(bModel.getSelectedAnnotationLayer()).size()>1){ return false; } // if there are no features at all, no forward annotation if(annotationService.listAnnotationFeature(bModel.getSelectedAnnotationLayer()).isEmpty()){ return false; } // we allow forward annotation only for a feature with a tagset if(annotationService.listAnnotationFeature(bModel.getSelectedAnnotationLayer()).get(0).getTagset()==null){ return false; } TagSet tagSet = annotationService.listAnnotationFeature(bModel.getSelectedAnnotationLayer()).get(0).getTagset(); // there should be at least one tag in the tagset if(annotationService.listTags(tagSet).size()==0){ return false; } return true; } private static String generateMessage(AnnotationLayer aLayer, String aLabel, boolean aDeleted) { String action = aDeleted ? "deleted" : "created/updated"; String msg = "The [" + aLayer.getUiName() + "] annotation has been " + action + "."; if (StringUtils.isNotBlank(aLabel)) { msg += " Label: [" + aLabel + "]"; } return msg; } class StyledComboBox<T> extends ComboBox<T> { public StyledComboBox(String id, IModel<String> model, List<T> choices) { super(id, model, choices); } public StyledComboBox(String string, List<T> choices) { super(string, choices); } private static final long serialVersionUID = 1L; @Override protected IJQueryTemplate newTemplate() { return new IJQueryTemplate() { private static final long serialVersionUID = 1L; /** * Marks the reordered entries in bold. * Same as text feature editor. */ @Override public String getText() { // Some docs on how the templates work in Kendo, in case we need // more fancy dropdowns // http://docs.telerik.com/kendo-ui/framework/templates/overview StringBuilder sb = new StringBuilder(); sb.append("# if (data.reordered == 'true') { #"); sb.append("<div title=\"#: data.description #\"><b>#: data.name #</b></div>\n"); sb.append("# } else { #"); sb.append("<div title=\"#: data.description #\">#: data.name #</div>\n"); sb.append("# } #"); return sb.toString(); } @Override public List<String> getTextProperties() { return Arrays.asList("name", "description", "reordered"); } }; } } }
Unable to change Layer while annotating, if the feature type is String (without tagset) #243 Probably, comment line 1330 thru 1333 with constraints to work -- NOT TESTED
webanno-brat/src/main/java/de/tudarmstadt/ukp/clarin/webanno/brat/annotation/component/AnnotationDetailEditorPanel.java
Unable to change Layer while annotating, if the feature type is String (without tagset) #243 Probably, comment line 1330 thru 1333 with constraints to work -- NOT TESTED
<ide><path>ebanno-brat/src/main/java/de/tudarmstadt/ukp/clarin/webanno/brat/annotation/component/AnnotationDetailEditorPanel.java <ide> import de.tudarmstadt.ukp.clarin.webanno.model.SourceDocumentState; <ide> import de.tudarmstadt.ukp.clarin.webanno.model.Tag; <ide> import de.tudarmstadt.ukp.clarin.webanno.model.TagSet; <add>import de.tudarmstadt.ukp.clarin.webanno.support.DefaultFocusBehavior; <ide> import de.tudarmstadt.ukp.clarin.webanno.support.DefaultFocusBehavior2; <ide> import de.tudarmstadt.ukp.clarin.webanno.support.DescriptionTooltipBehavior; <ide> import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.POS; <ide> private AnnotationFeatureForm annotationFeatureForm; <ide> private Label selectedTextLabel; <ide> private CheckBox forwardAnnotationCheck; <del> RefreshingView<FeatureModel> featureValues; <add> private RefreshingView<FeatureModel> featureValues; <ide> <ide> private AjaxButton deleteButton; <ide> private AjaxButton reverseButton; <ide> } <ide> } <ide> } <del> aTarget.add(annotationFeatureForm); <add> //aTarget.add(annotationFeatureForm); -- THIS CAUSES THE FOCUS TO BE ALWAYS TO THE FIRST ITEM #243 <ide> TypeAdapter adapter = getAdapter(annotationService, aBModel.getSelectedAnnotationLayer()); <ide> Selection selection = aBModel.getSelection(); <ide> if (selection.getAnnotation().isNotSet()) { <ide> } <ide> item.add(frag); <ide> <del> if (bModel.isForwardAnnotation()) { <add>/* if (bModel.isForwardAnnotation()) { <ide> forwardAnnotationText.add(new DefaultFocusBehavior2()); <ide> } else { <ide> // Disabled for Github Issue #243 <ide> // if (item.getIndex() == item.size() - 1) { <ide> // frag.getFocusComponent().add(new DefaultFocusBehavior()); <ide> // } <del> } <add> }*/ <ide> if (!fm.feature.getLayer().isReadonly()) { <ide> // whenever it is updating an annotation, it updates automatically when a component <ide> // for the feature lost focus - but updating is for every component edited <ide> } <ide> } <ide> <del> /* <del> * if (item.getIndex() == 0) { // Put focus on first feature <del> * frag.getFocusComponent().add(new DefaultFocusBehavior()); } <del> */ <add> if (bModel.isForwardAnnotation()) { <add> forwardAnnotationText.add(new DefaultFocusBehavior2()); <add> } else if (item.getIndex() == 0) { // Put focus on first feature <add> frag.getFocusComponent().add(new DefaultFocusBehavior()); } <add> <ide> <ide> // Add tooltip on label <ide> StringBuilder tooltipTitle = new StringBuilder();
Java
apache-2.0
e187a3ea28412e0bef3b13f09fb355cd6d3c0107
0
apache/felix-dev,apache/felix-dev,apache/felix-dev,apache/felix-dev
/* * 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.felix.framework.util; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.invoke.MethodHandles; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Executable; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.net.URLConnection; import java.net.URLStreamHandler; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.security.AccessControlContext; import java.security.AccessController; import java.security.Policy; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.Collection; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import java.util.function.Consumer; import java.util.jar.JarFile; import java.util.zip.ZipFile; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceReference; import org.osgi.framework.hooks.resolver.ResolverHook; import org.osgi.framework.hooks.service.ListenerHook; import org.osgi.framework.wiring.BundleCapability; import org.osgi.framework.wiring.BundleRequirement; import org.osgi.framework.wiring.BundleRevision; /** * <p> * This is a utility class to centralize all action that should be performed * in a <tt>doPrivileged()</tt> block. To perform a secure action, simply * create an instance of this class and use the specific method to perform * the desired action. When an instance is created, this class will capture * the security context and will then use that context when checking for * permission to perform the action. Instances of this class should not be * passed around since they may grant the receiver a capability to perform * privileged actions. * </p> **/ public class SecureAction { private static final byte[] accessor; static { byte[] result; try (ByteArrayOutputStream output = new ByteArrayOutputStream(); InputStream input = SecureAction.class.getResourceAsStream("accessor.bytes")) { byte[] buffer = new byte[input.available() > 0 ? input.available() : 1024]; for (int i = input.read(buffer); i != -1; i = input.read(buffer)) { output.write(buffer, 0, i); } result = output.toByteArray(); } catch (Throwable t) { t.printStackTrace(); result = new byte[0]; } accessor = result; getAccessor(URL.class); } private static final ThreadLocal m_actions = new ThreadLocal() { public Object initialValue() { return new Actions(); } }; protected static transient int BUFSIZE = 4096; private AccessControlContext m_acc = null; public SecureAction() { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INITIALIZE_CONTEXT_ACTION, null); m_acc = (AccessControlContext) AccessController.doPrivileged(actions); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { m_acc = AccessController.getContext(); } } public String getSystemProperty(String name, String def) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_PROPERTY_ACTION, name, def); return (String) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return System.getProperty(name, def); } } public ClassLoader getParentClassLoader(ClassLoader loader) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_PARENT_CLASS_LOADER_ACTION, loader); return (ClassLoader) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return loader.getParent(); } } public ClassLoader getSystemClassLoader() { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_SYSTEM_CLASS_LOADER_ACTION); return (ClassLoader) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return ClassLoader.getSystemClassLoader(); } } public ClassLoader getClassLoader(Class clazz) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_CLASS_LOADER_ACTION, clazz); return (ClassLoader) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return clazz.getClassLoader(); } } public Class forName(String name, ClassLoader classloader) throws ClassNotFoundException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.FOR_NAME_ACTION, name, classloader); return (Class) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof ClassNotFoundException) { throw (ClassNotFoundException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else if (classloader != null) { return Class.forName(name, true, classloader); } else { return Class.forName(name); } } public URL createURL(String protocol, String host, int port, String path, URLStreamHandler handler) throws MalformedURLException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.CREATE_URL_ACTION, protocol, host, new Integer(port), path, handler); return (URL) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof MalformedURLException) { throw (MalformedURLException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return new URL(protocol, host, port, path, handler); } } public URL createURL(URL context, String spec, URLStreamHandler handler) throws MalformedURLException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.CREATE_URL_WITH_CONTEXT_ACTION, context, spec, handler); return (URL) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof MalformedURLException) { throw (MalformedURLException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return new URL(context, spec, handler); } } public Process exec(String command) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.EXEC_ACTION, command); return (Process) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return Runtime.getRuntime().exec(command); } } public String getAbsolutePath(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_ABSOLUTE_PATH_ACTION, file); return (String) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.getAbsolutePath(); } } public boolean fileExists(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.FILE_EXISTS_ACTION, file); return ((Boolean) AccessController.doPrivileged(actions, m_acc)) .booleanValue(); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.exists(); } } public boolean isFile(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.FILE_IS_FILE_ACTION, file); return ((Boolean) AccessController.doPrivileged(actions, m_acc)) .booleanValue(); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.isFile(); } } public boolean isFileDirectory(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.FILE_IS_DIRECTORY_ACTION, file); return ((Boolean) AccessController.doPrivileged(actions, m_acc)) .booleanValue(); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.isDirectory(); } } public boolean mkdir(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.MAKE_DIRECTORY_ACTION, file); return ((Boolean) AccessController.doPrivileged(actions, m_acc)) .booleanValue(); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.mkdir(); } } public boolean mkdirs(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.MAKE_DIRECTORIES_ACTION, file); return ((Boolean) AccessController.doPrivileged(actions, m_acc)) .booleanValue(); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.mkdirs(); } } public File[] listDirectory(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.LIST_DIRECTORY_ACTION, file); return (File[]) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.listFiles(); } } public boolean renameFile(File oldFile, File newFile) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.RENAME_FILE_ACTION, oldFile, newFile); return ((Boolean) AccessController.doPrivileged(actions, m_acc)) .booleanValue(); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return oldFile.renameTo(newFile); } } public InputStream getInputStream(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_INPUT_ACTION, file); return (InputStream) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return Files.newInputStream(file.toPath()); } } public OutputStream getOutputStream(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_OUTPUT_ACTION, file); return (OutputStream) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return Files.newOutputStream(file.toPath()); } } public FileInputStream getFileInputStream(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_FILE_INPUT_ACTION, file); return (FileInputStream) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return new FileInputStream(file); } } public FileOutputStream getFileOutputStream(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_FILE_OUTPUT_ACTION, file); return (FileOutputStream) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return new FileOutputStream(file); } } public FileChannel getFileChannel(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_FILE_CHANNEL_ACTION, file); return (FileChannel) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return FileChannel.open(file.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); } } public URI toURI(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.TO_URI_ACTION, file); return (URI) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.toURI(); } } public InputStream getURLConnectionInputStream(URLConnection conn) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_URL_INPUT_ACTION, conn); return (InputStream) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return conn.getInputStream(); } } public boolean deleteFile(File target) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.DELETE_FILE_ACTION, target); return ((Boolean) AccessController.doPrivileged(actions, m_acc)) .booleanValue(); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return target.delete(); } } public File createTempFile(String prefix, String suffix, File dir) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.CREATE_TMPFILE_ACTION, prefix, suffix, dir); return (File) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return File.createTempFile(prefix, suffix, dir); } } public void deleteFileOnExit(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.DELETE_FILEONEXIT_ACTION, file); AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { file.deleteOnExit(); } } public URLConnection openURLConnection(URL url) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.OPEN_URLCONNECTION_ACTION, url); return (URLConnection) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return url.openConnection(); } } public ZipFile openZipFile(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.OPEN_ZIPFILE_ACTION, file); return (ZipFile) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return new ZipFile(file); } } public JarFile openJarFile(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.OPEN_JARFILE_ACTION, file); return (JarFile) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return new JarFile(file); } } public void startActivator(BundleActivator activator, BundleContext context) throws Exception { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.START_ACTIVATOR_ACTION, activator, context); AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw ex.getException(); } } else { activator.start(context); } } public void stopActivator(BundleActivator activator, BundleContext context) throws Exception { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.STOP_ACTIVATOR_ACTION, activator, context); AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw ex.getException(); } } else { activator.stop(context); } } public Policy getPolicy() { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_POLICY_ACTION, null); return (Policy) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return Policy.getPolicy(); } } public void addURLToURLClassLoader(URL extension, ClassLoader loader) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.ADD_EXTENSION_URL_ACTION, extension, loader); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] {URL.class}); getAccessor(URLClassLoader.class).accept(new AccessibleObject[]{addURL}); addURL.invoke(loader, new Object[]{extension}); } } public Constructor getConstructor(Class target, Class[] types) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_CONSTRUCTOR_ACTION, target, types); try { return (Constructor) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return target.getConstructor(types); } } public Constructor getDeclaredConstructor(Class target, Class[] types) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_DECLARED_CONSTRUCTOR_ACTION, target, types); try { return (Constructor) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return target.getDeclaredConstructor(types); } } public Method getMethod(Class target, String method, Class[] types) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_METHOD_ACTION, target, method, types); try { return (Method) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return target.getMethod(method, types); } } public Method getDeclaredMethod(Class target, String method, Class[] types) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_DECLARED_METHOD_ACTION, target, method, types); try { return (Method) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return target.getDeclaredMethod(method, types); } } public void setAccesssible(Executable ao) { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.SET_ACCESSIBLE_ACTION, ao); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw (RuntimeException) e.getException(); } } else { getAccessor(ao.getDeclaringClass()).accept(new AccessibleObject[]{ao}); } } public Object invoke(Method method, Object target, Object[] params) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_METHOD_ACTION, method, target, params); try { return AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { getAccessor(method.getDeclaringClass()).accept(new AccessibleObject[]{method}); return method.invoke(target, params); } } public Object invokeDirect(Method method, Object target, Object[] params) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_DIRECTMETHOD_ACTION, method, target, params); try { return AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return method.invoke(target, params); } } public Object invoke(Constructor constructor, Object[] params) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_CONSTRUCTOR_ACTION, constructor, params); try { return AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return constructor.newInstance(params); } } public Object getDeclaredField(Class targetClass, String name, Object target) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_FIELD_ACTION, targetClass, name, target); try { return AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { Field field = targetClass.getDeclaredField(name); getAccessor(targetClass).accept(new AccessibleObject[]{field}); return field.get(target); } } public Object swapStaticFieldIfNotClass(Class targetClazz, Class targetType, Class condition, String lockName) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.SWAP_FIELD_ACTION, targetClazz, targetType, condition, lockName); try { return AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return _swapStaticFieldIfNotClass(targetClazz, targetType, condition, lockName); } } private static volatile Consumer<AccessibleObject[]> m_accessorCache = null; @SuppressWarnings("unchecked") private static Consumer<AccessibleObject[]> getAccessor(Class clazz) { String packageName = clazz.getPackage().getName(); if ("java.net".equals(packageName) || "jdk.internal.loader".equals(packageName)) { if (m_accessorCache == null) { try { // Use reflection on Unsafe to avoid having to compile against it Class<?> unsafeClass = Class.forName("sun.misc.Unsafe"); //$NON-NLS-1$ Field theUnsafe = unsafeClass.getDeclaredField("theUnsafe"); //$NON-NLS-1$ // NOTE: deep reflection is allowed on sun.misc package for java 9. theUnsafe.setAccessible(true); Object unsafe = theUnsafe.get(null); Class<Consumer<AccessibleObject[]>> result; try { Method defineAnonymousClass = unsafeClass.getMethod("defineAnonymousClass", Class.class, byte[].class, Object[].class); //$NON-NLS-1$ result = (Class<Consumer<AccessibleObject[]>>) defineAnonymousClass.invoke(unsafe, URL.class, accessor , null);; } catch (NoSuchMethodException ex) { long offset = (long) unsafeClass.getMethod("staticFieldOffset", Field.class) .invoke(unsafe, MethodHandles.Lookup.class.getDeclaredField("IMPL_LOOKUP")); MethodHandles.Lookup lookup = (MethodHandles.Lookup) unsafeClass.getMethod("getObject", Object.class, long.class) .invoke(unsafe, MethodHandles.Lookup.class, offset); lookup = lookup.in(URL.class); Class<?> classOption = Class.forName("java.lang.invoke.MethodHandles$Lookup$ClassOption"); //$NON-NLS-1$ Object classOptions = Array.newInstance(classOption, 0); Method defineHiddenClass = MethodHandles.Lookup.class.getMethod("defineHiddenClass", byte[].class, boolean.class, //$NON-NLS-1$ classOptions.getClass()); lookup = (MethodHandles.Lookup) defineHiddenClass.invoke(lookup, accessor, Boolean.FALSE, classOptions); result = (Class<Consumer<AccessibleObject[]>>) lookup.lookupClass(); } m_accessorCache = result.getConstructor().newInstance(); } catch (Throwable t) { t.printStackTrace(); m_accessorCache = objects -> AccessibleObject.setAccessible(objects, true); } } return m_accessorCache; } else { return objects -> AccessibleObject.setAccessible(objects, true); } } private static Object _swapStaticFieldIfNotClass(Class targetClazz, Class targetType, Class condition, String lockName) throws Exception { Object lock = null; if (lockName != null) { try { Field lockField = targetClazz.getDeclaredField(lockName); getAccessor(targetClazz).accept(new AccessibleObject[]{lockField}); lock = lockField.get(null); } catch (NoSuchFieldException ex) { } } if (lock == null) { lock = targetClazz; } synchronized (lock) { Field[] fields = targetClazz.getDeclaredFields(); getAccessor(targetClazz).accept(fields); Object result = null; for (int i = 0; (i < fields.length) && (result == null); i++) { if (Modifier.isStatic(fields[i].getModifiers()) && (fields[i].getType() == targetType)) { result = fields[i].get(null); if (result != null) { if ((condition == null) || !result.getClass().getName().equals(condition.getName())) { fields[i].set(null, null); } } } } if (result != null) { if ((condition == null) || !result.getClass().getName().equals(condition.getName())) { // reset cache for (int i = 0; i < fields.length; i++) { if (Modifier.isStatic(fields[i].getModifiers()) && (fields[i].getType() == Hashtable.class)) { Hashtable cache = (Hashtable) fields[i].get(null); if (cache != null) { cache.clear(); } } } } return result; } } return null; } public void flush(Class targetClazz, Object lock) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.FLUSH_FIELD_ACTION, targetClazz, lock); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { _flush(targetClazz, lock); } } private static void _flush(Class targetClazz, Object lock) throws Exception { synchronized (lock) { Field[] fields = targetClazz.getDeclaredFields(); getAccessor(targetClazz).accept(fields); // reset cache for (int i = 0; i < fields.length; i++) { if (Modifier.isStatic(fields[i].getModifiers()) && ((fields[i].getType() == Hashtable.class) || (fields[i].getType() == HashMap.class))) { if (fields[i].getType() == Hashtable.class) { Hashtable cache = (Hashtable) fields[i].get(null); if (cache != null) { cache.clear(); } } else { HashMap cache = (HashMap) fields[i].get(null); if (cache != null) { cache.clear(); } } } } } } public void invokeBundleCollisionHook( org.osgi.framework.hooks.bundle.CollisionHook ch, int operationType, Bundle targetBundle, Collection<Bundle> collisionCandidates) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_BUNDLE_COLLISION_HOOK, ch, operationType, targetBundle, collisionCandidates); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { ch.filterCollisions(operationType, targetBundle, collisionCandidates); } } public void invokeBundleFindHook( org.osgi.framework.hooks.bundle.FindHook fh, BundleContext bc, Collection<Bundle> bundles) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_BUNDLE_FIND_HOOK, fh, bc, bundles); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { fh.find(bc, bundles); } } public void invokeBundleEventHook( org.osgi.framework.hooks.bundle.EventHook eh, BundleEvent event, Collection<BundleContext> contexts) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_BUNDLE_EVENT_HOOK, eh, event, contexts); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { eh.event(event, contexts); } } public void invokeWeavingHook( org.osgi.framework.hooks.weaving.WeavingHook wh, org.osgi.framework.hooks.weaving.WovenClass wc) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_WEAVING_HOOK, wh, wc); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { wh.weave(wc); } } public void invokeServiceEventHook( org.osgi.framework.hooks.service.EventHook eh, ServiceEvent event, Collection<BundleContext> contexts) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_SERVICE_EVENT_HOOK, eh, event, contexts); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { eh.event(event, contexts); } } public void invokeServiceFindHook( org.osgi.framework.hooks.service.FindHook fh, BundleContext context, String name, String filter, boolean allServices, Collection<ServiceReference<?>> references) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set( Actions.INVOKE_SERVICE_FIND_HOOK, fh, context, name, filter, (allServices) ? Boolean.TRUE : Boolean.FALSE, references); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { fh.find(context, name, filter, allServices, references); } } public void invokeServiceListenerHookAdded( org.osgi.framework.hooks.service.ListenerHook lh, Collection<ListenerHook.ListenerInfo> listeners) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_SERVICE_LISTENER_HOOK_ADDED, lh, listeners); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { lh.added(listeners); } } public void invokeServiceListenerHookRemoved( org.osgi.framework.hooks.service.ListenerHook lh, Collection<ListenerHook.ListenerInfo> listeners) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_SERVICE_LISTENER_HOOK_REMOVED, lh, listeners); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { lh.removed(listeners); } } public void invokeServiceEventListenerHook( org.osgi.framework.hooks.service.EventListenerHook elh, ServiceEvent event, Map<BundleContext, Collection<ListenerHook.ListenerInfo>> listeners) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_SERVICE_EVENT_LISTENER_HOOK, elh, event, listeners); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { elh.event(event, listeners); } } public ResolverHook invokeResolverHookFactory( org.osgi.framework.hooks.resolver.ResolverHookFactory rhf, Collection<BundleRevision> triggers) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_RESOLVER_HOOK_FACTORY, rhf, triggers); try { return (ResolverHook) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return rhf.begin(triggers); } } public void invokeResolverHookResolvable( org.osgi.framework.hooks.resolver.ResolverHook rh, Collection<BundleRevision> candidates) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_RESOLVER_HOOK_RESOLVABLE, rh, candidates); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { rh.filterResolvable(candidates); } } public void invokeResolverHookSingleton( org.osgi.framework.hooks.resolver.ResolverHook rh, BundleCapability singleton, Collection<BundleCapability> collisions) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_RESOLVER_HOOK_SINGLETON, rh, singleton, collisions); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { rh.filterSingletonCollisions(singleton, collisions); } } public void invokeResolverHookMatches( org.osgi.framework.hooks.resolver.ResolverHook rh, BundleRequirement req, Collection<BundleCapability> candidates) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_RESOLVER_HOOK_MATCHES, rh, req, candidates); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { rh.filterMatches(req, candidates); } } public void invokeResolverHookEnd( org.osgi.framework.hooks.resolver.ResolverHook rh) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_RESOLVER_HOOK_END, rh); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { rh.end(); } } public void invokeWovenClassListener( org.osgi.framework.hooks.weaving.WovenClassListener wcl, org.osgi.framework.hooks.weaving.WovenClass wc) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_WOVEN_CLASS_LISTENER, wcl, wc); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { wcl.modified(wc); } } public <T> T run(PrivilegedAction<T> action) { if (System.getSecurityManager() != null) { return AccessController.doPrivileged(action); } else { return action.run(); } } public <T> T run(PrivilegedExceptionAction<T> action) throws Exception { if (System.getSecurityManager() != null) { try { return AccessController.doPrivileged(action); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return action.run(); } } public String getCanonicalPath(File dataFile) throws IOException { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_CANONICAL_PATH, dataFile); try { return (String) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw (IOException) e.getException(); } } else { return dataFile.getCanonicalPath(); } } public Object createProxy(ClassLoader classLoader, Class<?>[] interfaces, InvocationHandler handler) { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.CREATE_PROXY, classLoader, interfaces, handler); try { return AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw (RuntimeException) e.getException(); } } else { return Proxy.newProxyInstance(classLoader, interfaces, handler); } } public long getLastModified(File file) { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.LAST_MODIFIED, file); try { return (Long) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw (RuntimeException) e.getException(); } } else { return file.lastModified(); } } private static class Actions implements PrivilegedExceptionAction { public static final int INITIALIZE_CONTEXT_ACTION = 0; public static final int ADD_EXTENSION_URL_ACTION = 1; public static final int CREATE_TMPFILE_ACTION = 2; public static final int CREATE_URL_ACTION = 3; public static final int CREATE_URL_WITH_CONTEXT_ACTION = 4; public static final int DELETE_FILE_ACTION = 5; public static final int EXEC_ACTION = 6; public static final int FILE_EXISTS_ACTION = 7; public static final int FILE_IS_DIRECTORY_ACTION = 8; public static final int FOR_NAME_ACTION = 9; public static final int GET_ABSOLUTE_PATH_ACTION = 10; public static final int GET_CONSTRUCTOR_ACTION = 11; public static final int GET_DECLARED_CONSTRUCTOR_ACTION = 12; public static final int GET_DECLARED_METHOD_ACTION = 13; public static final int GET_FIELD_ACTION = 14; public static final int GET_FILE_INPUT_ACTION = 15; public static final int GET_FILE_OUTPUT_ACTION = 16; public static final int TO_URI_ACTION = 17; public static final int GET_METHOD_ACTION = 18; public static final int GET_POLICY_ACTION = 19; public static final int GET_PROPERTY_ACTION = 20; public static final int GET_PARENT_CLASS_LOADER_ACTION = 21; public static final int GET_SYSTEM_CLASS_LOADER_ACTION = 22; public static final int GET_URL_INPUT_ACTION = 23; public static final int INVOKE_CONSTRUCTOR_ACTION = 24; public static final int INVOKE_DIRECTMETHOD_ACTION = 25; public static final int INVOKE_METHOD_ACTION = 26; public static final int LIST_DIRECTORY_ACTION = 27; public static final int MAKE_DIRECTORIES_ACTION = 28; public static final int MAKE_DIRECTORY_ACTION = 29; public static final int OPEN_ZIPFILE_ACTION = 30; public static final int OPEN_URLCONNECTION_ACTION = 31; public static final int RENAME_FILE_ACTION = 32; public static final int SET_ACCESSIBLE_ACTION = 33; public static final int START_ACTIVATOR_ACTION = 34; public static final int STOP_ACTIVATOR_ACTION = 35; public static final int SWAP_FIELD_ACTION = 36; public static final int SYSTEM_EXIT_ACTION = 37; public static final int FLUSH_FIELD_ACTION = 38; public static final int GET_CLASS_LOADER_ACTION = 39; public static final int INVOKE_BUNDLE_FIND_HOOK = 40; public static final int INVOKE_BUNDLE_EVENT_HOOK = 41; public static final int INVOKE_WEAVING_HOOK = 42; public static final int INVOKE_SERVICE_EVENT_HOOK = 43; public static final int INVOKE_SERVICE_FIND_HOOK = 44; public static final int INVOKE_SERVICE_LISTENER_HOOK_ADDED = 45; public static final int INVOKE_SERVICE_LISTENER_HOOK_REMOVED = 46; public static final int INVOKE_SERVICE_EVENT_LISTENER_HOOK = 47; public static final int INVOKE_RESOLVER_HOOK_FACTORY = 48; public static final int INVOKE_RESOLVER_HOOK_RESOLVABLE = 49; public static final int INVOKE_RESOLVER_HOOK_SINGLETON = 50; public static final int INVOKE_RESOLVER_HOOK_MATCHES = 51; public static final int INVOKE_RESOLVER_HOOK_END = 52; public static final int INVOKE_BUNDLE_COLLISION_HOOK = 53; public static final int OPEN_JARFILE_ACTION = 54; public static final int DELETE_FILEONEXIT_ACTION = 55; public static final int INVOKE_WOVEN_CLASS_LISTENER = 56; public static final int GET_CANONICAL_PATH = 57; public static final int CREATE_PROXY = 58; public static final int LAST_MODIFIED = 59; public static final int FILE_IS_FILE_ACTION = 60; public static final int GET_FILE_CHANNEL_ACTION = 61; private static final int GET_INPUT_ACTION = 62; private static final int GET_OUTPUT_ACTION = 63; private int m_action = -1; private Object m_arg1 = null; private Object m_arg2 = null; private Object m_arg3 = null; private Object m_arg4 = null; private Object m_arg5 = null; private Object m_arg6 = null; public void set(int action) { m_action = action; } public void set(int action, Object arg1) { m_action = action; m_arg1 = arg1; } public void set(int action, Object arg1, Object arg2) { m_action = action; m_arg1 = arg1; m_arg2 = arg2; } public void set(int action, Object arg1, Object arg2, Object arg3) { m_action = action; m_arg1 = arg1; m_arg2 = arg2; m_arg3 = arg3; } public void set(int action, Object arg1, Object arg2, Object arg3, Object arg4) { m_action = action; m_arg1 = arg1; m_arg2 = arg2; m_arg3 = arg3; m_arg4 = arg4; } public void set(int action, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5) { m_action = action; m_arg1 = arg1; m_arg2 = arg2; m_arg3 = arg3; m_arg4 = arg4; m_arg5 = arg5; } public void set(int action, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6) { m_action = action; m_arg1 = arg1; m_arg2 = arg2; m_arg3 = arg3; m_arg4 = arg4; m_arg5 = arg5; m_arg6 = arg6; } private void unset() { m_action = -1; m_arg1 = null; m_arg2 = null; m_arg3 = null; m_arg4 = null; m_arg5 = null; m_arg6 = null; } public Object run() throws Exception { int action = m_action; Object arg1 = m_arg1; Object arg2 = m_arg2; Object arg3 = m_arg3; Object arg4 = m_arg4; Object arg5 = m_arg5; Object arg6 = m_arg6; unset(); switch (action) { case INITIALIZE_CONTEXT_ACTION: return AccessController.getContext(); case ADD_EXTENSION_URL_ACTION: Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] {URL.class}); getAccessor(URLClassLoader.class).accept(new AccessibleObject[]{addURL}); addURL.invoke(arg2, new Object[]{arg1}); return null; case CREATE_TMPFILE_ACTION: return File.createTempFile((String) arg1, (String) arg2, (File) arg3); case CREATE_URL_ACTION: return new URL((String) arg1, (String) arg2, ((Integer) arg3).intValue(), (String) arg4, (URLStreamHandler) arg5); case CREATE_URL_WITH_CONTEXT_ACTION: return new URL((URL) arg1, (String) arg2, (URLStreamHandler) arg3); case DELETE_FILE_ACTION: return ((File) arg1).delete() ? Boolean.TRUE : Boolean.FALSE; case EXEC_ACTION: return Runtime.getRuntime().exec((String) arg1); case FILE_EXISTS_ACTION: return ((File) arg1).exists() ? Boolean.TRUE : Boolean.FALSE; case FILE_IS_DIRECTORY_ACTION: return ((File) arg1).isDirectory() ? Boolean.TRUE : Boolean.FALSE; case FOR_NAME_ACTION: return (arg2 == null) ? Class.forName((String) arg1) : Class.forName((String) arg1, true, (ClassLoader) arg2); case GET_ABSOLUTE_PATH_ACTION: return ((File) arg1).getAbsolutePath(); case GET_CONSTRUCTOR_ACTION: return ((Class) arg1).getConstructor((Class[]) arg2); case GET_DECLARED_CONSTRUCTOR_ACTION: return ((Class) arg1).getDeclaredConstructor((Class[]) arg2); case GET_DECLARED_METHOD_ACTION: return ((Class) arg1).getDeclaredMethod((String) arg2, (Class[]) arg3); case GET_FIELD_ACTION: Field field = ((Class) arg1).getDeclaredField((String) arg2); getAccessor((Class) arg1).accept(new AccessibleObject[]{field}); return field.get(arg3); case GET_FILE_INPUT_ACTION: return new FileInputStream((File) arg1); case GET_FILE_OUTPUT_ACTION: return new FileOutputStream((File) arg1); case TO_URI_ACTION: return ((File) arg1).toURI(); case GET_METHOD_ACTION: return ((Class) arg1).getMethod((String) arg2, (Class[]) arg3); case GET_POLICY_ACTION: return Policy.getPolicy(); case GET_PROPERTY_ACTION: return System.getProperty((String) arg1, (String) arg2); case GET_PARENT_CLASS_LOADER_ACTION: return ((ClassLoader) arg1).getParent(); case GET_SYSTEM_CLASS_LOADER_ACTION: return ClassLoader.getSystemClassLoader(); case GET_URL_INPUT_ACTION: return ((URLConnection) arg1).getInputStream(); case INVOKE_CONSTRUCTOR_ACTION: return ((Constructor) arg1).newInstance((Object[]) arg2); case INVOKE_DIRECTMETHOD_ACTION: return ((Method) arg1).invoke(arg2, (Object[]) arg3); case INVOKE_METHOD_ACTION: getAccessor(((Method) arg1).getDeclaringClass()).accept(new AccessibleObject[]{(Method) arg1}); return ((Method) arg1).invoke(arg2, (Object[]) arg3); case LIST_DIRECTORY_ACTION: return ((File) arg1).listFiles(); case MAKE_DIRECTORIES_ACTION: return ((File) arg1).mkdirs() ? Boolean.TRUE : Boolean.FALSE; case MAKE_DIRECTORY_ACTION: return ((File) arg1).mkdir() ? Boolean.TRUE : Boolean.FALSE; case OPEN_ZIPFILE_ACTION: return new ZipFile((File) arg1); case OPEN_URLCONNECTION_ACTION: return ((URL) arg1).openConnection(); case RENAME_FILE_ACTION: return ((File) arg1).renameTo((File) arg2) ? Boolean.TRUE : Boolean.FALSE; case SET_ACCESSIBLE_ACTION: getAccessor(((Executable) arg1).getDeclaringClass()).accept(new AccessibleObject[]{(Executable) arg1}); return null; case START_ACTIVATOR_ACTION: ((BundleActivator) arg1).start((BundleContext) arg2); return null; case STOP_ACTIVATOR_ACTION: ((BundleActivator) arg1).stop((BundleContext) arg2); return null; case SWAP_FIELD_ACTION: return _swapStaticFieldIfNotClass((Class) arg1, (Class) arg2, (Class) arg3, (String) arg4); case SYSTEM_EXIT_ACTION: System.exit(((Integer) arg1).intValue()); case FLUSH_FIELD_ACTION: _flush(((Class) arg1), arg2); return null; case GET_CLASS_LOADER_ACTION: return ((Class) arg1).getClassLoader(); case INVOKE_BUNDLE_FIND_HOOK: ((org.osgi.framework.hooks.bundle.FindHook) arg1).find( (BundleContext) arg2, (Collection<Bundle>) arg3); return null; case INVOKE_BUNDLE_EVENT_HOOK: ((org.osgi.framework.hooks.bundle.EventHook) arg1).event( (BundleEvent) arg2, (Collection<BundleContext>) arg3); return null; case INVOKE_WEAVING_HOOK: ((org.osgi.framework.hooks.weaving.WeavingHook) arg1).weave( (org.osgi.framework.hooks.weaving.WovenClass) arg2); return null; case INVOKE_SERVICE_EVENT_HOOK: ((org.osgi.framework.hooks.service.EventHook) arg1).event( (ServiceEvent) arg2, (Collection<BundleContext>) arg3); return null; case INVOKE_SERVICE_FIND_HOOK: ((org.osgi.framework.hooks.service.FindHook) arg1).find( (BundleContext) arg2, (String) arg3, (String) arg4, ((Boolean) arg5).booleanValue(), (Collection<ServiceReference<?>>) arg6); return null; case INVOKE_SERVICE_LISTENER_HOOK_ADDED: ((org.osgi.framework.hooks.service.ListenerHook) arg1).added( (Collection<ListenerHook.ListenerInfo>) arg2); return null; case INVOKE_SERVICE_LISTENER_HOOK_REMOVED: ((org.osgi.framework.hooks.service.ListenerHook) arg1).removed( (Collection<ListenerHook.ListenerInfo>) arg2); return null; case INVOKE_SERVICE_EVENT_LISTENER_HOOK: ((org.osgi.framework.hooks.service.EventListenerHook) arg1).event( (ServiceEvent) arg2, (Map<BundleContext, Collection<ListenerHook.ListenerInfo>>) arg3); return null; case INVOKE_RESOLVER_HOOK_FACTORY: return ((org.osgi.framework.hooks.resolver.ResolverHookFactory) arg1).begin( (Collection<BundleRevision>) arg2); case INVOKE_RESOLVER_HOOK_RESOLVABLE: ((org.osgi.framework.hooks.resolver.ResolverHook) arg1).filterResolvable( (Collection<BundleRevision>) arg2); return null; case INVOKE_RESOLVER_HOOK_SINGLETON: ((org.osgi.framework.hooks.resolver.ResolverHook) arg1) .filterSingletonCollisions( (BundleCapability) arg2, (Collection<BundleCapability>) arg3); return null; case INVOKE_RESOLVER_HOOK_MATCHES: ((org.osgi.framework.hooks.resolver.ResolverHook) arg1).filterMatches( (BundleRequirement) arg2, (Collection<BundleCapability>) arg3); return null; case INVOKE_RESOLVER_HOOK_END: ((org.osgi.framework.hooks.resolver.ResolverHook) arg1).end(); return null; case INVOKE_BUNDLE_COLLISION_HOOK: ((org.osgi.framework.hooks.bundle.CollisionHook) arg1).filterCollisions((Integer) arg2, (Bundle) arg3, (Collection<Bundle>) arg4); return null; case OPEN_JARFILE_ACTION: return new JarFile((File) arg1); case DELETE_FILEONEXIT_ACTION: ((File) arg1).deleteOnExit(); return null; case INVOKE_WOVEN_CLASS_LISTENER: ((org.osgi.framework.hooks.weaving.WovenClassListener) arg1).modified( (org.osgi.framework.hooks.weaving.WovenClass) arg2); return null; case GET_CANONICAL_PATH: return ((File) arg1).getCanonicalPath(); case CREATE_PROXY: return Proxy.newProxyInstance((ClassLoader)arg1, (Class<?>[])arg2, (InvocationHandler) arg3); case LAST_MODIFIED: return ((File) arg1).lastModified(); case FILE_IS_FILE_ACTION: return ((File) arg1).isFile() ? Boolean.TRUE : Boolean.FALSE; case GET_FILE_CHANNEL_ACTION: return FileChannel.open(((File) arg1).toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); case GET_INPUT_ACTION: return Files.newInputStream(((File) arg1).toPath()); case GET_OUTPUT_ACTION: return Files.newOutputStream(((File) arg1).toPath()); } return null; } } }
framework/src/main/java/org/apache/felix/framework/util/SecureAction.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.felix.framework.util; import java.io.*; import java.lang.reflect.*; import java.lang.reflect.Proxy; import java.net.*; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.security.*; import java.util.Collection; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import java.util.function.Consumer; import java.util.jar.JarFile; import java.util.zip.ZipFile; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceReference; import org.osgi.framework.hooks.resolver.ResolverHook; import org.osgi.framework.hooks.service.ListenerHook; import org.osgi.framework.wiring.BundleCapability; import org.osgi.framework.wiring.BundleRequirement; import org.osgi.framework.wiring.BundleRevision; /** * <p> * This is a utility class to centralize all action that should be performed * in a <tt>doPrivileged()</tt> block. To perform a secure action, simply * create an instance of this class and use the specific method to perform * the desired action. When an instance is created, this class will capture * the security context and will then use that context when checking for * permission to perform the action. Instances of this class should not be * passed around since they may grant the receiver a capability to perform * privileged actions. * </p> **/ public class SecureAction { private static final byte[] accessor; static { byte[] result; try (ByteArrayOutputStream output = new ByteArrayOutputStream(); InputStream input = SecureAction.class.getResourceAsStream("accessor.bytes")) { byte[] buffer = new byte[input.available() > 0 ? input.available() : 1024]; for (int i = input.read(buffer); i != -1; i = input.read(buffer)) { output.write(buffer, 0, i); } result = output.toByteArray(); } catch (Throwable t) { t.printStackTrace(); result = new byte[0]; } accessor = result; getAccessor(URL.class); } private static final ThreadLocal m_actions = new ThreadLocal() { public Object initialValue() { return new Actions(); } }; protected static transient int BUFSIZE = 4096; private AccessControlContext m_acc = null; public SecureAction() { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INITIALIZE_CONTEXT_ACTION, null); m_acc = (AccessControlContext) AccessController.doPrivileged(actions); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { m_acc = AccessController.getContext(); } } public String getSystemProperty(String name, String def) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_PROPERTY_ACTION, name, def); return (String) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return System.getProperty(name, def); } } public ClassLoader getParentClassLoader(ClassLoader loader) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_PARENT_CLASS_LOADER_ACTION, loader); return (ClassLoader) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return loader.getParent(); } } public ClassLoader getSystemClassLoader() { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_SYSTEM_CLASS_LOADER_ACTION); return (ClassLoader) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return ClassLoader.getSystemClassLoader(); } } public ClassLoader getClassLoader(Class clazz) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_CLASS_LOADER_ACTION, clazz); return (ClassLoader) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return clazz.getClassLoader(); } } public Class forName(String name, ClassLoader classloader) throws ClassNotFoundException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.FOR_NAME_ACTION, name, classloader); return (Class) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof ClassNotFoundException) { throw (ClassNotFoundException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else if (classloader != null) { return Class.forName(name, true, classloader); } else { return Class.forName(name); } } public URL createURL(String protocol, String host, int port, String path, URLStreamHandler handler) throws MalformedURLException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.CREATE_URL_ACTION, protocol, host, new Integer(port), path, handler); return (URL) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof MalformedURLException) { throw (MalformedURLException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return new URL(protocol, host, port, path, handler); } } public URL createURL(URL context, String spec, URLStreamHandler handler) throws MalformedURLException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.CREATE_URL_WITH_CONTEXT_ACTION, context, spec, handler); return (URL) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof MalformedURLException) { throw (MalformedURLException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return new URL(context, spec, handler); } } public Process exec(String command) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.EXEC_ACTION, command); return (Process) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return Runtime.getRuntime().exec(command); } } public String getAbsolutePath(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_ABSOLUTE_PATH_ACTION, file); return (String) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.getAbsolutePath(); } } public boolean fileExists(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.FILE_EXISTS_ACTION, file); return ((Boolean) AccessController.doPrivileged(actions, m_acc)) .booleanValue(); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.exists(); } } public boolean isFile(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.FILE_IS_FILE_ACTION, file); return ((Boolean) AccessController.doPrivileged(actions, m_acc)) .booleanValue(); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.isFile(); } } public boolean isFileDirectory(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.FILE_IS_DIRECTORY_ACTION, file); return ((Boolean) AccessController.doPrivileged(actions, m_acc)) .booleanValue(); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.isDirectory(); } } public boolean mkdir(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.MAKE_DIRECTORY_ACTION, file); return ((Boolean) AccessController.doPrivileged(actions, m_acc)) .booleanValue(); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.mkdir(); } } public boolean mkdirs(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.MAKE_DIRECTORIES_ACTION, file); return ((Boolean) AccessController.doPrivileged(actions, m_acc)) .booleanValue(); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.mkdirs(); } } public File[] listDirectory(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.LIST_DIRECTORY_ACTION, file); return (File[]) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.listFiles(); } } public boolean renameFile(File oldFile, File newFile) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.RENAME_FILE_ACTION, oldFile, newFile); return ((Boolean) AccessController.doPrivileged(actions, m_acc)) .booleanValue(); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return oldFile.renameTo(newFile); } } public InputStream getInputStream(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_INPUT_ACTION, file); return (InputStream) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return Files.newInputStream(file.toPath()); } } public OutputStream getOutputStream(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_OUTPUT_ACTION, file); return (OutputStream) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return Files.newOutputStream(file.toPath()); } } public FileInputStream getFileInputStream(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_FILE_INPUT_ACTION, file); return (FileInputStream) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return new FileInputStream(file); } } public FileOutputStream getFileOutputStream(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_FILE_OUTPUT_ACTION, file); return (FileOutputStream) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return new FileOutputStream(file); } } public FileChannel getFileChannel(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_FILE_CHANNEL_ACTION, file); return (FileChannel) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return FileChannel.open(file.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); } } public URI toURI(File file) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.TO_URI_ACTION, file); return (URI) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return file.toURI(); } } public InputStream getURLConnectionInputStream(URLConnection conn) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_URL_INPUT_ACTION, conn); return (InputStream) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return conn.getInputStream(); } } public boolean deleteFile(File target) { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.DELETE_FILE_ACTION, target); return ((Boolean) AccessController.doPrivileged(actions, m_acc)) .booleanValue(); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return target.delete(); } } public File createTempFile(String prefix, String suffix, File dir) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.CREATE_TMPFILE_ACTION, prefix, suffix, dir); return (File) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return File.createTempFile(prefix, suffix, dir); } } public void deleteFileOnExit(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.DELETE_FILEONEXIT_ACTION, file); AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { file.deleteOnExit(); } } public URLConnection openURLConnection(URL url) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.OPEN_URLCONNECTION_ACTION, url); return (URLConnection) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return url.openConnection(); } } public ZipFile openZipFile(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.OPEN_ZIPFILE_ACTION, file); return (ZipFile) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return new ZipFile(file); } } public JarFile openJarFile(File file) throws IOException { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.OPEN_JARFILE_ACTION, file); return (JarFile) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } throw (RuntimeException) ex.getException(); } } else { return new JarFile(file); } } public void startActivator(BundleActivator activator, BundleContext context) throws Exception { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.START_ACTIVATOR_ACTION, activator, context); AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw ex.getException(); } } else { activator.start(context); } } public void stopActivator(BundleActivator activator, BundleContext context) throws Exception { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.STOP_ACTIVATOR_ACTION, activator, context); AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw ex.getException(); } } else { activator.stop(context); } } public Policy getPolicy() { if (System.getSecurityManager() != null) { try { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_POLICY_ACTION, null); return (Policy) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException ex) { throw (RuntimeException) ex.getException(); } } else { return Policy.getPolicy(); } } public void addURLToURLClassLoader(URL extension, ClassLoader loader) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.ADD_EXTENSION_URL_ACTION, extension, loader); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] {URL.class}); getAccessor(URLClassLoader.class).accept(new AccessibleObject[]{addURL}); addURL.invoke(loader, new Object[]{extension}); } } public Constructor getConstructor(Class target, Class[] types) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_CONSTRUCTOR_ACTION, target, types); try { return (Constructor) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return target.getConstructor(types); } } public Constructor getDeclaredConstructor(Class target, Class[] types) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_DECLARED_CONSTRUCTOR_ACTION, target, types); try { return (Constructor) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return target.getDeclaredConstructor(types); } } public Method getMethod(Class target, String method, Class[] types) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_METHOD_ACTION, target, method, types); try { return (Method) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return target.getMethod(method, types); } } public Method getDeclaredMethod(Class target, String method, Class[] types) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_DECLARED_METHOD_ACTION, target, method, types); try { return (Method) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return target.getDeclaredMethod(method, types); } } public void setAccesssible(Executable ao) { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.SET_ACCESSIBLE_ACTION, ao); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw (RuntimeException) e.getException(); } } else { getAccessor(ao.getDeclaringClass()).accept(new AccessibleObject[]{ao}); } } public Object invoke(Method method, Object target, Object[] params) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_METHOD_ACTION, method, target, params); try { return AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { getAccessor(method.getDeclaringClass()).accept(new AccessibleObject[]{method}); return method.invoke(target, params); } } public Object invokeDirect(Method method, Object target, Object[] params) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_DIRECTMETHOD_ACTION, method, target, params); try { return AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return method.invoke(target, params); } } public Object invoke(Constructor constructor, Object[] params) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_CONSTRUCTOR_ACTION, constructor, params); try { return AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return constructor.newInstance(params); } } public Object getDeclaredField(Class targetClass, String name, Object target) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_FIELD_ACTION, targetClass, name, target); try { return AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { Field field = targetClass.getDeclaredField(name); getAccessor(targetClass).accept(new AccessibleObject[]{field}); return field.get(target); } } public Object swapStaticFieldIfNotClass(Class targetClazz, Class targetType, Class condition, String lockName) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.SWAP_FIELD_ACTION, targetClazz, targetType, condition, lockName); try { return AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return _swapStaticFieldIfNotClass(targetClazz, targetType, condition, lockName); } } private static volatile Consumer<AccessibleObject[]> m_accessorCache = null; @SuppressWarnings("unchecked") private static Consumer<AccessibleObject[]> getAccessor(Class clazz) { String packageName = clazz.getPackage().getName(); if ("java.net".equals(packageName) || "jdk.internal.loader".equals(packageName)) { if (m_accessorCache == null) { try { // Use reflection on Unsafe to avoid having to compile against it Class<?> unsafeClass = Class.forName("sun.misc.Unsafe"); //$NON-NLS-1$ Field theUnsafe = unsafeClass.getDeclaredField("theUnsafe"); //$NON-NLS-1$ // NOTE: deep reflection is allowed on sun.misc package for java 9. theUnsafe.setAccessible(true); Object unsafe = theUnsafe.get(null); // using defineAnonymousClass here because it seems more simple to get what we need Method defineAnonymousClass = unsafeClass.getMethod("defineAnonymousClass", Class.class, byte[].class, Object[].class); //$NON-NLS-1$ // The bytes stored in a resource to avoid real loading of it (see accessible.src for source). Class<Consumer<AccessibleObject[]>> result = (Class<Consumer<AccessibleObject[]>>) defineAnonymousClass.invoke(unsafe, URL.class, accessor , null); m_accessorCache = result.getConstructor().newInstance(); } catch (Throwable t) { t.printStackTrace(); m_accessorCache = objects -> AccessibleObject.setAccessible(objects, true); } } return m_accessorCache; } else { return objects -> AccessibleObject.setAccessible(objects, true); } } private static Object _swapStaticFieldIfNotClass(Class targetClazz, Class targetType, Class condition, String lockName) throws Exception { Object lock = null; if (lockName != null) { try { Field lockField = targetClazz.getDeclaredField(lockName); getAccessor(targetClazz).accept(new AccessibleObject[]{lockField}); lock = lockField.get(null); } catch (NoSuchFieldException ex) { } } if (lock == null) { lock = targetClazz; } synchronized (lock) { Field[] fields = targetClazz.getDeclaredFields(); getAccessor(targetClazz).accept(fields); Object result = null; for (int i = 0; (i < fields.length) && (result == null); i++) { if (Modifier.isStatic(fields[i].getModifiers()) && (fields[i].getType() == targetType)) { result = fields[i].get(null); if (result != null) { if ((condition == null) || !result.getClass().getName().equals(condition.getName())) { fields[i].set(null, null); } } } } if (result != null) { if ((condition == null) || !result.getClass().getName().equals(condition.getName())) { // reset cache for (int i = 0; i < fields.length; i++) { if (Modifier.isStatic(fields[i].getModifiers()) && (fields[i].getType() == Hashtable.class)) { Hashtable cache = (Hashtable) fields[i].get(null); if (cache != null) { cache.clear(); } } } } return result; } } return null; } public void flush(Class targetClazz, Object lock) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.FLUSH_FIELD_ACTION, targetClazz, lock); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { _flush(targetClazz, lock); } } private static void _flush(Class targetClazz, Object lock) throws Exception { synchronized (lock) { Field[] fields = targetClazz.getDeclaredFields(); getAccessor(targetClazz).accept(fields); // reset cache for (int i = 0; i < fields.length; i++) { if (Modifier.isStatic(fields[i].getModifiers()) && ((fields[i].getType() == Hashtable.class) || (fields[i].getType() == HashMap.class))) { if (fields[i].getType() == Hashtable.class) { Hashtable cache = (Hashtable) fields[i].get(null); if (cache != null) { cache.clear(); } } else { HashMap cache = (HashMap) fields[i].get(null); if (cache != null) { cache.clear(); } } } } } } public void invokeBundleCollisionHook( org.osgi.framework.hooks.bundle.CollisionHook ch, int operationType, Bundle targetBundle, Collection<Bundle> collisionCandidates) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_BUNDLE_COLLISION_HOOK, ch, operationType, targetBundle, collisionCandidates); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { ch.filterCollisions(operationType, targetBundle, collisionCandidates); } } public void invokeBundleFindHook( org.osgi.framework.hooks.bundle.FindHook fh, BundleContext bc, Collection<Bundle> bundles) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_BUNDLE_FIND_HOOK, fh, bc, bundles); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { fh.find(bc, bundles); } } public void invokeBundleEventHook( org.osgi.framework.hooks.bundle.EventHook eh, BundleEvent event, Collection<BundleContext> contexts) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_BUNDLE_EVENT_HOOK, eh, event, contexts); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { eh.event(event, contexts); } } public void invokeWeavingHook( org.osgi.framework.hooks.weaving.WeavingHook wh, org.osgi.framework.hooks.weaving.WovenClass wc) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_WEAVING_HOOK, wh, wc); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { wh.weave(wc); } } public void invokeServiceEventHook( org.osgi.framework.hooks.service.EventHook eh, ServiceEvent event, Collection<BundleContext> contexts) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_SERVICE_EVENT_HOOK, eh, event, contexts); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { eh.event(event, contexts); } } public void invokeServiceFindHook( org.osgi.framework.hooks.service.FindHook fh, BundleContext context, String name, String filter, boolean allServices, Collection<ServiceReference<?>> references) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set( Actions.INVOKE_SERVICE_FIND_HOOK, fh, context, name, filter, (allServices) ? Boolean.TRUE : Boolean.FALSE, references); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { fh.find(context, name, filter, allServices, references); } } public void invokeServiceListenerHookAdded( org.osgi.framework.hooks.service.ListenerHook lh, Collection<ListenerHook.ListenerInfo> listeners) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_SERVICE_LISTENER_HOOK_ADDED, lh, listeners); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { lh.added(listeners); } } public void invokeServiceListenerHookRemoved( org.osgi.framework.hooks.service.ListenerHook lh, Collection<ListenerHook.ListenerInfo> listeners) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_SERVICE_LISTENER_HOOK_REMOVED, lh, listeners); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { lh.removed(listeners); } } public void invokeServiceEventListenerHook( org.osgi.framework.hooks.service.EventListenerHook elh, ServiceEvent event, Map<BundleContext, Collection<ListenerHook.ListenerInfo>> listeners) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_SERVICE_EVENT_LISTENER_HOOK, elh, event, listeners); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { elh.event(event, listeners); } } public ResolverHook invokeResolverHookFactory( org.osgi.framework.hooks.resolver.ResolverHookFactory rhf, Collection<BundleRevision> triggers) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_RESOLVER_HOOK_FACTORY, rhf, triggers); try { return (ResolverHook) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return rhf.begin(triggers); } } public void invokeResolverHookResolvable( org.osgi.framework.hooks.resolver.ResolverHook rh, Collection<BundleRevision> candidates) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_RESOLVER_HOOK_RESOLVABLE, rh, candidates); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { rh.filterResolvable(candidates); } } public void invokeResolverHookSingleton( org.osgi.framework.hooks.resolver.ResolverHook rh, BundleCapability singleton, Collection<BundleCapability> collisions) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_RESOLVER_HOOK_SINGLETON, rh, singleton, collisions); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { rh.filterSingletonCollisions(singleton, collisions); } } public void invokeResolverHookMatches( org.osgi.framework.hooks.resolver.ResolverHook rh, BundleRequirement req, Collection<BundleCapability> candidates) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_RESOLVER_HOOK_MATCHES, rh, req, candidates); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { rh.filterMatches(req, candidates); } } public void invokeResolverHookEnd( org.osgi.framework.hooks.resolver.ResolverHook rh) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_RESOLVER_HOOK_END, rh); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { rh.end(); } } public void invokeWovenClassListener( org.osgi.framework.hooks.weaving.WovenClassListener wcl, org.osgi.framework.hooks.weaving.WovenClass wc) throws Exception { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.INVOKE_WOVEN_CLASS_LISTENER, wcl, wc); try { AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw e.getException(); } } else { wcl.modified(wc); } } public <T> T run(PrivilegedAction<T> action) { if (System.getSecurityManager() != null) { return AccessController.doPrivileged(action); } else { return action.run(); } } public <T> T run(PrivilegedExceptionAction<T> action) throws Exception { if (System.getSecurityManager() != null) { try { return AccessController.doPrivileged(action); } catch (PrivilegedActionException e) { throw e.getException(); } } else { return action.run(); } } public String getCanonicalPath(File dataFile) throws IOException { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.GET_CANONICAL_PATH, dataFile); try { return (String) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw (IOException) e.getException(); } } else { return dataFile.getCanonicalPath(); } } public Object createProxy(ClassLoader classLoader, Class<?>[] interfaces, InvocationHandler handler) { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.CREATE_PROXY, classLoader, interfaces, handler); try { return AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw (RuntimeException) e.getException(); } } else { return Proxy.newProxyInstance(classLoader, interfaces, handler); } } public long getLastModified(File file) { if (System.getSecurityManager() != null) { Actions actions = (Actions) m_actions.get(); actions.set(Actions.LAST_MODIFIED, file); try { return (Long) AccessController.doPrivileged(actions, m_acc); } catch (PrivilegedActionException e) { throw (RuntimeException) e.getException(); } } else { return file.lastModified(); } } private static class Actions implements PrivilegedExceptionAction { public static final int INITIALIZE_CONTEXT_ACTION = 0; public static final int ADD_EXTENSION_URL_ACTION = 1; public static final int CREATE_TMPFILE_ACTION = 2; public static final int CREATE_URL_ACTION = 3; public static final int CREATE_URL_WITH_CONTEXT_ACTION = 4; public static final int DELETE_FILE_ACTION = 5; public static final int EXEC_ACTION = 6; public static final int FILE_EXISTS_ACTION = 7; public static final int FILE_IS_DIRECTORY_ACTION = 8; public static final int FOR_NAME_ACTION = 9; public static final int GET_ABSOLUTE_PATH_ACTION = 10; public static final int GET_CONSTRUCTOR_ACTION = 11; public static final int GET_DECLARED_CONSTRUCTOR_ACTION = 12; public static final int GET_DECLARED_METHOD_ACTION = 13; public static final int GET_FIELD_ACTION = 14; public static final int GET_FILE_INPUT_ACTION = 15; public static final int GET_FILE_OUTPUT_ACTION = 16; public static final int TO_URI_ACTION = 17; public static final int GET_METHOD_ACTION = 18; public static final int GET_POLICY_ACTION = 19; public static final int GET_PROPERTY_ACTION = 20; public static final int GET_PARENT_CLASS_LOADER_ACTION = 21; public static final int GET_SYSTEM_CLASS_LOADER_ACTION = 22; public static final int GET_URL_INPUT_ACTION = 23; public static final int INVOKE_CONSTRUCTOR_ACTION = 24; public static final int INVOKE_DIRECTMETHOD_ACTION = 25; public static final int INVOKE_METHOD_ACTION = 26; public static final int LIST_DIRECTORY_ACTION = 27; public static final int MAKE_DIRECTORIES_ACTION = 28; public static final int MAKE_DIRECTORY_ACTION = 29; public static final int OPEN_ZIPFILE_ACTION = 30; public static final int OPEN_URLCONNECTION_ACTION = 31; public static final int RENAME_FILE_ACTION = 32; public static final int SET_ACCESSIBLE_ACTION = 33; public static final int START_ACTIVATOR_ACTION = 34; public static final int STOP_ACTIVATOR_ACTION = 35; public static final int SWAP_FIELD_ACTION = 36; public static final int SYSTEM_EXIT_ACTION = 37; public static final int FLUSH_FIELD_ACTION = 38; public static final int GET_CLASS_LOADER_ACTION = 39; public static final int INVOKE_BUNDLE_FIND_HOOK = 40; public static final int INVOKE_BUNDLE_EVENT_HOOK = 41; public static final int INVOKE_WEAVING_HOOK = 42; public static final int INVOKE_SERVICE_EVENT_HOOK = 43; public static final int INVOKE_SERVICE_FIND_HOOK = 44; public static final int INVOKE_SERVICE_LISTENER_HOOK_ADDED = 45; public static final int INVOKE_SERVICE_LISTENER_HOOK_REMOVED = 46; public static final int INVOKE_SERVICE_EVENT_LISTENER_HOOK = 47; public static final int INVOKE_RESOLVER_HOOK_FACTORY = 48; public static final int INVOKE_RESOLVER_HOOK_RESOLVABLE = 49; public static final int INVOKE_RESOLVER_HOOK_SINGLETON = 50; public static final int INVOKE_RESOLVER_HOOK_MATCHES = 51; public static final int INVOKE_RESOLVER_HOOK_END = 52; public static final int INVOKE_BUNDLE_COLLISION_HOOK = 53; public static final int OPEN_JARFILE_ACTION = 54; public static final int DELETE_FILEONEXIT_ACTION = 55; public static final int INVOKE_WOVEN_CLASS_LISTENER = 56; public static final int GET_CANONICAL_PATH = 57; public static final int CREATE_PROXY = 58; public static final int LAST_MODIFIED = 59; public static final int FILE_IS_FILE_ACTION = 60; public static final int GET_FILE_CHANNEL_ACTION = 61; private static final int GET_INPUT_ACTION = 62; private static final int GET_OUTPUT_ACTION = 63; private int m_action = -1; private Object m_arg1 = null; private Object m_arg2 = null; private Object m_arg3 = null; private Object m_arg4 = null; private Object m_arg5 = null; private Object m_arg6 = null; public void set(int action) { m_action = action; } public void set(int action, Object arg1) { m_action = action; m_arg1 = arg1; } public void set(int action, Object arg1, Object arg2) { m_action = action; m_arg1 = arg1; m_arg2 = arg2; } public void set(int action, Object arg1, Object arg2, Object arg3) { m_action = action; m_arg1 = arg1; m_arg2 = arg2; m_arg3 = arg3; } public void set(int action, Object arg1, Object arg2, Object arg3, Object arg4) { m_action = action; m_arg1 = arg1; m_arg2 = arg2; m_arg3 = arg3; m_arg4 = arg4; } public void set(int action, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5) { m_action = action; m_arg1 = arg1; m_arg2 = arg2; m_arg3 = arg3; m_arg4 = arg4; m_arg5 = arg5; } public void set(int action, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6) { m_action = action; m_arg1 = arg1; m_arg2 = arg2; m_arg3 = arg3; m_arg4 = arg4; m_arg5 = arg5; m_arg6 = arg6; } private void unset() { m_action = -1; m_arg1 = null; m_arg2 = null; m_arg3 = null; m_arg4 = null; m_arg5 = null; m_arg6 = null; } public Object run() throws Exception { int action = m_action; Object arg1 = m_arg1; Object arg2 = m_arg2; Object arg3 = m_arg3; Object arg4 = m_arg4; Object arg5 = m_arg5; Object arg6 = m_arg6; unset(); switch (action) { case INITIALIZE_CONTEXT_ACTION: return AccessController.getContext(); case ADD_EXTENSION_URL_ACTION: Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] {URL.class}); getAccessor(URLClassLoader.class).accept(new AccessibleObject[]{addURL}); addURL.invoke(arg2, new Object[]{arg1}); return null; case CREATE_TMPFILE_ACTION: return File.createTempFile((String) arg1, (String) arg2, (File) arg3); case CREATE_URL_ACTION: return new URL((String) arg1, (String) arg2, ((Integer) arg3).intValue(), (String) arg4, (URLStreamHandler) arg5); case CREATE_URL_WITH_CONTEXT_ACTION: return new URL((URL) arg1, (String) arg2, (URLStreamHandler) arg3); case DELETE_FILE_ACTION: return ((File) arg1).delete() ? Boolean.TRUE : Boolean.FALSE; case EXEC_ACTION: return Runtime.getRuntime().exec((String) arg1); case FILE_EXISTS_ACTION: return ((File) arg1).exists() ? Boolean.TRUE : Boolean.FALSE; case FILE_IS_DIRECTORY_ACTION: return ((File) arg1).isDirectory() ? Boolean.TRUE : Boolean.FALSE; case FOR_NAME_ACTION: return (arg2 == null) ? Class.forName((String) arg1) : Class.forName((String) arg1, true, (ClassLoader) arg2); case GET_ABSOLUTE_PATH_ACTION: return ((File) arg1).getAbsolutePath(); case GET_CONSTRUCTOR_ACTION: return ((Class) arg1).getConstructor((Class[]) arg2); case GET_DECLARED_CONSTRUCTOR_ACTION: return ((Class) arg1).getDeclaredConstructor((Class[]) arg2); case GET_DECLARED_METHOD_ACTION: return ((Class) arg1).getDeclaredMethod((String) arg2, (Class[]) arg3); case GET_FIELD_ACTION: Field field = ((Class) arg1).getDeclaredField((String) arg2); getAccessor((Class) arg1).accept(new AccessibleObject[]{field}); return field.get(arg3); case GET_FILE_INPUT_ACTION: return new FileInputStream((File) arg1); case GET_FILE_OUTPUT_ACTION: return new FileOutputStream((File) arg1); case TO_URI_ACTION: return ((File) arg1).toURI(); case GET_METHOD_ACTION: return ((Class) arg1).getMethod((String) arg2, (Class[]) arg3); case GET_POLICY_ACTION: return Policy.getPolicy(); case GET_PROPERTY_ACTION: return System.getProperty((String) arg1, (String) arg2); case GET_PARENT_CLASS_LOADER_ACTION: return ((ClassLoader) arg1).getParent(); case GET_SYSTEM_CLASS_LOADER_ACTION: return ClassLoader.getSystemClassLoader(); case GET_URL_INPUT_ACTION: return ((URLConnection) arg1).getInputStream(); case INVOKE_CONSTRUCTOR_ACTION: return ((Constructor) arg1).newInstance((Object[]) arg2); case INVOKE_DIRECTMETHOD_ACTION: return ((Method) arg1).invoke(arg2, (Object[]) arg3); case INVOKE_METHOD_ACTION: getAccessor(((Method) arg1).getDeclaringClass()).accept(new AccessibleObject[]{(Method) arg1}); return ((Method) arg1).invoke(arg2, (Object[]) arg3); case LIST_DIRECTORY_ACTION: return ((File) arg1).listFiles(); case MAKE_DIRECTORIES_ACTION: return ((File) arg1).mkdirs() ? Boolean.TRUE : Boolean.FALSE; case MAKE_DIRECTORY_ACTION: return ((File) arg1).mkdir() ? Boolean.TRUE : Boolean.FALSE; case OPEN_ZIPFILE_ACTION: return new ZipFile((File) arg1); case OPEN_URLCONNECTION_ACTION: return ((URL) arg1).openConnection(); case RENAME_FILE_ACTION: return ((File) arg1).renameTo((File) arg2) ? Boolean.TRUE : Boolean.FALSE; case SET_ACCESSIBLE_ACTION: getAccessor(((Executable) arg1).getDeclaringClass()).accept(new AccessibleObject[]{(Executable) arg1}); return null; case START_ACTIVATOR_ACTION: ((BundleActivator) arg1).start((BundleContext) arg2); return null; case STOP_ACTIVATOR_ACTION: ((BundleActivator) arg1).stop((BundleContext) arg2); return null; case SWAP_FIELD_ACTION: return _swapStaticFieldIfNotClass((Class) arg1, (Class) arg2, (Class) arg3, (String) arg4); case SYSTEM_EXIT_ACTION: System.exit(((Integer) arg1).intValue()); case FLUSH_FIELD_ACTION: _flush(((Class) arg1), arg2); return null; case GET_CLASS_LOADER_ACTION: return ((Class) arg1).getClassLoader(); case INVOKE_BUNDLE_FIND_HOOK: ((org.osgi.framework.hooks.bundle.FindHook) arg1).find( (BundleContext) arg2, (Collection<Bundle>) arg3); return null; case INVOKE_BUNDLE_EVENT_HOOK: ((org.osgi.framework.hooks.bundle.EventHook) arg1).event( (BundleEvent) arg2, (Collection<BundleContext>) arg3); return null; case INVOKE_WEAVING_HOOK: ((org.osgi.framework.hooks.weaving.WeavingHook) arg1).weave( (org.osgi.framework.hooks.weaving.WovenClass) arg2); return null; case INVOKE_SERVICE_EVENT_HOOK: ((org.osgi.framework.hooks.service.EventHook) arg1).event( (ServiceEvent) arg2, (Collection<BundleContext>) arg3); return null; case INVOKE_SERVICE_FIND_HOOK: ((org.osgi.framework.hooks.service.FindHook) arg1).find( (BundleContext) arg2, (String) arg3, (String) arg4, ((Boolean) arg5).booleanValue(), (Collection<ServiceReference<?>>) arg6); return null; case INVOKE_SERVICE_LISTENER_HOOK_ADDED: ((org.osgi.framework.hooks.service.ListenerHook) arg1).added( (Collection<ListenerHook.ListenerInfo>) arg2); return null; case INVOKE_SERVICE_LISTENER_HOOK_REMOVED: ((org.osgi.framework.hooks.service.ListenerHook) arg1).removed( (Collection<ListenerHook.ListenerInfo>) arg2); return null; case INVOKE_SERVICE_EVENT_LISTENER_HOOK: ((org.osgi.framework.hooks.service.EventListenerHook) arg1).event( (ServiceEvent) arg2, (Map<BundleContext, Collection<ListenerHook.ListenerInfo>>) arg3); return null; case INVOKE_RESOLVER_HOOK_FACTORY: return ((org.osgi.framework.hooks.resolver.ResolverHookFactory) arg1).begin( (Collection<BundleRevision>) arg2); case INVOKE_RESOLVER_HOOK_RESOLVABLE: ((org.osgi.framework.hooks.resolver.ResolverHook) arg1).filterResolvable( (Collection<BundleRevision>) arg2); return null; case INVOKE_RESOLVER_HOOK_SINGLETON: ((org.osgi.framework.hooks.resolver.ResolverHook) arg1) .filterSingletonCollisions( (BundleCapability) arg2, (Collection<BundleCapability>) arg3); return null; case INVOKE_RESOLVER_HOOK_MATCHES: ((org.osgi.framework.hooks.resolver.ResolverHook) arg1).filterMatches( (BundleRequirement) arg2, (Collection<BundleCapability>) arg3); return null; case INVOKE_RESOLVER_HOOK_END: ((org.osgi.framework.hooks.resolver.ResolverHook) arg1).end(); return null; case INVOKE_BUNDLE_COLLISION_HOOK: ((org.osgi.framework.hooks.bundle.CollisionHook) arg1).filterCollisions((Integer) arg2, (Bundle) arg3, (Collection<Bundle>) arg4); return null; case OPEN_JARFILE_ACTION: return new JarFile((File) arg1); case DELETE_FILEONEXIT_ACTION: ((File) arg1).deleteOnExit(); return null; case INVOKE_WOVEN_CLASS_LISTENER: ((org.osgi.framework.hooks.weaving.WovenClassListener) arg1).modified( (org.osgi.framework.hooks.weaving.WovenClass) arg2); return null; case GET_CANONICAL_PATH: return ((File) arg1).getCanonicalPath(); case CREATE_PROXY: return Proxy.newProxyInstance((ClassLoader)arg1, (Class<?>[])arg2, (InvocationHandler) arg3); case LAST_MODIFIED: return ((File) arg1).lastModified(); case FILE_IS_FILE_ACTION: return ((File) arg1).isFile() ? Boolean.TRUE : Boolean.FALSE; case GET_FILE_CHANNEL_ACTION: return FileChannel.open(((File) arg1).toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); case GET_INPUT_ACTION: return Files.newInputStream(((File) arg1).toPath()); case GET_OUTPUT_ACTION: return Files.newOutputStream(((File) arg1).toPath()); } return null; } } }
FELIX-6430: fix usage of unsave (#80)
framework/src/main/java/org/apache/felix/framework/util/SecureAction.java
FELIX-6430: fix usage of unsave (#80)
<ide><path>ramework/src/main/java/org/apache/felix/framework/util/SecureAction.java <ide> */ <ide> package org.apache.felix.framework.util; <ide> <del>import java.io.*; <del>import java.lang.reflect.*; <add>import java.io.ByteArrayOutputStream; <add>import java.io.File; <add>import java.io.FileInputStream; <add>import java.io.FileOutputStream; <add>import java.io.IOException; <add>import java.io.InputStream; <add>import java.io.OutputStream; <add>import java.lang.invoke.MethodHandles; <add>import java.lang.reflect.AccessibleObject; <add>import java.lang.reflect.Array; <add>import java.lang.reflect.Constructor; <add>import java.lang.reflect.Executable; <add>import java.lang.reflect.Field; <add>import java.lang.reflect.InvocationHandler; <add>import java.lang.reflect.Method; <add>import java.lang.reflect.Modifier; <ide> import java.lang.reflect.Proxy; <del>import java.net.*; <add>import java.net.MalformedURLException; <add>import java.net.URI; <add>import java.net.URL; <add>import java.net.URLClassLoader; <add>import java.net.URLConnection; <add>import java.net.URLStreamHandler; <ide> import java.nio.channels.FileChannel; <ide> import java.nio.file.Files; <ide> import java.nio.file.StandardOpenOption; <del>import java.security.*; <add>import java.security.AccessControlContext; <add>import java.security.AccessController; <add>import java.security.Policy; <add>import java.security.PrivilegedAction; <add>import java.security.PrivilegedActionException; <add>import java.security.PrivilegedExceptionAction; <ide> import java.util.Collection; <ide> import java.util.HashMap; <ide> import java.util.Hashtable; <ide> // NOTE: deep reflection is allowed on sun.misc package for java 9. <ide> theUnsafe.setAccessible(true); <ide> Object unsafe = theUnsafe.get(null); <del> // using defineAnonymousClass here because it seems more simple to get what we need <del> Method defineAnonymousClass = unsafeClass.getMethod("defineAnonymousClass", Class.class, byte[].class, Object[].class); //$NON-NLS-1$ <del> // The bytes stored in a resource to avoid real loading of it (see accessible.src for source). <del> <del> Class<Consumer<AccessibleObject[]>> result = <del> (Class<Consumer<AccessibleObject[]>>) <del> defineAnonymousClass.invoke(unsafe, URL.class, accessor , null); <add> Class<Consumer<AccessibleObject[]>> result; <add> try { <add> Method defineAnonymousClass = unsafeClass.getMethod("defineAnonymousClass", Class.class, byte[].class, Object[].class); //$NON-NLS-1$ <add> result = (Class<Consumer<AccessibleObject[]>>) defineAnonymousClass.invoke(unsafe, URL.class, accessor , null);; <add> } <add> catch (NoSuchMethodException ex) <add> { <add> long offset = (long) unsafeClass.getMethod("staticFieldOffset", Field.class) <add> .invoke(unsafe, MethodHandles.Lookup.class.getDeclaredField("IMPL_LOOKUP")); <add> <add> MethodHandles.Lookup lookup = (MethodHandles.Lookup) unsafeClass.getMethod("getObject", Object.class, long.class) <add> .invoke(unsafe, MethodHandles.Lookup.class, offset); <add> lookup = lookup.in(URL.class); <add> Class<?> classOption = Class.forName("java.lang.invoke.MethodHandles$Lookup$ClassOption"); //$NON-NLS-1$ <add> Object classOptions = Array.newInstance(classOption, 0); <add> Method defineHiddenClass = MethodHandles.Lookup.class.getMethod("defineHiddenClass", byte[].class, boolean.class, //$NON-NLS-1$ <add> classOptions.getClass()); <add> lookup = (MethodHandles.Lookup) defineHiddenClass.invoke(lookup, accessor, Boolean.FALSE, classOptions); <add> result = (Class<Consumer<AccessibleObject[]>>) lookup.lookupClass(); <add> } <ide> m_accessorCache = result.getConstructor().newInstance(); <ide> } <ide> catch (Throwable t)
Java
apache-2.0
error: pathspec 'src/org/ensembl/healthcheck/testcase/eg_core/SchemaPatchesApplied.java' did not match any file(s) known to git
b3a8ecbba4ece3809ebb3071669aa7b9507ee5b7
1
Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck
package org.ensembl.healthcheck.testcase.eg_core; import java.sql.Connection; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.DatabaseServer; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.SystemCommand; import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase; import org.ensembl.healthcheck.util.ActionAppendable; public class SchemaPatchesApplied extends SingleDatabaseTestCase { protected boolean passes; public boolean isPasses() { return passes; } public void setPasses(boolean passes) { this.passes = passes; } public boolean run(DatabaseRegistryEntry dbr) { setPasses(true); final String schemaPatchScript = "./perlcode/ensembl/misc-scripts/schema_patcher.pl"; SystemCommand systemCommand = new SystemCommand(); // If mysqldiff can't be found, the test can terminate right away. // if (!systemCommand.checkCanExecute(schemaPatchScript)) { ReportManager.problem(this, (Connection) null, "Can't find "+ schemaPatchScript +"! " + this.getShortTestName() + " relies on this program to " + "find missing patches.\n" ); passes = false; return passes; } String database = dbr.getName(); String type = dbr.getType().getName(); String release = dbr.getSchemaVersion(); DatabaseServer srv = dbr.getDatabaseServer(); logger.info("Running " + schemaPatchScript); final Connection conn = dbr.getConnection(); final SchemaPatchesApplied thisTestRef = this; String passwordOption = ""; if (!srv.getPass().isEmpty()) { passwordOption = "--pass=" + srv.getPass(); } String cmd = schemaPatchScript + " --host=" + srv.getHost() + " --port=" + srv.getPort() + " --user=" + srv.getUser() + " " + passwordOption + " --database=" + database + " --type=" + type + " --from " + release + " --release " + release + " --verbose" + " --dryrun" + " --fix" ; logger.info("Running " + cmd); systemCommand.runCmd( new String[] { schemaPatchScript, "--host=" + srv.getHost(), "--port=" + srv.getPort(), "--user=" + srv.getUser(), "" + passwordOption, "--database=" + database, "--type=" + type, "--from=" + release, "--release=" + release, "--verbose", "--dryrun", "--fix" }, new ActionAppendable() { @Override public void process(String message) { if (message.startsWith("Would apply ")) { // // Line 600 in schema_patcher.pl // printf( "Would apply patch '%s' (%s)\n", // //String pat = "Would apply (patch)"; String pat = "Would apply patch '(patch_.+sql)' \\((.+?)\\)"; Pattern pattern = Pattern.compile(pat); Matcher matcher = pattern.matcher(message); if (matcher.matches()) { String patchName = matcher.group(1); String type = matcher.group(2); ReportManager.problem(thisTestRef, conn, "Patch file has not been applied: " + patchName); thisTestRef.setPasses(false); } else { throw new RuntimeException( "Can't parse message from script!\n" + "(" + message + ")\n" + "Maybe the script " + schemaPatchScript + " has been updated and the message it outputs no longer is matched by the regular expression." ); } } } }, new ActionAppendable() { @Override public void process(String message) { ReportManager.problem(thisTestRef, conn, message); } } ); logger.info("Done running " + schemaPatchScript); return isPasses(); } }
src/org/ensembl/healthcheck/testcase/eg_core/SchemaPatchesApplied.java
New healthcheck to check for missing schema patches
src/org/ensembl/healthcheck/testcase/eg_core/SchemaPatchesApplied.java
New healthcheck to check for missing schema patches
<ide><path>rc/org/ensembl/healthcheck/testcase/eg_core/SchemaPatchesApplied.java <add>package org.ensembl.healthcheck.testcase.eg_core; <add> <add>import java.sql.Connection; <add>import java.util.regex.Matcher; <add>import java.util.regex.Pattern; <add> <add>import org.ensembl.healthcheck.DatabaseRegistryEntry; <add>import org.ensembl.healthcheck.DatabaseServer; <add>import org.ensembl.healthcheck.ReportManager; <add>import org.ensembl.healthcheck.SystemCommand; <add>import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase; <add>import org.ensembl.healthcheck.util.ActionAppendable; <add> <add>public class SchemaPatchesApplied extends SingleDatabaseTestCase { <add> <add> protected boolean passes; <add> <add> public boolean isPasses() { <add> return passes; <add> } <add> <add> public void setPasses(boolean passes) { <add> this.passes = passes; <add> } <add> <add> public boolean run(DatabaseRegistryEntry dbr) { <add> <add> setPasses(true); <add> <add> final String schemaPatchScript = "./perlcode/ensembl/misc-scripts/schema_patcher.pl"; <add> <add> SystemCommand systemCommand = new SystemCommand(); <add> <add> // If mysqldiff can't be found, the test can terminate right away. <add> // <add> if (!systemCommand.checkCanExecute(schemaPatchScript)) { <add> <add> ReportManager.problem(this, (Connection) null, <add> "Can't find "+ schemaPatchScript +"! " <add> + this.getShortTestName() + " relies on this program to " <add> + "find missing patches.\n" <add> ); <add> passes = false; <add> return passes; <add> } <add> <add> <add> String database = dbr.getName(); <add> String type = dbr.getType().getName(); <add> String release = dbr.getSchemaVersion(); <add> <add> DatabaseServer srv = dbr.getDatabaseServer(); <add> <add> logger.info("Running " + schemaPatchScript); <add> <add> final Connection conn = dbr.getConnection(); <add> final SchemaPatchesApplied thisTestRef = this; <add> <add> String passwordOption = ""; <add> <add> if (!srv.getPass().isEmpty()) { <add> passwordOption = "--pass=" + srv.getPass(); <add> } <add> <add> String cmd = <add> schemaPatchScript <add> + " --host=" + srv.getHost() <add> + " --port=" + srv.getPort() <add> + " --user=" + srv.getUser() <add> + " " + passwordOption <add> + " --database=" + database <add> + " --type=" + type <add> + " --from " + release <add> + " --release " + release <add> + " --verbose" <add> + " --dryrun" <add> + " --fix" <add> ; <add> <add> logger.info("Running " + cmd); <add> <add> systemCommand.runCmd( <add> new String[] { <add> schemaPatchScript, <add> "--host=" + srv.getHost(), <add> "--port=" + srv.getPort(), <add> "--user=" + srv.getUser(), <add> "" + passwordOption, <add> "--database=" + database, <add> "--type=" + type, <add> "--from=" + release, <add> "--release=" + release, <add> "--verbose", <add> "--dryrun", <add> "--fix" <add> }, <add> new ActionAppendable() { <add> @Override public void process(String message) { <add> <add> if (message.startsWith("Would apply ")) { <add> <add> // <add> // Line 600 in schema_patcher.pl <add> // printf( "Would apply patch '%s' (%s)\n", <add> // <add> //String pat = "Would apply (patch)"; <add> String pat = "Would apply patch '(patch_.+sql)' \\((.+?)\\)"; <add> <add> Pattern pattern = Pattern.compile(pat); <add> Matcher matcher = pattern.matcher(message); <add> <add> if (matcher.matches()) { <add> String patchName = matcher.group(1); <add> String type = matcher.group(2); <add> ReportManager.problem(thisTestRef, conn, "Patch file has not been applied: " + patchName); <add> thisTestRef.setPasses(false); <add> <add> } else { <add> throw new RuntimeException( <add> "Can't parse message from script!\n" <add> + "(" + message + ")\n" <add> + "Maybe the script " + schemaPatchScript + " has been updated and the message it outputs no longer is matched by the regular expression." <add> ); <add> } <add> } <add> } <add> }, <add> new ActionAppendable() { <add> @Override public void process(String message) { <add> ReportManager.problem(thisTestRef, conn, message); <add> } <add> } <add> ); <add> <add> logger.info("Done running " + schemaPatchScript); <add> <add> return isPasses(); <add> } <add>}
JavaScript
mit
0c5a603db3b615cabfc36bd66b70608361ff40b4
0
Ellisande/kanbonsai,Ellisande/kanbonsai
/* Services */ (function(services){ services.factory('socket', function ($rootScope, $location) { 'use strict'; var socket; var registeredEvents = []; var connect = function(){ if(!socket){ socket = io.connect('http://'+$location.host()+':5000'); } }; connect(); var globalOn = function(eventName, callback){ socket.on(eventName, function () { var args = arguments; $rootScope.$apply(function () { callback.apply(socket, args); }); }); }; var registeredOn = function (eventName, callback) { var proxyFunction = function () { var args = arguments; $rootScope.$apply(function () { callback.apply(socket, args); }); }; registeredEvents.push({ eventName: eventName, callback: proxyFunction }); socket.on(eventName, proxyFunction); }; var emitWrapper = function (eventName, data, callback) { socket.emit(eventName, data, function () { var args = arguments; $rootScope.$apply(function () { if (callback) { callback.apply(socket, args); } }); }); }; var cleanup = function(){ registeredEvents.forEach(function(event, index){ socket.removeListener(event.eventName, event.callback); }); }; return { global: globalOn, on: registeredOn, emit: emitWrapper, cleanup: cleanup }; }); services.factory('mtgDetails', function (){ return { capture: { meeting:'', user:'' }, captureDetails: function(meeting, user){ this.capture.meeting = angular.copy(meeting); this.capture.user = angular.copy(user); }, getDetails: function(){ var temp = this.capture; this.capture = {}; return temp; } }; }); services.factory('timer', function(socket, $timeout){ var duration = moment.duration(3, 'minutes'); var currentTimeout = {}; var startTimeout = function(){ if(duration.asSeconds() === 0){ socket.emit('timer:stop'); return; } duration.subtract(1, 'seconds'); currentTimeout = $timeout(startTimeout, 1000); }; var timer = { expired: true, duration: duration, start: function(){ socket.emit('timer:start'); }, stop: function(){ socket.emit('timer:stop'); } }; var reset = function(newDuration){ $timeout.cancel(currentTimeout); //Used to maintain the same duration reference, but reset it. duration.subtract(duration.asMilliseconds()).add(moment.duration(newDuration)); timer.expired = true; }; socket.global('timer:init', function(data){ reset(data.duration); }); socket.global('timer:start', function(data){ reset(data.duration); timer.expired = false; startTimeout(); }); socket.global('timer:stop', function(data){ reset(data.duration); }); return timer; }); })(angular.module('services',[])); function Meeting(name, startTime){ this.name = name; this.startTime = new Date(startTime); this.available = false; this.durationMinutes = 15; }
app/js/services.js
/* Services */ (function(services){ services.factory('socket', function ($rootScope, $location) { 'use strict'; var socket; var registeredEvents = []; var connect = function(){ if(!socket){ socket = io.connect('http://'+$location.host()+':5000'); } }; connect(); var globalOn = function(eventName, callback){ socket.on(eventName, function () { var args = arguments; $rootScope.$apply(function () { callback.apply(socket, args); }); }); }; var registeredOn = function (eventName, callback) { var proxyFunction = function () { var args = arguments; $rootScope.$apply(function () { callback.apply(socket, args); }); }; registeredEvents.push({ eventName: eventName, callback: proxyFunction }); socket.on(eventName, proxyFunction); }; var emitWrapper = function (eventName, data, callback) { socket.emit(eventName, data, function () { var args = arguments; $rootScope.$apply(function () { if (callback) { callback.apply(socket, args); } }); }); }; var cleanup = function(){ registeredEvents.forEach(function(event, index){ socket.removeListener(event.eventName, event.callback); }); }; return { global: globalOn, on: registeredOn, emit: emitWrapper, cleanup: cleanup }; }) services.factory('mtgDetails', function (){ return { capture: { meeting:'', user:'' }, captureDetails: function(meeting, user){ this.capture.meeting = angular.copy(meeting); this.capture.user = angular.copy(user); }, getDetails: function(){ var temp = this.capture; this.capture = {}; return temp; } }; }); services.factory('timer', function(socket, $timeout){ var duration = moment.duration(3, 'minutes'); var currentTimeout = {}; var startTimeout = function(){ if(duration.asSeconds() == 0){ socket.emit('timer:stop'); return; } duration.subtract(1, 'seconds'); currentTimeout = $timeout(startTimeout, 1000); }; var timer = { expired: true, duration: duration, start: function(){ socket.emit('timer:start'); }, stop: function(){ socket.emit('timer:stop'); } } var reset = function(newDuration){ $timeout.cancel(currentTimeout); //Used to maintain the same duration reference, but reset it. duration.subtract(duration.asMilliseconds()).add(moment.duration(newDuration)); timer.expired = true; }; socket.global('timer:init', function(data){ reset(data.duration); }); socket.global('timer:start', function(data){ reset(data.duration); timer.expired = false; startTimeout(); }); socket.global('timer:stop', function(data){ reset(data.duration); }); return timer; }); })(angular.module('services',[])); function Meeting(name, startTime){ this.name = name; this.startTime = new Date(startTime); this.available = false; this.durationMinutes = 15; }
Fix JSLint errors.
app/js/services.js
Fix JSLint errors.
<ide><path>pp/js/services.js <ide> emit: emitWrapper, <ide> cleanup: cleanup <ide> }; <del> }) <add> }); <ide> <ide> services.factory('mtgDetails', function (){ <ide> return { <ide> <ide> var currentTimeout = {}; <ide> var startTimeout = function(){ <del> if(duration.asSeconds() == 0){ <add> if(duration.asSeconds() === 0){ <ide> socket.emit('timer:stop'); <ide> return; <ide> } <ide> stop: function(){ <ide> socket.emit('timer:stop'); <ide> } <del> } <add> }; <ide> <ide> var reset = function(newDuration){ <ide> $timeout.cancel(currentTimeout);
Java
agpl-3.0
e7d8a83beb3f2c79b55c35ae9e6486a1c08db6c6
0
RapidInfoSys/Rapid,RapidInfoSys/Rapid,RapidInfoSys/Rapid,RapidInfoSys/Rapid
/* Copyright (C) 2022 - Gareth Edwards / Rapid Information Systems [email protected] This file is part of the Rapid Application Platform Rapid 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. The terms require you to include the original copyright, and the license notice in all redistributions. 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 in a file named "COPYING". If not, see <http://www.gnu.org/licenses/>. */ package com.rapid.server; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.net.InetAddress; import java.sql.PreparedStatement; import java.sql.ResultSetMetaData; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.apache.logging.log4j.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.rapid.actions.Database; import com.rapid.actions.Logic; import com.rapid.actions.Logic.Condition; import com.rapid.core.Action; import com.rapid.core.Application; import com.rapid.core.Application.Parameter; import com.rapid.core.Application.Resource; import com.rapid.core.Application.Resources; import com.rapid.core.Application.ValueList; import com.rapid.core.Applications.Versions; import com.rapid.core.Control; import com.rapid.core.Event; import com.rapid.core.Page; import com.rapid.core.Page.Lock; import com.rapid.core.Page.RoleControlHtml; import com.rapid.core.Page.Variable; import com.rapid.core.Page.Variables; import com.rapid.core.Pages; import com.rapid.core.Pages.PageHeader; import com.rapid.core.Pages.PageHeaders; import com.rapid.core.Settings; import com.rapid.core.Theme; import com.rapid.core.Workflow; import com.rapid.core.Workflows; import com.rapid.data.DataFactory; import com.rapid.data.DataFactory.Parameters; import com.rapid.data.DatabaseConnection; import com.rapid.forms.FormAdapter; import com.rapid.security.RapidSecurityAdapter; import com.rapid.security.SecurityAdapter; import com.rapid.security.SecurityAdapter.Role; import com.rapid.security.SecurityAdapter.SecurityAdapaterException; import com.rapid.security.SecurityAdapter.User; import com.rapid.security.SecurityAdapter.Users; import com.rapid.utils.Bytes; import com.rapid.utils.Files; import com.rapid.utils.Strings; import com.rapid.utils.XML; import com.rapid.utils.ZipFile; public class Designer extends RapidHttpServlet { private static final long serialVersionUID = 2L; // this byte buffer is used for reading the post data byte[] _byteBuffer = new byte[1024]; public Designer() { super(); } // helper method to set the content type, write, and close the stream for common JSON output private void sendJsonOutput(HttpServletResponse response, String output) throws IOException { // set response as json response.setContentType("application/json"); // get a writer from the response PrintWriter out = response.getWriter(); // write the output into the response out.print(output); // close the writer out.close(); // send it immediately out.flush(); } // print indentation private void printIndentation(PrintWriter out, int level) { // loop level for (int i = 0; i < level; i++) { out.print("\t"); } } // print details of an action private void printAction(Action action, PrintWriter out, boolean details, int level) { // print any indentation printIndentation(out, level); // retain the level at this point int thislevel = level + 2; // print the action out.print("\t\tAction:\t" + action.getId() + "\t" + action.getType() + "\r\n"); // create a sorted list List<String> sortedKeys = new ArrayList<>(); // a map for the properties we're going to print Map<String, String> keyValues = new HashMap<>(); // only required for details if (details) { // get the object properties Map<String, String> objectProperties = action.getProperties(); // loop them for (String key : objectProperties.keySet()) { // add the key sortedKeys.add(key); // add the value keyValues.put(key, objectProperties.get(key)); } } // get a JSONObject for this action which will turn the get/set properties into keys JSONObject jsonAction = new JSONObject(action); // get it's properties Iterator<String> keys = jsonAction.keys(); // a map of child actions Map<String, List<Action>> keyChildActions = new HashMap<>(); // loop them while (keys.hasNext()) { // get the next one String key = keys.next(); // if not there already and details or actions if (!sortedKeys.contains(key) && (details || key.endsWith("Actions") || "actions".equals(key))) { // add the key sortedKeys.add(key); try { // if the key ends with actions if ((key.endsWith("Actions") || "actions".equals(key)) && action.getChildActions() != null && action.getChildActions().size() > 0) { // get the child actions JSONArray jsonChildActions = jsonAction.optJSONArray(key); // if we got some if (jsonChildActions != null) { // list of child actions for this key List<Action> childActions = new ArrayList<>(); // loop the child actions for (int i = 0; i < jsonChildActions.length(); i++) { // get this one JSONObject jsonChildAction = jsonChildActions.getJSONObject(i); // get its id String childId = jsonChildAction.optString("id", null); // if there was one if (childId != null) { // loop them List<Action> as = action.getChildActions(); for (Action childAction : as) { // print the child actions if (childId.equals(childAction.getId())) { // add the child action childActions.add(childAction); // we're done break; } } } } // add the child actions for this key keyChildActions.put(key, childActions); } } else { String str = JSONObject.valueToString(jsonAction.get(key)); if (looksLikeJSONObject(str)) { JSONObject jsonObject = jsonAction.getJSONObject(key); str = printJSONObject(jsonObject, thislevel).replaceAll("\r\n\t*\r\n", "\r\n"); } else if (looksLikeJSONArray(str)) { JSONArray jsonArray = jsonAction.getJSONArray(key); str = printJSONArray(jsonArray, thislevel).replaceAll("\r\n\t*\r\n", "\r\n"); } // add the value keyValues.put(key, str); } } catch (JSONException e) {} } } // sort the keys Collections.sort(sortedKeys, String.CASE_INSENSITIVE_ORDER); // loop the sorted keys for (String key : sortedKeys) { // print it if not id, nor properties itself if (!"id".equals(key) && !"properties".equals(key) && !"type".equals(key) && !"childActions".equals(key)) { // print any indentation printIndentation(out, level); // print the key out.print("\t\t\t" + key); // get any child actions List<Action> childActions = keyChildActions.get(key); // if there are child actions for this key if (childActions != null) { // loop the child actions for (Action childAction : childActions) { // print a new line out.print("\r\n"); // print the child actions printAction(childAction, out, details, thislevel); } } else { // print the value out.print("\t" + keyValues.get(key) + "\r\n"); } } } } private static String printJSONObject(JSONObject jsonObject, int level) throws JSONException { int thisLevel = level + 2; String output = ""; Iterator<String> keys = jsonObject.keys(); while (keys.hasNext()) { String key = keys.next(); output += "\r\n"; for (int i = 0; i < thisLevel; i++) output += "\t"; // we want line breaks and tabs in values printed as is (not escaped) String value = jsonObject.get(key).toString(); // if it has line breaks - add one in front so it all appears on the margin if (value != null && value.contains("\n")) value = "\r\n" + value; if (looksLikeJSONObject(value)) { value = printJSONObject(jsonObject.getJSONObject(key), thisLevel); } else if (looksLikeJSONArray(value)) { value = printJSONArray(jsonObject.getJSONArray(key), thisLevel); } output += key + "\t" + value; } return output; } private static String printJSONArray(JSONArray jsonArray, int level) throws JSONException { int thisLevel = level + 2; String output = ""; for (int i = 0; i < jsonArray.length(); i++) { output += "\r\n"; String value = JSONObject.valueToString(jsonArray.get(i)); if (looksLikeJSONObject(value)) { value = printJSONObject(jsonArray.getJSONObject(i), level); } else if (looksLikeJSONArray(value)) { value = printJSONArray(jsonArray.getJSONArray(i), level); } else { for (int j = 0; j < thisLevel; j++) output += "\t"; } output += value; } return output; } private static boolean looksLikeJSONObject(String str) { return str.startsWith("{") && str.endsWith("}"); } private static boolean looksLikeJSONArray(String str) { return str.startsWith("[") && str.endsWith("]"); } // print details of events (used by page and controls) private void printEvents(List<Event> events, PrintWriter out, boolean details) { // check events if (events!= null) { if (events.size() > 0) { // loop them for (Event event : events) { // check actions if (event.getActions() != null) { if (event.getActions().size() > 0) { // print the event out.print("\tEvent:\t" + event.getType() + "\r\n"); // loop the actions for (Action action : event.getActions()) { // print the action details printAction(action, out, details, 0); } } } } } } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // fake a delay for testing slow servers // try { Thread.sleep(3000); } catch (InterruptedException e) {} // get request as Rapid request RapidRequest rapidRequest = new RapidRequest(this, request); // retain the servlet context ServletContext context = rapidRequest.getServletContext(); // get a reference to our logger Logger logger = getLogger(); // if monitor is alive then log the event if(_monitor != null && _monitor.isAlive(context) && _monitor.isLoggingAll()) _monitor.openEntry(); // we will store the length of the item we are adding long responseLength = 0; try { logger.debug("Designer GET request : " + request.getQueryString()); String actionName = rapidRequest.getActionName(); String output = ""; // get the rapid application Application rapidApplication = getApplications().get("rapid"); // check we got one if (rapidApplication != null) { // get rapid security SecurityAdapter rapidSecurity = rapidApplication.getSecurityAdapter(); // check we got some if (rapidSecurity != null) { // get the user name String userName = rapidRequest.getUserName(); // get the rapid user User rapidUser = rapidSecurity.getUser(rapidRequest); // check permission if (rapidSecurity.checkUserRole(rapidRequest, Rapid.DESIGN_ROLE)) { // whether we're trying to avoid caching boolean noCaching = Boolean.parseBoolean(context.getInitParameter("noCaching")); if (noCaching) { // try and avoid caching response.setHeader("Expires", "Sat, 15 March 1980 12:00:00 GMT"); // Set standard HTTP/1.1 no-cache headers. response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // Set IE extended HTTP/1.1 no-cache headers (use addHeader). response.addHeader("Cache-Control", "post-check=0, pre-check=0"); // Set standard HTTP/1.0 no-cache header. response.setHeader("Pragma", "no-cache"); } if ("getSystemData".equals(actionName)) { // create a system data object JSONObject jsonSystemData = new JSONObject(); // add the controls jsonSystemData.put("controls", getJsonControls()); // add the actions jsonSystemData.put("actions", getJsonActions()); // add the devices jsonSystemData.put("devices", getDevices()); // add the local date format jsonSystemData.put("localDateFormat", getLocalDateFormat()); // look for a controlAndActionSuffix String controlAndActionSuffix = context.getInitParameter("controlAndActionSuffix"); // update to empty string if not present - this is the default and expected for older versions of the web.xml if (controlAndActionSuffix == null) controlAndActionSuffix = ""; // add the controlAndActionPrefix jsonSystemData.put("controlAndActionSuffix", controlAndActionSuffix); // put into output string output = jsonSystemData.toString(); // send output as json sendJsonOutput(response, output); } else if ("getApps".equals(actionName)) { // create a json array for holding our apps JSONArray jsonApps = new JSONArray(); // get a sorted list of the applications for (String id : getApplications().getIds()) { // loop the versions for (String version : getApplications().getVersions(id).keySet()) { // get the this application version Application application = getApplications().get(id, version); // get the security SecurityAdapter security = application.getSecurityAdapter(); // recreate the request in the name of this app RapidRequest appRequest = new RapidRequest(this, request, application); // check the users password if (security.checkUserPassword(appRequest, rapidRequest.getUserName(), rapidRequest.getUserPassword())) { // check the users permission to design this application boolean designPermission = security.checkUserRole(appRequest, Rapid.DESIGN_ROLE); // if app is rapid do a further check if (designPermission && "rapid".equals(application.getId())) designPermission = security.checkUserRole(appRequest, Rapid.SUPER_ROLE); // if we got permssion - add this application to the list if (designPermission) { // create a json object JSONObject jsonApplication = new JSONObject(); // add the details we want jsonApplication.put("id", application.getId()); jsonApplication.put("name", application.getName()); jsonApplication.put("title", application.getTitle()); // add the object to the collection jsonApps.put(jsonApplication); // no need to check any further versions break; } } } } output = jsonApps.toString(); sendJsonOutput(response, output); } else if ("getVersions".equals(actionName)) { // create a json array for holding our apps JSONArray jsonVersions = new JSONArray(); // get the app id String appId = rapidRequest.getAppId(); // get the versions Versions versions = getApplications().getVersions(appId); // if there are any if (versions != null) { // loop the list of applications sorted by id (with rapid last) for (Application application : versions.sort()) { // get the security SecurityAdapter security = application.getSecurityAdapter(); // recreate the request in the name of this app RapidRequest appRequest = new RapidRequest(this, request, application); // check the users password if (security.checkUserPassword(appRequest, rapidRequest.getUserName(), rapidRequest.getUserPassword())) { // check the users permission to design this application boolean designPermission = application.getSecurityAdapter().checkUserRole(appRequest, Rapid.DESIGN_ROLE); // if app is rapid do a further check if (designPermission && "rapid".equals(application.getId())) designPermission = security.checkUserRole(appRequest, Rapid.SUPER_ROLE); // check the RapidDesign role is present in the users roles for this application if (designPermission) { // make a json object for this version JSONObject jsonVersion = new JSONObject(); // add the app id jsonVersion.put("id", application.getId()); // add the version jsonVersion.put("version", application.getVersion()); // add the status jsonVersion.put("status", application.getStatus()); // add the title jsonVersion.put("title", application.getTitle()); // add a formAdapter if present if (application.getIsForm()) jsonVersion.put("isForm", true); // add whether to show control Ids jsonVersion.put("showControlIds", application.getShowControlIds()); // add whether to show action Ids jsonVersion.put("showActionIds", application.getShowActionIds()); // add the web folder so we can update the iframe style sheets jsonVersion.put("webFolder", Application.getWebFolder(application)); // get the database connections List<DatabaseConnection> databaseConnections = application.getDatabaseConnections(); // check we have any if (databaseConnections != null) { // make an object we're going to return JSONArray jsonDatabaseConnections = new JSONArray(); // loop the connections for (DatabaseConnection databaseConnection : databaseConnections) { // add the connection name jsonDatabaseConnections.put(databaseConnection.getName()); } // add the connections to the app jsonVersion.put("databaseConnections", jsonDatabaseConnections); } // make an object we're going to return JSONArray jsonRoles = new JSONArray(); // retrieve the roles List<Role> roles = security.getRoles(appRequest); // check we got some if (roles != null) { // create a collection of names ArrayList<String> roleNames = new ArrayList<>(); // copy the names in if non-null for (Role role : roles) if (role.getName() != null) roleNames.add(role.getName()); // sort them Collections.sort(roleNames); // loop the sorted connections for (String roleName : roleNames) { // only add role if this is the rapid app, or it's not a special rapid permission if ("rapid".equals(application.getId()) || (!Rapid.ADMIN_ROLE.equals(roleName)&& !Rapid.SUPER_ROLE.equals(roleName) && !Rapid.USERS_ROLE.equals(roleName) && !Rapid.DESIGN_ROLE.equals(roleName))) jsonRoles.put(roleName); } } // add the security roles to the app jsonVersion.put("roles", jsonRoles); // get any value lists List<ValueList> valueLists = application.getValueLists(); // add all of the value lists jsonVersion.put("valueLists", valueLists); // get all the possible json actions JSONArray jsonActions = getJsonActions(); // make an array for the actions in this app JSONArray jsonAppActions = new JSONArray(); // get the types used in this app List<String> actionTypes = application.getActionTypes(); // if we have some if (actionTypes != null) { // loop the types used in this app for (String actionType : actionTypes) { // loop all the possible actions for (int i = 0; i < jsonActions.length(); i++) { // get an instance to the json action JSONObject jsonAction = jsonActions.getJSONObject(i); // if this is the type we've been looking for if (actionType.equals(jsonAction.getString("type"))) { // create a simple json object for thi action JSONObject jsonAppAction = new JSONObject(); // add just what we need jsonAppAction.put("type", jsonAction.getString("type")); jsonAppAction.put("name", jsonAction.getString("name")); jsonAppAction.put("visible", jsonAction.optBoolean("visible", true)); // add it to the app actions collection jsonAppActions.put(jsonAppAction); // start on the next app action break; } } } } // put the app actions we've just built into the app jsonVersion.put("actions", jsonAppActions); // get all the possible json controls JSONArray jsonControls = getJsonControls(); // make an array for the controls in this app JSONArray jsonAppControls = new JSONArray(); // get the control types used by this app List<String> controlTypes = application.getControlTypes(); // if we have some if (controlTypes != null) { // loop the types used in this app for (String controlType : controlTypes) { // loop all the possible controls for (int i = 0; i < jsonControls.length(); i++) { // get an instance to the json control JSONObject jsonControl = jsonControls.getJSONObject(i); // if this is the type we've been looking for if (controlType.equals(jsonControl.getString("type"))) { // create a simple json object for this control JSONObject jsonAppControl = new JSONObject(); // add just what we need jsonAppControl.put("type", jsonControl.getString("type")); jsonAppControl.put("name", jsonControl.getString("name")); jsonAppControl.put("image", jsonControl.optString("image")); jsonAppControl.put("category", jsonControl.optString("category")); jsonAppControl.put("canUserAdd", jsonControl.optString("canUserAdd")); // add it to the app controls collection jsonAppControls.put(jsonAppControl); // start on the next app control break; } } } } // put the app controls we've just built into the app jsonVersion.put("controls", jsonAppControls); // create a json object for the images JSONArray jsonImages = new JSONArray(); // get the directory in which the control xml files are stored File dir = new File (application.getWebFolder(context)); // if it exists (might not if deleted from the file system and apps not refreshed) if (dir.exists()) { // create a filter for finding image files FilenameFilter xmlFilenameFilter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".png") || name.toLowerCase().endsWith(".gif") || name.toLowerCase().endsWith(".jpg") || name.toLowerCase().endsWith(".jpeg") || name.toLowerCase().endsWith(".svg"); } }; // an array to hold the images as they come out of the filter List<String> images = new ArrayList<>(); // loop the image files in the folder for (File imageFile : dir.listFiles(xmlFilenameFilter)) { images.add(imageFile.getName()); } // sort the images Collections.sort(images); // loop the sorted images and add to json for (String image : images) jsonImages.put(image); } // put the images collection we've just built into the app jsonVersion.put("images", jsonImages); // create a json array for our style classes JSONArray jsonStyleClasses = new JSONArray(); // get all of the possible style classes List<String> styleClasses = application.getStyleClasses(); // if we had some if (styleClasses != null) { // loop and add to json array for (String styleClass : styleClasses) jsonStyleClasses.put(styleClass); } // put them into our application object jsonVersion.put("styleClasses", jsonStyleClasses); // look for any form adpter FormAdapter formAdapter = application.getFormAdapter(); // if we got one if (formAdapter != null) { // get the type String formAdapterType = formAdapter.getType(); // get the json form adpater details JSONArray jsonFormAdapters = getJsonFormAdapters(); // if we got some if (jsonFormAdapters != null) { // loop them for (int i = 0; i < jsonFormAdapters.length(); i++) { // get this form adapter JSONObject jsonFormAdapter = jsonFormAdapters.getJSONObject(i); // if this is the one we want if (formAdapterType.equals(jsonFormAdapter.optString("type"))) { // add the properties to the version jsonVersion.put("canSaveForms", jsonFormAdapter.optBoolean("canSaveForms")); jsonVersion.put("canGeneratePDF", jsonFormAdapter.optBoolean("canGeneratePDF")); jsonVersion.put("canSupportIntegrationProperties", jsonFormAdapter.optBoolean("canSupportIntegrationProperties")); // we're done break; } } } } // put the app into the collection jsonVersions.put(jsonVersion); } // design permission } // check user password } // versions loop } // got versions check output = jsonVersions.toString(); sendJsonOutput(response, output); } else if ("getPages".equals(actionName)) { Application application = rapidRequest.getApplication(); if (application == null) { // send an empty object output = "{}"; } else { JSONArray jsonPages = new JSONArray(); String startPageId = ""; Page startPage = application.getStartPage(context); if (startPage != null) startPageId = startPage.getId(); // loop the page headers for (PageHeader pageHeader : application.getPages().getSortedPages()) { // get the page - yip this means that apps loaded in the designer load all of their pages Page page = application.getPages().getPage(context, pageHeader.getId()); // create a simple json object for the page JSONObject jsonPage = new JSONObject(); // add simple properties jsonPage.put("id", page.getId()); jsonPage.put("name", page.getName()); jsonPage.put("title", page.getTitle()); jsonPage.put("label", page.getLabel()); jsonPage.put("simple", page.getSimple()); jsonPage.put("hideHeaderFooter", page.getHideHeaderFooter()); /* // get a list of page session variables - now deprecated by page variables with the optional session storage List<String> pageSessionVariables = page.getSessionVariables(); // add them if there are some if (pageSessionVariables != null) if (pageSessionVariables.size() > 0) jsonPage.put("sessionVariables", pageSessionVariables); */ // get page variables Variables pageVariables = page.getVariables(); // add them if there are some if (pageVariables != null && pageVariables.size() > 0) jsonPage.put("variables", pageVariables); // assume we don't need to know page visibilty boolean includePageVisibiltyControls = false; // if there is a form adapter if (application.getFormAdapter() != null) { // set to true includePageVisibiltyControls = true; // add visibility conditions List<Condition> pageVisibilityConditions = page.getVisibilityConditions(); // add them if there are some if (pageVisibilityConditions != null) if (pageVisibilityConditions.size() > 0) jsonPage.put("visibilityConditions", pageVisibilityConditions); } // assume no page is selected in the designer that we want dialogue controls for Boolean includeFromDialogue = false; // if this loadPages was from a save if (Boolean.parseBoolean(rapidRequest.getRequest().getParameter("fromSave"))) { // get the page from the rapidRequest Page designPage = rapidRequest.getPage(); // if there was one if (designPage != null) { // get the pageId String pageId = page.getId(); // if we are saving a page in the designer, we will want to includeFromDialogue on all of the others if (!pageId.equals(designPage.getId())) { // get the list of pages we can open a dialogue to on this page List<String> dialoguePageIds = page.getDialoguePageIds(); // if designerPageId is provided and this page is different from the one we're loading in the designer if (dialoguePageIds != null) { // if the page in the designer is one this page can navigate to as a dialogue if (dialoguePageIds.contains(designPage.getId())) includeFromDialogue = true; } } } } // get map of other page controls we can access from this page - keep designer page id null to avoid dialogue controls and events JSONArray jsonControls = page.getOtherPageComponents(this, includePageVisibiltyControls, includeFromDialogue); // if we got some add to the page if (jsonControls != null) jsonPage.put("controls", jsonControls); // check if the start page and add property if so if (startPageId.equals(page.getId())) jsonPage.put("startPage", true); // add the page to the collection jsonPages.put(jsonPage); } // set the output to the collection turned into a string output = jsonPages.toString(); } // application check sendJsonOutput(response, output); } else if ("getPage".equals(actionName)) { Application application = rapidRequest.getApplication(); Page page = rapidRequest.getPage(); if (page != null) { // assume we can't find the user String userDescription = "unknown"; // get the user User user = application.getSecurityAdapter().getUser(rapidRequest); // if we had one and they have a description use it if (user != null) if (user.getDescription() != null) userDescription = user.getDescription(); // remove any existing page locks for this user application.removeUserPageLocks(context, userName); // check the page lock (which removes it if it has expired) page.checkLock(); // if there is no current lock add a fresh one for the current user if (page.getLock() == null) page.setLock(new Lock(userName, userDescription, new Date())); // turn it into json JSONObject jsonPage = new JSONObject(page); // remove the bodyHtml property as it is rebuilt in the designer jsonPage.remove("htmlBody"); // remove the rolesHtml property as it is rebuilt in the designer jsonPage.remove("rolesHtml"); // remove allControls (the single all-control list) it is not required jsonPage.remove("allControls"); // remove the otherPageControls property as it is sent with getPages jsonPage.remove("otherPageControls"); // remove bodyStyleClasses property as it should be called classes jsonPage.remove("bodyStyleClasses"); // add the bodyStyleClasses as classes array if (page.getBodyStyleClasses() != null) jsonPage.put("classes", page.getBodyStyleClasses().split(" ")); // add a nicely formatted lock time if (page.getLock() != null && jsonPage.optJSONObject("lock") != null) { // get the date time formatter and format the lock date time String formattedDateTime = getLocalDateTimeFormatter().format(page.getLock().getDateTime()); // add a special property to the json jsonPage.getJSONObject("lock").put("formattedDateTime", formattedDateTime); } // add the css jsonPage.put("css", page.getAllCSS(context, application)); // add the device as page properties (even though we store this in the app) jsonPage.put("device", 1); jsonPage.put("zoom", 1); jsonPage.put("orientation", "P"); // add the form page type jsonPage.put("formPageType", page.getFormPageType()); // get any theme Theme theme = application.getTheme(context); // if there was one if (theme != null) { // check for headerHtmlDesigner if (theme.getHeaderHtmlDesigner() != null) { // add headerHtmlDesigner html jsonPage.put("headerHtml", theme.getHeaderHtmlDesigner()); } else { // add header html jsonPage.put("headerHtml", theme.getHeaderHtml()); } // check for footerHtmlDesigner if (theme.getFooterHtmlDesigner() != null) { // add footerHtmlDesigner html jsonPage.put("footerHtml", theme.getFooterHtmlDesigner()); } else { // add footer html jsonPage.put("footerHtml", theme.getFooterHtml()); } } // create an other pages object JSONObject jsonOtherPages = new JSONObject(); // get the pages Pages pages = application.getPages(); // get the pages headers PageHeaders pageHeaders = pages.getSortedPages(); // loop the page headers for (PageHeader pageHeader : pageHeaders) { // get this page id String pageId = page.getId(); // if we are loading a specific page and need to know any other components for it and this is not the destination page itself if (!pageId.equals(pageHeader.getId())) { // get the other page Page otherPage = application.getPages().getPage(context, pageHeader.getId()); // get the list of pages we can open a dialogue to on this page List<String> dialoguePageIds = otherPage.getDialoguePageIds(); // if we can open dialogues on this page if (dialoguePageIds != null) { // if the page id the designer is one this page navigates to on a dialogue if (dialoguePageIds.contains(pageId)) { // get other page components for this page JSONArray jsonControls = otherPage.getOtherPageComponents(this, false, true); // if we got some if (jsonControls != null) { // if we got some if (jsonControls.length() > 0) { // create an other page object JSONObject jsonOtherPage = new JSONObject(); // add the controls to the page jsonOtherPage.put("controls", jsonControls); // add the other page to the page collection jsonOtherPages.put(otherPage.getId(), jsonOtherPage); } } } } // dialoguePageIds check } } // get the list of pages that appear in a page panel on this page List<String> pagePanelPageIds = page.getPagePanelPageIds(); // if designerPageId is provided and this page is different from the one we're loading in the designer if (pagePanelPageIds != null) { // loop them for (String pagePanelPageId : pagePanelPageIds) { // get this page Page pagePanelPage = pages.getPage(context, pagePanelPageId); // get other page components for this page JSONArray jsonControls = pagePanelPage.getOtherPageComponents(this, false, true); // if we got some if (jsonControls != null) { // if we got some if (jsonControls.length() > 0) { // create an other page object JSONObject jsonOtherPage = new JSONObject(); // add the controls to the page jsonOtherPage.put("controls", jsonControls); // add the other page to the page collection jsonOtherPages.put(pagePanelPageId, jsonOtherPage); } } } } // pagePanelPageIds check // if other pages objects add to page if (jsonOtherPages.length() > 0) jsonPage.put("otherPages", jsonOtherPages); // print it to the output output = jsonPage.toString(); // send as json response sendJsonOutput(response, output); } } else if ("getFlows".equals(actionName)) { // the JSON array of workflows we are going to return JSONArray jsonFlows = new JSONArray(); // the JSON workflow we are going to return JSONObject jsonFlow = new JSONObject(); // give it an id and a name jsonFlow.put("id", "1"); jsonFlow.put("name", "Test"); // add it to the array jsonFlows.put(jsonFlow); // print it to the output output = jsonFlows.toString(); // send as json response sendJsonOutput(response, output); } else if ("getFlowVersions".equals(actionName)) { // the JSON array of workflows we are going to return JSONArray jsonFlows = new JSONArray(); // the JSON workflow we are going to return JSONObject jsonFlow = new JSONObject(); // give it an id and a name jsonFlow.put("version", "1"); jsonFlow.put("status", "0"); // the JSON array of workflows we are going to return JSONArray jsonActions = new JSONArray(); JSONArray jsonAllActions = getJsonActions(); // loop all actions for now for (int i = 0; i < jsonAllActions.length(); i++) { // get all action JSONObject jsonAllAction = jsonAllActions.getJSONObject(i); // if it is allowed in workflow if (jsonAllAction.optBoolean("canUseWorkflow")) { JSONObject jsonAction = new JSONObject(); jsonAction.put("type", jsonAllActions.getJSONObject(i).getString("type")); jsonActions.put(jsonAction); } } jsonFlow.put("actions",jsonActions); // add it to the array jsonFlows.put(jsonFlow); // print it to the output output = jsonFlows.toString(); // send as json response sendJsonOutput(response, output); } else if ("getFlow".equals(actionName)) { // the JSON workflow we are going to return JSONObject jsonFlow = new JSONObject(); // give it an id and a name jsonFlow.put("id", "1"); jsonFlow.put("name", "Test"); // print it to the output output = jsonFlow.toString(); // send as json response sendJsonOutput(response, output); } else if ("checkApp".equals(actionName)) { String appName = request.getParameter("name"); if (appName != null) { // retain whether we have an app with this name boolean exists = getApplications().exists(Files.safeName(appName)); // set the response output = Boolean.toString(exists); // send response as json sendJsonOutput(response, output); } } else if ("checkVersion".equals(actionName)) { String appName = request.getParameter("name"); String appVersion = request.getParameter("version"); if (appName != null && appVersion != null ) { // retain whether we have an app with this name boolean exists = getApplications().exists(Files.safeName(appName), Files.safeName(appVersion)); // set the response output = Boolean.toString(exists); // send response as json sendJsonOutput(response, output); } } else if ("checkPage".equals(actionName)) { String pageName = request.getParameter("name"); if (pageName != null) { // retain whether we have an app with this name boolean pageExists = false; // get the application Application application = rapidRequest.getApplication(); if (application != null) { for (PageHeader page : application.getPages().getSortedPages()) { if (pageName.toLowerCase().equals(page.getName().toLowerCase())) { pageExists = true; break; } } } // set the output output = Boolean.toString(pageExists); // send response as json sendJsonOutput(response, output); } } else if ("checkWorkflow".equals(actionName)) { String name = request.getParameter("name"); if (name != null) { // retain whether we have an app with this name boolean exists = false; // get the workflows Workflows workflows = getWorkflows(); // look for this on Workflow workflow = workflows.get(Files.safeName(name)); // if we got one if (workflow != null) exists = true; // set the output output = Boolean.toString(exists); // send response as json sendJsonOutput(response, output); } } else if ("pages".equals(actionName) || "questions".equals(actionName) || "text".equals(actionName) || "summary".equals(actionName) || "detail".equals(actionName)) { // set response as text response.setContentType("text/plain;charset=utf-8"); // get a writer from the response PrintWriter out = response.getWriter(); // get the application Application application = rapidRequest.getApplication(); // get the page headers PageHeaders pageHeaders = application.getPages().getSortedPages(); // get the root path String rootPath = context.getRealPath("/"); // get the root file File root = new File(rootPath); // get a date/time formatter SimpleDateFormat df = getLocalDateTimeFormatter(); // write some useful things at the top out.print("Server name:\t" + InetAddress.getLocalHost().getHostName() + "\r\n"); out.print("Instance name:\t" + root.getName() + "\r\n"); out.print("Rapid version:\t" + Rapid.VERSION + "\r\n"); out.print("Date and time:\t" + df.format(new Date()) + "\r\n\r\n"); out.print("Rapid " + actionName + " report:\r\n\r\n\r\n"); // id out.print("Application id:\t" + application.getId() + "\r\n"); // version out.print("Version:\t" + application.getVersion() + "\r\n"); // name out.print("Name:\t" + application.getName() + "\r\n"); // title out.print("Title:\t" + application.getTitle() + "\r\n"); // app details if ("summary".equals(actionName) || "detail".equals(actionName)) { int statusId = application.getStatus(); String status = statusId == 0 ? "In development" : statusId == 1 ? "Live" : statusId == 2 ? "Under maintenance" : null; if (status != null) out.print("Status:\t" + status + "\r\n"); // safe created date if (application.getCreatedDate() != null) out.print("Created date:\t" + df.format(application.getCreatedDate()) + "\r\n"); // safe created by if (application.getCreatedBy() != null) out.print("Created by:\t" + application.getCreatedBy() + "\r\n"); // safe modified date if (application.getModifiedDate() != null) out.print("Modified date:\t" + df.format(application.getModifiedDate()) + "\r\n"); // safe modified by if (application.getModifiedBy() != null) out.print("Modified by:\t" + application.getModifiedBy() + "\r\n"); if (application.getStartPageId() != null) out.print("Start page:\t" + application.getStartPageId() + "\r\n"); // description if (application.getDescription() != null && application.getDescription().trim().length() > 0) out.print("Description:\t" + application.getDescription() + "\r\n"); out.print("Form settings:\t" + application.getIsForm() + "\r\n"); if (application.getIsForm()) { // form if (application.getIsForm()) out.print("Form adapter:\t" + application.getFormAdapterType() + "\r\n"); out.print("Show form summary:\t" + application.getFormShowSummary() + "\r\n"); out.print("Disable autocomplete:\t" + application.getFormDisableAutoComplete() + "\r\n"); } out.print("Email form:\t" + application.getFormEmail() + "\r\n"); if (application.getFormEmail()) { if (application.getFormEmailFrom() != null) out.print("From address:\t" + application.getFormEmailFrom() + "\r\n"); if (application.getFormEmailTo() != null) out.print("To address:\t" + application.getFormEmailTo() + "\r\n"); if (application.getFormEmailAttachmentType() != null) out.print("Attachment type:\t" + application.getFormEmailAttachmentType() + "\r\n"); } out.print("Email customer:\t" + application.getFormEmailCustomer() + "\r\n"); if (application.getFormEmailCustomer()) { if (application.getFormEmailCustomerControlId() != null) out.print("Customer address:\t" + application.getFormEmailCustomerControlId() + "\r\n"); String emailTypeCode = application.getFormEmailCustomerType(); String emailType = "T".equals(emailTypeCode) ? "Text" : "H".equals(emailTypeCode) ? "HTML" : null; if (emailType != null) out.print("Email type:\t" + emailType + "\r\n"); if (application.getFormEmailCustomerSubject() != null) out.print("Email subject:\t" + application.getFormEmailCustomerSubject() + "\r\n"); if (application.getFormEmailCustomerBody() != null) out.print("Email body:\t" + application.getFormEmailCustomerBody() + "\r\n"); String attachmentTypeCode = application.getFormEmailCustomerAttachmentType(); String attachmentType = "csv".equals(attachmentTypeCode) ? "CSV" : "xml".equals(attachmentTypeCode) ? "XML" : "pdf".equals(attachmentTypeCode) ? "PDF" : null; if (attachmentType != null) out.print("Attachment type:\t" + attachmentType + "\r\n"); out.print("Form details file:\t" + application.getFormFile() + "\r\n"); String typeCode = application.getFormFileType(); String type = "pdf".equals(typeCode) ? "PDF" : "xml".equals(typeCode) ? "XML" : "CSV"; out.print("File type:\t" + type + "\r\n"); if (application.getFormFilePath() != null) out.print("Path:\t" + application.getFormFilePath() + "\r\n"); if (application.getFormFileUserName() != null) out.print("Username:\t" + application.getFormFileUserName() + "\r\n"); } out.print("Form webservice:\t" + application.getFormWebservice() + "\r\n"); if (application.getFormWebservice()) { if (application.getFormWebserviceURL() != null) out.print("URL:\t" + application.getFormWebserviceURL() + "\r\n"); String webserviceTypeCode = application.getFormWebserviceType(); String webserviceType = "restful".equals(webserviceTypeCode) ? "Restful XML" : "json".equals(webserviceTypeCode) ? "JSON" : "SOAP"; out.print("Data type:\t" + webserviceType + "\r\n"); if (application.getFormWebserviceSOAPAction() != null) out.print("SOAP action:\t" + application.getFormWebserviceSOAPAction() + "\r\n"); } // theme out.print("Theme:\t" + application.getThemeType() + "\r\n"); } // App parameters List<Parameter> parameters = application.getParameters(); out.print("\r\nApplication parameters:\t" + parameters.size() + "\r\n"); for (Parameter parameter : parameters) { out.print("Name:\t" + parameter.getName() + "\r\n"); out.print("\tDescription:\t" + parameter.getDescription() + "\r\n"); out.print("\tValue:\t" + parameter.getValue() + "\r\n"); } out.println(); // DB connections List<DatabaseConnection> connections = application.getDatabaseConnections(); out.print("\r\nDatabase connections:\t" + connections.size() + "\r\n"); for (DatabaseConnection connection : connections) { out.print("Name:\t" + connection.getName() + "\r\n"); out.print("\tDriver:\t" + connection.getDriverClass() + "\r\n"); out.print("\tConnection string:\t" + connection.getConnectionString() + "\r\n"); out.print("\tUsername:\t" + connection.getUserName() + "\r\n"); } out.println(); // App settings String settings = application.getSettingsId(); if (settings != null && !settings.isEmpty()) out.print("Settings:\t" + settings + "\r\n"); out.println(); // pages out.print("Pages:\t" + pageHeaders.size() + "\r\n"); // double line break out.print("\r\n"); // get any page id String pageId = request.getParameter("p"); // loop the page headers for (PageHeader pageHeader : pageHeaders) { // get the page Page page = application.getPages().getPage(context, pageHeader.getId()); // if a specific page has been asked for continue until it comes up if (pageId != null && !page.getId().equals(pageId)) continue; // get the label String label = page.getLabel(); // if we got one if (label == null) { label = ""; } else { if (label.length() > 0) label = " - " + label; } if ("questions".equals(actionName)) { // print the name and label out.print(page.getTitle()); // get any visibility conditions List<Logic.Condition> visibilityConditions = page.getVisibilityConditions(); // if we got some if (visibilityConditions != null && visibilityConditions.size() > 0) { out.print(" ("); // loop them for (int i = 0; i < visibilityConditions.size(); i++) { // get the condition Logic.Condition condition = visibilityConditions.get(i); // get value 1 Control control1 = application.getControl(context, condition.getValue1().getId()); // if we got one print it's name if (control1 == null) { out.print(condition.getValue1().toString().replace("System.field/", "")); } else { out.print(control1.getName()); } // print operation out.print(" " + condition.getOperation() + " "); // get control 2 Control control2 = application.getControl(context, condition.getValue2().getId()); // if we got one print it's name if (control2 == null) { out.print(condition.getValue2().toString().replace("System.field/", "")); } else { if (control2.getLabel() == null || control2.getLabel().isEmpty()) { out.print(control2.getName()); } else { out.print(control2.getLabel()); } } // if there are more if (i < visibilityConditions.size() - 1) out.print(" " + page.getConditionsType() + " "); } out.print(")"); } // closing line break out.print("\r\n"); } else if ("text".equals(actionName)) { // print the page name with some space around it out.print(page.getTitle() + "\r\n"); } // page headers if ("pages".equals(actionName) || "detail".equals(actionName) || "summary".equals(actionName)) { // page id out.print("Page:\t" + page.getId() + "\r\n"); // page title out.print("Title:\t" + page.getTitle() + "\r\n"); // safe created date if (page.getCreatedDate() != null) out.print("Created date:\t" + df.format(page.getCreatedDate()) + "\r\n"); // safe created by if (page.getCreatedBy() != null) out.print("Created by:\t" + page.getCreatedBy() + "\r\n"); // safe modified date if (page.getModifiedDate() != null) out.print("Modified date:\t" + df.format(page.getModifiedDate()) + "\r\n"); // safe modified by if (page.getModifiedBy() != null) out.print("Modified by:\t" + page.getModifiedBy() + "\r\n"); // action summary if ("pages".equals(actionName) || "summary".equals(actionName)) { out.print("Actions:\t" + page.getAllActions().size() + "\r\n"); } // print the number of controls out.print("Controls:\t" + page.getAllControls().size() + "\r\n"); // events, action, and details if ("summary".equals(actionName)) { // print page events printEvents(page.getEvents(), out, false); } // events, action, and details if ("detail".equals(actionName)) { out.print("Description:\t" + page.getDescription() + "\r\n"); out.print("Simple:\t" + page.getSimple() + "\r\n"); out.print("HideHeaderFooter:\t" + page.getHideHeaderFooter() + "\r\n"); // print page events printEvents(page.getEvents(), out, true); } } // check questions, summary, detail if ("questions".equals(actionName) || "text".equals(actionName) || "summary".equals(actionName) || "detail".equals(actionName)) { // get the controls List<Control> controls = page.getAllControls(); // loop them for (Control control : controls) { // get the name String name = control.getName(); // name null check if ((name != null && name.trim().length() > 0) || "summary".equals(actionName) || "detail".equals(actionName) || "text".equals(actionName)) { // get the label label = control.getLabel(); // get the type String type = control.getType(); // exclude panels, hidden values (except for questions), and datastores for summary if ("summary".equals(actionName) || "detail".equals(actionName) || (!type.contains("panel") && (!("hiddenvalue").equals(type) || "questions".equals(actionName)) && !("dataStore").equals(type))) { // if questions it's likely to be a form if ("questions".equals(actionName)) { // look for a form object String formObject = control.getProperty("formObject"); // if there is a label but not a button, but radios are allowed if ((label != null && (!control.getType().contains("button") || control.getType().contains("radio"))) || formObject != null) { // use name if label null if (label == null) label = name; // print the label out.print("\t" + label); // if we got one if (formObject != null) { // Get form integration values String formObjectAttribute = control.getProperty("formObjectAttribute"); String formObjectRole = control.getProperty("formObjectRole"); String formObjectType = control.getProperty("formObjectType"); String formObjectPartyNumber = control.getProperty("formObjectPartyNumber"); String formObjectQuestionNumber = control.getProperty("formObjectQuestionNumber"); String formObjectAddressNumber = control.getProperty("formObjectAddressNumber"); String formObjectText = control.getProperty("formObjectText"); if (formObject != null && !formObject.equals("")) { out.print(" ("); if (formObject != null) out.print(formObject); if (!"other".equalsIgnoreCase(formObject)) if (formObjectRole != null) out.print(" - " + formObjectRole); if (formObjectPartyNumber != null) out.print(" - party: " + formObjectPartyNumber); if ("party".equals(formObject)) out.print(" " + formObjectAttribute); if ("contact".equals(formObject)) out.print(" " + formObjectType); if ("address".equals(formObject)) { if (formObjectAddressNumber != null) out.print(" - address: " + formObjectAddressNumber); if (formObjectType != null) out.print(" - " + formObjectType); if (formObjectAttribute != null) out.print(" - " + formObjectAttribute); } if ("question".equals(formObject) || "other".equals(formObject)) if (formObjectQuestionNumber != null) out.print(" - question: " + formObjectQuestionNumber); if (formObjectText != null && formObjectText.length() > 0) out.print(" - '" + formObjectText + "'"); out.print(")"); } } out.print("\r\n"); } } else if ("text".equals(actionName)) { // no buttons if (!control.getType().endsWith("button")) { // get the text String text = control.getProperty("text"); // print the text if there was some if (text != null) { // trim it and remove any line breaks text = text.trim().replace("\r", "").replace("\n", ""); // if we have some if (text.length() > 0) out.print(text + "\r\n"); } // try responsivelabel if we don't have one yet if (label == null) label = control.getProperty("responsiveLabel"); // print the label if there was some if (label != null && label.trim().length() > 0) out.print(label); // if any options String options = control.getProperty("options"); // if we got some if (options != null) { out.print(" ("); // read into JSON JSONArray jsonOptions = new JSONArray(options); // loop for (int i = 0; i < jsonOptions.length(); i++) { // get the option JSONObject JSONOption = jsonOptions.getJSONObject(i); // get the option's text out.print(JSONOption.getString("text")); // add a comma if one is required if (i < jsonOptions.length() - 1) out.print(", "); } out.print(")"); } // print a line break if there was pritning above if (label != null && label.trim().length() > 0) out.print("\r\n"); // if this is a grid if ("grid".equals(control.getType())) { out.print(control.getName() + " ("); // get the columns JSONArray jsonColumns = new JSONArray(control.getProperty("columns")); // loop them for (int i = 0; i < jsonColumns.length(); i++) { // get the option JSONObject JSONOption = jsonColumns.getJSONObject(i); // get the option's text out.print(JSONOption.getString("title")); // add a comma if one is required if (i < jsonColumns.length() - 1) out.print(", "); } out.print(")\r\n"); } } } else { // print the control details out.print("Control:\t" + control.getId() +"\t" + type + "\t"); // name if (name != null && name.length() > 0) out.print(name); // label if (label != null && label.length() > 0) out.print("\t" + label); // line break out.print("\r\n"); } // if summary if ("summary".equals(actionName)) printEvents(control.getEvents(), out, false); // if details if ("detail".equals(actionName)) { // get the properties Map<String, String> properties = control.getProperties(); // get a list we'll sort for them List<String> sortedKeys = new ArrayList<>(); // loop them for (String key : properties.keySet()) { // add to sorted list sortedKeys.add(key); } // sort them Collections.sort(sortedKeys); // loop them for (String key : sortedKeys) { // print the properties (but not the properties itself) if (!"properties".equals(key)) out.print(key + "\t" + properties.get(key) + "\r\n"); } // print the event details printEvents(control.getEvents(), out, true); } // detail check } // exclusion check } // name check } // control loop } // report action check // add space after the page out.print("\r\n"); } // page loop // App Resources Resources resources = application.getAppResources(); out.println("\r\nResources:\t" + resources.size() + "\r\n"); for (Resource resource : resources) { if (resource.getName() != null) out.print("Name:\t" + resource.getName() + "\r\n"); if (resource.getContent() != null) out.print("Content:\t" + resource.getContent() + "\r\n"); } out.println(); // App CSS String styles = application.getStyles(); out.print("Styles:\t\r\n"); out.print(styles + "\r\n"); // close the writer out.close(); // send it immediately out.flush(); } else if ("export".equals(actionName)) { // get the application Application application = rapidRequest.getApplication(); // check we've got one if (application != null) { // the file name is the app id, an under score and then an underscore-safe version String fileName = application.getId() + "_" + application.getVersion().replace("_", "-") + ".zip"; // get the file for the zip we're about to create File zipFile = application.zip(this, rapidRequest, rapidUser, fileName); // set the type as a .zip response.setContentType("application/x-zip-compressed"); // Shows the download dialog response.setHeader("Content-disposition","attachment; filename=" + fileName); // send the file to browser OutputStream out = response.getOutputStream(); FileInputStream in = new FileInputStream(zipFile); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0){ out.write(buffer, 0, length); } in.close(); out.flush(); // delete the .zip file zipFile.delete(); output = "Zip file sent"; } // got application } else if ("updateids".equals(actionName)) { // get a writer from the response PrintWriter out = response.getWriter(); // check we have admin too if (rapidSecurity.checkUserRole(rapidRequest, Rapid.ADMIN_ROLE)) { // get the suffix String suffix = rapidRequest.getRapidServlet().getControlAndActionSuffix(); // set response as text response.setContentType("text/text"); // get the application Application application = rapidRequest.getApplication(); // print the app name and version out.print("Application : " + application.getName() + "/" + application.getVersion() + "\n"); // get the page headers PageHeaders pageHeaders = application.getPages().getSortedPages(); // get the pages config folder File appPagesFolder = new File(application.getConfigFolder(context) + "/pages"); // check it exists if (appPagesFolder.exists()) { // loop the page headers for (PageHeader pageHeader : pageHeaders) { // get the page Page page = application.getPages().getPage(context, pageHeader.getId()); // print the page name and id out.print("\nPage : " + page.getName() + "/" + page.getId() + "\n\n"); // loop the files for (File pageFile : appPagesFolder.listFiles()) { // if this is a page.xml file if (pageFile.getName().endsWith(".page.xml")) { // assume no id's found // read the copy to a string String pageXML = Strings.getString(pageFile); // get all page controls List<Control> controls = page.getAllControls(); // loop controls for (Control control : controls) { // get old/current id String id = control.getId(); // assume new id will be the same String newId = id; // drop suffix if starts with it if (newId.startsWith(suffix)) newId = newId.substring(suffix.length()); // add suffix to end newId += suffix; // check if id in file if (pageXML.contains(id)) { // show old and new id out.print(id + " ---> " + newId + " found in page file " + pageFile + "\n"); // replace pageXML = pageXML.replace(id, newId); } } // get all page actions List<Action> actions = page.getAllActions(); // loop actions for (Action action : actions) { // get old/current id String id = action.getId(); // assume new id will be the same String newId = id; // drop suffix if starts with it if (newId.startsWith(suffix)) newId = newId.substring(suffix.length()); // add suffix to end if not there already if (!newId.endsWith("_" + suffix)) newId += suffix; // check if id in file if (pageXML.contains(id)) { // show old and new id out.print(id + " ---> " + newId + " found in page file " + pageFile + "\n"); // replace pageXML = pageXML.replace(id, newId); } } // save it back Strings.saveString(pageXML, pageFile); } //page ending check } // page file loop } //page loop // get the application file File applicationFile = new File(application.getConfigFolder(context) + "/application.xml"); // if it exists if (applicationFile.exists()) { // reload the application from file Application reloadedApplication = Application.load(context, applicationFile, true); // replace it into the applications collection getApplications().put(reloadedApplication); } } // app pages folder exists } else { // not authenticated response.setStatus(403); // say so out.print("Not authorised"); } // close the writer out.close(); // send it immediately out.flush(); } else if ("getStyleClasses".equals(actionName)) { String a = request.getParameter("a"); String v = request.getParameter("v"); Application application = getApplications().get(a, v); List<String> classNames = application.getStyleClasses(); JSONArray json = new JSONArray(classNames); output = json.toString(); sendJsonOutput(response, output); } // action name check } else { // not authenticated response.setStatus(403); } // got design role } // rapidSecurity != null } // rapidApplication != null // log the response if (logger.isTraceEnabled()) { logger.trace("Designer GET response : " + output); } else { logger.debug("Designer GET response : " + output.length() + " bytes"); } // add up the accumulated response data with the output responseLength += output.length(); // if monitor is alive then log the event if(_monitor != null && _monitor.isAlive(context) && _monitor.isLoggingAll()) _monitor.commitEntry(rapidRequest, response, responseLength); } catch (Exception ex) { // if monitor is alive then log the event if(_monitor != null && _monitor.isAlive(context) && _monitor.isLoggingExceptions()) _monitor.commitEntry(rapidRequest, response, responseLength, ex.getMessage()); logger.debug("Designer GET error : " + ex.getMessage(), ex); sendException(rapidRequest, response, ex); } } private Control createControl(JSONObject jsonControl) throws JSONException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { // instantiate the control with the JSON Control control = new Control(jsonControl); // look in the JSON for a validation object JSONObject jsonValidation = jsonControl.optJSONObject("validation"); // add the validation object if we got one if (jsonValidation != null) control.setValidation(Control.getValidation(this, jsonValidation)); // look in the JSON for an event array JSONArray jsonEvents = jsonControl.optJSONArray("events"); // add the events if we found one if (jsonEvents != null) control.setEvents(Control.getEvents(this, jsonEvents)); // look in the JSON for a styles array JSONArray jsonStyles = jsonControl.optJSONArray("styles"); // if there were styles if (jsonStyles != null) control.setStyles(Control.getStyles(this, jsonStyles)); // look in the JSON for any child controls JSONArray jsonControls = jsonControl.optJSONArray("childControls"); // if there were child controls loop and create controls interatively if (jsonControls != null) { for (int i = 0; i < jsonControls.length(); i++) { control.addChildControl(createControl(jsonControls.getJSONObject(i))); } } // return the control we just made return control; } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // get the rapid request RapidRequest rapidRequest = new RapidRequest(this, request); // retain the servlet context ServletContext context = rapidRequest.getServletContext(); // get a reference to our logger Logger logger = getLogger(); // if monitor is alive then log the event if (_monitor != null && _monitor.isAlive(context) && _monitor.isLoggingAll()) _monitor.openEntry(); // we will store the length of the item we are adding long responseLength = 0; // extra detail for the monitor log String monitorEntryDetails = null; try { // assume no output String output = ""; // get the rapid application Application rapidApplication = getApplications().get("rapid"); // check we got one if (rapidApplication != null) { // get rapid security SecurityAdapter rapidSecurity = rapidApplication.getSecurityAdapter(); // check we got some if (rapidSecurity != null) { // get user name String userName = rapidRequest.getUserName(); if (userName == null) userName = ""; // check permission if (rapidSecurity.checkUserRole(rapidRequest, Rapid.DESIGN_ROLE)) { Application application = rapidRequest.getApplication(); if (application != null) { // get the body bytes from the request byte[] bodyBytes = rapidRequest.getBodyBytes(); if ("savePage".equals(rapidRequest.getActionName())) { String bodyString = new String(bodyBytes, "UTF-8"); if (logger.isTraceEnabled()) { logger.trace("Designer POST request : " + request.getQueryString() + " body : " + bodyString); } else { logger.debug("Designer POST request : " + request.getQueryString() + " body : " + bodyString.length() + " bytes"); } JSONObject jsonPage = new JSONObject(bodyString); // instantiate a new blank page Page newPage = new Page(); // set page properties newPage.setId(jsonPage.optString("id")); newPage.setName(jsonPage.optString("name")); newPage.setTitle(jsonPage.optString("title")); newPage.setFormPageType(jsonPage.optInt("formPageType")); newPage.setLabel(jsonPage.optString("label")); newPage.setDescription(jsonPage.optString("description")); newPage.setSimple(jsonPage.optBoolean("simple")); newPage.setHideHeaderFooter(jsonPage.optBoolean("hideHeaderFooter")); // look in the JSON for an event array JSONArray jsonEvents = jsonPage.optJSONArray("events"); // add the events if we found one if (jsonEvents != null) newPage.setEvents(Control.getEvents(this, jsonEvents)); // look in the JSON for a styles array JSONArray jsonStyles = jsonPage.optJSONArray("styles"); // if there were styles get and save if (jsonStyles != null) newPage.setStyles(Control.getStyles(this, jsonStyles)); // look in the JSON for a style classes array JSONArray jsonStyleClasses = jsonPage.optJSONArray("classes"); // if there were style classes if (jsonStyleClasses != null) { // start with empty string String styleClasses = ""; // loop array and build classes list for (int i = 0; i < jsonStyleClasses.length(); i++) styleClasses += jsonStyleClasses.getString(i) + " "; // trim for good measure styleClasses = styleClasses.trim(); // store if something there if (styleClasses.length() > 0) newPage.setBodyStyleClasses(styleClasses); } // if there are child controls from the page loop them and add to the pages control collection JSONArray jsonControls = jsonPage.optJSONArray("childControls"); if (jsonControls != null) { for (int i = 0; i < jsonControls.length(); i++) { // get the JSON control JSONObject jsonControl = jsonControls.getJSONObject(i); // call our function so it can go iterative newPage.addControl(createControl(jsonControl)); } } // if there are roles specified for this page JSONArray jsonUserRoles = jsonPage.optJSONArray("roles"); if (jsonUserRoles != null) { List<String> userRoles = new ArrayList<>(); for (int i = 0; i < jsonUserRoles.length(); i++) { // get the JSON role String jsonUserRole = jsonUserRoles.getString(i); // add to collection userRoles.add(jsonUserRole); } // assign to page newPage.setRoles(userRoles); } /* // look in the JSON for a sessionVariables array JSONArray jsonSessionVariables = jsonPage.optJSONArray("sessionVariables"); // if we found one if (jsonSessionVariables != null) { List<String> sessionVariables = new ArrayList<>(); for (int i = 0; i < jsonSessionVariables.length(); i++) { sessionVariables.add(jsonSessionVariables.getString(i)); } newPage.setSessionVariables(sessionVariables); } */ // look in the JSON for a sessionVariables array JSONArray jsonPageVariables = jsonPage.optJSONArray("variables"); // if we found one if (jsonPageVariables != null) { Variables pageVariables = new Variables(); for (int i = 0; i < jsonPageVariables.length(); i++) { JSONObject jsonPageVariable = jsonPageVariables.getJSONObject(i); pageVariables.add(new Variable(jsonPageVariable.getString("name"), jsonPageVariable.optBoolean("session"))); } newPage.setVariables(pageVariables); } // look in the JSON for a pageVisibilityRules array JSONArray jsonVisibilityConditions = jsonPage.optJSONArray("visibilityConditions"); // if we found one if (jsonVisibilityConditions != null) { List<Condition> visibilityConditions = new ArrayList<>(); for (int i = 0; i < jsonVisibilityConditions.length(); i++) { visibilityConditions.add(new Condition(jsonVisibilityConditions.getJSONObject(i))); } newPage.setVisibilityConditions(visibilityConditions); } // look in the JSON for a pageVisibilityRules array is an and or or (default to and) String jsonConditionsType = jsonPage.optString("conditionsType","and"); // set what we got newPage.setConditionsType(jsonConditionsType); // retrieve the html body String htmlBody = jsonPage.optString("htmlBody"); // if we got one trim it and retain in page if (htmlBody != null) newPage.setHtmlBody(htmlBody.trim()); // look in the JSON for roleControlhtml JSONObject jsonRoleControlHtml = jsonPage.optJSONObject("roleControlHtml"); // if we found some add it to the page if (jsonRoleControlHtml != null) newPage.setRoleControlHtml(new RoleControlHtml(jsonRoleControlHtml)); // fetch a copy of the old page (if there is one) Page oldPage = application.getPages().getPage(context, newPage.getId()); // if the page's name changed we need to remove it if (oldPage != null) { if (!oldPage.getName().equals(newPage.getName())) { oldPage.delete(this, rapidRequest, application); } } // save the new page to file long fileSize = newPage.save(this, rapidRequest, application, true); monitorEntryDetails = "" + fileSize; // get any pages collection (we're only sent it if it's been changed) JSONArray jsonPages = jsonPage.optJSONArray("pages"); // if we got some if (jsonPages != null) { // make a new map for the page orders Map<String, Integer> pageOrders = new HashMap<>(); // loop the page orders for (int i = 0; i < jsonPages.length(); i++) { // get the page id String pageId = jsonPages.getJSONObject(i).getString("id"); // add the order to the map pageOrders.put(pageId, i); } // replace the application pageOrders map application.setPageOrders(pageOrders); // update the application start page (forms only) if (application.getIsForm() && jsonPages.length() > 0) application.setStartPageId(jsonPages.getJSONObject(0).getString("id")); // save the application and the new orders application.save(this, rapidRequest, true); } boolean jsonPageOrderReset = jsonPage.optBoolean("pageOrderReset"); // empty the application pageOrders map so everything goes alphabetical if (jsonPageOrderReset) application.setPageOrders(null); // send a positive message output = "{\"message\":\"Saved!\"}"; // set the response type to json response.setContentType("application/json"); } else if ("testSQL".equals(rapidRequest.getActionName())) { // turn the body bytes into a string String bodyString = new String(bodyBytes, "UTF-8"); JSONObject jsonQuery = new JSONObject(bodyString); JSONArray jsonInputs = jsonQuery.optJSONArray("inputs"); JSONArray jsonOutputs = jsonQuery.optJSONArray("outputs"); boolean childQuery = jsonQuery.optBoolean("childQuery"); int databaseConnectionIndex = jsonQuery.optInt("databaseConnectionIndex",0); if (application.getDatabaseConnections() == null || databaseConnectionIndex > application.getDatabaseConnections().size() - 1) { throw new Exception("Database connection cannot be found."); } else { // get the sql String sql = jsonQuery.optString("SQL", null); if (sql == null || sql.isEmpty()) { throw new Exception("SQL must be provided"); } else { // make a data factory for the connection with that index with auto-commit false DataFactory df = new DataFactory(context, application, databaseConnectionIndex, false); try { // assume no outputs int outputs = 0; // if got some outputs reduce the check count for any duplicates if (jsonOutputs != null) { // start with full number of outputs outputs = jsonOutputs.length(); // retain fields List<String> fieldList = new ArrayList<>(); // loop outputs for (int i = 0; i < jsonOutputs.length(); i++) { // look for a field String field = jsonOutputs.getJSONObject(i).optString("field", null); // if we got one if (field != null) { // check if we have it already if (fieldList.contains(field)) { // we do so reduce the control count by one outputs --; } else { // we don't have this field yet so remember fieldList.add(field); } } } } // trim the sql sql = sql.trim(); // merge in any parameters sql = application.insertParameters(context, sql); // some jdbc drivers need the line breaks removing before they'll work properly - here's looking at you MS SQL Server! sql = sql.replace("\n", " "); // placeholder for parameters we may need Parameters parameters = null; // if the query has inputs if (jsonInputs != null) { // make a list of inputs List<String> inputs = new ArrayList<>(); // make a parameters object to send parameters = new Parameters(); // populate it with nulls for (int i = 0; i < jsonInputs.length(); i++) { // get this input JSONObject input = jsonInputs.getJSONObject(i); String inputId = input.getString("itemId"); String field = input.getString("field"); if (!field.isEmpty()) inputId += "." + input.getString("field"); // add this input inputs.add(inputId); // add a null parameter for it parameters.addNull(); } // get a parameter map which is where we have ?'s followed by number/name List<Integer> parameterMap = Database.getParameterMap(sql, inputs, application, context); // get the right-sized parameters (if we need them) using the map parameters = Database.mapParameters(parameterMap, parameters); // remove all ? numbers/names from the sql sql = Database.unspecifySqlSlots(sql); } // clean the sql for checking - it has been trimmed already String sqlCheck = sql.replace(" ", "").toLowerCase(); // if it is more than 7 characters just trim it as "declare" is the longest we check for next - some parent statements are empty! if (sqlCheck.length() > 7) sqlCheck.substring(0, 7); // check outputs (unless a child query) if (outputs == 0 && !childQuery) { // check verb if (sqlCheck.startsWith("select")) { // select should have outputs throw new Exception("Select statement should have at least one output"); } else { // not a select so just prepare the statement by way of testing it df.getPreparedStatement(rapidRequest, sql, parameters).execute(); } } else { // check the verb if (sqlCheck.startsWith("select") || sqlCheck.startsWith("with")) { // get the prepared statement PreparedStatement ps = df.getPreparedStatement(rapidRequest, sql, parameters); // get the jdbc connection string String connString = df.getConnectionString(); // execute the statement - required by Oracle, but not MS SQL, causes "JDBC: inconsistent internal state" for SQLite if (!connString.toLowerCase().contains("jdbc:sqlite:")) ps.execute(); // get the meta data ResultSetMetaData rsmd = ps.getMetaData(); // get the result columns int cols = rsmd.getColumnCount(); // check there are enough columns for the outputs if (outputs > cols) throw new Exception(outputs + " outputs, but only " + cols + " column" + (cols > 1 ? "s" : "") + " selected"); // check the outputs for (int i = 0; i < outputs; i++) { // get this output JSONObject jsonOutput = jsonOutputs.getJSONObject(i); // get the output field - it can be null or a blank space so this way we standardise on the blank String field = jsonOutput.optString("field",""); // if there was one if (!"".equals(field)) { // lower case it field = field.toLowerCase(); // assume we can't find a column for this output field boolean gotOutput = false; // loop the columns for (int j = 0; j < cols; j++) { // look for a query column with the same name as the field String sqlField = rsmd.getColumnLabel(j + 1).toLowerCase(); // if we got one if (field.equals(sqlField)) { // remember gotOutput = true; // we're done break; } } // if we didn't get this output if (!gotOutput) { ps.close(); df.close(); throw new Exception("Field \"" + field + "\" from output " + (i + 1) + " is not present in selected columns"); } } } // close the recordset ps.close(); } else if (sqlCheck.startsWith("exec") || sqlCheck.startsWith("begin") || sqlCheck.startsWith("declare")) { // get the prepared statement to check the parameters df.getPreparedStatement(rapidRequest, sql, parameters).execute(); } else if (sqlCheck.startsWith("call") || sqlCheck.startsWith("{call")) { // execute the callable statement to check for errors df.executeCallableStatement(rapidRequest, sql, parameters); } else { // get the prepared statement to check the parameters df.getPreparedStatement(rapidRequest, sql, parameters).execute(); // check the verb if (sqlCheck.startsWith("insert") || sqlCheck.startsWith("update") || sqlCheck.startsWith("delete")) { // loop the outputs for (int i = 0; i < outputs; i++) { // get the output JSONObject jsonOutput = jsonOutputs.getJSONObject(i); // get it's field, if present String field = jsonOutput.optString("field",""); // if we got a field if (!"".equals(field)) { field = field.toLowerCase(); if (!"rows".equals(field)) throw new Exception("Field \"" + field + "\" from output " + (i + 1) + " can only be \"rows\""); } } } else { throw new Exception("SQL statement not recognised"); } } // rollback anything df.rollback(); // close the data factory df.close(); } } catch (Exception ex) { // if we had a df if (df != null) { // rollback anything df.rollback(); // close the data factory df.close(); } // rethrow to inform user throw ex; } // send a positive message output = "{\"message\":\"OK\"}"; // set the response type to json response.setContentType("application/json"); } // sql check } // connection check } else if ("uploadImage".equals(rapidRequest.getActionName()) || "import".equals(rapidRequest.getActionName())) { // get the content type from the request String contentType = request.getContentType(); // get the position of the boundary from the content type int boundaryPosition = contentType.indexOf("boundary="); // derive the start of the meaning data by finding the boundary String boundary = contentType.substring(boundaryPosition + 10); // this is the double line break after which the data occurs byte[] pattern = {0x0D, 0x0A, 0x0D, 0x0A}; // find the position of the double line break int dataPosition = Bytes.findPattern(bodyBytes, pattern ); // the body header is everything up to the data String header = new String(bodyBytes, 0, dataPosition, "UTF-8"); // find the position of the filename in the data header int filenamePosition = header.indexOf("filename=\""); // extract the file name String filename = header.substring(filenamePosition + 10, header.indexOf("\"", filenamePosition + 10)); // find the position of the file type in the data header int fileTypePosition = header.toLowerCase().indexOf("type:"); // extract the file type String fileType = header.substring(fileTypePosition + 6); if ("uploadImage".equals(rapidRequest.getActionName())) { // check the file type if (!fileType.equals("image/jpeg") && !fileType.equals("image/gif") && !fileType.equals("image/png") && !fileType.equals("image/svg+xml") && !fileType.equals("application/pdf")) throw new Exception("Unsupported file type"); // get the web folder from the application String path = rapidRequest.getApplication().getWebFolder(context); // create a file output stream to save the data to FileOutputStream fos = new FileOutputStream (path + "/" + filename); // write the file data to the stream fos.write(bodyBytes, dataPosition + pattern.length, bodyBytes.length - dataPosition - pattern.length - boundary.length() - 9); // close the stream fos.close(); // log the file creation logger.debug("Saved image file " + path + filename); // create the response with the file name and upload type output = "{\"file\":\"" + filename + "\",\"type\":\"" + rapidRequest.getActionName() + "\"}"; } else if ("import".equals(rapidRequest.getActionName())) { // check the file type if (!"application/x-zip-compressed".equals(fileType) && !"application/zip".equals(fileType)) throw new Exception("Unsupported file type"); // get the name String appName = request.getParameter("name"); // check we were given one if (appName == null) throw new Exception("Name must be provided"); // get the version String appVersion = request.getParameter("version"); // check we were given one if (appVersion == null) throw new Exception("Version must be provided"); // look for keep settings boolean keepSettings = "true".equals(request.getParameter("settings")); // make the id from the safe and lower case name String appId = Files.safeName(appName).toLowerCase(); // make the version from the safe and lower case name appVersion = Files.safeName(appVersion); // get application destination folder File appFolderDest = new File(Application.getConfigFolder(context, appId, appVersion)); // get web contents destination folder File webFolderDest = new File(Application.getWebFolder(context, appId, appVersion)); // look for an existing application of this name and version Application existingApplication = getApplications().get(appId, appVersion); // if we have an existing application if (existingApplication != null) { // back it up first existingApplication.backup(this, rapidRequest, false); } // get a file for the temp directory File tempDir = new File(context.getRealPath("/") + "WEB-INF/temp"); // create it if not there if (!tempDir.exists()) tempDir.mkdir(); // the path we're saving to is the temp folder String path = context.getRealPath("/") + "/WEB-INF/temp/" + appId + ".zip"; // create a file output stream to save the data to FileOutputStream fos = new FileOutputStream (path); // write the file data to the stream fos.write(bodyBytes, dataPosition + pattern.length, bodyBytes.length - dataPosition - pattern.length - boundary.length() - 9); // close the stream fos.close(); // log the file creation logger.debug("Saved import file " + path); // get a file object for the zip file File zipFile = new File(path); // load it into a zip file object ZipFile zip = new ZipFile(zipFile); // unzip the file zip.unZip(); // delete the zip file zipFile.delete(); // unzip folder (for deletion) File unZipFolder = new File(context.getRealPath("/") + "/WEB-INF/temp/" + appId); // get application folders File appFolderSource = new File(context.getRealPath("/") + "/WEB-INF/temp/" + appId + "/WEB-INF"); // get web content folders File webFolderSource = new File(context.getRealPath("/") + "/WEB-INF/temp/" + appId + "/WebContent"); // check we have the right source folders if (webFolderSource.exists() && appFolderSource.exists()) { // get application.xml file File appFileSource = new File (appFolderSource + "/application.xml"); if (appFileSource.exists()) { // delete the appFolder if it exists if (appFolderDest.exists()) Files.deleteRecurring(appFolderDest); // delete the webFolder if it exists if (webFolderDest.exists()) Files.deleteRecurring(webFolderDest); // copy application content Files.copyFolder(appFolderSource, appFolderDest); // copy web content Files.copyFolder(webFolderSource, webFolderDest); try { // load the new application (but don't initialise, nor load pages) Application appNew = Application.load(context, new File (appFolderDest + "/application.xml"), false); // update application name appNew.setName(appName); // get the old id String appOldId = appNew.getId(); // make the new id appId = Files.safeName(appName).toLowerCase(); // update the id appNew.setId(appId); // get the old version String appOldVersion = appNew.getVersion(); // make the new version appVersion = Files.safeName(appVersion); // update the version appNew.setVersion(appVersion); // update the created by appNew.setCreatedBy(userName); // update the created date appNew.setCreatedDate(new Date()); // set the status to In development appNew.setStatus(Application.STATUS_DEVELOPMENT); // get the previous version Application appPrev = getApplications().get(appOldId); // if we're keeping settings if (keepSettings) { // if we had one if (appPrev != null) { // update database connections from old version appNew.setDatabaseConnections(appPrev.getDatabaseConnections()); // update parameters from old version appNew.setParameters(appPrev.getParameters()); // update settings from old version Application latestVersion = getApplications().get(appId); Settings oldSettings = Settings.load(context, latestVersion); appNew.setSettings(oldSettings); } // old version check } // keepSettings // a map of actions that might be unrecognised in any of the pages Map<String,Integer> unknownActions = new HashMap<>(); // a map of actions that might be unrecognised in any of the pages Map<String,Integer> unknownControls = new HashMap<>(); // look for page files File pagesFolder = new File(appFolderDest.getAbsolutePath() + "/pages"); // if the folder is there if (pagesFolder.exists()) { // create a filter for finding .page.xml files FilenameFilter xmlFilenameFilter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".page.xml"); } }; // loop the .page.xml files for (File pageFile : pagesFolder.listFiles(xmlFilenameFilter)) { // read the file into a string String fileString = Strings.getString(pageFile); // prepare a new file string which will update into String newFileString = null; // if the old app did not have a version (for backwards compatibility) if (appOldVersion == null) { // replace all properties that appear to have a url, and all created links - note the fix for cleaning up the double encoding newFileString = fileString .replace("applications/" + appOldId + "/", "applications/" + appId + "/" + appVersion + "/") .replace("~?a=" + appOldId + "&amp;", "~?a=" + appId + "&amp;v=" + appVersion + "&amp;") .replace("~?a=" + appOldId + "&amp;amp;", "~?a=" + appId + "&amp;v=" + appVersion + "&amp;"); } else { // replace all properties that appear to have a url, and all created links - note the fix for double encoding newFileString = fileString .replace("applications/" + appOldId + "/" + appOldVersion + "/", "applications/" + appId + "/" + appVersion + "/") .replace("~?a=" + appOldId + "&amp;v=" + appOldVersion + "&amp;", "~?a=" + appId + "&amp;v=" + appVersion + "&amp;") .replace("~?a=" + appOldId + "&amp;amp;v=" + appOldVersion + "&amp;amp;", "~?a=" + appId + "&amp;v=" + appVersion + "&amp;"); } // now open the string into a document Document pageDocument = XML.openDocument(newFileString); // get an xpath factory XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); // an expression for any attributes with a local name of "type" - to find actions XPathExpression expr = xpath.compile("//@*[local-name()='type']"); // get them NodeList nl = (NodeList) expr.evaluate(pageDocument, XPathConstants.NODESET); // get out system actions JSONArray jsonActions = getJsonActions(); // if we found any elements with a type attribute and we have system actions if (nl.getLength() > 0 && jsonActions.length() > 0) { // a list of action types List<String> types = new ArrayList<>(); // loop the json actions for (int i = 0; i < jsonActions.length(); i++) { // get the type String type = jsonActions.getJSONObject(i).optString("type").toLowerCase(); // if don't have it already add it if (!types.contains(type)) types.add(type); } // loop the action attributes we found for (int i = 0; i < nl.getLength(); i++) { // get this attribute Attr a = (Attr) nl.item(i); // get the value of the type String type = a.getTextContent().toLowerCase(); // remove any namespace if (type.contains(":")) type = type.substring(type.indexOf(":") + 1); // get the element the attribute is in Node n = a.getOwnerElement(); // if we don't know about this action type if (!types.contains(type)) { // assume this is the first int unknownCount = 1; // increment the count of unknown controls if (unknownActions.containsKey(type)) unknownCount = unknownActions.get(type) + 1; // store it unknownActions.put(type, unknownCount); } // got type check } // attribute loop } // attribute and system action check // an expression for any controls to get their type expr = xpath.compile("//controls/properties/entry[key='type']/value"); // get them nl = (NodeList) expr.evaluate(pageDocument, XPathConstants.NODESET); // get out system controls JSONArray jsonControls = getJsonControls(); // if we found any elements with a type attribute and we have system actions if (nl.getLength() > 0 && jsonControls.length() > 0) { // a list of action types List<String> types = new ArrayList<>(); // loop the json actions for (int i = 0; i < jsonControls.length(); i++) { // get the type String type = jsonControls.getJSONObject(i).optString("type").toLowerCase(); // if don't have it already add it if (!types.contains(type)) types.add(type); } // loop the control elements we found for (int i = 0; i < nl.getLength(); i++) { // get this element Element e = (Element) nl.item(i); // get the value of the type String type = e.getTextContent().toLowerCase(); // remove any namespace if (type.contains(":")) type = type.substring(type.indexOf(":") + 1); // if we don't know about this action type if (!types.contains(type)) { // assume this is the first int unknownCount = 1; // increment the count of unknown controls if (unknownControls.containsKey(type)) unknownCount = unknownControls.get(type) + 1; // store it unknownControls.put(type, unknownCount); } // got type check } // control loop } // control node loop // use the transformer to write to disk TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(pageDocument); StreamResult result = new StreamResult(pageFile); transformer.transform(source, result); } // page xml file loop } // pages folder check // if any items were removed if (unknownActions.keySet().size() > 0 || unknownControls.keySet().size() > 0) { // delete unzip folder Files.deleteRecurring(unZipFolder); // start error message String error = "Application can't be imported: "; // loop unknown actions for (String key : unknownActions.keySet()) { // get the number int count = unknownActions.get(key); // add message with correct plural error += count + " unrecognised action" + (count == 1 ? "" : "s") + " of type \"" + key + "\", "; } // loop unknown controls for (String key : unknownControls.keySet()) { // get the number int count = unknownControls.get(key); // add message with correct plural error += unknownControls.get(key) + " unrecognised control" + (count == 1 ? "" : "s") + " of type \"" + key + "\", "; } // remove the last comma error = error.substring(0, error.length() - 2); // throw the exception throw new Exception(error); } try { // now initialise with the new id but don't make the resource files (this reloads the pages and sets up the security adapter) appNew.initialise(context, false); } catch (Exception ex) { // log logger.error("Error initialising app on import : " + ex.getMessage(), ex); // usually the security adapter so set back to Rapid appNew.setSecurityAdapterType("rapid"); // try again appNew.initialise(context, false); } /* This was a different attempt tp only remove and add users to the new version from the previous that weren't already there but it doesn't take passwords into account // get the security for this application SecurityAdapter securityNew = appNew.getSecurityAdapter(); // if we're keeping settings, and there is an old app, and the security adapter allows users to be added if (keepSettings && appPrev != null && SecurityAdapter.hasManageUsers(context, appNew.getSecurityAdapterType())) { // a Rapid request we'll use to delete users from the new app RapidRequest deleteRequest = new RapidRequest(this, request, appNew); // get all users of the new app to remove Users usersNewToRemove = securityNew.getUsers(rapidRequest); // get all users of the new app to not add back as they're already there Users usersNewToNotAdd = securityNew.getUsers(rapidRequest); // get the security adapter from the previous version we want to keep the users from SecurityAdapter securityPrev = appPrev.getSecurityAdapter(); // get any old users (from the previous version) Users usersPrev = securityPrev.getUsers(rapidRequest); // if there are users from the previous version if (usersPrev != null && usersPrev.size() > 0) { // if there are current users if (usersNewToRemove != null && usersNewToRemove.size() > 0) { // remove any old users from the current users list (we don't want to delete them, just to add them back) usersNewToRemove.removeAll(usersPrev); // remove all new users that aren't previous version users for (int i = 0; i < usersNewToRemove.size(); i++) { // get this user User user = usersNewToRemove.get(i); // set their name in the delete Rapid request deleteRequest.setUserName(user.getName()); // delete users currently in the app from the import that we don't want in the new version securityNew.deleteUser(deleteRequest); } // remove new users from previous users so we don't add them back again usersPrev.removeAll(usersNewToNotAdd); } // add previous users to the new app that aren't already there for (User userPrev : usersPrev) { // add the old user to the new app securityNew.addUser(rapidRequest, userPrev); } } else { // if we failed to get users using the specified security make the new "safe" Rapid security adapter for the new app securityNew = new RapidSecurityAdapter(context, appNew); // add it to the new app appNew.setSecurityAdapter(context, "rapid"); } // old users check } // new app allows adding users and there is an old app to get them from */ // get the security for this application SecurityAdapter securityNew = appNew.getSecurityAdapter(); // if we're keeping settings, and there is an old app, and they're both Rapid if (keepSettings && appPrev != null && "rapid".equals(appPrev.getSecurityAdapterType()) && "rapid".equals(appNew.getSecurityAdapterType())) { // a Rapid request we'll use to delete users from the new app RapidRequest deleteRequest = new RapidRequest(this, request, appNew); // get all current users of the new app Users usersNew = securityNew.getUsers(rapidRequest); // if there are users if (usersNew != null && usersNew.size() > 0) { // remove all current of the new app for (int i = 0; i < usersNew.size(); i++) { // get this user User user = usersNew.get(i); // set their name in the delete Rapid request deleteRequest.setUserName(user.getName()); // delete them securityNew.deleteUser(deleteRequest); } } // users check // get the old security adapter SecurityAdapter securityOld = appPrev.getSecurityAdapter(); // get any old users from the previous version Users usersPrev = securityOld.getUsers(rapidRequest); // if there are users if (usersPrev != null && usersPrev.size() > 0) { // add old users to the new app for (User userOld : usersPrev) { // add the old user to the new app securityNew.addUser(rapidRequest, userOld); } } else { // if we failed to get users using the specified security make the new "safe" Rapid security adapter for the new app securityNew = new RapidSecurityAdapter(context, appNew); // add it to the new app appNew.setSecurityAdapter(context, "rapid"); } } // new app allows adding users and there is an old app to get them from // make a rapid request in the name of the import application RapidRequest importRapidRequest = new RapidRequest(this, request, appNew); // assume we don't have the user boolean gotUser = false; // allow for the user to be outside the try/catch below User user = null; try { // get the current user's record from the adapter user = securityNew.getUser(importRapidRequest); } catch (SecurityAdapaterException ex) { // log logger.error("Error getting user on app import : " + ex.getMessage(), ex); // set a new Rapid security adapter for the app (it will construct it) appNew.setSecurityAdapter(context, "rapid"); // retrieve the security adapter we just asked to be made securityNew = appNew.getSecurityAdapter(); } // check the current user is present in the app's security adapter if (user != null) { // now check the current user password is correct too if (securityNew.checkUserPassword(importRapidRequest, userName, rapidRequest.getUserPassword())) { // we have the right user with the right password gotUser = true; } else { // remove this user in case there is one with the same name but the password does not match securityNew.deleteUser(importRapidRequest); } } // if we don't have the user if (!gotUser) { // get the current user from the Rapid application User rapidUser = rapidSecurity.getUser(importRapidRequest); // create a new user based on the Rapid user user = new User(rapidUser); // add the new user to this application securityNew.addUser(importRapidRequest, user); } // add Admin roles for the new user if not present if (!securityNew.checkUserRole(importRapidRequest, com.rapid.server.Rapid.ADMIN_ROLE)) securityNew.addUserRole(importRapidRequest, com.rapid.server.Rapid.ADMIN_ROLE); // add Design role for the new user if not present if (!securityNew.checkUserRole(importRapidRequest, com.rapid.server.Rapid.DESIGN_ROLE)) securityNew.addUserRole(importRapidRequest, com.rapid.server.Rapid.DESIGN_ROLE); // reload the pages (actually clears down the pages collection and reloads the headers) appNew.getPages().loadpages(context); // save application (this will also initialise and rebuild the resources) long fileSize = appNew.save(this, rapidRequest, false); monitorEntryDetails = "" + fileSize; // add application to the collection getApplications().put(appNew); // delete unzip folder Files.deleteRecurring(unZipFolder); // send a positive message output = "{\"id\":\"" + appNew.getId() + "\",\"version\":\"" + appNew.getVersion() + "\"}"; } catch (Exception ex) { // delete the appFolder if it exists if (appFolderDest.exists()) Files.deleteRecurring(appFolderDest); // if the parent is empty delete it too if (appFolderDest.getParentFile().list().length <= 1) Files.deleteRecurring(appFolderDest.getParentFile()); // delete the webFolder if it exists if (webFolderDest.exists()) Files.deleteRecurring(webFolderDest); // if the parent is empty delete it too if (webFolderDest.getParentFile().list().length <= 1) Files.deleteRecurring(webFolderDest.getParentFile()); // rethrow exception throw ex; } } else { // delete unzip folder Files.deleteRecurring(unZipFolder); // throw excpetion throw new Exception("Must be a valid Rapid " + Rapid.VERSION + " file"); } } else { // delete unzip folder Files.deleteRecurring(unZipFolder); // throw excpetion throw new Exception("Must be a valid Rapid file"); } } } if (logger.isTraceEnabled()) { logger.trace("Designer POST response : " + output); } else { logger.debug("Designer POST response : " + output.length() + " bytes"); } PrintWriter out = response.getWriter(); out.print(output); out.close(); // record response size responseLength = output.length(); } // got an application } // got rapid design role } // got rapid security } // got rapid application // if monitor is alive then log the event if (_monitor != null && _monitor.isAlive(context) && _monitor.isLoggingAll()) { _monitor.setDetails(monitorEntryDetails); _monitor.commitEntry(rapidRequest, response, responseLength); } } catch (Exception ex) { // if monitor is alive then log the event if (_monitor != null && _monitor.isAlive(context) && _monitor.isLoggingExceptions()) { _monitor.setDetails(monitorEntryDetails); _monitor.commitEntry(rapidRequest, response, responseLength, ex.getMessage()); } getLogger().error("Designer POST error : ",ex); sendException(rapidRequest, response, ex); } } }
src/com/rapid/server/Designer.java
/* Copyright (C) 2022 - Gareth Edwards / Rapid Information Systems [email protected] This file is part of the Rapid Application Platform Rapid 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. The terms require you to include the original copyright, and the license notice in all redistributions. 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 in a file named "COPYING". If not, see <http://www.gnu.org/licenses/>. */ package com.rapid.server; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.net.InetAddress; import java.sql.PreparedStatement; import java.sql.ResultSetMetaData; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.apache.logging.log4j.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.rapid.actions.Database; import com.rapid.actions.Logic; import com.rapid.actions.Logic.Condition; import com.rapid.core.Action; import com.rapid.core.Application; import com.rapid.core.Application.Parameter; import com.rapid.core.Application.Resource; import com.rapid.core.Application.Resources; import com.rapid.core.Application.ValueList; import com.rapid.core.Applications.Versions; import com.rapid.core.Control; import com.rapid.core.Event; import com.rapid.core.Page; import com.rapid.core.Page.Lock; import com.rapid.core.Page.RoleControlHtml; import com.rapid.core.Page.Variable; import com.rapid.core.Page.Variables; import com.rapid.core.Pages; import com.rapid.core.Pages.PageHeader; import com.rapid.core.Pages.PageHeaders; import com.rapid.core.Settings; import com.rapid.core.Theme; import com.rapid.core.Workflow; import com.rapid.core.Workflows; import com.rapid.data.DataFactory; import com.rapid.data.DataFactory.Parameters; import com.rapid.data.DatabaseConnection; import com.rapid.forms.FormAdapter; import com.rapid.security.RapidSecurityAdapter; import com.rapid.security.SecurityAdapter; import com.rapid.security.SecurityAdapter.Role; import com.rapid.security.SecurityAdapter.SecurityAdapaterException; import com.rapid.security.SecurityAdapter.User; import com.rapid.security.SecurityAdapter.Users; import com.rapid.utils.Bytes; import com.rapid.utils.Files; import com.rapid.utils.Strings; import com.rapid.utils.XML; import com.rapid.utils.ZipFile; public class Designer extends RapidHttpServlet { private static final long serialVersionUID = 2L; // this byte buffer is used for reading the post data byte[] _byteBuffer = new byte[1024]; public Designer() { super(); } // helper method to set the content type, write, and close the stream for common JSON output private void sendJsonOutput(HttpServletResponse response, String output) throws IOException { // set response as json response.setContentType("application/json"); // get a writer from the response PrintWriter out = response.getWriter(); // write the output into the response out.print(output); // close the writer out.close(); // send it immediately out.flush(); } // print indentation private void printIndentation(PrintWriter out, int level) { // loop level for (int i = 0; i < level; i++) { out.print("\t"); } } // print details of an action private void printAction(Action action, PrintWriter out, boolean details, int level) { // print any indentation printIndentation(out, level); // retain the level at this point int thislevel = level + 2; // print the action out.print("\t\tAction:\t" + action.getId() + "\t" + action.getType() + "\r\n"); // create a sorted list List<String> sortedKeys = new ArrayList<>(); // a map for the properties we're going to print Map<String, String> keyValues = new HashMap<>(); // only required for details if (details) { // get the object properties Map<String, String> objectProperties = action.getProperties(); // loop them for (String key : objectProperties.keySet()) { // add the key sortedKeys.add(key); // add the value keyValues.put(key, objectProperties.get(key)); } } // get a JSONObject for this action which will turn the get/set properties into keys JSONObject jsonAction = new JSONObject(action); // get it's properties Iterator<String> keys = jsonAction.keys(); // a map of child actions Map<String, List<Action>> keyChildActions = new HashMap<>(); // loop them while (keys.hasNext()) { // get the next one String key = keys.next(); // if not there already and details or actions if (!sortedKeys.contains(key) && (details || key.endsWith("Actions") || "actions".equals(key))) { // add the key sortedKeys.add(key); try { // if the key ends with actions if ((key.endsWith("Actions") || "actions".equals(key)) && action.getChildActions() != null && action.getChildActions().size() > 0) { // get the child actions JSONArray jsonChildActions = jsonAction.optJSONArray(key); // if we got some if (jsonChildActions != null) { // list of child actions for this key List<Action> childActions = new ArrayList<>(); // loop the child actions for (int i = 0; i < jsonChildActions.length(); i++) { // get this one JSONObject jsonChildAction = jsonChildActions.getJSONObject(i); // get its id String childId = jsonChildAction.optString("id", null); // if there was one if (childId != null) { // loop them List<Action> as = action.getChildActions(); for (Action childAction : as) { // print the child actions if (childId.equals(childAction.getId())) { // add the child action childActions.add(childAction); // we're done break; } } } } // add the child actions for this key keyChildActions.put(key, childActions); } } else { String str = JSONObject.valueToString(jsonAction.get(key)); if (looksLikeJSONObject(str)) { JSONObject jsonObject = jsonAction.getJSONObject(key); str = printJSONObject(jsonObject, thislevel).replaceAll("\r\n\t*\r\n", "\r\n"); } else if (looksLikeJSONArray(str)) { JSONArray jsonArray = jsonAction.getJSONArray(key); str = printJSONArray(jsonArray, thislevel).replaceAll("\r\n\t*\r\n", "\r\n"); } // add the value keyValues.put(key, str); } } catch (JSONException e) {} } } // sort the keys Collections.sort(sortedKeys, String.CASE_INSENSITIVE_ORDER); // loop the sorted keys for (String key : sortedKeys) { // print it if not id, nor properties itself if (!"id".equals(key) && !"properties".equals(key) && !"type".equals(key) && !"childActions".equals(key)) { // print any indentation printIndentation(out, level); // print the key out.print("\t\t\t" + key); // get any child actions List<Action> childActions = keyChildActions.get(key); // if there are child actions for this key if (childActions != null) { // loop the child actions for (Action childAction : childActions) { // print a new line out.print("\r\n"); // print the child actions printAction(childAction, out, details, thislevel); } } else { // print the value out.print("\t" + keyValues.get(key) + "\r\n"); } } } } private static String printJSONObject(JSONObject jsonObject, int level) throws JSONException { int thisLevel = level + 2; String output = ""; Iterator<String> keys = jsonObject.keys(); while (keys.hasNext()) { String key = keys.next(); output += "\r\n"; for (int i = 0; i < thisLevel; i++) output += "\t"; // we want line breaks and tabs in values printed as is (not escaped) String value = jsonObject.get(key).toString(); // if it has line breaks - add one in front so it all appears on the margin if (value != null && value.contains("\n")) value = "\r\n" + value; if (looksLikeJSONObject(value)) { value = printJSONObject(jsonObject.getJSONObject(key), thisLevel); } else if (looksLikeJSONArray(value)) { value = printJSONArray(jsonObject.getJSONArray(key), thisLevel); } output += key + "\t" + value; } return output; } private static String printJSONArray(JSONArray jsonArray, int level) throws JSONException { int thisLevel = level + 2; String output = ""; for (int i = 0; i < jsonArray.length(); i++) { output += "\r\n"; String value = JSONObject.valueToString(jsonArray.get(i)); if (looksLikeJSONObject(value)) { value = printJSONObject(jsonArray.getJSONObject(i), level); } else if (looksLikeJSONArray(value)) { value = printJSONArray(jsonArray.getJSONArray(i), level); } else { for (int j = 0; j < thisLevel; j++) output += "\t"; } output += value; } return output; } private static boolean looksLikeJSONObject(String str) { return str.startsWith("{") && str.endsWith("}"); } private static boolean looksLikeJSONArray(String str) { return str.startsWith("[") && str.endsWith("]"); } // print details of events (used by page and controls) private void printEvents(List<Event> events, PrintWriter out, boolean details) { // check events if (events!= null) { if (events.size() > 0) { // loop them for (Event event : events) { // check actions if (event.getActions() != null) { if (event.getActions().size() > 0) { // print the event out.print("\tEvent:\t" + event.getType() + "\r\n"); // loop the actions for (Action action : event.getActions()) { // print the action details printAction(action, out, details, 0); } } } } } } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // fake a delay for testing slow servers // try { Thread.sleep(3000); } catch (InterruptedException e) {} // get request as Rapid request RapidRequest rapidRequest = new RapidRequest(this, request); // retain the servlet context ServletContext context = rapidRequest.getServletContext(); // get a reference to our logger Logger logger = getLogger(); // if monitor is alive then log the event if(_monitor != null && _monitor.isAlive(context) && _monitor.isLoggingAll()) _monitor.openEntry(); // we will store the length of the item we are adding long responseLength = 0; try { logger.debug("Designer GET request : " + request.getQueryString()); String actionName = rapidRequest.getActionName(); String output = ""; // get the rapid application Application rapidApplication = getApplications().get("rapid"); // check we got one if (rapidApplication != null) { // get rapid security SecurityAdapter rapidSecurity = rapidApplication.getSecurityAdapter(); // check we got some if (rapidSecurity != null) { // get the user name String userName = rapidRequest.getUserName(); // get the rapid user User rapidUser = rapidSecurity.getUser(rapidRequest); // check permission if (rapidSecurity.checkUserRole(rapidRequest, Rapid.DESIGN_ROLE)) { // whether we're trying to avoid caching boolean noCaching = Boolean.parseBoolean(context.getInitParameter("noCaching")); if (noCaching) { // try and avoid caching response.setHeader("Expires", "Sat, 15 March 1980 12:00:00 GMT"); // Set standard HTTP/1.1 no-cache headers. response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // Set IE extended HTTP/1.1 no-cache headers (use addHeader). response.addHeader("Cache-Control", "post-check=0, pre-check=0"); // Set standard HTTP/1.0 no-cache header. response.setHeader("Pragma", "no-cache"); } if ("getSystemData".equals(actionName)) { // create a system data object JSONObject jsonSystemData = new JSONObject(); // add the controls jsonSystemData.put("controls", getJsonControls()); // add the actions jsonSystemData.put("actions", getJsonActions()); // add the devices jsonSystemData.put("devices", getDevices()); // add the local date format jsonSystemData.put("localDateFormat", getLocalDateFormat()); // look for a controlAndActionSuffix String controlAndActionSuffix = context.getInitParameter("controlAndActionSuffix"); // update to empty string if not present - this is the default and expected for older versions of the web.xml if (controlAndActionSuffix == null) controlAndActionSuffix = ""; // add the controlAndActionPrefix jsonSystemData.put("controlAndActionSuffix", controlAndActionSuffix); // put into output string output = jsonSystemData.toString(); // send output as json sendJsonOutput(response, output); } else if ("getApps".equals(actionName)) { // create a json array for holding our apps JSONArray jsonApps = new JSONArray(); // get a sorted list of the applications for (String id : getApplications().getIds()) { // loop the versions for (String version : getApplications().getVersions(id).keySet()) { // get the this application version Application application = getApplications().get(id, version); // get the security SecurityAdapter security = application.getSecurityAdapter(); // recreate the request in the name of this app RapidRequest appRequest = new RapidRequest(this, request, application); // check the users password if (security.checkUserPassword(appRequest, rapidRequest.getUserName(), rapidRequest.getUserPassword())) { // check the users permission to design this application boolean designPermission = security.checkUserRole(appRequest, Rapid.DESIGN_ROLE); // if app is rapid do a further check if (designPermission && "rapid".equals(application.getId())) designPermission = security.checkUserRole(appRequest, Rapid.SUPER_ROLE); // if we got permssion - add this application to the list if (designPermission) { // create a json object JSONObject jsonApplication = new JSONObject(); // add the details we want jsonApplication.put("id", application.getId()); jsonApplication.put("name", application.getName()); jsonApplication.put("title", application.getTitle()); // add the object to the collection jsonApps.put(jsonApplication); // no need to check any further versions break; } } } } output = jsonApps.toString(); sendJsonOutput(response, output); } else if ("getVersions".equals(actionName)) { // create a json array for holding our apps JSONArray jsonVersions = new JSONArray(); // get the app id String appId = rapidRequest.getAppId(); // get the versions Versions versions = getApplications().getVersions(appId); // if there are any if (versions != null) { // loop the list of applications sorted by id (with rapid last) for (Application application : versions.sort()) { // get the security SecurityAdapter security = application.getSecurityAdapter(); // recreate the request in the name of this app RapidRequest appRequest = new RapidRequest(this, request, application); // check the users password if (security.checkUserPassword(appRequest, rapidRequest.getUserName(), rapidRequest.getUserPassword())) { // check the users permission to design this application boolean designPermission = application.getSecurityAdapter().checkUserRole(appRequest, Rapid.DESIGN_ROLE); // if app is rapid do a further check if (designPermission && "rapid".equals(application.getId())) designPermission = security.checkUserRole(appRequest, Rapid.SUPER_ROLE); // check the RapidDesign role is present in the users roles for this application if (designPermission) { // make a json object for this version JSONObject jsonVersion = new JSONObject(); // add the app id jsonVersion.put("id", application.getId()); // add the version jsonVersion.put("version", application.getVersion()); // add the status jsonVersion.put("status", application.getStatus()); // add the title jsonVersion.put("title", application.getTitle()); // add a formAdapter if present if (application.getIsForm()) jsonVersion.put("isForm", true); // add whether to show control Ids jsonVersion.put("showControlIds", application.getShowControlIds()); // add whether to show action Ids jsonVersion.put("showActionIds", application.getShowActionIds()); // add the web folder so we can update the iframe style sheets jsonVersion.put("webFolder", Application.getWebFolder(application)); // get the database connections List<DatabaseConnection> databaseConnections = application.getDatabaseConnections(); // check we have any if (databaseConnections != null) { // make an object we're going to return JSONArray jsonDatabaseConnections = new JSONArray(); // loop the connections for (DatabaseConnection databaseConnection : databaseConnections) { // add the connection name jsonDatabaseConnections.put(databaseConnection.getName()); } // add the connections to the app jsonVersion.put("databaseConnections", jsonDatabaseConnections); } // make an object we're going to return JSONArray jsonRoles = new JSONArray(); // retrieve the roles List<Role> roles = security.getRoles(appRequest); // check we got some if (roles != null) { // create a collection of names ArrayList<String> roleNames = new ArrayList<>(); // copy the names in if non-null for (Role role : roles) if (role.getName() != null) roleNames.add(role.getName()); // sort them Collections.sort(roleNames); // loop the sorted connections for (String roleName : roleNames) { // only add role if this is the rapid app, or it's not a special rapid permission if ("rapid".equals(application.getId()) || (!Rapid.ADMIN_ROLE.equals(roleName)&& !Rapid.SUPER_ROLE.equals(roleName) && !Rapid.USERS_ROLE.equals(roleName) && !Rapid.DESIGN_ROLE.equals(roleName))) jsonRoles.put(roleName); } } // add the security roles to the app jsonVersion.put("roles", jsonRoles); // get any value lists List<ValueList> valueLists = application.getValueLists(); // add all of the value lists jsonVersion.put("valueLists", valueLists); // get all the possible json actions JSONArray jsonActions = getJsonActions(); // make an array for the actions in this app JSONArray jsonAppActions = new JSONArray(); // get the types used in this app List<String> actionTypes = application.getActionTypes(); // if we have some if (actionTypes != null) { // loop the types used in this app for (String actionType : actionTypes) { // loop all the possible actions for (int i = 0; i < jsonActions.length(); i++) { // get an instance to the json action JSONObject jsonAction = jsonActions.getJSONObject(i); // if this is the type we've been looking for if (actionType.equals(jsonAction.getString("type"))) { // create a simple json object for thi action JSONObject jsonAppAction = new JSONObject(); // add just what we need jsonAppAction.put("type", jsonAction.getString("type")); jsonAppAction.put("name", jsonAction.getString("name")); jsonAppAction.put("visible", jsonAction.optBoolean("visible", true)); // add it to the app actions collection jsonAppActions.put(jsonAppAction); // start on the next app action break; } } } } // put the app actions we've just built into the app jsonVersion.put("actions", jsonAppActions); // get all the possible json controls JSONArray jsonControls = getJsonControls(); // make an array for the controls in this app JSONArray jsonAppControls = new JSONArray(); // get the control types used by this app List<String> controlTypes = application.getControlTypes(); // if we have some if (controlTypes != null) { // loop the types used in this app for (String controlType : controlTypes) { // loop all the possible controls for (int i = 0; i < jsonControls.length(); i++) { // get an instance to the json control JSONObject jsonControl = jsonControls.getJSONObject(i); // if this is the type we've been looking for if (controlType.equals(jsonControl.getString("type"))) { // create a simple json object for this control JSONObject jsonAppControl = new JSONObject(); // add just what we need jsonAppControl.put("type", jsonControl.getString("type")); jsonAppControl.put("name", jsonControl.getString("name")); jsonAppControl.put("image", jsonControl.optString("image")); jsonAppControl.put("category", jsonControl.optString("category")); jsonAppControl.put("canUserAdd", jsonControl.optString("canUserAdd")); // add it to the app controls collection jsonAppControls.put(jsonAppControl); // start on the next app control break; } } } } // put the app controls we've just built into the app jsonVersion.put("controls", jsonAppControls); // create a json object for the images JSONArray jsonImages = new JSONArray(); // get the directory in which the control xml files are stored File dir = new File (application.getWebFolder(context)); // if it exists (might not if deleted from the file system and apps not refreshed) if (dir.exists()) { // create a filter for finding image files FilenameFilter xmlFilenameFilter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".png") || name.toLowerCase().endsWith(".gif") || name.toLowerCase().endsWith(".jpg") || name.toLowerCase().endsWith(".jpeg") || name.toLowerCase().endsWith(".svg"); } }; // an array to hold the images as they come out of the filter List<String> images = new ArrayList<>(); // loop the image files in the folder for (File imageFile : dir.listFiles(xmlFilenameFilter)) { images.add(imageFile.getName()); } // sort the images Collections.sort(images); // loop the sorted images and add to json for (String image : images) jsonImages.put(image); } // put the images collection we've just built into the app jsonVersion.put("images", jsonImages); // create a json array for our style classes JSONArray jsonStyleClasses = new JSONArray(); // get all of the possible style classes List<String> styleClasses = application.getStyleClasses(); // if we had some if (styleClasses != null) { // loop and add to json array for (String styleClass : styleClasses) jsonStyleClasses.put(styleClass); } // put them into our application object jsonVersion.put("styleClasses", jsonStyleClasses); // look for any form adpter FormAdapter formAdapter = application.getFormAdapter(); // if we got one if (formAdapter != null) { // get the type String formAdapterType = formAdapter.getType(); // get the json form adpater details JSONArray jsonFormAdapters = getJsonFormAdapters(); // if we got some if (jsonFormAdapters != null) { // loop them for (int i = 0; i < jsonFormAdapters.length(); i++) { // get this form adapter JSONObject jsonFormAdapter = jsonFormAdapters.getJSONObject(i); // if this is the one we want if (formAdapterType.equals(jsonFormAdapter.optString("type"))) { // add the properties to the version jsonVersion.put("canSaveForms", jsonFormAdapter.optBoolean("canSaveForms")); jsonVersion.put("canGeneratePDF", jsonFormAdapter.optBoolean("canGeneratePDF")); jsonVersion.put("canSupportIntegrationProperties", jsonFormAdapter.optBoolean("canSupportIntegrationProperties")); // we're done break; } } } } // put the app into the collection jsonVersions.put(jsonVersion); } // design permission } // check user password } // versions loop } // got versions check output = jsonVersions.toString(); sendJsonOutput(response, output); } else if ("getPages".equals(actionName)) { Application application = rapidRequest.getApplication(); if (application == null) { // send an empty object output = "{}"; } else { JSONArray jsonPages = new JSONArray(); String startPageId = ""; Page startPage = application.getStartPage(context); if (startPage != null) startPageId = startPage.getId(); // loop the page headers for (PageHeader pageHeader : application.getPages().getSortedPages()) { // get the page - yip this means that apps loaded in the designer load all of their pages Page page = application.getPages().getPage(context, pageHeader.getId()); // create a simple json object for the page JSONObject jsonPage = new JSONObject(); // add simple properties jsonPage.put("id", page.getId()); jsonPage.put("name", page.getName()); jsonPage.put("title", page.getTitle()); jsonPage.put("label", page.getLabel()); jsonPage.put("simple", page.getSimple()); jsonPage.put("hideHeaderFooter", page.getHideHeaderFooter()); /* // get a list of page session variables - now deprecated by page variables with the optional session storage List<String> pageSessionVariables = page.getSessionVariables(); // add them if there are some if (pageSessionVariables != null) if (pageSessionVariables.size() > 0) jsonPage.put("sessionVariables", pageSessionVariables); */ // get page variables Variables pageVariables = page.getVariables(); // add them if there are some if (pageVariables != null && pageVariables.size() > 0) jsonPage.put("variables", pageVariables); // assume we don't need to know page visibilty boolean includePageVisibiltyControls = false; // if there is a form adapter if (application.getFormAdapter() != null) { // set to true includePageVisibiltyControls = true; // add visibility conditions List<Condition> pageVisibilityConditions = page.getVisibilityConditions(); // add them if there are some if (pageVisibilityConditions != null) if (pageVisibilityConditions.size() > 0) jsonPage.put("visibilityConditions", pageVisibilityConditions); } // assume no page is selected in the designer that we want dialogue controls for Boolean includeFromDialogue = false; // if this loadPages was from a save if (Boolean.parseBoolean(rapidRequest.getRequest().getParameter("fromSave"))) { // get the page from the rapidRequest Page designPage = rapidRequest.getPage(); // if there was one if (designPage != null) { // get the pageId String pageId = page.getId(); // if we are saving a page in the designer, we will want to includeFromDialogue on all of the others if (!pageId.equals(designPage.getId())) { // get the list of pages we can open a dialogue to on this page List<String> dialoguePageIds = page.getDialoguePageIds(); // if designerPageId is provided and this page is different from the one we're loading in the designer if (dialoguePageIds != null) { // if the page in the designer is one this page can navigate to as a dialogue if (dialoguePageIds.contains(designPage.getId())) includeFromDialogue = true; } } } } // get map of other page controls we can access from this page - keep designer page id null to avoid dialogue controls and events JSONArray jsonControls = page.getOtherPageComponents(this, includePageVisibiltyControls, includeFromDialogue); // if we got some add to the page if (jsonControls != null) jsonPage.put("controls", jsonControls); // check if the start page and add property if so if (startPageId.equals(page.getId())) jsonPage.put("startPage", true); // add the page to the collection jsonPages.put(jsonPage); } // set the output to the collection turned into a string output = jsonPages.toString(); } // application check sendJsonOutput(response, output); } else if ("getPage".equals(actionName)) { Application application = rapidRequest.getApplication(); Page page = rapidRequest.getPage(); if (page != null) { // assume we can't find the user String userDescription = "unknown"; // get the user User user = application.getSecurityAdapter().getUser(rapidRequest); // if we had one and they have a description use it if (user != null) if (user.getDescription() != null) userDescription = user.getDescription(); // remove any existing page locks for this user application.removeUserPageLocks(context, userName); // check the page lock (which removes it if it has expired) page.checkLock(); // if there is no current lock add a fresh one for the current user if (page.getLock() == null) page.setLock(new Lock(userName, userDescription, new Date())); // turn it into json JSONObject jsonPage = new JSONObject(page); // remove the bodyHtml property as it is rebuilt in the designer jsonPage.remove("htmlBody"); // remove the rolesHtml property as it is rebuilt in the designer jsonPage.remove("rolesHtml"); // remove allControls (the single all-control list) it is not required jsonPage.remove("allControls"); // remove the otherPageControls property as it is sent with getPages jsonPage.remove("otherPageControls"); // remove bodyStyleClasses property as it should be called classes jsonPage.remove("bodyStyleClasses"); // add the bodyStyleClasses as classes array if (page.getBodyStyleClasses() != null) jsonPage.put("classes", page.getBodyStyleClasses().split(" ")); // add a nicely formatted lock time if (page.getLock() != null && jsonPage.optJSONObject("lock") != null) { // get the date time formatter and format the lock date time String formattedDateTime = getLocalDateTimeFormatter().format(page.getLock().getDateTime()); // add a special property to the json jsonPage.getJSONObject("lock").put("formattedDateTime", formattedDateTime); } // add the css jsonPage.put("css", page.getAllCSS(context, application)); // add the device as page properties (even though we store this in the app) jsonPage.put("device", 1); jsonPage.put("zoom", 1); jsonPage.put("orientation", "P"); // add the form page type jsonPage.put("formPageType", page.getFormPageType()); // get any theme Theme theme = application.getTheme(context); // if there was one if (theme != null) { // check for headerHtmlDesigner if (theme.getHeaderHtmlDesigner() != null) { // add headerHtmlDesigner html jsonPage.put("headerHtml", theme.getHeaderHtmlDesigner()); } else { // add header html jsonPage.put("headerHtml", theme.getHeaderHtml()); } // check for footerHtmlDesigner if (theme.getFooterHtmlDesigner() != null) { // add footerHtmlDesigner html jsonPage.put("footerHtml", theme.getFooterHtmlDesigner()); } else { // add footer html jsonPage.put("footerHtml", theme.getFooterHtml()); } } // create an other pages object JSONObject jsonOtherPages = new JSONObject(); // get the pages Pages pages = application.getPages(); // get the pages headers PageHeaders pageHeaders = pages.getSortedPages(); // loop the page headers for (PageHeader pageHeader : pageHeaders) { // get this page id String pageId = page.getId(); // if we are loading a specific page and need to know any other components for it and this is not the destination page itself if (!pageId.equals(pageHeader.getId())) { // get the other page Page otherPage = application.getPages().getPage(context, pageHeader.getId()); // get the list of pages we can open a dialogue to on this page List<String> dialoguePageIds = otherPage.getDialoguePageIds(); // if we can open dialogues on this page if (dialoguePageIds != null) { // if the page id the designer is one this page navigates to on a dialogue if (dialoguePageIds.contains(pageId)) { // get other page components for this page JSONArray jsonControls = otherPage.getOtherPageComponents(this, false, true); // if we got some if (jsonControls != null) { // if we got some if (jsonControls.length() > 0) { // create an other page object JSONObject jsonOtherPage = new JSONObject(); // add the controls to the page jsonOtherPage.put("controls", jsonControls); // add the other page to the page collection jsonOtherPages.put(otherPage.getId(), jsonOtherPage); } } } } // dialoguePageIds check } } // get the list of pages that appear in a page panel on this page List<String> pagePanelPageIds = page.getPagePanelPageIds(); // if designerPageId is provided and this page is different from the one we're loading in the designer if (pagePanelPageIds != null) { // loop them for (String pagePanelPageId : pagePanelPageIds) { // get this page Page pagePanelPage = pages.getPage(context, pagePanelPageId); // get other page components for this page JSONArray jsonControls = pagePanelPage.getOtherPageComponents(this, false, true); // if we got some if (jsonControls != null) { // if we got some if (jsonControls.length() > 0) { // create an other page object JSONObject jsonOtherPage = new JSONObject(); // add the controls to the page jsonOtherPage.put("controls", jsonControls); // add the other page to the page collection jsonOtherPages.put(pagePanelPageId, jsonOtherPage); } } } } // pagePanelPageIds check // if other pages objects add to page if (jsonOtherPages.length() > 0) jsonPage.put("otherPages", jsonOtherPages); // print it to the output output = jsonPage.toString(); // send as json response sendJsonOutput(response, output); } } else if ("getFlows".equals(actionName)) { // the JSON array of workflows we are going to return JSONArray jsonFlows = new JSONArray(); // the JSON workflow we are going to return JSONObject jsonFlow = new JSONObject(); // give it an id and a name jsonFlow.put("id", "1"); jsonFlow.put("name", "Test"); // add it to the array jsonFlows.put(jsonFlow); // print it to the output output = jsonFlows.toString(); // send as json response sendJsonOutput(response, output); } else if ("getFlowVersions".equals(actionName)) { // the JSON array of workflows we are going to return JSONArray jsonFlows = new JSONArray(); // the JSON workflow we are going to return JSONObject jsonFlow = new JSONObject(); // give it an id and a name jsonFlow.put("version", "1"); jsonFlow.put("status", "0"); // the JSON array of workflows we are going to return JSONArray jsonActions = new JSONArray(); JSONArray jsonAllActions = getJsonActions(); // loop all actions for now for (int i = 0; i < jsonAllActions.length(); i++) { // get all action JSONObject jsonAllAction = jsonAllActions.getJSONObject(i); // if it is allowed in workflow if (jsonAllAction.optBoolean("canUseWorkflow")) { JSONObject jsonAction = new JSONObject(); jsonAction.put("type", jsonAllActions.getJSONObject(i).getString("type")); jsonActions.put(jsonAction); } } jsonFlow.put("actions",jsonActions); // add it to the array jsonFlows.put(jsonFlow); // print it to the output output = jsonFlows.toString(); // send as json response sendJsonOutput(response, output); } else if ("getFlow".equals(actionName)) { // the JSON workflow we are going to return JSONObject jsonFlow = new JSONObject(); // give it an id and a name jsonFlow.put("id", "1"); jsonFlow.put("name", "Test"); // print it to the output output = jsonFlow.toString(); // send as json response sendJsonOutput(response, output); } else if ("checkApp".equals(actionName)) { String appName = request.getParameter("name"); if (appName != null) { // retain whether we have an app with this name boolean exists = getApplications().exists(Files.safeName(appName)); // set the response output = Boolean.toString(exists); // send response as json sendJsonOutput(response, output); } } else if ("checkVersion".equals(actionName)) { String appName = request.getParameter("name"); String appVersion = request.getParameter("version"); if (appName != null && appVersion != null ) { // retain whether we have an app with this name boolean exists = getApplications().exists(Files.safeName(appName), Files.safeName(appVersion)); // set the response output = Boolean.toString(exists); // send response as json sendJsonOutput(response, output); } } else if ("checkPage".equals(actionName)) { String pageName = request.getParameter("name"); if (pageName != null) { // retain whether we have an app with this name boolean pageExists = false; // get the application Application application = rapidRequest.getApplication(); if (application != null) { for (PageHeader page : application.getPages().getSortedPages()) { if (pageName.toLowerCase().equals(page.getName().toLowerCase())) { pageExists = true; break; } } } // set the output output = Boolean.toString(pageExists); // send response as json sendJsonOutput(response, output); } } else if ("checkWorkflow".equals(actionName)) { String name = request.getParameter("name"); if (name != null) { // retain whether we have an app with this name boolean exists = false; // get the workflows Workflows workflows = getWorkflows(); // look for this on Workflow workflow = workflows.get(Files.safeName(name)); // if we got one if (workflow != null) exists = true; // set the output output = Boolean.toString(exists); // send response as json sendJsonOutput(response, output); } } else if ("pages".equals(actionName) || "questions".equals(actionName) || "text".equals(actionName) || "summary".equals(actionName) || "detail".equals(actionName)) { // set response as text response.setContentType("text/plain;charset=utf-8"); // get a writer from the response PrintWriter out = response.getWriter(); // get the application Application application = rapidRequest.getApplication(); // get the page headers PageHeaders pageHeaders = application.getPages().getSortedPages(); // get the root path String rootPath = context.getRealPath("/"); // get the root file File root = new File(rootPath); // get a date/time formatter SimpleDateFormat df = getLocalDateTimeFormatter(); // write some useful things at the top out.print("Server name:\t" + InetAddress.getLocalHost().getHostName() + "\r\n"); out.print("Instance name:\t" + root.getName() + "\r\n"); out.print("Rapid version:\t" + Rapid.VERSION + "\r\n"); out.print("Date and time:\t" + df.format(new Date()) + "\r\n\r\n"); out.print("Rapid " + actionName + " report:\r\n\r\n\r\n"); // id out.print("Application id:\t" + application.getId() + "\r\n"); // version out.print("Version:\t" + application.getVersion() + "\r\n"); // name out.print("Name:\t" + application.getName() + "\r\n"); // title out.print("Title:\t" + application.getTitle() + "\r\n"); // app details if ("summary".equals(actionName) || "detail".equals(actionName)) { int statusId = application.getStatus(); String status = statusId == 0 ? "In development" : statusId == 1 ? "Live" : statusId == 2 ? "Under maintenance" : null; if (status != null) out.print("Status:\t" + status + "\r\n"); // safe created date if (application.getCreatedDate() != null) out.print("Created date:\t" + df.format(application.getCreatedDate()) + "\r\n"); // safe created by if (application.getCreatedBy() != null) out.print("Created by:\t" + application.getCreatedBy() + "\r\n"); // safe modified date if (application.getModifiedDate() != null) out.print("Modified date:\t" + df.format(application.getModifiedDate()) + "\r\n"); // safe modified by if (application.getModifiedBy() != null) out.print("Modified by:\t" + application.getModifiedBy() + "\r\n"); if (application.getStartPageId() != null) out.print("Start page:\t" + application.getStartPageId() + "\r\n"); // description if (application.getDescription() != null && application.getDescription().trim().length() > 0) out.print("Description:\t" + application.getDescription() + "\r\n"); out.print("Form settings:\t" + application.getIsForm() + "\r\n"); if (application.getIsForm()) { // form if (application.getIsForm()) out.print("Form adapter:\t" + application.getFormAdapterType() + "\r\n"); out.print("Show form summary:\t" + application.getFormShowSummary() + "\r\n"); out.print("Disable autocomplete:\t" + application.getFormDisableAutoComplete() + "\r\n"); } out.print("Email form:\t" + application.getFormEmail() + "\r\n"); if (application.getFormEmail()) { if (application.getFormEmailFrom() != null) out.print("From address:\t" + application.getFormEmailFrom() + "\r\n"); if (application.getFormEmailTo() != null) out.print("To address:\t" + application.getFormEmailTo() + "\r\n"); if (application.getFormEmailAttachmentType() != null) out.print("Attachment type:\t" + application.getFormEmailAttachmentType() + "\r\n"); } out.print("Email customer:\t" + application.getFormEmailCustomer() + "\r\n"); if (application.getFormEmailCustomer()) { if (application.getFormEmailCustomerControlId() != null) out.print("Customer address:\t" + application.getFormEmailCustomerControlId() + "\r\n"); String emailTypeCode = application.getFormEmailCustomerType(); String emailType = "T".equals(emailTypeCode) ? "Text" : "H".equals(emailTypeCode) ? "HTML" : null; if (emailType != null) out.print("Email type:\t" + emailType + "\r\n"); if (application.getFormEmailCustomerSubject() != null) out.print("Email subject:\t" + application.getFormEmailCustomerSubject() + "\r\n"); if (application.getFormEmailCustomerBody() != null) out.print("Email body:\t" + application.getFormEmailCustomerBody() + "\r\n"); String attachmentTypeCode = application.getFormEmailCustomerAttachmentType(); String attachmentType = "csv".equals(attachmentTypeCode) ? "CSV" : "xml".equals(attachmentTypeCode) ? "XML" : "pdf".equals(attachmentTypeCode) ? "PDF" : null; if (attachmentType != null) out.print("Attachment type:\t" + attachmentType + "\r\n"); out.print("Form details file:\t" + application.getFormFile() + "\r\n"); String typeCode = application.getFormFileType(); String type = "pdf".equals(typeCode) ? "PDF" : "xml".equals(typeCode) ? "XML" : "CSV"; out.print("File type:\t" + type + "\r\n"); if (application.getFormFilePath() != null) out.print("Path:\t" + application.getFormFilePath() + "\r\n"); if (application.getFormFileUserName() != null) out.print("Username:\t" + application.getFormFileUserName() + "\r\n"); } out.print("Form webservice:\t" + application.getFormWebservice() + "\r\n"); if (application.getFormWebservice()) { if (application.getFormWebserviceURL() != null) out.print("URL:\t" + application.getFormWebserviceURL() + "\r\n"); String webserviceTypeCode = application.getFormWebserviceType(); String webserviceType = "restful".equals(webserviceTypeCode) ? "Restful XML" : "json".equals(webserviceTypeCode) ? "JSON" : "SOAP"; out.print("Data type:\t" + webserviceType + "\r\n"); if (application.getFormWebserviceSOAPAction() != null) out.print("SOAP action:\t" + application.getFormWebserviceSOAPAction() + "\r\n"); } // theme out.print("Theme:\t" + application.getThemeType() + "\r\n"); } // App parameters List<Parameter> parameters = application.getParameters(); out.print("\r\nApplication parameters:\t" + parameters.size() + "\r\n"); for (Parameter parameter : parameters) { out.print("Name:\t" + parameter.getName() + "\r\n"); out.print("\tDescription:\t" + parameter.getDescription() + "\r\n"); out.print("\tValue:\t" + parameter.getValue() + "\r\n"); } out.println(); // DB connections List<DatabaseConnection> connections = application.getDatabaseConnections(); out.print("\r\nDatabase connections:\t" + connections.size() + "\r\n"); for (DatabaseConnection connection : connections) { out.print("Name:\t" + connection.getName() + "\r\n"); out.print("\tDriver:\t" + connection.getDriverClass() + "\r\n"); out.print("\tConnection string:\t" + connection.getConnectionString() + "\r\n"); out.print("\tUsername:\t" + connection.getUserName() + "\r\n"); } out.println(); // App settings String settings = application.getSettingsId(); if (settings != null && !settings.isEmpty()) out.print("Settings:\t" + settings + "\r\n"); out.println(); // pages out.print("Pages:\t" + pageHeaders.size() + "\r\n"); // double line break out.print("\r\n"); // get any page id String pageId = request.getParameter("p"); // loop the page headers for (PageHeader pageHeader : pageHeaders) { // get the page Page page = application.getPages().getPage(context, pageHeader.getId()); // if a specific page has been asked for continue until it comes up if (pageId != null && !page.getId().equals(pageId)) continue; // get the label String label = page.getLabel(); // if we got one if (label == null) { label = ""; } else { if (label.length() > 0) label = " - " + label; } if ("questions".equals(actionName)) { // print the name and label out.print(page.getTitle()); // get any visibility conditions List<Logic.Condition> visibilityConditions = page.getVisibilityConditions(); // if we got some if (visibilityConditions != null && visibilityConditions.size() > 0) { out.print(" ("); // loop them for (int i = 0; i < visibilityConditions.size(); i++) { // get the condition Logic.Condition condition = visibilityConditions.get(i); // get value 1 Control control1 = application.getControl(context, condition.getValue1().getId()); // if we got one print it's name if (control1 == null) { out.print(condition.getValue1().toString().replace("System.field/", "")); } else { out.print(control1.getName()); } // print operation out.print(" " + condition.getOperation() + " "); // get control 2 Control control2 = application.getControl(context, condition.getValue2().getId()); // if we got one print it's name if (control2 == null) { out.print(condition.getValue2().toString().replace("System.field/", "")); } else { if (control2.getLabel() == null || control2.getLabel().isEmpty()) { out.print(control2.getName()); } else { out.print(control2.getLabel()); } } // if there are more if (i < visibilityConditions.size() - 1) out.print(" " + page.getConditionsType() + " "); } out.print(")"); } // closing line break out.print("\r\n"); } else if ("text".equals(actionName)) { // print the page name with some space around it out.print(page.getTitle() + "\r\n"); } // page headers if ("pages".equals(actionName) || "detail".equals(actionName) || "summary".equals(actionName)) { // page id out.print("Page:\t" + page.getId() + "\r\n"); // page title out.print("Title:\t" + page.getTitle() + "\r\n"); // safe created date if (page.getCreatedDate() != null) out.print("Created date:\t" + df.format(page.getCreatedDate()) + "\r\n"); // safe created by if (page.getCreatedBy() != null) out.print("Created by:\t" + page.getCreatedBy() + "\r\n"); // safe modified date if (page.getModifiedDate() != null) out.print("Modified date:\t" + df.format(page.getModifiedDate()) + "\r\n"); // safe modified by if (page.getModifiedBy() != null) out.print("Modified by:\t" + page.getModifiedBy() + "\r\n"); // action summary if ("pages".equals(actionName) || "summary".equals(actionName)) { out.print("Actions:\t" + page.getAllActions().size() + "\r\n"); } // print the number of controls out.print("Controls:\t" + page.getAllControls().size() + "\r\n"); // events, action, and details if ("summary".equals(actionName)) { // print page events printEvents(page.getEvents(), out, false); } // events, action, and details if ("detail".equals(actionName)) { out.print("Description:\t" + page.getDescription() + "\r\n"); out.print("Simple:\t" + page.getSimple() + "\r\n"); out.print("HideHeaderFooter:\t" + page.getHideHeaderFooter() + "\r\n"); // print page events printEvents(page.getEvents(), out, true); } } // check questions, summary, detail if ("questions".equals(actionName) || "text".equals(actionName) || "summary".equals(actionName) || "detail".equals(actionName)) { // get the controls List<Control> controls = page.getAllControls(); // loop them for (Control control : controls) { // get the name String name = control.getName(); // name null check if ((name != null && name.trim().length() > 0) || "summary".equals(actionName) || "detail".equals(actionName) || "text".equals(actionName)) { // get the label label = control.getLabel(); // get the type String type = control.getType(); // exclude panels, hidden values (except for questions), and datastores for summary if ("summary".equals(actionName) || "detail".equals(actionName) || (!type.contains("panel") && (!("hiddenvalue").equals(type) || "questions".equals(actionName)) && !("dataStore").equals(type))) { // if questions it's likely to be a form if ("questions".equals(actionName)) { // look for a form object String formObject = control.getProperty("formObject"); // if there is a label but not a button, but radios are allowed if ((label != null && (!control.getType().contains("button") || control.getType().contains("radio"))) || formObject != null) { // use name if label null if (label == null) label = name; // print the label out.print("\t" + label); // if we got one if (formObject != null) { // Get form integration values String formObjectAttribute = control.getProperty("formObjectAttribute"); String formObjectRole = control.getProperty("formObjectRole"); String formObjectType = control.getProperty("formObjectType"); String formObjectPartyNumber = control.getProperty("formObjectPartyNumber"); String formObjectQuestionNumber = control.getProperty("formObjectQuestionNumber"); String formObjectAddressNumber = control.getProperty("formObjectAddressNumber"); String formObjectText = control.getProperty("formObjectText"); if (formObject != null && !formObject.equals("")) { out.print(" ("); if (formObject != null) out.print(formObject); if (!"other".equalsIgnoreCase(formObject)) if (formObjectRole != null) out.print(" - " + formObjectRole); if (formObjectPartyNumber != null) out.print(" - party: " + formObjectPartyNumber); if ("party".equals(formObject)) out.print(" " + formObjectAttribute); if ("contact".equals(formObject)) out.print(" " + formObjectType); if ("address".equals(formObject)) { if (formObjectAddressNumber != null) out.print(" - address: " + formObjectAddressNumber); if (formObjectType != null) out.print(" - " + formObjectType); if (formObjectAttribute != null) out.print(" - " + formObjectAttribute); } if ("question".equals(formObject) || "other".equals(formObject)) if (formObjectQuestionNumber != null) out.print(" - question: " + formObjectQuestionNumber); if (formObjectText != null && formObjectText.length() > 0) out.print(" - '" + formObjectText + "'"); out.print(")"); } } out.print("\r\n"); } } else if ("text".equals(actionName)) { // no buttons if (!control.getType().endsWith("button")) { // get the text String text = control.getProperty("text"); // print the text if there was some if (text != null) { // trim it and remove any line breaks text = text.trim().replace("\r", "").replace("\n", ""); // if we have some if (text.length() > 0) out.print(text + "\r\n"); } // try responsivelabel if we don't have one yet if (label == null) label = control.getProperty("responsiveLabel"); // print the label if there was some if (label != null && label.trim().length() > 0) out.print(label); // if any options String options = control.getProperty("options"); // if we got some if (options != null) { out.print(" ("); // read into JSON JSONArray jsonOptions = new JSONArray(options); // loop for (int i = 0; i < jsonOptions.length(); i++) { // get the option JSONObject JSONOption = jsonOptions.getJSONObject(i); // get the option's text out.print(JSONOption.getString("text")); // add a comma if one is required if (i < jsonOptions.length() - 1) out.print(", "); } out.print(")"); } // print a line break if there was pritning above if (label != null && label.trim().length() > 0) out.print("\r\n"); // if this is a grid if ("grid".equals(control.getType())) { out.print(control.getName() + " ("); // get the columns JSONArray jsonColumns = new JSONArray(control.getProperty("columns")); // loop them for (int i = 0; i < jsonColumns.length(); i++) { // get the option JSONObject JSONOption = jsonColumns.getJSONObject(i); // get the option's text out.print(JSONOption.getString("title")); // add a comma if one is required if (i < jsonColumns.length() - 1) out.print(", "); } out.print(")\r\n"); } } } else { // print the control details out.print("Control:\t" + control.getId() +"\t" + type + "\t"); // name if (name != null && name.length() > 0) out.print(name); // label if (label != null && label.length() > 0) out.print("\t" + label); // line break out.print("\r\n"); } // if summary if ("summary".equals(actionName)) printEvents(control.getEvents(), out, false); // if details if ("detail".equals(actionName)) { // get the properties Map<String, String> properties = control.getProperties(); // get a list we'll sort for them List<String> sortedKeys = new ArrayList<>(); // loop them for (String key : properties.keySet()) { // add to sorted list sortedKeys.add(key); } // sort them Collections.sort(sortedKeys); // loop them for (String key : sortedKeys) { // print the properties (but not the properties itself) if (!"properties".equals(key)) out.print(key + "\t" + properties.get(key) + "\r\n"); } // print the event details printEvents(control.getEvents(), out, true); } // detail check } // exclusion check } // name check } // control loop } // report action check // add space after the page out.print("\r\n"); } // page loop // App Resources Resources resources = application.getAppResources(); out.println("\r\nResources:\t" + resources.size() + "\r\n"); for (Resource resource : resources) { if (resource.getName() != null) out.print("Name:\t" + resource.getName() + "\r\n"); if (resource.getContent() != null) out.print("Content:\t" + resource.getContent() + "\r\n"); } out.println(); // App CSS String styles = application.getStyles(); out.print("Styles:\t\r\n"); out.print(styles + "\r\n"); // close the writer out.close(); // send it immediately out.flush(); } else if ("export".equals(actionName)) { // get the application Application application = rapidRequest.getApplication(); // check we've got one if (application != null) { // the file name is the app id, an under score and then an underscore-safe version String fileName = application.getId() + "_" + application.getVersion().replace("_", "-") + ".zip"; // get the file for the zip we're about to create File zipFile = application.zip(this, rapidRequest, rapidUser, fileName); // set the type as a .zip response.setContentType("application/x-zip-compressed"); // Shows the download dialog response.setHeader("Content-disposition","attachment; filename=" + fileName); // send the file to browser OutputStream out = response.getOutputStream(); FileInputStream in = new FileInputStream(zipFile); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0){ out.write(buffer, 0, length); } in.close(); out.flush(); // delete the .zip file zipFile.delete(); output = "Zip file sent"; } // got application } else if ("updateids".equals(actionName)) { // get a writer from the response PrintWriter out = response.getWriter(); // check we have admin too if (rapidSecurity.checkUserRole(rapidRequest, Rapid.ADMIN_ROLE)) { // get the suffix String suffix = rapidRequest.getRapidServlet().getControlAndActionSuffix(); // set response as text response.setContentType("text/text"); // get the application Application application = rapidRequest.getApplication(); // print the app name and version out.print("Application : " + application.getName() + "/" + application.getVersion() + "\n"); // get the page headers PageHeaders pageHeaders = application.getPages().getSortedPages(); // get the pages config folder File appPagesFolder = new File(application.getConfigFolder(context) + "/pages"); // check it exists if (appPagesFolder.exists()) { // loop the page headers for (PageHeader pageHeader : pageHeaders) { // get the page Page page = application.getPages().getPage(context, pageHeader.getId()); // print the page name and id out.print("\nPage : " + page.getName() + "/" + page.getId() + "\n\n"); // loop the files for (File pageFile : appPagesFolder.listFiles()) { // if this is a page.xml file if (pageFile.getName().endsWith(".page.xml")) { // assume no id's found // read the copy to a string String pageXML = Strings.getString(pageFile); // get all page controls List<Control> controls = page.getAllControls(); // loop controls for (Control control : controls) { // get old/current id String id = control.getId(); // assume new id will be the same String newId = id; // drop suffix if starts with it if (newId.startsWith(suffix)) newId = newId.substring(suffix.length()); // add suffix to end newId += suffix; // check if id in file if (pageXML.contains(id)) { // show old and new id out.print(id + " ---> " + newId + " found in page file " + pageFile + "\n"); // replace pageXML = pageXML.replace(id, newId); } } // get all page actions List<Action> actions = page.getAllActions(); // loop actions for (Action action : actions) { // get old/current id String id = action.getId(); // assume new id will be the same String newId = id; // drop suffix if starts with it if (newId.startsWith(suffix)) newId = newId.substring(suffix.length()); // add suffix to end if not there already if (!newId.endsWith("_" + suffix)) newId += suffix; // check if id in file if (pageXML.contains(id)) { // show old and new id out.print(id + " ---> " + newId + " found in page file " + pageFile + "\n"); // replace pageXML = pageXML.replace(id, newId); } } // save it back Strings.saveString(pageXML, pageFile); } //page ending check } // page file loop } //page loop // get the application file File applicationFile = new File(application.getConfigFolder(context) + "/application.xml"); // if it exists if (applicationFile.exists()) { // reload the application from file Application reloadedApplication = Application.load(context, applicationFile, true); // replace it into the applications collection getApplications().put(reloadedApplication); } } // app pages folder exists } else { // not authenticated response.setStatus(403); // say so out.print("Not authorised"); } // close the writer out.close(); // send it immediately out.flush(); } else if ("getStyleClasses".equals(actionName)) { String a = request.getParameter("a"); String v = request.getParameter("v"); Application application = getApplications().get(a, v); List<String> classNames = application.getStyleClasses(); JSONArray json = new JSONArray(classNames); output = json.toString(); sendJsonOutput(response, output); } // action name check } else { // not authenticated response.setStatus(403); } // got design role } // rapidSecurity != null } // rapidApplication != null // log the response if (logger.isTraceEnabled()) { logger.trace("Designer GET response : " + output); } else { logger.debug("Designer GET response : " + output.length() + " bytes"); } // add up the accumulated response data with the output responseLength += output.length(); // if monitor is alive then log the event if(_monitor != null && _monitor.isAlive(context) && _monitor.isLoggingAll()) _monitor.commitEntry(rapidRequest, response, responseLength); } catch (Exception ex) { // if monitor is alive then log the event if(_monitor != null && _monitor.isAlive(context) && _monitor.isLoggingExceptions()) _monitor.commitEntry(rapidRequest, response, responseLength, ex.getMessage()); logger.debug("Designer GET error : " + ex.getMessage(), ex); sendException(rapidRequest, response, ex); } } private Control createControl(JSONObject jsonControl) throws JSONException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { // instantiate the control with the JSON Control control = new Control(jsonControl); // look in the JSON for a validation object JSONObject jsonValidation = jsonControl.optJSONObject("validation"); // add the validation object if we got one if (jsonValidation != null) control.setValidation(Control.getValidation(this, jsonValidation)); // look in the JSON for an event array JSONArray jsonEvents = jsonControl.optJSONArray("events"); // add the events if we found one if (jsonEvents != null) control.setEvents(Control.getEvents(this, jsonEvents)); // look in the JSON for a styles array JSONArray jsonStyles = jsonControl.optJSONArray("styles"); // if there were styles if (jsonStyles != null) control.setStyles(Control.getStyles(this, jsonStyles)); // look in the JSON for any child controls JSONArray jsonControls = jsonControl.optJSONArray("childControls"); // if there were child controls loop and create controls interatively if (jsonControls != null) { for (int i = 0; i < jsonControls.length(); i++) { control.addChildControl(createControl(jsonControls.getJSONObject(i))); } } // return the control we just made return control; } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // get the rapid request RapidRequest rapidRequest = new RapidRequest(this, request); // retain the servlet context ServletContext context = rapidRequest.getServletContext(); // get a reference to our logger Logger logger = getLogger(); // if monitor is alive then log the event if (_monitor != null && _monitor.isAlive(context) && _monitor.isLoggingAll()) _monitor.openEntry(); // we will store the length of the item we are adding long responseLength = 0; // extra detail for the monitor log String monitorEntryDetails = null; try { // assume no output String output = ""; // get the rapid application Application rapidApplication = getApplications().get("rapid"); // check we got one if (rapidApplication != null) { // get rapid security SecurityAdapter rapidSecurity = rapidApplication.getSecurityAdapter(); // check we got some if (rapidSecurity != null) { // get user name String userName = rapidRequest.getUserName(); if (userName == null) userName = ""; // check permission if (rapidSecurity.checkUserRole(rapidRequest, Rapid.DESIGN_ROLE)) { Application application = rapidRequest.getApplication(); if (application != null) { // get the body bytes from the request byte[] bodyBytes = rapidRequest.getBodyBytes(); if ("savePage".equals(rapidRequest.getActionName())) { String bodyString = new String(bodyBytes, "UTF-8"); if (logger.isTraceEnabled()) { logger.trace("Designer POST request : " + request.getQueryString() + " body : " + bodyString); } else { logger.debug("Designer POST request : " + request.getQueryString() + " body : " + bodyString.length() + " bytes"); } JSONObject jsonPage = new JSONObject(bodyString); // instantiate a new blank page Page newPage = new Page(); // set page properties newPage.setId(jsonPage.optString("id")); newPage.setName(jsonPage.optString("name")); newPage.setTitle(jsonPage.optString("title")); newPage.setFormPageType(jsonPage.optInt("formPageType")); newPage.setLabel(jsonPage.optString("label")); newPage.setDescription(jsonPage.optString("description")); newPage.setSimple(jsonPage.optBoolean("simple")); newPage.setHideHeaderFooter(jsonPage.optBoolean("hideHeaderFooter")); // look in the JSON for an event array JSONArray jsonEvents = jsonPage.optJSONArray("events"); // add the events if we found one if (jsonEvents != null) newPage.setEvents(Control.getEvents(this, jsonEvents)); // look in the JSON for a styles array JSONArray jsonStyles = jsonPage.optJSONArray("styles"); // if there were styles get and save if (jsonStyles != null) newPage.setStyles(Control.getStyles(this, jsonStyles)); // look in the JSON for a style classes array JSONArray jsonStyleClasses = jsonPage.optJSONArray("classes"); // if there were style classes if (jsonStyleClasses != null) { // start with empty string String styleClasses = ""; // loop array and build classes list for (int i = 0; i < jsonStyleClasses.length(); i++) styleClasses += jsonStyleClasses.getString(i) + " "; // trim for good measure styleClasses = styleClasses.trim(); // store if something there if (styleClasses.length() > 0) newPage.setBodyStyleClasses(styleClasses); } // if there are child controls from the page loop them and add to the pages control collection JSONArray jsonControls = jsonPage.optJSONArray("childControls"); if (jsonControls != null) { for (int i = 0; i < jsonControls.length(); i++) { // get the JSON control JSONObject jsonControl = jsonControls.getJSONObject(i); // call our function so it can go iterative newPage.addControl(createControl(jsonControl)); } } // if there are roles specified for this page JSONArray jsonUserRoles = jsonPage.optJSONArray("roles"); if (jsonUserRoles != null) { List<String> userRoles = new ArrayList<>(); for (int i = 0; i < jsonUserRoles.length(); i++) { // get the JSON role String jsonUserRole = jsonUserRoles.getString(i); // add to collection userRoles.add(jsonUserRole); } // assign to page newPage.setRoles(userRoles); } /* // look in the JSON for a sessionVariables array JSONArray jsonSessionVariables = jsonPage.optJSONArray("sessionVariables"); // if we found one if (jsonSessionVariables != null) { List<String> sessionVariables = new ArrayList<>(); for (int i = 0; i < jsonSessionVariables.length(); i++) { sessionVariables.add(jsonSessionVariables.getString(i)); } newPage.setSessionVariables(sessionVariables); } */ // look in the JSON for a sessionVariables array JSONArray jsonPageVariables = jsonPage.optJSONArray("variables"); // if we found one if (jsonPageVariables != null) { Variables pageVariables = new Variables(); for (int i = 0; i < jsonPageVariables.length(); i++) { JSONObject jsonPageVariable = jsonPageVariables.getJSONObject(i); pageVariables.add(new Variable(jsonPageVariable.getString("name"), jsonPageVariable.optBoolean("session"))); } newPage.setVariables(pageVariables); } // look in the JSON for a pageVisibilityRules array JSONArray jsonVisibilityConditions = jsonPage.optJSONArray("visibilityConditions"); // if we found one if (jsonVisibilityConditions != null) { List<Condition> visibilityConditions = new ArrayList<>(); for (int i = 0; i < jsonVisibilityConditions.length(); i++) { visibilityConditions.add(new Condition(jsonVisibilityConditions.getJSONObject(i))); } newPage.setVisibilityConditions(visibilityConditions); } // look in the JSON for a pageVisibilityRules array is an and or or (default to and) String jsonConditionsType = jsonPage.optString("conditionsType","and"); // set what we got newPage.setConditionsType(jsonConditionsType); // retrieve the html body String htmlBody = jsonPage.optString("htmlBody"); // if we got one trim it and retain in page if (htmlBody != null) newPage.setHtmlBody(htmlBody.trim()); // look in the JSON for roleControlhtml JSONObject jsonRoleControlHtml = jsonPage.optJSONObject("roleControlHtml"); // if we found some add it to the page if (jsonRoleControlHtml != null) newPage.setRoleControlHtml(new RoleControlHtml(jsonRoleControlHtml)); // fetch a copy of the old page (if there is one) Page oldPage = application.getPages().getPage(context, newPage.getId()); // if the page's name changed we need to remove it if (oldPage != null) { if (!oldPage.getName().equals(newPage.getName())) { oldPage.delete(this, rapidRequest, application); } } // save the new page to file long fileSize = newPage.save(this, rapidRequest, application, true); monitorEntryDetails = "" + fileSize; // get any pages collection (we're only sent it if it's been changed) JSONArray jsonPages = jsonPage.optJSONArray("pages"); // if we got some if (jsonPages != null) { // make a new map for the page orders Map<String, Integer> pageOrders = new HashMap<>(); // loop the page orders for (int i = 0; i < jsonPages.length(); i++) { // get the page id String pageId = jsonPages.getJSONObject(i).getString("id"); // add the order to the map pageOrders.put(pageId, i); } // replace the application pageOrders map application.setPageOrders(pageOrders); // update the application start page (forms only) if (application.getIsForm() && jsonPages.length() > 0) application.setStartPageId(jsonPages.getJSONObject(0).getString("id")); // save the application and the new orders application.save(this, rapidRequest, true); } boolean jsonPageOrderReset = jsonPage.optBoolean("pageOrderReset"); // empty the application pageOrders map so everything goes alphabetical if (jsonPageOrderReset) application.setPageOrders(null); // send a positive message output = "{\"message\":\"Saved!\"}"; // set the response type to json response.setContentType("application/json"); } else if ("testSQL".equals(rapidRequest.getActionName())) { // turn the body bytes into a string String bodyString = new String(bodyBytes, "UTF-8"); JSONObject jsonQuery = new JSONObject(bodyString); JSONArray jsonInputs = jsonQuery.optJSONArray("inputs"); JSONArray jsonOutputs = jsonQuery.optJSONArray("outputs"); boolean childQuery = jsonQuery.optBoolean("childQuery"); int databaseConnectionIndex = jsonQuery.optInt("databaseConnectionIndex",0); if (application.getDatabaseConnections() == null || databaseConnectionIndex > application.getDatabaseConnections().size() - 1) { throw new Exception("Database connection cannot be found."); } else { // get the sql String sql = jsonQuery.optString("SQL", null); if (sql == null || sql.isEmpty()) { throw new Exception("SQL must be provided"); } else { // make a data factory for the connection with that index with auto-commit false DataFactory df = new DataFactory(context, application, databaseConnectionIndex, false); try { // assume no outputs int outputs = 0; // if got some outputs reduce the check count for any duplicates if (jsonOutputs != null) { // start with full number of outputs outputs = jsonOutputs.length(); // retain fields List<String> fieldList = new ArrayList<>(); // loop outputs for (int i = 0; i < jsonOutputs.length(); i++) { // look for a field String field = jsonOutputs.getJSONObject(i).optString("field", null); // if we got one if (field != null) { // check if we have it already if (fieldList.contains(field)) { // we do so reduce the control count by one outputs --; } else { // we don't have this field yet so remember fieldList.add(field); } } } } // trim the sql sql = sql.trim(); // merge in any parameters sql = application.insertParameters(context, sql); // some jdbc drivers need the line breaks removing before they'll work properly - here's looking at you MS SQL Server! sql = sql.replace("\n", " "); // placeholder for parameters we may need Parameters parameters = null; // if the query has inputs if (jsonInputs != null) { // make a list of inputs List<String> inputs = new ArrayList<>(); // make a parameters object to send parameters = new Parameters(); // populate it with nulls for (int i = 0; i < jsonInputs.length(); i++) { // get this input JSONObject input = jsonInputs.getJSONObject(i); String inputId = input.getString("itemId"); String field = input.getString("field"); if (!field.isEmpty()) inputId += "." + input.getString("field"); // add this input inputs.add(inputId); // add a null parameter for it parameters.addNull(); } // get a parameter map which is where we have ?'s followed by number/name List<Integer> parameterMap = Database.getParameterMap(sql, inputs, application, context); // get the right-sized parameters (if we need them) using the map parameters = Database.mapParameters(parameterMap, parameters); // remove all ? numbers/names from the sql sql = Database.unspecifySqlSlots(sql); } // clean the sql for checking - it has been trimmed already String sqlCheck = sql.replace(" ", "").toLowerCase(); // if it is more than 7 characters just trim it as "declare" is the longest we check for next - some parent statements are empty! if (sqlCheck.length() > 7) sqlCheck.substring(0, 7); // check outputs (unless a child query) if (outputs == 0 && !childQuery) { // check verb if (sqlCheck.startsWith("select")) { // select should have outputs throw new Exception("Select statement should have at least one output"); } else { // not a select so just prepare the statement by way of testing it df.getPreparedStatement(rapidRequest, sql, parameters).execute(); } } else { // check the verb if (sqlCheck.startsWith("select") || sqlCheck.startsWith("with")) { // get the prepared statement PreparedStatement ps = df.getPreparedStatement(rapidRequest, sql, parameters); // get the jdbc connection string String connString = df.getConnectionString(); // execute the statement - required by Oracle, but not MS SQL, causes "JDBC: inconsistent internal state" for SQLite if (!connString.toLowerCase().contains("jdbc:sqlite:")) ps.execute(); // get the meta data ResultSetMetaData rsmd = ps.getMetaData(); // get the result columns int cols = rsmd.getColumnCount(); // check there are enough columns for the outputs if (outputs > cols) throw new Exception(outputs + " outputs, but only " + cols + " column" + (cols > 1 ? "s" : "") + " selected"); // check the outputs for (int i = 0; i < outputs; i++) { // get this output JSONObject jsonOutput = jsonOutputs.getJSONObject(i); // get the output field - it can be null or a blank space so this way we standardise on the blank String field = jsonOutput.optString("field",""); // if there was one if (!"".equals(field)) { // lower case it field = field.toLowerCase(); // assume we can't find a column for this output field boolean gotOutput = false; // loop the columns for (int j = 0; j < cols; j++) { // look for a query column with the same name as the field String sqlField = rsmd.getColumnLabel(j + 1).toLowerCase(); // if we got one if (field.equals(sqlField)) { // remember gotOutput = true; // we're done break; } } // if we didn't get this output if (!gotOutput) { ps.close(); df.close(); throw new Exception("Field \"" + field + "\" from output " + (i + 1) + " is not present in selected columns"); } } } // close the recordset ps.close(); } else if (sqlCheck.startsWith("exec") || sqlCheck.startsWith("begin") || sqlCheck.startsWith("declare")) { // get the prepared statement to check the parameters df.getPreparedStatement(rapidRequest, sql, parameters).execute(); } else if (sqlCheck.startsWith("call") || sqlCheck.startsWith("{call")) { // execute the callable statement to check for errors df.executeCallableStatement(rapidRequest, sql, parameters); } else { // get the prepared statement to check the parameters df.getPreparedStatement(rapidRequest, sql, parameters).execute(); // check the verb if (sqlCheck.startsWith("insert") || sqlCheck.startsWith("update") || sqlCheck.startsWith("delete")) { // loop the outputs for (int i = 0; i < outputs; i++) { // get the output JSONObject jsonOutput = jsonOutputs.getJSONObject(i); // get it's field, if present String field = jsonOutput.optString("field",""); // if we got a field if (!"".equals(field)) { field = field.toLowerCase(); if (!"rows".equals(field)) throw new Exception("Field \"" + field + "\" from output " + (i + 1) + " can only be \"rows\""); } } } else { throw new Exception("SQL statement not recognised"); } } // rollback anything df.rollback(); // close the data factory df.close(); } } catch (Exception ex) { // if we had a df if (df != null) { // rollback anything df.rollback(); // close the data factory df.close(); } // rethrow to inform user throw ex; } // send a positive message output = "{\"message\":\"OK\"}"; // set the response type to json response.setContentType("application/json"); } // sql check } // connection check } else if ("uploadImage".equals(rapidRequest.getActionName()) || "import".equals(rapidRequest.getActionName())) { // get the content type from the request String contentType = request.getContentType(); // get the position of the boundary from the content type int boundaryPosition = contentType.indexOf("boundary="); // derive the start of the meaning data by finding the boundary String boundary = contentType.substring(boundaryPosition + 10); // this is the double line break after which the data occurs byte[] pattern = {0x0D, 0x0A, 0x0D, 0x0A}; // find the position of the double line break int dataPosition = Bytes.findPattern(bodyBytes, pattern ); // the body header is everything up to the data String header = new String(bodyBytes, 0, dataPosition, "UTF-8"); // find the position of the filename in the data header int filenamePosition = header.indexOf("filename=\""); // extract the file name String filename = header.substring(filenamePosition + 10, header.indexOf("\"", filenamePosition + 10)); // find the position of the file type in the data header int fileTypePosition = header.toLowerCase().indexOf("type:"); // extract the file type String fileType = header.substring(fileTypePosition + 6); if ("uploadImage".equals(rapidRequest.getActionName())) { // check the file type if (!fileType.equals("image/jpeg") && !fileType.equals("image/gif") && !fileType.equals("image/png") && !fileType.equals("image/svg+xml") && !fileType.equals("application/pdf")) throw new Exception("Unsupported file type"); // get the web folder from the application String path = rapidRequest.getApplication().getWebFolder(context); // create a file output stream to save the data to FileOutputStream fos = new FileOutputStream (path + "/" + filename); // write the file data to the stream fos.write(bodyBytes, dataPosition + pattern.length, bodyBytes.length - dataPosition - pattern.length - boundary.length() - 9); // close the stream fos.close(); // log the file creation logger.debug("Saved image file " + path + filename); // create the response with the file name and upload type output = "{\"file\":\"" + filename + "\",\"type\":\"" + rapidRequest.getActionName() + "\"}"; } else if ("import".equals(rapidRequest.getActionName())) { // check the file type if (!"application/x-zip-compressed".equals(fileType) && !"application/zip".equals(fileType)) throw new Exception("Unsupported file type"); // get the name String appName = request.getParameter("name"); // check we were given one if (appName == null) throw new Exception("Name must be provided"); // get the version String appVersion = request.getParameter("version"); // check we were given one if (appVersion == null) throw new Exception("Version must be provided"); // look for keep settings boolean keepSettings = "true".equals(request.getParameter("settings")); // make the id from the safe and lower case name String appId = Files.safeName(appName).toLowerCase(); // make the version from the safe and lower case name appVersion = Files.safeName(appVersion); // get application destination folder File appFolderDest = new File(Application.getConfigFolder(context, appId, appVersion)); // get web contents destination folder File webFolderDest = new File(Application.getWebFolder(context, appId, appVersion)); // look for an existing application of this name and version Application existingApplication = getApplications().get(appId, appVersion); // if we have an existing application if (existingApplication != null) { // back it up first existingApplication.backup(this, rapidRequest, false); } // get a file for the temp directory File tempDir = new File(context.getRealPath("/") + "WEB-INF/temp"); // create it if not there if (!tempDir.exists()) tempDir.mkdir(); // the path we're saving to is the temp folder String path = context.getRealPath("/") + "/WEB-INF/temp/" + appId + ".zip"; // create a file output stream to save the data to FileOutputStream fos = new FileOutputStream (path); // write the file data to the stream fos.write(bodyBytes, dataPosition + pattern.length, bodyBytes.length - dataPosition - pattern.length - boundary.length() - 9); // close the stream fos.close(); // log the file creation logger.debug("Saved import file " + path); // get a file object for the zip file File zipFile = new File(path); // load it into a zip file object ZipFile zip = new ZipFile(zipFile); // unzip the file zip.unZip(); // delete the zip file zipFile.delete(); // unzip folder (for deletion) File unZipFolder = new File(context.getRealPath("/") + "/WEB-INF/temp/" + appId); // get application folders File appFolderSource = new File(context.getRealPath("/") + "/WEB-INF/temp/" + appId + "/WEB-INF"); // get web content folders File webFolderSource = new File(context.getRealPath("/") + "/WEB-INF/temp/" + appId + "/WebContent"); // check we have the right source folders if (webFolderSource.exists() && appFolderSource.exists()) { // get application.xml file File appFileSource = new File (appFolderSource + "/application.xml"); if (appFileSource.exists()) { // delete the appFolder if it exists if (appFolderDest.exists()) Files.deleteRecurring(appFolderDest); // delete the webFolder if it exists if (webFolderDest.exists()) Files.deleteRecurring(webFolderDest); // copy application content Files.copyFolder(appFolderSource, appFolderDest); // copy web content Files.copyFolder(webFolderSource, webFolderDest); try { // load the new application (but don't initialise, nor load pages) Application appNew = Application.load(context, new File (appFolderDest + "/application.xml"), false); // update application name appNew.setName(appName); // get the old id String appOldId = appNew.getId(); // make the new id appId = Files.safeName(appName).toLowerCase(); // update the id appNew.setId(appId); // get the old version String appOldVersion = appNew.getVersion(); // make the new version appVersion = Files.safeName(appVersion); // update the version appNew.setVersion(appVersion); // update the created by appNew.setCreatedBy(userName); // update the created date appNew.setCreatedDate(new Date()); // set the status to In development appNew.setStatus(Application.STATUS_DEVELOPMENT); // get the previous version Application appOld = getApplications().get(appOldId); // if we're keeping settings if (keepSettings) { // if we had one if (appOld != null) { // update database connections from old version appNew.setDatabaseConnections(appOld.getDatabaseConnections()); // update parameters from old version appNew.setParameters(appOld.getParameters()); // update settings from old version Application latestVersion = getApplications().get(appId); Settings oldSettings = Settings.load(context, latestVersion); appNew.setSettings(oldSettings); } // old version check } // keepSettings // a map of actions that might be unrecognised in any of the pages Map<String,Integer> unknownActions = new HashMap<>(); // a map of actions that might be unrecognised in any of the pages Map<String,Integer> unknownControls = new HashMap<>(); // look for page files File pagesFolder = new File(appFolderDest.getAbsolutePath() + "/pages"); // if the folder is there if (pagesFolder.exists()) { // create a filter for finding .page.xml files FilenameFilter xmlFilenameFilter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".page.xml"); } }; // loop the .page.xml files for (File pageFile : pagesFolder.listFiles(xmlFilenameFilter)) { // read the file into a string String fileString = Strings.getString(pageFile); // prepare a new file string which will update into String newFileString = null; // if the old app did not have a version (for backwards compatibility) if (appOldVersion == null) { // replace all properties that appear to have a url, and all created links - note the fix for cleaning up the double encoding newFileString = fileString .replace("applications/" + appOldId + "/", "applications/" + appId + "/" + appVersion + "/") .replace("~?a=" + appOldId + "&amp;", "~?a=" + appId + "&amp;v=" + appVersion + "&amp;") .replace("~?a=" + appOldId + "&amp;amp;", "~?a=" + appId + "&amp;v=" + appVersion + "&amp;"); } else { // replace all properties that appear to have a url, and all created links - note the fix for double encoding newFileString = fileString .replace("applications/" + appOldId + "/" + appOldVersion + "/", "applications/" + appId + "/" + appVersion + "/") .replace("~?a=" + appOldId + "&amp;v=" + appOldVersion + "&amp;", "~?a=" + appId + "&amp;v=" + appVersion + "&amp;") .replace("~?a=" + appOldId + "&amp;amp;v=" + appOldVersion + "&amp;amp;", "~?a=" + appId + "&amp;v=" + appVersion + "&amp;"); } // now open the string into a document Document pageDocument = XML.openDocument(newFileString); // get an xpath factory XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); // an expression for any attributes with a local name of "type" - to find actions XPathExpression expr = xpath.compile("//@*[local-name()='type']"); // get them NodeList nl = (NodeList) expr.evaluate(pageDocument, XPathConstants.NODESET); // get out system actions JSONArray jsonActions = getJsonActions(); // if we found any elements with a type attribute and we have system actions if (nl.getLength() > 0 && jsonActions.length() > 0) { // a list of action types List<String> types = new ArrayList<>(); // loop the json actions for (int i = 0; i < jsonActions.length(); i++) { // get the type String type = jsonActions.getJSONObject(i).optString("type").toLowerCase(); // if don't have it already add it if (!types.contains(type)) types.add(type); } // loop the action attributes we found for (int i = 0; i < nl.getLength(); i++) { // get this attribute Attr a = (Attr) nl.item(i); // get the value of the type String type = a.getTextContent().toLowerCase(); // remove any namespace if (type.contains(":")) type = type.substring(type.indexOf(":") + 1); // get the element the attribute is in Node n = a.getOwnerElement(); // if we don't know about this action type if (!types.contains(type)) { // assume this is the first int unknownCount = 1; // increment the count of unknown controls if (unknownActions.containsKey(type)) unknownCount = unknownActions.get(type) + 1; // store it unknownActions.put(type, unknownCount); } // got type check } // attribute loop } // attribute and system action check // an expression for any controls to get their type expr = xpath.compile("//controls/properties/entry[key='type']/value"); // get them nl = (NodeList) expr.evaluate(pageDocument, XPathConstants.NODESET); // get out system controls JSONArray jsonControls = getJsonControls(); // if we found any elements with a type attribute and we have system actions if (nl.getLength() > 0 && jsonControls.length() > 0) { // a list of action types List<String> types = new ArrayList<>(); // loop the json actions for (int i = 0; i < jsonControls.length(); i++) { // get the type String type = jsonControls.getJSONObject(i).optString("type").toLowerCase(); // if don't have it already add it if (!types.contains(type)) types.add(type); } // loop the control elements we found for (int i = 0; i < nl.getLength(); i++) { // get this element Element e = (Element) nl.item(i); // get the value of the type String type = e.getTextContent().toLowerCase(); // remove any namespace if (type.contains(":")) type = type.substring(type.indexOf(":") + 1); // if we don't know about this action type if (!types.contains(type)) { // assume this is the first int unknownCount = 1; // increment the count of unknown controls if (unknownControls.containsKey(type)) unknownCount = unknownControls.get(type) + 1; // store it unknownControls.put(type, unknownCount); } // got type check } // control loop } // control node loop // use the transformer to write to disk TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(pageDocument); StreamResult result = new StreamResult(pageFile); transformer.transform(source, result); } // page xml file loop } // pages folder check // if any items were removed if (unknownActions.keySet().size() > 0 || unknownControls.keySet().size() > 0) { // delete unzip folder Files.deleteRecurring(unZipFolder); // start error message String error = "Application can't be imported: "; // loop unknown actions for (String key : unknownActions.keySet()) { // get the number int count = unknownActions.get(key); // add message with correct plural error += count + " unrecognised action" + (count == 1 ? "" : "s") + " of type \"" + key + "\", "; } // loop unknown controls for (String key : unknownControls.keySet()) { // get the number int count = unknownControls.get(key); // add message with correct plural error += unknownControls.get(key) + " unrecognised control" + (count == 1 ? "" : "s") + " of type \"" + key + "\", "; } // remove the last comma error = error.substring(0, error.length() - 2); // throw the exception throw new Exception(error); } try { // now initialise with the new id but don't make the resource files (this reloads the pages and sets up the security adapter) appNew.initialise(context, false); } catch (Exception ex) { // log logger.error("Error initialising app on import : " + ex.getMessage(), ex); // usually the security adapter so set back to Rapid appNew.setSecurityAdapterType("rapid"); // try again appNew.initialise(context, false); } // get the security for this application SecurityAdapter security = appNew.getSecurityAdapter(); // if we're keeping settings, and there is an old app, and the security adapter allows users to be added if (keepSettings && appOld != null && SecurityAdapter.hasManageUsers(context, appNew.getSecurityAdapterType())) { // a Rapid request we'll use to delete users from the new app RapidRequest deleteRequest = new RapidRequest(this, request, appNew); // get all current users of the new app Users users = security.getUsers(rapidRequest); // if there are users if (users != null && users.size() > 0) { // remove all current users for (int i = 0; i < users.size(); i++) { // get this user User user = users.get(i); // set their name in the delete Rapid request deleteRequest.setUserName(user.getName()); // delete them security.deleteUser(deleteRequest); // one less to do i--; } } // users check // get the old security adapter SecurityAdapter securityOld = appOld.getSecurityAdapter(); // get any old users users = securityOld.getUsers(rapidRequest); // if there are users if (users != null && users.size() > 0) { // add old users to the new app for (User user : users) { // add the old user to the new app security.addUser(rapidRequest, user); } } else { // if we failed to get users using the specified security make the new "safe" Rapid security adapter for the new app security = new RapidSecurityAdapter(context, appNew); // add it to the new app appNew.setSecurityAdapter(context, "rapid"); } } // new app allows adding users and there is an old app to get them from // make a rapid request in the name of the import application RapidRequest importRapidRequest = new RapidRequest(this, request, appNew); // assume we don't have the user boolean gotUser = false; // allow for the user to be outside the try/catch below User user = null; try { // get the current user's record from the adapter user = security.getUser(importRapidRequest); } catch (SecurityAdapaterException ex) { // log logger.error("Error getting user on app import : " + ex.getMessage(), ex); // set a new Rapid security adapter for the app (it will construct it) appNew.setSecurityAdapter(context, "rapid"); // retrieve the security adapter we just asked to be made security = appNew.getSecurityAdapter(); } // check the current user is present in the app's security adapter if (user != null) { // now check the current user password is correct too if (security.checkUserPassword(importRapidRequest, userName, rapidRequest.getUserPassword())) { // we have the right user with the right password gotUser = true; } else { // remove this user in case there is one with the same name but the password does not match security.deleteUser(importRapidRequest); } } // if we don't have the user if (!gotUser) { // get the current user from the Rapid application User rapidUser = rapidSecurity.getUser(importRapidRequest); // create a new user based on the Rapid user user = new User(rapidUser); // add the new user to this application security.addUser(importRapidRequest, user); } // add Admin roles for the new user if not present if (!security.checkUserRole(importRapidRequest, com.rapid.server.Rapid.ADMIN_ROLE)) security.addUserRole(importRapidRequest, com.rapid.server.Rapid.ADMIN_ROLE); // add Design role for the new user if not present if (!security.checkUserRole(importRapidRequest, com.rapid.server.Rapid.DESIGN_ROLE)) security.addUserRole(importRapidRequest, com.rapid.server.Rapid.DESIGN_ROLE); // reload the pages (actually clears down the pages collection and reloads the headers) appNew.getPages().loadpages(context); // save application (this will also initialise and rebuild the resources) long fileSize = appNew.save(this, rapidRequest, false); monitorEntryDetails = "" + fileSize; // add application to the collection getApplications().put(appNew); // delete unzip folder Files.deleteRecurring(unZipFolder); // send a positive message output = "{\"id\":\"" + appNew.getId() + "\",\"version\":\"" + appNew.getVersion() + "\"}"; } catch (Exception ex) { // delete the appFolder if it exists if (appFolderDest.exists()) Files.deleteRecurring(appFolderDest); // if the parent is empty delete it too if (appFolderDest.getParentFile().list().length <= 1) Files.deleteRecurring(appFolderDest.getParentFile()); // delete the webFolder if it exists if (webFolderDest.exists()) Files.deleteRecurring(webFolderDest); // if the parent is empty delete it too if (webFolderDest.getParentFile().list().length <= 1) Files.deleteRecurring(webFolderDest.getParentFile()); // rethrow exception throw ex; } } else { // delete unzip folder Files.deleteRecurring(unZipFolder); // throw excpetion throw new Exception("Must be a valid Rapid " + Rapid.VERSION + " file"); } } else { // delete unzip folder Files.deleteRecurring(unZipFolder); // throw excpetion throw new Exception("Must be a valid Rapid file"); } } } if (logger.isTraceEnabled()) { logger.trace("Designer POST response : " + output); } else { logger.debug("Designer POST response : " + output.length() + " bytes"); } PrintWriter out = response.getWriter(); out.print(output); out.close(); // record response size responseLength = output.length(); } // got an application } // got rapid design role } // got rapid security } // got rapid application // if monitor is alive then log the event if (_monitor != null && _monitor.isAlive(context) && _monitor.isLoggingAll()) { _monitor.setDetails(monitorEntryDetails); _monitor.commitEntry(rapidRequest, response, responseLength); } } catch (Exception ex) { // if monitor is alive then log the event if (_monitor != null && _monitor.isAlive(context) && _monitor.isLoggingExceptions()) { _monitor.setDetails(monitorEntryDetails); _monitor.commitEntry(rapidRequest, response, responseLength, ex.getMessage()); } getLogger().error("Designer POST error : ",ex); sendException(rapidRequest, response, ex); } } }
App user copy only for Rapid security adapter
src/com/rapid/server/Designer.java
App user copy only for Rapid security adapter
<ide><path>rc/com/rapid/server/Designer.java <ide> <ide> // app details <ide> if ("summary".equals(actionName) || "detail".equals(actionName)) { <del> <add> <ide> int statusId = application.getStatus(); <ide> String status = statusId == 0 ? "In development" : statusId == 1 ? "Live" : statusId == 2 ? "Under maintenance" : null; <ide> if (status != null) out.print("Status:\t" + status + "\r\n"); <ide> if (application.getModifiedDate() != null) out.print("Modified date:\t" + df.format(application.getModifiedDate()) + "\r\n"); <ide> // safe modified by <ide> if (application.getModifiedBy() != null) out.print("Modified by:\t" + application.getModifiedBy() + "\r\n"); <del> <add> <ide> if (application.getStartPageId() != null) out.print("Start page:\t" + application.getStartPageId() + "\r\n"); <del> <add> <ide> // description <ide> if (application.getDescription() != null && application.getDescription().trim().length() > 0) out.print("Description:\t" + application.getDescription() + "\r\n"); <del> <add> <ide> out.print("Form settings:\t" + application.getIsForm() + "\r\n"); <ide> if (application.getIsForm()) { <ide> // form <ide> // theme <ide> out.print("Theme:\t" + application.getThemeType() + "\r\n"); <ide> } <del> <add> <ide> // App parameters <ide> List<Parameter> parameters = application.getParameters(); <ide> out.print("\r\nApplication parameters:\t" + parameters.size() + "\r\n"); <ide> out.print("\tValue:\t" + parameter.getValue() + "\r\n"); <ide> } <ide> out.println(); <del> <add> <ide> // DB connections <ide> List<DatabaseConnection> connections = application.getDatabaseConnections(); <ide> out.print("\r\nDatabase connections:\t" + connections.size() + "\r\n"); <ide> out.print("\tUsername:\t" + connection.getUserName() + "\r\n"); <ide> } <ide> out.println(); <del> <add> <ide> // App settings <ide> String settings = application.getSettingsId(); <ide> if (settings != null && !settings.isEmpty()) out.print("Settings:\t" + settings + "\r\n"); <ide> out.print("\r\n"); <ide> <ide> } // page loop <del> <add> <ide> // App Resources <ide> Resources resources = application.getAppResources(); <ide> out.println("\r\nResources:\t" + resources.size() + "\r\n"); <ide> if (resource.getContent() != null) out.print("Content:\t" + resource.getContent() + "\r\n"); <ide> } <ide> out.println(); <del> <add> <ide> // App CSS <ide> String styles = application.getStyles(); <ide> out.print("Styles:\t\r\n"); <ide> out.print(styles + "\r\n"); <del> <add> <ide> // close the writer <ide> out.close(); <ide> <ide> appNew.setStatus(Application.STATUS_DEVELOPMENT); <ide> <ide> // get the previous version <del> Application appOld = getApplications().get(appOldId); <add> Application appPrev = getApplications().get(appOldId); <ide> <ide> // if we're keeping settings <ide> if (keepSettings) { <ide> <ide> // if we had one <del> if (appOld != null) { <add> if (appPrev != null) { <ide> <ide> // update database connections from old version <del> appNew.setDatabaseConnections(appOld.getDatabaseConnections()); <add> appNew.setDatabaseConnections(appPrev.getDatabaseConnections()); <ide> <ide> // update parameters from old version <del> appNew.setParameters(appOld.getParameters()); <del> <add> appNew.setParameters(appPrev.getParameters()); <add> <ide> // update settings from old version <ide> Application latestVersion = getApplications().get(appId); <ide> Settings oldSettings = Settings.load(context, latestVersion); <ide> <ide> } <ide> <add> /* <add> <add> This was a different attempt tp only remove and add users to the new version from the previous that weren't already there but it doesn't take passwords into account <add> <ide> // get the security for this application <del> SecurityAdapter security = appNew.getSecurityAdapter(); <add> SecurityAdapter securityNew = appNew.getSecurityAdapter(); <ide> <ide> // if we're keeping settings, and there is an old app, and the security adapter allows users to be added <del> if (keepSettings && appOld != null && SecurityAdapter.hasManageUsers(context, appNew.getSecurityAdapterType())) { <add> if (keepSettings && appPrev != null && SecurityAdapter.hasManageUsers(context, appNew.getSecurityAdapterType())) { <ide> <ide> // a Rapid request we'll use to delete users from the new app <ide> RapidRequest deleteRequest = new RapidRequest(this, request, appNew); <ide> <add> // get all users of the new app to remove <add> Users usersNewToRemove = securityNew.getUsers(rapidRequest); <add> // get all users of the new app to not add back as they're already there <add> Users usersNewToNotAdd = securityNew.getUsers(rapidRequest); <add> <add> // get the security adapter from the previous version we want to keep the users from <add> SecurityAdapter securityPrev = appPrev.getSecurityAdapter(); <add> <add> // get any old users (from the previous version) <add> Users usersPrev = securityPrev.getUsers(rapidRequest); <add> <add> // if there are users from the previous version <add> if (usersPrev != null && usersPrev.size() > 0) { <add> <add> // if there are current users <add> if (usersNewToRemove != null && usersNewToRemove.size() > 0) { <add> <add> // remove any old users from the current users list (we don't want to delete them, just to add them back) <add> usersNewToRemove.removeAll(usersPrev); <add> <add> // remove all new users that aren't previous version users <add> for (int i = 0; i < usersNewToRemove.size(); i++) { <add> // get this user <add> User user = usersNewToRemove.get(i); <add> // set their name in the delete Rapid request <add> deleteRequest.setUserName(user.getName()); <add> // delete users currently in the app from the import that we don't want in the new version <add> securityNew.deleteUser(deleteRequest); <add> } <add> <add> // remove new users from previous users so we don't add them back again <add> usersPrev.removeAll(usersNewToNotAdd); <add> <add> } <add> <add> // add previous users to the new app that aren't already there <add> for (User userPrev : usersPrev) { <add> <add> // add the old user to the new app <add> securityNew.addUser(rapidRequest, userPrev); <add> <add> } <add> <add> } else { <add> <add> // if we failed to get users using the specified security make the new "safe" Rapid security adapter for the new app <add> securityNew = new RapidSecurityAdapter(context, appNew); <add> <add> // add it to the new app <add> appNew.setSecurityAdapter(context, "rapid"); <add> <add> } // old users check <add> <add> } // new app allows adding users and there is an old app to get them from <add> <add> */ <add> <add> // get the security for this application <add> SecurityAdapter securityNew = appNew.getSecurityAdapter(); <add> <add> // if we're keeping settings, and there is an old app, and they're both Rapid <add> if (keepSettings && appPrev != null && "rapid".equals(appPrev.getSecurityAdapterType()) && "rapid".equals(appNew.getSecurityAdapterType())) { <add> <add> // a Rapid request we'll use to delete users from the new app <add> RapidRequest deleteRequest = new RapidRequest(this, request, appNew); <add> <ide> // get all current users of the new app <del> Users users = security.getUsers(rapidRequest); <add> Users usersNew = securityNew.getUsers(rapidRequest); <ide> <ide> // if there are users <del> if (users != null && users.size() > 0) { <del> <del> // remove all current users <del> for (int i = 0; i < users.size(); i++) { <add> if (usersNew != null && usersNew.size() > 0) { <add> <add> // remove all current of the new app <add> for (int i = 0; i < usersNew.size(); i++) { <ide> // get this user <del> User user = users.get(i); <add> User user = usersNew.get(i); <ide> // set their name in the delete Rapid request <ide> deleteRequest.setUserName(user.getName()); <ide> // delete them <del> security.deleteUser(deleteRequest); <del> // one less to do <del> i--; <add> securityNew.deleteUser(deleteRequest); <ide> } <ide> <ide> } // users check <ide> <ide> // get the old security adapter <del> SecurityAdapter securityOld = appOld.getSecurityAdapter(); <del> <del> // get any old users <del> users = securityOld.getUsers(rapidRequest); <add> SecurityAdapter securityOld = appPrev.getSecurityAdapter(); <add> <add> // get any old users from the previous version <add> Users usersPrev = securityOld.getUsers(rapidRequest); <ide> <ide> // if there are users <del> if (users != null && users.size() > 0) { <add> if (usersPrev != null && usersPrev.size() > 0) { <ide> <ide> // add old users to the new app <del> for (User user : users) { <add> for (User userOld : usersPrev) { <ide> <ide> // add the old user to the new app <del> security.addUser(rapidRequest, user); <add> securityNew.addUser(rapidRequest, userOld); <ide> <ide> } <ide> <ide> } else { <ide> <ide> // if we failed to get users using the specified security make the new "safe" Rapid security adapter for the new app <del> security = new RapidSecurityAdapter(context, appNew); <add> securityNew = new RapidSecurityAdapter(context, appNew); <ide> <ide> // add it to the new app <ide> appNew.setSecurityAdapter(context, "rapid"); <ide> try { <ide> <ide> // get the current user's record from the adapter <del> user = security.getUser(importRapidRequest); <add> user = securityNew.getUser(importRapidRequest); <ide> <ide> } catch (SecurityAdapaterException ex) { <ide> <ide> // set a new Rapid security adapter for the app (it will construct it) <ide> appNew.setSecurityAdapter(context, "rapid"); <ide> // retrieve the security adapter we just asked to be made <del> security = appNew.getSecurityAdapter(); <add> securityNew = appNew.getSecurityAdapter(); <ide> } <ide> <ide> // check the current user is present in the app's security adapter <ide> if (user != null) { <ide> // now check the current user password is correct too <del> if (security.checkUserPassword(importRapidRequest, userName, rapidRequest.getUserPassword())) { <add> if (securityNew.checkUserPassword(importRapidRequest, userName, rapidRequest.getUserPassword())) { <ide> // we have the right user with the right password <ide> gotUser = true; <ide> } else { <ide> // remove this user in case there is one with the same name but the password does not match <del> security.deleteUser(importRapidRequest); <add> securityNew.deleteUser(importRapidRequest); <ide> } <ide> } <ide> <ide> // create a new user based on the Rapid user <ide> user = new User(rapidUser); <ide> // add the new user to this application <del> security.addUser(importRapidRequest, user); <add> securityNew.addUser(importRapidRequest, user); <ide> } <ide> <ide> // add Admin roles for the new user if not present <del> if (!security.checkUserRole(importRapidRequest, com.rapid.server.Rapid.ADMIN_ROLE)) <del> security.addUserRole(importRapidRequest, com.rapid.server.Rapid.ADMIN_ROLE); <add> if (!securityNew.checkUserRole(importRapidRequest, com.rapid.server.Rapid.ADMIN_ROLE)) <add> securityNew.addUserRole(importRapidRequest, com.rapid.server.Rapid.ADMIN_ROLE); <ide> <ide> // add Design role for the new user if not present <del> if (!security.checkUserRole(importRapidRequest, com.rapid.server.Rapid.DESIGN_ROLE)) <del> security.addUserRole(importRapidRequest, com.rapid.server.Rapid.DESIGN_ROLE); <add> if (!securityNew.checkUserRole(importRapidRequest, com.rapid.server.Rapid.DESIGN_ROLE)) <add> securityNew.addUserRole(importRapidRequest, com.rapid.server.Rapid.DESIGN_ROLE); <ide> <ide> // reload the pages (actually clears down the pages collection and reloads the headers) <ide> appNew.getPages().loadpages(context);
JavaScript
bsd-3-clause
e4e4745ec527808b162fad5a17f529c6be6c3c43
0
beagleterm/beagle-term,beagleterm/beagle-term
// Copyright (c) 2016, Sungguk Lim. Please see the AUTHORS file for details. // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. function DrawUi() {} DrawUi.prototype = { ShowSettingsDialog: function() { $('#settingsModal').modal('show'); }, /** * Called when Hterm terminmal is finished to load. * Every ui configuration(e.g. foo_button.focus() should be in here) */ OnHtermReady: function() { $('.modal-footer button').focus(); this.registerConnectBtnEvent_(); }, /** * @private */ registerConnectBtnEvent_: function() { var connectBtn = document.querySelector('#connectBtn'); connectBtn.addEventListener('click', function(event) { // Get the serial port (i.e. COM1, COM2, COM3, etc.) var portSelect = document.querySelector('#portDropdown'); var port = portSelect.options[portSelect.selectedIndex].value; // Get the baud rate (i.e. 9600, 38400, 57600, 115200, etc. ) var baudSelect = document.querySelector('#bitrateDropdown'); var bitrate = Number(baudSelect.options[baudSelect.selectedIndex].value); // Get the data bit (i.e. "seven" or "eight") var databitSelect = document.querySelector('#databitDropdown'); var databit = databitSelect.options[databitSelect.selectedIndex].value; // Get the parity bit (i.e. "no", "odd", or "even") var paritySelect = document.querySelector('#parityDropdown'); var parity = paritySelect.options[paritySelect.selectedIndex].value; // Get the stop bit (i.e. "one" or "two") var stopbitSelect = document.querySelector('#stopbitDropdown'); var stopbit = stopbitSelect.options[stopbitSelect.selectedIndex].value; // Get the flow control value (i.e. true or false) var fcSelect = document.querySelector('#flowControlDropdown'); var flowControlValue = fcSelect.options[fcSelect.selectedIndex].value; var flowControl = (flowControlValue === 'true'); // Format is ... // settings = Object {bitrate: 14400, dataBits: "eight", parityBit: "odd", // stopBits: "two", ctsFlowControl: true} var settings = { bitrate: bitrate, dataBits: databit, parityBit: parity, stopBits: stopbit, ctsFlowControl: flowControl }; chrome.storage.local.set(settings); chrome.serial.connect(port, { 'bitrate': settings.bitrate, 'dataBits': settings.dataBits, 'parityBit': settings.parityBit, 'stopBits': settings.stopBits, 'ctsFlowControl': settings.ctsFlowControl }, function(openInfo) { if (openInfo === undefined) { inputOutput.println('Unable to connect to device with value' + settings.toString()); // TODO: Open 'connection dialog' again. return; } inputOutput.println('Device found on ' + port + ' via Connection ID ' + openInfo.connectionId); self.connectionId = openInfo.connectionId; AddConnectedSerialId(openInfo.connectionId); chrome.serial.onReceive.addListener(function(info) { if (info && info.data) { inputOutput.print(ab2str(info.data)); } }); }); }); } };
app/js/draw_ui.js
// Copyright (c) 2016, Sungguk Lim. Please see the AUTHORS file for details. // All rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. function DrawUi() {} DrawUi.prototype = { ShowSettingsDialog: function() { $('#settingsModal').modal('show'); }, /** * Called when Hterm terminmal is finished to load. * Every ui configuration(e.g. foo_button.focus() should be in here) */ OnHtermReady: function() { $('.modal-footer button').focus(); this.registerCloseBtnEvent_(); }, /** * @private */ registerCloseBtnEvent_: function() { var connectBtn = document.querySelector('#connectBtn'); connectBtn.addEventListener('click', function(event) { // Get the serial port (i.e. COM1, COM2, COM3, etc.) var portSelect = document.querySelector('#portDropdown'); var port = portSelect.options[portSelect.selectedIndex].value; // Get the baud rate (i.e. 9600, 38400, 57600, 115200, etc. ) var baudSelect = document.querySelector('#bitrateDropdown'); var bitrate = Number(baudSelect.options[baudSelect.selectedIndex].value); // Get the data bit (i.e. "seven" or "eight") var databitSelect = document.querySelector('#databitDropdown'); var databit = databitSelect.options[databitSelect.selectedIndex].value; // Get the parity bit (i.e. "no", "odd", or "even") var paritySelect = document.querySelector('#parityDropdown'); var parity = paritySelect.options[paritySelect.selectedIndex].value; // Get the stop bit (i.e. "one" or "two") var stopbitSelect = document.querySelector('#stopbitDropdown'); var stopbit = stopbitSelect.options[stopbitSelect.selectedIndex].value; // Get the flow control value (i.e. true or false) var fcSelect = document.querySelector('#flowControlDropdown'); var flowControlValue = fcSelect.options[fcSelect.selectedIndex].value; var flowControl = (flowControlValue === 'true'); // Format is ... // settings = Object {bitrate: 14400, dataBits: "eight", parityBit: "odd", // stopBits: "two", ctsFlowControl: true} var settings = { bitrate: bitrate, dataBits: databit, parityBit: parity, stopBits: stopbit, ctsFlowControl: flowControl }; chrome.storage.local.set(settings); chrome.serial.connect(port, { 'bitrate': settings.bitrate, 'dataBits': settings.dataBits, 'parityBit': settings.parityBit, 'stopBits': settings.stopBits, 'ctsFlowControl': settings.ctsFlowControl }, function(openInfo) { if (openInfo === undefined) { inputOutput.println('Unable to connect to device with value' + settings.toString()); // TODO: Open 'connection dialog' again. return; } inputOutput.println('Device found on ' + port + ' via Connection ID ' + openInfo.connectionId); self.connectionId = openInfo.connectionId; AddConnectedSerialId(openInfo.connectionId); chrome.serial.onReceive.addListener(function(info) { if (info && info.data) { inputOutput.print(ab2str(info.data)); } }); }); }); } };
fix wrong function name
app/js/draw_ui.js
fix wrong function name
<ide><path>pp/js/draw_ui.js <ide> */ <ide> OnHtermReady: function() { <ide> $('.modal-footer button').focus(); <del> this.registerCloseBtnEvent_(); <add> this.registerConnectBtnEvent_(); <ide> }, <ide> <ide> /** <ide> * @private <ide> */ <del> registerCloseBtnEvent_: function() { <add> registerConnectBtnEvent_: function() { <ide> var connectBtn = document.querySelector('#connectBtn'); <ide> connectBtn.addEventListener('click', function(event) { <ide> // Get the serial port (i.e. COM1, COM2, COM3, etc.)
JavaScript
mit
7b26add64d9675b8aa5b63dbbde17f54863fec12
0
Bottr-js/Bottr
jest.unmock('../lib/event-emitter') var EventEmitter = require('../lib/event-emitter') test('should register listener', () => { var emitter = new EventEmitter() var handler = jest.fn() emitter.addListener('event', handler) expect(emitter.listeners).toEqual([ { eventName: 'event', handler: handler } ]) }); test('should register listener', () => { var emitter = new EventEmitter() var handler = jest.fn() emitter.addListener('event', handler) expect(emitter.listeners).toEqual([ { eventName: 'event', handler: handler } ]) }); test('should register fallback', () => { var emitter = new EventEmitter() var handler = jest.fn() emitter.fallback('event', handler) expect(emitter.fallbacks['event']).toEqual(handler) }); test('should emit event', () => { var emitter = new EventEmitter() var handler = jest.fn() emitter.addListener('event', handler) var event = emitter.emit('event') expect(event.eventName).toEqual('event') }); test('should emit event with correct handlers', () => { var emitter = new EventEmitter() var handler = jest.fn() var handler2 = jest.fn() emitter.addListener('event', handler) emitter.addListener('event2', handler2) var event = emitter.emit('event') expect(event.remainingListeners).toEqual([handler]) }); test('should emit event with correct arguments', () => { var emitter = new EventEmitter() var handler = jest.fn() emitter.addListener('event', handler) var event = emitter.emit('event', 1) expect(event.args).toEqual([ 1 ]) }); test('should use fallback for event with no handlers', () => { var emitter = new EventEmitter() var handler = jest.fn() emitter.fallback('event', handler) var event = emitter.emit('event') expect(handler).toBeCalled() }); test('should log error for event with no handlers or fallback', () => { jest.mock('console') var emitter = new EventEmitter() var handler = jest.fn() var spy = spyOn(console, 'error') var event = emitter.emit('event') expect(spy).toBeCalled() });
__tests__/event-emitter.js
jest.unmock('../lib/event-emitter') var EventEmitter = require('../lib/event-emitter') test('should register listener', () => { var emitter = new EventEmitter() var handler = jest.fn() emitter.addListener('event', handler) expect(emitter.listeners).toEqual([ { eventName: 'event', handler: handler } ]) }); test('should register listener', () => { var emitter = new EventEmitter() var handler = jest.fn() emitter.addListener('event', handler) expect(emitter.listeners).toEqual([ { eventName: 'event', handler: handler } ]) }); test('should register fallback', () => { var emitter = new EventEmitter() var handler = jest.fn() emitter.fallback('event', handler) expect(emitter.fallbacks['event']).toEqual(handler) }); // EventEmitter.prototype.emit = function(eventName) { // var event = new Event(eventName, eventListeners, args) // event.next(function(eventName) { // // var handler = emitter.unhandledHandlers[eventName] // // if (handler) { // handler.apply(this, args) // } else { // console.error('Unhandled event ' + eventName); // } // }) // } // test('should emit event', () => { var emitter = new EventEmitter() var handler = jest.fn() emitter.addListener('event', handler) var event = emitter.emit('event') expect(event.eventName).toEqual('event') }); test('should emit event with correct handlers', () => { var emitter = new EventEmitter() var handler = jest.fn() var handler2 = jest.fn() emitter.addListener('event', handler) emitter.addListener('event2', handler2) var event = emitter.emit('event') expect(event.remainingListeners).toEqual([handler]) }); test('should emit event with correct arguments', () => { var emitter = new EventEmitter() var handler = jest.fn() emitter.addListener('event', handler) var event = emitter.emit('event', 1) expect(event.args).toEqual([ 1 ]) }); test('should use fallback for event with no handlers', () => { var emitter = new EventEmitter() var handler = jest.fn() emitter.fallback('event', handler) var event = emitter.emit('event') expect(handler).toBeCalled() }); test('should log error for event with no handlers or fallback', () => { jest.mock('console') var emitter = new EventEmitter() var handler = jest.fn() var spy = spyOn(console, 'error') var event = emitter.emit('event') expect(spy).toBeCalled() });
All passes.
__tests__/event-emitter.js
All passes.
<ide><path>_tests__/event-emitter.js <ide> emitter.fallback('event', handler) <ide> expect(emitter.fallbacks['event']).toEqual(handler) <ide> }); <del> <del>// EventEmitter.prototype.emit = function(eventName) { <del>// var event = new Event(eventName, eventListeners, args) <del>// event.next(function(eventName) { <del>// <del>// var handler = emitter.unhandledHandlers[eventName] <del>// <del>// if (handler) { <del>// handler.apply(this, args) <del>// } else { <del>// console.error('Unhandled event ' + eventName); <del>// } <del>// }) <del>// } <del>// <ide> <ide> test('should emit event', () => { <ide> var emitter = new EventEmitter()
Java
apache-2.0
6e6e7dc86b90b02de68f9701372118c96f042e9b
0
dbeaver/dbeaver,dbeaver/dbeaver,dbeaver/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,Sargul/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,Sargul/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,serge-rider/dbeaver
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2020 DBeaver Corp and others * * 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.jkiss.dbeaver.model.data; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.model.*; import org.jkiss.dbeaver.model.exec.DBCAttributeMetaData; import org.jkiss.dbeaver.model.exec.DBCException; import org.jkiss.dbeaver.model.exec.DBCSession; import org.jkiss.dbeaver.model.sql.SQLUtils; import org.jkiss.dbeaver.model.struct.*; import org.jkiss.dbeaver.model.virtual.DBVEntity; import org.jkiss.dbeaver.model.virtual.DBVEntityForeignKey; import org.jkiss.dbeaver.model.virtual.DBVEntityForeignKeyColumn; import org.jkiss.dbeaver.model.virtual.DBVUtils; import org.jkiss.utils.CommonUtils; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Base attribute binding */ public abstract class DBDAttributeBinding implements DBSObject, DBSAttributeBase, DBSTypedObjectEx, DBPQualifiedObject { @NotNull protected DBDValueHandler valueHandler; @Nullable private DBSAttributeBase presentationAttribute; @Nullable private List<DBDAttributeBinding> nestedBindings; private boolean transformed; private boolean disableTransformers; protected DBDAttributeBinding(@NotNull DBDValueHandler valueHandler) { this.valueHandler = valueHandler; } /** * Custom attributes are client-side objects. They also don't have associated meta attributes. */ public boolean isCustom() { return false; } @Nullable @Override public abstract DBDAttributeBinding getParentObject(); /** * Attribute index in result set * @return attribute index (zero based) */ @Override public abstract int getOrdinalPosition(); /** * Attribute label */ @NotNull public abstract String getLabel(); /** * Attribute name */ @NotNull public abstract String getName(); /** * Meta attribute (obtained from result set) */ @Nullable public abstract DBCAttributeMetaData getMetaAttribute(); /** * Entity attribute (may be null). * It is always null if {@link #lateBinding(DBCSession, List)} wasn't called */ @Nullable public abstract DBSEntityAttribute getEntityAttribute(); /** * Most valuable attribute reference. * @return resolved entity attribute or just meta attribute */ @Nullable public DBSAttributeBase getAttribute() { DBSEntityAttribute attr = getEntityAttribute(); return attr == null ? getMetaAttribute() : attr; } /** * Presentation attribute. * Usually the same as {@link #getAttribute()} but may be explicitly set by attribute transformers. */ @Nullable public DBSAttributeBase getPresentationAttribute() { if (presentationAttribute != null) { return presentationAttribute; } return getAttribute(); } public void setPresentationAttribute(@Nullable DBSAttributeBase presentationAttribute) { this.presentationAttribute = presentationAttribute; } public boolean isPseudoAttribute() { return false; } public DBSDataContainer getDataContainer() { DBDAttributeBinding parentObject = getParentObject(); return parentObject == null ? null : parentObject.getDataContainer(); } /** * Row identifier (may be null) */ @Nullable public abstract DBDRowIdentifier getRowIdentifier(); public abstract String getRowIdentifierStatus(); @Nullable public abstract List<DBSEntityReferrer> getReferrers(); @Nullable public abstract Object extractNestedValue(@NotNull Object ownerValue) throws DBCException; /** * Attribute value handler */ @NotNull public DBDValueHandler getValueHandler() { return valueHandler; } public void setTransformHandler(@NotNull DBDValueHandler valueHandler) { this.valueHandler = valueHandler; this.transformed = true; } public boolean isTransformed() { return transformed; } public void disableTransformers(boolean disableTransformers) { this.disableTransformers = disableTransformers; } @NotNull public DBDValueRenderer getValueRenderer() { return valueHandler; } public boolean matches(@Nullable DBSAttributeBase attr, boolean searchByName) { if (attr != null && (this == attr || getMetaAttribute() == attr || getEntityAttribute() == attr)) { return true; } if (searchByName) { if (attr instanceof DBDAttributeBinding) { DBDAttributeBinding cmpAttr = (DBDAttributeBinding) attr; if (getLevel() != cmpAttr.getLevel() || getOrdinalPosition() != cmpAttr.getOrdinalPosition()) { return false; } // Match all hierarchy names for (DBDAttributeBinding a1 = cmpAttr, a2 = this; a1 != null && a2 != null; a1 = a1.getParentObject(), a2 = a2.getParentObject()) { if (!SQLUtils.compareAliases(attr.getName(), this.getName())) { return false; } } return true; } else if (attr != null) { return SQLUtils.compareAliases(attr.getName(), this.getName()); } } return false; } @Nullable public List<DBDAttributeBinding> getNestedBindings() { return nestedBindings; } public boolean hasNestedBindings() { return nestedBindings != null; } public void setNestedBindings(@NotNull List<DBDAttributeBinding> nestedBindings) { this.nestedBindings = nestedBindings; } @Nullable @Override public String getDescription() { DBSEntityAttribute attr = getEntityAttribute(); return attr == null ? null : attr.getDescription(); } @NotNull @Override public String getFullyQualifiedName(DBPEvaluationContext context) { final DBPDataSource dataSource = getDataSource(); if (getParentObject() == null) { return DBUtils.getQuotedIdentifier(dataSource, getName()); } char structSeparator = dataSource.getSQLDialect().getStructSeparator(); StringBuilder query = new StringBuilder(); boolean hasPrevIdentifier = false; for (DBDAttributeBinding attribute = this; attribute != null; attribute = attribute.getParentObject()) { if (attribute.isPseudoAttribute() || (attribute.getParentObject() == null && attribute.getDataKind() == DBPDataKind.DOCUMENT)) { // Skip pseudo attributes and document attributes (e.g. Mongo root document) continue; } if (hasPrevIdentifier) { query.insert(0, structSeparator); } query.insert(0, DBUtils.getQuotedIdentifier(dataSource, attribute.getName())); hasPrevIdentifier = true; } return query.toString(); } @Override public boolean isPersisted() { return false; } /** * Get parent by level. * @param grand 0 - self, 1 - direct parent, 2 - grand parent, etc * @return parent or null */ @Nullable public DBDAttributeBinding getParent(int grand) { if (grand == 0) { return this; } DBDAttributeBinding p = this; for (int i = 0; i < grand; i++) { if (p == null) { throw new IllegalArgumentException("Bad parent depth: " + grand); } p = p.getParentObject(); } return p; } @NotNull public DBDAttributeBinding getTopParent() { for (DBDAttributeBinding binding = this; ; binding = binding.getParentObject()) { if (binding.getParentObject() == null) { return binding; } } } /** * Attribute level. Zero based * @return attribute level (depth) */ public int getLevel() { if (getParentObject() == null) { return 0; } int level = 0; for (DBDAttributeBinding binding = getParentObject(); binding != null; binding = binding.getParentObject()) { level++; } return level; } @Nullable @Override public DBSDataType getDataType() { DBSEntityAttribute attribute = getEntityAttribute(); if (attribute instanceof DBSTypedObjectEx) { return ((DBSTypedObjectEx) attribute).getDataType(); } return null; } public void lateBinding(@NotNull DBCSession session, List<Object[]> rows) throws DBException { if (disableTransformers) { return; } DBSAttributeBase attribute = getAttribute(); final DBDAttributeTransformer[] transformers = DBVUtils.findAttributeTransformers(this, null); if (transformers != null) { session.getProgressMonitor().subTask("Transform attribute '" + attribute.getName() + "'"); final Map<String, Object> transformerOptions = DBVUtils.getAttributeTransformersOptions(this); for (DBDAttributeTransformer transformer : transformers) { transformer.transformAttribute(session, this, rows, transformerOptions); } } } protected List<DBSEntityReferrer> findVirtualReferrers() { DBSDataContainer dataContainer = getDataContainer(); if (dataContainer instanceof DBSEntity) { DBSEntity attrEntity = (DBSEntity) dataContainer; DBVEntity vEntity = DBVUtils.getVirtualEntity(attrEntity, false); if (vEntity != null) { List<DBVEntityForeignKey> foreignKeys = vEntity.getForeignKeys(); if (!CommonUtils.isEmpty(foreignKeys)) { List<DBSEntityReferrer> referrers = null; for (DBVEntityForeignKey vfk : foreignKeys) { for (DBVEntityForeignKeyColumn vfkc : vfk.getAttributes()) { if (CommonUtils.equalObjects(vfkc.getAttributeName(), getFullyQualifiedName(DBPEvaluationContext.DML))) { if (referrers == null) { referrers = new ArrayList<>(); } referrers.add(vfk); } } } return referrers; } } } return null; } @Override public String toString() { DBDAttributeBinding parentAttr = getParentObject(); if (parentAttr == null) { return getName(); } else { return parentAttr.getName() + "." + getName(); } } }
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/data/DBDAttributeBinding.java
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2020 DBeaver Corp and others * * 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.jkiss.dbeaver.model.data; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.model.*; import org.jkiss.dbeaver.model.exec.DBCAttributeMetaData; import org.jkiss.dbeaver.model.exec.DBCException; import org.jkiss.dbeaver.model.exec.DBCSession; import org.jkiss.dbeaver.model.sql.SQLUtils; import org.jkiss.dbeaver.model.struct.*; import org.jkiss.dbeaver.model.virtual.DBVEntity; import org.jkiss.dbeaver.model.virtual.DBVEntityForeignKey; import org.jkiss.dbeaver.model.virtual.DBVEntityForeignKeyColumn; import org.jkiss.dbeaver.model.virtual.DBVUtils; import org.jkiss.utils.CommonUtils; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Base attribute binding */ public abstract class DBDAttributeBinding implements DBSObject, DBSAttributeBase, DBSTypedObjectEx, DBPQualifiedObject { @NotNull protected DBDValueHandler valueHandler; @Nullable private DBSAttributeBase presentationAttribute; @Nullable private List<DBDAttributeBinding> nestedBindings; private boolean transformed; private boolean disableTransformers; protected DBDAttributeBinding(@NotNull DBDValueHandler valueHandler) { this.valueHandler = valueHandler; } /** * Custom attributes are client-side objects. They also don't have associated meta attributes. */ public boolean isCustom() { return false; } @Nullable @Override public abstract DBDAttributeBinding getParentObject(); /** * Attribute index in result set * @return attribute index (zero based) */ @Override public abstract int getOrdinalPosition(); /** * Attribute label */ @NotNull public abstract String getLabel(); /** * Attribute name */ @NotNull public abstract String getName(); /** * Meta attribute (obtained from result set) */ @Nullable public abstract DBCAttributeMetaData getMetaAttribute(); /** * Entity attribute (may be null). * It is always null if {@link #lateBinding(DBCSession, List)} wasn't called */ @Nullable public abstract DBSEntityAttribute getEntityAttribute(); /** * Most valuable attribute reference. * @return resolved entity attribute or just meta attribute */ @Nullable public DBSAttributeBase getAttribute() { DBSEntityAttribute attr = getEntityAttribute(); return attr == null ? getMetaAttribute() : attr; } /** * Presentation attribute. * Usually the same as {@link #getAttribute()} but may be explicitly set by attribute transformers. */ @Nullable public DBSAttributeBase getPresentationAttribute() { if (presentationAttribute != null) { return presentationAttribute; } return getAttribute(); } public void setPresentationAttribute(@Nullable DBSAttributeBase presentationAttribute) { this.presentationAttribute = presentationAttribute; } public boolean isPseudoAttribute() { return false; } public DBSDataContainer getDataContainer() { DBDAttributeBinding parentObject = getParentObject(); return parentObject == null ? null : parentObject.getDataContainer(); } /** * Row identifier (may be null) */ @Nullable public abstract DBDRowIdentifier getRowIdentifier(); public abstract String getRowIdentifierStatus(); @Nullable public abstract List<DBSEntityReferrer> getReferrers(); @Nullable public abstract Object extractNestedValue(@NotNull Object ownerValue) throws DBCException; /** * Attribute value handler */ @NotNull public DBDValueHandler getValueHandler() { return valueHandler; } public void setTransformHandler(@NotNull DBDValueHandler valueHandler) { this.valueHandler = valueHandler; this.transformed = true; } public boolean isTransformed() { return transformed; } public void disableTransformers(boolean disableTransformers) { this.disableTransformers = disableTransformers; } @NotNull public DBDValueRenderer getValueRenderer() { return valueHandler; } public boolean matches(@Nullable DBSAttributeBase attr, boolean searchByName) { if (attr != null && (this == attr || getMetaAttribute() == attr || getEntityAttribute() == attr)) { return true; } if (searchByName) { if (attr instanceof DBDAttributeBinding) { DBDAttributeBinding cmpAttr = (DBDAttributeBinding) attr; if (getLevel() != cmpAttr.getLevel() || getOrdinalPosition() != cmpAttr.getOrdinalPosition()) { return false; } // Match all hierarchy names for (DBDAttributeBinding a1 = cmpAttr, a2 = this; a1 != null && a2 != null; a1 = a1.getParentObject(), a2 = a2.getParentObject()) { if (!SQLUtils.compareAliases(attr.getName(), this.getName())) { return false; } } return true; } else if (attr != null) { return SQLUtils.compareAliases(attr.getName(), this.getName()); } } return false; } @Nullable public List<DBDAttributeBinding> getNestedBindings() { return nestedBindings; } public boolean hasNestedBindings() { return nestedBindings != null; } public void setNestedBindings(@NotNull List<DBDAttributeBinding> nestedBindings) { this.nestedBindings = nestedBindings; } @Nullable @Override public String getDescription() { DBSEntityAttribute attr = getEntityAttribute(); return attr == null ? null : attr.getDescription(); } @NotNull @Override public String getFullyQualifiedName(DBPEvaluationContext context) { final DBPDataSource dataSource = getDataSource(); if (getParentObject() == null) { return DBUtils.getQuotedIdentifier(dataSource, getName()); } char structSeparator = dataSource.getSQLDialect().getStructSeparator(); StringBuilder query = new StringBuilder(); boolean hasPrevIdentifier = false; for (DBDAttributeBinding attribute = this; attribute != null; attribute = attribute.getParentObject()) { if (attribute.isPseudoAttribute() || (attribute.getParentObject() == null && attribute.getDataKind() == DBPDataKind.DOCUMENT)) { // Skip pseudo attributes and document attributes (e.g. Mongo root document) continue; } if (hasPrevIdentifier) { query.insert(0, structSeparator); } query.insert(0, DBUtils.getQuotedIdentifier(dataSource, attribute.getName())); hasPrevIdentifier = true; } return query.toString(); } @Override public boolean isPersisted() { return false; } /** * Get parent by level. * @param grand 0 - self, 1 - direct parent, 2 - grand parent, etc * @return parent or null */ @Nullable public DBDAttributeBinding getParent(int grand) { if (grand == 0) { return this; } DBDAttributeBinding p = this; for (int i = 0; i < grand; i++) { if (p == null) { throw new IllegalArgumentException("Bad parent depth: " + grand); } p = p.getParentObject(); } return p; } @NotNull public DBDAttributeBinding getTopParent() { for (DBDAttributeBinding binding = this; ; binding = binding.getParentObject()) { if (binding.getParentObject() == null) { return binding; } } } /** * Attribute level. Zero based * @return attribute level (depth) */ public int getLevel() { if (getParentObject() == null) { return 0; } int level = 0; for (DBDAttributeBinding binding = getParentObject(); binding != null; binding = binding.getParentObject()) { level++; } return level; } @Nullable @Override public DBSDataType getDataType() { DBSEntityAttribute attribute = getEntityAttribute(); if (attribute instanceof DBSTypedObjectEx) { return ((DBSTypedObjectEx) attribute).getDataType(); } return null; } public void lateBinding(@NotNull DBCSession session, List<Object[]> rows) throws DBException { if (disableTransformers) { return; } DBSAttributeBase attribute = getAttribute(); final DBDAttributeTransformer[] transformers = DBVUtils.findAttributeTransformers(this, null); if (transformers != null) { session.getProgressMonitor().subTask("Transform attribute '" + attribute.getName() + "'"); final Map<String, Object> transformerOptions = DBVUtils.getAttributeTransformersOptions(this); for (DBDAttributeTransformer transformer : transformers) { transformer.transformAttribute(session, this, rows, transformerOptions); } } } protected List<DBSEntityReferrer> findVirtualReferrers() { DBSDataContainer dataContainer = getDataContainer(); if (dataContainer instanceof DBSEntity) { DBSEntity attrEntity = (DBSEntity) dataContainer; DBVEntity vEntity = DBVUtils.getVirtualEntity(attrEntity, false); if (vEntity != null) { List<DBVEntityForeignKey> foreignKeys = vEntity.getForeignKeys(); if (!CommonUtils.isEmpty(foreignKeys)) { List<DBSEntityReferrer> referrers = null; for (DBVEntityForeignKey vfk : foreignKeys) { for (DBVEntityForeignKeyColumn vfkc : vfk.getAttributes()) { if (CommonUtils.equalObjects(vfkc.getAttributeName(), getFullyQualifiedName(DBPEvaluationContext.DML))) { if (referrers == null) { referrers = new ArrayList<>(); } referrers.add(vfk); } } } return referrers; } } } return null; } @Override public String toString() { return getName() + " [" + getOrdinalPosition() + "]"; } }
toString Former-commit-id: 6c4b1dbc198e0b088afb15a544f67b06b91cc366
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/data/DBDAttributeBinding.java
toString
<ide><path>lugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/data/DBDAttributeBinding.java <ide> <ide> @Override <ide> public String toString() { <del> return getName() + " [" + getOrdinalPosition() + "]"; <add> DBDAttributeBinding parentAttr = getParentObject(); <add> if (parentAttr == null) { <add> return getName(); <add> } else { <add> return parentAttr.getName() + "." + getName(); <add> } <ide> } <ide> <ide> }
JavaScript
mit
ccddc082d51d05b85d8d5fe8f562ec99def3f9cc
0
tantalor/graphjs
if (typeof(require) !== 'undefined') { // commonjs var assert = require("assert"); try { var narwhal = require('narwhal'); } catch (e) {} if (narwhal) { var tests = {}; exports.test = function (name, fn) { tests['test '+name] = fn; }; exports.ok = function (value, name) { assert.ok(value, name); }; exports.export_tests = function (local_exports) { for (var test in tests) { local_exports[test] = tests[test] } tests = {}; }; } else { // node, ringo var tests = {}; if (typeof(print) === 'undefined') { // node var sys = require('sys'); var print = function (s) { sys.print(s+"\n"); } } exports.test = function (name, fn) { tests['test '+name] = fn; }; exports.ok = function (value, name) { try { assert.ok(value, name); } catch (e) { if (e.name === "AssertionError") { print(" FAIL: "+name); } throw e; } }; exports.export_tests = function (local_exports) { print("+ Running"); var passes = 0, fails = 0, errors = 0; for (var test in tests) { print(" + Running test "+test); try { tests[test](); passes++; } catch (e) { if (e.name === "AssertionError") { fails++; } else { errors++; } } } print("Passes: "+passes+", Fails: "+fails+", Errors: "+errors); tests = {}; }; } } else if (typeof(load) !== 'undefined') { // jsc var AssertionError = {}; var tests = {}; var exports = { test: function (name, fn) { tests['test '+name] = fn; }, ok: function (value, name) { if (!value) { print(" FAIL: "+name); throw AssertionError; } }, export_tests: function () { print("+ Running"); var passes = 0, fails = 0, errors = 0; for (var test in tests) { print(" + Running test "+test); try { tests[test](); passes++; } catch (e) { if (e === AssertionError) { fails++; } else { errors++; } } } print("Passes: "+passes+", Fails: "+fails+", Errors: "+errors); tests = {}; } }; exports; }
test-qunit.js
if (typeof(require) !== 'undefined') { // commonjs var assert = require("assert"); try { var narwhal = require('narwhal'); } catch (e) {} if (narwhal) { var tests = {}; exports.test = function (name, fn) { tests['test '+name] = fn; }; exports.ok = function (value, name) { assert.ok(value, name); }; exports.export_tests = function (local_exports) { for (var test in tests) { local_exports[test] = tests[test] } }; } else { // node, ringo var tests = {}; if (typeof(print) === 'undefined') { // node var sys = require('sys'); var print = function (s) { sys.print(s+"\n"); } } exports.test = function (name, fn) { tests['test '+name] = fn; }; exports.ok = function (value, name) { try { assert.ok(value, name); } catch (e) { if (e.name === "AssertionError") { print(" FAIL: "+name); } throw e; } }; exports.export_tests = function (local_exports) { print("+ Running"); var passes = 0, fails = 0, errors = 0; for (var test in tests) { print(" + Running test "+test); try { tests[test](); passes++; } catch (e) { if (e.name === "AssertionError") { fails++; } else { errors++; } } } print("Passes: "+passes+", Fails: "+fails+", Errors: "+errors); tests = {}; }; } } else if (typeof(load) !== 'undefined') { // jsc var AssertionError = {}; var tests = {}; var exports = { test: function (name, fn) { tests['test '+name] = fn; }, ok: function (value, name) { if (!value) { print(" FAIL: "+name); throw AssertionError; } }, export_tests: function () { print("+ Running"); var passes = 0, fails = 0, errors = 0; for (var test in tests) { print(" + Running test "+test); try { tests[test](); passes++; } catch (e) { if (e === AssertionError) { fails++; } else { errors++; } } } print("Passes: "+passes+", Fails: "+fails+", Errors: "+errors); tests = {}; } }; exports; }
clear tests for narwhal
test-qunit.js
clear tests for narwhal
<ide><path>est-qunit.js <ide> for (var test in tests) { <ide> local_exports[test] = tests[test] <ide> } <add> tests = {}; <ide> }; <ide> } else { <ide> // node, ringo
JavaScript
mit
43ef7fc814fef32676addac94d08fa09ff6fd13f
0
tsherif/scenejs,tsherif/scenejs
/** * @class Display compiled from a {@link SceneJS.Scene}, providing methods to render and pick. * @private * * <p>A Display is a container of {@link SceneJS_Object}s which are created (or updated) by a depth-first * <b>compilation traversal</b> of a {@link SceneJS.Scene}.</b> * * <h2>Rendering Pipeline</h2> * * <p>Conceptually, a Display implements a pipeline with the following stages:</p> * * <ol> * <li>Create or update {@link SceneJS_Object}s during scene compilation</li> * <li>Organise the {@link SceneJS_Object} into an <b>object list</b></li> * <li>Determine the GL state sort order for the object list</li> * <li>State sort the object list</li> * <li>Create a <b>draw list</b> containing {@link SceneJS_Chunk}s belonging to the {@link SceneJS_Object}s in the object list</li> * <li>Render the draw list to draw the image</li> * </ol> * * <p>An update to the scene causes the pipeline to be re-executed from one of these stages, and SceneJS is designed * so that the pipeline is always re-executed from the latest stage possible to avoid redoing work.</p> * * <p>For example:</p> * * <ul> * <li>when an object is created or updated, we need to (re)do stages 2, 3, 4, 5 and 6</li> * <li>when an object is made invisible, we need to redo stages 5 and 6</li> * <li>when an object is assigned to a different scene render layer (works like a render bin), we need to redo * stages 3, 4, 5, and 6</li> *<li>when the colour of an object changes, or maybe when the viewpoint changes, we simplt redo stage 6</li> * </ul> * * <h2>Object Creation</h2> * <p>The object soup (stage 1) is constructed by a depth-first traversal of the scene graph, which we think of as * "compiling" the scene graph into the Display. As traversal visits each scene node, the node's state core is * set on the Display (such as {@link #flags}, {@link #layer}, {@link #renderer} etc), which we think of as the * cores that are active at that instant during compilation. Each of the scene's leaf nodes is always * a {@link SceneJS.Geometry}, and when traversal visits one of those it calls {@link #buildObject} to create an * object in the soup. For each of the currently active cores, the object is given a {@link SceneJS_Chunk} * containing the WebGL calls for rendering it.</p> * * <p>The object also gets a shader (implemented by {@link SceneJS_Program}), taylored to render those state cores.</p> * * <p>Limited re-compilation may also be done on portions of a scene that have been added or sufficiently modified. When * traversal visits a {@link SceneJS.Geometry} for which an object already exists in the display, {@link #buildObject} * may update the {@link SceneJS_Chunk}s on the object as required for any changes in the core soup since the * last time the object was built. If differences among the cores require it, then {@link #buildObject} may also replace * the object's {@link SceneJS_Program} in order to render the new core soup configuration.</p> * * <p>So in summary, to each {@link SceneJS_Object} it builds, {@link #buildObject} creates a list of * {@link SceneJS_Chunk}s to render the set of node state cores that are currently set on the {@link SceneJS_Display}. * When {@link #buildObject} is re-building an existing object, it may replace one or more {@link SceneJS_Chunk}s * for state cores that have changed from the last time the object was built or re-built.</p> * <h2>Object Destruction</h2> * <p>Destruction of a scene graph branch simply involves a call to {@link #removeObject} for each {@link SceneJS.Geometry} * in the branch.</p> * * <h2>Draw List</h2> * <p>The draw list is actually comprised of two lists of state chunks: a "pick" list to render a pick buffer * for colour-indexed GPU picking, along with a "draw" list for normal image rendering. The chunks in these lists * are held in the state-sorted order of their objects in #_objectList, with runs of duplicate states removed.</p> * * <p>After a scene update, we set a flag on the display to indicate the stage we will need to redo from. The pipeline is * then lazy-redone on the next call to #render or #pick.</p> */ var SceneJS_Display = function (cfg) { // Display is bound to the lifetime of an HTML5 canvas this._canvas = cfg.canvas; // Factory which creates and recycles {@link SceneJS_Program} instances this._programFactory = new SceneJS_ProgramFactory({ canvas: cfg.canvas }); // Factory which creates and recycles {@link SceneJS.Chunk} instances this._chunkFactory = new SceneJS_ChunkFactory(); /** * True when the background is to be transparent * @type {boolean} */ this.transparent = cfg.transparent === true; /** * Node state core for the last {@link SceneJS.Enable} visited during scene graph compilation traversal * @type Object */ this.enable = null; /** * Node state core for the last {@link SceneJS.Flags} visited during scene graph compilation traversal * @type Object */ this.flags = null; /** * Node state core for the last {@link SceneJS.Layer} visited during scene graph compilation traversal * @type Object */ this.layer = null; /** * Node state core for the last {@link SceneJS.Stage} visited during scene graph compilation traversal * @type Object */ this.stage = null; /** * Node state core for the last {@link SceneJS.Renderer} visited during scene graph compilation traversal * @type Object */ this.renderer = null; /** * Node state core for the last {@link SceneJS.DepthBuf} visited during scene graph compilation traversal * @type Object */ this.depthBuffer = null; /** * Node state core for the last {@link SceneJS.ColorBuf} visited during scene graph compilation traversal * @type Object */ this.colorBuffer = null; /** * Node state core for the last {@link SceneJS.View} visited during scene graph compilation traversal * @type Object */ this.view = null; /** * Node state core for the last {@link SceneJS.Lights} visited during scene graph compilation traversal * @type Object */ this.lights = null; /** * Node state core for the last {@link SceneJS.Material} visited during scene graph compilation traversal * @type Object */ this.material = null; /** * Node state core for the last {@link SceneJS.Texture} visited during scene graph compilation traversal * @type Object */ this.texture = null; /** * Node state core for the last {@link SceneJS.Fresnel} visited during scene graph compilation traversal * @type Object */ this.fresnel = null; /** * Node state core for the last {@link SceneJS.Reflect} visited during scene graph compilation traversal * @type Object */ this.cubemap = null; /** * Node state core for the last {@link SceneJS.XForm} visited during scene graph compilation traversal * @type Object */ this.modelTransform = null; /** * Node state core for the last {@link SceneJS.LookAt} visited during scene graph compilation traversal * @type Object */ this.viewTransform = null; /** * Node state core for the last {@link SceneJS.Camera} visited during scene graph compilation traversal * @type Object */ this.projTransform = null; /** * Node state core for the last {@link SceneJS.RegionMap} visited during scene graph compilation traversal * @type Object */ this.regionMap = null; /** * Node state core for the last {@link SceneJS.ColorTarget} visited during scene graph compilation traversal * @type Object */ this.renderTarget = null; /** * Node state core for the last {@link SceneJS.Clips} visited during scene graph compilation traversal * @type Object */ this.clips = null; /** * Node state core for the last {@link SceneJS.MorphGeometry} visited during scene graph compilation traversal * @type Object */ this.morphGeometry = null; /** * Node state core for the last {@link SceneJS.Name} visited during scene graph compilation traversal * @type Object */ this.name = null; /** * Node state core for the last {@link SceneJS.Tag} visited during scene graph compilation traversal * @type Object */ this.tag = null; /** * Node state core for the last render {@link SceneJS.Node} listener encountered during scene graph compilation traversal * @type Object */ this.renderListeners = null; /** * Node state core for the last {@link SceneJS.Shader} visited during scene graph compilation traversal * @type Object */ this.shader = null; /** * Node state core for the last {@link SceneJS.ShaderParams} visited during scene graph compilation traversal * @type Object */ this.shaderParams = null; /** * Node state core for the last {@link SceneJS.Style} visited during scene graph compilation traversal * @type Object */ this.style = null; /** * Node state core for the last {@link SceneJS.Geometry} visited during scene graph compilation traversal * @type Object */ this.geometry = null; /* Factory which creates and recycles {@link SceneJS_Object} instances */ this._objectFactory = new SceneJS_ObjectFactory(); /** * The objects in the display */ this._objects = {}; /** * Ambient color, which must be given to gl.clearColor before draw list iteration */ this._ambientColor = [0, 0, 0, 1.0]; /** * The object list, containing all elements of #_objects, kept in GL state-sorted order */ this._objectList = []; this._objectListLen = 0; /* The "draw list", comprised collectively of three lists of state chunks belong to visible objects * within #_objectList: a "pick" list to render a pick buffer for colour-indexed GPU picking, along with an * "draw" list for normal image rendering. The chunks in these lists are held in the state-sorted order of * their objects in #_objectList, with runs of duplicate states removed. */ this._drawList = []; // State chunk list to render all objects this._drawListLen = 0; this._pickDrawList = []; // State chunk list to render scene to pick buffer this._pickDrawListLen = 0; this._targetList = []; this._targetListLen = 0; // Tracks the index of the first chunk in the transparency pass. The first run of chunks // in the list are for opaque objects, while the remainder are for transparent objects. // This supports a mode in which we only render the opaque chunks. this._drawListTransparentIndex = -1; /* The frame context holds state shared across a single render of the draw list, along with any results of * the render, such as pick hits */ this._frameCtx = { pickNames: [], // Pick names of objects hit during pick render, regionData: [], canvas: this._canvas, // The canvas VAO: null // Vertex array object extension }; /* The frame context has this facade which is given to scene node "rendered" listeners * to allow application code to access things like transform matrices from within those listeners. */ this._frameCtx.renderListenerCtx = new SceneJS.RenderContext(this._frameCtx); /*------------------------------------------------------------------------------------- * Flags which schedule what the display is to do when #render is next called. *------------------------------------------------------------------------------------*/ /** * Flags the object list as needing to be rebuilt from existing objects on the next call to {@link #render} or {@link #pick}. * Setting this will cause the rendering pipeline to be executed from stage #2 (see class comment), * causing object list rebuild, state order determination, state sort, draw list construction and image render. * @type Boolean */ this.objectListDirty = true; /** * Flags the object list as needing state orders to be computed on the next call to {@link #render} or {@link #pick}. * Setting this will cause the rendering pipeline to be executed from stage #3 (see class comment), * causing state order determination, state sort, draw list construction and image render. * @type Boolean */ this.stateOrderDirty = true; /** * Flags the object list as needing to be state sorted on the next call to {@link #render} or {@link #pick}. * Setting this will cause the rendering pipeline to be executed from stage #4 (see class comment), * causing state sort, draw list construction and image render. * @type Boolean */ this.stateSortDirty = true; /** * Flags the draw list as needing to be rebuilt from the object list on the next call to {@link #render} or {@link #pick}. * Setting this will cause the rendering pipeline to be executed from stage #5 (see class comment), * causing draw list construction and image render. * @type Boolean */ this.drawListDirty = true; /** * Flags the image as needing to be redrawn from the draw list on the next call to {@link #render} or {@link #pick}. * Setting this will cause the rendering pipeline to be executed from stage #6 (see class comment), * causing the image render. * @type Boolean */ this.imageDirty = true; /** * Flags the neccessity for the image buffer to be re-rendered from the draw list. * @type Boolean */ this.pickBufDirty = true; // Redraw pick buffer this.rayPickBufDirty = true; // Redraw raypick buffer }; /** * Reallocates WebGL resources for objects within this display */ SceneJS_Display.prototype.webglRestored = function () { this._programFactory.webglRestored();// Reallocate programs this._chunkFactory.webglRestored(); // Recache shader var locations var gl = this._canvas.gl; if (this.pickBuf) { this.pickBuf.webglRestored(gl); // Rebuild pick buffers } if (this.rayPickBuf) { this.rayPickBuf.webglRestored(gl); } this.imageDirty = true; // Need redraw }; /** * Internally creates (or updates) a {@link SceneJS_Object} of the given ID from whatever node state cores are currently set * on this {@link SceneJS_Display}. The object is created if it does not already exist in the display, otherwise it is * updated with the current state cores, possibly replacing cores already referenced by the object. * * @param {String} objectId ID of object to create or update */ SceneJS_Display.prototype.buildObject = function (objectId) { var object = this._objects[objectId]; if (!object) { // Create object object = this._objects[objectId] = this._objectFactory.getObject(objectId); this.objectListDirty = true; } object.stage = this.stage; object.layer = this.layer; object.renderTarget = this.renderTarget; object.texture = this.texture; object.cubemap = this.cubemap; object.geometry = this.geometry; object.enable = this.enable; object.flags = this.flags; object.tag = this.tag; //if (!object.hash) { var hash = ([ // Build current state hash this.geometry.hash, this.shader.hash, this.clips.hash, this.morphGeometry.hash, this.texture.hash, this.fresnel.hash, this.cubemap.hash, this.lights.hash, this.flags.hash, this.regionMap.hash ]).join(";"); if (!object.program || hash != object.hash) { // Get new program for object if no program or hash mismatch if (object.program) { this._programFactory.putProgram(object.program); } object.program = this._programFactory.getProgram(hash, this); object.hash = hash; } //} // Build draw chunks for object this._setChunk(object, 0, "program"); // Must be first this._setChunk(object, 1, "xform", this.modelTransform); this._setChunk(object, 2, "lookAt", this.viewTransform); this._setChunk(object, 3, "camera", this.projTransform); this._setChunk(object, 4, "flags", this.flags); this._setChunk(object, 5, "shader", this.shader); this._setChunk(object, 6, "shaderParams", this.shaderParams); this._setChunk(object, 7, "style", this.style); this._setChunk(object, 8, "depthBuffer", this.depthBuffer); this._setChunk(object, 9, "colorBuffer", this.colorBuffer); this._setChunk(object, 10, "view", this.view); this._setChunk(object, 11, "name", this.name); this._setChunk(object, 12, "lights", this.lights); this._setChunk(object, 13, "material", this.material); this._setChunk(object, 14, "texture", this.texture); this._setChunk(object, 15, "regionMap", this.regionMap); this._setChunk(object, 16, "fresnel", this.fresnel); this._setChunk(object, 17, "cubemap", this.cubemap); this._setChunk(object, 18, "clips", this.clips); this._setChunk(object, 19, "renderer", this.renderer); this._setChunk(object, 20, "geometry", this.morphGeometry, this.geometry); this._setChunk(object, 21, "listeners", this.renderListeners); // Must be after the above chunks this._setChunk(object, 22, "draw", this.geometry); // Must be last // At the very least, the object sort order // will need be recomputed this.stateOrderDirty = true; }; SceneJS_Display.prototype._setChunk = function (object, order, chunkType, core, core2) { var chunkId; var chunkClass = this._chunkFactory.chunkTypes[chunkType]; if (core) { // Core supplied if (core.empty) { // Only set default cores for state types that have them var oldChunk = object.chunks[order]; if (oldChunk) { this._chunkFactory.putChunk(oldChunk); // Release previous chunk to pool } object.chunks[order] = null; return; } // Note that core.stateId can be either a number or a string, that's why we make // chunkId a string here. // TODO: Would it be better if all were numbers? chunkId = chunkClass.prototype.programGlobal ? '_' + core.stateId : 'p' + object.program.id + '_' + core.stateId; if (core2) { chunkId += '__' + core2.stateId; } } else { // No core supplied, probably a program. // Only one chunk of this type per program. chunkId = 'p' + object.program.id; } // This is needed so that chunkFactory can distinguish between draw and geometry // chunks with the same core. chunkId = order + '__' + chunkId; var oldChunk = object.chunks[order]; if (oldChunk) { if (oldChunk.id == chunkId) { // Avoid needless chunk reattachment return; } this._chunkFactory.putChunk(oldChunk); // Release previous chunk to pool } object.chunks[order] = this._chunkFactory.getChunk(chunkId, chunkType, object.program, core, core2); // Attach new chunk // Ambient light is global across everything in display, and // can never be disabled, so grab it now because we want to // feed it to gl.clearColor before each display list render if (chunkType == "lights") { this._setAmbient(core); } }; SceneJS_Display.prototype._setAmbient = function (core) { var lights = core.lights; var light; for (var i = 0, len = lights.length; i < len; i++) { light = lights[i]; if (light.mode == "ambient") { this._ambientColor[0] = light.color[0]; this._ambientColor[1] = light.color[1]; this._ambientColor[2] = light.color[2]; } } }; /** * Removes an object from this display * * @param {String} objectId ID of object to remove */ SceneJS_Display.prototype.removeObject = function (objectId) { var object = this._objects[objectId]; if (!object) { return; } this._programFactory.putProgram(object.program); object.program = null; object.hash = null; this._objectFactory.putObject(object); delete this._objects[objectId]; this.objectListDirty = true; }; /** * Set a tag selector to selectively activate objects that have matching SceneJS.Tag nodes */ SceneJS_Display.prototype.selectTags = function (tagSelector) { this._tagSelector = tagSelector; this.drawListDirty = true; }; /** * Render this display. What actually happens in the method depends on what flags are set. * */ SceneJS_Display.prototype.render = function (params) { params = params || {}; if (this.objectListDirty) { this._buildObjectList(); // Build object render bin this.objectListDirty = false; this.stateOrderDirty = true; // Now needs state ordering } if (this.stateOrderDirty) { this._makeStateSortKeys(); // Compute state sort order this.stateOrderDirty = false; this.stateSortDirty = true; // Now needs state sorting } if (this.stateSortDirty) { this._stateSort(); // State sort the object render bin this.stateSortDirty = false; this.drawListDirty = true; // Now needs new visible object bin //this._logObjectList(); } if (this.drawListDirty) { // Render visible list while building transparent list this._buildDrawList(); this.imageDirty = true; //this._logDrawList(); //this._logPickList(); } if (this.imageDirty || params.force) { this._doDrawList({ // Render, no pick clear: (params.clear !== false), // Clear buffers by default opaqueOnly: params.opaqueOnly }); this.imageDirty = false; this.pickBufDirty = true; // Pick buff will now need rendering on next pick } }; SceneJS_Display.prototype._buildObjectList = function () { this._objectListLen = 0; for (var objectId in this._objects) { if (this._objects.hasOwnProperty(objectId)) { this._objectList[this._objectListLen++] = this._objects[objectId]; } } }; SceneJS_Display.prototype._makeStateSortKeys = function () { // console.log("--------------------------------------------------------------------------------------------------"); // console.log("SceneJS_Display_makeSortKeys"); var object; for (var i = 0, len = this._objectListLen; i < len; i++) { object = this._objectList[i]; if (!object.program) { // Non-visual object (eg. sound) object.sortKey = -1; } else { object.sortKey = ((object.stage.priority + 1) * 1000000000000) + ((object.flags.transparent ? 2 : 1) * 1000000000) + ((object.layer.priority + 1) * 1000000) + ((object.program.id + 1) * 1000) + object.texture.stateId; } } // console.log("--------------------------------------------------------------------------------------------------"); }; SceneJS_Display.prototype._stateSort = function () { this._objectList.length = this._objectListLen; this._objectList.sort(this._stateSortObjects); }; SceneJS_Display.prototype._stateSortObjects = function (a, b) { return a.sortKey - b.sortKey; }; SceneJS_Display.prototype._logObjectList = function () { console.log("--------------------------------------------------------------------------------------------------"); console.log(this._objectListLen + " objects"); for (var i = 0, len = this._objectListLen; i < len; i++) { var object = this._objectList[i]; console.log("SceneJS_Display : object[" + i + "] sortKey = " + object.sortKey); } console.log("--------------------------------------------------------------------------------------------------"); }; SceneJS_Display.prototype._buildDrawList = function () { this._lastStateId = this._lastStateId || []; this._lastPickStateId = this._lastPickStateId || []; for (var i = 0; i < 25; i++) { this._lastStateId[i] = null; this._lastPickStateId[i] = null; } this._drawListLen = 0; this._pickDrawListLen = 0; this._drawListTransparentIndex = -1; // For each render target, a list of objects to render to that target var targetObjectLists = {}; // A list of all the render target object lists var targetListList = []; // List of all targets var targetList = []; var object; var tagMask; var tagRegex; var tagCore; var flags; if (this._tagSelector) { tagMask = this._tagSelector.mask; tagRegex = this._tagSelector.regex; } this._objectDrawList = this._objectDrawList || []; this._objectDrawListLen = 0; for (var i = 0, len = this._objectListLen; i < len; i++) { object = this._objectList[i]; // Cull invisible objects if (object.enable.enabled === false) { continue; } flags = object.flags; // Cull invisible objects if (flags.enabled === false) { continue; } // Cull objects in disabled layers if (!object.layer.enabled) { continue; } // Cull objects with unmatched tags if (tagMask) { tagCore = object.tag; if (tagCore.tag) { if (tagCore.mask != tagMask) { // Scene tag mask was updated since last render tagCore.mask = tagMask; tagCore.matches = tagRegex.test(tagCore.tag); } if (!tagCore.matches) { continue; } } } // Put objects with render targets into a bin for each target if (object.renderTarget.targets) { var targets = object.renderTarget.targets; var target; var coreId; var list; for (var j = 0, lenj = targets.length; j < lenj; j++) { target = targets[j]; coreId = target.coreId; list = targetObjectLists[coreId]; if (!list) { list = []; targetObjectLists[coreId] = list; targetListList.push(list); targetList.push(this._chunkFactory.getChunk(target.stateId, "renderTarget", object.program, target)); } list.push(object); } } else { // this._objectDrawList[this._objectDrawListLen++] = object; } } // Append chunks for objects within render targets first var list; var target; var object; var pickable; for (var i = 0, len = targetListList.length; i < len; i++) { list = targetListList[i]; target = targetList[i]; this._appendRenderTargetChunk(target); for (var j = 0, lenj = list.length; j < lenj; j++) { object = list[j]; pickable = object.stage && object.stage.pickable; // We'll only pick objects in pickable stages this._appendObjectToDrawLists(object, pickable); } } if (object) { // Unbinds any render target bound previously this._appendRenderTargetChunk(this._chunkFactory.getChunk(-1, "renderTarget", object.program, {})); } // Append chunks for objects not in render targets for (var i = 0, len = this._objectDrawListLen; i < len; i++) { object = this._objectDrawList[i]; pickable = !object.stage || (object.stage && object.stage.pickable); // We'll only pick objects in pickable stages this._appendObjectToDrawLists(object, pickable); } this.drawListDirty = false; }; SceneJS_Display.prototype._appendRenderTargetChunk = function (chunk) { this._drawList[this._drawListLen++] = chunk; }; /** * Appends an object to the draw and pick lists. * @param object * @param pickable * @private */ SceneJS_Display.prototype._appendObjectToDrawLists = function (object, pickable) { var chunks = object.chunks; var picking = object.flags.picking; var chunk; for (var i = 0, len = chunks.length; i < len; i++) { chunk = chunks[i]; if (chunk) { // As we apply the state chunk lists we track the ID of most types of chunk in order // to cull redundant re-applications of runs of the same chunk - except for those chunks with a // 'unique' flag, because we don't want to cull runs of draw chunks because they contain the GL // drawElements calls which render the objects. if (chunk.draw) { if (chunk.unique || this._lastStateId[i] != chunk.id) { // Don't reapply repeated states this._drawList[this._drawListLen] = chunk; this._lastStateId[i] = chunk.id; // Get index of first chunk in transparency pass if (chunk.core && chunk.core && chunk.core.transparent) { if (this._drawListTransparentIndex < 0) { this._drawListTransparentIndex = this._drawListLen; } } this._drawListLen++; } } if (chunk.pick) { if (pickable !== false) { // Don't pick objects in unpickable stages if (picking) { // Don't pick unpickable objects if (chunk.unique || this._lastPickStateId[i] != chunk.id) { // Don't reapply repeated states this._pickDrawList[this._pickDrawListLen++] = chunk; this._lastPickStateId[i] = chunk.id; } } } } } } }; /** * Logs the contents of the draw list to the console. * @private */ SceneJS_Display.prototype._logDrawList = function () { console.log("--------------------------------------------------------------------------------------------------"); console.log(this._drawListLen + " draw list chunks"); for (var i = 0, len = this._drawListLen; i < len; i++) { var chunk = this._drawList[i]; console.log("[chunk " + i + "] type = " + chunk.type); switch (chunk.type) { case "draw": console.log("\n"); break; case "renderTarget": console.log(" bufType = " + chunk.core.bufType); break; } } console.log("--------------------------------------------------------------------------------------------------"); }; /** * Logs the contents of the pick list to the console. * @private */ SceneJS_Display.prototype._logPickList = function () { console.log("--------------------------------------------------------------------------------------------------"); console.log(this._pickDrawListLen + " pick list chunks"); for (var i = 0, len = this._pickDrawListLen; i < len; i++) { var chunk = this._pickDrawList[i]; console.log("[chunk " + i + "] type = " + chunk.type); switch (chunk.type) { case "draw": console.log("\n"); break; case "renderTarget": console.log(" bufType = " + chunk.core.bufType); break; } } console.log("--------------------------------------------------------------------------------------------------"); }; /** * Performs a pick on the display graph and returns info on the result. * @param {*} params * @returns {*} */ SceneJS_Display.prototype.pick = function (params) { var canvas = this._canvas.canvas; var resolutionScaling = this._canvas.resolutionScaling; var hit = null; var canvasX = params.canvasX * resolutionScaling; var canvasY = params.canvasY * resolutionScaling; var pickBuf = this.pickBuf; // Lazy-create pick buffer if (!pickBuf) { pickBuf = this.pickBuf = new SceneJS._webgl.RenderBuffer({canvas: this._canvas}); this.pickBufDirty = true; } this.render(); // Do any pending visible render // Colour-index pick to find the picked object pickBuf.bind(); // Re-render the pick buffer if the display has updated if (this.pickBufDirty) { pickBuf.clear(); this._doDrawList({ pick: true, regionPick: params.regionPick, clear: true }); this._canvas.gl.finish(); this.pickBufDirty = false; // Pick buffer up to date this.rayPickBufDirty = true; // Ray pick buffer now dirty } // Read pixel color in pick buffer at given coordinates, // convert to an index into the pick name list var pix = pickBuf.read(canvasX, canvasY); // Read pick buffer pickBuf.unbind(); // Unbind pick buffer if (params.regionPick) { // Region picking if (pix[0] === 0 && pix[1] === 0 && pix[2] === 0 && pix[3] === 0) { return null; } var regionColor = {r: pix[0] / 255, g: pix[1] / 255, b: pix[2] / 255, a: pix[3] / 255}; var regionData = this._frameCtx.regionData; var tolerance = 0.01; var data = {}; var color, delta; for (var i = 0, len = regionData.length; i < len; i++) { color = regionData[i].color; if (regionColor && regionData[i].data) { delta = Math.max( Math.abs(regionColor.r - color.r), Math.abs(regionColor.g - color.g), Math.abs(regionColor.b - color.b), Math.abs(regionColor.a - (color.a === undefined ? regionColor.a : color.a)) ); if (delta < tolerance) { data = regionData[i].data; break; } } } return { color: regionColor, regionData: data, canvasPos: [canvasX, canvasY] }; } // Ray-picking var pickedObjectIndex = pix[0] + pix[1] * 256 + pix[2] * 65536; var pickIndex = (pickedObjectIndex >= 1) ? pickedObjectIndex - 1 : -1; // Look up pick name from index var pickName = this._frameCtx.pickNames[pickIndex]; // Map pixel to name if (pickName) { hit = { name: pickName.name, path: pickName.path, nodeId: pickName.nodeId, canvasPos: [canvasX, canvasY] }; // Now do a ray-pick if requested if (params.rayPick) { // Lazy-create ray pick depth buffer var rayPickBuf = this.rayPickBuf; if (!rayPickBuf) { rayPickBuf = this.rayPickBuf = new SceneJS._webgl.RenderBuffer({canvas: this._canvas}); this.rayPickBufDirty = true; } // Render depth values to ray-pick depth buffer rayPickBuf.bind(); if (this.rayPickBufDirty) { rayPickBuf.clear(); this._doDrawList({ pick: true, rayPick: true, clear: true }); this.rayPickBufDirty = false; } // Read pixel from depth buffer, convert to normalised device Z coordinate, // which will be in range of [0..1] with z=0 at front pix = rayPickBuf.read(canvasX, canvasY); rayPickBuf.unbind(); var screenZ = this._unpackDepth(pix); var w = canvas.width; var h = canvas.height; // Calculate clip space coordinates, which will be in range // of x=[-1..1] and y=[-1..1], with y=(+1) at top var x = (canvasX - w / 2) / (w / 2); // Calculate clip space coordinates var y = -(canvasY - h / 2) / (h / 2); var projMat = this._frameCtx.cameraMat; var viewMat = this._frameCtx.viewMat; var pvMat = SceneJS_math_mulMat4(projMat, viewMat, []); var pvMatInverse = SceneJS_math_inverseMat4(pvMat, []); var world1 = SceneJS_math_transformVector4(pvMatInverse, [x, y, -1, 1]); world1 = SceneJS_math_mulVec4Scalar(world1, 1 / world1[3]); var world2 = SceneJS_math_transformVector4(pvMatInverse, [x, y, 1, 1]); world2 = SceneJS_math_mulVec4Scalar(world2, 1 / world2[3]); var dir = SceneJS_math_subVec3(world2, world1, []); var vWorld = SceneJS_math_addVec3(world1, SceneJS_math_mulVec4Scalar(dir, screenZ, []), []); // Got World-space intersect with surface of picked geometry hit.worldPos = vWorld; } } return hit; }; SceneJS_Display.prototype.readPixels = function (entries, size, opaqueOnly) { if (!this._readPixelBuf) { this._readPixelBuf = new SceneJS._webgl.RenderBuffer({canvas: this._canvas}); } this._readPixelBuf.bind(); this._readPixelBuf.clear(); this.render({ force: true, opaqueOnly: opaqueOnly }); var entry; var color; for (var i = 0; i < size; i++) { entry = entries[i] || (entries[i] = {}); color = this._readPixelBuf.read(entry.x, entry.y); entry.r = color[0]; entry.g = color[1]; entry.b = color[2]; entry.a = color[3]; } this._readPixelBuf.unbind(); }; /** * Unpacks a color-encoded depth * @param {Array(Number)} depthZ Depth encoded as an RGBA color value * @returns {Number} * @private */ SceneJS_Display.prototype._unpackDepth = function (depthZ) { var vec = [depthZ[0] / 256.0, depthZ[1] / 256.0, depthZ[2] / 256.0, depthZ[3] / 256.0]; var bitShift = [1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0]; return SceneJS_math_dotVector4(vec, bitShift); }; /** Renders either the draw or pick list. * * @param {*} params * @param {Boolean} params.clear Set true to clear the color, depth and stencil buffers first * @param {Boolean} params.pick Set true to render for picking * @param {Boolean} params.rayPick Set true to render for ray-picking * @param {Boolean} params.regionPick Set true to render for region-picking * @param {Boolean} params.transparent Set false to only render opaque objects * @private */ SceneJS_Display.prototype._doDrawList = function (params) { var gl = this._canvas.gl; // Reset frame context var frameCtx = this._frameCtx; frameCtx.renderTarget = null; frameCtx.targetIndex = 0; frameCtx.renderBuf = null; frameCtx.viewMat = null; frameCtx.modelMat = null; frameCtx.cameraMat = null; frameCtx.renderer = null; frameCtx.depthbufEnabled = null; frameCtx.clearDepth = null; frameCtx.depthFunc = gl.LESS; frameCtx.scissorTestEnabled = false; frameCtx.blendEnabled = false; frameCtx.backfaces = true; frameCtx.frontface = "ccw"; frameCtx.pick = !!params.pick; frameCtx.rayPick = !!params.rayPick; frameCtx.regionPick = !!params.regionPick; frameCtx.pickIndex = 0; frameCtx.textureUnit = 0; frameCtx.lineWidth = 1; frameCtx.transparent = false; frameCtx.ambientColor = this._ambientColor; frameCtx.aspect = this._canvas.canvas.width / this._canvas.canvas.height; // The extensions needs to be re-queried in case the context was lost and has been recreated. if (this._canvas.UINT_INDEX_ENABLED) { gl.getExtension("OES_element_index_uint"); } var VAO = gl.getExtension("OES_vertex_array_object"); frameCtx.VAO = (VAO) ? VAO : null; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); if (this.transparent || params.pick) { gl.clearColor(0, 0, 0, 0); } else { gl.clearColor(this._ambientColor[0], this._ambientColor[1], this._ambientColor[2], 1.0); } if (params.clear) { gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); } gl.frontFace(gl.CCW); gl.disable(gl.CULL_FACE); gl.disable(gl.BLEND); if (params.pick) { // Render for pick for (var i = 0, len = this._pickDrawListLen; i < len; i++) { this._pickDrawList[i].pick(frameCtx); } } else { // Option to only render opaque objects var len = (params.opaqueOnly && this._drawListTransparentIndex >= 0 ? this._drawListTransparentIndex : this._drawListLen); // Render for draw for (var i = 0; i < len; i++) { // Push opaque rendering chunks this._drawList[i].draw(frameCtx); } } gl.flush(); if (frameCtx.renderBuf) { frameCtx.renderBuf.unbind(); } if (frameCtx.VAO) { frameCtx.VAO.bindVertexArrayOES(null); for (var i = 0; i < 10; i++) { gl.disableVertexAttribArray(i); } } // // var numTextureUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); // for (var ii = 0; ii < numTextureUnits; ++ii) { // gl.activeTexture(gl.TEXTURE0 + ii); // gl.bindTexture(gl.TEXTURE_CUBE_MAP, null); // gl.bindTexture(gl.TEXTURE_2D, null); // } }; SceneJS_Display.prototype.destroy = function () { this._programFactory.destroy(); };
src/core/display/display.js
/** * @class Display compiled from a {@link SceneJS.Scene}, providing methods to render and pick. * @private * * <p>A Display is a container of {@link SceneJS_Object}s which are created (or updated) by a depth-first * <b>compilation traversal</b> of a {@link SceneJS.Scene}.</b> * * <h2>Rendering Pipeline</h2> * * <p>Conceptually, a Display implements a pipeline with the following stages:</p> * * <ol> * <li>Create or update {@link SceneJS_Object}s during scene compilation</li> * <li>Organise the {@link SceneJS_Object} into an <b>object list</b></li> * <li>Determine the GL state sort order for the object list</li> * <li>State sort the object list</li> * <li>Create a <b>draw list</b> containing {@link SceneJS_Chunk}s belonging to the {@link SceneJS_Object}s in the object list</li> * <li>Render the draw list to draw the image</li> * </ol> * * <p>An update to the scene causes the pipeline to be re-executed from one of these stages, and SceneJS is designed * so that the pipeline is always re-executed from the latest stage possible to avoid redoing work.</p> * * <p>For example:</p> * * <ul> * <li>when an object is created or updated, we need to (re)do stages 2, 3, 4, 5 and 6</li> * <li>when an object is made invisible, we need to redo stages 5 and 6</li> * <li>when an object is assigned to a different scene render layer (works like a render bin), we need to redo * stages 3, 4, 5, and 6</li> *<li>when the colour of an object changes, or maybe when the viewpoint changes, we simplt redo stage 6</li> * </ul> * * <h2>Object Creation</h2> * <p>The object soup (stage 1) is constructed by a depth-first traversal of the scene graph, which we think of as * "compiling" the scene graph into the Display. As traversal visits each scene node, the node's state core is * set on the Display (such as {@link #flags}, {@link #layer}, {@link #renderer} etc), which we think of as the * cores that are active at that instant during compilation. Each of the scene's leaf nodes is always * a {@link SceneJS.Geometry}, and when traversal visits one of those it calls {@link #buildObject} to create an * object in the soup. For each of the currently active cores, the object is given a {@link SceneJS_Chunk} * containing the WebGL calls for rendering it.</p> * * <p>The object also gets a shader (implemented by {@link SceneJS_Program}), taylored to render those state cores.</p> * * <p>Limited re-compilation may also be done on portions of a scene that have been added or sufficiently modified. When * traversal visits a {@link SceneJS.Geometry} for which an object already exists in the display, {@link #buildObject} * may update the {@link SceneJS_Chunk}s on the object as required for any changes in the core soup since the * last time the object was built. If differences among the cores require it, then {@link #buildObject} may also replace * the object's {@link SceneJS_Program} in order to render the new core soup configuration.</p> * * <p>So in summary, to each {@link SceneJS_Object} it builds, {@link #buildObject} creates a list of * {@link SceneJS_Chunk}s to render the set of node state cores that are currently set on the {@link SceneJS_Display}. * When {@link #buildObject} is re-building an existing object, it may replace one or more {@link SceneJS_Chunk}s * for state cores that have changed from the last time the object was built or re-built.</p> * <h2>Object Destruction</h2> * <p>Destruction of a scene graph branch simply involves a call to {@link #removeObject} for each {@link SceneJS.Geometry} * in the branch.</p> * * <h2>Draw List</h2> * <p>The draw list is actually comprised of two lists of state chunks: a "pick" list to render a pick buffer * for colour-indexed GPU picking, along with a "draw" list for normal image rendering. The chunks in these lists * are held in the state-sorted order of their objects in #_objectList, with runs of duplicate states removed.</p> * * <p>After a scene update, we set a flag on the display to indicate the stage we will need to redo from. The pipeline is * then lazy-redone on the next call to #render or #pick.</p> */ var SceneJS_Display = function (cfg) { // Display is bound to the lifetime of an HTML5 canvas this._canvas = cfg.canvas; // Factory which creates and recycles {@link SceneJS_Program} instances this._programFactory = new SceneJS_ProgramFactory({ canvas: cfg.canvas }); // Factory which creates and recycles {@link SceneJS.Chunk} instances this._chunkFactory = new SceneJS_ChunkFactory(); /** * True when the background is to be transparent * @type {boolean} */ this.transparent = cfg.transparent === true; /** * Node state core for the last {@link SceneJS.Enable} visited during scene graph compilation traversal * @type Object */ this.enable = null; /** * Node state core for the last {@link SceneJS.Flags} visited during scene graph compilation traversal * @type Object */ this.flags = null; /** * Node state core for the last {@link SceneJS.Layer} visited during scene graph compilation traversal * @type Object */ this.layer = null; /** * Node state core for the last {@link SceneJS.Stage} visited during scene graph compilation traversal * @type Object */ this.stage = null; /** * Node state core for the last {@link SceneJS.Renderer} visited during scene graph compilation traversal * @type Object */ this.renderer = null; /** * Node state core for the last {@link SceneJS.DepthBuf} visited during scene graph compilation traversal * @type Object */ this.depthBuffer = null; /** * Node state core for the last {@link SceneJS.ColorBuf} visited during scene graph compilation traversal * @type Object */ this.colorBuffer = null; /** * Node state core for the last {@link SceneJS.View} visited during scene graph compilation traversal * @type Object */ this.view = null; /** * Node state core for the last {@link SceneJS.Lights} visited during scene graph compilation traversal * @type Object */ this.lights = null; /** * Node state core for the last {@link SceneJS.Material} visited during scene graph compilation traversal * @type Object */ this.material = null; /** * Node state core for the last {@link SceneJS.Texture} visited during scene graph compilation traversal * @type Object */ this.texture = null; /** * Node state core for the last {@link SceneJS.Fresnel} visited during scene graph compilation traversal * @type Object */ this.fresnel = null; /** * Node state core for the last {@link SceneJS.Reflect} visited during scene graph compilation traversal * @type Object */ this.cubemap = null; /** * Node state core for the last {@link SceneJS.XForm} visited during scene graph compilation traversal * @type Object */ this.modelTransform = null; /** * Node state core for the last {@link SceneJS.LookAt} visited during scene graph compilation traversal * @type Object */ this.viewTransform = null; /** * Node state core for the last {@link SceneJS.Camera} visited during scene graph compilation traversal * @type Object */ this.projTransform = null; /** * Node state core for the last {@link SceneJS.RegionMap} visited during scene graph compilation traversal * @type Object */ this.regionMap = null; /** * Node state core for the last {@link SceneJS.ColorTarget} visited during scene graph compilation traversal * @type Object */ this.renderTarget = null; /** * Node state core for the last {@link SceneJS.Clips} visited during scene graph compilation traversal * @type Object */ this.clips = null; /** * Node state core for the last {@link SceneJS.MorphGeometry} visited during scene graph compilation traversal * @type Object */ this.morphGeometry = null; /** * Node state core for the last {@link SceneJS.Name} visited during scene graph compilation traversal * @type Object */ this.name = null; /** * Node state core for the last {@link SceneJS.Tag} visited during scene graph compilation traversal * @type Object */ this.tag = null; /** * Node state core for the last render {@link SceneJS.Node} listener encountered during scene graph compilation traversal * @type Object */ this.renderListeners = null; /** * Node state core for the last {@link SceneJS.Shader} visited during scene graph compilation traversal * @type Object */ this.shader = null; /** * Node state core for the last {@link SceneJS.ShaderParams} visited during scene graph compilation traversal * @type Object */ this.shaderParams = null; /** * Node state core for the last {@link SceneJS.Style} visited during scene graph compilation traversal * @type Object */ this.style = null; /** * Node state core for the last {@link SceneJS.Geometry} visited during scene graph compilation traversal * @type Object */ this.geometry = null; /* Factory which creates and recycles {@link SceneJS_Object} instances */ this._objectFactory = new SceneJS_ObjectFactory(); /** * The objects in the display */ this._objects = {}; /** * Ambient color, which must be given to gl.clearColor before draw list iteration */ this._ambientColor = [0, 0, 0, 1.0]; /** * The object list, containing all elements of #_objects, kept in GL state-sorted order */ this._objectList = []; this._objectListLen = 0; /* The "draw list", comprised collectively of three lists of state chunks belong to visible objects * within #_objectList: a "pick" list to render a pick buffer for colour-indexed GPU picking, along with an * "draw" list for normal image rendering. The chunks in these lists are held in the state-sorted order of * their objects in #_objectList, with runs of duplicate states removed. */ this._drawList = []; // State chunk list to render all objects this._drawListLen = 0; this._pickDrawList = []; // State chunk list to render scene to pick buffer this._pickDrawListLen = 0; this._targetList = []; this._targetListLen = 0; // Tracks the index of the first chunk in the transparency pass. The first run of chunks // in the list are for opaque objects, while the remainder are for transparent objects. // This supports a mode in which we only render the opaque chunks. this._drawListTransparentIndex = -1; /* The frame context holds state shared across a single render of the draw list, along with any results of * the render, such as pick hits */ this._frameCtx = { pickNames: [], // Pick names of objects hit during pick render, regionData: [], canvas: this._canvas, // The canvas VAO: null // Vertex array object extension }; /* The frame context has this facade which is given to scene node "rendered" listeners * to allow application code to access things like transform matrices from within those listeners. */ this._frameCtx.renderListenerCtx = new SceneJS.RenderContext(this._frameCtx); /*------------------------------------------------------------------------------------- * Flags which schedule what the display is to do when #render is next called. *------------------------------------------------------------------------------------*/ /** * Flags the object list as needing to be rebuilt from existing objects on the next call to {@link #render} or {@link #pick}. * Setting this will cause the rendering pipeline to be executed from stage #2 (see class comment), * causing object list rebuild, state order determination, state sort, draw list construction and image render. * @type Boolean */ this.objectListDirty = true; /** * Flags the object list as needing state orders to be computed on the next call to {@link #render} or {@link #pick}. * Setting this will cause the rendering pipeline to be executed from stage #3 (see class comment), * causing state order determination, state sort, draw list construction and image render. * @type Boolean */ this.stateOrderDirty = true; /** * Flags the object list as needing to be state sorted on the next call to {@link #render} or {@link #pick}. * Setting this will cause the rendering pipeline to be executed from stage #4 (see class comment), * causing state sort, draw list construction and image render. * @type Boolean */ this.stateSortDirty = true; /** * Flags the draw list as needing to be rebuilt from the object list on the next call to {@link #render} or {@link #pick}. * Setting this will cause the rendering pipeline to be executed from stage #5 (see class comment), * causing draw list construction and image render. * @type Boolean */ this.drawListDirty = true; /** * Flags the image as needing to be redrawn from the draw list on the next call to {@link #render} or {@link #pick}. * Setting this will cause the rendering pipeline to be executed from stage #6 (see class comment), * causing the image render. * @type Boolean */ this.imageDirty = true; /** * Flags the neccessity for the image buffer to be re-rendered from the draw list. * @type Boolean */ this.pickBufDirty = true; // Redraw pick buffer this.rayPickBufDirty = true; // Redraw raypick buffer }; /** * Reallocates WebGL resources for objects within this display */ SceneJS_Display.prototype.webglRestored = function () { this._programFactory.webglRestored();// Reallocate programs this._chunkFactory.webglRestored(); // Recache shader var locations var gl = this._canvas.gl; if (this.pickBuf) { this.pickBuf.webglRestored(gl); // Rebuild pick buffers } if (this.rayPickBuf) { this.rayPickBuf.webglRestored(gl); } this.imageDirty = true; // Need redraw }; /** * Internally creates (or updates) a {@link SceneJS_Object} of the given ID from whatever node state cores are currently set * on this {@link SceneJS_Display}. The object is created if it does not already exist in the display, otherwise it is * updated with the current state cores, possibly replacing cores already referenced by the object. * * @param {String} objectId ID of object to create or update */ SceneJS_Display.prototype.buildObject = function (objectId) { var object = this._objects[objectId]; if (!object) { // Create object object = this._objects[objectId] = this._objectFactory.getObject(objectId); this.objectListDirty = true; } object.stage = this.stage; object.layer = this.layer; object.renderTarget = this.renderTarget; object.texture = this.texture; object.cubemap = this.cubemap; object.geometry = this.geometry; object.enable = this.enable; object.flags = this.flags; object.tag = this.tag; //if (!object.hash) { var hash = ([ // Build current state hash this.geometry.hash, this.shader.hash, this.clips.hash, this.morphGeometry.hash, this.texture.hash, this.fresnel.hash, this.cubemap.hash, this.lights.hash, this.flags.hash, this.regionMap.hash ]).join(";"); if (!object.program || hash != object.hash) { // Get new program for object if no program or hash mismatch if (object.program) { this._programFactory.putProgram(object.program); } object.program = this._programFactory.getProgram(hash, this); object.hash = hash; } //} // Build draw chunks for object this._setChunk(object, 0, "program"); // Must be first this._setChunk(object, 1, "xform", this.modelTransform); this._setChunk(object, 2, "lookAt", this.viewTransform); this._setChunk(object, 3, "camera", this.projTransform); this._setChunk(object, 4, "flags", this.flags); this._setChunk(object, 5, "shader", this.shader); this._setChunk(object, 6, "shaderParams", this.shaderParams); this._setChunk(object, 7, "style", this.style); this._setChunk(object, 8, "depthBuffer", this.depthBuffer); this._setChunk(object, 9, "colorBuffer", this.colorBuffer); this._setChunk(object, 10, "view", this.view); this._setChunk(object, 11, "name", this.name); this._setChunk(object, 12, "lights", this.lights); this._setChunk(object, 13, "material", this.material); this._setChunk(object, 14, "texture", this.texture); this._setChunk(object, 15, "regionMap", this.regionMap); this._setChunk(object, 16, "fresnel", this.fresnel); this._setChunk(object, 17, "cubemap", this.cubemap); this._setChunk(object, 18, "clips", this.clips); this._setChunk(object, 19, "renderer", this.renderer); this._setChunk(object, 20, "geometry", this.morphGeometry, this.geometry); this._setChunk(object, 21, "listeners", this.renderListeners); // Must be after the above chunks this._setChunk(object, 22, "draw", this.geometry); // Must be last // At the very least, the object sort order // will need be recomputed this.stateOrderDirty = true; }; SceneJS_Display.prototype._setChunk = function (object, order, chunkType, core, core2) { var chunkId; var chunkClass = this._chunkFactory.chunkTypes[chunkType]; if (core) { // Core supplied if (core.empty) { // Only set default cores for state types that have them var oldChunk = object.chunks[order]; if (oldChunk) { this._chunkFactory.putChunk(oldChunk); // Release previous chunk to pool } object.chunks[order] = null; return; } // Note that core.stateId can be either a number or a string, that's why we make // chunkId a string here. // TODO: Would it be better if all were numbers? chunkId = chunkClass.prototype.programGlobal ? '_' + core.stateId : 'p' + object.program.id + '_' + core.stateId; if (core2) { chunkId += '__' + core2.stateId; } } else { // No core supplied, probably a program. // Only one chunk of this type per program. chunkId = 'p' + object.program.id; } // This is needed so that chunkFactory can distinguish between draw and geometry // chunks with the same core. chunkId = order + '__' + chunkId; var oldChunk = object.chunks[order]; if (oldChunk) { if (oldChunk.id == chunkId) { // Avoid needless chunk reattachment return; } this._chunkFactory.putChunk(oldChunk); // Release previous chunk to pool } object.chunks[order] = this._chunkFactory.getChunk(chunkId, chunkType, object.program, core, core2); // Attach new chunk // Ambient light is global across everything in display, and // can never be disabled, so grab it now because we want to // feed it to gl.clearColor before each display list render if (chunkType == "lights") { this._setAmbient(core); } }; SceneJS_Display.prototype._setAmbient = function (core) { var lights = core.lights; var light; for (var i = 0, len = lights.length; i < len; i++) { light = lights[i]; if (light.mode == "ambient") { this._ambientColor[0] = light.color[0]; this._ambientColor[1] = light.color[1]; this._ambientColor[2] = light.color[2]; } } }; /** * Removes an object from this display * * @param {String} objectId ID of object to remove */ SceneJS_Display.prototype.removeObject = function (objectId) { var object = this._objects[objectId]; if (!object) { return; } this._programFactory.putProgram(object.program); object.program = null; object.hash = null; this._objectFactory.putObject(object); delete this._objects[objectId]; this.objectListDirty = true; }; /** * Set a tag selector to selectively activate objects that have matching SceneJS.Tag nodes */ SceneJS_Display.prototype.selectTags = function (tagSelector) { this._tagSelector = tagSelector; this.drawListDirty = true; }; /** * Render this display. What actually happens in the method depends on what flags are set. * */ SceneJS_Display.prototype.render = function (params) { params = params || {}; if (this.objectListDirty) { this._buildObjectList(); // Build object render bin this.objectListDirty = false; this.stateOrderDirty = true; // Now needs state ordering } if (this.stateOrderDirty) { this._makeStateSortKeys(); // Compute state sort order this.stateOrderDirty = false; this.stateSortDirty = true; // Now needs state sorting } if (this.stateSortDirty) { this._stateSort(); // State sort the object render bin this.stateSortDirty = false; this.drawListDirty = true; // Now needs new visible object bin //this._logObjectList(); } if (this.drawListDirty) { // Render visible list while building transparent list this._buildDrawList(); this.imageDirty = true; //this._logDrawList(); //this._logPickList(); } if (this.imageDirty || params.force) { this._doDrawList({ // Render, no pick clear: (params.clear !== false), // Clear buffers by default opaqueOnly: params.opaqueOnly }); this.imageDirty = false; this.pickBufDirty = true; // Pick buff will now need rendering on next pick } }; SceneJS_Display.prototype._buildObjectList = function () { this._objectListLen = 0; for (var objectId in this._objects) { if (this._objects.hasOwnProperty(objectId)) { this._objectList[this._objectListLen++] = this._objects[objectId]; } } }; SceneJS_Display.prototype._makeStateSortKeys = function () { // console.log("--------------------------------------------------------------------------------------------------"); // console.log("SceneJS_Display_makeSortKeys"); var object; for (var i = 0, len = this._objectListLen; i < len; i++) { object = this._objectList[i]; if (!object.program) { // Non-visual object (eg. sound) object.sortKey = -1; } else { object.sortKey = ((object.stage.priority + 1) * 1000000000000) + ((object.flags.transparent ? 2 : 1) * 1000000000) + ((object.layer.priority + 1) * 1000000) + ((object.program.id + 1) * 1000) + object.texture.stateId; } } // console.log("--------------------------------------------------------------------------------------------------"); }; SceneJS_Display.prototype._stateSort = function () { this._objectList.length = this._objectListLen; this._objectList.sort(this._stateSortObjects); }; SceneJS_Display.prototype._stateSortObjects = function (a, b) { return a.sortKey - b.sortKey; }; SceneJS_Display.prototype._logObjectList = function () { console.log("--------------------------------------------------------------------------------------------------"); console.log(this._objectListLen + " objects"); for (var i = 0, len = this._objectListLen; i < len; i++) { var object = this._objectList[i]; console.log("SceneJS_Display : object[" + i + "] sortKey = " + object.sortKey); } console.log("--------------------------------------------------------------------------------------------------"); }; SceneJS_Display.prototype._buildDrawList = function () { this._lastStateId = this._lastStateId || []; this._lastPickStateId = this._lastPickStateId || []; for (var i = 0; i < 25; i++) { this._lastStateId[i] = null; this._lastPickStateId[i] = null; } this._drawListLen = 0; this._pickDrawListLen = 0; this._drawListTransparentIndex = -1; // For each render target, a list of objects to render to that target var targetObjectLists = {}; // A list of all the render target object lists var targetListList = []; // List of all targets var targetList = []; var object; var tagMask; var tagRegex; var tagCore; var flags; if (this._tagSelector) { tagMask = this._tagSelector.mask; tagRegex = this._tagSelector.regex; } this._objectDrawList = this._objectDrawList || []; this._objectDrawListLen = 0; for (var i = 0, len = this._objectListLen; i < len; i++) { object = this._objectList[i]; // Cull invisible objects if (object.enable.enabled === false) { continue; } flags = object.flags; // Cull invisible objects if (flags.enabled === false) { continue; } // Cull objects in disabled layers if (!object.layer.enabled) { continue; } // Cull objects with unmatched tags if (tagMask) { tagCore = object.tag; if (tagCore.tag) { if (tagCore.mask != tagMask) { // Scene tag mask was updated since last render tagCore.mask = tagMask; tagCore.matches = tagRegex.test(tagCore.tag); } if (!tagCore.matches) { continue; } } } // Put objects with render targets into a bin for each target if (object.renderTarget.targets) { var targets = object.renderTarget.targets; var target; var coreId; var list; for (var j = 0, lenj = targets.length; j < lenj; j++) { target = targets[j]; coreId = target.coreId; list = targetObjectLists[coreId]; if (!list) { list = []; targetObjectLists[coreId] = list; targetListList.push(list); targetList.push(this._chunkFactory.getChunk(target.stateId, "renderTarget", object.program, target)); } list.push(object); } } else { // this._objectDrawList[this._objectDrawListLen++] = object; } } // Append chunks for objects within render targets first var list; var target; var object; var pickable; for (var i = 0, len = targetListList.length; i < len; i++) { list = targetListList[i]; target = targetList[i]; this._appendRenderTargetChunk(target); for (var j = 0, lenj = list.length; j < lenj; j++) { object = list[j]; pickable = object.stage && object.stage.pickable; // We'll only pick objects in pickable stages this._appendObjectToDrawLists(object, pickable); } } if (object) { // Unbinds any render target bound previously this._appendRenderTargetChunk(this._chunkFactory.getChunk(-1, "renderTarget", object.program, {})); } // Append chunks for objects not in render targets for (var i = 0, len = this._objectDrawListLen; i < len; i++) { object = this._objectDrawList[i]; pickable = !object.stage || (object.stage && object.stage.pickable); // We'll only pick objects in pickable stages this._appendObjectToDrawLists(object, pickable); } this.drawListDirty = false; }; SceneJS_Display.prototype._appendRenderTargetChunk = function (chunk) { this._drawList[this._drawListLen++] = chunk; }; /** * Appends an object to the draw and pick lists. * @param object * @param pickable * @private */ SceneJS_Display.prototype._appendObjectToDrawLists = function (object, pickable) { var chunks = object.chunks; var picking = object.flags.picking; var chunk; for (var i = 0, len = chunks.length; i < len; i++) { chunk = chunks[i]; if (chunk) { // As we apply the state chunk lists we track the ID of most types of chunk in order // to cull redundant re-applications of runs of the same chunk - except for those chunks with a // 'unique' flag, because we don't want to cull runs of draw chunks because they contain the GL // drawElements calls which render the objects. if (chunk.draw) { if (chunk.unique || this._lastStateId[i] != chunk.id) { // Don't reapply repeated states this._drawList[this._drawListLen] = chunk; this._lastStateId[i] = chunk.id; // Get index of first chunk in transparency pass if (chunk.core && chunk.core && chunk.core.transparent) { if (this._drawListTransparentIndex < 0) { this._drawListTransparentIndex = this._drawListLen; } } this._drawListLen++; } } if (chunk.pick) { if (pickable !== false) { // Don't pick objects in unpickable stages if (picking) { // Don't pick unpickable objects if (chunk.unique || this._lastPickStateId[i] != chunk.id) { // Don't reapply repeated states this._pickDrawList[this._pickDrawListLen++] = chunk; this._lastPickStateId[i] = chunk.id; } } } } } } }; /** * Logs the contents of the draw list to the console. * @private */ SceneJS_Display.prototype._logDrawList = function () { console.log("--------------------------------------------------------------------------------------------------"); console.log(this._drawListLen + " draw list chunks"); for (var i = 0, len = this._drawListLen; i < len; i++) { var chunk = this._drawList[i]; console.log("[chunk " + i + "] type = " + chunk.type); switch (chunk.type) { case "draw": console.log("\n"); break; case "renderTarget": console.log(" bufType = " + chunk.core.bufType); break; } } console.log("--------------------------------------------------------------------------------------------------"); }; /** * Logs the contents of the pick list to the console. * @private */ SceneJS_Display.prototype._logPickList = function () { console.log("--------------------------------------------------------------------------------------------------"); console.log(this._pickDrawListLen + " pick list chunks"); for (var i = 0, len = this._pickDrawListLen; i < len; i++) { var chunk = this._pickDrawList[i]; console.log("[chunk " + i + "] type = " + chunk.type); switch (chunk.type) { case "draw": console.log("\n"); break; case "renderTarget": console.log(" bufType = " + chunk.core.bufType); break; } } console.log("--------------------------------------------------------------------------------------------------"); }; /** * Performs a pick on the display graph and returns info on the result. * @param {*} params * @returns {*} */ SceneJS_Display.prototype.pick = function (params) { var canvas = this._canvas.canvas; var resolutionScaling = this._canvas.resolutionScaling; var hit = null; var canvasX = params.canvasX * resolutionScaling; var canvasY = params.canvasY * resolutionScaling; var pickBuf = this.pickBuf; // Lazy-create pick buffer if (!pickBuf) { pickBuf = this.pickBuf = new SceneJS._webgl.RenderBuffer({canvas: this._canvas}); this.pickBufDirty = true; } this.render(); // Do any pending visible render // Colour-index pick to find the picked object pickBuf.bind(); // Re-render the pick buffer if the display has updated if (this.pickBufDirty) { pickBuf.clear(); this._doDrawList({ pick: true, regionPick: params.regionPick, clear: true }); this._canvas.gl.finish(); this.pickBufDirty = false; // Pick buffer up to date this.rayPickBufDirty = true; // Ray pick buffer now dirty } // Read pixel color in pick buffer at given coordinates, // convert to an index into the pick name list var pix = pickBuf.read(canvasX, canvasY); // Read pick buffer pickBuf.unbind(); // Unbind pick buffer if (params.regionPick) { // Region picking if (pix[0] === 0 && pix[1] === 0 && pix[2] === 0 && pix[3] === 0) { return null; } var regionColor = {r: pix[0] / 255, g: pix[1] / 255, b: pix[2] / 255, a: pix[3] / 255}; var regionData = this._frameCtx.regionData; var tolerance = 0.01; var data = {}; var color, delta; for (var i = 0, len = regionData.length; i < len; i++) { color = regionData[i].color; if (regionColor && regionData[i].data) { delta = Math.max( Math.abs(regionColor.r - color.r), Math.abs(regionColor.g - color.g), Math.abs(regionColor.b - color.b), Math.abs(regionColor.a - (color.a === undefined ? regionColor.a : color.a)) ); if (delta < tolerance) { data = regionData[i].data; break; } } } return { color: regionColor, regionData: data, canvasPos: [canvasX, canvasY] }; } // Ray-picking var pickedObjectIndex = pix[0] + pix[1] * 256 + pix[2] * 65536; var pickIndex = (pickedObjectIndex >= 1) ? pickedObjectIndex - 1 : -1; // Look up pick name from index var pickName = this._frameCtx.pickNames[pickIndex]; // Map pixel to name if (pickName) { hit = { name: pickName.name, path: pickName.path, nodeId: pickName.nodeId, canvasPos: [canvasX, canvasY] }; // Now do a ray-pick if requested if (params.rayPick) { // Lazy-create ray pick depth buffer var rayPickBuf = this.rayPickBuf; if (!rayPickBuf) { rayPickBuf = this.rayPickBuf = new SceneJS._webgl.RenderBuffer({canvas: this._canvas}); this.rayPickBufDirty = true; } // Render depth values to ray-pick depth buffer rayPickBuf.bind(); if (this.rayPickBufDirty) { rayPickBuf.clear(); this._doDrawList({ pick: true, rayPick: true, clear: true }); this.rayPickBufDirty = false; } // Read pixel from depth buffer, convert to normalised device Z coordinate, // which will be in range of [0..1] with z=0 at front pix = rayPickBuf.read(canvasX, canvasY); rayPickBuf.unbind(); var screenZ = this._unpackDepth(pix); var w = canvas.width; var h = canvas.height; // Calculate clip space coordinates, which will be in range // of x=[-1..1] and y=[-1..1], with y=(+1) at top var x = (canvasX - w / 2) / (w / 2); // Calculate clip space coordinates var y = -(canvasY - h / 2) / (h / 2); var projMat = this._frameCtx.cameraMat; var viewMat = this._frameCtx.viewMat; var pvMat = SceneJS_math_mulMat4(projMat, viewMat, []); var pvMatInverse = SceneJS_math_inverseMat4(pvMat, []); var world1 = SceneJS_math_transformVector4(pvMatInverse, [x, y, -1, 1]); world1 = SceneJS_math_mulVec4Scalar(world1, 1 / world1[3]); var world2 = SceneJS_math_transformVector4(pvMatInverse, [x, y, 1, 1]); world2 = SceneJS_math_mulVec4Scalar(world2, 1 / world2[3]); var dir = SceneJS_math_subVec3(world2, world1, []); var vWorld = SceneJS_math_addVec3(world1, SceneJS_math_mulVec4Scalar(dir, screenZ, []), []); // Got World-space intersect with surface of picked geometry hit.worldPos = vWorld; } } return hit; }; SceneJS_Display.prototype.readPixels = function (entries, size) { if (!this._readPixelBuf) { this._readPixelBuf = new SceneJS._webgl.RenderBuffer({canvas: this._canvas}); } this._readPixelBuf.bind(); this._readPixelBuf.clear(); this.render({force: true}); var entry; var color; for (var i = 0; i < size; i++) { entry = entries[i] || (entries[i] = {}); color = this._readPixelBuf.read(entry.x, entry.y); entry.r = color[0]; entry.g = color[1]; entry.b = color[2]; entry.a = color[3]; } this._readPixelBuf.unbind(); }; /** * Unpacks a color-encoded depth * @param {Array(Number)} depthZ Depth encoded as an RGBA color value * @returns {Number} * @private */ SceneJS_Display.prototype._unpackDepth = function (depthZ) { var vec = [depthZ[0] / 256.0, depthZ[1] / 256.0, depthZ[2] / 256.0, depthZ[3] / 256.0]; var bitShift = [1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0]; return SceneJS_math_dotVector4(vec, bitShift); }; /** Renders either the draw or pick list. * * @param {*} params * @param {Boolean} params.clear Set true to clear the color, depth and stencil buffers first * @param {Boolean} params.pick Set true to render for picking * @param {Boolean} params.rayPick Set true to render for ray-picking * @param {Boolean} params.regionPick Set true to render for region-picking * @param {Boolean} params.transparent Set false to only render opaque objects * @private */ SceneJS_Display.prototype._doDrawList = function (params) { var gl = this._canvas.gl; // Reset frame context var frameCtx = this._frameCtx; frameCtx.renderTarget = null; frameCtx.targetIndex = 0; frameCtx.renderBuf = null; frameCtx.viewMat = null; frameCtx.modelMat = null; frameCtx.cameraMat = null; frameCtx.renderer = null; frameCtx.depthbufEnabled = null; frameCtx.clearDepth = null; frameCtx.depthFunc = gl.LESS; frameCtx.scissorTestEnabled = false; frameCtx.blendEnabled = false; frameCtx.backfaces = true; frameCtx.frontface = "ccw"; frameCtx.pick = !!params.pick; frameCtx.rayPick = !!params.rayPick; frameCtx.regionPick = !!params.regionPick; frameCtx.pickIndex = 0; frameCtx.textureUnit = 0; frameCtx.lineWidth = 1; frameCtx.transparent = false; frameCtx.ambientColor = this._ambientColor; frameCtx.aspect = this._canvas.canvas.width / this._canvas.canvas.height; // The extensions needs to be re-queried in case the context was lost and has been recreated. if (this._canvas.UINT_INDEX_ENABLED) { gl.getExtension("OES_element_index_uint"); } var VAO = gl.getExtension("OES_vertex_array_object"); frameCtx.VAO = (VAO) ? VAO : null; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); if (this.transparent || params.pick) { gl.clearColor(0, 0, 0, 0); } else { gl.clearColor(this._ambientColor[0], this._ambientColor[1], this._ambientColor[2], 1.0); } if (params.clear) { gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); } gl.frontFace(gl.CCW); gl.disable(gl.CULL_FACE); gl.disable(gl.BLEND); if (params.pick) { // Render for pick for (var i = 0, len = this._pickDrawListLen; i < len; i++) { this._pickDrawList[i].pick(frameCtx); } } else { // Option to only render opaque objects var len = (params.opaqueOnly ? this._drawListTransparentIndex : this._drawListLen); // Render for draw for (var i = 0; i < len; i++) { // Push opaque rendering chunks this._drawList[i].draw(frameCtx); } } gl.flush(); if (frameCtx.renderBuf) { frameCtx.renderBuf.unbind(); } if (frameCtx.VAO) { frameCtx.VAO.bindVertexArrayOES(null); for (var i = 0; i < 10; i++) { gl.disableVertexAttribArray(i); } } // // var numTextureUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); // for (var ii = 0; ii < numTextureUnits; ++ii) { // gl.activeTexture(gl.TEXTURE0 + ii); // gl.bindTexture(gl.TEXTURE_CUBE_MAP, null); // gl.bindTexture(gl.TEXTURE_2D, null); // } }; SceneJS_Display.prototype.destroy = function () { this._programFactory.destroy(); };
Re-implement fixes to opaqueonly rendering
src/core/display/display.js
Re-implement fixes to opaqueonly rendering
<ide><path>rc/core/display/display.js <ide> return hit; <ide> }; <ide> <del>SceneJS_Display.prototype.readPixels = function (entries, size) { <add>SceneJS_Display.prototype.readPixels = function (entries, size, opaqueOnly) { <ide> <ide> if (!this._readPixelBuf) { <ide> this._readPixelBuf = new SceneJS._webgl.RenderBuffer({canvas: this._canvas}); <ide> <ide> this._readPixelBuf.clear(); <ide> <del> this.render({force: true}); <add> this.render({ <add> force: true, <add> opaqueOnly: opaqueOnly <add> }); <ide> <ide> var entry; <ide> var color; <ide> } else { <ide> <ide> // Option to only render opaque objects <del> var len = (params.opaqueOnly ? this._drawListTransparentIndex : this._drawListLen); <add> var len = (params.opaqueOnly && this._drawListTransparentIndex >= 0 ? this._drawListTransparentIndex : this._drawListLen); <ide> <ide> // Render for draw <ide> for (var i = 0; i < len; i++) { // Push opaque rendering chunks
Java
apache-2.0
e14a1ff958f08ebc2a7061c2868e31e075ed2274
0
yuanxxx/UltimateRecyclerView,sw926/UltimateRecyclerView,muyi126/UltimateRecyclerView,flyou/UltimateRecyclerView,JerryloveEmily/UltimateRecyclerView,freeman0211/UltimateRecyclerView,qingsong-xu/UltimateRecyclerView,Darin726/UltimateRecyclerView,marcoaros/UltimateRecyclerView,yizw/UltimateRecyclerView,YuzurihaInori/UltimateRecyclerView,hongyewell/UltimateRecyclerView,shiguol/UltimateRecyclerView,HasanAliKaraca/UltimateRecyclerView,TedaLIEz/UltimateRecyclerView,crazywenza/UltimateRecyclerView,ybin/UltimateRecyclerView,hihiwjc/UltimateRecyclerView,stronglee/UltimateRecyclerView,cymcsg/UltimateRecyclerView,onlynight/UltimateRecyclerView,liwangdong/UltimateRecyclerView,saeednt/UltimateRecyclerView,HiQianBei/UltimateRecyclerView,GG-YC/UltimateRecyclerView,MonoCloud/UltimateRecyclerView,hanhailong/UltimateRecyclerView,b-cuts/UltimateRecyclerView,ranjitzade/UltimateRecyclerView,zhengyuqin/UltimateRecyclerView,newtonker/UltimateRecyclerView,HKMOpen/UltimateRecyclerView,changjiashuai/UltimateRecyclerView,wangkang0627/UltimateRecyclerView,bigsui/UltimateRecyclerView,wklin8607/UltimateRecyclerView,bayan1987/UltimateRecyclerView,wlmxj/UltimateRecyclerView
package com.marshalchen.ultimaterecyclerview.demo; import android.graphics.Color; import android.graphics.Point; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.DisplayMetrics; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.AdView; import com.marshalchen.ultimaterecyclerview.AdmobAdapter; import com.marshalchen.ultimaterecyclerview.URLogs; import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView; import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder; import com.marshalchen.ultimaterecyclerview.demo.modules.SampleDataboxset; import com.marshalchen.ultimaterecyclerview.quickAdapter.easyRegularAdapter; import com.marshalchen.ultimaterecyclerview.quickAdapter.simpleAdmobAdapter; import com.marshalchen.ultimaterecyclerview.quickAdapter.switchableadapter; import java.util.ArrayList; import java.util.List; /** * Created by hesk on 4/8/15. */ public class TestAdvancedAdmobActivity extends AppCompatActivity { private UltimateRecyclerView ultimateRecyclerView; private boolean admob_test_mode = false; private LinearLayoutManager linearLayoutManager; private Toolbar toolbar; public static class adap extends simpleAdmobAdapter<String, VMoler, AdView> { public adap(AdView adview, boolean insertOnce, int setInterval, List<String> L) { super(adview, insertOnce, setInterval, L); } public adap(AdView adview, boolean insertOnce, int setInterval, List<String> L, AdviewListener listener) { super(adview, insertOnce, setInterval, L, listener); } @Override protected void withBindHolder(VMoler var1, String var2, int var3) { bindthisInhere(var1, var2, var3); } @Override protected int getNormalLayoutResId() { return R.layout.recycler_view_adapter; } @Override protected VMoler newViewHolder(View mview) { return new VMoler(mview); } @Override public UltimateRecyclerviewViewHolder getViewHolder(View view) { return new UltimateRecyclerviewViewHolder(view); } } public static class regular extends easyRegularAdapter<String, VMoler> { public regular(List list) { super(list); } @Override protected int getNormalLayoutResId() { return R.layout.recycler_view_adapter; } @Override protected VMoler newViewHolder(View view) { return new VMoler(view); } @Override public UltimateRecyclerviewViewHolder getViewHolder(View view) { return new UltimateRecyclerviewViewHolder(view); } @Override protected void withBindHolder(VMoler holderm, String data, int position) { bindthisInhere(holderm, data, position); } } private static void bindthisInhere(VMoler d, String data, int pos) { d.textViewSample.setText(data); } private AdView createadmob() { AdSize adSize = AdSize.SMART_BANNER; DisplayMetrics dm = getResources().getDisplayMetrics(); double density = dm.density * 160; double x = Math.pow(dm.widthPixels / density, 2); double y = Math.pow(dm.heightPixels / density, 2); double screenInches = Math.sqrt(x + y); if (screenInches > 8) { // > 728 X 90 adSize = AdSize.LEADERBOARD; } else if (screenInches > 6) { // > 468 X 60 adSize = AdSize.MEDIUM_RECTANGLE; } else { // > 320 X 50 adSize = AdSize.BANNER; } AdView mAdView = new AdView(this); mAdView.setAdSize(adSize); mAdView.setAdUnitId("/1015938/Hypebeast_App_320x50"); mAdView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); // Create an ad request. AdRequest.Builder adRequestBuilder = new AdRequest.Builder(); if (admob_test_mode) // Optionally populate the ad request builder. adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR); // Start loading the ad. mAdView.loadAd(adRequestBuilder.build()); return mAdView; } public static class VMoler extends UltimateRecyclerviewViewHolder implements View.OnClickListener, View.OnLongClickListener { public TextView textViewSample; public ImageView imageViewSample; public ProgressBar progressBarSample; public VMoler(View itemView) { super(itemView); textViewSample = (TextView) itemView.findViewById(R.id.textview); imageViewSample = (ImageView) itemView.findViewById(R.id.imageview); progressBarSample = (ProgressBar) itemView.findViewById(R.id.progressbar); progressBarSample.setVisibility(View.GONE); } @Override public void onClick(@NonNull View v) { URLogs.d(textViewSample.getText() + " clicked!"); } @Override public boolean onLongClick(@NonNull View v) { URLogs.d(textViewSample.getText() + " long clicked!"); return true; } } /** * example 1 implementation of the switch view */ private switchableadapter imple_switch_view(final UltimateRecyclerView rv) { final adap adp1 = new adap(createadmob(), false, 4, new ArrayList<String>(), new AdmobAdapter.AdviewListener() { @Override public AdView onGenerateAdview() { return createadmob(); } }); final regular adp2 = new regular(new ArrayList<String>()); final switchableadapter switchable = new switchableadapter(rv, adp2, adp1); return switchable; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.tool_bar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); ultimateRecyclerView = (UltimateRecyclerView) findViewById(R.id.ultimate_recycler_view); ultimateRecyclerView.setHasFixedSize(false); linearLayoutManager = new LinearLayoutManager(this); ultimateRecyclerView.setLayoutManager(linearLayoutManager); ultimateRecyclerView.setRecylerViewBackgroundColor(Color.parseColor("#ffffff")); /** * example 2 implementation enhancement of list view */ final switchableadapter sw = imple_switch_view(ultimateRecyclerView) .onEnableRefresh(100) .onEnableLoadmore(R.layout.custom_bottom_progressbar, 100, new switchableadapter.onLoadMore() { @Override public boolean request_start(int current_page_no, int itemsCount, int maxLastVisiblePosition, switchableadapter this_module) { this_module.load_more_data(SampleDataboxset.newList()); return true; } }); TextView b = (TextView) findViewById(R.id.del); b.setText("with Ad"); TextView a = (TextView) findViewById(R.id.add); a.setText("with out Ad"); a.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /** * example 2 implementation enhancement of list view * without advertisement configurations */ sw.init(false); } }); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /** * example 2 implementation enhancement of list view * with advertisement configuration */ sw.init(true); } }); } }
UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/TestAdvancedAdmobActivity.java
package com.marshalchen.ultimaterecyclerview.demo; import android.graphics.Color; import android.graphics.Point; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.DisplayMetrics; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.AdView; import com.marshalchen.ultimaterecyclerview.AdmobAdapter; import com.marshalchen.ultimaterecyclerview.URLogs; import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView; import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder; import com.marshalchen.ultimaterecyclerview.demo.modules.SampleDataboxset; import com.marshalchen.ultimaterecyclerview.quickAdapter.easyRegularAdapter; import com.marshalchen.ultimaterecyclerview.quickAdapter.simpleAdmobAdapter; import com.marshalchen.ultimaterecyclerview.quickAdapter.switchableadapter; import java.util.ArrayList; import java.util.List; /** * Created by hesk on 4/8/15. */ public class TestAdvancedAdmobActivity extends AppCompatActivity { private UltimateRecyclerView ultimateRecyclerView; private boolean admob_test_mode = false; private LinearLayoutManager linearLayoutManager; private Toolbar toolbar; public static class adap extends simpleAdmobAdapter<String, VMoler, AdView> { public adap(AdView adview, boolean insertOnce, int setInterval, List<String> L) { super(adview, insertOnce, setInterval, L); } public adap(AdView adview, boolean insertOnce, int setInterval, List<String> L, AdviewListener listener) { super(adview, insertOnce, setInterval, L, listener); } @Override protected void withBindHolder(VMoler var1, String var2, int var3) { bindthisInhere(var1, var2, var3); } @Override protected int getNormalLayoutResId() { return R.layout.recycler_view_adapter; } @Override protected VMoler newViewHolder(View mview) { return new VMoler(mview); } @Override public UltimateRecyclerviewViewHolder getViewHolder(View view) { return new UltimateRecyclerviewViewHolder(view); } } public static class regular extends easyRegularAdapter<String, VMoler> { public regular(List list) { super(list); } @Override protected int getNormalLayoutResId() { return R.layout.recycler_view_adapter; } @Override protected VMoler newViewHolder(View view) { return new VMoler(view); } @Override public UltimateRecyclerviewViewHolder getViewHolder(View view) { return new UltimateRecyclerviewViewHolder(view); } @Override protected void withBindHolder(VMoler holderm, String data, int position) { bindthisInhere(holderm, data, position); } } private static void bindthisInhere(VMoler d, String data, int pos) { d.textViewSample.setText(data); } private AdView createadmob() { AdSize adSize = AdSize.SMART_BANNER; DisplayMetrics dm = getResources().getDisplayMetrics(); double density = dm.density * 160; double x = Math.pow(dm.widthPixels / density, 2); double y = Math.pow(dm.heightPixels / density, 2); double screenInches = Math.sqrt(x + y); if (screenInches > 8) { // > 728 X 90 adSize = AdSize.LEADERBOARD; } else if (screenInches > 6) { // > 468 X 60 adSize = AdSize.MEDIUM_RECTANGLE; } else { // > 320 X 50 adSize = AdSize.BANNER; } AdView mAdView = new AdView(this); mAdView.setAdSize(adSize); mAdView.setAdUnitId("/1015938/Hypebeast_App_320x50"); mAdView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); // Create an ad request. AdRequest.Builder adRequestBuilder = new AdRequest.Builder(); if (admob_test_mode) // Optionally populate the ad request builder. adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR); // Start loading the ad. mAdView.loadAd(adRequestBuilder.build()); return mAdView; } public static class VMoler extends UltimateRecyclerviewViewHolder implements View.OnClickListener, View.OnLongClickListener { public TextView textViewSample; public ImageView imageViewSample; public ProgressBar progressBarSample; public VMoler(View itemView) { super(itemView); textViewSample = (TextView) itemView.findViewById(R.id.textview); imageViewSample = (ImageView) itemView.findViewById(R.id.imageview); progressBarSample = (ProgressBar) itemView.findViewById(R.id.progressbar); progressBarSample.setVisibility(View.GONE); } @Override public void onClick(@NonNull View v) { URLogs.d(textViewSample.getText() + " clicked!"); } @Override public boolean onLongClick(@NonNull View v) { URLogs.d(textViewSample.getText() + " long clicked!"); return true; } } /** * example 1 implementation of the switch view */ private switchableadapter imple_switch_view(final UltimateRecyclerView rv) { final adap adp1 = new adap(createadmob(), false, 4, new ArrayList<String>(), new AdmobAdapter.AdviewListener() { @Override public AdView onGenerateAdview() { return createadmob(); } }); final regular adp2 = new regular(new ArrayList<String>()); final switchableadapter switchable = new switchableadapter(rv, adp2, adp1); return switchable; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.tool_bar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); ultimateRecyclerView = (UltimateRecyclerView) findViewById(R.id.ultimate_recycler_view); ultimateRecyclerView.setHasFixedSize(false); linearLayoutManager = new LinearLayoutManager(this); ultimateRecyclerView.setLayoutManager(linearLayoutManager); ultimateRecyclerView.setRecylerViewBackgroundColor(Color.parseColor("#ffffff")); /** * example 2 implementation enhancement of list view */ final switchableadapter sw = imple_switch_view(ultimateRecyclerView) .onEnableRefresh(100) .onEnableLoadmore(R.layout.custom_bottom_progressbar, 100, new switchableadapter.onLoadMore() { @Override public boolean request_start(int current_page_no, int itemsCount, int maxLastVisiblePosition, switchableadapter this_module) { this_module.load_more_data(SampleDataboxset.newList()); return true; } }); TextView b = (TextView) findViewById(R.id.del); b.setText("with Ad"); TextView a = (TextView) findViewById(R.id.add); a.setText("with out Ad"); a.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /** * example 2 implementation enhancement of list view */ sw.init(false); } }); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /** * example 2 implementation enhancement of list view */ sw.init(true); } }); } }
more explaination
UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/TestAdvancedAdmobActivity.java
more explaination
<ide><path>ltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/TestAdvancedAdmobActivity.java <ide> public void onClick(View v) { <ide> /** <ide> * example 2 implementation enhancement of list view <add> * without advertisement configurations <ide> */ <ide> sw.init(false); <ide> } <ide> public void onClick(View v) { <ide> /** <ide> * example 2 implementation enhancement of list view <add> * with advertisement configuration <ide> */ <ide> sw.init(true); <ide> }
Java
apache-2.0
dce6bc1554ea648e6910ce2b80417a647c422397
0
Thotep/libgdx,sjosegarcia/libgdx,nrallakis/libgdx,saltares/libgdx,samskivert/libgdx,snovak/libgdx,Deftwun/libgdx,Gliby/libgdx,curtiszimmerman/libgdx,MovingBlocks/libgdx,TheAks999/libgdx,toloudis/libgdx,FyiurAmron/libgdx,alex-dorokhov/libgdx,Zomby2D/libgdx,ryoenji/libgdx,luischavez/libgdx,EsikAntony/libgdx,thepullman/libgdx,tommyettinger/libgdx,andyvand/libgdx,Arcnor/libgdx,anserran/libgdx,nudelchef/libgdx,anserran/libgdx,saqsun/libgdx,Thotep/libgdx,UnluckyNinja/libgdx,fiesensee/libgdx,youprofit/libgdx,xoppa/libgdx,Wisienkas/libgdx,ricardorigodon/libgdx,Xhanim/libgdx,PedroRomanoBarbosa/libgdx,gouessej/libgdx,czyzby/libgdx,sarkanyi/libgdx,revo09/libgdx,stickyd/libgdx,zhimaijoy/libgdx,js78/libgdx,billgame/libgdx,Badazdz/libgdx,xoppa/libgdx,jberberick/libgdx,Senth/libgdx,designcrumble/libgdx,toa5/libgdx,del-sol/libgdx,youprofit/libgdx,gdos/libgdx,zommuter/libgdx,JDReutt/libgdx,Xhanim/libgdx,PedroRomanoBarbosa/libgdx,xranby/libgdx,ya7lelkom/libgdx,haedri/libgdx-1,azakhary/libgdx,tell10glu/libgdx,MovingBlocks/libgdx,junkdog/libgdx,EsikAntony/libgdx,designcrumble/libgdx,KrisLee/libgdx,UnluckyNinja/libgdx,NathanSweet/libgdx,stickyd/libgdx,Heart2009/libgdx,del-sol/libgdx,UnluckyNinja/libgdx,mumer92/libgdx,davebaol/libgdx,tell10glu/libgdx,samskivert/libgdx,stinsonga/libgdx,Thotep/libgdx,jsjolund/libgdx,jsjolund/libgdx,firefly2442/libgdx,ThiagoGarciaAlves/libgdx,codepoke/libgdx,JFixby/libgdx,sinistersnare/libgdx,lordjone/libgdx,billgame/libgdx,gouessej/libgdx,jsjolund/libgdx,Arcnor/libgdx,309746069/libgdx,Deftwun/libgdx,nooone/libgdx,nrallakis/libgdx,codepoke/libgdx,billgame/libgdx,stickyd/libgdx,MetSystem/libgdx,anserran/libgdx,Wisienkas/libgdx,billgame/libgdx,josephknight/libgdx,Heart2009/libgdx,MikkelTAndersen/libgdx,toa5/libgdx,revo09/libgdx,firefly2442/libgdx,youprofit/libgdx,gf11speed/libgdx,Heart2009/libgdx,thepullman/libgdx,alireza-hosseini/libgdx,petugez/libgdx,xoppa/libgdx,FyiurAmron/libgdx,flaiker/libgdx,codepoke/libgdx,davebaol/libgdx,realitix/libgdx,PedroRomanoBarbosa/libgdx,saqsun/libgdx,Gliby/libgdx,1yvT0s/libgdx,bsmr-java/libgdx,toa5/libgdx,jasonwee/libgdx,tommycli/libgdx,gdos/libgdx,curtiszimmerman/libgdx,codepoke/libgdx,stickyd/libgdx,GreenLightning/libgdx,petugez/libgdx,Heart2009/libgdx,EsikAntony/libgdx,ttencate/libgdx,MathieuDuponchelle/gdx,samskivert/libgdx,bgroenks96/libgdx,kzganesan/libgdx,hyvas/libgdx,Zomby2D/libgdx,mumer92/libgdx,czyzby/libgdx,titovmaxim/libgdx,mumer92/libgdx,fiesensee/libgdx,kagehak/libgdx,luischavez/libgdx,yangweigbh/libgdx,stinsonga/libgdx,Zonglin-Li6565/libgdx,FyiurAmron/libgdx,MetSystem/libgdx,zhimaijoy/libgdx,mumer92/libgdx,tommycli/libgdx,gdos/libgdx,bsmr-java/libgdx,saltares/libgdx,Gliby/libgdx,tell10glu/libgdx,309746069/libgdx,nudelchef/libgdx,djom20/libgdx,bsmr-java/libgdx,Badazdz/libgdx,ninoalma/libgdx,luischavez/libgdx,thepullman/libgdx,PedroRomanoBarbosa/libgdx,MathieuDuponchelle/gdx,mumer92/libgdx,samskivert/libgdx,bsmr-java/libgdx,EsikAntony/libgdx,yangweigbh/libgdx,Badazdz/libgdx,ninoalma/libgdx,ninoalma/libgdx,hyvas/libgdx,309746069/libgdx,bsmr-java/libgdx,kzganesan/libgdx,kotcrab/libgdx,Wisienkas/libgdx,youprofit/libgdx,xpenatan/libgdx-LWJGL3,yangweigbh/libgdx,noelsison2/libgdx,fiesensee/libgdx,alireza-hosseini/libgdx,petugez/libgdx,saltares/libgdx,Thotep/libgdx,tommyettinger/libgdx,jasonwee/libgdx,anserran/libgdx,alex-dorokhov/libgdx,firefly2442/libgdx,FyiurAmron/libgdx,Heart2009/libgdx,youprofit/libgdx,js78/libgdx,JDReutt/libgdx,andyvand/libgdx,gouessej/libgdx,Dzamir/libgdx,copystudy/libgdx,toloudis/libgdx,xpenatan/libgdx-LWJGL3,Zomby2D/libgdx,MetSystem/libgdx,srwonka/libGdx,KrisLee/libgdx,basherone/libgdxcn,xpenatan/libgdx-LWJGL3,hyvas/libgdx,Xhanim/libgdx,alex-dorokhov/libgdx,fiesensee/libgdx,ThiagoGarciaAlves/libgdx,basherone/libgdxcn,titovmaxim/libgdx,zommuter/libgdx,bladecoder/libgdx,MovingBlocks/libgdx,haedri/libgdx-1,kzganesan/libgdx,JFixby/libgdx,JFixby/libgdx,tell10glu/libgdx,zommuter/libgdx,js78/libgdx,Senth/libgdx,ttencate/libgdx,josephknight/libgdx,FyiurAmron/libgdx,del-sol/libgdx,snovak/libgdx,nudelchef/libgdx,haedri/libgdx-1,FyiurAmron/libgdx,saqsun/libgdx,sarkanyi/libgdx,davebaol/libgdx,andyvand/libgdx,FredGithub/libgdx,sarkanyi/libgdx,kotcrab/libgdx,thepullman/libgdx,snovak/libgdx,libgdx/libgdx,cypherdare/libgdx,jasonwee/libgdx,thepullman/libgdx,toa5/libgdx,ninoalma/libgdx,del-sol/libgdx,petugez/libgdx,nave966/libgdx,shiweihappy/libgdx,Wisienkas/libgdx,JDReutt/libgdx,billgame/libgdx,kagehak/libgdx,MathieuDuponchelle/gdx,srwonka/libGdx,Thotep/libgdx,yangweigbh/libgdx,gouessej/libgdx,tell10glu/libgdx,Thotep/libgdx,codepoke/libgdx,zommuter/libgdx,sarkanyi/libgdx,sarkanyi/libgdx,UnluckyNinja/libgdx,ryoenji/libgdx,1yvT0s/libgdx,Dzamir/libgdx,MetSystem/libgdx,FyiurAmron/libgdx,kotcrab/libgdx,Arcnor/libgdx,ya7lelkom/libgdx,xranby/libgdx,Heart2009/libgdx,nrallakis/libgdx,toa5/libgdx,NathanSweet/libgdx,ricardorigodon/libgdx,zommuter/libgdx,SidneyXu/libgdx,codepoke/libgdx,shiweihappy/libgdx,katiepino/libgdx,Dzamir/libgdx,Deftwun/libgdx,shiweihappy/libgdx,nudelchef/libgdx,titovmaxim/libgdx,billgame/libgdx,ninoalma/libgdx,ztv/libgdx,jsjolund/libgdx,Arcnor/libgdx,zhimaijoy/libgdx,toloudis/libgdx,gf11speed/libgdx,MikkelTAndersen/libgdx,Zonglin-Li6565/libgdx,mumer92/libgdx,antag99/libgdx,sjosegarcia/libgdx,MadcowD/libgdx,youprofit/libgdx,alex-dorokhov/libgdx,azakhary/libgdx,jasonwee/libgdx,nave966/libgdx,alex-dorokhov/libgdx,309746069/libgdx,toloudis/libgdx,Zonglin-Li6565/libgdx,toloudis/libgdx,Zomby2D/libgdx,MadcowD/libgdx,noelsison2/libgdx,PedroRomanoBarbosa/libgdx,junkdog/libgdx,billgame/libgdx,hyvas/libgdx,saqsun/libgdx,MikkelTAndersen/libgdx,Zonglin-Li6565/libgdx,petugez/libgdx,jberberick/libgdx,junkdog/libgdx,fwolff/libgdx,Deftwun/libgdx,noelsison2/libgdx,copystudy/libgdx,TheAks999/libgdx,katiepino/libgdx,Deftwun/libgdx,gdos/libgdx,anserran/libgdx,bladecoder/libgdx,srwonka/libGdx,nudelchef/libgdx,yangweigbh/libgdx,xoppa/libgdx,NathanSweet/libgdx,JDReutt/libgdx,hyvas/libgdx,FredGithub/libgdx,nooone/libgdx,srwonka/libGdx,SidneyXu/libgdx,lordjone/libgdx,1yvT0s/libgdx,jasonwee/libgdx,kagehak/libgdx,MathieuDuponchelle/gdx,SidneyXu/libgdx,junkdog/libgdx,ryoenji/libgdx,PedroRomanoBarbosa/libgdx,ztv/libgdx,curtiszimmerman/libgdx,saqsun/libgdx,ninoalma/libgdx,luischavez/libgdx,bsmr-java/libgdx,MikkelTAndersen/libgdx,nudelchef/libgdx,libgdx/libgdx,zhimaijoy/libgdx,MikkelTAndersen/libgdx,BlueRiverInteractive/libgdx,FredGithub/libgdx,snovak/libgdx,ninoalma/libgdx,nrallakis/libgdx,codepoke/libgdx,MadcowD/libgdx,ztv/libgdx,sinistersnare/libgdx,gf11speed/libgdx,sinistersnare/libgdx,ya7lelkom/libgdx,ztv/libgdx,junkdog/libgdx,titovmaxim/libgdx,MovingBlocks/libgdx,nrallakis/libgdx,KrisLee/libgdx,TheAks999/libgdx,MathieuDuponchelle/gdx,Zonglin-Li6565/libgdx,MathieuDuponchelle/gdx,zommuter/libgdx,zommuter/libgdx,Wisienkas/libgdx,titovmaxim/libgdx,kzganesan/libgdx,Thotep/libgdx,josephknight/libgdx,JFixby/libgdx,jsjolund/libgdx,kagehak/libgdx,toa5/libgdx,youprofit/libgdx,collinsmith/libgdx,kagehak/libgdx,designcrumble/libgdx,EsikAntony/libgdx,309746069/libgdx,BlueRiverInteractive/libgdx,ya7lelkom/libgdx,andyvand/libgdx,js78/libgdx,flaiker/libgdx,bladecoder/libgdx,petugez/libgdx,xranby/libgdx,ya7lelkom/libgdx,309746069/libgdx,azakhary/libgdx,GreenLightning/libgdx,alireza-hosseini/libgdx,xoppa/libgdx,toloudis/libgdx,Zonglin-Li6565/libgdx,KrisLee/libgdx,curtiszimmerman/libgdx,BlueRiverInteractive/libgdx,MadcowD/libgdx,fwolff/libgdx,fiesensee/libgdx,lordjone/libgdx,katiepino/libgdx,sarkanyi/libgdx,Wisienkas/libgdx,josephknight/libgdx,MadcowD/libgdx,zhimaijoy/libgdx,josephknight/libgdx,Thotep/libgdx,jasonwee/libgdx,saltares/libgdx,shiweihappy/libgdx,fiesensee/libgdx,xpenatan/libgdx-LWJGL3,toloudis/libgdx,MadcowD/libgdx,katiepino/libgdx,junkdog/libgdx,MetSystem/libgdx,FredGithub/libgdx,revo09/libgdx,UnluckyNinja/libgdx,ThiagoGarciaAlves/libgdx,djom20/libgdx,alireza-hosseini/libgdx,ricardorigodon/libgdx,stickyd/libgdx,Badazdz/libgdx,djom20/libgdx,ttencate/libgdx,samskivert/libgdx,zhimaijoy/libgdx,collinsmith/libgdx,lordjone/libgdx,UnluckyNinja/libgdx,gouessej/libgdx,alireza-hosseini/libgdx,josephknight/libgdx,nooone/libgdx,KrisLee/libgdx,sjosegarcia/libgdx,xoppa/libgdx,davebaol/libgdx,realitix/libgdx,shiweihappy/libgdx,xranby/libgdx,jasonwee/libgdx,lordjone/libgdx,nelsonsilva/libgdx,bgroenks96/libgdx,alex-dorokhov/libgdx,zhimaijoy/libgdx,Dzamir/libgdx,tell10glu/libgdx,designcrumble/libgdx,billgame/libgdx,UnluckyNinja/libgdx,firefly2442/libgdx,fiesensee/libgdx,TheAks999/libgdx,SidneyXu/libgdx,SidneyXu/libgdx,revo09/libgdx,luischavez/libgdx,copystudy/libgdx,saltares/libgdx,kzganesan/libgdx,gdos/libgdx,collinsmith/libgdx,katiepino/libgdx,katiepino/libgdx,js78/libgdx,czyzby/libgdx,cypherdare/libgdx,nave966/libgdx,JDReutt/libgdx,srwonka/libGdx,cypherdare/libgdx,Zonglin-Li6565/libgdx,gf11speed/libgdx,Arcnor/libgdx,shiweihappy/libgdx,Dzamir/libgdx,MikkelTAndersen/libgdx,anserran/libgdx,TheAks999/libgdx,ttencate/libgdx,flaiker/libgdx,sinistersnare/libgdx,BlueRiverInteractive/libgdx,czyzby/libgdx,Senth/libgdx,Gliby/libgdx,alex-dorokhov/libgdx,MikkelTAndersen/libgdx,luischavez/libgdx,realitix/libgdx,jasonwee/libgdx,andyvand/libgdx,nelsonsilva/libgdx,antag99/libgdx,tell10glu/libgdx,MathieuDuponchelle/gdx,sinistersnare/libgdx,ttencate/libgdx,UnluckyNinja/libgdx,kotcrab/libgdx,haedri/libgdx-1,djom20/libgdx,MetSystem/libgdx,sjosegarcia/libgdx,bladecoder/libgdx,TheAks999/libgdx,309746069/libgdx,ThiagoGarciaAlves/libgdx,Heart2009/libgdx,nelsonsilva/libgdx,katiepino/libgdx,lordjone/libgdx,nrallakis/libgdx,antag99/libgdx,davebaol/libgdx,nudelchef/libgdx,libgdx/libgdx,hyvas/libgdx,yangweigbh/libgdx,tommyettinger/libgdx,alex-dorokhov/libgdx,Gliby/libgdx,Dzamir/libgdx,FredGithub/libgdx,309746069/libgdx,czyzby/libgdx,katiepino/libgdx,saqsun/libgdx,saltares/libgdx,FyiurAmron/libgdx,alireza-hosseini/libgdx,Deftwun/libgdx,tommyettinger/libgdx,jberberick/libgdx,noelsison2/libgdx,djom20/libgdx,gf11speed/libgdx,xoppa/libgdx,stinsonga/libgdx,xranby/libgdx,Senth/libgdx,GreenLightning/libgdx,copystudy/libgdx,toloudis/libgdx,1yvT0s/libgdx,titovmaxim/libgdx,luischavez/libgdx,junkdog/libgdx,yangweigbh/libgdx,BlueRiverInteractive/libgdx,haedri/libgdx-1,realitix/libgdx,bgroenks96/libgdx,fwolff/libgdx,sinistersnare/libgdx,bgroenks96/libgdx,lordjone/libgdx,KrisLee/libgdx,stickyd/libgdx,saltares/libgdx,GreenLightning/libgdx,libgdx/libgdx,Xhanim/libgdx,xpenatan/libgdx-LWJGL3,MathieuDuponchelle/gdx,nelsonsilva/libgdx,cypherdare/libgdx,Badazdz/libgdx,gdos/libgdx,Senth/libgdx,Badazdz/libgdx,kotcrab/libgdx,noelsison2/libgdx,snovak/libgdx,snovak/libgdx,Xhanim/libgdx,copystudy/libgdx,copystudy/libgdx,tommycli/libgdx,haedri/libgdx-1,libgdx/libgdx,luischavez/libgdx,azakhary/libgdx,ya7lelkom/libgdx,revo09/libgdx,mumer92/libgdx,thepullman/libgdx,designcrumble/libgdx,andyvand/libgdx,ryoenji/libgdx,djom20/libgdx,FredGithub/libgdx,realitix/libgdx,1yvT0s/libgdx,noelsison2/libgdx,flaiker/libgdx,Gliby/libgdx,sarkanyi/libgdx,youprofit/libgdx,MadcowD/libgdx,del-sol/libgdx,noelsison2/libgdx,nave966/libgdx,ricardorigodon/libgdx,gdos/libgdx,jberberick/libgdx,gouessej/libgdx,junkdog/libgdx,stickyd/libgdx,MovingBlocks/libgdx,codepoke/libgdx,andyvand/libgdx,ya7lelkom/libgdx,azakhary/libgdx,gdos/libgdx,gouessej/libgdx,designcrumble/libgdx,flaiker/libgdx,del-sol/libgdx,shiweihappy/libgdx,flaiker/libgdx,nelsonsilva/libgdx,JFixby/libgdx,gouessej/libgdx,KrisLee/libgdx,xranby/libgdx,Senth/libgdx,petugez/libgdx,srwonka/libGdx,bgroenks96/libgdx,Dzamir/libgdx,Deftwun/libgdx,tommycli/libgdx,jsjolund/libgdx,haedri/libgdx-1,JFixby/libgdx,fwolff/libgdx,kzganesan/libgdx,ricardorigodon/libgdx,xranby/libgdx,hyvas/libgdx,Xhanim/libgdx,MikkelTAndersen/libgdx,titovmaxim/libgdx,firefly2442/libgdx,curtiszimmerman/libgdx,copystudy/libgdx,bgroenks96/libgdx,KrisLee/libgdx,ya7lelkom/libgdx,jberberick/libgdx,copystudy/libgdx,gf11speed/libgdx,kzganesan/libgdx,collinsmith/libgdx,samskivert/libgdx,ttencate/libgdx,kagehak/libgdx,toa5/libgdx,tommycli/libgdx,nooone/libgdx,nave966/libgdx,yangweigbh/libgdx,josephknight/libgdx,czyzby/libgdx,del-sol/libgdx,del-sol/libgdx,sjosegarcia/libgdx,jberberick/libgdx,shiweihappy/libgdx,kagehak/libgdx,djom20/libgdx,samskivert/libgdx,collinsmith/libgdx,jsjolund/libgdx,JDReutt/libgdx,js78/libgdx,lordjone/libgdx,Arcnor/libgdx,firefly2442/libgdx,stinsonga/libgdx,sjosegarcia/libgdx,ryoenji/libgdx,mumer92/libgdx,fwolff/libgdx,1yvT0s/libgdx,ThiagoGarciaAlves/libgdx,GreenLightning/libgdx,ztv/libgdx,ryoenji/libgdx,andyvand/libgdx,fwolff/libgdx,curtiszimmerman/libgdx,1yvT0s/libgdx,ryoenji/libgdx,xpenatan/libgdx-LWJGL3,MovingBlocks/libgdx,kagehak/libgdx,azakhary/libgdx,snovak/libgdx,thepullman/libgdx,ricardorigodon/libgdx,Badazdz/libgdx,collinsmith/libgdx,curtiszimmerman/libgdx,bsmr-java/libgdx,realitix/libgdx,bsmr-java/libgdx,davebaol/libgdx,ztv/libgdx,ninoalma/libgdx,sjosegarcia/libgdx,TheAks999/libgdx,stinsonga/libgdx,antag99/libgdx,firefly2442/libgdx,Senth/libgdx,bladecoder/libgdx,petugez/libgdx,xpenatan/libgdx-LWJGL3,curtiszimmerman/libgdx,GreenLightning/libgdx,basherone/libgdxcn,JFixby/libgdx,Xhanim/libgdx,BlueRiverInteractive/libgdx,bgroenks96/libgdx,BlueRiverInteractive/libgdx,Dzamir/libgdx,1yvT0s/libgdx,GreenLightning/libgdx,josephknight/libgdx,SidneyXu/libgdx,TheAks999/libgdx,antag99/libgdx,anserran/libgdx,nave966/libgdx,alireza-hosseini/libgdx,ThiagoGarciaAlves/libgdx,djom20/libgdx,revo09/libgdx,JFixby/libgdx,BlueRiverInteractive/libgdx,JDReutt/libgdx,ttencate/libgdx,Wisienkas/libgdx,Zomby2D/libgdx,Heart2009/libgdx,czyzby/libgdx,kotcrab/libgdx,firefly2442/libgdx,bgroenks96/libgdx,xoppa/libgdx,xpenatan/libgdx-LWJGL3,srwonka/libGdx,collinsmith/libgdx,MadcowD/libgdx,srwonka/libGdx,ricardorigodon/libgdx,Badazdz/libgdx,Senth/libgdx,jberberick/libgdx,hyvas/libgdx,czyzby/libgdx,designcrumble/libgdx,antag99/libgdx,nrallakis/libgdx,EsikAntony/libgdx,noelsison2/libgdx,saqsun/libgdx,tell10glu/libgdx,nave966/libgdx,realitix/libgdx,GreenLightning/libgdx,MetSystem/libgdx,EsikAntony/libgdx,antag99/libgdx,ThiagoGarciaAlves/libgdx,Gliby/libgdx,samskivert/libgdx,sarkanyi/libgdx,realitix/libgdx,titovmaxim/libgdx,ricardorigodon/libgdx,snovak/libgdx,SidneyXu/libgdx,kotcrab/libgdx,kotcrab/libgdx,sjosegarcia/libgdx,haedri/libgdx-1,collinsmith/libgdx,nrallakis/libgdx,FredGithub/libgdx,gf11speed/libgdx,fwolff/libgdx,Zonglin-Li6565/libgdx,EsikAntony/libgdx,cypherdare/libgdx,fiesensee/libgdx,antag99/libgdx,MetSystem/libgdx,MovingBlocks/libgdx,Xhanim/libgdx,JDReutt/libgdx,anserran/libgdx,NathanSweet/libgdx,MovingBlocks/libgdx,nooone/libgdx,xranby/libgdx,stickyd/libgdx,tommycli/libgdx,SidneyXu/libgdx,basherone/libgdxcn,FredGithub/libgdx,nooone/libgdx,revo09/libgdx,PedroRomanoBarbosa/libgdx,ztv/libgdx,basherone/libgdxcn,js78/libgdx,gf11speed/libgdx,fwolff/libgdx,ThiagoGarciaAlves/libgdx,revo09/libgdx,designcrumble/libgdx,nave966/libgdx,flaiker/libgdx,toa5/libgdx,Deftwun/libgdx,Gliby/libgdx,MathieuDuponchelle/gdx,tommycli/libgdx,basherone/libgdxcn,PedroRomanoBarbosa/libgdx,alireza-hosseini/libgdx,js78/libgdx,jsjolund/libgdx,jberberick/libgdx,nelsonsilva/libgdx,ztv/libgdx,ttencate/libgdx,tommycli/libgdx,zommuter/libgdx,flaiker/libgdx,NathanSweet/libgdx,zhimaijoy/libgdx,saqsun/libgdx,tommyettinger/libgdx,saltares/libgdx,nudelchef/libgdx,Wisienkas/libgdx,thepullman/libgdx
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.scenes.scene2d.ui; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.BitmapFont.TextBounds; import com.badlogic.gdx.graphics.g2d.BitmapFontCache; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Group; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.Touchable; import com.badlogic.gdx.scenes.scene2d.utils.Align; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; /** A table that can be dragged and act as a modal window. The top padding is used as the window's title height. * <p> * The preferred size of a window is the preferred size of the title text and the children as layed out by the table. After adding * children to the window, it can be convenient to call {@link #pack()} to size the window to the size of the children. * @author Nathan Sweet */ public class Window extends Table { private WindowStyle style; private String title; private BitmapFontCache titleCache; boolean isMovable = true, isModal; final Vector2 dragOffset = new Vector2(); boolean dragging; private int titleAlignment = Align.center; boolean keepWithinParent = true; public Window (String title, Skin skin) { this(title, skin.get(WindowStyle.class)); setSkin(skin); } public Window (String title, Skin skin, String styleName) { this(title, skin.get(styleName, WindowStyle.class)); setSkin(skin); } public Window (String title, WindowStyle style) { if (title == null) throw new IllegalArgumentException("title cannot be null."); this.title = title; setTouchable(Touchable.enabled); setClip(true); setStyle(style); setWidth(150); setHeight(150); setTitle(title); addCaptureListener(new InputListener() { public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) { toFront(); return false; } }); addListener(new InputListener() { public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) { if (button == 0) { dragging = isMovable && getHeight() - y <= getPadTop() && y < getHeight() && x > 0 && x < getWidth(); dragOffset.set(x, y); } return dragging || isModal; } public void touchDragged (InputEvent event, float x, float y, int pointer) { if (!dragging) return; translate(x - dragOffset.x, y - dragOffset.y); if (keepWithinParent) { float parentWidth, parentHeight; Group parent = getParent(); Stage stage = getStage(); if (parent == stage.getRoot()) { parentWidth = stage.getWidth(); parentHeight = stage.getHeight(); } else { parentWidth = parent.getWidth(); parentHeight = parent.getHeight(); } if (getX() < 0) setX(0); if (getRight() > parentWidth) setX(parentWidth - getWidth()); if (getY() < 0) setY(0); if (getTop() > parentHeight) setY(parentHeight - getHeight()); } } public boolean mouseMoved (InputEvent event, float x, float y) { return isModal; } public boolean scrolled (InputEvent event, float x, float y, int amount) { return isModal; } public boolean keyDown (InputEvent event, int keycode) { return isModal; } public boolean keyUp (InputEvent event, int keycode) { return isModal; } public boolean keyTyped (InputEvent event, char character) { return isModal; } }); } public void setStyle (WindowStyle style) { if (style == null) throw new IllegalArgumentException("style cannot be null."); this.style = style; setBackground(style.background); titleCache = new BitmapFontCache(style.titleFont); titleCache.setColor(style.titleFontColor); if (title != null) setTitle(title); invalidateHierarchy(); } /** Returns the window's style. Modifying the returned style may not have an effect until {@link #setStyle(WindowStyle)} is * called. */ public WindowStyle getStyle () { return style; } protected void drawBackground (SpriteBatch batch, float parentAlpha) { if (style.stageBackground != null) { Color color = getColor(); batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); Stage stage = getStage(); Vector2 position = stageToLocalCoordinates(Vector2.tmp.set(0, 0)); Vector2 size = stageToLocalCoordinates(Vector2.tmp2.set(stage.getWidth(), stage.getHeight())); style.stageBackground.draw(batch, getX() + position.x, getY() + position.y, getX() + size.x, getY() + size.y); } super.drawBackground(batch, parentAlpha); // Draw the title without the batch transformed or clipping applied. float x = getX(), y = getY() + getHeight(); TextBounds bounds = titleCache.getBounds(); if ((titleAlignment & Align.left) != 0) x += getPadLeft(); else if ((titleAlignment & Align.right) != 0) x += getWidth() - bounds.width - getPadRight(); else x += (getWidth() - bounds.width) / 2; if ((titleAlignment & Align.top) == 0) { if ((titleAlignment & Align.bottom) != 0) y -= getPadTop() - bounds.height; else y -= (getPadTop() - bounds.height) / 2; } titleCache.setColor(Color.tmp.set(getColor()).mul(style.titleFontColor)); titleCache.setPosition((int)x, (int)y); titleCache.draw(batch, parentAlpha); } public Actor hit (float x, float y, boolean touchable) { Actor hit = super.hit(x, y, touchable); if (hit == null && isModal && (!touchable || getTouchable() == Touchable.enabled)) return this; return hit; } public void setTitle (String title) { this.title = title; titleCache.setMultiLineText(title, 0, 0); } public String getTitle () { return title; } /** @param titleAlignment {@link Align} */ public void setTitleAlignment (int titleAlignment) { this.titleAlignment = titleAlignment; } public void setMovable (boolean isMovable) { this.isMovable = isMovable; } public void setModal (boolean isModal) { this.isModal = isModal; } public void setKeepWithinParent (boolean keepWithinParent) { this.keepWithinParent = keepWithinParent; } public boolean isDragging () { return dragging; } public float getPrefWidth () { return Math.max(super.getPrefWidth(), titleCache.getBounds().width + getPadLeft() + getPadRight()); } /** The style for a window, see {@link Window}. * @author Nathan Sweet */ static public class WindowStyle { /** Optional. */ public Drawable background; public BitmapFont titleFont; /** Optional. */ public Color titleFontColor = new Color(1, 1, 1, 1); /** Optional. */ public Drawable stageBackground; public WindowStyle () { } public WindowStyle (BitmapFont titleFont, Color titleFontColor, Drawable background) { this.background = background; this.titleFont = titleFont; this.titleFontColor.set(titleFontColor); } public WindowStyle (WindowStyle style) { this.background = style.background; this.titleFont = style.titleFont; this.titleFontColor = new Color(style.titleFontColor); } } }
gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Window.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.scenes.scene2d.ui; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.BitmapFont.TextBounds; import com.badlogic.gdx.graphics.g2d.BitmapFontCache; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.Touchable; import com.badlogic.gdx.scenes.scene2d.utils.Align; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; /** A table that can be dragged and act as a modal window. The top padding is used as the window's title height. * <p> * The preferred size of a window is the preferred size of the title text and the children as layed out by the table. After adding * children to the window, it can be convenient to call {@link #pack()} to size the window to the size of the children. * @author Nathan Sweet */ public class Window extends Table { private WindowStyle style; private String title; private BitmapFontCache titleCache; boolean isMovable = true, isModal; final Vector2 dragOffset = new Vector2(); boolean dragging; private int titleAlignment = Align.center; public Window (String title, Skin skin) { this(title, skin.get(WindowStyle.class)); setSkin(skin); } public Window (String title, Skin skin, String styleName) { this(title, skin.get(styleName, WindowStyle.class)); setSkin(skin); } public Window (String title, WindowStyle style) { if (title == null) throw new IllegalArgumentException("title cannot be null."); this.title = title; setTouchable(Touchable.enabled); setClip(true); setStyle(style); setWidth(150); setHeight(150); setTitle(title); addCaptureListener(new InputListener() { public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) { toFront(); return false; } }); addListener(new InputListener() { public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) { if (button == 0) { dragging = isMovable && getHeight() - y <= getPadTop() && y < getHeight() && x > 0 && x < getWidth(); dragOffset.set(x, y); } return dragging || isModal; } public void touchDragged (InputEvent event, float x, float y, int pointer) { if (!dragging) return; translate(x - dragOffset.x, y - dragOffset.y); } public boolean mouseMoved (InputEvent event, float x, float y) { return isModal; } public boolean scrolled (InputEvent event, float x, float y, int amount) { return isModal; } public boolean keyDown (InputEvent event, int keycode) { return isModal; } public boolean keyUp (InputEvent event, int keycode) { return isModal; } public boolean keyTyped (InputEvent event, char character) { return isModal; } }); } public void setStyle (WindowStyle style) { if (style == null) throw new IllegalArgumentException("style cannot be null."); this.style = style; setBackground(style.background); titleCache = new BitmapFontCache(style.titleFont); titleCache.setColor(style.titleFontColor); if (title != null) setTitle(title); invalidateHierarchy(); } /** Returns the window's style. Modifying the returned style may not have an effect until {@link #setStyle(WindowStyle)} is * called. */ public WindowStyle getStyle () { return style; } protected void drawBackground (SpriteBatch batch, float parentAlpha) { if (style.stageBackground != null) { Color color = getColor(); batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); Stage stage = getStage(); Vector2 position = stageToLocalCoordinates(Vector2.tmp.set(0, 0)); Vector2 size = stageToLocalCoordinates(Vector2.tmp2.set(stage.getWidth(), stage.getHeight())); style.stageBackground.draw(batch, getX() + position.x, getY() + position.y, getX() + size.x, getY() + size.y); } super.drawBackground(batch, parentAlpha); // Draw the title without the batch transformed or clipping applied. float x = getX(), y = getY() + getHeight(); TextBounds bounds = titleCache.getBounds(); if ((titleAlignment & Align.left) != 0) x += getPadLeft(); else if ((titleAlignment & Align.right) != 0) x += getWidth() - bounds.width - getPadRight(); else x += (getWidth() - bounds.width) / 2; if ((titleAlignment & Align.top) == 0) { if ((titleAlignment & Align.bottom) != 0) y -= getPadTop() - bounds.height; else y -= (getPadTop() - bounds.height) / 2; } titleCache.setColor(Color.tmp.set(getColor()).mul(style.titleFontColor)); titleCache.setPosition((int)x, (int)y); titleCache.draw(batch, parentAlpha); } public Actor hit (float x, float y, boolean touchable) { Actor hit = super.hit(x, y, touchable); if (hit == null && isModal && (!touchable || getTouchable() == Touchable.enabled)) return this; return hit; } public void setTitle (String title) { this.title = title; titleCache.setMultiLineText(title, 0, 0); } public String getTitle () { return title; } /** @param titleAlignment {@link Align} */ public void setTitleAlignment (int titleAlignment) { this.titleAlignment = titleAlignment; } public void setMovable (boolean isMovable) { this.isMovable = isMovable; } public void setModal (boolean isModal) { this.isModal = isModal; } public boolean isDragging () { return dragging; } public float getPrefWidth () { return Math.max(super.getPrefWidth(), titleCache.getBounds().width + getPadLeft() + getPadRight()); } /** The style for a window, see {@link Window}. * @author Nathan Sweet */ static public class WindowStyle { /** Optional. */ public Drawable background; public BitmapFont titleFont; /** Optional. */ public Color titleFontColor = new Color(1, 1, 1, 1); /** Optional. */ public Drawable stageBackground; public WindowStyle () { } public WindowStyle (BitmapFont titleFont, Color titleFontColor, Drawable background) { this.background = background; this.titleFont = titleFont; this.titleFontColor.set(titleFontColor); } public WindowStyle (WindowStyle style) { this.background = style.background; this.titleFont = style.titleFont; this.titleFontColor = new Color(style.titleFontColor); } } }
Window, added keepWithinParent.
gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Window.java
Window, added keepWithinParent.
<ide><path>dx/src/com/badlogic/gdx/scenes/scene2d/ui/Window.java <ide> <ide> package com.badlogic.gdx.scenes.scene2d.ui; <ide> <del>import com.badlogic.gdx.Gdx; <ide> import com.badlogic.gdx.graphics.Color; <ide> import com.badlogic.gdx.graphics.g2d.BitmapFont; <ide> import com.badlogic.gdx.graphics.g2d.BitmapFont.TextBounds; <ide> import com.badlogic.gdx.graphics.g2d.BitmapFontCache; <ide> import com.badlogic.gdx.graphics.g2d.SpriteBatch; <ide> import com.badlogic.gdx.math.Vector2; <del>import com.badlogic.gdx.math.Vector3; <ide> import com.badlogic.gdx.scenes.scene2d.Actor; <add>import com.badlogic.gdx.scenes.scene2d.Group; <ide> import com.badlogic.gdx.scenes.scene2d.InputEvent; <ide> import com.badlogic.gdx.scenes.scene2d.InputListener; <ide> import com.badlogic.gdx.scenes.scene2d.Stage; <ide> final Vector2 dragOffset = new Vector2(); <ide> boolean dragging; <ide> private int titleAlignment = Align.center; <add> boolean keepWithinParent = true; <ide> <ide> public Window (String title, Skin skin) { <ide> this(title, skin.get(WindowStyle.class)); <ide> public void touchDragged (InputEvent event, float x, float y, int pointer) { <ide> if (!dragging) return; <ide> translate(x - dragOffset.x, y - dragOffset.y); <add> if (keepWithinParent) { <add> float parentWidth, parentHeight; <add> Group parent = getParent(); <add> Stage stage = getStage(); <add> if (parent == stage.getRoot()) { <add> parentWidth = stage.getWidth(); <add> parentHeight = stage.getHeight(); <add> } else { <add> parentWidth = parent.getWidth(); <add> parentHeight = parent.getHeight(); <add> } <add> if (getX() < 0) setX(0); <add> if (getRight() > parentWidth) setX(parentWidth - getWidth()); <add> if (getY() < 0) setY(0); <add> if (getTop() > parentHeight) setY(parentHeight - getHeight()); <add> } <ide> } <ide> <ide> public boolean mouseMoved (InputEvent event, float x, float y) { <ide> this.isModal = isModal; <ide> } <ide> <add> public void setKeepWithinParent (boolean keepWithinParent) { <add> this.keepWithinParent = keepWithinParent; <add> } <add> <ide> public boolean isDragging () { <ide> return dragging; <ide> }
JavaScript
mit
13e4a7256f2a327a10bbdd781dbef1cbd10e9f75
0
Sawtaytoes/Flic-Controller,Sawtaytoes/Flic-Controller
// Global Dir Hack global.baseDir = `${__dirname}/` // Load Config settings const dir = require(`${global.baseDir}/global-dirs`) const flicClient = require(`${dir.services}setup-flic-client`) const setupServer = require(`${dir.server}setup-server`) const startServer = require(`${dir.server}start-server`) // Load Middleware const discoverDevices = require(`${dir.middleware}discover-devices`) flicClient.init() const flicMiddleware = { get: action => (req, res) => res.send( action(flicClient)(req.params.name) ) } const serverSettings = setupServer() serverSettings.get( '/', (req, res) => res.end('You no be hearz.') ) serverSettings.get( '/discover-devices', flicMiddleware.get(discoverDevices) ) startServer(serverSettings)
index.js
// Global Dir Hack global.baseDir = `${__dirname}/` // Load Config settings const dir = require(`${global.baseDir}/global-dirs`) const lifxConfig = require(`${dir.services}setup-lifx-config`) const lifxClient = require(`${dir.services}setup-lifx-client`) const setupServer = require(`${dir.server}setup-server`) const startServer = require(`${dir.server}start-server`) // Load Middleware const discoverDevices = require(`${dir.middleware}discover-devices`) const toggleGroup = require(`${dir.middleware}toggle-group`) const toggleScene = require(`${dir.middleware}toggle-scene`) lifxClient.init() lifxConfig.init() const lifxMiddleware = { get: action => (req, res) => res.send( action(lifxClient, lifxConfig)(req.params.name) ) } const serverSettings = setupServer() serverSettings.get( '/', (req, res) => res.end('You no be hearz.') ) serverSettings.get( '/discover-devices', lifxMiddleware.get(discoverDevices) ) serverSettings.get( '/toggle-group/:name', lifxMiddleware.get(toggleGroup) ) serverSettings.get( '/toggle-scene/:name', lifxMiddleware.get(toggleScene) ) startServer(serverSettings)
Removed LIFX Controller middleware
index.js
Removed LIFX Controller middleware
<ide><path>ndex.js <ide> <ide> // Load Config settings <ide> const dir = require(`${global.baseDir}/global-dirs`) <del>const lifxConfig = require(`${dir.services}setup-lifx-config`) <del>const lifxClient = require(`${dir.services}setup-lifx-client`) <add>const flicClient = require(`${dir.services}setup-flic-client`) <ide> const setupServer = require(`${dir.server}setup-server`) <ide> const startServer = require(`${dir.server}start-server`) <ide> <ide> // Load Middleware <ide> const discoverDevices = require(`${dir.middleware}discover-devices`) <del>const toggleGroup = require(`${dir.middleware}toggle-group`) <del>const toggleScene = require(`${dir.middleware}toggle-scene`) <ide> <del>lifxClient.init() <del>lifxConfig.init() <add>flicClient.init() <ide> <del>const lifxMiddleware = { <add>const flicMiddleware = { <ide> get: action => (req, res) => res.send( <del> action(lifxClient, lifxConfig)(req.params.name) <add> action(flicClient)(req.params.name) <ide> ) <ide> } <ide> <ide> <ide> serverSettings.get( <ide> '/discover-devices', <del> lifxMiddleware.get(discoverDevices) <del>) <del> <del>serverSettings.get( <del> '/toggle-group/:name', <del> lifxMiddleware.get(toggleGroup) <del>) <del> <del>serverSettings.get( <del> '/toggle-scene/:name', <del> lifxMiddleware.get(toggleScene) <add> flicMiddleware.get(discoverDevices) <ide> ) <ide> <ide> startServer(serverSettings)