lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | apache-2.0 | 1e8c6fa50cd28c15f78e84cc1a50fbea2c1213e1 | 0 | hizel/lorsource,fat0troll/lorsource,bodqhrohro/lorsource,kloun/lorsource,maxcom/lorsource,hizel/lorsource,ymn/lorsource,kloun/lorsource,kloun/lorsource,maxcom/lorsource,hizel/lorsource,hizel/lorsource,bodqhrohro/lorsource,fat0troll/lorsource,bodqhrohro/lorsource,maxcom/lorsource,ymn/lorsource,ymn/lorsource,fat0troll/lorsource,maxcom/lorsource,ymn/lorsource,fat0troll/lorsource,kloun/lorsource | /*
* Copyright 1998-2010 Linux.org.ru
* 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 ru.org.linux.spring;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.servlet.ModelAndView;
import ru.org.linux.site.*;
import ru.org.linux.spring.dao.UserDao;
import ru.org.linux.util.StringUtil;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Properties;
@Controller
public class LostPasswordController {
@Autowired
private UserDao userDao;
@RequestMapping(value="/lostpwd.jsp", method= RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("lostpwd-form");
}
@RequestMapping(value="/reset-password", method= RequestMethod.GET)
public ModelAndView showCodeForm() {
return new ModelAndView("reset-password-form");
}
@RequestMapping(value="/lostpwd.jsp", method= RequestMethod.POST)
public ModelAndView sendPassword(@RequestParam("email") String email, HttpServletRequest request) throws Exception {
Template tmpl = Template.getTemplate(request);
if (Strings.isNullOrEmpty(email)) {
throw new BadInputException("email не задан");
}
User user = userDao.getByEmail(email);
if (user==null) {
throw new BadInputException("Ваш email не зарегистрирован");
}
user.checkBlocked();
user.checkAnonymous();
if (user.canModerate() && !tmpl.isModeratorSession()) {
throw new AccessViolationException("этот пароль могут сбросить только модераторы");
}
if (!userDao.canResetPassword(user)) {
throw new AccessViolationException("нельзя запрашивать пароль чаще одного раза в неделю");
}
Timestamp now = new Timestamp(System.currentTimeMillis());
try {
sendEmail(tmpl, user, email, now);
userDao.updateResetDate(user, now);
return new ModelAndView("action-done", "message", "Инструкция по сбросу пароля была отправлена на ваш email");
} catch (AddressException ex) {
throw new UserErrorException("Incorrect email address");
}
}
@RequestMapping(value="/reset-password", method= RequestMethod.POST)
public ModelAndView resetPassword(
@RequestParam("nick") String nick,
@RequestParam("code") String formCode,
HttpServletRequest request
) throws Exception {
Template tmpl = Template.getTemplate(request);
User user = userDao.getUser(nick);
user.checkBlocked();
user.checkAnonymous();
if (user.isAdministrator()) {
throw new AccessViolationException("this feature is not for you, ask me directly");
}
Timestamp resetDate = userDao.getResetDate(user);
String resetCode = getResetCode(tmpl.getSecret(), user.getNick(), user.getEmail(), resetDate);
if (!resetCode.equals(formCode)) {
throw new UserErrorException("Код не совпадает");
}
String password = userDao.resetPassword(user);
return new ModelAndView(
"action-done",
"message",
"Ваш новый пароль: " + StringUtil.escapeHtml(password)
);
}
private static String getResetCode(String base, String nick, String email, Timestamp tm) {
return StringUtil.md5hash(base + ':' + nick + ':' + email+ ':' +Long.toString(tm.getTime())+":reset");
}
private static void sendEmail(Template tmpl, User user, String email, Timestamp resetDate) throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", "localhost");
Session mailSession = Session.getDefaultInstance(props, null);
MimeMessage msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress("[email protected]"));
String resetCode = getResetCode(tmpl.getSecret(), user.getNick(), email, resetDate);
msg.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email));
msg.setSubject("Your password @linux.org.ru");
msg.setSentDate(new Date());
msg.setText(
"Здравствуйте!\n\n" +
"Для сброса вашего пароля перейдите по ссылке http://www.linux.org.ru/reset-password\n\n" +
"Ваш ник "+user.getNick()+", код подтверждения: " + resetCode + "\n\n" +
"Удачи!"
);
Transport.send(msg);
}
}
| src/main/java/ru/org/linux/spring/LostPasswordController.java | /*
* Copyright 1998-2010 Linux.org.ru
* 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 ru.org.linux.spring;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.servlet.ModelAndView;
import ru.org.linux.site.*;
import ru.org.linux.spring.dao.UserDao;
import ru.org.linux.util.StringUtil;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Properties;
@Controller
public class LostPasswordController {
@Autowired
private UserDao userDao;
@RequestMapping(value="/lostpwd.jsp", method= RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("lostpwd-form");
}
@RequestMapping(value="/reset-password", method= RequestMethod.GET)
public ModelAndView showCodeForm() {
return new ModelAndView("reset-password-form");
}
@RequestMapping(value="/lostpwd.jsp", method= RequestMethod.POST)
public ModelAndView sendPassword(@RequestParam("email") String email, HttpServletRequest request) throws Exception {
Template tmpl = Template.getTemplate(request);
if (Strings.isNullOrEmpty(email)) {
throw new BadInputException("email не задан");
}
User user = userDao.getByEmail(email);
if (user==null) {
throw new BadInputException("Ваш email не зарегистрирован");
}
user.checkBlocked();
user.checkAnonymous();
if (user.canModerate() && !tmpl.isModeratorSession()) {
throw new AccessViolationException("этот пароль могут сбросить только модераторы");
}
if (!userDao.canResetPassword(user)) {
throw new AccessViolationException("нельзя запрашивать пароль чаще одного раза в неделю");
}
Timestamp now = new Timestamp(System.currentTimeMillis());
try {
sendEmail(tmpl, user, email, now);
userDao.updateResetDate(user, now);
return new ModelAndView("action-done", "message", "Инструкция по сбросу пароля была отправлена на ваш email");
} catch (AddressException ex) {
throw new UserErrorException("Incorrect email address");
}
}
@RequestMapping(value="/reset-password", method= RequestMethod.POST)
public ModelAndView resetPassword(
@RequestParam("nick") String nick,
@RequestParam("code") String formCode,
HttpServletRequest request
) throws Exception {
Template tmpl = Template.getTemplate(request);
User user = userDao.getUser(nick);
user.checkBlocked();
user.checkAnonymous();
if (user.isAdministrator()) {
throw new AccessViolationException("this feature is not for you, ask me directly");
}
Timestamp resetDate = userDao.getResetDate(user);
String resetCode = getResetCode(tmpl.getSecret(), user.getNick(), user.getEmail(), resetDate);
if (!resetCode.equals(formCode)) {
throw new UserErrorException("Код не совпадает");
}
String password = userDao.resetPassword(user);
return new ModelAndView("action-done", "message", "Ваш новый пароль: " + password);
}
private static String getResetCode(String base, String nick, String email, Timestamp tm) {
return StringUtil.md5hash(base + ':' + nick + ':' + email+ ':' +Long.toString(tm.getTime())+":reset");
}
private static void sendEmail(Template tmpl, User user, String email, Timestamp resetDate) throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", "localhost");
Session mailSession = Session.getDefaultInstance(props, null);
MimeMessage msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress("[email protected]"));
String resetCode = getResetCode(tmpl.getSecret(), user.getNick(), email, resetDate);
msg.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email));
msg.setSubject("Your password @linux.org.ru");
msg.setSentDate(new Date());
msg.setText(
"Здравствуйте!\n\n" +
"Для сброса вашего пароля перейдите по ссылке http://www.linux.org.ru/reset-password\n\n" +
"Ваш ник "+user.getNick()+", код подтверждения: " + resetCode + "\n\n" +
"Удачи!"
);
Transport.send(msg);
}
}
| LostPasswordController: xml-encode нового пароля
| src/main/java/ru/org/linux/spring/LostPasswordController.java | LostPasswordController: xml-encode нового пароля | <ide><path>rc/main/java/ru/org/linux/spring/LostPasswordController.java
<ide>
<ide> String password = userDao.resetPassword(user);
<ide>
<del> return new ModelAndView("action-done", "message", "Ваш новый пароль: " + password);
<add> return new ModelAndView(
<add> "action-done",
<add> "message",
<add> "Ваш новый пароль: " + StringUtil.escapeHtml(password)
<add> );
<ide> }
<ide>
<ide> private static String getResetCode(String base, String nick, String email, Timestamp tm) { |
|
JavaScript | apache-2.0 | 1338329dcb4c7e69faab52f5cb42a97af04c732e | 0 | omniscale/gbi-editor,omniscale/gbi-editor | gbi.Layers = gbi.Layers || {};
/**
* Baseclass for layer
*
* @class
* @abstract
* @param [options]
* @param {Boolean} [options.isBaseLayer]
* @param {Boolean} [options.background=false]
* @param {Boolean} [options.displayInLayerSwitcher]
* @param {Boolean} [options.visibility]
*/
gbi.Layers.Layer = function(options) {
var defaults = {
isBaseLayer: false,
displayInLayerSwitcher: true,
visibility: true
}
this.options = $.extend({}, defaults, options);
this.isRaster = true;
this.isBackground = this.options.background || false;
};
gbi.Layers.Layer.prototype = {
CLASS_NAME: 'gbi.Layers.Layer',
/**
* Gets/sets layer visibility
*
* @memberof gbi.Layers.Layer
* @instance
* @param {Boolean} [visibility]
* @returns {Boolean} Returns visibility of layer of no param is given
*/
visible: function(visibility) {
if(arguments.length == 0) {
return this.olLayer.getVisibility();
}
this.olLayer.setVisibility(visibility);
},
/**
* Destroys
*
* @memberof gbi.Layers.Layer
* @instance
* @private
*/
destroy: function() {
this.olLayer.destroy();
},
/**
* Gets the type of layer
*
* @memberof gbi.Layers.Layer
* @instance
* @returns {String}
*/
type: function() {
//XXXkai: make constants
if(this.isBackground)
return 'background';
else if (this.isVector)
return 'vector';
else
return 'raster';
},
/**
* Registers an event
*
* @memberof gbi.Layers.Layer
* @instance
* @param {String} type event name
* @param {Object} obj "this" in func context
* @param {Function} func Called when event is triggered
*/
registerEvent: function(type, obj, func) {
if(this.olLayer) {
this.olLayer.events.register(type, obj, func);
}
},
/**
* Unregisters an event
*
* @memberof gbi.Layers.Layer
* @instance
* @param {String} type event name
* @param {Object} obj "this" in func context
* @param {Function} func Function given to {registerEvent}
*/
unregisterEvent: function(type, obj, func) {
if(this.olLayer) {
this.olLayer.events.unregister(type, obj, func);
}
},
/**
* Triggers an event
*
* @memberof gbi.Layers.Layer
* @instance
* @param {String} type event name
* @param {Object} obj Object commited to eventListener
*/
triggerEvent: function(type, obj) {
if(this.olLayer) {
this.olLayer.events.triggerEvent(type, obj);
}
}
};
/**
* Creates a OSM layer
*
* @constructor
* @extends gbi.Layers.Layer
* @param [options] All OpenLayers.Layer.OSM options are allowed. See {@link http://dev.openlayers.org/releases/OpenLayers-2.12/doc/apidocs/files/OpenLayers/Layer/OSM-js.html|OpenLayers.Layer.OSM}
* @param {String} options.name Name of the layer
*/
gbi.Layers.OSM = function(options) {
gbi.Layers.Layer.call(this, options);
this.olLayer = new OpenLayers.Layer.OSM(this.options.name, undefined, this.options);
};
gbi.Layers.OSM.prototype = new gbi.Layers.Layer();
$.extend(gbi.Layers.OSM.prototype, {
CLASS_NAME: 'gbi.Layers.OSM'
});
/**
* Creates a WMS layer
*
* @constructor
* @extends gbi.Layers.Layer
* @param [options] All OpenLayers.Layer.WMS options are allowed. See {@link http://dev.openlayers.org/releases/OpenLayers-2.12/doc/apidocs/files/OpenLayers/Layer/WMS-js.html|OpenLayers.Layer.WMS}
* @param {String} options.name Name of the layer
* @param {String} options.url
* @param {String[]} options.layers
* @param {String} [options.params.srs=EPSG:3857]
*/
gbi.Layers.WMS = function(options) {
var defaults = {
params: {
srs: 'EPSG:3857'
},
ratio: 1,
singleTile: true
};
gbi.Layers.Layer.call(this, $.extend({}, defaults, options));
var params = this.options.params
delete this.options.params
this.olLayer = new OpenLayers.Layer.WMS(this.options.name, this.options.url, params, this.options)
};
gbi.Layers.WMS.prototype = new gbi.Layers.Layer();
$.extend(gbi.Layers.WMS.prototype, {
CLASS_NAME: 'gbi.Layers.WMS'
});
/**
* Creates a WMTS layer
*
* @constructor
* @extends gbi.Layers.Layer
* @param [options] All OpenLayers.Layer.WMTS options are allowed. See {@link http://dev.openlayers.org/releases/OpenLayers-2.12/doc/apidocs/files/OpenLayers/Layer/WMTS-js.html|OpenLayers.Layer.WMTS}
* @param {String} options.name Name of the layer
* @param {String} options.url
* @param {String} options.layer
*/
gbi.Layers.WMTS = function(options) {
var defaults = {
getURL: this.tileURL,
matrixSet: 'GoogleMapsCompatible',
style: 'default'
};
gbi.Layers.Layer.call(this, $.extend({}, defaults, options));
this.olLayer = this.options.clone ? null : new OpenLayers.Layer.WMTS(this.options);
};
gbi.Layers.WMTS.prototype = new gbi.Layers.Layer();
$.extend(gbi.Layers.WMTS.prototype, {
CLASS_NAME: 'gbi.Layers.WMTS',
/**
* Generates the url for one tile
*
* @memberof gbi.Layers.WMTS
* @instance
* @private
* @param {OpenLayers.Bounds} bounds
* @returns {String} tileURL
*/
tileURL: function(bounds) {
var tileInfo = this.getTileInfo(bounds.getCenterLonLat());
return this.url
+ this.layer + '/'
+ this.matrixSet + '-'
+ this.matrix.identifier + '-'
+ tileInfo.col + '-'
+ tileInfo.row + '/tile';
},
/**
* Create a clone of this layer
*
* @memberof gbi.Layers.WMTS
* @instance
* @returns {gbi.Layers.WMTS}
*/
clone: function() {
var clone_options = $.extend({}, this.options, {clone: true});
var clone = new gbi.Layers.WMTS(clone_options);
//XXXkai: clone in layer...!
clone.olLayer = this.olLayer.clone();
return clone;
}
});
/**
* Creates a vector layer
*
* @constructor
* @extends gbi.Layers.Layer
* @param [options] All OpenLayers.Layer.Vector options are allowed. See {@link http://dev.openlayers.org/releases/OpenLayers-2.12/doc/apidocs/files/OpenLayers/Layer/Vector-js.html|OpenLayers.Layer.Vector}
* @param {String} options.name Layername
* @param {Boolean} [options.editable=true]
* @param {Boolean} [options.atrtibutePopop=false] Show a popup with feature attributes when select feature
*/
gbi.Layers.Vector = function(options) {
var defaults = {
editable: true,
attributePopup: false,
maxAttributeValues: 100
};
var default_symbolizers = {
"Point": {
pointRadius: 6,
fillColor: "#ee9900",
fillOpacity: 0.4,
strokeWidth: 1,
strokeOpacity: 1,
strokeColor: "#ee9900"
},
"Line": {
strokeWidth: 1,
strokeOpacity: 1,
strokeColor: "#ee9900"
},
"Polygon": {
strokeWidth: 1,
strokeOpacity: 1,
strokeColor: "#ee9900",
fillColor: "#ee9900",
fillOpacity: 0.4
}
};
this.selectStyle = new OpenLayers.Style();
this.selectStyle.addRules([new OpenLayers.Rule({symbolizer: {
fillColor: "blue",
fillOpacity: 0.4,
hoverFillColor: "white",
hoverFillOpacity: 0.8,
strokeColor: "blue",
strokeOpacity: 1,
strokeWidth: 2,
strokeLinecap: "round",
strokeDashstyle: "solid",
hoverStrokeColor: "red",
hoverStrokeOpacity: 1,
hoverStrokeWidth: 0.2,
pointRadius: 6,
hoverPointRadius: 1,
hoverPointUnit: "%",
pointerEvents: "visiblePainted",
cursor: "pointer",
fontColor: "#000000",
labelAlign: "cm",
labelOutlineColor: "white",
labelOutlineWidth: 3
}})]);
gbi.Layers.Layer.call(this, $.extend({}, defaults, options));
this.olLayer = new OpenLayers.Layer.Vector(this.options.name, this.options);
this.isVector = this.olLayer.isVector = true;
this.isRaster = false;
this.isBackground = false;
this.isActive = false;
this.isEditable = this.options.editable;
this.features = this.olLayer.features;
if(!this.options.styleMap) {
this.symbolizers = $.extend(true, {}, default_symbolizers, this.options.symbolizers);
this.setStyle(this.symbolizers);
} else {
this.symbolizers = this.options.styleMap.styles['default'].rules[0].symbolizer;
}
this.featureStylingRule = false;
this.featureStylingRuleIndex = [];
if(this.options.attributePopup) {
this.registerEvent('featureselected', this, this._showPopup);
this.registerEvent('featureunselected', this, this._removePopup);
}
//show popup when selectControl highlight a feature
//selectControl must trigger events on layer
if(this.options.hoverPopup) {
this.registerEvent('featurehighlighted', this, this._showPopup);
this.registerEvent('featureunhighlighted', this, this._removePopup);
}
}
gbi.Layers.Vector.prototype = new gbi.Layers.Layer();
$.extend(gbi.Layers.Vector.prototype, {
CLASS_NAME: 'gbi.Layers.Vector',
/**
* Sets the style of this layer
*
* @memberof gbi.Layers.Vector
* @instance
* @param {Object} symbolizers Object with styling informations. See {@link http://docs.openlayers.org/library/feature_styling.html|OpenLayers Styling}
*/
setStyle: function(symbolizers) {
$.extend(true, this.symbolizers, symbolizers);
var style = new OpenLayers.Style();
style.addRules([
new OpenLayers.Rule({symbolizer: this.symbolizers})
]);
if(this.olLayer.styleMap) {
this.olLayer.styleMap.styles['default'] = style;
this.olLayer.styleMap.styles['select'] = this.selectStyle;
} else {
this.olLayer.styleMap = new OpenLayers.StyleMap({
"default": style,
"select": this.selectStyle
});
}
this.olLayer.redraw();
},
/**
* Adds property filters
*
* At the moment, two types of filters are supported.
* 1. 'exact'
* Filter value must match exactly.
* 2. 'range'
* If min in filterOptions, all values >= min will be matched
* If max in filterOptions, all values < max will be matched
* If min and max in filterOptions, all min <= value < max will be matched
*
* @memberof gbi.Layers.Vector
* @instance
* @param {String} type
* @param {String} attribute
* @param {Object[]} filterOptions Contains the parameters for each filter
*/
addAttributeFilter: function(type, attribute, active, filterOptions) {
var self = this;
var rules = [];
this.featureStylingRule = $.isArray(filterOptions) && filterOptions.length > 0 ? {
type: type,
attribute: attribute,
active: active,
filterOptions: filterOptions
} : false;
for(var i = this.olLayer.styleMap.styles.default.rules.length - 1; i >= 0; i--) {
if(this.olLayer.styleMap.styles.default.rules[i].propertyFilter) {
self.olLayer.styleMap.styles.default.rules.splice(i, 1);
}
}
switch(type) {
case 'exact':
$.each(filterOptions, function(idx, filter) {
filter.olFilter = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.EQUAL_TO,
property: attribute,
value: filter.value
});
if(filter.symbolizer) {
rules.push(new OpenLayers.Rule({
filter: filter.olFilter,
symbolizer: filter.symbolizer,
propertyFilter: true
}));
}
});
break;
case 'range':
$.each(filterOptions, function(idx, filter) {
var minFilter = false;
var maxFilter = false;
var olFilter = false;
if(OpenLayers.String.isNumeric(filter.min)) {
minFilter = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO,
property: attribute,
value: OpenLayers.String.numericIf(filter.min)
});
}
if(OpenLayers.String.isNumeric(filter.max)) {
maxFilter = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.LESS_THAN,
property: attribute,
value: OpenLayers.String.numericIf(filter.max)
});
}
if(!minFilter && !maxFilter) {
return;
}
if(minFilter && maxFilter) {
olFilter = new OpenLayers.Filter.Logical({
type: OpenLayers.Filter.Logical.AND,
filters: [minFilter, maxFilter]
});
}
filter.olFilter = olFilter || minFilter || maxFilter;
if(filter.symbolizer) {
rules.push(new OpenLayers.Rule({
filter: filter.olFilter,
symbolizer: filter.symbolizer,
propertyFilter: true
}));
}
});
break;
};
$(gbi).trigger('gbi.layer.vector.ruleChanged', false);
if(rules.length == 0 || !active) {
this.olLayer.redraw();
return;
}
this.olLayer.styleMap.styles.default.rules = this.olLayer.styleMap.styles.default.rules.concat(rules);
this.olLayer.redraw();
},
/**
* Get a list of attributes of all features of this layer
*
* @memberof gbi.Layers.Vector
* @instance
* @returns {String[]} List of attributes
*/
featuresAttributes: function() {
var self = this;
var result = [];
$.each(this.olLayer.features, function(idx, feature) {
$.each(feature.attributes, function(key, value) {
if($.inArray(key, result) == -1) {
result.push(key);
}
});
});
return result;
},
/**
* Get a list of values of specified attribute
*
* @memberof gbi.Layers.Vector
* @instance
* @param {String} attribute
* @returns {Mixed[]} List of values of given attribute
*/
attributeValues: function(attribute) {
var self = this;
var result = [];
$.each(this.olLayer.features, function(idx, feature) {
if(feature.attributes[attribute] && $.inArray(feature.attributes[attribute], result) == -1) {
result.push(feature.attributes[attribute]);
}
if(result.length > self.options.maxAttributeValues) {
return false;
}
});
return result;
},
/**
* Get all filtered features sorted by matching filter
*
* @memberof gbi.Layers.Vector
* @instance
* @returns {Object} The returned Object has a attribute, type and result attribute.
* The result attribute is also an object containing color, min,
* max and value propties and a list of features
*/
filteredFeatures: function() {
var self = this;
var result = {};
var attribute = false;
var type = false;
if(this.featureStylingRule && this.featureStylingRule.attribute && this.featureStylingRule.filterOptions) {
$.each(this.featureStylingRule.filterOptions, function(idx, filterOption) {
if(!(filterOption.value || filterOption.min || filterOption.max) || !filterOption.olFilter) {
return true;
}
result[idx] = {
'color': filterOption.symbolizer.fillColor,
'value': filterOption.value,
'min': filterOption.min,
'max': filterOption.max,
'features': []
};
});
$.each(this.olLayer.features, function(id, feature) {
for(var i = self.featureStylingRule.filterOptions.length - 1; i >= 0; i--) {
var filterOption = self.featureStylingRule.filterOptions[i];
if(!filterOption.olFilter) {
break;
}
if(filterOption.olFilter.evaluate(feature)) {
result[i].features.push(feature);
break;
}
}
});
return {
attribute: this.featureStylingRule.attribute,
type: this.featureStylingRule.type,
result: result
};
}
},
/**
* Adds features to this layer
*
* @memberof gbi.Layers.Vector
* @instance
* @param {OpenLayers.Feature.Vector[]} features
*/
addFeatures: function(features, options) {
this.olLayer.addFeatures(features);
},
/**
* Adds a feature to this layer
*
* @memberof gbi.Layers.Vector
* @instance
* @param {OpenLayers.Feature.Vector} feature
*/
addFeature: function(feature, options) {
this.addFeatures([feature], options);
},
/**
* Change/Add an attribute of/to given feature
*
* @memberof gbi.Layers.Vector
* @instance
* @param {OpenLayers.Feature.Vector} feature
* @param {String} attribute
* @param {Object} value
*/
changeFeatureAttribute: function(feature, attribute, value) {
if(feature.attributes[attribute] != value) {
feature.attributes[attribute] = value;
$(gbi).trigger('gbi.layer.vector.featureAttributeChanged', feature);
}
},
/**
* Create a clone of this layer
*
* @memberof gbi.Layers.Vector
* @instance
* @returns {gbi.Layers.Vector}
*/
clone: function() {
var clone_options = $.extend({}, this.options, {clone: true});
var clone = new gbi.Layers.Vector(clone_options);
clone.olLayer = this.olLayer.clone();
return clone;
},
/**
* Unselects all selected features of this layer
*
* @memberof gbi.Layers.Vector
* @instance
*/
unSelectAllFeatures: function() {
var selectCtrl = new OpenLayers.Control.SelectFeature(this.olLayer);
selectCtrl.unselectAll();
selectCtrl.destroy();
if(this.popup) {
this._removePopup(this.popup);
}
},
/**
* Selects all features of this layer
*
* @memberof gbi.Layers.Vector
* @instance
*/
selectAllFeatures: function() {
var selectCtrl = new OpenLayers.Control.SelectFeature();
for(var i in this.features) {
if($.inArray(this.features[i], this.olLayer.selectedFeatures) == -1) {
selectCtrl.select(this.features[i]);
}
}
selectCtrl.destroy();
if(this.popup) {
this._removePopup(this.popup);
}
},
/**
* Center map on given feature
*
* @memberof gbi.Layers.Vector
* @instance
* @param {OpenLayers.Feature.Vector} feature
*/
showFeature: function(feature) {
var bounds = feature.geometry.getBounds();
this.olLayer.map.zoomToExtent(bounds);
},
/**
* Getter/Setter of listAttributes
*
* @memberof gbi.Layers.Vector
* @instance
* @param {String[]} List of attributes
* @returns {String[]} List of attributes
*/
listAttributes: function(listAttributes) {
if(listAttributes) {
this._listAttributes = listAttributes;
$(gbi).trigger('gbi.layer.vector.listAttributesChanged', false);
}
return this._listAttributes;
},
/**
* Getter/Setter of popupAttributes
*
* @memberof gbi.Layers.Vector
* @instance
* @param {String[]} List of attributes
* @returns {String[]} List of attributes
*/
popupAttributes: function(popupAttributes) {
if(popupAttributes) {
this._popupAttributes = popupAttributes;
$(gbi).trigger('gbi.layer.vector.popupAttributesChanged', false);
}
return this._popupAttributes;
},
/**
* Selects all features of this layer with have given property equal given value
*
* @memberof gbi.Layers.Vector
* @instance
* @param {String} property
* @param {String} value
*/
selectByPropertyValue: function(property, value) {
var self = this;
var selectCtrl = new OpenLayers.Control.SelectFeature();
$.each(this.olLayer.features, function(idx, feature) {
selectCtrl.unselect(feature);
if((property in feature.attributes && feature.attributes[property] == value)) {
selectCtrl.select(feature);
}
});
selectCtrl.destroy();
if(this.popup) {
this._removePopup(this.popup);
}
},
/**
* Zooms to data extend
*
* @memberof gbi.Layers.Vector
* @instance
*/
zoomToDataExtent: function() {
var dataExtent = this.olLayer.getDataExtent();
if(dataExtent) {
this.olLayer.map.zoomToExtent(dataExtent);
}
},
/**
* Displays a popup with feature attributes
*
* @memberof gbi.Layers.Vector
* @instance
* @private
* @param {OpenLayers.Feature.Vector} f
*/
_showPopup: function(f) {
if(this.popup && f.feature == this.popupFeature) {
this._removePopup();
}
this.popupFeature = f.feature;
var point = this.popupFeature.geometry.getCentroid();
var content = this._renderAttributes(this.popupFeature.attributes);
if($.isArray(this._popupAttributes) && this._popupAttributes.length == 0) {
content = OpenLayers.i18n('No attributes selected');
}
this.popup = new OpenLayers.Popup.Anchored(OpenLayers.i18n("Attributes"),
new OpenLayers.LonLat(point.x, point.y),
null,
content || OpenLayers.i18n('No attributes'),
null,
!this.options.hoverPopup);
this.popup.autoSize = true;
this.olLayer.map.addPopup(this.popup);
},
/**
* Hides a popup with feature attributes
*
* @memberof gbi.Layers.Vector
* @instance
* @private
*/
_removePopup: function() {
if(this.popup) {
this.olLayer.map.removePopup(this.popup);
this.popupFeature = false;
}
},
/**
* Renders attributes into a div
*
* @memberof gbi.Layers.Vector
* @instance
* @private
* @param {Object} attributes
* @returns {String} Ready to include html string
*/
_renderAttributes: function(attributes) {
var container = $('<div></div>');
if(this._popupAttributes) {
$.each(this._popupAttributes, function(idx, attribute) {
container.append($('<div><span>'+attribute+': </span><span>'+ (attributes[attribute] || OpenLayers.i18n('notDefined')) +'</span></div>'));
})
} else {
$.each(attributes, function(key, value) {
container.append($('<div><span>'+key+':</span><span>'+value+'</span></div>'));
});
}
return container.html();
}
});
/**
* Creates a GeoJSON layer
*
* @constructor
* @extends gbi.Layers.Vector
* @param options All OpenLayers.Layer.Vector options are allowed. See {@link http://dev.openlayers.org/releases/OpenLayers-2.12/doc/apidocs/files/OpenLayers/Layer/Vector-js.html|OpenLayers.Layer.Vector}
* @param {String} options.url Location of GeoJSON
*/
gbi.Layers.GeoJSON = function(options) {
var defaults = {};
var geoJSONExtension = {
protocol: new OpenLayers.Protocol.HTTP({
url: options.url,
format: new OpenLayers.Format.GeoJSON()
}),
strategies: [
new OpenLayers.Strategy.Fixed()
]
};
gbi.Layers.Vector.call(this, $.extend({}, defaults, options, geoJSONExtension));
};
gbi.Layers.GeoJSON.prototype = new gbi.Layers.Vector();
$.extend(gbi.Layers.GeoJSON.prototype, {
CLASS_NAME: 'gbi.Layers.GeoJSON'
});
/**
* Baseclass for saveable vector layers
*
* @class
* @abstract
* @param options All OpenLayers.Layer.Vector options are allowed. See {@link http://dev.openlayers.org/releases/OpenLayers-2.12/doc/apidocs/files/OpenLayers/Layer/Vector-js.html|OpenLayers.Layer.Vector}
* @param [options.callbacks]
* @param {Function[]} [options.callbacks.changes] Callbacks called when save status changes
* @param {Function[]} [options.callbacks.start] Callbacks called when transaction has started
* @param {Function[]} [options.callbacks.success] Callbacks called when transaction was successfull
* @param {Function[]} [options.callbacks.fail] Callbacks called when transaction has failed
*/
gbi.Layers.SaveableVector = function(options) {
var self = this;
this.saveStrategy = new OpenLayers.Strategy.Save();
this.saveStrategy.events.register('start', this, this._start);
this.saveStrategy.events.register('success', this, this._success);
this.saveStrategy.events.register('fail', this, this._fail);
this.callbacks = {};
if(options && options.callbacks) {
var self = this;
$.each(options.callbacks, function(key, callbacks) {
if(!$.isArray(callbacks)) {
callbacks = [callbacks];
}
self._addCallbacks(key, callbacks);
});
delete options.callbacks;
}
if(options) {
options.strategies.push(this.saveStrategy);
}
this.loaded = false;
this.unsavedChanges = false;
gbi.Layers.Vector.call(this, options);
this.olLayer.events.register('loadend', '', function(response) {
self.unsavedChanges = false;
if(response && response.object && response.object.features.length == 0) {
self.loaded = true;
}
self.olLayer.events.register('featureadded', self, self._trackStatus);
self.olLayer.events.register('featureremoved', self, self._trackStatus);
self.olLayer.events.register('afterfeaturemodified', self, self._trackStatus);
self.features = self.olLayer.features;
});
$(gbi).on('gbi.layer.vector.featureAttributeChanged', function(event, feature) {
feature.state = OpenLayers.State.UPDATE;
self.changesMade();
});
};
gbi.Layers.SaveableVector.prototype = new gbi.Layers.Vector();
$.extend(gbi.Layers.SaveableVector.prototype, {
CLASS_NAME: 'gbi.Layers.SaveableVector',
/**
* Saves all changes
*
* @memberof gbi.Layers.SaveableVector
* @instance
*/
save: function() {
this.unSelectAllFeatures();
this.saveStrategy.save();
},
/**
* Registers a callback
*
* @memberof gbi.Layers.SaveableVector
* @instance
* @param {String} key Event to bind
* @param {Function} callback Function to call
*/
registerCallback: function(key, callback) {
this._addCallbacks(key, [callback]);
},
/**
* Unregisters a callback
*
* @memberof gbi.Layers.SaveableVector
* @instance
* @param {String} key Event to unbind
* @param {Function} callback Function to remove
*/
unregisterCallback: function(key, callback) {
if(this.callbacks[key]) {
var idx = $.inArray(callback, this.callbacks[key])
if(idx > -1) {
this.callbacks[key].splice(idx, 1);
}
}
},
/**
* Adds callbacks
*
* @memberof gbi.Layers.SaveableVector
* @instance
* @private
* @param {String} key Event to bind
* @param {Function[]} Functions to call
*/
_addCallbacks: function(key, callbacks) {
if(this.callbacks[key]) {
this.callbacks[key] = this.callbacks[key].concat(callbacks);
} else {
this.callbacks[key] = callbacks;
}
},
/**
* Callback called when save status changes
*
* @memberof gbi.Layers.SaveableVector
* @instance
* @private
*/
_change: function() {
if(this.callbacks.changes) {
var self = this;
$.each(this.callbacks.changes, function(idx, callback) {
callback.call(self, self.unsavedChanges);
});
}
},
/**
* Callback called when transaction starts
*
* @memberof gbi.Layers.SaveableVector
* @instance
* @private
*/
_start: function(response) {
if(this.callbacks.start) {
var self = this;
$.each(this.callbacks.start, function(idx, callback) {
callback.call(self);
});
}
},
/**
* Callback called when transaction was successfull
*
* @memberof gbi.Layers.SaveableVector
* @instance
* @private
*/
_success: function(response) {
this.unsavedChanges = false;
this._change();
if(this.callbacks.success) {
var self = this;
$.each(this.callbacks.success, function(idx, callback) {
callback.call(self);
});
}
},
/**
* Callback called when transaction has failed
*
* @memberof gbi.Layers.SaveableVector
* @instance
* @private
*/
_fail: function(response) {
if(this.callbacks.fail) {
var self = this;
$.each(this.callbacks.fail, function(idx, callback) {
callback.call(self);
});
}
},
/**
* Callback called when feature was added, removed, edited
*
* @memberof gbi.Layers.SaveableVector
* @instance
* @private
*/
_trackStatus: function(e) {
if (e.feature && (e.feature.state == OpenLayers.State.DELETE || e.feature.state == OpenLayers.State.UPDATE || e.feature.state == OpenLayers.State.INSERT)) {
//XXXkai: set unsavedChanges to false when new feature inserted and then deleted?
this.unsavedChanges = true;
this._change();
}
},
/**
* Tells SaveableVector that something has changed
*
* @memberof gbi.Layers.SaveableVector
* @instance
*/
changesMade: function() {
this.unsavedChanges = true;
this._change();
}
});
/**
* Creates a Couch layer
*
* @constructor
* @extends gbi.Layers.SaveableVector
* @param opitons All OpenLayers.Layer.Vector options are allowed. See {@link http://dev.openlayers.org/releases/OpenLayers-2.12/doc/apidocs/files/OpenLayers/Layer/Vector-js.html|OpenLayers.Layer.Vector}
* @param {Boolean} [options.createDB=true] Creates a couchDB if not exists
* @param {Boolean} [options.loadStyle=true] Loads layer style from couchDB if exists
*/
gbi.Layers.Couch = function(options) {
var self = this;
var defaults = {
readExt: '_all_docs?include_docs=true',
bulkExt: '_bulk_docs?include_docs=true',
createDB: true,
loadStyle: true
};
options = $.extend({}, defaults, options);
this.haveCustomStyle = false;
this.styleRev = false;
this.format = new OpenLayers.Format.JSON();
var nameLowerCase = options.name.toLowerCase();
options.url += nameLowerCase.replace(/[^a-z0-9]*/g, '') + '/';
var couchExtension = {
protocol: new OpenLayers.Protocol.CouchDB({
url: options.url,
readExt: options.readExt,
bulkExt: options.bulkExt,
format: new OpenLayers.Format.CouchDB()
}),
strategies: [
new OpenLayers.Strategy.Fixed()
]
};
delete options.readExt;
delete options.bulkExt;
gbi.Layers.SaveableVector.call(this, $.extend({}, defaults, options, couchExtension));
if(this.options.createDB) {
this._createCouchDB();
}
this.registerEvent('featuresadded', this, function() {
self.loaded = true;
self.features = self.olLayer.features;
$(gbi).trigger('gbi.layer.couch.loadFeaturesEnd');
});
if(this.options.loadStyle) {
this._loadStyle();
}
};
gbi.Layers.Couch.prototype = new gbi.Layers.SaveableVector();
$.extend(gbi.Layers.Couch.prototype, {
CLASS_NAME: 'gbi.Layers.Couch',
/**
* Loads styling informations from couchDB
*
* @memberof gbi.Layers.Couch
* @instance
* @private
*/
_loadStyle: function() {
var self = this;
var format = new OpenLayers.Format.JSON();
var request = OpenLayers.Request.GET({
url: this.options.url + 'style',
async: false,
headers: {
'contentType': 'application/json'
},
success: function(response) {
var responseObject = self.format.read(response.responseText);
var rule = false;
if(responseObject.rule != undefined) {
var rule = responseObject.rule;
delete responseObject.rule;
}
if(responseObject._rev != undefined) {
self.styleRev = responseObject._rev;
delete responseObject._rev;
}
delete responseObject._id;
self.haveCustomStyle = Object.keys(responseObject).length > 0;
self.setStyle(responseObject);
if(rule) {
self.addAttributeFilter(rule.type, rule.attribute, rule.active, rule.filterOptions);
}
}
});
},
/**
* Prepares styling informations for insert into couchDB
*
* @memberof gbi.Layers.Couch
* @instance
* @private
*/
_saveStyle: function() {
var stylingData = $.extend(true, {}, this.symbolizers);
if(this.styleRev) {
stylingData['_rev'] = this.styleRev;
}
if(this.featureStylingRule) {
stylingData = this._addRule(stylingData);
}
this._saveStylingDate(stylingData);
},
/**
* Saves thematical styling to couchDB
*
* @memberof gbi.Layers.Couch
* @instance
* @private
*/
_saveRule: function() {
if(this.haveCustomStyle) {
this._saveStyle();
} else {
var stylingData = this._addRule({});
if(this.styleRev) {
stylingData['_rev'] = this.styleRev;
}
this._saveStylingDate(stylingData);
}
},
/**
* Add thematical styling to stylingData
*
* @memberof gbi.Layers.Couch
* @instance
* @private
* @param {Object} stylingData without thematical data
* @returns {Object} stylingData with thematical data
*/
_addRule : function(stylingData) {
if(!this.featureStylingRule) {
return stylingData;
}
stylingData['rule'] = $.extend(true, {}, this.featureStylingRule);
$.each(stylingData.rule.filterOptions, function(idx, filter) {
delete filter['olFilter'];
});
return stylingData;
},
/**
* Remove thematical styling before save stylingData to CouchDB
*
* @memberof gbi.Layers.Couch
* @instance
* @private
*/
_removeRule: function() {
delete this.featureStylingRule;
this._saveStyle()
},
/**
* Store style document in CouchDB
*
* @memberof gbi.Layers.Couch
* @instance
* @private
* @param {Object} stylingData
*/
_saveStylingDate: function(stylingData) {
var self = this;
var request = OpenLayers.Request.PUT({
url: this.options.url + 'style',
async: false,
headers: {
'Content-Type': 'application/json'
},
data: this.format.write(stylingData),
success: function(response) {
if(response.responseText) {
jsonResponse = self.format.read(response.responseText);
if(jsonResponse.rev) {
self.styleRev = jsonResponse.rev;
}
}
}
});
},
/**
* Checks if couchDB for this layer exists. If not, create couchDB
*
* @memberof gbi.Layers.Couch
* @instance
* @private
*/
_createCouchDB: function() {
var self = this;
//GET to see if couchDB already exist
OpenLayers.Request.GET({
url: this.options.url,
async: false,
failure: function(response) {
OpenLayers.Request.PUT({
url: self.options.url,
async: false,
success: function(response) {
self._createDefaultDocuments();
}
});
},
success: function(response) {
self.couchExists = true;
}
});
},
/**
* Creates default documents needed in couchDB for couch layer
*
* @memberof gbi.Layers.Couch
* @instance
* @private
*/
_createDefaultDocuments: function() {
var metadata = {
title: this.options.name,
type: 'GeoJSON'
}
OpenLayers.Request.PUT({
url: this.options.url + 'metadata',
async: false,
headers: {
'Content-Type': 'application/json'
},
data: this.format.write(metadata)
});
OpenLayers.Request.PUT({
url: this.options.url + 'style',
async: false,
headers: {
'Content-Type': 'application/json'
},
data: this.format.write({})
});
},
/**
* Removes couchDB for this layer and destroys the layer
*
* @memberof gbi.Layers.Couch
* @instance
*/
destroy: function() {
this._deleteCouchDB();
gbi.Layers.SaveableVector.prototype.destroy.apply(this)
},
/**
* Removes the couchDB for this layer
*
* @memberof gbi.Layers.Couch
* @instance
* @private
*/
_deleteCouchDB: function() {
OpenLayers.Request.DELETE({
url: this.options.url,
async: false,
headers: {
'Content-Type': 'application/json'
}
});
}
});
/**
* Creates a WFS layer
*
* @constructor
* @extends gbi.Layers.SaveableVector
* @param options All OpenLayers.Layer.Vector options are allowed. See {@link http://dev.openlayers.org/releases/OpenLayers-2.12/doc/apidocs/files/OpenLayers/Layer/Vector-js.html|OpenLayers.Layer.Vector}
* @param {String} options.featureNS Namespace
* @param {String} options.featureType
* @param {String} options.geometryName Name of geometry column
* @param {Integer} [options.maxFeatures=500]
* @param {String} options.typename
* @param {String} [options.srsName=EPSG:3857] EPSG code of WFS source
*/
gbi.Layers.WFS = function(options) {
var defaults = {
featureNS: '',
featureType: '',
geometryName: '',
version: '1.1.0',
maxFeatures: 500,
typename: '',
srsName: 'EPSG:3857'
};
options = $.extend({}, defaults, options);
var wfsExtension = {
protocol: new OpenLayers.Protocol.WFS({
version: '1.1.0_ordered',
url: options.url,
srsName: options.srsName,
featureNS: options.featureNS,
featureType: options.featureType,
geometryName: options.geometryName,
schema: options.url + 'service=wfs&request=DescribeFeatureType&version='+options.version+'&typename='+options.typename+':'+options.featureType,
maxFeatures: options.maxFeatures,
typename: options.typename + ':' + options.featureType
}),
strategies: [
new OpenLayers.Strategy.BBOX()
]
};
gbi.Layers.SaveableVector.call(this, $.extend({}, defaults, options, wfsExtension));
};
gbi.Layers.WFS.prototype = new gbi.Layers.SaveableVector();
$.extend(gbi.Layers.WFS.prototype, {
CLASS_NAME: 'gbi.Layers.WFS',
/**
* Adds a filter to the WFS request
*
* @memberof gbi.Layers.WFS
* @instance
* @param {String} property
* @param {String} value
*/
filter: function(property, value, type) {
var filterType;
switch(type) {
case 'like':
default:
filterType = OpenLayers.Filter.Comparison.LIKE;
break;
}
this.olLayer.filter = new OpenLayers.Filter.Comparison({
type: filterType,
property: property,
value: value
});
this.olLayer.refresh({force: true});
}
});
| src/gbi.layer.js | gbi.Layers = gbi.Layers || {};
/**
* Baseclass for layer
*
* @class
* @abstract
* @param [options]
* @param {Boolean} [options.isBaseLayer]
* @param {Boolean} [options.background=false]
* @param {Boolean} [options.displayInLayerSwitcher]
* @param {Boolean} [options.visibility]
*/
gbi.Layers.Layer = function(options) {
var defaults = {
isBaseLayer: false,
displayInLayerSwitcher: true,
visibility: true
}
this.options = $.extend({}, defaults, options);
this.isRaster = true;
this.isBackground = this.options.background || false;
};
gbi.Layers.Layer.prototype = {
CLASS_NAME: 'gbi.Layers.Layer',
/**
* Gets/sets layer visibility
*
* @memberof gbi.Layers.Layer
* @instance
* @param {Boolean} [visibility]
* @returns {Boolean} Returns visibility of layer of no param is given
*/
visible: function(visibility) {
if(arguments.length == 0) {
return this.olLayer.getVisibility();
}
this.olLayer.setVisibility(visibility);
},
/**
* Destroys
*
* @memberof gbi.Layers.Layer
* @instance
* @private
*/
destroy: function() {
this.olLayer.destroy();
},
/**
* Gets the type of layer
*
* @memberof gbi.Layers.Layer
* @instance
* @returns {String}
*/
type: function() {
//XXXkai: make constants
if(this.isBackground)
return 'background';
else if (this.isVector)
return 'vector';
else
return 'raster';
},
/**
* Registers an event
*
* @memberof gbi.Layers.Layer
* @instance
* @param {String} type event name
* @param {Object} obj "this" in func context
* @param {Function} func Called when event is triggered
*/
registerEvent: function(type, obj, func) {
if(this.olLayer) {
this.olLayer.events.register(type, obj, func);
}
},
/**
* Unregisters an event
*
* @memberof gbi.Layers.Layer
* @instance
* @param {String} type event name
* @param {Object} obj "this" in func context
* @param {Function} func Function given to {registerEvent}
*/
unregisterEvent: function(type, obj, func) {
if(this.olLayer) {
this.olLayer.events.unregister(type, obj, func);
}
},
/**
* Triggers an event
*
* @memberof gbi.Layers.Layer
* @instance
* @param {String} type event name
* @param {Object} obj Object commited to eventListener
*/
triggerEvent: function(type, obj) {
if(this.olLayer) {
this.olLayer.events.triggerEvent(type, obj);
}
}
};
/**
* Creates a OSM layer
*
* @constructor
* @extends gbi.Layers.Layer
* @param [options] All OpenLayers.Layer.OSM options are allowed. See {@link http://dev.openlayers.org/releases/OpenLayers-2.12/doc/apidocs/files/OpenLayers/Layer/OSM-js.html|OpenLayers.Layer.OSM}
* @param {String} options.name Name of the layer
*/
gbi.Layers.OSM = function(options) {
gbi.Layers.Layer.call(this, options);
this.olLayer = new OpenLayers.Layer.OSM(this.options.name, undefined, this.options);
};
gbi.Layers.OSM.prototype = new gbi.Layers.Layer();
$.extend(gbi.Layers.OSM.prototype, {
CLASS_NAME: 'gbi.Layers.OSM'
});
/**
* Creates a WMS layer
*
* @constructor
* @extends gbi.Layers.Layer
* @param [options] All OpenLayers.Layer.WMS options are allowed. See {@link http://dev.openlayers.org/releases/OpenLayers-2.12/doc/apidocs/files/OpenLayers/Layer/WMS-js.html|OpenLayers.Layer.WMS}
* @param {String} options.name Name of the layer
* @param {String} options.url
* @param {String[]} options.layers
* @param {String} [options.params.srs=EPSG:3857]
*/
gbi.Layers.WMS = function(options) {
var defaults = {
params: {
srs: 'EPSG:3857'
},
ratio: 1,
singleTile: true
};
gbi.Layers.Layer.call(this, $.extend({}, defaults, options));
var params = this.options.params
delete this.options.params
this.olLayer = new OpenLayers.Layer.WMS(this.options.name, this.options.url, params, this.options)
};
gbi.Layers.WMS.prototype = new gbi.Layers.Layer();
$.extend(gbi.Layers.WMS.prototype, {
CLASS_NAME: 'gbi.Layers.WMS'
});
/**
* Creates a WMTS layer
*
* @constructor
* @extends gbi.Layers.Layer
* @param [options] All OpenLayers.Layer.WMTS options are allowed. See {@link http://dev.openlayers.org/releases/OpenLayers-2.12/doc/apidocs/files/OpenLayers/Layer/WMTS-js.html|OpenLayers.Layer.WMTS}
* @param {String} options.name Name of the layer
* @param {String} options.url
* @param {String} options.layer
*/
gbi.Layers.WMTS = function(options) {
var defaults = {
getURL: this.tileURL,
matrixSet: 'GoogleMapsCompatible',
style: 'default'
};
gbi.Layers.Layer.call(this, $.extend({}, defaults, options));
this.olLayer = this.options.clone ? null : new OpenLayers.Layer.WMTS(this.options);
};
gbi.Layers.WMTS.prototype = new gbi.Layers.Layer();
$.extend(gbi.Layers.WMTS.prototype, {
CLASS_NAME: 'gbi.Layers.WMTS',
/**
* Generates the url for one tile
*
* @memberof gbi.Layers.WMTS
* @instance
* @private
* @param {OpenLayers.Bounds} bounds
* @returns {String} tileURL
*/
tileURL: function(bounds) {
var tileInfo = this.getTileInfo(bounds.getCenterLonLat());
return this.url
+ this.layer + '/'
+ this.matrixSet + '-'
+ this.matrix.identifier + '-'
+ tileInfo.col + '-'
+ tileInfo.row + '/tile';
},
/**
* Create a clone of this layer
*
* @memberof gbi.Layers.WMTS
* @instance
* @returns {gbi.Layers.WMTS}
*/
clone: function() {
var clone_options = $.extend({}, this.options, {clone: true});
var clone = new gbi.Layers.WMTS(clone_options);
//XXXkai: clone in layer...!
clone.olLayer = this.olLayer.clone();
return clone;
}
});
/**
* Creates a vector layer
*
* @constructor
* @extends gbi.Layers.Layer
* @param [options] All OpenLayers.Layer.Vector options are allowed. See {@link http://dev.openlayers.org/releases/OpenLayers-2.12/doc/apidocs/files/OpenLayers/Layer/Vector-js.html|OpenLayers.Layer.Vector}
* @param {String} options.name Layername
* @param {Boolean} [options.editable=true]
* @param {Boolean} [options.atrtibutePopop=false] Show a popup with feature attributes when select feature
*/
gbi.Layers.Vector = function(options) {
var defaults = {
editable: true,
attributePopup: false,
maxAttributeValues: 100
};
var default_symbolizers = {
"Point": {
pointRadius: 6,
fillColor: "#ee9900",
fillOpacity: 0.4,
strokeWidth: 1,
strokeOpacity: 1,
strokeColor: "#ee9900"
},
"Line": {
strokeWidth: 1,
strokeOpacity: 1,
strokeColor: "#ee9900"
},
"Polygon": {
strokeWidth: 1,
strokeOpacity: 1,
strokeColor: "#ee9900",
fillColor: "#ee9900",
fillOpacity: 0.4
}
};
this.selectStyle = new OpenLayers.Style();
this.selectStyle.addRules([new OpenLayers.Rule({symbolizer: {
fillColor: "blue",
fillOpacity: 0.4,
hoverFillColor: "white",
hoverFillOpacity: 0.8,
strokeColor: "blue",
strokeOpacity: 1,
strokeWidth: 2,
strokeLinecap: "round",
strokeDashstyle: "solid",
hoverStrokeColor: "red",
hoverStrokeOpacity: 1,
hoverStrokeWidth: 0.2,
pointRadius: 6,
hoverPointRadius: 1,
hoverPointUnit: "%",
pointerEvents: "visiblePainted",
cursor: "pointer",
fontColor: "#000000",
labelAlign: "cm",
labelOutlineColor: "white",
labelOutlineWidth: 3
}})]);
gbi.Layers.Layer.call(this, $.extend({}, defaults, options));
this.olLayer = new OpenLayers.Layer.Vector(this.options.name, this.options);
this.isVector = this.olLayer.isVector = true;
this.isRaster = false;
this.isBackground = false;
this.isActive = false;
this.isEditable = this.options.editable;
this.features = this.olLayer.features;
if(!this.options.styleMap) {
this.symbolizers = $.extend(true, {}, default_symbolizers, this.options.symbolizers);
this.setStyle(this.symbolizers);
} else {
this.symbolizers = this.options.styleMap.styles['default'].rules[0].symbolizer;
}
this.featureStylingRule = false;
this.featureStylingRuleIndex = [];
if(this.options.attributePopup) {
this.registerEvent('featureselected', this, this._showPopup);
this.registerEvent('featureunselected', this, this._removePopup);
}
//show popup when selectControl highlight a feature
//selectControl must trigger events on layer
if(this.options.hoverPopup) {
this.registerEvent('featurehighlighted', this, this._showPopup);
this.registerEvent('featureunhighlighted', this, this._removePopup);
}
}
gbi.Layers.Vector.prototype = new gbi.Layers.Layer();
$.extend(gbi.Layers.Vector.prototype, {
CLASS_NAME: 'gbi.Layers.Vector',
/**
* Sets the style of this layer
*
* @memberof gbi.Layers.Vector
* @instance
* @param {Object} symbolizers Object with styling informations. See {@link http://docs.openlayers.org/library/feature_styling.html|OpenLayers Styling}
*/
setStyle: function(symbolizers) {
$.extend(true, this.symbolizers, symbolizers);
var style = new OpenLayers.Style();
style.addRules([
new OpenLayers.Rule({symbolizer: this.symbolizers})
]);
if(this.olLayer.styleMap) {
this.olLayer.styleMap.styles['default'] = style;
this.olLayer.styleMap.styles['select'] = this.selectStyle;
} else {
this.olLayer.styleMap = new OpenLayers.StyleMap({
"default": style,
"select": this.selectStyle
});
}
this.olLayer.redraw();
},
/**
* Adds property filters
*
* At the moment, two types of filters are supported.
* 1. 'exact'
* Filter value must match exactly.
* 2. 'range'
* If min in filterOptions, all values >= min will be matched
* If max in filterOptions, all values < max will be matched
* If min and max in filterOptions, all min <= value < max will be matched
*
* @memberof gbi.Layers.Vector
* @instance
* @param {String} type
* @param {String} attribute
* @param {Object[]} filterOptions Contains the parameters for each filter
*/
addAttributeFilter: function(type, attribute, active, filterOptions) {
var self = this;
var rules = [];
this.featureStylingRule = $.isArray(filterOptions) && filterOptions.length > 0 ? {
type: type,
attribute: attribute,
active: active,
filterOptions: filterOptions
} : false;
for(var i = this.olLayer.styleMap.styles.default.rules.length - 1; i >= 0; i--) {
if(this.olLayer.styleMap.styles.default.rules[i].propertyFilter) {
self.olLayer.styleMap.styles.default.rules.splice(i, 1);
}
}
switch(type) {
case 'exact':
$.each(filterOptions, function(idx, filter) {
filter.olFilter = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.EQUAL_TO,
property: attribute,
value: filter.value
});
if(filter.symbolizer) {
rules.push(new OpenLayers.Rule({
filter: filter.olFilter,
symbolizer: filter.symbolizer,
propertyFilter: true
}));
}
});
break;
case 'range':
$.each(filterOptions, function(idx, filter) {
var minFilter = false;
var maxFilter = false;
var olFilter = false;
if(OpenLayers.String.isNumeric(filter.min)) {
minFilter = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO,
property: attribute,
value: OpenLayers.String.numericIf(filter.min)
});
}
if(OpenLayers.String.isNumeric(filter.max)) {
maxFilter = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.LESS_THAN,
property: attribute,
value: OpenLayers.String.numericIf(filter.max)
});
}
if(!minFilter && !maxFilter) {
return;
}
if(minFilter && maxFilter) {
olFilter = new OpenLayers.Filter.Logical({
type: OpenLayers.Filter.Logical.AND,
filters: [minFilter, maxFilter]
});
}
filter.olFilter = olFilter || minFilter || maxFilter;
if(filter.symbolizer) {
rules.push(new OpenLayers.Rule({
filter: filter.olFilter,
symbolizer: filter.symbolizer,
propertyFilter: true
}));
}
});
break;
};
$(gbi).trigger('gbi.layer.vector.ruleChanged', false);
if(rules.length == 0 || !active) {
this.olLayer.redraw();
return;
}
this.olLayer.styleMap.styles.default.rules = this.olLayer.styleMap.styles.default.rules.concat(rules);
this.olLayer.redraw();
},
/**
* Get a list of attributes of all features of this layer
*
* @memberof gbi.Layers.Vector
* @instance
* @returns {String[]} List of attributes
*/
featuresAttributes: function() {
var self = this;
var result = [];
$.each(this.olLayer.features, function(idx, feature) {
$.each(feature.attributes, function(key, value) {
if($.inArray(key, result) == -1) {
result.push(key);
}
});
});
return result;
},
/**
* Get a list of values of specified attribute
*
* @memberof gbi.Layers.Vector
* @instance
* @param {String} attribute
* @returns {Mixed[]} List of values of given attribute
*/
attributeValues: function(attribute) {
var self = this;
var result = [];
$.each(this.olLayer.features, function(idx, feature) {
if(feature.attributes[attribute] && $.inArray(feature.attributes[attribute], result) == -1) {
result.push(feature.attributes[attribute]);
}
if(result.length > self.options.maxAttributeValues) {
return false;
}
});
return result;
},
/**
* Get all filtered features sorted by matching filter
*
* @memberof gbi.Layers.Vector
* @instance
* @returns {Object} The returned Object has a attribute, type and result attribute.
* The result attribute is also an object containing color, min,
* max and value propties and a list of features
*/
filteredFeatures: function() {
var self = this;
var result = {};
var attribute = false;
var type = false;
if(this.featureStylingRule && this.featureStylingRule.attribute && this.featureStylingRule.filterOptions) {
$.each(this.featureStylingRule.filterOptions, function(idx, filterOption) {
if(!(filterOption.value || filterOption.min || filterOption.max) || !filterOption.olFilter) {
return true;
}
result[idx] = {
'color': filterOption.symbolizer.fillColor,
'value': filterOption.value,
'min': filterOption.min,
'max': filterOption.max,
'features': []
};
});
$.each(this.olLayer.features, function(id, feature) {
for(var i = self.featureStylingRule.filterOptions.length - 1; i >= 0; i--) {
var filterOption = self.featureStylingRule.filterOptions[i];
if(!filterOption.olFilter) {
break;
}
if(filterOption.olFilter.evaluate(feature)) {
result[i].features.push(feature);
break;
}
}
});
return {
attribute: this.featureStylingRule.attribute,
type: this.featureStylingRule.type,
result: result
};
}
},
/**
* Adds features to this layer
*
* @memberof gbi.Layers.Vector
* @instance
* @param {OpenLayers.Feature.Vector[]} features
*/
addFeatures: function(features, options) {
this.olLayer.addFeatures(features);
},
/**
* Adds a feature to this layer
*
* @memberof gbi.Layers.Vector
* @instance
* @param {OpenLayers.Feature.Vector} feature
*/
addFeature: function(feature, options) {
this.addFeatures([feature], options);
},
/**
* Change/Add an attribute of/to given feature
*
* @memberof gbi.Layers.Vector
* @instance
* @param {OpenLayers.Feature.Vector} feature
* @param {String} attribute
* @param {Object} value
*/
changeFeatureAttribute: function(feature, attribute, value) {
if(feature.attributes[attribute] != value) {
feature.attributes[attribute] = value;
$(gbi).trigger('gbi.layer.vector.featureAttributeChanged', feature);
}
},
/**
* Create a clone of this layer
*
* @memberof gbi.Layers.Vector
* @instance
* @returns {gbi.Layers.Vector}
*/
clone: function() {
var clone_options = $.extend({}, this.options, {clone: true});
var clone = new gbi.Layers.Vector(clone_options);
clone.olLayer = this.olLayer.clone();
return clone;
},
/**
* Unselects all selected features of this layer
*
* @memberof gbi.Layers.Vector
* @instance
*/
unSelectAllFeatures: function() {
var selectCtrl = new OpenLayers.Control.SelectFeature(this.olLayer);
selectCtrl.unselectAll();
selectCtrl.destroy();
if(this.popup) {
this._removePopup(this.popup);
}
},
/**
* Selects all features of this layer
*
* @memberof gbi.Layers.Vector
* @instance
*/
selectAllFeatures: function() {
var selectCtrl = new OpenLayers.Control.SelectFeature();
for(var i in this.features) {
if($.inArray(this.features[i], this.olLayer.selectedFeatures) == -1) {
selectCtrl.select(this.features[i]);
}
}
selectCtrl.destroy();
if(this.popup) {
this._removePopup(this.popup);
}
},
/**
* Center map on given feature
*
* @memberof gbi.Layers.Vector
* @instance
* @param {OpenLayers.Feature.Vector} feature
*/
showFeature: function(feature) {
var bounds = feature.geometry.getBounds();
this.olLayer.map.zoomToExtent(bounds);
},
/**
* Getter/Setter of listAttributes
*
* @memberof gbi.Layers.Vector
* @instance
* @param {String[]} List of attributes
* @returns {String[]} List of attributes
*/
listAttributes: function(listAttributes) {
if(listAttributes) {
this._listAttributes = listAttributes;
$(gbi).trigger('gbi.layer.vector.listAttributesChanged', false);
}
return this._listAttributes;
},
/**
* Getter/Setter of popupAttributes
*
* @memberof gbi.Layers.Vector
* @instance
* @param {String[]} List of attributes
* @returns {String[]} List of attributes
*/
popupAttributes: function(popupAttributes) {
if(popupAttributes) {
this._popupAttributes = popupAttributes;
$(gbi).trigger('gbi.layer.vector.popupAttributesChanged', false);
}
return this._popupAttributes;
},
/**
* Selects all features of this layer with have given property equal given value
*
* @memberof gbi.Layers.Vector
* @instance
* @param {String} property
* @param {String} value
*/
selectByPropertyValue: function(property, value) {
var self = this;
var selectCtrl = new OpenLayers.Control.SelectFeature();
$.each(this.olLayer.features, function(idx, feature) {
selectCtrl.unselect(feature);
if((property in feature.attributes && feature.attributes[property] == value)) {
selectCtrl.select(feature);
}
});
selectCtrl.destroy();
if(this.popup) {
this._removePopup(this.popup);
}
},
/**
* Zooms to data extend
*
* @memberof gbi.Layers.Vector
* @instance
*/
zoomToDataExtent: function() {
var dataExtent = this.olLayer.getDataExtent();
if(dataExtent) {
this.olLayer.map.zoomToExtent(dataExtent);
}
},
/**
* Displays a popup with feature attributes
*
* @memberof gbi.Layers.Vector
* @instance
* @private
* @param {OpenLayers.Feature.Vector} f
*/
_showPopup: function(f) {
if(this.popup && f.feature == this.popupFeature) {
this._removePopup();
}
this.popupFeature = f.feature;
var point = this.popupFeature.geometry.getCentroid();
var content = this._renderAttributes(this.popupFeature.attributes);
if($.isArray(this._popupAttributes) && this._popupAttributes.length == 0) {
content = OpenLayers.i18n('No attributes selected');
}
this.popup = new OpenLayers.Popup.Anchored(OpenLayers.i18n("Attributes"),
new OpenLayers.LonLat(point.x, point.y),
null,
content || OpenLayers.i18n('No attributes'),
null,
!this.options.hoverPopup);
this.popup.autoSize = true;
this.olLayer.map.addPopup(this.popup);
},
/**
* Hides a popup with feature attributes
*
* @memberof gbi.Layers.Vector
* @instance
* @private
*/
_removePopup: function() {
if(this.popup) {
this.olLayer.map.removePopup(this.popup);
}
},
/**
* Renders attributes into a div
*
* @memberof gbi.Layers.Vector
* @instance
* @private
* @param {Object} attributes
* @returns {String} Ready to include html string
*/
_renderAttributes: function(attributes) {
var container = $('<div></div>');
if(this._popupAttributes) {
$.each(this._popupAttributes, function(idx, attribute) {
container.append($('<div><span>'+attribute+': </span><span>'+ (attributes[attribute] || OpenLayers.i18n('notDefined')) +'</span></div>'));
})
} else {
$.each(attributes, function(key, value) {
container.append($('<div><span>'+key+':</span><span>'+value+'</span></div>'));
});
}
return container.html();
}
});
/**
* Creates a GeoJSON layer
*
* @constructor
* @extends gbi.Layers.Vector
* @param options All OpenLayers.Layer.Vector options are allowed. See {@link http://dev.openlayers.org/releases/OpenLayers-2.12/doc/apidocs/files/OpenLayers/Layer/Vector-js.html|OpenLayers.Layer.Vector}
* @param {String} options.url Location of GeoJSON
*/
gbi.Layers.GeoJSON = function(options) {
var defaults = {};
var geoJSONExtension = {
protocol: new OpenLayers.Protocol.HTTP({
url: options.url,
format: new OpenLayers.Format.GeoJSON()
}),
strategies: [
new OpenLayers.Strategy.Fixed()
]
};
gbi.Layers.Vector.call(this, $.extend({}, defaults, options, geoJSONExtension));
};
gbi.Layers.GeoJSON.prototype = new gbi.Layers.Vector();
$.extend(gbi.Layers.GeoJSON.prototype, {
CLASS_NAME: 'gbi.Layers.GeoJSON'
});
/**
* Baseclass for saveable vector layers
*
* @class
* @abstract
* @param options All OpenLayers.Layer.Vector options are allowed. See {@link http://dev.openlayers.org/releases/OpenLayers-2.12/doc/apidocs/files/OpenLayers/Layer/Vector-js.html|OpenLayers.Layer.Vector}
* @param [options.callbacks]
* @param {Function[]} [options.callbacks.changes] Callbacks called when save status changes
* @param {Function[]} [options.callbacks.start] Callbacks called when transaction has started
* @param {Function[]} [options.callbacks.success] Callbacks called when transaction was successfull
* @param {Function[]} [options.callbacks.fail] Callbacks called when transaction has failed
*/
gbi.Layers.SaveableVector = function(options) {
var self = this;
this.saveStrategy = new OpenLayers.Strategy.Save();
this.saveStrategy.events.register('start', this, this._start);
this.saveStrategy.events.register('success', this, this._success);
this.saveStrategy.events.register('fail', this, this._fail);
this.callbacks = {};
if(options && options.callbacks) {
var self = this;
$.each(options.callbacks, function(key, callbacks) {
if(!$.isArray(callbacks)) {
callbacks = [callbacks];
}
self._addCallbacks(key, callbacks);
});
delete options.callbacks;
}
if(options) {
options.strategies.push(this.saveStrategy);
}
this.loaded = false;
this.unsavedChanges = false;
gbi.Layers.Vector.call(this, options);
this.olLayer.events.register('loadend', '', function(response) {
self.unsavedChanges = false;
if(response && response.object && response.object.features.length == 0) {
self.loaded = true;
}
self.olLayer.events.register('featureadded', self, self._trackStatus);
self.olLayer.events.register('featureremoved', self, self._trackStatus);
self.olLayer.events.register('afterfeaturemodified', self, self._trackStatus);
self.features = self.olLayer.features;
});
$(gbi).on('gbi.layer.vector.featureAttributeChanged', function(event, feature) {
feature.state = OpenLayers.State.UPDATE;
self.changesMade();
});
};
gbi.Layers.SaveableVector.prototype = new gbi.Layers.Vector();
$.extend(gbi.Layers.SaveableVector.prototype, {
CLASS_NAME: 'gbi.Layers.SaveableVector',
/**
* Saves all changes
*
* @memberof gbi.Layers.SaveableVector
* @instance
*/
save: function() {
this.unSelectAllFeatures();
this.saveStrategy.save();
},
/**
* Registers a callback
*
* @memberof gbi.Layers.SaveableVector
* @instance
* @param {String} key Event to bind
* @param {Function} callback Function to call
*/
registerCallback: function(key, callback) {
this._addCallbacks(key, [callback]);
},
/**
* Unregisters a callback
*
* @memberof gbi.Layers.SaveableVector
* @instance
* @param {String} key Event to unbind
* @param {Function} callback Function to remove
*/
unregisterCallback: function(key, callback) {
if(this.callbacks[key]) {
var idx = $.inArray(callback, this.callbacks[key])
if(idx > -1) {
this.callbacks[key].splice(idx, 1);
}
}
},
/**
* Adds callbacks
*
* @memberof gbi.Layers.SaveableVector
* @instance
* @private
* @param {String} key Event to bind
* @param {Function[]} Functions to call
*/
_addCallbacks: function(key, callbacks) {
if(this.callbacks[key]) {
this.callbacks[key] = this.callbacks[key].concat(callbacks);
} else {
this.callbacks[key] = callbacks;
}
},
/**
* Callback called when save status changes
*
* @memberof gbi.Layers.SaveableVector
* @instance
* @private
*/
_change: function() {
if(this.callbacks.changes) {
var self = this;
$.each(this.callbacks.changes, function(idx, callback) {
callback.call(self, self.unsavedChanges);
});
}
},
/**
* Callback called when transaction starts
*
* @memberof gbi.Layers.SaveableVector
* @instance
* @private
*/
_start: function(response) {
if(this.callbacks.start) {
var self = this;
$.each(this.callbacks.start, function(idx, callback) {
callback.call(self);
});
}
},
/**
* Callback called when transaction was successfull
*
* @memberof gbi.Layers.SaveableVector
* @instance
* @private
*/
_success: function(response) {
this.unsavedChanges = false;
this._change();
if(this.callbacks.success) {
var self = this;
$.each(this.callbacks.success, function(idx, callback) {
callback.call(self);
});
}
},
/**
* Callback called when transaction has failed
*
* @memberof gbi.Layers.SaveableVector
* @instance
* @private
*/
_fail: function(response) {
if(this.callbacks.fail) {
var self = this;
$.each(this.callbacks.fail, function(idx, callback) {
callback.call(self);
});
}
},
/**
* Callback called when feature was added, removed, edited
*
* @memberof gbi.Layers.SaveableVector
* @instance
* @private
*/
_trackStatus: function(e) {
if (e.feature && (e.feature.state == OpenLayers.State.DELETE || e.feature.state == OpenLayers.State.UPDATE || e.feature.state == OpenLayers.State.INSERT)) {
//XXXkai: set unsavedChanges to false when new feature inserted and then deleted?
this.unsavedChanges = true;
this._change();
}
},
/**
* Tells SaveableVector that something has changed
*
* @memberof gbi.Layers.SaveableVector
* @instance
*/
changesMade: function() {
this.unsavedChanges = true;
this._change();
}
});
/**
* Creates a Couch layer
*
* @constructor
* @extends gbi.Layers.SaveableVector
* @param opitons All OpenLayers.Layer.Vector options are allowed. See {@link http://dev.openlayers.org/releases/OpenLayers-2.12/doc/apidocs/files/OpenLayers/Layer/Vector-js.html|OpenLayers.Layer.Vector}
* @param {Boolean} [options.createDB=true] Creates a couchDB if not exists
* @param {Boolean} [options.loadStyle=true] Loads layer style from couchDB if exists
*/
gbi.Layers.Couch = function(options) {
var self = this;
var defaults = {
readExt: '_all_docs?include_docs=true',
bulkExt: '_bulk_docs?include_docs=true',
createDB: true,
loadStyle: true
};
options = $.extend({}, defaults, options);
this.haveCustomStyle = false;
this.styleRev = false;
this.format = new OpenLayers.Format.JSON();
var nameLowerCase = options.name.toLowerCase();
options.url += nameLowerCase.replace(/[^a-z0-9]*/g, '') + '/';
var couchExtension = {
protocol: new OpenLayers.Protocol.CouchDB({
url: options.url,
readExt: options.readExt,
bulkExt: options.bulkExt,
format: new OpenLayers.Format.CouchDB()
}),
strategies: [
new OpenLayers.Strategy.Fixed()
]
};
delete options.readExt;
delete options.bulkExt;
gbi.Layers.SaveableVector.call(this, $.extend({}, defaults, options, couchExtension));
if(this.options.createDB) {
this._createCouchDB();
}
this.registerEvent('featuresadded', this, function() {
self.loaded = true;
self.features = self.olLayer.features;
$(gbi).trigger('gbi.layer.couch.loadFeaturesEnd');
});
if(this.options.loadStyle) {
this._loadStyle();
}
};
gbi.Layers.Couch.prototype = new gbi.Layers.SaveableVector();
$.extend(gbi.Layers.Couch.prototype, {
CLASS_NAME: 'gbi.Layers.Couch',
/**
* Loads styling informations from couchDB
*
* @memberof gbi.Layers.Couch
* @instance
* @private
*/
_loadStyle: function() {
var self = this;
var format = new OpenLayers.Format.JSON();
var request = OpenLayers.Request.GET({
url: this.options.url + 'style',
async: false,
headers: {
'contentType': 'application/json'
},
success: function(response) {
var responseObject = self.format.read(response.responseText);
var rule = false;
if(responseObject.rule != undefined) {
var rule = responseObject.rule;
delete responseObject.rule;
}
if(responseObject._rev != undefined) {
self.styleRev = responseObject._rev;
delete responseObject._rev;
}
delete responseObject._id;
self.haveCustomStyle = Object.keys(responseObject).length > 0;
self.setStyle(responseObject);
if(rule) {
self.addAttributeFilter(rule.type, rule.attribute, rule.active, rule.filterOptions);
}
}
});
},
/**
* Prepares styling informations for insert into couchDB
*
* @memberof gbi.Layers.Couch
* @instance
* @private
*/
_saveStyle: function() {
var stylingData = $.extend(true, {}, this.symbolizers);
if(this.styleRev) {
stylingData['_rev'] = this.styleRev;
}
if(this.featureStylingRule) {
stylingData = this._addRule(stylingData);
}
this._saveStylingDate(stylingData);
},
/**
* Saves thematical styling to couchDB
*
* @memberof gbi.Layers.Couch
* @instance
* @private
*/
_saveRule: function() {
if(this.haveCustomStyle) {
this._saveStyle();
} else {
var stylingData = this._addRule({});
if(this.styleRev) {
stylingData['_rev'] = this.styleRev;
}
this._saveStylingDate(stylingData);
}
},
/**
* Add thematical styling to stylingData
*
* @memberof gbi.Layers.Couch
* @instance
* @private
* @param {Object} stylingData without thematical data
* @returns {Object} stylingData with thematical data
*/
_addRule : function(stylingData) {
if(!this.featureStylingRule) {
return stylingData;
}
stylingData['rule'] = $.extend(true, {}, this.featureStylingRule);
$.each(stylingData.rule.filterOptions, function(idx, filter) {
delete filter['olFilter'];
});
return stylingData;
},
/**
* Remove thematical styling before save stylingData to CouchDB
*
* @memberof gbi.Layers.Couch
* @instance
* @private
*/
_removeRule: function() {
delete this.featureStylingRule;
this._saveStyle()
},
/**
* Store style document in CouchDB
*
* @memberof gbi.Layers.Couch
* @instance
* @private
* @param {Object} stylingData
*/
_saveStylingDate: function(stylingData) {
var self = this;
var request = OpenLayers.Request.PUT({
url: this.options.url + 'style',
async: false,
headers: {
'Content-Type': 'application/json'
},
data: this.format.write(stylingData),
success: function(response) {
if(response.responseText) {
jsonResponse = self.format.read(response.responseText);
if(jsonResponse.rev) {
self.styleRev = jsonResponse.rev;
}
}
}
});
},
/**
* Checks if couchDB for this layer exists. If not, create couchDB
*
* @memberof gbi.Layers.Couch
* @instance
* @private
*/
_createCouchDB: function() {
var self = this;
//GET to see if couchDB already exist
OpenLayers.Request.GET({
url: this.options.url,
async: false,
failure: function(response) {
OpenLayers.Request.PUT({
url: self.options.url,
async: false,
success: function(response) {
self._createDefaultDocuments();
}
});
},
success: function(response) {
self.couchExists = true;
}
});
},
/**
* Creates default documents needed in couchDB for couch layer
*
* @memberof gbi.Layers.Couch
* @instance
* @private
*/
_createDefaultDocuments: function() {
var metadata = {
title: this.options.name,
type: 'GeoJSON'
}
OpenLayers.Request.PUT({
url: this.options.url + 'metadata',
async: false,
headers: {
'Content-Type': 'application/json'
},
data: this.format.write(metadata)
});
OpenLayers.Request.PUT({
url: this.options.url + 'style',
async: false,
headers: {
'Content-Type': 'application/json'
},
data: this.format.write({})
});
},
/**
* Removes couchDB for this layer and destroys the layer
*
* @memberof gbi.Layers.Couch
* @instance
*/
destroy: function() {
this._deleteCouchDB();
gbi.Layers.SaveableVector.prototype.destroy.apply(this)
},
/**
* Removes the couchDB for this layer
*
* @memberof gbi.Layers.Couch
* @instance
* @private
*/
_deleteCouchDB: function() {
OpenLayers.Request.DELETE({
url: this.options.url,
async: false,
headers: {
'Content-Type': 'application/json'
}
});
}
});
/**
* Creates a WFS layer
*
* @constructor
* @extends gbi.Layers.SaveableVector
* @param options All OpenLayers.Layer.Vector options are allowed. See {@link http://dev.openlayers.org/releases/OpenLayers-2.12/doc/apidocs/files/OpenLayers/Layer/Vector-js.html|OpenLayers.Layer.Vector}
* @param {String} options.featureNS Namespace
* @param {String} options.featureType
* @param {String} options.geometryName Name of geometry column
* @param {Integer} [options.maxFeatures=500]
* @param {String} options.typename
* @param {String} [options.srsName=EPSG:3857] EPSG code of WFS source
*/
gbi.Layers.WFS = function(options) {
var defaults = {
featureNS: '',
featureType: '',
geometryName: '',
version: '1.1.0',
maxFeatures: 500,
typename: '',
srsName: 'EPSG:3857'
};
options = $.extend({}, defaults, options);
var wfsExtension = {
protocol: new OpenLayers.Protocol.WFS({
version: '1.1.0_ordered',
url: options.url,
srsName: options.srsName,
featureNS: options.featureNS,
featureType: options.featureType,
geometryName: options.geometryName,
schema: options.url + 'service=wfs&request=DescribeFeatureType&version='+options.version+'&typename='+options.typename+':'+options.featureType,
maxFeatures: options.maxFeatures,
typename: options.typename + ':' + options.featureType
}),
strategies: [
new OpenLayers.Strategy.BBOX()
]
};
gbi.Layers.SaveableVector.call(this, $.extend({}, defaults, options, wfsExtension));
};
gbi.Layers.WFS.prototype = new gbi.Layers.SaveableVector();
$.extend(gbi.Layers.WFS.prototype, {
CLASS_NAME: 'gbi.Layers.WFS',
/**
* Adds a filter to the WFS request
*
* @memberof gbi.Layers.WFS
* @instance
* @param {String} property
* @param {String} value
*/
filter: function(property, value, type) {
var filterType;
switch(type) {
case 'like':
default:
filterType = OpenLayers.Filter.Comparison.LIKE;
break;
}
this.olLayer.filter = new OpenLayers.Filter.Comparison({
type: filterType,
property: property,
value: value
});
this.olLayer.refresh({force: true});
}
});
| Set popupFeature to false after removing popup
| src/gbi.layer.js | Set popupFeature to false after removing popup | <ide><path>rc/gbi.layer.js
<ide> _removePopup: function() {
<ide> if(this.popup) {
<ide> this.olLayer.map.removePopup(this.popup);
<add> this.popupFeature = false;
<ide> }
<ide> },
<ide> /** |
|
Java | lgpl-2.1 | 7840244c2eb0ef9ddd7c8a41da88dd8ec0d8c342 | 0 | rhusar/wildfly,jstourac/wildfly,wildfly/wildfly,wildfly/wildfly,pferraro/wildfly,jstourac/wildfly,rhusar/wildfly,pferraro/wildfly,iweiss/wildfly,jstourac/wildfly,pferraro/wildfly,rhusar/wildfly,pferraro/wildfly,jstourac/wildfly,rhusar/wildfly,wildfly/wildfly,iweiss/wildfly,wildfly/wildfly,iweiss/wildfly,iweiss/wildfly | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.deployment.processors;
import java.util.Collection;
import org.jboss.as.ee.component.Attachments;
import org.jboss.as.ee.component.BindingConfiguration;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.ComponentConfigurator;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.ee.component.InjectionSource;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.component.EJBComponentDescription;
import org.jboss.as.ejb3.component.EJBViewDescription;
import org.jboss.as.ejb3.component.MethodIntf;
import org.jboss.as.ejb3.component.session.SessionBeanComponentDescription;
import org.jboss.as.ejb3.remote.RemoteViewInjectionSource;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.EjbDeploymentMarker;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.value.InjectedValue;
import org.jboss.msc.value.Values;
import org.wildfly.extension.requestcontroller.ControlPoint;
import org.wildfly.extension.requestcontroller.ControlPointService;
import org.wildfly.extension.requestcontroller.RequestControllerActivationMarker;
import org.wildfly.extension.requestcontroller.RunResult;
/**
* Sets up JNDI bindings for each of the views exposed by a {@link SessionBeanComponentDescription session bean}
*
* @author Jaikiran Pai
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class EjbJndiBindingsDeploymentUnitProcessor implements DeploymentUnitProcessor {
private final boolean appclient;
public EjbJndiBindingsDeploymentUnitProcessor(final boolean appclient) {
this.appclient = appclient;
}
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
// Only process EJB deployments
if (!EjbDeploymentMarker.isEjbDeployment(deploymentUnit)) {
return;
}
final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION);
final Collection<ComponentDescription> componentDescriptions = eeModuleDescription.getComponentDescriptions();
if (componentDescriptions != null) {
for (ComponentDescription componentDescription : componentDescriptions) {
// process only EJB session beans
if (componentDescription instanceof SessionBeanComponentDescription) {
this.setupJNDIBindings((EJBComponentDescription) componentDescription, deploymentUnit);
}
}
}
if (appclient) {
for (final ComponentDescription component : deploymentUnit.getAttachmentList(Attachments.ADDITIONAL_RESOLVABLE_COMPONENTS)) {
this.setupJNDIBindings((EJBComponentDescription) component, deploymentUnit);
}
}
}
/**
* Sets up jndi bindings for each of the views exposed by the passed <code>sessionBean</code>
*
* @param sessionBean The session bean
* @param deploymentUnit The deployment unit containing the session bean
*/
private void setupJNDIBindings(EJBComponentDescription sessionBean, DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException {
final Collection<ViewDescription> views = sessionBean.getViews();
if (views == null || views.isEmpty()) {
EjbLogger.DEPLOYMENT_LOGGER.noJNDIBindingsForSessionBean(sessionBean.getEJBName());
return;
}
// In case of EJB bindings, appname == .ear file name/application-name set in the application.xml (if it's an .ear deployment)
// NOTE: Do NOT use the app name from the EEModuleDescription.getApplicationName() because the Jakarta EE spec has a different and conflicting meaning for app name
// (where app name == module name in the absence of a .ear). Use EEModuleDescription.getEarApplicationName() instead
final String applicationName = sessionBean.getModuleDescription().getEarApplicationName();
final String distinctName = sessionBean.getModuleDescription().getDistinctName(); // default to empty string
final String globalJNDIBaseName = "java:global/" + (applicationName != null ? applicationName + "/" : "") + sessionBean.getModuleName() + "/" + sessionBean.getEJBName();
final String appJNDIBaseName = "java:app/" + sessionBean.getModuleName() + "/" + sessionBean.getEJBName();
final String moduleJNDIBaseName = "java:module/" + sessionBean.getEJBName();
final String remoteExportedJNDIBaseName = "java:jboss/exported/" + (applicationName != null ? applicationName + "/" : "") + sessionBean.getModuleName() + "/" + sessionBean.getEJBName();
final String ejbNamespaceBindingBaseName = "ejb:" + (applicationName != null ? applicationName : "") + "/" + sessionBean.getModuleName() + "/" + (distinctName != "" ? distinctName + "/" : "") + sessionBean.getEJBName();
// the base ServiceName which will be used to create the ServiceName(s) for each of the view bindings
final StringBuilder jndiBindingsLogMessage = new StringBuilder();
jndiBindingsLogMessage.append(System.lineSeparator()).append(System.lineSeparator());
// now create the bindings for each view under the java:global, java:app and java:module namespaces
EJBViewDescription ejbViewDescription = null;
for (ViewDescription viewDescription : views) {
boolean isEjbNamespaceBindingBaseName = false;
ejbViewDescription = (EJBViewDescription) viewDescription;
if (appclient && ejbViewDescription.getMethodIntf() != MethodIntf.REMOTE && ejbViewDescription.getMethodIntf() != MethodIntf.HOME) {
continue;
}
if (ejbViewDescription.getMethodIntf() != MethodIntf.REMOTE) {
isEjbNamespaceBindingBaseName = true;
}
if (!ejbViewDescription.hasJNDIBindings()) continue;
final String viewClassName = ejbViewDescription.getViewClassName();
// java:global bindings
final String globalJNDIName = globalJNDIBaseName + "!" + viewClassName;
registerBinding(sessionBean, viewDescription, globalJNDIName);
logBinding(jndiBindingsLogMessage, globalJNDIName);
// java:app bindings
final String appJNDIName = appJNDIBaseName + "!" + viewClassName;
registerBinding(sessionBean, viewDescription, appJNDIName);
logBinding(jndiBindingsLogMessage, appJNDIName);
// java:module bindings
final String moduleJNDIName = moduleJNDIBaseName + "!" + viewClassName;
registerBinding(sessionBean, viewDescription, moduleJNDIName);
logBinding(jndiBindingsLogMessage, moduleJNDIName);
// If it a remote or (remote) home view then bind the java:jboss/exported jndi names for the view
if(ejbViewDescription.getMethodIntf() == MethodIntf.REMOTE || ejbViewDescription.getMethodIntf() == MethodIntf.HOME) {
final String remoteJNDIName = remoteExportedJNDIBaseName + "!" + viewClassName;
if(RequestControllerActivationMarker.isRequestControllerEnabled(deploymentUnit)) {
registerControlPointBinding(sessionBean, viewDescription, remoteJNDIName, deploymentUnit);
} else {
registerBinding(sessionBean, viewDescription, remoteJNDIName);
}
logBinding(jndiBindingsLogMessage, remoteJNDIName);
}
// log EJB's ejb:/ namespace binding
final String ejbNamespaceBindingName = sessionBean.isStateful() ? ejbNamespaceBindingBaseName + "!" + viewClassName + "?stateful" : ejbNamespaceBindingBaseName + "!" + viewClassName;
if(!isEjbNamespaceBindingBaseName){
logBinding(jndiBindingsLogMessage, ejbNamespaceBindingName);
}
}
// EJB3.1 spec, section 4.4.1 Global JNDI Access states:
// In addition to the previous requirements, if the bean exposes only one of the
// applicable client interfaces(or alternatively has only a no-interface view), the container
// registers an entry for that view with the following syntax :
//
// java:global[/<app-name>]/<module-name>/<bean-name>
//
// Note that this also applies to java:app and java:module bindings
// as can be seen by the examples in 4.4.2.1
if (views.size() == 1) {
final EJBViewDescription viewDescription = (EJBViewDescription) views.iterator().next();
if (ejbViewDescription.hasJNDIBindings()) {
// java:global binding
registerBinding(sessionBean, viewDescription, globalJNDIBaseName);
logBinding(jndiBindingsLogMessage, globalJNDIBaseName);
// java:app binding
registerBinding(sessionBean, viewDescription, appJNDIBaseName);
logBinding(jndiBindingsLogMessage, appJNDIBaseName);
// java:module binding
registerBinding(sessionBean, viewDescription, moduleJNDIBaseName);
logBinding(jndiBindingsLogMessage, moduleJNDIBaseName);
}
}
// log the jndi bindings
EjbLogger.DEPLOYMENT_LOGGER.jndiBindings(sessionBean.getEJBName(), deploymentUnit, jndiBindingsLogMessage);
}
private void registerBinding(final EJBComponentDescription componentDescription, final ViewDescription viewDescription, final String jndiName) {
if (appclient) {
registerRemoteBinding(componentDescription, viewDescription, jndiName);
} else {
viewDescription.getBindingNames().add(jndiName);
}
}
private void registerRemoteBinding(final EJBComponentDescription componentDescription, final ViewDescription viewDescription, final String jndiName) {
final EEModuleDescription moduleDescription = componentDescription.getModuleDescription();
final InjectedValue<ClassLoader> viewClassLoader = new InjectedValue<ClassLoader>();
moduleDescription.getBindingConfigurations().add(new BindingConfiguration(jndiName, new RemoteViewInjectionSource(null, moduleDescription.getEarApplicationName(), moduleDescription.getModuleName(), moduleDescription.getDistinctName(), componentDescription.getComponentName(), viewDescription.getViewClassName(), componentDescription.isStateful(), viewClassLoader, appclient)));
componentDescription.getConfigurators().add(new ComponentConfigurator() {
public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
viewClassLoader.setValue(Values.immediateValue(configuration.getModuleClassLoader()));
}
});
}
private void registerControlPointBinding(final EJBComponentDescription componentDescription, final ViewDescription viewDescription, final String jndiName, final DeploymentUnit deploymentUnit) {
final EEModuleDescription moduleDescription = componentDescription.getModuleDescription();
final InjectedValue<ClassLoader> viewClassLoader = new InjectedValue<ClassLoader>();
final InjectedValue<ControlPoint> controlPointInjectedValue = new InjectedValue<>();
final RemoteViewInjectionSource delegate = new RemoteViewInjectionSource(null, moduleDescription.getEarApplicationName(), moduleDescription.getModuleName(), moduleDescription.getDistinctName(), componentDescription.getComponentName(), viewDescription.getViewClassName(), componentDescription.isStateful(), viewClassLoader, appclient);
final ServiceName depName = ControlPointService.serviceName(deploymentUnit.getParent() == null ? deploymentUnit.getName() : deploymentUnit.getParent().getName(), EJBComponentSuspendDeploymentUnitProcessor.ENTRY_POINT_NAME + deploymentUnit.getName() + "." + componentDescription.getComponentName());
componentDescription.getConfigurators().add((context, description, configuration) -> {
viewClassLoader.setValue(Values.immediateValue(configuration.getModuleClassLoader()));
configuration.getCreateDependencies().add((serviceBuilder, service) -> serviceBuilder.addDependency(depName, ControlPoint.class, controlPointInjectedValue));
});
//we need to wrap the injection source to allow graceful shutdown to function, although this is not ideal
//as it will also reject local lookups as well, although in general local code should never be looking up the
//exported bindings
//the other option would be to reject it at the remote naming service level, however then we loose the per-deployment granularity
final InjectionSource is = new InjectionSource() {
@Override
public void getResourceValue(ResolutionContext resolutionContext, ServiceBuilder<?> serviceBuilder, DeploymentPhaseContext phaseContext, Injector<ManagedReferenceFactory> injector) throws DeploymentUnitProcessingException {
final InjectedValue<ManagedReferenceFactory> delegateInjection = new InjectedValue<>();
delegate.getResourceValue(resolutionContext, serviceBuilder, phaseContext, delegateInjection);
injector.inject(new ManagedReferenceFactory() {
@Override
public ManagedReference getReference() {
ControlPoint cp = controlPointInjectedValue.getValue();
try {
RunResult res = cp.beginRequest();
if(res != RunResult.RUN) {
throw EjbLogger.ROOT_LOGGER.containerSuspended();
}
try {
return delegateInjection.getValue().getReference();
} finally {
cp.requestComplete();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
};
moduleDescription.getBindingConfigurations().add(new BindingConfiguration(jndiName, is));
}
private void logBinding(final StringBuilder jndiBindingsLogMessage, final String jndiName) {
jndiBindingsLogMessage.append("\t");
jndiBindingsLogMessage.append(jndiName);
jndiBindingsLogMessage.append(System.lineSeparator());
}
@Override
public void undeploy(DeploymentUnit context) {
}
}
| ejb3/src/main/java/org/jboss/as/ejb3/deployment/processors/EjbJndiBindingsDeploymentUnitProcessor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.deployment.processors;
import java.util.Collection;
import org.jboss.as.ee.component.Attachments;
import org.jboss.as.ee.component.BindingConfiguration;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.ComponentConfigurator;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.ee.component.InjectionSource;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.component.EJBComponentDescription;
import org.jboss.as.ejb3.component.EJBViewDescription;
import org.jboss.as.ejb3.component.MethodIntf;
import org.jboss.as.ejb3.component.session.SessionBeanComponentDescription;
import org.jboss.as.ejb3.remote.RemoteViewInjectionSource;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.EjbDeploymentMarker;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.value.InjectedValue;
import org.jboss.msc.value.Values;
import org.wildfly.extension.requestcontroller.ControlPoint;
import org.wildfly.extension.requestcontroller.ControlPointService;
import org.wildfly.extension.requestcontroller.RequestControllerActivationMarker;
import org.wildfly.extension.requestcontroller.RunResult;
/**
* Sets up JNDI bindings for each of the views exposed by a {@link SessionBeanComponentDescription session bean}
*
* @author Jaikiran Pai
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class EjbJndiBindingsDeploymentUnitProcessor implements DeploymentUnitProcessor {
private final boolean appclient;
public EjbJndiBindingsDeploymentUnitProcessor(final boolean appclient) {
this.appclient = appclient;
}
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
// Only process EJB deployments
if (!EjbDeploymentMarker.isEjbDeployment(deploymentUnit)) {
return;
}
final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION);
final Collection<ComponentDescription> componentDescriptions = eeModuleDescription.getComponentDescriptions();
if (componentDescriptions != null) {
for (ComponentDescription componentDescription : componentDescriptions) {
// process only EJB session beans
if (componentDescription instanceof SessionBeanComponentDescription) {
this.setupJNDIBindings((EJBComponentDescription) componentDescription, deploymentUnit);
}
}
}
if (appclient) {
for (final ComponentDescription component : deploymentUnit.getAttachmentList(Attachments.ADDITIONAL_RESOLVABLE_COMPONENTS)) {
this.setupJNDIBindings((EJBComponentDescription) component, deploymentUnit);
}
}
}
/**
* Sets up jndi bindings for each of the views exposed by the passed <code>sessionBean</code>
*
* @param sessionBean The session bean
* @param deploymentUnit The deployment unit containing the session bean
*/
private void setupJNDIBindings(EJBComponentDescription sessionBean, DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException {
final Collection<ViewDescription> views = sessionBean.getViews();
if (views == null || views.isEmpty()) {
EjbLogger.DEPLOYMENT_LOGGER.noJNDIBindingsForSessionBean(sessionBean.getEJBName());
return;
}
// In case of EJB bindings, appname == .ear file name/application-name set in the application.xml (if it's an .ear deployment)
// NOTE: Do NOT use the app name from the EEModuleDescription.getApplicationName() because the Jakarta EE spec has a different and conflicting meaning for app name
// (where app name == module name in the absence of a .ear). Use EEModuleDescription.getEarApplicationName() instead
final String applicationName = sessionBean.getModuleDescription().getEarApplicationName();
final String distinctName = sessionBean.getModuleDescription().getDistinctName(); // default to empty string
final String globalJNDIBaseName = "java:global/" + (applicationName != null ? applicationName + "/" : "") + sessionBean.getModuleName() + "/" + sessionBean.getEJBName();
final String appJNDIBaseName = "java:app/" + sessionBean.getModuleName() + "/" + sessionBean.getEJBName();
final String moduleJNDIBaseName = "java:module/" + sessionBean.getEJBName();
final String remoteExportedJNDIBaseName = "java:jboss/exported/" + (applicationName != null ? applicationName + "/" : "") + sessionBean.getModuleName() + "/" + sessionBean.getEJBName();
final String ejbNamespaceBindingBaseName = "ejb:" + (applicationName != null ? applicationName : "") + "/" + sessionBean.getModuleName() + "/" + (distinctName != "" ? distinctName + "/" : "") + sessionBean.getEJBName();
// the base ServiceName which will be used to create the ServiceName(s) for each of the view bindings
final StringBuilder jndiBindingsLogMessage = new StringBuilder();
jndiBindingsLogMessage.append(System.lineSeparator()).append(System.lineSeparator());
// now create the bindings for each view under the java:global, java:app and java:module namespaces
EJBViewDescription ejbViewDescription = null;
for (ViewDescription viewDescription : views) {
ejbViewDescription = (EJBViewDescription) viewDescription;
if (appclient && ejbViewDescription.getMethodIntf() != MethodIntf.REMOTE && ejbViewDescription.getMethodIntf() != MethodIntf.HOME) {
continue;
}
if (!ejbViewDescription.hasJNDIBindings()) continue;
final String viewClassName = ejbViewDescription.getViewClassName();
// java:global bindings
final String globalJNDIName = globalJNDIBaseName + "!" + viewClassName;
registerBinding(sessionBean, viewDescription, globalJNDIName);
logBinding(jndiBindingsLogMessage, globalJNDIName);
// java:app bindings
final String appJNDIName = appJNDIBaseName + "!" + viewClassName;
registerBinding(sessionBean, viewDescription, appJNDIName);
logBinding(jndiBindingsLogMessage, appJNDIName);
// java:module bindings
final String moduleJNDIName = moduleJNDIBaseName + "!" + viewClassName;
registerBinding(sessionBean, viewDescription, moduleJNDIName);
logBinding(jndiBindingsLogMessage, moduleJNDIName);
// If it a remote or (remote) home view then bind the java:jboss/exported jndi names for the view
if(ejbViewDescription.getMethodIntf() == MethodIntf.REMOTE || ejbViewDescription.getMethodIntf() == MethodIntf.HOME) {
final String remoteJNDIName = remoteExportedJNDIBaseName + "!" + viewClassName;
if(RequestControllerActivationMarker.isRequestControllerEnabled(deploymentUnit)) {
registerControlPointBinding(sessionBean, viewDescription, remoteJNDIName, deploymentUnit);
} else {
registerBinding(sessionBean, viewDescription, remoteJNDIName);
}
logBinding(jndiBindingsLogMessage, remoteJNDIName);
}
// log EJB's ejb:/ namespace binding
final String ejbNamespaceBindingName = sessionBean.isStateful() ? ejbNamespaceBindingBaseName + "!" + viewClassName + "?stateful" : ejbNamespaceBindingBaseName + "!" + viewClassName;
logBinding(jndiBindingsLogMessage, ejbNamespaceBindingName);
}
// EJB3.1 spec, section 4.4.1 Global JNDI Access states:
// In addition to the previous requirements, if the bean exposes only one of the
// applicable client interfaces(or alternatively has only a no-interface view), the container
// registers an entry for that view with the following syntax :
//
// java:global[/<app-name>]/<module-name>/<bean-name>
//
// Note that this also applies to java:app and java:module bindings
// as can be seen by the examples in 4.4.2.1
if (views.size() == 1) {
final EJBViewDescription viewDescription = (EJBViewDescription) views.iterator().next();
if (ejbViewDescription.hasJNDIBindings()) {
// java:global binding
registerBinding(sessionBean, viewDescription, globalJNDIBaseName);
logBinding(jndiBindingsLogMessage, globalJNDIBaseName);
// java:app binding
registerBinding(sessionBean, viewDescription, appJNDIBaseName);
logBinding(jndiBindingsLogMessage, appJNDIBaseName);
// java:module binding
registerBinding(sessionBean, viewDescription, moduleJNDIBaseName);
logBinding(jndiBindingsLogMessage, moduleJNDIBaseName);
}
}
// log the jndi bindings
EjbLogger.DEPLOYMENT_LOGGER.jndiBindings(sessionBean.getEJBName(), deploymentUnit, jndiBindingsLogMessage);
}
private void registerBinding(final EJBComponentDescription componentDescription, final ViewDescription viewDescription, final String jndiName) {
if (appclient) {
registerRemoteBinding(componentDescription, viewDescription, jndiName);
} else {
viewDescription.getBindingNames().add(jndiName);
}
}
private void registerRemoteBinding(final EJBComponentDescription componentDescription, final ViewDescription viewDescription, final String jndiName) {
final EEModuleDescription moduleDescription = componentDescription.getModuleDescription();
final InjectedValue<ClassLoader> viewClassLoader = new InjectedValue<ClassLoader>();
moduleDescription.getBindingConfigurations().add(new BindingConfiguration(jndiName, new RemoteViewInjectionSource(null, moduleDescription.getEarApplicationName(), moduleDescription.getModuleName(), moduleDescription.getDistinctName(), componentDescription.getComponentName(), viewDescription.getViewClassName(), componentDescription.isStateful(), viewClassLoader, appclient)));
componentDescription.getConfigurators().add(new ComponentConfigurator() {
public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
viewClassLoader.setValue(Values.immediateValue(configuration.getModuleClassLoader()));
}
});
}
private void registerControlPointBinding(final EJBComponentDescription componentDescription, final ViewDescription viewDescription, final String jndiName, final DeploymentUnit deploymentUnit) {
final EEModuleDescription moduleDescription = componentDescription.getModuleDescription();
final InjectedValue<ClassLoader> viewClassLoader = new InjectedValue<ClassLoader>();
final InjectedValue<ControlPoint> controlPointInjectedValue = new InjectedValue<>();
final RemoteViewInjectionSource delegate = new RemoteViewInjectionSource(null, moduleDescription.getEarApplicationName(), moduleDescription.getModuleName(), moduleDescription.getDistinctName(), componentDescription.getComponentName(), viewDescription.getViewClassName(), componentDescription.isStateful(), viewClassLoader, appclient);
final ServiceName depName = ControlPointService.serviceName(deploymentUnit.getParent() == null ? deploymentUnit.getName() : deploymentUnit.getParent().getName(), EJBComponentSuspendDeploymentUnitProcessor.ENTRY_POINT_NAME + deploymentUnit.getName() + "." + componentDescription.getComponentName());
componentDescription.getConfigurators().add((context, description, configuration) -> {
viewClassLoader.setValue(Values.immediateValue(configuration.getModuleClassLoader()));
configuration.getCreateDependencies().add((serviceBuilder, service) -> serviceBuilder.addDependency(depName, ControlPoint.class, controlPointInjectedValue));
});
//we need to wrap the injection source to allow graceful shutdown to function, although this is not ideal
//as it will also reject local lookups as well, although in general local code should never be looking up the
//exported bindings
//the other option would be to reject it at the remote naming service level, however then we loose the per-deployment granularity
final InjectionSource is = new InjectionSource() {
@Override
public void getResourceValue(ResolutionContext resolutionContext, ServiceBuilder<?> serviceBuilder, DeploymentPhaseContext phaseContext, Injector<ManagedReferenceFactory> injector) throws DeploymentUnitProcessingException {
final InjectedValue<ManagedReferenceFactory> delegateInjection = new InjectedValue<>();
delegate.getResourceValue(resolutionContext, serviceBuilder, phaseContext, delegateInjection);
injector.inject(new ManagedReferenceFactory() {
@Override
public ManagedReference getReference() {
ControlPoint cp = controlPointInjectedValue.getValue();
try {
RunResult res = cp.beginRequest();
if(res != RunResult.RUN) {
throw EjbLogger.ROOT_LOGGER.containerSuspended();
}
try {
return delegateInjection.getValue().getReference();
} finally {
cp.requestComplete();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
};
moduleDescription.getBindingConfigurations().add(new BindingConfiguration(jndiName, is));
}
private void logBinding(final StringBuilder jndiBindingsLogMessage, final String jndiName) {
jndiBindingsLogMessage.append("\t");
jndiBindingsLogMessage.append(jndiName);
jndiBindingsLogMessage.append(System.lineSeparator());
}
@Override
public void undeploy(DeploymentUnit context) {
}
}
| [WFLY-13088] Space added as per checkstyle
[WFLY-13088] EJB binding should not be listed if there is no Remote interface
| ejb3/src/main/java/org/jboss/as/ejb3/deployment/processors/EjbJndiBindingsDeploymentUnitProcessor.java | [WFLY-13088] Space added as per checkstyle | <ide><path>jb3/src/main/java/org/jboss/as/ejb3/deployment/processors/EjbJndiBindingsDeploymentUnitProcessor.java
<ide> // now create the bindings for each view under the java:global, java:app and java:module namespaces
<ide> EJBViewDescription ejbViewDescription = null;
<ide> for (ViewDescription viewDescription : views) {
<add> boolean isEjbNamespaceBindingBaseName = false;
<ide> ejbViewDescription = (EJBViewDescription) viewDescription;
<ide> if (appclient && ejbViewDescription.getMethodIntf() != MethodIntf.REMOTE && ejbViewDescription.getMethodIntf() != MethodIntf.HOME) {
<ide> continue;
<ide> }
<add> if (ejbViewDescription.getMethodIntf() != MethodIntf.REMOTE) {
<add> isEjbNamespaceBindingBaseName = true;
<add> }
<add>
<ide> if (!ejbViewDescription.hasJNDIBindings()) continue;
<ide>
<ide> final String viewClassName = ejbViewDescription.getViewClassName();
<ide> }
<ide>
<ide> // log EJB's ejb:/ namespace binding
<del> final String ejbNamespaceBindingName = sessionBean.isStateful() ? ejbNamespaceBindingBaseName + "!" + viewClassName + "?stateful" : ejbNamespaceBindingBaseName + "!" + viewClassName;
<del> logBinding(jndiBindingsLogMessage, ejbNamespaceBindingName);
<add> final String ejbNamespaceBindingName = sessionBean.isStateful() ? ejbNamespaceBindingBaseName + "!" + viewClassName + "?stateful" : ejbNamespaceBindingBaseName + "!" + viewClassName;
<add>
<add> if(!isEjbNamespaceBindingBaseName){
<add> logBinding(jndiBindingsLogMessage, ejbNamespaceBindingName);
<add> }
<add>
<ide>
<ide> }
<ide> |
|
Java | bsd-3-clause | 06589e0d9953c7b9259806da1759e1182e9da166 | 0 | CyberMobius/robolancers.training | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.subsystems;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.DoubleSolenoid.Value;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Victor;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.templates.RobotMap;
import edu.wpi.first.wpilibj.templates.commands.DriveWithJoystick;
/**
* @author Armond
*/
public class DriveTrain extends Subsystem{
private RobotDrive drive;
private double x, y, leftDrive, rightDrive;
public static SpeedController leftFrontMotor, rightFrontMotor, leftRearMotor, rightRearMotor;
public static DoubleSolenoid sonicShifterPair;
public DriveTrain(){
super("Drive Train");
leftFrontMotor = new Victor(RobotMap.LEFT_MOTOR_FRONT);
leftRearMotor = new Victor(RobotMap.LEFT_MOTOR_REAR);
rightFrontMotor = new Victor(RobotMap.RIGHT_MOTOR_FRONT);
rightRearMotor = new Victor(RobotMap.RIGHT_MOTOR_REAR);
sonicShifterPair = new DoubleSolenoid(1,2);
drive = new RobotDrive(leftFrontMotor, leftRearMotor, rightFrontMotor, rightRearMotor);
drive.setSafetyEnabled(false); //have this so compiler wont show "Robot Drive not outputting enough data"
sonicShifterPair.set(Value.kForward);
}
public void initDefaultCommand(){
setDefaultCommand(new DriveWithJoystick());
}
public void moveWithJoystick(double moveValue, double rotateValue, double speed){
if (RobotMap.MONO_JOYSTICK && RobotMap.ARCADE_DRIVE){
y = moveValue*speed;
x = rotateValue*speed;
drive.arcadeDrive(y,x);
}
else if(RobotMap.DUAL_JOYSTICK && RobotMap.TANK_DRIVE){
leftDrive = moveValue*speed;
rightDrive = rotateValue*speed;
drive.tankDrive(leftDrive,rightDrive);
}
else if(RobotMap.DUAL_JOYSTICK && RobotMap.RC_DRIVE){
y = moveValue*speed;
x = rotateValue*speed;
drive.arcadeDrive(y,x);
}
else if(RobotMap.WHEEL){
leftDrive = moveValue*speed;
rightDrive = rotateValue*speed;
drive.tankDrive(leftDrive,rightDrive);
}
}
}
| src/edu/wpi/first/wpilibj/templates/subsystems/DriveTrain.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.subsystems;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.DoubleSolenoid.Value;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Victor;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.templates.RobotMap;
import edu.wpi.first.wpilibj.templates.commands.DriveWithJoystick;
/**
* @author Armond
*/
public class DriveTrain extends Subsystem{
private RobotDrive drive;
private double x, y, leftDrive, rightDrive, speed;
public static SpeedController leftFrontMotor, rightFrontMotor, leftRearMotor, rightRearMotor;
public static DoubleSolenoid sonicShifterPair;
public DriveTrain(){
super("Drive Train");
leftFrontMotor = new Victor(RobotMap.LEFT_MOTOR_FRONT);
leftRearMotor = new Victor(RobotMap.LEFT_MOTOR_REAR);
rightFrontMotor = new Victor(RobotMap.RIGHT_MOTOR_FRONT);
rightRearMotor = new Victor(RobotMap.RIGHT_MOTOR_REAR);
sonicShifterPair = new DoubleSolenoid(1,2);
speed = 0.75;
drive = new RobotDrive(leftFrontMotor, leftRearMotor, rightFrontMotor, rightRearMotor);
drive.setSafetyEnabled(false); //have this so compiler wont show "Robot Drive not outputting enough data"
sonicShifterPair.set(Value.kForward);
}
public void initDefaultCommand(){
setDefaultCommand(new DriveWithJoystick());
}
public void moveWithJoystick(double moveValue, double rotateValue){
if (RobotMap.MONO_JOYSTICK){
y = moveValue*speed;
x = rotateValue*speed;
drive.arcadeDrive(y,x);
}
else if(RobotMap.DUAL_JOYSTICK){
leftDrive = moveValue*speed;
rightDrive = rotateValue*speed;
drive.tankDrive(leftDrive,rightDrive);
}
else if(RobotMap.WHEEL){
leftDrive = moveValue*speed;
rightDrive = rotateValue*speed;
drive.tankDrive(leftDrive,rightDrive);
}
}
}
| [no commit message]
| src/edu/wpi/first/wpilibj/templates/subsystems/DriveTrain.java | [no commit message] | <ide><path>rc/edu/wpi/first/wpilibj/templates/subsystems/DriveTrain.java
<ide>
<ide> public class DriveTrain extends Subsystem{
<ide> private RobotDrive drive;
<del> private double x, y, leftDrive, rightDrive, speed;
<add> private double x, y, leftDrive, rightDrive;
<ide>
<ide> public static SpeedController leftFrontMotor, rightFrontMotor, leftRearMotor, rightRearMotor;
<ide> public static DoubleSolenoid sonicShifterPair;
<ide>
<ide> sonicShifterPair = new DoubleSolenoid(1,2);
<ide>
<del> speed = 0.75;
<ide> drive = new RobotDrive(leftFrontMotor, leftRearMotor, rightFrontMotor, rightRearMotor);
<ide> drive.setSafetyEnabled(false); //have this so compiler wont show "Robot Drive not outputting enough data"
<ide>
<ide> setDefaultCommand(new DriveWithJoystick());
<ide> }
<ide>
<del> public void moveWithJoystick(double moveValue, double rotateValue){
<del> if (RobotMap.MONO_JOYSTICK){
<add> public void moveWithJoystick(double moveValue, double rotateValue, double speed){
<add> if (RobotMap.MONO_JOYSTICK && RobotMap.ARCADE_DRIVE){
<ide> y = moveValue*speed;
<ide> x = rotateValue*speed;
<ide> drive.arcadeDrive(y,x);
<ide> }
<del> else if(RobotMap.DUAL_JOYSTICK){
<add> else if(RobotMap.DUAL_JOYSTICK && RobotMap.TANK_DRIVE){
<ide> leftDrive = moveValue*speed;
<ide> rightDrive = rotateValue*speed;
<ide> drive.tankDrive(leftDrive,rightDrive);
<add> }
<add> else if(RobotMap.DUAL_JOYSTICK && RobotMap.RC_DRIVE){
<add> y = moveValue*speed;
<add> x = rotateValue*speed;
<add> drive.arcadeDrive(y,x);
<ide> }
<ide> else if(RobotMap.WHEEL){
<ide> leftDrive = moveValue*speed; |
|
Java | mit | d0b45545355b121c3553b6e6896b36bdb52c8ae3 | 0 | dalton/P2P-Project,dalton/P2P-Project | package edu.ufl.cise.cnt5106c;
import edu.ufl.cise.cnt5106c.log.LogHelper;
import edu.ufl.cise.cnt5106c.messages.Message;
import edu.ufl.cise.cnt5106c.messages.Request;
import java.util.Collection;
import java.util.TimerTask;
/**
*
* @author Giacomo Benincasa ([email protected])
*/
public class RequestTimer extends TimerTask {
private final Request _request;
private final FileManager _fileMgr;
private final Collection<Message> _queue;
private final int _remotePeerId;
RequestTimer (Request request, FileManager fileMgr, Collection<Message> queue, int remotePeerId) {
super();
_request = request;
_fileMgr = fileMgr;
_queue = queue;
_remotePeerId = remotePeerId;
}
@Override
public void run() {
if (_fileMgr.hasPart(_request.getPieceIndex())) {
LogHelper.getLogger().debug("Not rerequesting piece " + _request.getPieceIndex()
+ " to peer " + _remotePeerId);
}
else {
LogHelper.getLogger().debug("Rerequesting piece " + _request.getPieceIndex()
+ " to peer " + _remotePeerId);
_queue.add(_request);
}
}
}
| src/main/java/edu/ufl/cise/cnt5106c/RequestTimer.java | package edu.ufl.cise.cnt5106c;
import edu.ufl.cise.cnt5106c.log.LogHelper;
import edu.ufl.cise.cnt5106c.messages.Message;
import edu.ufl.cise.cnt5106c.messages.Request;
import java.util.Collection;
import java.util.TimerTask;
/**
*
* @author Giacomo Benincasa ([email protected])
*/
public class RequestTimer extends TimerTask {
private final Request _request;
private final FileManager _fileMgr;
private final Collection<Message> _queue;
private final int _remotePeerId;
RequestTimer (Request request, FileManager fileMgr, Collection<Message> queue, int remotePeerId) {
super();
_request = request;
_fileMgr = fileMgr;
_queue = queue;
_remotePeerId = remotePeerId;
}
@Override
public void run() {
if (!_fileMgr.hasPart(_request.getPieceIndex())) {
LogHelper.getLogger().debug("Rerequesting piece " + _request.getPieceIndex()
+ " to peer " + _remotePeerId);
_queue.add(_request);
}
}
}
| Added log. | src/main/java/edu/ufl/cise/cnt5106c/RequestTimer.java | Added log. | <ide><path>rc/main/java/edu/ufl/cise/cnt5106c/RequestTimer.java
<ide>
<ide> @Override
<ide> public void run() {
<del> if (!_fileMgr.hasPart(_request.getPieceIndex())) {
<add> if (_fileMgr.hasPart(_request.getPieceIndex())) {
<add> LogHelper.getLogger().debug("Not rerequesting piece " + _request.getPieceIndex()
<add> + " to peer " + _remotePeerId);
<add> }
<add> else {
<ide> LogHelper.getLogger().debug("Rerequesting piece " + _request.getPieceIndex()
<ide> + " to peer " + _remotePeerId);
<ide> _queue.add(_request); |
|
Java | apache-2.0 | cd8ddf44572c33254ff0a272e30a370d3b00d129 | 0 | ullgren/camel,davidkarlsen/camel,tdiesler/camel,ullgren/camel,cunningt/camel,apache/camel,tdiesler/camel,apache/camel,DariusX/camel,cunningt/camel,tadayosi/camel,pax95/camel,ullgren/camel,pmoerenhout/camel,pmoerenhout/camel,objectiser/camel,davidkarlsen/camel,cunningt/camel,Fabryprog/camel,pmoerenhout/camel,adessaigne/camel,alvinkwekel/camel,tadayosi/camel,apache/camel,DariusX/camel,nikhilvibhav/camel,pax95/camel,zregvart/camel,mcollovati/camel,apache/camel,zregvart/camel,tadayosi/camel,alvinkwekel/camel,pmoerenhout/camel,cunningt/camel,christophd/camel,zregvart/camel,nikhilvibhav/camel,apache/camel,CodeSmell/camel,mcollovati/camel,tdiesler/camel,Fabryprog/camel,gnodet/camel,pmoerenhout/camel,tdiesler/camel,tadayosi/camel,pax95/camel,adessaigne/camel,objectiser/camel,christophd/camel,christophd/camel,DariusX/camel,Fabryprog/camel,tdiesler/camel,pmoerenhout/camel,davidkarlsen/camel,christophd/camel,pax95/camel,apache/camel,nicolaferraro/camel,alvinkwekel/camel,mcollovati/camel,gnodet/camel,nicolaferraro/camel,Fabryprog/camel,gnodet/camel,nicolaferraro/camel,ullgren/camel,christophd/camel,gnodet/camel,adessaigne/camel,tdiesler/camel,pax95/camel,adessaigne/camel,christophd/camel,objectiser/camel,davidkarlsen/camel,pax95/camel,adessaigne/camel,nikhilvibhav/camel,CodeSmell/camel,mcollovati/camel,CodeSmell/camel,CodeSmell/camel,DariusX/camel,adessaigne/camel,objectiser/camel,nicolaferraro/camel,alvinkwekel/camel,gnodet/camel,cunningt/camel,tadayosi/camel,nikhilvibhav/camel,cunningt/camel,zregvart/camel,tadayosi/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.util;
import java.io.File;
import org.junit.Assert;
import org.junit.Test;
public class FileUtilTest extends Assert {
@Test
public void testNormalizePath() {
if (FileUtil.isWindows()) {
assertEquals("foo\\bar", FileUtil.normalizePath("foo/bar"));
assertEquals("foo\\bar\\baz", FileUtil.normalizePath("foo/bar\\baz"));
assertEquals("movefile\\sub\\sub2\\.done\\goodday.txt", FileUtil.normalizePath("movefile/sub/sub2\\.done\\goodday.txt"));
} else {
assertEquals("foo/bar", FileUtil.normalizePath("foo/bar"));
assertEquals("foo/bar/baz", FileUtil.normalizePath("foo/bar\\baz"));
assertEquals("movefile/sub/sub2/.done/goodday.txt", FileUtil.normalizePath("movefile/sub/sub2\\.done\\goodday.txt"));
}
}
@Test
public void testStripLeadingSeparator() {
assertEquals(null, FileUtil.stripLeadingSeparator(null));
assertEquals("foo", FileUtil.stripLeadingSeparator("foo"));
assertEquals("foo/bar", FileUtil.stripLeadingSeparator("foo/bar"));
assertEquals("foo/", FileUtil.stripLeadingSeparator("foo/"));
assertEquals("foo/bar", FileUtil.stripLeadingSeparator("/foo/bar"));
assertEquals("foo/bar", FileUtil.stripLeadingSeparator("//foo/bar"));
assertEquals("foo/bar", FileUtil.stripLeadingSeparator("///foo/bar"));
}
@Test
public void testHasLeadingSeparator() {
assertEquals(false, FileUtil.hasLeadingSeparator(null));
assertEquals(false, FileUtil.hasLeadingSeparator("foo"));
assertEquals(false, FileUtil.hasLeadingSeparator("foo/bar"));
assertEquals(false, FileUtil.hasLeadingSeparator("foo/"));
assertEquals(true, FileUtil.hasLeadingSeparator("/foo/bar"));
assertEquals(true, FileUtil.hasLeadingSeparator("//foo/bar"));
assertEquals(true, FileUtil.hasLeadingSeparator("///foo/bar"));
}
@Test
public void testStripFirstLeadingSeparator() {
assertEquals(null, FileUtil.stripFirstLeadingSeparator(null));
assertEquals("foo", FileUtil.stripFirstLeadingSeparator("foo"));
assertEquals("foo/bar", FileUtil.stripFirstLeadingSeparator("foo/bar"));
assertEquals("foo/", FileUtil.stripFirstLeadingSeparator("foo/"));
assertEquals("foo/bar", FileUtil.stripFirstLeadingSeparator("/foo/bar"));
assertEquals("/foo/bar", FileUtil.stripFirstLeadingSeparator("//foo/bar"));
assertEquals("//foo/bar", FileUtil.stripFirstLeadingSeparator("///foo/bar"));
}
@Test
public void testStripTrailingSeparator() {
assertEquals(null, FileUtil.stripTrailingSeparator(null));
assertEquals("foo", FileUtil.stripTrailingSeparator("foo"));
assertEquals("foo/bar", FileUtil.stripTrailingSeparator("foo/bar"));
assertEquals("foo", FileUtil.stripTrailingSeparator("foo/"));
assertEquals("foo/bar", FileUtil.stripTrailingSeparator("foo/bar/"));
assertEquals("/foo/bar", FileUtil.stripTrailingSeparator("/foo/bar"));
assertEquals("/foo/bar", FileUtil.stripTrailingSeparator("/foo/bar/"));
assertEquals("/foo/bar", FileUtil.stripTrailingSeparator("/foo/bar//"));
assertEquals("/foo/bar", FileUtil.stripTrailingSeparator("/foo/bar///"));
assertEquals("/foo", FileUtil.stripTrailingSeparator("/foo"));
assertEquals("/foo", FileUtil.stripTrailingSeparator("/foo/"));
assertEquals("/", FileUtil.stripTrailingSeparator("/"));
assertEquals("//", FileUtil.stripTrailingSeparator("//"));
}
@Test
public void testStripPath() {
assertEquals(null, FileUtil.stripPath(null));
assertEquals("", FileUtil.stripPath("/"));
assertEquals("foo.xml", FileUtil.stripPath("/foo.xml"));
assertEquals("foo", FileUtil.stripPath("foo"));
assertEquals("bar", FileUtil.stripPath("foo/bar"));
assertEquals("bar", FileUtil.stripPath("/foo/bar"));
}
@Test
public void testStripPathWithMixedSeparators() {
assertEquals(null, FileUtil.stripPath(null));
assertEquals("", FileUtil.stripPath("/"));
assertEquals("foo.xml", FileUtil.stripPath("/foo.xml"));
assertEquals("foo", FileUtil.stripPath("foo"));
assertEquals("baz", FileUtil.stripPath("foo/bar\\baz"));
assertEquals("bar", FileUtil.stripPath("\\foo\\bar"));
assertEquals("baz", FileUtil.stripPath("/foo\\bar/baz"));
}
@Test
public void testStripExt() {
assertEquals(null, FileUtil.stripExt(null));
assertEquals("foo", FileUtil.stripExt("foo"));
assertEquals("foo", FileUtil.stripExt("foo.xml"));
assertEquals("/foo/bar", FileUtil.stripExt("/foo/bar.xml"));
}
@Test
public void testOnlyExt() {
assertEquals(null, FileUtil.onlyExt(null));
assertEquals(null, FileUtil.onlyExt("foo"));
assertEquals("xml", FileUtil.onlyExt("foo.xml"));
assertEquals("xml", FileUtil.onlyExt("/foo/bar.xml"));
assertEquals("tar.gz", FileUtil.onlyExt("/foo/bigfile.tar.gz"));
assertEquals("tar.gz", FileUtil.onlyExt("/foo.bar/bigfile.tar.gz"));
}
@Test
public void testOnlyPath() {
assertEquals(null, FileUtil.onlyPath(null));
assertEquals(null, FileUtil.onlyPath("foo"));
assertEquals(null, FileUtil.onlyPath("foo.xml"));
assertEquals("foo", FileUtil.onlyPath("foo/bar.xml"));
assertEquals("/foo", FileUtil.onlyPath("/foo/bar.xml"));
assertEquals("/foo/bar", FileUtil.onlyPath("/foo/bar/baz.xml"));
assertEquals("/", FileUtil.onlyPath("/foo.xml"));
assertEquals("/bar", FileUtil.onlyPath("/bar/foo.xml"));
}
@Test
public void testOnlyPathWithMixedSeparators() {
assertEquals(null, FileUtil.onlyPath(null));
assertEquals(null, FileUtil.onlyPath("foo"));
assertEquals(null, FileUtil.onlyPath("foo.xml"));
assertEquals("foo", FileUtil.onlyPath("foo/bar.xml"));
assertEquals("/foo", FileUtil.onlyPath("/foo\\bar.xml"));
assertEquals("\\foo\\bar", FileUtil.onlyPath("\\foo\\bar/baz.xml"));
assertEquals("\\", FileUtil.onlyPath("\\foo.xml"));
assertEquals("/bar", FileUtil.onlyPath("/bar\\foo.xml"));
}
@Test
public void testCompactPath() {
assertEquals(null, FileUtil.compactPath(null));
if (FileUtil.isWindows()) {
assertEquals("..\\foo", FileUtil.compactPath("..\\foo"));
assertEquals("..\\..\\foo", FileUtil.compactPath("..\\..\\foo"));
assertEquals("..\\..\\foo\\bar", FileUtil.compactPath("..\\..\\foo\\bar"));
assertEquals("..\\..\\foo", FileUtil.compactPath("..\\..\\foo\\bar\\.."));
assertEquals("foo", FileUtil.compactPath("foo"));
assertEquals("bar", FileUtil.compactPath("foo\\..\\bar"));
assertEquals("bar\\baz", FileUtil.compactPath("foo\\..\\bar\\baz"));
assertEquals("foo\\baz", FileUtil.compactPath("foo\\bar\\..\\baz"));
assertEquals("baz", FileUtil.compactPath("foo\\bar\\..\\..\\baz"));
assertEquals("..\\baz", FileUtil.compactPath("foo\\bar\\..\\..\\..\\baz"));
assertEquals("..\\foo\\bar", FileUtil.compactPath("..\\foo\\bar"));
assertEquals("foo\\bar\\baz", FileUtil.compactPath("foo\\bar\\.\\baz"));
assertEquals("foo\\bar\\baz", FileUtil.compactPath("foo\\bar\\\\baz"));
assertEquals("\\foo\\bar\\baz", FileUtil.compactPath("\\foo\\bar\\baz"));
// Test that multiple back-slashes at the beginning are preserved, this is necessary for network UNC paths.
assertEquals("\\\\foo\\bar\\baz", FileUtil.compactPath("\\\\foo\\bar\\baz"));
assertEquals("\\", FileUtil.compactPath("\\"));
assertEquals("\\", FileUtil.compactPath("/"));
assertEquals("/", FileUtil.compactPath("\\", '/'));
assertEquals("/", FileUtil.compactPath("/", '/'));
} else {
assertEquals("../foo", FileUtil.compactPath("../foo"));
assertEquals("../../foo", FileUtil.compactPath("../../foo"));
assertEquals("../../foo/bar", FileUtil.compactPath("../../foo/bar"));
assertEquals("../../foo", FileUtil.compactPath("../../foo/bar/.."));
assertEquals("foo", FileUtil.compactPath("foo"));
assertEquals("bar", FileUtil.compactPath("foo/../bar"));
assertEquals("bar/baz", FileUtil.compactPath("foo/../bar/baz"));
assertEquals("foo/baz", FileUtil.compactPath("foo/bar/../baz"));
assertEquals("baz", FileUtil.compactPath("foo/bar/../../baz"));
assertEquals("../baz", FileUtil.compactPath("foo/bar/../../../baz"));
assertEquals("../foo/bar", FileUtil.compactPath("../foo/bar"));
assertEquals("foo/bar/baz", FileUtil.compactPath("foo/bar/./baz"));
assertEquals("foo/bar/baz", FileUtil.compactPath("foo/bar//baz"));
assertEquals("/foo/bar/baz", FileUtil.compactPath("/foo/bar/baz"));
// Do not preserve multiple slashes at the beginning if not on Windows.
assertEquals("/foo/bar/baz", FileUtil.compactPath("//foo/bar/baz"));
assertEquals("/", FileUtil.compactPath("/"));
assertEquals("/", FileUtil.compactPath("\\"));
assertEquals("/", FileUtil.compactPath("/", '/'));
assertEquals("/", FileUtil.compactPath("\\", '/'));
}
}
@Test
public void testCompactWindowsStylePath() {
String path = "E:\\workspace\\foo\\bar\\some-thing\\.\\target\\processes\\2";
String expected = "E:\\workspace\\foo\\bar\\some-thing\\target\\processes\\2";
assertEquals(expected, FileUtil.compactPath(path, '\\'));
}
@Test
public void testCompactPathSeparator() {
assertEquals(null, FileUtil.compactPath(null, '\''));
assertEquals("..\\foo", FileUtil.compactPath("..\\foo", '\\'));
assertEquals("../foo", FileUtil.compactPath("../foo", '/'));
assertEquals("../foo/bar", FileUtil.compactPath("../foo\\bar", '/'));
assertEquals("..\\foo\\bar", FileUtil.compactPath("../foo\\bar", '\\'));
}
@Test
public void testDefaultTempFileSuffixAndPrefix() throws Exception {
File tmp = FileUtil.createTempFile("tmp-", ".tmp", new File("target/tmp"));
assertNotNull(tmp);
assertTrue("Should be a file", tmp.isFile());
}
@Test
public void testDefaultTempFile() throws Exception {
File tmp = FileUtil.createTempFile(null, null, new File("target/tmp"));
assertNotNull(tmp);
assertTrue("Should be a file", tmp.isFile());
}
@Test
public void testDefaultTempFileParent() throws Exception {
File tmp = FileUtil.createTempFile(null, null, new File("target"));
assertNotNull(tmp);
assertTrue("Should be a file", tmp.isFile());
}
@Test
public void testCreateNewFile() throws Exception {
File file = new File("target/data/foo.txt");
if (file.exists()) {
FileUtil.deleteFile(file);
}
assertFalse("File should not exist " + file, file.exists());
assertTrue("A new file should be created " + file, FileUtil.createNewFile(file));
}
@Test
public void testRenameUsingDelete() throws Exception {
File file = new File("target/data/foo.txt");
if (!file.exists()) {
FileUtil.createNewFile(file);
}
File target = new File("target/bar.txt");
FileUtil.renameFileUsingCopy(file, target);
assertTrue("File not copied", target.exists());
assertFalse("File not deleted", file.exists());
}
}
| core/camel-core/src/test/java/org/apache/camel/util/FileUtilTest.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.util;
import java.io.File;
import org.junit.Assert;
import org.junit.Test;
public class FileUtilTest extends Assert {
@Test
public void testNormalizePath() {
if (FileUtil.isWindows()) {
assertEquals("foo\\bar", FileUtil.normalizePath("foo/bar"));
assertEquals("foo\\bar\\baz", FileUtil.normalizePath("foo/bar\\baz"));
assertEquals("movefile\\sub\\sub2\\.done\\goodday.txt", FileUtil.normalizePath("movefile/sub/sub2\\.done\\goodday.txt"));
} else {
assertEquals("foo/bar", FileUtil.normalizePath("foo/bar"));
assertEquals("foo/bar/baz", FileUtil.normalizePath("foo/bar\\baz"));
assertEquals("movefile/sub/sub2/.done/goodday.txt", FileUtil.normalizePath("movefile/sub/sub2\\.done\\goodday.txt"));
}
}
@Test
public void testStripLeadingSeparator() {
assertEquals(null, FileUtil.stripLeadingSeparator(null));
assertEquals("foo", FileUtil.stripLeadingSeparator("foo"));
assertEquals("foo/bar", FileUtil.stripLeadingSeparator("foo/bar"));
assertEquals("foo/", FileUtil.stripLeadingSeparator("foo/"));
assertEquals("foo/bar", FileUtil.stripLeadingSeparator("/foo/bar"));
assertEquals("foo/bar", FileUtil.stripLeadingSeparator("//foo/bar"));
assertEquals("foo/bar", FileUtil.stripLeadingSeparator("///foo/bar"));
}
@Test
public void testHasLeadingSeparator() {
assertEquals(false, FileUtil.hasLeadingSeparator(null));
assertEquals(false, FileUtil.hasLeadingSeparator("foo"));
assertEquals(false, FileUtil.hasLeadingSeparator("foo/bar"));
assertEquals(false, FileUtil.hasLeadingSeparator("foo/"));
assertEquals(true, FileUtil.hasLeadingSeparator("/foo/bar"));
assertEquals(true, FileUtil.hasLeadingSeparator("//foo/bar"));
assertEquals(true, FileUtil.hasLeadingSeparator("///foo/bar"));
}
@Test
public void testStripFirstLeadingSeparator() {
assertEquals(null, FileUtil.stripFirstLeadingSeparator(null));
assertEquals("foo", FileUtil.stripFirstLeadingSeparator("foo"));
assertEquals("foo/bar", FileUtil.stripFirstLeadingSeparator("foo/bar"));
assertEquals("foo/", FileUtil.stripFirstLeadingSeparator("foo/"));
assertEquals("foo/bar", FileUtil.stripFirstLeadingSeparator("/foo/bar"));
assertEquals("/foo/bar", FileUtil.stripFirstLeadingSeparator("//foo/bar"));
assertEquals("//foo/bar", FileUtil.stripFirstLeadingSeparator("///foo/bar"));
}
@Test
public void testStripTrailingSeparator() {
assertEquals(null, FileUtil.stripTrailingSeparator(null));
assertEquals("foo", FileUtil.stripTrailingSeparator("foo"));
assertEquals("foo/bar", FileUtil.stripTrailingSeparator("foo/bar"));
assertEquals("foo", FileUtil.stripTrailingSeparator("foo/"));
assertEquals("foo/bar", FileUtil.stripTrailingSeparator("foo/bar/"));
assertEquals("/foo/bar", FileUtil.stripTrailingSeparator("/foo/bar"));
assertEquals("/foo/bar", FileUtil.stripTrailingSeparator("/foo/bar/"));
assertEquals("/foo/bar", FileUtil.stripTrailingSeparator("/foo/bar//"));
assertEquals("/foo/bar", FileUtil.stripTrailingSeparator("/foo/bar///"));
assertEquals("/foo", FileUtil.stripTrailingSeparator("/foo"));
assertEquals("/foo", FileUtil.stripTrailingSeparator("/foo/"));
assertEquals("/", FileUtil.stripTrailingSeparator("/"));
assertEquals("//", FileUtil.stripTrailingSeparator("//"));
}
@Test
public void testStripPath() {
assertEquals(null, FileUtil.stripPath(null));
assertEquals("", FileUtil.stripPath("/"));
assertEquals("foo.xml", FileUtil.stripPath("/foo.xml"));
assertEquals("foo", FileUtil.stripPath("foo"));
assertEquals("bar", FileUtil.stripPath("foo/bar"));
assertEquals("bar", FileUtil.stripPath("/foo/bar"));
}
@Test
public void testStripPathWithMixedSeparators() {
assertEquals(null, FileUtil.stripPath(null));
assertEquals("", FileUtil.stripPath("/"));
assertEquals("foo.xml", FileUtil.stripPath("/foo.xml"));
assertEquals("foo", FileUtil.stripPath("foo"));
assertEquals("baz", FileUtil.stripPath("foo/bar\\baz"));
assertEquals("bar", FileUtil.stripPath("\\foo\\bar"));
assertEquals("baz", FileUtil.stripPath("/foo\\bar/baz"));
}
@Test
public void testStripExt() {
assertEquals(null, FileUtil.stripExt(null));
assertEquals("foo", FileUtil.stripExt("foo"));
assertEquals("foo", FileUtil.stripExt("foo.xml"));
assertEquals("/foo/bar", FileUtil.stripExt("/foo/bar.xml"));
}
@Test
public void testOnlyExt() {
assertEquals(null, FileUtil.onlyExt(null));
assertEquals(null, FileUtil.onlyExt("foo"));
assertEquals("xml", FileUtil.onlyExt("foo.xml"));
assertEquals("xml", FileUtil.onlyExt("/foo/bar.xml"));
assertEquals("tar.gz", FileUtil.onlyExt("/foo/bigfile.tar.gz"));
assertEquals("tar.gz", FileUtil.onlyExt("/foo.bar/bigfile.tar.gz"));
}
@Test
public void testOnlyPath() {
assertEquals(null, FileUtil.onlyPath(null));
assertEquals(null, FileUtil.onlyPath("foo"));
assertEquals(null, FileUtil.onlyPath("foo.xml"));
assertEquals("foo", FileUtil.onlyPath("foo/bar.xml"));
assertEquals("/foo", FileUtil.onlyPath("/foo/bar.xml"));
assertEquals("/foo/bar", FileUtil.onlyPath("/foo/bar/baz.xml"));
assertEquals("/", FileUtil.onlyPath("/foo.xml"));
assertEquals("/bar", FileUtil.onlyPath("/bar/foo.xml"));
}
@Test
public void testOnlyPathWithMixedSeparators() {
assertEquals(null, FileUtil.onlyPath(null));
assertEquals(null, FileUtil.onlyPath("foo"));
assertEquals(null, FileUtil.onlyPath("foo.xml"));
assertEquals("foo", FileUtil.onlyPath("foo/bar.xml"));
assertEquals("/foo", FileUtil.onlyPath("/foo\\bar.xml"));
assertEquals("\\foo\\bar", FileUtil.onlyPath("\\foo\\bar/baz.xml"));
assertEquals("\\", FileUtil.onlyPath("\\foo.xml"));
assertEquals("/bar", FileUtil.onlyPath("/bar\\foo.xml"));
}
@Test
public void testCompactPath() {
assertEquals(null, FileUtil.compactPath(null));
if (FileUtil.isWindows()) {
assertEquals("..\\foo", FileUtil.compactPath("..\\foo"));
assertEquals("..\\..\\foo", FileUtil.compactPath("..\\..\\foo"));
assertEquals("..\\..\\foo\\bar", FileUtil.compactPath("..\\..\\foo\\bar"));
assertEquals("..\\..\\foo", FileUtil.compactPath("..\\..\\foo\\bar\\.."));
assertEquals("foo", FileUtil.compactPath("foo"));
assertEquals("bar", FileUtil.compactPath("foo\\..\\bar"));
assertEquals("bar\\baz", FileUtil.compactPath("foo\\..\\bar\\baz"));
assertEquals("foo\\baz", FileUtil.compactPath("foo\\bar\\..\\baz"));
assertEquals("baz", FileUtil.compactPath("foo\\bar\\..\\..\\baz"));
assertEquals("..\\baz", FileUtil.compactPath("foo\\bar\\..\\..\\..\\baz"));
assertEquals("..\\foo\\bar", FileUtil.compactPath("..\\foo\\bar"));
assertEquals("foo\\bar\\baz", FileUtil.compactPath("foo\\bar\\.\\baz"));
assertEquals("foo\\bar\\baz", FileUtil.compactPath("foo\\bar\\\\baz"));
assertEquals("\\foo\\bar\\baz", FileUtil.compactPath("\\foo\\bar\\baz"));
assertEquals("\\", FileUtil.compactPath("\\"));
assertEquals("\\", FileUtil.compactPath("/"));
assertEquals("/", FileUtil.compactPath("\\", '/'));
assertEquals("/", FileUtil.compactPath("/", '/'));
} else {
assertEquals("../foo", FileUtil.compactPath("../foo"));
assertEquals("../../foo", FileUtil.compactPath("../../foo"));
assertEquals("../../foo/bar", FileUtil.compactPath("../../foo/bar"));
assertEquals("../../foo", FileUtil.compactPath("../../foo/bar/.."));
assertEquals("foo", FileUtil.compactPath("foo"));
assertEquals("bar", FileUtil.compactPath("foo/../bar"));
assertEquals("bar/baz", FileUtil.compactPath("foo/../bar/baz"));
assertEquals("foo/baz", FileUtil.compactPath("foo/bar/../baz"));
assertEquals("baz", FileUtil.compactPath("foo/bar/../../baz"));
assertEquals("../baz", FileUtil.compactPath("foo/bar/../../../baz"));
assertEquals("../foo/bar", FileUtil.compactPath("../foo/bar"));
assertEquals("foo/bar/baz", FileUtil.compactPath("foo/bar/./baz"));
assertEquals("foo/bar/baz", FileUtil.compactPath("foo/bar//baz"));
assertEquals("/foo/bar/baz", FileUtil.compactPath("/foo/bar/baz"));
assertEquals("/", FileUtil.compactPath("/"));
assertEquals("/", FileUtil.compactPath("\\"));
assertEquals("/", FileUtil.compactPath("/", '/'));
assertEquals("/", FileUtil.compactPath("\\", '/'));
}
}
@Test
public void testCompactWindowsStylePath() {
String path = "E:\\workspace\\foo\\bar\\some-thing\\.\\target\\processes\\2";
String expected = "E:\\workspace\\foo\\bar\\some-thing\\target\\processes\\2";
assertEquals(expected, FileUtil.compactPath(path, '\\'));
}
@Test
public void testCompactPathSeparator() {
assertEquals(null, FileUtil.compactPath(null, '\''));
assertEquals("..\\foo", FileUtil.compactPath("..\\foo", '\\'));
assertEquals("../foo", FileUtil.compactPath("../foo", '/'));
assertEquals("../foo/bar", FileUtil.compactPath("../foo\\bar", '/'));
assertEquals("..\\foo\\bar", FileUtil.compactPath("../foo\\bar", '\\'));
}
@Test
public void testDefaultTempFileSuffixAndPrefix() throws Exception {
File tmp = FileUtil.createTempFile("tmp-", ".tmp", new File("target/tmp"));
assertNotNull(tmp);
assertTrue("Should be a file", tmp.isFile());
}
@Test
public void testDefaultTempFile() throws Exception {
File tmp = FileUtil.createTempFile(null, null, new File("target/tmp"));
assertNotNull(tmp);
assertTrue("Should be a file", tmp.isFile());
}
@Test
public void testDefaultTempFileParent() throws Exception {
File tmp = FileUtil.createTempFile(null, null, new File("target"));
assertNotNull(tmp);
assertTrue("Should be a file", tmp.isFile());
}
@Test
public void testCreateNewFile() throws Exception {
File file = new File("target/data/foo.txt");
if (file.exists()) {
FileUtil.deleteFile(file);
}
assertFalse("File should not exist " + file, file.exists());
assertTrue("A new file should be created " + file, FileUtil.createNewFile(file));
}
@Test
public void testRenameUsingDelete() throws Exception {
File file = new File("target/data/foo.txt");
if (!file.exists()) {
FileUtil.createNewFile(file);
}
File target = new File("target/bar.txt");
FileUtil.renameFileUsingCopy(file, target);
assertTrue("File not copied", target.exists());
assertFalse("File not deleted", file.exists());
}
}
| CAMEL-13667
Windows network UNC paths not treated correctly (File2/tempPrefix) test
| core/camel-core/src/test/java/org/apache/camel/util/FileUtilTest.java | CAMEL-13667 | <ide><path>ore/camel-core/src/test/java/org/apache/camel/util/FileUtilTest.java
<ide> assertEquals("foo\\bar\\baz", FileUtil.compactPath("foo\\bar\\.\\baz"));
<ide> assertEquals("foo\\bar\\baz", FileUtil.compactPath("foo\\bar\\\\baz"));
<ide> assertEquals("\\foo\\bar\\baz", FileUtil.compactPath("\\foo\\bar\\baz"));
<add> // Test that multiple back-slashes at the beginning are preserved, this is necessary for network UNC paths.
<add> assertEquals("\\\\foo\\bar\\baz", FileUtil.compactPath("\\\\foo\\bar\\baz"));
<ide> assertEquals("\\", FileUtil.compactPath("\\"));
<ide> assertEquals("\\", FileUtil.compactPath("/"));
<ide> assertEquals("/", FileUtil.compactPath("\\", '/'));
<ide> assertEquals("foo/bar/baz", FileUtil.compactPath("foo/bar/./baz"));
<ide> assertEquals("foo/bar/baz", FileUtil.compactPath("foo/bar//baz"));
<ide> assertEquals("/foo/bar/baz", FileUtil.compactPath("/foo/bar/baz"));
<add> // Do not preserve multiple slashes at the beginning if not on Windows.
<add> assertEquals("/foo/bar/baz", FileUtil.compactPath("//foo/bar/baz"));
<ide> assertEquals("/", FileUtil.compactPath("/"));
<ide> assertEquals("/", FileUtil.compactPath("\\"));
<ide> assertEquals("/", FileUtil.compactPath("/", '/')); |
|
Java | mit | 5a3b98b2d5a3304baa8096cc4c9decd065847af7 | 0 | nking/shared,nking/shared | package algorithms.util;
/**
* A class to estimate the amount of memory an object takes.
* The user should know if it is to be on the heap or
* stack (method local variables) when comparing the results to
* available memory.
*
* Options for other data-types will be added as needed.
*
* @author nichole
*/
public class ObjectSpaceEstimator {
/*
memory usage of an object:
overhead of each object + memory required for type padded to 8 byte values
overhead = ref to class, gc state info, + synchronization info
OVERHEAD = 16 bytes
http://users.elis.ugent.be/~leeckhou/papers/SPE06.pdf
----------------
Table III. Java types and their sizes in number of bits when used in the
heap (‘field size’ column) and when used on the
stack (‘size on stack’ column).
32-bit platform 64-bit platform
Field Size on Field Size on
Java types size stack size stack
boolean 32 32 32 64
byte 32 32 32 64
char 32 32 32 64
short 32 32 32 64
int 32 32 32 64
float 32 32 32 64
reference 32 32 64 64
array reference 32 32 32 32
returnAddress 32 32 64 64
long 64 64 64 128
double 64 64 64 128
JVM HEAP:
-- shared among all virtual machine threads.
holds instance variables, static fields, array elements
-- strings are stored on the heap
JVM METHOD AREA: [THIS is logically part of the HEAP, but in small vms may not gc it.]
-- shared among all virtual machine threads.
holds structures for compiled code:
runtime constant pool
field data
method data
code for methods and constructors
Thread Stack:
-- local variables, references to objects, and primitives
Frame:
-- new one is created each time a method is invoked and destroyed
when it's completed.
(holds data and partial results.)
-- has a LIFO operand stack (max depth is determined at compile time)
-- the operand stack is empty when frame is created
-- jvm loads constants, local variable values, or fields onto operand stack
-- default size dpends on architecture and impl. usually is 512K or 1024K
*/
private int nBoolean = 0;
private int nByte = 0;
private int nChar = 0;
private int nShort = 0;
private int nInt = 0;
private int nFloat = 0;
private int nObjRefs = 0;
private int nArrayRefs = 0;
private int nLong = 0;
private int nDouble = 0;
private int nReturnAddress = 0;
// sizes in bytes as [heap 32 bit, stack 32 bit, heap 54 bit, stack 64 bit]
private final static int objOverheadSz = 16;
private final static int[] word3264 = new int[]{4, 4, 4, 8};
private static String arch = System.getProperty("sun.arch.data.model");
private static boolean is32Bit = ((arch != null) && arch.equals("64")) ? false : true;
private final static int[] booleanSz = word3264;
private final static int[] byteSz = word3264;
private final static int[] charSz = word3264;
private final static int[] shortSz = word3264;
private final static int[] intSz = word3264;
private final static int[] floatSz = word3264;
private final static int[] refSz = new int[]{4, 4, 8, 8};
private final static int[] arrayRefSz = new int[]{4, 4, 4, 4};
private final static int[] returnAddressSz = new int[]{4, 4, 8, 8};
private final static int[] longSz = new int[]{8, 8, 8, 16};
private final static int[] doubleSz = new int[]{8, 8, 8, 16};
/**
* @param nBoolean the number of boolean primitives
*/
public void setNBooleanFields(int nBoolean) {
this.nBoolean = nBoolean;
}
/**
* @param nByte the number of byte primitives
*/
public void setNByteFields(int nByte) {
this.nByte = nByte;
}
/**
* @param nChar the number of char primitives to set
*/
public void setNCharFields(int nChar) {
this.nChar = nChar;
}
/**
* @param nShort the number of short primitives
*/
public void setNShortFields(int nShort) {
this.nShort = nShort;
}
/**
* @param nInt the number of int primitives
*/
public void setNIntFields(int nInt) {
this.nInt = nInt;
}
/**
* @param nFloat the number of float primitives
*/
public void setNFloatFields(int nFloat) {
this.nFloat = nFloat;
}
/**
* @param nObjRefs the number of object references
*/
public void setNObjRefsFields(int nObjRefs) {
this.nObjRefs = nObjRefs;
}
/**
* @param nArrayRefs the number of array references to set
*/
public void setNArrayRefsFields(int nArrayRefs) {
this.nArrayRefs = nArrayRefs;
}
/**
* @param nLong the number of long primitives
*/
public void setNLongFields(int nLong) {
this.nLong = nLong;
}
/**
* @param nDouble the number of double primitives
*/
public void setNDoubleFields(int nDouble) {
this.nDouble = nDouble;
}
/**
* @param nReturnAddress the nReturnAddress to set
*/
public void setNReturnAddress(int nReturnAddress) {
this.nReturnAddress = nReturnAddress;
}
/**
* estimate the size of an object in bytes for the given settings and for
* placement on the heap.
* @return total size in bytes for the object placed on the heap.
*/
public long estimateSizeOnHeap() {
return estimateSize(true);
}
/**
* estimate the size of an object in bytes for the given settings and for
* placement on the stack (variables specific to a method frame, that is,
* local variables).
*
* @return total size in bytes for the object places on the stack.
*/
public long estimateSizeOnStack() {
return estimateSize(false);
}
private long estimateSize(boolean calcForHeap) {
int idx;
if (is32Bit) {
if (calcForHeap) {
idx = 0;
} else {
idx = 1;
}
} else {
if (calcForHeap) {
idx = 2;
} else {
idx = 3;
}
}
long total = 0;
// add fields
total += nBoolean * booleanSz[idx];
total += nByte * byteSz[idx];
total += nChar * charSz[idx];
total += nShort * shortSz[idx];
total += nInt * intSz[idx];
total += nFloat * floatSz[idx];
total += nObjRefs * refSz[idx];
total += nArrayRefs * arrayRefSz[idx];
total += nLong * longSz[idx];
total += nDouble * doubleSz[idx];
total += nReturnAddress * returnAddressSz[idx];
// add object overhead
total += 8;
// pad up to 8 byte boundary
long pad = total % 8;
total += pad;
return total;
}
}
| src/main/java/algorithms/util/ObjectSpaceEstimator.java | package algorithms.util;
/**
* A class to estimate the amount of memory an object takes.
* The user should know if it is to be on the heap or
* stack (method local variables) when comparing the results to
* available memory.
*
* @author nichole
*/
public class ObjectSpaceEstimator {
/*
memory usage of an object:
overhead of each object + memory required for type padded to 8 byte values
overhead = ref to class, gc state info, + synchronization info
OVERHEAD = 16 bytes
http://users.elis.ugent.be/~leeckhou/papers/SPE06.pdf
----------------
Table III. Java types and their sizes in number of bits when used in the
heap (‘field size’ column) and when used on the
stack (‘size on stack’ column).
32-bit platform 64-bit platform
Field Size on Field Size on
Java types size stack size stack
boolean 32 32 32 64
byte 32 32 32 64
char 32 32 32 64
short 32 32 32 64
int 32 32 32 64
float 32 32 32 64
reference 32 32 64 64
array reference 32 32 32 32
returnAddress 32 32 64 64
long 64 64 64 128
double 64 64 64 128
JVM HEAP:
-- shared among all virtual machine threads.
holds instance variables, static fields, array elements
-- strings are stored on the heap
JVM METHOD AREA: [THIS is logically part of the HEAP, but in small vms may not gc it.]
-- shared among all virtual machine threads.
holds structures for compiled code:
runtime constant pool
field data
method data
code for methods and constructors
Thread Stack:
-- local variables, references to objects, and primitives
Frame:
-- new one is created each time a method is invoked and destroyed
when it's completed.
(holds data and partial results.)
-- has a LIFO operand stack (max depth is determined at compile time)
-- the operand stack is empty when frame is created
-- jvm loads constants, local variable values, or fields onto operand stack
-- default size dpends on architecture and impl. usually is 512K or 1024K
*/
}
| first draft of object size estimator, not yet
tested.
| src/main/java/algorithms/util/ObjectSpaceEstimator.java | first draft of object size estimator, not yet tested. | <ide><path>rc/main/java/algorithms/util/ObjectSpaceEstimator.java
<ide> * The user should know if it is to be on the heap or
<ide> * stack (method local variables) when comparing the results to
<ide> * available memory.
<add> *
<add> * Options for other data-types will be added as needed.
<ide> *
<ide> * @author nichole
<ide> */
<ide> -- jvm loads constants, local variable values, or fields onto operand stack
<ide> -- default size dpends on architecture and impl. usually is 512K or 1024K
<ide> */
<add>
<add> private int nBoolean = 0;
<add> private int nByte = 0;
<add> private int nChar = 0;
<add> private int nShort = 0;
<add> private int nInt = 0;
<add> private int nFloat = 0;
<add> private int nObjRefs = 0;
<add> private int nArrayRefs = 0;
<add> private int nLong = 0;
<add> private int nDouble = 0;
<add> private int nReturnAddress = 0;
<add>
<add> // sizes in bytes as [heap 32 bit, stack 32 bit, heap 54 bit, stack 64 bit]
<add> private final static int objOverheadSz = 16;
<add>
<add> private final static int[] word3264 = new int[]{4, 4, 4, 8};
<add>
<add> private static String arch = System.getProperty("sun.arch.data.model");
<add> private static boolean is32Bit = ((arch != null) && arch.equals("64")) ? false : true;
<add>
<add> private final static int[] booleanSz = word3264;
<add> private final static int[] byteSz = word3264;
<add> private final static int[] charSz = word3264;
<add> private final static int[] shortSz = word3264;
<add> private final static int[] intSz = word3264;
<add> private final static int[] floatSz = word3264;
<add> private final static int[] refSz = new int[]{4, 4, 8, 8};
<add> private final static int[] arrayRefSz = new int[]{4, 4, 4, 4};
<add> private final static int[] returnAddressSz = new int[]{4, 4, 8, 8};
<add> private final static int[] longSz = new int[]{8, 8, 8, 16};
<add> private final static int[] doubleSz = new int[]{8, 8, 8, 16};
<add>
<add> /**
<add> * @param nBoolean the number of boolean primitives
<add> */
<add> public void setNBooleanFields(int nBoolean) {
<add> this.nBoolean = nBoolean;
<add> }
<add>
<add> /**
<add> * @param nByte the number of byte primitives
<add> */
<add> public void setNByteFields(int nByte) {
<add> this.nByte = nByte;
<add> }
<add>
<add> /**
<add> * @param nChar the number of char primitives to set
<add> */
<add> public void setNCharFields(int nChar) {
<add> this.nChar = nChar;
<add> }
<add>
<add> /**
<add> * @param nShort the number of short primitives
<add> */
<add> public void setNShortFields(int nShort) {
<add> this.nShort = nShort;
<add> }
<add>
<add> /**
<add> * @param nInt the number of int primitives
<add> */
<add> public void setNIntFields(int nInt) {
<add> this.nInt = nInt;
<add> }
<add>
<add> /**
<add> * @param nFloat the number of float primitives
<add> */
<add> public void setNFloatFields(int nFloat) {
<add> this.nFloat = nFloat;
<add> }
<add>
<add> /**
<add> * @param nObjRefs the number of object references
<add> */
<add> public void setNObjRefsFields(int nObjRefs) {
<add> this.nObjRefs = nObjRefs;
<add> }
<add>
<add> /**
<add> * @param nArrayRefs the number of array references to set
<add> */
<add> public void setNArrayRefsFields(int nArrayRefs) {
<add> this.nArrayRefs = nArrayRefs;
<add> }
<add>
<add> /**
<add> * @param nLong the number of long primitives
<add> */
<add> public void setNLongFields(int nLong) {
<add> this.nLong = nLong;
<add> }
<add>
<add> /**
<add> * @param nDouble the number of double primitives
<add> */
<add> public void setNDoubleFields(int nDouble) {
<add> this.nDouble = nDouble;
<add> }
<add>
<add> /**
<add> * @param nReturnAddress the nReturnAddress to set
<add> */
<add> public void setNReturnAddress(int nReturnAddress) {
<add> this.nReturnAddress = nReturnAddress;
<add> }
<add>
<add> /**
<add> * estimate the size of an object in bytes for the given settings and for
<add> * placement on the heap.
<add> * @return total size in bytes for the object placed on the heap.
<add> */
<add> public long estimateSizeOnHeap() {
<add> return estimateSize(true);
<add> }
<add>
<add> /**
<add> * estimate the size of an object in bytes for the given settings and for
<add> * placement on the stack (variables specific to a method frame, that is,
<add> * local variables).
<add> *
<add> * @return total size in bytes for the object places on the stack.
<add> */
<add> public long estimateSizeOnStack() {
<add> return estimateSize(false);
<add> }
<add>
<add> private long estimateSize(boolean calcForHeap) {
<add>
<add> int idx;
<add> if (is32Bit) {
<add> if (calcForHeap) {
<add> idx = 0;
<add> } else {
<add> idx = 1;
<add> }
<add> } else {
<add> if (calcForHeap) {
<add> idx = 2;
<add> } else {
<add> idx = 3;
<add> }
<add> }
<add>
<add> long total = 0;
<add>
<add> // add fields
<add> total += nBoolean * booleanSz[idx];
<add> total += nByte * byteSz[idx];
<add> total += nChar * charSz[idx];
<add> total += nShort * shortSz[idx];
<add> total += nInt * intSz[idx];
<add> total += nFloat * floatSz[idx];
<add> total += nObjRefs * refSz[idx];
<add> total += nArrayRefs * arrayRefSz[idx];
<add> total += nLong * longSz[idx];
<add> total += nDouble * doubleSz[idx];
<add> total += nReturnAddress * returnAddressSz[idx];
<add>
<add> // add object overhead
<add> total += 8;
<add>
<add> // pad up to 8 byte boundary
<add> long pad = total % 8;
<add> total += pad;
<add>
<add> return total;
<add> }
<ide> } |
|
Java | apache-2.0 | 64e0d4fdea5bf8eeaad14aa8f187f800722f9d44 | 0 | MaybeAGame/MaybeAGame | package pl.grzegorz2047.maybeagame.extension;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Scanner;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Taki tam test wczytywania prostych rozszerzeń
*/
public class ExtensionLoader {
public boolean loadExtensions() throws MalformedURLException {
File extensionsDirectory = createExtensionsFileIfNotExists();
File[] jars = extensionsDirectory.listFiles();
if (isExtensionsDirectoryEmpty(jars)) return false;
for (File jar : jars) {
if (!hasJarExtension(jar)) continue;
try {
ZipInputStream zip = new ZipInputStream(new FileInputStream(jar.getPath()));
JarFile jarFile = new JarFile(jar);
getContentOfJarAndLoadIt(jar, zip, jarFile);
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
private void getContentOfJarAndLoadIt(File jar, ZipInputStream zip, JarFile jarFile) throws IOException {
for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
if (isItExtentionSettingFile(entry)) {
Scanner scanner = new Scanner(jarFile.getInputStream(entry));
if(!scanner.hasNextLine()){
Logger.getLogger("MaybeAGame").log(Level.SEVERE, "Jar file named " + jar.getName() + " doesnt have extension.info");
break;
}
String line = scanner.nextLine();
String[] partsOfLine = line.split(":");
String classPath = "";
if(partsOfLine.length == 2){
if(partsOfLine[0].equals("main")){
classPath = partsOfLine[1];
}
}else {
break;
}
System.out.println("Znalazlem plik!");
URL url = jar.toURI().toURL();
Class[] parameters = new Class[]{URL.class};
URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class<URLClassLoader> sysClass = URLClassLoader.class;
try {
Extension instance = getInstanceOfExtension(classPath, url, parameters, sysLoader, sysClass);
instance.onEnable();
} catch (Exception ex) {
System.err.println("Nie udalo sie wczytac " + jar.getName() + "! Sprawdz poprawnosc sciezki main! " + ex.getMessage());
break;
}
break;
}
}
}
private Extension getInstanceOfExtension(String classPath, URL url, Class[] parameters, URLClassLoader sysLoader, Class<URLClassLoader> sysClass) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, ClassNotFoundException, InstantiationException {
Method method = sysClass.getDeclaredMethod("addURL", parameters);
method.setAccessible(true);
method.invoke(sysLoader, url);
Constructor cs = ClassLoader.getSystemClassLoader().loadClass(classPath).getConstructor();
return (Extension) cs.newInstance();
}
private boolean isItExtentionSettingFile(ZipEntry entry) {
return !entry.isDirectory() && entry.getName().equals("extension.info");
}
private boolean hasJarExtension(File jar) {
return jar.getName().endsWith(".jar");
}
private boolean isExtensionsDirectoryEmpty(File[] jars) {
return jars == null || jars.length == 0;
}
private File createExtensionsFileIfNotExists() {
File extensionsDirectory = new File("extensions");
if (!extensionsDirectory.isDirectory()) {
extensionsDirectory.mkdir();
}
return extensionsDirectory;
}
}
| core/src/pl/grzegorz2047/maybeagame/extension/ExtensionLoader.java | package pl.grzegorz2047.maybeagame.extension;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Scanner;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Taki tam test wczytywania prostych rozszerzeń
*/
public class ExtensionLoader {
public boolean loadExtensions() throws MalformedURLException {
File extensionsDirectory = new File("extensions");
if (!extensionsDirectory.isDirectory()) {
return extensionsDirectory.mkdir();
}
File[] jars = extensionsDirectory.listFiles();
if (jars == null || jars.length == 0) return false;
for (File jar : jars) {
if (!jar.getName().endsWith(".jar")) continue;
try {
ZipInputStream zip = new ZipInputStream(new FileInputStream(jar.getPath()));
JarFile jarFile = new JarFile(jar);
System.out.println("PATH: " + jar.getPath());
System.out.println("URI: " + jar.toURI());
System.out.println("URL: " + jar.toURI().toURL());
for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
if (!entry.isDirectory() && entry.getName().equals("extension.info")) {
Scanner scanner = new Scanner(jarFile.getInputStream(entry));
if(!scanner.hasNextLine()){
Logger.getLogger("MaybeAGame").log(Level.SEVERE, "Jar file named " + jar.getName() + " doesnt have extension.info");
break;
}
String line = scanner.nextLine();
String[] partsOfLine = line.split(":");
String classPath = "";
if(partsOfLine.length == 2){
if(partsOfLine[0].equals("main")){
classPath = partsOfLine[1];
}
}else {
break;
}
System.out.println("Znalazlem plik!");
URL url = jar.toURI().toURL();
Class[] parameters = new Class[]{URL.class};
URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class<URLClassLoader> sysClass = URLClassLoader.class;
try {
Method method = sysClass.getDeclaredMethod("addURL", parameters);
method.setAccessible(true);
method.invoke(sysLoader, url);
Constructor cs = ClassLoader.getSystemClassLoader().loadClass(classPath).getConstructor();
Extension instance = (Extension) cs.newInstance();
instance.onEnable();
} catch (Exception ex) {
System.err.println("Nie udalo sie wczytac " + jar.getName() + "! Sprawdz poprawnosc sciezki main! " + ex.getMessage());
break;
}
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
}
| first refactoring
| core/src/pl/grzegorz2047/maybeagame/extension/ExtensionLoader.java | first refactoring | <ide><path>ore/src/pl/grzegorz2047/maybeagame/extension/ExtensionLoader.java
<ide> import java.io.IOException;
<ide> import java.io.InputStream;
<ide> import java.lang.reflect.Constructor;
<add>import java.lang.reflect.InvocationTargetException;
<ide> import java.lang.reflect.Method;
<ide> import java.net.MalformedURLException;
<ide> import java.net.URL;
<ide> public class ExtensionLoader {
<ide>
<ide> public boolean loadExtensions() throws MalformedURLException {
<del> File extensionsDirectory = new File("extensions");
<del> if (!extensionsDirectory.isDirectory()) {
<del> return extensionsDirectory.mkdir();
<del> }
<add> File extensionsDirectory = createExtensionsFileIfNotExists();
<ide> File[] jars = extensionsDirectory.listFiles();
<del> if (jars == null || jars.length == 0) return false;
<add> if (isExtensionsDirectoryEmpty(jars)) return false;
<ide> for (File jar : jars) {
<del> if (!jar.getName().endsWith(".jar")) continue;
<add> if (!hasJarExtension(jar)) continue;
<ide> try {
<ide> ZipInputStream zip = new ZipInputStream(new FileInputStream(jar.getPath()));
<ide> JarFile jarFile = new JarFile(jar);
<del> System.out.println("PATH: " + jar.getPath());
<del> System.out.println("URI: " + jar.toURI());
<del> System.out.println("URL: " + jar.toURI().toURL());
<del> for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
<del> if (!entry.isDirectory() && entry.getName().equals("extension.info")) {
<del> Scanner scanner = new Scanner(jarFile.getInputStream(entry));
<del> if(!scanner.hasNextLine()){
<del> Logger.getLogger("MaybeAGame").log(Level.SEVERE, "Jar file named " + jar.getName() + " doesnt have extension.info");
<del> break;
<del> }
<del> String line = scanner.nextLine();
<del> String[] partsOfLine = line.split(":");
<del> String classPath = "";
<del> if(partsOfLine.length == 2){
<del> if(partsOfLine[0].equals("main")){
<del> classPath = partsOfLine[1];
<del> }
<del> }else {
<del> break;
<del> }
<del> System.out.println("Znalazlem plik!");
<del> URL url = jar.toURI().toURL();
<del>
<del> Class[] parameters = new Class[]{URL.class};
<del>
<del> URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
<del> Class<URLClassLoader> sysClass = URLClassLoader.class;
<del> try {
<del> Method method = sysClass.getDeclaredMethod("addURL", parameters);
<del> method.setAccessible(true);
<del> method.invoke(sysLoader, url);
<del>
<del> Constructor cs = ClassLoader.getSystemClassLoader().loadClass(classPath).getConstructor();
<del> Extension instance = (Extension) cs.newInstance();
<del> instance.onEnable();
<del> } catch (Exception ex) {
<del> System.err.println("Nie udalo sie wczytac " + jar.getName() + "! Sprawdz poprawnosc sciezki main! " + ex.getMessage());
<del> break;
<del> }
<del> break;
<del> }
<del> }
<add> getContentOfJarAndLoadIt(jar, zip, jarFile);
<ide> } catch (IOException e) {
<ide> e.printStackTrace();
<ide> }
<ide> }
<ide> return true;
<ide> }
<add>
<add> private void getContentOfJarAndLoadIt(File jar, ZipInputStream zip, JarFile jarFile) throws IOException {
<add> for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
<add> if (isItExtentionSettingFile(entry)) {
<add> Scanner scanner = new Scanner(jarFile.getInputStream(entry));
<add> if(!scanner.hasNextLine()){
<add> Logger.getLogger("MaybeAGame").log(Level.SEVERE, "Jar file named " + jar.getName() + " doesnt have extension.info");
<add> break;
<add> }
<add> String line = scanner.nextLine();
<add> String[] partsOfLine = line.split(":");
<add> String classPath = "";
<add> if(partsOfLine.length == 2){
<add> if(partsOfLine[0].equals("main")){
<add> classPath = partsOfLine[1];
<add> }
<add> }else {
<add> break;
<add> }
<add> System.out.println("Znalazlem plik!");
<add> URL url = jar.toURI().toURL();
<add>
<add> Class[] parameters = new Class[]{URL.class};
<add>
<add> URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
<add> Class<URLClassLoader> sysClass = URLClassLoader.class;
<add> try {
<add> Extension instance = getInstanceOfExtension(classPath, url, parameters, sysLoader, sysClass);
<add> instance.onEnable();
<add> } catch (Exception ex) {
<add> System.err.println("Nie udalo sie wczytac " + jar.getName() + "! Sprawdz poprawnosc sciezki main! " + ex.getMessage());
<add> break;
<add> }
<add> break;
<add> }
<add> }
<add> }
<add>
<add> private Extension getInstanceOfExtension(String classPath, URL url, Class[] parameters, URLClassLoader sysLoader, Class<URLClassLoader> sysClass) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, ClassNotFoundException, InstantiationException {
<add> Method method = sysClass.getDeclaredMethod("addURL", parameters);
<add> method.setAccessible(true);
<add> method.invoke(sysLoader, url);
<add>
<add> Constructor cs = ClassLoader.getSystemClassLoader().loadClass(classPath).getConstructor();
<add> return (Extension) cs.newInstance();
<add> }
<add>
<add> private boolean isItExtentionSettingFile(ZipEntry entry) {
<add> return !entry.isDirectory() && entry.getName().equals("extension.info");
<add> }
<add>
<add> private boolean hasJarExtension(File jar) {
<add> return jar.getName().endsWith(".jar");
<add> }
<add>
<add> private boolean isExtensionsDirectoryEmpty(File[] jars) {
<add> return jars == null || jars.length == 0;
<add> }
<add>
<add> private File createExtensionsFileIfNotExists() {
<add> File extensionsDirectory = new File("extensions");
<add> if (!extensionsDirectory.isDirectory()) {
<add> extensionsDirectory.mkdir();
<add> }
<add> return extensionsDirectory;
<add> }
<ide> } |
|
Java | apache-2.0 | 1ce73f5a67a8d10c9b85020abe6c213374190033 | 0 | RaviKumar7443/JPETSTORE,RaviKumar7443/JPETSTORE,RaviKumar7443/JPETSTORE | package org.mybatis.jpetstore.domain;
import java.io.Serializable;
import java.math.BigDecimal;
public class ItemCalculate implements Serializable {
private String itemId;
private String productId;
private BigDecimal listPrice;
private BigDecimal unitCost;
private int supplierId;
private String status;
private String attribute1;
private String attribute2;
private String attribute3;
private String attribute4;
private String attribute5;
private Product product;
private int quantity;
public String CalculateTotal(int quantity, BigDecimal unitCost) {
return quantity*unitCost;
}
}
#Comment added on date:Fri Dec 2 09:27:04 UTC 2016
#Comment added on date:Fri Dec 2 09:30:46 UTC 2016
#Comment added on date:Fri Dec 2 09:31:06 UTC 2016
| src/main/java/org/mybatis/jpetstore/domain/Calculate.java | package org.mybatis.jpetstore.domain;
import java.io.Serializable;
import java.math.BigDecimal;
public class ItemCalculate implements Serializable {
private String itemId;
private String productId;
private BigDecimal listPrice;
private BigDecimal unitCost;
private int supplierId;
private String status;
private String attribute1;
private String attribute2;
private String attribute3;
private String attribute4;
private String attribute5;
private Product product;
private int quantity;
public String CalculateTotal(int quantity, BigDecimal unitCost) {
return quantity*unitCost;
}
}
#Comment added on date:Fri Dec 2 09:27:04 UTC 2016
#Comment added on date:Fri Dec 2 09:30:46 UTC 2016
| Fri Dec 2 09:31:06 UTC 2016
| src/main/java/org/mybatis/jpetstore/domain/Calculate.java | Fri Dec 2 09:31:06 UTC 2016 | <ide><path>rc/main/java/org/mybatis/jpetstore/domain/Calculate.java
<ide> }
<ide> #Comment added on date:Fri Dec 2 09:27:04 UTC 2016
<ide> #Comment added on date:Fri Dec 2 09:30:46 UTC 2016
<add>#Comment added on date:Fri Dec 2 09:31:06 UTC 2016 |
|
Java | mit | f39a4981eb27b384d783ce390522dd4cc9e52499 | 0 | fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg | package ua.com.fielden.platform.utils;
import static java.lang.String.format;
import static ua.com.fielden.platform.entity.AbstractEntity.DESC;
import static ua.com.fielden.platform.entity.AbstractEntity.ID;
import static ua.com.fielden.platform.entity.AbstractEntity.KEY;
import static ua.com.fielden.platform.entity.AbstractEntity.VERSION;
import static ua.com.fielden.platform.reflection.AnnotationReflector.getKeyType;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.AbstractUnionEntity;
import ua.com.fielden.platform.entity.ActivatableAbstractEntity;
import ua.com.fielden.platform.entity.DynamicEntityKey;
import ua.com.fielden.platform.entity.annotation.DescTitle;
import ua.com.fielden.platform.entity.annotation.IsProperty;
import ua.com.fielden.platform.entity.annotation.KeyType;
import ua.com.fielden.platform.entity.annotation.MapEntityTo;
import ua.com.fielden.platform.entity.fetch.FetchProviderFactory;
import ua.com.fielden.platform.entity.fetch.IFetchProvider;
import ua.com.fielden.platform.entity.meta.MetaProperty;
import ua.com.fielden.platform.entity.meta.PropertyDescriptor;
import ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils;
import ua.com.fielden.platform.entity.query.model.EntityResultQueryModel;
import ua.com.fielden.platform.error.Result;
import ua.com.fielden.platform.reflection.AnnotationReflector;
import ua.com.fielden.platform.reflection.Finder;
import ua.com.fielden.platform.reflection.TitlesDescsGetter;
import ua.com.fielden.platform.reflection.asm.impl.DynamicEntityClassLoader;
import ua.com.fielden.platform.serialisation.api.ISerialiser;
import ua.com.fielden.platform.types.Money;
import ua.com.fielden.platform.utils.ConverterFactory.Converter;
public class EntityUtils {
private final static Logger logger = Logger.getLogger(EntityUtils.class);
/** Private default constructor to prevent instantiation. */
private EntityUtils() {
}
/**
* dd/MM/yyyy format instance
*/
public static final String dateWithoutTimeFormat = "dd/MM/yyyy";
/**
* Convenient method for value to {@link String} conversion
*
* @param value
* @param valueType
* @return
*/
public static String toString(final Object value, final Class<?> valueType) {
if (value == null) {
return "";
}
if (valueType == Integer.class || valueType == int.class) {
return NumberFormat.getInstance().format(value);
} else if (Number.class.isAssignableFrom(valueType) || valueType == double.class) {
return NumberFormat.getInstance().format(new BigDecimal(value.toString()));
} else if (valueType == Date.class || valueType == DateTime.class) {
final Date date = valueType == Date.class ? (Date) value : ((DateTime) value).toDate();
return new SimpleDateFormat(dateWithoutTimeFormat).format(date) + " " + DateFormat.getTimeInstance(DateFormat.SHORT).format(date);
} else if (Money.class.isAssignableFrom(valueType)) {
return value instanceof Number ? new Money(value.toString()).toString() : value.toString();
} else if (valueType == BigDecimalWithTwoPlaces.class) {
return value instanceof Number ? String.format("%,10.2f", value) : value.toString();
} else {
return value.toString();
}
}
/**
* Invokes method {@link #toString(Object, Class)} with the second argument being assigned as value's class.
*
* @param value
* @return
*/
public static String toString(final Object value) {
if (value == null) {
return "";
}
return toString(value, value.getClass());
}
/**
* Null-safe comparator.
*
* @param o1
* @param o2
* @return
*/
public static <T> int safeCompare(final Comparable<T> c1, final T c2) {
if (c1 == null && c2 == null) {
return 0;
} else if (c1 == null) {
return -1;
} else if (c2 == null) {
return 1;
} else {
return c1.compareTo(c2);
}
}
/**
* Null-safe equals based on the {@link AbstractEntity}'s id property. If id property is not present in both entities then default equals for entities will be called.
*
* @param entity1
* @param entity2
* @return
*/
public static boolean areEqual(final AbstractEntity<?> entity1, final AbstractEntity<?> entity2) {
if (entity1 != null && entity2 != null) {
if (entity1.getId() == null && entity2.getId() == null) {
return entity1.equals(entity2);
} else {
return equalsEx(entity1.getId(), entity2.getId());
}
}
return entity1 == entity2;
}
/**
* A convenient method to safely compare entity values even if they are <code>null</code>.
* <p>
* The <code>null</code> value is considered to be smaller than a non-null value.
*
* @param o1
* @param o2
* @return
*/
@SuppressWarnings("rawtypes")
public static <T extends AbstractEntity<K>, K extends Comparable> int compare(final T o1, final T o2) {
return safeCompare(o1, o2);
}
/**
* Returns value that indicates whether entity is among entities. The equality comparison is based on {@link #areEquals(AbstractEntity, AbstractEntity)} method
*
* @param entities
* @param entity
* @return
*/
public static <T extends AbstractEntity<?>> boolean containsById(final List<T> entities, final T entity) {
for (final AbstractEntity<?> e : entities) {
if (areEqual(e, entity)) {
return true;
}
}
return false;
}
/**
* Returns index of the entity in the entities list. The equality comparison is based on the {@link #areEquals(AbstractEntity, AbstractEntity)} method.
*
* @param entities
* @param entity
* @return
*/
public static <T extends AbstractEntity<?>> int indexOfById(final List<T> entities, final T entity) {
for (int index = 0; index < entities.size(); index++) {
if (areEqual(entities.get(index), entity)) {
return index;
}
}
return -1;
}
/**
* This method chooses appropriate Converter for any types of property. Even for properties of [AbstractEntity's descendant type] or List<[AbstractEntity's descendant type]> or
* List<String>
*
* @param entity
* @param propertyName
* @return
*/
public static Converter chooseConverterBasedUponPropertyType(final AbstractEntity<?> entity, final String propertyName, final ShowingStrategy showingStrategy) {
final MetaProperty<?> metaProperty = Finder.findMetaProperty(entity, propertyName);
return chooseConverterBasedUponPropertyType(metaProperty, showingStrategy);
}
/**
* this method chooses appropriate Converter for any types of property. Even for properties of [AbstractEntity's descendant type] or List<[AbstractEntity's descendant type]> or
* List<String>
*
* @param entity
* @param propertyName
* @return
*/
public static Converter chooseConverterBasedUponPropertyType(final Class<?> propertyType, final Class<?> collectionType, final ShowingStrategy showingStrategy) {
if (propertyType.equals(String.class)) {
return null;
} else if (Number.class.isAssignableFrom(propertyType)) {
return ConverterFactory.createNumberConverter();
} else if (Money.class.isAssignableFrom(propertyType)) {
return ConverterFactory.createMoneyConverter();
} else if (Date.class.equals(propertyType) || DateTime.class.equals(propertyType)) {
return ConverterFactory.createDateConverter();
} else if (AbstractEntity.class.isAssignableFrom(propertyType)) {
return ConverterFactory.createAbstractEntityOrListConverter(showingStrategy);
} else if (List.class.isAssignableFrom(propertyType)) {
if (collectionType != null) {
final Class<?> typeArgClass = collectionType;
if (AbstractEntity.class.isAssignableFrom(typeArgClass)) {
return ConverterFactory.createAbstractEntityOrListConverter(showingStrategy);
} else if (typeArgClass.equals(String.class)) {
return ConverterFactory.createStringListConverter();
} else {
System.out.println(new Exception("listType actualTypeArgument is not String or descendant of AbstractEntity!"));
return null;
}
} else {
System.out.println(new Exception("listType is not Parameterized???!!"));
return null;
}
} else if (Enum.class.isAssignableFrom(propertyType)) {
return ConverterFactory.createTrivialConverter();
} else {
return null;
}
}
/**
* Does the same as {@link #chooseConverterBasedUponPropertyType(AbstractEntity, String)}
*
* @param metaProperty
* @return
*/
public static Converter chooseConverterBasedUponPropertyType(final MetaProperty<?> metaProperty, final ShowingStrategy showingStrategy) {
return chooseConverterBasedUponPropertyType(metaProperty.getType(), metaProperty.getPropertyAnnotationType(), showingStrategy);
}
/**
* Obtains {@link MetaProperty} using {@link #findFirstFailedMetaProperty(AbstractEntity, String)} and returns {@link #getLabelText(MetaProperty, boolean)}
*
* @return the subject's text value
* @throws MissingConverterException
* @throws ClassCastException
* if the subject value is not a String
*/
public static String getLabelText(final AbstractEntity<?> entity, final String propertyName, final ShowingStrategy showingStrategy) {
final MetaProperty<?> metaProperty = findFirstFailedMetaProperty(entity, propertyName);
return getLabelText(metaProperty, false, showingStrategy);
}
public enum ShowingStrategy {
KEY_ONLY, DESC_ONLY, KEY_AND_DESC
}
/**
* Gets converter for passed {@link MetaProperty} with showKeyOnly param and returns {@link #getLabelText(MetaProperty, Converter)}
*
* @param metaProperty
* @param showKeyOnly
* @return
*/
public static String getLabelText(final MetaProperty<?> metaProperty, final boolean returnEmptyStringIfInvalid, final ShowingStrategy showingStrategy) {
final ConverterFactory.Converter converter = chooseConverterBasedUponPropertyType(metaProperty, showingStrategy);
return getLabelText(metaProperty, returnEmptyStringIfInvalid, converter);
}
/**
* Returns text value for passed {@link MetaProperty} using passed {@link Converter}.
*
* @param returnEmptyStringIfInvalid
* - if {@link Boolean#TRUE} passed as this parameter, then empty string will be returned if passed {@link MetaProperty} is invalid (converter is not used at all in
* this case). Otherwise {@link MetaProperty#getLastInvalidValue()} will be obtained from invalid {@link MetaProperty}, converted using passed {@link Converter} and
* returned.
*
* @return the subject's text value
* @throws MissingConverterException
* @throws ClassCastException
* if the subject value is not a String
*/
public static String getLabelText(final MetaProperty<?> metaProperty, final boolean returnEmptyStringIfInvalid, final Converter converter) {
if (metaProperty != null) {
// hierarchy is valid, only the last property could be invalid
final Object value = metaProperty.getLastAttemptedValue();
if (!metaProperty.isValid() && returnEmptyStringIfInvalid) {
return "";
}
return getLabelText(value, converter);
} else {
// some property (not the last) is invalid, thus showing empty string
return "";
}
}
/**
* Returns label text representation of value using specified converter.
*
* @param value
* @param converter
* @return
*/
public static String getLabelText(final Object value, final Converter converter) {
if (value != null && !value.getClass().equals(String.class) && converter == null) {
return value.toString();
}
final String str = converter != null ? converter.convertToString(value) : (String) value;
return str == null ? "" : str;
}
/**
* Formats passeed value according to its type.
*
* @param value
* @param valueType
* @return
*/
public static String formatTooltip(final Object value, final Class<?> valueType) {
if (value == null) {
return "";
}
if (valueType == Integer.class) {
return NumberFormat.getInstance().format(value);
} else if (Number.class.isAssignableFrom(valueType)) {
return NumberFormat.getInstance().format(new BigDecimal(value.toString()));
} else if (valueType == Date.class || valueType == DateTime.class) {
final Object convertedValue = value instanceof DateTime ? ((DateTime) value).toDate() : value;
return new SimpleDateFormat(dateWithoutTimeFormat).format(convertedValue) + " " + DateFormat.getTimeInstance(DateFormat.SHORT).format(convertedValue);
} else {
return value.toString();
}
}
/**
* Checks and answers if the two objects are both {@code null} or equal.
*
* <pre>
* #equals(null, null) == true
* #equals("Hi", "Hi") == true
* #equals("Hi", null) == false
* #equals(null, "Hi") == false
* #equals("Hi", "Ho") == false
* </pre>
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return boolean {@code true} if and only if both objects are {@code null} or equal
*/
public static boolean equalsEx(final Object o1, final Object o2) {
return o1 == o2 || o1 != null && o2 != null && o1.equals(o2);
}
/**
* Returns current value(if property is valid, then its value, otherwise last incorrect value of corresponding meta-property) of property of passed entity.<br>
* <br>
* Note : does not support dot-notated property names.
*
* @param entity
* @param propertyName
* @return
*/
public static Object getCurrentValue(final AbstractEntity<?> entity, final String propertyName) {
final MetaProperty<?> metaProperty = entity.getProperty(propertyName);
if (metaProperty == null) {
throw new IllegalArgumentException("Couldn't find meta-property named '" + propertyName + "' in " + entity);
} else {
return metaProperty.isValid() ? entity.get(propertyName) : metaProperty.getLastInvalidValue();
}
}
/**
* Returns either {@link MetaProperty} corresponding to last property in <code>propertyName</code> if all previous {@link MetaProperty}ies are valid and without warnings, or
* first failed {@link MetaProperty} or one with warning.
*
* @param entity
* @param propertyName
* @return
*/
public static MetaProperty<?> findFirstFailedMetaProperty(final AbstractEntity<?> entity, final String propertyName) {
final List<MetaProperty<?>> metaProperties = Finder.findMetaProperties(entity, propertyName);
return findFirstFailedMetaProperty(metaProperties);
}
/**
* Does the same as method {@link #findFirstFailedMetaProperty(AbstractEntity, String)} but already on the provided list of {@link MetaProperty}s.
*
* @param metaProperties
* @return
*/
public static MetaProperty<?> findFirstFailedMetaProperty(final List<MetaProperty<?>> metaProperties) {
MetaProperty<?> firstFailedMetaProperty = metaProperties.get(metaProperties.size() - 1);
for (int i = 0; i < metaProperties.size(); i++) {
final MetaProperty<?> metaProperty = metaProperties.get(i);
if (!metaProperty.isValid() || metaProperty.hasWarnings()) {
firstFailedMetaProperty = metaProperty;
break;
}
}
return firstFailedMetaProperty;
}
/**
* This method throws Result (so can be used to specify DYNAMIC validation inside the date setters) when the specified finish/start dates are invalid together.
*
* @param start
* @param finish
* @param fieldPrefix
* - the prefix for the field in the error message for e.g. "actual" or "early".
* @param finishSetter
* - use true if validation have to be performed inside the "finish" date setter, false - inside the "start" date setter
* @throws Result
*/
public static void validateDateRange(final Date start, final Date finish, final MetaProperty<Date> startProperty, final MetaProperty<Date> finishProperty, final boolean finishSetter) {
if (finish != null) {
if (start != null) {
if (start.after(finish)) {
throw Result.failure(finishSetter
? format("Property [%s] (value [%s]) cannot be before property [%s] (value [%s]).", finishProperty.getTitle(), toString(finish) , startProperty.getTitle(), toString(start))
: format("Property [%s] (value [%s]) cannot be after property [%s] (value [%s]).", startProperty.getTitle(), toString(start), finishProperty.getTitle(), toString(finish)));
}
} else {
throw Result.failure(finishSetter
? format("Property [%s] (value [%s]) cannot be specified without property [%s].", finishProperty.getTitle(), finish, startProperty.getTitle())
: format("Property [%s] cannot be empty if property [%s] (value [%s]) if specified.", startProperty.getTitle(), finishProperty.getTitle(), finish));
}
}
}
/**
* This method throws Result (so can be used to specify DYNAMIC validation inside the date setters) when the specified finish/start date times are invalid together.
*
* @param start
* @param finish
* @param fieldPrefix
* - the prefix for the field in the error message for e.g. "actual" or "early".
* @param finishSetter
* - use true if validation have to be performed inside the "finish" date setter, false - inside the "start" date setter
* @throws Result
*/
public static void validateDateTimeRange(final DateTime start, final DateTime finish, final MetaProperty<DateTime> startProperty, final MetaProperty<DateTime> finishProperty, final boolean finishSetter) {
if (finish != null) {
if (start != null) {
if (start.isAfter(finish)) {
throw Result.failure(finishSetter
? format("Property [%s] (value [%s]) cannot be before property [%s] (value [%s]).", finishProperty.getTitle(), toString(finish) , startProperty.getTitle(), toString(start))
: format("Property [%s] (value [%s]) cannot be after property [%s] (value [%s]).", startProperty.getTitle(), toString(start), finishProperty.getTitle(), toString(finish)));
}
} else {
throw Result.failure(finishSetter
? format("Property [%s] (value [%s]) cannot be specified without property [%s].", finishProperty.getTitle(), finish, startProperty.getTitle())
: format("Property [%s] cannot be empty if property [%s] (value [%s]) if specified.", startProperty.getTitle(), finishProperty.getTitle(), finish));
}
}
}
/**
* A convenient method for validating two integer properties that form a range [from;to].
* <p>
* Note, the use use Of Number is not possible because it does not implement interface Comparable due to valid reasons. See
* http://stackoverflow.com/questions/480632/why-doesnt-java-lang-number-implement-comparable from more.
*
* @param start
* @param finish
* @param startProperty
* @param finishProperty
* @param finishSetter
* @throws Result
*/
public static void validateIntegerRange(final Integer start, final Integer finish, final MetaProperty<Integer> startProperty, final MetaProperty<Integer> finishProperty, final boolean finishSetter) {
if (finish != null) {
if (start != null) {
if (start.compareTo(finish) > 0) { // after(finish)
throw new Result("", new Exception(finishSetter ? //
/* */finishProperty.getTitle() + " cannot be less than " + startProperty.getTitle() + "." //
: startProperty.getTitle() + " cannot be greater than " + finishProperty.getTitle() + "."));
}
} else {
throw new Result("", new Exception(finishSetter ? //
/* */finishProperty.getTitle() + " cannot be specified without " + startProperty.getTitle() //
: startProperty.getTitle() + " cannot be empty when " + finishProperty.getTitle() + " is specified."));
}
}
}
/**
* A convenient method for validating two double properties that form a range [from;to].
*
* @param start
* @param finish
* @param startProperty
* @param finishProperty
* @param finishSetter
* @throws Result
*/
public static void validateDoubleRange(final Double start, final Double finish, final MetaProperty<Double> startProperty, final MetaProperty<Double> finishProperty, final boolean finishSetter) {
if (finish != null) {
if (start != null) {
if (start.compareTo(finish) > 0) { // after(finish)
throw new Result("", new Exception(finishSetter ? //
/* */finishProperty.getTitle() + " cannot be less than " + startProperty.getTitle() + "." //
: startProperty.getTitle() + " cannot be greater than " + finishProperty.getTitle() + "."));
}
} else {
throw new Result("", new Exception(finishSetter ? //
/* */finishProperty.getTitle() + " cannot be specified without " + startProperty.getTitle() //
: startProperty.getTitle() + " cannot be empty when " + finishProperty.getTitle() + " is specified."));
}
}
}
/**
* A convenient method for validating two money properties that form a range [from;to].
*
* @param start
* @param finish
* @param startProperty
* @param finishProperty
* @param finishSetter
* @throws Result
*/
public static void validateMoneyRange(final Money start, final Money finish, final MetaProperty<Money> startProperty, final MetaProperty<Money> finishProperty, final boolean finishSetter) {
if (finish != null) {
if (start != null) {
if (start.compareTo(finish) > 0) { // after(finish)
throw new Result("", new Exception(finishSetter ? //
/* */finishProperty.getTitle() + " cannot be less than " + startProperty.getTitle() + "." //
: startProperty.getTitle() + " cannot be greater than " + finishProperty.getTitle() + "."));
}
} else {
throw new Result("", new Exception(finishSetter ? //
/* */finishProperty.getTitle() + " cannot be specified without " + startProperty.getTitle() //
: startProperty.getTitle() + " cannot be empty when " + finishProperty.getTitle() + " is specified."));
}
}
}
/**
* Indicates whether type represents enumeration.
*
* @param type
* @return
*/
public static boolean isEnum(final Class<?> type) {
return Enum.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents "rangable" values like {@link Number}, {@link Money} or {@link Date}.
*
* @param type
* @return
*/
public static boolean isRangeType(final Class<?> type) {
return Number.class.isAssignableFrom(type) || Money.class.isAssignableFrom(type) || Date.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents boolean values.
*
* @param type
* @return
*/
public static boolean isBoolean(final Class<?> type) {
return boolean.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents date values.
*
* @param type
* @return
*/
public static boolean isDate(final Class<?> type) {
return Date.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents {@link DateTime} values.
*
* @param type
* @return
*/
public static boolean isDateTime(final Class<?> type) {
return DateTime.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents string values.
*
* @return
*/
public static boolean isString(final Class<?> type) {
return String.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents {@link AbstractEntity}-typed values.
*
* @return
*/
public static boolean isEntityType(final Class<?> type) {
return AbstractEntity.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents {@link ActivatableAbstractEntity}-typed values.
*
* @return
*/
public static boolean isActivatableEntityType(final Class<?> type) {
return ActivatableAbstractEntity.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents {@link Integer}-typed values.
*
* @return
*/
public static boolean isInteger(final Class<?> type) {
return Integer.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents either {@link BigDecimal} or {@link Money}-typed values.
*
* @return
*/
public static boolean isDecimal(final Class<?> type) {
return BigDecimal.class.isAssignableFrom(type) || Money.class.isAssignableFrom(type);
}
public static boolean isDynamicEntityKey(final Class<?> type) {
return DynamicEntityKey.class.isAssignableFrom(type);
}
/**
* Indicates that given entity type is mapped to database.
*
* @return
*/
public static boolean isPersistedEntityType(final Class<?> type) {
return type != null && isEntityType(type) && AnnotationReflector.getAnnotation(type, MapEntityTo.class) != null;
}
/**
* Determines if entity type represents one-2-one entity (e.g. VehicleFinancialDetails for Vehicle).
*
* @param entityType
* @return
*/
public static boolean isOneToOne(final Class<? extends AbstractEntity<?>> entityType) {
return isPersistedEntityType(getKeyType(entityType));
}
/**
* Identifies whether the entity type represent a composite entity.
*
* @param entityType
* @return
*/
public static <T extends AbstractEntity<?>> boolean isCompositeEntity(final Class<T> entityType) {
final KeyType keyAnnotation = AnnotationReflector.getAnnotation(entityType, KeyType.class);
if (keyAnnotation != null) {
return DynamicEntityKey.class.isAssignableFrom(keyAnnotation.value());
} else {
return false;
}
}
/**
* Indicates that given entity type is based on query model.
*
* @return
*/
public static <ET extends AbstractEntity<?>> boolean isQueryBasedEntityType(final Class<ET> type) {
return type != null && isEntityType(type) && AnnotationReflector.getAnnotation(type, MapEntityTo.class) == null && getEntityModelsOfQueryBasedEntityType(type).size() > 0;
}
/**
* Returns list of query models, which given entity type is based on (assuming it is after all).
*
* @param entityType
* @return
*/
public static <ET extends AbstractEntity<?>> List<EntityResultQueryModel<ET>> getEntityModelsOfQueryBasedEntityType(final Class<ET> entityType) {
final List<EntityResultQueryModel<ET>> result = new ArrayList<EntityResultQueryModel<ET>>();
try {
final Field exprField = entityType.getDeclaredField("model_");
exprField.setAccessible(true);
result.add((EntityResultQueryModel<ET>) exprField.get(null));
return result;
} catch (final Exception e) {
}
try {
final Field exprField = entityType.getDeclaredField("models_");
exprField.setAccessible(true);
result.addAll((List<EntityResultQueryModel<ET>>) exprField.get(null));
return result;
} catch (final Exception e) {
}
return result;
}
/**
* Indicates whether type represents {@link Collection}-typed values.
*
* @return
*/
public static boolean isCollectional(final Class<?> type) {
return Collection.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents {@link PropertyDescriptor}-typed values.
*
* @return
*/
public static boolean isPropertyDescriptor(final Class<?> type) {
return PropertyDescriptor.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents {@link AbstractUnionEntity}-typed values.
*
* @return
*/
public static boolean isUnionEntityType(final Class<?> type) {
return type != null && AbstractUnionEntity.class.isAssignableFrom(type);
}
/**
* Returns a deep copy of an object (all hierarchy of properties will be copied).<br>
* <br>
*
* <b>Important</b> : Depending on {@link ISerialiser} implementation, all classes that are used in passed object hierarchy should correspond some contract. For e.g. Kryo based
* serialiser requires all the classes to be registered and to have default constructor, simple java serialiser requires all the classes to implement {@link Serializable} etc.
*
* @param oldObj
* @param serialiser
* @return -- <code>null</code> if <code>oldObj</code> is <code>null</code>, otherwise a deep copy of <code>oldObj</code>.
*
*/
public static <T> T deepCopy(final T oldObj, final ISerialiser serialiser) {
if (oldObj == null) { // obviously return null if oldObj == null
return null;
}
try {
final byte[] serialised = serialiser.serialise(oldObj);
return serialiser.deserialise(serialised, (Class<T>) oldObj.getClass());
} catch (final Exception e) {
throw deepCopyError(oldObj, e);
}
// final ObjectOutputStream oos = null;
// final ObjectInputStream ois = null;
// try {
// final ByteArrayOutputStream bos = new ByteArrayOutputStream(); // A
// oos = new ObjectOutputStream(bos); // B
// // serialize and pass the object
// oos.writeObject(oldObj); // C
// oos.flush(); // D
// final ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); // E
// ois = new ObjectInputStream(bin); // F
// // return the new object
// return (T) ois.readObject(); // G
// } catch (final Exception e) {
// throw deepCopyError(oldObj, e);
// } finally {
// try {
// if (oos != null) {
// oos.close();
// }
// if (ois != null) {
// ois.close();
// }
// } catch (final IOException e2) {
// throw deepCopyError(oldObj, e2);
// }
// }
}
/**
* Returns the not enhanced copy of the specified enhancedEntity.
*
* @param enhancedEntity
* @return
*/
@SuppressWarnings("unchecked")
public static <T extends AbstractEntity<?>> T makeNotEnhanced(final T enhancedEntity) {
return enhancedEntity == null ? null : (T) enhancedEntity.copy(DynamicEntityClassLoader.getOriginalType(enhancedEntity.getType()));
}
/**
* Returns the not enhanced copy of the list of enhanced entities.
*
* @param enhancedEntities
* @return
*/
public static <T extends AbstractEntity<?>> List<T> makeNotEnhanced(final List<T> enhancedEntities) {
if (enhancedEntities == null) {
return null;
}
final List<T> notEnhnacedEntities = new ArrayList<>();
for (final T entry : enhancedEntities) {
notEnhnacedEntities.add(makeNotEnhanced(entry));
}
return notEnhnacedEntities;
}
protected static IllegalStateException deepCopyError(final Object oldObj, final Exception e) {
final String message = "The deep copy operation has been failed for object [" + oldObj + "]. Cause = [" + e.getMessage() + "].";
e.printStackTrace();
logger.error(message);
return new IllegalStateException(message);
}
/**
* A convenient method for extracting type information from all enum value for a specified enum type.
*
* @param <E>
* @param type
* @return
*/
public static <E extends Enum<E>> List<Class<?>> extractTypes(final Class<E> type) {
final List<Class<?>> result = new ArrayList<Class<?>>();
result.add(type);
final EnumSet<E> mnemonicEnumSet = EnumSet.allOf(type);
for (final E value : mnemonicEnumSet) {
result.add(value.getClass());
}
return result;
}
/**
* Splits dot.notated property in two parts: first level property and the rest of subproperties.
*
* @param dotNotatedPropName
* @return
*/
public static Pair<String, String> splitPropByFirstDot(final String dotNotatedPropName) {
final int firstDotIndex = dotNotatedPropName.indexOf(".");
if (firstDotIndex != -1) {
return new Pair<String, String>(dotNotatedPropName.substring(0, firstDotIndex), dotNotatedPropName.substring(firstDotIndex + 1));
} else {
return new Pair<String, String>(dotNotatedPropName, null);
}
}
/**
* Splits dot.notated property in two parts: last subproperty (as second part) and prior subproperties.
*
* @param dotNotatedPropName
* @return
*/
public static Pair<String, String> splitPropByLastDot(final String dotNotatedPropName) {
final int lastDotIndex = findLastDotInString(0, dotNotatedPropName);
if (lastDotIndex != -1) {
return new Pair<String, String>(dotNotatedPropName.substring(0, lastDotIndex - 1), dotNotatedPropName.substring(lastDotIndex));
} else {
return new Pair<String, String>(null, dotNotatedPropName);
}
}
private static int findLastDotInString(final int fromPosition, final String dotNotatedPropName) {
final int nextDotIndex = dotNotatedPropName.indexOf(".", fromPosition);
if (nextDotIndex != -1) {
return findLastDotInString(nextDotIndex + 1, dotNotatedPropName);
} else {
return fromPosition;
}
}
/**
* Returns true if the provided <code>dotNotationProp</code> is a valid property in the specified entity type.
*
* @param type
* @param dotNotationProp
* @return
*/
public static boolean isProperty(final Class<?> type, final String dotNotationProp) {
try {
return AnnotationReflector.isAnnotationPresent(Finder.findFieldByName(type, dotNotationProp), IsProperty.class);
} catch (final Exception ex) {
logger.warn(ex);
return false;
}
}
/**
* Retrieves all persisted properties fields within given entity type
*
* @param entityType
* @return
*/
public static List<Field> getRealProperties(final Class<? extends AbstractEntity<?>> entityType) {
final List<Field> result = new ArrayList<>();
for (final Field propField : Finder.findRealProperties(entityType)) { //, MapTo.class
if (!(DESC.equals(propField.getName()) && !hasDescProperty(entityType))) {
result.add(propField);
}
}
return result;
}
public static boolean hasDescProperty(final Class<? extends AbstractEntity<?>> entityType) {
return AnnotationReflector.isAnnotationPresentForClass(DescTitle.class, entityType);
}
/**
* Retrieves all collectional properties fields within given entity type
*
* @param entityType
* @return
*/
public static List<Field> getCollectionalProperties(final Class<? extends AbstractEntity<?>> entityType) {
final List<Field> result = new ArrayList<>();
for (final Field propField : Finder.findRealProperties(entityType)) {
if (Collection.class.isAssignableFrom(propField.getType()) && Finder.hasLinkProperty(entityType, propField.getName())) {
result.add(propField);
}
}
return result;
}
public static class BigDecimalWithTwoPlaces {
};
/**
* Produces list of props that should be added to order model instead of composite key.
*
* @param entityType
* @param prefix
* @return
*/
public static List<String> getOrderPropsFromCompositeEntityKey(final Class<? extends AbstractEntity<DynamicEntityKey>> entityType, final String prefix) {
final List<String> result = new ArrayList<>();
final List<Field> keyProps = Finder.getKeyMembers(entityType);
for (final Field keyMemberProp : keyProps) {
if (DynamicEntityKey.class.equals(getKeyType(keyMemberProp.getType()))) {
result.addAll(getOrderPropsFromCompositeEntityKey((Class<AbstractEntity<DynamicEntityKey>>) keyMemberProp.getType(), (prefix != null ? prefix + "." : "")
+ keyMemberProp.getName()));
} else if (isEntityType(keyMemberProp.getType())) {
result.add((prefix != null ? prefix + "." : "") + keyMemberProp.getName() + ".key");
} else {
result.add((prefix != null ? prefix + "." : "") + keyMemberProp.getName());
}
}
return result;
}
public static SortedSet<String> getFirstLevelProps(final Set<String> allProps) {
final SortedSet<String> result = new TreeSet<String>();
for (final String prop : allProps) {
result.add(splitPropByFirstDot(prop).getKey());
}
return result;
}
/**
* A convenient method for constructing a pair of property and its title as defined at the entity type level.
*
* @param entityType
* @param propName
* @return
*/
public static Pair<String, String> titleAndProp(final Class<? extends AbstractEntity<?>> entityType, final String propName) {
return new Pair<>(TitlesDescsGetter.getTitleAndDesc(propName, entityType).getKey(), propName);
}
/**
* Returns <code>true</code> if the original value is stale according to fresh value for current version of entity, <code>false</code> otherwise.
*
* @param originalValue
* -- original value for the property of stale entity
* @param freshValue
* -- fresh value for the property of current (fresh) version of entity
* @return
*/
public static boolean isStale(final Object originalValue, final Object freshValue) {
return !EntityUtils.equalsEx(freshValue, originalValue);
}
/**
* Returns <code>true</code> if the new value for stale entity conflicts with fresh value for current version of entity, <code>false</code> otherwise.
*
* @param staleNewValue
* -- new value for the property of stale entity
* @param staleOriginalValue
* -- original value for the property of stale entity
* @param freshValue
* -- fresh value for the property of current (fresh) version of entity
* @return
*/
public static boolean isConflicting(final Object staleNewValue, final Object staleOriginalValue, final Object freshValue) {
// old implementation:
// return (freshValue == null && staleOriginalValue != null && staleNewValue != null) ||
// (freshValue != null && staleOriginalValue == null && staleNewValue == null) ||
// (freshValue != null && !freshValue.equals(staleOriginalValue) && !freshValue.equals(staleNewValue));
return isStale(staleOriginalValue, freshValue) && !EntityUtils.equalsEx(staleNewValue, freshValue);
}
/**
* Creates empty {@link IFetchProvider} for concrete <code>entityType</code> with instrumentation.
*
* @param entityType
* @param instrumented
* @return
*/
public static <T extends AbstractEntity<?>> IFetchProvider<T> fetch(final Class<T> entityType, final boolean instumented) {
return FetchProviderFactory.createDefaultFetchProvider(entityType, instumented);
}
public static <T extends AbstractEntity<?>> IFetchProvider<T> fetch(final Class<T> entityType) {
return FetchProviderFactory.createDefaultFetchProvider(entityType, false);
}
/**
* Creates {@link IFetchProvider} for concrete <code>entityType</code> with 'key' and 'desc' (analog of {@link EntityQueryUtils#fetchKeyAndDescOnly(Class)}) with instrumentation.
*
* @param entityType
* @param instrumented
* @return
*/
public static <T extends AbstractEntity<?>> IFetchProvider<T> fetchWithKeyAndDesc(final Class<T> entityType, final boolean instrumented) {
return FetchProviderFactory.createFetchProviderWithKeyAndDesc(entityType, instrumented);
}
public static <T extends AbstractEntity<?>> IFetchProvider<T> fetchWithKeyAndDesc(final Class<T> entityType) {
return FetchProviderFactory.createFetchProviderWithKeyAndDesc(entityType, false);
}
/**
* Creates empty {@link IFetchProvider} for concrete <code>entityType</code> <b>without</b> instrumentation.
*
* @param entityType
* @return
*/
public static <T extends AbstractEntity<?>> IFetchProvider<T> fetchNotInstrumented(final Class<T> entityType) {
return FetchProviderFactory.createDefaultFetchProvider(entityType, false);
}
/**
* Creates {@link IFetchProvider} for concrete <code>entityType</code> with 'key' and 'desc' (analog of {@link EntityQueryUtils#fetchKeyAndDescOnly(Class)}) <b>without</b> instrumentation.
*
* @param entityType
* @return
*/
public static <T extends AbstractEntity<?>> IFetchProvider<T> fetchNotInstrumentedWithKeyAndDesc(final Class<T> entityType) {
return FetchProviderFactory.createFetchProviderWithKeyAndDesc(entityType, false);
}
/**
* Tries to perform shallow copy of collectional value. If unsuccessful, throws unsuccessful {@link Result} describing the error.
*
* @param value
* @return
*/
public static <T> T copyCollectionalValue(final T value) {
if (value == null) {
return null; // return (null) copy
}
try {
final Collection<?> collection = (Collection<?>) value;
// try to obtain empty constructor to perform shallow copying of collection
final Constructor<? extends Collection> constructor = collection.getClass().getConstructor();
final Collection copy = constructor.newInstance();
copy.addAll(collection);
// return non-empty copy
return (T) copy;
} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
logger.error(e.getMessage(), e);
throw Result.failure(String.format("Collection copying has been failed. Type [%s]. Exception [%s].", value.getClass(), e.getMessage())); // throw result indicating the failure of copying
}
}
/**
* The most generic and most straightforward function to copy properties from instance <code>fromEntity</code> to <code>toEntity</code>.
*
* @param fromEntity
* @param toEntity
* @param skipProperties -- a sequence of property names, which may include ID and VERSION.
*/
public static <T extends AbstractEntity> void copy(final AbstractEntity<?> fromEntity, final T toEntity, final String... skipProperties) {
// convert an array with property names to be skipped into a set for more efficient use
final Set<String> skipPropertyName = new HashSet<>(Arrays.asList(skipProperties));
// Under certain circumstances copying happens for an uninstrumented entity instance
// In such cases there would be no meta-properties, and copying would fail.
// Therefore, it is important to perform ad-hoc property retrieval via reflection.
final List<String> realProperties = Finder.streamRealProperties(fromEntity.getType()).map(field -> field.getName()).collect(Collectors.toList());
// Need to add ID and VERSION in order for them to be treated as entity properties
// They will get skipped if provided as part of skipProperties array
realProperties.add(ID);
realProperties.add(VERSION);
// Copy each identified property, which is not proxied or skipped into a new instance.
realProperties.stream()
.filter(name -> !skipPropertyName.contains(name))
.filter(propName -> !fromEntity.proxiedPropertyNames().contains(propName))
.forEach(propName -> {
if (KEY.equals(propName) && toEntity.getKeyType().equals(fromEntity.getKeyType()) && DynamicEntityKey.class.isAssignableFrom(fromEntity.getKeyType())) {
toEntity.setKey(new DynamicEntityKey(toEntity));
} else {
try {
toEntity.set(propName, fromEntity.get(propName));
} catch (final Exception e) {
logger.trace(format("Setter for property %s did not succeed during coping.", propName), e);
}
}
});
}
} | platform-pojo-bl/src/main/java/ua/com/fielden/platform/utils/EntityUtils.java | package ua.com.fielden.platform.utils;
import static java.lang.String.format;
import static ua.com.fielden.platform.entity.AbstractEntity.DESC;
import static ua.com.fielden.platform.entity.AbstractEntity.ID;
import static ua.com.fielden.platform.entity.AbstractEntity.KEY;
import static ua.com.fielden.platform.entity.AbstractEntity.VERSION;
import static ua.com.fielden.platform.reflection.AnnotationReflector.getKeyType;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.AbstractUnionEntity;
import ua.com.fielden.platform.entity.ActivatableAbstractEntity;
import ua.com.fielden.platform.entity.DynamicEntityKey;
import ua.com.fielden.platform.entity.annotation.DescTitle;
import ua.com.fielden.platform.entity.annotation.IsProperty;
import ua.com.fielden.platform.entity.annotation.KeyType;
import ua.com.fielden.platform.entity.annotation.MapEntityTo;
import ua.com.fielden.platform.entity.fetch.FetchProviderFactory;
import ua.com.fielden.platform.entity.fetch.IFetchProvider;
import ua.com.fielden.platform.entity.meta.MetaProperty;
import ua.com.fielden.platform.entity.meta.PropertyDescriptor;
import ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils;
import ua.com.fielden.platform.entity.query.model.EntityResultQueryModel;
import ua.com.fielden.platform.error.Result;
import ua.com.fielden.platform.reflection.AnnotationReflector;
import ua.com.fielden.platform.reflection.Finder;
import ua.com.fielden.platform.reflection.TitlesDescsGetter;
import ua.com.fielden.platform.reflection.asm.impl.DynamicEntityClassLoader;
import ua.com.fielden.platform.serialisation.api.ISerialiser;
import ua.com.fielden.platform.types.Money;
import ua.com.fielden.platform.utils.ConverterFactory.Converter;
public class EntityUtils {
private final static Logger logger = Logger.getLogger(EntityUtils.class);
/** Private default constructor to prevent instantiation. */
private EntityUtils() {
}
/**
* dd/MM/yyyy format instance
*/
public static final String dateWithoutTimeFormat = "dd/MM/yyyy";
/**
* Convenient method for value to {@link String} conversion
*
* @param value
* @param valueType
* @return
*/
public static String toString(final Object value, final Class<?> valueType) {
if (value == null) {
return "";
}
if (valueType == Integer.class || valueType == int.class) {
return NumberFormat.getInstance().format(value);
} else if (Number.class.isAssignableFrom(valueType) || valueType == double.class) {
return NumberFormat.getInstance().format(new BigDecimal(value.toString()));
} else if (valueType == Date.class || valueType == DateTime.class) {
final Date date = valueType == Date.class ? (Date) value : ((DateTime) value).toDate();
return new SimpleDateFormat(dateWithoutTimeFormat).format(date) + " " + DateFormat.getTimeInstance(DateFormat.SHORT).format(date);
} else if (Money.class.isAssignableFrom(valueType)) {
return value instanceof Number ? new Money(value.toString()).toString() : value.toString();
} else if (valueType == BigDecimalWithTwoPlaces.class) {
return value instanceof Number ? String.format("%,10.2f", value) : value.toString();
} else {
return value.toString();
}
}
/**
* Invokes method {@link #toString(Object, Class)} with the second argument being assigned as value's class.
*
* @param value
* @return
*/
public static String toString(final Object value) {
if (value == null) {
return "";
}
return toString(value, value.getClass());
}
/**
* Null-safe comparator.
*
* @param o1
* @param o2
* @return
*/
public static <T> int safeCompare(final Comparable<T> c1, final T c2) {
if (c1 == null && c2 == null) {
return 0;
} else if (c1 == null) {
return -1;
} else if (c2 == null) {
return 1;
} else {
return c1.compareTo(c2);
}
}
/**
* Null-safe equals based on the {@link AbstractEntity}'s id property. If id property is not present in both entities then default equals for entities will be called.
*
* @param entity1
* @param entity2
* @return
*/
public static boolean areEqual(final AbstractEntity<?> entity1, final AbstractEntity<?> entity2) {
if (entity1 != null && entity2 != null) {
if (entity1.getId() == null && entity2.getId() == null) {
return entity1.equals(entity2);
} else {
return equalsEx(entity1.getId(), entity2.getId());
}
}
return entity1 == entity2;
}
/**
* A convenient method to safely compare entity values even if they are <code>null</code>.
* <p>
* The <code>null</code> value is considered to be smaller than a non-null value.
*
* @param o1
* @param o2
* @return
*/
@SuppressWarnings("rawtypes")
public static <T extends AbstractEntity<K>, K extends Comparable> int compare(final T o1, final T o2) {
if (o1 == o2) {
return 0;
} else if (o1 == null && o2 != null) {
return -1;
} else if (o1 != null && o2 == null) {
return 1;
} else {
return o1.compareTo(o2);
}
}
/**
* Returns value that indicates whether entity is among entities. The equality comparison is based on {@link #areEquals(AbstractEntity, AbstractEntity)} method
*
* @param entities
* @param entity
* @return
*/
public static <T extends AbstractEntity<?>> boolean containsById(final List<T> entities, final T entity) {
for (final AbstractEntity<?> e : entities) {
if (areEqual(e, entity)) {
return true;
}
}
return false;
}
/**
* Returns index of the entity in the entities list. The equality comparison is based on the {@link #areEquals(AbstractEntity, AbstractEntity)} method.
*
* @param entities
* @param entity
* @return
*/
public static <T extends AbstractEntity<?>> int indexOfById(final List<T> entities, final T entity) {
for (int index = 0; index < entities.size(); index++) {
if (areEqual(entities.get(index), entity)) {
return index;
}
}
return -1;
}
/**
* This method chooses appropriate Converter for any types of property. Even for properties of [AbstractEntity's descendant type] or List<[AbstractEntity's descendant type]> or
* List<String>
*
* @param entity
* @param propertyName
* @return
*/
public static Converter chooseConverterBasedUponPropertyType(final AbstractEntity<?> entity, final String propertyName, final ShowingStrategy showingStrategy) {
final MetaProperty<?> metaProperty = Finder.findMetaProperty(entity, propertyName);
return chooseConverterBasedUponPropertyType(metaProperty, showingStrategy);
}
/**
* this method chooses appropriate Converter for any types of property. Even for properties of [AbstractEntity's descendant type] or List<[AbstractEntity's descendant type]> or
* List<String>
*
* @param entity
* @param propertyName
* @return
*/
public static Converter chooseConverterBasedUponPropertyType(final Class<?> propertyType, final Class<?> collectionType, final ShowingStrategy showingStrategy) {
if (propertyType.equals(String.class)) {
return null;
} else if (Number.class.isAssignableFrom(propertyType)) {
return ConverterFactory.createNumberConverter();
} else if (Money.class.isAssignableFrom(propertyType)) {
return ConverterFactory.createMoneyConverter();
} else if (Date.class.equals(propertyType) || DateTime.class.equals(propertyType)) {
return ConverterFactory.createDateConverter();
} else if (AbstractEntity.class.isAssignableFrom(propertyType)) {
return ConverterFactory.createAbstractEntityOrListConverter(showingStrategy);
} else if (List.class.isAssignableFrom(propertyType)) {
if (collectionType != null) {
final Class<?> typeArgClass = collectionType;
if (AbstractEntity.class.isAssignableFrom(typeArgClass)) {
return ConverterFactory.createAbstractEntityOrListConverter(showingStrategy);
} else if (typeArgClass.equals(String.class)) {
return ConverterFactory.createStringListConverter();
} else {
System.out.println(new Exception("listType actualTypeArgument is not String or descendant of AbstractEntity!"));
return null;
}
} else {
System.out.println(new Exception("listType is not Parameterized???!!"));
return null;
}
} else if (Enum.class.isAssignableFrom(propertyType)) {
return ConverterFactory.createTrivialConverter();
} else {
return null;
}
}
/**
* Does the same as {@link #chooseConverterBasedUponPropertyType(AbstractEntity, String)}
*
* @param metaProperty
* @return
*/
public static Converter chooseConverterBasedUponPropertyType(final MetaProperty<?> metaProperty, final ShowingStrategy showingStrategy) {
return chooseConverterBasedUponPropertyType(metaProperty.getType(), metaProperty.getPropertyAnnotationType(), showingStrategy);
}
/**
* Obtains {@link MetaProperty} using {@link #findFirstFailedMetaProperty(AbstractEntity, String)} and returns {@link #getLabelText(MetaProperty, boolean)}
*
* @return the subject's text value
* @throws MissingConverterException
* @throws ClassCastException
* if the subject value is not a String
*/
public static String getLabelText(final AbstractEntity<?> entity, final String propertyName, final ShowingStrategy showingStrategy) {
final MetaProperty<?> metaProperty = findFirstFailedMetaProperty(entity, propertyName);
return getLabelText(metaProperty, false, showingStrategy);
}
public enum ShowingStrategy {
KEY_ONLY, DESC_ONLY, KEY_AND_DESC
}
/**
* Gets converter for passed {@link MetaProperty} with showKeyOnly param and returns {@link #getLabelText(MetaProperty, Converter)}
*
* @param metaProperty
* @param showKeyOnly
* @return
*/
public static String getLabelText(final MetaProperty<?> metaProperty, final boolean returnEmptyStringIfInvalid, final ShowingStrategy showingStrategy) {
final ConverterFactory.Converter converter = chooseConverterBasedUponPropertyType(metaProperty, showingStrategy);
return getLabelText(metaProperty, returnEmptyStringIfInvalid, converter);
}
/**
* Returns text value for passed {@link MetaProperty} using passed {@link Converter}.
*
* @param returnEmptyStringIfInvalid
* - if {@link Boolean#TRUE} passed as this parameter, then empty string will be returned if passed {@link MetaProperty} is invalid (converter is not used at all in
* this case). Otherwise {@link MetaProperty#getLastInvalidValue()} will be obtained from invalid {@link MetaProperty}, converted using passed {@link Converter} and
* returned.
*
* @return the subject's text value
* @throws MissingConverterException
* @throws ClassCastException
* if the subject value is not a String
*/
public static String getLabelText(final MetaProperty<?> metaProperty, final boolean returnEmptyStringIfInvalid, final Converter converter) {
if (metaProperty != null) {
// hierarchy is valid, only the last property could be invalid
final Object value = metaProperty.getLastAttemptedValue();
if (!metaProperty.isValid() && returnEmptyStringIfInvalid) {
return "";
}
return getLabelText(value, converter);
} else {
// some property (not the last) is invalid, thus showing empty string
return "";
}
}
/**
* Returns label text representation of value using specified converter.
*
* @param value
* @param converter
* @return
*/
public static String getLabelText(final Object value, final Converter converter) {
if (value != null && !value.getClass().equals(String.class) && converter == null) {
return value.toString();
}
final String str = converter != null ? converter.convertToString(value) : (String) value;
return str == null ? "" : str;
}
/**
* Formats passeed value according to its type.
*
* @param value
* @param valueType
* @return
*/
public static String formatTooltip(final Object value, final Class<?> valueType) {
if (value == null) {
return "";
}
if (valueType == Integer.class) {
return NumberFormat.getInstance().format(value);
} else if (Number.class.isAssignableFrom(valueType)) {
return NumberFormat.getInstance().format(new BigDecimal(value.toString()));
} else if (valueType == Date.class || valueType == DateTime.class) {
final Object convertedValue = value instanceof DateTime ? ((DateTime) value).toDate() : value;
return new SimpleDateFormat(dateWithoutTimeFormat).format(convertedValue) + " " + DateFormat.getTimeInstance(DateFormat.SHORT).format(convertedValue);
} else {
return value.toString();
}
}
/**
* Checks and answers if the two objects are both {@code null} or equal.
*
* <pre>
* #equals(null, null) == true
* #equals("Hi", "Hi") == true
* #equals("Hi", null) == false
* #equals(null, "Hi") == false
* #equals("Hi", "Ho") == false
* </pre>
*
* @param o1
* the first object to compare
* @param o2
* the second object to compare
* @return boolean {@code true} if and only if both objects are {@code null} or equal
*/
public static boolean equalsEx(final Object o1, final Object o2) {
return o1 == o2 || o1 != null && o2 != null && o1.equals(o2);
}
/**
* Returns current value(if property is valid, then its value, otherwise last incorrect value of corresponding meta-property) of property of passed entity.<br>
* <br>
* Note : does not support dot-notated property names.
*
* @param entity
* @param propertyName
* @return
*/
public static Object getCurrentValue(final AbstractEntity<?> entity, final String propertyName) {
final MetaProperty<?> metaProperty = entity.getProperty(propertyName);
if (metaProperty == null) {
throw new IllegalArgumentException("Couldn't find meta-property named '" + propertyName + "' in " + entity);
} else {
return metaProperty.isValid() ? entity.get(propertyName) : metaProperty.getLastInvalidValue();
}
}
/**
* Returns either {@link MetaProperty} corresponding to last property in <code>propertyName</code> if all previous {@link MetaProperty}ies are valid and without warnings, or
* first failed {@link MetaProperty} or one with warning.
*
* @param entity
* @param propertyName
* @return
*/
public static MetaProperty<?> findFirstFailedMetaProperty(final AbstractEntity<?> entity, final String propertyName) {
final List<MetaProperty<?>> metaProperties = Finder.findMetaProperties(entity, propertyName);
return findFirstFailedMetaProperty(metaProperties);
}
/**
* Does the same as method {@link #findFirstFailedMetaProperty(AbstractEntity, String)} but already on the provided list of {@link MetaProperty}s.
*
* @param metaProperties
* @return
*/
public static MetaProperty<?> findFirstFailedMetaProperty(final List<MetaProperty<?>> metaProperties) {
MetaProperty<?> firstFailedMetaProperty = metaProperties.get(metaProperties.size() - 1);
for (int i = 0; i < metaProperties.size(); i++) {
final MetaProperty<?> metaProperty = metaProperties.get(i);
if (!metaProperty.isValid() || metaProperty.hasWarnings()) {
firstFailedMetaProperty = metaProperty;
break;
}
}
return firstFailedMetaProperty;
}
/**
* This method throws Result (so can be used to specify DYNAMIC validation inside the date setters) when the specified finish/start dates are invalid together.
*
* @param start
* @param finish
* @param fieldPrefix
* - the prefix for the field in the error message for e.g. "actual" or "early".
* @param finishSetter
* - use true if validation have to be performed inside the "finish" date setter, false - inside the "start" date setter
* @throws Result
*/
public static void validateDateRange(final Date start, final Date finish, final MetaProperty<Date> startProperty, final MetaProperty<Date> finishProperty, final boolean finishSetter) {
if (finish != null) {
if (start != null) {
if (start.after(finish)) {
throw Result.failure(finishSetter
? format("Property [%s] (value [%s]) cannot be before property [%s] (value [%s]).", finishProperty.getTitle(), toString(finish) , startProperty.getTitle(), toString(start))
: format("Property [%s] (value [%s]) cannot be after property [%s] (value [%s]).", startProperty.getTitle(), toString(start), finishProperty.getTitle(), toString(finish)));
}
} else {
throw Result.failure(finishSetter
? format("Property [%s] (value [%s]) cannot be specified without property [%s].", finishProperty.getTitle(), finish, startProperty.getTitle())
: format("Property [%s] cannot be empty if property [%s] (value [%s]) if specified.", startProperty.getTitle(), finishProperty.getTitle(), finish));
}
}
}
/**
* This method throws Result (so can be used to specify DYNAMIC validation inside the date setters) when the specified finish/start date times are invalid together.
*
* @param start
* @param finish
* @param fieldPrefix
* - the prefix for the field in the error message for e.g. "actual" or "early".
* @param finishSetter
* - use true if validation have to be performed inside the "finish" date setter, false - inside the "start" date setter
* @throws Result
*/
public static void validateDateTimeRange(final DateTime start, final DateTime finish, final MetaProperty<DateTime> startProperty, final MetaProperty<DateTime> finishProperty, final boolean finishSetter) {
if (finish != null) {
if (start != null) {
if (start.isAfter(finish)) {
throw Result.failure(finishSetter
? format("Property [%s] (value [%s]) cannot be before property [%s] (value [%s]).", finishProperty.getTitle(), toString(finish) , startProperty.getTitle(), toString(start))
: format("Property [%s] (value [%s]) cannot be after property [%s] (value [%s]).", startProperty.getTitle(), toString(start), finishProperty.getTitle(), toString(finish)));
}
} else {
throw Result.failure(finishSetter
? format("Property [%s] (value [%s]) cannot be specified without property [%s].", finishProperty.getTitle(), finish, startProperty.getTitle())
: format("Property [%s] cannot be empty if property [%s] (value [%s]) if specified.", startProperty.getTitle(), finishProperty.getTitle(), finish));
}
}
}
/**
* A convenient method for validating two integer properties that form a range [from;to].
* <p>
* Note, the use use Of Number is not possible because it does not implement interface Comparable due to valid reasons. See
* http://stackoverflow.com/questions/480632/why-doesnt-java-lang-number-implement-comparable from more.
*
* @param start
* @param finish
* @param startProperty
* @param finishProperty
* @param finishSetter
* @throws Result
*/
public static void validateIntegerRange(final Integer start, final Integer finish, final MetaProperty<Integer> startProperty, final MetaProperty<Integer> finishProperty, final boolean finishSetter) {
if (finish != null) {
if (start != null) {
if (start.compareTo(finish) > 0) { // after(finish)
throw new Result("", new Exception(finishSetter ? //
/* */finishProperty.getTitle() + " cannot be less than " + startProperty.getTitle() + "." //
: startProperty.getTitle() + " cannot be greater than " + finishProperty.getTitle() + "."));
}
} else {
throw new Result("", new Exception(finishSetter ? //
/* */finishProperty.getTitle() + " cannot be specified without " + startProperty.getTitle() //
: startProperty.getTitle() + " cannot be empty when " + finishProperty.getTitle() + " is specified."));
}
}
}
/**
* A convenient method for validating two double properties that form a range [from;to].
*
* @param start
* @param finish
* @param startProperty
* @param finishProperty
* @param finishSetter
* @throws Result
*/
public static void validateDoubleRange(final Double start, final Double finish, final MetaProperty<Double> startProperty, final MetaProperty<Double> finishProperty, final boolean finishSetter) {
if (finish != null) {
if (start != null) {
if (start.compareTo(finish) > 0) { // after(finish)
throw new Result("", new Exception(finishSetter ? //
/* */finishProperty.getTitle() + " cannot be less than " + startProperty.getTitle() + "." //
: startProperty.getTitle() + " cannot be greater than " + finishProperty.getTitle() + "."));
}
} else {
throw new Result("", new Exception(finishSetter ? //
/* */finishProperty.getTitle() + " cannot be specified without " + startProperty.getTitle() //
: startProperty.getTitle() + " cannot be empty when " + finishProperty.getTitle() + " is specified."));
}
}
}
/**
* A convenient method for validating two money properties that form a range [from;to].
*
* @param start
* @param finish
* @param startProperty
* @param finishProperty
* @param finishSetter
* @throws Result
*/
public static void validateMoneyRange(final Money start, final Money finish, final MetaProperty<Money> startProperty, final MetaProperty<Money> finishProperty, final boolean finishSetter) {
if (finish != null) {
if (start != null) {
if (start.compareTo(finish) > 0) { // after(finish)
throw new Result("", new Exception(finishSetter ? //
/* */finishProperty.getTitle() + " cannot be less than " + startProperty.getTitle() + "." //
: startProperty.getTitle() + " cannot be greater than " + finishProperty.getTitle() + "."));
}
} else {
throw new Result("", new Exception(finishSetter ? //
/* */finishProperty.getTitle() + " cannot be specified without " + startProperty.getTitle() //
: startProperty.getTitle() + " cannot be empty when " + finishProperty.getTitle() + " is specified."));
}
}
}
/**
* Indicates whether type represents enumeration.
*
* @param type
* @return
*/
public static boolean isEnum(final Class<?> type) {
return Enum.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents "rangable" values like {@link Number}, {@link Money} or {@link Date}.
*
* @param type
* @return
*/
public static boolean isRangeType(final Class<?> type) {
return Number.class.isAssignableFrom(type) || Money.class.isAssignableFrom(type) || Date.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents boolean values.
*
* @param type
* @return
*/
public static boolean isBoolean(final Class<?> type) {
return boolean.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents date values.
*
* @param type
* @return
*/
public static boolean isDate(final Class<?> type) {
return Date.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents {@link DateTime} values.
*
* @param type
* @return
*/
public static boolean isDateTime(final Class<?> type) {
return DateTime.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents string values.
*
* @return
*/
public static boolean isString(final Class<?> type) {
return String.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents {@link AbstractEntity}-typed values.
*
* @return
*/
public static boolean isEntityType(final Class<?> type) {
return AbstractEntity.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents {@link ActivatableAbstractEntity}-typed values.
*
* @return
*/
public static boolean isActivatableEntityType(final Class<?> type) {
return ActivatableAbstractEntity.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents {@link Integer}-typed values.
*
* @return
*/
public static boolean isInteger(final Class<?> type) {
return Integer.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents either {@link BigDecimal} or {@link Money}-typed values.
*
* @return
*/
public static boolean isDecimal(final Class<?> type) {
return BigDecimal.class.isAssignableFrom(type) || Money.class.isAssignableFrom(type);
}
public static boolean isDynamicEntityKey(final Class<?> type) {
return DynamicEntityKey.class.isAssignableFrom(type);
}
/**
* Indicates that given entity type is mapped to database.
*
* @return
*/
public static boolean isPersistedEntityType(final Class<?> type) {
return type != null && isEntityType(type) && AnnotationReflector.getAnnotation(type, MapEntityTo.class) != null;
}
/**
* Determines if entity type represents one-2-one entity (e.g. VehicleFinancialDetails for Vehicle).
*
* @param entityType
* @return
*/
public static boolean isOneToOne(final Class<? extends AbstractEntity<?>> entityType) {
return isPersistedEntityType(getKeyType(entityType));
}
/**
* Identifies whether the entity type represent a composite entity.
*
* @param entityType
* @return
*/
public static <T extends AbstractEntity<?>> boolean isCompositeEntity(final Class<T> entityType) {
final KeyType keyAnnotation = AnnotationReflector.getAnnotation(entityType, KeyType.class);
if (keyAnnotation != null) {
return DynamicEntityKey.class.isAssignableFrom(keyAnnotation.value());
} else {
return false;
}
}
/**
* Indicates that given entity type is based on query model.
*
* @return
*/
public static <ET extends AbstractEntity<?>> boolean isQueryBasedEntityType(final Class<ET> type) {
return type != null && isEntityType(type) && AnnotationReflector.getAnnotation(type, MapEntityTo.class) == null && getEntityModelsOfQueryBasedEntityType(type).size() > 0;
}
/**
* Returns list of query models, which given entity type is based on (assuming it is after all).
*
* @param entityType
* @return
*/
public static <ET extends AbstractEntity<?>> List<EntityResultQueryModel<ET>> getEntityModelsOfQueryBasedEntityType(final Class<ET> entityType) {
final List<EntityResultQueryModel<ET>> result = new ArrayList<EntityResultQueryModel<ET>>();
try {
final Field exprField = entityType.getDeclaredField("model_");
exprField.setAccessible(true);
result.add((EntityResultQueryModel<ET>) exprField.get(null));
return result;
} catch (final Exception e) {
}
try {
final Field exprField = entityType.getDeclaredField("models_");
exprField.setAccessible(true);
result.addAll((List<EntityResultQueryModel<ET>>) exprField.get(null));
return result;
} catch (final Exception e) {
}
return result;
}
/**
* Indicates whether type represents {@link Collection}-typed values.
*
* @return
*/
public static boolean isCollectional(final Class<?> type) {
return Collection.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents {@link PropertyDescriptor}-typed values.
*
* @return
*/
public static boolean isPropertyDescriptor(final Class<?> type) {
return PropertyDescriptor.class.isAssignableFrom(type);
}
/**
* Indicates whether type represents {@link AbstractUnionEntity}-typed values.
*
* @return
*/
public static boolean isUnionEntityType(final Class<?> type) {
return type != null && AbstractUnionEntity.class.isAssignableFrom(type);
}
/**
* Returns a deep copy of an object (all hierarchy of properties will be copied).<br>
* <br>
*
* <b>Important</b> : Depending on {@link ISerialiser} implementation, all classes that are used in passed object hierarchy should correspond some contract. For e.g. Kryo based
* serialiser requires all the classes to be registered and to have default constructor, simple java serialiser requires all the classes to implement {@link Serializable} etc.
*
* @param oldObj
* @param serialiser
* @return -- <code>null</code> if <code>oldObj</code> is <code>null</code>, otherwise a deep copy of <code>oldObj</code>.
*
*/
public static <T> T deepCopy(final T oldObj, final ISerialiser serialiser) {
if (oldObj == null) { // obviously return null if oldObj == null
return null;
}
try {
final byte[] serialised = serialiser.serialise(oldObj);
return serialiser.deserialise(serialised, (Class<T>) oldObj.getClass());
} catch (final Exception e) {
throw deepCopyError(oldObj, e);
}
// final ObjectOutputStream oos = null;
// final ObjectInputStream ois = null;
// try {
// final ByteArrayOutputStream bos = new ByteArrayOutputStream(); // A
// oos = new ObjectOutputStream(bos); // B
// // serialize and pass the object
// oos.writeObject(oldObj); // C
// oos.flush(); // D
// final ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); // E
// ois = new ObjectInputStream(bin); // F
// // return the new object
// return (T) ois.readObject(); // G
// } catch (final Exception e) {
// throw deepCopyError(oldObj, e);
// } finally {
// try {
// if (oos != null) {
// oos.close();
// }
// if (ois != null) {
// ois.close();
// }
// } catch (final IOException e2) {
// throw deepCopyError(oldObj, e2);
// }
// }
}
/**
* Returns the not enhanced copy of the specified enhancedEntity.
*
* @param enhancedEntity
* @return
*/
@SuppressWarnings("unchecked")
public static <T extends AbstractEntity<?>> T makeNotEnhanced(final T enhancedEntity) {
return enhancedEntity == null ? null : (T) enhancedEntity.copy(DynamicEntityClassLoader.getOriginalType(enhancedEntity.getType()));
}
/**
* Returns the not enhanced copy of the list of enhanced entities.
*
* @param enhancedEntities
* @return
*/
public static <T extends AbstractEntity<?>> List<T> makeNotEnhanced(final List<T> enhancedEntities) {
if (enhancedEntities == null) {
return null;
}
final List<T> notEnhnacedEntities = new ArrayList<>();
for (final T entry : enhancedEntities) {
notEnhnacedEntities.add(makeNotEnhanced(entry));
}
return notEnhnacedEntities;
}
protected static IllegalStateException deepCopyError(final Object oldObj, final Exception e) {
final String message = "The deep copy operation has been failed for object [" + oldObj + "]. Cause = [" + e.getMessage() + "].";
e.printStackTrace();
logger.error(message);
return new IllegalStateException(message);
}
/**
* A convenient method for extracting type information from all enum value for a specified enum type.
*
* @param <E>
* @param type
* @return
*/
public static <E extends Enum<E>> List<Class<?>> extractTypes(final Class<E> type) {
final List<Class<?>> result = new ArrayList<Class<?>>();
result.add(type);
final EnumSet<E> mnemonicEnumSet = EnumSet.allOf(type);
for (final E value : mnemonicEnumSet) {
result.add(value.getClass());
}
return result;
}
/**
* Splits dot.notated property in two parts: first level property and the rest of subproperties.
*
* @param dotNotatedPropName
* @return
*/
public static Pair<String, String> splitPropByFirstDot(final String dotNotatedPropName) {
final int firstDotIndex = dotNotatedPropName.indexOf(".");
if (firstDotIndex != -1) {
return new Pair<String, String>(dotNotatedPropName.substring(0, firstDotIndex), dotNotatedPropName.substring(firstDotIndex + 1));
} else {
return new Pair<String, String>(dotNotatedPropName, null);
}
}
/**
* Splits dot.notated property in two parts: last subproperty (as second part) and prior subproperties.
*
* @param dotNotatedPropName
* @return
*/
public static Pair<String, String> splitPropByLastDot(final String dotNotatedPropName) {
final int lastDotIndex = findLastDotInString(0, dotNotatedPropName);
if (lastDotIndex != -1) {
return new Pair<String, String>(dotNotatedPropName.substring(0, lastDotIndex - 1), dotNotatedPropName.substring(lastDotIndex));
} else {
return new Pair<String, String>(null, dotNotatedPropName);
}
}
private static int findLastDotInString(final int fromPosition, final String dotNotatedPropName) {
final int nextDotIndex = dotNotatedPropName.indexOf(".", fromPosition);
if (nextDotIndex != -1) {
return findLastDotInString(nextDotIndex + 1, dotNotatedPropName);
} else {
return fromPosition;
}
}
/**
* Returns true if the provided <code>dotNotationProp</code> is a valid property in the specified entity type.
*
* @param type
* @param dotNotationProp
* @return
*/
public static boolean isProperty(final Class<?> type, final String dotNotationProp) {
try {
return AnnotationReflector.isAnnotationPresent(Finder.findFieldByName(type, dotNotationProp), IsProperty.class);
} catch (final Exception ex) {
logger.warn(ex);
return false;
}
}
/**
* Retrieves all persisted properties fields within given entity type
*
* @param entityType
* @return
*/
public static List<Field> getRealProperties(final Class<? extends AbstractEntity<?>> entityType) {
final List<Field> result = new ArrayList<>();
for (final Field propField : Finder.findRealProperties(entityType)) { //, MapTo.class
if (!(DESC.equals(propField.getName()) && !hasDescProperty(entityType))) {
result.add(propField);
}
}
return result;
}
public static boolean hasDescProperty(final Class<? extends AbstractEntity<?>> entityType) {
return AnnotationReflector.isAnnotationPresentForClass(DescTitle.class, entityType);
}
/**
* Retrieves all collectional properties fields within given entity type
*
* @param entityType
* @return
*/
public static List<Field> getCollectionalProperties(final Class<? extends AbstractEntity<?>> entityType) {
final List<Field> result = new ArrayList<>();
for (final Field propField : Finder.findRealProperties(entityType)) {
if (Collection.class.isAssignableFrom(propField.getType()) && Finder.hasLinkProperty(entityType, propField.getName())) {
result.add(propField);
}
}
return result;
}
public static class BigDecimalWithTwoPlaces {
};
/**
* Produces list of props that should be added to order model instead of composite key.
*
* @param entityType
* @param prefix
* @return
*/
public static List<String> getOrderPropsFromCompositeEntityKey(final Class<? extends AbstractEntity<DynamicEntityKey>> entityType, final String prefix) {
final List<String> result = new ArrayList<>();
final List<Field> keyProps = Finder.getKeyMembers(entityType);
for (final Field keyMemberProp : keyProps) {
if (DynamicEntityKey.class.equals(getKeyType(keyMemberProp.getType()))) {
result.addAll(getOrderPropsFromCompositeEntityKey((Class<AbstractEntity<DynamicEntityKey>>) keyMemberProp.getType(), (prefix != null ? prefix + "." : "")
+ keyMemberProp.getName()));
} else if (isEntityType(keyMemberProp.getType())) {
result.add((prefix != null ? prefix + "." : "") + keyMemberProp.getName() + ".key");
} else {
result.add((prefix != null ? prefix + "." : "") + keyMemberProp.getName());
}
}
return result;
}
public static SortedSet<String> getFirstLevelProps(final Set<String> allProps) {
final SortedSet<String> result = new TreeSet<String>();
for (final String prop : allProps) {
result.add(splitPropByFirstDot(prop).getKey());
}
return result;
}
/**
* A convenient method for constructing a pair of property and its title as defined at the entity type level.
*
* @param entityType
* @param propName
* @return
*/
public static Pair<String, String> titleAndProp(final Class<? extends AbstractEntity<?>> entityType, final String propName) {
return new Pair<>(TitlesDescsGetter.getTitleAndDesc(propName, entityType).getKey(), propName);
}
/**
* Returns <code>true</code> if the original value is stale according to fresh value for current version of entity, <code>false</code> otherwise.
*
* @param originalValue
* -- original value for the property of stale entity
* @param freshValue
* -- fresh value for the property of current (fresh) version of entity
* @return
*/
public static boolean isStale(final Object originalValue, final Object freshValue) {
return !EntityUtils.equalsEx(freshValue, originalValue);
}
/**
* Returns <code>true</code> if the new value for stale entity conflicts with fresh value for current version of entity, <code>false</code> otherwise.
*
* @param staleNewValue
* -- new value for the property of stale entity
* @param staleOriginalValue
* -- original value for the property of stale entity
* @param freshValue
* -- fresh value for the property of current (fresh) version of entity
* @return
*/
public static boolean isConflicting(final Object staleNewValue, final Object staleOriginalValue, final Object freshValue) {
// old implementation:
// return (freshValue == null && staleOriginalValue != null && staleNewValue != null) ||
// (freshValue != null && staleOriginalValue == null && staleNewValue == null) ||
// (freshValue != null && !freshValue.equals(staleOriginalValue) && !freshValue.equals(staleNewValue));
return isStale(staleOriginalValue, freshValue) && !EntityUtils.equalsEx(staleNewValue, freshValue);
}
/**
* Creates empty {@link IFetchProvider} for concrete <code>entityType</code> with instrumentation.
*
* @param entityType
* @param instrumented
* @return
*/
public static <T extends AbstractEntity<?>> IFetchProvider<T> fetch(final Class<T> entityType, final boolean instumented) {
return FetchProviderFactory.createDefaultFetchProvider(entityType, instumented);
}
public static <T extends AbstractEntity<?>> IFetchProvider<T> fetch(final Class<T> entityType) {
return FetchProviderFactory.createDefaultFetchProvider(entityType, false);
}
/**
* Creates {@link IFetchProvider} for concrete <code>entityType</code> with 'key' and 'desc' (analog of {@link EntityQueryUtils#fetchKeyAndDescOnly(Class)}) with instrumentation.
*
* @param entityType
* @param instrumented
* @return
*/
public static <T extends AbstractEntity<?>> IFetchProvider<T> fetchWithKeyAndDesc(final Class<T> entityType, final boolean instrumented) {
return FetchProviderFactory.createFetchProviderWithKeyAndDesc(entityType, instrumented);
}
public static <T extends AbstractEntity<?>> IFetchProvider<T> fetchWithKeyAndDesc(final Class<T> entityType) {
return FetchProviderFactory.createFetchProviderWithKeyAndDesc(entityType, false);
}
/**
* Creates empty {@link IFetchProvider} for concrete <code>entityType</code> <b>without</b> instrumentation.
*
* @param entityType
* @return
*/
public static <T extends AbstractEntity<?>> IFetchProvider<T> fetchNotInstrumented(final Class<T> entityType) {
return FetchProviderFactory.createDefaultFetchProvider(entityType, false);
}
/**
* Creates {@link IFetchProvider} for concrete <code>entityType</code> with 'key' and 'desc' (analog of {@link EntityQueryUtils#fetchKeyAndDescOnly(Class)}) <b>without</b> instrumentation.
*
* @param entityType
* @return
*/
public static <T extends AbstractEntity<?>> IFetchProvider<T> fetchNotInstrumentedWithKeyAndDesc(final Class<T> entityType) {
return FetchProviderFactory.createFetchProviderWithKeyAndDesc(entityType, false);
}
/**
* Tries to perform shallow copy of collectional value. If unsuccessful, throws unsuccessful {@link Result} describing the error.
*
* @param value
* @return
*/
public static <T> T copyCollectionalValue(final T value) {
if (value == null) {
return null; // return (null) copy
}
try {
final Collection<?> collection = (Collection<?>) value;
// try to obtain empty constructor to perform shallow copying of collection
final Constructor<? extends Collection> constructor = collection.getClass().getConstructor();
final Collection copy = constructor.newInstance();
copy.addAll(collection);
// return non-empty copy
return (T) copy;
} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
logger.error(e.getMessage(), e);
throw Result.failure(String.format("Collection copying has been failed. Type [%s]. Exception [%s].", value.getClass(), e.getMessage())); // throw result indicating the failure of copying
}
}
/**
* The most generic and most straightforward function to copy properties from instance <code>fromEntity</code> to <code>toEntity</code>.
*
* @param fromEntity
* @param toEntity
* @param skipProperties -- a sequence of property names, which may include ID and VERSION.
*/
public static <T extends AbstractEntity> void copy(final AbstractEntity<?> fromEntity, final T toEntity, final String... skipProperties) {
// convert an array with property names to be skipped into a set for more efficient use
final Set<String> skipPropertyName = new HashSet<>(Arrays.asList(skipProperties));
// Under certain circumstances copying happens for an uninstrumented entity instance
// In such cases there would be no meta-properties, and copying would fail.
// Therefore, it is important to perform ad-hoc property retrieval via reflection.
final List<String> realProperties = Finder.streamRealProperties(fromEntity.getType()).map(field -> field.getName()).collect(Collectors.toList());
// Need to add ID and VERSION in order for them to be treated as entity properties
// They will get skipped if provided as part of skipProperties array
realProperties.add(ID);
realProperties.add(VERSION);
// Copy each identified property, which is not proxied or skipped into a new instance.
realProperties.stream()
.filter(name -> !skipPropertyName.contains(name))
.filter(propName -> !fromEntity.proxiedPropertyNames().contains(propName))
.forEach(propName -> {
if (KEY.equals(propName) && toEntity.getKeyType().equals(fromEntity.getKeyType()) && DynamicEntityKey.class.isAssignableFrom(fromEntity.getKeyType())) {
toEntity.setKey(new DynamicEntityKey(toEntity));
} else {
try {
toEntity.set(propName, fromEntity.get(propName));
} catch (final Exception e) {
logger.trace(format("Setter for property %s did not succeed during coping.", propName), e);
}
}
});
}
} | Adjusted method 'compare' to reuse 'safeCompare'.
| platform-pojo-bl/src/main/java/ua/com/fielden/platform/utils/EntityUtils.java | Adjusted method 'compare' to reuse 'safeCompare'. | <ide><path>latform-pojo-bl/src/main/java/ua/com/fielden/platform/utils/EntityUtils.java
<ide> */
<ide> @SuppressWarnings("rawtypes")
<ide> public static <T extends AbstractEntity<K>, K extends Comparable> int compare(final T o1, final T o2) {
<del> if (o1 == o2) {
<del> return 0;
<del> } else if (o1 == null && o2 != null) {
<del> return -1;
<del> } else if (o1 != null && o2 == null) {
<del> return 1;
<del> } else {
<del> return o1.compareTo(o2);
<del> }
<add> return safeCompare(o1, o2);
<ide> }
<ide>
<ide> |
|
Java | mit | error: pathspec 'src/exception/NotImplementedException.java' did not match any file(s) known to git
| 896b949fa2376075f13631f0316352ea2349b8bd | 1 | jediweon/pork_sandwich | package exception;
public class NotImplementedException extends Exception {
}
| src/exception/NotImplementedException.java | [Implement] the class may be needed
| src/exception/NotImplementedException.java | [Implement] the class may be needed | <ide><path>rc/exception/NotImplementedException.java
<add>package exception;
<add>
<add>public class NotImplementedException extends Exception {
<add>
<add>} |
|
Java | apache-2.0 | 4a31ad110a7423bdbdf4fef0566a3e12ecc0a6a5 | 0 | iocanel/sundrio,sundrio/sundrio,sundrio/sundrio | /*
* Copyright 2015 The original 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 io.sundr.builder.internal.processor;
import io.sundr.builder.Constants;
import io.sundr.builder.annotations.Inline;
import io.sundr.builder.internal.BuilderContext;
import io.sundr.builder.internal.BuilderContextManager;
import io.sundr.builder.internal.functions.ClazzAs;
import io.sundr.builder.internal.functions.TypeAs;
import io.sundr.builder.internal.utils.BuilderUtils;
import io.sundr.codegen.model.JavaClazz;
import io.sundr.codegen.model.JavaClazzBuilder;
import io.sundr.codegen.model.JavaMethod;
import io.sundr.codegen.model.JavaMethodBuilder;
import io.sundr.codegen.model.JavaType;
import io.sundr.codegen.model.JavaTypeBuilder;
import io.sundr.codegen.processor.JavaGeneratingProcessor;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import static io.sundr.codegen.utils.TypeUtils.typeGenericOf;
public abstract class AbstractBuilderProcessor extends JavaGeneratingProcessor {
void generateLocalDependenciesIfNeeded() {
BuilderContext context = BuilderContextManager.getContext();
if (context.getGenerateBuilderPackage() && !Constants.DEFAULT_BUILDER_PACKAGE.equals(context.getBuilderPackage())) {
try {
generateFromClazz(context.getVisitableInterface(),
Constants.DEFAULT_INTERFACE_TEMPLATE_LOCATION
);
generateFromClazz(context.getVisitorInterface(),
Constants.DEFAULT_INTERFACE_TEMPLATE_LOCATION
);
generateFromClazz(context.getVisitableBuilderInterface(),
Constants.DEFAULT_INTERFACE_TEMPLATE_LOCATION
);
generateFromClazz(context.getBuilderInterface(),
Constants.DEFAULT_INTERFACE_TEMPLATE_LOCATION
);
generateFromClazz(context.getFluentInterface(),
Constants.DEFAULT_INTERFACE_TEMPLATE_LOCATION
);
generateFromClazz(context.getBaseFluentClass(),
Constants.DEFAULT_CLASS_TEMPLATE_LOCATION
);
generateFromClazz(context.getNestedInterface(),
Constants.DEFAULT_INTERFACE_TEMPLATE_LOCATION
);
generateFromClazz(context.getEditableInterface(),
Constants.DEFAULT_INTERFACE_TEMPLATE_LOCATION
);
} catch (Exception e) {
//
}
}
}
/**
* Selects a builder template based on the criteria.
* @param validationEnabled Flag that indicates if validationEnabled is enabled.
* @return
*/
String selectBuilderTemplate(boolean validationEnabled) {
if (validationEnabled) {
return Constants.VALIDATING_BUILDER_TEMPLATE_LOCATION;
} else {
return Constants.DEFAULT_BUILDER_TEMPLATE_LOCATION;
}
}
JavaClazz inlineableOf(BuilderContext ctx, JavaClazz clazz, Inline inline) {
JavaClazz base = ClazzAs.INLINEABLE.apply(clazz);
JavaType baseInterface = typeGenericOf(BuilderUtils.getInlineType(ctx, inline), clazz.getType());
JavaMethod method = new JavaMethodBuilder(base.getMethods().iterator().next()).withName(inline.value()).build();
JavaType fluentImpl = TypeAs.FLUENT_IMPL.apply(clazz.getType());
JavaType fluentInterface = TypeAs.FLUENT_INTERFACE.apply(clazz.getType());
JavaType shallowInlineType = new JavaTypeBuilder(base.getType())
.withClassName(inline.prefix() + base.getType().getClassName() + inline.suffix())
.addToInterfaces(baseInterface)
.build();
JavaType inlineType = new JavaTypeBuilder(shallowInlineType)
.withSuperClass(typeGenericOf(fluentImpl, shallowInlineType))
.addToInterfaces(typeGenericOf(fluentInterface, shallowInlineType))
.build();
Set<JavaMethod> constructors = new LinkedHashSet<JavaMethod>();
for (JavaMethod constructor : base.getConstructors()) {
constructors.add(new JavaMethodBuilder(constructor).withReturnType(inlineType).build());
}
return new JavaClazzBuilder(base)
.withType(inlineType)
.withConstructors(constructors)
.withMethods(new HashSet<JavaMethod>(Arrays.asList(method)))
.build();
}
}
| annotations/builder/src/main/java/io/sundr/builder/internal/processor/AbstractBuilderProcessor.java | /*
* Copyright 2015 The original 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 io.sundr.builder.internal.processor;
import io.sundr.builder.Constants;
import io.sundr.builder.annotations.Inline;
import io.sundr.builder.internal.BuilderContext;
import io.sundr.builder.internal.BuilderContextManager;
import io.sundr.builder.internal.functions.ClazzAs;
import io.sundr.builder.internal.functions.TypeAs;
import io.sundr.builder.internal.utils.BuilderUtils;
import io.sundr.codegen.model.JavaClazz;
import io.sundr.codegen.model.JavaClazzBuilder;
import io.sundr.codegen.model.JavaMethod;
import io.sundr.codegen.model.JavaMethodBuilder;
import io.sundr.codegen.model.JavaType;
import io.sundr.codegen.model.JavaTypeBuilder;
import io.sundr.codegen.processor.JavaGeneratingProcessor;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import static io.sundr.codegen.utils.TypeUtils.typeGenericOf;
public abstract class AbstractBuilderProcessor extends JavaGeneratingProcessor {
void generateLocalDependenciesIfNeeded() {
BuilderContext context = BuilderContextManager.getContext();
if (context.getGenerateBuilderPackage() && !Constants.DEFAULT_BUILDER_PACKAGE.equals(context.getBuilderPackage())) {
try {
generateFromClazz(context.getVisitableInterface(),
Constants.DEFAULT_INTERFACE_TEMPLATE_LOCATION
);
generateFromClazz(context.getVisitorInterface(),
Constants.DEFAULT_INTERFACE_TEMPLATE_LOCATION
);
generateFromClazz(context.getVisitableBuilderInterface(),
Constants.DEFAULT_INTERFACE_TEMPLATE_LOCATION
);
generateFromClazz(context.getBuilderInterface(),
Constants.DEFAULT_INTERFACE_TEMPLATE_LOCATION
);
generateFromClazz(context.getFluentInterface(),
Constants.DEFAULT_INTERFACE_TEMPLATE_LOCATION
);
generateFromClazz(context.getBaseFluentClass(),
Constants.DEFAULT_CLASS_TEMPLATE_LOCATION
);
generateFromClazz(context.getNestedInterface(),
Constants.DEFAULT_INTERFACE_TEMPLATE_LOCATION
);
generateFromClazz(context.getEditableInterface(),
Constants.DEFAULT_INTERFACE_TEMPLATE_LOCATION
);
} catch (Exception e) {
//
}
}
}
/**
* Selects a builder template based on the criteria.
* @param validationEnabled Flag that indicates if validationEnabled is enabled.
* @return
*/
String selectBuilderTemplate(boolean validationEnabled) {
if (validationEnabled) {
return Constants.VALIDATING_BUILDER_TEMPLATE_LOCATION;
} else {
return Constants.DEFAULT_BUILDER_TEMPLATE_LOCATION;
}
}
JavaClazz inlineableOf(BuilderContext ctx, JavaClazz clazz, Inline inline) {
JavaClazz base = ClazzAs.INLINEABLE.apply(clazz);
JavaType baseInterface = typeGenericOf(BuilderUtils.getInlineType(ctx, inline), clazz.getType());
JavaMethod method = new JavaMethodBuilder(base.getMethods().iterator().next()).withName(inline.value()).build();
JavaType fluent = TypeAs.FLUENT_IMPL.apply(clazz.getType());
JavaType shallowInlineType = new JavaTypeBuilder(base.getType())
.withClassName(inline.prefix() + base.getType().getClassName() + inline.suffix())
.addToInterfaces(baseInterface)
.build();
JavaType inlineType = new JavaTypeBuilder(shallowInlineType)
.withSuperClass(typeGenericOf(fluent, shallowInlineType))
.build();
Set<JavaMethod> constructors = new LinkedHashSet<JavaMethod>();
for (JavaMethod constructor : base.getConstructors()) {
constructors.add(new JavaMethodBuilder(constructor).withReturnType(inlineType).build());
}
return new JavaClazzBuilder(base)
.withType(inlineType)
.withConstructors(constructors)
.withMethods(new HashSet<JavaMethod>(Arrays.asList(method)))
.build();
}
}
| Inlinables now extend fluent impl and implement the fluent interface.
| annotations/builder/src/main/java/io/sundr/builder/internal/processor/AbstractBuilderProcessor.java | Inlinables now extend fluent impl and implement the fluent interface. | <ide><path>nnotations/builder/src/main/java/io/sundr/builder/internal/processor/AbstractBuilderProcessor.java
<ide> JavaType baseInterface = typeGenericOf(BuilderUtils.getInlineType(ctx, inline), clazz.getType());
<ide> JavaMethod method = new JavaMethodBuilder(base.getMethods().iterator().next()).withName(inline.value()).build();
<ide>
<del> JavaType fluent = TypeAs.FLUENT_IMPL.apply(clazz.getType());
<add> JavaType fluentImpl = TypeAs.FLUENT_IMPL.apply(clazz.getType());
<add> JavaType fluentInterface = TypeAs.FLUENT_INTERFACE.apply(clazz.getType());
<add>
<ide> JavaType shallowInlineType = new JavaTypeBuilder(base.getType())
<ide> .withClassName(inline.prefix() + base.getType().getClassName() + inline.suffix())
<ide> .addToInterfaces(baseInterface)
<ide> .build();
<ide>
<ide> JavaType inlineType = new JavaTypeBuilder(shallowInlineType)
<del> .withSuperClass(typeGenericOf(fluent, shallowInlineType))
<add> .withSuperClass(typeGenericOf(fluentImpl, shallowInlineType))
<add> .addToInterfaces(typeGenericOf(fluentInterface, shallowInlineType))
<ide> .build();
<ide>
<ide> Set<JavaMethod> constructors = new LinkedHashSet<JavaMethod>(); |
|
Java | apache-2.0 | 63f98dd5ee5dd1bb8bb8cd729c6d49cad34d403e | 0 | raphw/byte-buddy,raphw/byte-buddy,raphw/byte-buddy | /*
* Copyright 2014 - 2019 Rafael Winterhalter
*
* 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 net.bytebuddy.agent.builder;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.ClassFileVersion;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.asm.AsmVisitorWrapper;
import net.bytebuddy.build.EntryPoint;
import net.bytebuddy.build.HashCodeAndEqualsPlugin;
import net.bytebuddy.build.Plugin;
import net.bytebuddy.description.field.FieldDescription;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.method.ParameterDescription;
import net.bytebuddy.description.modifier.*;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.*;
import net.bytebuddy.dynamic.loading.ClassInjector;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.dynamic.scaffold.InstrumentedType;
import net.bytebuddy.dynamic.scaffold.TypeValidation;
import net.bytebuddy.dynamic.scaffold.inline.MethodNameTransformer;
import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
import net.bytebuddy.implementation.ExceptionMethod;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.implementation.LoadedTypeInitializer;
import net.bytebuddy.implementation.MethodCall;
import net.bytebuddy.implementation.auxiliary.AuxiliaryType;
import net.bytebuddy.implementation.bytecode.ByteCodeAppender;
import net.bytebuddy.implementation.bytecode.Duplication;
import net.bytebuddy.implementation.bytecode.StackManipulation;
import net.bytebuddy.implementation.bytecode.TypeCreation;
import net.bytebuddy.implementation.bytecode.assign.Assigner;
import net.bytebuddy.implementation.bytecode.assign.TypeCasting;
import net.bytebuddy.implementation.bytecode.collection.ArrayFactory;
import net.bytebuddy.implementation.bytecode.constant.ClassConstant;
import net.bytebuddy.implementation.bytecode.constant.IntegerConstant;
import net.bytebuddy.implementation.bytecode.constant.TextConstant;
import net.bytebuddy.implementation.bytecode.member.FieldAccess;
import net.bytebuddy.implementation.bytecode.member.MethodInvocation;
import net.bytebuddy.implementation.bytecode.member.MethodReturn;
import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.matcher.LatentMatcher;
import net.bytebuddy.pool.TypePool;
import net.bytebuddy.utility.CompoundList;
import net.bytebuddy.utility.JavaConstant;
import net.bytebuddy.utility.JavaModule;
import net.bytebuddy.utility.JavaType;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import java.io.*;
import java.lang.instrument.ClassDefinition;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static net.bytebuddy.matcher.ElementMatchers.*;
/**
* <p>
* An agent builder provides a convenience API for defining a
* <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/instrument/package-summary.html">Java agent</a>. By default,
* this transformation is applied by rebasing the type if not specified otherwise by setting a
* {@link TypeStrategy}.
* </p>
* <p>
* When defining several {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s, the agent builder always
* applies the transformers that were supplied with the last applicable matcher. Therefore, more general transformers
* should be defined first.
* </p>
* <p>
* <b>Note</b>: Any transformation is performed using the {@link AccessControlContext} of an agent's creator.
* </p>
* <p>
* <b>Important</b>: Types that implement lambda expressions (functional interfaces) are not instrumented by default but
* only when enabling the builder's {@link LambdaInstrumentationStrategy}.
* </p>
*/
public interface AgentBuilder {
/**
* Defines the given {@link net.bytebuddy.ByteBuddy} instance to be used by the created agent.
*
* @param byteBuddy The Byte Buddy instance to be used.
* @return A new instance of this agent builder which makes use of the given {@code byteBuddy} instance.
*/
AgentBuilder with(ByteBuddy byteBuddy);
/**
* Defines the given {@link net.bytebuddy.agent.builder.AgentBuilder.Listener} to be notified by the created agent.
* The given listener is notified after any other listener that is already registered. If a listener is registered
* twice, it is also notified twice.
*
* @param listener The listener to be notified.
* @return A new instance of this agent builder which creates an agent that informs the given listener about
* events.
*/
AgentBuilder with(Listener listener);
/**
* Defines a circularity lock that is acquired upon executing code that potentially loads new classes. While the
* lock is acquired, any class file transformer refrains from transforming any classes. By default, all created
* agents use a shared {@link CircularityLock} to avoid that any classes that are required to execute an agent
* causes a {@link ClassCircularityError}.
*
* @param circularityLock The circularity lock to use.
* @return A new instance of this agent builder which creates an agent that uses the supplied circularity lock.
*/
AgentBuilder with(CircularityLock circularityLock);
/**
* Defines the use of the given type locator for locating a {@link TypeDescription} for an instrumented type.
*
* @param poolStrategy The type locator to use.
* @return A new instance of this agent builder which uses the given type locator for looking up class files.
*/
AgentBuilder with(PoolStrategy poolStrategy);
/**
* Defines the use of the given location strategy for locating binary data to given class names.
*
* @param locationStrategy The location strategy to use.
* @return A new instance of this agent builder which uses the given location strategy for looking up class files.
*/
AgentBuilder with(LocationStrategy locationStrategy);
/**
* Defines how types should be transformed, e.g. if they should be rebased or redefined by the created agent.
*
* @param typeStrategy The type strategy to use.
* @return A new instance of this agent builder which uses the given type strategy.
*/
AgentBuilder with(TypeStrategy typeStrategy);
/**
* Defines a given initialization strategy to be applied to generated types. An initialization strategy is responsible
* for setting up a type after it was loaded. This initialization must be performed after the transformation because
* a Java agent is only invoked before loading a type. By default, the initialization logic is added to a class's type
* initializer which queries a global object for any objects that are to be injected into the generated type.
*
* @param initializationStrategy The initialization strategy to use.
* @return A new instance of this agent builder that applies the given initialization strategy.
*/
AgentBuilder with(InitializationStrategy initializationStrategy);
/**
* <p>
* Specifies a strategy for modifying types that were already loaded prior to the installation of this transformer.
* </p>
* <p>
* <b>Note</b>: Defining a redefinition strategy resets any refinements of a previously set redefinition strategy.
* </p>
* <p>
* <b>Important</b>: Most JVMs do not support changes of a class's structure after a class was already
* loaded. Therefore, it is typically required that this class file transformer was built while enabling
* {@link AgentBuilder#disableClassFormatChanges()}.
* </p>
*
* @param redefinitionStrategy The redefinition strategy to apply.
* @return A new instance of this agent builder that applies the given redefinition strategy.
*/
RedefinitionListenable.WithoutBatchStrategy with(RedefinitionStrategy redefinitionStrategy);
/**
* <p>
* Enables or disables management of the JVM's {@code LambdaMetafactory} which is responsible for creating classes that
* implement lambda expressions. Without this feature enabled, classes that are represented by lambda expressions are
* not instrumented by the JVM such that Java agents have no effect on them when a lambda expression's class is loaded
* for the first time.
* </p>
* <p>
* When activating this feature, Byte Buddy instruments the {@code LambdaMetafactory} and takes over the responsibility
* of creating classes that represent lambda expressions. In doing so, Byte Buddy has the opportunity to apply the built
* class file transformer. If the current VM does not support lambda expressions, activating this feature has no effect.
* </p>
* <p>
* <b>Important</b>: If this feature is active, it is important to release the built class file transformer when
* deactivating it. Normally, it is sufficient to call {@link Instrumentation#removeTransformer(ClassFileTransformer)}.
* When this feature is enabled, it is however also required to invoke
* {@link LambdaInstrumentationStrategy#release(ClassFileTransformer, Instrumentation)}. Otherwise, the executing VMs class
* loader retains a reference to the class file transformer what can cause a memory leak.
* </p>
*
* @param lambdaInstrumentationStrategy {@code true} if this feature should be enabled.
* @return A new instance of this agent builder where this feature is explicitly enabled or disabled.
*/
AgentBuilder with(LambdaInstrumentationStrategy lambdaInstrumentationStrategy);
/**
* Specifies a strategy to be used for resolving {@link TypeDescription} for any type handled by the created transformer.
*
* @param descriptionStrategy The description strategy to use.
* @return A new instance of this agent builder that applies the given description strategy.
*/
AgentBuilder with(DescriptionStrategy descriptionStrategy);
/**
* Specifies a fallback strategy to that this agent builder applies upon installing an agent and during class file transformation.
*
* @param fallbackStrategy The fallback strategy to be used.
* @return A new agent builder that applies the supplied fallback strategy.
*/
AgentBuilder with(FallbackStrategy fallbackStrategy);
/**
* Specifies a class file buffer strategy that determines the use of the buffer supplied to a class file transformer.
*
* @param classFileBufferStrategy The class file buffer strategy to use.
* @return A new agent builder that applies the supplied class file buffer strategy.
*/
AgentBuilder with(ClassFileBufferStrategy classFileBufferStrategy);
/**
* Adds an installation listener that is notified during installation events. Installation listeners are only invoked if
* a class file transformer is installed using this agent builder's installation methods and uninstalled via the created
* {@link ResettableClassFileTransformer}'s {@code reset} methods.
*
* @param installationListener The installation listener to register.
* @return A new agent builder that applies the supplied installation listener.
*/
AgentBuilder with(InstallationListener installationListener);
/**
* Defines a strategy for injecting auxiliary types into the target class loader.
*
* @param injectionStrategy The injection strategy to use.
* @return A new agent builder with the supplied injection strategy configured.
*/
AgentBuilder with(InjectionStrategy injectionStrategy);
/**
* Adds a decorator for the created class file transformer.
*
* @param transformerDecorator A decorator to wrap the created class file transformer.
* @return A new agent builder that applies the supplied transformer decorator.
*/
AgentBuilder with(TransformerDecorator transformerDecorator);
/**
* Enables the use of the given native method prefix for instrumented methods. Note that this prefix is also
* applied when preserving non-native methods. The use of this prefix is also registered when installing the
* final agent with an {@link java.lang.instrument.Instrumentation}.
*
* @param prefix The prefix to be used.
* @return A new instance of this agent builder which uses the given native method prefix.
*/
AgentBuilder enableNativeMethodPrefix(String prefix);
/**
* Disables the use of a native method prefix for instrumented methods.
*
* @return A new instance of this agent builder which does not use a native method prefix.
*/
AgentBuilder disableNativeMethodPrefix();
/**
* <p>
* Disables all implicit changes on a class file that Byte Buddy would apply for certain instrumentations. When
* using this option, it is no longer possible to rebase a method, i.e. intercepted methods are fully replaced. Furthermore,
* it is no longer possible to implicitly apply loaded type initializers for explicitly initializing the generated type.
* </p>
* <p>
* This is equivalent to setting {@link InitializationStrategy.NoOp} and {@link TypeStrategy.Default#REDEFINE_FROZEN}
* (unless it is configured as {@link TypeStrategy.Default#DECORATE} where this strategy is retained)
* as well as configuring the underlying {@link ByteBuddy} instance to use a {@link net.bytebuddy.implementation.Implementation.Context.Disabled}.
* Using this strategy also configures Byte Buddy to create frozen instrumented types and discards any explicit configuration.
* </p>
*
* @return A new instance of this agent builder that does not apply any implicit changes to the received class file.
*/
AgentBuilder disableClassFormatChanges();
/**
* Assures that all modules of the supplied types are read by the module of any instrumented type. If the current VM does not support
* the Java module system, calling this method has no effect and this instance is returned.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param type The types for which to assure their module-visibility from any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Class<?>... type);
/**
* Assures that all supplied modules are read by the module of any instrumented type.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param module The modules for which to assure their module-visibility from any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, JavaModule... module);
/**
* Assures that all supplied modules are read by the module of any instrumented type.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param modules The modules for which to assure their module-visibility from any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules);
/**
* Assures that all modules of the supplied types are read by the module of any instrumented type and vice versa.
* If the current VM does not support the Java module system, calling this method has no effect and this instance is returned.
* Setting this option will also ensure that the instrumented type's package is opened to the target module, if applicable.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param type The types for which to assure their module-visibility from and to any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Class<?>... type);
/**
* Assures that all supplied modules are read by the module of any instrumented type and vice versa.
* Setting this option will also ensure that the instrumented type's package is opened to the target module.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param module The modules for which to assure their module-visibility from and to any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, JavaModule... module);
/**
* Assures that all supplied modules are read by the module of any instrumented type and vice versa.
* Setting this option will also ensure that the instrumented type's package is opened to the target module.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param modules The modules for which to assure their module-visibility from and to any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules);
/**
* <p>
* Matches a type being loaded in order to apply the supplied {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type.
* If several matchers positively match a type only the latest registered matcher is considered for transformation.
* </p>
* <p>
* If this matcher is chained with additional subsequent matchers, any matcher is executed in registration order with matchers that were registered
* first being executed first. Doing so, later transformations can override transformations that are applied by this matcher. To avoid this, it is
* possible to register this transformation as terminal via {@link Identified.Extendable#asTerminalTransformation()} where no subsequent matchers
* are applied if this matcher matched a given type.
* </p>
* <p>
* <b>Note</b>: When applying a matcher, regard the performance implications by {@link AgentBuilder#ignore(ElementMatcher)}. The former
* matcher is applied first such that it makes sense to ignore name spaces that are irrelevant to instrumentation. If possible, it is
* also recommended, to exclude class loaders such as for example the bootstrap class loader by using
* {@link AgentBuilder#type(ElementMatcher, ElementMatcher)} instead.
* </p>
*
* @param typeMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied on the type being loaded that
* decides if the entailed {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should
* be applied for that type.
* @return A definable that represents this agent builder which allows for the definition of one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when the given {@code typeMatcher}
* indicates a match.
*/
Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher);
/**
* <p>
* Matches a type being loaded in order to apply the supplied {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type.
* If several matchers positively match a type only the latest registered matcher is considered for transformation.
* </p>
* <p>
* If this matcher is chained with additional subsequent matchers, any matcher is executed in registration order with matchers that were registered
* first being executed first. Doing so, later transformations can override transformations that are applied by this matcher. To avoid this, it is
* possible to register this transformation as terminal via {@link Identified.Extendable#asTerminalTransformation()} where no subsequent matchers
* are applied if this matcher matched a given type.
* </p>
* <p>
* <b>Note</b>: When applying a matcher, regard the performance implications by {@link AgentBuilder#ignore(ElementMatcher)}. The former
* matcher is applied first such that it makes sense to ignore name spaces that are irrelevant to instrumentation. If possible, it
* is also recommended, to exclude class loaders such as for example the bootstrap class loader.
* </p>
*
* @param typeMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied on the type being
* loaded that decides if the entailed
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should be applied for
* that type.
* @param classLoaderMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied to the
* {@link java.lang.ClassLoader} that is loading the type being loaded. This matcher
* is always applied first where the type matcher is not applied in case that this
* matcher does not indicate a match.
* @return A definable that represents this agent builder which allows for the definition of one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when both the given
* {@code typeMatcher} and {@code classLoaderMatcher} indicate a match.
*/
Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher);
/**
* <p>
* Matches a type being loaded in order to apply the supplied {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type.
* If several matchers positively match a type only the latest registered matcher is considered for transformation.
* </p>
* <p>
* If this matcher is chained with additional subsequent matchers, any matcher is executed in registration order with matchers that were registered
* first being executed first. Doing so, later transformations can override transformations that are applied by this matcher. To avoid this, it is
* possible to register this transformation as terminal via {@link Identified.Extendable#asTerminalTransformation()} where no subsequent matchers
* are applied if this matcher matched a given type.
* </p>
* <p>
* <b>Note</b>: When applying a matcher, regard the performance implications by {@link AgentBuilder#ignore(ElementMatcher)}. The former
* matcher is applied first such that it makes sense to ignore name spaces that are irrelevant to instrumentation. If possible, it
* is also recommended, to exclude class loaders such as for example the bootstrap class loader.
* </p>
*
* @param typeMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied on the type being
* loaded that decides if the entailed
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should be applied for
* that type.
* @param classLoaderMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied to the
* {@link java.lang.ClassLoader} that is loading the type being loaded. This matcher
* is always applied second where the type matcher is not applied in case that this
* matcher does not indicate a match.
* @param moduleMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied to the {@link JavaModule}
* of the type being loaded. This matcher is always applied first where the class loader and
* type matchers are not applied in case that this matcher does not indicate a match. On a JVM
* that does not support the Java modules system, this matcher is not applied.
* @return A definable that represents this agent builder which allows for the definition of one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when both the given
* {@code typeMatcher} and {@code classLoaderMatcher} indicate a match.
*/
Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher);
/**
* <p>
* Matches a type being loaded in order to apply the supplied {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type.
* If several matchers positively match a type only the latest registered matcher is considered for transformation.
* </p>
* <p>
* If this matcher is chained with additional subsequent matchers, any matcher is executed in registration order with matchers that were registered
* first being executed first. Doing so, later transformations can override transformations that are applied by this matcher. To avoid this, it is
* possible to register this transformation as terminal via {@link Identified.Extendable#asTerminalTransformation()} where no subsequent matchers
* are applied if this matcher matched a given type.
* </p>
* <p>
* <b>Note</b>: When applying a matcher, regard the performance implications by {@link AgentBuilder#ignore(ElementMatcher)}. The former
* matcher is applied first such that it makes sense to ignore name spaces that are irrelevant to instrumentation. If possible, it
* is also recommended, to exclude class loaders such as for example the bootstrap class loader.
* </p>
*
* @param matcher A matcher that decides if the entailed {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should be
* applied for a type that is being loaded.
* @return A definable that represents this agent builder which allows for the definition of one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when the given {@code matcher}
* indicates a match.
*/
Identified.Narrowable type(RawMatcher matcher);
/**
* <p>
* Excludes any type that is matched by the provided matcher from instrumentation and considers types by all {@link ClassLoader}s.
* By default, Byte Buddy does not instrument synthetic types or types that are loaded by the bootstrap class loader.
* </p>
* <p>
* When ignoring a type, any subsequently chained matcher is applied after this matcher in the order of their registration. Also, if
* any matcher indicates that a type is to be ignored, none of the following chained matchers is executed.
* </p>
* <p>
* <b>Note</b>: For performance reasons, it is recommended to always include a matcher that excludes as many namespaces
* as possible. Byte Buddy can determine a type's name without parsing its class file and can therefore discard such
* types with minimal overhead. When a different property of a type - such as for example its modifiers or its annotations
* is accessed - Byte Buddy parses the class file lazily in order to allow for such a matching. Therefore, any exclusion
* of a name should always be done as a first step and even if it does not influence the selection of what types are
* matched. Without changing this property, the class file of every type is being parsed!
* </p>
* <p>
* <b>Warning</b>: If a type is loaded during the instrumentation of the same type, this causes the original call site that loads the type
* to remain unbound, causing a {@link LinkageError}. It is therefore important to not instrument types that may be loaded during the application
* of a {@link Transformer}. For this reason, it is not recommended to instrument classes of the bootstrap class loader that Byte Buddy might
* require for instrumenting a class or to instrument any of Byte Buddy's classes. If such instrumentation is desired, it is important to
* assert for each class that they are not loaded during instrumentation.
* </p>
*
* @param typeMatcher A matcher that identifies types that should not be instrumented.
* @return A new instance of this agent builder that ignores all types that are matched by the provided matcher.
* All previous matchers for ignored types are discarded.
*/
Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher);
/**
* <p>
* Excludes any type that is matched by the provided matcher and is loaded by a class loader matching the second matcher.
* By default, Byte Buddy does not instrument synthetic types, types within a {@code net.bytebuddy.*} package or types that
* are loaded by the bootstrap class loader.
* </p>
* <p>
* When ignoring a type, any subsequently chained matcher is applied after this matcher in the order of their registration. Also, if
* any matcher indicates that a type is to be ignored, none of the following chained matchers is executed.
* </p>
* <p>
* <b>Note</b>: For performance reasons, it is recommended to always include a matcher that excludes as many namespaces
* as possible. Byte Buddy can determine a type's name without parsing its class file and can therefore discard such
* types with minimal overhead. When a different property of a type - such as for example its modifiers or its annotations
* is accessed - Byte Buddy parses the class file lazily in order to allow for such a matching. Therefore, any exclusion
* of a name should always be done as a first step and even if it does not influence the selection of what types are
* matched. Without changing this property, the class file of every type is being parsed!
* </p>
* <p>
* <b>Warning</b>: If a type is loaded during the instrumentation of the same type, this causes the original call site that loads the type
* to remain unbound, causing a {@link LinkageError}. It is therefore important to not instrument types that may be loaded during the application
* of a {@link Transformer}. For this reason, it is not recommended to instrument classes of the bootstrap class loader that Byte Buddy might
* require for instrumenting a class or to instrument any of Byte Buddy's classes. If such instrumentation is desired, it is important to
* assert for each class that they are not loaded during instrumentation.
* </p>
*
* @param typeMatcher A matcher that identifies types that should not be instrumented.
* @param classLoaderMatcher A matcher that identifies a class loader that identifies classes that should not be instrumented.
* @return A new instance of this agent builder that ignores all types that are matched by the provided matcher.
* All previous matchers for ignored types are discarded.
*/
Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher);
/**
* <p>
* Excludes any type that is matched by the provided matcher and is loaded by a class loader matching the second matcher.
* By default, Byte Buddy does not instrument synthetic types, types within a {@code net.bytebuddy.*} package or types that
* are loaded by the bootstrap class loader.
* </p>
* <p>
* When ignoring a type, any subsequently chained matcher is applied after this matcher in the order of their registration. Also, if
* any matcher indicates that a type is to be ignored, none of the following chained matchers is executed.
* </p>
* <p>
* <b>Note</b>: For performance reasons, it is recommended to always include a matcher that excludes as many namespaces
* as possible. Byte Buddy can determine a type's name without parsing its class file and can therefore discard such
* types with minimal overhead. When a different property of a type - such as for example its modifiers or its annotations
* is accessed - Byte Buddy parses the class file lazily in order to allow for such a matching. Therefore, any exclusion
* of a name should always be done as a first step and even if it does not influence the selection of what types are
* matched. Without changing this property, the class file of every type is being parsed!
* </p>
* <p>
* <b>Warning</b>: If a type is loaded during the instrumentation of the same type, this causes the original call site that loads the type
* to remain unbound, causing a {@link LinkageError}. It is therefore important to not instrument types that may be loaded during the application
* of a {@link Transformer}. For this reason, it is not recommended to instrument classes of the bootstrap class loader that Byte Buddy might
* require for instrumenting a class or to instrument any of Byte Buddy's classes. If such instrumentation is desired, it is important to
* assert for each class that they are not loaded during instrumentation.
* </p>
*
* @param typeMatcher A matcher that identifies types that should not be instrumented.
* @param classLoaderMatcher A matcher that identifies a class loader that identifies classes that should not be instrumented.
* @param moduleMatcher A matcher that identifies a module that identifies classes that should not be instrumented. On a JVM
* that does not support the Java modules system, this matcher is not applied.
* @return A new instance of this agent builder that ignores all types that are matched by the provided matcher.
* All previous matchers for ignored types are discarded.
*/
Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher);
/**
* <p>
* Excludes any type that is matched by the raw matcher provided to this method. By default, Byte Buddy does not
* instrument synthetic types, types within a {@code net.bytebuddy.*} package or types that are loaded by the bootstrap class loader.
* </p>
* <p>
* When ignoring a type, any subsequently chained matcher is applied after this matcher in the order of their registration. Also, if
* any matcher indicates that a type is to be ignored, none of the following chained matchers is executed.
* </p>
* <p>
* <b>Note</b>: For performance reasons, it is recommended to always include a matcher that excludes as many namespaces
* as possible. Byte Buddy can determine a type's name without parsing its class file and can therefore discard such
* types with minimal overhead. When a different property of a type - such as for example its modifiers or its annotations
* is accessed - Byte Buddy parses the class file lazily in order to allow for such a matching. Therefore, any exclusion
* of a name should always be done as a first step and even if it does not influence the selection of what types are
* matched. Without changing this property, the class file of every type is being parsed!
* </p>
* <p>
* <b>Warning</b>: If a type is loaded during the instrumentation of the same type, this causes the original call site that loads the type
* to remain unbound, causing a {@link LinkageError}. It is therefore important to not instrument types that may be loaded during the application
* of a {@link Transformer}. For this reason, it is not recommended to instrument classes of the bootstrap class loader that Byte Buddy might
* require for instrumenting a class or to instrument any of Byte Buddy's classes. If such instrumentation is desired, it is important to
* assert for each class that they are not loaded during instrumentation.
* </p>
*
* @param rawMatcher A raw matcher that identifies types that should not be instrumented.
* @return A new instance of this agent builder that ignores all types that are matched by the provided matcher.
* All previous matchers for ignored types are discarded.
*/
Ignored ignore(RawMatcher rawMatcher);
/**
* Creates a {@link ResettableClassFileTransformer} that implements the configuration of this
* agent builder. When using a raw class file transformer, the {@link InstallationListener} callbacks are
* not invoked and the set {@link RedefinitionStrategy} is not applied onto currently loaded classes.
*
* @return A class file transformer that implements the configuration of this agent builder.
*/
ClassFileTransformer makeRaw();
/**
* <p>
* Creates and installs a {@link ResettableClassFileTransformer} that implements the configuration of
* this agent builder with a given {@link java.lang.instrument.Instrumentation}. If retransformation is enabled,
* the installation also causes all loaded types to be retransformed.
* </p>
* <p>
* In order to assure the correct handling of the {@link InstallationListener}, an uninstallation should be applied
* via the {@link ResettableClassFileTransformer}'s {@code reset} methods.
* </p>
*
* @param instrumentation The instrumentation on which this agent builder's configuration is to be installed.
* @return The installed class file transformer.
*/
ResettableClassFileTransformer installOn(Instrumentation instrumentation);
/**
* <p>
* Creates and installs a {@link ResettableClassFileTransformer} that implements the configuration of
* this agent builder with the Byte Buddy-agent which must be installed prior to calling this method. If retransformation
* is enabled, the installation also causes all loaded types to be retransformed.
* </p>
* <p>
* In order to assure the correct handling of the {@link InstallationListener}, an uninstallation should be applied
* via the {@link ResettableClassFileTransformer}'s {@code reset} methods.
* </p>
*
* @return The installed class file transformer.
* @see AgentBuilder#installOn(Instrumentation)
*/
ResettableClassFileTransformer installOnByteBuddyAgent();
/**
* <p>
* Creates and installs a {@link ResettableClassFileTransformer} that implements the configuration of
* this agent builder with a given {@link java.lang.instrument.Instrumentation}. If retransformation is enabled,
* the installation also causes all loaded types to be retransformed which have changed compared to the previous
* class file transformer that is provided as an argument.
* </p>
* <p>
* In order to assure the correct handling of the {@link InstallationListener}, an uninstallation should be applied
* via the {@link ResettableClassFileTransformer}'s {@code reset} methods.
* </p>
*
* @param instrumentation The instrumentation on which this agent builder's configuration is to be installed.
* @param classFileTransformer The class file transformer that is being patched.
* @return The installed class file transformer.
*/
ResettableClassFileTransformer patchOn(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer);
/**
* <p>
* Creates and installs a {@link ResettableClassFileTransformer} that implements the configuration of
* this agent builder with the Byte Buddy-agent which must be installed prior to calling this method. If retransformation
* is enabled, the installation also causes all loaded types to be retransformed which have changed compared to the previous
* class file transformer that is provided as an argument.
* </p>
* <p>
* In order to assure the correct handling of the {@link InstallationListener}, an uninstallation should be applied
* via the {@link ResettableClassFileTransformer}'s {@code reset} methods.
* </p>
*
* @param classFileTransformer The class file transformer that is being patched.
* @return The installed class file transformer.
* @see AgentBuilder#patchOn(Instrumentation, ResettableClassFileTransformer)
*/
ResettableClassFileTransformer patchOnByteBuddyAgent(ResettableClassFileTransformer classFileTransformer);
/**
* An abstraction for extending a matcher.
*
* @param <T> The type that is produced by chaining a matcher.
*/
interface Matchable<T extends Matchable<T>> {
/**
* Defines a matching that is positive if both the previous matcher and the supplied matcher are matched. When matching a
* type, class loaders are not considered.
*
* @param typeMatcher A matcher for the type being matched.
* @return A chained matcher.
*/
T and(ElementMatcher<? super TypeDescription> typeMatcher);
/**
* Defines a matching that is positive if both the previous matcher and the supplied matcher are matched.
*
* @param typeMatcher A matcher for the type being matched.
* @param classLoaderMatcher A matcher for the type's class loader.
* @return A chained matcher.
*/
T and(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher);
/**
* Defines a matching that is positive if both the previous matcher and the supplied matcher are matched.
*
* @param typeMatcher A matcher for the type being matched.
* @param classLoaderMatcher A matcher for the type's class loader.
* @param moduleMatcher A matcher for the type's module. On a JVM that does not support modules, the Java module is represented by {@code null}.
* @return A chained matcher.
*/
T and(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher);
/**
* Defines a matching that is positive if both the previous matcher and the supplied matcher are matched.
*
* @param rawMatcher A raw matcher for the type being matched.
* @return A chained matcher.
*/
T and(RawMatcher rawMatcher);
/**
* Defines a matching that is positive if the previous matcher or the supplied matcher are matched. When matching a
* type, the class loader is not considered.
*
* @param typeMatcher A matcher for the type being matched.
* @return A chained matcher.
*/
T or(ElementMatcher<? super TypeDescription> typeMatcher);
/**
* Defines a matching that is positive if the previous matcher or the supplied matcher are matched.
*
* @param typeMatcher A matcher for the type being matched.
* @param classLoaderMatcher A matcher for the type's class loader.
* @return A chained matcher.
*/
T or(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher);
/**
* Defines a matching that is positive if the previous matcher or the supplied matcher are matched.
*
* @param typeMatcher A matcher for the type being matched.
* @param classLoaderMatcher A matcher for the type's class loader.
* @param moduleMatcher A matcher for the type's module. On a JVM that does not support modules, the Java module is represented by {@code null}.
* @return A chained matcher.
*/
T or(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher);
/**
* Defines a matching that is positive if the previous matcher or the supplied matcher are matched.
*
* @param rawMatcher A raw matcher for the type being matched.
* @return A chained matcher.
*/
T or(RawMatcher rawMatcher);
/**
* An abstract base implementation of a matchable.
*
* @param <S> The type that is produced by chaining a matcher.
*/
abstract class AbstractBase<S extends Matchable<S>> implements Matchable<S> {
/**
* {@inheritDoc}
*/
public S and(ElementMatcher<? super TypeDescription> typeMatcher) {
return and(typeMatcher, any());
}
/**
* {@inheritDoc}
*/
public S and(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) {
return and(typeMatcher, classLoaderMatcher, any());
}
/**
* {@inheritDoc}
*/
public S and(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return and(new RawMatcher.ForElementMatchers(typeMatcher, classLoaderMatcher, moduleMatcher));
}
/**
* {@inheritDoc}
*/
public S or(ElementMatcher<? super TypeDescription> typeMatcher) {
return or(typeMatcher, any());
}
/**
* {@inheritDoc}
*/
public S or(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) {
return or(typeMatcher, classLoaderMatcher, any());
}
/**
* {@inheritDoc}
*/
public S or(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return or(new RawMatcher.ForElementMatchers(typeMatcher, classLoaderMatcher, moduleMatcher));
}
}
}
/**
* Allows to further specify ignored types.
*/
interface Ignored extends Matchable<Ignored>, AgentBuilder {
/* this is merely a unionizing interface that does not declare methods */
}
/**
* An agent builder configuration that allows the registration of listeners to the redefinition process.
*/
interface RedefinitionListenable extends AgentBuilder {
/**
* <p>
* A redefinition listener is invoked before each batch of type redefinitions and on every error as well as
* after the redefinition was completed. A redefinition listener can be used for debugging or logging purposes
* and to apply actions between each batch, e.g. to pause or wait in order to avoid rendering the current VM
* non-responsive if a lot of classes are redefined.
* </p>
* <p>
* Adding several listeners does not replace previous listeners but applies them in the registration order.
* </p>
*
* @param redefinitionListener The listener to register.
* @return A new instance of this agent builder which notifies the specified listener upon type redefinitions.
*/
RedefinitionListenable with(RedefinitionStrategy.Listener redefinitionListener);
/**
* Enables resubmission of failed transformations by applying a retransformation of the loaded type. This can be meaningful if
* class files cannot be located from the class loader as a resource where the loaded type becomes available.
*
* @param resubmissionScheduler A scheduler which is responsible for scheduling the resubmission job.
* @return A new instance of this agent builder that applies resubmission.
*/
AgentBuilder withResubmission(RedefinitionStrategy.ResubmissionScheduler resubmissionScheduler);
/**
* Enables resubmission of failed transformations by applying a retransformation of the loaded type. This can be meaningful if
* class files cannot be located from the class loader as a resource where the loaded type becomes available.
*
* @param resubmissionScheduler A scheduler which is responsible for scheduling the resubmission job.
* @param matcher A matcher that filters throwable instances where non-matched throwables are not triggering a resubmission.
* @return A new instance of this agent builder that applies resubmission.
*/
AgentBuilder withResubmission(RedefinitionStrategy.ResubmissionScheduler resubmissionScheduler, ElementMatcher<? super Throwable> matcher);
/**
* An agent builder configuration strategy that allows the definition of a discovery strategy.
*/
interface WithImplicitDiscoveryStrategy extends RedefinitionListenable {
/**
* Limits the redefinition attempt to the specified types.
*
* @param type The types to consider for redefinition.
* @return A new instance of this agent builder which only considers the supplied types for redefinition.
*/
RedefinitionListenable redefineOnly(Class<?>... type);
/**
* A discovery strategy is responsible for locating loaded types that should be considered for redefinition.
*
* @param redefinitionDiscoveryStrategy The redefinition discovery strategy to use.
* @return A new instance of this agent builder which makes use of the specified discovery strategy.
*/
RedefinitionListenable with(RedefinitionStrategy.DiscoveryStrategy redefinitionDiscoveryStrategy);
}
/**
* An agent builder configuration that allows the configuration of a batching strategy.
*/
interface WithoutBatchStrategy extends WithImplicitDiscoveryStrategy {
/**
* A batch allocator is responsible for diving a redefining of existing types into several chunks. This allows
* to narrow down errors for the redefining of specific types or to apply a {@link RedefinitionStrategy.Listener}
* action between chunks.
*
* @param redefinitionBatchAllocator The batch allocator to use.
* @return A new instance of this agent builder which makes use of the specified batch allocator.
*/
WithImplicitDiscoveryStrategy with(RedefinitionStrategy.BatchAllocator redefinitionBatchAllocator);
}
}
/**
* Describes an {@link net.bytebuddy.agent.builder.AgentBuilder} which was handed a matcher for identifying
* types to instrumented in order to supply one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s.
*/
interface Identified {
/**
* Applies the given transformer for the already supplied matcher.
*
* @param transformer The transformer to apply.
* @return A new instance of this agent builder with the transformer being applied when the previously supplied matcher
* identified a type for instrumentation which also allows for the registration of subsequent transformers.
*/
Extendable transform(Transformer transformer);
/**
* Allows to specify a type matcher for a type to instrument.
*/
interface Narrowable extends Matchable<Narrowable>, Identified {
/* this is merely a unionizing interface that does not declare methods */
}
/**
* This interface is used to allow for optionally providing several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer} to applied when a matcher identifies a type
* to be instrumented. Any subsequent transformers are applied in the order they are registered.
*/
interface Extendable extends AgentBuilder, Identified {
/**
* Applies the previously defined transformation as terminal such that no subsequent transformers are applied even
* if their matchers would include the type that was matched for applying this transformer. If this option is not set,
* subsequent transformations are applied after this transformation such that it is possible that they override non-additive
* type transformations.
*
* @return A new agent builder that applies the previously configured transformer terminally.
*/
AgentBuilder asTerminalTransformation();
}
}
/**
* A matcher that allows to determine if a {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}
* should be applied during the execution of a {@link java.lang.instrument.ClassFileTransformer} that was
* generated by an {@link net.bytebuddy.agent.builder.AgentBuilder}.
*/
interface RawMatcher {
/**
* Decides if the given {@code typeDescription} should be instrumented with the entailed
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s.
*
* @param typeDescription A description of the type to be instrumented.
* @param classLoader The class loader of the instrumented type. Might be {@code null} if this class
* loader represents the bootstrap class loader.
* @param module The transformed type's module or {@code null} if the current VM does not support modules.
* @param classBeingRedefined The class being redefined which is only not {@code null} if a retransformation
* is applied.
* @param protectionDomain The protection domain of the type being transformed.
* @return {@code true} if the entailed {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should
* be applied for the given {@code typeDescription}.
*/
boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain);
/**
* A matcher that always or never matches a type.
*/
enum Trivial implements RawMatcher {
/**
* Always matches a type.
*/
MATCHING(true),
/**
* Never matches a type.
*/
NON_MATCHING(false);
/**
* {@code true} if this matcher always matches a type.
*/
private final boolean matches;
/**
* Creates a new trivial raw matcher.
*
* @param matches {@code true} if this matcher always matches a type.
*/
Trivial(boolean matches) {
this.matches = matches;
}
/**
* {@inheritDoc}
*/
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return matches;
}
}
/**
* A raw matcher indicating the state of a type's class loading.
*/
enum ForLoadState implements RawMatcher {
/**
* Indicates that a type was already loaded.
*/
LOADED(false),
/**
* Indicates that a type was not yet loaded.
*/
UNLOADED(true);
/**
* {@code true} if a type is expected to be unloaded..
*/
private final boolean unloaded;
/**
* Creates a new load state matcher.
*
* @param unloaded {@code true} if a type is expected to be unloaded..
*/
ForLoadState(boolean unloaded) {
this.unloaded = unloaded;
}
/**
* {@inheritDoc}
*/
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return classBeingRedefined == null == unloaded;
}
}
/**
* Only matches loaded types that can be fully resolved. Types with missing dependencies might not be
* resolvable and can therefore trigger errors during redefinition.
*/
enum ForResolvableTypes implements RawMatcher {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
if (classBeingRedefined != null) {
try {
return Class.forName(classBeingRedefined.getName(), true, classLoader) == classBeingRedefined;
} catch (Throwable ignored) {
return false;
}
} else {
return true;
}
}
/**
* Returns an inverted version of this matcher.
*
* @return An inverted version of this matcher.
*/
public RawMatcher inverted() {
return new Inversion(this);
}
}
/**
* A conjunction of two raw matchers.
*/
@HashCodeAndEqualsPlugin.Enhance
class Conjunction implements RawMatcher {
/**
* The left matcher which is applied first.
*/
private final RawMatcher left;
/**
* The right matcher which is applied second.
*/
private final RawMatcher right;
/**
* Creates a new conjunction of two raw matchers.
*
* @param left The left matcher which is applied first.
* @param right The right matcher which is applied second.
*/
protected Conjunction(RawMatcher left, RawMatcher right) {
this.left = left;
this.right = right;
}
/**
* {@inheritDoc}
*/
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return left.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)
&& right.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain);
}
}
/**
* A disjunction of two raw matchers.
*/
@HashCodeAndEqualsPlugin.Enhance
class Disjunction implements RawMatcher {
/**
* The left matcher which is applied first.
*/
private final RawMatcher left;
/**
* The right matcher which is applied second.
*/
private final RawMatcher right;
/**
* Creates a new disjunction of two raw matchers.
*
* @param left The left matcher which is applied first.
* @param right The right matcher which is applied second.
*/
protected Disjunction(RawMatcher left, RawMatcher right) {
this.left = left;
this.right = right;
}
/**
* {@inheritDoc}
*/
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return left.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)
|| right.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain);
}
}
/**
* A raw matcher that inverts a raw matcher's result.
*/
@HashCodeAndEqualsPlugin.Enhance
class Inversion implements RawMatcher {
/**
* The matcher to invert.
*/
private final RawMatcher matcher;
/**
* Creates a raw matcher that inverts its result.
*
* @param matcher The matcher to invert.
*/
public Inversion(RawMatcher matcher) {
this.matcher = matcher;
}
/**
* {@inheritDoc}
*/
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return !matcher.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain);
}
}
/**
* A raw matcher implementation that checks a {@link TypeDescription}
* and its {@link java.lang.ClassLoader} against two suitable matchers in order to determine if the matched
* type should be instrumented.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForElementMatchers implements RawMatcher {
/**
* The type matcher to apply to a {@link TypeDescription}.
*/
private final ElementMatcher<? super TypeDescription> typeMatcher;
/**
* The class loader matcher to apply to a {@link java.lang.ClassLoader}.
*/
private final ElementMatcher<? super ClassLoader> classLoaderMatcher;
/**
* A module matcher to apply to a {@code java.lang.Module}.
*/
private final ElementMatcher<? super JavaModule> moduleMatcher;
/**
* Creates a new {@link net.bytebuddy.agent.builder.AgentBuilder.RawMatcher} that only matches the
* supplied {@link TypeDescription} against a supplied matcher.
*
* @param typeMatcher The type matcher to apply to a {@link TypeDescription}.
*/
public ForElementMatchers(ElementMatcher<? super TypeDescription> typeMatcher) {
this(typeMatcher, any());
}
/**
* Creates a new {@link net.bytebuddy.agent.builder.AgentBuilder.RawMatcher} that only matches the
* supplied {@link TypeDescription} and its {@link java.lang.ClassLoader} against two matcher in order
* to decided if an instrumentation should be conducted.
*
* @param typeMatcher The type matcher to apply to a {@link TypeDescription}.
* @param classLoaderMatcher The class loader matcher to apply to a {@link java.lang.ClassLoader}.
*/
public ForElementMatchers(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher) {
this(typeMatcher, classLoaderMatcher, any());
}
/**
* Creates a new {@link net.bytebuddy.agent.builder.AgentBuilder.RawMatcher} that only matches the
* supplied {@link TypeDescription}, its {@link java.lang.ClassLoader} and module against element
* suitable matchers.
*
* @param typeMatcher The type matcher to apply to a {@link TypeDescription}.
* @param classLoaderMatcher The class loader matcher to apply to a {@link java.lang.ClassLoader}.
* @param moduleMatcher A module matcher to apply to a {@code java.lang.Module}.
*/
public ForElementMatchers(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
this.typeMatcher = typeMatcher;
this.classLoaderMatcher = classLoaderMatcher;
this.moduleMatcher = moduleMatcher;
}
/**
* {@inheritDoc}
*/
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return moduleMatcher.matches(module) && classLoaderMatcher.matches(classLoader) && typeMatcher.matches(typeDescription);
}
}
}
/**
* A listener that is informed about events that occur during an instrumentation process.
*/
interface Listener {
/**
* Indicates that a transformed type is loaded.
*/
boolean LOADED = true;
/**
* Invoked upon a type being supplied to a transformer.
*
* @param typeName The binary name of the instrumented type.
* @param classLoader The class loader which is loading this type.
* @param module The instrumented type's module or {@code null} if the current VM does not support modules.
* @param loaded {@code true} if the type is already loaded.
*/
void onDiscovery(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded);
/**
* Invoked prior to a successful transformation being applied.
*
* @param typeDescription The type that is being transformed.
* @param classLoader The class loader which is loading this type.
* @param module The transformed type's module or {@code null} if the current VM does not support modules.
* @param loaded {@code true} if the type is already loaded.
* @param dynamicType The dynamic type that was created.
*/
void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType);
/**
* Invoked when a type is not transformed but ignored.
*
* @param typeDescription The type being ignored for transformation.
* @param classLoader The class loader which is loading this type.
* @param module The ignored type's module or {@code null} if the current VM does not support modules.
* @param loaded {@code true} if the type is already loaded.
*/
void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded);
/**
* Invoked when an error has occurred during transformation.
*
* @param typeName The binary name of the instrumented type.
* @param classLoader The class loader which is loading this type.
* @param module The instrumented type's module or {@code null} if the current VM does not support modules.
* @param loaded {@code true} if the type is already loaded.
* @param throwable The occurred error.
*/
void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable);
/**
* Invoked after a class was attempted to be loaded, independently of its treatment.
*
* @param typeName The binary name of the instrumented type.
* @param classLoader The class loader which is loading this type.
* @param module The instrumented type's module or {@code null} if the current VM does not support modules.
* @param loaded {@code true} if the type is already loaded.
*/
void onComplete(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded);
/**
* A no-op implementation of a {@link net.bytebuddy.agent.builder.AgentBuilder.Listener}.
*/
enum NoOp implements Listener {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public void onDiscovery(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onComplete(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
/* do nothing */
}
}
/**
* An adapter for a listener where all methods are implemented as non-operational.
*/
abstract class Adapter implements Listener {
/**
* {@inheritDoc}
*/
public void onDiscovery(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onComplete(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
/* do nothing */
}
}
/**
* A listener that writes events to a {@link PrintStream}. This listener prints a line per event, including the event type and
* the name of the type in question.
*/
@HashCodeAndEqualsPlugin.Enhance
class StreamWriting implements Listener {
/**
* The prefix that is appended to all written messages.
*/
protected static final String PREFIX = "[Byte Buddy]";
/**
* The print stream written to.
*/
private final PrintStream printStream;
/**
* Creates a new stream writing listener.
*
* @param printStream The print stream written to.
*/
public StreamWriting(PrintStream printStream) {
this.printStream = printStream;
}
/**
* Creates a new stream writing listener that writes to {@link System#out}.
*
* @return A listener writing events to the standard output stream.
*/
public static StreamWriting toSystemOut() {
return new StreamWriting(System.out);
}
/**
* Creates a new stream writing listener that writes to {@link System#err}.
*
* @return A listener writing events to the standard error stream.
*/
public static StreamWriting toSystemError() {
return new StreamWriting(System.err);
}
/**
* Returns a version of this listener that only reports successfully transformed classes and failed transformations.
*
* @return A version of this listener that only reports successfully transformed classes and failed transformations.
*/
public Listener withTransformationsOnly() {
return new WithTransformationsOnly(this);
}
/**
* Returns a version of this listener that only reports failed transformations.
*
* @return A version of this listener that only reports failed transformations.
*/
public Listener withErrorsOnly() {
return new WithErrorsOnly(this);
}
/**
* {@inheritDoc}
*/
public void onDiscovery(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
printStream.printf(PREFIX + " DISCOVERY %s [%s, %s, loaded=%b]%n", typeName, classLoader, module, loaded);
}
/**
* {@inheritDoc}
*/
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType) {
printStream.printf(PREFIX + " TRANSFORM %s [%s, %s, loaded=%b]%n", typeDescription.getName(), classLoader, module, loaded);
}
/**
* {@inheritDoc}
*/
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded) {
printStream.printf(PREFIX + " IGNORE %s [%s, %s, loaded=%b]%n", typeDescription.getName(), classLoader, module, loaded);
}
/**
* {@inheritDoc}
*/
public void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable) {
synchronized (printStream) {
printStream.printf(PREFIX + " ERROR %s [%s, %s, loaded=%b]%n", typeName, classLoader, module, loaded);
throwable.printStackTrace(printStream);
}
}
/**
* {@inheritDoc}
*/
public void onComplete(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
printStream.printf(PREFIX + " COMPLETE %s [%s, %s, loaded=%b]%n", typeName, classLoader, module, loaded);
}
}
/**
* A listener that filters types with a given name from being logged.
*/
@HashCodeAndEqualsPlugin.Enhance
class Filtering implements Listener {
/**
* The matcher to decide upon a type should be logged.
*/
private final ElementMatcher<? super String> matcher;
/**
* The delegate listener.
*/
private final Listener delegate;
/**
* Creates a new filtering listener.
*
* @param matcher The matcher to decide upon a type should be logged.
* @param delegate The delegate listener.
*/
public Filtering(ElementMatcher<? super String> matcher, Listener delegate) {
this.matcher = matcher;
this.delegate = delegate;
}
/**
* {@inheritDoc}
*/
public void onDiscovery(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
if (matcher.matches(typeName)) {
delegate.onDiscovery(typeName, classLoader, module, loaded);
}
}
/**
* {@inheritDoc}
*/
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType) {
if (matcher.matches(typeDescription.getName())) {
delegate.onTransformation(typeDescription, classLoader, module, loaded, dynamicType);
}
}
/**
* {@inheritDoc}
*/
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded) {
if (matcher.matches(typeDescription.getName())) {
delegate.onIgnored(typeDescription, classLoader, module, loaded);
}
}
/**
* {@inheritDoc}
*/
public void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable) {
if (matcher.matches(typeName)) {
delegate.onError(typeName, classLoader, module, loaded, throwable);
}
}
/**
* {@inheritDoc}
*/
public void onComplete(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
if (matcher.matches(typeName)) {
delegate.onComplete(typeName, classLoader, module, loaded);
}
}
}
/**
* A listener that only delegates events if they are successful or failed transformations.
*/
@HashCodeAndEqualsPlugin.Enhance
class WithTransformationsOnly extends Adapter {
/**
* The delegate listener.
*/
private final Listener delegate;
/**
* Creates a new listener that only delegates events if they are successful or failed transformations.
*
* @param delegate The delegate listener.
*/
public WithTransformationsOnly(Listener delegate) {
this.delegate = delegate;
}
@Override
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType) {
delegate.onTransformation(typeDescription, classLoader, module, loaded, dynamicType);
}
@Override
public void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable) {
delegate.onError(typeName, classLoader, module, loaded, throwable);
}
}
/**
* A listener that only delegates events if they are failed transformations.
*/
@HashCodeAndEqualsPlugin.Enhance
class WithErrorsOnly extends Adapter {
/**
* The delegate listener.
*/
private final Listener delegate;
/**
* Creates a new listener that only delegates events if they are failed transformations.
*
* @param delegate The delegate listener.
*/
public WithErrorsOnly(Listener delegate) {
this.delegate = delegate;
}
@Override
public void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable) {
delegate.onError(typeName, classLoader, module, loaded, throwable);
}
}
/**
* A listener that adds read-edges to any module of an instrumented class upon its transformation and opens the class's package to the module.
*/
@HashCodeAndEqualsPlugin.Enhance
class ModuleReadEdgeCompleting extends Adapter {
/**
* The instrumentation instance used for adding read edges.
*/
private final Instrumentation instrumentation;
/**
* {@code true} if the listener should also add a read-edge from the supplied modules to the instrumented type's module.
* This will also ensure that the package of the instrumented type is exported to the target module.
*/
private final boolean addTargetEdge;
/**
* The modules to add as a read edge to any transformed class's module.
*/
private final Set<? extends JavaModule> modules;
/**
* Creates a new module read-edge completing listener.
*
* @param instrumentation The instrumentation instance used for adding read edges.
* @param addTargetEdge {@code true} if the listener should also add a read-edge from the supplied
* modules to the instrumented type's module. This will also ensure that the package
* of the instrumented type is exported to the target module.
* @param modules The modules to add as a read edge to any transformed class's module.
*/
public ModuleReadEdgeCompleting(Instrumentation instrumentation, boolean addTargetEdge, Set<? extends JavaModule> modules) {
this.instrumentation = instrumentation;
this.addTargetEdge = addTargetEdge;
this.modules = modules;
}
/**
* Resolves a listener that adds module edges from and to the instrumented type's module.
*
* @param instrumentation The instrumentation instance used for adding read edges.
* @param addTargetEdge {@code true} if the listener should also add a read-edge from the supplied
* modules to the instrumented type's module. This will also ensure that the package
* of the instrumented type is exported to the target module.
* @param type The types for which to extract the modules.
* @return An appropriate listener.
*/
public static Listener of(Instrumentation instrumentation, boolean addTargetEdge, Class<?>... type) {
Set<JavaModule> modules = new HashSet<JavaModule>();
for (Class<?> aType : type) {
modules.add(JavaModule.ofType(aType));
}
return modules.isEmpty()
? Listener.NoOp.INSTANCE
: new Listener.ModuleReadEdgeCompleting(instrumentation, addTargetEdge, modules);
}
@Override
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType) {
if (module != JavaModule.UNSUPPORTED && module.isNamed()) {
for (JavaModule target : modules) {
if (!module.canRead(target) || addTargetEdge && !module.isOpened(typeDescription.getPackage(), target)) {
module.modify(instrumentation,
Collections.singleton(target),
Collections.<String, Set<JavaModule>>emptyMap(),
!addTargetEdge || typeDescription.getPackage() == null
? Collections.<String, Set<JavaModule>>emptyMap()
: Collections.singletonMap(typeDescription.getPackage().getName(), Collections.singleton(target)),
Collections.<Class<?>>emptySet(),
Collections.<Class<?>, List<Class<?>>>emptyMap());
}
if (addTargetEdge && !target.canRead(module)) {
target.modify(instrumentation,
Collections.singleton(module),
Collections.<String, Set<JavaModule>>emptyMap(),
Collections.<String, Set<JavaModule>>emptyMap(),
Collections.<Class<?>>emptySet(),
Collections.<Class<?>, List<Class<?>>>emptyMap());
}
}
}
}
}
/**
* A compound listener that allows to group several listeners in one instance.
*/
@HashCodeAndEqualsPlugin.Enhance
class Compound implements Listener {
/**
* The listeners that are represented by this compound listener in their application order.
*/
private final List<Listener> listeners;
/**
* Creates a new compound listener.
*
* @param listener The listeners to apply in their application order.
*/
public Compound(Listener... listener) {
this(Arrays.asList(listener));
}
/**
* Creates a new compound listener.
*
* @param listeners The listeners to apply in their application order.
*/
public Compound(List<? extends Listener> listeners) {
this.listeners = new ArrayList<Listener>();
for (Listener listener : listeners) {
if (listener instanceof Compound) {
this.listeners.addAll(((Compound) listener).listeners);
} else if (!(listener instanceof NoOp)) {
this.listeners.add(listener);
}
}
}
/**
* {@inheritDoc}
*/
public void onDiscovery(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
for (Listener listener : listeners) {
listener.onDiscovery(typeName, classLoader, module, loaded);
}
}
/**
* {@inheritDoc}
*/
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType) {
for (Listener listener : listeners) {
listener.onTransformation(typeDescription, classLoader, module, loaded, dynamicType);
}
}
/**
* {@inheritDoc}
*/
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded) {
for (Listener listener : listeners) {
listener.onIgnored(typeDescription, classLoader, module, loaded);
}
}
/**
* {@inheritDoc}
*/
public void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable) {
for (Listener listener : listeners) {
listener.onError(typeName, classLoader, module, loaded, throwable);
}
}
/**
* {@inheritDoc}
*/
public void onComplete(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
for (Listener listener : listeners) {
listener.onComplete(typeName, classLoader, module, loaded);
}
}
}
}
/**
* A circularity lock is responsible for preventing that a {@link ClassFileLocator} is used recursively.
* This can happen when a class file transformation causes another class to be loaded. Without avoiding
* such circularities, a class loading is aborted by a {@link ClassCircularityError} which causes the
* class loading to fail.
*/
interface CircularityLock {
/**
* Attempts to acquire a circularity lock.
*
* @return {@code true} if the lock was acquired successfully, {@code false} if it is already hold.
*/
boolean acquire();
/**
* Releases the circularity lock if it is currently acquired.
*/
void release();
/**
* An inactive circularity lock which is always acquirable.
*/
enum Inactive implements CircularityLock {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public boolean acquire() {
return true;
}
/**
* {@inheritDoc}
*/
public void release() {
/* do nothing */
}
}
/**
* A default implementation of a circularity lock. Since class loading already synchronizes on a class loader,
* it suffices to apply a thread-local lock.
*/
class Default extends ThreadLocal<Boolean> implements CircularityLock {
/**
* Indicates that the circularity lock is not currently acquired.
*/
private static final Boolean NOT_ACQUIRED = null;
/**
* {@inheritDoc}
*/
public boolean acquire() {
if (get() == NOT_ACQUIRED) {
set(true);
return true;
} else {
return false;
}
}
/**
* {@inheritDoc}
*/
public void release() {
set(NOT_ACQUIRED);
}
}
/**
* A circularity lock that holds a global monitor and does not permit concurrent access.
*/
@HashCodeAndEqualsPlugin.Enhance
class Global implements CircularityLock {
/**
* The lock to hold.
*/
private final Lock lock;
/**
* The time to wait for the lock.
*/
private final long time;
/**
* The time's time unit.
*/
private final TimeUnit timeUnit;
/**
* Creates a new global circularity lock that does not wait for a release.
*/
public Global() {
this(0, TimeUnit.MILLISECONDS);
}
/**
* Creates a new global circularity lock.
*
* @param time The time to wait for the lock.
* @param timeUnit The time's time unit.
*/
public Global(long time, TimeUnit timeUnit) {
lock = new ReentrantLock();
this.time = time;
this.timeUnit = timeUnit;
}
/**
* {@inheritDoc}
*/
public boolean acquire() {
try {
return time == 0
? lock.tryLock()
: lock.tryLock(time, timeUnit);
} catch (InterruptedException ignored) {
return false;
}
}
/**
* {@inheritDoc}
*/
public void release() {
lock.unlock();
}
}
}
/**
* A type strategy is responsible for creating a type builder for a type that is being instrumented.
*/
interface TypeStrategy {
/**
* Creates a type builder for a given type.
*
* @param typeDescription The type being instrumented.
* @param byteBuddy The Byte Buddy configuration.
* @param classFileLocator The class file locator to use.
* @param methodNameTransformer The method name transformer to use.
* @param classLoader The instrumented type's class loader or {@code null} if the type is loaded by the bootstrap loader.
* @param module The instrumented type's module or {@code null} if it is not declared by a module.
* @param protectionDomain The instrumented type's protection domain or {@code null} if it does not define a protection domain.
* @return A type builder for the given arguments.
*/
DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodNameTransformer methodNameTransformer,
ClassLoader classLoader,
JavaModule module,
ProtectionDomain protectionDomain);
/**
* Default implementations of type strategies.
*/
enum Default implements TypeStrategy {
/**
* A definition handler that performs a rebasing for all types.
*/
REBASE {
/** {@inheritDoc} */
public DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodNameTransformer methodNameTransformer,
ClassLoader classLoader,
JavaModule module,
ProtectionDomain protectionDomain) {
return byteBuddy.rebase(typeDescription, classFileLocator, methodNameTransformer);
}
},
/**
* <p>
* A definition handler that performs a redefinition for all types.
* </p>
* <p>
* Note that the default agent builder is configured to apply a self initialization where a static class initializer
* is added to the redefined class. This can be disabled by for example using a {@link InitializationStrategy.Minimal} or
* {@link InitializationStrategy.NoOp}. Also, consider the constraints implied by {@link ByteBuddy#redefine(TypeDescription, ClassFileLocator)}.
* </p>
* <p>
* For prohibiting any changes on a class file, use {@link AgentBuilder#disableClassFormatChanges()}
* </p>
*/
REDEFINE {
/** {@inheritDoc} */
public DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodNameTransformer methodNameTransformer,
ClassLoader classLoader,
JavaModule module,
ProtectionDomain protectionDomain) {
return byteBuddy.redefine(typeDescription, classFileLocator);
}
},
/**
* <p>
* A definition handler that performs a redefinition for all types and ignores all methods that were not declared by the instrumented type.
* </p>
* <p>
* Note that the default agent builder is configured to apply a self initialization where a static class initializer
* is added to the redefined class. This can be disabled by for example using a {@link InitializationStrategy.Minimal} or
* {@link InitializationStrategy.NoOp}. Also, consider the constraints implied by {@link ByteBuddy#redefine(TypeDescription, ClassFileLocator)}.
* Using this strategy also configures Byte Buddy to create frozen instrumented types and discards any explicit configuration.
* </p>
* <p>
* For prohibiting any changes on a class file, use {@link AgentBuilder#disableClassFormatChanges()}
* </p>
*/
REDEFINE_FROZEN {
/** {@inheritDoc} */
public DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodNameTransformer methodNameTransformer,
ClassLoader classLoader,
JavaModule module,
ProtectionDomain protectionDomain) {
return byteBuddy.with(InstrumentedType.Factory.Default.FROZEN)
.with(VisibilityBridgeStrategy.Default.NEVER)
.redefine(typeDescription, classFileLocator)
.ignoreAlso(LatentMatcher.ForSelfDeclaredMethod.NOT_DECLARED);
}
},
/**
* <p>
* A definition handler that performs a decoration of declared methods only. Using this type strategy
* implies the limitations that are described by {@link ByteBuddy#decorate(TypeDescription, ClassFileLocator)}.
* This type strategy can be useful when only applying {@link AsmVisitorWrapper}s without attempting to change
* the class file layout..
* </p>
* <p>
* Note that the default agent builder is configured to apply a self initialization where a static class initializer
* is added to the redefined class. This can be disabled by for example using a {@link InitializationStrategy.Minimal} or
* {@link InitializationStrategy.NoOp}. Also, consider the constraints implied by {@link ByteBuddy#redefine(TypeDescription, ClassFileLocator)}.
* Using this strategy also configures Byte Buddy to create frozen instrumented types and discards any explicit configuration.
* </p>
* <p>
* For prohibiting any changes on a class file, use {@link AgentBuilder#disableClassFormatChanges()}
* </p>
*/
DECORATE {
/** {@inheritDoc} */
public DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodNameTransformer methodNameTransformer,
ClassLoader classLoader,
JavaModule module,
ProtectionDomain protectionDomain) {
return byteBuddy.decorate(typeDescription, classFileLocator);
}
}
}
/**
* A type strategy that applies a build {@link EntryPoint}.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForBuildEntryPoint implements TypeStrategy {
/**
* The entry point to apply.
*/
private final EntryPoint entryPoint;
/**
* Creates a new type strategy for an entry point.
*
* @param entryPoint The entry point to apply.
*/
public ForBuildEntryPoint(EntryPoint entryPoint) {
this.entryPoint = entryPoint;
}
/**
* {@inheritDoc}
*/
public DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodNameTransformer methodNameTransformer,
ClassLoader classLoader,
JavaModule module,
ProtectionDomain protectionDomain) {
return entryPoint.transform(typeDescription, byteBuddy, classFileLocator, methodNameTransformer);
}
}
}
/**
* A transformer allows to apply modifications to a {@link net.bytebuddy.dynamic.DynamicType}. Such a modification
* is then applied to any instrumented type that was matched by the preceding matcher.
*/
interface Transformer {
/**
* Allows for a transformation of a {@link net.bytebuddy.dynamic.DynamicType.Builder}.
*
* @param builder The dynamic builder to transform.
* @param typeDescription The description of the type currently being instrumented.
* @param classLoader The class loader of the instrumented class. Might be {@code null} to represent the bootstrap class loader.
* @param module The class's module or {@code null} if the current VM does not support modules.
* @return A transformed version of the supplied {@code builder}.
*/
DynamicType.Builder<?> transform(DynamicType.Builder<?> builder,
TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module);
/**
* A transformer that applies a build {@link Plugin}. Note that a transformer is never completed as class loading
* might happen dynamically such that plugins are not closed.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForBuildPlugin implements Transformer {
/**
* The plugin to apply.
*/
private final Plugin plugin;
/**
* Creates a new transformer for a build {@link Plugin}.
*
* @param plugin The plugin to apply.
*/
public ForBuildPlugin(Plugin plugin) {
this.plugin = plugin;
}
/**
* {@inheritDoc}
*/
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder,
TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module) {
return plugin.apply(builder, typeDescription, ClassFileLocator.ForClassLoader.of(classLoader));
}
}
/**
* A transformer for applying an {@link Advice} where this advice class might reference types of both the agent's and the user's
* class loader. Using this transformer, it is possible to apply advice without including any library dependencies of this advice
* class which are then rather looked up from the transformed class's class loader. For this to work, it is required to register
* the advice class's class loader manually via the {@code include} methods and to reference the advice class by its fully-qualified
* name. The advice class is then never loaded by rather described by a {@link TypePool}.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForAdvice implements Transformer {
/**
* The advice to use.
*/
private final Advice.WithCustomMapping advice;
/**
* The exception handler to register for the advice.
*/
private final Advice.ExceptionHandler exceptionHandler;
/**
* The assigner to use for the advice.
*/
private final Assigner assigner;
/**
* The class file locator to query for the advice class.
*/
private final ClassFileLocator classFileLocator;
/**
* The pool strategy to use for looking up an advice.
*/
private final PoolStrategy poolStrategy;
/**
* The location strategy to use for class loaders when resolving advice classes.
*/
private final LocationStrategy locationStrategy;
/**
* The advice entries to apply.
*/
private final List<Entry> entries;
/**
* Creates a new advice transformer with a default setup.
*/
public ForAdvice() {
this(Advice.withCustomMapping());
}
/**
* Creates a new advice transformer which applies the given advice.
*
* @param advice The configured advice to use.
*/
public ForAdvice(Advice.WithCustomMapping advice) {
this(advice,
Advice.ExceptionHandler.Default.SUPPRESSING,
Assigner.DEFAULT,
ClassFileLocator.NoOp.INSTANCE,
PoolStrategy.Default.FAST,
LocationStrategy.ForClassLoader.STRONG,
Collections.<Entry>emptyList());
}
/**
* Creates a new advice transformer.
*
* @param advice The configured advice to use.
* @param exceptionHandler The exception handler to use.
* @param assigner The assigner to use.
* @param classFileLocator The class file locator to use.
* @param poolStrategy The pool strategy to use for looking up an advice.
* @param locationStrategy The location strategy to use for class loaders when resolving advice classes.
* @param entries The advice entries to apply.
*/
protected ForAdvice(Advice.WithCustomMapping advice,
Advice.ExceptionHandler exceptionHandler,
Assigner assigner,
ClassFileLocator classFileLocator,
PoolStrategy poolStrategy,
LocationStrategy locationStrategy,
List<Entry> entries) {
this.advice = advice;
this.exceptionHandler = exceptionHandler;
this.assigner = assigner;
this.classFileLocator = classFileLocator;
this.poolStrategy = poolStrategy;
this.locationStrategy = locationStrategy;
this.entries = entries;
}
/**
* {@inheritDoc}
*/
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder,
TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module) {
ClassFileLocator classFileLocator = new ClassFileLocator.Compound(this.classFileLocator, locationStrategy.classFileLocator(classLoader, module));
TypePool typePool = poolStrategy.typePool(classFileLocator, classLoader);
AsmVisitorWrapper.ForDeclaredMethods asmVisitorWrapper = new AsmVisitorWrapper.ForDeclaredMethods();
for (Entry entry : entries) {
asmVisitorWrapper = asmVisitorWrapper.invokable(entry.getMatcher().resolve(typeDescription), entry.resolve(advice, typePool, classFileLocator)
.withAssigner(assigner)
.withExceptionHandler(exceptionHandler));
}
return builder.visit(asmVisitorWrapper);
}
/**
* Registers a pool strategy for creating a {@link TypePool} that should be used for creating the advice class.
*
* @param poolStrategy The pool strategy to use.
* @return A new instance of this advice transformer that applies the supplied pool strategy.
*/
public ForAdvice with(PoolStrategy poolStrategy) {
return new ForAdvice(advice, exceptionHandler, assigner, classFileLocator, poolStrategy, locationStrategy, entries);
}
/**
* Registers a location strategy for creating a {@link ClassFileLocator} from the class loader that is supplied during transformation
* that should be used for looking up advice-relevant classes.
*
* @param locationStrategy The location strategy to use.
* @return A new instance of this advice transformer that applies the supplied location strategy.
*/
public ForAdvice with(LocationStrategy locationStrategy) {
return new ForAdvice(advice, exceptionHandler, assigner, classFileLocator, poolStrategy, locationStrategy, entries);
}
/**
* Registers an exception handler for suppressed exceptions to use by the registered advice.
*
* @param exceptionHandler The exception handler to use.
* @return A new instance of this advice transformer that applies the supplied exception handler.
* @see Advice#withExceptionHandler(StackManipulation)
*/
public ForAdvice withExceptionHandler(Advice.ExceptionHandler exceptionHandler) {
return new ForAdvice(advice, exceptionHandler, assigner, classFileLocator, poolStrategy, locationStrategy, entries);
}
/**
* Registers an assigner to be used by the advice class.
*
* @param assigner The assigner to use.
* @return A new instance of this advice transformer that applies the supplied assigner.
* @see Advice#withAssigner(Assigner)
*/
public ForAdvice with(Assigner assigner) {
return new ForAdvice(advice, exceptionHandler, assigner, classFileLocator, poolStrategy, locationStrategy, entries);
}
/**
* Includes the supplied class loaders as a source for looking up an advice class or its dependencies.
* Note that the supplied class loaders are queried for types before the class loader of the instrumented class.
*
* @param classLoader The class loaders to include when looking up classes in their order. Duplicates are filtered.
* @return A new instance of this advice transformer that considers the supplied class loaders as a lookup source.
*/
public ForAdvice include(ClassLoader... classLoader) {
Set<ClassFileLocator> classFileLocators = new LinkedHashSet<ClassFileLocator>();
for (ClassLoader aClassLoader : classLoader) {
classFileLocators.add(ClassFileLocator.ForClassLoader.of(aClassLoader));
}
return include(new ArrayList<ClassFileLocator>(classFileLocators));
}
/**
* Includes the supplied class file locators as a source for looking up an advice class or its dependencies.
* Note that the supplied class loaders are queried for types before the class loader of the instrumented class.
*
* @param classFileLocator The class file locators to include when looking up classes in their order. Duplicates are filtered.
* @return A new instance of this advice transformer that considers the supplied class file locators as a lookup source.
*/
public ForAdvice include(ClassFileLocator... classFileLocator) {
return include(Arrays.asList(classFileLocator));
}
/**
* Includes the supplied class file locators as a source for looking up an advice class or its dependencies.
* Note that the supplied class loaders are queried for types before the class loader of the instrumented class.
*
* @param classFileLocators The class file locators to include when looking up classes in their order. Duplicates are filtered.
* @return A new instance of this advice transformer that considers the supplied class file locators as a lookup source.
*/
public ForAdvice include(List<? extends ClassFileLocator> classFileLocators) {
return new ForAdvice(advice,
exceptionHandler,
assigner,
new ClassFileLocator.Compound(CompoundList.of(classFileLocator, classFileLocators)),
poolStrategy,
locationStrategy,
entries);
}
/**
* Applies the given advice class onto all methods that satisfy the supplied matcher.
*
* @param matcher The matcher to determine what methods the advice should be applied to.
* @param name The fully-qualified, binary name of the advice class.
* @return A new instance of this advice transformer that applies the given advice to all matched methods of an instrumented type.
*/
public ForAdvice advice(ElementMatcher<? super MethodDescription> matcher, String name) {
return advice(new LatentMatcher.Resolved<MethodDescription>(matcher), name);
}
/**
* Applies the given advice class onto all methods that satisfy the supplied matcher.
*
* @param matcher The matcher to determine what methods the advice should be applied to.
* @param name The fully-qualified, binary name of the advice class.
* @return A new instance of this advice transformer that applies the given advice to all matched methods of an instrumented type.
*/
public ForAdvice advice(LatentMatcher<? super MethodDescription> matcher, String name) {
return new ForAdvice(advice,
exceptionHandler,
assigner,
classFileLocator,
poolStrategy,
locationStrategy,
CompoundList.of(entries, new Entry.ForUnifiedAdvice(matcher, name)));
}
/**
* Applies the given advice class onto all methods that satisfy the supplied matcher.
*
* @param matcher The matcher to determine what methods the advice should be applied to.
* @param enter The fully-qualified, binary name of the enter advice class.
* @param exit The fully-qualified, binary name of the exit advice class.
* @return A new instance of this advice transformer that applies the given advice to all matched methods of an instrumented type.
*/
public ForAdvice advice(ElementMatcher<? super MethodDescription> matcher, String enter, String exit) {
return advice(new LatentMatcher.Resolved<MethodDescription>(matcher), enter, exit);
}
/**
* Applies the given advice class onto all methods that satisfy the supplied matcher.
*
* @param matcher The matcher to determine what methods the advice should be applied to.
* @param enter The fully-qualified, binary name of the enter advice class.
* @param exit The fully-qualified, binary name of the exit advice class.
* @return A new instance of this advice transformer that applies the given advice to all matched methods of an instrumented type.
*/
public ForAdvice advice(LatentMatcher<? super MethodDescription> matcher, String enter, String exit) {
return new ForAdvice(advice,
exceptionHandler,
assigner,
classFileLocator,
poolStrategy,
locationStrategy,
CompoundList.of(entries, new Entry.ForSplitAdvice(matcher, enter, exit)));
}
/**
* An entry for an advice to apply.
*/
@HashCodeAndEqualsPlugin.Enhance
protected abstract static class Entry {
/**
* The matcher for advised methods.
*/
private final LatentMatcher<? super MethodDescription> matcher;
/**
* Creates a new entry.
*
* @param matcher The matcher for advised methods.
*/
protected Entry(LatentMatcher<? super MethodDescription> matcher) {
this.matcher = matcher;
}
/**
* Returns the matcher for advised methods.
*
* @return The matcher for advised methods.
*/
protected LatentMatcher<? super MethodDescription> getMatcher() {
return matcher;
}
/**
* Resolves the advice for this entry.
*
* @param advice The advice configuration.
* @param typePool The type pool to use.
* @param classFileLocator The class file locator to use.
* @return The resolved advice.
*/
protected abstract Advice resolve(Advice.WithCustomMapping advice, TypePool typePool, ClassFileLocator classFileLocator);
/**
* An entry for an advice class where both the (optional) entry and exit advice methods are declared by the same class.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class ForUnifiedAdvice extends Entry {
/**
* The name of the advice class.
*/
protected final String name;
/**
* Creates a new entry for an advice class where both the (optional) entry and exit advice methods are declared by the same class.
*
* @param matcher The matcher for advised methods.
* @param name The name of the advice class.
*/
protected ForUnifiedAdvice(LatentMatcher<? super MethodDescription> matcher, String name) {
super(matcher);
this.name = name;
}
@Override
protected Advice resolve(Advice.WithCustomMapping advice, TypePool typePool, ClassFileLocator classFileLocator) {
return advice.to(typePool.describe(name).resolve(), classFileLocator);
}
}
/**
* An entry for an advice class where both entry and exit advice methods are declared by the different classes.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class ForSplitAdvice extends Entry {
/**
* The fully-qualified, binary name of the enter advice class.
*/
private final String enter;
/**
* The fully-qualified, binary name of the exit advice class.
*/
private final String exit;
/**
* Creates a new entry for an advice class with explicit entry and exit advice classes.
*
* @param matcher The matcher for advised methods.
* @param enter The fully-qualified, binary name of the enter advice class.
* @param exit The fully-qualified, binary name of the exit advice class.
*/
protected ForSplitAdvice(LatentMatcher<? super MethodDescription> matcher, String enter, String exit) {
super(matcher);
this.enter = enter;
this.exit = exit;
}
@Override
protected Advice resolve(Advice.WithCustomMapping advice, TypePool typePool, ClassFileLocator classFileLocator) {
return advice.to(typePool.describe(enter).resolve(), typePool.describe(exit).resolve(), classFileLocator);
}
}
}
}
}
/**
* A type locator allows to specify how {@link TypeDescription}s are resolved by an {@link net.bytebuddy.agent.builder.AgentBuilder}.
*/
interface PoolStrategy {
/**
* Creates a type pool for a given class file locator.
*
* @param classFileLocator The class file locator to use.
* @param classLoader The class loader for which the class file locator was created.
* @return A type pool for the supplied class file locator.
*/
TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader);
/**
* <p>
* A default type locator that resolves types only if any property that is not the type's name is requested.
* </p>
* <p>
* The returned type pool uses a {@link net.bytebuddy.pool.TypePool.CacheProvider.Simple} and the
* {@link ClassFileLocator} that is provided by the builder's {@link LocationStrategy}.
* </p>
*/
enum Default implements PoolStrategy {
/**
* A type locator that parses the code segment of each method for extracting information about parameter
* names even if they are not explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#EXTENDED
*/
EXTENDED(TypePool.Default.ReaderMode.EXTENDED),
/**
* A type locator that skips the code segment of each method and does therefore not extract information
* about parameter names. Parameter names are still included if they are explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#FAST
*/
FAST(TypePool.Default.ReaderMode.FAST);
/**
* The reader mode to apply by this type locator.
*/
private final TypePool.Default.ReaderMode readerMode;
/**
* Creates a new type locator.
*
* @param readerMode The reader mode to apply by this type locator.
*/
Default(TypePool.Default.ReaderMode readerMode) {
this.readerMode = readerMode;
}
/**
* {@inheritDoc}
*/
public TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader) {
return new TypePool.Default.WithLazyResolution(TypePool.CacheProvider.Simple.withObjectType(), classFileLocator, readerMode);
}
}
/**
* <p>
* A type locator that resolves all type descriptions eagerly.
* </p>
* <p>
* The returned type pool uses a {@link net.bytebuddy.pool.TypePool.CacheProvider.Simple} and the
* {@link ClassFileLocator} that is provided by the builder's {@link LocationStrategy}.
* </p>
*/
enum Eager implements PoolStrategy {
/**
* A type locator that parses the code segment of each method for extracting information about parameter
* names even if they are not explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#EXTENDED
*/
EXTENDED(TypePool.Default.ReaderMode.EXTENDED),
/**
* A type locator that skips the code segment of each method and does therefore not extract information
* about parameter names. Parameter names are still included if they are explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#FAST
*/
FAST(TypePool.Default.ReaderMode.FAST);
/**
* The reader mode to apply by this type locator.
*/
private final TypePool.Default.ReaderMode readerMode;
/**
* Creates a new type locator.
*
* @param readerMode The reader mode to apply by this type locator.
*/
Eager(TypePool.Default.ReaderMode readerMode) {
this.readerMode = readerMode;
}
/**
* {@inheritDoc}
*/
public TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader) {
return new TypePool.Default(TypePool.CacheProvider.Simple.withObjectType(), classFileLocator, readerMode);
}
}
/**
* <p>
* A type locator that attempts loading a type if it cannot be located by the underlying lazy type pool.
* </p>
* <p>
* The returned type pool uses a {@link net.bytebuddy.pool.TypePool.CacheProvider.Simple} and the
* {@link ClassFileLocator} that is provided by the builder's {@link LocationStrategy}. Any types
* are loaded via the instrumented type's {@link ClassLoader}.
* </p>
*/
enum ClassLoading implements PoolStrategy {
/**
* A type locator that parses the code segment of each method for extracting information about parameter
* names even if they are not explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#EXTENDED
*/
EXTENDED(TypePool.Default.ReaderMode.EXTENDED),
/**
* A type locator that skips the code segment of each method and does therefore not extract information
* about parameter names. Parameter names are still included if they are explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#FAST
*/
FAST(TypePool.Default.ReaderMode.FAST);
/**
* The reader mode to apply by this type locator.
*/
private final TypePool.Default.ReaderMode readerMode;
/**
* Creates a new type locator.
*
* @param readerMode The reader mode to apply by this type locator.
*/
ClassLoading(TypePool.Default.ReaderMode readerMode) {
this.readerMode = readerMode;
}
/**
* {@inheritDoc}
*/
public TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader) {
return TypePool.ClassLoading.of(classLoader, new TypePool.Default.WithLazyResolution(TypePool.CacheProvider.Simple.withObjectType(), classFileLocator, readerMode));
}
}
/**
* <p>
* A type locator that uses type pools but allows for the configuration of a custom cache provider by class loader. Note that a
* {@link TypePool} can grow in size and that a static reference is kept to this pool by Byte Buddy's registration of a
* {@link ClassFileTransformer} what can cause a memory leak if the supplied caches are not cleared on a regular basis. Also note
* that a cache provider can be accessed concurrently by multiple {@link ClassLoader}s.
* </p>
* <p>
* All types that are returned by the locator's type pool are resolved lazily.
* </p>
*/
@HashCodeAndEqualsPlugin.Enhance
abstract class WithTypePoolCache implements PoolStrategy {
/**
* The reader mode to use for parsing a class file.
*/
protected final TypePool.Default.ReaderMode readerMode;
/**
* Creates a new type locator that creates {@link TypePool}s but provides a custom {@link net.bytebuddy.pool.TypePool.CacheProvider}.
*
* @param readerMode The reader mode to use for parsing a class file.
*/
protected WithTypePoolCache(TypePool.Default.ReaderMode readerMode) {
this.readerMode = readerMode;
}
/**
* {@inheritDoc}
*/
public TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader) {
return new TypePool.Default.WithLazyResolution(locate(classLoader), classFileLocator, readerMode);
}
/**
* Locates a cache provider for a given class loader.
*
* @param classLoader The class loader for which to locate a cache. This class loader might be {@code null} to represent the bootstrap loader.
* @return The cache provider to use.
*/
protected abstract TypePool.CacheProvider locate(ClassLoader classLoader);
/**
* An implementation of a type locator {@link WithTypePoolCache} (note documentation of the linked class) that is based on a
* {@link ConcurrentMap}. It is the responsibility of the type locator's user to avoid the type locator from leaking memory.
*/
@HashCodeAndEqualsPlugin.Enhance
public static class Simple extends WithTypePoolCache {
/**
* The concurrent map that is used for storing a cache provider per class loader.
*/
private final ConcurrentMap<? super ClassLoader, TypePool.CacheProvider> cacheProviders;
/**
* Creates a new type locator that caches a cache provider per class loader in a concurrent map. The type
* locator uses a fast {@link net.bytebuddy.pool.TypePool.Default.ReaderMode}.
*
* @param cacheProviders The concurrent map that is used for storing a cache provider per class loader.
*/
public Simple(ConcurrentMap<? super ClassLoader, TypePool.CacheProvider> cacheProviders) {
this(TypePool.Default.ReaderMode.FAST, cacheProviders);
}
/**
* Creates a new type locator that caches a cache provider per class loader in a concurrent map.
*
* @param readerMode The reader mode to use for parsing a class file.
* @param cacheProviders The concurrent map that is used for storing a cache provider per class loader.
*/
public Simple(TypePool.Default.ReaderMode readerMode, ConcurrentMap<? super ClassLoader, TypePool.CacheProvider> cacheProviders) {
super(readerMode);
this.cacheProviders = cacheProviders;
}
@Override
protected TypePool.CacheProvider locate(ClassLoader classLoader) {
classLoader = classLoader == null ? getBootstrapMarkerLoader() : classLoader;
TypePool.CacheProvider cacheProvider = cacheProviders.get(classLoader);
while (cacheProvider == null) {
cacheProvider = TypePool.CacheProvider.Simple.withObjectType();
TypePool.CacheProvider previous = cacheProviders.putIfAbsent(classLoader, cacheProvider);
if (previous != null) {
cacheProvider = previous;
}
}
return cacheProvider;
}
/**
* <p>
* Returns the class loader to serve as a cache key if a cache provider for the bootstrap class loader is requested.
* This class loader is represented by {@code null} in the JVM which is an invalid value for many {@link ConcurrentMap}
* implementations.
* </p>
* <p>
* By default, {@link ClassLoader#getSystemClassLoader()} is used as such a key as any resource location for the
* bootstrap class loader is performed via the system class loader within Byte Buddy as {@code null} cannot be queried
* for resources via method calls such that this does not make a difference.
* </p>
*
* @return A class loader to represent the bootstrap class loader.
*/
protected ClassLoader getBootstrapMarkerLoader() {
return ClassLoader.getSystemClassLoader();
}
}
}
}
/**
* An initialization strategy which determines the handling of {@link net.bytebuddy.implementation.LoadedTypeInitializer}s
* and the loading of auxiliary types. The agent builder does not reuse the {@link TypeResolutionStrategy} as Javaagents cannot access
* a loaded class after a transformation such that different initialization strategies become meaningful.
*/
interface InitializationStrategy {
/**
* Creates a new dispatcher for injecting this initialization strategy during a transformation process.
*
* @return The dispatcher to be used.
*/
Dispatcher dispatcher();
/**
* A dispatcher for changing a class file to adapt a self-initialization strategy.
*/
interface Dispatcher {
/**
* Transforms the instrumented type to implement an appropriate initialization strategy.
*
* @param builder The builder which should implement the initialization strategy.
* @return The given {@code builder} with the initialization strategy applied.
*/
DynamicType.Builder<?> apply(DynamicType.Builder<?> builder);
/**
* Registers a dynamic type for initialization and/or begins the initialization process.
*
* @param dynamicType The dynamic type that is created.
* @param classLoader The class loader of the dynamic type which can be {@code null} to represent the bootstrap class loader.
* @param protectionDomain The instrumented type's protection domain or {@code null} if no protection domain is available.
* @param injectionStrategy The injection strategy to use.
*/
void register(DynamicType dynamicType, ClassLoader classLoader, ProtectionDomain protectionDomain, InjectionStrategy injectionStrategy);
}
/**
* A non-initializing initialization strategy.
*/
enum NoOp implements InitializationStrategy, Dispatcher {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Dispatcher dispatcher() {
return this;
}
/**
* {@inheritDoc}
*/
public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder) {
return builder;
}
/**
* {@inheritDoc}
*/
public void register(DynamicType dynamicType, ClassLoader classLoader, ProtectionDomain protectionDomain, InjectionStrategy injectionStrategy) {
/* do nothing */
}
}
/**
* An initialization strategy that loads auxiliary types before loading the instrumented type. This strategy skips all types
* that are a subtype of the instrumented type which would cause a premature loading of the instrumented type and abort
* the instrumentation process.
*/
enum Minimal implements InitializationStrategy, Dispatcher {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Dispatcher dispatcher() {
return this;
}
/**
* {@inheritDoc}
*/
public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder) {
return builder;
}
/**
* {@inheritDoc}
*/
public void register(DynamicType dynamicType, ClassLoader classLoader, ProtectionDomain protectionDomain, InjectionStrategy injectionStrategy) {
Map<TypeDescription, byte[]> auxiliaryTypes = dynamicType.getAuxiliaryTypes();
Map<TypeDescription, byte[]> independentTypes = new LinkedHashMap<TypeDescription, byte[]>(auxiliaryTypes);
for (TypeDescription auxiliaryType : auxiliaryTypes.keySet()) {
if (!auxiliaryType.getDeclaredAnnotations().isAnnotationPresent(AuxiliaryType.SignatureRelevant.class)) {
independentTypes.remove(auxiliaryType);
}
}
if (!independentTypes.isEmpty()) {
ClassInjector classInjector = injectionStrategy.resolve(classLoader, protectionDomain);
Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers = dynamicType.getLoadedTypeInitializers();
for (Map.Entry<TypeDescription, Class<?>> entry : classInjector.inject(independentTypes).entrySet()) {
loadedTypeInitializers.get(entry.getKey()).onLoad(entry.getValue());
}
}
}
}
/**
* An initialization strategy that adds a code block to an instrumented type's type initializer which
* then calls a specific class that is responsible for the explicit initialization.
*/
@HashCodeAndEqualsPlugin.Enhance
abstract class SelfInjection implements InitializationStrategy {
/**
* The nexus accessor to use.
*/
protected final NexusAccessor nexusAccessor;
/**
* Creates a new self-injection strategy.
*
* @param nexusAccessor The nexus accessor to use.
*/
protected SelfInjection(NexusAccessor nexusAccessor) {
this.nexusAccessor = nexusAccessor;
}
/**
* {@inheritDoc}
*/
@SuppressFBWarnings(value = "DMI_RANDOM_USED_ONLY_ONCE", justification = "Avoiding synchronization without security concerns")
public InitializationStrategy.Dispatcher dispatcher() {
return dispatcher(new Random().nextInt());
}
/**
* Creates a new dispatcher.
*
* @param identification The identification code to use.
* @return An appropriate dispatcher for an initialization strategy.
*/
protected abstract InitializationStrategy.Dispatcher dispatcher(int identification);
/**
* A dispatcher for a self-initialization strategy.
*/
@HashCodeAndEqualsPlugin.Enhance
protected abstract static class Dispatcher implements InitializationStrategy.Dispatcher {
/**
* The nexus accessor to use.
*/
protected final NexusAccessor nexusAccessor;
/**
* A random identification for the applied self-initialization.
*/
protected final int identification;
/**
* Creates a new dispatcher.
*
* @param nexusAccessor The nexus accessor to use.
* @param identification A random identification for the applied self-initialization.
*/
protected Dispatcher(NexusAccessor nexusAccessor, int identification) {
this.nexusAccessor = nexusAccessor;
this.identification = identification;
}
/**
* {@inheritDoc}
*/
public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder) {
return builder.initializer(new NexusAccessor.InitializationAppender(identification));
}
/**
* A type initializer that injects all auxiliary types of the instrumented type.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class InjectingInitializer implements LoadedTypeInitializer {
/**
* The instrumented type.
*/
private final TypeDescription instrumentedType;
/**
* The auxiliary types mapped to their class file representation.
*/
private final Map<TypeDescription, byte[]> rawAuxiliaryTypes;
/**
* The instrumented types and auxiliary types mapped to their loaded type initializers.
* The instrumented types and auxiliary types mapped to their loaded type initializers.
*/
private final Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers;
/**
* The class injector to use.
*/
private final ClassInjector classInjector;
/**
* Creates a new injection initializer.
*
* @param instrumentedType The instrumented type.
* @param rawAuxiliaryTypes The auxiliary types mapped to their class file representation.
* @param loadedTypeInitializers The instrumented types and auxiliary types mapped to their loaded type initializers.
* @param classInjector The class injector to use.
*/
protected InjectingInitializer(TypeDescription instrumentedType,
Map<TypeDescription, byte[]> rawAuxiliaryTypes,
Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers,
ClassInjector classInjector) {
this.instrumentedType = instrumentedType;
this.rawAuxiliaryTypes = rawAuxiliaryTypes;
this.loadedTypeInitializers = loadedTypeInitializers;
this.classInjector = classInjector;
}
/**
* {@inheritDoc}
*/
public void onLoad(Class<?> type) {
for (Map.Entry<TypeDescription, Class<?>> auxiliary : classInjector.inject(rawAuxiliaryTypes).entrySet()) {
loadedTypeInitializers.get(auxiliary.getKey()).onLoad(auxiliary.getValue());
}
loadedTypeInitializers.get(instrumentedType).onLoad(type);
}
/**
* {@inheritDoc}
*/
public boolean isAlive() {
return true;
}
}
}
/**
* A form of self-injection where auxiliary types that are annotated by
* {@link net.bytebuddy.implementation.auxiliary.AuxiliaryType.SignatureRelevant} of the instrumented type are loaded lazily and
* any other auxiliary type is loaded eagerly.
*/
public static class Split extends SelfInjection {
/**
* Creates a new split self-injection strategy that uses a default nexus accessor.
*/
public Split() {
this(new NexusAccessor());
}
/**
* Creates a new split self-injection strategy that uses the supplied nexus accessor.
*
* @param nexusAccessor The nexus accessor to use.
*/
public Split(NexusAccessor nexusAccessor) {
super(nexusAccessor);
}
@Override
protected InitializationStrategy.Dispatcher dispatcher(int identification) {
return new Dispatcher(nexusAccessor, identification);
}
/**
* A dispatcher for the {@link net.bytebuddy.agent.builder.AgentBuilder.InitializationStrategy.SelfInjection.Split} strategy.
*/
protected static class Dispatcher extends SelfInjection.Dispatcher {
/**
* Creates a new split dispatcher.
*
* @param nexusAccessor The nexus accessor to use.
* @param identification A random identification for the applied self-initialization.
*/
protected Dispatcher(NexusAccessor nexusAccessor, int identification) {
super(nexusAccessor, identification);
}
/**
* {@inheritDoc}
*/
public void register(DynamicType dynamicType, ClassLoader classLoader, ProtectionDomain protectionDomain, InjectionStrategy injectionStrategy) {
Map<TypeDescription, byte[]> auxiliaryTypes = dynamicType.getAuxiliaryTypes();
LoadedTypeInitializer loadedTypeInitializer;
if (!auxiliaryTypes.isEmpty()) {
TypeDescription instrumentedType = dynamicType.getTypeDescription();
ClassInjector classInjector = injectionStrategy.resolve(classLoader, protectionDomain);
Map<TypeDescription, byte[]> independentTypes = new LinkedHashMap<TypeDescription, byte[]>(auxiliaryTypes);
Map<TypeDescription, byte[]> dependentTypes = new LinkedHashMap<TypeDescription, byte[]>(auxiliaryTypes);
for (TypeDescription auxiliaryType : auxiliaryTypes.keySet()) {
(auxiliaryType.getDeclaredAnnotations().isAnnotationPresent(AuxiliaryType.SignatureRelevant.class)
? dependentTypes
: independentTypes).remove(auxiliaryType);
}
Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers = dynamicType.getLoadedTypeInitializers();
if (!independentTypes.isEmpty()) {
for (Map.Entry<TypeDescription, Class<?>> entry : classInjector.inject(independentTypes).entrySet()) {
loadedTypeInitializers.get(entry.getKey()).onLoad(entry.getValue());
}
}
Map<TypeDescription, LoadedTypeInitializer> lazyInitializers = new HashMap<TypeDescription, LoadedTypeInitializer>(loadedTypeInitializers);
loadedTypeInitializers.keySet().removeAll(independentTypes.keySet());
loadedTypeInitializer = lazyInitializers.size() > 1 // there exist auxiliary types that need lazy loading
? new Dispatcher.InjectingInitializer(instrumentedType, dependentTypes, lazyInitializers, classInjector)
: lazyInitializers.get(instrumentedType);
} else {
loadedTypeInitializer = dynamicType.getLoadedTypeInitializers().get(dynamicType.getTypeDescription());
}
nexusAccessor.register(dynamicType.getTypeDescription().getName(), classLoader, identification, loadedTypeInitializer);
}
}
}
/**
* A form of self-injection where any auxiliary type is loaded lazily.
*/
public static class Lazy extends SelfInjection {
/**
* Creates a new lazy self-injection strategy that uses a default nexus accessor.
*/
public Lazy() {
this(new NexusAccessor());
}
/**
* Creates a new lazy self-injection strategy that uses the supplied nexus accessor.
*
* @param nexusAccessor The nexus accessor to use.
*/
public Lazy(NexusAccessor nexusAccessor) {
super(nexusAccessor);
}
@Override
protected InitializationStrategy.Dispatcher dispatcher(int identification) {
return new Dispatcher(nexusAccessor, identification);
}
/**
* A dispatcher for the {@link net.bytebuddy.agent.builder.AgentBuilder.InitializationStrategy.SelfInjection.Lazy} strategy.
*/
protected static class Dispatcher extends SelfInjection.Dispatcher {
/**
* Creates a new lazy dispatcher.
*
* @param nexusAccessor The nexus accessor to use.
* @param identification A random identification for the applied self-initialization.
*/
protected Dispatcher(NexusAccessor nexusAccessor, int identification) {
super(nexusAccessor, identification);
}
/**
* {@inheritDoc}
*/
public void register(DynamicType dynamicType, ClassLoader classLoader, ProtectionDomain protectionDomain, InjectionStrategy injectionStrategy) {
Map<TypeDescription, byte[]> auxiliaryTypes = dynamicType.getAuxiliaryTypes();
LoadedTypeInitializer loadedTypeInitializer = auxiliaryTypes.isEmpty()
? dynamicType.getLoadedTypeInitializers().get(dynamicType.getTypeDescription())
: new Dispatcher.InjectingInitializer(dynamicType.getTypeDescription(), auxiliaryTypes, dynamicType.getLoadedTypeInitializers(), injectionStrategy.resolve(classLoader, protectionDomain));
nexusAccessor.register(dynamicType.getTypeDescription().getName(), classLoader, identification, loadedTypeInitializer);
}
}
}
/**
* A form of self-injection where any auxiliary type is loaded eagerly.
*/
public static class Eager extends SelfInjection {
/**
* Creates a new eager self-injection strategy that uses a default nexus accessor.
*/
public Eager() {
this(new NexusAccessor());
}
/**
* Creates a new eager self-injection strategy that uses the supplied nexus accessor.
*
* @param nexusAccessor The nexus accessor to use.
*/
public Eager(NexusAccessor nexusAccessor) {
super(nexusAccessor);
}
@Override
protected InitializationStrategy.Dispatcher dispatcher(int identification) {
return new Dispatcher(nexusAccessor, identification);
}
/**
* A dispatcher for the {@link net.bytebuddy.agent.builder.AgentBuilder.InitializationStrategy.SelfInjection.Eager} strategy.
*/
protected static class Dispatcher extends SelfInjection.Dispatcher {
/**
* Creates a new eager dispatcher.
*
* @param nexusAccessor The nexus accessor to use.
* @param identification A random identification for the applied self-initialization.
*/
protected Dispatcher(NexusAccessor nexusAccessor, int identification) {
super(nexusAccessor, identification);
}
/**
* {@inheritDoc}
*/
public void register(DynamicType dynamicType, ClassLoader classLoader, ProtectionDomain protectionDomain, InjectionStrategy injectionStrategy) {
Map<TypeDescription, byte[]> auxiliaryTypes = dynamicType.getAuxiliaryTypes();
Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers = dynamicType.getLoadedTypeInitializers();
if (!auxiliaryTypes.isEmpty()) {
for (Map.Entry<TypeDescription, Class<?>> entry : injectionStrategy.resolve(classLoader, protectionDomain).inject(auxiliaryTypes).entrySet()) {
loadedTypeInitializers.get(entry.getKey()).onLoad(entry.getValue());
}
}
LoadedTypeInitializer loadedTypeInitializer = loadedTypeInitializers.get(dynamicType.getTypeDescription());
nexusAccessor.register(dynamicType.getTypeDescription().getName(), classLoader, identification, loadedTypeInitializer);
}
}
}
}
}
/**
* A strategy for injecting auxiliary types into a class loader.
*/
interface InjectionStrategy {
/**
* Resolves the class injector to use for a given class loader and protection domain.
*
* @param classLoader The class loader to use.
* @param protectionDomain The protection domain to use.
* @return The class injector to use.
*/
ClassInjector resolve(ClassLoader classLoader, ProtectionDomain protectionDomain);
/**
* An injection strategy that does not permit class injection.
*/
enum Disabled implements InjectionStrategy {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public ClassInjector resolve(ClassLoader classLoader, ProtectionDomain protectionDomain) {
throw new IllegalStateException("Class injection is disabled");
}
}
/**
* An injection strategy that uses Java reflection. This strategy is not capable of injecting classes into the bootstrap class loader.
*/
enum UsingReflection implements InjectionStrategy {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public ClassInjector resolve(ClassLoader classLoader, ProtectionDomain protectionDomain) {
if (classLoader == null) {
throw new IllegalStateException("Cannot inject auxiliary class into bootstrap loader using reflection");
} else if (ClassInjector.UsingReflection.isAvailable()) {
return new ClassInjector.UsingReflection(classLoader, protectionDomain);
} else {
throw new IllegalStateException("Reflection-based injection is not available on the current VM");
}
}
}
/**
* An injection strategy that uses {@code sun.misc.Unsafe} to inject classes.
*/
enum UsingUnsafe implements InjectionStrategy {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public ClassInjector resolve(ClassLoader classLoader, ProtectionDomain protectionDomain) {
if (ClassInjector.UsingUnsafe.isAvailable()) {
return new ClassInjector.UsingUnsafe(classLoader, protectionDomain);
} else {
throw new IllegalStateException("Unsafe-based injection is not available on the current VM");
}
}
/**
* An injection strategy that uses a factory for creating an unsafe injector.
*/
@HashCodeAndEqualsPlugin.Enhance
public static class OfFactory implements InjectionStrategy {
/**
* The factory to use for creating an unsafe injector.
*/
private final ClassInjector.UsingUnsafe.Factory factory;
/**
* Creates an injection strategy based on a factory.
*
* @param factory The factory to use for creating an unsafe injector.
*/
public OfFactory(ClassInjector.UsingUnsafe.Factory factory) {
this.factory = factory;
}
/**
* {@inheritDoc}
*/
public ClassInjector resolve(ClassLoader classLoader, ProtectionDomain protectionDomain) {
return factory.make(classLoader, protectionDomain);
}
}
}
/**
* An injection strategy that uses bootstrap injection using an {@link Instrumentation} instance.
*/
@HashCodeAndEqualsPlugin.Enhance
class UsingInstrumentation implements InjectionStrategy {
/**
* The instrumentation instance to use.
*/
private final Instrumentation instrumentation;
/**
* The folder to store jar files being used for bootstrap injection.
*/
private final File folder;
/**
* Creates a new bootstrap injection strategy.
*
* @param instrumentation The instrumentation instance to use.
* @param folder The folder to store jar files being used for bootstrap injection.
*/
public UsingInstrumentation(Instrumentation instrumentation, File folder) {
this.instrumentation = instrumentation;
this.folder = folder;
}
/**
* {@inheritDoc}
*/
public ClassInjector resolve(ClassLoader classLoader, ProtectionDomain protectionDomain) {
return classLoader == null
? ClassInjector.UsingInstrumentation.of(folder, ClassInjector.UsingInstrumentation.Target.BOOTSTRAP, instrumentation)
: UsingReflection.INSTANCE.resolve(classLoader, protectionDomain);
}
}
}
/**
* A description strategy is responsible for resolving a {@link TypeDescription} when transforming or retransforming/-defining a type.
*/
interface DescriptionStrategy {
/**
* Indicates if this description strategy makes use of loaded type information and yields a different type description if no loaded type is available.
*
* @return {@code true} if this description strategy prefers loaded type information when describing a type and only uses a type pool
* if loaded type information is not available.
*/
boolean isLoadedFirst();
/**
* Describes the given type.
*
* @param typeName The binary name of the type to describe.
* @param type The type that is being redefined, if a redefinition is applied or {@code null} if no redefined type is available.
* @param typePool The type pool to use for locating a type if required.
* @param classLoader The type's class loader where {@code null} represents the bootstrap class loader.
* @param circularityLock The currently used circularity lock.
* @param module The type's module or {@code null} if the current VM does not support modules.
* @return An appropriate type description.
*/
TypeDescription apply(String typeName, Class<?> type, TypePool typePool, CircularityLock circularityLock, ClassLoader classLoader, JavaModule module);
/**
* Default implementations of a {@link DescriptionStrategy}.
*/
enum Default implements DescriptionStrategy {
/**
* A description type strategy represents a type as a {@link net.bytebuddy.description.type.TypeDescription.ForLoadedType} if a
* retransformation or redefinition is applied on a type. Using a loaded type typically results in better performance as no
* I/O is required for resolving type descriptions. However, any interaction with the type is carried out via the Java reflection
* API. Using the reflection API triggers eager loading of any type that is part of a method or field signature. If any of these
* types are missing from the class path, this eager loading will cause a {@link NoClassDefFoundError}. Some Java code declares
* optional dependencies to other classes which are only realized if the optional dependency is present. Such code relies on the
* Java reflection API not being used for types using optional dependencies.
*
* @see FallbackStrategy.Simple#ENABLED
* @see FallbackStrategy.ByThrowableType#ofOptionalTypes()
*/
HYBRID(true) {
/** {@inheritDoc} */
public TypeDescription apply(String typeName,
Class<?> type,
TypePool typePool,
CircularityLock circularityLock,
ClassLoader classLoader,
JavaModule module) {
return type == null
? typePool.describe(typeName).resolve()
: TypeDescription.ForLoadedType.of(type);
}
},
/**
* <p>
* A description strategy that always describes Java types using a {@link TypePool}. This requires that any type - even if it is already
* loaded and a {@link Class} instance is available - is processed as a non-loaded type description. Doing so can cause overhead as processing
* loaded types is supported very efficiently by a JVM.
* </p>
* <p>
* Avoiding the usage of loaded types can improve robustness as this approach does not rely on the Java reflection API which triggers eager
* validation of this loaded type which can fail an application if optional types are used by any types field or method signatures. Also, it
* is possible to guarantee debugging meta data to be available also for retransformed or redefined types if a {@link TypeStrategy} specifies
* the extraction of such meta data.
* </p>
*/
POOL_ONLY(false) {
/** {@inheritDoc} */
public TypeDescription apply(String typeName,
Class<?> type,
TypePool typePool,
CircularityLock circularityLock,
ClassLoader classLoader,
JavaModule module) {
return typePool.describe(typeName).resolve();
}
},
/**
* <p>
* A description strategy that always describes Java types using a {@link TypePool} unless a type cannot be resolved by a pool and a loaded
* {@link Class} instance is available. Doing so can cause overhead as processing loaded types is supported very efficiently by a JVM.
* </p>
* <p>
* Avoiding the usage of loaded types can improve robustness as this approach does not rely on the Java reflection API which triggers eager
* validation of this loaded type which can fail an application if optional types are used by any types field or method signatures. Also, it
* is possible to guarantee debugging meta data to be available also for retransformed or redefined types if a {@link TypeStrategy} specifies
* the extraction of such meta data.
* </p>
*/
POOL_FIRST(false) {
/** {@inheritDoc} */
public TypeDescription apply(String typeName,
Class<?> type,
TypePool typePool,
CircularityLock circularityLock,
ClassLoader classLoader,
JavaModule module) {
TypePool.Resolution resolution = typePool.describe(typeName);
return resolution.isResolved() || type == null
? resolution.resolve()
: TypeDescription.ForLoadedType.of(type);
}
};
/**
* Indicates if loaded type information is preferred over using a type pool for describing a type.
*/
private final boolean loadedFirst;
/**
* Indicates if loaded type information is preferred over using a type pool for describing a type.
*
* @param loadedFirst {@code true} if loaded type information is preferred over using a type pool for describing a type.
*/
Default(boolean loadedFirst) {
this.loadedFirst = loadedFirst;
}
/**
* Creates a description strategy that uses this strategy but loads any super type. If a super type is not yet loaded,
* this causes this super type to never be instrumented. Therefore, this option should only be used if all instrumented
* types are guaranteed to be top-level types.
*
* @return This description strategy where all super types are loaded during the instrumentation.
* @see SuperTypeLoading
*/
public DescriptionStrategy withSuperTypeLoading() {
return new SuperTypeLoading(this);
}
/**
* {@inheritDoc}
*/
public boolean isLoadedFirst() {
return loadedFirst;
}
/**
* Creates a description strategy that uses this strategy but loads any super type asynchronously. Super types are loaded via
* another thread supplied by the executor service to enforce the instrumentation of any such super type. It is recommended
* to allow the executor service to create new threads without bound as class loading blocks any thread until all super types
* were instrumented.
*
* @param executorService The executor service to use.
* @return This description strategy where all super types are loaded asynchronously during the instrumentation.
* @see SuperTypeLoading.Asynchronous
*/
public DescriptionStrategy withSuperTypeLoading(ExecutorService executorService) {
return new SuperTypeLoading.Asynchronous(this, executorService);
}
}
/**
* <p>
* A description strategy that enforces the loading of any super type of a type description but delegates the actual type description
* to another description strategy.
* </p>
* <p>
* <b>Warning</b>: When using this description strategy, a type is not instrumented if any of its subtypes is loaded first.
* The instrumentation API does not submit such types to a class file transformer on most VM implementations.
* </p>
*/
@HashCodeAndEqualsPlugin.Enhance
class SuperTypeLoading implements DescriptionStrategy {
/**
* The delegate description strategy.
*/
private final DescriptionStrategy delegate;
/**
* Creates a new description strategy that enforces loading of a super type.
*
* @param delegate The delegate description strategy.
*/
public SuperTypeLoading(DescriptionStrategy delegate) {
this.delegate = delegate;
}
/**
* {@inheritDoc}
*/
public boolean isLoadedFirst() {
return delegate.isLoadedFirst();
}
/**
* {@inheritDoc}
*/
public TypeDescription apply(String typeName,
Class<?> type,
TypePool typePool,
CircularityLock circularityLock,
ClassLoader classLoader,
JavaModule module) {
TypeDescription typeDescription = delegate.apply(typeName, type, typePool, circularityLock, classLoader, module);
return typeDescription instanceof TypeDescription.ForLoadedType
? typeDescription
: new TypeDescription.SuperTypeLoading(typeDescription, classLoader, new UnlockingClassLoadingDelegate(circularityLock));
}
/**
* A class loading delegate that unlocks the circularity lock during class loading.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class UnlockingClassLoadingDelegate implements TypeDescription.SuperTypeLoading.ClassLoadingDelegate {
/**
* The circularity lock to unlock.
*/
private final CircularityLock circularityLock;
/**
* Creates an unlocking class loading delegate.
*
* @param circularityLock The circularity lock to unlock.
*/
protected UnlockingClassLoadingDelegate(CircularityLock circularityLock) {
this.circularityLock = circularityLock;
}
/**
* {@inheritDoc}
*/
public Class<?> load(String name, ClassLoader classLoader) throws ClassNotFoundException {
circularityLock.release();
try {
return Class.forName(name, false, classLoader);
} finally {
circularityLock.acquire();
}
}
}
/**
* <p>
* A description strategy that enforces the loading of any super type of a type description but delegates the actual type description
* to another description strategy.
* </p>
* <p>
* <b>Note</b>: This description strategy delegates class loading to another thread in order to enforce the instrumentation of any
* unloaded super type. This requires the executor service to supply at least as many threads as the deepest type hierarchy within the
* application minus one for the instrumented type as class loading blocks any thread until all of its super types are loaded. These
* threads are typically short lived which predestines the use of a {@link Executors#newCachedThreadPool()} without any upper bound
* for the maximum number of created threads.
* </p>
* <p>
* <b>Important</b>: This strategy can dead-lock under two circumstances:
* </p>
* <ul>
* <li>
* <b>Classes declare circularities</b>: Under normal circumstances, such scenarios result in a {@link ClassCircularityError} but
* can result in dead-locks when using this instrumentation strategy.
* </li>
* <li>
* <b>Class loaders declare custom locks</b>: If a class loader locks another lock but itself during class loading, this lock cannot
* be released by this strategy.
* </li>
* </ul>
* <p>
* For the above reasons, it is not recommended to use this strategy when the target class loader is unknown or if the target application
* might contain corrupt class files.
* </p>
*/
@HashCodeAndEqualsPlugin.Enhance
public static class Asynchronous implements DescriptionStrategy {
/**
* The delegate description strategy.
*/
private final DescriptionStrategy delegate;
/**
* The executor service to use for loading super types.
*/
private final ExecutorService executorService;
/**
* Creates a new description strategy that enforces super type loading from another thread.
*
* @param delegate The delegate description strategy.
* @param executorService The executor service to use for loading super types.
*/
public Asynchronous(DescriptionStrategy delegate, ExecutorService executorService) {
this.delegate = delegate;
this.executorService = executorService;
}
/**
* {@inheritDoc}
*/
public boolean isLoadedFirst() {
return delegate.isLoadedFirst();
}
/**
* {@inheritDoc}
*/
public TypeDescription apply(String typeName,
Class<?> type,
TypePool typePool,
CircularityLock circularityLock,
ClassLoader classLoader,
JavaModule module) {
TypeDescription typeDescription = delegate.apply(typeName, type, typePool, circularityLock, classLoader, module);
return typeDescription instanceof TypeDescription.ForLoadedType
? typeDescription
: new TypeDescription.SuperTypeLoading(typeDescription, classLoader, new ThreadSwitchingClassLoadingDelegate(executorService));
}
/**
* A class loading delegate that delegates loading of the super type to another thread.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class ThreadSwitchingClassLoadingDelegate implements TypeDescription.SuperTypeLoading.ClassLoadingDelegate {
/**
* The executor service to delegate class loading to.
*/
private final ExecutorService executorService;
/**
* Creates a new thread-switching class loading delegate.
*
* @param executorService The executor service to delegate class loading to.
*/
protected ThreadSwitchingClassLoadingDelegate(ExecutorService executorService) {
this.executorService = executorService;
}
/**
* {@inheritDoc}
*/
public Class<?> load(String name, ClassLoader classLoader) {
boolean holdsLock = classLoader != null && Thread.holdsLock(classLoader);
AtomicBoolean signal = new AtomicBoolean(holdsLock);
Future<Class<?>> future = executorService.submit(holdsLock
? new NotifyingClassLoadingAction(name, classLoader, signal)
: new SimpleClassLoadingAction(name, classLoader));
try {
while (holdsLock && signal.get()) {
classLoader.wait();
}
return future.get();
} catch (ExecutionException exception) {
throw new IllegalStateException("Could not load " + name + " asynchronously", exception.getCause());
} catch (Exception exception) {
throw new IllegalStateException("Could not load " + name + " asynchronously", exception);
}
}
/**
* A class loading action that simply loads a type.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class SimpleClassLoadingAction implements Callable<Class<?>> {
/**
* The loaded type's name.
*/
private final String name;
/**
* The type's class loader or {@code null} if the type is loaded by the bootstrap loader.
*/
private final ClassLoader classLoader;
/**
* Creates a simple class loading action.
*
* @param name The loaded type's name.
* @param classLoader The type's class loader or {@code null} if the type is loaded by the bootstrap loader.
*/
protected SimpleClassLoadingAction(String name, ClassLoader classLoader) {
this.name = name;
this.classLoader = classLoader;
}
/**
* {@inheritDoc}
*/
public Class<?> call() throws ClassNotFoundException {
return Class.forName(name, false, classLoader);
}
}
/**
* A class loading action that notifies the class loader's lock after the type was loaded.
*/
protected static class NotifyingClassLoadingAction implements Callable<Class<?>> {
/**
* The loaded type's name.
*/
private final String name;
/**
* The type's class loader or {@code null} if the type is loaded by the bootstrap loader.
*/
private final ClassLoader classLoader;
/**
* The signal that indicates the completion of the class loading with {@code false}.
*/
private final AtomicBoolean signal;
/**
* Creates a notifying class loading action.
*
* @param name The loaded type's name.
* @param classLoader The type's class loader or {@code null} if the type is loaded by the bootstrap loader.
* @param signal The signal that indicates the completion of the class loading with {@code false}.
*/
protected NotifyingClassLoadingAction(String name, ClassLoader classLoader, AtomicBoolean signal) {
this.name = name;
this.classLoader = classLoader;
this.signal = signal;
}
/**
* {@inheritDoc}
*/
public Class<?> call() throws ClassNotFoundException {
synchronized (classLoader) {
try {
return Class.forName(name, false, classLoader);
} finally {
signal.set(false);
classLoader.notifyAll();
}
}
}
}
}
}
}
}
/**
* A strategy for creating a {@link ClassFileLocator} when instrumenting a type.
*/
interface LocationStrategy {
/**
* Creates a class file locator for a given class loader and module combination.
*
* @param classLoader The class loader that is loading an instrumented type. Might be {@code null} to represent the bootstrap class loader.
* @param module The type's module or {@code null} if Java modules are not supported on the current VM.
* @return The class file locator to use.
*/
ClassFileLocator classFileLocator(ClassLoader classLoader, JavaModule module);
/**
* A location strategy that never locates any byte code.
*/
enum NoOp implements LocationStrategy {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public ClassFileLocator classFileLocator(ClassLoader classLoader, JavaModule module) {
return ClassFileLocator.NoOp.INSTANCE;
}
}
/**
* A location strategy that locates class files by querying an instrumented type's {@link ClassLoader}.
*/
enum ForClassLoader implements LocationStrategy {
/**
* A location strategy that keeps a strong reference to the class loader the created class file locator represents.
*/
STRONG {
/** {@inheritDoc} */
public ClassFileLocator classFileLocator(ClassLoader classLoader, JavaModule module) {
return ClassFileLocator.ForClassLoader.of(classLoader);
}
},
/**
* A location strategy that keeps a weak reference to the class loader the created class file locator represents.
* As a consequence, any returned class file locator stops working once the represented class loader is garbage collected.
*/
WEAK {
/** {@inheritDoc} */
public ClassFileLocator classFileLocator(ClassLoader classLoader, JavaModule module) {
return ClassFileLocator.ForClassLoader.WeaklyReferenced.of(classLoader);
}
};
/**
* Adds additional location strategies as fallbacks to this location strategy.
*
* @param classFileLocator The class file locators to query if this location strategy cannot locate a class file.
* @return A compound location strategy that first applies this location strategy and then queries the supplied class file locators.
*/
public LocationStrategy withFallbackTo(ClassFileLocator... classFileLocator) {
return withFallbackTo(Arrays.asList(classFileLocator));
}
/**
* Adds additional location strategies as fallbacks to this location strategy.
*
* @param classFileLocators The class file locators to query if this location strategy cannot locate a class file.
* @return A compound location strategy that first applies this location strategy and then queries the supplied class file locators.
*/
public LocationStrategy withFallbackTo(Collection<? extends ClassFileLocator> classFileLocators) {
List<LocationStrategy> locationStrategies = new ArrayList<LocationStrategy>(classFileLocators.size());
for (ClassFileLocator classFileLocator : classFileLocators) {
locationStrategies.add(new Simple(classFileLocator));
}
return withFallbackTo(locationStrategies);
}
/**
* Adds additional location strategies as fallbacks to this location strategy.
*
* @param locationStrategy The fallback location strategies to use.
* @return A compound location strategy that first applies this location strategy and then the supplied fallback location strategies
* in the supplied order.
*/
public LocationStrategy withFallbackTo(LocationStrategy... locationStrategy) {
return withFallbackTo(Arrays.asList(locationStrategy));
}
/**
* Adds additional location strategies as fallbacks to this location strategy.
*
* @param locationStrategies The fallback location strategies to use.
* @return A compound location strategy that first applies this location strategy and then the supplied fallback location strategies
* in the supplied order.
*/
public LocationStrategy withFallbackTo(List<? extends LocationStrategy> locationStrategies) {
List<LocationStrategy> allLocationStrategies = new ArrayList<LocationStrategy>(locationStrategies.size() + 1);
allLocationStrategies.add(this);
allLocationStrategies.addAll(locationStrategies);
return new Compound(allLocationStrategies);
}
}
/**
* A simple location strategy that queries a given class file locator.
*/
@HashCodeAndEqualsPlugin.Enhance
class Simple implements LocationStrategy {
/**
* The class file locator to query.
*/
private final ClassFileLocator classFileLocator;
/**
* A simple location strategy that queries a given class file locator.
*
* @param classFileLocator The class file locator to query.
*/
public Simple(ClassFileLocator classFileLocator) {
this.classFileLocator = classFileLocator;
}
/**
* {@inheritDoc}
*/
public ClassFileLocator classFileLocator(ClassLoader classLoader, JavaModule module) {
return classFileLocator;
}
}
/**
* A compound location strategy that applies a list of location strategies.
*/
@HashCodeAndEqualsPlugin.Enhance
class Compound implements LocationStrategy {
/**
* The location strategies in their application order.
*/
private final List<LocationStrategy> locationStrategies;
/**
* Creates a new compound location strategy.
*
* @param locationStrategy The location strategies in their application order.
*/
public Compound(LocationStrategy... locationStrategy) {
this(Arrays.asList(locationStrategy));
}
/**
* Creates a new compound location strategy.
*
* @param locationStrategies The location strategies in their application order.
*/
public Compound(List<? extends LocationStrategy> locationStrategies) {
this.locationStrategies = new ArrayList<LocationStrategy>();
for (LocationStrategy locationStrategy : locationStrategies) {
if (locationStrategy instanceof Compound) {
this.locationStrategies.addAll(((Compound) locationStrategy).locationStrategies);
} else if (!(locationStrategy instanceof NoOp)) {
this.locationStrategies.add(locationStrategy);
}
}
}
/**
* {@inheritDoc}
*/
public ClassFileLocator classFileLocator(ClassLoader classLoader, JavaModule module) {
List<ClassFileLocator> classFileLocators = new ArrayList<ClassFileLocator>(locationStrategies.size());
for (LocationStrategy locationStrategy : locationStrategies) {
classFileLocators.add(locationStrategy.classFileLocator(classLoader, module));
}
return new ClassFileLocator.Compound(classFileLocators);
}
}
}
/**
* A fallback strategy allows to reattempt a transformation or a consideration for redefinition/retransformation in case an exception
* occurs. Doing so, it is possible to use a {@link TypePool} rather than using a loaded type description backed by a {@link Class}.
* Loaded types can raise exceptions and errors if a {@link ClassLoader} cannot resolve all types that this class references. Using
* a type pool, such errors can be avoided as type descriptions can be resolved lazily, avoiding such errors.
*/
interface FallbackStrategy {
/**
* Returns {@code true} if the supplied type and throwable combination should result in a reattempt where the
* loaded type is not used for querying information.
*
* @param type The loaded type that was queried during the transformation attempt.
* @param throwable The error or exception that was caused during the transformation.
* @return {@code true} if the supplied type and throwable combination should
*/
boolean isFallback(Class<?> type, Throwable throwable);
/**
* A simple fallback strategy that either always reattempts a transformation or never does so.
*/
enum Simple implements FallbackStrategy {
/**
* An enabled fallback strategy that always attempts a new trial.
*/
ENABLED(true),
/**
* A disabled fallback strategy that never attempts a new trial.
*/
DISABLED(false);
/**
* {@code true} if this fallback strategy is enabled.
*/
private final boolean enabled;
/**
* Creates a new default fallback strategy.
*
* @param enabled {@code true} if this fallback strategy is enabled.
*/
Simple(boolean enabled) {
this.enabled = enabled;
}
/**
* {@inheritDoc}
*/
public boolean isFallback(Class<?> type, Throwable throwable) {
return enabled;
}
}
/**
* A fallback strategy that discriminates by the type of the {@link Throwable} that triggered a request.
*/
@HashCodeAndEqualsPlugin.Enhance
class ByThrowableType implements FallbackStrategy {
/**
* A set of throwable types that should trigger a fallback attempt.
*/
private final Set<? extends Class<? extends Throwable>> types;
/**
* Creates a new throwable type-discriminating fallback strategy.
*
* @param type The throwable types that should trigger a fallback.
*/
@SuppressWarnings("unchecked") // In absence of @SafeVarargs
public ByThrowableType(Class<? extends Throwable>... type) {
this(new HashSet<Class<? extends Throwable>>(Arrays.asList(type)));
}
/**
* Creates a new throwable type-discriminating fallback strategy.
*
* @param types The throwable types that should trigger a fallback.
*/
public ByThrowableType(Set<? extends Class<? extends Throwable>> types) {
this.types = types;
}
/**
* Creates a fallback strategy that attempts a fallback if an error indicating a type error is the reason for requesting a reattempt.
*
* @return A fallback strategy that triggers a reattempt if a {@link LinkageError} or a {@link TypeNotPresentException} is raised.
*/
@SuppressWarnings("unchecked") // In absence of @SafeVarargs
public static FallbackStrategy ofOptionalTypes() {
return new ByThrowableType(LinkageError.class, TypeNotPresentException.class);
}
/**
* {@inheritDoc}
*/
public boolean isFallback(Class<?> type, Throwable throwable) {
for (Class<? extends Throwable> aType : types) {
if (aType.isInstance(throwable)) {
return true;
}
}
return false;
}
}
}
/**
* A listener that is notified during the installation and the resetting of a class file transformer.
*/
interface InstallationListener {
/**
* Indicates that an exception is handled.
*/
Throwable SUPPRESS_ERROR = null;
/**
* Invoked prior to the installation of a class file transformer.
*
* @param instrumentation The instrumentation on which the class file transformer is installed.
* @param classFileTransformer The class file transformer that is being installed.
*/
void onBeforeInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer);
/**
* Invoked upon the successful installation of a class file transformer. This method is only invoked if no error occurred during the
* installation or if such an error was handled by {@link InstallationListener#onError(Instrumentation, ResettableClassFileTransformer, Throwable)}.
*
* @param instrumentation The instrumentation on which the class file transformer is installed.
* @param classFileTransformer The class file transformer that is being installed.
*/
void onInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer);
/**
* Invoked if an installation causes an error. The listener has an opportunity to handle the error. This method is invoked prior to
* {@link InstallationListener#onInstall(Instrumentation, ResettableClassFileTransformer)}.
*
* @param instrumentation The instrumentation on which the class file transformer is installed.
* @param classFileTransformer The class file transformer that is being installed.
* @param throwable The throwable that causes the error.
* @return The error to propagate or {@code null} if the error is handled. Any subsequent listeners are not called if the exception is handled.
*/
Throwable onError(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer, Throwable throwable);
/**
* Invoked if an installation is reset.
*
* @param instrumentation The instrumentation on which the class file transformer is installed.
* @param classFileTransformer The class file transformer that is being installed.
*/
void onReset(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer);
/**
* A non-operational listener that does not do anything.
*/
enum NoOp implements InstallationListener {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public void onBeforeInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public Throwable onError(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer, Throwable throwable) {
return throwable;
}
/**
* {@inheritDoc}
*/
public void onReset(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
/* do nothing */
}
}
/**
* A listener that suppresses any installation error.
*/
enum ErrorSuppressing implements InstallationListener {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public void onBeforeInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public Throwable onError(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer, Throwable throwable) {
return SUPPRESS_ERROR;
}
/**
* {@inheritDoc}
*/
public void onReset(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
/* do nothing */
}
}
/**
* An adapter implementation for an installation listener that serves as a convenience.
*/
abstract class Adapter implements InstallationListener {
/**
* {@inheritDoc}
*/
public void onBeforeInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public Throwable onError(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer, Throwable throwable) {
return throwable;
}
/**
* {@inheritDoc}
*/
public void onReset(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
/* do nothing */
}
}
/**
* This installation listener prints the status of any installation to a {@link PrintStream}.
*/
@HashCodeAndEqualsPlugin.Enhance
class StreamWriting implements InstallationListener {
/**
* The prefix prepended to any message written.
*/
protected static final String PREFIX = "[Byte Buddy]";
/**
* The print stream to write to.
*/
private final PrintStream printStream;
/**
* Creates a new stream writing installation listener.
*
* @param printStream The print stream to write to.
*/
public StreamWriting(PrintStream printStream) {
this.printStream = printStream;
}
/**
* Creates a stream writing installation listener that prints to {@link System#out}.
*
* @return An installation listener that prints to {@link System#out}.
*/
public static InstallationListener toSystemOut() {
return new StreamWriting(System.out);
}
/**
* Creates a stream writing installation listener that prints to {@link System#err}.
*
* @return An installation listener that prints to {@link System#err}.
*/
public static InstallationListener toSystemError() {
return new StreamWriting(System.err);
}
/**
* {@inheritDoc}
*/
public void onBeforeInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
printStream.printf(PREFIX + " BEFORE_INSTALL %s on %s%n", classFileTransformer, instrumentation);
}
/**
* {@inheritDoc}
*/
public void onInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
printStream.printf(PREFIX + " INSTALL %s on %s%n", classFileTransformer, instrumentation);
}
/**
* {@inheritDoc}
*/
public Throwable onError(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer, Throwable throwable) {
synchronized (printStream) {
printStream.printf(PREFIX + " ERROR %s on %s%n", classFileTransformer, instrumentation);
throwable.printStackTrace(printStream);
}
return throwable;
}
/**
* {@inheritDoc}
*/
public void onReset(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
printStream.printf(PREFIX + " RESET %s on %s%n", classFileTransformer, instrumentation);
}
}
/**
* A compound installation listener.
*/
@HashCodeAndEqualsPlugin.Enhance
class Compound implements InstallationListener {
/**
* The installation listeners to notify.
*/
private final List<InstallationListener> installationListeners;
/**
* Creates a new compound listener.
*
* @param installationListener The installation listeners to notify.
*/
public Compound(InstallationListener... installationListener) {
this(Arrays.asList(installationListener));
}
/**
* Creates a new compound listener.
*
* @param installationListeners The installation listeners to notify.
*/
public Compound(List<? extends InstallationListener> installationListeners) {
this.installationListeners = new ArrayList<InstallationListener>();
for (InstallationListener installationListener : installationListeners) {
if (installationListener instanceof Compound) {
this.installationListeners.addAll(((Compound) installationListener).installationListeners);
} else if (!(installationListener instanceof NoOp)) {
this.installationListeners.add(installationListener);
}
}
}
/**
* {@inheritDoc}
*/
public void onBeforeInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
for (InstallationListener installationListener : installationListeners) {
installationListener.onBeforeInstall(instrumentation, classFileTransformer);
}
}
/**
* {@inheritDoc}
*/
public void onInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
for (InstallationListener installationListener : installationListeners) {
installationListener.onInstall(instrumentation, classFileTransformer);
}
}
/**
* {@inheritDoc}
*/
public Throwable onError(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer, Throwable throwable) {
for (InstallationListener installationListener : installationListeners) {
if (throwable == SUPPRESS_ERROR) {
return SUPPRESS_ERROR;
}
throwable = installationListener.onError(instrumentation, classFileTransformer, throwable);
}
return throwable;
}
/**
* {@inheritDoc}
*/
public void onReset(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
for (InstallationListener installationListener : installationListeners) {
installationListener.onReset(instrumentation, classFileTransformer);
}
}
}
}
/**
* This strategy determines how the provided class file buffer is used.
*/
interface ClassFileBufferStrategy {
/**
* Resolves a class file locator for the class file buffer that is provided to the class file transformer.
*
* @param name The instrumented type's binary name.
* @param binaryRepresentation The instrumented type's binary representation.
* @param classLoader The instrumented type's class loader or {@code null} if the type is loaded by the bootstrap class loader.
* @param module The instrumented type's module or {@code null} if the current VM does not support modules.
* @param protectionDomain The instrumented type's protection domain.
* @return An appropriate class file locator.
*/
ClassFileLocator resolve(String name, byte[] binaryRepresentation, ClassLoader classLoader, JavaModule module, ProtectionDomain protectionDomain);
/**
* An implementation of default class file buffer strategy.
*/
enum Default implements ClassFileBufferStrategy {
/**
* A class file buffer strategy that retains the original class file buffer.
*/
RETAINING {
/** {@inheritDoc} */
public ClassFileLocator resolve(String name,
byte[] binaryRepresentation,
ClassLoader classLoader,
JavaModule module,
ProtectionDomain protectionDomain) {
return ClassFileLocator.Simple.of(name, binaryRepresentation);
}
},
/**
* <p>
* A class file buffer strategy that discards the original class file buffer.
* </p>
* <p>
* <b>Warning</b>: This strategy discards any changes that were applied by previous Java agents.
* </p>
*/
DISCARDING {
/** {@inheritDoc} */
public ClassFileLocator resolve(String name,
byte[] binaryRepresentation,
ClassLoader classLoader,
JavaModule module,
ProtectionDomain protectionDomain) {
return ClassFileLocator.NoOp.INSTANCE;
}
}
}
}
/**
* A decorator that allows to change the class file transformer that is registered.
*/
interface TransformerDecorator {
/**
* Decorates the applied class file transformer.
*
* @param classFileTransformer The original transformer created by the agent builder.
* @return The class file transformer that is actually being registered.
*/
ResettableClassFileTransformer decorate(ResettableClassFileTransformer classFileTransformer);
/**
* A transformer decorator that retains the original transformer.
*/
enum NoOp implements TransformerDecorator {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer decorate(ResettableClassFileTransformer classFileTransformer) {
return classFileTransformer;
}
}
/**
* A compound transformer decorator.
*/
@HashCodeAndEqualsPlugin.Enhance
class Compound implements TransformerDecorator {
/**
* The listeners to invoke.
*/
private final List<TransformerDecorator> transformerDecorators;
/**
* Creates a new compound transformer decorator.
*
* @param transformerDecorator The transformer decorators to add.
*/
public Compound(TransformerDecorator... transformerDecorator) {
this(Arrays.asList(transformerDecorator));
}
/**
* Creates a new compound listener.
*
* @param transformerDecorators The transformerDecorators to invoke.
*/
public Compound(List<? extends TransformerDecorator> transformerDecorators) {
this.transformerDecorators = new ArrayList<TransformerDecorator>();
for (TransformerDecorator transformerDecorator : transformerDecorators) {
if (transformerDecorator instanceof Compound) {
this.transformerDecorators.addAll(((Compound) transformerDecorator).transformerDecorators);
} else if (!(transformerDecorator instanceof NoOp)) {
this.transformerDecorators.add(transformerDecorator);
}
}
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer decorate(ResettableClassFileTransformer classFileTransformer) {
for (TransformerDecorator transformerDecorator : transformerDecorators) {
classFileTransformer = transformerDecorator.decorate(classFileTransformer);
}
return classFileTransformer;
}
}
}
/**
* <p>
* A redefinition strategy regulates how already loaded classes are modified by a built agent.
* </p>
* <p>
* <b>Important</b>: Most JVMs do not support changes of a class's structure after a class was already
* loaded. Therefore, it is typically required that this class file transformer was built while enabling
* {@link AgentBuilder#disableClassFormatChanges()}.
* </p>
*/
enum RedefinitionStrategy {
/**
* Disables redefinition such that already loaded classes are not affected by the agent.
*/
DISABLED(false, false) {
@Override
public void apply(Instrumentation instrumentation,
AgentBuilder.Listener listener,
CircularityLock circularityLock,
PoolStrategy poolStrategy,
LocationStrategy locationStrategy,
DiscoveryStrategy discoveryStrategy,
BatchAllocator redefinitionBatchAllocator,
Listener redefinitionListener,
LambdaInstrumentationStrategy lambdaInstrumentationStrategy,
DescriptionStrategy descriptionStrategy,
FallbackStrategy fallbackStrategy,
RawMatcher matcher) {
/* do nothing */
}
@Override
protected void check(Instrumentation instrumentation) {
throw new IllegalStateException("Cannot apply redefinition on disabled strategy");
}
@Override
protected Collector make() {
throw new IllegalStateException("A disabled redefinition strategy cannot create a collector");
}
},
/**
* <p>
* Applies a <b>redefinition</b> to all classes that are already loaded and that would have been transformed if
* the built agent was registered before they were loaded. The created {@link ClassFileTransformer} is <b>not</b>
* registered for applying retransformations.
* </p>
* <p>
* Using this strategy, a redefinition is applied as a single transformation request. This means that a single illegal
* redefinition of a class causes the entire redefinition attempt to fail.
* </p>
* <p>
* <b>Note</b>: When applying a redefinition, it is normally required to use a {@link TypeStrategy} that applies
* a redefinition instead of rebasing classes such as {@link TypeStrategy.Default#REDEFINE}. Also, consider
* the constrains given by this type strategy.
* </p>
*/
REDEFINITION(true, false) {
@Override
protected void check(Instrumentation instrumentation) {
if (!instrumentation.isRedefineClassesSupported()) {
throw new IllegalStateException("Cannot apply redefinition on " + instrumentation);
}
}
@Override
protected Collector make() {
return new Collector.ForRedefinition();
}
},
/**
* <p>
* Applies a <b>retransformation</b> to all classes that are already loaded and that would have been transformed if
* the built agent was registered before they were loaded. The created {@link ClassFileTransformer} is registered
* for applying retransformations.
* </p>
* <p>
* Using this strategy, a retransformation is applied as a single transformation request. This means that a single illegal
* retransformation of a class causes the entire retransformation attempt to fail.
* </p>
* <p>
* <b>Note</b>: When applying a retransformation, it is normally required to use a {@link TypeStrategy} that applies
* a redefinition instead of rebasing classes such as {@link TypeStrategy.Default#REDEFINE}. Also, consider
* the constrains given by this type strategy.
* </p>
*/
RETRANSFORMATION(true, true) {
@Override
protected void check(Instrumentation instrumentation) {
if (!DISPATCHER.isRetransformClassesSupported(instrumentation)) {
throw new IllegalStateException("Cannot apply retransformation on " + instrumentation);
}
}
@Override
protected Collector make() {
return new Collector.ForRetransformation();
}
};
/**
* A dispatcher to use for interacting with the instrumentation API.
*/
protected static final Dispatcher DISPATCHER = AccessController.doPrivileged(Dispatcher.CreationAction.INSTANCE);
/**
* Indicates that this redefinition strategy is enabled.
*/
private final boolean enabled;
/**
* {@code true} if this strategy applies retransformation.
*/
private final boolean retransforming;
/**
* Creates a new redefinition strategy.
*
* @param enabled {@code true} if this strategy is enabled.
* @param retransforming {@code true} if this strategy applies retransformation.
*/
RedefinitionStrategy(boolean enabled, boolean retransforming) {
this.enabled = enabled;
this.retransforming = retransforming;
}
/**
* Indicates if this strategy requires a class file transformer to be registered with a hint to apply the
* transformer for retransformation.
*
* @return {@code true} if a class file transformer must be registered with a hint for retransformation.
*/
protected boolean isRetransforming() {
return retransforming;
}
/**
* Checks if this strategy can be applied to the supplied instrumentation instance.
*
* @param instrumentation The instrumentation instance to validate.
*/
protected abstract void check(Instrumentation instrumentation);
/**
* Indicates that this redefinition strategy applies a modification of already loaded classes.
*
* @return {@code true} if this redefinition strategy applies a modification of already loaded classes.
*/
protected boolean isEnabled() {
return enabled;
}
/**
* Creates a collector instance that is responsible for collecting loaded classes for potential retransformation.
*
* @return A new collector for collecting already loaded classes for transformation.
*/
protected abstract Collector make();
/**
* Applies this redefinition strategy by submitting all loaded types to redefinition. If this redefinition strategy is disabled,
* this method is non-operational.
*
* @param instrumentation The instrumentation instance to use.
* @param listener The listener to notify on transformations.
* @param circularityLock The circularity lock to use.
* @param poolStrategy The type locator to use.
* @param locationStrategy The location strategy to use.
* @param redefinitionDiscoveryStrategy The discovery strategy for loaded types to be redefined.
* @param redefinitionBatchAllocator The batch allocator for the redefinition strategy to apply.
* @param redefinitionListener The redefinition listener for the redefinition strategy to apply.
* @param lambdaInstrumentationStrategy A strategy to determine of the {@code LambdaMetafactory} should be instrumented to allow for the
* instrumentation of classes that represent lambda expressions.
* @param descriptionStrategy The description strategy for resolving type descriptions for types.
* @param fallbackStrategy The fallback strategy to apply.
* @param matcher The matcher to identify what types to redefine.
*/
protected void apply(Instrumentation instrumentation,
AgentBuilder.Listener listener,
CircularityLock circularityLock,
PoolStrategy poolStrategy,
LocationStrategy locationStrategy,
DiscoveryStrategy redefinitionDiscoveryStrategy,
BatchAllocator redefinitionBatchAllocator,
Listener redefinitionListener,
LambdaInstrumentationStrategy lambdaInstrumentationStrategy,
DescriptionStrategy descriptionStrategy,
FallbackStrategy fallbackStrategy,
RawMatcher matcher) {
check(instrumentation);
int batch = RedefinitionStrategy.BatchAllocator.FIRST_BATCH;
for (Iterable<Class<?>> types : redefinitionDiscoveryStrategy.resolve(instrumentation)) {
RedefinitionStrategy.Collector collector = make();
for (Class<?> type : types) {
if (type == null || type.isArray() || !lambdaInstrumentationStrategy.isInstrumented(type)) {
continue;
}
JavaModule module = JavaModule.ofType(type);
try {
TypePool typePool = poolStrategy.typePool(locationStrategy.classFileLocator(type.getClassLoader(), module), type.getClassLoader());
try {
collector.consider(matcher,
listener,
descriptionStrategy.apply(TypeDescription.ForLoadedType.getName(type), type, typePool, circularityLock, type.getClassLoader(), module),
type,
type,
module,
!DISPATCHER.isModifiableClass(instrumentation, type));
} catch (Throwable throwable) {
if (descriptionStrategy.isLoadedFirst() && fallbackStrategy.isFallback(type, throwable)) {
collector.consider(matcher,
listener,
typePool.describe(TypeDescription.ForLoadedType.getName(type)).resolve(),
type,
module);
} else {
throw throwable;
}
}
} catch (Throwable throwable) {
try {
try {
listener.onDiscovery(TypeDescription.ForLoadedType.getName(type), type.getClassLoader(), module, AgentBuilder.Listener.LOADED);
} finally {
try {
listener.onError(TypeDescription.ForLoadedType.getName(type), type.getClassLoader(), module, AgentBuilder.Listener.LOADED, throwable);
} finally {
listener.onComplete(TypeDescription.ForLoadedType.getName(type), type.getClassLoader(), module, AgentBuilder.Listener.LOADED);
}
}
} catch (Throwable ignored) {
// Ignore exceptions that are thrown by listeners to mimic the behavior of a transformation.
}
}
}
batch = collector.apply(instrumentation, circularityLock, locationStrategy, listener, redefinitionBatchAllocator, redefinitionListener, batch);
}
}
/**
* A batch allocator which is responsible for applying a redefinition in a batches. A class redefinition or
* retransformation can be a time-consuming operation rendering a JVM non-responsive. In combination with a
* a {@link RedefinitionStrategy.Listener}, it is also possible to apply pauses between batches to distribute
* the load of a retransformation over time.
*/
public interface BatchAllocator {
/**
* The index of the first batch.
*/
int FIRST_BATCH = 0;
/**
* Splits a list of types to be retransformed into separate batches.
*
* @param types A list of types which should be retransformed.
* @return An iterable of retransformations within a batch.
*/
Iterable<? extends List<Class<?>>> batch(List<Class<?>> types);
/**
* A batch allocator that includes all types in a single batch.
*/
enum ForTotal implements BatchAllocator {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Iterable<? extends List<Class<?>>> batch(List<Class<?>> types) {
return types.isEmpty()
? Collections.<List<Class<?>>>emptySet()
: Collections.singleton(types);
}
}
/**
* A batch allocator that creates chunks with a fixed size as batch jobs.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForFixedSize implements BatchAllocator {
/**
* The size of each chunk.
*/
private final int size;
/**
* Creates a new batch allocator that creates fixed-sized chunks.
*
* @param size The size of each chunk.
*/
protected ForFixedSize(int size) {
this.size = size;
}
/**
* Creates a new batch allocator that creates chunks of a fixed size.
*
* @param size The size of each chunk or {@code 0} if the batch should be included in a single chunk.
* @return An appropriate batch allocator.
*/
public static BatchAllocator ofSize(int size) {
if (size > 0) {
return new ForFixedSize(size);
} else if (size == 0) {
return ForTotal.INSTANCE;
} else {
throw new IllegalArgumentException("Cannot define a batch with a negative size: " + size);
}
}
/**
* {@inheritDoc}
*/
public Iterable<? extends List<Class<?>>> batch(List<Class<?>> types) {
List<List<Class<?>>> batches = new ArrayList<List<Class<?>>>();
for (int index = 0; index < types.size(); index += size) {
batches.add(new ArrayList<Class<?>>(types.subList(index, Math.min(types.size(), index + size))));
}
return batches;
}
}
/**
* A batch allocator that groups all batches by discriminating types using a type matcher.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForMatchedGrouping implements BatchAllocator {
/**
* The type matchers to apply.
*/
private final Collection<? extends ElementMatcher<? super TypeDescription>> matchers;
/**
* Creates a new batch allocator that groups all batches by discriminating types using a type matcher. All batches
* are applied in their application order with any unmatched type being included in the last batch.
*
* @param matcher The type matchers to apply in their application order.
*/
@SuppressWarnings("unchecked") // In absence of @SafeVarargs
public ForMatchedGrouping(ElementMatcher<? super TypeDescription>... matcher) {
this(new LinkedHashSet<ElementMatcher<? super TypeDescription>>(Arrays.asList(matcher)));
}
/**
* Creates a new batch allocator that groups all batches by discriminating types using a type matcher. All batches
* are applied in their application order with any unmatched type being included in the last batch.
*
* @param matchers The type matchers to apply in their application order.
*/
public ForMatchedGrouping(Collection<? extends ElementMatcher<? super TypeDescription>> matchers) {
this.matchers = matchers;
}
/**
* Assures that any group is at least of a given size. If a group is smaller than a given size, it is merged with its types
* are merged with its subsequent group(s) as long as such groups exist.
*
* @param threshold The minimum threshold for any batch.
* @return An appropriate batch allocator.
*/
public BatchAllocator withMinimum(int threshold) {
return Slicing.withMinimum(threshold, this);
}
/**
* Assures that any group is at least of a given size. If a group is bigger than a given size, it is split into two several
* batches.
*
* @param threshold The maximum threshold for any batch.
* @return An appropriate batch allocator.
*/
public BatchAllocator withMaximum(int threshold) {
return Slicing.withMaximum(threshold, this);
}
/**
* Assures that any group is within a size range described by the supplied minimum and maximum. Groups are split and merged
* according to the supplied thresholds. The last group contains might be smaller than the supplied minimum.
*
* @param minimum The minimum threshold for any batch.
* @param maximum The maximum threshold for any batch.
* @return An appropriate batch allocator.
*/
public BatchAllocator withinRange(int minimum, int maximum) {
return Slicing.withinRange(minimum, maximum, this);
}
/**
* {@inheritDoc}
*/
public Iterable<? extends List<Class<?>>> batch(List<Class<?>> types) {
Map<ElementMatcher<? super TypeDescription>, List<Class<?>>> matched = new LinkedHashMap<ElementMatcher<? super TypeDescription>, List<Class<?>>>();
List<Class<?>> unmatched = new ArrayList<Class<?>>();
for (ElementMatcher<? super TypeDescription> matcher : matchers) {
matched.put(matcher, new ArrayList<Class<?>>());
}
typeLoop:
for (Class<?> type : types) {
for (ElementMatcher<? super TypeDescription> matcher : matchers) {
if (matcher.matches(TypeDescription.ForLoadedType.of(type))) {
matched.get(matcher).add(type);
continue typeLoop;
}
}
unmatched.add(type);
}
List<List<Class<?>>> batches = new ArrayList<List<Class<?>>>(matchers.size() + 1);
for (List<Class<?>> batch : matched.values()) {
if (!batch.isEmpty()) {
batches.add(batch);
}
}
if (!unmatched.isEmpty()) {
batches.add(unmatched);
}
return batches;
}
}
/**
* A slicing batch allocator that assures that any batch is within a certain size range.
*/
@HashCodeAndEqualsPlugin.Enhance
class Slicing implements BatchAllocator {
/**
* The minimum size of each slice.
*/
private final int minimum;
/**
* The maximum size of each slice.
*/
private final int maximum;
/**
* The delegate batch allocator.
*/
private final BatchAllocator batchAllocator;
/**
* Creates a new slicing batch allocator.
*
* @param minimum The minimum size of each slice.
* @param maximum The maximum size of each slice.
* @param batchAllocator The delegate batch allocator.
*/
protected Slicing(int minimum, int maximum, BatchAllocator batchAllocator) {
this.minimum = minimum;
this.maximum = maximum;
this.batchAllocator = batchAllocator;
}
/**
* Creates a new slicing batch allocator.
*
* @param minimum The minimum size of each slice.
* @param batchAllocator The delegate batch allocator.
* @return An appropriate slicing batch allocator.
*/
public static BatchAllocator withMinimum(int minimum, BatchAllocator batchAllocator) {
return withinRange(minimum, Integer.MAX_VALUE, batchAllocator);
}
/**
* Creates a new slicing batch allocator.
*
* @param maximum The maximum size of each slice.
* @param batchAllocator The delegate batch allocator.
* @return An appropriate slicing batch allocator.
*/
public static BatchAllocator withMaximum(int maximum, BatchAllocator batchAllocator) {
return withinRange(1, maximum, batchAllocator);
}
/**
* Creates a new slicing batch allocator.
*
* @param minimum The minimum size of each slice.
* @param maximum The maximum size of each slice.
* @param batchAllocator The delegate batch allocator.
* @return An appropriate slicing batch allocator.
*/
public static BatchAllocator withinRange(int minimum, int maximum, BatchAllocator batchAllocator) {
if (minimum <= 0) {
throw new IllegalArgumentException("Minimum must be a positive number: " + minimum);
} else if (minimum > maximum) {
throw new IllegalArgumentException("Minimum must not be bigger than maximum: " + minimum + " >" + maximum);
}
return new Slicing(minimum, maximum, batchAllocator);
}
/**
* {@inheritDoc}
*/
public Iterable<? extends List<Class<?>>> batch(List<Class<?>> types) {
return new SlicingIterable(minimum, maximum, batchAllocator.batch(types));
}
/**
* An iterable that slices batches into parts of a minimum and maximum size.
*/
protected static class SlicingIterable implements Iterable<List<Class<?>>> {
/**
* The minimum size of any slice.
*/
private final int minimum;
/**
* The maximum size of any slice.
*/
private final int maximum;
/**
* The delegate iterable.
*/
private final Iterable<? extends List<Class<?>>> iterable;
/**
* Creates a new slicing iterable.
*
* @param minimum The minimum size of any slice.
* @param maximum The maximum size of any slice.
* @param iterable The delegate iterable.
*/
protected SlicingIterable(int minimum, int maximum, Iterable<? extends List<Class<?>>> iterable) {
this.minimum = minimum;
this.maximum = maximum;
this.iterable = iterable;
}
/**
* {@inheritDoc}
*/
public Iterator<List<Class<?>>> iterator() {
return new SlicingIterator(minimum, maximum, iterable.iterator());
}
/**
* An iterator that slices batches into parts of a minimum and maximum size.
*/
protected static class SlicingIterator implements Iterator<List<Class<?>>> {
/**
* The minimum size of any slice.
*/
private final int minimum;
/**
* The maximum size of any slice.
*/
private final int maximum;
/**
* The delegate iterator.
*/
private final Iterator<? extends List<Class<?>>> iterator;
/**
* A buffer containing all types that surpassed the maximum.
*/
private List<Class<?>> buffer;
/**
* Creates a new slicing iterator.
*
* @param minimum The minimum size of any slice.
* @param maximum The maximum size of any slice.
* @param iterator The delegate iterator.
*/
protected SlicingIterator(int minimum, int maximum, Iterator<? extends List<Class<?>>> iterator) {
this.minimum = minimum;
this.maximum = maximum;
this.iterator = iterator;
buffer = new ArrayList<Class<?>>();
}
/**
* {@inheritDoc}
*/
public boolean hasNext() {
return !buffer.isEmpty() || iterator.hasNext();
}
/**
* {@inheritDoc}
*/
public List<Class<?>> next() {
if (buffer.isEmpty()) {
buffer = iterator.next();
}
while (buffer.size() < minimum && iterator.hasNext()) {
buffer.addAll(iterator.next());
}
if (buffer.size() > maximum) {
try {
return buffer.subList(0, maximum);
} finally {
buffer = new ArrayList<Class<?>>(buffer.subList(maximum, buffer.size()));
}
} else {
try {
return buffer;
} finally {
buffer = new ArrayList<Class<?>>();
}
}
}
/**
* {@inheritDoc}
*/
public void remove() {
throw new UnsupportedOperationException("remove");
}
}
}
}
/**
* A partitioning batch allocator that splits types for redefinition into a fixed amount of parts.
*/
@HashCodeAndEqualsPlugin.Enhance
class Partitioning implements BatchAllocator {
/**
* The amount of batches to generate.
*/
private final int parts;
/**
* Creates a new batch allocator that splits types for redefinition into a fixed amount of parts.
*
* @param parts The amount of parts to create.
*/
protected Partitioning(int parts) {
this.parts = parts;
}
/**
* Creates a part-splitting batch allocator.
*
* @param parts The amount of parts to create.
* @return A batch allocator that splits the redefined types into a fixed amount of batches.
*/
public static BatchAllocator of(int parts) {
if (parts < 1) {
throw new IllegalArgumentException("A batch size must be positive: " + parts);
}
return new Partitioning(parts);
}
/**
* {@inheritDoc}
*/
public Iterable<? extends List<Class<?>>> batch(List<Class<?>> types) {
if (types.isEmpty()) {
return Collections.emptyList();
} else {
List<List<Class<?>>> batches = new ArrayList<List<Class<?>>>();
int size = types.size() / parts, reminder = types.size() % parts;
for (int index = reminder; index < types.size(); index += size) {
batches.add(new ArrayList<Class<?>>(types.subList(index, index + size)));
}
if (batches.isEmpty()) {
return Collections.singletonList(types);
} else {
batches.get(0).addAll(0, types.subList(0, reminder));
return batches;
}
}
}
}
}
/**
* A listener to be applied during a redefinition.
*/
public interface Listener {
/**
* Invoked before applying a batch.
*
* @param index A running index of the batch starting at {@code 0}.
* @param batch The types included in this batch.
* @param types All types included in the redefinition.
*/
void onBatch(int index, List<Class<?>> batch, List<Class<?>> types);
/**
* Invoked upon an error during a batch. This method is not invoked if the failure handler handled this error.
*
* @param index A running index of the batch starting at {@code 0}.
* @param batch The types included in this batch.
* @param throwable The throwable that caused this invocation.
* @param types All types included in the redefinition.
* @return A set of classes which should be attempted to be redefined. Typically, this should be a subset of the classes
* contained in {@code batch} but not all classes.
*/
Iterable<? extends List<Class<?>>> onError(int index, List<Class<?>> batch, Throwable throwable, List<Class<?>> types);
/**
* Invoked upon completion of all batches.
*
* @param amount The total amount of batches that were executed.
* @param types All types included in the redefinition.
* @param failures A mapping of batch types to their unhandled failures.
*/
void onComplete(int amount, List<Class<?>> types, Map<List<Class<?>>, Throwable> failures);
/**
* A non-operational listener.
*/
enum NoOp implements Listener {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public void onBatch(int index, List<Class<?>> batch, List<Class<?>> types) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public Iterable<? extends List<Class<?>>> onError(int index, List<Class<?>> batch, Throwable throwable, List<Class<?>> types) {
return Collections.emptyList();
}
/**
* {@inheritDoc}
*/
public void onComplete(int amount, List<Class<?>> types, Map<List<Class<?>>, Throwable> failures) {
/* do nothing */
}
}
/**
* A listener that invokes {@link Thread#yield()} prior to every batch but the first batch.
*/
enum Yielding implements Listener {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public void onBatch(int index, List<Class<?>> batch, List<Class<?>> types) {
if (index > 0) {
Thread.yield();
}
}
/**
* {@inheritDoc}
*/
public Iterable<? extends List<Class<?>>> onError(int index, List<Class<?>> batch, Throwable throwable, List<Class<?>> types) {
return Collections.emptyList();
}
/**
* {@inheritDoc}
*/
public void onComplete(int amount, List<Class<?>> types, Map<List<Class<?>>, Throwable> failures) {
/* do nothing */
}
}
/**
* A listener that halts a retransformation process upon an exception.
*/
enum ErrorEscalating implements Listener {
/**
* A listener that fails the retransformation upon the first failed retransformation of a batch.
*/
FAIL_FAST {
/** {@inheritDoc} */
public Iterable<? extends List<Class<?>>> onError(int index, List<Class<?>> batch, Throwable throwable, List<Class<?>> types) {
throw new IllegalStateException("Could not transform any of " + batch, throwable);
}
/** {@inheritDoc} */
public void onComplete(int amount, List<Class<?>> types, Map<List<Class<?>>, Throwable> failures) {
/* do nothing */
}
},
/**
* A listener that fails the retransformation after all batches were executed if any error occurred.
*/
FAIL_LAST {
/** {@inheritDoc} */
public Iterable<? extends List<Class<?>>> onError(int index, List<Class<?>> batch, Throwable throwable, List<Class<?>> types) {
return Collections.emptyList();
}
/** {@inheritDoc} */
public void onComplete(int amount, List<Class<?>> types, Map<List<Class<?>>, Throwable> failures) {
if (!failures.isEmpty()) {
throw new IllegalStateException("Could not transform any of " + failures);
}
}
};
/**
* {@inheritDoc}
*/
public void onBatch(int index, List<Class<?>> batch, List<Class<?>> types) {
/* do nothing */
}
}
/**
* A listener adapter that offers non-operational implementations of all listener methods.
*/
@HashCodeAndEqualsPlugin.Enhance
abstract class Adapter implements Listener {
/**
* {@inheritDoc}
*/
public void onBatch(int index, List<Class<?>> batch, List<Class<?>> types) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public Iterable<? extends List<Class<?>>> onError(int index, List<Class<?>> batch, Throwable throwable, List<Class<?>> types) {
return Collections.emptyList();
}
/**
* {@inheritDoc}
*/
public void onComplete(int amount, List<Class<?>> types, Map<List<Class<?>>, Throwable> failures) {
/* do nothing */
}
}
/**
* <p>
* A batch reallocator allows to split up a failed retransformation into additional batches which are reenqueed to the
* current retransformation process. To do so, any batch with at least to classes is rerouted through a {@link BatchAllocator}
* which is responsible for regrouping the classes that failed to be retransformed into new batches.
* </p>
* <p>
* <b>Important</b>: To avoid endless looping over classes that cannot be successfully retransformed, the supplied batch
* allocator must not resubmit batches that previously failed as an identical outcome is likely.
* </p>
*/
@HashCodeAndEqualsPlugin.Enhance
class BatchReallocator extends Adapter {
/**
* The batch allocator to use for reallocating failed batches.
*/
private final BatchAllocator batchAllocator;
/**
* Creates a new batch reallocator.
*
* @param batchAllocator The batch allocator to use for reallocating failed batches.
*/
public BatchReallocator(BatchAllocator batchAllocator) {
this.batchAllocator = batchAllocator;
}
/**
* Creates a batch allocator that splits any batch into two parts and resubmits these parts as two batches.
*
* @return A batch reallocating batch listener that splits failed batches into two parts for resubmission.
*/
public static Listener splitting() {
return new BatchReallocator(new BatchAllocator.Partitioning(2));
}
@Override
public Iterable<? extends List<Class<?>>> onError(int index, List<Class<?>> batch, Throwable throwable, List<Class<?>> types) {
return batch.size() < 2
? Collections.<List<Class<?>>>emptyList()
: batchAllocator.batch(batch);
}
}
/**
* A listener that invokes {@link Thread#sleep(long)} prior to every batch but the first batch.
*/
@HashCodeAndEqualsPlugin.Enhance
class Pausing extends Adapter {
/**
* The time to sleep in milliseconds between every two batches.
*/
private final long value;
/**
* Creates a new pausing listener.
*
* @param value The time to sleep in milliseconds between every two batches.
*/
protected Pausing(long value) {
this.value = value;
}
/**
* Creates a listener that pauses for the specified amount of time. If the specified value is {@code 0}, a
* non-operational listener is returned.
*
* @param value The amount of time to pause between redefinition batches.
* @param timeUnit The time unit of {@code value}.
* @return An appropriate listener.
*/
public static Listener of(long value, TimeUnit timeUnit) {
if (value > 0L) {
return new Pausing(timeUnit.toMillis(value));
} else if (value == 0L) {
return NoOp.INSTANCE;
} else {
throw new IllegalArgumentException("Cannot sleep for a non-positive amount of time: " + value);
}
}
@Override
public void onBatch(int index, List<Class<?>> batch, List<Class<?>> types) {
if (index > 0) {
try {
Thread.sleep(value);
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
throw new RuntimeException("Sleep was interrupted", exception);
}
}
}
}
/**
* A listener that writes events to a {@link PrintStream}.
*/
@HashCodeAndEqualsPlugin.Enhance
class StreamWriting implements Listener {
/**
* The print stream to write any events to.
*/
private final PrintStream printStream;
/**
* Creates a new stream writing listener.
*
* @param printStream The print stream to write any events to.
*/
public StreamWriting(PrintStream printStream) {
this.printStream = printStream;
}
/**
* Writes the stream result to {@link System#out}.
*
* @return An appropriate listener.
*/
public static Listener toSystemOut() {
return new StreamWriting(System.out);
}
/**
* Writes the stream result to {@link System#err}.
*
* @return An appropriate listener.
*/
public static Listener toSystemError() {
return new StreamWriting(System.err);
}
/**
* {@inheritDoc}
*/
public void onBatch(int index, List<Class<?>> batch, List<Class<?>> types) {
printStream.printf(AgentBuilder.Listener.StreamWriting.PREFIX + " REDEFINE BATCH #%d [%d of %d type(s)]%n", index, batch.size(), types.size());
}
/**
* {@inheritDoc}
*/
public Iterable<? extends List<Class<?>>> onError(int index, List<Class<?>> batch, Throwable throwable, List<Class<?>> types) {
synchronized (printStream) {
printStream.printf(AgentBuilder.Listener.StreamWriting.PREFIX + " REDEFINE ERROR #%d [%d of %d type(s)]%n", index, batch.size(), types.size());
throwable.printStackTrace(printStream);
}
return Collections.emptyList();
}
/**
* {@inheritDoc}
*/
public void onComplete(int amount, List<Class<?>> types, Map<List<Class<?>>, Throwable> failures) {
printStream.printf(AgentBuilder.Listener.StreamWriting.PREFIX + " REDEFINE COMPLETE %d batch(es) containing %d types [%d failed batch(es)]%n", amount, types.size(), failures.size());
}
}
/**
* A compound listener that delegates events to several listeners.
*/
@HashCodeAndEqualsPlugin.Enhance
class Compound implements Listener {
/**
* The listeners to invoke.
*/
private final List<Listener> listeners;
/**
* Creates a new compound listener.
*
* @param listener The listeners to invoke.
*/
public Compound(Listener... listener) {
this(Arrays.asList(listener));
}
/**
* Creates a new compound listener.
*
* @param listeners The listeners to invoke.
*/
public Compound(List<? extends Listener> listeners) {
this.listeners = new ArrayList<Listener>();
for (Listener listener : listeners) {
if (listener instanceof Compound) {
this.listeners.addAll(((Compound) listener).listeners);
} else if (!(listener instanceof NoOp)) {
this.listeners.add(listener);
}
}
}
/**
* {@inheritDoc}
*/
public void onBatch(int index, List<Class<?>> batch, List<Class<?>> types) {
for (Listener listener : listeners) {
listener.onBatch(index, batch, types);
}
}
/**
* {@inheritDoc}
*/
public Iterable<? extends List<Class<?>>> onError(int index, List<Class<?>> batch, Throwable throwable, List<Class<?>> types) {
List<Iterable<? extends List<Class<?>>>> reattempts = new ArrayList<Iterable<? extends List<Class<?>>>>();
for (Listener listener : listeners) {
reattempts.add(listener.onError(index, batch, throwable, types));
}
return new CompoundIterable(reattempts);
}
/**
* {@inheritDoc}
*/
public void onComplete(int amount, List<Class<?>> types, Map<List<Class<?>>, Throwable> failures) {
for (Listener listener : listeners) {
listener.onComplete(amount, types, failures);
}
}
/**
* A compound iterable.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class CompoundIterable implements Iterable<List<Class<?>>> {
/**
* The iterables to consider.
*/
private final List<Iterable<? extends List<Class<?>>>> iterables;
/**
* Creates a compound iterable.
*
* @param iterables The iterables to consider.
*/
protected CompoundIterable(List<Iterable<? extends List<Class<?>>>> iterables) {
this.iterables = iterables;
}
/**
* {@inheritDoc}
*/
public Iterator<List<Class<?>>> iterator() {
return new CompoundIterator(new ArrayList<Iterable<? extends List<Class<?>>>>(iterables));
}
/**
* A compound iterator that combines several iterables.
*/
protected static class CompoundIterator implements Iterator<List<Class<?>>> {
/**
* The current iterator or {@code null} if no such iterator is defined.
*/
private Iterator<? extends List<Class<?>>> current;
/**
* A backlog of iterables to still consider.
*/
private final List<Iterable<? extends List<Class<?>>>> backlog;
/**
* Creates a compound iterator.
*
* @param iterables The iterables to consider.
*/
protected CompoundIterator(List<Iterable<? extends List<Class<?>>>> iterables) {
backlog = iterables;
forward();
}
/**
* {@inheritDoc}
*/
public boolean hasNext() {
return current != null && current.hasNext();
}
/**
* {@inheritDoc}
*/
public List<Class<?>> next() {
try {
if (current != null) {
return current.next();
} else {
throw new NoSuchElementException();
}
} finally {
forward();
}
}
/**
* Forwards the iterator to the next relevant iterable.
*/
private void forward() {
while ((current == null || !current.hasNext()) && !backlog.isEmpty()) {
current = backlog.remove(0).iterator();
}
}
/**
* {@inheritDoc}
*/
public void remove() {
throw new UnsupportedOperationException("remove");
}
}
}
}
}
/**
* A strategy for discovering types to redefine.
*/
public interface DiscoveryStrategy {
/**
* Resolves an iterable of types to retransform. Types might be loaded during a previous retransformation which might require
* multiple passes for a retransformation.
*
* @param instrumentation The instrumentation instance used for the redefinition.
* @return An iterable of types to consider for retransformation.
*/
Iterable<Iterable<Class<?>>> resolve(Instrumentation instrumentation);
/**
* A discovery strategy that considers all loaded types supplied by {@link Instrumentation#getAllLoadedClasses()}.
*/
enum SinglePass implements DiscoveryStrategy {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Iterable<Iterable<Class<?>>> resolve(Instrumentation instrumentation) {
return Collections.<Iterable<Class<?>>>singleton(Arrays.<Class<?>>asList(instrumentation.getAllLoadedClasses()));
}
}
/**
* A discovery strategy that considers all loaded types supplied by {@link Instrumentation#getAllLoadedClasses()}. For each reiteration,
* this strategy checks if additional types were loaded after the previously supplied types. Doing so, types that were loaded during
* instrumentations can be retransformed as such types are not passed to any class file transformer.
*/
enum Reiterating implements DiscoveryStrategy {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Iterable<Iterable<Class<?>>> resolve(Instrumentation instrumentation) {
return new ReiteratingIterable(instrumentation);
}
/**
* An iterable that returns any loaded types and checks if any additional types were loaded during the last instrumentation.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class ReiteratingIterable implements Iterable<Iterable<Class<?>>> {
/**
* The instrumentation instance to use.
*/
private final Instrumentation instrumentation;
/**
* Creates a new reiterating iterable.
*
* @param instrumentation The instrumentation instance to use.
*/
protected ReiteratingIterable(Instrumentation instrumentation) {
this.instrumentation = instrumentation;
}
/**
* {@inheritDoc}
*/
public Iterator<Iterable<Class<?>>> iterator() {
return new ReiteratingIterator(instrumentation);
}
}
/**
* A reiterating iterator that considers types that were loaded during an instrumentation.
*/
protected static class ReiteratingIterator implements Iterator<Iterable<Class<?>>> {
/**
* The instrumentation instance to use.
*/
private final Instrumentation instrumentation;
/**
* A set containing all previously discovered types.
*/
private final Set<Class<?>> processed;
/**
* The current list of types or {@code null} if the current list of types is not prepared.
*/
private List<Class<?>> types;
/**
* Creates a new reiterating iterator.
*
* @param instrumentation The instrumentation instance to use.
*/
protected ReiteratingIterator(Instrumentation instrumentation) {
this.instrumentation = instrumentation;
processed = new HashSet<Class<?>>();
}
/**
* {@inheritDoc}
*/
public boolean hasNext() {
if (types == null) {
types = new ArrayList<Class<?>>();
for (Class<?> type : instrumentation.getAllLoadedClasses()) {
if (type != null && processed.add(type)) {
types.add(type);
}
}
}
return !types.isEmpty();
}
/**
* {@inheritDoc}
*/
public Iterable<Class<?>> next() {
if (hasNext()) {
try {
return types;
} finally {
types = null;
}
} else {
throw new NoSuchElementException();
}
}
/**
* {@inheritDoc}
*/
public void remove() {
throw new UnsupportedOperationException("remove");
}
}
}
/**
* An explicit discovery strategy that only attempts the redefinition of specific types.
*/
@HashCodeAndEqualsPlugin.Enhance
class Explicit implements DiscoveryStrategy {
/**
* The types to redefine.
*/
private final Set<Class<?>> types;
/**
* Creates a new explicit discovery strategy.
*
* @param type The types to redefine.
*/
public Explicit(Class<?>... type) {
this(new LinkedHashSet<Class<?>>(Arrays.asList(type)));
}
/**
* Creates a new explicit discovery strategy.
*
* @param types The types to redefine.
*/
public Explicit(Set<Class<?>> types) {
this.types = types;
}
/**
* {@inheritDoc}
*/
public Iterable<Iterable<Class<?>>> resolve(Instrumentation instrumentation) {
return Collections.<Iterable<Class<?>>>singleton(types);
}
}
}
/**
* A resubmission scheduler is responsible for scheduling a job that is resubmitting unloaded types that failed during retransformation.
*/
public interface ResubmissionScheduler {
/**
* Checks if this scheduler is currently available.
*
* @return {@code true} if this scheduler is alive.
*/
boolean isAlive();
/**
* Schedules a resubmission job for regular application.
*
* @param job The job to schedule.
* @return A cancelable that is canceled upon resetting the corresponding class file transformer.
*/
Cancelable schedule(Runnable job);
/**
* A cancelable allows to discontinue a resubmission job.
*/
interface Cancelable {
/**
* Cancels this resubmission job.
*/
void cancel();
/**
* A non-operational cancelable.
*/
enum NoOp implements Cancelable {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public void cancel() {
/* do nothing */
}
}
/**
* A cancelable for a {@link Future}.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForFuture implements Cancelable {
/**
* The future to cancel upon cancellation of this instance.
*/
private final Future<?> future;
/**
* Creates a cancelable for a future.
*
* @param future The future to cancel upon cancellation of this instance.
*/
public ForFuture(Future<?> future) {
this.future = future;
}
/**
* {@inheritDoc}
*/
public void cancel() {
future.cancel(true);
}
}
}
/**
* A resubmission scheduler that does not apply any scheduling.
*/
enum NoOp implements ResubmissionScheduler {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public boolean isAlive() {
return false;
}
/**
* {@inheritDoc}
*/
public Cancelable schedule(Runnable job) {
return Cancelable.NoOp.INSTANCE;
}
}
/**
* A resubmission scheduler that schedules jobs at a fixed rate.
*/
@HashCodeAndEqualsPlugin.Enhance
class AtFixedRate implements ResubmissionScheduler {
/**
* The executor service to schedule to.
*/
private final ScheduledExecutorService scheduledExecutorService;
/**
* The time interval between schedulings.
*/
private final long time;
/**
* The time's time unit.
*/
private final TimeUnit timeUnit;
/**
* Creates a new resubmission scheduler which schedules executions at a fixed rate.
*
* @param scheduledExecutorService The executor service to schedule to.
* @param time The time interval between schedulings.
* @param timeUnit The time's time unit.
*/
public AtFixedRate(ScheduledExecutorService scheduledExecutorService, long time, TimeUnit timeUnit) {
this.scheduledExecutorService = scheduledExecutorService;
this.time = time;
this.timeUnit = timeUnit;
}
/**
* {@inheritDoc}
*/
public boolean isAlive() {
return !scheduledExecutorService.isShutdown();
}
/**
* {@inheritDoc}
*/
public Cancelable schedule(Runnable job) {
return new Cancelable.ForFuture(scheduledExecutorService.scheduleAtFixedRate(job, time, time, timeUnit));
}
}
/**
* A resubmission scheduler that schedules jobs with a fixed delay.
*/
@HashCodeAndEqualsPlugin.Enhance
class WithFixedDelay implements ResubmissionScheduler {
/**
* The executor service to schedule to.
*/
private final ScheduledExecutorService scheduledExecutorService;
/**
* The time interval to pause between completed jobs.
*/
private final long time;
/**
* The time's time unit.
*/
private final TimeUnit timeUnit;
/**
* Creates a new resubmission scheduler with a fixed delay between job executions.
*
* @param scheduledExecutorService The executor service to schedule to.
* @param time The time interval to pause between completed jobs.
* @param timeUnit The time's time unit.
*/
public WithFixedDelay(ScheduledExecutorService scheduledExecutorService, long time, TimeUnit timeUnit) {
this.scheduledExecutorService = scheduledExecutorService;
this.time = time;
this.timeUnit = timeUnit;
}
/**
* {@inheritDoc}
*/
public boolean isAlive() {
return !scheduledExecutorService.isShutdown();
}
/**
* {@inheritDoc}
*/
public Cancelable schedule(Runnable job) {
return new Cancelable.ForFuture(scheduledExecutorService.scheduleWithFixedDelay(job, time, time, timeUnit));
}
}
}
/**
* A resubmission strategy is responsible for enabling resubmission of types that failed to resubmit.
*/
protected interface ResubmissionStrategy {
/**
* Invoked upon installation of an agent builder.
*
* @param instrumentation The instrumentation instance to use.
* @param locationStrategy The location strategy to use.
* @param listener The listener to use.
* @param installationListener The installation listener to use.
* @param circularityLock The circularity lock to use.
* @param matcher The matcher to apply for analyzing if a type is to be resubmitted.
* @param redefinitionStrategy The redefinition strategy to use.
* @param redefinitionBatchAllocator The batch allocator to use.
* @param redefinitionBatchListener The batch listener to notify.
* @return A potentially modified listener to apply.
*/
Installation apply(Instrumentation instrumentation,
LocationStrategy locationStrategy,
AgentBuilder.Listener listener,
InstallationListener installationListener,
CircularityLock circularityLock,
RawMatcher matcher,
RedefinitionStrategy redefinitionStrategy,
RedefinitionStrategy.BatchAllocator redefinitionBatchAllocator,
RedefinitionStrategy.Listener redefinitionBatchListener);
/**
* A disabled resubmission strategy.
*/
enum Disabled implements ResubmissionStrategy {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Installation apply(Instrumentation instrumentation,
LocationStrategy locationStrategy,
AgentBuilder.Listener listener,
InstallationListener installationListener,
CircularityLock circularityLock,
RawMatcher matcher,
RedefinitionStrategy redefinitionStrategy,
BatchAllocator redefinitionBatchAllocator,
Listener redefinitionBatchListener) {
return new Installation(listener, installationListener);
}
}
/**
* An enabled resubmission strategy.
*/
@HashCodeAndEqualsPlugin.Enhance
class Enabled implements ResubmissionStrategy {
/**
* A scheduler that is responsible for resubmission of types.
*/
private final ResubmissionScheduler resubmissionScheduler;
/**
* The matcher for filtering error causes.
*/
private final ElementMatcher<? super Throwable> matcher;
/**
* Creates a new enabled resubmission strategy.
*
* @param resubmissionScheduler A scheduler that is responsible for resubmission of types.
* @param matcher The matcher for filtering error causes.
*/
protected Enabled(ResubmissionScheduler resubmissionScheduler, ElementMatcher<? super Throwable> matcher) {
this.resubmissionScheduler = resubmissionScheduler;
this.matcher = matcher;
}
/**
* {@inheritDoc}
*/
public Installation apply(Instrumentation instrumentation,
LocationStrategy locationStrategy,
AgentBuilder.Listener listener,
InstallationListener installationListener,
CircularityLock circularityLock,
RawMatcher matcher,
RedefinitionStrategy redefinitionStrategy,
RedefinitionStrategy.BatchAllocator redefinitionBatchAllocator,
RedefinitionStrategy.Listener redefinitionBatchListener) {
if (redefinitionStrategy.isEnabled() && resubmissionScheduler.isAlive()) {
ConcurrentMap<StorageKey, Set<String>> types = new ConcurrentHashMap<StorageKey, Set<String>>();
return new Installation(new AgentBuilder.Listener.Compound(new ResubmissionListener(this.matcher, types), listener),
new InstallationListener.Compound(new ResubmissionInstallationListener(resubmissionScheduler,
instrumentation,
locationStrategy,
listener,
circularityLock,
matcher,
redefinitionStrategy,
redefinitionBatchAllocator,
redefinitionBatchListener,
types), installationListener));
} else {
return new Installation(listener, installationListener);
}
}
/**
* A listener that registers types for resubmission that failed during transformations.
*/
protected static class ResubmissionListener extends AgentBuilder.Listener.Adapter {
/**
* The matcher for filtering error causes.
*/
private final ElementMatcher<? super Throwable> matcher;
/**
* A map of class loaders to their types to resubmit.
*/
private final ConcurrentMap<StorageKey, Set<String>> types;
/**
* @param matcher The matcher for filtering error causes.
* @param types A map of class loaders to their types to resubmit.
*/
protected ResubmissionListener(ElementMatcher<? super Throwable> matcher, ConcurrentMap<StorageKey, Set<String>> types) {
this.matcher = matcher;
this.types = types;
}
/**
* {@inheritDoc}
*/
@SuppressFBWarnings(value = "GC_UNRELATED_TYPES", justification = "Use of unrelated key is intended for avoiding unnecessary weak reference")
public void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable) {
if (!loaded && matcher.matches(throwable)) {
Set<String> types = this.types.get(new LookupKey(classLoader));
if (types == null) {
types = new ConcurrentHashSet<String>();
Set<String> previous = this.types.putIfAbsent(new StorageKey(classLoader), types);
if (previous != null) {
types = previous;
}
}
types.add(typeName);
}
}
/**
* A set projection for a {@link ConcurrentHashMap}.
*
* @param <T> The element type of the set projection.
*/
protected static class ConcurrentHashSet<T> extends AbstractSet<T> {
/**
* The delegate map.
*/
private final ConcurrentMap<T, Boolean> delegate;
/**
* Creates a concurrent hash set.
*/
protected ConcurrentHashSet() {
delegate = new ConcurrentHashMap<T, Boolean>();
}
@Override
public boolean add(T value) {
return delegate.put(value, Boolean.TRUE) == null;
}
@Override
public boolean remove(Object value) {
return delegate.remove(value) != null;
}
/**
* {@inheritDoc}
*/
public Iterator<T> iterator() {
return delegate.keySet().iterator();
}
/**
* {@inheritDoc}
*/
public int size() {
return delegate.size();
}
}
}
/**
* A job that resubmits any matched type that previously failed during transformation.
*/
protected static class ResubmissionInstallationListener extends AgentBuilder.InstallationListener.Adapter implements Runnable {
/**
* The resubmission scheduler to use.
*/
private final ResubmissionScheduler resubmissionScheduler;
/**
* The instrumentation instance to use.
*/
private final Instrumentation instrumentation;
/**
* The location strategy to use.
*/
private final LocationStrategy locationStrategy;
/**
* The listener to use.
*/
private final AgentBuilder.Listener listener;
/**
* The circularity lock to use.
*/
private final CircularityLock circularityLock;
/**
* The matcher to apply for analyzing if a type is to be resubmitted.
*/
private final RawMatcher matcher;
/**
* The redefinition strategy to use.
*/
private final RedefinitionStrategy redefinitionStrategy;
/**
* The batch allocator to use.
*/
private final BatchAllocator redefinitionBatchAllocator;
/**
* The batch listener to notify.
*/
private final Listener redefinitionBatchListener;
/**
* A map of class loaders to their types to resubmit.
*/
private final ConcurrentMap<StorageKey, Set<String>> types;
/**
* This scheduler's cancelable or {@code null} if no cancelable was registered.
*/
private volatile ResubmissionScheduler.Cancelable cancelable;
/**
* Creates a new resubmission job.
*
* @param resubmissionScheduler The resubmission scheduler to use.
* @param instrumentation The instrumentation instance to use.
* @param locationStrategy The location strategy to use.
* @param listener The listener to use.
* @param circularityLock The circularity lock to use.
* @param matcher The matcher to apply for analyzing if a type is to be resubmitted.
* @param redefinitionStrategy The redefinition strategy to use.
* @param redefinitionBatchAllocator The batch allocator to use.
* @param redefinitionBatchListener The batch listener to notify.
* @param types A map of class loaders to their types to resubmit.
*/
protected ResubmissionInstallationListener(ResubmissionScheduler resubmissionScheduler,
Instrumentation instrumentation,
LocationStrategy locationStrategy,
AgentBuilder.Listener listener,
CircularityLock circularityLock,
RawMatcher matcher,
RedefinitionStrategy redefinitionStrategy,
BatchAllocator redefinitionBatchAllocator,
Listener redefinitionBatchListener,
ConcurrentMap<StorageKey, Set<String>> types) {
this.resubmissionScheduler = resubmissionScheduler;
this.instrumentation = instrumentation;
this.locationStrategy = locationStrategy;
this.listener = listener;
this.circularityLock = circularityLock;
this.matcher = matcher;
this.redefinitionStrategy = redefinitionStrategy;
this.redefinitionBatchAllocator = redefinitionBatchAllocator;
this.redefinitionBatchListener = redefinitionBatchListener;
this.types = types;
}
@Override
public void onInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
cancelable = resubmissionScheduler.schedule(this);
}
@Override
public void onReset(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
ResubmissionScheduler.Cancelable cancelable = this.cancelable;
if (cancelable != null) {
cancelable.cancel();
}
}
/**
* {@inheritDoc}
*/
public void run() {
boolean release = circularityLock.acquire();
try {
Iterator<Map.Entry<StorageKey, Set<String>>> entries = types.entrySet().iterator();
List<Class<?>> types = new ArrayList<Class<?>>();
while (entries.hasNext()) {
if (Thread.interrupted()) {
return;
}
Map.Entry<StorageKey, Set<String>> entry = entries.next();
ClassLoader classLoader = entry.getKey().get();
if (classLoader != null || entry.getKey().isBootstrapLoader()) {
Iterator<String> iterator = entry.getValue().iterator();
while (iterator.hasNext()) {
if (Thread.interrupted()) {
return;
}
try {
Class<?> type = Class.forName(iterator.next(), false, classLoader);
try {
if (DISPATCHER.isModifiableClass(instrumentation, type) && matcher.matches(TypeDescription.ForLoadedType.of(type),
type.getClassLoader(),
JavaModule.ofType(type),
type,
type.getProtectionDomain())) {
types.add(type);
}
} catch (Throwable throwable) {
try {
listener.onDiscovery(TypeDescription.ForLoadedType.getName(type),
type.getClassLoader(),
JavaModule.ofType(type),
AgentBuilder.Listener.LOADED);
} finally {
try {
listener.onError(TypeDescription.ForLoadedType.getName(type),
type.getClassLoader(),
JavaModule.ofType(type),
AgentBuilder.Listener.LOADED,
throwable);
} finally {
listener.onComplete(TypeDescription.ForLoadedType.getName(type),
type.getClassLoader(),
JavaModule.ofType(type),
AgentBuilder.Listener.LOADED);
}
}
}
} catch (Throwable ignored) {
/* do nothing */
} finally {
iterator.remove();
}
}
} else {
entries.remove();
}
}
if (!types.isEmpty()) {
RedefinitionStrategy.Collector collector = redefinitionStrategy.make();
collector.include(types);
collector.apply(instrumentation,
circularityLock,
locationStrategy,
listener,
redefinitionBatchAllocator,
redefinitionBatchListener,
BatchAllocator.FIRST_BATCH);
}
} finally {
if (release) {
circularityLock.release();
}
}
}
}
/**
* A key for a class loader that can only be used for looking up a preexisting value but avoids reference management.
*/
protected static class LookupKey {
/**
* The represented class loader.
*/
private final ClassLoader classLoader;
/**
* The represented class loader's hash code or {@code 0} if this entry represents the bootstrap class loader.
*/
private final int hashCode;
/**
* Creates a new lookup key.
*
* @param classLoader The represented class loader.
*/
protected LookupKey(ClassLoader classLoader) {
this.classLoader = classLoader;
hashCode = System.identityHashCode(classLoader);
}
@Override
public int hashCode() {
return hashCode;
}
@Override
@SuppressFBWarnings(value = "EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS", justification = "Cross-comparison is intended")
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof LookupKey) {
return classLoader == ((LookupKey) other).classLoader;
} else if (other instanceof StorageKey) {
StorageKey storageKey = (StorageKey) other;
return hashCode == storageKey.hashCode && classLoader == storageKey.get();
} else {
return false;
}
}
}
/**
* A key for a class loader that only weakly references the class loader.
*/
protected static class StorageKey extends WeakReference<ClassLoader> {
/**
* The represented class loader's hash code or {@code 0} if this entry represents the bootstrap class loader.
*/
private final int hashCode;
/**
* Creates a new storage key.
*
* @param classLoader The represented class loader or {@code null} for the bootstrap class loader.
*/
protected StorageKey(ClassLoader classLoader) {
super(classLoader);
hashCode = System.identityHashCode(classLoader);
}
/**
* Checks if this reference represents the bootstrap class loader.
*
* @return {@code true} if this entry represents the bootstrap class loader.
*/
protected boolean isBootstrapLoader() {
return hashCode == 0;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
@SuppressFBWarnings(value = "EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS", justification = "Cross-comparison is intended")
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof LookupKey) {
LookupKey lookupKey = (LookupKey) other;
return hashCode == lookupKey.hashCode && get() == lookupKey.classLoader;
} else if (other instanceof StorageKey) {
StorageKey storageKey = (StorageKey) other;
return hashCode == storageKey.hashCode && get() == storageKey.get();
} else {
return false;
}
}
}
}
/**
* Represents an installation of a resubmission strategy.
*/
@HashCodeAndEqualsPlugin.Enhance
class Installation {
/**
* The listener to apply.
*/
private final AgentBuilder.Listener listener;
/**
* The installation listener to apply.
*/
private final InstallationListener installationListener;
/**
* Creates a new installation.
*
* @param listener The listener to apply.
* @param installationListener The installation listener to apply.
*/
protected Installation(AgentBuilder.Listener listener, InstallationListener installationListener) {
this.listener = listener;
this.installationListener = installationListener;
}
/**
* Returns the listener to apply.
*
* @return The listener to apply.
*/
protected AgentBuilder.Listener getListener() {
return listener;
}
/**
* Returns the installation listener to apply.
*
* @return The installation listener to apply.
*/
protected InstallationListener getInstallationListener() {
return installationListener;
}
}
}
/**
* A dispatcher for interacting with the instrumentation API.
*/
protected interface Dispatcher {
/**
* Checks if the supplied type is modifiable.
*
* @param instrumentation The instrumentation instance available.
* @param type The type to check for modifiability.
* @return {@code true} if the supplied type is modifiable.
*/
boolean isModifiableClass(Instrumentation instrumentation, Class<?> type);
/**
* Checks if retransformation is supported for the supplied instrumentation instance.
*
* @param instrumentation The instrumentation instance available.
* @return {@code true} if the supplied instance supports retransformation.
*/
boolean isRetransformClassesSupported(Instrumentation instrumentation);
/**
* Retransforms the supplied classes.
*
* @param instrumentation The instrumentation instance to use for retransformation.
* @param type The types to retransform.
* @throws UnmodifiableClassException If the supplied classes cannot be retransformed.
*/
void retransformClasses(Instrumentation instrumentation, Class<?>[] type) throws UnmodifiableClassException;
/**
* An action for creating a dispatcher.
*/
enum CreationAction implements PrivilegedAction<Dispatcher> {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Dispatcher run() {
try {
return new ForJava6CapableVm(Instrumentation.class.getMethod("isModifiableClass", Class.class),
Instrumentation.class.getMethod("isRetransformClassesSupported"),
Instrumentation.class.getMethod("retransformClasses", Class[].class));
} catch (NoSuchMethodException ignored) {
return ForLegacyVm.INSTANCE;
}
}
}
/**
* A dispatcher for a legacy VM.
*/
enum ForLegacyVm implements Dispatcher {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public boolean isModifiableClass(Instrumentation instrumentation, Class<?> type) {
return !type.isArray() && !type.isPrimitive();
}
/**
* {@inheritDoc}
*/
public boolean isRetransformClassesSupported(Instrumentation instrumentation) {
return false;
}
/**
* {@inheritDoc}
*/
public void retransformClasses(Instrumentation instrumentation, Class<?>[] type) {
throw new UnsupportedOperationException("The current VM does not support retransformation");
}
}
/**
* A dispatcher for a Java 6 capable VM.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForJava6CapableVm implements Dispatcher {
/**
* The {@code Instrumentation#isModifiableClass} method.
*/
private final Method isModifiableClass;
/**
* The {@code Instrumentation#isRetransformClassesSupported} method.
*/
private final Method isRetransformClassesSupported;
/**
* The {@code Instrumentation#retransformClasses} method.
*/
private final Method retransformClasses;
/**
* Creates a new Java 6 capable dispatcher.
*
* @param isModifiableClass The {@code Instrumentation#isModifiableClass} method.
* @param isRetransformClassesSupported The {@code Instrumentation#isRetransformClassesSupported} method.
* @param retransformClasses The {@code Instrumentation#retransformClasses} method.
*/
protected ForJava6CapableVm(Method isModifiableClass, Method isRetransformClassesSupported, Method retransformClasses) {
this.isModifiableClass = isModifiableClass;
this.isRetransformClassesSupported = isRetransformClassesSupported;
this.retransformClasses = retransformClasses;
}
/**
* {@inheritDoc}
*/
public boolean isModifiableClass(Instrumentation instrumentation, Class<?> type) {
try {
return (Boolean) isModifiableClass.invoke(instrumentation, type);
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Cannot access java.lang.instrument.Instrumentation#isModifiableClass", exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException("Error invoking java.lang.instrument.Instrumentation#isModifiableClass", exception.getCause());
}
}
/**
* {@inheritDoc}
*/
public boolean isRetransformClassesSupported(Instrumentation instrumentation) {
try {
return (Boolean) isRetransformClassesSupported.invoke(instrumentation);
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Cannot access java.lang.instrument.Instrumentation#isRetransformClassesSupported", exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException("Error invoking java.lang.instrument.Instrumentation#isRetransformClassesSupported", exception.getCause());
}
}
/**
* {@inheritDoc}
*/
public void retransformClasses(Instrumentation instrumentation, Class<?>[] type) throws UnmodifiableClassException {
try {
retransformClasses.invoke(instrumentation, (Object) type);
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Cannot access java.lang.instrument.Instrumentation#retransformClasses", exception);
} catch (InvocationTargetException exception) {
Throwable cause = exception.getCause();
if (cause instanceof UnmodifiableClassException) {
throw (UnmodifiableClassException) cause;
} else {
throw new IllegalStateException("Error invoking java.lang.instrument.Instrumentation#retransformClasses", cause);
}
}
}
}
}
/**
* A collector is responsible for collecting classes that are to be considered for modification.
*/
protected abstract static class Collector {
/**
* A representation for a non-available loaded type.
*/
private static final Class<?> NO_LOADED_TYPE = null;
/**
* All types that were collected for redefinition.
*/
protected final List<Class<?>> types;
/**
* Creates a new collector.
*/
protected Collector() {
types = new ArrayList<Class<?>>();
}
/**
* Does consider the retransformation or redefinition of a loaded type without a loaded type representation.
*
* @param matcher The type matcher to apply.
* @param listener The listener to apply during the consideration.
* @param typeDescription The type description of the type being considered.
* @param type The loaded type being considered.
* @param module The type's Java module or {@code null} if the current VM does not support modules.
*/
protected void consider(RawMatcher matcher,
AgentBuilder.Listener listener,
TypeDescription typeDescription,
Class<?> type,
JavaModule module) {
consider(matcher, listener, typeDescription, type, NO_LOADED_TYPE, module, false);
}
/**
* Does consider the retransformation or redefinition of a loaded type.
*
* @param matcher A type matcher to apply.
* @param listener The listener to apply during the consideration.
* @param typeDescription The type description of the type being considered.
* @param type The loaded type being considered.
* @param classBeingRedefined The loaded type being considered or {@code null} if it should be considered non-available.
* @param module The type's Java module or {@code null} if the current VM does not support modules.
* @param unmodifiable {@code true} if the current type should be considered unmodifiable.
*/
protected void consider(RawMatcher matcher,
AgentBuilder.Listener listener,
TypeDescription typeDescription,
Class<?> type,
Class<?> classBeingRedefined,
JavaModule module,
boolean unmodifiable) {
if (unmodifiable || !matcher.matches(typeDescription, type.getClassLoader(), module, classBeingRedefined, type.getProtectionDomain())) {
try {
try {
listener.onDiscovery(TypeDescription.ForLoadedType.getName(type), type.getClassLoader(), module, classBeingRedefined != null);
listener.onIgnored(typeDescription, type.getClassLoader(), module, classBeingRedefined != null);
} catch (Throwable throwable) {
listener.onError(TypeDescription.ForLoadedType.getName(type), type.getClassLoader(), module, classBeingRedefined != null, throwable);
} finally {
listener.onComplete(TypeDescription.ForLoadedType.getName(type), type.getClassLoader(), module, classBeingRedefined != null);
}
} catch (Throwable ignored) {
// Ignore exceptions that are thrown by listeners to mimic the behavior of a transformation.
}
} else {
types.add(type);
}
}
/**
* Includes all the supplied types in this collector.
*
* @param types The types to include.
*/
protected void include(List<Class<?>> types) {
this.types.addAll(types);
}
/**
* Applies all types that this collector collected.
*
* @param instrumentation The instrumentation instance to apply changes to.
* @param circularityLock The circularity lock to use.
* @param locationStrategy The location strategy to use.
* @param listener The listener to use.
* @param redefinitionBatchAllocator The redefinition batch allocator to use.
* @param redefinitionListener The redefinition listener to use.
* @param batch The next batch's index.
* @return The next batch's index after this application.
*/
protected int apply(Instrumentation instrumentation,
CircularityLock circularityLock,
LocationStrategy locationStrategy,
AgentBuilder.Listener listener,
BatchAllocator redefinitionBatchAllocator,
Listener redefinitionListener,
int batch) {
Map<List<Class<?>>, Throwable> failures = new HashMap<List<Class<?>>, Throwable>();
PrependableIterator prepanedableIterator = new PrependableIterator(redefinitionBatchAllocator.batch(this.types));
while (prepanedableIterator.hasNext()) {
List<Class<?>> types = prepanedableIterator.next();
redefinitionListener.onBatch(batch, types, this.types);
try {
doApply(instrumentation, circularityLock, types, locationStrategy, listener);
} catch (Throwable throwable) {
prepanedableIterator.prepend(redefinitionListener.onError(batch, types, throwable, this.types));
failures.put(types, throwable);
}
batch += 1;
}
redefinitionListener.onComplete(batch, types, failures);
return batch;
}
/**
* Applies this collector.
*
* @param instrumentation The instrumentation instance to apply the transformation for.
* @param circularityLock The circularity lock to use.
* @param types The types of the current patch to transform.
* @param locationStrategy The location strategy to use.
* @param listener the listener to notify.
* @throws UnmodifiableClassException If a class is not modifiable.
* @throws ClassNotFoundException If a class could not be found.
*/
protected abstract void doApply(Instrumentation instrumentation,
CircularityLock circularityLock,
List<Class<?>> types,
LocationStrategy locationStrategy,
AgentBuilder.Listener listener) throws UnmodifiableClassException, ClassNotFoundException;
/**
* An iterator that allows prepending of iterables to be applied previous to another iterator.
*/
protected static class PrependableIterator implements Iterator<List<Class<?>>> {
/**
* The current iterator.
*/
private Iterator<? extends List<Class<?>>> current;
/**
* The backlog of iterators to apply.
*/
private final LinkedList<Iterator<? extends List<Class<?>>>> backlog;
/**
* Creates a new prependable iterator.
*
* @param origin The original iterable to begin with.
*/
protected PrependableIterator(Iterable<? extends List<Class<?>>> origin) {
current = origin.iterator();
backlog = new LinkedList<Iterator<? extends List<Class<?>>>>();
}
/**
* Prepends an iterable to the backlog.
*
* @param iterable The iterable to prepend.
*/
public void prepend(Iterable<? extends List<Class<?>>> iterable) {
Iterator<? extends List<Class<?>>> iterator = iterable.iterator();
if (iterator.hasNext()) {
if (current.hasNext()) {
backlog.addLast(current);
}
current = iterator;
}
}
/**
* {@inheritDoc}
*/
public boolean hasNext() {
return current.hasNext();
}
/**
* {@inheritDoc}
*/
public List<Class<?>> next() {
try {
return current.next();
} finally {
while (!current.hasNext() && !backlog.isEmpty()) {
current = backlog.removeLast();
}
}
}
/**
* {@inheritDoc}
*/
public void remove() {
throw new UnsupportedOperationException("remove");
}
}
/**
* A collector that applies a <b>redefinition</b> of already loaded classes.
*/
protected static class ForRedefinition extends Collector {
@Override
protected void doApply(Instrumentation instrumentation,
CircularityLock circularityLock,
List<Class<?>> types,
LocationStrategy locationStrategy,
AgentBuilder.Listener listener) throws UnmodifiableClassException, ClassNotFoundException {
List<ClassDefinition> classDefinitions = new ArrayList<ClassDefinition>(types.size());
for (Class<?> type : types) {
try {
try {
classDefinitions.add(new ClassDefinition(type, locationStrategy.classFileLocator(type.getClassLoader(), JavaModule.ofType(type))
.locate(TypeDescription.ForLoadedType.getName(type))
.resolve()));
} catch (Throwable throwable) {
JavaModule module = JavaModule.ofType(type);
try {
listener.onDiscovery(TypeDescription.ForLoadedType.getName(type), type.getClassLoader(), module, AgentBuilder.Listener.LOADED);
} finally {
try {
listener.onError(TypeDescription.ForLoadedType.getName(type), type.getClassLoader(), module, AgentBuilder.Listener.LOADED, throwable);
} finally {
listener.onComplete(TypeDescription.ForLoadedType.getName(type), type.getClassLoader(), module, AgentBuilder.Listener.LOADED);
}
}
}
} catch (Throwable ignored) {
// Ignore exceptions that are thrown by listeners to mimic the behavior of a transformation.
}
}
if (!classDefinitions.isEmpty()) {
circularityLock.release();
try {
instrumentation.redefineClasses(classDefinitions.toArray(new ClassDefinition[0]));
} finally {
circularityLock.acquire();
}
}
}
}
/**
* A collector that applies a <b>retransformation</b> of already loaded classes.
*/
protected static class ForRetransformation extends Collector {
@Override
protected void doApply(Instrumentation instrumentation,
CircularityLock circularityLock,
List<Class<?>> types,
LocationStrategy locationStrategy,
AgentBuilder.Listener listener) throws UnmodifiableClassException {
if (!types.isEmpty()) {
circularityLock.release();
try {
DISPATCHER.retransformClasses(instrumentation, types.toArray(new Class<?>[0]));
} finally {
circularityLock.acquire();
}
}
}
}
}
}
/**
* Implements the instrumentation of the {@code LambdaMetafactory} if this feature is enabled.
*/
enum LambdaInstrumentationStrategy {
/**
* A strategy that enables instrumentation of the {@code LambdaMetafactory} if such a factory exists on the current VM.
* Classes representing lambda expressions that are created by Byte Buddy are fully compatible to those created by
* the JVM and can be serialized or deserialized to one another. The classes do however show a few differences:
* <ul>
* <li>Byte Buddy's classes are public with a public executing transformer. Doing so, it is not necessary to instantiate a
* non-capturing lambda expression by reflection. This is done because Byte Buddy is not necessarily capable
* of using reflection due to an active security manager.</li>
* <li>Byte Buddy's classes are not marked as synthetic as an agent builder does not instrument synthetic classes
* by default.</li>
* </ul>
*/
ENABLED {
@Override
protected void apply(ByteBuddy byteBuddy,
Instrumentation instrumentation,
ClassFileTransformer classFileTransformer) {
if (LambdaFactory.register(classFileTransformer, new LambdaInstanceFactory(byteBuddy))) {
Class<?> lambdaMetaFactory;
try {
lambdaMetaFactory = Class.forName("java.lang.invoke.LambdaMetafactory");
} catch (ClassNotFoundException ignored) {
return;
}
byteBuddy.with(Implementation.Context.Disabled.Factory.INSTANCE)
.redefine(lambdaMetaFactory)
.visit(new AsmVisitorWrapper.ForDeclaredMethods()
.method(named("metafactory"), MetaFactoryRedirection.INSTANCE)
.method(named("altMetafactory"), AlternativeMetaFactoryRedirection.INSTANCE))
.make()
.load(lambdaMetaFactory.getClassLoader(), ClassReloadingStrategy.of(instrumentation));
}
}
@Override
protected boolean isInstrumented(Class<?> type) {
return true;
}
},
/**
* A strategy that does not instrument the {@code LambdaMetafactory}.
*/
DISABLED {
@Override
protected void apply(ByteBuddy byteBuddy,
Instrumentation instrumentation,
ClassFileTransformer classFileTransformer) {
/* do nothing */
}
@Override
protected boolean isInstrumented(Class<?> type) {
return type == null || !type.getName().contains("/");
}
};
/**
* The name of the current VM's {@code Unsafe} class that is visible to the bootstrap loader.
*/
private static final String UNSAFE_CLASS = ClassFileVersion.ofThisVm(ClassFileVersion.JAVA_V6).isAtLeast(ClassFileVersion.JAVA_V9)
? "jdk/internal/misc/Unsafe"
: "sun/misc/Unsafe";
/**
* Indicates that an original implementation can be ignored when redefining a method.
*/
protected static final MethodVisitor IGNORE_ORIGINAL = null;
/**
* Releases the supplied class file transformer when it was built with {@link AgentBuilder#with(LambdaInstrumentationStrategy)} enabled.
* Subsequently, the class file transformer is no longer applied when a class that represents a lambda expression is created.
*
* @param classFileTransformer The class file transformer to release.
* @param instrumentation The instrumentation instance that is used to potentially rollback the instrumentation of the {@code LambdaMetafactory}.
*/
public static void release(ClassFileTransformer classFileTransformer, Instrumentation instrumentation) {
if (LambdaFactory.release(classFileTransformer)) {
try {
ClassReloadingStrategy.of(instrumentation).reset(Class.forName("java.lang.invoke.LambdaMetafactory"));
} catch (Exception exception) {
throw new IllegalStateException("Could not release lambda transformer", exception);
}
}
}
/**
* Returns an enabled lambda instrumentation strategy for {@code true}.
*
* @param enabled If lambda instrumentation should be enabled.
* @return {@code true} if the returned strategy should be enabled.
*/
public static LambdaInstrumentationStrategy of(boolean enabled) {
return enabled
? ENABLED
: DISABLED;
}
/**
* Applies a transformation to lambda instances if applicable.
*
* @param byteBuddy The Byte Buddy instance to use.
* @param instrumentation The instrumentation instance for applying a redefinition.
* @param classFileTransformer The class file transformer to apply.
*/
protected abstract void apply(ByteBuddy byteBuddy, Instrumentation instrumentation, ClassFileTransformer classFileTransformer);
/**
* Indicates if this strategy enables instrumentation of the {@code LambdaMetafactory}.
*
* @return {@code true} if this strategy is enabled.
*/
public boolean isEnabled() {
return this == ENABLED;
}
/**
* Validates if the supplied class is instrumented. For lambda types (which are loaded by anonymous class loader), this method
* should return false if lambda instrumentation is disabled.
*
* @param type The redefined type or {@code null} if no such type exists.
* @return {@code true} if the supplied type should be instrumented according to this strategy.
*/
protected abstract boolean isInstrumented(Class<?> type);
/**
* A factory that creates instances that represent lambda expressions.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class LambdaInstanceFactory {
/**
* The name of a factory for a lambda expression.
*/
private static final String LAMBDA_FACTORY = "get$Lambda";
/**
* A prefix for a field that represents a property of a lambda expression.
*/
private static final String FIELD_PREFIX = "arg$";
/**
* The infix to use for naming classes that represent lambda expression. The additional prefix
* is necessary because the subsequent counter is not sufficient to keep names unique compared
* to the original factory.
*/
private static final String LAMBDA_TYPE_INFIX = "$$Lambda$ByteBuddy$";
/**
* A type-safe constant to express that a class is not already loaded when applying a class file transformer.
*/
private static final Class<?> NOT_PREVIOUSLY_DEFINED = null;
/**
* A counter for naming lambda expressions randomly.
*/
private static final AtomicInteger LAMBDA_NAME_COUNTER = new AtomicInteger();
/**
* The Byte Buddy instance to use for creating lambda objects.
*/
private final ByteBuddy byteBuddy;
/**
* Creates a new lambda instance factory.
*
* @param byteBuddy The Byte Buddy instance to use for creating lambda objects.
*/
protected LambdaInstanceFactory(ByteBuddy byteBuddy) {
this.byteBuddy = byteBuddy;
}
/**
* Applies this lambda meta factory.
*
* @param targetTypeLookup A lookup context representing the creating class of this lambda expression.
* @param lambdaMethodName The name of the lambda expression's represented method.
* @param factoryMethodType The type of the lambda expression's represented method.
* @param lambdaMethodType The type of the lambda expression's factory method.
* @param targetMethodHandle A handle representing the target of the lambda expression's method.
* @param specializedLambdaMethodType A specialization of the type of the lambda expression's represented method.
* @param serializable {@code true} if the lambda expression should be serializable.
* @param markerInterfaces A list of interfaces for the lambda expression to represent.
* @param additionalBridges A list of additional bridge methods to be implemented by the lambda expression.
* @param classFileTransformers A collection of class file transformers to apply when creating the class.
* @return A binary representation of the transformed class file.
*/
public byte[] make(Object targetTypeLookup,
String lambdaMethodName,
Object factoryMethodType,
Object lambdaMethodType,
Object targetMethodHandle,
Object specializedLambdaMethodType,
boolean serializable,
List<Class<?>> markerInterfaces,
List<?> additionalBridges,
Collection<? extends ClassFileTransformer> classFileTransformers) {
JavaConstant.MethodType factoryMethod = JavaConstant.MethodType.ofLoaded(factoryMethodType);
JavaConstant.MethodType lambdaMethod = JavaConstant.MethodType.ofLoaded(lambdaMethodType);
JavaConstant.MethodHandle targetMethod = JavaConstant.MethodHandle.ofLoaded(targetMethodHandle, targetTypeLookup);
JavaConstant.MethodType specializedLambdaMethod = JavaConstant.MethodType.ofLoaded(specializedLambdaMethodType);
Class<?> targetType = JavaConstant.MethodHandle.lookupType(targetTypeLookup);
String lambdaClassName = targetType.getName() + LAMBDA_TYPE_INFIX + LAMBDA_NAME_COUNTER.incrementAndGet();
DynamicType.Builder<?> builder = byteBuddy
.subclass(factoryMethod.getReturnType(), ConstructorStrategy.Default.NO_CONSTRUCTORS)
.modifiers(TypeManifestation.FINAL, Visibility.PUBLIC)
.implement(markerInterfaces)
.name(lambdaClassName)
.defineConstructor(Visibility.PUBLIC)
.withParameters(factoryMethod.getParameterTypes())
.intercept(ConstructorImplementation.INSTANCE)
.method(named(lambdaMethodName)
.and(takesArguments(lambdaMethod.getParameterTypes()))
.and(returns(lambdaMethod.getReturnType())))
.intercept(new LambdaMethodImplementation(targetMethod, specializedLambdaMethod));
int index = 0;
for (TypeDescription capturedType : factoryMethod.getParameterTypes()) {
builder = builder.defineField(FIELD_PREFIX + ++index, capturedType, Visibility.PRIVATE, FieldManifestation.FINAL);
}
if (!factoryMethod.getParameterTypes().isEmpty()) {
builder = builder.defineMethod(LAMBDA_FACTORY, factoryMethod.getReturnType(), Visibility.PRIVATE, Ownership.STATIC)
.withParameters(factoryMethod.getParameterTypes())
.intercept(FactoryImplementation.INSTANCE);
}
if (serializable) {
if (!markerInterfaces.contains(Serializable.class)) {
builder = builder.implement(Serializable.class);
}
builder = builder.defineMethod("writeReplace", Object.class, Visibility.PRIVATE)
.intercept(new SerializationImplementation(TypeDescription.ForLoadedType.of(targetType),
factoryMethod.getReturnType(),
lambdaMethodName,
lambdaMethod,
targetMethod,
JavaConstant.MethodType.ofLoaded(specializedLambdaMethodType)));
} else if (factoryMethod.getReturnType().isAssignableTo(Serializable.class)) {
builder = builder.defineMethod("readObject", void.class, Visibility.PRIVATE)
.withParameters(ObjectInputStream.class)
.throwing(NotSerializableException.class)
.intercept(ExceptionMethod.throwing(NotSerializableException.class, "Non-serializable lambda"))
.defineMethod("writeObject", void.class, Visibility.PRIVATE)
.withParameters(ObjectOutputStream.class)
.throwing(NotSerializableException.class)
.intercept(ExceptionMethod.throwing(NotSerializableException.class, "Non-serializable lambda"));
}
for (Object additionalBridgeType : additionalBridges) {
JavaConstant.MethodType additionalBridge = JavaConstant.MethodType.ofLoaded(additionalBridgeType);
builder = builder.defineMethod(lambdaMethodName, additionalBridge.getReturnType(), MethodManifestation.BRIDGE, Visibility.PUBLIC)
.withParameters(additionalBridge.getParameterTypes())
.intercept(new BridgeMethodImplementation(lambdaMethodName, lambdaMethod));
}
byte[] classFile = builder.make().getBytes();
for (ClassFileTransformer classFileTransformer : classFileTransformers) {
try {
byte[] transformedClassFile = classFileTransformer.transform(targetType.getClassLoader(),
lambdaClassName.replace('.', '/'),
NOT_PREVIOUSLY_DEFINED,
targetType.getProtectionDomain(),
classFile);
classFile = transformedClassFile == null
? classFile
: transformedClassFile;
} catch (Throwable ignored) {
/* do nothing */
}
}
return classFile;
}
/**
* Implements a lambda class's executing transformer.
*/
@SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "An enumeration does not serialize fields")
protected enum ConstructorImplementation implements Implementation {
/**
* The singleton instance.
*/
INSTANCE;
/**
* A reference to the {@link Object} class's default executing transformer.
*/
private final MethodDescription.InDefinedShape objectConstructor;
/**
* Creates a new executing transformer implementation.
*/
ConstructorImplementation() {
objectConstructor = TypeDescription.OBJECT.getDeclaredMethods().filter(isConstructor()).getOnly();
}
/**
* {@inheritDoc}
*/
public ByteCodeAppender appender(Target implementationTarget) {
return new Appender(implementationTarget.getInstrumentedType().getDeclaredFields());
}
/**
* {@inheritDoc}
*/
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
/**
* An appender to implement the executing transformer.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class Appender implements ByteCodeAppender {
/**
* The fields that are declared by the instrumented type.
*/
private final List<FieldDescription.InDefinedShape> declaredFields;
/**
* Creates a new appender.
*
* @param declaredFields The fields that are declared by the instrumented type.
*/
protected Appender(List<FieldDescription.InDefinedShape> declaredFields) {
this.declaredFields = declaredFields;
}
/**
* {@inheritDoc}
*/
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
List<StackManipulation> fieldAssignments = new ArrayList<StackManipulation>(declaredFields.size() * 3);
for (ParameterDescription parameterDescription : instrumentedMethod.getParameters()) {
fieldAssignments.add(MethodVariableAccess.loadThis());
fieldAssignments.add(MethodVariableAccess.load(parameterDescription));
fieldAssignments.add(FieldAccess.forField(declaredFields.get(parameterDescription.getIndex())).write());
}
return new Size(new StackManipulation.Compound(
MethodVariableAccess.loadThis(),
MethodInvocation.invoke(INSTANCE.objectConstructor),
new StackManipulation.Compound(fieldAssignments),
MethodReturn.VOID
).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
}
}
/**
* An implementation of a instance factory for a lambda expression's class.
*/
protected enum FactoryImplementation implements Implementation {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public ByteCodeAppender appender(Target implementationTarget) {
return new Appender(implementationTarget.getInstrumentedType());
}
/**
* {@inheritDoc}
*/
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
/**
* An appender for a lambda expression factory.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class Appender implements ByteCodeAppender {
/**
* The instrumented type.
*/
private final TypeDescription instrumentedType;
/**
* Creates a new appender.
*
* @param instrumentedType The instrumented type.
*/
protected Appender(TypeDescription instrumentedType) {
this.instrumentedType = instrumentedType;
}
/**
* {@inheritDoc}
*/
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
return new Size(new StackManipulation.Compound(
TypeCreation.of(instrumentedType),
Duplication.SINGLE,
MethodVariableAccess.allArgumentsOf(instrumentedMethod),
MethodInvocation.invoke(instrumentedType.getDeclaredMethods().filter(isConstructor()).getOnly()),
MethodReturn.REFERENCE
).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
}
}
/**
* Implements a lambda expression's functional method.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class LambdaMethodImplementation implements Implementation {
/**
* The handle of the target method of the lambda expression.
*/
private final JavaConstant.MethodHandle targetMethod;
/**
* The specialized type of the lambda method.
*/
private final JavaConstant.MethodType specializedLambdaMethod;
/**
* Creates a implementation of a lambda expression's functional method.
*
* @param targetMethod The target method of the lambda expression.
* @param specializedLambdaMethod The specialized type of the lambda method.
*/
protected LambdaMethodImplementation(JavaConstant.MethodHandle targetMethod, JavaConstant.MethodType specializedLambdaMethod) {
this.targetMethod = targetMethod;
this.specializedLambdaMethod = specializedLambdaMethod;
}
/**
* {@inheritDoc}
*/
public ByteCodeAppender appender(Target implementationTarget) {
return new Appender(targetMethod.getOwnerType()
.getDeclaredMethods()
.filter(hasMethodName(targetMethod.getName())
.and(returns(targetMethod.getReturnType()))
.and(takesArguments(targetMethod.getParameterTypes())))
.getOnly(),
specializedLambdaMethod,
implementationTarget.getInstrumentedType().getDeclaredFields());
}
/**
* {@inheritDoc}
*/
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
/**
* An appender for a lambda expression's functional method.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class Appender implements ByteCodeAppender {
/**
* The target method of the lambda expression.
*/
private final MethodDescription targetMethod;
/**
* The specialized type of the lambda method.
*/
private final JavaConstant.MethodType specializedLambdaMethod;
/**
* The instrumented type's declared fields.
*/
private final List<FieldDescription.InDefinedShape> declaredFields;
/**
* Creates an appender of a lambda expression's functional method.
*
* @param targetMethod The target method of the lambda expression.
* @param specializedLambdaMethod The specialized type of the lambda method.
* @param declaredFields The instrumented type's declared fields.
*/
protected Appender(MethodDescription targetMethod,
JavaConstant.MethodType specializedLambdaMethod,
List<FieldDescription.InDefinedShape> declaredFields) {
this.targetMethod = targetMethod;
this.specializedLambdaMethod = specializedLambdaMethod;
this.declaredFields = declaredFields;
}
/**
* {@inheritDoc}
*/
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
StackManipulation preparation = targetMethod.isConstructor()
? new StackManipulation.Compound(TypeCreation.of(targetMethod.getDeclaringType().asErasure()), Duplication.SINGLE)
: StackManipulation.Trivial.INSTANCE;
List<StackManipulation> fieldAccess = new ArrayList<StackManipulation>(declaredFields.size() * 2 + 1);
for (FieldDescription.InDefinedShape fieldDescription : declaredFields) {
fieldAccess.add(MethodVariableAccess.loadThis());
fieldAccess.add(FieldAccess.forField(fieldDescription).read());
}
List<StackManipulation> parameterAccess = new ArrayList<StackManipulation>(instrumentedMethod.getParameters().size() * 2);
for (ParameterDescription parameterDescription : instrumentedMethod.getParameters()) {
parameterAccess.add(MethodVariableAccess.load(parameterDescription));
parameterAccess.add(Assigner.DEFAULT.assign(parameterDescription.getType(),
specializedLambdaMethod.getParameterTypes().get(parameterDescription.getIndex()).asGenericType(),
Assigner.Typing.DYNAMIC));
}
return new Size(new StackManipulation.Compound(
preparation,
new StackManipulation.Compound(fieldAccess),
new StackManipulation.Compound(parameterAccess),
MethodInvocation.invoke(targetMethod),
Assigner.DEFAULT.assign(targetMethod.isConstructor()
? targetMethod.getDeclaringType().asGenericType()
: targetMethod.getReturnType(),
specializedLambdaMethod.getReturnType().asGenericType(),
Assigner.Typing.DYNAMIC),
MethodReturn.of(specializedLambdaMethod.getReturnType())
).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
}
}
/**
* Implements the {@code writeReplace} method for serializable lambda expressions.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class SerializationImplementation implements Implementation {
/**
* The lambda expression's declaring type.
*/
private final TypeDescription targetType;
/**
* The lambda expression's functional type.
*/
private final TypeDescription lambdaType;
/**
* The lambda expression's functional method name.
*/
private final String lambdaMethodName;
/**
* The method type of the lambda expression's functional method.
*/
private final JavaConstant.MethodType lambdaMethod;
/**
* A handle that references the lambda expressions invocation target.
*/
private final JavaConstant.MethodHandle targetMethod;
/**
* The specialized method type of the lambda expression's functional method.
*/
private final JavaConstant.MethodType specializedMethod;
/**
* Creates a new implementation for a serializable's lambda expression's {@code writeReplace} method.
*
* @param targetType The lambda expression's declaring type.
* @param lambdaType The lambda expression's functional type.
* @param lambdaMethodName The lambda expression's functional method name.
* @param lambdaMethod The method type of the lambda expression's functional method.
* @param targetMethod A handle that references the lambda expressions invocation target.
* @param specializedMethod The specialized method type of the lambda expression's functional method.
*/
protected SerializationImplementation(TypeDescription targetType,
TypeDescription lambdaType,
String lambdaMethodName,
JavaConstant.MethodType lambdaMethod,
JavaConstant.MethodHandle targetMethod,
JavaConstant.MethodType specializedMethod) {
this.targetType = targetType;
this.lambdaType = lambdaType;
this.lambdaMethodName = lambdaMethodName;
this.lambdaMethod = lambdaMethod;
this.targetMethod = targetMethod;
this.specializedMethod = specializedMethod;
}
/**
* {@inheritDoc}
*/
public ByteCodeAppender appender(Target implementationTarget) {
TypeDescription serializedLambda;
try {
serializedLambda = TypeDescription.ForLoadedType.of(Class.forName("java.lang.invoke.SerializedLambda"));
} catch (ClassNotFoundException exception) {
throw new IllegalStateException("Cannot find class for lambda serialization", exception);
}
List<StackManipulation> lambdaArguments = new ArrayList<StackManipulation>(implementationTarget.getInstrumentedType().getDeclaredFields().size());
for (FieldDescription.InDefinedShape fieldDescription : implementationTarget.getInstrumentedType().getDeclaredFields()) {
lambdaArguments.add(new StackManipulation.Compound(MethodVariableAccess.loadThis(),
FieldAccess.forField(fieldDescription).read(),
Assigner.DEFAULT.assign(fieldDescription.getType(), TypeDescription.Generic.OBJECT, Assigner.Typing.STATIC)));
}
return new ByteCodeAppender.Simple(new StackManipulation.Compound(
TypeCreation.of(serializedLambda),
Duplication.SINGLE,
ClassConstant.of(targetType),
new TextConstant(lambdaType.getInternalName()),
new TextConstant(lambdaMethodName),
new TextConstant(lambdaMethod.getDescriptor()),
IntegerConstant.forValue(targetMethod.getHandleType().getIdentifier()),
new TextConstant(targetMethod.getOwnerType().getInternalName()),
new TextConstant(targetMethod.getName()),
new TextConstant(targetMethod.getDescriptor()),
new TextConstant(specializedMethod.getDescriptor()),
ArrayFactory.forType(TypeDescription.Generic.OBJECT).withValues(lambdaArguments),
MethodInvocation.invoke(serializedLambda.getDeclaredMethods().filter(isConstructor()).getOnly()),
MethodReturn.REFERENCE
));
}
/**
* {@inheritDoc}
*/
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
}
/**
* Implements an explicit bridge method for a lambda expression.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class BridgeMethodImplementation implements Implementation {
/**
* The name of the lambda expression's functional method.
*/
private final String lambdaMethodName;
/**
* The actual type of the lambda expression's functional method.
*/
private final JavaConstant.MethodType lambdaMethod;
/**
* Creates a new bridge method implementation for a lambda expression.
*
* @param lambdaMethodName The name of the lambda expression's functional method.
* @param lambdaMethod The actual type of the lambda expression's functional method.
*/
protected BridgeMethodImplementation(String lambdaMethodName, JavaConstant.MethodType lambdaMethod) {
this.lambdaMethodName = lambdaMethodName;
this.lambdaMethod = lambdaMethod;
}
/**
* {@inheritDoc}
*/
public ByteCodeAppender appender(Target implementationTarget) {
return new Appender(implementationTarget.invokeSuper(new MethodDescription.SignatureToken(lambdaMethodName,
lambdaMethod.getReturnType(),
lambdaMethod.getParameterTypes())));
}
/**
* {@inheritDoc}
*/
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
/**
* An appender for implementing a bridge method for a lambda expression.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class Appender implements ByteCodeAppender {
/**
* The invocation of the bridge's target method.
*/
private final SpecialMethodInvocation bridgeTargetInvocation;
/**
* Creates a new appender for invoking a lambda expression's bridge method target.
*
* @param bridgeTargetInvocation The invocation of the bridge's target method.
*/
protected Appender(SpecialMethodInvocation bridgeTargetInvocation) {
this.bridgeTargetInvocation = bridgeTargetInvocation;
}
/**
* {@inheritDoc}
*/
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
return new Compound(new Simple(
MethodVariableAccess.allArgumentsOf(instrumentedMethod)
.asBridgeOf(bridgeTargetInvocation.getMethodDescription())
.prependThisReference(),
bridgeTargetInvocation,
bridgeTargetInvocation.getMethodDescription().getReturnType().asErasure().isAssignableTo(instrumentedMethod.getReturnType().asErasure())
? StackManipulation.Trivial.INSTANCE
: TypeCasting.to(instrumentedMethod.getReceiverType()),
MethodReturn.of(instrumentedMethod.getReturnType())
)).apply(methodVisitor, implementationContext, instrumentedMethod);
}
}
}
}
/**
* Implements the regular lambda meta factory. The implementation represents the following code:
* <blockquote><pre>
* public static CallSite metafactory(MethodHandles.Lookup caller,
* String invokedName,
* MethodType invokedType,
* MethodType samMethodType,
* MethodHandle implMethod,
* MethodType instantiatedMethodType) throws Exception {
* Unsafe unsafe = Unsafe.getUnsafe();
* {@code Class<?>} lambdaClass = unsafe.defineAnonymousClass(caller.lookupClass(),
* (byte[]) ClassLoader.getSystemClassLoader().loadClass("net.bytebuddy.agent.builder.LambdaFactory").getDeclaredMethod("make",
* Object.class,
* String.class,
* Object.class,
* Object.class,
* Object.class,
* Object.class,
* boolean.class,
* List.class,
* List.class).invoke(null,
* caller,
* invokedName,
* invokedType,
* samMethodType,
* implMethod,
* instantiatedMethodType,
* false,
* Collections.emptyList(),
* Collections.emptyList()),
* null);
* unsafe.ensureClassInitialized(lambdaClass);
* return invokedType.parameterCount() == 0
* ? new ConstantCallSite(MethodHandles.constant(invokedType.returnType(), lambdaClass.getDeclaredConstructors()[0].newInstance()))
* : new ConstantCallSite(MethodHandles.Lookup.IMPL_LOOKUP.findStatic(lambdaClass, "get$Lambda", invokedType));
* </pre></blockquote>
*/
protected enum MetaFactoryRedirection implements AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public MethodVisitor wrap(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
TypePool typePool,
int writerFlags,
int readerFlags) {
methodVisitor.visitCode();
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, UNSAFE_CLASS, "getUnsafe", "()L" + UNSAFE_CLASS + ";", false);
methodVisitor.visitVarInsn(Opcodes.ASTORE, 6);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 6);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "lookupClass", "()Ljava/lang/Class;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/ClassLoader", "getSystemClassLoader", "()Ljava/lang/ClassLoader;", false);
methodVisitor.visitLdcInsn("net.bytebuddy.agent.builder.LambdaFactory");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/ClassLoader", "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;", false);
methodVisitor.visitLdcInsn("make");
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 9);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/String;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_3);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_5);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 6);
methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Boolean", "TYPE", "Ljava/lang/Class;");
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 7);
methodVisitor.visitLdcInsn(Type.getType("Ljava/util/List;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 8);
methodVisitor.visitLdcInsn(Type.getType("Ljava/util/List;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredMethod", "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;", false);
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 9);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_3);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 4);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_5);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 5);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 6);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 7);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Collections", "emptyList", "()Ljava/util/List;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 8);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Collections", "emptyList", "()Ljava/util/List;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Method", "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", false);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "[B");
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, UNSAFE_CLASS, "defineAnonymousClass", "(Ljava/lang/Class;[B[Ljava/lang/Object;)Ljava/lang/Class;", false);
methodVisitor.visitVarInsn(Opcodes.ASTORE, 7);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 6);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 7);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, UNSAFE_CLASS, "ensureClassInitialized", "(Ljava/lang/Class;)V", false);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodType", "parameterCount", "()I", false);
Label conditionalDefault = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFNE, conditionalDefault);
methodVisitor.visitTypeInsn(Opcodes.NEW, "java/lang/invoke/ConstantCallSite");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodType", "returnType", "()Ljava/lang/Class;", false);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 7);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredConstructors", "()[Ljava/lang/reflect/Constructor;", false);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Constructor", "newInstance", "([Ljava/lang/Object;)Ljava/lang/Object;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/invoke/MethodHandles", "constant", "(Ljava/lang/Class;Ljava/lang/Object;)Ljava/lang/invoke/MethodHandle;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/invoke/ConstantCallSite", "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false);
Label conditionalAlternative = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, conditionalAlternative);
methodVisitor.visitLabel(conditionalDefault);
methodVisitor.visitFrame(Opcodes.F_APPEND, 2, new Object[]{UNSAFE_CLASS, "java/lang/Class"}, 0, null);
methodVisitor.visitTypeInsn(Opcodes.NEW, "java/lang/invoke/ConstantCallSite");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/invoke/MethodHandles$Lookup", "IMPL_LOOKUP", "Ljava/lang/invoke/MethodHandles$Lookup;");
methodVisitor.visitVarInsn(Opcodes.ALOAD, 7);
methodVisitor.visitLdcInsn("get$Lambda");
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "findStatic", "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/MethodHandle;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/invoke/ConstantCallSite", "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false);
methodVisitor.visitLabel(conditionalAlternative);
methodVisitor.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[]{"java/lang/invoke/CallSite"});
methodVisitor.visitInsn(Opcodes.ARETURN);
methodVisitor.visitMaxs(8, 8);
methodVisitor.visitEnd();
return IGNORE_ORIGINAL;
}
}
/**
* Implements the alternative lambda meta factory. The implementation represents the following code:
* <blockquote><pre>
* public static CallSite altMetafactory(MethodHandles.Lookup caller,
* String invokedName,
* MethodType invokedType,
* Object... args) throws Exception {
* int flags = (Integer) args[3];
* int argIndex = 4;
* {@code Class<?>[]} markerInterface;
* if ((flags {@code &} FLAG_MARKERS) != 0) {
* int markerCount = (Integer) args[argIndex++];
* markerInterface = new {@code Class<?>}[markerCount];
* System.arraycopy(args, argIndex, markerInterface, 0, markerCount);
* argIndex += markerCount;
* } else {
* markerInterface = new {@code Class<?>}[0];
* }
* MethodType[] additionalBridge;
* if ((flags {@code &} FLAG_BRIDGES) != 0) {
* int bridgeCount = (Integer) args[argIndex++];
* additionalBridge = new MethodType[bridgeCount];
* System.arraycopy(args, argIndex, additionalBridge, 0, bridgeCount);
* // argIndex += bridgeCount;
* } else {
* additionalBridge = new MethodType[0];
* }
* Unsafe unsafe = Unsafe.getUnsafe();
* {@code Class<?>} lambdaClass = unsafe.defineAnonymousClass(caller.lookupClass(),
* (byte[]) ClassLoader.getSystemClassLoader().loadClass("net.bytebuddy.agent.builder.LambdaFactory").getDeclaredMethod("make",
* Object.class,
* String.class,
* Object.class,
* Object.class,
* Object.class,
* Object.class,
* boolean.class,
* List.class,
* List.class).invoke(null,
* caller,
* invokedName,
* invokedType,
* args[0],
* args[1],
* args[2],
* (flags {@code &} FLAG_SERIALIZABLE) != 0,
* Arrays.asList(markerInterface),
* Arrays.asList(additionalBridge)),
* null);
* unsafe.ensureClassInitialized(lambdaClass);
* return invokedType.parameterCount() == 0
* ? new ConstantCallSite(MethodHandles.constant(invokedType.returnType(), lambdaClass.getDeclaredConstructors()[0].newInstance()))
* : new ConstantCallSite(MethodHandles.Lookup.IMPL_LOOKUP.findStatic(lambdaClass, "get$Lambda", invokedType));
* }
* </pre></blockquote>
*/
protected enum AlternativeMetaFactoryRedirection implements AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public MethodVisitor wrap(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
TypePool typePool,
int writerFlags,
int readerFlags) {
methodVisitor.visitCode();
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitInsn(Opcodes.ICONST_3);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Integer");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 4);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 5);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 4);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitInsn(Opcodes.IAND);
Label markerInterfaceLoop = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFEQ, markerInterfaceLoop);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 5);
methodVisitor.visitIincInsn(5, 1);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Integer");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 7);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 7);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class");
methodVisitor.visitVarInsn(Opcodes.ASTORE, 6);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 5);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 6);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 7);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/System", "arraycopy", "(Ljava/lang/Object;ILjava/lang/Object;II)V", false);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 5);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 7);
methodVisitor.visitInsn(Opcodes.IADD);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 5);
Label markerInterfaceExit = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, markerInterfaceExit);
methodVisitor.visitLabel(markerInterfaceLoop);
methodVisitor.visitFrame(Opcodes.F_APPEND, 2, new Object[]{Opcodes.INTEGER, Opcodes.INTEGER}, 0, null);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class");
methodVisitor.visitVarInsn(Opcodes.ASTORE, 6);
methodVisitor.visitLabel(markerInterfaceExit);
methodVisitor.visitFrame(Opcodes.F_APPEND, 1, new Object[]{"[Ljava/lang/Class;"}, 0, null);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 4);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitInsn(Opcodes.IAND);
Label additionalBridgesLoop = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFEQ, additionalBridgesLoop);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 5);
methodVisitor.visitIincInsn(5, 1);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Integer");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 8);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 8);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/invoke/MethodType");
methodVisitor.visitVarInsn(Opcodes.ASTORE, 7);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 5);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 7);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 8);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/System", "arraycopy", "(Ljava/lang/Object;ILjava/lang/Object;II)V", false);
Label additionalBridgesExit = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, additionalBridgesExit);
methodVisitor.visitLabel(additionalBridgesLoop);
methodVisitor.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/invoke/MethodType");
methodVisitor.visitVarInsn(Opcodes.ASTORE, 7);
methodVisitor.visitLabel(additionalBridgesExit);
methodVisitor.visitFrame(Opcodes.F_APPEND, 1, new Object[]{"[Ljava/lang/invoke/MethodType;"}, 0, null);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, UNSAFE_CLASS, "getUnsafe", "()L" + UNSAFE_CLASS + ";", false);
methodVisitor.visitVarInsn(Opcodes.ASTORE, 8);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 8);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "lookupClass", "()Ljava/lang/Class;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/ClassLoader", "getSystemClassLoader", "()Ljava/lang/ClassLoader;", false);
methodVisitor.visitLdcInsn("net.bytebuddy.agent.builder.LambdaFactory");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/ClassLoader", "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;", false);
methodVisitor.visitLdcInsn("make");
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 9);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/String;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_3);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_5);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 6);
methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Boolean", "TYPE", "Ljava/lang/Class;");
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 7);
methodVisitor.visitLdcInsn(Type.getType("Ljava/util/List;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 8);
methodVisitor.visitLdcInsn(Type.getType("Ljava/util/List;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredMethod", "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;", false);
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 9);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_3);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_5);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 6);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 4);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitInsn(Opcodes.IAND);
Label callSiteConditional = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFEQ, callSiteConditional);
methodVisitor.visitInsn(Opcodes.ICONST_1);
Label callSiteAlternative = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, callSiteAlternative);
methodVisitor.visitLabel(callSiteConditional);
methodVisitor.visitFrame(Opcodes.F_FULL, 9, new Object[]{"java/lang/invoke/MethodHandles$Lookup", "java/lang/String", "java/lang/invoke/MethodType", "[Ljava/lang/Object;", Opcodes.INTEGER, Opcodes.INTEGER, "[Ljava/lang/Class;", "[Ljava/lang/invoke/MethodType;", UNSAFE_CLASS}, 7, new Object[]{UNSAFE_CLASS, "java/lang/Class", "java/lang/reflect/Method", Opcodes.NULL, "[Ljava/lang/Object;", "[Ljava/lang/Object;", Opcodes.INTEGER});
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitLabel(callSiteAlternative);
methodVisitor.visitFrame(Opcodes.F_FULL, 9, new Object[]{"java/lang/invoke/MethodHandles$Lookup", "java/lang/String", "java/lang/invoke/MethodType", "[Ljava/lang/Object;", Opcodes.INTEGER, Opcodes.INTEGER, "[Ljava/lang/Class;", "[Ljava/lang/invoke/MethodType;", UNSAFE_CLASS}, 8, new Object[]{UNSAFE_CLASS, "java/lang/Class", "java/lang/reflect/Method", Opcodes.NULL, "[Ljava/lang/Object;", "[Ljava/lang/Object;", Opcodes.INTEGER, Opcodes.INTEGER});
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 7);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 6);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Arrays", "asList", "([Ljava/lang/Object;)Ljava/util/List;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 8);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 7);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Arrays", "asList", "([Ljava/lang/Object;)Ljava/util/List;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Method", "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", false);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "[B");
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, UNSAFE_CLASS, "defineAnonymousClass", "(Ljava/lang/Class;[B[Ljava/lang/Object;)Ljava/lang/Class;", false);
methodVisitor.visitVarInsn(Opcodes.ASTORE, 9);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 8);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 9);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, UNSAFE_CLASS, "ensureClassInitialized", "(Ljava/lang/Class;)V", false);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodType", "parameterCount", "()I", false);
Label callSiteJump = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFNE, callSiteJump);
methodVisitor.visitTypeInsn(Opcodes.NEW, "java/lang/invoke/ConstantCallSite");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodType", "returnType", "()Ljava/lang/Class;", false);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 9);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredConstructors", "()[Ljava/lang/reflect/Constructor;", false);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Constructor", "newInstance", "([Ljava/lang/Object;)Ljava/lang/Object;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/invoke/MethodHandles", "constant", "(Ljava/lang/Class;Ljava/lang/Object;)Ljava/lang/invoke/MethodHandle;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/invoke/ConstantCallSite", "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false);
Label callSiteExit = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, callSiteExit);
methodVisitor.visitLabel(callSiteJump);
methodVisitor.visitFrame(Opcodes.F_APPEND, 1, new Object[]{"java/lang/Class"}, 0, null);
methodVisitor.visitTypeInsn(Opcodes.NEW, "java/lang/invoke/ConstantCallSite");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/invoke/MethodHandles$Lookup", "IMPL_LOOKUP", "Ljava/lang/invoke/MethodHandles$Lookup;");
methodVisitor.visitVarInsn(Opcodes.ALOAD, 9);
methodVisitor.visitLdcInsn("get$Lambda");
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "findStatic", "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/MethodHandle;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/invoke/ConstantCallSite", "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false);
methodVisitor.visitLabel(callSiteExit);
methodVisitor.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[]{"java/lang/invoke/CallSite"});
methodVisitor.visitInsn(Opcodes.ARETURN);
methodVisitor.visitMaxs(9, 10);
methodVisitor.visitEnd();
return IGNORE_ORIGINAL;
}
}
}
/**
* <p>
* The default implementation of an {@link net.bytebuddy.agent.builder.AgentBuilder}.
* </p>
* <p>
* By default, Byte Buddy ignores any types loaded by the bootstrap class loader and
* any synthetic type. Self-injection and rebasing is enabled. In order to avoid class format changes, set
* {@link AgentBuilder#disableClassFormatChanges()}. All types are parsed without their debugging information
* ({@link PoolStrategy.Default#FAST}).
* </p>
*/
@HashCodeAndEqualsPlugin.Enhance
class Default implements AgentBuilder {
/**
* The name of the Byte Buddy {@code net.bytebuddy.agent.Installer} class.
*/
private static final String INSTALLER_TYPE = "net.bytebuddy.agent.Installer";
/**
* The name of the {@code net.bytebuddy.agent.Installer} getter for reading an installed {@link Instrumentation}.
*/
private static final String INSTRUMENTATION_GETTER = "getInstrumentation";
/**
* Indicator for access to a static member via reflection to make the code more readable.
*/
private static final Object STATIC_MEMBER = null;
/**
* The value that is to be returned from a {@link java.lang.instrument.ClassFileTransformer} to indicate
* that no class file transformation is to be applied.
*/
private static final byte[] NO_TRANSFORMATION = null;
/**
* Indicates that a loaded type should be considered as non-available.
*/
private static final Class<?> NO_LOADED_TYPE = null;
/**
* A dipatcher to use for interacting with the instrumentation API.
*/
private static final Dispatcher DISPATCHER = AccessController.doPrivileged(Dispatcher.CreationAction.INSTANCE);
/**
* The default circularity lock that assures that no agent created by any agent builder within this
* class loader causes a class loading circularity.
*/
private static final CircularityLock DEFAULT_LOCK = new CircularityLock.Default();
/**
* The {@link net.bytebuddy.ByteBuddy} instance to be used.
*/
protected final ByteBuddy byteBuddy;
/**
* The listener to notify on transformations.
*/
protected final Listener listener;
/**
* The circularity lock to use.
*/
protected final CircularityLock circularityLock;
/**
* The type locator to use.
*/
protected final PoolStrategy poolStrategy;
/**
* The definition handler to use.
*/
protected final TypeStrategy typeStrategy;
/**
* The location strategy to use.
*/
protected final LocationStrategy locationStrategy;
/**
* The native method strategy to use.
*/
protected final NativeMethodStrategy nativeMethodStrategy;
/**
* A decorator to wrap the created class file transformer.
*/
protected final TransformerDecorator transformerDecorator;
/**
* The initialization strategy to use for creating classes.
*/
protected final InitializationStrategy initializationStrategy;
/**
* The redefinition strategy to apply.
*/
protected final RedefinitionStrategy redefinitionStrategy;
/**
* The discovery strategy for loaded types to be redefined.
*/
protected final RedefinitionStrategy.DiscoveryStrategy redefinitionDiscoveryStrategy;
/**
* The batch allocator for the redefinition strategy to apply.
*/
protected final RedefinitionStrategy.BatchAllocator redefinitionBatchAllocator;
/**
* The redefinition listener for the redefinition strategy to apply.
*/
protected final RedefinitionStrategy.Listener redefinitionListener;
/**
* The resubmission strategy to apply.
*/
protected final RedefinitionStrategy.ResubmissionStrategy redefinitionResubmissionStrategy;
/**
* The injection strategy for injecting classes into a class loader.
*/
protected final InjectionStrategy injectionStrategy;
/**
* A strategy to determine of the {@code LambdaMetafactory} should be instrumented to allow for the instrumentation
* of classes that represent lambda expressions.
*/
protected final LambdaInstrumentationStrategy lambdaInstrumentationStrategy;
/**
* The description strategy for resolving type descriptions for types.
*/
protected final DescriptionStrategy descriptionStrategy;
/**
* The fallback strategy to apply.
*/
protected final FallbackStrategy fallbackStrategy;
/**
* The class file buffer strategy to use.
*/
protected final ClassFileBufferStrategy classFileBufferStrategy;
/**
* The installation listener to notify.
*/
protected final InstallationListener installationListener;
/**
* Identifies types that should not be instrumented.
*/
protected final RawMatcher ignoreMatcher;
/**
* The transformation object for handling type transformations.
*/
protected final List<Transformation> transformations;
/**
* Creates a new default agent builder that uses a default {@link net.bytebuddy.ByteBuddy} instance for creating classes.
*/
public Default() {
this(new ByteBuddy());
}
/**
* Creates a new agent builder with default settings. By default, Byte Buddy ignores any types loaded by the bootstrap class loader, any
* type within a {@code net.bytebuddy} package and any synthetic type. Self-injection and rebasing is enabled. In order to avoid class format
* changes, set {@link AgentBuilder#disableClassFormatChanges()}. All types are parsed without their debugging information
* ({@link PoolStrategy.Default#FAST}).
*
* @param byteBuddy The Byte Buddy instance to be used.
*/
public Default(ByteBuddy byteBuddy) {
this(byteBuddy,
Listener.NoOp.INSTANCE,
DEFAULT_LOCK,
PoolStrategy.Default.FAST,
TypeStrategy.Default.REBASE,
LocationStrategy.ForClassLoader.STRONG,
NativeMethodStrategy.Disabled.INSTANCE,
TransformerDecorator.NoOp.INSTANCE,
new InitializationStrategy.SelfInjection.Split(),
RedefinitionStrategy.DISABLED,
RedefinitionStrategy.DiscoveryStrategy.SinglePass.INSTANCE,
RedefinitionStrategy.BatchAllocator.ForTotal.INSTANCE,
RedefinitionStrategy.Listener.NoOp.INSTANCE,
RedefinitionStrategy.ResubmissionStrategy.Disabled.INSTANCE,
InjectionStrategy.UsingReflection.INSTANCE,
LambdaInstrumentationStrategy.DISABLED,
DescriptionStrategy.Default.HYBRID,
FallbackStrategy.ByThrowableType.ofOptionalTypes(),
ClassFileBufferStrategy.Default.RETAINING,
InstallationListener.NoOp.INSTANCE,
new RawMatcher.Disjunction(
new RawMatcher.ForElementMatchers(any(), isBootstrapClassLoader().or(isExtensionClassLoader())),
new RawMatcher.ForElementMatchers(nameStartsWith("net.bytebuddy.").or(nameStartsWith("sun.reflect.")).<TypeDescription>or(isSynthetic()))),
Collections.<Transformation>emptyList());
}
/**
* Creates a new default agent builder.
*
* @param byteBuddy The Byte Buddy instance to be used.
* @param listener The listener to notify on transformations.
* @param circularityLock The circularity lock to use.
* @param poolStrategy The type locator to use.
* @param typeStrategy The definition handler to use.
* @param locationStrategy The location strategy to use.
* @param nativeMethodStrategy The native method strategy to apply.
* @param transformerDecorator A decorator to wrap the created class file transformer.
* @param initializationStrategy The initialization strategy to use for transformed types.
* @param redefinitionStrategy The redefinition strategy to apply.
* @param redefinitionDiscoveryStrategy The discovery strategy for loaded types to be redefined.
* @param redefinitionBatchAllocator The batch allocator for the redefinition strategy to apply.
* @param redefinitionListener The redefinition listener for the redefinition strategy to apply.
* @param redefinitionResubmissionStrategy The resubmission strategy to apply.
* @param injectionStrategy The injection strategy for injecting classes into a class loader.
* @param lambdaInstrumentationStrategy A strategy to determine of the {@code LambdaMetafactory} should be instrumented to allow for the
* instrumentation of classes that represent lambda expressions.
* @param descriptionStrategy The description strategy for resolving type descriptions for types.
* @param fallbackStrategy The fallback strategy to apply.
* @param classFileBufferStrategy The class file buffer strategy to use.
* @param installationListener The installation listener to notify.
* @param ignoreMatcher Identifies types that should not be instrumented.
* @param transformations The transformations to apply for any non-ignored type.
*/
protected Default(ByteBuddy byteBuddy,
Listener listener,
CircularityLock circularityLock,
PoolStrategy poolStrategy,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
NativeMethodStrategy nativeMethodStrategy,
TransformerDecorator transformerDecorator,
InitializationStrategy initializationStrategy,
RedefinitionStrategy redefinitionStrategy,
RedefinitionStrategy.DiscoveryStrategy redefinitionDiscoveryStrategy,
RedefinitionStrategy.BatchAllocator redefinitionBatchAllocator,
RedefinitionStrategy.Listener redefinitionListener,
RedefinitionStrategy.ResubmissionStrategy redefinitionResubmissionStrategy,
InjectionStrategy injectionStrategy,
LambdaInstrumentationStrategy lambdaInstrumentationStrategy,
DescriptionStrategy descriptionStrategy,
FallbackStrategy fallbackStrategy,
ClassFileBufferStrategy classFileBufferStrategy,
InstallationListener installationListener,
RawMatcher ignoreMatcher,
List<Transformation> transformations) {
this.byteBuddy = byteBuddy;
this.listener = listener;
this.circularityLock = circularityLock;
this.poolStrategy = poolStrategy;
this.typeStrategy = typeStrategy;
this.locationStrategy = locationStrategy;
this.nativeMethodStrategy = nativeMethodStrategy;
this.transformerDecorator = transformerDecorator;
this.initializationStrategy = initializationStrategy;
this.redefinitionStrategy = redefinitionStrategy;
this.redefinitionDiscoveryStrategy = redefinitionDiscoveryStrategy;
this.redefinitionBatchAllocator = redefinitionBatchAllocator;
this.redefinitionListener = redefinitionListener;
this.redefinitionResubmissionStrategy = redefinitionResubmissionStrategy;
this.injectionStrategy = injectionStrategy;
this.lambdaInstrumentationStrategy = lambdaInstrumentationStrategy;
this.descriptionStrategy = descriptionStrategy;
this.fallbackStrategy = fallbackStrategy;
this.classFileBufferStrategy = classFileBufferStrategy;
this.installationListener = installationListener;
this.ignoreMatcher = ignoreMatcher;
this.transformations = transformations;
}
/**
* Creates an {@link AgentBuilder} that realizes the provided build plugins. As {@link EntryPoint}, {@link EntryPoint.Default#REBASE} is implied.
*
* @param plugin The build plugins to apply as a Java agent.
* @return An appropriate agent builder.
*/
public static AgentBuilder of(Plugin... plugin) {
return of(Arrays.asList(plugin));
}
/**
* Creates an {@link AgentBuilder} that realizes the provided build plugins. As {@link EntryPoint}, {@link EntryPoint.Default#REBASE} is implied.
*
* @param plugins The build plugins to apply as a Java agent.
* @return An appropriate agent builder.
*/
public static AgentBuilder of(List<? extends Plugin> plugins) {
return of(EntryPoint.Default.REBASE, plugins);
}
/**
* Creates an {@link AgentBuilder} that realizes the provided build plugins.
*
* @param entryPoint The build entry point to use.
* @param plugin The build plugins to apply as a Java agent.
* @return An appropriate agent builder.
*/
public static AgentBuilder of(EntryPoint entryPoint, Plugin... plugin) {
return of(entryPoint, Arrays.asList(plugin));
}
/**
* Creates an {@link AgentBuilder} that realizes the provided build plugins.
*
* @param entryPoint The build entry point to use.
* @param plugins The build plugins to apply as a Java agent.
* @return An appropriate agent builder.
*/
public static AgentBuilder of(EntryPoint entryPoint, List<? extends Plugin> plugins) {
return of(entryPoint, ClassFileVersion.ofThisVm(), plugins);
}
/**
* Creates an {@link AgentBuilder} that realizes the provided build plugins. As {@link EntryPoint}, {@link EntryPoint.Default#REBASE} is implied.
*
* @param classFileVersion The class file version to use.
* @param plugin The build plugins to apply as a Java agent.
* @return An appropriate agent builder.
*/
public static AgentBuilder of(ClassFileVersion classFileVersion, Plugin... plugin) {
return of(classFileVersion, Arrays.asList(plugin));
}
/**
* Creates an {@link AgentBuilder} that realizes the provided build plugins. As {@link EntryPoint}, {@link EntryPoint.Default#REBASE} is implied.
*
* @param classFileVersion The class file version to use.
* @param plugins The build plugins to apply as a Java agent.
* @return An appropriate agent builder.
*/
public static AgentBuilder of(ClassFileVersion classFileVersion, List<? extends Plugin> plugins) {
return of(EntryPoint.Default.REBASE, classFileVersion, plugins);
}
/**
* Creates an {@link AgentBuilder} that realizes the provided build plugins.
*
* @param entryPoint The build entry point to use.
* @param classFileVersion The class file version to use.
* @param plugin The build plugins to apply as a Java agent.
* @return An appropriate agent builder.
*/
public static AgentBuilder of(EntryPoint entryPoint, ClassFileVersion classFileVersion, Plugin... plugin) {
return of(entryPoint, classFileVersion, Arrays.asList(plugin));
}
/**
* Creates an {@link AgentBuilder} that realizes the provided build plugins.
*
* @param entryPoint The build entry point to use.
* @param classFileVersion The class file version to use.
* @param plugins The build plugins to apply as a Java agent.
* @return An appropriate agent builder.
*/
public static AgentBuilder of(EntryPoint entryPoint, ClassFileVersion classFileVersion, List<? extends Plugin> plugins) {
AgentBuilder agentBuilder = new AgentBuilder.Default(entryPoint.byteBuddy(classFileVersion)).with(new TypeStrategy.ForBuildEntryPoint(entryPoint));
for (Plugin plugin : plugins) {
agentBuilder = agentBuilder.type(plugin).transform(new Transformer.ForBuildPlugin(plugin));
}
return agentBuilder;
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(ByteBuddy byteBuddy) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(Listener listener) {
return new Default(byteBuddy,
new Listener.Compound(this.listener, listener),
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(CircularityLock circularityLock) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(TypeStrategy typeStrategy) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(PoolStrategy poolStrategy) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(LocationStrategy locationStrategy) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder enableNativeMethodPrefix(String prefix) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
NativeMethodStrategy.ForPrefix.of(prefix),
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder disableNativeMethodPrefix() {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
NativeMethodStrategy.Disabled.INSTANCE,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(TransformerDecorator transformerDecorator) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
new TransformerDecorator.Compound(this.transformerDecorator, transformerDecorator),
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public RedefinitionListenable.WithoutBatchStrategy with(RedefinitionStrategy redefinitionStrategy) {
return new Redefining(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
RedefinitionStrategy.DiscoveryStrategy.SinglePass.INSTANCE,
RedefinitionStrategy.BatchAllocator.ForTotal.INSTANCE,
RedefinitionStrategy.Listener.NoOp.INSTANCE,
RedefinitionStrategy.ResubmissionStrategy.Disabled.INSTANCE,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(InitializationStrategy initializationStrategy) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(LambdaInstrumentationStrategy lambdaInstrumentationStrategy) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(DescriptionStrategy descriptionStrategy) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(FallbackStrategy fallbackStrategy) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(ClassFileBufferStrategy classFileBufferStrategy) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(InstallationListener installationListener) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
new InstallationListener.Compound(this.installationListener, installationListener),
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(InjectionStrategy injectionStrategy) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder disableClassFormatChanges() {
return new Default(byteBuddy.with(Implementation.Context.Disabled.Factory.INSTANCE),
listener,
circularityLock,
poolStrategy,
typeStrategy == TypeStrategy.Default.DECORATE
? TypeStrategy.Default.DECORATE
: TypeStrategy.Default.REDEFINE_FROZEN,
locationStrategy,
NativeMethodStrategy.Disabled.INSTANCE,
transformerDecorator,
InitializationStrategy.NoOp.INSTANCE,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Class<?>... type) {
return JavaModule.isSupported()
? with(Listener.ModuleReadEdgeCompleting.of(instrumentation, false, type))
: this;
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, JavaModule... module) {
return assureReadEdgeTo(instrumentation, Arrays.asList(module));
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules) {
return with(new Listener.ModuleReadEdgeCompleting(instrumentation, false, new HashSet<JavaModule>(modules)));
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Class<?>... type) {
return JavaModule.isSupported()
? with(Listener.ModuleReadEdgeCompleting.of(instrumentation, true, type))
: this;
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, JavaModule... module) {
return assureReadEdgeFromAndTo(instrumentation, Arrays.asList(module));
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules) {
return with(new Listener.ModuleReadEdgeCompleting(instrumentation, true, new HashSet<JavaModule>(modules)));
}
/**
* {@inheritDoc}
*/
public Identified.Narrowable type(RawMatcher matcher) {
return new Transforming(matcher, Collections.<Transformer>emptyList(), false);
}
/**
* {@inheritDoc}
*/
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher) {
return type(typeMatcher, any());
}
/**
* {@inheritDoc}
*/
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) {
return type(typeMatcher, classLoaderMatcher, any());
}
/**
* {@inheritDoc}
*/
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return type(new RawMatcher.ForElementMatchers(typeMatcher, classLoaderMatcher, not(supportsModules()).or(moduleMatcher)));
}
/**
* {@inheritDoc}
*/
public Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher) {
return ignore(typeMatcher, any());
}
/**
* {@inheritDoc}
*/
public Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) {
return ignore(typeMatcher, classLoaderMatcher, any());
}
/**
* {@inheritDoc}
*/
public Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return ignore(new RawMatcher.ForElementMatchers(typeMatcher, classLoaderMatcher, not(supportsModules()).or(moduleMatcher)));
}
/**
* {@inheritDoc}
*/
public Ignored ignore(RawMatcher rawMatcher) {
return new Ignoring(rawMatcher);
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer makeRaw() {
return makeRaw(listener, InstallationListener.NoOp.INSTANCE);
}
/**
* Creates a new class file transformer with a given listener.
*
* @param listener The listener to supply.
* @param installationListener The installation listener to notify.
* @return The resettable class file transformer to use.
*/
private ResettableClassFileTransformer makeRaw(Listener listener, InstallationListener installationListener) {
return ExecutingTransformer.FACTORY.make(byteBuddy,
listener,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
initializationStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations,
circularityLock);
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer installOn(Instrumentation instrumentation) {
if (!circularityLock.acquire()) {
throw new IllegalStateException("Could not acquire the circularity lock upon installation.");
}
try {
return doInstall(instrumentation, new Transformation.SimpleMatcher(ignoreMatcher, transformations));
} finally {
circularityLock.release();
}
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer installOnByteBuddyAgent() {
try {
return installOn((Instrumentation) ClassLoader.getSystemClassLoader()
.loadClass(INSTALLER_TYPE)
.getMethod(INSTRUMENTATION_GETTER)
.invoke(STATIC_MEMBER));
} catch (RuntimeException exception) {
throw exception;
} catch (Exception exception) {
throw new IllegalStateException("The Byte Buddy agent is not installed or not accessible", exception);
}
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer patchOn(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
if (!circularityLock.acquire()) {
throw new IllegalStateException("Could not acquire the circularity lock upon installation.");
}
try {
if (!classFileTransformer.reset(instrumentation, RedefinitionStrategy.DISABLED)) {
throw new IllegalArgumentException("Cannot patch unregistered class file transformer: " + classFileTransformer);
}
return doInstall(instrumentation, new Transformation.DifferentialMatcher(ignoreMatcher, transformations, classFileTransformer));
} finally {
circularityLock.release();
}
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer patchOnByteBuddyAgent(ResettableClassFileTransformer classFileTransformer) {
try {
return patchOn((Instrumentation) ClassLoader.getSystemClassLoader()
.loadClass(INSTALLER_TYPE)
.getMethod(INSTRUMENTATION_GETTER)
.invoke(STATIC_MEMBER), classFileTransformer);
} catch (RuntimeException exception) {
throw exception;
} catch (Exception exception) {
throw new IllegalStateException("The Byte Buddy agent is not installed or not accessible", exception);
}
}
/**
* Installs the class file transformer.
*
* @param instrumentation The instrumentation to install the matcher on.
* @param matcher The matcher to identify redefined types.
* @return The created class file transformer.
*/
private ResettableClassFileTransformer doInstall(Instrumentation instrumentation, RawMatcher matcher) {
RedefinitionStrategy.ResubmissionStrategy.Installation installation = redefinitionResubmissionStrategy.apply(instrumentation,
locationStrategy,
listener,
installationListener,
circularityLock,
new Transformation.SimpleMatcher(ignoreMatcher, transformations),
redefinitionStrategy,
redefinitionBatchAllocator,
redefinitionListener);
ResettableClassFileTransformer classFileTransformer = transformerDecorator.decorate(makeRaw(installation.getListener(),
installation.getInstallationListener()));
installation.getInstallationListener().onBeforeInstall(instrumentation, classFileTransformer);
try {
DISPATCHER.addTransformer(instrumentation, classFileTransformer, redefinitionStrategy.isRetransforming());
nativeMethodStrategy.apply(instrumentation, classFileTransformer);
lambdaInstrumentationStrategy.apply(byteBuddy, instrumentation, classFileTransformer);
redefinitionStrategy.apply(instrumentation,
installation.getListener(),
circularityLock,
poolStrategy,
locationStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
matcher);
} catch (Throwable throwable) {
throwable = installation.getInstallationListener().onError(instrumentation, classFileTransformer, throwable);
if (throwable != null) {
instrumentation.removeTransformer(classFileTransformer);
throw new IllegalStateException("Could not install class file transformer", throwable);
}
}
installation.getInstallationListener().onInstall(instrumentation, classFileTransformer);
return classFileTransformer;
}
/**
* A dispatcher for interacting with the instrumentation API.
*/
protected interface Dispatcher {
/**
* Returns {@code true} if the supplied instrumentation instance supports setting native method prefixes.
*
* @param instrumentation The instrumentation instance to use.
* @return {@code true} if the supplied instrumentation instance supports native method prefixes.
*/
boolean isNativeMethodPrefixSupported(Instrumentation instrumentation);
/**
* Sets a native method prefix for the supplied class file transformer.
*
* @param instrumentation The instrumentation instance to use.
* @param classFileTransformer The class file transformer for which the prefix is set.
* @param prefix The prefix to set.
*/
void setNativeMethodPrefix(Instrumentation instrumentation, ClassFileTransformer classFileTransformer, String prefix);
/**
* Adds a class file transformer to an instrumentation instance.
*
* @param instrumentation The instrumentation instance to use for registration.
* @param classFileTransformer The class file transformer to register.
* @param canRetransform {@code true} if the class file transformer is capable of retransformation.
*/
void addTransformer(Instrumentation instrumentation, ClassFileTransformer classFileTransformer, boolean canRetransform);
/**
* An action for creating a dispatcher.
*/
enum CreationAction implements PrivilegedAction<Dispatcher> {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Dispatcher run() {
try {
return new Dispatcher.ForJava6CapableVm(Instrumentation.class.getMethod("isNativeMethodPrefixSupported"),
Instrumentation.class.getMethod("setNativeMethodPrefix", ClassFileTransformer.class, String.class),
Instrumentation.class.getMethod("addTransformer", ClassFileTransformer.class, boolean.class));
} catch (NoSuchMethodException ignored) {
return Dispatcher.ForLegacyVm.INSTANCE;
}
}
}
/**
* A dispatcher for a legacy VM.
*/
enum ForLegacyVm implements Dispatcher {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public boolean isNativeMethodPrefixSupported(Instrumentation instrumentation) {
return false;
}
/**
* {@inheritDoc}
*/
public void setNativeMethodPrefix(Instrumentation instrumentation, ClassFileTransformer classFileTransformer, String prefix) {
throw new UnsupportedOperationException("The current VM does not support native method prefixes");
}
/**
* {@inheritDoc}
*/
public void addTransformer(Instrumentation instrumentation, ClassFileTransformer classFileTransformer, boolean canRetransform) {
if (canRetransform) {
throw new UnsupportedOperationException("The current VM does not support retransformation");
}
instrumentation.addTransformer(classFileTransformer);
}
}
/**
* A dispatcher for a Java 6 capable VM.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForJava6CapableVm implements Dispatcher {
/**
* The {@code Instrumentation#isNativeMethodPrefixSupported} method.
*/
private final Method isNativeMethodPrefixSupported;
/**
* The {@code Instrumentation#setNativeMethodPrefix} method.
*/
private final Method setNativeMethodPrefix;
/**
* The {@code Instrumentation#addTransformer} method.
*/
private final Method addTransformer;
/**
* Creates a new Java 6 capable dispatcher.
*
* @param isNativeMethodPrefixSupported The {@code Instrumentation#isNativeMethodPrefixSupported} method.
* @param setNativeMethodPrefix The {@code Instrumentation#setNativeMethodPrefix} method.
* @param addTransformer The {@code Instrumentation#addTransformer} method.
*/
protected ForJava6CapableVm(Method isNativeMethodPrefixSupported, Method setNativeMethodPrefix, Method addTransformer) {
this.isNativeMethodPrefixSupported = isNativeMethodPrefixSupported;
this.setNativeMethodPrefix = setNativeMethodPrefix;
this.addTransformer = addTransformer;
}
/**
* {@inheritDoc}
*/
public boolean isNativeMethodPrefixSupported(Instrumentation instrumentation) {
try {
return (Boolean) isNativeMethodPrefixSupported.invoke(instrumentation);
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Cannot access java.lang.instrument.Instrumentation#isNativeMethodPrefixSupported", exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException("Error invoking java.lang.instrument.Instrumentation#isNativeMethodPrefixSupported", exception.getCause());
}
}
/**
* {@inheritDoc}
*/
public void setNativeMethodPrefix(Instrumentation instrumentation, ClassFileTransformer classFileTransformer, String prefix) {
try {
setNativeMethodPrefix.invoke(instrumentation, classFileTransformer, prefix);
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Cannot access java.lang.instrument.Instrumentation#setNativeMethodPrefix", exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException("Error invoking java.lang.instrument.Instrumentation#setNativeMethodPrefix", exception.getCause());
}
}
/**
* {@inheritDoc}
*/
public void addTransformer(Instrumentation instrumentation, ClassFileTransformer classFileTransformer, boolean canRetransform) {
try {
addTransformer.invoke(instrumentation, classFileTransformer, canRetransform);
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Cannot access java.lang.instrument.Instrumentation#addTransformer", exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException("Error invoking java.lang.instrument.Instrumentation#addTransformer", exception.getCause());
}
}
}
}
/**
* A strategy for determining if a native method name prefix should be used when rebasing methods.
*/
protected interface NativeMethodStrategy {
/**
* Resolves the method name transformer for this strategy.
*
* @return A method name transformer for this strategy.
*/
MethodNameTransformer resolve();
/**
* Applies this native method strategy.
*
* @param instrumentation The instrumentation to apply this strategy upon.
* @param classFileTransformer The class file transformer being registered.
*/
void apply(Instrumentation instrumentation, ClassFileTransformer classFileTransformer);
/**
* A native method strategy that suffixes method names with a random suffix and disables native method rebasement.
*/
enum Disabled implements NativeMethodStrategy {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public MethodNameTransformer resolve() {
return MethodNameTransformer.Suffixing.withRandomSuffix();
}
/**
* {@inheritDoc}
*/
public void apply(Instrumentation instrumentation, ClassFileTransformer classFileTransformer) {
/* do nothing */
}
}
/**
* A native method strategy that prefixes method names with a fixed value for supporting rebasing of native methods.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForPrefix implements NativeMethodStrategy {
/**
* The method name prefix.
*/
private final String prefix;
/**
* Creates a new name prefixing native method strategy.
*
* @param prefix The method name prefix.
*/
protected ForPrefix(String prefix) {
this.prefix = prefix;
}
/**
* Creates a new native method strategy for prefixing method names.
*
* @param prefix The method name prefix.
* @return An appropriate native method strategy.
*/
protected static NativeMethodStrategy of(String prefix) {
if (prefix.length() == 0) {
throw new IllegalArgumentException("A method name prefix must not be the empty string");
}
return new ForPrefix(prefix);
}
/**
* {@inheritDoc}
*/
public MethodNameTransformer resolve() {
return new MethodNameTransformer.Prefixing(prefix);
}
/**
* {@inheritDoc}
*/
public void apply(Instrumentation instrumentation, ClassFileTransformer classFileTransformer) {
if (!DISPATCHER.isNativeMethodPrefixSupported(instrumentation)) {
throw new IllegalArgumentException("A prefix for native methods is not supported: " + instrumentation);
}
DISPATCHER.setNativeMethodPrefix(instrumentation, classFileTransformer, prefix);
}
}
}
/**
* A transformation to apply.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class Transformation {
/**
* Indicates that a type should not be ignored.
*/
protected static final byte[] NONE = null;
/**
* The matcher to identify types for transformation.
*/
private final RawMatcher matcher;
/**
* A list of transformers to apply.
*/
private final List<Transformer> transformers;
/**
* {@code true} if this transformation is terminal.
*/
private final boolean terminal;
/**
* Creates a new transformation.
*
* @param matcher The matcher to identify types eligable for transformation.
* @param transformers A list of transformers to apply.
* @param terminal Indicates that this transformation is terminal.
*/
protected Transformation(RawMatcher matcher, List<Transformer> transformers, boolean terminal) {
this.matcher = matcher;
this.transformers = transformers;
this.terminal = terminal;
}
/**
* Returns the matcher to identify types for transformation.
*
* @return The matcher to identify types for transformation.
*/
protected RawMatcher getMatcher() {
return matcher;
}
/**
* Returns a list of transformers to apply.
*
* @return A list of transformers to apply.
*/
protected List<Transformer> getTransformers() {
return transformers;
}
/**
* Returns {@code true} if this transformation is terminal.
*
* @return {@code true} if this transformation is terminal.
*/
protected boolean isTerminal() {
return terminal;
}
/**
* A matcher that matches any type that is touched by a transformer without being ignored.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class SimpleMatcher implements RawMatcher {
/**
* Identifies types that should not be instrumented.
*/
private final RawMatcher ignoreMatcher;
/**
* The transformations to apply on non-ignored types.
*/
private final List<Transformation> transformations;
/**
* Creates a new simple matcher.
*
* @param ignoreMatcher Identifies types that should not be instrumented.
* @param transformations The transformations to apply on non-ignored types.
*/
protected SimpleMatcher(RawMatcher ignoreMatcher, List<Transformation> transformations) {
this.ignoreMatcher = ignoreMatcher;
this.transformations = transformations;
}
/**
* {@inheritDoc}
*/
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
if (ignoreMatcher.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)) {
return false;
}
for (Transformation transformation : transformations) {
if (transformation.getMatcher().matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)) {
return true;
}
}
return false;
}
}
/**
* A matcher that considers the differential of two transformers' transformations.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class DifferentialMatcher implements RawMatcher {
/**
* Identifies types that should not be instrumented.
*/
private final RawMatcher ignoreMatcher;
/**
* The transformations to apply on non-ignored types.
*/
private final List<Transformation> transformations;
/**
* The class file transformer representing the differential.
*/
private final ResettableClassFileTransformer classFileTransformer;
/**
* Creates a new differential matcher.
*
* @param ignoreMatcher Identifies types that should not be instrumented.
* @param transformations The transformations to apply on non-ignored types.
* @param classFileTransformer The class file transformer representing the differential.
*/
protected DifferentialMatcher(RawMatcher ignoreMatcher,
List<Transformation> transformations,
ResettableClassFileTransformer classFileTransformer) {
this.ignoreMatcher = ignoreMatcher;
this.transformations = transformations;
this.classFileTransformer = classFileTransformer;
}
/**
* {@inheritDoc}
*/
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
Iterator<Transformer> iterator = classFileTransformer.iterator(typeDescription, classLoader, module, classBeingRedefined, protectionDomain);
if (ignoreMatcher.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)) {
return iterator.hasNext();
}
for (Transformation transformation : transformations) {
if (transformation.getMatcher().matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)) {
for (Transformer transformer : transformation.getTransformers()) {
if (!iterator.hasNext() || !iterator.next().equals(transformer)) {
return true;
}
}
}
}
return iterator.hasNext();
}
}
/**
* An iterator over a list of transformations that match a raw matcher specification.
*/
protected static class TransformerIterator implements Iterator<Transformer> {
/**
* A description of the matched type.
*/
private final TypeDescription typeDescription;
/**
* The type's class loader.
*/
private final ClassLoader classLoader;
/**
* The type's module.
*/
private final JavaModule module;
/**
* The class being redefined or {@code null} if the type was not previously loaded.
*/
private final Class<?> classBeingRedefined;
/**
* The type's protection domain.
*/
private final ProtectionDomain protectionDomain;
/**
* An iterator over the remaining transformations that were not yet considered.
*/
private final Iterator<Transformation> transformations;
/**
* An iterator over the currently matched transformers.
*/
private Iterator<Transformer> transformers;
/**
* Creates a new iterator.
*
* @param typeDescription A description of the matched type.
* @param classLoader The type's class loader.
* @param module The type's module.
* @param classBeingRedefined The class being redefined or {@code null} if the type was not previously loaded.
* @param protectionDomain The type's protection domain.
* @param transformations The matched transformations.
*/
protected TransformerIterator(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
List<Transformation> transformations) {
this.typeDescription = typeDescription;
this.classLoader = classLoader;
this.module = module;
this.classBeingRedefined = classBeingRedefined;
this.protectionDomain = protectionDomain;
this.transformations = transformations.iterator();
transformers = Collections.<Transformer>emptySet().iterator();
while (!transformers.hasNext() && this.transformations.hasNext()) {
Transformation transformation = this.transformations.next();
if (transformation.getMatcher().matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)) {
transformers = transformation.getTransformers().iterator();
}
}
}
/**
* {@inheritDoc}
*/
public boolean hasNext() {
return transformers.hasNext();
}
/**
* {@inheritDoc}
*/
public Transformer next() {
try {
return transformers.next();
} finally {
while (!transformers.hasNext() && transformations.hasNext()) {
Transformation transformation = transformations.next();
if (transformation.getMatcher().matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)) {
transformers = transformation.getTransformers().iterator();
}
}
}
}
/**
* {@inheritDoc}
*/
public void remove() {
throw new UnsupportedOperationException("remove");
}
}
}
/**
* A {@link java.lang.instrument.ClassFileTransformer} that implements the enclosing agent builder's
* configuration.
*/
protected static class ExecutingTransformer extends ResettableClassFileTransformer.AbstractBase {
/**
* A factory for creating a {@link ClassFileTransformer} that supports the features of the current VM.
*/
protected static final Factory FACTORY = AccessController.doPrivileged(Factory.CreationAction.INSTANCE);
/**
* The Byte Buddy instance to be used.
*/
private final ByteBuddy byteBuddy;
/**
* The type locator to use.
*/
private final PoolStrategy poolStrategy;
/**
* The definition handler to use.
*/
private final TypeStrategy typeStrategy;
/**
* The listener to notify on transformations.
*/
private final Listener listener;
/**
* The native method strategy to apply.
*/
private final NativeMethodStrategy nativeMethodStrategy;
/**
* The initialization strategy to use for transformed types.
*/
private final InitializationStrategy initializationStrategy;
/**
* The injection strategy to use.
*/
private final InjectionStrategy injectionStrategy;
/**
* The lambda instrumentation strategy to use.
*/
private final LambdaInstrumentationStrategy lambdaInstrumentationStrategy;
/**
* The description strategy for resolving type descriptions for types.
*/
private final DescriptionStrategy descriptionStrategy;
/**
* The location strategy to use.
*/
private final LocationStrategy locationStrategy;
/**
* The fallback strategy to use.
*/
private final FallbackStrategy fallbackStrategy;
/**
* The class file buffer strategy to use.
*/
private final ClassFileBufferStrategy classFileBufferStrategy;
/**
* The installation listener to notify.
*/
private final InstallationListener installationListener;
/**
* Identifies types that should not be instrumented.
*/
private final RawMatcher ignoreMatcher;
/**
* The transformations to apply on non-ignored types.
*/
private final List<Transformation> transformations;
/**
* A lock that prevents circular class transformations.
*/
private final CircularityLock circularityLock;
/**
* The access control context to use for loading classes.
*/
private final AccessControlContext accessControlContext;
/**
* Creates a new class file transformer.
*
* @param byteBuddy The Byte Buddy instance to be used.
* @param listener The listener to notify on transformations.
* @param poolStrategy The type locator to use.
* @param typeStrategy The definition handler to use.
* @param locationStrategy The location strategy to use.
* @param nativeMethodStrategy The native method strategy to apply.
* @param initializationStrategy The initialization strategy to use for transformed types.
* @param injectionStrategy The injection strategy to use.
* @param lambdaInstrumentationStrategy The lambda instrumentation strategy to use.
* @param descriptionStrategy The description strategy for resolving type descriptions for types.
* @param fallbackStrategy The fallback strategy to use.
* @param installationListener The installation listener to notify.
* @param classFileBufferStrategy The class file buffer strategy to use.
* @param ignoreMatcher Identifies types that should not be instrumented.
* @param transformations The transformations to apply on non-ignored types.
* @param circularityLock The circularity lock to use.
*/
public ExecutingTransformer(ByteBuddy byteBuddy,
Listener listener,
PoolStrategy poolStrategy,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
NativeMethodStrategy nativeMethodStrategy,
InitializationStrategy initializationStrategy,
InjectionStrategy injectionStrategy,
LambdaInstrumentationStrategy lambdaInstrumentationStrategy,
DescriptionStrategy descriptionStrategy,
FallbackStrategy fallbackStrategy,
ClassFileBufferStrategy classFileBufferStrategy,
InstallationListener installationListener,
RawMatcher ignoreMatcher,
List<Transformation> transformations,
CircularityLock circularityLock) {
this.byteBuddy = byteBuddy;
this.typeStrategy = typeStrategy;
this.poolStrategy = poolStrategy;
this.locationStrategy = locationStrategy;
this.listener = listener;
this.nativeMethodStrategy = nativeMethodStrategy;
this.initializationStrategy = initializationStrategy;
this.injectionStrategy = injectionStrategy;
this.lambdaInstrumentationStrategy = lambdaInstrumentationStrategy;
this.descriptionStrategy = descriptionStrategy;
this.fallbackStrategy = fallbackStrategy;
this.classFileBufferStrategy = classFileBufferStrategy;
this.installationListener = installationListener;
this.ignoreMatcher = ignoreMatcher;
this.transformations = transformations;
this.circularityLock = circularityLock;
accessControlContext = AccessController.getContext();
}
/**
* {@inheritDoc}
*/
public byte[] transform(ClassLoader classLoader,
String internalTypeName,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] binaryRepresentation) {
if (circularityLock.acquire()) {
try {
return AccessController.doPrivileged(new LegacyVmDispatcher(classLoader,
internalTypeName,
classBeingRedefined,
protectionDomain,
binaryRepresentation), accessControlContext);
} finally {
circularityLock.release();
}
} else {
return NO_TRANSFORMATION;
}
}
/**
* Applies a transformation for a class that was captured by this {@link ClassFileTransformer}. Invoking this method
* allows to process module information which is available since Java 9.
*
* @param rawModule The instrumented class's Java {@code java.lang.Module}.
* @param classLoader The type's class loader or {@code null} if the type is loaded by the bootstrap loader.
* @param internalTypeName The internal name of the instrumented class.
* @param classBeingRedefined The loaded {@link Class} being redefined or {@code null} if no such class exists.
* @param protectionDomain The instrumented type's protection domain.
* @param binaryRepresentation The class file of the instrumented class in its current state.
* @return The transformed class file or an empty byte array if this transformer does not apply an instrumentation.
*/
protected byte[] transform(Object rawModule,
ClassLoader classLoader,
String internalTypeName,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] binaryRepresentation) {
if (circularityLock.acquire()) {
try {
return AccessController.doPrivileged(new Java9CapableVmDispatcher(rawModule,
classLoader,
internalTypeName,
classBeingRedefined,
protectionDomain,
binaryRepresentation), accessControlContext);
} finally {
circularityLock.release();
}
} else {
return NO_TRANSFORMATION;
}
}
/**
* Applies a transformation for a class that was captured by this {@link ClassFileTransformer}.
*
* @param module The instrumented class's Java module in its wrapped form or {@code null} if the current VM does not support modules.
* @param classLoader The instrumented class's class loader.
* @param internalTypeName The internal name of the instrumented class.
* @param classBeingRedefined The loaded {@link Class} being redefined or {@code null} if no such class exists.
* @param protectionDomain The instrumented type's protection domain.
* @param binaryRepresentation The class file of the instrumented class in its current state.
* @return The transformed class file or an empty byte array if this transformer does not apply an instrumentation.
*/
private byte[] transform(JavaModule module,
ClassLoader classLoader,
String internalTypeName,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] binaryRepresentation) {
if (internalTypeName == null || !lambdaInstrumentationStrategy.isInstrumented(classBeingRedefined)) {
return NO_TRANSFORMATION;
}
String typeName = internalTypeName.replace('/', '.');
try {
listener.onDiscovery(typeName, classLoader, module, classBeingRedefined != null);
ClassFileLocator classFileLocator = new ClassFileLocator.Compound(classFileBufferStrategy.resolve(typeName,
binaryRepresentation,
classLoader,
module,
protectionDomain), locationStrategy.classFileLocator(classLoader, module));
TypePool typePool = poolStrategy.typePool(classFileLocator, classLoader);
try {
return doTransform(module, classLoader, typeName, classBeingRedefined, classBeingRedefined != null, protectionDomain, typePool, classFileLocator);
} catch (Throwable throwable) {
if (classBeingRedefined != null && descriptionStrategy.isLoadedFirst() && fallbackStrategy.isFallback(classBeingRedefined, throwable)) {
return doTransform(module, classLoader, typeName, NO_LOADED_TYPE, Listener.LOADED, protectionDomain, typePool, classFileLocator);
} else {
throw throwable;
}
}
} catch (Throwable throwable) {
listener.onError(typeName, classLoader, module, classBeingRedefined != null, throwable);
return NO_TRANSFORMATION;
} finally {
listener.onComplete(typeName, classLoader, module, classBeingRedefined != null);
}
}
/**
* Applies a transformation for a class that was captured by this {@link ClassFileTransformer}.
*
* @param module The instrumented class's Java module in its wrapped form or {@code null} if the current VM does not support modules.
* @param classLoader The instrumented class's class loader.
* @param typeName The binary name of the instrumented class.
* @param classBeingRedefined The loaded {@link Class} being redefined or {@code null} if no such class exists.
* @param loaded {@code true} if the instrumented type is loaded.
* @param protectionDomain The instrumented type's protection domain.
* @param typePool The type pool to use.
* @param classFileLocator The class file locator to use.
* @return The transformed class file or an empty byte array if this transformer does not apply an instrumentation.
*/
private byte[] doTransform(JavaModule module,
ClassLoader classLoader,
String typeName,
Class<?> classBeingRedefined,
boolean loaded,
ProtectionDomain protectionDomain,
TypePool typePool,
ClassFileLocator classFileLocator) {
TypeDescription typeDescription = descriptionStrategy.apply(typeName, classBeingRedefined, typePool, circularityLock, classLoader, module);
if (ignoreMatcher.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)) {
listener.onIgnored(typeDescription, classLoader, module, loaded);
return Transformation.NONE;
}
List<Transformer> transformers = new ArrayList<Transformer>();
for (Transformation transformation : transformations) {
if (transformation.getMatcher().matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)) {
transformers.addAll(transformation.getTransformers());
if (transformation.isTerminal()) {
break;
}
}
}
if (transformers.isEmpty()) {
listener.onIgnored(typeDescription, classLoader, module, loaded);
return Transformation.NONE;
}
DynamicType.Builder<?> builder = typeStrategy.builder(typeDescription,
byteBuddy,
classFileLocator,
nativeMethodStrategy.resolve(),
classLoader,
module,
protectionDomain);
InitializationStrategy.Dispatcher dispatcher = initializationStrategy.dispatcher();
for (Transformer transformer : transformers) {
builder = transformer.transform(builder, typeDescription, classLoader, module);
}
DynamicType.Unloaded<?> dynamicType = dispatcher.apply(builder).make(TypeResolutionStrategy.Disabled.INSTANCE, typePool);
dispatcher.register(dynamicType, classLoader, protectionDomain, injectionStrategy);
listener.onTransformation(typeDescription, classLoader, module, loaded, dynamicType);
return dynamicType.getBytes();
}
/**
* {@inheritDoc}
*/
public Iterator<Transformer> iterator(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return ignoreMatcher.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)
? Collections.<Transformer>emptySet().iterator()
: new Transformation.TransformerIterator(typeDescription, classLoader, module, classBeingRedefined, protectionDomain, transformations);
}
/**
* {@inheritDoc}
*/
public synchronized boolean reset(Instrumentation instrumentation,
ResettableClassFileTransformer classFileTransformer,
RedefinitionStrategy redefinitionStrategy,
RedefinitionStrategy.DiscoveryStrategy redefinitionDiscoveryStrategy,
RedefinitionStrategy.BatchAllocator redefinitionBatchAllocator,
RedefinitionStrategy.Listener redefinitionListener) {
if (instrumentation.removeTransformer(classFileTransformer)) {
redefinitionStrategy.apply(instrumentation,
Listener.NoOp.INSTANCE,
CircularityLock.Inactive.INSTANCE,
poolStrategy,
locationStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
new Transformation.SimpleMatcher(ignoreMatcher, transformations));
installationListener.onReset(instrumentation, classFileTransformer);
return true;
} else {
return false;
}
}
/* does not implement hashCode and equals in order to align with identity treatment of the JVM */
/**
* A factory for creating a {@link ClassFileTransformer} for the current VM.
*/
protected interface Factory {
/**
* Creates a new class file transformer for the current VM.
*
* @param byteBuddy The Byte Buddy instance to be used.
* @param listener The listener to notify on transformations.
* @param poolStrategy The type locator to use.
* @param typeStrategy The definition handler to use.
* @param locationStrategy The location strategy to use.
* @param nativeMethodStrategy The native method strategy to apply.
* @param initializationStrategy The initialization strategy to use for transformed types.
* @param injectionStrategy The injection strategy to use.
* @param lambdaInstrumentationStrategy The lambda instrumentation strategy to use.
* @param descriptionStrategy The description strategy for resolving type descriptions for types.
* @param fallbackStrategy The fallback strategy to use.
* @param classFileBufferStrategy The class file buffer strategy to use.
* @param installationListener The installation listener to notify.
* @param ignoreMatcher Identifies types that should not be instrumented.
* @param transformations The transformations to apply on non-ignored types.
* @param circularityLock The circularity lock to use.
* @return A class file transformer for the current VM that supports the API of the current VM.
*/
ResettableClassFileTransformer make(ByteBuddy byteBuddy,
Listener listener,
PoolStrategy poolStrategy,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
NativeMethodStrategy nativeMethodStrategy,
InitializationStrategy initializationStrategy,
InjectionStrategy injectionStrategy,
LambdaInstrumentationStrategy lambdaInstrumentationStrategy,
DescriptionStrategy descriptionStrategy,
FallbackStrategy fallbackStrategy,
ClassFileBufferStrategy classFileBufferStrategy,
InstallationListener installationListener,
RawMatcher ignoreMatcher,
List<Transformation> transformations,
CircularityLock circularityLock);
/**
* An action to create an implementation of {@link ExecutingTransformer} that support Java 9 modules.
*/
enum CreationAction implements PrivilegedAction<Factory> {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Exception should not be rethrown but trigger a fallback")
public Factory run() {
try {
return new Factory.ForJava9CapableVm(new ByteBuddy()
.with(TypeValidation.DISABLED)
.subclass(ExecutingTransformer.class)
.name(ExecutingTransformer.class.getName() + "$ByteBuddy$ModuleSupport")
.method(named("transform").and(takesArgument(0, JavaType.MODULE.load())))
.intercept(MethodCall.invoke(ExecutingTransformer.class.getDeclaredMethod("transform",
Object.class,
ClassLoader.class,
String.class,
Class.class,
ProtectionDomain.class,
byte[].class)).onSuper().withAllArguments())
.make()
.load(ExecutingTransformer.class.getClassLoader(),
ClassLoadingStrategy.Default.WRAPPER_PERSISTENT.with(ExecutingTransformer.class.getProtectionDomain()))
.getLoaded()
.getDeclaredConstructor(ByteBuddy.class,
Listener.class,
PoolStrategy.class,
TypeStrategy.class,
LocationStrategy.class,
NativeMethodStrategy.class,
InitializationStrategy.class,
InjectionStrategy.class,
LambdaInstrumentationStrategy.class,
DescriptionStrategy.class,
FallbackStrategy.class,
ClassFileBufferStrategy.class,
InstallationListener.class,
RawMatcher.class,
List.class,
CircularityLock.class));
} catch (Exception ignored) {
return Factory.ForLegacyVm.INSTANCE;
}
}
}
/**
* A factory for a class file transformer on a JVM that supports the {@code java.lang.Module} API to override
* the newly added method of the {@link ClassFileTransformer} to capture an instrumented class's module.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForJava9CapableVm implements Factory {
/**
* A constructor for creating a {@link ClassFileTransformer} that overrides the newly added method for extracting
* the {@code java.lang.Module} of an instrumented class.
*/
private final Constructor<? extends ResettableClassFileTransformer> executingTransformer;
/**
* Creates a class file transformer factory for a Java 9 capable VM.
*
* @param executingTransformer A constructor for creating a {@link ClassFileTransformer} that overrides the newly added
* method for extracting the {@code java.lang.Module} of an instrumented class.
*/
protected ForJava9CapableVm(Constructor<? extends ResettableClassFileTransformer> executingTransformer) {
this.executingTransformer = executingTransformer;
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer make(ByteBuddy byteBuddy,
Listener listener,
PoolStrategy poolStrategy,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
NativeMethodStrategy nativeMethodStrategy,
InitializationStrategy initializationStrategy,
InjectionStrategy injectionStrategy,
LambdaInstrumentationStrategy lambdaInstrumentationStrategy,
DescriptionStrategy descriptionStrategy,
FallbackStrategy fallbackStrategy,
ClassFileBufferStrategy classFileBufferStrategy,
InstallationListener installationListener,
RawMatcher ignoreMatcher,
List<Transformation> transformations,
CircularityLock circularityLock) {
try {
return executingTransformer.newInstance(byteBuddy,
listener,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
initializationStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations,
circularityLock);
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Cannot access " + executingTransformer, exception);
} catch (InstantiationException exception) {
throw new IllegalStateException("Cannot instantiate " + executingTransformer.getDeclaringClass(), exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException("Cannot invoke " + executingTransformer, exception.getCause());
}
}
}
/**
* A factory for a {@link ClassFileTransformer} on a VM that does not support the {@code java.lang.Module} API.
*/
enum ForLegacyVm implements Factory {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer make(ByteBuddy byteBuddy,
Listener listener,
PoolStrategy poolStrategy,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
NativeMethodStrategy nativeMethodStrategy,
InitializationStrategy initializationStrategy,
InjectionStrategy injectionStrategy,
LambdaInstrumentationStrategy lambdaInstrumentationStrategy,
DescriptionStrategy descriptionStrategy,
FallbackStrategy fallbackStrategy,
ClassFileBufferStrategy classFileBufferStrategy,
InstallationListener installationListener,
RawMatcher ignoreMatcher,
List<Transformation> transformations,
CircularityLock circularityLock) {
return new ExecutingTransformer(byteBuddy,
listener,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
initializationStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations,
circularityLock);
}
}
}
/**
* A privileged action for transforming a class on a JVM prior to Java 9.
*/
@HashCodeAndEqualsPlugin.Enhance(includeSyntheticFields = true)
protected class LegacyVmDispatcher implements PrivilegedAction<byte[]> {
/**
* The type's class loader or {@code null} if the bootstrap class loader is represented.
*/
private final ClassLoader classLoader;
/**
* The type's internal name or {@code null} if no such name exists.
*/
private final String internalTypeName;
/**
* The class being redefined or {@code null} if no such class exists.
*/
private final Class<?> classBeingRedefined;
/**
* The type's protection domain.
*/
private final ProtectionDomain protectionDomain;
/**
* The type's binary representation.
*/
private final byte[] binaryRepresentation;
/**
* Creates a new type transformation dispatcher.
*
* @param classLoader The type's class loader or {@code null} if the bootstrap class loader is represented.
* @param internalTypeName The type's internal name or {@code null} if no such name exists.
* @param classBeingRedefined The class being redefined or {@code null} if no such class exists.
* @param protectionDomain The type's protection domain.
* @param binaryRepresentation The type's binary representation.
*/
protected LegacyVmDispatcher(ClassLoader classLoader,
String internalTypeName,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] binaryRepresentation) {
this.classLoader = classLoader;
this.internalTypeName = internalTypeName;
this.classBeingRedefined = classBeingRedefined;
this.protectionDomain = protectionDomain;
this.binaryRepresentation = binaryRepresentation;
}
/**
* {@inheritDoc}
*/
public byte[] run() {
return transform(JavaModule.UNSUPPORTED,
classLoader,
internalTypeName,
classBeingRedefined,
protectionDomain,
binaryRepresentation);
}
}
/**
* A privileged action for transforming a class on a JVM that supports modules.
*/
@HashCodeAndEqualsPlugin.Enhance(includeSyntheticFields = true)
protected class Java9CapableVmDispatcher implements PrivilegedAction<byte[]> {
/**
* The type's {@code java.lang.Module}.
*/
private final Object rawModule;
/**
* The type's class loader or {@code null} if the type is loaded by the bootstrap loader.
*/
private final ClassLoader classLoader;
/**
* The type's internal name or {@code null} if no such name exists.
*/
private final String internalTypeName;
/**
* The class being redefined or {@code null} if no such class exists.
*/
private final Class<?> classBeingRedefined;
/**
* The type's protection domain.
*/
private final ProtectionDomain protectionDomain;
/**
* The type's binary representation.
*/
private final byte[] binaryRepresentation;
/**
* Creates a new legacy dispatcher.
*
* @param rawModule The type's {@code java.lang.Module}.
* @param classLoader The type's class loader or {@code null} if the type is loaded by the bootstrap loader.
* @param internalTypeName The type's internal name or {@code null} if no such name exists.
* @param classBeingRedefined The class being redefined or {@code null} if no such class exists.
* @param protectionDomain The type's protection domain.
* @param binaryRepresentation The type's binary representation.
*/
protected Java9CapableVmDispatcher(Object rawModule,
ClassLoader classLoader,
String internalTypeName,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] binaryRepresentation) {
this.rawModule = rawModule;
this.classLoader = classLoader;
this.internalTypeName = internalTypeName;
this.classBeingRedefined = classBeingRedefined;
this.protectionDomain = protectionDomain;
this.binaryRepresentation = binaryRepresentation;
}
/**
* {@inheritDoc}
*/
public byte[] run() {
return transform(JavaModule.of(rawModule),
classLoader,
internalTypeName,
classBeingRedefined,
protectionDomain,
binaryRepresentation);
}
}
}
/**
* An abstract implementation of an agent builder that delegates all invocation to another instance.
*
* @param <T> The type that is produced by chaining a matcher.
*/
protected abstract class Delegator<T extends Matchable<T>> extends Matchable.AbstractBase<T> implements AgentBuilder {
/**
* Materializes the currently described {@link net.bytebuddy.agent.builder.AgentBuilder}.
*
* @return An agent builder that represents the currently described entry of this instance.
*/
protected abstract AgentBuilder materialize();
/**
* {@inheritDoc}
*/
public AgentBuilder with(ByteBuddy byteBuddy) {
return materialize().with(byteBuddy);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(Listener listener) {
return materialize().with(listener);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(CircularityLock circularityLock) {
return materialize().with(circularityLock);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(TypeStrategy typeStrategy) {
return materialize().with(typeStrategy);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(PoolStrategy poolStrategy) {
return materialize().with(poolStrategy);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(LocationStrategy locationStrategy) {
return materialize().with(locationStrategy);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(InitializationStrategy initializationStrategy) {
return materialize().with(initializationStrategy);
}
/**
* {@inheritDoc}
*/
public RedefinitionListenable.WithoutBatchStrategy with(RedefinitionStrategy redefinitionStrategy) {
return materialize().with(redefinitionStrategy);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(LambdaInstrumentationStrategy lambdaInstrumentationStrategy) {
return materialize().with(lambdaInstrumentationStrategy);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(DescriptionStrategy descriptionStrategy) {
return materialize().with(descriptionStrategy);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(FallbackStrategy fallbackStrategy) {
return materialize().with(fallbackStrategy);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(ClassFileBufferStrategy classFileBufferStrategy) {
return materialize().with(classFileBufferStrategy);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(InstallationListener installationListener) {
return materialize().with(installationListener);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(InjectionStrategy injectionStrategy) {
return materialize().with(injectionStrategy);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(TransformerDecorator transformerDecorator) {
return materialize().with(transformerDecorator);
}
/**
* {@inheritDoc}
*/
public AgentBuilder enableNativeMethodPrefix(String prefix) {
return materialize().enableNativeMethodPrefix(prefix);
}
/**
* {@inheritDoc}
*/
public AgentBuilder disableNativeMethodPrefix() {
return materialize().disableNativeMethodPrefix();
}
/**
* {@inheritDoc}
*/
public AgentBuilder disableClassFormatChanges() {
return materialize().disableClassFormatChanges();
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Class<?>... type) {
return materialize().assureReadEdgeTo(instrumentation, type);
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, JavaModule... module) {
return materialize().assureReadEdgeTo(instrumentation, module);
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules) {
return materialize().assureReadEdgeTo(instrumentation, modules);
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Class<?>... type) {
return materialize().assureReadEdgeFromAndTo(instrumentation, type);
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, JavaModule... module) {
return materialize().assureReadEdgeFromAndTo(instrumentation, module);
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules) {
return materialize().assureReadEdgeFromAndTo(instrumentation, modules);
}
/**
* {@inheritDoc}
*/
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher) {
return materialize().type(typeMatcher);
}
/**
* {@inheritDoc}
*/
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) {
return materialize().type(typeMatcher, classLoaderMatcher);
}
/**
* {@inheritDoc}
*/
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return materialize().type(typeMatcher, classLoaderMatcher, moduleMatcher);
}
/**
* {@inheritDoc}
*/
public Identified.Narrowable type(RawMatcher matcher) {
return materialize().type(matcher);
}
/**
* {@inheritDoc}
*/
public Ignored ignore(ElementMatcher<? super TypeDescription> ignoredTypes) {
return materialize().ignore(ignoredTypes);
}
/**
* {@inheritDoc}
*/
public Ignored ignore(ElementMatcher<? super TypeDescription> ignoredTypes, ElementMatcher<? super ClassLoader> ignoredClassLoaders) {
return materialize().ignore(ignoredTypes, ignoredClassLoaders);
}
/**
* {@inheritDoc}
*/
public Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return materialize().ignore(typeMatcher, classLoaderMatcher, moduleMatcher);
}
/**
* {@inheritDoc}
*/
public Ignored ignore(RawMatcher rawMatcher) {
return materialize().ignore(rawMatcher);
}
/**
* {@inheritDoc}
*/
public ClassFileTransformer makeRaw() {
return materialize().makeRaw();
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer installOn(Instrumentation instrumentation) {
return materialize().installOn(instrumentation);
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer installOnByteBuddyAgent() {
return materialize().installOnByteBuddyAgent();
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer patchOn(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
return materialize().patchOn(instrumentation, classFileTransformer);
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer patchOnByteBuddyAgent(ResettableClassFileTransformer classFileTransformer) {
return materialize().patchOnByteBuddyAgent(classFileTransformer);
}
}
/**
* A delegator transformer for further precising what types to ignore.
*/
@HashCodeAndEqualsPlugin.Enhance(includeSyntheticFields = true)
protected class Ignoring extends Delegator<Ignored> implements Ignored {
/**
* A matcher for identifying types that should not be instrumented.
*/
private final RawMatcher rawMatcher;
/**
* Creates a new agent builder for further specifying what types to ignore.
*
* @param rawMatcher A matcher for identifying types that should not be instrumented.
*/
protected Ignoring(RawMatcher rawMatcher) {
this.rawMatcher = rawMatcher;
}
@Override
protected AgentBuilder materialize() {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
rawMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public Ignored and(RawMatcher rawMatcher) {
return new Ignoring(new RawMatcher.Conjunction(this.rawMatcher, rawMatcher));
}
/**
* {@inheritDoc}
*/
public Ignored or(RawMatcher rawMatcher) {
return new Ignoring(new RawMatcher.Disjunction(this.rawMatcher, rawMatcher));
}
}
/**
* An implementation of a default agent builder that allows for refinement of the redefinition strategy.
*/
protected static class Redefining extends Default implements RedefinitionListenable.WithoutBatchStrategy {
/**
* Creates a new default agent builder that allows for refinement of the redefinition strategy.
*
* @param byteBuddy The Byte Buddy instance to be used.
* @param listener The listener to notify on transformations.
* @param circularityLock The circularity lock to use.
* @param poolStrategy The type locator to use.
* @param typeStrategy The definition handler to use.
* @param locationStrategy The location strategy to use.
* @param nativeMethodStrategy The native method strategy to apply.
* @param transformerDecorator A decorator to wrap the created class file transformer.
* @param initializationStrategy The initialization strategy to use for transformed types.
* @param redefinitionStrategy The redefinition strategy to apply.
* @param redefinitionDiscoveryStrategy The discovery strategy for loaded types to be redefined.
* @param redefinitionBatchAllocator The batch allocator for the redefinition strategy to apply.
* @param redefinitionListener The redefinition listener for the redefinition strategy to apply.
* @param redefinitionResubmissionStrategy The resubmission strategy to apply.
* @param injectionStrategy The injection strategy to use.
* @param lambdaInstrumentationStrategy A strategy to determine of the {@code LambdaMetafactory} should be instrumented to allow for the
* instrumentation of classes that represent lambda expressions.
* @param descriptionStrategy The description strategy for resolving type descriptions for types.
* @param fallbackStrategy The fallback strategy to apply.
* @param classFileBufferStrategy The class file buffer strategy to use.
* @param installationListener The installation listener to notify.
* @param ignoreMatcher Identifies types that should not be instrumented.
* @param transformations The transformations to apply on non-ignored types.
*/
protected Redefining(ByteBuddy byteBuddy,
Listener listener,
CircularityLock circularityLock,
PoolStrategy poolStrategy,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
NativeMethodStrategy nativeMethodStrategy,
TransformerDecorator transformerDecorator,
InitializationStrategy initializationStrategy,
RedefinitionStrategy redefinitionStrategy,
RedefinitionStrategy.DiscoveryStrategy redefinitionDiscoveryStrategy,
RedefinitionStrategy.BatchAllocator redefinitionBatchAllocator,
RedefinitionStrategy.Listener redefinitionListener,
RedefinitionStrategy.ResubmissionStrategy redefinitionResubmissionStrategy,
InjectionStrategy injectionStrategy,
LambdaInstrumentationStrategy lambdaInstrumentationStrategy,
DescriptionStrategy descriptionStrategy,
FallbackStrategy fallbackStrategy,
ClassFileBufferStrategy classFileBufferStrategy,
InstallationListener installationListener,
RawMatcher ignoreMatcher,
List<Transformation> transformations) {
super(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public WithImplicitDiscoveryStrategy with(RedefinitionStrategy.BatchAllocator redefinitionBatchAllocator) {
if (!redefinitionStrategy.isEnabled()) {
throw new IllegalStateException("Cannot set redefinition batch allocator when redefinition is disabled");
}
return new Redefining(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public RedefinitionListenable redefineOnly(Class<?>... type) {
return with(new RedefinitionStrategy.DiscoveryStrategy.Explicit(type));
}
/**
* {@inheritDoc}
*/
public RedefinitionListenable with(RedefinitionStrategy.DiscoveryStrategy redefinitionDiscoveryStrategy) {
if (!redefinitionStrategy.isEnabled()) {
throw new IllegalStateException("Cannot set redefinition discovery strategy when redefinition is disabled");
}
return new Redefining(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public RedefinitionListenable with(RedefinitionStrategy.Listener redefinitionListener) {
if (!redefinitionStrategy.isEnabled()) {
throw new IllegalStateException("Cannot set redefinition listener when redefinition is disabled");
}
return new Redefining(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
new RedefinitionStrategy.Listener.Compound(this.redefinitionListener, redefinitionListener),
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder withResubmission(RedefinitionStrategy.ResubmissionScheduler resubmissionScheduler) {
return withResubmission(resubmissionScheduler, any());
}
/**
* {@inheritDoc}
*/
public AgentBuilder withResubmission(RedefinitionStrategy.ResubmissionScheduler resubmissionScheduler, ElementMatcher<? super Throwable> matcher) {
if (!redefinitionStrategy.isEnabled()) {
throw new IllegalStateException("Cannot enable redefinition resubmission when redefinition is disabled");
}
return new Redefining(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
new RedefinitionStrategy.ResubmissionStrategy.Enabled(resubmissionScheduler, matcher),
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
}
/**
* A helper class that describes a {@link net.bytebuddy.agent.builder.AgentBuilder.Default} after supplying
* a {@link net.bytebuddy.agent.builder.AgentBuilder.RawMatcher} such that one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s can be supplied.
*/
@HashCodeAndEqualsPlugin.Enhance(includeSyntheticFields = true)
protected class Transforming extends Delegator<Identified.Narrowable> implements Identified.Extendable, Identified.Narrowable {
/**
* The supplied raw matcher.
*/
private final RawMatcher rawMatcher;
/**
* The supplied transformer.
*/
private final List<Transformer> transformers;
/**
* {@code true} if this transformer is a terminal transformation.
*/
private final boolean terminal;
/**
* Creates a new matched default agent builder.
*
* @param rawMatcher The supplied raw matcher.
* @param transformers The transformers to apply.
* @param terminal {@code true} if this transformer is a terminal transformation.
*/
protected Transforming(RawMatcher rawMatcher, List<Transformer> transformers, boolean terminal) {
this.rawMatcher = rawMatcher;
this.transformers = transformers;
this.terminal = terminal;
}
@Override
protected AgentBuilder materialize() {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
CompoundList.of(transformations, new Transformation(rawMatcher, transformers, terminal)));
}
/**
* {@inheritDoc}
*/
public Identified.Extendable transform(Transformer transformer) {
return new Transforming(rawMatcher, CompoundList.of(this.transformers, transformer), terminal);
}
/**
* {@inheritDoc}
*/
public AgentBuilder asTerminalTransformation() {
return new Transforming(rawMatcher, transformers, true);
}
/**
* {@inheritDoc}
*/
public Narrowable and(RawMatcher rawMatcher) {
return new Transforming(new RawMatcher.Conjunction(this.rawMatcher, rawMatcher), transformers, terminal);
}
/**
* {@inheritDoc}
*/
public Narrowable or(RawMatcher rawMatcher) {
return new Transforming(new RawMatcher.Disjunction(this.rawMatcher, rawMatcher), transformers, terminal);
}
}
}
}
| byte-buddy-dep/src/main/java/net/bytebuddy/agent/builder/AgentBuilder.java | /*
* Copyright 2014 - 2019 Rafael Winterhalter
*
* 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 net.bytebuddy.agent.builder;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.ClassFileVersion;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.asm.AsmVisitorWrapper;
import net.bytebuddy.build.EntryPoint;
import net.bytebuddy.build.HashCodeAndEqualsPlugin;
import net.bytebuddy.build.Plugin;
import net.bytebuddy.description.field.FieldDescription;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.method.ParameterDescription;
import net.bytebuddy.description.modifier.*;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.*;
import net.bytebuddy.dynamic.loading.ClassInjector;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.dynamic.scaffold.InstrumentedType;
import net.bytebuddy.dynamic.scaffold.TypeValidation;
import net.bytebuddy.dynamic.scaffold.inline.MethodNameTransformer;
import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
import net.bytebuddy.implementation.ExceptionMethod;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.implementation.LoadedTypeInitializer;
import net.bytebuddy.implementation.MethodCall;
import net.bytebuddy.implementation.auxiliary.AuxiliaryType;
import net.bytebuddy.implementation.bytecode.ByteCodeAppender;
import net.bytebuddy.implementation.bytecode.Duplication;
import net.bytebuddy.implementation.bytecode.StackManipulation;
import net.bytebuddy.implementation.bytecode.TypeCreation;
import net.bytebuddy.implementation.bytecode.assign.Assigner;
import net.bytebuddy.implementation.bytecode.assign.TypeCasting;
import net.bytebuddy.implementation.bytecode.collection.ArrayFactory;
import net.bytebuddy.implementation.bytecode.constant.ClassConstant;
import net.bytebuddy.implementation.bytecode.constant.IntegerConstant;
import net.bytebuddy.implementation.bytecode.constant.TextConstant;
import net.bytebuddy.implementation.bytecode.member.FieldAccess;
import net.bytebuddy.implementation.bytecode.member.MethodInvocation;
import net.bytebuddy.implementation.bytecode.member.MethodReturn;
import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.matcher.LatentMatcher;
import net.bytebuddy.pool.TypePool;
import net.bytebuddy.utility.CompoundList;
import net.bytebuddy.utility.JavaConstant;
import net.bytebuddy.utility.JavaModule;
import net.bytebuddy.utility.JavaType;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import java.io.*;
import java.lang.instrument.ClassDefinition;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static net.bytebuddy.matcher.ElementMatchers.*;
/**
* <p>
* An agent builder provides a convenience API for defining a
* <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/instrument/package-summary.html">Java agent</a>. By default,
* this transformation is applied by rebasing the type if not specified otherwise by setting a
* {@link TypeStrategy}.
* </p>
* <p>
* When defining several {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s, the agent builder always
* applies the transformers that were supplied with the last applicable matcher. Therefore, more general transformers
* should be defined first.
* </p>
* <p>
* <b>Note</b>: Any transformation is performed using the {@link AccessControlContext} of an agent's creator.
* </p>
* <p>
* <b>Important</b>: Types that implement lambda expressions (functional interfaces) are not instrumented by default but
* only when enabling the builder's {@link LambdaInstrumentationStrategy}.
* </p>
*/
public interface AgentBuilder {
/**
* Defines the given {@link net.bytebuddy.ByteBuddy} instance to be used by the created agent.
*
* @param byteBuddy The Byte Buddy instance to be used.
* @return A new instance of this agent builder which makes use of the given {@code byteBuddy} instance.
*/
AgentBuilder with(ByteBuddy byteBuddy);
/**
* Defines the given {@link net.bytebuddy.agent.builder.AgentBuilder.Listener} to be notified by the created agent.
* The given listener is notified after any other listener that is already registered. If a listener is registered
* twice, it is also notified twice.
*
* @param listener The listener to be notified.
* @return A new instance of this agent builder which creates an agent that informs the given listener about
* events.
*/
AgentBuilder with(Listener listener);
/**
* Defines a circularity lock that is acquired upon executing code that potentially loads new classes. While the
* lock is acquired, any class file transformer refrains from transforming any classes. By default, all created
* agents use a shared {@link CircularityLock} to avoid that any classes that are required to execute an agent
* causes a {@link ClassCircularityError}.
*
* @param circularityLock The circularity lock to use.
* @return A new instance of this agent builder which creates an agent that uses the supplied circularity lock.
*/
AgentBuilder with(CircularityLock circularityLock);
/**
* Defines the use of the given type locator for locating a {@link TypeDescription} for an instrumented type.
*
* @param poolStrategy The type locator to use.
* @return A new instance of this agent builder which uses the given type locator for looking up class files.
*/
AgentBuilder with(PoolStrategy poolStrategy);
/**
* Defines the use of the given location strategy for locating binary data to given class names.
*
* @param locationStrategy The location strategy to use.
* @return A new instance of this agent builder which uses the given location strategy for looking up class files.
*/
AgentBuilder with(LocationStrategy locationStrategy);
/**
* Defines how types should be transformed, e.g. if they should be rebased or redefined by the created agent.
*
* @param typeStrategy The type strategy to use.
* @return A new instance of this agent builder which uses the given type strategy.
*/
AgentBuilder with(TypeStrategy typeStrategy);
/**
* Defines a given initialization strategy to be applied to generated types. An initialization strategy is responsible
* for setting up a type after it was loaded. This initialization must be performed after the transformation because
* a Java agent is only invoked before loading a type. By default, the initialization logic is added to a class's type
* initializer which queries a global object for any objects that are to be injected into the generated type.
*
* @param initializationStrategy The initialization strategy to use.
* @return A new instance of this agent builder that applies the given initialization strategy.
*/
AgentBuilder with(InitializationStrategy initializationStrategy);
/**
* <p>
* Specifies a strategy for modifying types that were already loaded prior to the installation of this transformer.
* </p>
* <p>
* <b>Note</b>: Defining a redefinition strategy resets any refinements of a previously set redefinition strategy.
* </p>
* <p>
* <b>Important</b>: Most JVMs do not support changes of a class's structure after a class was already
* loaded. Therefore, it is typically required that this class file transformer was built while enabling
* {@link AgentBuilder#disableClassFormatChanges()}.
* </p>
*
* @param redefinitionStrategy The redefinition strategy to apply.
* @return A new instance of this agent builder that applies the given redefinition strategy.
*/
RedefinitionListenable.WithoutBatchStrategy with(RedefinitionStrategy redefinitionStrategy);
/**
* <p>
* Enables or disables management of the JVM's {@code LambdaMetafactory} which is responsible for creating classes that
* implement lambda expressions. Without this feature enabled, classes that are represented by lambda expressions are
* not instrumented by the JVM such that Java agents have no effect on them when a lambda expression's class is loaded
* for the first time.
* </p>
* <p>
* When activating this feature, Byte Buddy instruments the {@code LambdaMetafactory} and takes over the responsibility
* of creating classes that represent lambda expressions. In doing so, Byte Buddy has the opportunity to apply the built
* class file transformer. If the current VM does not support lambda expressions, activating this feature has no effect.
* </p>
* <p>
* <b>Important</b>: If this feature is active, it is important to release the built class file transformer when
* deactivating it. Normally, it is sufficient to call {@link Instrumentation#removeTransformer(ClassFileTransformer)}.
* When this feature is enabled, it is however also required to invoke
* {@link LambdaInstrumentationStrategy#release(ClassFileTransformer, Instrumentation)}. Otherwise, the executing VMs class
* loader retains a reference to the class file transformer what can cause a memory leak.
* </p>
*
* @param lambdaInstrumentationStrategy {@code true} if this feature should be enabled.
* @return A new instance of this agent builder where this feature is explicitly enabled or disabled.
*/
AgentBuilder with(LambdaInstrumentationStrategy lambdaInstrumentationStrategy);
/**
* Specifies a strategy to be used for resolving {@link TypeDescription} for any type handled by the created transformer.
*
* @param descriptionStrategy The description strategy to use.
* @return A new instance of this agent builder that applies the given description strategy.
*/
AgentBuilder with(DescriptionStrategy descriptionStrategy);
/**
* Specifies a fallback strategy to that this agent builder applies upon installing an agent and during class file transformation.
*
* @param fallbackStrategy The fallback strategy to be used.
* @return A new agent builder that applies the supplied fallback strategy.
*/
AgentBuilder with(FallbackStrategy fallbackStrategy);
/**
* Specifies a class file buffer strategy that determines the use of the buffer supplied to a class file transformer.
*
* @param classFileBufferStrategy The class file buffer strategy to use.
* @return A new agent builder that applies the supplied class file buffer strategy.
*/
AgentBuilder with(ClassFileBufferStrategy classFileBufferStrategy);
/**
* Adds an installation listener that is notified during installation events. Installation listeners are only invoked if
* a class file transformer is installed using this agent builder's installation methods and uninstalled via the created
* {@link ResettableClassFileTransformer}'s {@code reset} methods.
*
* @param installationListener The installation listener to register.
* @return A new agent builder that applies the supplied installation listener.
*/
AgentBuilder with(InstallationListener installationListener);
/**
* Defines a strategy for injecting auxiliary types into the target class loader.
*
* @param injectionStrategy The injection strategy to use.
* @return A new agent builder with the supplied injection strategy configured.
*/
AgentBuilder with(InjectionStrategy injectionStrategy);
/**
* Adds a decorator for the created class file transformer.
*
* @param transformerDecorator A decorator to wrap the created class file transformer.
* @return A new agent builder that applies the supplied transformer decorator.
*/
AgentBuilder with(TransformerDecorator transformerDecorator);
/**
* Enables the use of the given native method prefix for instrumented methods. Note that this prefix is also
* applied when preserving non-native methods. The use of this prefix is also registered when installing the
* final agent with an {@link java.lang.instrument.Instrumentation}.
*
* @param prefix The prefix to be used.
* @return A new instance of this agent builder which uses the given native method prefix.
*/
AgentBuilder enableNativeMethodPrefix(String prefix);
/**
* Disables the use of a native method prefix for instrumented methods.
*
* @return A new instance of this agent builder which does not use a native method prefix.
*/
AgentBuilder disableNativeMethodPrefix();
/**
* <p>
* Disables all implicit changes on a class file that Byte Buddy would apply for certain instrumentations. When
* using this option, it is no longer possible to rebase a method, i.e. intercepted methods are fully replaced. Furthermore,
* it is no longer possible to implicitly apply loaded type initializers for explicitly initializing the generated type.
* </p>
* <p>
* This is equivalent to setting {@link InitializationStrategy.NoOp} and {@link TypeStrategy.Default#REDEFINE_FROZEN}
* (unless it is configured as {@link TypeStrategy.Default#DECORATE} where this strategy is retained)
* as well as configuring the underlying {@link ByteBuddy} instance to use a {@link net.bytebuddy.implementation.Implementation.Context.Disabled}.
* Using this strategy also configures Byte Buddy to create frozen instrumented types and discards any explicit configuration.
* </p>
*
* @return A new instance of this agent builder that does not apply any implicit changes to the received class file.
*/
AgentBuilder disableClassFormatChanges();
/**
* Assures that all modules of the supplied types are read by the module of any instrumented type. If the current VM does not support
* the Java module system, calling this method has no effect and this instance is returned.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param type The types for which to assure their module-visibility from any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Class<?>... type);
/**
* Assures that all supplied modules are read by the module of any instrumented type.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param module The modules for which to assure their module-visibility from any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, JavaModule... module);
/**
* Assures that all supplied modules are read by the module of any instrumented type.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param modules The modules for which to assure their module-visibility from any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules);
/**
* Assures that all modules of the supplied types are read by the module of any instrumented type and vice versa.
* If the current VM does not support the Java module system, calling this method has no effect and this instance is returned.
* Setting this option will also ensure that the instrumented type's package is opened to the target module, if applicable.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param type The types for which to assure their module-visibility from and to any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Class<?>... type);
/**
* Assures that all supplied modules are read by the module of any instrumented type and vice versa.
* Setting this option will also ensure that the instrumented type's package is opened to the target module.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param module The modules for which to assure their module-visibility from and to any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, JavaModule... module);
/**
* Assures that all supplied modules are read by the module of any instrumented type and vice versa.
* Setting this option will also ensure that the instrumented type's package is opened to the target module.
*
* @param instrumentation The instrumentation instance that is used for adding a module read-dependency.
* @param modules The modules for which to assure their module-visibility from and to any instrumented class.
* @return A new instance of this agent builder that assures the supplied types module visibility.
* @see Listener.ModuleReadEdgeCompleting
*/
AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules);
/**
* <p>
* Matches a type being loaded in order to apply the supplied {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type.
* If several matchers positively match a type only the latest registered matcher is considered for transformation.
* </p>
* <p>
* If this matcher is chained with additional subsequent matchers, any matcher is executed in registration order with matchers that were registered
* first being executed first. Doing so, later transformations can override transformations that are applied by this matcher. To avoid this, it is
* possible to register this transformation as terminal via {@link Identified.Extendable#asTerminalTransformation()} where no subsequent matchers
* are applied if this matcher matched a given type.
* </p>
* <p>
* <b>Note</b>: When applying a matcher, regard the performance implications by {@link AgentBuilder#ignore(ElementMatcher)}. The former
* matcher is applied first such that it makes sense to ignore name spaces that are irrelevant to instrumentation. If possible, it is
* also recommended, to exclude class loaders such as for example the bootstrap class loader by using
* {@link AgentBuilder#type(ElementMatcher, ElementMatcher)} instead.
* </p>
*
* @param typeMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied on the type being loaded that
* decides if the entailed {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should
* be applied for that type.
* @return A definable that represents this agent builder which allows for the definition of one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when the given {@code typeMatcher}
* indicates a match.
*/
Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher);
/**
* <p>
* Matches a type being loaded in order to apply the supplied {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type.
* If several matchers positively match a type only the latest registered matcher is considered for transformation.
* </p>
* <p>
* If this matcher is chained with additional subsequent matchers, any matcher is executed in registration order with matchers that were registered
* first being executed first. Doing so, later transformations can override transformations that are applied by this matcher. To avoid this, it is
* possible to register this transformation as terminal via {@link Identified.Extendable#asTerminalTransformation()} where no subsequent matchers
* are applied if this matcher matched a given type.
* </p>
* <p>
* <b>Note</b>: When applying a matcher, regard the performance implications by {@link AgentBuilder#ignore(ElementMatcher)}. The former
* matcher is applied first such that it makes sense to ignore name spaces that are irrelevant to instrumentation. If possible, it
* is also recommended, to exclude class loaders such as for example the bootstrap class loader.
* </p>
*
* @param typeMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied on the type being
* loaded that decides if the entailed
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should be applied for
* that type.
* @param classLoaderMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied to the
* {@link java.lang.ClassLoader} that is loading the type being loaded. This matcher
* is always applied first where the type matcher is not applied in case that this
* matcher does not indicate a match.
* @return A definable that represents this agent builder which allows for the definition of one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when both the given
* {@code typeMatcher} and {@code classLoaderMatcher} indicate a match.
*/
Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher);
/**
* <p>
* Matches a type being loaded in order to apply the supplied {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type.
* If several matchers positively match a type only the latest registered matcher is considered for transformation.
* </p>
* <p>
* If this matcher is chained with additional subsequent matchers, any matcher is executed in registration order with matchers that were registered
* first being executed first. Doing so, later transformations can override transformations that are applied by this matcher. To avoid this, it is
* possible to register this transformation as terminal via {@link Identified.Extendable#asTerminalTransformation()} where no subsequent matchers
* are applied if this matcher matched a given type.
* </p>
* <p>
* <b>Note</b>: When applying a matcher, regard the performance implications by {@link AgentBuilder#ignore(ElementMatcher)}. The former
* matcher is applied first such that it makes sense to ignore name spaces that are irrelevant to instrumentation. If possible, it
* is also recommended, to exclude class loaders such as for example the bootstrap class loader.
* </p>
*
* @param typeMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied on the type being
* loaded that decides if the entailed
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should be applied for
* that type.
* @param classLoaderMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied to the
* {@link java.lang.ClassLoader} that is loading the type being loaded. This matcher
* is always applied second where the type matcher is not applied in case that this
* matcher does not indicate a match.
* @param moduleMatcher An {@link net.bytebuddy.matcher.ElementMatcher} that is applied to the {@link JavaModule}
* of the type being loaded. This matcher is always applied first where the class loader and
* type matchers are not applied in case that this matcher does not indicate a match. On a JVM
* that does not support the Java modules system, this matcher is not applied.
* @return A definable that represents this agent builder which allows for the definition of one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when both the given
* {@code typeMatcher} and {@code classLoaderMatcher} indicate a match.
*/
Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher);
/**
* <p>
* Matches a type being loaded in order to apply the supplied {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s before loading this type.
* If several matchers positively match a type only the latest registered matcher is considered for transformation.
* </p>
* <p>
* If this matcher is chained with additional subsequent matchers, any matcher is executed in registration order with matchers that were registered
* first being executed first. Doing so, later transformations can override transformations that are applied by this matcher. To avoid this, it is
* possible to register this transformation as terminal via {@link Identified.Extendable#asTerminalTransformation()} where no subsequent matchers
* are applied if this matcher matched a given type.
* </p>
* <p>
* <b>Note</b>: When applying a matcher, regard the performance implications by {@link AgentBuilder#ignore(ElementMatcher)}. The former
* matcher is applied first such that it makes sense to ignore name spaces that are irrelevant to instrumentation. If possible, it
* is also recommended, to exclude class loaders such as for example the bootstrap class loader.
* </p>
*
* @param matcher A matcher that decides if the entailed {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should be
* applied for a type that is being loaded.
* @return A definable that represents this agent builder which allows for the definition of one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s to be applied when the given {@code matcher}
* indicates a match.
*/
Identified.Narrowable type(RawMatcher matcher);
/**
* <p>
* Excludes any type that is matched by the provided matcher from instrumentation and considers types by all {@link ClassLoader}s.
* By default, Byte Buddy does not instrument synthetic types or types that are loaded by the bootstrap class loader.
* </p>
* <p>
* When ignoring a type, any subsequently chained matcher is applied after this matcher in the order of their registration. Also, if
* any matcher indicates that a type is to be ignored, none of the following chained matchers is executed.
* </p>
* <p>
* <b>Note</b>: For performance reasons, it is recommended to always include a matcher that excludes as many namespaces
* as possible. Byte Buddy can determine a type's name without parsing its class file and can therefore discard such
* types with minimal overhead. When a different property of a type - such as for example its modifiers or its annotations
* is accessed - Byte Buddy parses the class file lazily in order to allow for such a matching. Therefore, any exclusion
* of a name should always be done as a first step and even if it does not influence the selection of what types are
* matched. Without changing this property, the class file of every type is being parsed!
* </p>
* <p>
* <b>Warning</b>: If a type is loaded during the instrumentation of the same type, this causes the original call site that loads the type
* to remain unbound, causing a {@link LinkageError}. It is therefore important to not instrument types that may be loaded during the application
* of a {@link Transformer}. For this reason, it is not recommended to instrument classes of the bootstrap class loader that Byte Buddy might
* require for instrumenting a class or to instrument any of Byte Buddy's classes. If such instrumentation is desired, it is important to
* assert for each class that they are not loaded during instrumentation.
* </p>
*
* @param typeMatcher A matcher that identifies types that should not be instrumented.
* @return A new instance of this agent builder that ignores all types that are matched by the provided matcher.
* All previous matchers for ignored types are discarded.
*/
Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher);
/**
* <p>
* Excludes any type that is matched by the provided matcher and is loaded by a class loader matching the second matcher.
* By default, Byte Buddy does not instrument synthetic types, types within a {@code net.bytebuddy.*} package or types that
* are loaded by the bootstrap class loader.
* </p>
* <p>
* When ignoring a type, any subsequently chained matcher is applied after this matcher in the order of their registration. Also, if
* any matcher indicates that a type is to be ignored, none of the following chained matchers is executed.
* </p>
* <p>
* <b>Note</b>: For performance reasons, it is recommended to always include a matcher that excludes as many namespaces
* as possible. Byte Buddy can determine a type's name without parsing its class file and can therefore discard such
* types with minimal overhead. When a different property of a type - such as for example its modifiers or its annotations
* is accessed - Byte Buddy parses the class file lazily in order to allow for such a matching. Therefore, any exclusion
* of a name should always be done as a first step and even if it does not influence the selection of what types are
* matched. Without changing this property, the class file of every type is being parsed!
* </p>
* <p>
* <b>Warning</b>: If a type is loaded during the instrumentation of the same type, this causes the original call site that loads the type
* to remain unbound, causing a {@link LinkageError}. It is therefore important to not instrument types that may be loaded during the application
* of a {@link Transformer}. For this reason, it is not recommended to instrument classes of the bootstrap class loader that Byte Buddy might
* require for instrumenting a class or to instrument any of Byte Buddy's classes. If such instrumentation is desired, it is important to
* assert for each class that they are not loaded during instrumentation.
* </p>
*
* @param typeMatcher A matcher that identifies types that should not be instrumented.
* @param classLoaderMatcher A matcher that identifies a class loader that identifies classes that should not be instrumented.
* @return A new instance of this agent builder that ignores all types that are matched by the provided matcher.
* All previous matchers for ignored types are discarded.
*/
Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher);
/**
* <p>
* Excludes any type that is matched by the provided matcher and is loaded by a class loader matching the second matcher.
* By default, Byte Buddy does not instrument synthetic types, types within a {@code net.bytebuddy.*} package or types that
* are loaded by the bootstrap class loader.
* </p>
* <p>
* When ignoring a type, any subsequently chained matcher is applied after this matcher in the order of their registration. Also, if
* any matcher indicates that a type is to be ignored, none of the following chained matchers is executed.
* </p>
* <p>
* <b>Note</b>: For performance reasons, it is recommended to always include a matcher that excludes as many namespaces
* as possible. Byte Buddy can determine a type's name without parsing its class file and can therefore discard such
* types with minimal overhead. When a different property of a type - such as for example its modifiers or its annotations
* is accessed - Byte Buddy parses the class file lazily in order to allow for such a matching. Therefore, any exclusion
* of a name should always be done as a first step and even if it does not influence the selection of what types are
* matched. Without changing this property, the class file of every type is being parsed!
* </p>
* <p>
* <b>Warning</b>: If a type is loaded during the instrumentation of the same type, this causes the original call site that loads the type
* to remain unbound, causing a {@link LinkageError}. It is therefore important to not instrument types that may be loaded during the application
* of a {@link Transformer}. For this reason, it is not recommended to instrument classes of the bootstrap class loader that Byte Buddy might
* require for instrumenting a class or to instrument any of Byte Buddy's classes. If such instrumentation is desired, it is important to
* assert for each class that they are not loaded during instrumentation.
* </p>
*
* @param typeMatcher A matcher that identifies types that should not be instrumented.
* @param classLoaderMatcher A matcher that identifies a class loader that identifies classes that should not be instrumented.
* @param moduleMatcher A matcher that identifies a module that identifies classes that should not be instrumented. On a JVM
* that does not support the Java modules system, this matcher is not applied.
* @return A new instance of this agent builder that ignores all types that are matched by the provided matcher.
* All previous matchers for ignored types are discarded.
*/
Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher);
/**
* <p>
* Excludes any type that is matched by the raw matcher provided to this method. By default, Byte Buddy does not
* instrument synthetic types, types within a {@code net.bytebuddy.*} package or types that are loaded by the bootstrap class loader.
* </p>
* <p>
* When ignoring a type, any subsequently chained matcher is applied after this matcher in the order of their registration. Also, if
* any matcher indicates that a type is to be ignored, none of the following chained matchers is executed.
* </p>
* <p>
* <b>Note</b>: For performance reasons, it is recommended to always include a matcher that excludes as many namespaces
* as possible. Byte Buddy can determine a type's name without parsing its class file and can therefore discard such
* types with minimal overhead. When a different property of a type - such as for example its modifiers or its annotations
* is accessed - Byte Buddy parses the class file lazily in order to allow for such a matching. Therefore, any exclusion
* of a name should always be done as a first step and even if it does not influence the selection of what types are
* matched. Without changing this property, the class file of every type is being parsed!
* </p>
* <p>
* <b>Warning</b>: If a type is loaded during the instrumentation of the same type, this causes the original call site that loads the type
* to remain unbound, causing a {@link LinkageError}. It is therefore important to not instrument types that may be loaded during the application
* of a {@link Transformer}. For this reason, it is not recommended to instrument classes of the bootstrap class loader that Byte Buddy might
* require for instrumenting a class or to instrument any of Byte Buddy's classes. If such instrumentation is desired, it is important to
* assert for each class that they are not loaded during instrumentation.
* </p>
*
* @param rawMatcher A raw matcher that identifies types that should not be instrumented.
* @return A new instance of this agent builder that ignores all types that are matched by the provided matcher.
* All previous matchers for ignored types are discarded.
*/
Ignored ignore(RawMatcher rawMatcher);
/**
* Creates a {@link ResettableClassFileTransformer} that implements the configuration of this
* agent builder. When using a raw class file transformer, the {@link InstallationListener} callbacks are
* not invoked and the set {@link RedefinitionStrategy} is not applied onto currently loaded classes.
*
* @return A class file transformer that implements the configuration of this agent builder.
*/
ClassFileTransformer makeRaw();
/**
* <p>
* Creates and installs a {@link ResettableClassFileTransformer} that implements the configuration of
* this agent builder with a given {@link java.lang.instrument.Instrumentation}. If retransformation is enabled,
* the installation also causes all loaded types to be retransformed.
* </p>
* <p>
* In order to assure the correct handling of the {@link InstallationListener}, an uninstallation should be applied
* via the {@link ResettableClassFileTransformer}'s {@code reset} methods.
* </p>
*
* @param instrumentation The instrumentation on which this agent builder's configuration is to be installed.
* @return The installed class file transformer.
*/
ResettableClassFileTransformer installOn(Instrumentation instrumentation);
/**
* <p>
* Creates and installs a {@link ResettableClassFileTransformer} that implements the configuration of
* this agent builder with the Byte Buddy-agent which must be installed prior to calling this method. If retransformation
* is enabled, the installation also causes all loaded types to be retransformed.
* </p>
* <p>
* In order to assure the correct handling of the {@link InstallationListener}, an uninstallation should be applied
* via the {@link ResettableClassFileTransformer}'s {@code reset} methods.
* </p>
*
* @return The installed class file transformer.
* @see AgentBuilder#installOn(Instrumentation)
*/
ResettableClassFileTransformer installOnByteBuddyAgent();
/**
* <p>
* Creates and installs a {@link ResettableClassFileTransformer} that implements the configuration of
* this agent builder with a given {@link java.lang.instrument.Instrumentation}. If retransformation is enabled,
* the installation also causes all loaded types to be retransformed which have changed compared to the previous
* class file transformer that is provided as an argument.
* </p>
* <p>
* In order to assure the correct handling of the {@link InstallationListener}, an uninstallation should be applied
* via the {@link ResettableClassFileTransformer}'s {@code reset} methods.
* </p>
*
* @param instrumentation The instrumentation on which this agent builder's configuration is to be installed.
* @param classFileTransformer The class file transformer that is being patched.
* @return The installed class file transformer.
*/
ResettableClassFileTransformer patchOn(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer);
/**
* <p>
* Creates and installs a {@link ResettableClassFileTransformer} that implements the configuration of
* this agent builder with the Byte Buddy-agent which must be installed prior to calling this method. If retransformation
* is enabled, the installation also causes all loaded types to be retransformed which have changed compared to the previous
* class file transformer that is provided as an argument.
* </p>
* <p>
* In order to assure the correct handling of the {@link InstallationListener}, an uninstallation should be applied
* via the {@link ResettableClassFileTransformer}'s {@code reset} methods.
* </p>
*
* @param classFileTransformer The class file transformer that is being patched.
* @return The installed class file transformer.
* @see AgentBuilder#patchOn(Instrumentation, ResettableClassFileTransformer)
*/
ResettableClassFileTransformer patchOnByteBuddyAgent(ResettableClassFileTransformer classFileTransformer);
/**
* An abstraction for extending a matcher.
*
* @param <T> The type that is produced by chaining a matcher.
*/
interface Matchable<T extends Matchable<T>> {
/**
* Defines a matching that is positive if both the previous matcher and the supplied matcher are matched. When matching a
* type, class loaders are not considered.
*
* @param typeMatcher A matcher for the type being matched.
* @return A chained matcher.
*/
T and(ElementMatcher<? super TypeDescription> typeMatcher);
/**
* Defines a matching that is positive if both the previous matcher and the supplied matcher are matched.
*
* @param typeMatcher A matcher for the type being matched.
* @param classLoaderMatcher A matcher for the type's class loader.
* @return A chained matcher.
*/
T and(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher);
/**
* Defines a matching that is positive if both the previous matcher and the supplied matcher are matched.
*
* @param typeMatcher A matcher for the type being matched.
* @param classLoaderMatcher A matcher for the type's class loader.
* @param moduleMatcher A matcher for the type's module. On a JVM that does not support modules, the Java module is represented by {@code null}.
* @return A chained matcher.
*/
T and(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher);
/**
* Defines a matching that is positive if both the previous matcher and the supplied matcher are matched.
*
* @param rawMatcher A raw matcher for the type being matched.
* @return A chained matcher.
*/
T and(RawMatcher rawMatcher);
/**
* Defines a matching that is positive if the previous matcher or the supplied matcher are matched. When matching a
* type, the class loader is not considered.
*
* @param typeMatcher A matcher for the type being matched.
* @return A chained matcher.
*/
T or(ElementMatcher<? super TypeDescription> typeMatcher);
/**
* Defines a matching that is positive if the previous matcher or the supplied matcher are matched.
*
* @param typeMatcher A matcher for the type being matched.
* @param classLoaderMatcher A matcher for the type's class loader.
* @return A chained matcher.
*/
T or(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher);
/**
* Defines a matching that is positive if the previous matcher or the supplied matcher are matched.
*
* @param typeMatcher A matcher for the type being matched.
* @param classLoaderMatcher A matcher for the type's class loader.
* @param moduleMatcher A matcher for the type's module. On a JVM that does not support modules, the Java module is represented by {@code null}.
* @return A chained matcher.
*/
T or(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher);
/**
* Defines a matching that is positive if the previous matcher or the supplied matcher are matched.
*
* @param rawMatcher A raw matcher for the type being matched.
* @return A chained matcher.
*/
T or(RawMatcher rawMatcher);
/**
* An abstract base implementation of a matchable.
*
* @param <S> The type that is produced by chaining a matcher.
*/
abstract class AbstractBase<S extends Matchable<S>> implements Matchable<S> {
/**
* {@inheritDoc}
*/
public S and(ElementMatcher<? super TypeDescription> typeMatcher) {
return and(typeMatcher, any());
}
/**
* {@inheritDoc}
*/
public S and(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) {
return and(typeMatcher, classLoaderMatcher, any());
}
/**
* {@inheritDoc}
*/
public S and(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return and(new RawMatcher.ForElementMatchers(typeMatcher, classLoaderMatcher, moduleMatcher));
}
/**
* {@inheritDoc}
*/
public S or(ElementMatcher<? super TypeDescription> typeMatcher) {
return or(typeMatcher, any());
}
/**
* {@inheritDoc}
*/
public S or(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) {
return or(typeMatcher, classLoaderMatcher, any());
}
/**
* {@inheritDoc}
*/
public S or(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return or(new RawMatcher.ForElementMatchers(typeMatcher, classLoaderMatcher, moduleMatcher));
}
}
}
/**
* Allows to further specify ignored types.
*/
interface Ignored extends Matchable<Ignored>, AgentBuilder {
/* this is merely a unionizing interface that does not declare methods */
}
/**
* An agent builder configuration that allows the registration of listeners to the redefinition process.
*/
interface RedefinitionListenable extends AgentBuilder {
/**
* <p>
* A redefinition listener is invoked before each batch of type redefinitions and on every error as well as
* after the redefinition was completed. A redefinition listener can be used for debugging or logging purposes
* and to apply actions between each batch, e.g. to pause or wait in order to avoid rendering the current VM
* non-responsive if a lot of classes are redefined.
* </p>
* <p>
* Adding several listeners does not replace previous listeners but applies them in the registration order.
* </p>
*
* @param redefinitionListener The listener to register.
* @return A new instance of this agent builder which notifies the specified listener upon type redefinitions.
*/
RedefinitionListenable with(RedefinitionStrategy.Listener redefinitionListener);
/**
* Enables resubmission of failed transformations by applying a retransformation of the loaded type. This can be meaningful if
* class files cannot be located from the class loader as a resource where the loaded type becomes available.
*
* @param resubmissionScheduler A scheduler which is responsible for scheduling the resubmission job.
* @return A new instance of this agent builder that applies resubmission.
*/
AgentBuilder withResubmission(RedefinitionStrategy.ResubmissionScheduler resubmissionScheduler);
/**
* Enables resubmission of failed transformations by applying a retransformation of the loaded type. This can be meaningful if
* class files cannot be located from the class loader as a resource where the loaded type becomes available.
*
* @param resubmissionScheduler A scheduler which is responsible for scheduling the resubmission job.
* @param matcher A matcher that filters throwable instances where non-matched throwables are not triggering a resubmission.
* @return A new instance of this agent builder that applies resubmission.
*/
AgentBuilder withResubmission(RedefinitionStrategy.ResubmissionScheduler resubmissionScheduler, ElementMatcher<? super Throwable> matcher);
/**
* An agent builder configuration strategy that allows the definition of a discovery strategy.
*/
interface WithImplicitDiscoveryStrategy extends RedefinitionListenable {
/**
* Limits the redefinition attempt to the specified types.
*
* @param type The types to consider for redefinition.
* @return A new instance of this agent builder which only considers the supplied types for redefinition.
*/
RedefinitionListenable redefineOnly(Class<?>... type);
/**
* A discovery strategy is responsible for locating loaded types that should be considered for redefinition.
*
* @param redefinitionDiscoveryStrategy The redefinition discovery strategy to use.
* @return A new instance of this agent builder which makes use of the specified discovery strategy.
*/
RedefinitionListenable with(RedefinitionStrategy.DiscoveryStrategy redefinitionDiscoveryStrategy);
}
/**
* An agent builder configuration that allows the configuration of a batching strategy.
*/
interface WithoutBatchStrategy extends WithImplicitDiscoveryStrategy {
/**
* A batch allocator is responsible for diving a redefining of existing types into several chunks. This allows
* to narrow down errors for the redefining of specific types or to apply a {@link RedefinitionStrategy.Listener}
* action between chunks.
*
* @param redefinitionBatchAllocator The batch allocator to use.
* @return A new instance of this agent builder which makes use of the specified batch allocator.
*/
WithImplicitDiscoveryStrategy with(RedefinitionStrategy.BatchAllocator redefinitionBatchAllocator);
}
}
/**
* Describes an {@link net.bytebuddy.agent.builder.AgentBuilder} which was handed a matcher for identifying
* types to instrumented in order to supply one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s.
*/
interface Identified {
/**
* Applies the given transformer for the already supplied matcher.
*
* @param transformer The transformer to apply.
* @return A new instance of this agent builder with the transformer being applied when the previously supplied matcher
* identified a type for instrumentation which also allows for the registration of subsequent transformers.
*/
Extendable transform(Transformer transformer);
/**
* Allows to specify a type matcher for a type to instrument.
*/
interface Narrowable extends Matchable<Narrowable>, Identified {
/* this is merely a unionizing interface that does not declare methods */
}
/**
* This interface is used to allow for optionally providing several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer} to applied when a matcher identifies a type
* to be instrumented. Any subsequent transformers are applied in the order they are registered.
*/
interface Extendable extends AgentBuilder, Identified {
/**
* Applies the previously defined transformation as terminal such that no subsequent transformers are applied even
* if their matchers would include the type that was matched for applying this transformer. If this option is not set,
* subsequent transformations are applied after this transformation such that it is possible that they override non-additive
* type transformations.
*
* @return A new agent builder that applies the previously configured transformer terminally.
*/
AgentBuilder asTerminalTransformation();
}
}
/**
* A matcher that allows to determine if a {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}
* should be applied during the execution of a {@link java.lang.instrument.ClassFileTransformer} that was
* generated by an {@link net.bytebuddy.agent.builder.AgentBuilder}.
*/
interface RawMatcher {
/**
* Decides if the given {@code typeDescription} should be instrumented with the entailed
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s.
*
* @param typeDescription A description of the type to be instrumented.
* @param classLoader The class loader of the instrumented type. Might be {@code null} if this class
* loader represents the bootstrap class loader.
* @param module The transformed type's module or {@code null} if the current VM does not support modules.
* @param classBeingRedefined The class being redefined which is only not {@code null} if a retransformation
* is applied.
* @param protectionDomain The protection domain of the type being transformed.
* @return {@code true} if the entailed {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s should
* be applied for the given {@code typeDescription}.
*/
boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain);
/**
* A matcher that always or never matches a type.
*/
enum Trivial implements RawMatcher {
/**
* Always matches a type.
*/
MATCHING(true),
/**
* Never matches a type.
*/
NON_MATCHING(false);
/**
* {@code true} if this matcher always matches a type.
*/
private final boolean matches;
/**
* Creates a new trivial raw matcher.
*
* @param matches {@code true} if this matcher always matches a type.
*/
Trivial(boolean matches) {
this.matches = matches;
}
/**
* {@inheritDoc}
*/
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return matches;
}
}
/**
* A raw matcher indicating the state of a type's class loading.
*/
enum ForLoadState implements RawMatcher {
/**
* Indicates that a type was already loaded.
*/
LOADED(false),
/**
* Indicates that a type was not yet loaded.
*/
UNLOADED(true);
/**
* {@code true} if a type is expected to be unloaded..
*/
private final boolean unloaded;
/**
* Creates a new load state matcher.
*
* @param unloaded {@code true} if a type is expected to be unloaded..
*/
ForLoadState(boolean unloaded) {
this.unloaded = unloaded;
}
/**
* {@inheritDoc}
*/
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return classBeingRedefined == null == unloaded;
}
}
/**
* Only matches loaded types that can be fully resolved. Types with missing dependencies might not be
* resolvable and can therefore trigger errors during redefinition.
*/
enum ForResolvableTypes implements RawMatcher {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
if (classBeingRedefined != null) {
try {
return Class.forName(classBeingRedefined.getName(), true, classLoader) == classBeingRedefined;
} catch (Throwable ignored) {
return false;
}
} else {
return true;
}
}
/**
* Returns an inverted version of this matcher.
*
* @return An inverted version of this matcher.
*/
public RawMatcher inverted() {
return new Inversion(this);
}
}
/**
* A conjunction of two raw matchers.
*/
@HashCodeAndEqualsPlugin.Enhance
class Conjunction implements RawMatcher {
/**
* The left matcher which is applied first.
*/
private final RawMatcher left;
/**
* The right matcher which is applied second.
*/
private final RawMatcher right;
/**
* Creates a new conjunction of two raw matchers.
*
* @param left The left matcher which is applied first.
* @param right The right matcher which is applied second.
*/
protected Conjunction(RawMatcher left, RawMatcher right) {
this.left = left;
this.right = right;
}
/**
* {@inheritDoc}
*/
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return left.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)
&& right.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain);
}
}
/**
* A disjunction of two raw matchers.
*/
@HashCodeAndEqualsPlugin.Enhance
class Disjunction implements RawMatcher {
/**
* The left matcher which is applied first.
*/
private final RawMatcher left;
/**
* The right matcher which is applied second.
*/
private final RawMatcher right;
/**
* Creates a new disjunction of two raw matchers.
*
* @param left The left matcher which is applied first.
* @param right The right matcher which is applied second.
*/
protected Disjunction(RawMatcher left, RawMatcher right) {
this.left = left;
this.right = right;
}
/**
* {@inheritDoc}
*/
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return left.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)
|| right.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain);
}
}
/**
* A raw matcher that inverts a raw matcher's result.
*/
@HashCodeAndEqualsPlugin.Enhance
class Inversion implements RawMatcher {
/**
* The matcher to invert.
*/
private final RawMatcher matcher;
/**
* Creates a raw matcher that inverts its result.
*
* @param matcher The matcher to invert.
*/
public Inversion(RawMatcher matcher) {
this.matcher = matcher;
}
/**
* {@inheritDoc}
*/
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return !matcher.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain);
}
}
/**
* A raw matcher implementation that checks a {@link TypeDescription}
* and its {@link java.lang.ClassLoader} against two suitable matchers in order to determine if the matched
* type should be instrumented.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForElementMatchers implements RawMatcher {
/**
* The type matcher to apply to a {@link TypeDescription}.
*/
private final ElementMatcher<? super TypeDescription> typeMatcher;
/**
* The class loader matcher to apply to a {@link java.lang.ClassLoader}.
*/
private final ElementMatcher<? super ClassLoader> classLoaderMatcher;
/**
* A module matcher to apply to a {@code java.lang.Module}.
*/
private final ElementMatcher<? super JavaModule> moduleMatcher;
/**
* Creates a new {@link net.bytebuddy.agent.builder.AgentBuilder.RawMatcher} that only matches the
* supplied {@link TypeDescription} against a supplied matcher.
*
* @param typeMatcher The type matcher to apply to a {@link TypeDescription}.
*/
public ForElementMatchers(ElementMatcher<? super TypeDescription> typeMatcher) {
this(typeMatcher, any());
}
/**
* Creates a new {@link net.bytebuddy.agent.builder.AgentBuilder.RawMatcher} that only matches the
* supplied {@link TypeDescription} and its {@link java.lang.ClassLoader} against two matcher in order
* to decided if an instrumentation should be conducted.
*
* @param typeMatcher The type matcher to apply to a {@link TypeDescription}.
* @param classLoaderMatcher The class loader matcher to apply to a {@link java.lang.ClassLoader}.
*/
public ForElementMatchers(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher) {
this(typeMatcher, classLoaderMatcher, any());
}
/**
* Creates a new {@link net.bytebuddy.agent.builder.AgentBuilder.RawMatcher} that only matches the
* supplied {@link TypeDescription}, its {@link java.lang.ClassLoader} and module against element
* suitable matchers.
*
* @param typeMatcher The type matcher to apply to a {@link TypeDescription}.
* @param classLoaderMatcher The class loader matcher to apply to a {@link java.lang.ClassLoader}.
* @param moduleMatcher A module matcher to apply to a {@code java.lang.Module}.
*/
public ForElementMatchers(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
this.typeMatcher = typeMatcher;
this.classLoaderMatcher = classLoaderMatcher;
this.moduleMatcher = moduleMatcher;
}
/**
* {@inheritDoc}
*/
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return moduleMatcher.matches(module) && classLoaderMatcher.matches(classLoader) && typeMatcher.matches(typeDescription);
}
}
}
/**
* A listener that is informed about events that occur during an instrumentation process.
*/
interface Listener {
/**
* Indicates that a transformed type is loaded.
*/
boolean LOADED = true;
/**
* Invoked upon a type being supplied to a transformer.
*
* @param typeName The binary name of the instrumented type.
* @param classLoader The class loader which is loading this type.
* @param module The instrumented type's module or {@code null} if the current VM does not support modules.
* @param loaded {@code true} if the type is already loaded.
*/
void onDiscovery(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded);
/**
* Invoked prior to a successful transformation being applied.
*
* @param typeDescription The type that is being transformed.
* @param classLoader The class loader which is loading this type.
* @param module The transformed type's module or {@code null} if the current VM does not support modules.
* @param loaded {@code true} if the type is already loaded.
* @param dynamicType The dynamic type that was created.
*/
void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType);
/**
* Invoked when a type is not transformed but ignored.
*
* @param typeDescription The type being ignored for transformation.
* @param classLoader The class loader which is loading this type.
* @param module The ignored type's module or {@code null} if the current VM does not support modules.
* @param loaded {@code true} if the type is already loaded.
*/
void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded);
/**
* Invoked when an error has occurred during transformation.
*
* @param typeName The binary name of the instrumented type.
* @param classLoader The class loader which is loading this type.
* @param module The instrumented type's module or {@code null} if the current VM does not support modules.
* @param loaded {@code true} if the type is already loaded.
* @param throwable The occurred error.
*/
void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable);
/**
* Invoked after a class was attempted to be loaded, independently of its treatment.
*
* @param typeName The binary name of the instrumented type.
* @param classLoader The class loader which is loading this type.
* @param module The instrumented type's module or {@code null} if the current VM does not support modules.
* @param loaded {@code true} if the type is already loaded.
*/
void onComplete(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded);
/**
* A no-op implementation of a {@link net.bytebuddy.agent.builder.AgentBuilder.Listener}.
*/
enum NoOp implements Listener {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public void onDiscovery(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onComplete(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
/* do nothing */
}
}
/**
* An adapter for a listener where all methods are implemented as non-operational.
*/
abstract class Adapter implements Listener {
/**
* {@inheritDoc}
*/
public void onDiscovery(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onComplete(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
/* do nothing */
}
}
/**
* A listener that writes events to a {@link PrintStream}. This listener prints a line per event, including the event type and
* the name of the type in question.
*/
@HashCodeAndEqualsPlugin.Enhance
class StreamWriting implements Listener {
/**
* The prefix that is appended to all written messages.
*/
protected static final String PREFIX = "[Byte Buddy]";
/**
* The print stream written to.
*/
private final PrintStream printStream;
/**
* Creates a new stream writing listener.
*
* @param printStream The print stream written to.
*/
public StreamWriting(PrintStream printStream) {
this.printStream = printStream;
}
/**
* Creates a new stream writing listener that writes to {@link System#out}.
*
* @return A listener writing events to the standard output stream.
*/
public static StreamWriting toSystemOut() {
return new StreamWriting(System.out);
}
/**
* Creates a new stream writing listener that writes to {@link System#err}.
*
* @return A listener writing events to the standard error stream.
*/
public static StreamWriting toSystemError() {
return new StreamWriting(System.err);
}
/**
* Returns a version of this listener that only reports successfully transformed classes and failed transformations.
*
* @return A version of this listener that only reports successfully transformed classes and failed transformations.
*/
public Listener withTransformationsOnly() {
return new WithTransformationsOnly(this);
}
/**
* Returns a version of this listener that only reports failed transformations.
*
* @return A version of this listener that only reports failed transformations.
*/
public Listener withErrorsOnly() {
return new WithErrorsOnly(this);
}
/**
* {@inheritDoc}
*/
public void onDiscovery(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
printStream.printf(PREFIX + " DISCOVERY %s [%s, %s, loaded=%b]%n", typeName, classLoader, module, loaded);
}
/**
* {@inheritDoc}
*/
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType) {
printStream.printf(PREFIX + " TRANSFORM %s [%s, %s, loaded=%b]%n", typeDescription.getName(), classLoader, module, loaded);
}
/**
* {@inheritDoc}
*/
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded) {
printStream.printf(PREFIX + " IGNORE %s [%s, %s, loaded=%b]%n", typeDescription.getName(), classLoader, module, loaded);
}
/**
* {@inheritDoc}
*/
public void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable) {
synchronized (printStream) {
printStream.printf(PREFIX + " ERROR %s [%s, %s, loaded=%b]%n", typeName, classLoader, module, loaded);
throwable.printStackTrace(printStream);
}
}
/**
* {@inheritDoc}
*/
public void onComplete(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
printStream.printf(PREFIX + " COMPLETE %s [%s, %s, loaded=%b]%n", typeName, classLoader, module, loaded);
}
}
/**
* A listener that filters types with a given name from being logged.
*/
@HashCodeAndEqualsPlugin.Enhance
class Filtering implements Listener {
/**
* The matcher to decide upon a type should be logged.
*/
private final ElementMatcher<? super String> matcher;
/**
* The delegate listener.
*/
private final Listener delegate;
/**
* Creates a new filtering listener.
*
* @param matcher The matcher to decide upon a type should be logged.
* @param delegate The delegate listener.
*/
public Filtering(ElementMatcher<? super String> matcher, Listener delegate) {
this.matcher = matcher;
this.delegate = delegate;
}
/**
* {@inheritDoc}
*/
public void onDiscovery(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
if (matcher.matches(typeName)) {
delegate.onDiscovery(typeName, classLoader, module, loaded);
}
}
/**
* {@inheritDoc}
*/
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType) {
if (matcher.matches(typeDescription.getName())) {
delegate.onTransformation(typeDescription, classLoader, module, loaded, dynamicType);
}
}
/**
* {@inheritDoc}
*/
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded) {
if (matcher.matches(typeDescription.getName())) {
delegate.onIgnored(typeDescription, classLoader, module, loaded);
}
}
/**
* {@inheritDoc}
*/
public void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable) {
if (matcher.matches(typeName)) {
delegate.onError(typeName, classLoader, module, loaded, throwable);
}
}
/**
* {@inheritDoc}
*/
public void onComplete(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
if (matcher.matches(typeName)) {
delegate.onComplete(typeName, classLoader, module, loaded);
}
}
}
/**
* A listener that only delegates events if they are successful or failed transformations.
*/
@HashCodeAndEqualsPlugin.Enhance
class WithTransformationsOnly extends Adapter {
/**
* The delegate listener.
*/
private final Listener delegate;
/**
* Creates a new listener that only delegates events if they are successful or failed transformations.
*
* @param delegate The delegate listener.
*/
public WithTransformationsOnly(Listener delegate) {
this.delegate = delegate;
}
@Override
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType) {
delegate.onTransformation(typeDescription, classLoader, module, loaded, dynamicType);
}
@Override
public void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable) {
delegate.onError(typeName, classLoader, module, loaded, throwable);
}
}
/**
* A listener that only delegates events if they are failed transformations.
*/
@HashCodeAndEqualsPlugin.Enhance
class WithErrorsOnly extends Adapter {
/**
* The delegate listener.
*/
private final Listener delegate;
/**
* Creates a new listener that only delegates events if they are failed transformations.
*
* @param delegate The delegate listener.
*/
public WithErrorsOnly(Listener delegate) {
this.delegate = delegate;
}
@Override
public void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable) {
delegate.onError(typeName, classLoader, module, loaded, throwable);
}
}
/**
* A listener that adds read-edges to any module of an instrumented class upon its transformation and opens the class's package to the module.
*/
@HashCodeAndEqualsPlugin.Enhance
class ModuleReadEdgeCompleting extends Adapter {
/**
* The instrumentation instance used for adding read edges.
*/
private final Instrumentation instrumentation;
/**
* {@code true} if the listener should also add a read-edge from the supplied modules to the instrumented type's module.
* This will also ensure that the package of the instrumented type is exported to the target module.
*/
private final boolean addTargetEdge;
/**
* The modules to add as a read edge to any transformed class's module.
*/
private final Set<? extends JavaModule> modules;
/**
* Creates a new module read-edge completing listener.
*
* @param instrumentation The instrumentation instance used for adding read edges.
* @param addTargetEdge {@code true} if the listener should also add a read-edge from the supplied
* modules to the instrumented type's module. This will also ensure that the package
* of the instrumented type is exported to the target module.
* @param modules The modules to add as a read edge to any transformed class's module.
*/
public ModuleReadEdgeCompleting(Instrumentation instrumentation, boolean addTargetEdge, Set<? extends JavaModule> modules) {
this.instrumentation = instrumentation;
this.addTargetEdge = addTargetEdge;
this.modules = modules;
}
/**
* Resolves a listener that adds module edges from and to the instrumented type's module.
*
* @param instrumentation The instrumentation instance used for adding read edges.
* @param addTargetEdge {@code true} if the listener should also add a read-edge from the supplied
* modules to the instrumented type's module. This will also ensure that the package
* of the instrumented type is exported to the target module.
* @param type The types for which to extract the modules.
* @return An appropriate listener.
*/
public static Listener of(Instrumentation instrumentation, boolean addTargetEdge, Class<?>... type) {
Set<JavaModule> modules = new HashSet<JavaModule>();
for (Class<?> aType : type) {
modules.add(JavaModule.ofType(aType));
}
return modules.isEmpty()
? Listener.NoOp.INSTANCE
: new Listener.ModuleReadEdgeCompleting(instrumentation, addTargetEdge, modules);
}
@Override
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType) {
if (module != JavaModule.UNSUPPORTED && module.isNamed()) {
for (JavaModule target : modules) {
if (!module.canRead(target) || addTargetEdge && !module.isOpened(typeDescription.getPackage(), target)) {
module.modify(instrumentation,
Collections.singleton(target),
Collections.<String, Set<JavaModule>>emptyMap(),
!addTargetEdge || typeDescription.getPackage() == null
? Collections.<String, Set<JavaModule>>emptyMap()
: Collections.singletonMap(typeDescription.getPackage().getName(), Collections.singleton(target)),
Collections.<Class<?>>emptySet(),
Collections.<Class<?>, List<Class<?>>>emptyMap());
}
if (addTargetEdge && !target.canRead(module)) {
target.modify(instrumentation,
Collections.singleton(module),
Collections.<String, Set<JavaModule>>emptyMap(),
Collections.<String, Set<JavaModule>>emptyMap(),
Collections.<Class<?>>emptySet(),
Collections.<Class<?>, List<Class<?>>>emptyMap());
}
}
}
}
}
/**
* A compound listener that allows to group several listeners in one instance.
*/
@HashCodeAndEqualsPlugin.Enhance
class Compound implements Listener {
/**
* The listeners that are represented by this compound listener in their application order.
*/
private final List<Listener> listeners;
/**
* Creates a new compound listener.
*
* @param listener The listeners to apply in their application order.
*/
public Compound(Listener... listener) {
this(Arrays.asList(listener));
}
/**
* Creates a new compound listener.
*
* @param listeners The listeners to apply in their application order.
*/
public Compound(List<? extends Listener> listeners) {
this.listeners = new ArrayList<Listener>();
for (Listener listener : listeners) {
if (listener instanceof Compound) {
this.listeners.addAll(((Compound) listener).listeners);
} else if (!(listener instanceof NoOp)) {
this.listeners.add(listener);
}
}
}
/**
* {@inheritDoc}
*/
public void onDiscovery(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
for (Listener listener : listeners) {
listener.onDiscovery(typeName, classLoader, module, loaded);
}
}
/**
* {@inheritDoc}
*/
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded, DynamicType dynamicType) {
for (Listener listener : listeners) {
listener.onTransformation(typeDescription, classLoader, module, loaded, dynamicType);
}
}
/**
* {@inheritDoc}
*/
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, boolean loaded) {
for (Listener listener : listeners) {
listener.onIgnored(typeDescription, classLoader, module, loaded);
}
}
/**
* {@inheritDoc}
*/
public void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable) {
for (Listener listener : listeners) {
listener.onError(typeName, classLoader, module, loaded, throwable);
}
}
/**
* {@inheritDoc}
*/
public void onComplete(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded) {
for (Listener listener : listeners) {
listener.onComplete(typeName, classLoader, module, loaded);
}
}
}
}
/**
* A circularity lock is responsible for preventing that a {@link ClassFileLocator} is used recursively.
* This can happen when a class file transformation causes another class to be loaded. Without avoiding
* such circularities, a class loading is aborted by a {@link ClassCircularityError} which causes the
* class loading to fail.
*/
interface CircularityLock {
/**
* Attempts to acquire a circularity lock.
*
* @return {@code true} if the lock was acquired successfully, {@code false} if it is already hold.
*/
boolean acquire();
/**
* Releases the circularity lock if it is currently acquired.
*/
void release();
/**
* An inactive circularity lock which is always acquirable.
*/
enum Inactive implements CircularityLock {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public boolean acquire() {
return true;
}
/**
* {@inheritDoc}
*/
public void release() {
/* do nothing */
}
}
/**
* A default implementation of a circularity lock. Since class loading already synchronizes on a class loader,
* it suffices to apply a thread-local lock.
*/
class Default extends ThreadLocal<Boolean> implements CircularityLock {
/**
* Indicates that the circularity lock is not currently acquired.
*/
private static final Boolean NOT_ACQUIRED = null;
/**
* {@inheritDoc}
*/
public boolean acquire() {
if (get() == NOT_ACQUIRED) {
set(true);
return true;
} else {
return false;
}
}
/**
* {@inheritDoc}
*/
public void release() {
set(NOT_ACQUIRED);
}
}
/**
* A circularity lock that holds a global monitor and does not permit concurrent access.
*/
@HashCodeAndEqualsPlugin.Enhance
class Global implements CircularityLock {
/**
* The lock to hold.
*/
private final Lock lock;
/**
* The time to wait for the lock.
*/
private final long time;
/**
* The time's time unit.
*/
private final TimeUnit timeUnit;
/**
* Creates a new global circularity lock that does not wait for a release.
*/
public Global() {
this(0, TimeUnit.MILLISECONDS);
}
/**
* Creates a new global circularity lock.
*
* @param time The time to wait for the lock.
* @param timeUnit The time's time unit.
*/
public Global(long time, TimeUnit timeUnit) {
lock = new ReentrantLock();
this.time = time;
this.timeUnit = timeUnit;
}
/**
* {@inheritDoc}
*/
public boolean acquire() {
try {
return time == 0
? lock.tryLock()
: lock.tryLock(time, timeUnit);
} catch (InterruptedException ignored) {
return false;
}
}
/**
* {@inheritDoc}
*/
public void release() {
lock.unlock();
}
}
}
/**
* A type strategy is responsible for creating a type builder for a type that is being instrumented.
*/
interface TypeStrategy {
/**
* Creates a type builder for a given type.
*
* @param typeDescription The type being instrumented.
* @param byteBuddy The Byte Buddy configuration.
* @param classFileLocator The class file locator to use.
* @param methodNameTransformer The method name transformer to use.
* @param classLoader The instrumented type's class loader or {@code null} if the type is loaded by the bootstrap loader.
* @param module The instrumented type's module or {@code null} if it is not declared by a module.
* @param protectionDomain The instrumented type's protection domain or {@code null} if it does not define a protection domain.
* @return A type builder for the given arguments.
*/
DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodNameTransformer methodNameTransformer,
ClassLoader classLoader,
JavaModule module,
ProtectionDomain protectionDomain);
/**
* Default implementations of type strategies.
*/
enum Default implements TypeStrategy {
/**
* A definition handler that performs a rebasing for all types.
*/
REBASE {
/** {@inheritDoc} */
public DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodNameTransformer methodNameTransformer,
ClassLoader classLoader,
JavaModule module,
ProtectionDomain protectionDomain) {
return byteBuddy.rebase(typeDescription, classFileLocator, methodNameTransformer);
}
},
/**
* <p>
* A definition handler that performs a redefinition for all types.
* </p>
* <p>
* Note that the default agent builder is configured to apply a self initialization where a static class initializer
* is added to the redefined class. This can be disabled by for example using a {@link InitializationStrategy.Minimal} or
* {@link InitializationStrategy.NoOp}. Also, consider the constraints implied by {@link ByteBuddy#redefine(TypeDescription, ClassFileLocator)}.
* </p>
* <p>
* For prohibiting any changes on a class file, use {@link AgentBuilder#disableClassFormatChanges()}
* </p>
*/
REDEFINE {
/** {@inheritDoc} */
public DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodNameTransformer methodNameTransformer,
ClassLoader classLoader,
JavaModule module,
ProtectionDomain protectionDomain) {
return byteBuddy.redefine(typeDescription, classFileLocator);
}
},
/**
* <p>
* A definition handler that performs a redefinition for all types and ignores all methods that were not declared by the instrumented type.
* </p>
* <p>
* Note that the default agent builder is configured to apply a self initialization where a static class initializer
* is added to the redefined class. This can be disabled by for example using a {@link InitializationStrategy.Minimal} or
* {@link InitializationStrategy.NoOp}. Also, consider the constraints implied by {@link ByteBuddy#redefine(TypeDescription, ClassFileLocator)}.
* Using this strategy also configures Byte Buddy to create frozen instrumented types and discards any explicit configuration.
* </p>
* <p>
* For prohibiting any changes on a class file, use {@link AgentBuilder#disableClassFormatChanges()}
* </p>
*/
REDEFINE_FROZEN {
/** {@inheritDoc} */
public DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodNameTransformer methodNameTransformer,
ClassLoader classLoader,
JavaModule module,
ProtectionDomain protectionDomain) {
return byteBuddy.with(InstrumentedType.Factory.Default.FROZEN)
.with(VisibilityBridgeStrategy.Default.NEVER)
.redefine(typeDescription, classFileLocator)
.ignoreAlso(LatentMatcher.ForSelfDeclaredMethod.NOT_DECLARED);
}
},
/**
* <p>
* A definition handler that performs a decoration of declared methods only. Using this type strategy
* implies the limitations that are described by {@link ByteBuddy#decorate(TypeDescription, ClassFileLocator)}.
* This type strategy can be useful when only applying {@link AsmVisitorWrapper}s without attempting to change
* the class file layout..
* </p>
* <p>
* Note that the default agent builder is configured to apply a self initialization where a static class initializer
* is added to the redefined class. This can be disabled by for example using a {@link InitializationStrategy.Minimal} or
* {@link InitializationStrategy.NoOp}. Also, consider the constraints implied by {@link ByteBuddy#redefine(TypeDescription, ClassFileLocator)}.
* Using this strategy also configures Byte Buddy to create frozen instrumented types and discards any explicit configuration.
* </p>
* <p>
* For prohibiting any changes on a class file, use {@link AgentBuilder#disableClassFormatChanges()}
* </p>
*/
DECORATE {
/** {@inheritDoc} */
public DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodNameTransformer methodNameTransformer,
ClassLoader classLoader,
JavaModule module,
ProtectionDomain protectionDomain) {
return byteBuddy.decorate(typeDescription, classFileLocator);
}
}
}
/**
* A type strategy that applies a build {@link EntryPoint}.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForBuildEntryPoint implements TypeStrategy {
/**
* The entry point to apply.
*/
private final EntryPoint entryPoint;
/**
* Creates a new type strategy for an entry point.
*
* @param entryPoint The entry point to apply.
*/
public ForBuildEntryPoint(EntryPoint entryPoint) {
this.entryPoint = entryPoint;
}
/**
* {@inheritDoc}
*/
public DynamicType.Builder<?> builder(TypeDescription typeDescription,
ByteBuddy byteBuddy,
ClassFileLocator classFileLocator,
MethodNameTransformer methodNameTransformer,
ClassLoader classLoader,
JavaModule module,
ProtectionDomain protectionDomain) {
return entryPoint.transform(typeDescription, byteBuddy, classFileLocator, methodNameTransformer);
}
}
}
/**
* A transformer allows to apply modifications to a {@link net.bytebuddy.dynamic.DynamicType}. Such a modification
* is then applied to any instrumented type that was matched by the preceding matcher.
*/
interface Transformer {
/**
* Allows for a transformation of a {@link net.bytebuddy.dynamic.DynamicType.Builder}.
*
* @param builder The dynamic builder to transform.
* @param typeDescription The description of the type currently being instrumented.
* @param classLoader The class loader of the instrumented class. Might be {@code null} to represent the bootstrap class loader.
* @param module The class's module or {@code null} if the current VM does not support modules.
* @return A transformed version of the supplied {@code builder}.
*/
DynamicType.Builder<?> transform(DynamicType.Builder<?> builder,
TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module);
/**
* A transformer that applies a build {@link Plugin}. Note that a transformer is never completed as class loading
* might happen dynamically such that plugins are not closed.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForBuildPlugin implements Transformer {
/**
* The plugin to apply.
*/
private final Plugin plugin;
/**
* Creates a new transformer for a build {@link Plugin}.
*
* @param plugin The plugin to apply.
*/
public ForBuildPlugin(Plugin plugin) {
this.plugin = plugin;
}
/**
* {@inheritDoc}
*/
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder,
TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module) {
return plugin.apply(builder, typeDescription, ClassFileLocator.ForClassLoader.of(classLoader));
}
}
/**
* A transformer for applying an {@link Advice} where this advice class might reference types of both the agent's and the user's
* class loader. Using this transformer, it is possible to apply advice without including any library dependencies of this advice
* class which are then rather looked up from the transformed class's class loader. For this to work, it is required to register
* the advice class's class loader manually via the {@code include} methods and to reference the advice class by its fully-qualified
* name. The advice class is then never loaded by rather described by a {@link TypePool}.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForAdvice implements Transformer {
/**
* The advice to use.
*/
private final Advice.WithCustomMapping advice;
/**
* The exception handler to register for the advice.
*/
private final Advice.ExceptionHandler exceptionHandler;
/**
* The assigner to use for the advice.
*/
private final Assigner assigner;
/**
* The class file locator to query for the advice class.
*/
private final ClassFileLocator classFileLocator;
/**
* The pool strategy to use for looking up an advice.
*/
private final PoolStrategy poolStrategy;
/**
* The location strategy to use for class loaders when resolving advice classes.
*/
private final LocationStrategy locationStrategy;
/**
* The advice entries to apply.
*/
private final List<Entry> entries;
/**
* Creates a new advice transformer with a default setup.
*/
public ForAdvice() {
this(Advice.withCustomMapping());
}
/**
* Creates a new advice transformer which applies the given advice.
*
* @param advice The configured advice to use.
*/
public ForAdvice(Advice.WithCustomMapping advice) {
this(advice,
Advice.ExceptionHandler.Default.SUPPRESSING,
Assigner.DEFAULT,
ClassFileLocator.NoOp.INSTANCE,
PoolStrategy.Default.FAST,
LocationStrategy.ForClassLoader.STRONG,
Collections.<Entry>emptyList());
}
/**
* Creates a new advice transformer.
*
* @param advice The configured advice to use.
* @param exceptionHandler The exception handler to use.
* @param assigner The assigner to use.
* @param classFileLocator The class file locator to use.
* @param poolStrategy The pool strategy to use for looking up an advice.
* @param locationStrategy The location strategy to use for class loaders when resolving advice classes.
* @param entries The advice entries to apply.
*/
protected ForAdvice(Advice.WithCustomMapping advice,
Advice.ExceptionHandler exceptionHandler,
Assigner assigner,
ClassFileLocator classFileLocator,
PoolStrategy poolStrategy,
LocationStrategy locationStrategy,
List<Entry> entries) {
this.advice = advice;
this.exceptionHandler = exceptionHandler;
this.assigner = assigner;
this.classFileLocator = classFileLocator;
this.poolStrategy = poolStrategy;
this.locationStrategy = locationStrategy;
this.entries = entries;
}
/**
* {@inheritDoc}
*/
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder,
TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module) {
ClassFileLocator classFileLocator = new ClassFileLocator.Compound(this.classFileLocator, locationStrategy.classFileLocator(classLoader, module));
TypePool typePool = poolStrategy.typePool(classFileLocator, classLoader);
AsmVisitorWrapper.ForDeclaredMethods asmVisitorWrapper = new AsmVisitorWrapper.ForDeclaredMethods();
for (Entry entry : entries) {
asmVisitorWrapper = asmVisitorWrapper.invokable(entry.getMatcher().resolve(typeDescription), entry.resolve(advice, typePool, classFileLocator)
.withAssigner(assigner)
.withExceptionHandler(exceptionHandler));
}
return builder.visit(asmVisitorWrapper);
}
/**
* Registers a pool strategy for creating a {@link TypePool} that should be used for creating the advice class.
*
* @param poolStrategy The pool strategy to use.
* @return A new instance of this advice transformer that applies the supplied pool strategy.
*/
public ForAdvice with(PoolStrategy poolStrategy) {
return new ForAdvice(advice, exceptionHandler, assigner, classFileLocator, poolStrategy, locationStrategy, entries);
}
/**
* Registers a location strategy for creating a {@link ClassFileLocator} from the class loader that is supplied during transformation
* that should be used for looking up advice-relevant classes.
*
* @param locationStrategy The location strategy to use.
* @return A new instance of this advice transformer that applies the supplied location strategy.
*/
public ForAdvice with(LocationStrategy locationStrategy) {
return new ForAdvice(advice, exceptionHandler, assigner, classFileLocator, poolStrategy, locationStrategy, entries);
}
/**
* Registers an exception handler for suppressed exceptions to use by the registered advice.
*
* @param exceptionHandler The exception handler to use.
* @return A new instance of this advice transformer that applies the supplied exception handler.
* @see Advice#withExceptionHandler(StackManipulation)
*/
public ForAdvice withExceptionHandler(Advice.ExceptionHandler exceptionHandler) {
return new ForAdvice(advice, exceptionHandler, assigner, classFileLocator, poolStrategy, locationStrategy, entries);
}
/**
* Registers an assigner to be used by the advice class.
*
* @param assigner The assigner to use.
* @return A new instance of this advice transformer that applies the supplied assigner.
* @see Advice#withAssigner(Assigner)
*/
public ForAdvice with(Assigner assigner) {
return new ForAdvice(advice, exceptionHandler, assigner, classFileLocator, poolStrategy, locationStrategy, entries);
}
/**
* Includes the supplied class loaders as a source for looking up an advice class or its dependencies.
* Note that the supplied class loaders are queried for types before the class loader of the instrumented class.
*
* @param classLoader The class loaders to include when looking up classes in their order. Duplicates are filtered.
* @return A new instance of this advice transformer that considers the supplied class loaders as a lookup source.
*/
public ForAdvice include(ClassLoader... classLoader) {
Set<ClassFileLocator> classFileLocators = new LinkedHashSet<ClassFileLocator>();
for (ClassLoader aClassLoader : classLoader) {
classFileLocators.add(ClassFileLocator.ForClassLoader.of(aClassLoader));
}
return include(new ArrayList<ClassFileLocator>(classFileLocators));
}
/**
* Includes the supplied class file locators as a source for looking up an advice class or its dependencies.
* Note that the supplied class loaders are queried for types before the class loader of the instrumented class.
*
* @param classFileLocator The class file locators to include when looking up classes in their order. Duplicates are filtered.
* @return A new instance of this advice transformer that considers the supplied class file locators as a lookup source.
*/
public ForAdvice include(ClassFileLocator... classFileLocator) {
return include(Arrays.asList(classFileLocator));
}
/**
* Includes the supplied class file locators as a source for looking up an advice class or its dependencies.
* Note that the supplied class loaders are queried for types before the class loader of the instrumented class.
*
* @param classFileLocators The class file locators to include when looking up classes in their order. Duplicates are filtered.
* @return A new instance of this advice transformer that considers the supplied class file locators as a lookup source.
*/
public ForAdvice include(List<? extends ClassFileLocator> classFileLocators) {
return new ForAdvice(advice,
exceptionHandler,
assigner,
new ClassFileLocator.Compound(CompoundList.of(classFileLocator, classFileLocators)),
poolStrategy,
locationStrategy,
entries);
}
/**
* Applies the given advice class onto all methods that satisfy the supplied matcher.
*
* @param matcher The matcher to determine what methods the advice should be applied to.
* @param name The fully-qualified, binary name of the advice class.
* @return A new instance of this advice transformer that applies the given advice to all matched methods of an instrumented type.
*/
public ForAdvice advice(ElementMatcher<? super MethodDescription> matcher, String name) {
return advice(new LatentMatcher.Resolved<MethodDescription>(matcher), name);
}
/**
* Applies the given advice class onto all methods that satisfy the supplied matcher.
*
* @param matcher The matcher to determine what methods the advice should be applied to.
* @param name The fully-qualified, binary name of the advice class.
* @return A new instance of this advice transformer that applies the given advice to all matched methods of an instrumented type.
*/
public ForAdvice advice(LatentMatcher<? super MethodDescription> matcher, String name) {
return new ForAdvice(advice,
exceptionHandler,
assigner,
classFileLocator,
poolStrategy,
locationStrategy,
CompoundList.of(entries, new Entry.ForUnifiedAdvice(matcher, name)));
}
/**
* Applies the given advice class onto all methods that satisfy the supplied matcher.
*
* @param matcher The matcher to determine what methods the advice should be applied to.
* @param enter The fully-qualified, binary name of the enter advice class.
* @param exit The fully-qualified, binary name of the exit advice class.
* @return A new instance of this advice transformer that applies the given advice to all matched methods of an instrumented type.
*/
public ForAdvice advice(ElementMatcher<? super MethodDescription> matcher, String enter, String exit) {
return advice(new LatentMatcher.Resolved<MethodDescription>(matcher), enter, exit);
}
/**
* Applies the given advice class onto all methods that satisfy the supplied matcher.
*
* @param matcher The matcher to determine what methods the advice should be applied to.
* @param enter The fully-qualified, binary name of the enter advice class.
* @param exit The fully-qualified, binary name of the exit advice class.
* @return A new instance of this advice transformer that applies the given advice to all matched methods of an instrumented type.
*/
public ForAdvice advice(LatentMatcher<? super MethodDescription> matcher, String enter, String exit) {
return new ForAdvice(advice,
exceptionHandler,
assigner,
classFileLocator,
poolStrategy,
locationStrategy,
CompoundList.of(entries, new Entry.ForSplitAdvice(matcher, enter, exit)));
}
/**
* An entry for an advice to apply.
*/
@HashCodeAndEqualsPlugin.Enhance
protected abstract static class Entry {
/**
* The matcher for advised methods.
*/
private final LatentMatcher<? super MethodDescription> matcher;
/**
* Creates a new entry.
*
* @param matcher The matcher for advised methods.
*/
protected Entry(LatentMatcher<? super MethodDescription> matcher) {
this.matcher = matcher;
}
/**
* Returns the matcher for advised methods.
*
* @return The matcher for advised methods.
*/
protected LatentMatcher<? super MethodDescription> getMatcher() {
return matcher;
}
/**
* Resolves the advice for this entry.
*
* @param advice The advice configuration.
* @param typePool The type pool to use.
* @param classFileLocator The class file locator to use.
* @return The resolved advice.
*/
protected abstract Advice resolve(Advice.WithCustomMapping advice, TypePool typePool, ClassFileLocator classFileLocator);
/**
* An entry for an advice class where both the (optional) entry and exit advice methods are declared by the same class.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class ForUnifiedAdvice extends Entry {
/**
* The name of the advice class.
*/
protected final String name;
/**
* Creates a new entry for an advice class where both the (optional) entry and exit advice methods are declared by the same class.
*
* @param matcher The matcher for advised methods.
* @param name The name of the advice class.
*/
protected ForUnifiedAdvice(LatentMatcher<? super MethodDescription> matcher, String name) {
super(matcher);
this.name = name;
}
@Override
protected Advice resolve(Advice.WithCustomMapping advice, TypePool typePool, ClassFileLocator classFileLocator) {
return advice.to(typePool.describe(name).resolve(), classFileLocator);
}
}
/**
* An entry for an advice class where both entry and exit advice methods are declared by the different classes.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class ForSplitAdvice extends Entry {
/**
* The fully-qualified, binary name of the enter advice class.
*/
private final String enter;
/**
* The fully-qualified, binary name of the exit advice class.
*/
private final String exit;
/**
* Creates a new entry for an advice class with explicit entry and exit advice classes.
*
* @param matcher The matcher for advised methods.
* @param enter The fully-qualified, binary name of the enter advice class.
* @param exit The fully-qualified, binary name of the exit advice class.
*/
protected ForSplitAdvice(LatentMatcher<? super MethodDescription> matcher, String enter, String exit) {
super(matcher);
this.enter = enter;
this.exit = exit;
}
@Override
protected Advice resolve(Advice.WithCustomMapping advice, TypePool typePool, ClassFileLocator classFileLocator) {
return advice.to(typePool.describe(enter).resolve(), typePool.describe(exit).resolve(), classFileLocator);
}
}
}
}
}
/**
* A type locator allows to specify how {@link TypeDescription}s are resolved by an {@link net.bytebuddy.agent.builder.AgentBuilder}.
*/
interface PoolStrategy {
/**
* Creates a type pool for a given class file locator.
*
* @param classFileLocator The class file locator to use.
* @param classLoader The class loader for which the class file locator was created.
* @return A type pool for the supplied class file locator.
*/
TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader);
/**
* <p>
* A default type locator that resolves types only if any property that is not the type's name is requested.
* </p>
* <p>
* The returned type pool uses a {@link net.bytebuddy.pool.TypePool.CacheProvider.Simple} and the
* {@link ClassFileLocator} that is provided by the builder's {@link LocationStrategy}.
* </p>
*/
enum Default implements PoolStrategy {
/**
* A type locator that parses the code segment of each method for extracting information about parameter
* names even if they are not explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#EXTENDED
*/
EXTENDED(TypePool.Default.ReaderMode.EXTENDED),
/**
* A type locator that skips the code segment of each method and does therefore not extract information
* about parameter names. Parameter names are still included if they are explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#FAST
*/
FAST(TypePool.Default.ReaderMode.FAST);
/**
* The reader mode to apply by this type locator.
*/
private final TypePool.Default.ReaderMode readerMode;
/**
* Creates a new type locator.
*
* @param readerMode The reader mode to apply by this type locator.
*/
Default(TypePool.Default.ReaderMode readerMode) {
this.readerMode = readerMode;
}
/**
* {@inheritDoc}
*/
public TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader) {
return new TypePool.Default.WithLazyResolution(TypePool.CacheProvider.Simple.withObjectType(), classFileLocator, readerMode);
}
}
/**
* <p>
* A type locator that resolves all type descriptions eagerly.
* </p>
* <p>
* The returned type pool uses a {@link net.bytebuddy.pool.TypePool.CacheProvider.Simple} and the
* {@link ClassFileLocator} that is provided by the builder's {@link LocationStrategy}.
* </p>
*/
enum Eager implements PoolStrategy {
/**
* A type locator that parses the code segment of each method for extracting information about parameter
* names even if they are not explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#EXTENDED
*/
EXTENDED(TypePool.Default.ReaderMode.EXTENDED),
/**
* A type locator that skips the code segment of each method and does therefore not extract information
* about parameter names. Parameter names are still included if they are explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#FAST
*/
FAST(TypePool.Default.ReaderMode.FAST);
/**
* The reader mode to apply by this type locator.
*/
private final TypePool.Default.ReaderMode readerMode;
/**
* Creates a new type locator.
*
* @param readerMode The reader mode to apply by this type locator.
*/
Eager(TypePool.Default.ReaderMode readerMode) {
this.readerMode = readerMode;
}
/**
* {@inheritDoc}
*/
public TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader) {
return new TypePool.Default(TypePool.CacheProvider.Simple.withObjectType(), classFileLocator, readerMode);
}
}
/**
* <p>
* A type locator that attempts loading a type if it cannot be located by the underlying lazy type pool.
* </p>
* <p>
* The returned type pool uses a {@link net.bytebuddy.pool.TypePool.CacheProvider.Simple} and the
* {@link ClassFileLocator} that is provided by the builder's {@link LocationStrategy}. Any types
* are loaded via the instrumented type's {@link ClassLoader}.
* </p>
*/
enum ClassLoading implements PoolStrategy {
/**
* A type locator that parses the code segment of each method for extracting information about parameter
* names even if they are not explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#EXTENDED
*/
EXTENDED(TypePool.Default.ReaderMode.EXTENDED),
/**
* A type locator that skips the code segment of each method and does therefore not extract information
* about parameter names. Parameter names are still included if they are explicitly included in a class file.
*
* @see net.bytebuddy.pool.TypePool.Default.ReaderMode#FAST
*/
FAST(TypePool.Default.ReaderMode.FAST);
/**
* The reader mode to apply by this type locator.
*/
private final TypePool.Default.ReaderMode readerMode;
/**
* Creates a new type locator.
*
* @param readerMode The reader mode to apply by this type locator.
*/
ClassLoading(TypePool.Default.ReaderMode readerMode) {
this.readerMode = readerMode;
}
/**
* {@inheritDoc}
*/
public TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader) {
return TypePool.ClassLoading.of(classLoader, new TypePool.Default.WithLazyResolution(TypePool.CacheProvider.Simple.withObjectType(), classFileLocator, readerMode));
}
}
/**
* <p>
* A type locator that uses type pools but allows for the configuration of a custom cache provider by class loader. Note that a
* {@link TypePool} can grow in size and that a static reference is kept to this pool by Byte Buddy's registration of a
* {@link ClassFileTransformer} what can cause a memory leak if the supplied caches are not cleared on a regular basis. Also note
* that a cache provider can be accessed concurrently by multiple {@link ClassLoader}s.
* </p>
* <p>
* All types that are returned by the locator's type pool are resolved lazily.
* </p>
*/
@HashCodeAndEqualsPlugin.Enhance
abstract class WithTypePoolCache implements PoolStrategy {
/**
* The reader mode to use for parsing a class file.
*/
protected final TypePool.Default.ReaderMode readerMode;
/**
* Creates a new type locator that creates {@link TypePool}s but provides a custom {@link net.bytebuddy.pool.TypePool.CacheProvider}.
*
* @param readerMode The reader mode to use for parsing a class file.
*/
protected WithTypePoolCache(TypePool.Default.ReaderMode readerMode) {
this.readerMode = readerMode;
}
/**
* {@inheritDoc}
*/
public TypePool typePool(ClassFileLocator classFileLocator, ClassLoader classLoader) {
return new TypePool.Default.WithLazyResolution(locate(classLoader), classFileLocator, readerMode);
}
/**
* Locates a cache provider for a given class loader.
*
* @param classLoader The class loader for which to locate a cache. This class loader might be {@code null} to represent the bootstrap loader.
* @return The cache provider to use.
*/
protected abstract TypePool.CacheProvider locate(ClassLoader classLoader);
/**
* An implementation of a type locator {@link WithTypePoolCache} (note documentation of the linked class) that is based on a
* {@link ConcurrentMap}. It is the responsibility of the type locator's user to avoid the type locator from leaking memory.
*/
@HashCodeAndEqualsPlugin.Enhance
public static class Simple extends WithTypePoolCache {
/**
* The concurrent map that is used for storing a cache provider per class loader.
*/
private final ConcurrentMap<? super ClassLoader, TypePool.CacheProvider> cacheProviders;
/**
* Creates a new type locator that caches a cache provider per class loader in a concurrent map. The type
* locator uses a fast {@link net.bytebuddy.pool.TypePool.Default.ReaderMode}.
*
* @param cacheProviders The concurrent map that is used for storing a cache provider per class loader.
*/
public Simple(ConcurrentMap<? super ClassLoader, TypePool.CacheProvider> cacheProviders) {
this(TypePool.Default.ReaderMode.FAST, cacheProviders);
}
/**
* Creates a new type locator that caches a cache provider per class loader in a concurrent map.
*
* @param readerMode The reader mode to use for parsing a class file.
* @param cacheProviders The concurrent map that is used for storing a cache provider per class loader.
*/
public Simple(TypePool.Default.ReaderMode readerMode, ConcurrentMap<? super ClassLoader, TypePool.CacheProvider> cacheProviders) {
super(readerMode);
this.cacheProviders = cacheProviders;
}
@Override
protected TypePool.CacheProvider locate(ClassLoader classLoader) {
classLoader = classLoader == null ? getBootstrapMarkerLoader() : classLoader;
TypePool.CacheProvider cacheProvider = cacheProviders.get(classLoader);
while (cacheProvider == null) {
cacheProvider = TypePool.CacheProvider.Simple.withObjectType();
TypePool.CacheProvider previous = cacheProviders.putIfAbsent(classLoader, cacheProvider);
if (previous != null) {
cacheProvider = previous;
}
}
return cacheProvider;
}
/**
* <p>
* Returns the class loader to serve as a cache key if a cache provider for the bootstrap class loader is requested.
* This class loader is represented by {@code null} in the JVM which is an invalid value for many {@link ConcurrentMap}
* implementations.
* </p>
* <p>
* By default, {@link ClassLoader#getSystemClassLoader()} is used as such a key as any resource location for the
* bootstrap class loader is performed via the system class loader within Byte Buddy as {@code null} cannot be queried
* for resources via method calls such that this does not make a difference.
* </p>
*
* @return A class loader to represent the bootstrap class loader.
*/
protected ClassLoader getBootstrapMarkerLoader() {
return ClassLoader.getSystemClassLoader();
}
}
}
}
/**
* An initialization strategy which determines the handling of {@link net.bytebuddy.implementation.LoadedTypeInitializer}s
* and the loading of auxiliary types. The agent builder does not reuse the {@link TypeResolutionStrategy} as Javaagents cannot access
* a loaded class after a transformation such that different initialization strategies become meaningful.
*/
interface InitializationStrategy {
/**
* Creates a new dispatcher for injecting this initialization strategy during a transformation process.
*
* @return The dispatcher to be used.
*/
Dispatcher dispatcher();
/**
* A dispatcher for changing a class file to adapt a self-initialization strategy.
*/
interface Dispatcher {
/**
* Transforms the instrumented type to implement an appropriate initialization strategy.
*
* @param builder The builder which should implement the initialization strategy.
* @return The given {@code builder} with the initialization strategy applied.
*/
DynamicType.Builder<?> apply(DynamicType.Builder<?> builder);
/**
* Registers a dynamic type for initialization and/or begins the initialization process.
*
* @param dynamicType The dynamic type that is created.
* @param classLoader The class loader of the dynamic type which can be {@code null} to represent the bootstrap class loader.
* @param protectionDomain The instrumented type's protection domain or {@code null} if no protection domain is available.
* @param injectionStrategy The injection strategy to use.
*/
void register(DynamicType dynamicType, ClassLoader classLoader, ProtectionDomain protectionDomain, InjectionStrategy injectionStrategy);
}
/**
* A non-initializing initialization strategy.
*/
enum NoOp implements InitializationStrategy, Dispatcher {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Dispatcher dispatcher() {
return this;
}
/**
* {@inheritDoc}
*/
public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder) {
return builder;
}
/**
* {@inheritDoc}
*/
public void register(DynamicType dynamicType, ClassLoader classLoader, ProtectionDomain protectionDomain, InjectionStrategy injectionStrategy) {
/* do nothing */
}
}
/**
* An initialization strategy that loads auxiliary types before loading the instrumented type. This strategy skips all types
* that are a subtype of the instrumented type which would cause a premature loading of the instrumented type and abort
* the instrumentation process.
*/
enum Minimal implements InitializationStrategy, Dispatcher {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Dispatcher dispatcher() {
return this;
}
/**
* {@inheritDoc}
*/
public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder) {
return builder;
}
/**
* {@inheritDoc}
*/
public void register(DynamicType dynamicType, ClassLoader classLoader, ProtectionDomain protectionDomain, InjectionStrategy injectionStrategy) {
Map<TypeDescription, byte[]> auxiliaryTypes = dynamicType.getAuxiliaryTypes();
Map<TypeDescription, byte[]> independentTypes = new LinkedHashMap<TypeDescription, byte[]>(auxiliaryTypes);
for (TypeDescription auxiliaryType : auxiliaryTypes.keySet()) {
if (!auxiliaryType.getDeclaredAnnotations().isAnnotationPresent(AuxiliaryType.SignatureRelevant.class)) {
independentTypes.remove(auxiliaryType);
}
}
if (!independentTypes.isEmpty()) {
ClassInjector classInjector = injectionStrategy.resolve(classLoader, protectionDomain);
Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers = dynamicType.getLoadedTypeInitializers();
for (Map.Entry<TypeDescription, Class<?>> entry : classInjector.inject(independentTypes).entrySet()) {
loadedTypeInitializers.get(entry.getKey()).onLoad(entry.getValue());
}
}
}
}
/**
* An initialization strategy that adds a code block to an instrumented type's type initializer which
* then calls a specific class that is responsible for the explicit initialization.
*/
@HashCodeAndEqualsPlugin.Enhance
abstract class SelfInjection implements InitializationStrategy {
/**
* The nexus accessor to use.
*/
protected final NexusAccessor nexusAccessor;
/**
* Creates a new self-injection strategy.
*
* @param nexusAccessor The nexus accessor to use.
*/
protected SelfInjection(NexusAccessor nexusAccessor) {
this.nexusAccessor = nexusAccessor;
}
/**
* {@inheritDoc}
*/
@SuppressFBWarnings(value = "DMI_RANDOM_USED_ONLY_ONCE", justification = "Avoiding synchronization without security concerns")
public InitializationStrategy.Dispatcher dispatcher() {
return dispatcher(new Random().nextInt());
}
/**
* Creates a new dispatcher.
*
* @param identification The identification code to use.
* @return An appropriate dispatcher for an initialization strategy.
*/
protected abstract InitializationStrategy.Dispatcher dispatcher(int identification);
/**
* A dispatcher for a self-initialization strategy.
*/
@HashCodeAndEqualsPlugin.Enhance
protected abstract static class Dispatcher implements InitializationStrategy.Dispatcher {
/**
* The nexus accessor to use.
*/
protected final NexusAccessor nexusAccessor;
/**
* A random identification for the applied self-initialization.
*/
protected final int identification;
/**
* Creates a new dispatcher.
*
* @param nexusAccessor The nexus accessor to use.
* @param identification A random identification for the applied self-initialization.
*/
protected Dispatcher(NexusAccessor nexusAccessor, int identification) {
this.nexusAccessor = nexusAccessor;
this.identification = identification;
}
/**
* {@inheritDoc}
*/
public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder) {
return builder.initializer(new NexusAccessor.InitializationAppender(identification));
}
/**
* A type initializer that injects all auxiliary types of the instrumented type.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class InjectingInitializer implements LoadedTypeInitializer {
/**
* The instrumented type.
*/
private final TypeDescription instrumentedType;
/**
* The auxiliary types mapped to their class file representation.
*/
private final Map<TypeDescription, byte[]> rawAuxiliaryTypes;
/**
* The instrumented types and auxiliary types mapped to their loaded type initializers.
* The instrumented types and auxiliary types mapped to their loaded type initializers.
*/
private final Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers;
/**
* The class injector to use.
*/
private final ClassInjector classInjector;
/**
* Creates a new injection initializer.
*
* @param instrumentedType The instrumented type.
* @param rawAuxiliaryTypes The auxiliary types mapped to their class file representation.
* @param loadedTypeInitializers The instrumented types and auxiliary types mapped to their loaded type initializers.
* @param classInjector The class injector to use.
*/
protected InjectingInitializer(TypeDescription instrumentedType,
Map<TypeDescription, byte[]> rawAuxiliaryTypes,
Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers,
ClassInjector classInjector) {
this.instrumentedType = instrumentedType;
this.rawAuxiliaryTypes = rawAuxiliaryTypes;
this.loadedTypeInitializers = loadedTypeInitializers;
this.classInjector = classInjector;
}
/**
* {@inheritDoc}
*/
public void onLoad(Class<?> type) {
for (Map.Entry<TypeDescription, Class<?>> auxiliary : classInjector.inject(rawAuxiliaryTypes).entrySet()) {
loadedTypeInitializers.get(auxiliary.getKey()).onLoad(auxiliary.getValue());
}
loadedTypeInitializers.get(instrumentedType).onLoad(type);
}
/**
* {@inheritDoc}
*/
public boolean isAlive() {
return true;
}
}
}
/**
* A form of self-injection where auxiliary types that are annotated by
* {@link net.bytebuddy.implementation.auxiliary.AuxiliaryType.SignatureRelevant} of the instrumented type are loaded lazily and
* any other auxiliary type is loaded eagerly.
*/
public static class Split extends SelfInjection {
/**
* Creates a new split self-injection strategy that uses a default nexus accessor.
*/
public Split() {
this(new NexusAccessor());
}
/**
* Creates a new split self-injection strategy that uses the supplied nexus accessor.
*
* @param nexusAccessor The nexus accessor to use.
*/
public Split(NexusAccessor nexusAccessor) {
super(nexusAccessor);
}
@Override
protected InitializationStrategy.Dispatcher dispatcher(int identification) {
return new Dispatcher(nexusAccessor, identification);
}
/**
* A dispatcher for the {@link net.bytebuddy.agent.builder.AgentBuilder.InitializationStrategy.SelfInjection.Split} strategy.
*/
protected static class Dispatcher extends SelfInjection.Dispatcher {
/**
* Creates a new split dispatcher.
*
* @param nexusAccessor The nexus accessor to use.
* @param identification A random identification for the applied self-initialization.
*/
protected Dispatcher(NexusAccessor nexusAccessor, int identification) {
super(nexusAccessor, identification);
}
/**
* {@inheritDoc}
*/
public void register(DynamicType dynamicType, ClassLoader classLoader, ProtectionDomain protectionDomain, InjectionStrategy injectionStrategy) {
Map<TypeDescription, byte[]> auxiliaryTypes = dynamicType.getAuxiliaryTypes();
LoadedTypeInitializer loadedTypeInitializer;
if (!auxiliaryTypes.isEmpty()) {
TypeDescription instrumentedType = dynamicType.getTypeDescription();
ClassInjector classInjector = injectionStrategy.resolve(classLoader, protectionDomain);
Map<TypeDescription, byte[]> independentTypes = new LinkedHashMap<TypeDescription, byte[]>(auxiliaryTypes);
Map<TypeDescription, byte[]> dependentTypes = new LinkedHashMap<TypeDescription, byte[]>(auxiliaryTypes);
for (TypeDescription auxiliaryType : auxiliaryTypes.keySet()) {
(auxiliaryType.getDeclaredAnnotations().isAnnotationPresent(AuxiliaryType.SignatureRelevant.class)
? dependentTypes
: independentTypes).remove(auxiliaryType);
}
Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers = dynamicType.getLoadedTypeInitializers();
if (!independentTypes.isEmpty()) {
for (Map.Entry<TypeDescription, Class<?>> entry : classInjector.inject(independentTypes).entrySet()) {
loadedTypeInitializers.get(entry.getKey()).onLoad(entry.getValue());
}
}
Map<TypeDescription, LoadedTypeInitializer> lazyInitializers = new HashMap<TypeDescription, LoadedTypeInitializer>(loadedTypeInitializers);
loadedTypeInitializers.keySet().removeAll(independentTypes.keySet());
loadedTypeInitializer = lazyInitializers.size() > 1 // there exist auxiliary types that need lazy loading
? new Dispatcher.InjectingInitializer(instrumentedType, dependentTypes, lazyInitializers, classInjector)
: lazyInitializers.get(instrumentedType);
} else {
loadedTypeInitializer = dynamicType.getLoadedTypeInitializers().get(dynamicType.getTypeDescription());
}
nexusAccessor.register(dynamicType.getTypeDescription().getName(), classLoader, identification, loadedTypeInitializer);
}
}
}
/**
* A form of self-injection where any auxiliary type is loaded lazily.
*/
public static class Lazy extends SelfInjection {
/**
* Creates a new lazy self-injection strategy that uses a default nexus accessor.
*/
public Lazy() {
this(new NexusAccessor());
}
/**
* Creates a new lazy self-injection strategy that uses the supplied nexus accessor.
*
* @param nexusAccessor The nexus accessor to use.
*/
public Lazy(NexusAccessor nexusAccessor) {
super(nexusAccessor);
}
@Override
protected InitializationStrategy.Dispatcher dispatcher(int identification) {
return new Dispatcher(nexusAccessor, identification);
}
/**
* A dispatcher for the {@link net.bytebuddy.agent.builder.AgentBuilder.InitializationStrategy.SelfInjection.Lazy} strategy.
*/
protected static class Dispatcher extends SelfInjection.Dispatcher {
/**
* Creates a new lazy dispatcher.
*
* @param nexusAccessor The nexus accessor to use.
* @param identification A random identification for the applied self-initialization.
*/
protected Dispatcher(NexusAccessor nexusAccessor, int identification) {
super(nexusAccessor, identification);
}
/**
* {@inheritDoc}
*/
public void register(DynamicType dynamicType, ClassLoader classLoader, ProtectionDomain protectionDomain, InjectionStrategy injectionStrategy) {
Map<TypeDescription, byte[]> auxiliaryTypes = dynamicType.getAuxiliaryTypes();
LoadedTypeInitializer loadedTypeInitializer = auxiliaryTypes.isEmpty()
? dynamicType.getLoadedTypeInitializers().get(dynamicType.getTypeDescription())
: new Dispatcher.InjectingInitializer(dynamicType.getTypeDescription(), auxiliaryTypes, dynamicType.getLoadedTypeInitializers(), injectionStrategy.resolve(classLoader, protectionDomain));
nexusAccessor.register(dynamicType.getTypeDescription().getName(), classLoader, identification, loadedTypeInitializer);
}
}
}
/**
* A form of self-injection where any auxiliary type is loaded eagerly.
*/
public static class Eager extends SelfInjection {
/**
* Creates a new eager self-injection strategy that uses a default nexus accessor.
*/
public Eager() {
this(new NexusAccessor());
}
/**
* Creates a new eager self-injection strategy that uses the supplied nexus accessor.
*
* @param nexusAccessor The nexus accessor to use.
*/
public Eager(NexusAccessor nexusAccessor) {
super(nexusAccessor);
}
@Override
protected InitializationStrategy.Dispatcher dispatcher(int identification) {
return new Dispatcher(nexusAccessor, identification);
}
/**
* A dispatcher for the {@link net.bytebuddy.agent.builder.AgentBuilder.InitializationStrategy.SelfInjection.Eager} strategy.
*/
protected static class Dispatcher extends SelfInjection.Dispatcher {
/**
* Creates a new eager dispatcher.
*
* @param nexusAccessor The nexus accessor to use.
* @param identification A random identification for the applied self-initialization.
*/
protected Dispatcher(NexusAccessor nexusAccessor, int identification) {
super(nexusAccessor, identification);
}
/**
* {@inheritDoc}
*/
public void register(DynamicType dynamicType, ClassLoader classLoader, ProtectionDomain protectionDomain, InjectionStrategy injectionStrategy) {
Map<TypeDescription, byte[]> auxiliaryTypes = dynamicType.getAuxiliaryTypes();
Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers = dynamicType.getLoadedTypeInitializers();
if (!auxiliaryTypes.isEmpty()) {
for (Map.Entry<TypeDescription, Class<?>> entry : injectionStrategy.resolve(classLoader, protectionDomain).inject(auxiliaryTypes).entrySet()) {
loadedTypeInitializers.get(entry.getKey()).onLoad(entry.getValue());
}
}
LoadedTypeInitializer loadedTypeInitializer = loadedTypeInitializers.get(dynamicType.getTypeDescription());
nexusAccessor.register(dynamicType.getTypeDescription().getName(), classLoader, identification, loadedTypeInitializer);
}
}
}
}
}
/**
* A strategy for injecting auxiliary types into a class loader.
*/
interface InjectionStrategy {
/**
* Resolves the class injector to use for a given class loader and protection domain.
*
* @param classLoader The class loader to use.
* @param protectionDomain The protection domain to use.
* @return The class injector to use.
*/
ClassInjector resolve(ClassLoader classLoader, ProtectionDomain protectionDomain);
/**
* An injection strategy that does not permit class injection.
*/
enum Disabled implements InjectionStrategy {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public ClassInjector resolve(ClassLoader classLoader, ProtectionDomain protectionDomain) {
throw new IllegalStateException("Class injection is disabled");
}
}
/**
* An injection strategy that uses Java reflection. This strategy is not capable of injecting classes into the bootstrap class loader.
*/
enum UsingReflection implements InjectionStrategy {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public ClassInjector resolve(ClassLoader classLoader, ProtectionDomain protectionDomain) {
if (classLoader == null) {
throw new IllegalStateException("Cannot inject auxiliary class into bootstrap loader using reflection");
} else if (ClassInjector.UsingReflection.isAvailable()) {
return new ClassInjector.UsingReflection(classLoader, protectionDomain);
} else {
throw new IllegalStateException("Reflection-based injection is not available on the current VM");
}
}
}
/**
* An injection strategy that uses {@code sun.misc.Unsafe} to inject classes.
*/
enum UsingUnsafe implements InjectionStrategy {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public ClassInjector resolve(ClassLoader classLoader, ProtectionDomain protectionDomain) {
if (ClassInjector.UsingUnsafe.isAvailable()) {
return new ClassInjector.UsingUnsafe(classLoader, protectionDomain);
} else {
throw new IllegalStateException("Unsafe-based injection is not available on the current VM");
}
}
/**
* An injection strategy that uses a factory for creating an unsafe injector.
*/
@HashCodeAndEqualsPlugin.Enhance
public static class OfFactory implements InjectionStrategy {
/**
* The factory to use for creating an unsafe injector.
*/
private final ClassInjector.UsingUnsafe.Factory factory;
/**
* Creates an injection strategy based on a factory.
*
* @param factory The factory to use for creating an unsafe injector.
*/
public OfFactory(ClassInjector.UsingUnsafe.Factory factory) {
this.factory = factory;
}
/**
* {@inheritDoc}
*/
public ClassInjector resolve(ClassLoader classLoader, ProtectionDomain protectionDomain) {
return factory.make(classLoader, protectionDomain);
}
}
}
/**
* An injection strategy that uses bootstrap injection using an {@link Instrumentation} instance.
*/
@HashCodeAndEqualsPlugin.Enhance
class UsingInstrumentation implements InjectionStrategy {
/**
* The instrumentation instance to use.
*/
private final Instrumentation instrumentation;
/**
* The folder to store jar files being used for bootstrap injection.
*/
private final File folder;
/**
* Creates a new bootstrap injection strategy.
*
* @param instrumentation The instrumentation instance to use.
* @param folder The folder to store jar files being used for bootstrap injection.
*/
public UsingInstrumentation(Instrumentation instrumentation, File folder) {
this.instrumentation = instrumentation;
this.folder = folder;
}
/**
* {@inheritDoc}
*/
public ClassInjector resolve(ClassLoader classLoader, ProtectionDomain protectionDomain) {
return classLoader == null
? ClassInjector.UsingInstrumentation.of(folder, ClassInjector.UsingInstrumentation.Target.BOOTSTRAP, instrumentation)
: UsingReflection.INSTANCE.resolve(classLoader, protectionDomain);
}
}
}
/**
* A description strategy is responsible for resolving a {@link TypeDescription} when transforming or retransforming/-defining a type.
*/
interface DescriptionStrategy {
/**
* Indicates if this description strategy makes use of loaded type information and yields a different type description if no loaded type is available.
*
* @return {@code true} if this description strategy prefers loaded type information when describing a type and only uses a type pool
* if loaded type information is not available.
*/
boolean isLoadedFirst();
/**
* Describes the given type.
*
* @param typeName The binary name of the type to describe.
* @param type The type that is being redefined, if a redefinition is applied or {@code null} if no redefined type is available.
* @param typePool The type pool to use for locating a type if required.
* @param classLoader The type's class loader where {@code null} represents the bootstrap class loader.
* @param circularityLock The currently used circularity lock.
* @param module The type's module or {@code null} if the current VM does not support modules.
* @return An appropriate type description.
*/
TypeDescription apply(String typeName, Class<?> type, TypePool typePool, CircularityLock circularityLock, ClassLoader classLoader, JavaModule module);
/**
* Default implementations of a {@link DescriptionStrategy}.
*/
enum Default implements DescriptionStrategy {
/**
* A description type strategy represents a type as a {@link net.bytebuddy.description.type.TypeDescription.ForLoadedType} if a
* retransformation or redefinition is applied on a type. Using a loaded type typically results in better performance as no
* I/O is required for resolving type descriptions. However, any interaction with the type is carried out via the Java reflection
* API. Using the reflection API triggers eager loading of any type that is part of a method or field signature. If any of these
* types are missing from the class path, this eager loading will cause a {@link NoClassDefFoundError}. Some Java code declares
* optional dependencies to other classes which are only realized if the optional dependency is present. Such code relies on the
* Java reflection API not being used for types using optional dependencies.
*
* @see FallbackStrategy.Simple#ENABLED
* @see FallbackStrategy.ByThrowableType#ofOptionalTypes()
*/
HYBRID(true) {
/** {@inheritDoc} */
public TypeDescription apply(String typeName,
Class<?> type,
TypePool typePool,
CircularityLock circularityLock,
ClassLoader classLoader,
JavaModule module) {
return type == null
? typePool.describe(typeName).resolve()
: TypeDescription.ForLoadedType.of(type);
}
},
/**
* <p>
* A description strategy that always describes Java types using a {@link TypePool}. This requires that any type - even if it is already
* loaded and a {@link Class} instance is available - is processed as a non-loaded type description. Doing so can cause overhead as processing
* loaded types is supported very efficiently by a JVM.
* </p>
* <p>
* Avoiding the usage of loaded types can improve robustness as this approach does not rely on the Java reflection API which triggers eager
* validation of this loaded type which can fail an application if optional types are used by any types field or method signatures. Also, it
* is possible to guarantee debugging meta data to be available also for retransformed or redefined types if a {@link TypeStrategy} specifies
* the extraction of such meta data.
* </p>
*/
POOL_ONLY(false) {
/** {@inheritDoc} */
public TypeDescription apply(String typeName,
Class<?> type,
TypePool typePool,
CircularityLock circularityLock,
ClassLoader classLoader,
JavaModule module) {
return typePool.describe(typeName).resolve();
}
},
/**
* <p>
* A description strategy that always describes Java types using a {@link TypePool} unless a type cannot be resolved by a pool and a loaded
* {@link Class} instance is available. Doing so can cause overhead as processing loaded types is supported very efficiently by a JVM.
* </p>
* <p>
* Avoiding the usage of loaded types can improve robustness as this approach does not rely on the Java reflection API which triggers eager
* validation of this loaded type which can fail an application if optional types are used by any types field or method signatures. Also, it
* is possible to guarantee debugging meta data to be available also for retransformed or redefined types if a {@link TypeStrategy} specifies
* the extraction of such meta data.
* </p>
*/
POOL_FIRST(false) {
/** {@inheritDoc} */
public TypeDescription apply(String typeName,
Class<?> type,
TypePool typePool,
CircularityLock circularityLock,
ClassLoader classLoader,
JavaModule module) {
TypePool.Resolution resolution = typePool.describe(typeName);
return resolution.isResolved() || type == null
? resolution.resolve()
: TypeDescription.ForLoadedType.of(type);
}
};
/**
* Indicates if loaded type information is preferred over using a type pool for describing a type.
*/
private final boolean loadedFirst;
/**
* Indicates if loaded type information is preferred over using a type pool for describing a type.
*
* @param loadedFirst {@code true} if loaded type information is preferred over using a type pool for describing a type.
*/
Default(boolean loadedFirst) {
this.loadedFirst = loadedFirst;
}
/**
* Creates a description strategy that uses this strategy but loads any super type. If a super type is not yet loaded,
* this causes this super type to never be instrumented. Therefore, this option should only be used if all instrumented
* types are guaranteed to be top-level types.
*
* @return This description strategy where all super types are loaded during the instrumentation.
* @see SuperTypeLoading
*/
public DescriptionStrategy withSuperTypeLoading() {
return new SuperTypeLoading(this);
}
/**
* {@inheritDoc}
*/
public boolean isLoadedFirst() {
return loadedFirst;
}
/**
* Creates a description strategy that uses this strategy but loads any super type asynchronously. Super types are loaded via
* another thread supplied by the executor service to enforce the instrumentation of any such super type. It is recommended
* to allow the executor service to create new threads without bound as class loading blocks any thread until all super types
* were instrumented.
*
* @param executorService The executor service to use.
* @return This description strategy where all super types are loaded asynchronously during the instrumentation.
* @see SuperTypeLoading.Asynchronous
*/
public DescriptionStrategy withSuperTypeLoading(ExecutorService executorService) {
return new SuperTypeLoading.Asynchronous(this, executorService);
}
}
/**
* <p>
* A description strategy that enforces the loading of any super type of a type description but delegates the actual type description
* to another description strategy.
* </p>
* <p>
* <b>Warning</b>: When using this description strategy, a type is not instrumented if any of its subtypes is loaded first.
* The instrumentation API does not submit such types to a class file transformer on most VM implementations.
* </p>
*/
@HashCodeAndEqualsPlugin.Enhance
class SuperTypeLoading implements DescriptionStrategy {
/**
* The delegate description strategy.
*/
private final DescriptionStrategy delegate;
/**
* Creates a new description strategy that enforces loading of a super type.
*
* @param delegate The delegate description strategy.
*/
public SuperTypeLoading(DescriptionStrategy delegate) {
this.delegate = delegate;
}
/**
* {@inheritDoc}
*/
public boolean isLoadedFirst() {
return delegate.isLoadedFirst();
}
/**
* {@inheritDoc}
*/
public TypeDescription apply(String typeName,
Class<?> type,
TypePool typePool,
CircularityLock circularityLock,
ClassLoader classLoader,
JavaModule module) {
TypeDescription typeDescription = delegate.apply(typeName, type, typePool, circularityLock, classLoader, module);
return typeDescription instanceof TypeDescription.ForLoadedType
? typeDescription
: new TypeDescription.SuperTypeLoading(typeDescription, classLoader, new UnlockingClassLoadingDelegate(circularityLock));
}
/**
* A class loading delegate that unlocks the circularity lock during class loading.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class UnlockingClassLoadingDelegate implements TypeDescription.SuperTypeLoading.ClassLoadingDelegate {
/**
* The circularity lock to unlock.
*/
private final CircularityLock circularityLock;
/**
* Creates an unlocking class loading delegate.
*
* @param circularityLock The circularity lock to unlock.
*/
protected UnlockingClassLoadingDelegate(CircularityLock circularityLock) {
this.circularityLock = circularityLock;
}
/**
* {@inheritDoc}
*/
public Class<?> load(String name, ClassLoader classLoader) throws ClassNotFoundException {
circularityLock.release();
try {
return Class.forName(name, false, classLoader);
} finally {
circularityLock.acquire();
}
}
}
/**
* <p>
* A description strategy that enforces the loading of any super type of a type description but delegates the actual type description
* to another description strategy.
* </p>
* <p>
* <b>Note</b>: This description strategy delegates class loading to another thread in order to enforce the instrumentation of any
* unloaded super type. This requires the executor service to supply at least as many threads as the deepest type hierarchy within the
* application minus one for the instrumented type as class loading blocks any thread until all of its super types are loaded. These
* threads are typically short lived which predestines the use of a {@link Executors#newCachedThreadPool()} without any upper bound
* for the maximum number of created threads.
* </p>
* <p>
* <b>Important</b>: This strategy can dead-lock under two circumstances:
* </p>
* <ul>
* <li>
* <b>Classes declare circularities</b>: Under normal circumstances, such scenarios result in a {@link ClassCircularityError} but
* can result in dead-locks when using this instrumentation strategy.
* </li>
* <li>
* <b>Class loaders declare custom locks</b>: If a class loader locks another lock but itself during class loading, this lock cannot
* be released by this strategy.
* </li>
* </ul>
* <p>
* For the above reasons, it is not recommended to use this strategy when the target class loader is unknown or if the target application
* might contain corrupt class files.
* </p>
*/
@HashCodeAndEqualsPlugin.Enhance
public static class Asynchronous implements DescriptionStrategy {
/**
* The delegate description strategy.
*/
private final DescriptionStrategy delegate;
/**
* The executor service to use for loading super types.
*/
private final ExecutorService executorService;
/**
* Creates a new description strategy that enforces super type loading from another thread.
*
* @param delegate The delegate description strategy.
* @param executorService The executor service to use for loading super types.
*/
public Asynchronous(DescriptionStrategy delegate, ExecutorService executorService) {
this.delegate = delegate;
this.executorService = executorService;
}
/**
* {@inheritDoc}
*/
public boolean isLoadedFirst() {
return delegate.isLoadedFirst();
}
/**
* {@inheritDoc}
*/
public TypeDescription apply(String typeName,
Class<?> type,
TypePool typePool,
CircularityLock circularityLock,
ClassLoader classLoader,
JavaModule module) {
TypeDescription typeDescription = delegate.apply(typeName, type, typePool, circularityLock, classLoader, module);
return typeDescription instanceof TypeDescription.ForLoadedType
? typeDescription
: new TypeDescription.SuperTypeLoading(typeDescription, classLoader, new ThreadSwitchingClassLoadingDelegate(executorService));
}
/**
* A class loading delegate that delegates loading of the super type to another thread.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class ThreadSwitchingClassLoadingDelegate implements TypeDescription.SuperTypeLoading.ClassLoadingDelegate {
/**
* The executor service to delegate class loading to.
*/
private final ExecutorService executorService;
/**
* Creates a new thread-switching class loading delegate.
*
* @param executorService The executor service to delegate class loading to.
*/
protected ThreadSwitchingClassLoadingDelegate(ExecutorService executorService) {
this.executorService = executorService;
}
/**
* {@inheritDoc}
*/
public Class<?> load(String name, ClassLoader classLoader) {
boolean holdsLock = classLoader != null && Thread.holdsLock(classLoader);
AtomicBoolean signal = new AtomicBoolean(holdsLock);
Future<Class<?>> future = executorService.submit(holdsLock
? new NotifyingClassLoadingAction(name, classLoader, signal)
: new SimpleClassLoadingAction(name, classLoader));
try {
while (holdsLock && signal.get()) {
classLoader.wait();
}
return future.get();
} catch (ExecutionException exception) {
throw new IllegalStateException("Could not load " + name + " asynchronously", exception.getCause());
} catch (Exception exception) {
throw new IllegalStateException("Could not load " + name + " asynchronously", exception);
}
}
/**
* A class loading action that simply loads a type.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class SimpleClassLoadingAction implements Callable<Class<?>> {
/**
* The loaded type's name.
*/
private final String name;
/**
* The type's class loader or {@code null} if the type is loaded by the bootstrap loader.
*/
private final ClassLoader classLoader;
/**
* Creates a simple class loading action.
*
* @param name The loaded type's name.
* @param classLoader The type's class loader or {@code null} if the type is loaded by the bootstrap loader.
*/
protected SimpleClassLoadingAction(String name, ClassLoader classLoader) {
this.name = name;
this.classLoader = classLoader;
}
/**
* {@inheritDoc}
*/
public Class<?> call() throws ClassNotFoundException {
return Class.forName(name, false, classLoader);
}
}
/**
* A class loading action that notifies the class loader's lock after the type was loaded.
*/
protected static class NotifyingClassLoadingAction implements Callable<Class<?>> {
/**
* The loaded type's name.
*/
private final String name;
/**
* The type's class loader or {@code null} if the type is loaded by the bootstrap loader.
*/
private final ClassLoader classLoader;
/**
* The signal that indicates the completion of the class loading with {@code false}.
*/
private final AtomicBoolean signal;
/**
* Creates a notifying class loading action.
*
* @param name The loaded type's name.
* @param classLoader The type's class loader or {@code null} if the type is loaded by the bootstrap loader.
* @param signal The signal that indicates the completion of the class loading with {@code false}.
*/
protected NotifyingClassLoadingAction(String name, ClassLoader classLoader, AtomicBoolean signal) {
this.name = name;
this.classLoader = classLoader;
this.signal = signal;
}
/**
* {@inheritDoc}
*/
public Class<?> call() throws ClassNotFoundException {
synchronized (classLoader) {
try {
return Class.forName(name, false, classLoader);
} finally {
signal.set(false);
classLoader.notifyAll();
}
}
}
}
}
}
}
}
/**
* A strategy for creating a {@link ClassFileLocator} when instrumenting a type.
*/
interface LocationStrategy {
/**
* Creates a class file locator for a given class loader and module combination.
*
* @param classLoader The class loader that is loading an instrumented type. Might be {@code null} to represent the bootstrap class loader.
* @param module The type's module or {@code null} if Java modules are not supported on the current VM.
* @return The class file locator to use.
*/
ClassFileLocator classFileLocator(ClassLoader classLoader, JavaModule module);
/**
* A location strategy that never locates any byte code.
*/
enum NoOp implements LocationStrategy {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public ClassFileLocator classFileLocator(ClassLoader classLoader, JavaModule module) {
return ClassFileLocator.NoOp.INSTANCE;
}
}
/**
* A location strategy that locates class files by querying an instrumented type's {@link ClassLoader}.
*/
enum ForClassLoader implements LocationStrategy {
/**
* A location strategy that keeps a strong reference to the class loader the created class file locator represents.
*/
STRONG {
/** {@inheritDoc} */
public ClassFileLocator classFileLocator(ClassLoader classLoader, JavaModule module) {
return ClassFileLocator.ForClassLoader.of(classLoader);
}
},
/**
* A location strategy that keeps a weak reference to the class loader the created class file locator represents.
* As a consequence, any returned class file locator stops working once the represented class loader is garbage collected.
*/
WEAK {
/** {@inheritDoc} */
public ClassFileLocator classFileLocator(ClassLoader classLoader, JavaModule module) {
return ClassFileLocator.ForClassLoader.WeaklyReferenced.of(classLoader);
}
};
/**
* Adds additional location strategies as fallbacks to this location strategy.
*
* @param classFileLocator The class file locators to query if this location strategy cannot locate a class file.
* @return A compound location strategy that first applies this location strategy and then queries the supplied class file locators.
*/
public LocationStrategy withFallbackTo(ClassFileLocator... classFileLocator) {
return withFallbackTo(Arrays.asList(classFileLocator));
}
/**
* Adds additional location strategies as fallbacks to this location strategy.
*
* @param classFileLocators The class file locators to query if this location strategy cannot locate a class file.
* @return A compound location strategy that first applies this location strategy and then queries the supplied class file locators.
*/
public LocationStrategy withFallbackTo(Collection<? extends ClassFileLocator> classFileLocators) {
List<LocationStrategy> locationStrategies = new ArrayList<LocationStrategy>(classFileLocators.size());
for (ClassFileLocator classFileLocator : classFileLocators) {
locationStrategies.add(new Simple(classFileLocator));
}
return withFallbackTo(locationStrategies);
}
/**
* Adds additional location strategies as fallbacks to this location strategy.
*
* @param locationStrategy The fallback location strategies to use.
* @return A compound location strategy that first applies this location strategy and then the supplied fallback location strategies
* in the supplied order.
*/
public LocationStrategy withFallbackTo(LocationStrategy... locationStrategy) {
return withFallbackTo(Arrays.asList(locationStrategy));
}
/**
* Adds additional location strategies as fallbacks to this location strategy.
*
* @param locationStrategies The fallback location strategies to use.
* @return A compound location strategy that first applies this location strategy and then the supplied fallback location strategies
* in the supplied order.
*/
public LocationStrategy withFallbackTo(List<? extends LocationStrategy> locationStrategies) {
List<LocationStrategy> allLocationStrategies = new ArrayList<LocationStrategy>(locationStrategies.size() + 1);
allLocationStrategies.add(this);
allLocationStrategies.addAll(locationStrategies);
return new Compound(allLocationStrategies);
}
}
/**
* A simple location strategy that queries a given class file locator.
*/
@HashCodeAndEqualsPlugin.Enhance
class Simple implements LocationStrategy {
/**
* The class file locator to query.
*/
private final ClassFileLocator classFileLocator;
/**
* A simple location strategy that queries a given class file locator.
*
* @param classFileLocator The class file locator to query.
*/
public Simple(ClassFileLocator classFileLocator) {
this.classFileLocator = classFileLocator;
}
/**
* {@inheritDoc}
*/
public ClassFileLocator classFileLocator(ClassLoader classLoader, JavaModule module) {
return classFileLocator;
}
}
/**
* A compound location strategy that applies a list of location strategies.
*/
@HashCodeAndEqualsPlugin.Enhance
class Compound implements LocationStrategy {
/**
* The location strategies in their application order.
*/
private final List<LocationStrategy> locationStrategies;
/**
* Creates a new compound location strategy.
*
* @param locationStrategy The location strategies in their application order.
*/
public Compound(LocationStrategy... locationStrategy) {
this(Arrays.asList(locationStrategy));
}
/**
* Creates a new compound location strategy.
*
* @param locationStrategies The location strategies in their application order.
*/
public Compound(List<? extends LocationStrategy> locationStrategies) {
this.locationStrategies = new ArrayList<LocationStrategy>();
for (LocationStrategy locationStrategy : locationStrategies) {
if (locationStrategy instanceof Compound) {
this.locationStrategies.addAll(((Compound) locationStrategy).locationStrategies);
} else if (!(locationStrategy instanceof NoOp)) {
this.locationStrategies.add(locationStrategy);
}
}
}
/**
* {@inheritDoc}
*/
public ClassFileLocator classFileLocator(ClassLoader classLoader, JavaModule module) {
List<ClassFileLocator> classFileLocators = new ArrayList<ClassFileLocator>(locationStrategies.size());
for (LocationStrategy locationStrategy : locationStrategies) {
classFileLocators.add(locationStrategy.classFileLocator(classLoader, module));
}
return new ClassFileLocator.Compound(classFileLocators);
}
}
}
/**
* A fallback strategy allows to reattempt a transformation or a consideration for redefinition/retransformation in case an exception
* occurs. Doing so, it is possible to use a {@link TypePool} rather than using a loaded type description backed by a {@link Class}.
* Loaded types can raise exceptions and errors if a {@link ClassLoader} cannot resolve all types that this class references. Using
* a type pool, such errors can be avoided as type descriptions can be resolved lazily, avoiding such errors.
*/
interface FallbackStrategy {
/**
* Returns {@code true} if the supplied type and throwable combination should result in a reattempt where the
* loaded type is not used for querying information.
*
* @param type The loaded type that was queried during the transformation attempt.
* @param throwable The error or exception that was caused during the transformation.
* @return {@code true} if the supplied type and throwable combination should
*/
boolean isFallback(Class<?> type, Throwable throwable);
/**
* A simple fallback strategy that either always reattempts a transformation or never does so.
*/
enum Simple implements FallbackStrategy {
/**
* An enabled fallback strategy that always attempts a new trial.
*/
ENABLED(true),
/**
* A disabled fallback strategy that never attempts a new trial.
*/
DISABLED(false);
/**
* {@code true} if this fallback strategy is enabled.
*/
private final boolean enabled;
/**
* Creates a new default fallback strategy.
*
* @param enabled {@code true} if this fallback strategy is enabled.
*/
Simple(boolean enabled) {
this.enabled = enabled;
}
/**
* {@inheritDoc}
*/
public boolean isFallback(Class<?> type, Throwable throwable) {
return enabled;
}
}
/**
* A fallback strategy that discriminates by the type of the {@link Throwable} that triggered a request.
*/
@HashCodeAndEqualsPlugin.Enhance
class ByThrowableType implements FallbackStrategy {
/**
* A set of throwable types that should trigger a fallback attempt.
*/
private final Set<? extends Class<? extends Throwable>> types;
/**
* Creates a new throwable type-discriminating fallback strategy.
*
* @param type The throwable types that should trigger a fallback.
*/
@SuppressWarnings("unchecked") // In absence of @SafeVarargs
public ByThrowableType(Class<? extends Throwable>... type) {
this(new HashSet<Class<? extends Throwable>>(Arrays.asList(type)));
}
/**
* Creates a new throwable type-discriminating fallback strategy.
*
* @param types The throwable types that should trigger a fallback.
*/
public ByThrowableType(Set<? extends Class<? extends Throwable>> types) {
this.types = types;
}
/**
* Creates a fallback strategy that attempts a fallback if an error indicating a type error is the reason for requesting a reattempt.
*
* @return A fallback strategy that triggers a reattempt if a {@link LinkageError} or a {@link TypeNotPresentException} is raised.
*/
@SuppressWarnings("unchecked") // In absence of @SafeVarargs
public static FallbackStrategy ofOptionalTypes() {
return new ByThrowableType(LinkageError.class, TypeNotPresentException.class);
}
/**
* {@inheritDoc}
*/
public boolean isFallback(Class<?> type, Throwable throwable) {
for (Class<? extends Throwable> aType : types) {
if (aType.isInstance(throwable)) {
return true;
}
}
return false;
}
}
}
/**
* A listener that is notified during the installation and the resetting of a class file transformer.
*/
interface InstallationListener {
/**
* Indicates that an exception is handled.
*/
Throwable SUPPRESS_ERROR = null;
/**
* Invoked prior to the installation of a class file transformer.
*
* @param instrumentation The instrumentation on which the class file transformer is installed.
* @param classFileTransformer The class file transformer that is being installed.
*/
void onBeforeInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer);
/**
* Invoked upon the successful installation of a class file transformer. This method is only invoked if no error occurred during the
* installation or if such an error was handled by {@link InstallationListener#onError(Instrumentation, ResettableClassFileTransformer, Throwable)}.
*
* @param instrumentation The instrumentation on which the class file transformer is installed.
* @param classFileTransformer The class file transformer that is being installed.
*/
void onInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer);
/**
* Invoked if an installation causes an error. The listener has an opportunity to handle the error. This method is invoked prior to
* {@link InstallationListener#onInstall(Instrumentation, ResettableClassFileTransformer)}.
*
* @param instrumentation The instrumentation on which the class file transformer is installed.
* @param classFileTransformer The class file transformer that is being installed.
* @param throwable The throwable that causes the error.
* @return The error to propagate or {@code null} if the error is handled. Any subsequent listeners are not called if the exception is handled.
*/
Throwable onError(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer, Throwable throwable);
/**
* Invoked if an installation is reset.
*
* @param instrumentation The instrumentation on which the class file transformer is installed.
* @param classFileTransformer The class file transformer that is being installed.
*/
void onReset(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer);
/**
* A non-operational listener that does not do anything.
*/
enum NoOp implements InstallationListener {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public void onBeforeInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public Throwable onError(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer, Throwable throwable) {
return throwable;
}
/**
* {@inheritDoc}
*/
public void onReset(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
/* do nothing */
}
}
/**
* A listener that suppresses any installation error.
*/
enum ErrorSuppressing implements InstallationListener {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public void onBeforeInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public Throwable onError(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer, Throwable throwable) {
return SUPPRESS_ERROR;
}
/**
* {@inheritDoc}
*/
public void onReset(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
/* do nothing */
}
}
/**
* An adapter implementation for an installation listener that serves as a convenience.
*/
abstract class Adapter implements InstallationListener {
/**
* {@inheritDoc}
*/
public void onBeforeInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public void onInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public Throwable onError(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer, Throwable throwable) {
return throwable;
}
/**
* {@inheritDoc}
*/
public void onReset(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
/* do nothing */
}
}
/**
* This installation listener prints the status of any installation to a {@link PrintStream}.
*/
@HashCodeAndEqualsPlugin.Enhance
class StreamWriting implements InstallationListener {
/**
* The prefix prepended to any message written.
*/
protected static final String PREFIX = "[Byte Buddy]";
/**
* The print stream to write to.
*/
private final PrintStream printStream;
/**
* Creates a new stream writing installation listener.
*
* @param printStream The print stream to write to.
*/
public StreamWriting(PrintStream printStream) {
this.printStream = printStream;
}
/**
* Creates a stream writing installation listener that prints to {@link System#out}.
*
* @return An installation listener that prints to {@link System#out}.
*/
public static InstallationListener toSystemOut() {
return new StreamWriting(System.out);
}
/**
* Creates a stream writing installation listener that prints to {@link System#err}.
*
* @return An installation listener that prints to {@link System#err}.
*/
public static InstallationListener toSystemError() {
return new StreamWriting(System.err);
}
/**
* {@inheritDoc}
*/
public void onBeforeInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
printStream.printf(PREFIX + " BEFORE_INSTALL %s on %s%n", classFileTransformer, instrumentation);
}
/**
* {@inheritDoc}
*/
public void onInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
printStream.printf(PREFIX + " INSTALL %s on %s%n", classFileTransformer, instrumentation);
}
/**
* {@inheritDoc}
*/
public Throwable onError(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer, Throwable throwable) {
synchronized (printStream) {
printStream.printf(PREFIX + " ERROR %s on %s%n", classFileTransformer, instrumentation);
throwable.printStackTrace(printStream);
}
return throwable;
}
/**
* {@inheritDoc}
*/
public void onReset(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
printStream.printf(PREFIX + " RESET %s on %s%n", classFileTransformer, instrumentation);
}
}
/**
* A compound installation listener.
*/
@HashCodeAndEqualsPlugin.Enhance
class Compound implements InstallationListener {
/**
* The installation listeners to notify.
*/
private final List<InstallationListener> installationListeners;
/**
* Creates a new compound listener.
*
* @param installationListener The installation listeners to notify.
*/
public Compound(InstallationListener... installationListener) {
this(Arrays.asList(installationListener));
}
/**
* Creates a new compound listener.
*
* @param installationListeners The installation listeners to notify.
*/
public Compound(List<? extends InstallationListener> installationListeners) {
this.installationListeners = new ArrayList<InstallationListener>();
for (InstallationListener installationListener : installationListeners) {
if (installationListener instanceof Compound) {
this.installationListeners.addAll(((Compound) installationListener).installationListeners);
} else if (!(installationListener instanceof NoOp)) {
this.installationListeners.add(installationListener);
}
}
}
/**
* {@inheritDoc}
*/
public void onBeforeInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
for (InstallationListener installationListener : installationListeners) {
installationListener.onBeforeInstall(instrumentation, classFileTransformer);
}
}
/**
* {@inheritDoc}
*/
public void onInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
for (InstallationListener installationListener : installationListeners) {
installationListener.onInstall(instrumentation, classFileTransformer);
}
}
/**
* {@inheritDoc}
*/
public Throwable onError(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer, Throwable throwable) {
for (InstallationListener installationListener : installationListeners) {
if (throwable == SUPPRESS_ERROR) {
return SUPPRESS_ERROR;
}
throwable = installationListener.onError(instrumentation, classFileTransformer, throwable);
}
return throwable;
}
/**
* {@inheritDoc}
*/
public void onReset(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
for (InstallationListener installationListener : installationListeners) {
installationListener.onReset(instrumentation, classFileTransformer);
}
}
}
}
/**
* This strategy determines how the provided class file buffer is used.
*/
interface ClassFileBufferStrategy {
/**
* Resolves a class file locator for the class file buffer that is provided to the class file transformer.
*
* @param name The instrumented type's binary name.
* @param binaryRepresentation The instrumented type's binary representation.
* @param classLoader The instrumented type's class loader or {@code null} if the type is loaded by the bootstrap class loader.
* @param module The instrumented type's module or {@code null} if the current VM does not support modules.
* @param protectionDomain The instrumented type's protection domain.
* @return An appropriate class file locator.
*/
ClassFileLocator resolve(String name, byte[] binaryRepresentation, ClassLoader classLoader, JavaModule module, ProtectionDomain protectionDomain);
/**
* An implementation of default class file buffer strategy.
*/
enum Default implements ClassFileBufferStrategy {
/**
* A class file buffer strategy that retains the original class file buffer.
*/
RETAINING {
/** {@inheritDoc} */
public ClassFileLocator resolve(String name,
byte[] binaryRepresentation,
ClassLoader classLoader,
JavaModule module,
ProtectionDomain protectionDomain) {
return ClassFileLocator.Simple.of(name, binaryRepresentation);
}
},
/**
* <p>
* A class file buffer strategy that discards the original class file buffer.
* </p>
* <p>
* <b>Warning</b>: This strategy discards any changes that were applied by previous Java agents.
* </p>
*/
DISCARDING {
/** {@inheritDoc} */
public ClassFileLocator resolve(String name,
byte[] binaryRepresentation,
ClassLoader classLoader,
JavaModule module,
ProtectionDomain protectionDomain) {
return ClassFileLocator.NoOp.INSTANCE;
}
}
}
}
/**
* A decorator that allows to change the class file transformer that is registered.
*/
interface TransformerDecorator {
/**
* Decorates the applied class file transformer.
*
* @param classFileTransformer The original transformer created by the agent builder.
* @return The class file transformer that is actually being registered.
*/
ResettableClassFileTransformer decorate(ResettableClassFileTransformer classFileTransformer);
/**
* A transformer decorator that retains the original transformer.
*/
enum NoOp implements TransformerDecorator {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer decorate(ResettableClassFileTransformer classFileTransformer) {
return classFileTransformer;
}
}
/**
* A compound transformer decorator.
*/
@HashCodeAndEqualsPlugin.Enhance
class Compound implements TransformerDecorator {
/**
* The listeners to invoke.
*/
private final List<TransformerDecorator> transformerDecorators;
/**
* Creates a new compound transformer decorator.
*
* @param transformerDecorator The transformer decorators to add.
*/
public Compound(TransformerDecorator... transformerDecorator) {
this(Arrays.asList(transformerDecorator));
}
/**
* Creates a new compound listener.
*
* @param transformerDecorators The transformerDecorators to invoke.
*/
public Compound(List<? extends TransformerDecorator> transformerDecorators) {
this.transformerDecorators = new ArrayList<TransformerDecorator>();
for (TransformerDecorator transformerDecorator : transformerDecorators) {
if (transformerDecorator instanceof Compound) {
this.transformerDecorators.addAll(((Compound) transformerDecorator).transformerDecorators);
} else if (!(transformerDecorator instanceof NoOp)) {
this.transformerDecorators.add(transformerDecorator);
}
}
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer decorate(ResettableClassFileTransformer classFileTransformer) {
for (TransformerDecorator transformerDecorator : transformerDecorators) {
classFileTransformer = transformerDecorator.decorate(classFileTransformer);
}
return classFileTransformer;
}
}
}
/**
* <p>
* A redefinition strategy regulates how already loaded classes are modified by a built agent.
* </p>
* <p>
* <b>Important</b>: Most JVMs do not support changes of a class's structure after a class was already
* loaded. Therefore, it is typically required that this class file transformer was built while enabling
* {@link AgentBuilder#disableClassFormatChanges()}.
* </p>
*/
enum RedefinitionStrategy {
/**
* Disables redefinition such that already loaded classes are not affected by the agent.
*/
DISABLED(false, false) {
@Override
public void apply(Instrumentation instrumentation,
AgentBuilder.Listener listener,
CircularityLock circularityLock,
PoolStrategy poolStrategy,
LocationStrategy locationStrategy,
DiscoveryStrategy discoveryStrategy,
BatchAllocator redefinitionBatchAllocator,
Listener redefinitionListener,
LambdaInstrumentationStrategy lambdaInstrumentationStrategy,
DescriptionStrategy descriptionStrategy,
FallbackStrategy fallbackStrategy,
RawMatcher matcher) {
/* do nothing */
}
@Override
protected void check(Instrumentation instrumentation) {
throw new IllegalStateException("Cannot apply redefinition on disabled strategy");
}
@Override
protected Collector make() {
throw new IllegalStateException("A disabled redefinition strategy cannot create a collector");
}
},
/**
* <p>
* Applies a <b>redefinition</b> to all classes that are already loaded and that would have been transformed if
* the built agent was registered before they were loaded. The created {@link ClassFileTransformer} is <b>not</b>
* registered for applying retransformations.
* </p>
* <p>
* Using this strategy, a redefinition is applied as a single transformation request. This means that a single illegal
* redefinition of a class causes the entire redefinition attempt to fail.
* </p>
* <p>
* <b>Note</b>: When applying a redefinition, it is normally required to use a {@link TypeStrategy} that applies
* a redefinition instead of rebasing classes such as {@link TypeStrategy.Default#REDEFINE}. Also, consider
* the constrains given by this type strategy.
* </p>
*/
REDEFINITION(true, false) {
@Override
protected void check(Instrumentation instrumentation) {
if (!instrumentation.isRedefineClassesSupported()) {
throw new IllegalStateException("Cannot apply redefinition on " + instrumentation);
}
}
@Override
protected Collector make() {
return new Collector.ForRedefinition();
}
},
/**
* <p>
* Applies a <b>retransformation</b> to all classes that are already loaded and that would have been transformed if
* the built agent was registered before they were loaded. The created {@link ClassFileTransformer} is registered
* for applying retransformations.
* </p>
* <p>
* Using this strategy, a retransformation is applied as a single transformation request. This means that a single illegal
* retransformation of a class causes the entire retransformation attempt to fail.
* </p>
* <p>
* <b>Note</b>: When applying a retransformation, it is normally required to use a {@link TypeStrategy} that applies
* a redefinition instead of rebasing classes such as {@link TypeStrategy.Default#REDEFINE}. Also, consider
* the constrains given by this type strategy.
* </p>
*/
RETRANSFORMATION(true, true) {
@Override
protected void check(Instrumentation instrumentation) {
if (!DISPATCHER.isRetransformClassesSupported(instrumentation)) {
throw new IllegalStateException("Cannot apply retransformation on " + instrumentation);
}
}
@Override
protected Collector make() {
return new Collector.ForRetransformation();
}
};
/**
* A dispatcher to use for interacting with the instrumentation API.
*/
protected static final Dispatcher DISPATCHER = AccessController.doPrivileged(Dispatcher.CreationAction.INSTANCE);
/**
* Indicates that this redefinition strategy is enabled.
*/
private final boolean enabled;
/**
* {@code true} if this strategy applies retransformation.
*/
private final boolean retransforming;
/**
* Creates a new redefinition strategy.
*
* @param enabled {@code true} if this strategy is enabled.
* @param retransforming {@code true} if this strategy applies retransformation.
*/
RedefinitionStrategy(boolean enabled, boolean retransforming) {
this.enabled = enabled;
this.retransforming = retransforming;
}
/**
* Indicates if this strategy requires a class file transformer to be registered with a hint to apply the
* transformer for retransformation.
*
* @return {@code true} if a class file transformer must be registered with a hint for retransformation.
*/
protected boolean isRetransforming() {
return retransforming;
}
/**
* Checks if this strategy can be applied to the supplied instrumentation instance.
*
* @param instrumentation The instrumentation instance to validate.
*/
protected abstract void check(Instrumentation instrumentation);
/**
* Indicates that this redefinition strategy applies a modification of already loaded classes.
*
* @return {@code true} if this redefinition strategy applies a modification of already loaded classes.
*/
protected boolean isEnabled() {
return enabled;
}
/**
* Creates a collector instance that is responsible for collecting loaded classes for potential retransformation.
*
* @return A new collector for collecting already loaded classes for transformation.
*/
protected abstract Collector make();
/**
* Applies this redefinition strategy by submitting all loaded types to redefinition. If this redefinition strategy is disabled,
* this method is non-operational.
*
* @param instrumentation The instrumentation instance to use.
* @param listener The listener to notify on transformations.
* @param circularityLock The circularity lock to use.
* @param poolStrategy The type locator to use.
* @param locationStrategy The location strategy to use.
* @param redefinitionDiscoveryStrategy The discovery strategy for loaded types to be redefined.
* @param redefinitionBatchAllocator The batch allocator for the redefinition strategy to apply.
* @param redefinitionListener The redefinition listener for the redefinition strategy to apply.
* @param lambdaInstrumentationStrategy A strategy to determine of the {@code LambdaMetafactory} should be instrumented to allow for the
* instrumentation of classes that represent lambda expressions.
* @param descriptionStrategy The description strategy for resolving type descriptions for types.
* @param fallbackStrategy The fallback strategy to apply.
* @param matcher The matcher to identify what types to redefine.
*/
protected void apply(Instrumentation instrumentation,
AgentBuilder.Listener listener,
CircularityLock circularityLock,
PoolStrategy poolStrategy,
LocationStrategy locationStrategy,
DiscoveryStrategy redefinitionDiscoveryStrategy,
BatchAllocator redefinitionBatchAllocator,
Listener redefinitionListener,
LambdaInstrumentationStrategy lambdaInstrumentationStrategy,
DescriptionStrategy descriptionStrategy,
FallbackStrategy fallbackStrategy,
RawMatcher matcher) {
check(instrumentation);
int batch = RedefinitionStrategy.BatchAllocator.FIRST_BATCH;
for (Iterable<Class<?>> types : redefinitionDiscoveryStrategy.resolve(instrumentation)) {
RedefinitionStrategy.Collector collector = make();
for (Class<?> type : types) {
if (type == null || type.isArray() || !lambdaInstrumentationStrategy.isInstrumented(type)) {
continue;
}
JavaModule module = JavaModule.ofType(type);
try {
TypePool typePool = poolStrategy.typePool(locationStrategy.classFileLocator(type.getClassLoader(), module), type.getClassLoader());
try {
collector.consider(matcher,
listener,
descriptionStrategy.apply(TypeDescription.ForLoadedType.getName(type), type, typePool, circularityLock, type.getClassLoader(), module),
type,
type,
module,
!DISPATCHER.isModifiableClass(instrumentation, type));
} catch (Throwable throwable) {
if (descriptionStrategy.isLoadedFirst() && fallbackStrategy.isFallback(type, throwable)) {
collector.consider(matcher,
listener,
typePool.describe(TypeDescription.ForLoadedType.getName(type)).resolve(),
type,
module);
} else {
throw throwable;
}
}
} catch (Throwable throwable) {
try {
try {
listener.onDiscovery(TypeDescription.ForLoadedType.getName(type), type.getClassLoader(), module, AgentBuilder.Listener.LOADED);
} finally {
try {
listener.onError(TypeDescription.ForLoadedType.getName(type), type.getClassLoader(), module, AgentBuilder.Listener.LOADED, throwable);
} finally {
listener.onComplete(TypeDescription.ForLoadedType.getName(type), type.getClassLoader(), module, AgentBuilder.Listener.LOADED);
}
}
} catch (Throwable ignored) {
// Ignore exceptions that are thrown by listeners to mimic the behavior of a transformation.
}
}
}
batch = collector.apply(instrumentation, circularityLock, locationStrategy, listener, redefinitionBatchAllocator, redefinitionListener, batch);
}
}
/**
* A batch allocator which is responsible for applying a redefinition in a batches. A class redefinition or
* retransformation can be a time-consuming operation rendering a JVM non-responsive. In combination with a
* a {@link RedefinitionStrategy.Listener}, it is also possible to apply pauses between batches to distribute
* the load of a retransformation over time.
*/
public interface BatchAllocator {
/**
* The index of the first batch.
*/
int FIRST_BATCH = 0;
/**
* Splits a list of types to be retransformed into separate batches.
*
* @param types A list of types which should be retransformed.
* @return An iterable of retransformations within a batch.
*/
Iterable<? extends List<Class<?>>> batch(List<Class<?>> types);
/**
* A batch allocator that includes all types in a single batch.
*/
enum ForTotal implements BatchAllocator {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Iterable<? extends List<Class<?>>> batch(List<Class<?>> types) {
return types.isEmpty()
? Collections.<List<Class<?>>>emptySet()
: Collections.singleton(types);
}
}
/**
* A batch allocator that creates chunks with a fixed size as batch jobs.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForFixedSize implements BatchAllocator {
/**
* The size of each chunk.
*/
private final int size;
/**
* Creates a new batch allocator that creates fixed-sized chunks.
*
* @param size The size of each chunk.
*/
protected ForFixedSize(int size) {
this.size = size;
}
/**
* Creates a new batch allocator that creates chunks of a fixed size.
*
* @param size The size of each chunk or {@code 0} if the batch should be included in a single chunk.
* @return An appropriate batch allocator.
*/
public static BatchAllocator ofSize(int size) {
if (size > 0) {
return new ForFixedSize(size);
} else if (size == 0) {
return ForTotal.INSTANCE;
} else {
throw new IllegalArgumentException("Cannot define a batch with a negative size: " + size);
}
}
/**
* {@inheritDoc}
*/
public Iterable<? extends List<Class<?>>> batch(List<Class<?>> types) {
List<List<Class<?>>> batches = new ArrayList<List<Class<?>>>();
for (int index = 0; index < types.size(); index += size) {
batches.add(new ArrayList<Class<?>>(types.subList(index, Math.min(types.size(), index + size))));
}
return batches;
}
}
/**
* A batch allocator that groups all batches by discriminating types using a type matcher.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForMatchedGrouping implements BatchAllocator {
/**
* The type matchers to apply.
*/
private final Collection<? extends ElementMatcher<? super TypeDescription>> matchers;
/**
* Creates a new batch allocator that groups all batches by discriminating types using a type matcher. All batches
* are applied in their application order with any unmatched type being included in the last batch.
*
* @param matcher The type matchers to apply in their application order.
*/
@SuppressWarnings("unchecked") // In absence of @SafeVarargs
public ForMatchedGrouping(ElementMatcher<? super TypeDescription>... matcher) {
this(new LinkedHashSet<ElementMatcher<? super TypeDescription>>(Arrays.asList(matcher)));
}
/**
* Creates a new batch allocator that groups all batches by discriminating types using a type matcher. All batches
* are applied in their application order with any unmatched type being included in the last batch.
*
* @param matchers The type matchers to apply in their application order.
*/
public ForMatchedGrouping(Collection<? extends ElementMatcher<? super TypeDescription>> matchers) {
this.matchers = matchers;
}
/**
* Assures that any group is at least of a given size. If a group is smaller than a given size, it is merged with its types
* are merged with its subsequent group(s) as long as such groups exist.
*
* @param threshold The minimum threshold for any batch.
* @return An appropriate batch allocator.
*/
public BatchAllocator withMinimum(int threshold) {
return Slicing.withMinimum(threshold, this);
}
/**
* Assures that any group is at least of a given size. If a group is bigger than a given size, it is split into two several
* batches.
*
* @param threshold The maximum threshold for any batch.
* @return An appropriate batch allocator.
*/
public BatchAllocator withMaximum(int threshold) {
return Slicing.withMaximum(threshold, this);
}
/**
* Assures that any group is within a size range described by the supplied minimum and maximum. Groups are split and merged
* according to the supplied thresholds. The last group contains might be smaller than the supplied minimum.
*
* @param minimum The minimum threshold for any batch.
* @param maximum The maximum threshold for any batch.
* @return An appropriate batch allocator.
*/
public BatchAllocator withinRange(int minimum, int maximum) {
return Slicing.withinRange(minimum, maximum, this);
}
/**
* {@inheritDoc}
*/
public Iterable<? extends List<Class<?>>> batch(List<Class<?>> types) {
Map<ElementMatcher<? super TypeDescription>, List<Class<?>>> matched = new LinkedHashMap<ElementMatcher<? super TypeDescription>, List<Class<?>>>();
List<Class<?>> unmatched = new ArrayList<Class<?>>();
for (ElementMatcher<? super TypeDescription> matcher : matchers) {
matched.put(matcher, new ArrayList<Class<?>>());
}
typeLoop:
for (Class<?> type : types) {
for (ElementMatcher<? super TypeDescription> matcher : matchers) {
if (matcher.matches(TypeDescription.ForLoadedType.of(type))) {
matched.get(matcher).add(type);
continue typeLoop;
}
}
unmatched.add(type);
}
List<List<Class<?>>> batches = new ArrayList<List<Class<?>>>(matchers.size() + 1);
for (List<Class<?>> batch : matched.values()) {
if (!batch.isEmpty()) {
batches.add(batch);
}
}
if (!unmatched.isEmpty()) {
batches.add(unmatched);
}
return batches;
}
}
/**
* A slicing batch allocator that assures that any batch is within a certain size range.
*/
@HashCodeAndEqualsPlugin.Enhance
class Slicing implements BatchAllocator {
/**
* The minimum size of each slice.
*/
private final int minimum;
/**
* The maximum size of each slice.
*/
private final int maximum;
/**
* The delegate batch allocator.
*/
private final BatchAllocator batchAllocator;
/**
* Creates a new slicing batch allocator.
*
* @param minimum The minimum size of each slice.
* @param maximum The maximum size of each slice.
* @param batchAllocator The delegate batch allocator.
*/
protected Slicing(int minimum, int maximum, BatchAllocator batchAllocator) {
this.minimum = minimum;
this.maximum = maximum;
this.batchAllocator = batchAllocator;
}
/**
* Creates a new slicing batch allocator.
*
* @param minimum The minimum size of each slice.
* @param batchAllocator The delegate batch allocator.
* @return An appropriate slicing batch allocator.
*/
public static BatchAllocator withMinimum(int minimum, BatchAllocator batchAllocator) {
return withinRange(minimum, Integer.MAX_VALUE, batchAllocator);
}
/**
* Creates a new slicing batch allocator.
*
* @param maximum The maximum size of each slice.
* @param batchAllocator The delegate batch allocator.
* @return An appropriate slicing batch allocator.
*/
public static BatchAllocator withMaximum(int maximum, BatchAllocator batchAllocator) {
return withinRange(1, maximum, batchAllocator);
}
/**
* Creates a new slicing batch allocator.
*
* @param minimum The minimum size of each slice.
* @param maximum The maximum size of each slice.
* @param batchAllocator The delegate batch allocator.
* @return An appropriate slicing batch allocator.
*/
public static BatchAllocator withinRange(int minimum, int maximum, BatchAllocator batchAllocator) {
if (minimum <= 0) {
throw new IllegalArgumentException("Minimum must be a positive number: " + minimum);
} else if (minimum > maximum) {
throw new IllegalArgumentException("Minimum must not be bigger than maximum: " + minimum + " >" + maximum);
}
return new Slicing(minimum, maximum, batchAllocator);
}
/**
* {@inheritDoc}
*/
public Iterable<? extends List<Class<?>>> batch(List<Class<?>> types) {
return new SlicingIterable(minimum, maximum, batchAllocator.batch(types));
}
/**
* An iterable that slices batches into parts of a minimum and maximum size.
*/
protected static class SlicingIterable implements Iterable<List<Class<?>>> {
/**
* The minimum size of any slice.
*/
private final int minimum;
/**
* The maximum size of any slice.
*/
private final int maximum;
/**
* The delegate iterable.
*/
private final Iterable<? extends List<Class<?>>> iterable;
/**
* Creates a new slicing iterable.
*
* @param minimum The minimum size of any slice.
* @param maximum The maximum size of any slice.
* @param iterable The delegate iterable.
*/
protected SlicingIterable(int minimum, int maximum, Iterable<? extends List<Class<?>>> iterable) {
this.minimum = minimum;
this.maximum = maximum;
this.iterable = iterable;
}
/**
* {@inheritDoc}
*/
public Iterator<List<Class<?>>> iterator() {
return new SlicingIterator(minimum, maximum, iterable.iterator());
}
/**
* An iterator that slices batches into parts of a minimum and maximum size.
*/
protected static class SlicingIterator implements Iterator<List<Class<?>>> {
/**
* The minimum size of any slice.
*/
private final int minimum;
/**
* The maximum size of any slice.
*/
private final int maximum;
/**
* The delegate iterator.
*/
private final Iterator<? extends List<Class<?>>> iterator;
/**
* A buffer containing all types that surpassed the maximum.
*/
private List<Class<?>> buffer;
/**
* Creates a new slicing iterator.
*
* @param minimum The minimum size of any slice.
* @param maximum The maximum size of any slice.
* @param iterator The delegate iterator.
*/
protected SlicingIterator(int minimum, int maximum, Iterator<? extends List<Class<?>>> iterator) {
this.minimum = minimum;
this.maximum = maximum;
this.iterator = iterator;
buffer = new ArrayList<Class<?>>();
}
/**
* {@inheritDoc}
*/
public boolean hasNext() {
return !buffer.isEmpty() || iterator.hasNext();
}
/**
* {@inheritDoc}
*/
public List<Class<?>> next() {
if (buffer.isEmpty()) {
buffer = iterator.next();
}
while (buffer.size() < minimum && iterator.hasNext()) {
buffer.addAll(iterator.next());
}
if (buffer.size() > maximum) {
try {
return buffer.subList(0, maximum);
} finally {
buffer = new ArrayList<Class<?>>(buffer.subList(maximum, buffer.size()));
}
} else {
try {
return buffer;
} finally {
buffer = new ArrayList<Class<?>>();
}
}
}
/**
* {@inheritDoc}
*/
public void remove() {
throw new UnsupportedOperationException("remove");
}
}
}
}
/**
* A partitioning batch allocator that splits types for redefinition into a fixed amount of parts.
*/
@HashCodeAndEqualsPlugin.Enhance
class Partitioning implements BatchAllocator {
/**
* The amount of batches to generate.
*/
private final int parts;
/**
* Creates a new batch allocator that splits types for redefinition into a fixed amount of parts.
*
* @param parts The amount of parts to create.
*/
protected Partitioning(int parts) {
this.parts = parts;
}
/**
* Creates a part-splitting batch allocator.
*
* @param parts The amount of parts to create.
* @return A batch allocator that splits the redefined types into a fixed amount of batches.
*/
public static BatchAllocator of(int parts) {
if (parts < 1) {
throw new IllegalArgumentException("A batch size must be positive: " + parts);
}
return new Partitioning(parts);
}
/**
* {@inheritDoc}
*/
public Iterable<? extends List<Class<?>>> batch(List<Class<?>> types) {
if (types.isEmpty()) {
return Collections.emptyList();
} else {
List<List<Class<?>>> batches = new ArrayList<List<Class<?>>>();
int size = types.size() / parts, reminder = types.size() % parts;
for (int index = reminder; index < types.size(); index += size) {
batches.add(new ArrayList<Class<?>>(types.subList(index, index + size)));
}
if (batches.isEmpty()) {
return Collections.singletonList(types);
} else {
batches.get(0).addAll(0, types.subList(0, reminder));
return batches;
}
}
}
}
}
/**
* A listener to be applied during a redefinition.
*/
public interface Listener {
/**
* Invoked before applying a batch.
*
* @param index A running index of the batch starting at {@code 0}.
* @param batch The types included in this batch.
* @param types All types included in the redefinition.
*/
void onBatch(int index, List<Class<?>> batch, List<Class<?>> types);
/**
* Invoked upon an error during a batch. This method is not invoked if the failure handler handled this error.
*
* @param index A running index of the batch starting at {@code 0}.
* @param batch The types included in this batch.
* @param throwable The throwable that caused this invocation.
* @param types All types included in the redefinition.
* @return A set of classes which should be attempted to be redefined. Typically, this should be a subset of the classes
* contained in {@code batch} but not all classes.
*/
Iterable<? extends List<Class<?>>> onError(int index, List<Class<?>> batch, Throwable throwable, List<Class<?>> types);
/**
* Invoked upon completion of all batches.
*
* @param amount The total amount of batches that were executed.
* @param types All types included in the redefinition.
* @param failures A mapping of batch types to their unhandled failures.
*/
void onComplete(int amount, List<Class<?>> types, Map<List<Class<?>>, Throwable> failures);
/**
* A non-operational listener.
*/
enum NoOp implements Listener {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public void onBatch(int index, List<Class<?>> batch, List<Class<?>> types) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public Iterable<? extends List<Class<?>>> onError(int index, List<Class<?>> batch, Throwable throwable, List<Class<?>> types) {
return Collections.emptyList();
}
/**
* {@inheritDoc}
*/
public void onComplete(int amount, List<Class<?>> types, Map<List<Class<?>>, Throwable> failures) {
/* do nothing */
}
}
/**
* A listener that invokes {@link Thread#yield()} prior to every batch but the first batch.
*/
enum Yielding implements Listener {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public void onBatch(int index, List<Class<?>> batch, List<Class<?>> types) {
if (index > 0) {
Thread.yield();
}
}
/**
* {@inheritDoc}
*/
public Iterable<? extends List<Class<?>>> onError(int index, List<Class<?>> batch, Throwable throwable, List<Class<?>> types) {
return Collections.emptyList();
}
/**
* {@inheritDoc}
*/
public void onComplete(int amount, List<Class<?>> types, Map<List<Class<?>>, Throwable> failures) {
/* do nothing */
}
}
/**
* A listener that halts a retransformation process upon an exception.
*/
enum ErrorEscalating implements Listener {
/**
* A listener that fails the retransformation upon the first failed retransformation of a batch.
*/
FAIL_FAST {
/** {@inheritDoc} */
public Iterable<? extends List<Class<?>>> onError(int index, List<Class<?>> batch, Throwable throwable, List<Class<?>> types) {
throw new IllegalStateException("Could not transform any of " + batch, throwable);
}
/** {@inheritDoc} */
public void onComplete(int amount, List<Class<?>> types, Map<List<Class<?>>, Throwable> failures) {
/* do nothing */
}
},
/**
* A listener that fails the retransformation after all batches were executed if any error occurred.
*/
FAIL_LAST {
/** {@inheritDoc} */
public Iterable<? extends List<Class<?>>> onError(int index, List<Class<?>> batch, Throwable throwable, List<Class<?>> types) {
return Collections.emptyList();
}
/** {@inheritDoc} */
public void onComplete(int amount, List<Class<?>> types, Map<List<Class<?>>, Throwable> failures) {
if (!failures.isEmpty()) {
throw new IllegalStateException("Could not transform any of " + failures);
}
}
};
/**
* {@inheritDoc}
*/
public void onBatch(int index, List<Class<?>> batch, List<Class<?>> types) {
/* do nothing */
}
}
/**
* A listener adapter that offers non-operational implementations of all listener methods.
*/
@HashCodeAndEqualsPlugin.Enhance
abstract class Adapter implements Listener {
/**
* {@inheritDoc}
*/
public void onBatch(int index, List<Class<?>> batch, List<Class<?>> types) {
/* do nothing */
}
/**
* {@inheritDoc}
*/
public Iterable<? extends List<Class<?>>> onError(int index, List<Class<?>> batch, Throwable throwable, List<Class<?>> types) {
return Collections.emptyList();
}
/**
* {@inheritDoc}
*/
public void onComplete(int amount, List<Class<?>> types, Map<List<Class<?>>, Throwable> failures) {
/* do nothing */
}
}
/**
* <p>
* A batch reallocator allows to split up a failed retransformation into additional batches which are reenqueed to the
* current retransformation process. To do so, any batch with at least to classes is rerouted through a {@link BatchAllocator}
* which is responsible for regrouping the classes that failed to be retransformed into new batches.
* </p>
* <p>
* <b>Important</b>: To avoid endless looping over classes that cannot be successfully retransformed, the supplied batch
* allocator must not resubmit batches that previously failed as an identical outcome is likely.
* </p>
*/
@HashCodeAndEqualsPlugin.Enhance
class BatchReallocator extends Adapter {
/**
* The batch allocator to use for reallocating failed batches.
*/
private final BatchAllocator batchAllocator;
/**
* Creates a new batch reallocator.
*
* @param batchAllocator The batch allocator to use for reallocating failed batches.
*/
public BatchReallocator(BatchAllocator batchAllocator) {
this.batchAllocator = batchAllocator;
}
/**
* Creates a batch allocator that splits any batch into two parts and resubmits these parts as two batches.
*
* @return A batch reallocating batch listener that splits failed batches into two parts for resubmission.
*/
public static Listener splitting() {
return new BatchReallocator(new BatchAllocator.Partitioning(2));
}
@Override
public Iterable<? extends List<Class<?>>> onError(int index, List<Class<?>> batch, Throwable throwable, List<Class<?>> types) {
return batch.size() < 2
? Collections.<List<Class<?>>>emptyList()
: batchAllocator.batch(batch);
}
}
/**
* A listener that invokes {@link Thread#sleep(long)} prior to every batch but the first batch.
*/
@HashCodeAndEqualsPlugin.Enhance
class Pausing extends Adapter {
/**
* The time to sleep in milliseconds between every two batches.
*/
private final long value;
/**
* Creates a new pausing listener.
*
* @param value The time to sleep in milliseconds between every two batches.
*/
protected Pausing(long value) {
this.value = value;
}
/**
* Creates a listener that pauses for the specified amount of time. If the specified value is {@code 0}, a
* non-operational listener is returned.
*
* @param value The amount of time to pause between redefinition batches.
* @param timeUnit The time unit of {@code value}.
* @return An appropriate listener.
*/
public static Listener of(long value, TimeUnit timeUnit) {
if (value > 0L) {
return new Pausing(timeUnit.toMillis(value));
} else if (value == 0L) {
return NoOp.INSTANCE;
} else {
throw new IllegalArgumentException("Cannot sleep for a non-positive amount of time: " + value);
}
}
@Override
public void onBatch(int index, List<Class<?>> batch, List<Class<?>> types) {
if (index > 0) {
try {
Thread.sleep(value);
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
throw new RuntimeException("Sleep was interrupted", exception);
}
}
}
}
/**
* A listener that writes events to a {@link PrintStream}.
*/
@HashCodeAndEqualsPlugin.Enhance
class StreamWriting implements Listener {
/**
* The print stream to write any events to.
*/
private final PrintStream printStream;
/**
* Creates a new stream writing listener.
*
* @param printStream The print stream to write any events to.
*/
public StreamWriting(PrintStream printStream) {
this.printStream = printStream;
}
/**
* Writes the stream result to {@link System#out}.
*
* @return An appropriate listener.
*/
public static Listener toSystemOut() {
return new StreamWriting(System.out);
}
/**
* Writes the stream result to {@link System#err}.
*
* @return An appropriate listener.
*/
public static Listener toSystemError() {
return new StreamWriting(System.err);
}
/**
* {@inheritDoc}
*/
public void onBatch(int index, List<Class<?>> batch, List<Class<?>> types) {
printStream.printf(AgentBuilder.Listener.StreamWriting.PREFIX + " REDEFINE BATCH #%d [%d of %d type(s)]%n", index, batch.size(), types.size());
}
/**
* {@inheritDoc}
*/
public Iterable<? extends List<Class<?>>> onError(int index, List<Class<?>> batch, Throwable throwable, List<Class<?>> types) {
synchronized (printStream) {
printStream.printf(AgentBuilder.Listener.StreamWriting.PREFIX + " REDEFINE ERROR #%d [%d of %d type(s)]%n", index, batch.size(), types.size());
throwable.printStackTrace(printStream);
}
return Collections.emptyList();
}
/**
* {@inheritDoc}
*/
public void onComplete(int amount, List<Class<?>> types, Map<List<Class<?>>, Throwable> failures) {
printStream.printf(AgentBuilder.Listener.StreamWriting.PREFIX + " REDEFINE COMPLETE %d batch(es) containing %d types [%d failed batch(es)]%n", amount, types.size(), failures.size());
}
}
/**
* A compound listener that delegates events to several listeners.
*/
@HashCodeAndEqualsPlugin.Enhance
class Compound implements Listener {
/**
* The listeners to invoke.
*/
private final List<Listener> listeners;
/**
* Creates a new compound listener.
*
* @param listener The listeners to invoke.
*/
public Compound(Listener... listener) {
this(Arrays.asList(listener));
}
/**
* Creates a new compound listener.
*
* @param listeners The listeners to invoke.
*/
public Compound(List<? extends Listener> listeners) {
this.listeners = new ArrayList<Listener>();
for (Listener listener : listeners) {
if (listener instanceof Compound) {
this.listeners.addAll(((Compound) listener).listeners);
} else if (!(listener instanceof NoOp)) {
this.listeners.add(listener);
}
}
}
/**
* {@inheritDoc}
*/
public void onBatch(int index, List<Class<?>> batch, List<Class<?>> types) {
for (Listener listener : listeners) {
listener.onBatch(index, batch, types);
}
}
/**
* {@inheritDoc}
*/
public Iterable<? extends List<Class<?>>> onError(int index, List<Class<?>> batch, Throwable throwable, List<Class<?>> types) {
List<Iterable<? extends List<Class<?>>>> reattempts = new ArrayList<Iterable<? extends List<Class<?>>>>();
for (Listener listener : listeners) {
reattempts.add(listener.onError(index, batch, throwable, types));
}
return new CompoundIterable(reattempts);
}
/**
* {@inheritDoc}
*/
public void onComplete(int amount, List<Class<?>> types, Map<List<Class<?>>, Throwable> failures) {
for (Listener listener : listeners) {
listener.onComplete(amount, types, failures);
}
}
/**
* A compound iterable.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class CompoundIterable implements Iterable<List<Class<?>>> {
/**
* The iterables to consider.
*/
private final List<Iterable<? extends List<Class<?>>>> iterables;
/**
* Creates a compound iterable.
*
* @param iterables The iterables to consider.
*/
protected CompoundIterable(List<Iterable<? extends List<Class<?>>>> iterables) {
this.iterables = iterables;
}
/**
* {@inheritDoc}
*/
public Iterator<List<Class<?>>> iterator() {
return new CompoundIterator(new ArrayList<Iterable<? extends List<Class<?>>>>(iterables));
}
/**
* A compound iterator that combines several iterables.
*/
protected static class CompoundIterator implements Iterator<List<Class<?>>> {
/**
* The current iterator or {@code null} if no such iterator is defined.
*/
private Iterator<? extends List<Class<?>>> current;
/**
* A backlog of iterables to still consider.
*/
private final List<Iterable<? extends List<Class<?>>>> backlog;
/**
* Creates a compound iterator.
*
* @param iterables The iterables to consider.
*/
protected CompoundIterator(List<Iterable<? extends List<Class<?>>>> iterables) {
backlog = iterables;
forward();
}
/**
* {@inheritDoc}
*/
public boolean hasNext() {
return current != null && current.hasNext();
}
/**
* {@inheritDoc}
*/
public List<Class<?>> next() {
try {
if (current != null) {
return current.next();
} else {
throw new NoSuchElementException();
}
} finally {
forward();
}
}
/**
* Forwards the iterator to the next relevant iterable.
*/
private void forward() {
while ((current == null || !current.hasNext()) && !backlog.isEmpty()) {
current = backlog.remove(0).iterator();
}
}
/**
* {@inheritDoc}
*/
public void remove() {
throw new UnsupportedOperationException("remove");
}
}
}
}
}
/**
* A strategy for discovering types to redefine.
*/
public interface DiscoveryStrategy {
/**
* Resolves an iterable of types to retransform. Types might be loaded during a previous retransformation which might require
* multiple passes for a retransformation.
*
* @param instrumentation The instrumentation instance used for the redefinition.
* @return An iterable of types to consider for retransformation.
*/
Iterable<Iterable<Class<?>>> resolve(Instrumentation instrumentation);
/**
* A discovery strategy that considers all loaded types supplied by {@link Instrumentation#getAllLoadedClasses()}.
*/
enum SinglePass implements DiscoveryStrategy {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Iterable<Iterable<Class<?>>> resolve(Instrumentation instrumentation) {
return Collections.<Iterable<Class<?>>>singleton(Arrays.<Class<?>>asList(instrumentation.getAllLoadedClasses()));
}
}
/**
* A discovery strategy that considers all loaded types supplied by {@link Instrumentation#getAllLoadedClasses()}. For each reiteration,
* this strategy checks if additional types were loaded after the previously supplied types. Doing so, types that were loaded during
* instrumentations can be retransformed as such types are not passed to any class file transformer.
*/
enum Reiterating implements DiscoveryStrategy {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Iterable<Iterable<Class<?>>> resolve(Instrumentation instrumentation) {
return new ReiteratingIterable(instrumentation);
}
/**
* An iterable that returns any loaded types and checks if any additional types were loaded during the last instrumentation.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class ReiteratingIterable implements Iterable<Iterable<Class<?>>> {
/**
* The instrumentation instance to use.
*/
private final Instrumentation instrumentation;
/**
* Creates a new reiterating iterable.
*
* @param instrumentation The instrumentation instance to use.
*/
protected ReiteratingIterable(Instrumentation instrumentation) {
this.instrumentation = instrumentation;
}
/**
* {@inheritDoc}
*/
public Iterator<Iterable<Class<?>>> iterator() {
return new ReiteratingIterator(instrumentation);
}
}
/**
* A reiterating iterator that considers types that were loaded during an instrumentation.
*/
protected static class ReiteratingIterator implements Iterator<Iterable<Class<?>>> {
/**
* The instrumentation instance to use.
*/
private final Instrumentation instrumentation;
/**
* A set containing all previously discovered types.
*/
private final Set<Class<?>> processed;
/**
* The current list of types or {@code null} if the current list of types is not prepared.
*/
private List<Class<?>> types;
/**
* Creates a new reiterating iterator.
*
* @param instrumentation The instrumentation instance to use.
*/
protected ReiteratingIterator(Instrumentation instrumentation) {
this.instrumentation = instrumentation;
processed = new HashSet<Class<?>>();
}
/**
* {@inheritDoc}
*/
public boolean hasNext() {
if (types == null) {
types = new ArrayList<Class<?>>();
for (Class<?> type : instrumentation.getAllLoadedClasses()) {
if (type != null && processed.add(type)) {
types.add(type);
}
}
}
return !types.isEmpty();
}
/**
* {@inheritDoc}
*/
public Iterable<Class<?>> next() {
if (hasNext()) {
try {
return types;
} finally {
types = null;
}
} else {
throw new NoSuchElementException();
}
}
/**
* {@inheritDoc}
*/
public void remove() {
throw new UnsupportedOperationException("remove");
}
}
}
/**
* An explicit discovery strategy that only attempts the redefinition of specific types.
*/
@HashCodeAndEqualsPlugin.Enhance
class Explicit implements DiscoveryStrategy {
/**
* The types to redefine.
*/
private final Set<Class<?>> types;
/**
* Creates a new explicit discovery strategy.
*
* @param type The types to redefine.
*/
public Explicit(Class<?>... type) {
this(new LinkedHashSet<Class<?>>(Arrays.asList(type)));
}
/**
* Creates a new explicit discovery strategy.
*
* @param types The types to redefine.
*/
public Explicit(Set<Class<?>> types) {
this.types = types;
}
/**
* {@inheritDoc}
*/
public Iterable<Iterable<Class<?>>> resolve(Instrumentation instrumentation) {
return Collections.<Iterable<Class<?>>>singleton(types);
}
}
}
/**
* A resubmission scheduler is responsible for scheduling a job that is resubmitting unloaded types that failed during retransformation.
*/
public interface ResubmissionScheduler {
/**
* Checks if this scheduler is currently available.
*
* @return {@code true} if this scheduler is alive.
*/
boolean isAlive();
/**
* Schedules a resubmission job for regular application.
*
* @param job The job to schedule.
* @return A cancelable that is canceled upon resetting the corresponding class file transformer.
*/
Cancelable schedule(Runnable job);
/**
* A cancelable allows to discontinue a resubmission job.
*/
interface Cancelable {
/**
* Cancels this resubmission job.
*/
void cancel();
/**
* A non-operational cancelable.
*/
enum NoOp implements Cancelable {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public void cancel() {
/* do nothing */
}
}
/**
* A cancelable for a {@link Future}.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForFuture implements Cancelable {
/**
* The future to cancel upon cancellation of this instance.
*/
private final Future<?> future;
/**
* Creates a cancelable for a future.
*
* @param future The future to cancel upon cancellation of this instance.
*/
public ForFuture(Future<?> future) {
this.future = future;
}
/**
* {@inheritDoc}
*/
public void cancel() {
future.cancel(true);
}
}
}
/**
* A resubmission scheduler that does not apply any scheduling.
*/
enum NoOp implements ResubmissionScheduler {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public boolean isAlive() {
return false;
}
/**
* {@inheritDoc}
*/
public Cancelable schedule(Runnable job) {
return Cancelable.NoOp.INSTANCE;
}
}
/**
* A resubmission scheduler that schedules jobs at a fixed rate.
*/
@HashCodeAndEqualsPlugin.Enhance
class AtFixedRate implements ResubmissionScheduler {
/**
* The executor service to schedule to.
*/
private final ScheduledExecutorService scheduledExecutorService;
/**
* The time interval between schedulings.
*/
private final long time;
/**
* The time's time unit.
*/
private final TimeUnit timeUnit;
/**
* Creates a new resubmission scheduler which schedules executions at a fixed rate.
*
* @param scheduledExecutorService The executor service to schedule to.
* @param time The time interval between schedulings.
* @param timeUnit The time's time unit.
*/
public AtFixedRate(ScheduledExecutorService scheduledExecutorService, long time, TimeUnit timeUnit) {
this.scheduledExecutorService = scheduledExecutorService;
this.time = time;
this.timeUnit = timeUnit;
}
/**
* {@inheritDoc}
*/
public boolean isAlive() {
return !scheduledExecutorService.isShutdown();
}
/**
* {@inheritDoc}
*/
public Cancelable schedule(Runnable job) {
return new Cancelable.ForFuture(scheduledExecutorService.scheduleAtFixedRate(job, time, time, timeUnit));
}
}
/**
* A resubmission scheduler that schedules jobs with a fixed delay.
*/
@HashCodeAndEqualsPlugin.Enhance
class WithFixedDelay implements ResubmissionScheduler {
/**
* The executor service to schedule to.
*/
private final ScheduledExecutorService scheduledExecutorService;
/**
* The time interval to pause between completed jobs.
*/
private final long time;
/**
* The time's time unit.
*/
private final TimeUnit timeUnit;
/**
* Creates a new resubmission scheduler with a fixed delay between job executions.
*
* @param scheduledExecutorService The executor service to schedule to.
* @param time The time interval to pause between completed jobs.
* @param timeUnit The time's time unit.
*/
public WithFixedDelay(ScheduledExecutorService scheduledExecutorService, long time, TimeUnit timeUnit) {
this.scheduledExecutorService = scheduledExecutorService;
this.time = time;
this.timeUnit = timeUnit;
}
/**
* {@inheritDoc}
*/
public boolean isAlive() {
return !scheduledExecutorService.isShutdown();
}
/**
* {@inheritDoc}
*/
public Cancelable schedule(Runnable job) {
return new Cancelable.ForFuture(scheduledExecutorService.scheduleWithFixedDelay(job, time, time, timeUnit));
}
}
}
/**
* A resubmission strategy is responsible for enabling resubmission of types that failed to resubmit.
*/
protected interface ResubmissionStrategy {
/**
* Invoked upon installation of an agent builder.
*
* @param instrumentation The instrumentation instance to use.
* @param locationStrategy The location strategy to use.
* @param listener The listener to use.
* @param installationListener The installation listener to use.
* @param circularityLock The circularity lock to use.
* @param matcher The matcher to apply for analyzing if a type is to be resubmitted.
* @param redefinitionStrategy The redefinition strategy to use.
* @param redefinitionBatchAllocator The batch allocator to use.
* @param redefinitionBatchListener The batch listener to notify.
* @return A potentially modified listener to apply.
*/
Installation apply(Instrumentation instrumentation,
LocationStrategy locationStrategy,
AgentBuilder.Listener listener,
InstallationListener installationListener,
CircularityLock circularityLock,
RawMatcher matcher,
RedefinitionStrategy redefinitionStrategy,
RedefinitionStrategy.BatchAllocator redefinitionBatchAllocator,
RedefinitionStrategy.Listener redefinitionBatchListener);
/**
* A disabled resubmission strategy.
*/
enum Disabled implements ResubmissionStrategy {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Installation apply(Instrumentation instrumentation,
LocationStrategy locationStrategy,
AgentBuilder.Listener listener,
InstallationListener installationListener,
CircularityLock circularityLock,
RawMatcher matcher,
RedefinitionStrategy redefinitionStrategy,
BatchAllocator redefinitionBatchAllocator,
Listener redefinitionBatchListener) {
return new Installation(listener, installationListener);
}
}
/**
* An enabled resubmission strategy.
*/
@HashCodeAndEqualsPlugin.Enhance
class Enabled implements ResubmissionStrategy {
/**
* A scheduler that is responsible for resubmission of types.
*/
private final ResubmissionScheduler resubmissionScheduler;
/**
* The matcher for filtering error causes.
*/
private final ElementMatcher<? super Throwable> matcher;
/**
* Creates a new enabled resubmission strategy.
*
* @param resubmissionScheduler A scheduler that is responsible for resubmission of types.
* @param matcher The matcher for filtering error causes.
*/
protected Enabled(ResubmissionScheduler resubmissionScheduler, ElementMatcher<? super Throwable> matcher) {
this.resubmissionScheduler = resubmissionScheduler;
this.matcher = matcher;
}
/**
* {@inheritDoc}
*/
public Installation apply(Instrumentation instrumentation,
LocationStrategy locationStrategy,
AgentBuilder.Listener listener,
InstallationListener installationListener,
CircularityLock circularityLock,
RawMatcher matcher,
RedefinitionStrategy redefinitionStrategy,
RedefinitionStrategy.BatchAllocator redefinitionBatchAllocator,
RedefinitionStrategy.Listener redefinitionBatchListener) {
if (redefinitionStrategy.isEnabled() && resubmissionScheduler.isAlive()) {
ConcurrentMap<StorageKey, Set<String>> types = new ConcurrentHashMap<StorageKey, Set<String>>();
return new Installation(new AgentBuilder.Listener.Compound(new ResubmissionListener(this.matcher, types), listener),
new InstallationListener.Compound(new ResubmissionInstallationListener(resubmissionScheduler,
instrumentation,
locationStrategy,
listener,
circularityLock,
matcher,
redefinitionStrategy,
redefinitionBatchAllocator,
redefinitionBatchListener,
types), installationListener));
} else {
return new Installation(listener, installationListener);
}
}
/**
* A listener that registers types for resubmission that failed during transformations.
*/
protected static class ResubmissionListener extends AgentBuilder.Listener.Adapter {
/**
* The matcher for filtering error causes.
*/
private final ElementMatcher<? super Throwable> matcher;
/**
* A map of class loaders to their types to resubmit.
*/
private final ConcurrentMap<StorageKey, Set<String>> types;
/**
* @param matcher The matcher for filtering error causes.
* @param types A map of class loaders to their types to resubmit.
*/
protected ResubmissionListener(ElementMatcher<? super Throwable> matcher, ConcurrentMap<StorageKey, Set<String>> types) {
this.matcher = matcher;
this.types = types;
}
/**
* {@inheritDoc}
*/
@SuppressFBWarnings(value = "GC_UNRELATED_TYPES", justification = "Use of unrelated key is intended for avoiding unnecessary weak reference")
public void onError(String typeName, ClassLoader classLoader, JavaModule module, boolean loaded, Throwable throwable) {
if (!loaded && matcher.matches(throwable)) {
Set<String> types = this.types.get(new LookupKey(classLoader));
if (types == null) {
types = new ConcurrentHashSet<String>();
Set<String> previous = this.types.putIfAbsent(new StorageKey(classLoader), types);
if (previous != null) {
types = previous;
}
}
types.add(typeName);
}
}
/**
* A set projection for a {@link ConcurrentHashMap}.
*
* @param <T> The element type of the set projection.
*/
protected static class ConcurrentHashSet<T> extends AbstractSet<T> {
/**
* The delegate map.
*/
private final ConcurrentMap<T, Boolean> delegate;
/**
* Creates a concurrent hash set.
*/
protected ConcurrentHashSet() {
delegate = new ConcurrentHashMap<T, Boolean>();
}
@Override
public boolean add(T value) {
return delegate.put(value, Boolean.TRUE) == null;
}
@Override
public boolean remove(Object value) {
return delegate.remove(value) != null;
}
/**
* {@inheritDoc}
*/
public Iterator<T> iterator() {
return delegate.keySet().iterator();
}
/**
* {@inheritDoc}
*/
public int size() {
return delegate.size();
}
}
}
/**
* A job that resubmits any matched type that previously failed during transformation.
*/
protected static class ResubmissionInstallationListener extends AgentBuilder.InstallationListener.Adapter implements Runnable {
/**
* The resubmission scheduler to use.
*/
private final ResubmissionScheduler resubmissionScheduler;
/**
* The instrumentation instance to use.
*/
private final Instrumentation instrumentation;
/**
* The location strategy to use.
*/
private final LocationStrategy locationStrategy;
/**
* The listener to use.
*/
private final AgentBuilder.Listener listener;
/**
* The circularity lock to use.
*/
private final CircularityLock circularityLock;
/**
* The matcher to apply for analyzing if a type is to be resubmitted.
*/
private final RawMatcher matcher;
/**
* The redefinition strategy to use.
*/
private final RedefinitionStrategy redefinitionStrategy;
/**
* The batch allocator to use.
*/
private final BatchAllocator redefinitionBatchAllocator;
/**
* The batch listener to notify.
*/
private final Listener redefinitionBatchListener;
/**
* A map of class loaders to their types to resubmit.
*/
private final ConcurrentMap<StorageKey, Set<String>> types;
/**
* This scheduler's cancelable or {@code null} if no cancelable was registered.
*/
private volatile ResubmissionScheduler.Cancelable cancelable;
/**
* Creates a new resubmission job.
*
* @param resubmissionScheduler The resubmission scheduler to use.
* @param instrumentation The instrumentation instance to use.
* @param locationStrategy The location strategy to use.
* @param listener The listener to use.
* @param circularityLock The circularity lock to use.
* @param matcher The matcher to apply for analyzing if a type is to be resubmitted.
* @param redefinitionStrategy The redefinition strategy to use.
* @param redefinitionBatchAllocator The batch allocator to use.
* @param redefinitionBatchListener The batch listener to notify.
* @param types A map of class loaders to their types to resubmit.
*/
protected ResubmissionInstallationListener(ResubmissionScheduler resubmissionScheduler,
Instrumentation instrumentation,
LocationStrategy locationStrategy,
AgentBuilder.Listener listener,
CircularityLock circularityLock,
RawMatcher matcher,
RedefinitionStrategy redefinitionStrategy,
BatchAllocator redefinitionBatchAllocator,
Listener redefinitionBatchListener,
ConcurrentMap<StorageKey, Set<String>> types) {
this.resubmissionScheduler = resubmissionScheduler;
this.instrumentation = instrumentation;
this.locationStrategy = locationStrategy;
this.listener = listener;
this.circularityLock = circularityLock;
this.matcher = matcher;
this.redefinitionStrategy = redefinitionStrategy;
this.redefinitionBatchAllocator = redefinitionBatchAllocator;
this.redefinitionBatchListener = redefinitionBatchListener;
this.types = types;
}
@Override
public void onInstall(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
cancelable = resubmissionScheduler.schedule(this);
}
@Override
public void onReset(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
ResubmissionScheduler.Cancelable cancelable = this.cancelable;
if (cancelable != null) {
cancelable.cancel();
}
}
/**
* {@inheritDoc}
*/
public void run() {
boolean release = circularityLock.acquire();
try {
Iterator<Map.Entry<StorageKey, Set<String>>> entries = types.entrySet().iterator();
List<Class<?>> types = new ArrayList<Class<?>>();
while (entries.hasNext()) {
if (Thread.interrupted()) {
return;
}
Map.Entry<StorageKey, Set<String>> entry = entries.next();
ClassLoader classLoader = entry.getKey().get();
if (classLoader != null || entry.getKey().isBootstrapLoader()) {
Iterator<String> iterator = entry.getValue().iterator();
while (iterator.hasNext()) {
if (Thread.interrupted()) {
return;
}
try {
Class<?> type = Class.forName(iterator.next(), false, classLoader);
try {
if (DISPATCHER.isModifiableClass(instrumentation, type) && matcher.matches(TypeDescription.ForLoadedType.of(type),
type.getClassLoader(),
JavaModule.ofType(type),
type,
type.getProtectionDomain())) {
types.add(type);
}
} catch (Throwable throwable) {
try {
listener.onDiscovery(TypeDescription.ForLoadedType.getName(type),
type.getClassLoader(),
JavaModule.ofType(type),
AgentBuilder.Listener.LOADED);
} finally {
try {
listener.onError(TypeDescription.ForLoadedType.getName(type),
type.getClassLoader(),
JavaModule.ofType(type),
AgentBuilder.Listener.LOADED,
throwable);
} finally {
listener.onComplete(TypeDescription.ForLoadedType.getName(type),
type.getClassLoader(),
JavaModule.ofType(type),
AgentBuilder.Listener.LOADED);
}
}
}
} catch (Throwable ignored) {
/* do nothing */
} finally {
iterator.remove();
}
}
} else {
entries.remove();
}
}
if (!types.isEmpty()) {
RedefinitionStrategy.Collector collector = redefinitionStrategy.make();
collector.include(types);
collector.apply(instrumentation,
circularityLock,
locationStrategy,
listener,
redefinitionBatchAllocator,
redefinitionBatchListener,
BatchAllocator.FIRST_BATCH);
}
} finally {
if (release) {
circularityLock.release();
}
}
}
}
/**
* A key for a class loader that can only be used for looking up a preexisting value but avoids reference management.
*/
protected static class LookupKey {
/**
* The represented class loader.
*/
private final ClassLoader classLoader;
/**
* The represented class loader's hash code or {@code 0} if this entry represents the bootstrap class loader.
*/
private final int hashCode;
/**
* Creates a new lookup key.
*
* @param classLoader The represented class loader.
*/
protected LookupKey(ClassLoader classLoader) {
this.classLoader = classLoader;
hashCode = System.identityHashCode(classLoader);
}
@Override
public int hashCode() {
return hashCode;
}
@Override
@SuppressFBWarnings(value = "EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS", justification = "Cross-comparison is intended")
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof LookupKey) {
return classLoader == ((LookupKey) other).classLoader;
} else if (other instanceof StorageKey) {
StorageKey storageKey = (StorageKey) other;
return hashCode == storageKey.hashCode && classLoader == storageKey.get();
} else {
return false;
}
}
}
/**
* A key for a class loader that only weakly references the class loader.
*/
protected static class StorageKey extends WeakReference<ClassLoader> {
/**
* The represented class loader's hash code or {@code 0} if this entry represents the bootstrap class loader.
*/
private final int hashCode;
/**
* Creates a new storage key.
*
* @param classLoader The represented class loader or {@code null} for the bootstrap class loader.
*/
protected StorageKey(ClassLoader classLoader) {
super(classLoader);
hashCode = System.identityHashCode(classLoader);
}
/**
* Checks if this reference represents the bootstrap class loader.
*
* @return {@code true} if this entry represents the bootstrap class loader.
*/
protected boolean isBootstrapLoader() {
return hashCode == 0;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
@SuppressFBWarnings(value = "EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS", justification = "Cross-comparison is intended")
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof LookupKey) {
LookupKey lookupKey = (LookupKey) other;
return hashCode == lookupKey.hashCode && get() == lookupKey.classLoader;
} else if (other instanceof StorageKey) {
StorageKey storageKey = (StorageKey) other;
return hashCode == storageKey.hashCode && get() == storageKey.get();
} else {
return false;
}
}
}
}
/**
* Represents an installation of a resubmission strategy.
*/
@HashCodeAndEqualsPlugin.Enhance
class Installation {
/**
* The listener to apply.
*/
private final AgentBuilder.Listener listener;
/**
* The installation listener to apply.
*/
private final InstallationListener installationListener;
/**
* Creates a new installation.
*
* @param listener The listener to apply.
* @param installationListener The installation listener to apply.
*/
protected Installation(AgentBuilder.Listener listener, InstallationListener installationListener) {
this.listener = listener;
this.installationListener = installationListener;
}
/**
* Returns the listener to apply.
*
* @return The listener to apply.
*/
protected AgentBuilder.Listener getListener() {
return listener;
}
/**
* Returns the installation listener to apply.
*
* @return The installation listener to apply.
*/
protected InstallationListener getInstallationListener() {
return installationListener;
}
}
}
/**
* A dispatcher for interacting with the instrumentation API.
*/
protected interface Dispatcher {
/**
* Checks if the supplied type is modifiable.
*
* @param instrumentation The instrumentation instance available.
* @param type The type to check for modifiability.
* @return {@code true} if the supplied type is modifiable.
*/
boolean isModifiableClass(Instrumentation instrumentation, Class<?> type);
/**
* Checks if retransformation is supported for the supplied instrumentation instance.
*
* @param instrumentation The instrumentation instance available.
* @return {@code true} if the supplied instance supports retransformation.
*/
boolean isRetransformClassesSupported(Instrumentation instrumentation);
/**
* Retransforms the supplied classes.
*
* @param instrumentation The instrumentation instance to use for retransformation.
* @param type The types to retransform.
* @throws UnmodifiableClassException If the supplied classes cannot be retransformed.
*/
void retransformClasses(Instrumentation instrumentation, Class<?>[] type) throws UnmodifiableClassException;
/**
* An action for creating a dispatcher.
*/
enum CreationAction implements PrivilegedAction<Dispatcher> {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Dispatcher run() {
try {
return new ForJava6CapableVm(Instrumentation.class.getMethod("isModifiableClass", Class.class),
Instrumentation.class.getMethod("isRetransformClassesSupported"),
Instrumentation.class.getMethod("retransformClasses", Class[].class));
} catch (NoSuchMethodException ignored) {
return ForLegacyVm.INSTANCE;
}
}
}
/**
* A dispatcher for a legacy VM.
*/
enum ForLegacyVm implements Dispatcher {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public boolean isModifiableClass(Instrumentation instrumentation, Class<?> type) {
return !type.isArray() && !type.isPrimitive();
}
/**
* {@inheritDoc}
*/
public boolean isRetransformClassesSupported(Instrumentation instrumentation) {
return false;
}
/**
* {@inheritDoc}
*/
public void retransformClasses(Instrumentation instrumentation, Class<?>[] type) {
throw new UnsupportedOperationException("The current VM does not support retransformation");
}
}
/**
* A dispatcher for a Java 6 capable VM.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForJava6CapableVm implements Dispatcher {
/**
* The {@code Instrumentation#isModifiableClass} method.
*/
private final Method isModifiableClass;
/**
* The {@code Instrumentation#isRetransformClassesSupported} method.
*/
private final Method isRetransformClassesSupported;
/**
* The {@code Instrumentation#retransformClasses} method.
*/
private final Method retransformClasses;
/**
* Creates a new Java 6 capable dispatcher.
*
* @param isModifiableClass The {@code Instrumentation#isModifiableClass} method.
* @param isRetransformClassesSupported The {@code Instrumentation#isRetransformClassesSupported} method.
* @param retransformClasses The {@code Instrumentation#retransformClasses} method.
*/
protected ForJava6CapableVm(Method isModifiableClass, Method isRetransformClassesSupported, Method retransformClasses) {
this.isModifiableClass = isModifiableClass;
this.isRetransformClassesSupported = isRetransformClassesSupported;
this.retransformClasses = retransformClasses;
}
/**
* {@inheritDoc}
*/
public boolean isModifiableClass(Instrumentation instrumentation, Class<?> type) {
try {
return (Boolean) isModifiableClass.invoke(instrumentation, type);
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Cannot access java.lang.instrument.Instrumentation#isModifiableClass", exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException("Error invoking java.lang.instrument.Instrumentation#isModifiableClass", exception.getCause());
}
}
/**
* {@inheritDoc}
*/
public boolean isRetransformClassesSupported(Instrumentation instrumentation) {
try {
return (Boolean) isRetransformClassesSupported.invoke(instrumentation);
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Cannot access java.lang.instrument.Instrumentation#isRetransformClassesSupported", exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException("Error invoking java.lang.instrument.Instrumentation#isRetransformClassesSupported", exception.getCause());
}
}
/**
* {@inheritDoc}
*/
public void retransformClasses(Instrumentation instrumentation, Class<?>[] type) throws UnmodifiableClassException {
try {
retransformClasses.invoke(instrumentation, (Object) type);
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Cannot access java.lang.instrument.Instrumentation#retransformClasses", exception);
} catch (InvocationTargetException exception) {
Throwable cause = exception.getCause();
if (cause instanceof UnmodifiableClassException) {
throw (UnmodifiableClassException) cause;
} else {
throw new IllegalStateException("Error invoking java.lang.instrument.Instrumentation#retransformClasses", cause);
}
}
}
}
}
/**
* A collector is responsible for collecting classes that are to be considered for modification.
*/
protected abstract static class Collector {
/**
* A representation for a non-available loaded type.
*/
private static final Class<?> NO_LOADED_TYPE = null;
/**
* All types that were collected for redefinition.
*/
protected final List<Class<?>> types;
/**
* Creates a new collector.
*/
protected Collector() {
types = new ArrayList<Class<?>>();
}
/**
* Does consider the retransformation or redefinition of a loaded type without a loaded type representation.
*
* @param matcher The type matcher to apply.
* @param listener The listener to apply during the consideration.
* @param typeDescription The type description of the type being considered.
* @param type The loaded type being considered.
* @param module The type's Java module or {@code null} if the current VM does not support modules.
*/
protected void consider(RawMatcher matcher,
AgentBuilder.Listener listener,
TypeDescription typeDescription,
Class<?> type,
JavaModule module) {
consider(matcher, listener, typeDescription, type, NO_LOADED_TYPE, module, false);
}
/**
* Does consider the retransformation or redefinition of a loaded type.
*
* @param matcher A type matcher to apply.
* @param listener The listener to apply during the consideration.
* @param typeDescription The type description of the type being considered.
* @param type The loaded type being considered.
* @param classBeingRedefined The loaded type being considered or {@code null} if it should be considered non-available.
* @param module The type's Java module or {@code null} if the current VM does not support modules.
* @param unmodifiable {@code true} if the current type should be considered unmodifiable.
*/
protected void consider(RawMatcher matcher,
AgentBuilder.Listener listener,
TypeDescription typeDescription,
Class<?> type,
Class<?> classBeingRedefined,
JavaModule module,
boolean unmodifiable) {
if (unmodifiable || !matcher.matches(typeDescription, type.getClassLoader(), module, classBeingRedefined, type.getProtectionDomain())) {
try {
try {
listener.onDiscovery(TypeDescription.ForLoadedType.getName(type), type.getClassLoader(), module, classBeingRedefined != null);
listener.onIgnored(typeDescription, type.getClassLoader(), module, classBeingRedefined != null);
} catch (Throwable throwable) {
listener.onError(TypeDescription.ForLoadedType.getName(type), type.getClassLoader(), module, classBeingRedefined != null, throwable);
} finally {
listener.onComplete(TypeDescription.ForLoadedType.getName(type), type.getClassLoader(), module, classBeingRedefined != null);
}
} catch (Throwable ignored) {
// Ignore exceptions that are thrown by listeners to mimic the behavior of a transformation.
}
} else {
types.add(type);
}
}
/**
* Includes all the supplied types in this collector.
*
* @param types The types to include.
*/
protected void include(List<Class<?>> types) {
this.types.addAll(types);
}
/**
* Applies all types that this collector collected.
*
* @param instrumentation The instrumentation instance to apply changes to.
* @param circularityLock The circularity lock to use.
* @param locationStrategy The location strategy to use.
* @param listener The listener to use.
* @param redefinitionBatchAllocator The redefinition batch allocator to use.
* @param redefinitionListener The redefinition listener to use.
* @param batch The next batch's index.
* @return The next batch's index after this application.
*/
protected int apply(Instrumentation instrumentation,
CircularityLock circularityLock,
LocationStrategy locationStrategy,
AgentBuilder.Listener listener,
BatchAllocator redefinitionBatchAllocator,
Listener redefinitionListener,
int batch) {
Map<List<Class<?>>, Throwable> failures = new HashMap<List<Class<?>>, Throwable>();
PrependableIterator prepanedableIterator = new PrependableIterator(redefinitionBatchAllocator.batch(this.types));
while (prepanedableIterator.hasNext()) {
List<Class<?>> types = prepanedableIterator.next();
redefinitionListener.onBatch(batch, types, this.types);
try {
doApply(instrumentation, circularityLock, types, locationStrategy, listener);
} catch (Throwable throwable) {
prepanedableIterator.prepend(redefinitionListener.onError(batch, types, throwable, this.types));
failures.put(types, throwable);
}
batch += 1;
}
redefinitionListener.onComplete(batch, types, failures);
return batch;
}
/**
* Applies this collector.
*
* @param instrumentation The instrumentation instance to apply the transformation for.
* @param circularityLock The circularity lock to use.
* @param types The types of the current patch to transform.
* @param locationStrategy The location strategy to use.
* @param listener the listener to notify.
* @throws UnmodifiableClassException If a class is not modifiable.
* @throws ClassNotFoundException If a class could not be found.
*/
protected abstract void doApply(Instrumentation instrumentation,
CircularityLock circularityLock,
List<Class<?>> types,
LocationStrategy locationStrategy,
AgentBuilder.Listener listener) throws UnmodifiableClassException, ClassNotFoundException;
/**
* An iterator that allows prepending of iterables to be applied previous to another iterator.
*/
protected static class PrependableIterator implements Iterator<List<Class<?>>> {
/**
* The current iterator.
*/
private Iterator<? extends List<Class<?>>> current;
/**
* The backlog of iterators to apply.
*/
private final LinkedList<Iterator<? extends List<Class<?>>>> backlog;
/**
* Creates a new prependable iterator.
*
* @param origin The original iterable to begin with.
*/
protected PrependableIterator(Iterable<? extends List<Class<?>>> origin) {
current = origin.iterator();
backlog = new LinkedList<Iterator<? extends List<Class<?>>>>();
}
/**
* Prepends an iterable to the backlog.
*
* @param iterable The iterable to prepend.
*/
public void prepend(Iterable<? extends List<Class<?>>> iterable) {
Iterator<? extends List<Class<?>>> iterator = iterable.iterator();
if (iterator.hasNext()) {
if (current.hasNext()) {
backlog.addLast(current);
}
current = iterator;
}
}
/**
* {@inheritDoc}
*/
public boolean hasNext() {
return current.hasNext();
}
/**
* {@inheritDoc}
*/
public List<Class<?>> next() {
try {
return current.next();
} finally {
while (!current.hasNext() && !backlog.isEmpty()) {
current = backlog.removeLast();
}
}
}
/**
* {@inheritDoc}
*/
public void remove() {
throw new UnsupportedOperationException("remove");
}
}
/**
* A collector that applies a <b>redefinition</b> of already loaded classes.
*/
protected static class ForRedefinition extends Collector {
@Override
protected void doApply(Instrumentation instrumentation,
CircularityLock circularityLock,
List<Class<?>> types,
LocationStrategy locationStrategy,
AgentBuilder.Listener listener) throws UnmodifiableClassException, ClassNotFoundException {
List<ClassDefinition> classDefinitions = new ArrayList<ClassDefinition>(types.size());
for (Class<?> type : types) {
try {
try {
classDefinitions.add(new ClassDefinition(type, locationStrategy.classFileLocator(type.getClassLoader(), JavaModule.ofType(type))
.locate(TypeDescription.ForLoadedType.getName(type))
.resolve()));
} catch (Throwable throwable) {
JavaModule module = JavaModule.ofType(type);
try {
listener.onDiscovery(TypeDescription.ForLoadedType.getName(type), type.getClassLoader(), module, AgentBuilder.Listener.LOADED);
} finally {
try {
listener.onError(TypeDescription.ForLoadedType.getName(type), type.getClassLoader(), module, AgentBuilder.Listener.LOADED, throwable);
} finally {
listener.onComplete(TypeDescription.ForLoadedType.getName(type), type.getClassLoader(), module, AgentBuilder.Listener.LOADED);
}
}
}
} catch (Throwable ignored) {
// Ignore exceptions that are thrown by listeners to mimic the behavior of a transformation.
}
}
if (!classDefinitions.isEmpty()) {
circularityLock.release();
try {
instrumentation.redefineClasses(classDefinitions.toArray(new ClassDefinition[0]));
} finally {
circularityLock.acquire();
}
}
}
}
/**
* A collector that applies a <b>retransformation</b> of already loaded classes.
*/
protected static class ForRetransformation extends Collector {
@Override
protected void doApply(Instrumentation instrumentation,
CircularityLock circularityLock,
List<Class<?>> types,
LocationStrategy locationStrategy,
AgentBuilder.Listener listener) throws UnmodifiableClassException {
if (!types.isEmpty()) {
circularityLock.release();
try {
DISPATCHER.retransformClasses(instrumentation, types.toArray(new Class<?>[0]));
} finally {
circularityLock.acquire();
}
}
}
}
}
}
/**
* Implements the instrumentation of the {@code LambdaMetafactory} if this feature is enabled.
*/
enum LambdaInstrumentationStrategy {
/**
* A strategy that enables instrumentation of the {@code LambdaMetafactory} if such a factory exists on the current VM.
* Classes representing lambda expressions that are created by Byte Buddy are fully compatible to those created by
* the JVM and can be serialized or deserialized to one another. The classes do however show a few differences:
* <ul>
* <li>Byte Buddy's classes are public with a public executing transformer. Doing so, it is not necessary to instantiate a
* non-capturing lambda expression by reflection. This is done because Byte Buddy is not necessarily capable
* of using reflection due to an active security manager.</li>
* <li>Byte Buddy's classes are not marked as synthetic as an agent builder does not instrument synthetic classes
* by default.</li>
* </ul>
*/
ENABLED {
@Override
protected void apply(ByteBuddy byteBuddy,
Instrumentation instrumentation,
ClassFileTransformer classFileTransformer) {
if (LambdaFactory.register(classFileTransformer, new LambdaInstanceFactory(byteBuddy))) {
Class<?> lambdaMetaFactory;
try {
lambdaMetaFactory = Class.forName("java.lang.invoke.LambdaMetafactory");
} catch (ClassNotFoundException ignored) {
return;
}
byteBuddy.with(Implementation.Context.Disabled.Factory.INSTANCE)
.redefine(lambdaMetaFactory)
.visit(new AsmVisitorWrapper.ForDeclaredMethods()
.method(named("metafactory"), MetaFactoryRedirection.INSTANCE)
.method(named("altMetafactory"), AlternativeMetaFactoryRedirection.INSTANCE))
.make()
.load(lambdaMetaFactory.getClassLoader(), ClassReloadingStrategy.of(instrumentation));
}
}
@Override
protected boolean isInstrumented(Class<?> type) {
return true;
}
},
/**
* A strategy that does not instrument the {@code LambdaMetafactory}.
*/
DISABLED {
@Override
protected void apply(ByteBuddy byteBuddy,
Instrumentation instrumentation,
ClassFileTransformer classFileTransformer) {
/* do nothing */
}
@Override
protected boolean isInstrumented(Class<?> type) {
return type == null || !type.getName().contains("/");
}
};
/**
* The name of the current VM's {@code Unsafe} class that is visible to the bootstrap loader.
*/
private static final String UNSAFE_CLASS = ClassFileVersion.ofThisVm(ClassFileVersion.JAVA_V6).isAtLeast(ClassFileVersion.JAVA_V9)
? "jdk/internal/misc/Unsafe"
: "sun/misc/Unsafe";
/**
* Indicates that an original implementation can be ignored when redefining a method.
*/
protected static final MethodVisitor IGNORE_ORIGINAL = null;
/**
* Releases the supplied class file transformer when it was built with {@link AgentBuilder#with(LambdaInstrumentationStrategy)} enabled.
* Subsequently, the class file transformer is no longer applied when a class that represents a lambda expression is created.
*
* @param classFileTransformer The class file transformer to release.
* @param instrumentation The instrumentation instance that is used to potentially rollback the instrumentation of the {@code LambdaMetafactory}.
*/
public static void release(ClassFileTransformer classFileTransformer, Instrumentation instrumentation) {
if (LambdaFactory.release(classFileTransformer)) {
try {
ClassReloadingStrategy.of(instrumentation).reset(Class.forName("java.lang.invoke.LambdaMetafactory"));
} catch (Exception exception) {
throw new IllegalStateException("Could not release lambda transformer", exception);
}
}
}
/**
* Returns an enabled lambda instrumentation strategy for {@code true}.
*
* @param enabled If lambda instrumentation should be enabled.
* @return {@code true} if the returned strategy should be enabled.
*/
public static LambdaInstrumentationStrategy of(boolean enabled) {
return enabled
? ENABLED
: DISABLED;
}
/**
* Applies a transformation to lambda instances if applicable.
*
* @param byteBuddy The Byte Buddy instance to use.
* @param instrumentation The instrumentation instance for applying a redefinition.
* @param classFileTransformer The class file transformer to apply.
*/
protected abstract void apply(ByteBuddy byteBuddy, Instrumentation instrumentation, ClassFileTransformer classFileTransformer);
/**
* Indicates if this strategy enables instrumentation of the {@code LambdaMetafactory}.
*
* @return {@code true} if this strategy is enabled.
*/
public boolean isEnabled() {
return this == ENABLED;
}
/**
* Validates if the supplied class is instrumented. For lambda types (which are loaded by anonymous class loader), this method
* should return false if lambda instrumentation is disabled.
*
* @param type The redefined type or {@code null} if no such type exists.
* @return {@code true} if the supplied type should be instrumented according to this strategy.
*/
protected abstract boolean isInstrumented(Class<?> type);
/**
* A factory that creates instances that represent lambda expressions.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class LambdaInstanceFactory {
/**
* The name of a factory for a lambda expression.
*/
private static final String LAMBDA_FACTORY = "get$Lambda";
/**
* A prefix for a field that represents a property of a lambda expression.
*/
private static final String FIELD_PREFIX = "arg$";
/**
* The infix to use for naming classes that represent lambda expression. The additional prefix
* is necessary because the subsequent counter is not sufficient to keep names unique compared
* to the original factory.
*/
private static final String LAMBDA_TYPE_INFIX = "$$Lambda$ByteBuddy$";
/**
* A type-safe constant to express that a class is not already loaded when applying a class file transformer.
*/
private static final Class<?> NOT_PREVIOUSLY_DEFINED = null;
/**
* A counter for naming lambda expressions randomly.
*/
private static final AtomicInteger LAMBDA_NAME_COUNTER = new AtomicInteger();
/**
* The Byte Buddy instance to use for creating lambda objects.
*/
private final ByteBuddy byteBuddy;
/**
* Creates a new lambda instance factory.
*
* @param byteBuddy The Byte Buddy instance to use for creating lambda objects.
*/
protected LambdaInstanceFactory(ByteBuddy byteBuddy) {
this.byteBuddy = byteBuddy;
}
/**
* Applies this lambda meta factory.
*
* @param targetTypeLookup A lookup context representing the creating class of this lambda expression.
* @param lambdaMethodName The name of the lambda expression's represented method.
* @param factoryMethodType The type of the lambda expression's represented method.
* @param lambdaMethodType The type of the lambda expression's factory method.
* @param targetMethodHandle A handle representing the target of the lambda expression's method.
* @param specializedLambdaMethodType A specialization of the type of the lambda expression's represented method.
* @param serializable {@code true} if the lambda expression should be serializable.
* @param markerInterfaces A list of interfaces for the lambda expression to represent.
* @param additionalBridges A list of additional bridge methods to be implemented by the lambda expression.
* @param classFileTransformers A collection of class file transformers to apply when creating the class.
* @return A binary representation of the transformed class file.
*/
public byte[] make(Object targetTypeLookup,
String lambdaMethodName,
Object factoryMethodType,
Object lambdaMethodType,
Object targetMethodHandle,
Object specializedLambdaMethodType,
boolean serializable,
List<Class<?>> markerInterfaces,
List<?> additionalBridges,
Collection<? extends ClassFileTransformer> classFileTransformers) {
JavaConstant.MethodType factoryMethod = JavaConstant.MethodType.ofLoaded(factoryMethodType);
JavaConstant.MethodType lambdaMethod = JavaConstant.MethodType.ofLoaded(lambdaMethodType);
JavaConstant.MethodHandle targetMethod = JavaConstant.MethodHandle.ofLoaded(targetMethodHandle, targetTypeLookup);
JavaConstant.MethodType specializedLambdaMethod = JavaConstant.MethodType.ofLoaded(specializedLambdaMethodType);
Class<?> targetType = JavaConstant.MethodHandle.lookupType(targetTypeLookup);
String lambdaClassName = targetType.getName() + LAMBDA_TYPE_INFIX + LAMBDA_NAME_COUNTER.incrementAndGet();
DynamicType.Builder<?> builder = byteBuddy
.subclass(factoryMethod.getReturnType(), ConstructorStrategy.Default.NO_CONSTRUCTORS)
.modifiers(TypeManifestation.FINAL, Visibility.PUBLIC)
.implement(markerInterfaces)
.name(lambdaClassName)
.defineConstructor(Visibility.PUBLIC)
.withParameters(factoryMethod.getParameterTypes())
.intercept(ConstructorImplementation.INSTANCE)
.method(named(lambdaMethodName)
.and(takesArguments(lambdaMethod.getParameterTypes()))
.and(returns(lambdaMethod.getReturnType())))
.intercept(new LambdaMethodImplementation(targetMethod, specializedLambdaMethod));
int index = 0;
for (TypeDescription capturedType : factoryMethod.getParameterTypes()) {
builder = builder.defineField(FIELD_PREFIX + ++index, capturedType, Visibility.PRIVATE, FieldManifestation.FINAL);
}
if (!factoryMethod.getParameterTypes().isEmpty()) {
builder = builder.defineMethod(LAMBDA_FACTORY, factoryMethod.getReturnType(), Visibility.PRIVATE, Ownership.STATIC)
.withParameters(factoryMethod.getParameterTypes())
.intercept(FactoryImplementation.INSTANCE);
}
if (serializable) {
if (!markerInterfaces.contains(Serializable.class)) {
builder = builder.implement(Serializable.class);
}
builder = builder.defineMethod("writeReplace", Object.class, Visibility.PRIVATE)
.intercept(new SerializationImplementation(TypeDescription.ForLoadedType.of(targetType),
factoryMethod.getReturnType(),
lambdaMethodName,
lambdaMethod,
targetMethod,
JavaConstant.MethodType.ofLoaded(specializedLambdaMethodType)));
} else if (factoryMethod.getReturnType().isAssignableTo(Serializable.class)) {
builder = builder.defineMethod("readObject", void.class, Visibility.PRIVATE)
.withParameters(ObjectInputStream.class)
.throwing(NotSerializableException.class)
.intercept(ExceptionMethod.throwing(NotSerializableException.class, "Non-serializable lambda"))
.defineMethod("writeObject", void.class, Visibility.PRIVATE)
.withParameters(ObjectOutputStream.class)
.throwing(NotSerializableException.class)
.intercept(ExceptionMethod.throwing(NotSerializableException.class, "Non-serializable lambda"));
}
for (Object additionalBridgeType : additionalBridges) {
JavaConstant.MethodType additionalBridge = JavaConstant.MethodType.ofLoaded(additionalBridgeType);
builder = builder.defineMethod(lambdaMethodName, additionalBridge.getReturnType(), MethodManifestation.BRIDGE, Visibility.PUBLIC)
.withParameters(additionalBridge.getParameterTypes())
.intercept(new BridgeMethodImplementation(lambdaMethodName, lambdaMethod));
}
byte[] classFile = builder.make().getBytes();
for (ClassFileTransformer classFileTransformer : classFileTransformers) {
try {
byte[] transformedClassFile = classFileTransformer.transform(targetType.getClassLoader(),
lambdaClassName.replace('.', '/'),
NOT_PREVIOUSLY_DEFINED,
targetType.getProtectionDomain(),
classFile);
classFile = transformedClassFile == null
? classFile
: transformedClassFile;
} catch (Throwable ignored) {
/* do nothing */
}
}
return classFile;
}
/**
* Implements a lambda class's executing transformer.
*/
@SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "An enumeration does not serialize fields")
protected enum ConstructorImplementation implements Implementation {
/**
* The singleton instance.
*/
INSTANCE;
/**
* A reference to the {@link Object} class's default executing transformer.
*/
private final MethodDescription.InDefinedShape objectConstructor;
/**
* Creates a new executing transformer implementation.
*/
ConstructorImplementation() {
objectConstructor = TypeDescription.OBJECT.getDeclaredMethods().filter(isConstructor()).getOnly();
}
/**
* {@inheritDoc}
*/
public ByteCodeAppender appender(Target implementationTarget) {
return new Appender(implementationTarget.getInstrumentedType().getDeclaredFields());
}
/**
* {@inheritDoc}
*/
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
/**
* An appender to implement the executing transformer.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class Appender implements ByteCodeAppender {
/**
* The fields that are declared by the instrumented type.
*/
private final List<FieldDescription.InDefinedShape> declaredFields;
/**
* Creates a new appender.
*
* @param declaredFields The fields that are declared by the instrumented type.
*/
protected Appender(List<FieldDescription.InDefinedShape> declaredFields) {
this.declaredFields = declaredFields;
}
/**
* {@inheritDoc}
*/
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
List<StackManipulation> fieldAssignments = new ArrayList<StackManipulation>(declaredFields.size() * 3);
for (ParameterDescription parameterDescription : instrumentedMethod.getParameters()) {
fieldAssignments.add(MethodVariableAccess.loadThis());
fieldAssignments.add(MethodVariableAccess.load(parameterDescription));
fieldAssignments.add(FieldAccess.forField(declaredFields.get(parameterDescription.getIndex())).write());
}
return new Size(new StackManipulation.Compound(
MethodVariableAccess.loadThis(),
MethodInvocation.invoke(INSTANCE.objectConstructor),
new StackManipulation.Compound(fieldAssignments),
MethodReturn.VOID
).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
}
}
/**
* An implementation of a instance factory for a lambda expression's class.
*/
protected enum FactoryImplementation implements Implementation {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public ByteCodeAppender appender(Target implementationTarget) {
return new Appender(implementationTarget.getInstrumentedType());
}
/**
* {@inheritDoc}
*/
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
/**
* An appender for a lambda expression factory.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class Appender implements ByteCodeAppender {
/**
* The instrumented type.
*/
private final TypeDescription instrumentedType;
/**
* Creates a new appender.
*
* @param instrumentedType The instrumented type.
*/
protected Appender(TypeDescription instrumentedType) {
this.instrumentedType = instrumentedType;
}
/**
* {@inheritDoc}
*/
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
return new Size(new StackManipulation.Compound(
TypeCreation.of(instrumentedType),
Duplication.SINGLE,
MethodVariableAccess.allArgumentsOf(instrumentedMethod),
MethodInvocation.invoke(instrumentedType.getDeclaredMethods().filter(isConstructor()).getOnly()),
MethodReturn.REFERENCE
).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
}
}
/**
* Implements a lambda expression's functional method.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class LambdaMethodImplementation implements Implementation {
/**
* The handle of the target method of the lambda expression.
*/
private final JavaConstant.MethodHandle targetMethod;
/**
* The specialized type of the lambda method.
*/
private final JavaConstant.MethodType specializedLambdaMethod;
/**
* Creates a implementation of a lambda expression's functional method.
*
* @param targetMethod The target method of the lambda expression.
* @param specializedLambdaMethod The specialized type of the lambda method.
*/
protected LambdaMethodImplementation(JavaConstant.MethodHandle targetMethod, JavaConstant.MethodType specializedLambdaMethod) {
this.targetMethod = targetMethod;
this.specializedLambdaMethod = specializedLambdaMethod;
}
/**
* {@inheritDoc}
*/
public ByteCodeAppender appender(Target implementationTarget) {
return new Appender(targetMethod.getOwnerType()
.getDeclaredMethods()
.filter(hasMethodName(targetMethod.getName())
.and(returns(targetMethod.getReturnType()))
.and(takesArguments(targetMethod.getParameterTypes())))
.getOnly(),
specializedLambdaMethod,
implementationTarget.getInstrumentedType().getDeclaredFields());
}
/**
* {@inheritDoc}
*/
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
/**
* An appender for a lambda expression's functional method.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class Appender implements ByteCodeAppender {
/**
* The target method of the lambda expression.
*/
private final MethodDescription targetMethod;
/**
* The specialized type of the lambda method.
*/
private final JavaConstant.MethodType specializedLambdaMethod;
/**
* The instrumented type's declared fields.
*/
private final List<FieldDescription.InDefinedShape> declaredFields;
/**
* Creates an appender of a lambda expression's functional method.
*
* @param targetMethod The target method of the lambda expression.
* @param specializedLambdaMethod The specialized type of the lambda method.
* @param declaredFields The instrumented type's declared fields.
*/
protected Appender(MethodDescription targetMethod,
JavaConstant.MethodType specializedLambdaMethod,
List<FieldDescription.InDefinedShape> declaredFields) {
this.targetMethod = targetMethod;
this.specializedLambdaMethod = specializedLambdaMethod;
this.declaredFields = declaredFields;
}
/**
* {@inheritDoc}
*/
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
StackManipulation preparation = targetMethod.isConstructor()
? new StackManipulation.Compound(TypeCreation.of(targetMethod.getDeclaringType().asErasure()), Duplication.SINGLE)
: StackManipulation.Trivial.INSTANCE;
List<StackManipulation> fieldAccess = new ArrayList<StackManipulation>(declaredFields.size() * 2 + 1);
for (FieldDescription.InDefinedShape fieldDescription : declaredFields) {
fieldAccess.add(MethodVariableAccess.loadThis());
fieldAccess.add(FieldAccess.forField(fieldDescription).read());
}
List<StackManipulation> parameterAccess = new ArrayList<StackManipulation>(instrumentedMethod.getParameters().size() * 2);
for (ParameterDescription parameterDescription : instrumentedMethod.getParameters()) {
parameterAccess.add(MethodVariableAccess.load(parameterDescription));
parameterAccess.add(Assigner.DEFAULT.assign(parameterDescription.getType(),
specializedLambdaMethod.getParameterTypes().get(parameterDescription.getIndex()).asGenericType(),
Assigner.Typing.DYNAMIC));
}
return new Size(new StackManipulation.Compound(
preparation,
new StackManipulation.Compound(fieldAccess),
new StackManipulation.Compound(parameterAccess),
MethodInvocation.invoke(targetMethod),
Assigner.DEFAULT.assign(targetMethod.isConstructor()
? targetMethod.getDeclaringType().asGenericType()
: targetMethod.getReturnType(),
specializedLambdaMethod.getReturnType().asGenericType(),
Assigner.Typing.DYNAMIC),
MethodReturn.of(specializedLambdaMethod.getReturnType())
).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
}
}
/**
* Implements the {@code writeReplace} method for serializable lambda expressions.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class SerializationImplementation implements Implementation {
/**
* The lambda expression's declaring type.
*/
private final TypeDescription targetType;
/**
* The lambda expression's functional type.
*/
private final TypeDescription lambdaType;
/**
* The lambda expression's functional method name.
*/
private final String lambdaMethodName;
/**
* The method type of the lambda expression's functional method.
*/
private final JavaConstant.MethodType lambdaMethod;
/**
* A handle that references the lambda expressions invocation target.
*/
private final JavaConstant.MethodHandle targetMethod;
/**
* The specialized method type of the lambda expression's functional method.
*/
private final JavaConstant.MethodType specializedMethod;
/**
* Creates a new implementation for a serializable's lambda expression's {@code writeReplace} method.
*
* @param targetType The lambda expression's declaring type.
* @param lambdaType The lambda expression's functional type.
* @param lambdaMethodName The lambda expression's functional method name.
* @param lambdaMethod The method type of the lambda expression's functional method.
* @param targetMethod A handle that references the lambda expressions invocation target.
* @param specializedMethod The specialized method type of the lambda expression's functional method.
*/
protected SerializationImplementation(TypeDescription targetType,
TypeDescription lambdaType,
String lambdaMethodName,
JavaConstant.MethodType lambdaMethod,
JavaConstant.MethodHandle targetMethod,
JavaConstant.MethodType specializedMethod) {
this.targetType = targetType;
this.lambdaType = lambdaType;
this.lambdaMethodName = lambdaMethodName;
this.lambdaMethod = lambdaMethod;
this.targetMethod = targetMethod;
this.specializedMethod = specializedMethod;
}
/**
* {@inheritDoc}
*/
public ByteCodeAppender appender(Target implementationTarget) {
TypeDescription serializedLambda;
try {
serializedLambda = TypeDescription.ForLoadedType.of(Class.forName("java.lang.invoke.SerializedLambda"));
} catch (ClassNotFoundException exception) {
throw new IllegalStateException("Cannot find class for lambda serialization", exception);
}
List<StackManipulation> lambdaArguments = new ArrayList<StackManipulation>(implementationTarget.getInstrumentedType().getDeclaredFields().size());
for (FieldDescription.InDefinedShape fieldDescription : implementationTarget.getInstrumentedType().getDeclaredFields()) {
lambdaArguments.add(new StackManipulation.Compound(MethodVariableAccess.loadThis(),
FieldAccess.forField(fieldDescription).read(),
Assigner.DEFAULT.assign(fieldDescription.getType(), TypeDescription.Generic.OBJECT, Assigner.Typing.STATIC)));
}
return new ByteCodeAppender.Simple(new StackManipulation.Compound(
TypeCreation.of(serializedLambda),
Duplication.SINGLE,
ClassConstant.of(targetType),
new TextConstant(lambdaType.getInternalName()),
new TextConstant(lambdaMethodName),
new TextConstant(lambdaMethod.getDescriptor()),
IntegerConstant.forValue(targetMethod.getHandleType().getIdentifier()),
new TextConstant(targetMethod.getOwnerType().getInternalName()),
new TextConstant(targetMethod.getName()),
new TextConstant(targetMethod.getDescriptor()),
new TextConstant(specializedMethod.getDescriptor()),
ArrayFactory.forType(TypeDescription.Generic.OBJECT).withValues(lambdaArguments),
MethodInvocation.invoke(serializedLambda.getDeclaredMethods().filter(isConstructor()).getOnly()),
MethodReturn.REFERENCE
));
}
/**
* {@inheritDoc}
*/
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
}
/**
* Implements an explicit bridge method for a lambda expression.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class BridgeMethodImplementation implements Implementation {
/**
* The name of the lambda expression's functional method.
*/
private final String lambdaMethodName;
/**
* The actual type of the lambda expression's functional method.
*/
private final JavaConstant.MethodType lambdaMethod;
/**
* Creates a new bridge method implementation for a lambda expression.
*
* @param lambdaMethodName The name of the lambda expression's functional method.
* @param lambdaMethod The actual type of the lambda expression's functional method.
*/
protected BridgeMethodImplementation(String lambdaMethodName, JavaConstant.MethodType lambdaMethod) {
this.lambdaMethodName = lambdaMethodName;
this.lambdaMethod = lambdaMethod;
}
/**
* {@inheritDoc}
*/
public ByteCodeAppender appender(Target implementationTarget) {
return new Appender(implementationTarget.invokeSuper(new MethodDescription.SignatureToken(lambdaMethodName,
lambdaMethod.getReturnType(),
lambdaMethod.getParameterTypes())));
}
/**
* {@inheritDoc}
*/
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
/**
* An appender for implementing a bridge method for a lambda expression.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class Appender implements ByteCodeAppender {
/**
* The invocation of the bridge's target method.
*/
private final SpecialMethodInvocation bridgeTargetInvocation;
/**
* Creates a new appender for invoking a lambda expression's bridge method target.
*
* @param bridgeTargetInvocation The invocation of the bridge's target method.
*/
protected Appender(SpecialMethodInvocation bridgeTargetInvocation) {
this.bridgeTargetInvocation = bridgeTargetInvocation;
}
/**
* {@inheritDoc}
*/
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
return new Compound(new Simple(
MethodVariableAccess.allArgumentsOf(instrumentedMethod)
.asBridgeOf(bridgeTargetInvocation.getMethodDescription())
.prependThisReference(),
bridgeTargetInvocation,
bridgeTargetInvocation.getMethodDescription().getReturnType().asErasure().isAssignableTo(instrumentedMethod.getReturnType().asErasure())
? StackManipulation.Trivial.INSTANCE
: TypeCasting.to(instrumentedMethod.getReceiverType()),
MethodReturn.of(instrumentedMethod.getReturnType())
)).apply(methodVisitor, implementationContext, instrumentedMethod);
}
}
}
}
/**
* Implements the regular lambda meta factory. The implementation represents the following code:
* <blockquote><pre>
* public static CallSite metafactory(MethodHandles.Lookup caller,
* String invokedName,
* MethodType invokedType,
* MethodType samMethodType,
* MethodHandle implMethod,
* MethodType instantiatedMethodType) throws Exception {
* Unsafe unsafe = Unsafe.getUnsafe();
* {@code Class<?>} lambdaClass = unsafe.defineAnonymousClass(caller.lookupClass(),
* (byte[]) ClassLoader.getSystemClassLoader().loadClass("net.bytebuddy.agent.builder.LambdaFactory").getDeclaredMethod("make",
* Object.class,
* String.class,
* Object.class,
* Object.class,
* Object.class,
* Object.class,
* boolean.class,
* List.class,
* List.class).invoke(null,
* caller,
* invokedName,
* invokedType,
* samMethodType,
* implMethod,
* instantiatedMethodType,
* false,
* Collections.emptyList(),
* Collections.emptyList()),
* null);
* unsafe.ensureClassInitialized(lambdaClass);
* return invokedType.parameterCount() == 0
* ? new ConstantCallSite(MethodHandles.constant(invokedType.returnType(), lambdaClass.getDeclaredConstructors()[0].newInstance()))
* : new ConstantCallSite(MethodHandles.Lookup.IMPL_LOOKUP.findStatic(lambdaClass, "get$Lambda", invokedType));
* </pre></blockquote>
*/
protected enum MetaFactoryRedirection implements AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public MethodVisitor wrap(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
TypePool typePool,
int writerFlags,
int readerFlags) {
methodVisitor.visitCode();
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, UNSAFE_CLASS, "getUnsafe", "()L" + UNSAFE_CLASS + ";", false);
methodVisitor.visitVarInsn(Opcodes.ASTORE, 6);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 6);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "lookupClass", "()Ljava/lang/Class;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/ClassLoader", "getSystemClassLoader", "()Ljava/lang/ClassLoader;", false);
methodVisitor.visitLdcInsn("net.bytebuddy.agent.builder.LambdaFactory");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/ClassLoader", "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;", false);
methodVisitor.visitLdcInsn("make");
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 9);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/String;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_3);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_5);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 6);
methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Boolean", "TYPE", "Ljava/lang/Class;");
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 7);
methodVisitor.visitLdcInsn(Type.getType("Ljava/util/List;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 8);
methodVisitor.visitLdcInsn(Type.getType("Ljava/util/List;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredMethod", "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;", false);
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 9);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_3);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 4);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_5);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 5);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 6);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 7);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Collections", "emptyList", "()Ljava/util/List;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 8);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Collections", "emptyList", "()Ljava/util/List;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Method", "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", false);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "[B");
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, UNSAFE_CLASS, "defineAnonymousClass", "(Ljava/lang/Class;[B[Ljava/lang/Object;)Ljava/lang/Class;", false);
methodVisitor.visitVarInsn(Opcodes.ASTORE, 7);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 6);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 7);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, UNSAFE_CLASS, "ensureClassInitialized", "(Ljava/lang/Class;)V", false);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodType", "parameterCount", "()I", false);
Label conditionalDefault = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFNE, conditionalDefault);
methodVisitor.visitTypeInsn(Opcodes.NEW, "java/lang/invoke/ConstantCallSite");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodType", "returnType", "()Ljava/lang/Class;", false);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 7);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredConstructors", "()[Ljava/lang/reflect/Constructor;", false);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Constructor", "newInstance", "([Ljava/lang/Object;)Ljava/lang/Object;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/invoke/MethodHandles", "constant", "(Ljava/lang/Class;Ljava/lang/Object;)Ljava/lang/invoke/MethodHandle;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/invoke/ConstantCallSite", "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false);
Label conditionalAlternative = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, conditionalAlternative);
methodVisitor.visitLabel(conditionalDefault);
methodVisitor.visitFrame(Opcodes.F_APPEND, 2, new Object[]{UNSAFE_CLASS, "java/lang/Class"}, 0, null);
methodVisitor.visitTypeInsn(Opcodes.NEW, "java/lang/invoke/ConstantCallSite");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/invoke/MethodHandles$Lookup", "IMPL_LOOKUP", "Ljava/lang/invoke/MethodHandles$Lookup;");
methodVisitor.visitVarInsn(Opcodes.ALOAD, 7);
methodVisitor.visitLdcInsn("get$Lambda");
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "findStatic", "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/MethodHandle;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/invoke/ConstantCallSite", "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false);
methodVisitor.visitLabel(conditionalAlternative);
methodVisitor.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[]{"java/lang/invoke/CallSite"});
methodVisitor.visitInsn(Opcodes.ARETURN);
methodVisitor.visitMaxs(8, 8);
methodVisitor.visitEnd();
return IGNORE_ORIGINAL;
}
}
/**
* Implements the alternative lambda meta factory. The implementation represents the following code:
* <blockquote><pre>
* public static CallSite altMetafactory(MethodHandles.Lookup caller,
* String invokedName,
* MethodType invokedType,
* Object... args) throws Exception {
* int flags = (Integer) args[3];
* int argIndex = 4;
* {@code Class<?>[]} markerInterface;
* if ((flags {@code &} FLAG_MARKERS) != 0) {
* int markerCount = (Integer) args[argIndex++];
* markerInterface = new {@code Class<?>}[markerCount];
* System.arraycopy(args, argIndex, markerInterface, 0, markerCount);
* argIndex += markerCount;
* } else {
* markerInterface = new {@code Class<?>}[0];
* }
* MethodType[] additionalBridge;
* if ((flags {@code &} FLAG_BRIDGES) != 0) {
* int bridgeCount = (Integer) args[argIndex++];
* additionalBridge = new MethodType[bridgeCount];
* System.arraycopy(args, argIndex, additionalBridge, 0, bridgeCount);
* // argIndex += bridgeCount;
* } else {
* additionalBridge = new MethodType[0];
* }
* Unsafe unsafe = Unsafe.getUnsafe();
* {@code Class<?>} lambdaClass = unsafe.defineAnonymousClass(caller.lookupClass(),
* (byte[]) ClassLoader.getSystemClassLoader().loadClass("net.bytebuddy.agent.builder.LambdaFactory").getDeclaredMethod("make",
* Object.class,
* String.class,
* Object.class,
* Object.class,
* Object.class,
* Object.class,
* boolean.class,
* List.class,
* List.class).invoke(null,
* caller,
* invokedName,
* invokedType,
* args[0],
* args[1],
* args[2],
* (flags {@code &} FLAG_SERIALIZABLE) != 0,
* Arrays.asList(markerInterface),
* Arrays.asList(additionalBridge)),
* null);
* unsafe.ensureClassInitialized(lambdaClass);
* return invokedType.parameterCount() == 0
* ? new ConstantCallSite(MethodHandles.constant(invokedType.returnType(), lambdaClass.getDeclaredConstructors()[0].newInstance()))
* : new ConstantCallSite(MethodHandles.Lookup.IMPL_LOOKUP.findStatic(lambdaClass, "get$Lambda", invokedType));
* }
* </pre></blockquote>
*/
protected enum AlternativeMetaFactoryRedirection implements AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public MethodVisitor wrap(TypeDescription instrumentedType,
MethodDescription instrumentedMethod,
MethodVisitor methodVisitor,
Implementation.Context implementationContext,
TypePool typePool,
int writerFlags,
int readerFlags) {
methodVisitor.visitCode();
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitInsn(Opcodes.ICONST_3);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Integer");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 4);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 5);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 4);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitInsn(Opcodes.IAND);
Label markerInterfaceLoop = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFEQ, markerInterfaceLoop);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 5);
methodVisitor.visitIincInsn(5, 1);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Integer");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 7);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 7);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class");
methodVisitor.visitVarInsn(Opcodes.ASTORE, 6);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 5);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 6);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 7);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/System", "arraycopy", "(Ljava/lang/Object;ILjava/lang/Object;II)V", false);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 5);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 7);
methodVisitor.visitInsn(Opcodes.IADD);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 5);
Label markerInterfaceExit = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, markerInterfaceExit);
methodVisitor.visitLabel(markerInterfaceLoop);
methodVisitor.visitFrame(Opcodes.F_APPEND, 2, new Object[]{Opcodes.INTEGER, Opcodes.INTEGER}, 0, null);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class");
methodVisitor.visitVarInsn(Opcodes.ASTORE, 6);
methodVisitor.visitLabel(markerInterfaceExit);
methodVisitor.visitFrame(Opcodes.F_APPEND, 1, new Object[]{"[Ljava/lang/Class;"}, 0, null);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 4);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitInsn(Opcodes.IAND);
Label additionalBridgesLoop = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFEQ, additionalBridgesLoop);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 5);
methodVisitor.visitIincInsn(5, 1);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Integer");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 8);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 8);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/invoke/MethodType");
methodVisitor.visitVarInsn(Opcodes.ASTORE, 7);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 5);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 7);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 8);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/System", "arraycopy", "(Ljava/lang/Object;ILjava/lang/Object;II)V", false);
Label additionalBridgesExit = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, additionalBridgesExit);
methodVisitor.visitLabel(additionalBridgesLoop);
methodVisitor.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/invoke/MethodType");
methodVisitor.visitVarInsn(Opcodes.ASTORE, 7);
methodVisitor.visitLabel(additionalBridgesExit);
methodVisitor.visitFrame(Opcodes.F_APPEND, 1, new Object[]{"[Ljava/lang/invoke/MethodType;"}, 0, null);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, UNSAFE_CLASS, "getUnsafe", "()L" + UNSAFE_CLASS + ";", false);
methodVisitor.visitVarInsn(Opcodes.ASTORE, 8);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 8);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "lookupClass", "()Ljava/lang/Class;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/ClassLoader", "getSystemClassLoader", "()Ljava/lang/ClassLoader;", false);
methodVisitor.visitLdcInsn("net.bytebuddy.agent.builder.LambdaFactory");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/ClassLoader", "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;", false);
methodVisitor.visitLdcInsn("make");
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 9);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Class");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/String;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_3);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_5);
methodVisitor.visitLdcInsn(Type.getType("Ljava/lang/Object;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 6);
methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Boolean", "TYPE", "Ljava/lang/Class;");
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 7);
methodVisitor.visitLdcInsn(Type.getType("Ljava/util/List;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 8);
methodVisitor.visitLdcInsn(Type.getType("Ljava/util/List;"));
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredMethod", "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;", false);
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 9);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_3);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_4);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitInsn(Opcodes.ICONST_5);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
methodVisitor.visitInsn(Opcodes.ICONST_2);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 6);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 4);
methodVisitor.visitInsn(Opcodes.ICONST_1);
methodVisitor.visitInsn(Opcodes.IAND);
Label callSiteConditional = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFEQ, callSiteConditional);
methodVisitor.visitInsn(Opcodes.ICONST_1);
Label callSiteAlternative = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, callSiteAlternative);
methodVisitor.visitLabel(callSiteConditional);
methodVisitor.visitFrame(Opcodes.F_FULL, 9, new Object[]{"java/lang/invoke/MethodHandles$Lookup", "java/lang/String", "java/lang/invoke/MethodType", "[Ljava/lang/Object;", Opcodes.INTEGER, Opcodes.INTEGER, "[Ljava/lang/Class;", "[Ljava/lang/invoke/MethodType;", UNSAFE_CLASS}, 7, new Object[]{UNSAFE_CLASS, "java/lang/Class", "java/lang/reflect/Method", Opcodes.NULL, "[Ljava/lang/Object;", "[Ljava/lang/Object;", Opcodes.INTEGER});
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitLabel(callSiteAlternative);
methodVisitor.visitFrame(Opcodes.F_FULL, 9, new Object[]{"java/lang/invoke/MethodHandles$Lookup", "java/lang/String", "java/lang/invoke/MethodType", "[Ljava/lang/Object;", Opcodes.INTEGER, Opcodes.INTEGER, "[Ljava/lang/Class;", "[Ljava/lang/invoke/MethodType;", UNSAFE_CLASS}, 8, new Object[]{UNSAFE_CLASS, "java/lang/Class", "java/lang/reflect/Method", Opcodes.NULL, "[Ljava/lang/Object;", "[Ljava/lang/Object;", Opcodes.INTEGER, Opcodes.INTEGER});
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 7);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 6);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Arrays", "asList", "([Ljava/lang/Object;)Ljava/util/List;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitIntInsn(Opcodes.BIPUSH, 8);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 7);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Arrays", "asList", "([Ljava/lang/Object;)Ljava/util/List;", false);
methodVisitor.visitInsn(Opcodes.AASTORE);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Method", "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", false);
methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, "[B");
methodVisitor.visitInsn(Opcodes.ACONST_NULL);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, UNSAFE_CLASS, "defineAnonymousClass", "(Ljava/lang/Class;[B[Ljava/lang/Object;)Ljava/lang/Class;", false);
methodVisitor.visitVarInsn(Opcodes.ASTORE, 9);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 8);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 9);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, UNSAFE_CLASS, "ensureClassInitialized", "(Ljava/lang/Class;)V", false);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodType", "parameterCount", "()I", false);
Label callSiteJump = new Label();
methodVisitor.visitJumpInsn(Opcodes.IFNE, callSiteJump);
methodVisitor.visitTypeInsn(Opcodes.NEW, "java/lang/invoke/ConstantCallSite");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodType", "returnType", "()Ljava/lang/Class;", false);
methodVisitor.visitVarInsn(Opcodes.ALOAD, 9);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getDeclaredConstructors", "()[Ljava/lang/reflect/Constructor;", false);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitInsn(Opcodes.AALOAD);
methodVisitor.visitInsn(Opcodes.ICONST_0);
methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/reflect/Constructor", "newInstance", "([Ljava/lang/Object;)Ljava/lang/Object;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/invoke/MethodHandles", "constant", "(Ljava/lang/Class;Ljava/lang/Object;)Ljava/lang/invoke/MethodHandle;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/invoke/ConstantCallSite", "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false);
Label callSiteExit = new Label();
methodVisitor.visitJumpInsn(Opcodes.GOTO, callSiteExit);
methodVisitor.visitLabel(callSiteJump);
methodVisitor.visitFrame(Opcodes.F_APPEND, 1, new Object[]{"java/lang/Class"}, 0, null);
methodVisitor.visitTypeInsn(Opcodes.NEW, "java/lang/invoke/ConstantCallSite");
methodVisitor.visitInsn(Opcodes.DUP);
methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/invoke/MethodHandles$Lookup", "IMPL_LOOKUP", "Ljava/lang/invoke/MethodHandles$Lookup;");
methodVisitor.visitVarInsn(Opcodes.ALOAD, 9);
methodVisitor.visitLdcInsn("get$Lambda");
methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "findStatic", "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/MethodHandle;", false);
methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/invoke/ConstantCallSite", "<init>", "(Ljava/lang/invoke/MethodHandle;)V", false);
methodVisitor.visitLabel(callSiteExit);
methodVisitor.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[]{"java/lang/invoke/CallSite"});
methodVisitor.visitInsn(Opcodes.ARETURN);
methodVisitor.visitMaxs(9, 10);
methodVisitor.visitEnd();
return IGNORE_ORIGINAL;
}
}
}
/**
* <p>
* The default implementation of an {@link net.bytebuddy.agent.builder.AgentBuilder}.
* </p>
* <p>
* By default, Byte Buddy ignores any types loaded by the bootstrap class loader and
* any synthetic type. Self-injection and rebasing is enabled. In order to avoid class format changes, set
* {@link AgentBuilder#disableClassFormatChanges()}. All types are parsed without their debugging information
* ({@link PoolStrategy.Default#FAST}).
* </p>
*/
@HashCodeAndEqualsPlugin.Enhance
class Default implements AgentBuilder {
/**
* The name of the Byte Buddy {@code net.bytebuddy.agent.Installer} class.
*/
private static final String INSTALLER_TYPE = "net.bytebuddy.agent.Installer";
/**
* The name of the {@code net.bytebuddy.agent.Installer} getter for reading an installed {@link Instrumentation}.
*/
private static final String INSTRUMENTATION_GETTER = "getInstrumentation";
/**
* Indicator for access to a static member via reflection to make the code more readable.
*/
private static final Object STATIC_MEMBER = null;
/**
* The value that is to be returned from a {@link java.lang.instrument.ClassFileTransformer} to indicate
* that no class file transformation is to be applied.
*/
private static final byte[] NO_TRANSFORMATION = null;
/**
* Indicates that a loaded type should be considered as non-available.
*/
private static final Class<?> NO_LOADED_TYPE = null;
/**
* A dipatcher to use for interacting with the instrumentation API.
*/
private static final Dispatcher DISPATCHER = AccessController.doPrivileged(Dispatcher.CreationAction.INSTANCE);
/**
* The default circularity lock that assures that no agent created by any agent builder within this
* class loader causes a class loading circularity.
*/
private static final CircularityLock DEFAULT_LOCK = new CircularityLock.Default();
/**
* The {@link net.bytebuddy.ByteBuddy} instance to be used.
*/
protected final ByteBuddy byteBuddy;
/**
* The listener to notify on transformations.
*/
protected final Listener listener;
/**
* The circularity lock to use.
*/
protected final CircularityLock circularityLock;
/**
* The type locator to use.
*/
protected final PoolStrategy poolStrategy;
/**
* The definition handler to use.
*/
protected final TypeStrategy typeStrategy;
/**
* The location strategy to use.
*/
protected final LocationStrategy locationStrategy;
/**
* The native method strategy to use.
*/
protected final NativeMethodStrategy nativeMethodStrategy;
/**
* A decorator to wrap the created class file transformer.
*/
protected final TransformerDecorator transformerDecorator;
/**
* The initialization strategy to use for creating classes.
*/
protected final InitializationStrategy initializationStrategy;
/**
* The redefinition strategy to apply.
*/
protected final RedefinitionStrategy redefinitionStrategy;
/**
* The discovery strategy for loaded types to be redefined.
*/
protected final RedefinitionStrategy.DiscoveryStrategy redefinitionDiscoveryStrategy;
/**
* The batch allocator for the redefinition strategy to apply.
*/
protected final RedefinitionStrategy.BatchAllocator redefinitionBatchAllocator;
/**
* The redefinition listener for the redefinition strategy to apply.
*/
protected final RedefinitionStrategy.Listener redefinitionListener;
/**
* The resubmission strategy to apply.
*/
protected final RedefinitionStrategy.ResubmissionStrategy redefinitionResubmissionStrategy;
/**
* The injection strategy for injecting classes into a class loader.
*/
protected final InjectionStrategy injectionStrategy;
/**
* A strategy to determine of the {@code LambdaMetafactory} should be instrumented to allow for the instrumentation
* of classes that represent lambda expressions.
*/
protected final LambdaInstrumentationStrategy lambdaInstrumentationStrategy;
/**
* The description strategy for resolving type descriptions for types.
*/
protected final DescriptionStrategy descriptionStrategy;
/**
* The fallback strategy to apply.
*/
protected final FallbackStrategy fallbackStrategy;
/**
* The class file buffer strategy to use.
*/
protected final ClassFileBufferStrategy classFileBufferStrategy;
/**
* The installation listener to notify.
*/
protected final InstallationListener installationListener;
/**
* Identifies types that should not be instrumented.
*/
protected final RawMatcher ignoreMatcher;
/**
* The transformation object for handling type transformations.
*/
protected final List<Transformation> transformations;
/**
* Creates a new default agent builder that uses a default {@link net.bytebuddy.ByteBuddy} instance for creating classes.
*/
public Default() {
this(new ByteBuddy());
}
/**
* Creates a new agent builder with default settings. By default, Byte Buddy ignores any types loaded by the bootstrap class loader, any
* type within a {@code net.bytebuddy} package and any synthetic type. Self-injection and rebasing is enabled. In order to avoid class format
* changes, set {@link AgentBuilder#disableClassFormatChanges()}. All types are parsed without their debugging information
* ({@link PoolStrategy.Default#FAST}).
*
* @param byteBuddy The Byte Buddy instance to be used.
*/
public Default(ByteBuddy byteBuddy) {
this(byteBuddy,
Listener.NoOp.INSTANCE,
DEFAULT_LOCK,
PoolStrategy.Default.FAST,
TypeStrategy.Default.REBASE,
LocationStrategy.ForClassLoader.STRONG,
NativeMethodStrategy.Disabled.INSTANCE,
TransformerDecorator.NoOp.INSTANCE,
new InitializationStrategy.SelfInjection.Split(),
RedefinitionStrategy.DISABLED,
RedefinitionStrategy.DiscoveryStrategy.SinglePass.INSTANCE,
RedefinitionStrategy.BatchAllocator.ForTotal.INSTANCE,
RedefinitionStrategy.Listener.NoOp.INSTANCE,
RedefinitionStrategy.ResubmissionStrategy.Disabled.INSTANCE,
InjectionStrategy.UsingReflection.INSTANCE,
LambdaInstrumentationStrategy.DISABLED,
DescriptionStrategy.Default.HYBRID,
FallbackStrategy.ByThrowableType.ofOptionalTypes(),
ClassFileBufferStrategy.Default.RETAINING,
InstallationListener.NoOp.INSTANCE,
new RawMatcher.Disjunction(
new RawMatcher.ForElementMatchers(any(), isBootstrapClassLoader().or(isExtensionClassLoader())),
new RawMatcher.ForElementMatchers(nameStartsWith("net.bytebuddy.").or(nameStartsWith("sun.reflect.")).<TypeDescription>or(isSynthetic()))),
Collections.<Transformation>emptyList());
}
/**
* Creates a new default agent builder.
*
* @param byteBuddy The Byte Buddy instance to be used.
* @param listener The listener to notify on transformations.
* @param circularityLock The circularity lock to use.
* @param poolStrategy The type locator to use.
* @param typeStrategy The definition handler to use.
* @param locationStrategy The location strategy to use.
* @param nativeMethodStrategy The native method strategy to apply.
* @param transformerDecorator A decorator to wrap the created class file transformer.
* @param initializationStrategy The initialization strategy to use for transformed types.
* @param redefinitionStrategy The redefinition strategy to apply.
* @param redefinitionDiscoveryStrategy The discovery strategy for loaded types to be redefined.
* @param redefinitionBatchAllocator The batch allocator for the redefinition strategy to apply.
* @param redefinitionListener The redefinition listener for the redefinition strategy to apply.
* @param redefinitionResubmissionStrategy The resubmission strategy to apply.
* @param injectionStrategy The injection strategy for injecting classes into a class loader.
* @param lambdaInstrumentationStrategy A strategy to determine of the {@code LambdaMetafactory} should be instrumented to allow for the
* instrumentation of classes that represent lambda expressions.
* @param descriptionStrategy The description strategy for resolving type descriptions for types.
* @param fallbackStrategy The fallback strategy to apply.
* @param classFileBufferStrategy The class file buffer strategy to use.
* @param installationListener The installation listener to notify.
* @param ignoreMatcher Identifies types that should not be instrumented.
* @param transformations The transformations to apply for any non-ignored type.
*/
protected Default(ByteBuddy byteBuddy,
Listener listener,
CircularityLock circularityLock,
PoolStrategy poolStrategy,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
NativeMethodStrategy nativeMethodStrategy,
TransformerDecorator transformerDecorator,
InitializationStrategy initializationStrategy,
RedefinitionStrategy redefinitionStrategy,
RedefinitionStrategy.DiscoveryStrategy redefinitionDiscoveryStrategy,
RedefinitionStrategy.BatchAllocator redefinitionBatchAllocator,
RedefinitionStrategy.Listener redefinitionListener,
RedefinitionStrategy.ResubmissionStrategy redefinitionResubmissionStrategy,
InjectionStrategy injectionStrategy,
LambdaInstrumentationStrategy lambdaInstrumentationStrategy,
DescriptionStrategy descriptionStrategy,
FallbackStrategy fallbackStrategy,
ClassFileBufferStrategy classFileBufferStrategy,
InstallationListener installationListener,
RawMatcher ignoreMatcher,
List<Transformation> transformations) {
this.byteBuddy = byteBuddy;
this.listener = listener;
this.circularityLock = circularityLock;
this.poolStrategy = poolStrategy;
this.typeStrategy = typeStrategy;
this.locationStrategy = locationStrategy;
this.nativeMethodStrategy = nativeMethodStrategy;
this.transformerDecorator = transformerDecorator;
this.initializationStrategy = initializationStrategy;
this.redefinitionStrategy = redefinitionStrategy;
this.redefinitionDiscoveryStrategy = redefinitionDiscoveryStrategy;
this.redefinitionBatchAllocator = redefinitionBatchAllocator;
this.redefinitionListener = redefinitionListener;
this.redefinitionResubmissionStrategy = redefinitionResubmissionStrategy;
this.injectionStrategy = injectionStrategy;
this.lambdaInstrumentationStrategy = lambdaInstrumentationStrategy;
this.descriptionStrategy = descriptionStrategy;
this.fallbackStrategy = fallbackStrategy;
this.classFileBufferStrategy = classFileBufferStrategy;
this.installationListener = installationListener;
this.ignoreMatcher = ignoreMatcher;
this.transformations = transformations;
}
/**
* Creates an {@link AgentBuilder} that realizes the provided build plugins. As {@link EntryPoint}, {@link EntryPoint.Default#REBASE} is implied.
*
* @param plugin The build plugins to apply as a Java agent.
* @return An appropriate agent builder.
*/
public static AgentBuilder of(Plugin... plugin) {
return of(Arrays.asList(plugin));
}
/**
* Creates an {@link AgentBuilder} that realizes the provided build plugins. As {@link EntryPoint}, {@link EntryPoint.Default#REBASE} is implied.
*
* @param plugins The build plugins to apply as a Java agent.
* @return An appropriate agent builder.
*/
public static AgentBuilder of(List<? extends Plugin> plugins) {
return of(EntryPoint.Default.REBASE, plugins);
}
/**
* Creates an {@link AgentBuilder} that realizes the provided build plugins.
*
* @param entryPoint The build entry point to use.
* @param plugin The build plugins to apply as a Java agent.
* @return An appropriate agent builder.
*/
public static AgentBuilder of(EntryPoint entryPoint, Plugin... plugin) {
return of(entryPoint, Arrays.asList(plugin));
}
/**
* Creates an {@link AgentBuilder} that realizes the provided build plugins.
*
* @param entryPoint The build entry point to use.
* @param plugins The build plugins to apply as a Java agent.
* @return An appropriate agent builder.
*/
public static AgentBuilder of(EntryPoint entryPoint, List<? extends Plugin> plugins) {
return of(entryPoint, ClassFileVersion.ofThisVm(), plugins);
}
/**
* Creates an {@link AgentBuilder} that realizes the provided build plugins. As {@link EntryPoint}, {@link EntryPoint.Default#REBASE} is implied.
*
* @param classFileVersion The class file version to use.
* @param plugin The build plugins to apply as a Java agent.
* @return An appropriate agent builder.
*/
public static AgentBuilder of(ClassFileVersion classFileVersion, Plugin... plugin) {
return of(classFileVersion, Arrays.asList(plugin));
}
/**
* Creates an {@link AgentBuilder} that realizes the provided build plugins. As {@link EntryPoint}, {@link EntryPoint.Default#REBASE} is implied.
*
* @param classFileVersion The class file version to use.
* @param plugins The build plugins to apply as a Java agent.
* @return An appropriate agent builder.
*/
public static AgentBuilder of(ClassFileVersion classFileVersion, List<? extends Plugin> plugins) {
return of(EntryPoint.Default.REBASE, classFileVersion, plugins);
}
/**
* Creates an {@link AgentBuilder} that realizes the provided build plugins.
*
* @param entryPoint The build entry point to use.
* @param classFileVersion The class file version to use.
* @param plugin The build plugins to apply as a Java agent.
* @return An appropriate agent builder.
*/
public static AgentBuilder of(EntryPoint entryPoint, ClassFileVersion classFileVersion, Plugin... plugin) {
return of(entryPoint, classFileVersion, Arrays.asList(plugin));
}
/**
* Creates an {@link AgentBuilder} that realizes the provided build plugins.
*
* @param entryPoint The build entry point to use.
* @param classFileVersion The class file version to use.
* @param plugins The build plugins to apply as a Java agent.
* @return An appropriate agent builder.
*/
public static AgentBuilder of(EntryPoint entryPoint, ClassFileVersion classFileVersion, List<? extends Plugin> plugins) {
AgentBuilder agentBuilder = new AgentBuilder.Default(entryPoint.byteBuddy(classFileVersion)).with(new TypeStrategy.ForBuildEntryPoint(entryPoint));
for (Plugin plugin : plugins) {
agentBuilder = agentBuilder.type(plugin).transform(new Transformer.ForBuildPlugin(plugin));
}
return agentBuilder;
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(ByteBuddy byteBuddy) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(Listener listener) {
return new Default(byteBuddy,
new Listener.Compound(this.listener, listener),
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(CircularityLock circularityLock) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(TypeStrategy typeStrategy) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(PoolStrategy poolStrategy) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(LocationStrategy locationStrategy) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder enableNativeMethodPrefix(String prefix) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
NativeMethodStrategy.ForPrefix.of(prefix),
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder disableNativeMethodPrefix() {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
NativeMethodStrategy.Disabled.INSTANCE,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(TransformerDecorator transformerDecorator) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
new TransformerDecorator.Compound(this.transformerDecorator, transformerDecorator),
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public RedefinitionListenable.WithoutBatchStrategy with(RedefinitionStrategy redefinitionStrategy) {
return new Redefining(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
RedefinitionStrategy.DiscoveryStrategy.SinglePass.INSTANCE,
RedefinitionStrategy.BatchAllocator.ForTotal.INSTANCE,
RedefinitionStrategy.Listener.NoOp.INSTANCE,
RedefinitionStrategy.ResubmissionStrategy.Disabled.INSTANCE,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(InitializationStrategy initializationStrategy) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(LambdaInstrumentationStrategy lambdaInstrumentationStrategy) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(DescriptionStrategy descriptionStrategy) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(FallbackStrategy fallbackStrategy) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(ClassFileBufferStrategy classFileBufferStrategy) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(InstallationListener installationListener) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
new InstallationListener.Compound(this.installationListener, installationListener),
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(InjectionStrategy injectionStrategy) {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder disableClassFormatChanges() {
return new Default(byteBuddy.with(Implementation.Context.Disabled.Factory.INSTANCE),
listener,
circularityLock,
poolStrategy,
typeStrategy == TypeStrategy.Default.DECORATE
? TypeStrategy.Default.DECORATE
: TypeStrategy.Default.REDEFINE_FROZEN,
locationStrategy,
NativeMethodStrategy.Disabled.INSTANCE,
transformerDecorator,
InitializationStrategy.NoOp.INSTANCE,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Class<?>... type) {
return JavaModule.isSupported()
? with(Listener.ModuleReadEdgeCompleting.of(instrumentation, false, type))
: this;
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, JavaModule... module) {
return assureReadEdgeTo(instrumentation, Arrays.asList(module));
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules) {
return with(new Listener.ModuleReadEdgeCompleting(instrumentation, false, new HashSet<JavaModule>(modules)));
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Class<?>... type) {
return JavaModule.isSupported()
? with(Listener.ModuleReadEdgeCompleting.of(instrumentation, true, type))
: this;
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, JavaModule... module) {
return assureReadEdgeFromAndTo(instrumentation, Arrays.asList(module));
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules) {
return with(new Listener.ModuleReadEdgeCompleting(instrumentation, true, new HashSet<JavaModule>(modules)));
}
/**
* {@inheritDoc}
*/
public Identified.Narrowable type(RawMatcher matcher) {
return new Transforming(matcher, Collections.<Transformer>emptyList(), false);
}
/**
* {@inheritDoc}
*/
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher) {
return type(typeMatcher, any());
}
/**
* {@inheritDoc}
*/
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) {
return type(typeMatcher, classLoaderMatcher, any());
}
/**
* {@inheritDoc}
*/
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return type(new RawMatcher.ForElementMatchers(typeMatcher, classLoaderMatcher, not(supportsModules()).or(moduleMatcher)));
}
/**
* {@inheritDoc}
*/
public Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher) {
return ignore(typeMatcher, any());
}
/**
* {@inheritDoc}
*/
public Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) {
return ignore(typeMatcher, classLoaderMatcher, any());
}
/**
* {@inheritDoc}
*/
public Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return ignore(new RawMatcher.ForElementMatchers(typeMatcher, classLoaderMatcher, not(supportsModules()).or(moduleMatcher)));
}
/**
* {@inheritDoc}
*/
public Ignored ignore(RawMatcher rawMatcher) {
return new Ignoring(rawMatcher);
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer makeRaw() {
return makeRaw(listener, InstallationListener.NoOp.INSTANCE);
}
/**
* Creates a new class file transformer with a given listener.
*
* @param listener The listener to supply.
* @param installationListener The installation listener to notify.
* @return The resettable class file transformer to use.
*/
private ResettableClassFileTransformer makeRaw(Listener listener, InstallationListener installationListener) {
return ExecutingTransformer.FACTORY.make(byteBuddy,
listener,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
initializationStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations,
circularityLock);
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer installOn(Instrumentation instrumentation) {
if (!circularityLock.acquire()) {
throw new IllegalStateException("Could not acquire the circularity lock upon installation.");
}
try {
return doInstall(instrumentation, new Transformation.SimpleMatcher(ignoreMatcher, transformations));
} finally {
circularityLock.release();
}
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer installOnByteBuddyAgent() {
try {
return installOn((Instrumentation) ClassLoader.getSystemClassLoader()
.loadClass(INSTALLER_TYPE)
.getMethod(INSTRUMENTATION_GETTER)
.invoke(STATIC_MEMBER));
} catch (RuntimeException exception) {
throw exception;
} catch (Exception exception) {
throw new IllegalStateException("The Byte Buddy agent is not installed or not accessible", exception);
}
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer patchOn(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
if (!circularityLock.acquire()) {
throw new IllegalStateException("Could not acquire the circularity lock upon installation.");
}
try {
if (!classFileTransformer.reset(instrumentation, RedefinitionStrategy.DISABLED)) {
throw new IllegalArgumentException("Cannot patch unregistered class file transformer: " + classFileTransformer);
}
return doInstall(instrumentation, new Transformation.DifferentialMatcher(ignoreMatcher, transformations, classFileTransformer));
} finally {
circularityLock.release();
}
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer patchOnByteBuddyAgent(ResettableClassFileTransformer classFileTransformer) {
try {
return patchOn((Instrumentation) ClassLoader.getSystemClassLoader()
.loadClass(INSTALLER_TYPE)
.getMethod(INSTRUMENTATION_GETTER)
.invoke(STATIC_MEMBER), classFileTransformer);
} catch (RuntimeException exception) {
throw exception;
} catch (Exception exception) {
throw new IllegalStateException("The Byte Buddy agent is not installed or not accessible", exception);
}
}
/**
* Installs the class file transformer.
*
* @param instrumentation The instrumentation to install the matcher on.
* @param matcher The matcher to identify redefined types.
* @return The created class file transformer.
*/
private ResettableClassFileTransformer doInstall(Instrumentation instrumentation, RawMatcher matcher) {
RedefinitionStrategy.ResubmissionStrategy.Installation installation = redefinitionResubmissionStrategy.apply(instrumentation,
locationStrategy,
listener,
installationListener,
circularityLock,
new Transformation.SimpleMatcher(ignoreMatcher, transformations),
redefinitionStrategy,
redefinitionBatchAllocator,
redefinitionListener);
ResettableClassFileTransformer classFileTransformer = transformerDecorator.decorate(makeRaw(installation.getListener(),
installation.getInstallationListener()));
installation.getInstallationListener().onBeforeInstall(instrumentation, classFileTransformer);
try {
DISPATCHER.addTransformer(instrumentation, classFileTransformer, redefinitionStrategy.isRetransforming());
nativeMethodStrategy.apply(instrumentation, classFileTransformer);
lambdaInstrumentationStrategy.apply(byteBuddy, instrumentation, classFileTransformer);
redefinitionStrategy.apply(instrumentation,
installation.getListener(),
circularityLock,
poolStrategy,
locationStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
matcher);
} catch (Throwable throwable) {
throwable = installation.getInstallationListener().onError(instrumentation, classFileTransformer, throwable);
if (throwable != null) {
instrumentation.removeTransformer(classFileTransformer);
throw new IllegalStateException("Could not install class file transformer", throwable);
}
}
installation.getInstallationListener().onInstall(instrumentation, classFileTransformer);
return classFileTransformer;
}
/**
* A dispatcher for interacting with the instrumentation API.
*/
protected interface Dispatcher {
/**
* Returns {@code true} if the supplied instrumentation instance supports setting native method prefixes.
*
* @param instrumentation The instrumentation instance to use.
* @return {@code true} if the supplied instrumentation instance supports native method prefixes.
*/
boolean isNativeMethodPrefixSupported(Instrumentation instrumentation);
/**
* Sets a native method prefix for the supplied class file transformer.
*
* @param instrumentation The instrumentation instance to use.
* @param classFileTransformer The class file transformer for which the prefix is set.
* @param prefix The prefix to set.
*/
void setNativeMethodPrefix(Instrumentation instrumentation, ClassFileTransformer classFileTransformer, String prefix);
/**
* Adds a class file transformer to an instrumentation instance.
*
* @param instrumentation The instrumentation instance to use for registration.
* @param classFileTransformer The class file transformer to register.
* @param canRetransform {@code true} if the class file transformer is capable of retransformation.
*/
void addTransformer(Instrumentation instrumentation, ClassFileTransformer classFileTransformer, boolean canRetransform);
/**
* An action for creating a dispatcher.
*/
enum CreationAction implements PrivilegedAction<Dispatcher> {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Dispatcher run() {
try {
return new Dispatcher.ForJava6CapableVm(Instrumentation.class.getMethod("isNativeMethodPrefixSupported"),
Instrumentation.class.getMethod("setNativeMethodPrefix", ClassFileTransformer.class, String.class),
Instrumentation.class.getMethod("addTransformer", ClassFileTransformer.class, boolean.class));
} catch (NoSuchMethodException ignored) {
return Dispatcher.ForLegacyVm.INSTANCE;
}
}
}
/**
* A dispatcher for a legacy VM.
*/
enum ForLegacyVm implements Dispatcher {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public boolean isNativeMethodPrefixSupported(Instrumentation instrumentation) {
return false;
}
/**
* {@inheritDoc}
*/
public void setNativeMethodPrefix(Instrumentation instrumentation, ClassFileTransformer classFileTransformer, String prefix) {
throw new UnsupportedOperationException("The current VM does not support native method prefixes");
}
/**
* {@inheritDoc}
*/
public void addTransformer(Instrumentation instrumentation, ClassFileTransformer classFileTransformer, boolean canRetransform) {
if (canRetransform) {
throw new UnsupportedOperationException("The current VM does not support retransformation");
}
instrumentation.addTransformer(classFileTransformer);
}
}
/**
* A dispatcher for a Java 6 capable VM.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForJava6CapableVm implements Dispatcher {
/**
* The {@code Instrumentation#isNativeMethodPrefixSupported} method.
*/
private final Method isNativeMethodPrefixSupported;
/**
* The {@code Instrumentation#setNativeMethodPrefix} method.
*/
private final Method setNativeMethodPrefix;
/**
* The {@code Instrumentation#addTransformer} method.
*/
private final Method addTransformer;
/**
* Creates a new Java 6 capable dispatcher.
*
* @param isNativeMethodPrefixSupported The {@code Instrumentation#isNativeMethodPrefixSupported} method.
* @param setNativeMethodPrefix The {@code Instrumentation#setNativeMethodPrefix} method.
* @param addTransformer The {@code Instrumentation#addTransformer} method.
*/
protected ForJava6CapableVm(Method isNativeMethodPrefixSupported, Method setNativeMethodPrefix, Method addTransformer) {
this.isNativeMethodPrefixSupported = isNativeMethodPrefixSupported;
this.setNativeMethodPrefix = setNativeMethodPrefix;
this.addTransformer = addTransformer;
}
/**
* {@inheritDoc}
*/
public boolean isNativeMethodPrefixSupported(Instrumentation instrumentation) {
try {
return (Boolean) isNativeMethodPrefixSupported.invoke(instrumentation);
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Cannot access java.lang.instrument.Instrumentation#isNativeMethodPrefixSupported", exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException("Error invoking java.lang.instrument.Instrumentation#isNativeMethodPrefixSupported", exception.getCause());
}
}
/**
* {@inheritDoc}
*/
public void setNativeMethodPrefix(Instrumentation instrumentation, ClassFileTransformer classFileTransformer, String prefix) {
try {
setNativeMethodPrefix.invoke(instrumentation, classFileTransformer, prefix);
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Cannot access java.lang.instrument.Instrumentation#setNativeMethodPrefix", exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException("Error invoking java.lang.instrument.Instrumentation#setNativeMethodPrefix", exception.getCause());
}
}
/**
* {@inheritDoc}
*/
public void addTransformer(Instrumentation instrumentation, ClassFileTransformer classFileTransformer, boolean canRetransform) {
try {
addTransformer.invoke(instrumentation, classFileTransformer, canRetransform);
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Cannot access java.lang.instrument.Instrumentation#addTransformer", exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException("Error invoking java.lang.instrument.Instrumentation#addTransformer", exception.getCause());
}
}
}
}
/**
* A strategy for determining if a native method name prefix should be used when rebasing methods.
*/
protected interface NativeMethodStrategy {
/**
* Resolves the method name transformer for this strategy.
*
* @return A method name transformer for this strategy.
*/
MethodNameTransformer resolve();
/**
* Applies this native method strategy.
*
* @param instrumentation The instrumentation to apply this strategy upon.
* @param classFileTransformer The class file transformer being registered.
*/
void apply(Instrumentation instrumentation, ClassFileTransformer classFileTransformer);
/**
* A native method strategy that suffixes method names with a random suffix and disables native method rebasement.
*/
enum Disabled implements NativeMethodStrategy {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public MethodNameTransformer resolve() {
return MethodNameTransformer.Suffixing.withRandomSuffix();
}
/**
* {@inheritDoc}
*/
public void apply(Instrumentation instrumentation, ClassFileTransformer classFileTransformer) {
/* do nothing */
}
}
/**
* A native method strategy that prefixes method names with a fixed value for supporting rebasing of native methods.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForPrefix implements NativeMethodStrategy {
/**
* The method name prefix.
*/
private final String prefix;
/**
* Creates a new name prefixing native method strategy.
*
* @param prefix The method name prefix.
*/
protected ForPrefix(String prefix) {
this.prefix = prefix;
}
/**
* Creates a new native method strategy for prefixing method names.
*
* @param prefix The method name prefix.
* @return An appropriate native method strategy.
*/
protected static NativeMethodStrategy of(String prefix) {
if (prefix.length() == 0) {
throw new IllegalArgumentException("A method name prefix must not be the empty string");
}
return new ForPrefix(prefix);
}
/**
* {@inheritDoc}
*/
public MethodNameTransformer resolve() {
return new MethodNameTransformer.Prefixing(prefix);
}
/**
* {@inheritDoc}
*/
public void apply(Instrumentation instrumentation, ClassFileTransformer classFileTransformer) {
if (!DISPATCHER.isNativeMethodPrefixSupported(instrumentation)) {
throw new IllegalArgumentException("A prefix for native methods is not supported: " + instrumentation);
}
DISPATCHER.setNativeMethodPrefix(instrumentation, classFileTransformer, prefix);
}
}
}
/**
* A transformation to apply.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class Transformation {
/**
* Indicates that a type should not be ignored.
*/
protected static final byte[] NONE = null;
/**
* The matcher to identify types for transformation.
*/
private final RawMatcher matcher;
/**
* A list of transformers to apply.
*/
private final List<Transformer> transformers;
/**
* {@code true} if this transformation is terminal.
*/
private final boolean terminal;
/**
* Creates a new transformation.
*
* @param matcher The matcher to identify types eligable for transformation.
* @param transformers A list of transformers to apply.
* @param terminal Indicates that this transformation is terminal.
*/
protected Transformation(RawMatcher matcher, List<Transformer> transformers, boolean terminal) {
this.matcher = matcher;
this.transformers = transformers;
this.terminal = terminal;
}
/**
* Returns the matcher to identify types for transformation.
*
* @return The matcher to identify types for transformation.
*/
protected RawMatcher getMatcher() {
return matcher;
}
/**
* Returns a list of transformers to apply.
*
* @return A list of transformers to apply.
*/
protected List<Transformer> getTransformers() {
return transformers;
}
/**
* Returns {@code true} if this transformation is terminal.
*
* @return {@code true} if this transformation is terminal.
*/
protected boolean isTerminal() {
return terminal;
}
/**
* A matcher that matches any type that is touched by a transformer without being ignored.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class SimpleMatcher implements RawMatcher {
/**
* Identifies types that should not be instrumented.
*/
private final RawMatcher ignoreMatcher;
/**
* The transformations to apply on non-ignored types.
*/
private final List<Transformation> transformations;
/**
* Creates a new simple matcher.
*
* @param ignoreMatcher Identifies types that should not be instrumented.
* @param transformations The transformations to apply on non-ignored types.
*/
protected SimpleMatcher(RawMatcher ignoreMatcher, List<Transformation> transformations) {
this.ignoreMatcher = ignoreMatcher;
this.transformations = transformations;
}
/**
* {@inheritDoc}
*/
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
if (ignoreMatcher.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)) {
return false;
}
for (Transformation transformation : transformations) {
if (transformation.getMatcher().matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)) {
return true;
}
}
return false;
}
}
/**
* A matcher that considers the differential of two transformers' transformations.
*/
@HashCodeAndEqualsPlugin.Enhance
protected static class DifferentialMatcher implements RawMatcher {
/**
* Identifies types that should not be instrumented.
*/
private final RawMatcher ignoreMatcher;
/**
* The transformations to apply on non-ignored types.
*/
private final List<Transformation> transformations;
/**
* The class file transformer representing the differential.
*/
private final ResettableClassFileTransformer classFileTransformer;
/**
* Creates a new differential matcher.
*
* @param ignoreMatcher Identifies types that should not be instrumented.
* @param transformations The transformations to apply on non-ignored types.
* @param classFileTransformer The class file transformer representing the differential.
*/
protected DifferentialMatcher(RawMatcher ignoreMatcher,
List<Transformation> transformations,
ResettableClassFileTransformer classFileTransformer) {
this.ignoreMatcher = ignoreMatcher;
this.transformations = transformations;
this.classFileTransformer = classFileTransformer;
}
/**
* {@inheritDoc}
*/
public boolean matches(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
Iterator<Transformer> iterator = classFileTransformer.iterator(typeDescription, classLoader, module, classBeingRedefined, protectionDomain);
if (ignoreMatcher.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)) {
return iterator.hasNext();
}
for (Transformation transformation : transformations) {
if (transformation.getMatcher().matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)) {
for (Transformer transformer : transformation.getTransformers()) {
if (!iterator.hasNext() || !iterator.next().equals(transformer)) {
return true;
}
}
}
}
return iterator.hasNext();
}
}
/**
* An iterator over a list of transformations that match a raw matcher specification.
*/
protected static class TransformerIterator implements Iterator<Transformer> {
/**
* A description of the matched type.
*/
private final TypeDescription typeDescription;
/**
* The type's class loader.
*/
private final ClassLoader classLoader;
/**
* The type's module.
*/
private final JavaModule module;
/**
* The class being redefined or {@code null} if the type was not previously loaded.
*/
private final Class<?> classBeingRedefined;
/**
* The type's protection domain.
*/
private final ProtectionDomain protectionDomain;
/**
* An iterator over the remaining transformations that were not yet considered.
*/
private final Iterator<Transformation> transformations;
/**
* An iterator over the currently matched transformers.
*/
private Iterator<Transformer> transformers;
/**
* Creates a new iterator.
*
* @param typeDescription A description of the matched type.
* @param classLoader The type's class loader.
* @param module The type's module.
* @param classBeingRedefined The class being redefined or {@code null} if the type was not previously loaded.
* @param protectionDomain The type's protection domain.
* @param transformations The matched transformations.
*/
protected TransformerIterator(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
List<Transformation> transformations) {
this.typeDescription = typeDescription;
this.classLoader = classLoader;
this.module = module;
this.classBeingRedefined = classBeingRedefined;
this.protectionDomain = protectionDomain;
this.transformations = transformations.iterator();
transformers = Collections.<Transformer>emptySet().iterator();
while (!transformers.hasNext() && this.transformations.hasNext()) {
Transformation transformation = this.transformations.next();
if (transformation.getMatcher().matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)) {
transformers = transformation.getTransformers().iterator();
}
}
}
/**
* {@inheritDoc}
*/
public boolean hasNext() {
return transformers.hasNext();
}
/**
* {@inheritDoc}
*/
public Transformer next() {
try {
return transformers.next();
} finally {
while (!transformers.hasNext() && transformations.hasNext()) {
Transformation transformation = transformations.next();
if (transformation.getMatcher().matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)) {
transformers = transformation.getTransformers().iterator();
}
}
}
}
/**
* {@inheritDoc}
*/
public void remove() {
throw new UnsupportedOperationException("remove");
}
}
}
/**
* A {@link java.lang.instrument.ClassFileTransformer} that implements the enclosing agent builder's
* configuration.
*/
protected static class ExecutingTransformer extends ResettableClassFileTransformer.AbstractBase {
/**
* A factory for creating a {@link ClassFileTransformer} that supports the features of the current VM.
*/
protected static final Factory FACTORY = AccessController.doPrivileged(Factory.CreationAction.INSTANCE);
/**
* The Byte Buddy instance to be used.
*/
private final ByteBuddy byteBuddy;
/**
* The type locator to use.
*/
private final PoolStrategy poolStrategy;
/**
* The definition handler to use.
*/
private final TypeStrategy typeStrategy;
/**
* The listener to notify on transformations.
*/
private final Listener listener;
/**
* The native method strategy to apply.
*/
private final NativeMethodStrategy nativeMethodStrategy;
/**
* The initialization strategy to use for transformed types.
*/
private final InitializationStrategy initializationStrategy;
/**
* The injection strategy to use.
*/
private final InjectionStrategy injectionStrategy;
/**
* The lambda instrumentation strategy to use.
*/
private final LambdaInstrumentationStrategy lambdaInstrumentationStrategy;
/**
* The description strategy for resolving type descriptions for types.
*/
private final DescriptionStrategy descriptionStrategy;
/**
* The location strategy to use.
*/
private final LocationStrategy locationStrategy;
/**
* The fallback strategy to use.
*/
private final FallbackStrategy fallbackStrategy;
/**
* The class file buffer strategy to use.
*/
private final ClassFileBufferStrategy classFileBufferStrategy;
/**
* The installation listener to notify.
*/
private final InstallationListener installationListener;
/**
* Identifies types that should not be instrumented.
*/
private final RawMatcher ignoreMatcher;
/**
* The transformations to apply on non-ignored types.
*/
private final List<Transformation> transformations;
/**
* A lock that prevents circular class transformations.
*/
private final CircularityLock circularityLock;
/**
* The access control context to use for loading classes.
*/
private final AccessControlContext accessControlContext;
/**
* Creates a new class file transformer.
*
* @param byteBuddy The Byte Buddy instance to be used.
* @param listener The listener to notify on transformations.
* @param poolStrategy The type locator to use.
* @param typeStrategy The definition handler to use.
* @param locationStrategy The location strategy to use.
* @param nativeMethodStrategy The native method strategy to apply.
* @param initializationStrategy The initialization strategy to use for transformed types.
* @param injectionStrategy The injection strategy to use.
* @param lambdaInstrumentationStrategy The lambda instrumentation strategy to use.
* @param descriptionStrategy The description strategy for resolving type descriptions for types.
* @param fallbackStrategy The fallback strategy to use.
* @param installationListener The installation listener to notify.
* @param classFileBufferStrategy The class file buffer strategy to use.
* @param ignoreMatcher Identifies types that should not be instrumented.
* @param transformations The transformations to apply on non-ignored types.
* @param circularityLock The circularity lock to use.
*/
public ExecutingTransformer(ByteBuddy byteBuddy,
Listener listener,
PoolStrategy poolStrategy,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
NativeMethodStrategy nativeMethodStrategy,
InitializationStrategy initializationStrategy,
InjectionStrategy injectionStrategy,
LambdaInstrumentationStrategy lambdaInstrumentationStrategy,
DescriptionStrategy descriptionStrategy,
FallbackStrategy fallbackStrategy,
ClassFileBufferStrategy classFileBufferStrategy,
InstallationListener installationListener,
RawMatcher ignoreMatcher,
List<Transformation> transformations,
CircularityLock circularityLock) {
this.byteBuddy = byteBuddy;
this.typeStrategy = typeStrategy;
this.poolStrategy = poolStrategy;
this.locationStrategy = locationStrategy;
this.listener = listener;
this.nativeMethodStrategy = nativeMethodStrategy;
this.initializationStrategy = initializationStrategy;
this.injectionStrategy = injectionStrategy;
this.lambdaInstrumentationStrategy = lambdaInstrumentationStrategy;
this.descriptionStrategy = descriptionStrategy;
this.fallbackStrategy = fallbackStrategy;
this.classFileBufferStrategy = classFileBufferStrategy;
this.installationListener = installationListener;
this.ignoreMatcher = ignoreMatcher;
this.transformations = transformations;
this.circularityLock = circularityLock;
accessControlContext = AccessController.getContext();
}
/**
* {@inheritDoc}
*/
public byte[] transform(ClassLoader classLoader,
String internalTypeName,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] binaryRepresentation) {
if (circularityLock.acquire()) {
try {
return AccessController.doPrivileged(new LegacyVmDispatcher(classLoader,
internalTypeName,
classBeingRedefined,
protectionDomain,
binaryRepresentation), accessControlContext);
} finally {
circularityLock.release();
}
} else {
return NO_TRANSFORMATION;
}
}
/**
* Applies a transformation for a class that was captured by this {@link ClassFileTransformer}. Invoking this method
* allows to process module information which is available since Java 9.
*
* @param rawModule The instrumented class's Java {@code java.lang.Module}.
* @param classLoader The type's class loader or {@code null} if the type is loaded by the bootstrap loader.
* @param internalTypeName The internal name of the instrumented class.
* @param classBeingRedefined The loaded {@link Class} being redefined or {@code null} if no such class exists.
* @param protectionDomain The instrumented type's protection domain.
* @param binaryRepresentation The class file of the instrumented class in its current state.
* @return The transformed class file or an empty byte array if this transformer does not apply an instrumentation.
*/
protected byte[] transform(Object rawModule,
ClassLoader classLoader,
String internalTypeName,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] binaryRepresentation) {
if (circularityLock.acquire()) {
try {
return AccessController.doPrivileged(new Java9CapableVmDispatcher(rawModule,
classLoader,
internalTypeName,
classBeingRedefined,
protectionDomain,
binaryRepresentation), accessControlContext);
} finally {
circularityLock.release();
}
} else {
return NO_TRANSFORMATION;
}
}
/**
* Applies a transformation for a class that was captured by this {@link ClassFileTransformer}.
*
* @param module The instrumented class's Java module in its wrapped form or {@code null} if the current VM does not support modules.
* @param classLoader The instrumented class's class loader.
* @param internalTypeName The internal name of the instrumented class.
* @param classBeingRedefined The loaded {@link Class} being redefined or {@code null} if no such class exists.
* @param protectionDomain The instrumented type's protection domain.
* @param binaryRepresentation The class file of the instrumented class in its current state.
* @return The transformed class file or an empty byte array if this transformer does not apply an instrumentation.
*/
private byte[] transform(JavaModule module,
ClassLoader classLoader,
String internalTypeName,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] binaryRepresentation) {
if (internalTypeName == null || !lambdaInstrumentationStrategy.isInstrumented(classBeingRedefined)) {
return NO_TRANSFORMATION;
}
String typeName = internalTypeName.replace('/', '.');
try {
listener.onDiscovery(typeName, classLoader, module, classBeingRedefined != null);
ClassFileLocator classFileLocator = new ClassFileLocator.Compound(classFileBufferStrategy.resolve(typeName,
binaryRepresentation,
classLoader,
module,
protectionDomain), locationStrategy.classFileLocator(classLoader, module));
TypePool typePool = poolStrategy.typePool(classFileLocator, classLoader);
try {
return doTransform(module, classLoader, typeName, classBeingRedefined, classBeingRedefined != null, protectionDomain, typePool, classFileLocator);
} catch (Throwable throwable) {
if (classBeingRedefined != null && descriptionStrategy.isLoadedFirst() && fallbackStrategy.isFallback(classBeingRedefined, throwable)) {
return doTransform(module, classLoader, typeName, NO_LOADED_TYPE, Listener.LOADED, protectionDomain, typePool, classFileLocator);
} else {
throw throwable;
}
}
} catch (Throwable throwable) {
listener.onError(typeName, classLoader, module, classBeingRedefined != null, throwable);
return NO_TRANSFORMATION;
} finally {
listener.onComplete(typeName, classLoader, module, classBeingRedefined != null);
}
}
/**
* Applies a transformation for a class that was captured by this {@link ClassFileTransformer}.
*
* @param module The instrumented class's Java module in its wrapped form or {@code null} if the current VM does not support modules.
* @param classLoader The instrumented class's class loader.
* @param typeName The binary name of the instrumented class.
* @param classBeingRedefined The loaded {@link Class} being redefined or {@code null} if no such class exists.
* @param loaded {@code true} if the instrumented type is loaded.
* @param protectionDomain The instrumented type's protection domain.
* @param typePool The type pool to use.
* @param classFileLocator The class file locator to use.
* @return The transformed class file or an empty byte array if this transformer does not apply an instrumentation.
*/
private byte[] doTransform(JavaModule module,
ClassLoader classLoader,
String typeName,
Class<?> classBeingRedefined,
boolean loaded,
ProtectionDomain protectionDomain,
TypePool typePool,
ClassFileLocator classFileLocator) {
TypeDescription typeDescription = descriptionStrategy.apply(typeName, classBeingRedefined, typePool, circularityLock, classLoader, module);
if (ignoreMatcher.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)) {
listener.onIgnored(typeDescription, classLoader, module, loaded);
return Transformation.NONE;
}
List<Transformer> transformers = new ArrayList<Transformer>();
for (Transformation transformation : transformations) {
if (transformation.getMatcher().matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)) {
transformers.addAll(transformation.getTransformers());
if (transformation.isTerminal()) {
break;
}
}
}
if (transformers.isEmpty()) {
listener.onIgnored(typeDescription, classLoader, module, loaded);
return Transformation.NONE;
}
DynamicType.Builder<?> builder = typeStrategy.builder(typeDescription,
byteBuddy,
classFileLocator,
nativeMethodStrategy.resolve(),
classLoader,
module,
protectionDomain);
InitializationStrategy.Dispatcher dispatcher = initializationStrategy.dispatcher();
for (Transformer transformer : transformers) {
builder = transformer.transform(builder, typeDescription, classLoader, module);
}
DynamicType.Unloaded<?> dynamicType = dispatcher.apply(builder).make(TypeResolutionStrategy.Disabled.INSTANCE, typePool);
dispatcher.register(dynamicType, classLoader, protectionDomain, injectionStrategy);
listener.onTransformation(typeDescription, classLoader, module, loaded, dynamicType);
return dynamicType.getBytes();
}
/**
* {@inheritDoc}
*/
public Iterator<Transformer> iterator(TypeDescription typeDescription,
ClassLoader classLoader,
JavaModule module,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain) {
return ignoreMatcher.matches(typeDescription, classLoader, module, classBeingRedefined, protectionDomain)
? Collections.<Transformer>emptySet().iterator()
: new Transformation.TransformerIterator(typeDescription, classLoader, module, classBeingRedefined, protectionDomain, transformations);
}
/**
* {@inheritDoc}
*/
public synchronized boolean reset(Instrumentation instrumentation,
ResettableClassFileTransformer classFileTransformer,
RedefinitionStrategy redefinitionStrategy,
RedefinitionStrategy.DiscoveryStrategy redefinitionDiscoveryStrategy,
RedefinitionStrategy.BatchAllocator redefinitionBatchAllocator,
RedefinitionStrategy.Listener redefinitionListener) {
if (instrumentation.removeTransformer(classFileTransformer)) {
redefinitionStrategy.apply(instrumentation,
Listener.NoOp.INSTANCE,
CircularityLock.Inactive.INSTANCE,
poolStrategy,
locationStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
new Transformation.SimpleMatcher(ignoreMatcher, transformations));
installationListener.onReset(instrumentation, classFileTransformer);
return true;
} else {
return false;
}
}
/* does not implement hashCode and equals in order to align with identity treatment of the JVM */
/**
* A factory for creating a {@link ClassFileTransformer} for the current VM.
*/
protected interface Factory {
/**
* Creates a new class file transformer for the current VM.
*
* @param byteBuddy The Byte Buddy instance to be used.
* @param listener The listener to notify on transformations.
* @param poolStrategy The type locator to use.
* @param typeStrategy The definition handler to use.
* @param locationStrategy The location strategy to use.
* @param nativeMethodStrategy The native method strategy to apply.
* @param initializationStrategy The initialization strategy to use for transformed types.
* @param injectionStrategy The injection strategy to use.
* @param lambdaInstrumentationStrategy The lambda instrumentation strategy to use.
* @param descriptionStrategy The description strategy for resolving type descriptions for types.
* @param fallbackStrategy The fallback strategy to use.
* @param classFileBufferStrategy The class file buffer strategy to use.
* @param installationListener The installation listener to notify.
* @param ignoreMatcher Identifies types that should not be instrumented.
* @param transformations The transformations to apply on non-ignored types.
* @param circularityLock The circularity lock to use.
* @return A class file transformer for the current VM that supports the API of the current VM.
*/
ResettableClassFileTransformer make(ByteBuddy byteBuddy,
Listener listener,
PoolStrategy poolStrategy,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
NativeMethodStrategy nativeMethodStrategy,
InitializationStrategy initializationStrategy,
InjectionStrategy injectionStrategy,
LambdaInstrumentationStrategy lambdaInstrumentationStrategy,
DescriptionStrategy descriptionStrategy,
FallbackStrategy fallbackStrategy,
ClassFileBufferStrategy classFileBufferStrategy,
InstallationListener installationListener,
RawMatcher ignoreMatcher,
List<Transformation> transformations,
CircularityLock circularityLock);
/**
* An action to create an implementation of {@link ExecutingTransformer} that support Java 9 modules.
*/
enum CreationAction implements PrivilegedAction<Factory> {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Exception should not be rethrown but trigger a fallback")
public Factory run() {
try {
return new Factory.ForJava9CapableVm(new ByteBuddy()
.with(TypeValidation.DISABLED)
.subclass(ExecutingTransformer.class)
.name(ExecutingTransformer.class.getName() + "$ByteBuddy$ModuleSupport")
.method(named("transform").and(takesArgument(0, JavaType.MODULE.load())))
.intercept(MethodCall.invoke(ExecutingTransformer.class.getDeclaredMethod("transform",
Object.class,
ClassLoader.class,
String.class,
Class.class,
ProtectionDomain.class,
byte[].class)).onSuper().withAllArguments())
.make()
.load(ExecutingTransformer.class.getClassLoader(),
ClassLoadingStrategy.Default.WRAPPER_PERSISTENT.with(ExecutingTransformer.class.getProtectionDomain()))
.getLoaded()
.getDeclaredConstructor(ByteBuddy.class,
Listener.class,
PoolStrategy.class,
TypeStrategy.class,
LocationStrategy.class,
NativeMethodStrategy.class,
InitializationStrategy.class,
InjectionStrategy.class,
LambdaInstrumentationStrategy.class,
DescriptionStrategy.class,
FallbackStrategy.class,
ClassFileBufferStrategy.class,
InstallationListener.class,
RawMatcher.class,
Transformation.class,
CircularityLock.class));
} catch (Exception ignored) {
return Factory.ForLegacyVm.INSTANCE;
}
}
}
/**
* A factory for a class file transformer on a JVM that supports the {@code java.lang.Module} API to override
* the newly added method of the {@link ClassFileTransformer} to capture an instrumented class's module.
*/
@HashCodeAndEqualsPlugin.Enhance
class ForJava9CapableVm implements Factory {
/**
* A constructor for creating a {@link ClassFileTransformer} that overrides the newly added method for extracting
* the {@code java.lang.Module} of an instrumented class.
*/
private final Constructor<? extends ResettableClassFileTransformer> executingTransformer;
/**
* Creates a class file transformer factory for a Java 9 capable VM.
*
* @param executingTransformer A constructor for creating a {@link ClassFileTransformer} that overrides the newly added
* method for extracting the {@code java.lang.Module} of an instrumented class.
*/
protected ForJava9CapableVm(Constructor<? extends ResettableClassFileTransformer> executingTransformer) {
this.executingTransformer = executingTransformer;
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer make(ByteBuddy byteBuddy,
Listener listener,
PoolStrategy poolStrategy,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
NativeMethodStrategy nativeMethodStrategy,
InitializationStrategy initializationStrategy,
InjectionStrategy injectionStrategy,
LambdaInstrumentationStrategy lambdaInstrumentationStrategy,
DescriptionStrategy descriptionStrategy,
FallbackStrategy fallbackStrategy,
ClassFileBufferStrategy classFileBufferStrategy,
InstallationListener installationListener,
RawMatcher ignoreMatcher,
List<Transformation> transformations,
CircularityLock circularityLock) {
try {
return executingTransformer.newInstance(byteBuddy,
listener,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
initializationStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations,
circularityLock);
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Cannot access " + executingTransformer, exception);
} catch (InstantiationException exception) {
throw new IllegalStateException("Cannot instantiate " + executingTransformer.getDeclaringClass(), exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException("Cannot invoke " + executingTransformer, exception.getCause());
}
}
}
/**
* A factory for a {@link ClassFileTransformer} on a VM that does not support the {@code java.lang.Module} API.
*/
enum ForLegacyVm implements Factory {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer make(ByteBuddy byteBuddy,
Listener listener,
PoolStrategy poolStrategy,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
NativeMethodStrategy nativeMethodStrategy,
InitializationStrategy initializationStrategy,
InjectionStrategy injectionStrategy,
LambdaInstrumentationStrategy lambdaInstrumentationStrategy,
DescriptionStrategy descriptionStrategy,
FallbackStrategy fallbackStrategy,
ClassFileBufferStrategy classFileBufferStrategy,
InstallationListener installationListener,
RawMatcher ignoreMatcher,
List<Transformation> transformations,
CircularityLock circularityLock) {
return new ExecutingTransformer(byteBuddy,
listener,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
initializationStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations,
circularityLock);
}
}
}
/**
* A privileged action for transforming a class on a JVM prior to Java 9.
*/
@HashCodeAndEqualsPlugin.Enhance(includeSyntheticFields = true)
protected class LegacyVmDispatcher implements PrivilegedAction<byte[]> {
/**
* The type's class loader or {@code null} if the bootstrap class loader is represented.
*/
private final ClassLoader classLoader;
/**
* The type's internal name or {@code null} if no such name exists.
*/
private final String internalTypeName;
/**
* The class being redefined or {@code null} if no such class exists.
*/
private final Class<?> classBeingRedefined;
/**
* The type's protection domain.
*/
private final ProtectionDomain protectionDomain;
/**
* The type's binary representation.
*/
private final byte[] binaryRepresentation;
/**
* Creates a new type transformation dispatcher.
*
* @param classLoader The type's class loader or {@code null} if the bootstrap class loader is represented.
* @param internalTypeName The type's internal name or {@code null} if no such name exists.
* @param classBeingRedefined The class being redefined or {@code null} if no such class exists.
* @param protectionDomain The type's protection domain.
* @param binaryRepresentation The type's binary representation.
*/
protected LegacyVmDispatcher(ClassLoader classLoader,
String internalTypeName,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] binaryRepresentation) {
this.classLoader = classLoader;
this.internalTypeName = internalTypeName;
this.classBeingRedefined = classBeingRedefined;
this.protectionDomain = protectionDomain;
this.binaryRepresentation = binaryRepresentation;
}
/**
* {@inheritDoc}
*/
public byte[] run() {
return transform(JavaModule.UNSUPPORTED,
classLoader,
internalTypeName,
classBeingRedefined,
protectionDomain,
binaryRepresentation);
}
}
/**
* A privileged action for transforming a class on a JVM that supports modules.
*/
@HashCodeAndEqualsPlugin.Enhance(includeSyntheticFields = true)
protected class Java9CapableVmDispatcher implements PrivilegedAction<byte[]> {
/**
* The type's {@code java.lang.Module}.
*/
private final Object rawModule;
/**
* The type's class loader or {@code null} if the type is loaded by the bootstrap loader.
*/
private final ClassLoader classLoader;
/**
* The type's internal name or {@code null} if no such name exists.
*/
private final String internalTypeName;
/**
* The class being redefined or {@code null} if no such class exists.
*/
private final Class<?> classBeingRedefined;
/**
* The type's protection domain.
*/
private final ProtectionDomain protectionDomain;
/**
* The type's binary representation.
*/
private final byte[] binaryRepresentation;
/**
* Creates a new legacy dispatcher.
*
* @param rawModule The type's {@code java.lang.Module}.
* @param classLoader The type's class loader or {@code null} if the type is loaded by the bootstrap loader.
* @param internalTypeName The type's internal name or {@code null} if no such name exists.
* @param classBeingRedefined The class being redefined or {@code null} if no such class exists.
* @param protectionDomain The type's protection domain.
* @param binaryRepresentation The type's binary representation.
*/
protected Java9CapableVmDispatcher(Object rawModule,
ClassLoader classLoader,
String internalTypeName,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] binaryRepresentation) {
this.rawModule = rawModule;
this.classLoader = classLoader;
this.internalTypeName = internalTypeName;
this.classBeingRedefined = classBeingRedefined;
this.protectionDomain = protectionDomain;
this.binaryRepresentation = binaryRepresentation;
}
/**
* {@inheritDoc}
*/
public byte[] run() {
return transform(JavaModule.of(rawModule),
classLoader,
internalTypeName,
classBeingRedefined,
protectionDomain,
binaryRepresentation);
}
}
}
/**
* An abstract implementation of an agent builder that delegates all invocation to another instance.
*
* @param <T> The type that is produced by chaining a matcher.
*/
protected abstract class Delegator<T extends Matchable<T>> extends Matchable.AbstractBase<T> implements AgentBuilder {
/**
* Materializes the currently described {@link net.bytebuddy.agent.builder.AgentBuilder}.
*
* @return An agent builder that represents the currently described entry of this instance.
*/
protected abstract AgentBuilder materialize();
/**
* {@inheritDoc}
*/
public AgentBuilder with(ByteBuddy byteBuddy) {
return materialize().with(byteBuddy);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(Listener listener) {
return materialize().with(listener);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(CircularityLock circularityLock) {
return materialize().with(circularityLock);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(TypeStrategy typeStrategy) {
return materialize().with(typeStrategy);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(PoolStrategy poolStrategy) {
return materialize().with(poolStrategy);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(LocationStrategy locationStrategy) {
return materialize().with(locationStrategy);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(InitializationStrategy initializationStrategy) {
return materialize().with(initializationStrategy);
}
/**
* {@inheritDoc}
*/
public RedefinitionListenable.WithoutBatchStrategy with(RedefinitionStrategy redefinitionStrategy) {
return materialize().with(redefinitionStrategy);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(LambdaInstrumentationStrategy lambdaInstrumentationStrategy) {
return materialize().with(lambdaInstrumentationStrategy);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(DescriptionStrategy descriptionStrategy) {
return materialize().with(descriptionStrategy);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(FallbackStrategy fallbackStrategy) {
return materialize().with(fallbackStrategy);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(ClassFileBufferStrategy classFileBufferStrategy) {
return materialize().with(classFileBufferStrategy);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(InstallationListener installationListener) {
return materialize().with(installationListener);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(InjectionStrategy injectionStrategy) {
return materialize().with(injectionStrategy);
}
/**
* {@inheritDoc}
*/
public AgentBuilder with(TransformerDecorator transformerDecorator) {
return materialize().with(transformerDecorator);
}
/**
* {@inheritDoc}
*/
public AgentBuilder enableNativeMethodPrefix(String prefix) {
return materialize().enableNativeMethodPrefix(prefix);
}
/**
* {@inheritDoc}
*/
public AgentBuilder disableNativeMethodPrefix() {
return materialize().disableNativeMethodPrefix();
}
/**
* {@inheritDoc}
*/
public AgentBuilder disableClassFormatChanges() {
return materialize().disableClassFormatChanges();
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Class<?>... type) {
return materialize().assureReadEdgeTo(instrumentation, type);
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, JavaModule... module) {
return materialize().assureReadEdgeTo(instrumentation, module);
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules) {
return materialize().assureReadEdgeTo(instrumentation, modules);
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Class<?>... type) {
return materialize().assureReadEdgeFromAndTo(instrumentation, type);
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, JavaModule... module) {
return materialize().assureReadEdgeFromAndTo(instrumentation, module);
}
/**
* {@inheritDoc}
*/
public AgentBuilder assureReadEdgeFromAndTo(Instrumentation instrumentation, Collection<? extends JavaModule> modules) {
return materialize().assureReadEdgeFromAndTo(instrumentation, modules);
}
/**
* {@inheritDoc}
*/
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher) {
return materialize().type(typeMatcher);
}
/**
* {@inheritDoc}
*/
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher, ElementMatcher<? super ClassLoader> classLoaderMatcher) {
return materialize().type(typeMatcher, classLoaderMatcher);
}
/**
* {@inheritDoc}
*/
public Identified.Narrowable type(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return materialize().type(typeMatcher, classLoaderMatcher, moduleMatcher);
}
/**
* {@inheritDoc}
*/
public Identified.Narrowable type(RawMatcher matcher) {
return materialize().type(matcher);
}
/**
* {@inheritDoc}
*/
public Ignored ignore(ElementMatcher<? super TypeDescription> ignoredTypes) {
return materialize().ignore(ignoredTypes);
}
/**
* {@inheritDoc}
*/
public Ignored ignore(ElementMatcher<? super TypeDescription> ignoredTypes, ElementMatcher<? super ClassLoader> ignoredClassLoaders) {
return materialize().ignore(ignoredTypes, ignoredClassLoaders);
}
/**
* {@inheritDoc}
*/
public Ignored ignore(ElementMatcher<? super TypeDescription> typeMatcher,
ElementMatcher<? super ClassLoader> classLoaderMatcher,
ElementMatcher<? super JavaModule> moduleMatcher) {
return materialize().ignore(typeMatcher, classLoaderMatcher, moduleMatcher);
}
/**
* {@inheritDoc}
*/
public Ignored ignore(RawMatcher rawMatcher) {
return materialize().ignore(rawMatcher);
}
/**
* {@inheritDoc}
*/
public ClassFileTransformer makeRaw() {
return materialize().makeRaw();
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer installOn(Instrumentation instrumentation) {
return materialize().installOn(instrumentation);
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer installOnByteBuddyAgent() {
return materialize().installOnByteBuddyAgent();
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer patchOn(Instrumentation instrumentation, ResettableClassFileTransformer classFileTransformer) {
return materialize().patchOn(instrumentation, classFileTransformer);
}
/**
* {@inheritDoc}
*/
public ResettableClassFileTransformer patchOnByteBuddyAgent(ResettableClassFileTransformer classFileTransformer) {
return materialize().patchOnByteBuddyAgent(classFileTransformer);
}
}
/**
* A delegator transformer for further precising what types to ignore.
*/
@HashCodeAndEqualsPlugin.Enhance(includeSyntheticFields = true)
protected class Ignoring extends Delegator<Ignored> implements Ignored {
/**
* A matcher for identifying types that should not be instrumented.
*/
private final RawMatcher rawMatcher;
/**
* Creates a new agent builder for further specifying what types to ignore.
*
* @param rawMatcher A matcher for identifying types that should not be instrumented.
*/
protected Ignoring(RawMatcher rawMatcher) {
this.rawMatcher = rawMatcher;
}
@Override
protected AgentBuilder materialize() {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
rawMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public Ignored and(RawMatcher rawMatcher) {
return new Ignoring(new RawMatcher.Conjunction(this.rawMatcher, rawMatcher));
}
/**
* {@inheritDoc}
*/
public Ignored or(RawMatcher rawMatcher) {
return new Ignoring(new RawMatcher.Disjunction(this.rawMatcher, rawMatcher));
}
}
/**
* An implementation of a default agent builder that allows for refinement of the redefinition strategy.
*/
protected static class Redefining extends Default implements RedefinitionListenable.WithoutBatchStrategy {
/**
* Creates a new default agent builder that allows for refinement of the redefinition strategy.
*
* @param byteBuddy The Byte Buddy instance to be used.
* @param listener The listener to notify on transformations.
* @param circularityLock The circularity lock to use.
* @param poolStrategy The type locator to use.
* @param typeStrategy The definition handler to use.
* @param locationStrategy The location strategy to use.
* @param nativeMethodStrategy The native method strategy to apply.
* @param transformerDecorator A decorator to wrap the created class file transformer.
* @param initializationStrategy The initialization strategy to use for transformed types.
* @param redefinitionStrategy The redefinition strategy to apply.
* @param redefinitionDiscoveryStrategy The discovery strategy for loaded types to be redefined.
* @param redefinitionBatchAllocator The batch allocator for the redefinition strategy to apply.
* @param redefinitionListener The redefinition listener for the redefinition strategy to apply.
* @param redefinitionResubmissionStrategy The resubmission strategy to apply.
* @param injectionStrategy The injection strategy to use.
* @param lambdaInstrumentationStrategy A strategy to determine of the {@code LambdaMetafactory} should be instrumented to allow for the
* instrumentation of classes that represent lambda expressions.
* @param descriptionStrategy The description strategy for resolving type descriptions for types.
* @param fallbackStrategy The fallback strategy to apply.
* @param classFileBufferStrategy The class file buffer strategy to use.
* @param installationListener The installation listener to notify.
* @param ignoreMatcher Identifies types that should not be instrumented.
* @param transformations The transformations to apply on non-ignored types.
*/
protected Redefining(ByteBuddy byteBuddy,
Listener listener,
CircularityLock circularityLock,
PoolStrategy poolStrategy,
TypeStrategy typeStrategy,
LocationStrategy locationStrategy,
NativeMethodStrategy nativeMethodStrategy,
TransformerDecorator transformerDecorator,
InitializationStrategy initializationStrategy,
RedefinitionStrategy redefinitionStrategy,
RedefinitionStrategy.DiscoveryStrategy redefinitionDiscoveryStrategy,
RedefinitionStrategy.BatchAllocator redefinitionBatchAllocator,
RedefinitionStrategy.Listener redefinitionListener,
RedefinitionStrategy.ResubmissionStrategy redefinitionResubmissionStrategy,
InjectionStrategy injectionStrategy,
LambdaInstrumentationStrategy lambdaInstrumentationStrategy,
DescriptionStrategy descriptionStrategy,
FallbackStrategy fallbackStrategy,
ClassFileBufferStrategy classFileBufferStrategy,
InstallationListener installationListener,
RawMatcher ignoreMatcher,
List<Transformation> transformations) {
super(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public WithImplicitDiscoveryStrategy with(RedefinitionStrategy.BatchAllocator redefinitionBatchAllocator) {
if (!redefinitionStrategy.isEnabled()) {
throw new IllegalStateException("Cannot set redefinition batch allocator when redefinition is disabled");
}
return new Redefining(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public RedefinitionListenable redefineOnly(Class<?>... type) {
return with(new RedefinitionStrategy.DiscoveryStrategy.Explicit(type));
}
/**
* {@inheritDoc}
*/
public RedefinitionListenable with(RedefinitionStrategy.DiscoveryStrategy redefinitionDiscoveryStrategy) {
if (!redefinitionStrategy.isEnabled()) {
throw new IllegalStateException("Cannot set redefinition discovery strategy when redefinition is disabled");
}
return new Redefining(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public RedefinitionListenable with(RedefinitionStrategy.Listener redefinitionListener) {
if (!redefinitionStrategy.isEnabled()) {
throw new IllegalStateException("Cannot set redefinition listener when redefinition is disabled");
}
return new Redefining(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
new RedefinitionStrategy.Listener.Compound(this.redefinitionListener, redefinitionListener),
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
/**
* {@inheritDoc}
*/
public AgentBuilder withResubmission(RedefinitionStrategy.ResubmissionScheduler resubmissionScheduler) {
return withResubmission(resubmissionScheduler, any());
}
/**
* {@inheritDoc}
*/
public AgentBuilder withResubmission(RedefinitionStrategy.ResubmissionScheduler resubmissionScheduler, ElementMatcher<? super Throwable> matcher) {
if (!redefinitionStrategy.isEnabled()) {
throw new IllegalStateException("Cannot enable redefinition resubmission when redefinition is disabled");
}
return new Redefining(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
new RedefinitionStrategy.ResubmissionStrategy.Enabled(resubmissionScheduler, matcher),
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
transformations);
}
}
/**
* A helper class that describes a {@link net.bytebuddy.agent.builder.AgentBuilder.Default} after supplying
* a {@link net.bytebuddy.agent.builder.AgentBuilder.RawMatcher} such that one or several
* {@link net.bytebuddy.agent.builder.AgentBuilder.Transformer}s can be supplied.
*/
@HashCodeAndEqualsPlugin.Enhance(includeSyntheticFields = true)
protected class Transforming extends Delegator<Identified.Narrowable> implements Identified.Extendable, Identified.Narrowable {
/**
* The supplied raw matcher.
*/
private final RawMatcher rawMatcher;
/**
* The supplied transformer.
*/
private final List<Transformer> transformers;
/**
* {@code true} if this transformer is a terminal transformation.
*/
private final boolean terminal;
/**
* Creates a new matched default agent builder.
*
* @param rawMatcher The supplied raw matcher.
* @param transformers The transformers to apply.
* @param terminal {@code true} if this transformer is a terminal transformation.
*/
protected Transforming(RawMatcher rawMatcher, List<Transformer> transformers, boolean terminal) {
this.rawMatcher = rawMatcher;
this.transformers = transformers;
this.terminal = terminal;
}
@Override
protected AgentBuilder materialize() {
return new Default(byteBuddy,
listener,
circularityLock,
poolStrategy,
typeStrategy,
locationStrategy,
nativeMethodStrategy,
transformerDecorator,
initializationStrategy,
redefinitionStrategy,
redefinitionDiscoveryStrategy,
redefinitionBatchAllocator,
redefinitionListener,
redefinitionResubmissionStrategy,
injectionStrategy,
lambdaInstrumentationStrategy,
descriptionStrategy,
fallbackStrategy,
classFileBufferStrategy,
installationListener,
ignoreMatcher,
CompoundList.of(transformations, new Transformation(rawMatcher, transformers, terminal)));
}
/**
* {@inheritDoc}
*/
public Identified.Extendable transform(Transformer transformer) {
return new Transforming(rawMatcher, CompoundList.of(this.transformers, transformer), terminal);
}
/**
* {@inheritDoc}
*/
public AgentBuilder asTerminalTransformation() {
return new Transforming(rawMatcher, transformers, true);
}
/**
* {@inheritDoc}
*/
public Narrowable and(RawMatcher rawMatcher) {
return new Transforming(new RawMatcher.Conjunction(this.rawMatcher, rawMatcher), transformers, terminal);
}
/**
* {@inheritDoc}
*/
public Narrowable or(RawMatcher rawMatcher) {
return new Transforming(new RawMatcher.Disjunction(this.rawMatcher, rawMatcher), transformers, terminal);
}
}
}
}
| Fixes transformer factory.
| byte-buddy-dep/src/main/java/net/bytebuddy/agent/builder/AgentBuilder.java | Fixes transformer factory. | <ide><path>yte-buddy-dep/src/main/java/net/bytebuddy/agent/builder/AgentBuilder.java
<ide> ClassFileBufferStrategy.class,
<ide> InstallationListener.class,
<ide> RawMatcher.class,
<del> Transformation.class,
<add> List.class,
<ide> CircularityLock.class));
<ide> } catch (Exception ignored) {
<ide> return Factory.ForLegacyVm.INSTANCE; |
|
Java | apache-2.0 | c5e8456ef84ec311b5eaee325f4bfcae42322e70 | 0 | ox-it/wl-oauth | package uk.ac.ox.oucs.oauth.tool.user.pages;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.ExternalLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.sakaiproject.tool.api.SessionManager;
import uk.ac.ox.oucs.oauth.domain.Accessor;
import uk.ac.ox.oucs.oauth.domain.Consumer;
import uk.ac.ox.oucs.oauth.exception.InvalidConsumerException;
import uk.ac.ox.oucs.oauth.service.OAuthService;
import uk.ac.ox.oucs.oauth.tool.pages.SakaiPage;
import java.util.ArrayList;
import java.util.Collection;
/**
* @author Colin Hebert
*/
public class ListAccessors extends SakaiPage {
@SpringBean
private SessionManager sessionManager;
@SpringBean
private OAuthService oAuthService;
public ListAccessors() {
String userId = sessionManager.getCurrentSessionUserId();
Collection<Accessor> accessors = oAuthService.getAccessAccessorForUser(userId);
ListView<Accessor> accessorList = new ListView<Accessor>("accessorlist", new ArrayList<Accessor>(accessors)) {
@Override
protected void populateItem(ListItem<Accessor> components) {
try {
final Consumer consumer = oAuthService.getConsumer(components.getModelObject().getConsumerId());
ExternalLink consumerHomepage = new ExternalLink("consumerUrl", consumer.getURL(), consumer.getName());
consumerHomepage.add(new SimpleAttributeModifier("target", "_parent"));
consumerHomepage.setEnabled(consumer.getURL() != null && !consumer.getURL().isEmpty());
components.add(consumerHomepage);
components.add(new Label("consumerDescription", consumer.getDescription()));
components.add(new Label("creationDate", new StringResourceModel("creation.date", null,
new Object[]{components.getModelObject().getCreationDate()})));
components.add(new Label("expirationDate", new StringResourceModel("expiration.date", null, new Object[]{components.getModelObject().getExpirationDate()})));
components.add(new Link<Accessor>("delete", components.getModel()) {
@Override
public void onClick() {
try {
oAuthService.revokeAccessor(getModelObject().getToken());
setResponsePage(getPage().getClass());
getSession().info(consumer.getName() + "' token has been removed.");
} catch (Exception e) {
warn("Couldn't remove '" + consumer.getName() + "'s token': " + e.getLocalizedMessage());
}
}
});
} catch (InvalidConsumerException invalidConsumerException) {
//Invalid consumer, it is probably deleted
//For security reasons, this token should be revoked
oAuthService.revokeAccessor(components.getModelObject().getToken());
components.setVisible(false);
}
}
@Override
public boolean isVisible() {
return !getModelObject().isEmpty() && super.isVisible();
}
};
add(accessorList);
Label noAccessorLabel = new Label("noAccessor", new ResourceModel("no.accessor"));
noAccessorLabel.setVisible(!accessorList.isVisible());
add(noAccessorLabel);
}
}
| tool/src/main/java/uk/ac/ox/oucs/oauth/tool/user/pages/ListAccessors.java | package uk.ac.ox.oucs.oauth.tool.user.pages;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.ExternalLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.sakaiproject.tool.api.SessionManager;
import uk.ac.ox.oucs.oauth.domain.Accessor;
import uk.ac.ox.oucs.oauth.domain.Consumer;
import uk.ac.ox.oucs.oauth.exception.InvalidConsumerException;
import uk.ac.ox.oucs.oauth.service.OAuthService;
import uk.ac.ox.oucs.oauth.tool.pages.SakaiPage;
import java.util.ArrayList;
import java.util.Collection;
/**
* @author Colin Hebert
*/
public class ListAccessors extends SakaiPage {
@SpringBean
private SessionManager sessionManager;
@SpringBean
private OAuthService oAuthService;
public ListAccessors() {
String userId = sessionManager.getCurrentSessionUserId();
Collection<Accessor> accessors = oAuthService.getAccessAccessorForUser(userId);
ListView<Accessor> accessorList = new ListView<Accessor>("accessorlist", new ArrayList<Accessor>(accessors)) {
@Override
protected void populateItem(ListItem<Accessor> components) {
try {
final Consumer consumer = oAuthService.getConsumer(components.getModelObject().getConsumerId());
ExternalLink consumerHomepage = new ExternalLink("consumerUrl", consumer.getURL(), consumer.getName());
consumerHomepage.setEnabled(consumer.getURL() != null && !consumer.getURL().isEmpty());
components.add(consumerHomepage);
components.add(new Label("consumerDescription", consumer.getDescription()));
components.add(new Label("creationDate", new StringResourceModel("creation.date", null,
new Object[]{components.getModelObject().getCreationDate()})));
components.add(new Label("expirationDate", new StringResourceModel("expiration.date", null, new Object[]{components.getModelObject().getExpirationDate()})));
components.add(new Link<Accessor>("delete", components.getModel()) {
@Override
public void onClick() {
try {
oAuthService.revokeAccessor(getModelObject().getToken());
setResponsePage(getPage().getClass());
getSession().info(consumer.getName() + "' token has been removed.");
} catch (Exception e) {
warn("Couldn't remove '" + consumer.getName() + "'s token': " + e.getLocalizedMessage());
}
}
});
} catch (InvalidConsumerException invalidConsumerException) {
//Invalid consumer, it is probably deleted
//For security reasons, this token should be revoked
oAuthService.revokeAccessor(components.getModelObject().getToken());
components.setVisible(false);
}
}
@Override
public boolean isVisible() {
return !getModelObject().isEmpty() && super.isVisible();
}
};
add(accessorList);
Label noAccessorLabel = new Label("noAccessor", new ResourceModel("no.accessor"));
noAccessorLabel.setVisible(!accessorList.isVisible());
add(noAccessorLabel);
}
}
| Open external links in the main frame
| tool/src/main/java/uk/ac/ox/oucs/oauth/tool/user/pages/ListAccessors.java | Open external links in the main frame | <ide><path>ool/src/main/java/uk/ac/ox/oucs/oauth/tool/user/pages/ListAccessors.java
<ide> package uk.ac.ox.oucs.oauth.tool.user.pages;
<ide>
<add>import org.apache.wicket.behavior.SimpleAttributeModifier;
<ide> import org.apache.wicket.markup.html.basic.Label;
<ide> import org.apache.wicket.markup.html.link.ExternalLink;
<ide> import org.apache.wicket.markup.html.link.Link;
<ide> try {
<ide> final Consumer consumer = oAuthService.getConsumer(components.getModelObject().getConsumerId());
<ide> ExternalLink consumerHomepage = new ExternalLink("consumerUrl", consumer.getURL(), consumer.getName());
<add> consumerHomepage.add(new SimpleAttributeModifier("target", "_parent"));
<ide> consumerHomepage.setEnabled(consumer.getURL() != null && !consumer.getURL().isEmpty());
<ide> components.add(consumerHomepage);
<ide> components.add(new Label("consumerDescription", consumer.getDescription())); |
|
Java | apache-2.0 | 18f0e0e8700b4ca39df85d40b07b77e770ce66fe | 0 | mtransitapps/mtransit-for-android,mtransitapps/mtransit-for-android,mtransitapps/mtransit-for-android | package org.mtransit.android.ui.fragment;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Locale;
import org.mtransit.android.R;
import org.mtransit.android.commons.BundleUtils;
import org.mtransit.android.commons.MTLog;
import org.mtransit.android.commons.PreferenceUtils;
import org.mtransit.android.commons.StringUtils;
import org.mtransit.android.commons.task.MTAsyncTask;
import org.mtransit.android.data.AgencyProperties;
import org.mtransit.android.data.DataSourceProvider;
import org.mtransit.android.data.DataSourceType;
import org.mtransit.android.task.StatusLoader;
import org.mtransit.android.ui.MTActivityWithLocation;
import org.mtransit.android.ui.MainActivity;
import org.mtransit.android.ui.view.SlidingTabLayout;
import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
public class AgencyTypeFragment extends ABFragment implements ViewPager.OnPageChangeListener, MTActivityWithLocation.UserLocationListener {
private static final String TAG = AgencyTypeFragment.class.getSimpleName();
@Override
public String getLogTag() {
return TAG + "-" + this.type;
}
private static final String EXTRA_TYPE_ID = "extra_type_id";
public static AgencyTypeFragment newInstance(DataSourceType type) {
AgencyTypeFragment f = new AgencyTypeFragment();
Bundle args = new Bundle();
args.putInt(EXTRA_TYPE_ID, type.getId());
f.setArguments(args);
return f;
}
private DataSourceType type;
private Location userLocation;
private AgencyPagerAdapter adapter;
private int lastPageSelected = -1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
final View view = inflater.inflate(R.layout.fragment_agency_type, container, false);
setupView(view);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
restoreInstanceState(savedInstanceState);
if (this.adapter == null) {
initTabsAndViewPager();
}
switchView(getView());
}
@Override
public void onDestroy() {
super.onDestroy();
this.adapter = null;
}
private void setupView(View view) {
if (view == null || this.adapter == null) {
return;
}
final ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPager.setAdapter(this.adapter);
viewPager.setOffscreenPageLimit(3);
final SlidingTabLayout tabs = (SlidingTabLayout) view.findViewById(R.id.tabs);
tabs.setViewPager(viewPager);
tabs.setOnPageChangeListener(this);
tabs.setSelectedIndicatorColors(0xff666666);
}
private void restoreInstanceState(Bundle savedInstanceState) {
Integer typeId = BundleUtils.getInt(EXTRA_TYPE_ID, savedInstanceState, getArguments());
if (typeId != null) {
this.type = DataSourceType.parseId(typeId);
((MainActivity) getActivity()).notifyABChange();
}
}
private void initTabsAndViewPager() {
final List<AgencyProperties> availableAgencies = this.type == null ? null : DataSourceProvider.get().getTypeDataSources(getActivity(), this.type);
if (availableAgencies == null) {
return;
}
this.adapter = new AgencyPagerAdapter(this, availableAgencies);
final View view = getView();
setupView(view);
final ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
this.lastPageSelected = 0;
new MTAsyncTask<Void, Void, Integer>() {
private final String TAG = AgencyTypeFragment.class.getSimpleName() + ">LoadLastPageSelectedFromUserPreferences";
public String getLogTag() {
return TAG;
}
@Override
protected Integer doInBackgroundMT(Void... params) {
try {
final String agencyAuthority = PreferenceUtils.getPrefLcl(getActivity(),
PreferenceUtils.getPREFS_LCL_AGENCY_TYPE_TAB_AGENCY(AgencyTypeFragment.this.type.getId()),
PreferenceUtils.PREFS_LCL_AGENCY_TYPE_TAB_AGENCY_DEFAULT);
for (int i = 0; i < availableAgencies.size(); i++) {
if (availableAgencies.get(i).getAuthority().equals(agencyAuthority)) {
return i;
}
}
} catch (Exception e) {
MTLog.w(TAG, e, "Error while determining the select agency tab!");
}
return null;
}
@Override
protected void onPostExecute(Integer lastPageSelected) {
if (AgencyTypeFragment.this.lastPageSelected != 0) {
return; // user has manually move to another page before, too late
}
if (lastPageSelected != null) {
AgencyTypeFragment.this.lastPageSelected = lastPageSelected.intValue();
viewPager.setCurrentItem(AgencyTypeFragment.this.lastPageSelected);
}
switchView(view);
onPageSelected(AgencyTypeFragment.this.lastPageSelected); // tell current page it's selected
}
}.execute();
}
@Override
public void onUserLocationChanged(Location newLocation) {
if (newLocation != null) {
this.userLocation = newLocation;
final List<Fragment> fragments = getChildFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
if (fragment != null && fragment instanceof MTActivityWithLocation.UserLocationListener) {
((MTActivityWithLocation.UserLocationListener) fragment).onUserLocationChanged(this.userLocation);
}
}
}
if (this.adapter != null) {
this.adapter.setUserLocation(newLocation);
}
}
}
private void switchView(View view) {
if (this.adapter == null) {
showLoading(view);
} else if (this.adapter.getCount() > 0) {
showTabsAndViewPager(view);
} else {
showEmpty(view);
}
}
private void showTabsAndViewPager(View view) {
if (view.findViewById(R.id.loading) != null) { // IF inflated/present DO
view.findViewById(R.id.loading).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.empty) != null) { // IF inflated/present DO
view.findViewById(R.id.empty).setVisibility(View.GONE); // hide
}
view.findViewById(R.id.tabs).setVisibility(View.VISIBLE); // show
view.findViewById(R.id.viewpager).setVisibility(View.VISIBLE); // show
}
private void showLoading(View view) {
if (view.findViewById(R.id.tabs) != null) { // IF inflated/present DO
view.findViewById(R.id.tabs).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.viewpager) != null) { // IF inflated/present DO
view.findViewById(R.id.viewpager).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.empty) != null) { // IF inflated/present DO
view.findViewById(R.id.empty).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.loading) == null) { // IF NOT present/inflated DO
((ViewStub) view.findViewById(R.id.loading_stub)).inflate(); // inflate
}
view.findViewById(R.id.loading).setVisibility(View.VISIBLE); // show
}
private void showEmpty(View view) {
if (view.findViewById(R.id.tabs) != null) { // IF inflated/present DO
view.findViewById(R.id.tabs).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.viewpager) != null) { // IF inflated/present DO
view.findViewById(R.id.viewpager).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.loading) != null) { // IF inflated/present DO
view.findViewById(R.id.loading).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.empty) == null) { // IF NOT present/inflated DO
((ViewStub) view.findViewById(R.id.empty_stub)).inflate(); // inflate
}
view.findViewById(R.id.empty).setVisibility(View.VISIBLE); // show
}
@Override
public void onPageSelected(int position) {
StatusLoader.get().clearAllTasks();
if (this.adapter != null) {
PreferenceUtils.savePrefLcl(getActivity(), PreferenceUtils.getPREFS_LCL_AGENCY_TYPE_TAB_AGENCY(this.type.getId()), this.adapter.getAgency(position)
.getAuthority(), false);
}
final List<Fragment> fragments = getChildFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
if (fragment instanceof VisibilityAwareFragment) {
final VisibilityAwareFragment visibilityAwareFragment = (VisibilityAwareFragment) fragment;
visibilityAwareFragment.setFragmentVisisbleAtPosition(position);
}
}
}
this.lastPageSelected = position;
if (this.adapter != null) {
this.adapter.setLastVisisbleFragmentPosition(this.lastPageSelected);
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageScrollStateChanged(int state) {
switch (state) {
case ViewPager.SCROLL_STATE_IDLE:
List<Fragment> fragments = getChildFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
if (fragment instanceof VisibilityAwareFragment) {
final VisibilityAwareFragment visibilityAwareFragment = (VisibilityAwareFragment) fragment;
visibilityAwareFragment.setFragmentVisisbleAtPosition(this.lastPageSelected); // resume
}
}
}
break;
case ViewPager.SCROLL_STATE_DRAGGING:
List<Fragment> fragments2 = getChildFragmentManager().getFragments();
if (fragments2 != null) {
for (Fragment fragment : fragments2) {
if (fragment instanceof VisibilityAwareFragment) {
final VisibilityAwareFragment visibilityAwareFragment = (VisibilityAwareFragment) fragment;
visibilityAwareFragment.setFragmentVisisbleAtPosition(-1); // pause
}
}
}
break;
}
}
@Override
public CharSequence getABTitle(Context context) {
if (this.type == null) {
return context.getString(R.string.ellipsis);
}
return context.getString(this.type.getShortNameResId()).toUpperCase(Locale.ENGLISH);
}
private static class AgencyPagerAdapter extends FragmentStatePagerAdapter {
private List<AgencyProperties> agencies;
private WeakReference<Context> contextWR;
private Location userLocation;
private int lastVisisbleFragmentPosition = -1;
public AgencyPagerAdapter(AgencyTypeFragment agencyTypeFragment, List<AgencyProperties> agencies) {
super(agencyTypeFragment.getChildFragmentManager());
this.contextWR = new WeakReference<Context>(agencyTypeFragment.getActivity());
this.agencies = agencies;
}
public AgencyProperties getAgency(int position) {
return this.agencies.size() == 0 ? null : this.agencies.get(position);
}
public void setUserLocation(Location userLocation) {
this.userLocation = userLocation;
}
public void setLastVisisbleFragmentPosition(int lastVisisbleFragmentPosition) {
this.lastVisisbleFragmentPosition = lastVisisbleFragmentPosition;
}
@Override
public int getCount() {
return this.agencies == null ? 0 : this.agencies.size();
}
@Override
public CharSequence getPageTitle(int position) {
final Context context = this.contextWR == null ? null : this.contextWR.get();
if (context == null) {
return StringUtils.EMPTY;
}
if (this.agencies == null || position >= this.agencies.size()) {
return StringUtils.EMPTY;
}
return this.agencies.get(position).getShortName();
}
@Override
public Fragment getItem(int position) {
final AgencyProperties agency = getAgency(position);
if (agency.isRTS()) {
final RTSAgencyRoutesFragment f = RTSAgencyRoutesFragment.newInstance(position, this.lastVisisbleFragmentPosition, agency);
f.setLogTag(agency.getShortName());
return f;
}
return AgencyPOIsFragment.newInstance(position, this.lastVisisbleFragmentPosition, agency, this.userLocation);
}
}
}
| src/org/mtransit/android/ui/fragment/AgencyTypeFragment.java | package org.mtransit.android.ui.fragment;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Locale;
import org.mtransit.android.R;
import org.mtransit.android.commons.BundleUtils;
import org.mtransit.android.commons.MTLog;
import org.mtransit.android.commons.PreferenceUtils;
import org.mtransit.android.commons.StringUtils;
import org.mtransit.android.commons.task.MTAsyncTask;
import org.mtransit.android.data.AgencyProperties;
import org.mtransit.android.data.DataSourceProvider;
import org.mtransit.android.data.DataSourceType;
import org.mtransit.android.task.StatusLoader;
import org.mtransit.android.ui.MTActivityWithLocation;
import org.mtransit.android.ui.MainActivity;
import org.mtransit.android.ui.view.SlidingTabLayout;
import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
public class AgencyTypeFragment extends ABFragment implements ViewPager.OnPageChangeListener, MTActivityWithLocation.UserLocationListener {
private static final String TAG = AgencyTypeFragment.class.getSimpleName();
@Override
public String getLogTag() {
return TAG + "-" + this.type;
}
private static final String EXTRA_TYPE_ID = "extra_type_id";
public static AgencyTypeFragment newInstance(DataSourceType type) {
AgencyTypeFragment f = new AgencyTypeFragment();
Bundle args = new Bundle();
args.putInt(EXTRA_TYPE_ID, type.getId());
f.setArguments(args);
return f;
}
private DataSourceType type;
private Location userLocation;
private AgencyPagerAdapter adapter;
private int lastPageSelected = -1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
final View view = inflater.inflate(R.layout.fragment_agency_type, container, false);
setupView(view);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
restoreInstanceState(savedInstanceState);
if (this.adapter == null) {
initTabsAndViewPager();
}
switchView(getView());
}
@Override
public void onDestroy() {
super.onDestroy();
this.adapter = null;
}
private void setupView(View view) {
if (view == null || this.adapter == null) {
return;
}
final ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPager.setAdapter(this.adapter);
viewPager.setOffscreenPageLimit(3);
final SlidingTabLayout tabs = (SlidingTabLayout) view.findViewById(R.id.tabs);
tabs.setViewPager(viewPager);
tabs.setOnPageChangeListener(this);
tabs.setSelectedIndicatorColors(0xff666666);
}
private void restoreInstanceState(Bundle savedInstanceState) {
Integer typeId = BundleUtils.getInt(EXTRA_TYPE_ID, savedInstanceState, getArguments());
if (typeId != null) {
this.type = DataSourceType.parseId(typeId);
((MainActivity) getActivity()).notifyABChange();
}
}
private void initTabsAndViewPager() {
final List<AgencyProperties> availableAgencies = this.type == null ? null : DataSourceProvider.get().getTypeDataSources(getActivity(), this.type);
if (availableAgencies == null) {
return;
}
this.adapter = new AgencyPagerAdapter(this, availableAgencies);
final View view = getView();
setupView(view);
final ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
this.lastPageSelected = 0;
new MTAsyncTask<Void, Void, Integer>() {
private final String TAG = AgencyTypeFragment.class.getSimpleName() + ">LoadLastPageSelectedFromUserPreferences";
public String getLogTag() {
return TAG;
}
@Override
protected Integer doInBackgroundMT(Void... params) {
try {
final String agencyAuthority = PreferenceUtils.getPrefLcl(getActivity(),
PreferenceUtils.getPREFS_LCL_AGENCY_TYPE_TAB_AGENCY(AgencyTypeFragment.this.type.getId()),
PreferenceUtils.PREFS_LCL_AGENCY_TYPE_TAB_AGENCY_DEFAULT);
for (int i = 0; i < availableAgencies.size(); i++) {
if (availableAgencies.get(i).getAuthority().equals(agencyAuthority)) {
return i;
}
}
} catch (Exception e) {
MTLog.w(TAG, e, "Error while determining the select agency tab!");
}
return null;
}
@Override
protected void onPostExecute(Integer lastPageSelected) {
if (AgencyTypeFragment.this.lastPageSelected != 0) {
return; // user has manually move to another page before, too late
}
if (lastPageSelected != null) {
AgencyTypeFragment.this.lastPageSelected = lastPageSelected.intValue();
viewPager.setCurrentItem(AgencyTypeFragment.this.lastPageSelected);
}
switchView(view);
onPageSelected(AgencyTypeFragment.this.lastPageSelected); // tell current page it's selected
}
}.execute();
}
@Override
public void onUserLocationChanged(Location newLocation) {
if (newLocation != null) {
this.userLocation = newLocation;
final List<Fragment> fragments = getChildFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
if (fragment != null && fragment instanceof MTActivityWithLocation.UserLocationListener) {
((MTActivityWithLocation.UserLocationListener) fragment).onUserLocationChanged(this.userLocation);
}
}
}
if (this.adapter != null) {
this.adapter.setUserLocation(newLocation);
}
}
}
private void switchView(View view) {
if (this.adapter == null) {
showLoading(view);
} else if (this.adapter.getCount() > 0) {
showTabsAndViewPager(view);
} else {
showEmpty(view);
}
}
private void showTabsAndViewPager(View view) {
if (view.findViewById(R.id.loading) != null) { // IF inflated/present DO
view.findViewById(R.id.loading).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.empty) != null) { // IF inflated/present DO
view.findViewById(R.id.empty).setVisibility(View.GONE); // hide
}
view.findViewById(R.id.tabs).setVisibility(View.VISIBLE); // show
view.findViewById(R.id.viewpager).setVisibility(View.VISIBLE); // show
}
private void showLoading(View view) {
if (view.findViewById(R.id.tabs) != null) { // IF inflated/present DO
view.findViewById(R.id.tabs).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.viewpager) != null) { // IF inflated/present DO
view.findViewById(R.id.viewpager).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.empty) != null) { // IF inflated/present DO
view.findViewById(R.id.empty).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.loading) == null) { // IF NOT present/inflated DO
((ViewStub) view.findViewById(R.id.loading_stub)).inflate(); // inflate
}
view.findViewById(R.id.loading).setVisibility(View.VISIBLE); // show
}
private void showEmpty(View view) {
if (view.findViewById(R.id.tabs) != null) { // IF inflated/present DO
view.findViewById(R.id.tabs).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.viewpager) != null) { // IF inflated/present DO
view.findViewById(R.id.viewpager).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.loading) != null) { // IF inflated/present DO
view.findViewById(R.id.loading).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.empty) == null) { // IF NOT present/inflated DO
((ViewStub) view.findViewById(R.id.empty_stub)).inflate(); // inflate
}
view.findViewById(R.id.empty).setVisibility(View.VISIBLE); // show
}
@Override
public void onPageSelected(int position) {
StatusLoader.get().clearAllTasks();
if (this.adapter != null) {
PreferenceUtils.savePrefLcl(getActivity(), PreferenceUtils.getPREFS_LCL_AGENCY_TYPE_TAB_AGENCY(this.type.getId()), this.adapter.getAgency(position)
.getAuthority(), false);
}
final List<Fragment> fragments = getChildFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
if (fragment instanceof VisibilityAwareFragment) {
final VisibilityAwareFragment visibilityAwareFragment = (VisibilityAwareFragment) fragment;
visibilityAwareFragment.setFragmentVisisbleAtPosition(position);
}
}
}
this.lastPageSelected = position;
if (this.adapter != null) {
this.adapter.setLastVisisbleFragmentPosition(this.lastPageSelected);
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageScrollStateChanged(int state) {
switch (state) {
case ViewPager.SCROLL_STATE_IDLE:
List<Fragment> fragments = getChildFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
if (fragment instanceof VisibilityAwareFragment) {
final VisibilityAwareFragment visibilityAwareFragment = (VisibilityAwareFragment) fragment;
visibilityAwareFragment.setFragmentVisisbleAtPosition(this.lastPageSelected); // resume
}
}
}
break;
case ViewPager.SCROLL_STATE_DRAGGING:
List<Fragment> fragments2 = getChildFragmentManager().getFragments();
if (fragments2 != null) {
for (Fragment fragment : fragments2) {
if (fragment instanceof VisibilityAwareFragment) {
final VisibilityAwareFragment visibilityAwareFragment = (VisibilityAwareFragment) fragment;
visibilityAwareFragment.setFragmentVisisbleAtPosition(-1); // pause
}
}
}
break;
}
}
@Override
public CharSequence getABTitle(Context context) {
if (this.type == null) {
return context.getString(R.string.ellipsis);
}
return context.getString(this.type.getShortNameResId()).toUpperCase(Locale.ENGLISH);
}
@Override
public int getABIconDrawableResId() {
if (this.type != null && this.type.getMenuResId() != -1) {
return this.type.getMenuResId();
}
return super.getABIconDrawableResId();
}
private static class AgencyPagerAdapter extends FragmentStatePagerAdapter {
private List<AgencyProperties> agencies;
private WeakReference<Context> contextWR;
private Location userLocation;
private int lastVisisbleFragmentPosition = -1;
public AgencyPagerAdapter(AgencyTypeFragment agencyTypeFragment, List<AgencyProperties> agencies) {
super(agencyTypeFragment.getChildFragmentManager());
this.contextWR = new WeakReference<Context>(agencyTypeFragment.getActivity());
this.agencies = agencies;
}
public AgencyProperties getAgency(int position) {
return this.agencies.size() == 0 ? null : this.agencies.get(position);
}
public void setUserLocation(Location userLocation) {
this.userLocation = userLocation;
}
public void setLastVisisbleFragmentPosition(int lastVisisbleFragmentPosition) {
this.lastVisisbleFragmentPosition = lastVisisbleFragmentPosition;
}
@Override
public int getCount() {
return this.agencies == null ? 0 : this.agencies.size();
}
@Override
public CharSequence getPageTitle(int position) {
final Context context = this.contextWR == null ? null : this.contextWR.get();
if (context == null) {
return StringUtils.EMPTY;
}
if (this.agencies == null || position >= this.agencies.size()) {
return StringUtils.EMPTY;
}
return this.agencies.get(position).getShortName();
}
@Override
public Fragment getItem(int position) {
final AgencyProperties agency = getAgency(position);
if (agency.isRTS()) {
final RTSAgencyRoutesFragment f = RTSAgencyRoutesFragment.newInstance(position, this.lastVisisbleFragmentPosition, agency);
f.setLogTag(agency.getShortName());
return f;
}
return AgencyPOIsFragment.newInstance(position, this.lastVisisbleFragmentPosition, agency, this.userLocation);
}
}
}
| Code cleaning.
| src/org/mtransit/android/ui/fragment/AgencyTypeFragment.java | Code cleaning. | <ide><path>rc/org/mtransit/android/ui/fragment/AgencyTypeFragment.java
<ide> }
<ide>
<ide>
<del> @Override
<del> public int getABIconDrawableResId() {
<del> if (this.type != null && this.type.getMenuResId() != -1) {
<del> return this.type.getMenuResId();
<del> }
<del> return super.getABIconDrawableResId();
<del> }
<del>
<del>
<ide> private static class AgencyPagerAdapter extends FragmentStatePagerAdapter {
<ide>
<ide> private List<AgencyProperties> agencies; |
|
Java | apache-2.0 | 7c07ffb882454b6fe584f9fa3f426c2863529d49 | 0 | lime-company/lime-security-powerauth,lime-company/lime-security-powerauth | /*
* PowerAuth Crypto Library
* Copyright 2018 Wultra 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 io.getlime.security.powerauth.crypto.lib.generator;
import com.google.common.io.BaseEncoding;
import io.getlime.security.powerauth.crypto.lib.config.PowerAuthConfiguration;
import io.getlime.security.powerauth.crypto.lib.encryptor.ecies.kdf.KdfX9_63;
import io.getlime.security.powerauth.crypto.lib.model.RecoveryInfo;
import io.getlime.security.powerauth.crypto.lib.model.RecoverySeed;
import io.getlime.security.powerauth.crypto.lib.model.exception.GenericCryptoException;
import io.getlime.security.powerauth.crypto.lib.util.CRC16;
import io.getlime.security.powerauth.provider.exception.CryptoProviderException;
import javax.crypto.SecretKey;
import java.nio.ByteBuffer;
import java.security.InvalidKeyException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
/**
* Generator of identifiers used in PowerAuth protocol.
*
* @author Petr Dvorak, [email protected]
* @author Roman Strobl, [email protected]
*
*/
public class IdentifierGenerator {
/**
* Default length of Activation ID Short and Activation OTP.
*/
private static final int BASE32_KEY_LENGTH = 5;
/**
* Default length of Activation Code before conversion to Base32.
* See {@link #generateActivationCode()} method for details.
*/
private static final int ACTIVATION_CODE_BYTES_LENGTH = 12;
/**
* Default length of random bytes used for Activation Code.
* See {@link #generateActivationCode()} method for details.
*/
private static final int ACTIVATION_CODE_RANDOM_BYTES_LENGTH = 10;
private final KeyGenerator keyGenerator = new KeyGenerator();
/**
* Generate a new random activation ID - a UUID level 4 instance.
*
* @return New pseudo-random activation ID.
*/
public String generateActivationId() {
return UUID.randomUUID().toString();
}
/**
* Generate a new string of a default length (5) with characters from Base32 encoding.
*
* @return New string with Base32 characters of a given length.
*/
private String generateBase32Token() {
byte[] randomBytes = keyGenerator.generateRandomBytes(BASE32_KEY_LENGTH);
return BaseEncoding.base32().omitPadding().encode(randomBytes).substring(0, BASE32_KEY_LENGTH);
}
/**
* Generate version 3.0 or higher activation code. The format of activation code is "ABCDE-FGHIJ-KLMNO-PQRST".
* <p>
* Activation code construction:
* <ul>
* <li>Generate 10 random bytes.</li>
* <li>Calculate CRC-16 from that 10 bytes.</li>
* <li>Append CRC-16 (2 bytes) in big endian order at the end of random bytes.</li>
* <li>Generate Base32 representation from these 12 bytes, without padding characters.</li>
* <li>Split Base32 string into 4 groups, each one contains 5 characters. Use "-" as separator.</li>
* </ul>
*
* @return Generated activation code.
*/
public String generateActivationCode() {
try {
// Generate 10 random bytes.
byte[] randomBytes = keyGenerator.generateRandomBytes(ACTIVATION_CODE_RANDOM_BYTES_LENGTH);
return generateActivationCode(randomBytes);
} catch (GenericCryptoException ex) {
// Exception cannot occur, the random code length is specified correctly
return null;
}
}
/**
* Generate version 3.0 or higher activation code using provided random bytes. The format of activation code
* is "ABCDE-FGHIJ-KLMNO-PQRST".
* <p>
* Activation code construction:
* <ul>
* <li>Use provided 10 random bytes.</li>
* <li>Calculate CRC-16 from that 10 bytes.</li>
* <li>Append CRC-16 (2 bytes) in big endian order at the end of random bytes.</li>
* <li>Generate Base32 representation from these 12 bytes, without padding characters.</li>
* <li>Split Base32 string into 4 groups, each one contains 5 characters. Use "-" as separator.</li>
* </ul>
*
* @return Generated activation code.
*/
public String generateActivationCode(byte[] randomBytes) throws GenericCryptoException {
if (randomBytes == null || randomBytes.length != ACTIVATION_CODE_RANDOM_BYTES_LENGTH) {
throw new GenericCryptoException("Invalid request in generateActivationCode");
}
ByteBuffer byteBuffer = ByteBuffer.allocate(ACTIVATION_CODE_BYTES_LENGTH);
byteBuffer.put(randomBytes);
// Calculate CRC-16 from that 10 bytes.
CRC16 crc16 = new CRC16();
crc16.update(randomBytes, 0, ACTIVATION_CODE_RANDOM_BYTES_LENGTH);
long crc = crc16.getValue();
// Append CRC-16 (2 bytes) in big endian order at the end of random bytes.
byteBuffer.putShort((short) crc);
// Encode activation code.
return encodeActivationCode(byteBuffer.array());
}
/**
* Validate activation code using CRC-16 checksum. The expected format of activation code is "ABCDE-FGHIJ-KLMNO-PQRST".
*
* @param activationCode Activation code.
* @return Whether activation code is correct.
*/
public boolean validateActivationCode(String activationCode) {
if (activationCode == null) {
return false;
}
String partRegexp = "[A-Z2-7]{" + BASE32_KEY_LENGTH + "}";
String activationCodeRegexp = partRegexp + "-" + partRegexp + "-" + partRegexp + "-" + partRegexp;
// Verify activation code using regular expression
if (!activationCode.matches(activationCodeRegexp)) {
return false;
}
// Decode the Base32 value
byte[] activationCodeBytes = BaseEncoding.base32().decode(activationCode.replace("-", ""));
// Verify byte array length
if (activationCodeBytes.length != ACTIVATION_CODE_BYTES_LENGTH) {
return false;
}
// Compute checksum from first 10 bytes
CRC16 crc16 = new CRC16();
crc16.update(activationCodeBytes, 0, ACTIVATION_CODE_RANDOM_BYTES_LENGTH);
long actualChecksum = crc16.getValue();
// Convert the two CRC-16 bytes to long, see Longs.fromByteArray()
long expectedChecksum = ((long) activationCodeBytes[ACTIVATION_CODE_BYTES_LENGTH - 2] & 255L) << 8 | (long) activationCodeBytes[ACTIVATION_CODE_BYTES_LENGTH - 1] & 255L;
// Compare checksum values
return expectedChecksum == actualChecksum;
}
/**
* Generate recovery code and PUK.
* @return Recovery code and PUK.
* @throws GenericCryptoException In case of any cryptography error.
* @throws CryptoProviderException In case cryptography provider is incorrectly initialized.
* @throws InvalidKeyException In case key is invalid.
*/
public RecoveryInfo generateRecoveryCode() throws GenericCryptoException, CryptoProviderException, InvalidKeyException {
final SecretKey secretKey = keyGenerator.generateRandomSecretKey();
return generateRecoveryCode(secretKey, 1, false);
}
/**
* Generate recovery code and PUKs for given secret key, return optional seed information.
* @param secretKey Secret key to use for derivation of recovery code and PUK.
* @param pukCount Number of PUKs to generate.
* @param exportSeed Whether to export seed information.
* @return Recovery code, PUKs and optional seed information.
* @throws GenericCryptoException In case of any cryptography error.
* @throws CryptoProviderException In case cryptography provider is incorrectly initialized.
* @throws InvalidKeyException In case key is invalid.
*/
public RecoveryInfo generateRecoveryCode(SecretKey secretKey, int pukCount, boolean exportSeed) throws GenericCryptoException, CryptoProviderException, InvalidKeyException {
if (secretKey == null) {
throw new GenericCryptoException("Invalid key");
}
byte[] secretKeyBytes = PowerAuthConfiguration.INSTANCE.getKeyConvertor().convertSharedSecretKeyToBytes(secretKey);
// Generate random nonce
byte[] nonceBytes = keyGenerator.generateRandomBytes(32);
// Derive recovery key using KDF 9.63 using nonce as shared info, trim output to 26 bytes
byte[] derivedKeyBytes = KdfX9_63.derive(secretKeyBytes, nonceBytes, 26);
// Construct recovery code using derived recovery key (first 10 bytes)
final String recoveryCode = generateRecoveryCode(derivedKeyBytes);
// Generate PUK base key using derived recovery key (next 16 bytes)
final SecretKey recoveryPukBaseKey = generatePukBaseKey(derivedKeyBytes);
final Map<Integer, Long> pukDerivationIndexes = new LinkedHashMap<>();
final Map<Integer, String> puks = new LinkedHashMap<>();
for (int i = 1; i <= pukCount; i++) {
byte[] derivationIndexBytes;
Long derivationIndex;
do {
// Generate random derivation index which must be unique
derivationIndexBytes = keyGenerator.generateRandomBytes(8);
derivationIndex = ByteBuffer.wrap(derivationIndexBytes).getLong();
} while (pukDerivationIndexes.values().contains(derivationIndex));
// Generate recovery PUK and store it including derivation index
String pukDerived = generatePuk(recoveryPukBaseKey, derivationIndexBytes);
puks.put(i, pukDerived);
pukDerivationIndexes.put(i, derivationIndex);
}
if (exportSeed) {
RecoverySeed seed = new RecoverySeed(nonceBytes, pukDerivationIndexes);
return new RecoveryInfo(recoveryCode, puks, seed);
} else {
return new RecoveryInfo(recoveryCode, puks);
}
}
/**
* Derive recovery code and PUKs for given secret key and seed information.
* @param secretKey Secret key to use for derivation of recovery code and PUKs.
* @param seed Seed information containing nonce and puk derivation indexes.
* @return Derived recovery code and PUKs.
* @throws GenericCryptoException In case of any cryptography error.
* @throws CryptoProviderException In case cryptography provider is incorrectly initialized.
* @throws InvalidKeyException In case key is invalid.
*/
public RecoveryInfo deriveRecoveryCode(SecretKey secretKey, RecoverySeed seed) throws GenericCryptoException, CryptoProviderException, InvalidKeyException {
if (secretKey == null || seed == null) {
throw new GenericCryptoException("Invalid input data");
}
byte[] secretKeyBytes = PowerAuthConfiguration.INSTANCE.getKeyConvertor().convertSharedSecretKeyToBytes(secretKey);
// Get nonce and derivation indexes
final byte[] nonceBytes = seed.getNonce();
final Map<Integer, Long> pukDerivationIndexes = seed.getPukDerivationIndexes();
if (nonceBytes == null || pukDerivationIndexes == null || pukDerivationIndexes.isEmpty()) {
throw new GenericCryptoException("Invalid input data");
}
// Derive recovery key using KDF 9.63 using nonce as shared info, trim output to 26 bytes
byte[] derivedKeyBytes = KdfX9_63.derive(secretKeyBytes, nonceBytes, 26);
// Construct recovery code using derived recovery key (first 10 bytes)
final String recoveryCode = generateRecoveryCode(derivedKeyBytes);
// Generate PUK base key using derived recovery key (next 16 bytes)
final SecretKey recoveryPukBaseKey = generatePukBaseKey(derivedKeyBytes);
// Derive PUKs using derivation indexes
final Map<Integer, String> puks = new LinkedHashMap<>();
for (int i = 1; i <= pukDerivationIndexes.size(); i++) {
Long index = pukDerivationIndexes.get(i);
byte[] indexBytes = ByteBuffer.allocate(8).putLong(index).array();
String pukDerived = generatePuk(recoveryPukBaseKey, indexBytes);
puks.put(i, pukDerived);
}
// Return result
RecoveryInfo result = new RecoveryInfo();
result.setRecoveryCode(recoveryCode);
result.setPuks(puks);
return result;
}
/**
* Generate recovery code using derived key.
* @param derivedKeyBytes Derived key bytes.
* @return Recovery code.
* @throws GenericCryptoException In case of any cryptography error.
*/
private String generateRecoveryCode(byte[] derivedKeyBytes) throws GenericCryptoException {
// Extract first 10 bytes from derived key as recovery code key bytes
byte[] recoveryCodeBytes = new byte[10];
System.arraycopy(derivedKeyBytes, 0, recoveryCodeBytes, 0, 10);
// Construct recovery code using derived recovery code key
return generateActivationCode(recoveryCodeBytes);
}
/**
* Generate base key for generating PUKs using derived key.
* @param derivedKeyBytes Derived key bytes.
* @return PUK base key.
*/
private SecretKey generatePukBaseKey(byte[] derivedKeyBytes) {
// Extract bytes 10-25 as recovery puk base key bytes
final byte[] recoveryPukBaseKeyBytes = new byte[16];
System.arraycopy(derivedKeyBytes, 10, recoveryPukBaseKeyBytes, 0, 16);
return PowerAuthConfiguration.INSTANCE.getKeyConvertor().convertBytesToSharedSecretKey(recoveryPukBaseKeyBytes);
}
/**
* Generate recovery PUK using recovery base key and index bytes.
* @param recoveryPukBaseKey Recovery base key.
* @param indexBytes PUK index bytes.
* @return Generated PUK.
* @throws GenericCryptoException In case of any cryptography error.
* @throws CryptoProviderException In case cryptography provider is incorrectly initialized.
* @throws InvalidKeyException In case key is invalid.
*/
private String generatePuk(SecretKey recoveryPukBaseKey, byte[] indexBytes) throws CryptoProviderException, InvalidKeyException, GenericCryptoException {
SecretKey pukKey = keyGenerator.deriveSecretKey(recoveryPukBaseKey, indexBytes);
byte[] pukKeyBytes = PowerAuthConfiguration.INSTANCE.getKeyConvertor().convertSharedSecretKeyToBytes(pukKey);
// Extract last 8 bytes from PUK key bytes
byte[] truncatedBytes = new byte[8];
System.arraycopy(pukKeyBytes, 8, truncatedBytes, 0, 8);
// Decimalize the PUK
long puk = (ByteBuffer.wrap(truncatedBytes).getLong() & 0xFFFFFFFFFFL) % (long) (Math.pow(10, 10));
return String.format("%010d", puk);
}
/**
* Convert activation code bytes to Base32 String representation.
*
* @param activationCodeBytes Raw activation code bytes.
* @return Base32 String representation of activation code.
*/
private String encodeActivationCode(byte[] activationCodeBytes) {
// Generate Base32 representation from 12 activation code bytes, without padding characters.
String base32Encoded = BaseEncoding.base32().omitPadding().encode(activationCodeBytes);
// Split Base32 string into 4 groups, each one contains 5 characters. Use "-" as separator.
return base32Encoded.substring(0, BASE32_KEY_LENGTH)
+ "-"
+ base32Encoded.substring(BASE32_KEY_LENGTH, BASE32_KEY_LENGTH * 2)
+ "-"
+ base32Encoded.substring(BASE32_KEY_LENGTH * 2, BASE32_KEY_LENGTH * 3)
+ "-"
+ base32Encoded.substring(BASE32_KEY_LENGTH * 3, BASE32_KEY_LENGTH * 4);
}
}
| powerauth-java-crypto/src/main/java/io/getlime/security/powerauth/crypto/lib/generator/IdentifierGenerator.java | /*
* PowerAuth Crypto Library
* Copyright 2018 Wultra 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 io.getlime.security.powerauth.crypto.lib.generator;
import com.google.common.io.BaseEncoding;
import io.getlime.security.powerauth.crypto.lib.config.PowerAuthConfiguration;
import io.getlime.security.powerauth.crypto.lib.encryptor.ecies.kdf.KdfX9_63;
import io.getlime.security.powerauth.crypto.lib.model.RecoveryInfo;
import io.getlime.security.powerauth.crypto.lib.model.RecoverySeed;
import io.getlime.security.powerauth.crypto.lib.model.exception.GenericCryptoException;
import io.getlime.security.powerauth.crypto.lib.util.CRC16;
import io.getlime.security.powerauth.provider.exception.CryptoProviderException;
import javax.crypto.SecretKey;
import java.nio.ByteBuffer;
import java.security.InvalidKeyException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
/**
* Generator of identifiers used in PowerAuth protocol.
*
* @author Petr Dvorak, [email protected]
* @author Roman Strobl, [email protected]
*
*/
public class IdentifierGenerator {
/**
* Default length of Activation ID Short and Activation OTP.
*/
private static final int BASE32_KEY_LENGTH = 5;
/**
* Default length of Activation Code before conversion to Base32.
* See {@link #generateActivationCode()} method for details.
*/
private static final int ACTIVATION_CODE_BYTES_LENGTH = 12;
/**
* Default length of random bytes used for Activation Code.
* See {@link #generateActivationCode()} method for details.
*/
private static final int ACTIVATION_CODE_RANDOM_BYTES_LENGTH = 10;
private final KeyGenerator keyGenerator = new KeyGenerator();
/**
* Generate a new random activation ID - a UUID level 4 instance.
*
* @return New pseudo-random activation ID.
*/
public String generateActivationId() {
return UUID.randomUUID().toString();
}
/**
* Generate a new string of a default length (5) with characters from Base32 encoding.
*
* @return New string with Base32 characters of a given length.
*/
private String generateBase32Token() {
byte[] randomBytes = keyGenerator.generateRandomBytes(BASE32_KEY_LENGTH);
return BaseEncoding.base32().omitPadding().encode(randomBytes).substring(0, BASE32_KEY_LENGTH);
}
/**
* Generate version 3.0 or higher activation code. The format of activation code is "ABCDE-FGHIJ-KLMNO-PQRST".
* <p>
* Activation code construction:
* <ul>
* <li>Generate 10 random bytes.</li>
* <li>Calculate CRC-16 from that 10 bytes.</li>
* <li>Append CRC-16 (2 bytes) in big endian order at the end of random bytes.</li>
* <li>Generate Base32 representation from these 12 bytes, without padding characters.</li>
* <li>Split Base32 string into 4 groups, each one contains 5 characters. Use "-" as separator.</li>
* </ul>
*
* @return Generated activation code.
*/
public String generateActivationCode() {
try {
// Generate 10 random bytes.
byte[] randomBytes = keyGenerator.generateRandomBytes(ACTIVATION_CODE_RANDOM_BYTES_LENGTH);
return generateActivationCode(randomBytes);
} catch (GenericCryptoException ex) {
// Exception cannot occur, the random code length is specified correctly
return null;
}
}
/**
* Generate version 3.0 or higher activation code using provided random bytes. The format of activation code
* is "ABCDE-FGHIJ-KLMNO-PQRST".
* <p>
* Activation code construction:
* <ul>
* <li>Use provided 10 random bytes.</li>
* <li>Calculate CRC-16 from that 10 bytes.</li>
* <li>Append CRC-16 (2 bytes) in big endian order at the end of random bytes.</li>
* <li>Generate Base32 representation from these 12 bytes, without padding characters.</li>
* <li>Split Base32 string into 4 groups, each one contains 5 characters. Use "-" as separator.</li>
* </ul>
*
* @return Generated activation code.
*/
public String generateActivationCode(byte[] randomBytes) throws GenericCryptoException {
if (randomBytes == null || randomBytes.length != ACTIVATION_CODE_RANDOM_BYTES_LENGTH) {
throw new GenericCryptoException("Invalid request in generateActivationCode");
}
ByteBuffer byteBuffer = ByteBuffer.allocate(ACTIVATION_CODE_BYTES_LENGTH);
byteBuffer.put(randomBytes);
// Calculate CRC-16 from that 10 bytes.
CRC16 crc16 = new CRC16();
crc16.update(randomBytes, 0, ACTIVATION_CODE_RANDOM_BYTES_LENGTH);
long crc = crc16.getValue();
// Append CRC-16 (2 bytes) in big endian order at the end of random bytes.
byteBuffer.putShort((short) crc);
// Encode activation code.
return encodeActivationCode(byteBuffer.array());
}
/**
* Validate activation code using CRC-16 checksum. The expected format of activation code is "ABCDE-FGHIJ-KLMNO-PQRST".
*
* @param activationCode Activation code.
* @return Whether activation code is correct.
*/
public boolean validateActivationCode(String activationCode) {
if (activationCode == null) {
return false;
}
String partRegexp = "[A-Z2-7]{" + BASE32_KEY_LENGTH + "}";
String activationCodeRegexp = partRegexp + "-" + partRegexp + "-" + partRegexp + "-" + partRegexp;
// Verify activation code using regular expression
if (!activationCode.matches(activationCodeRegexp)) {
return false;
}
// Decode the Base32 value
byte[] activationCodeBytes = BaseEncoding.base32().decode(activationCode.replace("-", ""));
// Verify byte array length
if (activationCodeBytes.length != ACTIVATION_CODE_BYTES_LENGTH) {
return false;
}
// Compute checksum from first 10 bytes
CRC16 crc16 = new CRC16();
crc16.update(activationCodeBytes, 0, ACTIVATION_CODE_RANDOM_BYTES_LENGTH);
long actualChecksum = crc16.getValue();
// Convert the two CRC-16 bytes to long, see Longs.fromByteArray()
long expectedChecksum = ((long) activationCodeBytes[ACTIVATION_CODE_BYTES_LENGTH - 2] & 255L) << 8 | (long) activationCodeBytes[ACTIVATION_CODE_BYTES_LENGTH - 1] & 255L;
// Compare checksum values
return expectedChecksum == actualChecksum;
}
/**
* Generate recovery code and PUK for given secret key.
* @return Recovery code and PUK.
* @throws GenericCryptoException In case of any cryptography error.
* @throws CryptoProviderException In case cryptography provider is incorrectly initialized.
* @throws InvalidKeyException In case key is invalid.
*/
public RecoveryInfo generateRecoveryCode() throws GenericCryptoException, CryptoProviderException, InvalidKeyException {
final SecretKey secretKey = keyGenerator.generateRandomSecretKey();
return generateRecoveryCode(secretKey, 1, false);
}
/**
* Generate recovery code and PUKs for given secret key, return optional seed information.
* @param secretKey Secret key to use for derivation of recovery code and PUK.
* @param pukCount Number of PUKs to generate.
* @param exportSeed Whether to export seed information.
* @return Recovery code, PUKs and optional seed information.
* @throws GenericCryptoException In case of any cryptography error.
* @throws CryptoProviderException In case cryptography provider is incorrectly initialized.
* @throws InvalidKeyException In case key is invalid.
*/
public RecoveryInfo generateRecoveryCode(SecretKey secretKey, int pukCount, boolean exportSeed) throws GenericCryptoException, CryptoProviderException, InvalidKeyException {
if (secretKey == null) {
throw new GenericCryptoException("Invalid key");
}
byte[] secretKeyBytes = PowerAuthConfiguration.INSTANCE.getKeyConvertor().convertSharedSecretKeyToBytes(secretKey);
// Generate random nonce
byte[] nonceBytes = keyGenerator.generateRandomBytes(32);
// Derive recovery key using KDF 9.63 using nonce as shared info, trim output to 26 bytes
byte[] derivedKeyBytes = KdfX9_63.derive(secretKeyBytes, nonceBytes, 26);
// Construct recovery code using derived recovery key (first 10 bytes)
final String recoveryCode = generateRecoveryCode(derivedKeyBytes);
// Generate PUK base key using derived recovery key (next 16 bytes)
final SecretKey recoveryPukBaseKey = generatePukBaseKey(derivedKeyBytes);
final Map<Integer, Long> pukDerivationIndexes = new LinkedHashMap<>();
final Map<Integer, String> puks = new LinkedHashMap<>();
for (int i = 1; i <= pukCount; i++) {
byte[] derivationIndexBytes;
Long derivationIndex;
do {
// Generate random derivation index which must be unique
derivationIndexBytes = keyGenerator.generateRandomBytes(8);
derivationIndex = ByteBuffer.wrap(derivationIndexBytes).getLong();
} while (pukDerivationIndexes.values().contains(derivationIndex));
// Generate recovery PUK and store it including derivation index
String pukDerived = generatePuk(recoveryPukBaseKey, derivationIndexBytes);
puks.put(i, pukDerived);
pukDerivationIndexes.put(i, derivationIndex);
}
if (exportSeed) {
RecoverySeed seed = new RecoverySeed(nonceBytes, pukDerivationIndexes);
return new RecoveryInfo(recoveryCode, puks, seed);
} else {
return new RecoveryInfo(recoveryCode, puks);
}
}
/**
* Derive recovery code and PUKs for given secret key and seed information.
* @param secretKey Secret key to use for derivation of recovery code and PUKs.
* @param seed Seed information containing nonce and puk derivation indexes.
* @return Derived recovery code and PUKs.
* @throws GenericCryptoException In case of any cryptography error.
* @throws CryptoProviderException In case cryptography provider is incorrectly initialized.
* @throws InvalidKeyException In case key is invalid.
*/
public RecoveryInfo deriveRecoveryCode(SecretKey secretKey, RecoverySeed seed) throws GenericCryptoException, CryptoProviderException, InvalidKeyException {
if (secretKey == null || seed == null) {
throw new GenericCryptoException("Invalid input data");
}
byte[] secretKeyBytes = PowerAuthConfiguration.INSTANCE.getKeyConvertor().convertSharedSecretKeyToBytes(secretKey);
// Get nonce and derivation indexes
final byte[] nonceBytes = seed.getNonce();
final Map<Integer, Long> pukDerivationIndexes = seed.getPukDerivationIndexes();
if (nonceBytes == null || pukDerivationIndexes == null || pukDerivationIndexes.isEmpty()) {
throw new GenericCryptoException("Invalid input data");
}
// Derive recovery key using KDF 9.63 using nonce as shared info, trim output to 26 bytes
byte[] derivedKeyBytes = KdfX9_63.derive(secretKeyBytes, nonceBytes, 26);
// Construct recovery code using derived recovery key (first 10 bytes)
final String recoveryCode = generateRecoveryCode(derivedKeyBytes);
// Generate PUK base key using derived recovery key (next 16 bytes)
final SecretKey recoveryPukBaseKey = generatePukBaseKey(derivedKeyBytes);
// Derive PUKs using derivation indexes
final Map<Integer, String> puks = new LinkedHashMap<>();
for (int i = 1; i <= pukDerivationIndexes.size(); i++) {
Long index = pukDerivationIndexes.get(i);
byte[] indexBytes = ByteBuffer.allocate(8).putLong(index).array();
String pukDerived = generatePuk(recoveryPukBaseKey, indexBytes);
puks.put(i, pukDerived);
}
// Return result
RecoveryInfo result = new RecoveryInfo();
result.setRecoveryCode(recoveryCode);
result.setPuks(puks);
return result;
}
/**
* Generate recovery code using derived key.
* @param derivedKeyBytes Derived key bytes.
* @return Recovery code.
* @throws GenericCryptoException In case of any cryptography error.
*/
private String generateRecoveryCode(byte[] derivedKeyBytes) throws GenericCryptoException {
// Extract first 10 bytes from derived key as recovery code key bytes
byte[] recoveryCodeBytes = new byte[10];
System.arraycopy(derivedKeyBytes, 0, recoveryCodeBytes, 0, 10);
// Construct recovery code using derived recovery code key
return generateActivationCode(recoveryCodeBytes);
}
/**
* Generate base key for generating PUKs using derived key.
* @param derivedKeyBytes Derived key bytes.
* @return PUK base key.
*/
private SecretKey generatePukBaseKey(byte[] derivedKeyBytes) {
// Extract bytes 10-25 as recovery puk base key bytes
final byte[] recoveryPukBaseKeyBytes = new byte[16];
System.arraycopy(derivedKeyBytes, 10, recoveryPukBaseKeyBytes, 0, 16);
return PowerAuthConfiguration.INSTANCE.getKeyConvertor().convertBytesToSharedSecretKey(recoveryPukBaseKeyBytes);
}
/**
* Generate recovery PUK using recovery base key and index bytes.
* @param recoveryPukBaseKey Recovery base key.
* @param indexBytes PUK index bytes.
* @return Generated PUK.
* @throws GenericCryptoException In case of any cryptography error.
* @throws CryptoProviderException In case cryptography provider is incorrectly initialized.
* @throws InvalidKeyException In case key is invalid.
*/
private String generatePuk(SecretKey recoveryPukBaseKey, byte[] indexBytes) throws CryptoProviderException, InvalidKeyException, GenericCryptoException {
SecretKey pukKey = keyGenerator.deriveSecretKey(recoveryPukBaseKey, indexBytes);
byte[] pukKeyBytes = PowerAuthConfiguration.INSTANCE.getKeyConvertor().convertSharedSecretKeyToBytes(pukKey);
// Extract last 8 bytes from PUK key bytes
byte[] truncatedBytes = new byte[8];
System.arraycopy(pukKeyBytes, 8, truncatedBytes, 0, 8);
// Decimalize the PUK
long puk = (ByteBuffer.wrap(truncatedBytes).getLong() & 0xFFFFFFFFFFL) % (long) (Math.pow(10, 10));
return String.format("%010d", puk);
}
/**
* Convert activation code bytes to Base32 String representation.
*
* @param activationCodeBytes Raw activation code bytes.
* @return Base32 String representation of activation code.
*/
private String encodeActivationCode(byte[] activationCodeBytes) {
// Generate Base32 representation from 12 activation code bytes, without padding characters.
String base32Encoded = BaseEncoding.base32().omitPadding().encode(activationCodeBytes);
// Split Base32 string into 4 groups, each one contains 5 characters. Use "-" as separator.
return base32Encoded.substring(0, BASE32_KEY_LENGTH)
+ "-"
+ base32Encoded.substring(BASE32_KEY_LENGTH, BASE32_KEY_LENGTH * 2)
+ "-"
+ base32Encoded.substring(BASE32_KEY_LENGTH * 2, BASE32_KEY_LENGTH * 3)
+ "-"
+ base32Encoded.substring(BASE32_KEY_LENGTH * 3, BASE32_KEY_LENGTH * 4);
}
}
| Update JavaDoc
| powerauth-java-crypto/src/main/java/io/getlime/security/powerauth/crypto/lib/generator/IdentifierGenerator.java | Update JavaDoc | <ide><path>owerauth-java-crypto/src/main/java/io/getlime/security/powerauth/crypto/lib/generator/IdentifierGenerator.java
<ide> }
<ide>
<ide> /**
<del> * Generate recovery code and PUK for given secret key.
<add> * Generate recovery code and PUK.
<ide> * @return Recovery code and PUK.
<ide> * @throws GenericCryptoException In case of any cryptography error.
<ide> * @throws CryptoProviderException In case cryptography provider is incorrectly initialized. |
|
Java | apache-2.0 | 0a6c01f8ae4e0cae9f834b0f0bb8cc7beff92f89 | 0 | voho/web,voho/web | package cz.voho.wiki.parser;
import cz.voho.wiki.model.ParsedWikiPage;
import cz.voho.wiki.model.WikiPageSource;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class JavadocPreprocessorTest {
private final JavadocPreprocessor toTest = new JavadocPreprocessor();
@Test
public void noMatch() {
final String source = "Hello, there is no link here.";
final String actual = parseSource(source);
final String expected = source;
assertEquals(expected, actual);
}
@Test
public void singleUnmatch() {
final String source = "*Hello*, there is no *link* here.";
final String actual = parseSource(source);
final String expected = source;
assertEquals(expected, actual);
}
@Test
public void singleMatch() {
final String source = "Here is the link: *javadoc:org.slf4j.Logger* and that is it!";
final String actual = parseSource(source);
final String expected = "Here is the link: [org.slf4j.**Logger**](https://github.com/search?l=Java&q=org.slf4j.Logger&type=Code) and that is it!";
assertEquals(expected, actual);
}
@Test
public void multiMatch() {
final String source = "Here is the *link*: *javadoc:org.slf4j.Logger* and that is it! Maybe one more: *javadoc:org.slf4j.Logger*";
final String actual = parseSource(source);
final String expected = "Here is the *link*: [org.slf4j.**Logger**](https://github.com/search?l=Java&q=org.slf4j.Logger&type=Code) and that is it! Maybe one more: [org.slf4j.**Logger**](https://github.com/search?l=Java&q=org.slf4j.Logger&type=Code)";
assertEquals(expected, actual);
}
@Test
public void mixedMatch() {
final String source = "Here is the *link*: *javadoc:org.slf4j.Logger* and that is it!";
final String actual = parseSource(source);
final String expected = "Here is the *link*: [org.slf4j.**Logger**](https://github.com/search?l=Java&q=org.slf4j.Logger&type=Code) and that is it!";
assertEquals(expected, actual);
}
private String parseSource(final String source) {
final ParsedWikiPage page = new ParsedWikiPage();
page.setSource(new WikiPageSource());
page.getSource().setMarkdownSource(source);
toTest.preprocessSource(page);
return page.getSource().getMarkdownSource();
}
}
| website/src/test/java/cz/voho/wiki/parser/JavadocPreprocessorTest.java | package cz.voho.wiki.parser;
import cz.voho.wiki.model.ParsedWikiPage;
import cz.voho.wiki.model.WikiPageSource;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class JavadocPreprocessorTest {
private JavadocPreprocessor toTest = new JavadocPreprocessor();
@Test
public void noMatch() {
String source = "Hello, there is no link here.";
String actual = parseSource(source);
String expected = source;
assertEquals(expected, actual);
}
@Test
public void singleUnmatch() {
String source = "*Hello*, there is no *link* here.";
String actual = parseSource(source);
String expected = source;
assertEquals(expected, actual);
}
@Test
public void singleMatch() {
String source = "Here is the link: *javadoc:org.slf4j.Logger* and that is it!";
String actual = parseSource(source);
String expected = "Here is the link: [org.slf4j.**Logger**](http://grepcode.com/search?query=org.slf4j.Logger) and that is it!";
assertEquals(expected, actual);
}
@Test
public void multiMatch() {
String source = "Here is the *link*: *javadoc:org.slf4j.Logger* and that is it! Maybe one more: *javadoc:org.slf4j.Logger*";
String actual = parseSource(source);
String expected = "Here is the *link*: [org.slf4j.**Logger**](http://grepcode.com/search?query=org.slf4j.Logger) and that is it! Maybe one more: [org.slf4j.**Logger**](http://grepcode.com/search?query=org.slf4j.Logger)";
assertEquals(expected, actual);
}
@Test
public void mixedMatch() {
String source = "Here is the *link*: *javadoc:org.slf4j.Logger* and that is it!";
String actual = parseSource(source);
String expected = "Here is the *link*: [org.slf4j.**Logger**](http://grepcode.com/search?query=org.slf4j.Logger) and that is it!";
assertEquals(expected, actual);
}
private String parseSource(String source) {
ParsedWikiPage page = new ParsedWikiPage();
page.setSource(new WikiPageSource());
page.getSource().setMarkdownSource(source);
toTest.preprocessSource(page);
return page.getSource().getMarkdownSource();
}
} | finally fixed unit tests
| website/src/test/java/cz/voho/wiki/parser/JavadocPreprocessorTest.java | finally fixed unit tests | <ide><path>ebsite/src/test/java/cz/voho/wiki/parser/JavadocPreprocessorTest.java
<ide> import static org.junit.Assert.assertEquals;
<ide>
<ide> public class JavadocPreprocessorTest {
<del> private JavadocPreprocessor toTest = new JavadocPreprocessor();
<add> private final JavadocPreprocessor toTest = new JavadocPreprocessor();
<ide>
<ide> @Test
<ide> public void noMatch() {
<del> String source = "Hello, there is no link here.";
<del> String actual = parseSource(source);
<del> String expected = source;
<add> final String source = "Hello, there is no link here.";
<add> final String actual = parseSource(source);
<add> final String expected = source;
<ide> assertEquals(expected, actual);
<ide> }
<ide>
<ide> @Test
<ide> public void singleUnmatch() {
<del> String source = "*Hello*, there is no *link* here.";
<del> String actual = parseSource(source);
<del> String expected = source;
<add> final String source = "*Hello*, there is no *link* here.";
<add> final String actual = parseSource(source);
<add> final String expected = source;
<ide> assertEquals(expected, actual);
<ide> }
<ide>
<ide> @Test
<ide> public void singleMatch() {
<del> String source = "Here is the link: *javadoc:org.slf4j.Logger* and that is it!";
<del> String actual = parseSource(source);
<del> String expected = "Here is the link: [org.slf4j.**Logger**](http://grepcode.com/search?query=org.slf4j.Logger) and that is it!";
<add> final String source = "Here is the link: *javadoc:org.slf4j.Logger* and that is it!";
<add> final String actual = parseSource(source);
<add> final String expected = "Here is the link: [org.slf4j.**Logger**](https://github.com/search?l=Java&q=org.slf4j.Logger&type=Code) and that is it!";
<ide> assertEquals(expected, actual);
<ide> }
<ide>
<ide> @Test
<ide> public void multiMatch() {
<del> String source = "Here is the *link*: *javadoc:org.slf4j.Logger* and that is it! Maybe one more: *javadoc:org.slf4j.Logger*";
<del> String actual = parseSource(source);
<del> String expected = "Here is the *link*: [org.slf4j.**Logger**](http://grepcode.com/search?query=org.slf4j.Logger) and that is it! Maybe one more: [org.slf4j.**Logger**](http://grepcode.com/search?query=org.slf4j.Logger)";
<add> final String source = "Here is the *link*: *javadoc:org.slf4j.Logger* and that is it! Maybe one more: *javadoc:org.slf4j.Logger*";
<add> final String actual = parseSource(source);
<add> final String expected = "Here is the *link*: [org.slf4j.**Logger**](https://github.com/search?l=Java&q=org.slf4j.Logger&type=Code) and that is it! Maybe one more: [org.slf4j.**Logger**](https://github.com/search?l=Java&q=org.slf4j.Logger&type=Code)";
<ide> assertEquals(expected, actual);
<ide> }
<ide>
<ide> @Test
<ide> public void mixedMatch() {
<del> String source = "Here is the *link*: *javadoc:org.slf4j.Logger* and that is it!";
<del> String actual = parseSource(source);
<del> String expected = "Here is the *link*: [org.slf4j.**Logger**](http://grepcode.com/search?query=org.slf4j.Logger) and that is it!";
<add> final String source = "Here is the *link*: *javadoc:org.slf4j.Logger* and that is it!";
<add> final String actual = parseSource(source);
<add> final String expected = "Here is the *link*: [org.slf4j.**Logger**](https://github.com/search?l=Java&q=org.slf4j.Logger&type=Code) and that is it!";
<ide> assertEquals(expected, actual);
<ide> }
<ide>
<del> private String parseSource(String source) {
<del> ParsedWikiPage page = new ParsedWikiPage();
<add> private String parseSource(final String source) {
<add> final ParsedWikiPage page = new ParsedWikiPage();
<ide> page.setSource(new WikiPageSource());
<ide> page.getSource().setMarkdownSource(source);
<ide> toTest.preprocessSource(page); |
|
Java | mit | da689e5f445328b8dec5402903302e35920becca | 0 | vilnius/tvarkau-vilniu,vilnius/tvarkau-vilniu,ViliusKraujutis/tvarkau-vilniu | package lt.vilnius.tvarkau;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.model.LatLng;
import com.viewpagerindicator.CirclePageIndicator;
import org.greenrobot.eventbus.EventBus;
import org.threeten.bp.LocalDateTime;
import org.threeten.bp.ZoneOffset;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import autodagger.AutoComponent;
import autodagger.AutoInjector;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemSelected;
import icepick.State;
import lt.vilnius.tvarkau.api.ApiMethod;
import lt.vilnius.tvarkau.api.ApiRequest;
import lt.vilnius.tvarkau.api.ApiResponse;
import lt.vilnius.tvarkau.api.GetNewProblemParams;
import lt.vilnius.tvarkau.api.LegacyApiModule;
import lt.vilnius.tvarkau.api.LegacyApiService;
import lt.vilnius.tvarkau.entity.Profile;
import lt.vilnius.tvarkau.entity.ReportType;
import lt.vilnius.tvarkau.events_listeners.NewProblemAddedEvent;
import lt.vilnius.tvarkau.utils.FormatUtils;
import lt.vilnius.tvarkau.utils.GlobalConsts;
import lt.vilnius.tvarkau.utils.ImageUtils;
import lt.vilnius.tvarkau.utils.KeyboardUtils;
import lt.vilnius.tvarkau.utils.PermissionUtils;
import lt.vilnius.tvarkau.views.adapters.ProblemImagesPagerAdapter;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static lt.vilnius.tvarkau.ChooseReportTypeActivity.EXTRA_REPORT_TYPE;
@AutoComponent(modules = {LegacyApiModule.class, AppModule.class, SharedPreferencesModule.class})
@AutoInjector
@Singleton
public class NewProblemActivity extends BaseActivity {
@Inject LegacyApiService legacyApiService;
@Inject SharedPreferences myProblemsPreferences;
private static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int GALLERY_REQUEST_CODE = 2;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 10;
private static final int MAP_PERMISSION_REQUEST_CODE = 20;
public static final int REQUEST_PLACE_PICKER = 11;
public static final int REQUEST_PROFILE = 12;
public static final int REQUEST_CHOOSE_REPORT_TYPE = 13;
public static final String[] MAP_PERMISSIONS = new String[]{ACCESS_FINE_LOCATION};
private static final String[] LOCATION_PERMISSIONS = {WRITE_EXTERNAL_STORAGE, CAMERA, READ_EXTERNAL_STORAGE};
public static final String PROBLEM_PREFERENCE_KEY = "problem";
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.report_problem_location)
EditText reportProblemLocation;
@BindView(R.id.problem_images_view_pager)
ViewPager problemImagesViewPager;
@BindView(R.id.problem_images_view_pager_indicator)
CirclePageIndicator problemImagesViewPagerIndicator;
@BindView(R.id.report_problem_type)
EditText reportProblemType;
@BindView(R.id.report_problem_privacy_mode)
Spinner reportProblemPrivacyMode;
@BindView(R.id.report_problem_description)
EditText reportProblemDescription;
@BindView(R.id.report_problem_location_wrapper)
TextInputLayout reportProblemLocationWrapper;
@BindView(R.id.report_problem_description_wrapper)
TextInputLayout reportProblemDescriptionWrapper;
@BindView(R.id.report_problem_type_wrapper)
TextInputLayout reportProblemTypeWrapper;
@BindView(R.id.report_problem_take_photo)
ImageView reportProblemTakePhoto;
@State
File lastPhotoFile;
@State
LatLng locationCords;
@State
ArrayList<Uri> imagesURIs;
@State
Profile profile;
@State
ReportType reportType;
@State
String address;
private Snackbar snackbar;
private String photoFileName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_problem);
ButterKnife.bind(this);
DaggerNewProblemActivityComponent
.builder()
.appModule(new AppModule(this.getApplication()))
.sharedPreferencesModule(new SharedPreferencesModule())
.legacyApiModule(new LegacyApiModule())
.build()
.inject(this);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);
initProblemImagesPager();
initPrivacyModeSpinner();
imagesURIs = new ArrayList<>();
}
private void initPrivacyModeSpinner() {
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.report_privacy_mode, R.layout.item_report_type_spinner);
adapter.setDropDownViewResource(R.layout.item_report_type_spinner_dropdown);
reportProblemPrivacyMode.setAdapter(adapter);
}
private void initProblemImagesPager() {
problemImagesViewPager.setAdapter(new ProblemImagesPagerAdapter(this, null));
problemImagesViewPager.setOffscreenPageLimit(3);
problemImagesViewPagerIndicator.setViewPager(problemImagesViewPager);
problemImagesViewPagerIndicator.setVisibility(View.GONE);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.action_send:
sendProblem();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.new_problem_toolbar_menu, menu);
return true;
}
public void sendProblem() {
if (validateProblemInputs()) {
ProgressDialog progressDialog = createProgressDialog();
progressDialog.setCancelable(false);
progressDialog.show();
Observable<String[]> photoObservable;
if (imagesURIs != null) {
photoObservable = Observable.from(imagesURIs)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.map(uri -> Uri.fromFile(new File(ImageUtils.getPhotoPathFromUri(this, uri))))
.map(ImageUtils::convertToBase64EncodedString)
.toList()
.map(encodedPhotos -> {
if (encodedPhotos.size() > 0) {
String[] encodedPhotosArray = new String[encodedPhotos.size()];
encodedPhotos.toArray(encodedPhotosArray);
return encodedPhotosArray;
} else {
return null;
}
});
} else {
photoObservable = Observable.just(null);
}
Action1<ApiResponse<Integer>> onSuccess = apiResponse -> {
if (apiResponse.getResult() != null) {
String newProblemId = apiResponse.getResult().toString();
myProblemsPreferences
.edit()
.putString(PROBLEM_PREFERENCE_KEY + newProblemId, newProblemId)
.apply();
EventBus.getDefault().post(new NewProblemAddedEvent());
progressDialog.dismiss();
if (reportProblemDescription.hasFocus()) {
KeyboardUtils.closeSoftKeyboard(this, reportProblemDescription);
}
Toast.makeText(this, R.string.problem_successfully_sent, Toast.LENGTH_SHORT).show();
setResult(RESULT_OK);
finish();
}
};
Action1<Throwable> onError = throwable -> {
LogApp.logCrash(throwable);
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), R.string.error_submitting_problem, Toast.LENGTH_SHORT).show();
};
photoObservable
.subscribeOn(Schedulers.io())
.flatMap(encodedPhotos ->
Observable.just(
new GetNewProblemParams.Builder()
.setSessionId(null)
.setDescription(reportProblemDescription.getText().toString())
.setType(reportType.getName())
.setAddress(address)
.setLatitude(locationCords.latitude)
.setLongitude(locationCords.longitude)
.setPhoto(encodedPhotos)
.setEmail(null)
.setPhone(null)
.setMessageDescription(null)
.create())
).map(params -> new ApiRequest<>(ApiMethod.NEW_PROBLEM, params))
.flatMap(request -> legacyApiService.postNewProblem(request))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
onSuccess,
onError
);
}
}
private ProgressDialog createProgressDialog() {
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage(getString(R.string.sending_problem));
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
return progressDialog;
}
private boolean validateProblemInputs() {
boolean addressIsValid = false;
boolean descriptionIsValid = false;
boolean problemTypeIsValid = false;
if (address != null) {
addressIsValid = true;
reportProblemDescriptionWrapper.setError(null);
} else {
reportProblemLocationWrapper.setError(getText(R.string.error_problem_location_is_empty));
}
if (reportProblemDescription.getText() != null && reportProblemDescription.getText().length() > 0) {
descriptionIsValid = true;
} else {
reportProblemDescriptionWrapper.setError(getText(R.string.error_problem_description_is_empty));
}
if (reportType != null) {
problemTypeIsValid = true;
} else {
reportProblemTypeWrapper.setError(getText(R.string.error_problem_type_is_empty));
}
return addressIsValid && descriptionIsValid && problemTypeIsValid;
}
private void openPhotoSelectorDialog() {
AlertDialog.Builder imagePickerDialogBuilder = new AlertDialog.Builder(this, R.style.MyDialogTheme);
View view = LayoutInflater.from(this).inflate(R.layout.image_picker_dialog, null);
TextView cameraButton = ButterKnife.findById(view, R.id.camera_button);
TextView galleryButton = ButterKnife.findById(view, R.id.gallery_button);
imagePickerDialogBuilder
.setTitle(this.getResources().getString(R.string.add_photos))
.setView(view)
.setPositiveButton(R.string.cancel, (dialog, whichButton) -> dialog.dismiss())
.create();
AlertDialog imagePickerDialog = imagePickerDialogBuilder.show();
cameraButton.setOnClickListener(v -> {
launchCamera();
imagePickerDialog.dismiss();
});
galleryButton.setOnClickListener(v -> {
openGallery();
imagePickerDialog.dismiss();
});
}
private void launchCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String timestamp = FormatUtils.formatLocalDateTimeToSeconds(LocalDateTime.now(ZoneOffset.UTC));
photoFileName = "IMG_" + timestamp + ".jpg";
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImageUtils.getTakenPhotoFileUri(this, photoFileName));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
}
private void openGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, GALLERY_REQUEST_CODE);
}
}
@OnClick(R.id.report_problem_take_photo)
public void onTakePhotoClicked() {
if (PermissionUtils.isAllPermissionsGranted(this, LOCATION_PERMISSIONS)) {
openPhotoSelectorDialog();
} else {
ActivityCompat.requestPermissions(this, LOCATION_PERMISSIONS, LOCATION_PERMISSION_REQUEST_CODE);
}
}
@OnClick(R.id.report_problem_type)
public void onChooseProblemTypeClicked() {
Intent intent = new Intent(this, ChooseReportTypeActivity.class);
startActivityForResult(intent, REQUEST_CHOOSE_REPORT_TYPE);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE:
if (PermissionUtils.isAllPermissionsGranted(this, LOCATION_PERMISSIONS)) {
openPhotoSelectorDialog();
} else {
Toast.makeText(this, R.string.error_need_camera_and_storage_permission, Toast.LENGTH_SHORT).show();
}
break;
case MAP_PERMISSION_REQUEST_CODE:
if (PermissionUtils.isAllPermissionsGranted(this, MAP_PERMISSIONS)) {
showPlacePicker(getCurrentFocus());
} else {
Toast.makeText(this, R.string.error_need_location_permission, Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private boolean isEditedByUser() {
return reportProblemDescription.getText().length() > 0
|| reportProblemLocation.getText().length() > 0
|| (reportType != null && reportType.getName() != null)
|| (imagesURIs != null && imagesURIs.size() > 0);
}
@Override
public void onBackPressed() {
if (reportProblemDescription.hasFocus()) {
KeyboardUtils.closeSoftKeyboard(this, reportProblemDescription);
}
if (isEditedByUser()) {
new AlertDialog.Builder(this, R.style.MyDialogTheme)
.setMessage(getString(R.string.discard_changes_title))
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.discard_changes_positive, (dialog, whichButton) ->
NewProblemActivity.super.onBackPressed())
.setNegativeButton(R.string.discard_changes_negative, null).show();
} else {
super.onBackPressed();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_IMAGE_CAPTURE:
Uri takenImageUri = ImageUtils.getTakenPhotoFileUri(this, photoFileName);
setImagesInViewPager(takenImageUri);
break;
case GALLERY_REQUEST_CODE:
ClipData clipData = data.getClipData();
if (clipData != null) {
for (int i = 0; i < clipData.getItemCount(); i++) {
setImagesInViewPager(clipData.getItemAt(i).getUri());
}
} else if (data.getData() != null) {
Uri uri = data.getData();
setImagesInViewPager(uri);
}
break;
case REQUEST_PLACE_PICKER:
Place place = PlacePicker.getPlace(this, data);
LatLng latLng = place.getLatLng();
Geocoder geocoder = new Geocoder(this);
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
} catch (IOException e) {
LogApp.logCrash(e);
}
if (addresses != null && addresses.size() > 0) {
if (addresses.get(0).getLocality() != null) {
String city = addresses.get(0).getLocality();
if (city.equalsIgnoreCase(GlobalConsts.CITY_VILNIUS)) {
address = addresses.get(0).getAddressLine(0);
reportProblemLocationWrapper.setError(null);
reportProblemLocation.setText(address);
locationCords = latLng;
if (snackbar != null && snackbar.isShown()) {
snackbar.dismiss();
}
} else {
showIncorrectPlaceSnackbar();
}
}
} else {
showIncorrectPlaceSnackbar();
}
break;
case REQUEST_PROFILE:
profile = Profile.returnProfile(this);
break;
case REQUEST_CHOOSE_REPORT_TYPE:
if (data.hasExtra(EXTRA_REPORT_TYPE)) {
reportType = data.getParcelableExtra(EXTRA_REPORT_TYPE);
reportProblemTypeWrapper.setError(null);
reportProblemType.setText(reportType.getName());
}
break;
}
} else {
switch (requestCode) {
case REQUEST_PROFILE:
reportProblemPrivacyMode.setSelection(0);
break;
case REQUEST_IMAGE_CAPTURE:
Toast.makeText(this, R.string.photo_capture_error, Toast.LENGTH_SHORT).show();
}
}
}
private void setImagesInViewPager(Uri uri) {
imagesURIs.add(uri);
String[] imagesPath = new String[imagesURIs.size()];
for (int i = 0; i < imagesURIs.size(); i++) {
String path = ImageUtils.getPhotoPathFromUri(this, imagesURIs.get(i));
if (path != null) {
imagesPath[i] = new File(path).toString();
} else {
imagesURIs.remove(uri);
Toast.makeText(this, R.string.error_taking_image_from_server, Toast.LENGTH_LONG).show();
}
}
if (imagesURIs.size() > 1) {
problemImagesViewPagerIndicator.setVisibility(View.VISIBLE);
}
if (imagesURIs.size() > 0) {
problemImagesViewPager.setAdapter(new ProblemImagesPagerAdapter<>(this, imagesPath));
}
}
private void showIncorrectPlaceSnackbar() {
View view = this.getCurrentFocus();
snackbar = Snackbar.make(view, R.string.error_location_incorrect, Snackbar.LENGTH_INDEFINITE);
snackbar.setAction(R.string.choose_again, v -> showPlacePicker(view))
.setActionTextColor(ContextCompat.getColor(this, R.color.snackbar_action_text))
.show();
}
@OnClick(R.id.report_problem_location)
public void onProblemLocationClicked(View view) {
if ((PermissionUtils.isAllPermissionsGranted(this, MAP_PERMISSIONS))) {
showPlacePicker(view);
} else {
requestPermissions(MAP_PERMISSIONS, MAP_PERMISSION_REQUEST_CODE);
}
}
@OnItemSelected(R.id.report_problem_privacy_mode)
public void onPrivacyModeSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
profile = null;
break;
case 1:
profile = Profile.returnProfile(this);
if (profile == null) {
Intent intent = new Intent(this, MyProfileActivity.class);
startActivityForResult(intent, REQUEST_PROFILE);
}
break;
}
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return false;
}
private void showPlacePicker(View view) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
Intent intent = builder.build(this);
Bundle bundle = ActivityOptionsCompat.makeScaleUpAnimation(view, 0, 0, view.getWidth(), view.getHeight()).toBundle();
ActivityCompat.startActivityForResult(this, intent, REQUEST_PLACE_PICKER, bundle);
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
LogApp.logCrash(e);
Snackbar.make(view, R.string.check_google_play_services, Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.open, v -> {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com" +
".google.android.gms"));
startActivity(intent);
})
.setActionTextColor(ContextCompat.getColor(this, R.color.snackbar_action_text))
.show();
}
}
}
| app/src/main/java/lt/vilnius/tvarkau/NewProblemActivity.java | package lt.vilnius.tvarkau;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.model.LatLng;
import com.viewpagerindicator.CirclePageIndicator;
import org.greenrobot.eventbus.EventBus;
import org.threeten.bp.LocalDateTime;
import org.threeten.bp.ZoneOffset;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import autodagger.AutoComponent;
import autodagger.AutoInjector;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemSelected;
import icepick.State;
import lt.vilnius.tvarkau.api.ApiMethod;
import lt.vilnius.tvarkau.api.ApiRequest;
import lt.vilnius.tvarkau.api.ApiResponse;
import lt.vilnius.tvarkau.api.GetNewProblemParams;
import lt.vilnius.tvarkau.api.LegacyApiModule;
import lt.vilnius.tvarkau.api.LegacyApiService;
import lt.vilnius.tvarkau.entity.Profile;
import lt.vilnius.tvarkau.entity.ReportType;
import lt.vilnius.tvarkau.events_listeners.NewProblemAddedEvent;
import lt.vilnius.tvarkau.utils.FormatUtils;
import lt.vilnius.tvarkau.utils.GlobalConsts;
import lt.vilnius.tvarkau.utils.ImageUtils;
import lt.vilnius.tvarkau.utils.KeyboardUtils;
import lt.vilnius.tvarkau.utils.PermissionUtils;
import lt.vilnius.tvarkau.views.adapters.ProblemImagesPagerAdapter;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static lt.vilnius.tvarkau.ChooseReportTypeActivity.EXTRA_REPORT_TYPE;
@AutoComponent(modules = {LegacyApiModule.class, AppModule.class, SharedPreferencesModule.class})
@AutoInjector
@Singleton
public class NewProblemActivity extends BaseActivity {
@Inject LegacyApiService legacyApiService;
@Inject SharedPreferences myProblemsPreferences;
private static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int GALLERY_REQUEST_CODE = 2;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 10;
private static final int MAP_PERMISSION_REQUEST_CODE = 20;
public static final int REQUEST_PLACE_PICKER = 11;
public static final int REQUEST_PROFILE = 12;
public static final int REQUEST_CHOOSE_REPORT_TYPE = 13;
public static final String[] MAP_PERMISSIONS = new String[]{ACCESS_FINE_LOCATION};
private static final String[] LOCATION_PERMISSIONS = {WRITE_EXTERNAL_STORAGE, CAMERA, READ_EXTERNAL_STORAGE};
public static final String PROBLEM_PREFERENCE_KEY = "problem";
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.report_problem_location)
EditText addProblemLocation;
@BindView(R.id.problem_images_view_pager)
ViewPager problemImagesViewPager;
@BindView(R.id.problem_images_view_pager_indicator)
CirclePageIndicator problemImagesViewPagerIndicator;
@BindView(R.id.report_problem_type)
EditText reportProblemType;
@BindView(R.id.report_problem_privacy_mode)
Spinner reportProblemPrivacyMode;
@BindView(R.id.report_problem_description)
EditText reportProblemDescription;
@BindView(R.id.report_problem_location_wrapper)
TextInputLayout reportProblemLocationWrapper;
@BindView(R.id.report_problem_description_wrapper)
TextInputLayout reportProblemDescriptionWrapper;
@BindView(R.id.report_problem_type_wrapper)
TextInputLayout reportProblemTypeWrapper;
@BindView(R.id.report_problem_take_photo)
ImageView reportProblemTakePhoto;
@State
File lastPhotoFile;
@State
LatLng locationCords;
@State
ArrayList<Uri> imagesURIs;
@State
Profile profile;
@State
ReportType reportType;
@State
String address;
private Snackbar snackbar;
private String photoFileName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_problem);
ButterKnife.bind(this);
DaggerNewProblemActivityComponent
.builder()
.appModule(new AppModule(this.getApplication()))
.sharedPreferencesModule(new SharedPreferencesModule())
.legacyApiModule(new LegacyApiModule())
.build()
.inject(this);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);
initProblemImagesPager();
initPrivacyModeSpinner();
imagesURIs = new ArrayList<>();
}
private void initPrivacyModeSpinner() {
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.report_privacy_mode, R.layout.item_report_type_spinner);
adapter.setDropDownViewResource(R.layout.item_report_type_spinner_dropdown);
reportProblemPrivacyMode.setAdapter(adapter);
}
private void initProblemImagesPager() {
problemImagesViewPager.setAdapter(new ProblemImagesPagerAdapter(this, null));
problemImagesViewPager.setOffscreenPageLimit(3);
problemImagesViewPagerIndicator.setViewPager(problemImagesViewPager);
problemImagesViewPagerIndicator.setVisibility(View.GONE);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.action_send:
sendProblem();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.new_problem_toolbar_menu, menu);
return true;
}
public void sendProblem() {
if (validateProblemInputs()) {
ProgressDialog progressDialog = createProgressDialog();
progressDialog.setCancelable(false);
progressDialog.show();
Observable<String[]> photoObservable;
if (imagesURIs != null) {
photoObservable = Observable.from(imagesURIs)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.map(uri -> Uri.fromFile(new File(ImageUtils.getPhotoPathFromUri(this, uri))))
.map(ImageUtils::convertToBase64EncodedString)
.toList()
.map(encodedPhotos -> {
if (encodedPhotos.size() > 0) {
String[] encodedPhotosArray = new String[encodedPhotos.size()];
encodedPhotos.toArray(encodedPhotosArray);
return encodedPhotosArray;
} else {
return null;
}
});
} else {
photoObservable = Observable.just(null);
}
Action1<ApiResponse<Integer>> onSuccess = apiResponse -> {
if (apiResponse.getResult() != null) {
String newProblemId = apiResponse.getResult().toString();
myProblemsPreferences
.edit()
.putString(PROBLEM_PREFERENCE_KEY + newProblemId, newProblemId)
.apply();
EventBus.getDefault().post(new NewProblemAddedEvent());
progressDialog.dismiss();
if (reportProblemDescription.hasFocus()) {
KeyboardUtils.closeSoftKeyboard(this, reportProblemDescription);
}
Toast.makeText(this, R.string.problem_successfully_sent, Toast.LENGTH_SHORT).show();
setResult(RESULT_OK);
finish();
}
};
Action1<Throwable> onError = throwable -> {
LogApp.logCrash(throwable);
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), R.string.error_submitting_problem, Toast.LENGTH_SHORT).show();
};
photoObservable
.subscribeOn(Schedulers.io())
.flatMap(encodedPhotos ->
Observable.just(
new GetNewProblemParams.Builder()
.setSessionId(null)
.setDescription(reportProblemDescription.getText().toString())
.setType(reportType.getName())
.setAddress(address)
.setLatitude(locationCords.latitude)
.setLongitude(locationCords.longitude)
.setPhoto(encodedPhotos)
.setEmail(null)
.setPhone(null)
.setMessageDescription(null)
.create())
).map(params -> new ApiRequest<>(ApiMethod.NEW_PROBLEM, params))
.flatMap(request -> legacyApiService.postNewProblem(request))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
onSuccess,
onError
);
}
}
private ProgressDialog createProgressDialog() {
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage(getString(R.string.sending_problem));
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
return progressDialog;
}
private boolean validateProblemInputs() {
boolean addressIsValid = false;
boolean descriptionIsValid = false;
boolean problemTypeIsValid = false;
if (address != null) {
addressIsValid = true;
reportProblemDescriptionWrapper.setError(null);
} else {
reportProblemLocationWrapper.setError(getText(R.string.error_problem_location_is_empty));
}
if (reportProblemDescription.getText() != null && reportProblemDescription.getText().length() > 0) {
descriptionIsValid = true;
} else {
reportProblemDescriptionWrapper.setError(getText(R.string.error_problem_description_is_empty));
}
if (reportType != null) {
problemTypeIsValid = true;
} else {
reportProblemTypeWrapper.setError(getText(R.string.error_problem_type_is_empty));
}
return addressIsValid && descriptionIsValid && problemTypeIsValid;
}
private void openPhotoSelectorDialog() {
AlertDialog.Builder imagePickerDialogBuilder = new AlertDialog.Builder(this, R.style.MyDialogTheme);
View view = LayoutInflater.from(this).inflate(R.layout.image_picker_dialog, null);
TextView cameraButton = ButterKnife.findById(view, R.id.camera_button);
TextView galleryButton = ButterKnife.findById(view, R.id.gallery_button);
imagePickerDialogBuilder
.setTitle(this.getResources().getString(R.string.add_photos))
.setView(view)
.setPositiveButton(R.string.cancel, (dialog, whichButton) -> dialog.dismiss())
.create();
AlertDialog imagePickerDialog = imagePickerDialogBuilder.show();
cameraButton.setOnClickListener(v -> {
launchCamera();
imagePickerDialog.dismiss();
});
galleryButton.setOnClickListener(v -> {
openGallery();
imagePickerDialog.dismiss();
});
}
private void launchCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String timestamp = FormatUtils.formatLocalDateTimeToSeconds(LocalDateTime.now(ZoneOffset.UTC));
photoFileName = "IMG_" + timestamp + ".jpg";
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImageUtils.getTakenPhotoFileUri(this, photoFileName));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
}
private void openGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, GALLERY_REQUEST_CODE);
}
}
@OnClick(R.id.report_problem_take_photo)
public void onTakePhotoClicked() {
if (PermissionUtils.isAllPermissionsGranted(this, LOCATION_PERMISSIONS)) {
openPhotoSelectorDialog();
} else {
ActivityCompat.requestPermissions(this, LOCATION_PERMISSIONS, LOCATION_PERMISSION_REQUEST_CODE);
}
}
@OnClick(R.id.report_problem_type)
public void onChooseProblemTypeClicked() {
Intent intent = new Intent(this, ChooseReportTypeActivity.class);
startActivityForResult(intent, REQUEST_CHOOSE_REPORT_TYPE);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE:
if (PermissionUtils.isAllPermissionsGranted(this, LOCATION_PERMISSIONS)) {
openPhotoSelectorDialog();
} else {
Toast.makeText(this, R.string.error_need_camera_and_storage_permission, Toast.LENGTH_SHORT).show();
}
break;
case MAP_PERMISSION_REQUEST_CODE:
if (PermissionUtils.isAllPermissionsGranted(this, MAP_PERMISSIONS)) {
showPlacePicker(getCurrentFocus());
} else {
Toast.makeText(this, R.string.error_need_location_permission, Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private boolean isEditedByUser() {
return reportProblemDescription.getText().length() > 0 ||
reportProblemPrivacyMode.getSelectedItemPosition() > 0 ||
reportType != null || locationCords != null || imagesURIs != null;
}
@Override
public void onBackPressed() {
if (reportProblemDescription.hasFocus()) {
KeyboardUtils.closeSoftKeyboard(this, reportProblemDescription);
}
if (isEditedByUser()) {
new AlertDialog.Builder(this, R.style.MyDialogTheme)
.setMessage(getString(R.string.discard_changes_title))
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.discard_changes_positive, (dialog, whichButton) ->
NewProblemActivity.super.onBackPressed())
.setNegativeButton(R.string.discard_changes_negative, null).show();
} else {
super.onBackPressed();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_IMAGE_CAPTURE:
Uri takenImageUri = ImageUtils.getTakenPhotoFileUri(this, photoFileName);
setImagesInViewPager(takenImageUri);
break;
case GALLERY_REQUEST_CODE:
ClipData clipData = data.getClipData();
if (clipData != null) {
for (int i = 0; i < clipData.getItemCount(); i++) {
setImagesInViewPager(clipData.getItemAt(i).getUri());
}
} else if (data.getData() != null) {
Uri uri = data.getData();
setImagesInViewPager(uri);
}
break;
case REQUEST_PLACE_PICKER:
Place place = PlacePicker.getPlace(this, data);
LatLng latLng = place.getLatLng();
Geocoder geocoder = new Geocoder(this);
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
} catch (IOException e) {
LogApp.logCrash(e);
}
if (addresses != null && addresses.size() > 0) {
if (addresses.get(0).getLocality() != null) {
String city = addresses.get(0).getLocality();
if (city.equalsIgnoreCase(GlobalConsts.CITY_VILNIUS)) {
address = addresses.get(0).getAddressLine(0);
reportProblemLocationWrapper.setError(null);
addProblemLocation.setText(address);
locationCords = latLng;
if (snackbar != null && snackbar.isShown()) {
snackbar.dismiss();
}
} else {
showIncorrectPlaceSnackbar();
}
}
} else {
showIncorrectPlaceSnackbar();
}
break;
case REQUEST_PROFILE:
profile = Profile.returnProfile(this);
break;
case REQUEST_CHOOSE_REPORT_TYPE:
if (data.hasExtra(EXTRA_REPORT_TYPE)) {
reportType = data.getParcelableExtra(EXTRA_REPORT_TYPE);
reportProblemTypeWrapper.setError(null);
reportProblemType.setText(reportType.getName());
}
break;
}
} else {
switch (requestCode) {
case REQUEST_PROFILE:
reportProblemPrivacyMode.setSelection(0);
break;
case REQUEST_IMAGE_CAPTURE:
Toast.makeText(this, R.string.photo_capture_error, Toast.LENGTH_SHORT).show();
}
}
}
private void setImagesInViewPager(Uri uri) {
imagesURIs.add(uri);
String[] imagesPath = new String[imagesURIs.size()];
for (int i = 0; i < imagesURIs.size(); i++) {
String path = ImageUtils.getPhotoPathFromUri(this, imagesURIs.get(i));
if (path != null) {
imagesPath[i] = new File(path).toString();
} else {
imagesURIs.remove(uri);
Toast.makeText(this, R.string.error_taking_image_from_server, Toast.LENGTH_LONG).show();
}
}
if (imagesURIs.size() > 1) {
problemImagesViewPagerIndicator.setVisibility(View.VISIBLE);
}
if (imagesURIs.size() > 0) {
problemImagesViewPager.setAdapter(new ProblemImagesPagerAdapter<>(this, imagesPath));
}
}
private void showIncorrectPlaceSnackbar() {
View view = this.getCurrentFocus();
snackbar = Snackbar.make(view, R.string.error_location_incorrect, Snackbar.LENGTH_INDEFINITE);
snackbar.setAction(R.string.choose_again, v -> showPlacePicker(view))
.setActionTextColor(ContextCompat.getColor(this, R.color.snackbar_action_text))
.show();
}
@OnClick(R.id.report_problem_location)
public void onProblemLocationClicked(View view) {
if ((PermissionUtils.isAllPermissionsGranted(this, MAP_PERMISSIONS))) {
showPlacePicker(view);
} else {
requestPermissions(MAP_PERMISSIONS, MAP_PERMISSION_REQUEST_CODE);
}
}
@OnItemSelected(R.id.report_problem_privacy_mode)
public void onPrivacyModeSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
profile = null;
break;
case 1:
profile = Profile.returnProfile(this);
if (profile == null) {
Intent intent = new Intent(this, MyProfileActivity.class);
startActivityForResult(intent, REQUEST_PROFILE);
}
break;
}
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return false;
}
private void showPlacePicker(View view) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
Intent intent = builder.build(this);
Bundle bundle = ActivityOptionsCompat.makeScaleUpAnimation(view, 0, 0, view.getWidth(), view.getHeight()).toBundle();
ActivityCompat.startActivityForResult(this, intent, REQUEST_PLACE_PICKER, bundle);
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
LogApp.logCrash(e);
Snackbar.make(view, R.string.check_google_play_services, Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.open, v -> {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com" +
".google.android.gms"));
startActivity(intent);
})
.setActionTextColor(ContextCompat.getColor(this, R.color.snackbar_action_text))
.show();
}
}
}
| Show New report save changes dialog on back pressed only on data change
| app/src/main/java/lt/vilnius/tvarkau/NewProblemActivity.java | Show New report save changes dialog on back pressed only on data change | <ide><path>pp/src/main/java/lt/vilnius/tvarkau/NewProblemActivity.java
<ide> @BindView(R.id.toolbar)
<ide> Toolbar toolbar;
<ide> @BindView(R.id.report_problem_location)
<del> EditText addProblemLocation;
<add> EditText reportProblemLocation;
<ide> @BindView(R.id.problem_images_view_pager)
<ide> ViewPager problemImagesViewPager;
<ide> @BindView(R.id.problem_images_view_pager_indicator)
<ide> }
<ide>
<ide> private boolean isEditedByUser() {
<del> return reportProblemDescription.getText().length() > 0 ||
<del> reportProblemPrivacyMode.getSelectedItemPosition() > 0 ||
<del> reportType != null || locationCords != null || imagesURIs != null;
<add> return reportProblemDescription.getText().length() > 0
<add> || reportProblemLocation.getText().length() > 0
<add> || (reportType != null && reportType.getName() != null)
<add> || (imagesURIs != null && imagesURIs.size() > 0);
<ide> }
<ide>
<ide> @Override
<ide> if (city.equalsIgnoreCase(GlobalConsts.CITY_VILNIUS)) {
<ide> address = addresses.get(0).getAddressLine(0);
<ide> reportProblemLocationWrapper.setError(null);
<del> addProblemLocation.setText(address);
<add> reportProblemLocation.setText(address);
<ide> locationCords = latLng;
<ide> if (snackbar != null && snackbar.isShown()) {
<ide> snackbar.dismiss(); |
|
Java | bsd-3-clause | 46fb92d3a5e92a2f4abb9ffc8b4901f38545dd50 | 0 | smartdevicelink/sdl_android | /*
* Copyright (c) 2017 - 2019, SmartDeviceLink Consortium, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 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.
*
* Neither the name of the SmartDeviceLink Consortium, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.smartdevicelink.proxy.rpc;
import androidx.annotation.NonNull;
import com.smartdevicelink.proxy.RPCStruct;
import com.smartdevicelink.proxy.rpc.enums.CompassDirection;
import com.smartdevicelink.proxy.rpc.enums.Dimension;
import com.smartdevicelink.util.SdlDataTypeConverter;
import java.util.Hashtable;
/**
* Describes the GPS data. Not all data will be available on all carlines.
* <p><b>Parameter List</b></p>
* <table border="1" rules="all">
* <tr>
* <th>Name</th>
* <th>Type</th>
* <th>Description</th>
* <th>SmartDeviceLink Ver. Available</th>
* </tr>
* <tr>
* <td>longitudeDegrees</td>
* <td>Double</td>
* <td>Minvalue: - 180
* <b>Maxvalue: 180
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>latitudeDegrees</td>
* <td>Double</td>
* <td>Minvalue: - 90<b>Maxvalue: 90
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>utcYear</td>
* <td>Integer</td>
* <td>Minvalue: 2010<b>Maxvalue: 2100
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>utcMonth</td>
* <td>Integer</td>
* <td>Minvalue: 1<b>Maxvalue: 12
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>utcDay</td>
* <td>Integer</td>
* <td>Minvalue: 1<b>Maxvalue: 31
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>utcHours</td>
* <td>Integer</td>
* <td>Minvalue: 0<b>Maxvalue: 23
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>utcMinutes</td>
* <td>Integer</td>
* <td>Minvalue: 0<b>Maxvalue: 59
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>utcSeconds</td>
* <td>Integer</td>
* <td>Minvalue: 0<b>Maxvalue: 59
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>pdop</td>
* <td>Integer</td>
* <td>Positional Dilution of Precision. If undefined or unavailable, then value shall be set to 0.<b>Minvalue: 0<b>Maxvalue: 1000
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>hdop</td>
* <td>Integer</td>
* <td>Horizontal Dilution of Precision. If value is unknown, value shall be set to 0.<b>Minvalue: 0<b>Maxvalue: 1000
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>vdop</td>
* <td>Integer</td>
* <td>Vertical Dilution of Precision. If value is unknown, value shall be set to 0.<b>Minvalue: 0<b>Maxvalue: 1000
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>actual</td>
* <td>Boolean</td>
* <td>True, if coordinates are based on satellites.
* False, if based on dead reckoning
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>satellites</td>
* <td>Integer</td>
* <td>Number of satellites in view
* <b>Minvalue: 0
* <b>Maxvalue: 31
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>altitude</td>
* <td>Integer</td>
* <td>Altitude in meters
* <b>Minvalue: -10000</b>
* <b>Maxvalue: 10000</b>
* <b>Note:</b> SYNC uses Mean Sea Level for calculating GPS. </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>heading</td>
* <td>Double</td>
* <td>The heading. North is 0, East is 90, etc.
* <b>Minvalue: 0
* <b>Maxvalue: 359.99
* <b>Resolution is 0.01
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>speed</td>
* <td>Integer</td>
* <td>The speed in KPH
* <b>Minvalue: 0
* <b>Maxvalue: 500
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* </table>
* @since SmartDeviceLink 2.0
*/
public class GPSData extends RPCStruct {
public static final String KEY_LONGITUDE_DEGREES = "longitudeDegrees";
public static final String KEY_LATITUDE_DEGREES = "latitudeDegrees";
public static final String KEY_UTC_YEAR = "utcYear";
public static final String KEY_UTC_MONTH = "utcMonth";
public static final String KEY_UTC_DAY = "utcDay";
public static final String KEY_UTC_HOURS = "utcHours";
public static final String KEY_UTC_MINUTES = "utcMinutes";
public static final String KEY_UTC_SECONDS = "utcSeconds";
public static final String KEY_COMPASS_DIRECTION = "compassDirection";
public static final String KEY_PDOP = "pdop";
public static final String KEY_VDOP = "vdop";
public static final String KEY_HDOP = "hdop";
public static final String KEY_ACTUAL = "actual";
public static final String KEY_SATELLITES = "satellites";
public static final String KEY_DIMENSION = "dimension";
public static final String KEY_ALTITUDE = "altitude";
public static final String KEY_HEADING = "heading";
public static final String KEY_SPEED = "speed";
public static final String KEY_SHIFTED = "shifted";
/**
* Constructs a newly allocated GPSData object
*/
public GPSData() { }
/**
* Constructs a newly allocated GPSData object indicated by the Hashtable parameter
* @param hash The Hashtable to use
*/
public GPSData(Hashtable<String, Object> hash) {
super(hash);
}
/**
* Constructs a newly allocated GPSData object
*/
public GPSData(@NonNull Double longitudeDegrees, @NonNull Double latitudeDegrees) {
this();
setLongitudeDegrees(longitudeDegrees);
setLatitudeDegrees(latitudeDegrees);
}
/**
* set longitude degrees
* @param longitudeDegrees degrees of the longitudinal position
*/
public void setLongitudeDegrees(@NonNull Double longitudeDegrees) {
setValue(KEY_LONGITUDE_DEGREES, longitudeDegrees);
}
/**
* get longitude degrees
* @return longitude degrees
*/
public Double getLongitudeDegrees() {
Object object = getValue(KEY_LONGITUDE_DEGREES);
return SdlDataTypeConverter.objectToDouble(object);
}
/**
* set latitude degrees
* @param latitudeDegrees degrees of the latitudinal position
*/
public void setLatitudeDegrees(@NonNull Double latitudeDegrees) {
setValue(KEY_LATITUDE_DEGREES, latitudeDegrees);
}
/**
* get latitude degrees
* @return latitude degrees
*/
public Double getLatitudeDegrees() {
Object object = getValue(KEY_LATITUDE_DEGREES);
return SdlDataTypeConverter.objectToDouble(object);
}
/**
* set utc year
* @param utcYear utc year
*/
public void setUtcYear(Integer utcYear) {
setValue(KEY_UTC_YEAR, utcYear);
}
/**
* get utc year
* @return utc year
*/
public Integer getUtcYear() {
return getInteger(KEY_UTC_YEAR);
}
/**
* set utc month
* @param utcMonth utc month
*/
public void setUtcMonth(Integer utcMonth) {
setValue(KEY_UTC_MONTH, utcMonth);
}
/**
* get utc month
* @return utc month
*/
public Integer getUtcMonth() {
return getInteger(KEY_UTC_MONTH);
}
/**
* set utc day
* @param utcDay utc day
*/
public void setUtcDay(Integer utcDay) {
setValue(KEY_UTC_DAY, utcDay);
}
/**
* get utc day
* @return utc day
*/
public Integer getUtcDay() {
return getInteger(KEY_UTC_DAY);
}
/**
* set utc hours
* @param utcHours utc hours
*/
public void setUtcHours(Integer utcHours) {
setValue(KEY_UTC_HOURS, utcHours);
}
/**
* get utc hours
* @return utc hours
*/
public Integer getUtcHours() {
return getInteger(KEY_UTC_HOURS);
}
/**
* set utc minutes
* @param utcMinutes utc minutes
*/
public void setUtcMinutes(Integer utcMinutes) {
setValue(KEY_UTC_MINUTES, utcMinutes);
}
/**
* get utc minutes
* @return utc minutes
*/
public Integer getUtcMinutes() {
return getInteger(KEY_UTC_MINUTES);
}
/**
* set utc seconds
* @param utcSeconds utc seconds
*/
public void setUtcSeconds(Integer utcSeconds) {
setValue(KEY_UTC_SECONDS, utcSeconds);
}
/**
* get utc seconds
* @return utc seconds
*/
public Integer getUtcSeconds() {
return getInteger(KEY_UTC_SECONDS);
}
public void setCompassDirection(CompassDirection compassDirection) {
setValue(KEY_COMPASS_DIRECTION, compassDirection);
}
public CompassDirection getCompassDirection() {
return (CompassDirection) getObject(CompassDirection.class, KEY_COMPASS_DIRECTION);
}
/**
* set the positional dilution of precision
* @param pdop the positional dilution of precision
*/
public void setPdop(Double pdop) {
setValue(KEY_PDOP, pdop);
}
/**
* get the positional dilution of precision
*/
public Double getPdop() {
Object object = getValue(KEY_PDOP);
return SdlDataTypeConverter.objectToDouble(object);
}
/**
* set the horizontal dilution of precision
* @param hdop the horizontal dilution of precision
*/
public void setHdop(Double hdop) {
setValue(KEY_HDOP, hdop);
}
/**
* get the horizontal dilution of precision
* @return the horizontal dilution of precision
*/
public Double getHdop() {
Object object = getValue(KEY_HDOP);
return SdlDataTypeConverter.objectToDouble(object);
}
/**
* set the vertical dilution of precision
* @param vdop the vertical dilution of precision
*/
public void setVdop(Double vdop) {
setValue(KEY_VDOP, vdop);
}
/**
* get the vertical dilution of precision
* @return the vertical dilution of precision
*/
public Double getVdop() {
Object object = getValue(KEY_VDOP);
return SdlDataTypeConverter.objectToDouble(object);
}
/**
* set what coordinates based on
* @param actual True, if coordinates are based on satellites.False, if based on dead reckoning
*/
public void setActual(Boolean actual) {
setValue(KEY_ACTUAL, actual);
}
/**
* get what coordinates based on
* @return True, if coordinates are based on satellites.False, if based on dead reckoning
*/
public Boolean getActual() {
return getBoolean(KEY_ACTUAL);
}
/**
* set the number of satellites in view
* @param satellites the number of satellites in view
*/
public void setSatellites(Integer satellites) {
setValue(KEY_SATELLITES, satellites);
}
/**
* get the number of satellites in view
* @return the number of satellites in view
*/
public Integer getSatellites() {
return getInteger(KEY_SATELLITES);
}
public void setDimension(Dimension dimension) {
setValue(KEY_DIMENSION, dimension);
}
public Dimension getDimension() {
return (Dimension) getObject(Dimension.class, KEY_DIMENSION);
}
/**
* set altitude in meters
* @param altitude altitude in meters
*/
public void setAltitude(Double altitude) {
setValue(KEY_ALTITUDE, altitude);
}
/**
* get altitude in meters
* @return altitude in meters
*/
public Double getAltitude() {
Object object = getValue(KEY_ALTITUDE);
return SdlDataTypeConverter.objectToDouble(object);
}
/**
* set the heading.North is 0, East is 90, etc.
* @param heading the heading.
*/
public void setHeading(Double heading) {
setValue(KEY_HEADING, heading);
}
/**
* get the heading
*/
public Double getHeading() {
Object object = getValue(KEY_HEADING);
return SdlDataTypeConverter.objectToDouble(object);
}
/**
* set speed in KPH
* @param speed the speed
*/
public void setSpeed(Double speed) {
setValue(KEY_SPEED, speed);
}
/**
* get the speed in KPH
* @return the speed in KPH
*/
public Double getSpeed() {
Object object = getValue(KEY_SPEED);
return SdlDataTypeConverter.objectToDouble(object);
}
/**
* Sets the shifted param for GPSData.
* @param shifted True, if GPS lat/long, time, and altitude have been purposefully shifted (requires a proprietary algorithm to unshift).
* False, if the GPS data is raw and un-shifted.
* If not provided, then value is assumed False.
*/
public void setShifted(Boolean shifted) {
setValue(KEY_SHIFTED, shifted);
}
/**
* Gets the shifted param for GPSData.
* @return Boolean - True, if GPS lat/long, time, and altitude have been purposefully shifted (requires a proprietary algorithm to unshift).
*/
public Boolean getShifted() {
return getBoolean(KEY_SHIFTED);
}
}
| base/src/main/java/com/smartdevicelink/proxy/rpc/GPSData.java | /*
* Copyright (c) 2017 - 2019, SmartDeviceLink Consortium, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 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.
*
* Neither the name of the SmartDeviceLink Consortium, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.smartdevicelink.proxy.rpc;
import androidx.annotation.NonNull;
import com.smartdevicelink.proxy.RPCStruct;
import com.smartdevicelink.proxy.rpc.enums.CompassDirection;
import com.smartdevicelink.proxy.rpc.enums.Dimension;
import com.smartdevicelink.util.SdlDataTypeConverter;
import java.util.Hashtable;
/**
* Describes the GPS data. Not all data will be available on all carlines.
* <p><b>Parameter List</b></p>
* <table border="1" rules="all">
* <tr>
* <th>Name</th>
* <th>Type</th>
* <th>Description</th>
* <th>SmartDeviceLink Ver. Available</th>
* </tr>
* <tr>
* <td>longitudeDegrees</td>
* <td>Double</td>
* <td>Minvalue: - 180
* <b>Maxvalue: 180
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>latitudeDegrees</td>
* <td>Double</td>
* <td>Minvalue: - 90<b>Maxvalue: 90
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>utcYear</td>
* <td>Integer</td>
* <td>Minvalue: 2010<b>Maxvalue: 2100
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>utcMonth</td>
* <td>Integer</td>
* <td>Minvalue: 1<b>Maxvalue: 12
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>utcDay</td>
* <td>Integer</td>
* <td>Minvalue: 1<b>Maxvalue: 31
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>utcHours</td>
* <td>Integer</td>
* <td>Minvalue: 0<b>Maxvalue: 23
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>utcMinutes</td>
* <td>Integer</td>
* <td>Minvalue: 0<b>Maxvalue: 59
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>utcSeconds</td>
* <td>Integer</td>
* <td>Minvalue: 0<b>Maxvalue: 59
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>pdop</td>
* <td>Integer</td>
* <td>Positional Dilution of Precision. If undefined or unavailable, then value shall be set to 0.<b>Minvalue: 0<b>Maxvalue: 1000
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>hdop</td>
* <td>Integer</td>
* <td>Horizontal Dilution of Precision. If value is unknown, value shall be set to 0.<b>Minvalue: 0<b>Maxvalue: 1000
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>vdop</td>
* <td>Integer</td>
* <td>Vertical Dilution of Precision. If value is unknown, value shall be set to 0.<b>Minvalue: 0<b>Maxvalue: 1000
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>actual</td>
* <td>Boolean</td>
* <td>True, if coordinates are based on satellites.
* False, if based on dead reckoning
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>satellites</td>
* <td>Integer</td>
* <td>Number of satellites in view
* <b>Minvalue: 0
* <b>Maxvalue: 31
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>altitude</td>
* <td>Integer</td>
* <td>Altitude in meters
* <b>Minvalue: -10000</b>
* <b>Maxvalue: 10000</b>
* <b>Note:</b> SYNC uses Mean Sea Level for calculating GPS. </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>heading</td>
* <td>Double</td>
* <td>The heading. North is 0, East is 90, etc.
* <b>Minvalue: 0
* <b>Maxvalue: 359.99
* <b>Resolution is 0.01
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* <tr>
* <td>speed</td>
* <td>Integer</td>
* <td>The speed in KPH
* <b>Minvalue: 0
* <b>Maxvalue: 500
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* </table>
* @since SmartDeviceLink 2.0
*/
public class GPSData extends RPCStruct {
public static final String KEY_LONGITUDE_DEGREES = "longitudeDegrees";
public static final String KEY_LATITUDE_DEGREES = "latitudeDegrees";
public static final String KEY_UTC_YEAR = "utcYear";
public static final String KEY_UTC_MONTH = "utcMonth";
public static final String KEY_UTC_DAY = "utcDay";
public static final String KEY_UTC_HOURS = "utcHours";
public static final String KEY_UTC_MINUTES = "utcMinutes";
public static final String KEY_UTC_SECONDS = "utcSeconds";
public static final String KEY_COMPASS_DIRECTION = "compassDirection";
public static final String KEY_PDOP = "pdop";
public static final String KEY_VDOP = "vdop";
public static final String KEY_HDOP = "hdop";
public static final String KEY_ACTUAL = "actual";
public static final String KEY_SATELLITES = "satellites";
public static final String KEY_DIMENSION = "dimension";
public static final String KEY_ALTITUDE = "altitude";
public static final String KEY_HEADING = "heading";
public static final String KEY_SPEED = "speed";
public static final String KEY_SHIFTED = "shifted";
/**
* Constructs a newly allocated GPSData object
*/
public GPSData() { }
/**
* Constructs a newly allocated GPSData object indicated by the Hashtable parameter
* @param hash The Hashtable to use
*/
public GPSData(Hashtable<String, Object> hash) {
super(hash);
}
/**
* Constructs a newly allocated GPSData object
* @deprecated Use {@link #GPSData(@NonNull Double, @NonNull Double)()} instead
*/
@Deprecated
public GPSData(@NonNull Double longitudeDegrees, @NonNull Double latitudeDegrees, @NonNull Integer utcYear,
@NonNull Integer utcMonth, @NonNull Integer utcDay, @NonNull Integer utcHours,
@NonNull Integer utcMinutes, @NonNull Integer utcSeconds, @NonNull CompassDirection compassDirection,
@NonNull Double pdop, @NonNull Double hdop, @NonNull Double vdop, @NonNull Boolean actual,
@NonNull Integer satellites, @NonNull Dimension dimension, @NonNull Double altitude, @NonNull Double heading, @NonNull Double speed) {
this();
setLongitudeDegrees(longitudeDegrees);
setLatitudeDegrees(latitudeDegrees);
setUtcYear(utcYear);
setUtcMonth(utcMonth);
setUtcDay(utcDay);
setUtcHours(utcHours);
setUtcMinutes(utcMinutes);
setUtcSeconds(utcSeconds);
setCompassDirection(compassDirection);
setPdop(pdop);
setHdop(hdop);
setVdop(vdop);
setActual(actual);
setSatellites(satellites);
setDimension(dimension);
setAltitude(altitude);
setHeading(heading);
setSpeed(speed);
}
/**
* Constructs a newly allocated GPSData object
*/
public GPSData(@NonNull Double longitudeDegrees, @NonNull Double latitudeDegrees) {
this();
setLongitudeDegrees(longitudeDegrees);
setLatitudeDegrees(latitudeDegrees);
}
/**
* set longitude degrees
* @param longitudeDegrees degrees of the longitudinal position
*/
public void setLongitudeDegrees(@NonNull Double longitudeDegrees) {
setValue(KEY_LONGITUDE_DEGREES, longitudeDegrees);
}
/**
* get longitude degrees
* @return longitude degrees
*/
public Double getLongitudeDegrees() {
Object object = getValue(KEY_LONGITUDE_DEGREES);
return SdlDataTypeConverter.objectToDouble(object);
}
/**
* set latitude degrees
* @param latitudeDegrees degrees of the latitudinal position
*/
public void setLatitudeDegrees(@NonNull Double latitudeDegrees) {
setValue(KEY_LATITUDE_DEGREES, latitudeDegrees);
}
/**
* get latitude degrees
* @return latitude degrees
*/
public Double getLatitudeDegrees() {
Object object = getValue(KEY_LATITUDE_DEGREES);
return SdlDataTypeConverter.objectToDouble(object);
}
/**
* set utc year
* @param utcYear utc year
*/
public void setUtcYear(Integer utcYear) {
setValue(KEY_UTC_YEAR, utcYear);
}
/**
* get utc year
* @return utc year
*/
public Integer getUtcYear() {
return getInteger(KEY_UTC_YEAR);
}
/**
* set utc month
* @param utcMonth utc month
*/
public void setUtcMonth(Integer utcMonth) {
setValue(KEY_UTC_MONTH, utcMonth);
}
/**
* get utc month
* @return utc month
*/
public Integer getUtcMonth() {
return getInteger(KEY_UTC_MONTH);
}
/**
* set utc day
* @param utcDay utc day
*/
public void setUtcDay(Integer utcDay) {
setValue(KEY_UTC_DAY, utcDay);
}
/**
* get utc day
* @return utc day
*/
public Integer getUtcDay() {
return getInteger(KEY_UTC_DAY);
}
/**
* set utc hours
* @param utcHours utc hours
*/
public void setUtcHours(Integer utcHours) {
setValue(KEY_UTC_HOURS, utcHours);
}
/**
* get utc hours
* @return utc hours
*/
public Integer getUtcHours() {
return getInteger(KEY_UTC_HOURS);
}
/**
* set utc minutes
* @param utcMinutes utc minutes
*/
public void setUtcMinutes(Integer utcMinutes) {
setValue(KEY_UTC_MINUTES, utcMinutes);
}
/**
* get utc minutes
* @return utc minutes
*/
public Integer getUtcMinutes() {
return getInteger(KEY_UTC_MINUTES);
}
/**
* set utc seconds
* @param utcSeconds utc seconds
*/
public void setUtcSeconds(Integer utcSeconds) {
setValue(KEY_UTC_SECONDS, utcSeconds);
}
/**
* get utc seconds
* @return utc seconds
*/
public Integer getUtcSeconds() {
return getInteger(KEY_UTC_SECONDS);
}
public void setCompassDirection(CompassDirection compassDirection) {
setValue(KEY_COMPASS_DIRECTION, compassDirection);
}
public CompassDirection getCompassDirection() {
return (CompassDirection) getObject(CompassDirection.class, KEY_COMPASS_DIRECTION);
}
/**
* set the positional dilution of precision
* @param pdop the positional dilution of precision
*/
public void setPdop(Double pdop) {
setValue(KEY_PDOP, pdop);
}
/**
* get the positional dilution of precision
*/
public Double getPdop() {
Object object = getValue(KEY_PDOP);
return SdlDataTypeConverter.objectToDouble(object);
}
/**
* set the horizontal dilution of precision
* @param hdop the horizontal dilution of precision
*/
public void setHdop(Double hdop) {
setValue(KEY_HDOP, hdop);
}
/**
* get the horizontal dilution of precision
* @return the horizontal dilution of precision
*/
public Double getHdop() {
Object object = getValue(KEY_HDOP);
return SdlDataTypeConverter.objectToDouble(object);
}
/**
* set the vertical dilution of precision
* @param vdop the vertical dilution of precision
*/
public void setVdop(Double vdop) {
setValue(KEY_VDOP, vdop);
}
/**
* get the vertical dilution of precision
* @return the vertical dilution of precision
*/
public Double getVdop() {
Object object = getValue(KEY_VDOP);
return SdlDataTypeConverter.objectToDouble(object);
}
/**
* set what coordinates based on
* @param actual True, if coordinates are based on satellites.False, if based on dead reckoning
*/
public void setActual(Boolean actual) {
setValue(KEY_ACTUAL, actual);
}
/**
* get what coordinates based on
* @return True, if coordinates are based on satellites.False, if based on dead reckoning
*/
public Boolean getActual() {
return getBoolean(KEY_ACTUAL);
}
/**
* set the number of satellites in view
* @param satellites the number of satellites in view
*/
public void setSatellites(Integer satellites) {
setValue(KEY_SATELLITES, satellites);
}
/**
* get the number of satellites in view
* @return the number of satellites in view
*/
public Integer getSatellites() {
return getInteger(KEY_SATELLITES);
}
public void setDimension(Dimension dimension) {
setValue(KEY_DIMENSION, dimension);
}
public Dimension getDimension() {
return (Dimension) getObject(Dimension.class, KEY_DIMENSION);
}
/**
* set altitude in meters
* @param altitude altitude in meters
*/
public void setAltitude(Double altitude) {
setValue(KEY_ALTITUDE, altitude);
}
/**
* get altitude in meters
* @return altitude in meters
*/
public Double getAltitude() {
Object object = getValue(KEY_ALTITUDE);
return SdlDataTypeConverter.objectToDouble(object);
}
/**
* set the heading.North is 0, East is 90, etc.
* @param heading the heading.
*/
public void setHeading(Double heading) {
setValue(KEY_HEADING, heading);
}
/**
* get the heading
*/
public Double getHeading() {
Object object = getValue(KEY_HEADING);
return SdlDataTypeConverter.objectToDouble(object);
}
/**
* set speed in KPH
* @param speed the speed
*/
public void setSpeed(Double speed) {
setValue(KEY_SPEED, speed);
}
/**
* get the speed in KPH
* @return the speed in KPH
*/
public Double getSpeed() {
Object object = getValue(KEY_SPEED);
return SdlDataTypeConverter.objectToDouble(object);
}
/**
* Sets the shifted param for GPSData.
* @param shifted True, if GPS lat/long, time, and altitude have been purposefully shifted (requires a proprietary algorithm to unshift).
* False, if the GPS data is raw and un-shifted.
* If not provided, then value is assumed False.
*/
public void setShifted(Boolean shifted) {
setValue(KEY_SHIFTED, shifted);
}
/**
* Gets the shifted param for GPSData.
* @return Boolean - True, if GPS lat/long, time, and altitude have been purposefully shifted (requires a proprietary algorithm to unshift).
*/
public Boolean getShifted() {
return getBoolean(KEY_SHIFTED);
}
}
| Remove deprecated constructor from GPSData
| base/src/main/java/com/smartdevicelink/proxy/rpc/GPSData.java | Remove deprecated constructor from GPSData | <ide><path>ase/src/main/java/com/smartdevicelink/proxy/rpc/GPSData.java
<ide>
<ide> /**
<ide> * Constructs a newly allocated GPSData object
<del> * @deprecated Use {@link #GPSData(@NonNull Double, @NonNull Double)()} instead
<del> */
<del> @Deprecated
<del> public GPSData(@NonNull Double longitudeDegrees, @NonNull Double latitudeDegrees, @NonNull Integer utcYear,
<del> @NonNull Integer utcMonth, @NonNull Integer utcDay, @NonNull Integer utcHours,
<del> @NonNull Integer utcMinutes, @NonNull Integer utcSeconds, @NonNull CompassDirection compassDirection,
<del> @NonNull Double pdop, @NonNull Double hdop, @NonNull Double vdop, @NonNull Boolean actual,
<del> @NonNull Integer satellites, @NonNull Dimension dimension, @NonNull Double altitude, @NonNull Double heading, @NonNull Double speed) {
<del> this();
<del> setLongitudeDegrees(longitudeDegrees);
<del> setLatitudeDegrees(latitudeDegrees);
<del> setUtcYear(utcYear);
<del> setUtcMonth(utcMonth);
<del> setUtcDay(utcDay);
<del> setUtcHours(utcHours);
<del> setUtcMinutes(utcMinutes);
<del> setUtcSeconds(utcSeconds);
<del> setCompassDirection(compassDirection);
<del> setPdop(pdop);
<del> setHdop(hdop);
<del> setVdop(vdop);
<del> setActual(actual);
<del> setSatellites(satellites);
<del> setDimension(dimension);
<del> setAltitude(altitude);
<del> setHeading(heading);
<del> setSpeed(speed);
<del> }
<del>
<del> /**
<del> * Constructs a newly allocated GPSData object
<ide> */
<ide> public GPSData(@NonNull Double longitudeDegrees, @NonNull Double latitudeDegrees) {
<ide> this(); |
|
Java | mit | e352c1fe713824cffaf70a874d1d68b7bd8f92c7 | 0 | jenkinsci/authentication-tokens-plugin | /*
* The MIT License
*
* Copyright (c) 2015, CloudBees, Inc., Stephen Connolly.
*
* 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.authentication.tokens.api;
import com.cloudbees.plugins.credentials.Credentials;
import com.cloudbees.plugins.credentials.CredentialsMatcher;
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.ExtensionList;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
/**
* Utility class for manipulating authentication tokens.
*
* @since 1.0
*/
public final class AuthenticationTokens {
/**
* Our logger.
*/
private static final Logger LOGGER = Logger.getLogger(AuthenticationTokens.class.getName());
/**
* Do not instantiate this utility class.
*/
private AuthenticationTokens() {
throw new IllegalAccessError("Utility class");
}
/**
* Builds a matcher for credentials that can be converted into the supplied token type.
*
* @param tokenClass the type of token
* @param <T> the type of token
* @return a matcher for the type of token
*/
public static <T> CredentialsMatcher matcher(Class<T> tokenClass) {
return matcher(new AuthenticationTokenContext<T>(tokenClass));
}
/**
* Builds a matcher for credentials that can be converted into the supplied token type.
*
* @param context the context that an authentication token is required in.
* @param <T> the type of token.
* @return a matcher for the type of token.
* @since 1.2
*/
public static <T> CredentialsMatcher matcher(AuthenticationTokenContext<T> context) {
List<CredentialsMatcher> matchers = new ArrayList<CredentialsMatcher>();
for (AuthenticationTokenSource<?, ?> source : ExtensionList.lookup(AuthenticationTokenSource.class)) {
if (source.fits(context)) {
matchers.add(source.matcher());
}
}
return matchers.isEmpty()
? CredentialsMatchers.never()
: CredentialsMatchers.anyOf(matchers.toArray(new CredentialsMatcher[matchers.size()]));
}
/**
* Converts the supplied credentials into the specified token.
*
* @param type the type of token to convert to.
* @param credentials the credentials instance to convert.
* @param <T> the type of token to convert to.
* @param <C> the type of credentials to convert,
* @return the token or {@code null} if the credentials could not be converted.
*/
@SuppressWarnings("unchecked")
@CheckForNull
public static <T, C extends Credentials> T convert(@NonNull Class<T> type, @CheckForNull C credentials) {
if (credentials == null) {
return null;
}
return convert(new AuthenticationTokenContext<T>(type), credentials);
}
/**
* Converts the supplied credentials into the specified token.
*
* @param context the context that an authentication token is required in.
* @param credentials the credentials instance to convert.
* @param <T> the type of token to convert to.
* @param <C> the type of credentials to convert,
* @return the token or {@code null} if the credentials could not be converted.
* @since 1.2
*/
@SuppressWarnings("unchecked")
@CheckForNull
public static <T, C extends Credentials> T convert(@NonNull AuthenticationTokenContext<T> context, @CheckForNull C credentials) {
if (credentials == null) {
return null;
}
// we want the best match first
SortedMap<Integer,AuthenticationTokenSource> matches = new TreeMap<Integer, AuthenticationTokenSource>(
Collections.reverseOrder());
for (AuthenticationTokenSource<?, ?> source : ExtensionList.lookup(AuthenticationTokenSource.class)) {
Integer score = source.score(context, credentials);
if (score != null && !matches.containsKey(score)) {
// if there are two extensions with the same score,
// then the first (i.e. highest Extension.ordinal should win)
matches.put(score, source);
}
}
// now try all the matches (form best to worst) until we get a conversion
for (AuthenticationTokenSource<?,?> source: matches.values()) {
if (source.produces(context.getTokenClass()) && source.consumes(credentials)) { // redundant test, but for safety
AuthenticationTokenSource<? extends T, ? super C> s =
(AuthenticationTokenSource<? extends T, ? super C>) source;
T token = null;
try {
token = s.convert(credentials);
} catch (AuthenticationTokenException e) {
LogRecord lr = new LogRecord(Level.FINE,
"Could not convert credentials {0} into token of type {1} using source {2}: {3}");
lr.setThrown(e);
lr.setParameters(new Object[]{credentials, context.getTokenClass(), s, e.getMessage()});
LOGGER.log(lr);
}
if (token != null) {
return token;
}
}
}
return null;
}
/**
* Converts the best match of the supplied credentials into the specified token.
*
* @param context the context that an authentication token is required in.
* @param credentials the credentials instances to try and convert.
* @param <T> the type of token to convert to.
* @param <C> the type of credentials to convert,
* @return the token or {@code null} if the credentials could not be converted.
* @since 1.2
*/
@SuppressWarnings("unchecked")
@CheckForNull
public static <T, C extends Credentials> T convert(@NonNull AuthenticationTokenContext<T> context,
@NonNull C... credentials) {
return convert(context, Arrays.asList(credentials));
}
/**
* Converts the best match of the supplied credentials into the specified token.
*
* @param context the context that an authentication token is required in.
* @param credentials the credentials instances to try and convert.
* @param <T> the type of token to convert to.
* @param <C> the type of credentials to convert,
* @return the token or {@code null} if the credentials could not be converted.
* @since 1.2
*/
@SuppressWarnings("unchecked")
@CheckForNull
public static <T, C extends Credentials> T convert(@NonNull AuthenticationTokenContext<T> context,
@NonNull List<C> credentials) {
// we want the best match first
SortedMap<Integer, Map.Entry<C, AuthenticationTokenSource>> matches =
new TreeMap<Integer, Map.Entry<C, AuthenticationTokenSource>>(
Collections.reverseOrder());
for (C credential : credentials) {
for (AuthenticationTokenSource<?, ?> source : ExtensionList.lookup(AuthenticationTokenSource.class)) {
Integer score = source.score(context, credential);
if (score != null && !matches.containsKey(score)) {
// if there are two extensions with the same score,
// then the first (i.e. highest Extension.ordinal should win)
// if there are two credentials with the same scoe,
// then the first in the list should win.
matches.put(score, new AbstractMap.SimpleEntry<C, AuthenticationTokenSource>(credential, source));
}
}
}
// now try all the matches (form best to worst) until we get a conversion
for (Map.Entry<C, AuthenticationTokenSource> entry : matches.values()) {
C credential = entry.getKey();
AuthenticationTokenSource source = entry.getValue();
if (source.produces(context.getTokenClass()) && source
.consumes(credential)) { // redundant test, but for safety
AuthenticationTokenSource<? extends T, ? super C> s =
(AuthenticationTokenSource<? extends T, ? super C>) source;
T token = null;
try {
token = s.convert(credential);
} catch (AuthenticationTokenException e) {
LogRecord lr = new LogRecord(Level.FINE,
"Could not convert credentials {0} into token of type {1} using source {2}: {3}");
lr.setThrown(e);
lr.setParameters(new Object[]{credentials, context.getTokenClass(), s, e.getMessage()});
LOGGER.log(lr);
}
if (token != null) {
return token;
}
}
}
return null;
}
}
| src/main/java/jenkins/authentication/tokens/api/AuthenticationTokens.java | /*
* The MIT License
*
* Copyright (c) 2015, CloudBees, Inc., Stephen Connolly.
*
* 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.authentication.tokens.api;
import com.cloudbees.plugins.credentials.Credentials;
import com.cloudbees.plugins.credentials.CredentialsMatcher;
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.ExtensionList;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
/**
* Utility class for manipulating authentication tokens.
*
* @since 1.0
*/
public final class AuthenticationTokens {
/**
* Our logger.
*/
private static final Logger LOGGER = Logger.getLogger(AuthenticationTokens.class.getName());
/**
* Do not instantiate this utility class.
*/
private AuthenticationTokens() {
throw new IllegalAccessError("Utility class");
}
/**
* Builds a matcher for credentials that can be converted into the supplied token type.
*
* @param tokenClass the type of token
* @param <T> the type of token
* @return a matcher for the type of token
*/
public static <T> CredentialsMatcher matcher(Class<T> tokenClass) {
return matcher(new AuthenticationTokenContext<T>(tokenClass));
}
/**
* Builds a matcher for credentials that can be converted into the supplied token type.
*
* @param context the context that an authentication token is required in.
* @param <T> the type of token.
* @return a matcher for the type of token.
* @since 1.2
*/
public static <T> CredentialsMatcher matcher(AuthenticationTokenContext<T> context) {
List<CredentialsMatcher> matchers = new ArrayList<CredentialsMatcher>();
for (AuthenticationTokenSource<?, ?> source : ExtensionList.lookup(AuthenticationTokenSource.class)) {
if (source.fits(context)) {
matchers.add(source.matcher());
}
}
return matchers.isEmpty()
? CredentialsMatchers.never()
: CredentialsMatchers.anyOf(matchers.toArray(new CredentialsMatcher[matchers.size()]));
}
/**
* Converts the supplied credentials into the specified token.
*
* @param type the type of token to convert to.
* @param credentials the credentials instance to convert.
* @param <T> the type of token to convert to.
* @param <C> the type of credentials to convert,
* @return the token or {@code null} if the credentials could not be converted.
*/
@SuppressWarnings("unchecked")
@CheckForNull
public static <T, C extends Credentials> T convert(@NonNull Class<T> type, @CheckForNull C credentials) {
if (credentials == null) {
return null;
}
return convert(new AuthenticationTokenContext<T>(type), credentials);
}
/**
* Converts the supplied credentials into the specified token.
*
* @param context the context that an authentication token is required in.
* @param credentials the credentials instance to convert.
* @param <T> the type of token to convert to.
* @param <C> the type of credentials to convert,
* @return the token or {@code null} if the credentials could not be converted.
* @since 1.2
*/
@SuppressWarnings("unchecked")
@CheckForNull
public static <T, C extends Credentials> T convert(@NonNull AuthenticationTokenContext<T> context, @CheckForNull C credentials) {
if (credentials == null) {
return null;
}
// we want the best match first
SortedMap<Integer,AuthenticationTokenSource> matches = new TreeMap<Integer, AuthenticationTokenSource>(
Collections.reverseOrder());
for (AuthenticationTokenSource<?, ?> source : ExtensionList.lookup(AuthenticationTokenSource.class)) {
Integer score = source.score(context, credentials);
if (score != null && !matches.containsKey(score)) {
// if there are two extensions with the same score,
// then the first (i.e. highest Extension.ordinal should win)
matches.put(score, source);
}
}
// now try all the matches (form best to worst) until we get a conversion
for (AuthenticationTokenSource<?,?> source: matches.values()) {
if (source.produces(context.getTokenClass()) && source.consumes(credentials)) { // redundant test, but for safety
AuthenticationTokenSource<? extends T, ? super C> s =
(AuthenticationTokenSource<? extends T, ? super C>) source;
T token = null;
try {
token = s.convert(credentials);
} catch (AuthenticationTokenException e) {
LogRecord lr = new LogRecord(Level.FINE,
"Could not convert credentials {0} into token of type {1} using source {2}: {3}");
lr.setThrown(e);
lr.setParameters(new Object[]{credentials, context.getTokenClass(), s, e.getMessage()});
LOGGER.log(lr);
}
if (token != null) {
return token;
}
}
}
return null;
}
/**
* Converts the best match of the supplied credentials into the specified token.
*
* @param context the context that an authentication token is required in.
* @param credentials the credentials instances to try and convert.
* @param <T> the type of token to convert to.
* @param <C> the type of credentials to convert,
* @return the token or {@code null} if the credentials could not be converted.
* @since 1.2
*/
@SuppressWarnings("unchecked")
@CheckForNull
public static <T, C extends Credentials> T convert(@NonNull AuthenticationTokenContext<T> context,
@NonNull C... credentials) {
return convert(context, Arrays.asList(credentials));
}
/**
* Converts the best match of the supplied credentials into the specified token.
*
* @param context the context that an authentication token is required in.
* @param credentials the credentials instances to try and convert.
* @param <T> the type of token to convert to.
* @param <C> the type of credentials to convert,
* @return the token or {@code null} if the credentials could not be converted.
* @since 1.2
*/
@SuppressWarnings("unchecked")
@CheckForNull
public static <T, C extends Credentials> T convert(@NonNull AuthenticationTokenContext<T> context,
@NonNull List<C> credentials) {
// we want the best match first
SortedMap<Integer, Map.Entry<C, AuthenticationTokenSource>> matches =
new TreeMap<Integer, Map.Entry<C, AuthenticationTokenSource>>(
Collections.reverseOrder());
Jenkins jenkins = Jenkins.getInstance();
if(jenkins == null){
LogRecord lr = new LogRecord(Level.FINE,
"No Jenkins object was found; no conversion could be made.");
LOGGER.log(lr);
return null;
}
for (C credential : credentials) {
for (AuthenticationTokenSource<?, ?> source : jenkins
.getExtensionList(AuthenticationTokenSource.class)) {
Integer score = source.score(context, credential);
if (score != null && !matches.containsKey(score)) {
// if there are two extensions with the same score,
// then the first (i.e. highest Extension.ordinal should win)
// if there are two credentials with the same scoe,
// then the first in the list should win.
matches.put(score, new AbstractMap.SimpleEntry<C, AuthenticationTokenSource>(credential, source));
}
}
}
// now try all the matches (form best to worst) until we get a conversion
for (Map.Entry<C, AuthenticationTokenSource> entry : matches.values()) {
C credential = entry.getKey();
AuthenticationTokenSource source = entry.getValue();
if (source.produces(context.getTokenClass()) && source
.consumes(credential)) { // redundant test, but for safety
AuthenticationTokenSource<? extends T, ? super C> s =
(AuthenticationTokenSource<? extends T, ? super C>) source;
T token = null;
try {
token = s.convert(credential);
} catch (AuthenticationTokenException e) {
LogRecord lr = new LogRecord(Level.FINE,
"Could not convert credentials {0} into token of type {1} using source {2}: {3}");
lr.setThrown(e);
lr.setParameters(new Object[]{credentials, context.getTokenClass(), s, e.getMessage()});
LOGGER.log(lr);
}
if (token != null) {
return token;
}
}
}
return null;
}
}
| Fix last ExtensionList
| src/main/java/jenkins/authentication/tokens/api/AuthenticationTokens.java | Fix last ExtensionList | <ide><path>rc/main/java/jenkins/authentication/tokens/api/AuthenticationTokens.java
<ide> new TreeMap<Integer, Map.Entry<C, AuthenticationTokenSource>>(
<ide> Collections.reverseOrder());
<ide>
<del> Jenkins jenkins = Jenkins.getInstance();
<del> if(jenkins == null){
<del> LogRecord lr = new LogRecord(Level.FINE,
<del> "No Jenkins object was found; no conversion could be made.");
<del> LOGGER.log(lr);
<del> return null;
<del> }
<ide> for (C credential : credentials) {
<del> for (AuthenticationTokenSource<?, ?> source : jenkins
<del> .getExtensionList(AuthenticationTokenSource.class)) {
<add> for (AuthenticationTokenSource<?, ?> source : ExtensionList.lookup(AuthenticationTokenSource.class)) {
<ide> Integer score = source.score(context, credential);
<ide> if (score != null && !matches.containsKey(score)) {
<ide> // if there are two extensions with the same score, |
|
Java | apache-2.0 | error: pathspec 'MimeType.java' did not match any file(s) known to git
| b784b764514ff797ae2a01f9368d3b86d1fc4d28 | 1 | boaglio/java-enum-mimetype |
/**
* Fernando Boaglio
*
* Fonte inicial:
* http://www.java2s.com/Code/Java/Network-Protocol/enumMimeType.htm
*/
public enum MimeType {
$323("text/h323"),
$3gp("video/3gpp"),
$7z("application/x-7z-compressed"),
abw("application/x-abiword"),
ai("application/postscript"),
aif("audio/x-aiff"),
aifc("audio/x-aiff"),
aiff("audio/x-aiff"),
alc("chemical/x-alchemy"),
art("image/x-jg"),
asc("text/plain"),
asf("video/x-ms-asf"),
$asn("chemical/x-ncbi-asn1"),
asn("chemical/x-ncbi-asn1-spec"),
aso("chemical/x-ncbi-asn1-binary"),
asx("video/x-ms-asf"),
atom("application/atom"),
atomcat("application/atomcat+xml"),
atomsrv("application/atomserv+xml"),
au("audio/basic"),
avi("video/x-msvideo"),
bak("application/x-trash"),
bat("application/x-msdos-program"),
b("chemical/x-molconn-Z"),
bcpio("application/x-bcpio"),
bib("text/x-bibtex"),
bin("application/octet-stream"),
bmp("image/x-ms-bmp"),
book("application/x-maker"),
boo("text/x-boo"),
bsd("chemical/x-crossfire"),
c3d("chemical/x-chem3d"),
cab("application/x-cab"),
cac("chemical/x-cache"),
cache("chemical/x-cache"),
cap("application/cap"),
cascii("chemical/x-cactvs-binary"),
cat("application/vnd.ms-pki.seccat"),
cbin("chemical/x-cactvs-binary"),
cbr("application/x-cbr"),
cbz("application/x-cbz"),
cc("text/x-c++src"),
cdf("application/x-cdf"),
cdr("image/x-coreldraw"),
cdt("image/x-coreldrawtemplate"),
cdx("chemical/x-cdx"),
cdy("application/vnd.cinderella"),
cef("chemical/x-cxf"),
cer("chemical/x-cerius"),
chm("chemical/x-chemdraw"),
chrt("application/x-kchart"),
cif("chemical/x-cif"),
$class("application/java-vm"),
cls("text/x-tex"),
cmdf("chemical/x-cmdf"),
cml("chemical/x-cml"),
cod("application/vnd.rim.cod"),
com("application/x-msdos-program"),
cpa("chemical/x-compass"),
cpio("application/x-cpio"),
cpp("text/x-c++src"),
$cpt("application/mac-compactpro"),
cpt("image/x-corelphotopaint"),
crl("application/x-pkcs7-crl"),
crt("application/x-x509-ca-cert"),
csf("chemical/x-cache-csf"),
$csh("application/x-csh"),
csh("text/x-csh"),
csm("chemical/x-csml"),
csml("chemical/x-csml"),
css("text/css"),
csv("text/csv"),
ctab("chemical/x-cactvs-binary"),
c("text/x-csrc"),
ctx("chemical/x-ctx"),
cu("application/cu-seeme"),
cub("chemical/x-gaussian-cube"),
cxf("chemical/x-cxf"),
cxx("text/x-c++src"),
dat("chemical/x-mopac-input"),
dcr("application/x-director"),
deb("application/x-debian-package"),
diff("text/x-diff"),
dif("video/dv"),
dir("application/x-director"),
djv("image/vnd.djvu"),
djvu("image/vnd.djvu"),
dll("application/x-msdos-program"),
dl("video/dl"),
dmg("application/x-apple-diskimage"),
dms("application/x-dms"),
doc("application/msword"),
docm("application/vnd.ms-word.document.macroEnabled.12"),
docx("application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
dot("application/msword"),
dotx("application/vnd.openxmlformats-officedocument.wordprocessingml.template"),
dotm("application/vnd.ms-word.template.macroEnabled.12"),
d("text/x-dsrc"),
dvi("application/x-dvi"),
dv("video/dv"),
dx("chemical/x-jcamp-dx"),
dxr("application/x-director"),
emb("chemical/x-embl-dl-nucleotide"),
embl("chemical/x-embl-dl-nucleotide"),
eml("message/rfc822"),
$ent("chemical/x-ncbi-asn1-ascii"),
ent("chemical/x-pdb"),
eps("application/postscript"),
etx("text/x-setext"),
exe("application/x-msdos-program"),
ez("application/andrew-inset"),
fb("application/x-maker"),
fbdoc("application/x-maker"),
fch("chemical/x-gaussian-checkpoint"),
fchk("chemical/x-gaussian-checkpoint"),
fig("application/x-xfig"),
flac("application/x-flac"),
fli("video/fli"),
fm("application/x-maker"),
frame("application/x-maker"),
frm("application/x-maker"),
gal("chemical/x-gaussian-log"),
gam("chemical/x-gamess-input"),
gamin("chemical/x-gamess-input"),
gau("chemical/x-gaussian-input"),
gcd("text/x-pcs-gcd"),
gcf("application/x-graphing-calculator"),
gcg("chemical/x-gcg8-sequence"),
gen("chemical/x-genbank"),
gf("application/x-tex-gf"),
gif("image/gif"),
gjc("chemical/x-gaussian-input"),
gjf("chemical/x-gaussian-input"),
gl("video/gl"),
gnumeric("application/x-gnumeric"),
gpt("chemical/x-mopac-graph"),
gsf("application/x-font"),
gsm("audio/x-gsm"),
gtar("application/x-gtar"),
hdf("application/x-hdf"),
hh("text/x-c++hdr"),
hin("chemical/x-hin"),
hpp("text/x-c++hdr"),
hqx("application/mac-binhex40"),
hs("text/x-haskell"),
hta("application/hta"),
htc("text/x-component"),
$h("text/x-chdr"),
html("text/html"),
htm("text/html"),
hxx("text/x-c++hdr"),
ica("application/x-ica"),
ice("x-conference/x-cooltalk"),
ico("image/x-icon"),
ics("text/calendar"),
icz("text/calendar"),
ief("image/ief"),
iges("model/iges"),
igs("model/iges"),
iii("application/x-iphone"),
inp("chemical/x-gamess-input"),
ins("application/x-internet-signup"),
iso("application/x-iso9660-image"),
isp("application/x-internet-signup"),
ist("chemical/x-isostar"),
istr("chemical/x-isostar"),
jad("text/vnd.sun.j2me.app-descriptor"),
jar("application/java-archive"),
java("text/x-java"),
jdx("chemical/x-jcamp-dx"),
jmz("application/x-jmol"),
jng("image/x-jng"),
jnlp("application/x-java-jnlp-file"),
jpeg("image/jpeg"),
jpe("image/jpeg"),
jpg("image/jpeg"),
js("application/x-javascript"),
kar("audio/midi"),
key("application/pgp-keys"),
kil("application/x-killustrator"),
kin("chemical/x-kinemage"),
kml("application/vnd.google-earth.kml+xml"),
kmz("application/vnd.google-earth.kmz"),
kpr("application/x-kpresenter"),
kpt("application/x-kpresenter"),
ksp("application/x-kspread"),
kwd("application/x-kword"),
kwt("application/x-kword"),
latex("application/x-latex"),
lha("application/x-lha"),
lhs("text/x-literate-haskell"),
lsf("video/x-la-asf"),
lsx("video/x-la-asf"),
ltx("text/x-tex"),
lyx("application/x-lyx"),
lzh("application/x-lzh"),
lzx("application/x-lzx"),
$m3u("audio/mpegurl"),
m3u("audio/x-mpegurl"),
$m4a("audio/mpeg"),
m4a("video/mp4"),
m4b("video/mp4"),
m4v("video/mp4"),
maker("application/x-maker"),
man("application/x-troff-man"),
mcif("chemical/x-mmcif"),
mcm("chemical/x-macmolecule"),
mdb("application/msaccess"),
me("application/x-troff-me"),
mesh("model/mesh"),
mid("audio/midi"),
midi("audio/midi"),
mif("application/x-mif"),
mm("application/x-freemind"),
mmd("chemical/x-macromodel-input"),
mmf("application/vnd.smaf"),
mml("text/mathml"),
mmod("chemical/x-macromodel-input"),
mng("video/x-mng"),
moc("text/x-moc"),
mol2("chemical/x-mol2"),
mol("chemical/x-mdl-molfile"),
moo("chemical/x-mopac-out"),
mop("chemical/x-mopac-input"),
mopcrt("chemical/x-mopac-input"),
movie("video/x-sgi-movie"),
mov("video/quicktime"),
mp2("audio/mpeg"),
mp3("audio/mpeg"),
mp4("video/mp4"),
mpc("chemical/x-mopac-input"),
mpega("audio/mpeg"),
mpeg("video/mpeg"),
mpe("video/mpeg"),
mpga("audio/mpeg"),
mpg("video/mpeg"),
ms("application/x-troff-ms"),
msh("model/mesh"),
msi("application/x-msi"),
msg("application/vnd.ms-outlook"),
mvb("chemical/x-mopac-vib"),
mxu("video/vnd.mpegurl"),
nb("application/mathematica"),
nc("application/x-netcdf"),
nwc("application/x-nwc"),
o("application/x-object"),
oda("application/oda"),
odb("application/vnd.oasis.opendocument.database"),
odc("application/vnd.oasis.opendocument.chart"),
odf("application/vnd.oasis.opendocument.formula"),
odg("application/vnd.oasis.opendocument.graphics"),
odi("application/vnd.oasis.opendocument.image"),
odm("application/vnd.oasis.opendocument.text-master"),
odp("application/vnd.oasis.opendocument.presentation"),
ods("application/vnd.oasis.opendocument.spreadsheet"),
odt("application/vnd.oasis.opendocument.text"),
oga("audio/ogg"),
ogg("application/ogg"),
ogv("video/ogg"),
ogx("application/ogg"),
old("application/x-trash"),
otg("application/vnd.oasis.opendocument.graphics-template"),
oth("application/vnd.oasis.opendocument.text-web"),
otp("application/vnd.oasis.opendocument.presentation-template"),
ots("application/vnd.oasis.opendocument.spreadsheet-template"),
ott("application/vnd.oasis.opendocument.text-template"),
oza("application/x-oz-application"),
p7r("application/x-pkcs7-certreqresp"),
pac("application/x-ns-proxy-autoconfig"),
pas("text/x-pascal"),
patch("text/x-diff"),
pat("image/x-coreldrawpattern"),
pbm("image/x-portable-bitmap"),
pcap("application/cap"),
pcf("application/x-font"),
pcx("image/pcx"),
pdb("chemical/x-pdb"),
pdf("application/pdf"),
pfa("application/x-font"),
pfb("application/x-font"),
pgm("image/x-portable-graymap"),
pgn("application/x-chess-pgn"),
pgp("application/pgp-signature"),
php3("application/x-httpd-php3"),
php3p("application/x-httpd-php3-preprocessed"),
php4("application/x-httpd-php4"),
php("application/x-httpd-php"),
phps("application/x-httpd-php-source"),
pht("application/x-httpd-php"),
phtml("application/x-httpd-php"),
pk("application/x-tex-pk"),
pls("audio/x-scpls"),
pl("text/x-perl"),
pm("text/x-perl"),
png("image/png"),
pnm("image/x-portable-anymap"),
pot("text/plain"),
potm("application/vnd.ms-powerpoint.template.macroEnabled.12"),
potx("application/vnd.openxmlformats-officedocument.presentationml.template"),
ppm("image/x-portable-pixmap"),
ppam("application/vnd.ms-powerpoint.addin.macroEnabled.12"),
pps("application/vnd.ms-powerpoint"),
ppsm("application/vnd.ms-powerpoint.slideshow.macroEnabled.12"),
ppsx("application/vnd.openxmlformats-officedocument.presentationml.slideshow"),
ppt("application/vnd.ms-powerpoint"),
pptm("application/vnd.ms-powerpoint.presentation.macroEnabled.12"),
pptx("application/vnd.openxmlformats-officedocument.presentationml.presentation"),
prf("application/pics-rules"),
prt("chemical/x-ncbi-asn1-ascii"),
ps("application/postscript"),
psd("image/x-photoshop"),
p("text/x-pascal"),
pyc("application/x-python-code"),
pyo("application/x-python-code"),
py("text/x-python"),
qtl("application/x-quicktimeplayer"),
qt("video/quicktime"),
$ra("audio/x-pn-realaudio"),
ra("audio/x-realaudio"),
ram("audio/x-pn-realaudio"),
rar("application/rar"),
ras("image/x-cmu-raster"),
rd("chemical/x-mdl-rdfile"),
rdf("application/rdf+xml"),
rgb("image/x-rgb"),
rhtml("application/x-httpd-eruby"),
rm("audio/x-pn-realaudio"),
roff("application/x-troff"),
ros("chemical/x-rosdal"),
rpm("application/x-redhat-package-manager"),
rss("application/rss+xml"),
rtf("application/rtf"),
rtx("text/richtext"),
rxn("chemical/x-mdl-rxnfile"),
sct("text/scriptlet"),
sd2("audio/x-sd2"),
sda("application/vnd.stardivision.draw"),
sdc("application/vnd.stardivision.calc"),
sd("chemical/x-mdl-sdfile"),
sdd("application/vnd.stardivision.impress"),
$sdf("application/vnd.stardivision.math"),
sdf("chemical/x-mdl-sdfile"),
sds("application/vnd.stardivision.chart"),
sdw("application/vnd.stardivision.writer"),
ser("application/java-serialized-object"),
sgf("application/x-go-sgf"),
sgl("application/vnd.stardivision.writer-global"),
$sh("application/x-sh"),
shar("application/x-shar"),
sh("text/x-sh"),
shtml("text/html"),
sid("audio/prs.sid"),
sik("application/x-trash"),
silo("model/mesh"),
sis("application/vnd.symbian.install"),
sisx("x-epoc/x-sisx-app"),
sit("application/x-stuffit"),
sitx("application/x-stuffit"),
sldm("application/vnd.ms-powerpoint.slide.macroEnabled.12"),
sldx("application/vnd.openxmlformats-officedocument.presentationml.slide"),
skd("application/x-koan"),
skm("application/x-koan"),
skp("application/x-koan"),
skt("application/x-koan"),
smi("application/smil"),
smil("application/smil"),
snd("audio/basic"),
spc("chemical/x-galactic-spc"),
$spl("application/futuresplash"),
spl("application/x-futuresplash"),
spx("audio/ogg"),
src("application/x-wais-source"),
stc("application/vnd.sun.xml.calc.template"),
std("application/vnd.sun.xml.draw.template"),
sti("application/vnd.sun.xml.impress.template"),
stl("application/vnd.ms-pki.stl"),
stw("application/vnd.sun.xml.writer.template"),
sty("text/x-tex"),
sv4cpio("application/x-sv4cpio"),
sv4crc("application/x-sv4crc"),
svg("image/svg+xml"),
svgz("image/svg+xml"),
sw("chemical/x-swissprot"),
swf("application/x-shockwave-flash"),
swfl("application/x-shockwave-flash"),
sxc("application/vnd.sun.xml.calc"),
sxd("application/vnd.sun.xml.draw"),
sxg("application/vnd.sun.xml.writer.global"),
sxi("application/vnd.sun.xml.impress"),
sxm("application/vnd.sun.xml.math"),
sxw("application/vnd.sun.xml.writer"),
t("application/x-troff"),
tar("application/x-tar"),
taz("application/x-gtar"),
$tcl("application/x-tcl"),
tcl("text/x-tcl"),
texi("application/x-texinfo"),
texinfo("application/x-texinfo"),
tex("text/x-tex"),
text("text/plain"),
tgf("chemical/x-mdl-tgf"),
tgz("application/x-gtar"),
tiff("image/tiff"),
tif("image/tiff"),
tk("text/x-tcl"),
tm("text/texmacs"),
torrent("application/x-bittorrent"),
tr("application/x-troff"),
tsp("application/dsptype"),
ts("text/texmacs"),
tsv("text/tab-separated-values"),
txt("text/plain"),
udeb("application/x-debian-package"),
uls("text/iuls"),
ustar("application/x-ustar"),
val("chemical/x-ncbi-asn1-binary"),
vcd("application/x-cdlink"),
vcf("text/x-vcard"),
vcs("text/x-vcalendar"),
vmd("chemical/x-vmd"),
vms("chemical/x-vamas-iso14976"),
$vrml("model/vrml"),
vrml("x-world/x-vrml"),
vrm("x-world/x-vrml"),
vsd("application/vnd.visio"),
wad("application/x-doom"),
wav("audio/x-wav"),
wax("audio/x-ms-wax"),
wbmp("image/vnd.wap.wbmp"),
wbxml("application/vnd.wap.wbxml"),
wk("application/x-123"),
wma("audio/x-ms-wma"),
wmd("application/x-ms-wmd"),
wmlc("application/vnd.wap.wmlc"),
wmlsc("application/vnd.wap.wmlscriptc"),
wmls("text/vnd.wap.wmlscript"),
wml("text/vnd.wap.wml"),
wm("video/x-ms-wm"),
wmv("video/x-ms-wmv"),
wmx("video/x-ms-wmx"),
wmz("application/x-ms-wmz"),
wp5("application/wordperfect5.1"),
wpd("application/wordperfect"),
$wrl("model/vrml"),
wrl("x-world/x-vrml"),
wsc("text/scriptlet"),
wvx("video/x-ms-wvx"),
wz("application/x-wingz"),
xbm("image/x-xbitmap"),
xcf("application/x-xcf"),
xht("application/xhtml+xml"),
xhtml("application/xhtml+xml"),
xlb("application/vnd.ms-excel"),
xls("application/vnd.ms-excel"),
xlsb("application/vnd.ms-excel.sheet.binary.macroEnabled.12"),
xlam("application/vnd.ms-excel.addin.macroEnabled.12"),
xlsm("application/application/vnd.ms-excel.sheet.macroEnabled.12"),
xlsx("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
xltm("application/vnd.ms-excel.template.macroEnabled.12"),
xltx("application/vnd.openxmlformats-officedocument.spreadsheetml.template"),
xlt("application/vnd.ms-excel"),
xml("application/xml"),
xpi("application/x-xpinstall"),
xpm("image/x-xpixmap"),
xsl("application/xml"),
xtel("chemical/x-xtel"),
xul("application/vnd.mozilla.xul+xml"),
xwd("image/x-xwindowdump"),
xyz("chemical/x-xyz"),
zip("application/zip"),
zmt("chemical/x-mopac-input"),
undefined("application/octet-stream");
public String contentType;
public String getContentType() {
return this.contentType;
}
MimeType(String contentType) {
this.contentType = contentType;
}
public static MimeType getByExtension(String extension) {
MimeType mimeType = undefined;
if (extension != null && extension.length() > 2) {
for (MimeType mt : MimeType.values()) {
if (mt.name().equalsIgnoreCase(extension)) {
mimeType = mt;
break;
}
}
}
return mimeType;
}
}
| MimeType.java | Initial import
| MimeType.java | Initial import | <ide><path>imeType.java
<add>
<add>
<add>/**
<add> * Fernando Boaglio
<add> *
<add> * Fonte inicial:
<add> * http://www.java2s.com/Code/Java/Network-Protocol/enumMimeType.htm
<add> */
<add>public enum MimeType {
<add>
<add> $323("text/h323"),
<add> $3gp("video/3gpp"),
<add> $7z("application/x-7z-compressed"),
<add> abw("application/x-abiword"),
<add> ai("application/postscript"),
<add> aif("audio/x-aiff"),
<add> aifc("audio/x-aiff"),
<add> aiff("audio/x-aiff"),
<add> alc("chemical/x-alchemy"),
<add> art("image/x-jg"),
<add> asc("text/plain"),
<add> asf("video/x-ms-asf"),
<add> $asn("chemical/x-ncbi-asn1"),
<add> asn("chemical/x-ncbi-asn1-spec"),
<add> aso("chemical/x-ncbi-asn1-binary"),
<add> asx("video/x-ms-asf"),
<add> atom("application/atom"),
<add> atomcat("application/atomcat+xml"),
<add> atomsrv("application/atomserv+xml"),
<add> au("audio/basic"),
<add> avi("video/x-msvideo"),
<add> bak("application/x-trash"),
<add> bat("application/x-msdos-program"),
<add> b("chemical/x-molconn-Z"),
<add> bcpio("application/x-bcpio"),
<add> bib("text/x-bibtex"),
<add> bin("application/octet-stream"),
<add> bmp("image/x-ms-bmp"),
<add> book("application/x-maker"),
<add> boo("text/x-boo"),
<add> bsd("chemical/x-crossfire"),
<add> c3d("chemical/x-chem3d"),
<add> cab("application/x-cab"),
<add> cac("chemical/x-cache"),
<add> cache("chemical/x-cache"),
<add> cap("application/cap"),
<add> cascii("chemical/x-cactvs-binary"),
<add> cat("application/vnd.ms-pki.seccat"),
<add> cbin("chemical/x-cactvs-binary"),
<add> cbr("application/x-cbr"),
<add> cbz("application/x-cbz"),
<add> cc("text/x-c++src"),
<add> cdf("application/x-cdf"),
<add> cdr("image/x-coreldraw"),
<add> cdt("image/x-coreldrawtemplate"),
<add> cdx("chemical/x-cdx"),
<add> cdy("application/vnd.cinderella"),
<add> cef("chemical/x-cxf"),
<add> cer("chemical/x-cerius"),
<add> chm("chemical/x-chemdraw"),
<add> chrt("application/x-kchart"),
<add> cif("chemical/x-cif"),
<add> $class("application/java-vm"),
<add> cls("text/x-tex"),
<add> cmdf("chemical/x-cmdf"),
<add> cml("chemical/x-cml"),
<add> cod("application/vnd.rim.cod"),
<add> com("application/x-msdos-program"),
<add> cpa("chemical/x-compass"),
<add> cpio("application/x-cpio"),
<add> cpp("text/x-c++src"),
<add> $cpt("application/mac-compactpro"),
<add> cpt("image/x-corelphotopaint"),
<add> crl("application/x-pkcs7-crl"),
<add> crt("application/x-x509-ca-cert"),
<add> csf("chemical/x-cache-csf"),
<add> $csh("application/x-csh"),
<add> csh("text/x-csh"),
<add> csm("chemical/x-csml"),
<add> csml("chemical/x-csml"),
<add> css("text/css"),
<add> csv("text/csv"),
<add> ctab("chemical/x-cactvs-binary"),
<add> c("text/x-csrc"),
<add> ctx("chemical/x-ctx"),
<add> cu("application/cu-seeme"),
<add> cub("chemical/x-gaussian-cube"),
<add> cxf("chemical/x-cxf"),
<add> cxx("text/x-c++src"),
<add> dat("chemical/x-mopac-input"),
<add> dcr("application/x-director"),
<add> deb("application/x-debian-package"),
<add> diff("text/x-diff"),
<add> dif("video/dv"),
<add> dir("application/x-director"),
<add> djv("image/vnd.djvu"),
<add> djvu("image/vnd.djvu"),
<add> dll("application/x-msdos-program"),
<add> dl("video/dl"),
<add> dmg("application/x-apple-diskimage"),
<add> dms("application/x-dms"),
<add> doc("application/msword"),
<add> docm("application/vnd.ms-word.document.macroEnabled.12"),
<add> docx("application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
<add> dot("application/msword"),
<add> dotx("application/vnd.openxmlformats-officedocument.wordprocessingml.template"),
<add> dotm("application/vnd.ms-word.template.macroEnabled.12"),
<add> d("text/x-dsrc"),
<add> dvi("application/x-dvi"),
<add> dv("video/dv"),
<add> dx("chemical/x-jcamp-dx"),
<add> dxr("application/x-director"),
<add> emb("chemical/x-embl-dl-nucleotide"),
<add> embl("chemical/x-embl-dl-nucleotide"),
<add> eml("message/rfc822"),
<add> $ent("chemical/x-ncbi-asn1-ascii"),
<add> ent("chemical/x-pdb"),
<add> eps("application/postscript"),
<add> etx("text/x-setext"),
<add> exe("application/x-msdos-program"),
<add> ez("application/andrew-inset"),
<add> fb("application/x-maker"),
<add> fbdoc("application/x-maker"),
<add> fch("chemical/x-gaussian-checkpoint"),
<add> fchk("chemical/x-gaussian-checkpoint"),
<add> fig("application/x-xfig"),
<add> flac("application/x-flac"),
<add> fli("video/fli"),
<add> fm("application/x-maker"),
<add> frame("application/x-maker"),
<add> frm("application/x-maker"),
<add> gal("chemical/x-gaussian-log"),
<add> gam("chemical/x-gamess-input"),
<add> gamin("chemical/x-gamess-input"),
<add> gau("chemical/x-gaussian-input"),
<add> gcd("text/x-pcs-gcd"),
<add> gcf("application/x-graphing-calculator"),
<add> gcg("chemical/x-gcg8-sequence"),
<add> gen("chemical/x-genbank"),
<add> gf("application/x-tex-gf"),
<add> gif("image/gif"),
<add> gjc("chemical/x-gaussian-input"),
<add> gjf("chemical/x-gaussian-input"),
<add> gl("video/gl"),
<add> gnumeric("application/x-gnumeric"),
<add> gpt("chemical/x-mopac-graph"),
<add> gsf("application/x-font"),
<add> gsm("audio/x-gsm"),
<add> gtar("application/x-gtar"),
<add> hdf("application/x-hdf"),
<add> hh("text/x-c++hdr"),
<add> hin("chemical/x-hin"),
<add> hpp("text/x-c++hdr"),
<add> hqx("application/mac-binhex40"),
<add> hs("text/x-haskell"),
<add> hta("application/hta"),
<add> htc("text/x-component"),
<add> $h("text/x-chdr"),
<add> html("text/html"),
<add> htm("text/html"),
<add> hxx("text/x-c++hdr"),
<add> ica("application/x-ica"),
<add> ice("x-conference/x-cooltalk"),
<add> ico("image/x-icon"),
<add> ics("text/calendar"),
<add> icz("text/calendar"),
<add> ief("image/ief"),
<add> iges("model/iges"),
<add> igs("model/iges"),
<add> iii("application/x-iphone"),
<add> inp("chemical/x-gamess-input"),
<add> ins("application/x-internet-signup"),
<add> iso("application/x-iso9660-image"),
<add> isp("application/x-internet-signup"),
<add> ist("chemical/x-isostar"),
<add> istr("chemical/x-isostar"),
<add> jad("text/vnd.sun.j2me.app-descriptor"),
<add> jar("application/java-archive"),
<add> java("text/x-java"),
<add> jdx("chemical/x-jcamp-dx"),
<add> jmz("application/x-jmol"),
<add> jng("image/x-jng"),
<add> jnlp("application/x-java-jnlp-file"),
<add> jpeg("image/jpeg"),
<add> jpe("image/jpeg"),
<add> jpg("image/jpeg"),
<add> js("application/x-javascript"),
<add> kar("audio/midi"),
<add> key("application/pgp-keys"),
<add> kil("application/x-killustrator"),
<add> kin("chemical/x-kinemage"),
<add> kml("application/vnd.google-earth.kml+xml"),
<add> kmz("application/vnd.google-earth.kmz"),
<add> kpr("application/x-kpresenter"),
<add> kpt("application/x-kpresenter"),
<add> ksp("application/x-kspread"),
<add> kwd("application/x-kword"),
<add> kwt("application/x-kword"),
<add> latex("application/x-latex"),
<add> lha("application/x-lha"),
<add> lhs("text/x-literate-haskell"),
<add> lsf("video/x-la-asf"),
<add> lsx("video/x-la-asf"),
<add> ltx("text/x-tex"),
<add> lyx("application/x-lyx"),
<add> lzh("application/x-lzh"),
<add> lzx("application/x-lzx"),
<add> $m3u("audio/mpegurl"),
<add> m3u("audio/x-mpegurl"),
<add> $m4a("audio/mpeg"),
<add> m4a("video/mp4"),
<add> m4b("video/mp4"),
<add> m4v("video/mp4"),
<add> maker("application/x-maker"),
<add> man("application/x-troff-man"),
<add> mcif("chemical/x-mmcif"),
<add> mcm("chemical/x-macmolecule"),
<add> mdb("application/msaccess"),
<add> me("application/x-troff-me"),
<add> mesh("model/mesh"),
<add> mid("audio/midi"),
<add> midi("audio/midi"),
<add> mif("application/x-mif"),
<add> mm("application/x-freemind"),
<add> mmd("chemical/x-macromodel-input"),
<add> mmf("application/vnd.smaf"),
<add> mml("text/mathml"),
<add> mmod("chemical/x-macromodel-input"),
<add> mng("video/x-mng"),
<add> moc("text/x-moc"),
<add> mol2("chemical/x-mol2"),
<add> mol("chemical/x-mdl-molfile"),
<add> moo("chemical/x-mopac-out"),
<add> mop("chemical/x-mopac-input"),
<add> mopcrt("chemical/x-mopac-input"),
<add> movie("video/x-sgi-movie"),
<add> mov("video/quicktime"),
<add> mp2("audio/mpeg"),
<add> mp3("audio/mpeg"),
<add> mp4("video/mp4"),
<add> mpc("chemical/x-mopac-input"),
<add> mpega("audio/mpeg"),
<add> mpeg("video/mpeg"),
<add> mpe("video/mpeg"),
<add> mpga("audio/mpeg"),
<add> mpg("video/mpeg"),
<add> ms("application/x-troff-ms"),
<add> msh("model/mesh"),
<add> msi("application/x-msi"),
<add> msg("application/vnd.ms-outlook"),
<add> mvb("chemical/x-mopac-vib"),
<add> mxu("video/vnd.mpegurl"),
<add> nb("application/mathematica"),
<add> nc("application/x-netcdf"),
<add> nwc("application/x-nwc"),
<add> o("application/x-object"),
<add> oda("application/oda"),
<add> odb("application/vnd.oasis.opendocument.database"),
<add> odc("application/vnd.oasis.opendocument.chart"),
<add> odf("application/vnd.oasis.opendocument.formula"),
<add> odg("application/vnd.oasis.opendocument.graphics"),
<add> odi("application/vnd.oasis.opendocument.image"),
<add> odm("application/vnd.oasis.opendocument.text-master"),
<add> odp("application/vnd.oasis.opendocument.presentation"),
<add> ods("application/vnd.oasis.opendocument.spreadsheet"),
<add> odt("application/vnd.oasis.opendocument.text"),
<add> oga("audio/ogg"),
<add> ogg("application/ogg"),
<add> ogv("video/ogg"),
<add> ogx("application/ogg"),
<add> old("application/x-trash"),
<add> otg("application/vnd.oasis.opendocument.graphics-template"),
<add> oth("application/vnd.oasis.opendocument.text-web"),
<add> otp("application/vnd.oasis.opendocument.presentation-template"),
<add> ots("application/vnd.oasis.opendocument.spreadsheet-template"),
<add> ott("application/vnd.oasis.opendocument.text-template"),
<add> oza("application/x-oz-application"),
<add> p7r("application/x-pkcs7-certreqresp"),
<add> pac("application/x-ns-proxy-autoconfig"),
<add> pas("text/x-pascal"),
<add> patch("text/x-diff"),
<add> pat("image/x-coreldrawpattern"),
<add> pbm("image/x-portable-bitmap"),
<add> pcap("application/cap"),
<add> pcf("application/x-font"),
<add> pcx("image/pcx"),
<add> pdb("chemical/x-pdb"),
<add> pdf("application/pdf"),
<add> pfa("application/x-font"),
<add> pfb("application/x-font"),
<add> pgm("image/x-portable-graymap"),
<add> pgn("application/x-chess-pgn"),
<add> pgp("application/pgp-signature"),
<add> php3("application/x-httpd-php3"),
<add> php3p("application/x-httpd-php3-preprocessed"),
<add> php4("application/x-httpd-php4"),
<add> php("application/x-httpd-php"),
<add> phps("application/x-httpd-php-source"),
<add> pht("application/x-httpd-php"),
<add> phtml("application/x-httpd-php"),
<add> pk("application/x-tex-pk"),
<add> pls("audio/x-scpls"),
<add> pl("text/x-perl"),
<add> pm("text/x-perl"),
<add> png("image/png"),
<add> pnm("image/x-portable-anymap"),
<add> pot("text/plain"),
<add> potm("application/vnd.ms-powerpoint.template.macroEnabled.12"),
<add> potx("application/vnd.openxmlformats-officedocument.presentationml.template"),
<add> ppm("image/x-portable-pixmap"),
<add> ppam("application/vnd.ms-powerpoint.addin.macroEnabled.12"),
<add> pps("application/vnd.ms-powerpoint"),
<add> ppsm("application/vnd.ms-powerpoint.slideshow.macroEnabled.12"),
<add> ppsx("application/vnd.openxmlformats-officedocument.presentationml.slideshow"),
<add> ppt("application/vnd.ms-powerpoint"),
<add> pptm("application/vnd.ms-powerpoint.presentation.macroEnabled.12"),
<add> pptx("application/vnd.openxmlformats-officedocument.presentationml.presentation"),
<add> prf("application/pics-rules"),
<add> prt("chemical/x-ncbi-asn1-ascii"),
<add> ps("application/postscript"),
<add> psd("image/x-photoshop"),
<add> p("text/x-pascal"),
<add> pyc("application/x-python-code"),
<add> pyo("application/x-python-code"),
<add> py("text/x-python"),
<add> qtl("application/x-quicktimeplayer"),
<add> qt("video/quicktime"),
<add> $ra("audio/x-pn-realaudio"),
<add> ra("audio/x-realaudio"),
<add> ram("audio/x-pn-realaudio"),
<add> rar("application/rar"),
<add> ras("image/x-cmu-raster"),
<add> rd("chemical/x-mdl-rdfile"),
<add> rdf("application/rdf+xml"),
<add> rgb("image/x-rgb"),
<add> rhtml("application/x-httpd-eruby"),
<add> rm("audio/x-pn-realaudio"),
<add> roff("application/x-troff"),
<add> ros("chemical/x-rosdal"),
<add> rpm("application/x-redhat-package-manager"),
<add> rss("application/rss+xml"),
<add> rtf("application/rtf"),
<add> rtx("text/richtext"),
<add> rxn("chemical/x-mdl-rxnfile"),
<add> sct("text/scriptlet"),
<add> sd2("audio/x-sd2"),
<add> sda("application/vnd.stardivision.draw"),
<add> sdc("application/vnd.stardivision.calc"),
<add> sd("chemical/x-mdl-sdfile"),
<add> sdd("application/vnd.stardivision.impress"),
<add> $sdf("application/vnd.stardivision.math"),
<add> sdf("chemical/x-mdl-sdfile"),
<add> sds("application/vnd.stardivision.chart"),
<add> sdw("application/vnd.stardivision.writer"),
<add> ser("application/java-serialized-object"),
<add> sgf("application/x-go-sgf"),
<add> sgl("application/vnd.stardivision.writer-global"),
<add> $sh("application/x-sh"),
<add> shar("application/x-shar"),
<add> sh("text/x-sh"),
<add> shtml("text/html"),
<add> sid("audio/prs.sid"),
<add> sik("application/x-trash"),
<add> silo("model/mesh"),
<add> sis("application/vnd.symbian.install"),
<add> sisx("x-epoc/x-sisx-app"),
<add> sit("application/x-stuffit"),
<add> sitx("application/x-stuffit"),
<add> sldm("application/vnd.ms-powerpoint.slide.macroEnabled.12"),
<add> sldx("application/vnd.openxmlformats-officedocument.presentationml.slide"),
<add> skd("application/x-koan"),
<add> skm("application/x-koan"),
<add> skp("application/x-koan"),
<add> skt("application/x-koan"),
<add> smi("application/smil"),
<add> smil("application/smil"),
<add> snd("audio/basic"),
<add> spc("chemical/x-galactic-spc"),
<add> $spl("application/futuresplash"),
<add> spl("application/x-futuresplash"),
<add> spx("audio/ogg"),
<add> src("application/x-wais-source"),
<add> stc("application/vnd.sun.xml.calc.template"),
<add> std("application/vnd.sun.xml.draw.template"),
<add> sti("application/vnd.sun.xml.impress.template"),
<add> stl("application/vnd.ms-pki.stl"),
<add> stw("application/vnd.sun.xml.writer.template"),
<add> sty("text/x-tex"),
<add> sv4cpio("application/x-sv4cpio"),
<add> sv4crc("application/x-sv4crc"),
<add> svg("image/svg+xml"),
<add> svgz("image/svg+xml"),
<add> sw("chemical/x-swissprot"),
<add> swf("application/x-shockwave-flash"),
<add> swfl("application/x-shockwave-flash"),
<add> sxc("application/vnd.sun.xml.calc"),
<add> sxd("application/vnd.sun.xml.draw"),
<add> sxg("application/vnd.sun.xml.writer.global"),
<add> sxi("application/vnd.sun.xml.impress"),
<add> sxm("application/vnd.sun.xml.math"),
<add> sxw("application/vnd.sun.xml.writer"),
<add> t("application/x-troff"),
<add> tar("application/x-tar"),
<add> taz("application/x-gtar"),
<add> $tcl("application/x-tcl"),
<add> tcl("text/x-tcl"),
<add> texi("application/x-texinfo"),
<add> texinfo("application/x-texinfo"),
<add> tex("text/x-tex"),
<add> text("text/plain"),
<add> tgf("chemical/x-mdl-tgf"),
<add> tgz("application/x-gtar"),
<add> tiff("image/tiff"),
<add> tif("image/tiff"),
<add> tk("text/x-tcl"),
<add> tm("text/texmacs"),
<add> torrent("application/x-bittorrent"),
<add> tr("application/x-troff"),
<add> tsp("application/dsptype"),
<add> ts("text/texmacs"),
<add> tsv("text/tab-separated-values"),
<add> txt("text/plain"),
<add> udeb("application/x-debian-package"),
<add> uls("text/iuls"),
<add> ustar("application/x-ustar"),
<add> val("chemical/x-ncbi-asn1-binary"),
<add> vcd("application/x-cdlink"),
<add> vcf("text/x-vcard"),
<add> vcs("text/x-vcalendar"),
<add> vmd("chemical/x-vmd"),
<add> vms("chemical/x-vamas-iso14976"),
<add> $vrml("model/vrml"),
<add> vrml("x-world/x-vrml"),
<add> vrm("x-world/x-vrml"),
<add> vsd("application/vnd.visio"),
<add> wad("application/x-doom"),
<add> wav("audio/x-wav"),
<add> wax("audio/x-ms-wax"),
<add> wbmp("image/vnd.wap.wbmp"),
<add> wbxml("application/vnd.wap.wbxml"),
<add> wk("application/x-123"),
<add> wma("audio/x-ms-wma"),
<add> wmd("application/x-ms-wmd"),
<add> wmlc("application/vnd.wap.wmlc"),
<add> wmlsc("application/vnd.wap.wmlscriptc"),
<add> wmls("text/vnd.wap.wmlscript"),
<add> wml("text/vnd.wap.wml"),
<add> wm("video/x-ms-wm"),
<add> wmv("video/x-ms-wmv"),
<add> wmx("video/x-ms-wmx"),
<add> wmz("application/x-ms-wmz"),
<add> wp5("application/wordperfect5.1"),
<add> wpd("application/wordperfect"),
<add> $wrl("model/vrml"),
<add> wrl("x-world/x-vrml"),
<add> wsc("text/scriptlet"),
<add> wvx("video/x-ms-wvx"),
<add> wz("application/x-wingz"),
<add> xbm("image/x-xbitmap"),
<add> xcf("application/x-xcf"),
<add> xht("application/xhtml+xml"),
<add> xhtml("application/xhtml+xml"),
<add> xlb("application/vnd.ms-excel"),
<add> xls("application/vnd.ms-excel"),
<add> xlsb("application/vnd.ms-excel.sheet.binary.macroEnabled.12"),
<add> xlam("application/vnd.ms-excel.addin.macroEnabled.12"),
<add> xlsm("application/application/vnd.ms-excel.sheet.macroEnabled.12"),
<add> xlsx("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
<add> xltm("application/vnd.ms-excel.template.macroEnabled.12"),
<add> xltx("application/vnd.openxmlformats-officedocument.spreadsheetml.template"),
<add> xlt("application/vnd.ms-excel"),
<add> xml("application/xml"),
<add> xpi("application/x-xpinstall"),
<add> xpm("image/x-xpixmap"),
<add> xsl("application/xml"),
<add> xtel("chemical/x-xtel"),
<add> xul("application/vnd.mozilla.xul+xml"),
<add> xwd("image/x-xwindowdump"),
<add> xyz("chemical/x-xyz"),
<add> zip("application/zip"),
<add> zmt("chemical/x-mopac-input"),
<add> undefined("application/octet-stream");
<add>
<add> public String contentType;
<add>
<add> public String getContentType() {
<add> return this.contentType;
<add> }
<add>
<add> MimeType(String contentType) {
<add>
<add> this.contentType = contentType;
<add> }
<add>
<add> public static MimeType getByExtension(String extension) {
<add>
<add> MimeType mimeType = undefined;
<add> if (extension != null && extension.length() > 2) {
<add> for (MimeType mt : MimeType.values()) {
<add>
<add> if (mt.name().equalsIgnoreCase(extension)) {
<add> mimeType = mt;
<add> break;
<add> }
<add> }
<add> }
<add>
<add> return mimeType;
<add>
<add> }
<add>
<add>} |
|
Java | apache-2.0 | 60e033738039e344cd3ae0a120abc80b9637339b | 0 | Praveen2112/presto,smartnews/presto,losipiuk/presto,losipiuk/presto,smartnews/presto,ebyhr/presto,Praveen2112/presto,dain/presto,dain/presto,ebyhr/presto,smartnews/presto,ebyhr/presto,Praveen2112/presto,smartnews/presto,dain/presto,Praveen2112/presto,dain/presto,dain/presto,ebyhr/presto,losipiuk/presto,losipiuk/presto,ebyhr/presto,smartnews/presto,losipiuk/presto,Praveen2112/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.trino.plugin.memory;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.Ints;
import io.trino.Session;
import io.trino.execution.QueryStats;
import io.trino.metadata.QualifiedObjectName;
import io.trino.operator.OperatorStats;
import io.trino.plugin.base.metrics.LongCount;
import io.trino.spi.QueryId;
import io.trino.spi.metrics.Count;
import io.trino.spi.metrics.Metrics;
import io.trino.testing.BaseConnectorTest;
import io.trino.testing.DistributedQueryRunner;
import io.trino.testing.MaterializedResult;
import io.trino.testing.MaterializedRow;
import io.trino.testing.QueryRunner;
import io.trino.testing.ResultWithQueryId;
import io.trino.testing.TestingConnectorBehavior;
import io.trino.testing.sql.TestTable;
import io.trino.testng.services.Flaky;
import io.trino.tpch.TpchTable;
import org.intellij.lang.annotations.Language;
import org.testng.SkipException;
import org.testng.annotations.Test;
import java.util.List;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static io.trino.SystemSessionProperties.ENABLE_LARGE_DYNAMIC_FILTERS;
import static io.trino.plugin.memory.MemoryQueryRunner.createMemoryQueryRunner;
import static io.trino.sql.analyzer.FeaturesConfig.JoinDistributionType;
import static io.trino.sql.analyzer.FeaturesConfig.JoinDistributionType.BROADCAST;
import static io.trino.testing.assertions.Assert.assertEquals;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.testng.Assert.assertTrue;
public class TestMemoryConnectorTest
extends BaseConnectorTest
{
private static final int LINEITEM_COUNT = 60175;
private static final int ORDERS_COUNT = 15000;
private static final int PART_COUNT = 2000;
private static final int CUSTOMER_COUNT = 1500;
@Override
protected QueryRunner createQueryRunner()
throws Exception
{
return createMemoryQueryRunner(
// Adjust DF limits to test edge cases
ImmutableMap.<String, String>builder()
.put("dynamic-filtering.small-broadcast.max-distinct-values-per-driver", "100")
.put("dynamic-filtering.small-broadcast.range-row-limit-per-driver", "100")
.put("dynamic-filtering.large-broadcast.max-distinct-values-per-driver", "100")
.put("dynamic-filtering.large-broadcast.range-row-limit-per-driver", "100000")
.put("dynamic-filtering.large-partitioned.max-distinct-values-per-driver", "100")
.put("dynamic-filtering.large-partitioned.range-row-limit-per-driver", "100000")
// disable semi join to inner join rewrite to test semi join operators explicitly
.put("optimizer.rewrite-filtering-semi-join-to-inner-join", "false")
.build(),
ImmutableSet.<TpchTable<?>>builder()
.addAll(REQUIRED_TPCH_TABLES)
.add(TpchTable.PART)
.add(TpchTable.LINE_ITEM)
.build());
}
@Override
protected boolean hasBehavior(TestingConnectorBehavior connectorBehavior)
{
switch (connectorBehavior) {
case SUPPORTS_PREDICATE_PUSHDOWN:
case SUPPORTS_LIMIT_PUSHDOWN:
case SUPPORTS_TOPN_PUSHDOWN:
case SUPPORTS_AGGREGATION_PUSHDOWN:
return false;
case SUPPORTS_ADD_COLUMN:
case SUPPORTS_DROP_COLUMN:
case SUPPORTS_RENAME_COLUMN:
return false;
case SUPPORTS_COMMENT_ON_TABLE:
case SUPPORTS_COMMENT_ON_COLUMN:
return false;
case SUPPORTS_RENAME_SCHEMA:
return false;
case SUPPORTS_CREATE_VIEW:
return true;
default:
return super.hasBehavior(connectorBehavior);
}
}
@Override
protected TestTable createTableWithDefaultColumns()
{
throw new SkipException("Cassandra connector does not support column default values");
}
// it has to be RuntimeException as FailureInfo$FailureException is private
@Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "line 1:1: Destination table 'memory.default.nation' already exists")
public void testCreateTableWhenTableIsAlreadyCreated()
{
@Language("SQL") String createTableSql = "CREATE TABLE nation AS SELECT * FROM tpch.tiny.nation";
assertUpdate(createTableSql);
}
@Test
public void testSelect()
{
assertUpdate("CREATE TABLE test_select AS SELECT * FROM tpch.tiny.nation", "SELECT count(*) FROM nation");
assertQuery("SELECT * FROM test_select ORDER BY nationkey", "SELECT * FROM nation ORDER BY nationkey");
assertQueryResult("INSERT INTO test_select SELECT * FROM tpch.tiny.nation", 25L);
assertQueryResult("INSERT INTO test_select SELECT * FROM tpch.tiny.nation", 25L);
assertQueryResult("SELECT count(*) FROM test_select", 75L);
}
@Test
// TODO (https://github.com/trinodb/trino/issues/8691) fix the test
@Flaky(issue = "https://github.com/trinodb/trino/issues/8691", match = "ComparisonFailure: expected:<LongCount\\{total=\\[\\d+]}> but was:<LongCount\\{total=\\[\\d+]}>")
public void testCustomMetricsScanFilter()
{
Metrics metrics = collectCustomMetrics("SELECT partkey FROM part WHERE partkey % 1000 > 0");
assertThat(metrics.getMetrics().get("rows")).isEqualTo(new LongCount(PART_COUNT));
assertThat(metrics.getMetrics().get("started")).isEqualTo(metrics.getMetrics().get("finished"));
assertThat(((Count) metrics.getMetrics().get("finished")).getTotal()).isGreaterThan(0);
}
@Test
public void testCustomMetricsScanOnly()
{
Metrics metrics = collectCustomMetrics("SELECT partkey FROM part");
assertThat(metrics.getMetrics().get("rows")).isEqualTo(new LongCount(PART_COUNT));
assertThat(metrics.getMetrics().get("started")).isEqualTo(metrics.getMetrics().get("finished"));
assertThat(((Count) metrics.getMetrics().get("finished")).getTotal()).isGreaterThan(0);
}
private Metrics collectCustomMetrics(String sql)
{
DistributedQueryRunner runner = (DistributedQueryRunner) getQueryRunner();
ResultWithQueryId<MaterializedResult> result = runner.executeWithQueryId(getSession(), sql);
return runner
.getCoordinator()
.getQueryManager()
.getFullQueryInfo(result.getQueryId())
.getQueryStats()
.getOperatorSummaries()
.stream()
.map(OperatorStats::getMetrics)
.reduce(Metrics.EMPTY, Metrics::mergeWith);
}
@Test(timeOut = 30_000)
public void testPhysicalInputPositions()
{
ResultWithQueryId<MaterializedResult> result = getDistributedQueryRunner().executeWithQueryId(
getSession(),
"SELECT * FROM lineitem JOIN tpch.tiny.supplier ON lineitem.suppkey = supplier.suppkey " +
"AND supplier.name = 'Supplier#000000001'");
assertEquals(result.getResult().getRowCount(), 615);
OperatorStats probeStats = getScanOperatorStats(getDistributedQueryRunner(), result.getQueryId()).stream()
.findFirst().orElseThrow();
assertEquals(probeStats.getInputPositions(), 615);
assertEquals(probeStats.getPhysicalInputPositions(), LINEITEM_COUNT);
}
@Test(timeOut = 30_000, dataProvider = "joinDistributionTypes")
public void testJoinDynamicFilteringNone(JoinDistributionType joinDistributionType)
{
// Probe-side is not scanned at all, due to dynamic filtering:
assertDynamicFiltering(
"SELECT * FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND orders.totalprice < 0",
noJoinReordering(joinDistributionType),
0,
0, ORDERS_COUNT);
}
@Test(timeOut = 30_000, dataProvider = "joinDistributionTypes")
public void testJoinLargeBuildSideDynamicFiltering(JoinDistributionType joinDistributionType)
{
@Language("SQL") String sql = "SELECT * FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey and orders.custkey BETWEEN 300 AND 700";
int expectedRowCount = 15793;
// Probe-side is fully scanned because the build-side is too large for dynamic filtering:
assertDynamicFiltering(
sql,
noJoinReordering(joinDistributionType),
expectedRowCount,
LINEITEM_COUNT, ORDERS_COUNT);
// Probe-side is partially scanned because we extract min/max from large build-side for dynamic filtering
assertDynamicFiltering(
sql,
withLargeDynamicFilters(joinDistributionType),
expectedRowCount,
60139, ORDERS_COUNT);
}
@Test(timeOut = 30_000, dataProvider = "joinDistributionTypes")
public void testJoinDynamicFilteringSingleValue(JoinDistributionType joinDistributionType)
{
assertQueryResult("SELECT orderkey FROM orders WHERE comment = 'nstructions sleep furiously among '", 1L);
assertQueryResult("SELECT COUNT() FROM lineitem WHERE orderkey = 1", 6L);
assertQueryResult("SELECT partkey FROM part WHERE comment = 'onic deposits'", 1552L);
assertQueryResult("SELECT COUNT() FROM lineitem WHERE partkey = 1552", 39L);
// Join lineitem with a single row of orders
assertDynamicFiltering(
"SELECT * FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND orders.comment = 'nstructions sleep furiously among '",
noJoinReordering(joinDistributionType),
6,
6, ORDERS_COUNT);
// Join lineitem with a single row of part
assertDynamicFiltering(
"SELECT l.comment FROM lineitem l, part p WHERE p.partkey = l.partkey AND p.comment = 'onic deposits'",
noJoinReordering(joinDistributionType),
39,
39, PART_COUNT);
}
@Test
public void testJoinDynamicFilteringImplicitCoercion()
{
assertUpdate("CREATE TABLE coerce_test AS SELECT CAST(orderkey as INT) orderkey_int FROM tpch.tiny.lineitem", "SELECT count(*) FROM lineitem");
// Probe-side is partially scanned, dynamic filters from build side are coerced to the probe column type
assertDynamicFiltering(
"SELECT * FROM coerce_test l JOIN orders o ON l.orderkey_int = o.orderkey AND o.comment = 'nstructions sleep furiously among '",
noJoinReordering(BROADCAST),
6,
6, ORDERS_COUNT);
}
@Test(timeOut = 30_000, dataProvider = "joinDistributionTypes")
public void testJoinDynamicFilteringBlockProbeSide(JoinDistributionType joinDistributionType)
{
// Wait for both build sides to finish before starting the scan of 'lineitem' table (should be very selective given the dynamic filters).
assertDynamicFiltering(
"SELECT l.comment" +
" FROM lineitem l, part p, orders o" +
" WHERE l.orderkey = o.orderkey AND o.comment = 'nstructions sleep furiously among '" +
" AND p.partkey = l.partkey AND p.comment = 'onic deposits'",
noJoinReordering(joinDistributionType),
1,
1, PART_COUNT, ORDERS_COUNT);
}
@Test(timeOut = 30_000, dataProvider = "joinDistributionTypes")
public void testSemiJoinDynamicFilteringNone(JoinDistributionType joinDistributionType)
{
// Probe-side is not scanned at all, due to dynamic filtering:
assertDynamicFiltering(
"SELECT * FROM lineitem WHERE lineitem.orderkey IN (SELECT orders.orderkey FROM orders WHERE orders.totalprice < 0)",
noJoinReordering(joinDistributionType),
0,
0, ORDERS_COUNT);
}
@Test(timeOut = 30_000, dataProvider = "joinDistributionTypes")
public void testSemiJoinLargeBuildSideDynamicFiltering(JoinDistributionType joinDistributionType)
{
// Probe-side is fully scanned because the build-side is too large for dynamic filtering:
@Language("SQL") String sql = "SELECT * FROM lineitem WHERE lineitem.orderkey IN " +
"(SELECT orders.orderkey FROM orders WHERE orders.custkey BETWEEN 300 AND 700)";
int expectedRowCount = 15793;
// Probe-side is fully scanned because the build-side is too large for dynamic filtering:
assertDynamicFiltering(
sql,
noJoinReordering(joinDistributionType),
expectedRowCount,
LINEITEM_COUNT, ORDERS_COUNT);
// Probe-side is partially scanned because we extract min/max from large build-side for dynamic filtering
assertDynamicFiltering(
sql,
withLargeDynamicFilters(joinDistributionType),
expectedRowCount,
60139, ORDERS_COUNT);
}
@Test(timeOut = 30_000, dataProvider = "joinDistributionTypes")
public void testSemiJoinDynamicFilteringSingleValue(JoinDistributionType joinDistributionType)
{
// Join lineitem with a single row of orders
assertDynamicFiltering(
"SELECT * FROM lineitem WHERE lineitem.orderkey IN (SELECT orders.orderkey FROM orders WHERE orders.comment = 'nstructions sleep furiously among ')",
noJoinReordering(joinDistributionType),
6,
6, ORDERS_COUNT);
// Join lineitem with a single row of part
assertDynamicFiltering(
"SELECT l.comment FROM lineitem l WHERE l.partkey IN (SELECT p.partkey FROM part p WHERE p.comment = 'onic deposits')",
noJoinReordering(joinDistributionType),
39,
39, PART_COUNT);
}
@Test(timeOut = 30_000, dataProvider = "joinDistributionTypes")
public void testSemiJoinDynamicFilteringBlockProbeSide(JoinDistributionType joinDistributionType)
{
// Wait for both build sides to finish before starting the scan of 'lineitem' table (should be very selective given the dynamic filters).
assertDynamicFiltering(
"SELECT t.comment FROM " +
"(SELECT * FROM lineitem l WHERE l.orderkey IN (SELECT o.orderkey FROM orders o WHERE o.comment = 'nstructions sleep furiously among ')) t " +
"WHERE t.partkey IN (SELECT p.partkey FROM part p WHERE p.comment = 'onic deposits')",
noJoinReordering(joinDistributionType),
1,
1, ORDERS_COUNT, PART_COUNT);
}
@Test
@Flaky(issue = "https://github.com/trinodb/trino/issues/5172", match = "Lists differ at element")
public void testCrossJoinDynamicFiltering()
{
assertUpdate("DROP TABLE IF EXISTS probe");
assertUpdate("CREATE TABLE probe (k VARCHAR, v INTEGER)");
assertUpdate("INSERT INTO probe VALUES ('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', NULL)", 5);
assertUpdate("DROP TABLE IF EXISTS build");
assertUpdate("CREATE TABLE build (vmin INTEGER, vmax INTEGER)");
assertUpdate("INSERT INTO build VALUES (1, 2), (NULL, NULL)", 2);
Session session = noJoinReordering(BROADCAST);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin", session, 3, 3, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v > vmin", session, 2, 2, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v <= vmax", session, 3, 3, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v < vmax", session, 2, 2, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin AND v < vmax", session, 1, 1, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v > vmin AND v <= vmax", session, 1, 1, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v > vmin AND v < vmax", session, 0, 0, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v > vmin AND vmax < 0", session, 0, 0, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v BETWEEN vmin AND vmax", session, 2, 2, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin AND v <= vmax", session, 2, 2, 2);
assertDynamicFiltering("SELECT * FROM probe, build WHERE v BETWEEN vmin AND vmax", session, 2, 2, 2);
assertDynamicFiltering("SELECT * FROM probe, build WHERE v >= vmin AND v <= vmax", session, 2, 2, 2);
// TODO: support complex inequality join clauses: https://github.com/trinodb/trino/issues/5755
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v BETWEEN vmin AND vmax - 1", session, 1, 3, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v BETWEEN vmin + 1 AND vmax", session, 1, 3, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v BETWEEN vmin + 1 AND vmax - 1", session, 0, 5, 2);
assertDynamicFiltering("SELECT * FROM probe, build WHERE v BETWEEN vmin AND vmax - 1", session, 1, 3, 2);
assertDynamicFiltering("SELECT * FROM probe, build WHERE v BETWEEN vmin + 1 AND vmax", session, 1, 3, 2);
assertDynamicFiltering("SELECT * FROM probe, build WHERE v BETWEEN vmin + 1 AND vmax - 1", session, 0, 5, 2);
// TODO: make sure it works after https://github.com/trinodb/trino/issues/5777 is fixed
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin AND v <= vmax - 1", session, 1, 1, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin + 1 AND v <= vmax", session, 1, 1, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin + 1 AND v <= vmax - 1", session, 0, 0, 2);
// TODO: support complex inequality join clauses: https://github.com/trinodb/trino/issues/5755
assertDynamicFiltering("SELECT * FROM probe, build WHERE v >= vmin AND v <= vmax - 1", session, 1, 3, 2);
assertDynamicFiltering("SELECT * FROM probe, build WHERE v >= vmin + 1 AND v <= vmax", session, 1, 3, 2);
assertDynamicFiltering("SELECT * FROM probe, build WHERE v >= vmin + 1 AND v <= vmax - 1", session, 0, 5, 2);
assertDynamicFiltering("SELECT * FROM probe WHERE v <= (SELECT max(vmax) FROM build)", session, 3, 3, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v IS NOT DISTINCT FROM vmin", session, 2, 2, 2);
}
@Test
public void testIsNotDistinctFromNaN()
{
assertUpdate("DROP TABLE IF EXISTS probe_nan");
assertUpdate("CREATE TABLE probe_nan (v DOUBLE)");
assertUpdate("INSERT INTO probe_nan VALUES 0, 1, 2, NULL, nan()", 5);
assertUpdate("DROP TABLE IF EXISTS build_nan");
assertUpdate("CREATE TABLE build_nan (v DOUBLE)");
assertUpdate("INSERT INTO build_nan VALUES 1, NULL, nan()", 3);
Session session = noJoinReordering(BROADCAST);
assertDynamicFiltering("SELECT * FROM probe_nan p JOIN build_nan b ON p.v IS NOT DISTINCT FROM b.v", session, 3, 5, 3);
assertDynamicFiltering("SELECT * FROM probe_nan p JOIN build_nan b ON p.v = b.v", session, 1, 1, 3);
}
@Test
public void testCrossJoinLargeBuildSideDynamicFiltering()
{
// Probe-side is fully scanned because the build-side is too large for dynamic filtering:
assertDynamicFiltering(
"SELECT * FROM orders o, customer c WHERE o.custkey < c.custkey AND c.name < 'Customer#000001000' AND o.custkey > 1000",
noJoinReordering(BROADCAST),
0,
ORDERS_COUNT, CUSTOMER_COUNT);
}
@Test(timeOut = 30_000, dataProvider = "joinDistributionTypes")
public void testJoinDynamicFilteringMultiJoin(JoinDistributionType joinDistributionType)
{
assertUpdate("DROP TABLE IF EXISTS t0");
assertUpdate("DROP TABLE IF EXISTS t1");
assertUpdate("DROP TABLE IF EXISTS t2");
assertUpdate("CREATE TABLE t0 (k0 integer, v0 real)");
assertUpdate("CREATE TABLE t1 (k1 integer, v1 real)");
assertUpdate("CREATE TABLE t2 (k2 integer, v2 real)");
assertUpdate("INSERT INTO t0 VALUES (1, 1.0)", 1);
assertUpdate("INSERT INTO t1 VALUES (1, 2.0)", 1);
assertUpdate("INSERT INTO t2 VALUES (1, 3.0)", 1);
assertQuery(
noJoinReordering(joinDistributionType),
"SELECT k0, k1, k2 FROM t0, t1, t2 WHERE (k0 = k1) AND (k0 = k2) AND (v0 + v1 = v2)",
"SELECT 1, 1, 1");
}
private void assertDynamicFiltering(@Language("SQL") String selectQuery, Session session, int expectedRowCount, int... expectedOperatorRowsRead)
{
ResultWithQueryId<MaterializedResult> result = getDistributedQueryRunner().executeWithQueryId(session, selectQuery);
assertEquals(result.getResult().getRowCount(), expectedRowCount);
assertEquals(getOperatorRowsRead(getDistributedQueryRunner(), result.getQueryId()), Ints.asList(expectedOperatorRowsRead));
}
private Session withLargeDynamicFilters(JoinDistributionType joinDistributionType)
{
return Session.builder(noJoinReordering(joinDistributionType))
.setSystemProperty(ENABLE_LARGE_DYNAMIC_FILTERS, "true")
.build();
}
private static List<Integer> getOperatorRowsRead(DistributedQueryRunner runner, QueryId queryId)
{
return getScanOperatorStats(runner, queryId).stream()
.map(OperatorStats::getInputPositions)
.map(Math::toIntExact)
.collect(toImmutableList());
}
private static List<OperatorStats> getScanOperatorStats(DistributedQueryRunner runner, QueryId queryId)
{
QueryStats stats = runner.getCoordinator().getQueryManager().getFullQueryInfo(queryId).getQueryStats();
return stats.getOperatorSummaries()
.stream()
.filter(summary -> summary.getOperatorType().contains("Scan"))
.collect(toImmutableList());
}
@Test
public void testCreateTableWithNoData()
{
assertUpdate("CREATE TABLE test_empty (a BIGINT)");
assertQueryResult("SELECT count(*) FROM test_empty", 0L);
assertQueryResult("INSERT INTO test_empty SELECT nationkey FROM tpch.tiny.nation", 25L);
assertQueryResult("SELECT count(*) FROM test_empty", 25L);
}
@Test
public void testCreateFilteredOutTable()
{
assertUpdate("CREATE TABLE filtered_out AS SELECT nationkey FROM tpch.tiny.nation WHERE nationkey < 0", "SELECT count(nationkey) FROM nation WHERE nationkey < 0");
assertQueryResult("SELECT count(*) FROM filtered_out", 0L);
assertQueryResult("INSERT INTO filtered_out SELECT nationkey FROM tpch.tiny.nation", 25L);
assertQueryResult("SELECT count(*) FROM filtered_out", 25L);
}
@Test
public void testSelectFromEmptyTable()
{
assertUpdate("CREATE TABLE test_select_empty AS SELECT * FROM tpch.tiny.nation WHERE nationkey > 1000", "SELECT count(*) FROM nation WHERE nationkey > 1000");
assertQueryResult("SELECT count(*) FROM test_select_empty", 0L);
}
@Test
public void testSelectSingleRow()
{
assertQuery("SELECT * FROM tpch.tiny.nation WHERE nationkey = 1", "SELECT * FROM nation WHERE nationkey = 1");
}
@Test
public void testSelectColumnsSubset()
{
assertQuery("SELECT nationkey, regionkey FROM tpch.tiny.nation ORDER BY nationkey", "SELECT nationkey, regionkey FROM nation ORDER BY nationkey");
}
@Test
public void testCreateTableInNonDefaultSchema()
{
assertUpdate("CREATE SCHEMA schema1");
assertUpdate("CREATE SCHEMA schema2");
assertQueryResult("SHOW SCHEMAS", "default", "information_schema", "schema1", "schema2");
assertUpdate("CREATE TABLE schema1.nation AS SELECT * FROM tpch.tiny.nation WHERE nationkey % 2 = 0", "SELECT count(*) FROM nation WHERE MOD(nationkey, 2) = 0");
assertUpdate("CREATE TABLE schema2.nation AS SELECT * FROM tpch.tiny.nation WHERE nationkey % 2 = 1", "SELECT count(*) FROM nation WHERE MOD(nationkey, 2) = 1");
assertQueryResult("SELECT count(*) FROM schema1.nation", 13L);
assertQueryResult("SELECT count(*) FROM schema2.nation", 12L);
}
@Test
public void testCreateTableAndViewInNotExistSchema()
{
int tablesBeforeCreate = listMemoryTables().size();
assertQueryFails("CREATE TABLE schema3.test_table3 (x date)", "Schema schema3 not found");
assertQueryFails("CREATE VIEW schema4.test_view4 AS SELECT 123 x", "Schema schema4 not found");
assertQueryFails("CREATE OR REPLACE VIEW schema5.test_view5 AS SELECT 123 x", "Schema schema5 not found");
int tablesAfterCreate = listMemoryTables().size();
assertEquals(tablesBeforeCreate, tablesAfterCreate);
}
@Test
public void testViews()
{
@Language("SQL") String query = "SELECT orderkey, orderstatus, totalprice / 2 half FROM orders";
assertUpdate("CREATE VIEW test_view AS SELECT 123 x");
assertUpdate("CREATE OR REPLACE VIEW test_view AS " + query);
assertQueryFails("CREATE TABLE test_view (x date)", "View \\[default.test_view] already exists");
assertQueryFails("CREATE VIEW test_view AS SELECT 123 x", "View already exists: default.test_view");
assertQuery("SELECT * FROM test_view", query);
assertTrue(computeActual("SHOW TABLES").getOnlyColumnAsSet().contains("test_view"));
assertUpdate("DROP VIEW test_view");
assertQueryFails("DROP VIEW test_view", "line 1:1: View 'memory.default.test_view' does not exist");
}
@Test
public void testRenameView()
{
@Language("SQL") String query = "SELECT orderkey, orderstatus, totalprice / 2 half FROM orders";
assertUpdate("CREATE VIEW test_view_to_be_renamed AS " + query);
assertQueryFails("ALTER VIEW test_view_to_be_renamed RENAME TO memory.test_schema_not_exist.test_view_renamed", "Schema test_schema_not_exist not found");
assertUpdate("ALTER VIEW test_view_to_be_renamed RENAME TO test_view_renamed");
assertQuery("SELECT * FROM test_view_renamed", query);
assertUpdate("CREATE SCHEMA test_different_schema");
assertUpdate("ALTER VIEW test_view_renamed RENAME TO test_different_schema.test_view_renamed");
assertQuery("SELECT * FROM test_different_schema.test_view_renamed", query);
assertUpdate("DROP VIEW test_different_schema.test_view_renamed");
assertUpdate("DROP SCHEMA test_different_schema");
}
private List<QualifiedObjectName> listMemoryTables()
{
return getQueryRunner().listTables(getSession(), "memory", "default");
}
private void assertQueryResult(@Language("SQL") String sql, Object... expected)
{
MaterializedResult rows = computeActual(sql);
assertEquals(rows.getRowCount(), expected.length);
for (int i = 0; i < expected.length; i++) {
MaterializedRow materializedRow = rows.getMaterializedRows().get(i);
int fieldCount = materializedRow.getFieldCount();
assertEquals(fieldCount, 1, format("Expected only one column, but got '%d'", fieldCount));
Object value = materializedRow.getField(0);
assertEquals(value, expected[i]);
assertEquals(materializedRow.getFieldCount(), 1);
}
}
}
| plugin/trino-memory/src/test/java/io/trino/plugin/memory/TestMemoryConnectorTest.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.trino.plugin.memory;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.Ints;
import io.trino.Session;
import io.trino.execution.QueryStats;
import io.trino.metadata.QualifiedObjectName;
import io.trino.operator.OperatorStats;
import io.trino.plugin.base.metrics.LongCount;
import io.trino.spi.QueryId;
import io.trino.spi.metrics.Count;
import io.trino.spi.metrics.Metrics;
import io.trino.testing.BaseConnectorTest;
import io.trino.testing.DistributedQueryRunner;
import io.trino.testing.MaterializedResult;
import io.trino.testing.MaterializedRow;
import io.trino.testing.QueryRunner;
import io.trino.testing.ResultWithQueryId;
import io.trino.testing.TestingConnectorBehavior;
import io.trino.testing.sql.TestTable;
import io.trino.testng.services.Flaky;
import io.trino.tpch.TpchTable;
import org.intellij.lang.annotations.Language;
import org.testng.SkipException;
import org.testng.annotations.Test;
import java.util.List;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static io.trino.SystemSessionProperties.ENABLE_LARGE_DYNAMIC_FILTERS;
import static io.trino.plugin.memory.MemoryQueryRunner.createMemoryQueryRunner;
import static io.trino.sql.analyzer.FeaturesConfig.JoinDistributionType;
import static io.trino.sql.analyzer.FeaturesConfig.JoinDistributionType.BROADCAST;
import static io.trino.testing.assertions.Assert.assertEquals;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.testng.Assert.assertTrue;
public class TestMemoryConnectorTest
extends BaseConnectorTest
{
private static final int LINEITEM_COUNT = 60175;
private static final int ORDERS_COUNT = 15000;
private static final int PART_COUNT = 2000;
private static final int CUSTOMER_COUNT = 1500;
@Override
protected QueryRunner createQueryRunner()
throws Exception
{
return createMemoryQueryRunner(
// Adjust DF limits to test edge cases
ImmutableMap.<String, String>builder()
.put("dynamic-filtering.small-broadcast.max-distinct-values-per-driver", "100")
.put("dynamic-filtering.small-broadcast.range-row-limit-per-driver", "100")
.put("dynamic-filtering.large-broadcast.max-distinct-values-per-driver", "100")
.put("dynamic-filtering.large-broadcast.range-row-limit-per-driver", "100000")
.put("dynamic-filtering.large-partitioned.max-distinct-values-per-driver", "100")
.put("dynamic-filtering.large-partitioned.range-row-limit-per-driver", "100000")
// disable semi join to inner join rewrite to test semi join operators explicitly
.put("optimizer.rewrite-filtering-semi-join-to-inner-join", "false")
.build(),
ImmutableSet.<TpchTable<?>>builder()
.addAll(REQUIRED_TPCH_TABLES)
.add(TpchTable.PART)
.add(TpchTable.LINE_ITEM)
.build());
}
@Override
protected boolean hasBehavior(TestingConnectorBehavior connectorBehavior)
{
switch (connectorBehavior) {
case SUPPORTS_PREDICATE_PUSHDOWN:
case SUPPORTS_LIMIT_PUSHDOWN:
case SUPPORTS_TOPN_PUSHDOWN:
case SUPPORTS_AGGREGATION_PUSHDOWN:
return false;
case SUPPORTS_ADD_COLUMN:
case SUPPORTS_DROP_COLUMN:
case SUPPORTS_RENAME_COLUMN:
return false;
case SUPPORTS_COMMENT_ON_TABLE:
case SUPPORTS_COMMENT_ON_COLUMN:
return false;
case SUPPORTS_RENAME_SCHEMA:
return false;
case SUPPORTS_CREATE_VIEW:
return true;
default:
return super.hasBehavior(connectorBehavior);
}
}
@Override
protected TestTable createTableWithDefaultColumns()
{
throw new SkipException("Cassandra connector does not support column default values");
}
@Test
public void testCreateAndDropTable()
{
int tablesBeforeCreate = listMemoryTables().size();
assertUpdate("CREATE TABLE test AS SELECT * FROM tpch.tiny.nation", "SELECT count(*) FROM nation");
assertEquals(listMemoryTables().size(), tablesBeforeCreate + 1);
assertUpdate("DROP TABLE test");
assertEquals(listMemoryTables().size(), tablesBeforeCreate);
}
// it has to be RuntimeException as FailureInfo$FailureException is private
@Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "line 1:1: Destination table 'memory.default.nation' already exists")
public void testCreateTableWhenTableIsAlreadyCreated()
{
@Language("SQL") String createTableSql = "CREATE TABLE nation AS SELECT * FROM tpch.tiny.nation";
assertUpdate(createTableSql);
}
@Test
public void testSelect()
{
assertUpdate("CREATE TABLE test_select AS SELECT * FROM tpch.tiny.nation", "SELECT count(*) FROM nation");
assertQuery("SELECT * FROM test_select ORDER BY nationkey", "SELECT * FROM nation ORDER BY nationkey");
assertQueryResult("INSERT INTO test_select SELECT * FROM tpch.tiny.nation", 25L);
assertQueryResult("INSERT INTO test_select SELECT * FROM tpch.tiny.nation", 25L);
assertQueryResult("SELECT count(*) FROM test_select", 75L);
}
@Test
// TODO (https://github.com/trinodb/trino/issues/8691) fix the test
@Flaky(issue = "https://github.com/trinodb/trino/issues/8691", match = "ComparisonFailure: expected:<LongCount\\{total=\\[\\d+]}> but was:<LongCount\\{total=\\[\\d+]}>")
public void testCustomMetricsScanFilter()
{
Metrics metrics = collectCustomMetrics("SELECT partkey FROM part WHERE partkey % 1000 > 0");
assertThat(metrics.getMetrics().get("rows")).isEqualTo(new LongCount(PART_COUNT));
assertThat(metrics.getMetrics().get("started")).isEqualTo(metrics.getMetrics().get("finished"));
assertThat(((Count) metrics.getMetrics().get("finished")).getTotal()).isGreaterThan(0);
}
@Test
public void testCustomMetricsScanOnly()
{
Metrics metrics = collectCustomMetrics("SELECT partkey FROM part");
assertThat(metrics.getMetrics().get("rows")).isEqualTo(new LongCount(PART_COUNT));
assertThat(metrics.getMetrics().get("started")).isEqualTo(metrics.getMetrics().get("finished"));
assertThat(((Count) metrics.getMetrics().get("finished")).getTotal()).isGreaterThan(0);
}
private Metrics collectCustomMetrics(String sql)
{
DistributedQueryRunner runner = (DistributedQueryRunner) getQueryRunner();
ResultWithQueryId<MaterializedResult> result = runner.executeWithQueryId(getSession(), sql);
return runner
.getCoordinator()
.getQueryManager()
.getFullQueryInfo(result.getQueryId())
.getQueryStats()
.getOperatorSummaries()
.stream()
.map(OperatorStats::getMetrics)
.reduce(Metrics.EMPTY, Metrics::mergeWith);
}
@Test(timeOut = 30_000)
public void testPhysicalInputPositions()
{
ResultWithQueryId<MaterializedResult> result = getDistributedQueryRunner().executeWithQueryId(
getSession(),
"SELECT * FROM lineitem JOIN tpch.tiny.supplier ON lineitem.suppkey = supplier.suppkey " +
"AND supplier.name = 'Supplier#000000001'");
assertEquals(result.getResult().getRowCount(), 615);
OperatorStats probeStats = getScanOperatorStats(getDistributedQueryRunner(), result.getQueryId()).stream()
.findFirst().orElseThrow();
assertEquals(probeStats.getInputPositions(), 615);
assertEquals(probeStats.getPhysicalInputPositions(), LINEITEM_COUNT);
}
@Test(timeOut = 30_000, dataProvider = "joinDistributionTypes")
public void testJoinDynamicFilteringNone(JoinDistributionType joinDistributionType)
{
// Probe-side is not scanned at all, due to dynamic filtering:
assertDynamicFiltering(
"SELECT * FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND orders.totalprice < 0",
noJoinReordering(joinDistributionType),
0,
0, ORDERS_COUNT);
}
@Test(timeOut = 30_000, dataProvider = "joinDistributionTypes")
public void testJoinLargeBuildSideDynamicFiltering(JoinDistributionType joinDistributionType)
{
@Language("SQL") String sql = "SELECT * FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey and orders.custkey BETWEEN 300 AND 700";
int expectedRowCount = 15793;
// Probe-side is fully scanned because the build-side is too large for dynamic filtering:
assertDynamicFiltering(
sql,
noJoinReordering(joinDistributionType),
expectedRowCount,
LINEITEM_COUNT, ORDERS_COUNT);
// Probe-side is partially scanned because we extract min/max from large build-side for dynamic filtering
assertDynamicFiltering(
sql,
withLargeDynamicFilters(joinDistributionType),
expectedRowCount,
60139, ORDERS_COUNT);
}
@Test(timeOut = 30_000, dataProvider = "joinDistributionTypes")
public void testJoinDynamicFilteringSingleValue(JoinDistributionType joinDistributionType)
{
assertQueryResult("SELECT orderkey FROM orders WHERE comment = 'nstructions sleep furiously among '", 1L);
assertQueryResult("SELECT COUNT() FROM lineitem WHERE orderkey = 1", 6L);
assertQueryResult("SELECT partkey FROM part WHERE comment = 'onic deposits'", 1552L);
assertQueryResult("SELECT COUNT() FROM lineitem WHERE partkey = 1552", 39L);
// Join lineitem with a single row of orders
assertDynamicFiltering(
"SELECT * FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND orders.comment = 'nstructions sleep furiously among '",
noJoinReordering(joinDistributionType),
6,
6, ORDERS_COUNT);
// Join lineitem with a single row of part
assertDynamicFiltering(
"SELECT l.comment FROM lineitem l, part p WHERE p.partkey = l.partkey AND p.comment = 'onic deposits'",
noJoinReordering(joinDistributionType),
39,
39, PART_COUNT);
}
@Test
public void testJoinDynamicFilteringImplicitCoercion()
{
assertUpdate("CREATE TABLE coerce_test AS SELECT CAST(orderkey as INT) orderkey_int FROM tpch.tiny.lineitem", "SELECT count(*) FROM lineitem");
// Probe-side is partially scanned, dynamic filters from build side are coerced to the probe column type
assertDynamicFiltering(
"SELECT * FROM coerce_test l JOIN orders o ON l.orderkey_int = o.orderkey AND o.comment = 'nstructions sleep furiously among '",
noJoinReordering(BROADCAST),
6,
6, ORDERS_COUNT);
}
@Test(timeOut = 30_000, dataProvider = "joinDistributionTypes")
public void testJoinDynamicFilteringBlockProbeSide(JoinDistributionType joinDistributionType)
{
// Wait for both build sides to finish before starting the scan of 'lineitem' table (should be very selective given the dynamic filters).
assertDynamicFiltering(
"SELECT l.comment" +
" FROM lineitem l, part p, orders o" +
" WHERE l.orderkey = o.orderkey AND o.comment = 'nstructions sleep furiously among '" +
" AND p.partkey = l.partkey AND p.comment = 'onic deposits'",
noJoinReordering(joinDistributionType),
1,
1, PART_COUNT, ORDERS_COUNT);
}
@Test(timeOut = 30_000, dataProvider = "joinDistributionTypes")
public void testSemiJoinDynamicFilteringNone(JoinDistributionType joinDistributionType)
{
// Probe-side is not scanned at all, due to dynamic filtering:
assertDynamicFiltering(
"SELECT * FROM lineitem WHERE lineitem.orderkey IN (SELECT orders.orderkey FROM orders WHERE orders.totalprice < 0)",
noJoinReordering(joinDistributionType),
0,
0, ORDERS_COUNT);
}
@Test(timeOut = 30_000, dataProvider = "joinDistributionTypes")
public void testSemiJoinLargeBuildSideDynamicFiltering(JoinDistributionType joinDistributionType)
{
// Probe-side is fully scanned because the build-side is too large for dynamic filtering:
@Language("SQL") String sql = "SELECT * FROM lineitem WHERE lineitem.orderkey IN " +
"(SELECT orders.orderkey FROM orders WHERE orders.custkey BETWEEN 300 AND 700)";
int expectedRowCount = 15793;
// Probe-side is fully scanned because the build-side is too large for dynamic filtering:
assertDynamicFiltering(
sql,
noJoinReordering(joinDistributionType),
expectedRowCount,
LINEITEM_COUNT, ORDERS_COUNT);
// Probe-side is partially scanned because we extract min/max from large build-side for dynamic filtering
assertDynamicFiltering(
sql,
withLargeDynamicFilters(joinDistributionType),
expectedRowCount,
60139, ORDERS_COUNT);
}
@Test(timeOut = 30_000, dataProvider = "joinDistributionTypes")
public void testSemiJoinDynamicFilteringSingleValue(JoinDistributionType joinDistributionType)
{
// Join lineitem with a single row of orders
assertDynamicFiltering(
"SELECT * FROM lineitem WHERE lineitem.orderkey IN (SELECT orders.orderkey FROM orders WHERE orders.comment = 'nstructions sleep furiously among ')",
noJoinReordering(joinDistributionType),
6,
6, ORDERS_COUNT);
// Join lineitem with a single row of part
assertDynamicFiltering(
"SELECT l.comment FROM lineitem l WHERE l.partkey IN (SELECT p.partkey FROM part p WHERE p.comment = 'onic deposits')",
noJoinReordering(joinDistributionType),
39,
39, PART_COUNT);
}
@Test(timeOut = 30_000, dataProvider = "joinDistributionTypes")
public void testSemiJoinDynamicFilteringBlockProbeSide(JoinDistributionType joinDistributionType)
{
// Wait for both build sides to finish before starting the scan of 'lineitem' table (should be very selective given the dynamic filters).
assertDynamicFiltering(
"SELECT t.comment FROM " +
"(SELECT * FROM lineitem l WHERE l.orderkey IN (SELECT o.orderkey FROM orders o WHERE o.comment = 'nstructions sleep furiously among ')) t " +
"WHERE t.partkey IN (SELECT p.partkey FROM part p WHERE p.comment = 'onic deposits')",
noJoinReordering(joinDistributionType),
1,
1, ORDERS_COUNT, PART_COUNT);
}
@Test
@Flaky(issue = "https://github.com/trinodb/trino/issues/5172", match = "Lists differ at element")
public void testCrossJoinDynamicFiltering()
{
assertUpdate("DROP TABLE IF EXISTS probe");
assertUpdate("CREATE TABLE probe (k VARCHAR, v INTEGER)");
assertUpdate("INSERT INTO probe VALUES ('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', NULL)", 5);
assertUpdate("DROP TABLE IF EXISTS build");
assertUpdate("CREATE TABLE build (vmin INTEGER, vmax INTEGER)");
assertUpdate("INSERT INTO build VALUES (1, 2), (NULL, NULL)", 2);
Session session = noJoinReordering(BROADCAST);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin", session, 3, 3, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v > vmin", session, 2, 2, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v <= vmax", session, 3, 3, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v < vmax", session, 2, 2, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin AND v < vmax", session, 1, 1, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v > vmin AND v <= vmax", session, 1, 1, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v > vmin AND v < vmax", session, 0, 0, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v > vmin AND vmax < 0", session, 0, 0, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v BETWEEN vmin AND vmax", session, 2, 2, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin AND v <= vmax", session, 2, 2, 2);
assertDynamicFiltering("SELECT * FROM probe, build WHERE v BETWEEN vmin AND vmax", session, 2, 2, 2);
assertDynamicFiltering("SELECT * FROM probe, build WHERE v >= vmin AND v <= vmax", session, 2, 2, 2);
// TODO: support complex inequality join clauses: https://github.com/trinodb/trino/issues/5755
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v BETWEEN vmin AND vmax - 1", session, 1, 3, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v BETWEEN vmin + 1 AND vmax", session, 1, 3, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v BETWEEN vmin + 1 AND vmax - 1", session, 0, 5, 2);
assertDynamicFiltering("SELECT * FROM probe, build WHERE v BETWEEN vmin AND vmax - 1", session, 1, 3, 2);
assertDynamicFiltering("SELECT * FROM probe, build WHERE v BETWEEN vmin + 1 AND vmax", session, 1, 3, 2);
assertDynamicFiltering("SELECT * FROM probe, build WHERE v BETWEEN vmin + 1 AND vmax - 1", session, 0, 5, 2);
// TODO: make sure it works after https://github.com/trinodb/trino/issues/5777 is fixed
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin AND v <= vmax - 1", session, 1, 1, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin + 1 AND v <= vmax", session, 1, 1, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v >= vmin + 1 AND v <= vmax - 1", session, 0, 0, 2);
// TODO: support complex inequality join clauses: https://github.com/trinodb/trino/issues/5755
assertDynamicFiltering("SELECT * FROM probe, build WHERE v >= vmin AND v <= vmax - 1", session, 1, 3, 2);
assertDynamicFiltering("SELECT * FROM probe, build WHERE v >= vmin + 1 AND v <= vmax", session, 1, 3, 2);
assertDynamicFiltering("SELECT * FROM probe, build WHERE v >= vmin + 1 AND v <= vmax - 1", session, 0, 5, 2);
assertDynamicFiltering("SELECT * FROM probe WHERE v <= (SELECT max(vmax) FROM build)", session, 3, 3, 2);
assertDynamicFiltering("SELECT * FROM probe JOIN build ON v IS NOT DISTINCT FROM vmin", session, 2, 2, 2);
}
@Test
public void testIsNotDistinctFromNaN()
{
assertUpdate("DROP TABLE IF EXISTS probe_nan");
assertUpdate("CREATE TABLE probe_nan (v DOUBLE)");
assertUpdate("INSERT INTO probe_nan VALUES 0, 1, 2, NULL, nan()", 5);
assertUpdate("DROP TABLE IF EXISTS build_nan");
assertUpdate("CREATE TABLE build_nan (v DOUBLE)");
assertUpdate("INSERT INTO build_nan VALUES 1, NULL, nan()", 3);
Session session = noJoinReordering(BROADCAST);
assertDynamicFiltering("SELECT * FROM probe_nan p JOIN build_nan b ON p.v IS NOT DISTINCT FROM b.v", session, 3, 5, 3);
assertDynamicFiltering("SELECT * FROM probe_nan p JOIN build_nan b ON p.v = b.v", session, 1, 1, 3);
}
@Test
public void testCrossJoinLargeBuildSideDynamicFiltering()
{
// Probe-side is fully scanned because the build-side is too large for dynamic filtering:
assertDynamicFiltering(
"SELECT * FROM orders o, customer c WHERE o.custkey < c.custkey AND c.name < 'Customer#000001000' AND o.custkey > 1000",
noJoinReordering(BROADCAST),
0,
ORDERS_COUNT, CUSTOMER_COUNT);
}
@Test(timeOut = 30_000, dataProvider = "joinDistributionTypes")
public void testJoinDynamicFilteringMultiJoin(JoinDistributionType joinDistributionType)
{
assertUpdate("DROP TABLE IF EXISTS t0");
assertUpdate("DROP TABLE IF EXISTS t1");
assertUpdate("DROP TABLE IF EXISTS t2");
assertUpdate("CREATE TABLE t0 (k0 integer, v0 real)");
assertUpdate("CREATE TABLE t1 (k1 integer, v1 real)");
assertUpdate("CREATE TABLE t2 (k2 integer, v2 real)");
assertUpdate("INSERT INTO t0 VALUES (1, 1.0)", 1);
assertUpdate("INSERT INTO t1 VALUES (1, 2.0)", 1);
assertUpdate("INSERT INTO t2 VALUES (1, 3.0)", 1);
assertQuery(
noJoinReordering(joinDistributionType),
"SELECT k0, k1, k2 FROM t0, t1, t2 WHERE (k0 = k1) AND (k0 = k2) AND (v0 + v1 = v2)",
"SELECT 1, 1, 1");
}
private void assertDynamicFiltering(@Language("SQL") String selectQuery, Session session, int expectedRowCount, int... expectedOperatorRowsRead)
{
ResultWithQueryId<MaterializedResult> result = getDistributedQueryRunner().executeWithQueryId(session, selectQuery);
assertEquals(result.getResult().getRowCount(), expectedRowCount);
assertEquals(getOperatorRowsRead(getDistributedQueryRunner(), result.getQueryId()), Ints.asList(expectedOperatorRowsRead));
}
private Session withLargeDynamicFilters(JoinDistributionType joinDistributionType)
{
return Session.builder(noJoinReordering(joinDistributionType))
.setSystemProperty(ENABLE_LARGE_DYNAMIC_FILTERS, "true")
.build();
}
private static List<Integer> getOperatorRowsRead(DistributedQueryRunner runner, QueryId queryId)
{
return getScanOperatorStats(runner, queryId).stream()
.map(OperatorStats::getInputPositions)
.map(Math::toIntExact)
.collect(toImmutableList());
}
private static List<OperatorStats> getScanOperatorStats(DistributedQueryRunner runner, QueryId queryId)
{
QueryStats stats = runner.getCoordinator().getQueryManager().getFullQueryInfo(queryId).getQueryStats();
return stats.getOperatorSummaries()
.stream()
.filter(summary -> summary.getOperatorType().contains("Scan"))
.collect(toImmutableList());
}
@Test
public void testCreateTableWithNoData()
{
assertUpdate("CREATE TABLE test_empty (a BIGINT)");
assertQueryResult("SELECT count(*) FROM test_empty", 0L);
assertQueryResult("INSERT INTO test_empty SELECT nationkey FROM tpch.tiny.nation", 25L);
assertQueryResult("SELECT count(*) FROM test_empty", 25L);
}
@Test
public void testCreateFilteredOutTable()
{
assertUpdate("CREATE TABLE filtered_out AS SELECT nationkey FROM tpch.tiny.nation WHERE nationkey < 0", "SELECT count(nationkey) FROM nation WHERE nationkey < 0");
assertQueryResult("SELECT count(*) FROM filtered_out", 0L);
assertQueryResult("INSERT INTO filtered_out SELECT nationkey FROM tpch.tiny.nation", 25L);
assertQueryResult("SELECT count(*) FROM filtered_out", 25L);
}
@Test
public void testSelectFromEmptyTable()
{
assertUpdate("CREATE TABLE test_select_empty AS SELECT * FROM tpch.tiny.nation WHERE nationkey > 1000", "SELECT count(*) FROM nation WHERE nationkey > 1000");
assertQueryResult("SELECT count(*) FROM test_select_empty", 0L);
}
@Test
public void testSelectSingleRow()
{
assertQuery("SELECT * FROM tpch.tiny.nation WHERE nationkey = 1", "SELECT * FROM nation WHERE nationkey = 1");
}
@Test
public void testSelectColumnsSubset()
{
assertQuery("SELECT nationkey, regionkey FROM tpch.tiny.nation ORDER BY nationkey", "SELECT nationkey, regionkey FROM nation ORDER BY nationkey");
}
@Test
public void testCreateTableInNonDefaultSchema()
{
assertUpdate("CREATE SCHEMA schema1");
assertUpdate("CREATE SCHEMA schema2");
assertQueryResult("SHOW SCHEMAS", "default", "information_schema", "schema1", "schema2");
assertUpdate("CREATE TABLE schema1.nation AS SELECT * FROM tpch.tiny.nation WHERE nationkey % 2 = 0", "SELECT count(*) FROM nation WHERE MOD(nationkey, 2) = 0");
assertUpdate("CREATE TABLE schema2.nation AS SELECT * FROM tpch.tiny.nation WHERE nationkey % 2 = 1", "SELECT count(*) FROM nation WHERE MOD(nationkey, 2) = 1");
assertQueryResult("SELECT count(*) FROM schema1.nation", 13L);
assertQueryResult("SELECT count(*) FROM schema2.nation", 12L);
}
@Test
public void testCreateTableAndViewInNotExistSchema()
{
int tablesBeforeCreate = listMemoryTables().size();
assertQueryFails("CREATE TABLE schema3.test_table3 (x date)", "Schema schema3 not found");
assertQueryFails("CREATE VIEW schema4.test_view4 AS SELECT 123 x", "Schema schema4 not found");
assertQueryFails("CREATE OR REPLACE VIEW schema5.test_view5 AS SELECT 123 x", "Schema schema5 not found");
int tablesAfterCreate = listMemoryTables().size();
assertEquals(tablesBeforeCreate, tablesAfterCreate);
}
@Test
public void testViews()
{
@Language("SQL") String query = "SELECT orderkey, orderstatus, totalprice / 2 half FROM orders";
assertUpdate("CREATE VIEW test_view AS SELECT 123 x");
assertUpdate("CREATE OR REPLACE VIEW test_view AS " + query);
assertQueryFails("CREATE TABLE test_view (x date)", "View \\[default.test_view] already exists");
assertQueryFails("CREATE VIEW test_view AS SELECT 123 x", "View already exists: default.test_view");
assertQuery("SELECT * FROM test_view", query);
assertTrue(computeActual("SHOW TABLES").getOnlyColumnAsSet().contains("test_view"));
assertUpdate("DROP VIEW test_view");
assertQueryFails("DROP VIEW test_view", "line 1:1: View 'memory.default.test_view' does not exist");
}
@Test
public void testRenameView()
{
@Language("SQL") String query = "SELECT orderkey, orderstatus, totalprice / 2 half FROM orders";
assertUpdate("CREATE VIEW test_view_to_be_renamed AS " + query);
assertQueryFails("ALTER VIEW test_view_to_be_renamed RENAME TO memory.test_schema_not_exist.test_view_renamed", "Schema test_schema_not_exist not found");
assertUpdate("ALTER VIEW test_view_to_be_renamed RENAME TO test_view_renamed");
assertQuery("SELECT * FROM test_view_renamed", query);
assertUpdate("CREATE SCHEMA test_different_schema");
assertUpdate("ALTER VIEW test_view_renamed RENAME TO test_different_schema.test_view_renamed");
assertQuery("SELECT * FROM test_different_schema.test_view_renamed", query);
assertUpdate("DROP VIEW test_different_schema.test_view_renamed");
assertUpdate("DROP SCHEMA test_different_schema");
}
private List<QualifiedObjectName> listMemoryTables()
{
return getQueryRunner().listTables(getSession(), "memory", "default");
}
private void assertQueryResult(@Language("SQL") String sql, Object... expected)
{
MaterializedResult rows = computeActual(sql);
assertEquals(rows.getRowCount(), expected.length);
for (int i = 0; i < expected.length; i++) {
MaterializedRow materializedRow = rows.getMaterializedRows().get(i);
int fieldCount = materializedRow.getFieldCount();
assertEquals(fieldCount, 1, format("Expected only one column, but got '%d'", fieldCount));
Object value = materializedRow.getField(0);
assertEquals(value, expected[i]);
assertEquals(materializedRow.getFieldCount(), 1);
}
}
}
| Remove obsolete test
AbstractTestDistributedQueries already runs testCreateTable which
creates a table, drops it and then asserts that the table is indeed
dropped.
| plugin/trino-memory/src/test/java/io/trino/plugin/memory/TestMemoryConnectorTest.java | Remove obsolete test | <ide><path>lugin/trino-memory/src/test/java/io/trino/plugin/memory/TestMemoryConnectorTest.java
<ide> throw new SkipException("Cassandra connector does not support column default values");
<ide> }
<ide>
<del> @Test
<del> public void testCreateAndDropTable()
<del> {
<del> int tablesBeforeCreate = listMemoryTables().size();
<del> assertUpdate("CREATE TABLE test AS SELECT * FROM tpch.tiny.nation", "SELECT count(*) FROM nation");
<del> assertEquals(listMemoryTables().size(), tablesBeforeCreate + 1);
<del>
<del> assertUpdate("DROP TABLE test");
<del> assertEquals(listMemoryTables().size(), tablesBeforeCreate);
<del> }
<del>
<ide> // it has to be RuntimeException as FailureInfo$FailureException is private
<ide> @Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "line 1:1: Destination table 'memory.default.nation' already exists")
<ide> public void testCreateTableWhenTableIsAlreadyCreated() |
|
Java | mpl-2.0 | 7297ae7f1f57e6eff3ce3a4033f49a6cc2b5b728 | 0 | vertretungsplanme/substitution-schedule-parser,vertretungsplanme/substitution-schedule-parser | /*
* substitution-schedule-parser - Java library for parsing schools' substitution schedules
* Copyright (c) 2016 Johan v. Forstner
*
* 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 https://mozilla.org/MPL/2.0/.
*/
package me.vertretungsplan.parser;
import me.vertretungsplan.exception.CredentialInvalidException;
import me.vertretungsplan.objects.SubstitutionSchedule;
import me.vertretungsplan.objects.SubstitutionScheduleData;
import me.vertretungsplan.objects.credential.UserPasswordCredential;
import org.apache.http.client.HttpResponseException;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.parser.Parser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Parser for substitution schedules in XML format created by the <a href="http://indiware.de/">Indiware</a>
* software and hosted on <a href="https://www.stundenplan24.de/">Stundenplan24.de</a>. Schools only providing the
* mobile version ("Indiware mobil") of the schedule instead of the desktop version ("Vertretungsplan") are currently
* not supported. The parser also supports schedules in the same format hosted on different URLs.
* <p>
* This parser can be accessed using <code>"stundenplan24"</code> for {@link SubstitutionScheduleData#setApi(String)}.
*
* <h4>Configuration parameters</h4>
* These parameters can be supplied in {@link SubstitutionScheduleData#setData(JSONObject)} to configure the parser:
*
* <dl>
* <dt><code>schoolNumber</code> (String, required if <code>baseurl</code> not specified)</dt>
* <dd>The 8-digit school number used to access the schedule. It can be found in the URL.</dd>
*
* <dl>
* <dt><code>baseurl</code> (String, required if <code>schoolNumber</code> not specified)</dt>
* <dd>Schedule hosted on a custom URL. The URL normally ends with "/vplan" (without slash at the end).</dd>
*
* <dt><code>classes</code> (Array of Strings, required)</dt>
* <dd>The list of all classes, as they can appear in the schedule</dd>
* </dl>
*
* When specifying <code>schoolNumber</code>, you have to use a
* {@link me.vertretungsplan.objects.authentication.UserPasswordAuthenticationData}
* because all schedules on Stundenplan24.de seem to be protected by a login. Schedules on custom URLs may use
* different kinds of login, in that case the parameters from {@link LoginHandler} are supported.
*/
public class IndiwareStundenplan24Parser extends IndiwareParser {
private static final int MAX_DAYS = 7;
private static final String ENCODING = "UTF-8";
public IndiwareStundenplan24Parser(SubstitutionScheduleData scheduleData,
CookieProvider cookieProvider) {
super(scheduleData, cookieProvider);
}
@Override
public SubstitutionSchedule getSubstitutionSchedule()
throws IOException, JSONException, CredentialInvalidException {
String baseurl;
boolean isTeacher;
if (data.has("schoolNumber")) {
isTeacher = scheduleData.getType() == SubstitutionSchedule.Type.TEACHER;
baseurl = "https://www.stundenplan24.de/" + data.getString("schoolNumber") +
(isTeacher ? "/vplanle/" : "/vplan/");
if (credential == null || !(credential instanceof UserPasswordCredential)) {
throw new IOException("no login");
}
String login = ((UserPasswordCredential) credential).getUsername();
String password = ((UserPasswordCredential) credential).getPassword();
executor.auth(login, password);
} else {
baseurl = data.getString("baseurl") + "/";
isTeacher = data.getString("baseurl").endsWith("vplanle") || data.optBoolean("teacher");
new LoginHandler(scheduleData, credential, cookieProvider).handleLogin(executor, cookieStore);
}
List<Document> docs = new ArrayList<>();
for (int i = 0; i < MAX_DAYS; i++) {
LocalDate date = LocalDate.now().plusDays(i);
String dateStr = DateTimeFormat.forPattern("yyyyMMdd").print(date);
String suffix = isTeacher ? "Le" : "Kl";
String url = baseurl + "vdaten/Vplan" + suffix + dateStr + ".xml?_=" + System.currentTimeMillis();
try {
String xml = httpGet(url, ENCODING);
Document doc = Jsoup.parse(xml, url, Parser.xmlParser());
if (doc.select("kopf datei").text().equals("Vplan" + suffix + dateStr + ".xml")) {
docs.add(doc);
}
} catch (HttpResponseException e) {
if (e.getStatusCode() != 404 && e.getStatusCode() != 300) throw e;
}
}
SubstitutionSchedule v = SubstitutionSchedule.fromData(scheduleData);
for (Document doc : docs) {
v.addDay(parseIndiwareDay(doc, false));
}
v.setWebsite(baseurl);
v.setClasses(getAllClasses());
v.setTeachers(getAllTeachers());
return v;
}
}
| parser/src/main/java/me/vertretungsplan/parser/IndiwareStundenplan24Parser.java | /*
* substitution-schedule-parser - Java library for parsing schools' substitution schedules
* Copyright (c) 2016 Johan v. Forstner
*
* 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 https://mozilla.org/MPL/2.0/.
*/
package me.vertretungsplan.parser;
import me.vertretungsplan.exception.CredentialInvalidException;
import me.vertretungsplan.objects.SubstitutionSchedule;
import me.vertretungsplan.objects.SubstitutionScheduleData;
import me.vertretungsplan.objects.credential.UserPasswordCredential;
import org.apache.http.client.HttpResponseException;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.parser.Parser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Parser for substitution schedules in XML format created by the <a href="http://indiware.de/">Indiware</a>
* software and hosted on <a href="https://www.stundenplan24.de/">Stundenplan24.de</a>. Schools only providing the
* mobile version ("Indiware mobil") of the schedule instead of the desktop version ("Vertretungsplan") are currently
* not supported. The parser also supports schedules in the same format hosted on different URLs.
* <p>
* This parser can be accessed using <code>"stundenplan24"</code> for {@link SubstitutionScheduleData#setApi(String)}.
*
* <h4>Configuration parameters</h4>
* These parameters can be supplied in {@link SubstitutionScheduleData#setData(JSONObject)} to configure the parser:
*
* <dl>
* <dt><code>schoolNumber</code> (String, required if <code>baseurl</code> not specified)</dt>
* <dd>The 8-digit school number used to access the schedule. It can be found in the URL.</dd>
*
* <dl>
* <dt><code>baseurl</code> (String, required if <code>schoolNumber</code> not specified)</dt>
* <dd>Schedule hosted on a custom URL. The URL normally ends with "/vplan" (without slash at the end).</dd>
*
* <dt><code>classes</code> (Array of Strings, required)</dt>
* <dd>The list of all classes, as they can appear in the schedule</dd>
* </dl>
*
* When specifying <code>schoolNumber</code>, you have to use a
* {@link me.vertretungsplan.objects.authentication.UserPasswordAuthenticationData}
* because all schedules on Stundenplan24.de seem to be protected by a login. Schedules on custom URLs may use
* different kinds of login, in that case the parameters from {@link LoginHandler} are supported.
*/
public class IndiwareStundenplan24Parser extends IndiwareParser {
private static final int MAX_DAYS = 7;
private static final String ENCODING = "UTF-8";
public IndiwareStundenplan24Parser(SubstitutionScheduleData scheduleData,
CookieProvider cookieProvider) {
super(scheduleData, cookieProvider);
}
@Override
public SubstitutionSchedule getSubstitutionSchedule()
throws IOException, JSONException, CredentialInvalidException {
String baseurl;
boolean isTeacher;
if (data.has("schoolNumber")) {
isTeacher = scheduleData.getType() == SubstitutionSchedule.Type.TEACHER;
baseurl = "https://www.stundenplan24.de/" + data.getString("schoolNumber") +
(isTeacher ? "/vplanle/" : "/vplan/");
if (credential == null || !(credential instanceof UserPasswordCredential)) {
throw new IOException("no login");
}
String login = ((UserPasswordCredential) credential).getUsername();
String password = ((UserPasswordCredential) credential).getPassword();
executor.auth(login, password);
} else {
baseurl = data.getString("baseurl") + "/";
isTeacher = data.getString("baseurl").endsWith("vplanle");
new LoginHandler(scheduleData, credential, cookieProvider).handleLogin(executor, cookieStore);
}
List<Document> docs = new ArrayList<>();
for (int i = 0; i < MAX_DAYS; i++) {
LocalDate date = LocalDate.now().plusDays(i);
String dateStr = DateTimeFormat.forPattern("yyyyMMdd").print(date);
String suffix = isTeacher ? "Le" : "Kl";
String url = baseurl + "vdaten/Vplan" + suffix + dateStr + ".xml?_=" + System.currentTimeMillis();
try {
String xml = httpGet(url, ENCODING);
Document doc = Jsoup.parse(xml, url, Parser.xmlParser());
if (doc.select("kopf datei").text().equals("Vplan" + suffix + dateStr + ".xml")) {
docs.add(doc);
}
} catch (HttpResponseException e) {
if (e.getStatusCode() != 404 && e.getStatusCode() != 300) throw e;
}
}
SubstitutionSchedule v = SubstitutionSchedule.fromData(scheduleData);
for (Document doc : docs) {
v.addDay(parseIndiwareDay(doc, false));
}
v.setWebsite(baseurl);
v.setClasses(getAllClasses());
v.setTeachers(getAllTeachers());
return v;
}
}
| stundenplan24: allow to manually switch to teacher schedule on custom URLs
| parser/src/main/java/me/vertretungsplan/parser/IndiwareStundenplan24Parser.java | stundenplan24: allow to manually switch to teacher schedule on custom URLs | <ide><path>arser/src/main/java/me/vertretungsplan/parser/IndiwareStundenplan24Parser.java
<ide> executor.auth(login, password);
<ide> } else {
<ide> baseurl = data.getString("baseurl") + "/";
<del> isTeacher = data.getString("baseurl").endsWith("vplanle");
<add> isTeacher = data.getString("baseurl").endsWith("vplanle") || data.optBoolean("teacher");
<ide> new LoginHandler(scheduleData, credential, cookieProvider).handleLogin(executor, cookieStore);
<ide> }
<ide> |
|
Java | mit | f669e8b47b2c5875c79d905a24432d4c827ece35 | 0 | drcrazy/TechReborn,Dimmerworld/TechReborn,TechReborn/TechReborn | package techreborn.items.tools;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.IItemPropertyGetter;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.translation.I18n;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import reborncore.api.power.IEnergyItemInfo;
import reborncore.common.powerSystem.PoweredItem;
import reborncore.common.util.ChatUtils;
import techreborn.client.TechRebornCreativeTab;
import techreborn.config.ConfigTechReborn;
import techreborn.init.ModItems;
import techreborn.lib.MessageIDs;
import javax.annotation.Nullable;
import java.util.List;
public class ItemNanosaber extends ItemSword implements IEnergyItemInfo {
public int cost = 250;
public ItemNanosaber() {
super(ToolMaterial.DIAMOND);
setNoRepair();
setCreativeTab(TechRebornCreativeTab.instance);
setMaxStackSize(1);
setMaxDamage(1);
setUnlocalizedName("techreborn.nanosaber");
this.addPropertyOverride(new ResourceLocation("techreborn:active"), new IItemPropertyGetter() {
@SideOnly(Side.CLIENT)
public float apply(ItemStack stack,
@Nullable
World worldIn,
@Nullable
EntityLivingBase entityIn) {
if (stack != null && stack.getTagCompound().getBoolean("isActive")) {
return 1.0F;
}
return 0.0F;
}
});
}
@Override
public Multimap<String, AttributeModifier> getAttributeModifiers(EntityEquipmentSlot slot,
ItemStack stack) {
Multimap<String, AttributeModifier> multimap = HashMultimap.<String, AttributeModifier>create();
int modifier = 0;
if (stack.getTagCompound().getBoolean("isActive"))
modifier = 9;
if (slot == EntityEquipmentSlot.MAINHAND) {
multimap.put(SharedMonsterAttributes.ATTACK_DAMAGE.getAttributeUnlocalizedName(),
new AttributeModifier(ATTACK_DAMAGE_MODIFIER, "Weapon modifier", (double) modifier, 0));
multimap.put(SharedMonsterAttributes.ATTACK_SPEED.getAttributeUnlocalizedName(),
new AttributeModifier(ATTACK_SPEED_MODIFIER, "Weapon modifier", -2.4000000953674316D, 0));
}
return multimap;
}
@Override
public boolean hitEntity(ItemStack itemstack, EntityLivingBase entityliving,
EntityLivingBase entityliving1) {
if (PoweredItem.canUseEnergy(cost, itemstack)) {
PoweredItem.useEnergy(cost, itemstack);
return true;
} else {
return false;
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@SideOnly(Side.CLIENT)
public void getSubItems(Item item,
CreativeTabs par2CreativeTabs, List itemList) {
ItemStack inactiveUncharged = new ItemStack(ModItems.nanosaber);
inactiveUncharged.setTagCompound(new NBTTagCompound());
inactiveUncharged.getTagCompound().setBoolean("isActive", false);
ItemStack inactiveCharged = new ItemStack(ModItems.nanosaber);
inactiveCharged.setTagCompound(new NBTTagCompound());
inactiveCharged.getTagCompound().setBoolean("isActive", false);
PoweredItem.setEnergy(getMaxPower(inactiveCharged), inactiveCharged);
ItemStack activeUncharged = new ItemStack(ModItems.nanosaber);
activeUncharged.setTagCompound(new NBTTagCompound());
activeUncharged.getTagCompound().setBoolean("isActive", true);
ItemStack activeCharged = new ItemStack(ModItems.nanosaber);
activeCharged.setTagCompound(new NBTTagCompound());
activeCharged.getTagCompound().setBoolean("isActive", true);
PoweredItem.setEnergy(getMaxPower(activeCharged), activeCharged);
itemList.add(inactiveUncharged);
itemList.add(inactiveCharged);
itemList.add(activeUncharged);
itemList.add(activeCharged);
}
public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean par4) {
if (stack.getTagCompound() == null || !stack.getTagCompound().getBoolean("isActive")) {
list.add(TextFormatting.GRAY + I18n.translateToLocal("techreborn.message.nanosaberInactive"));
} else {
list.add(TextFormatting.GRAY + I18n.translateToLocal("techreborn.message.nanosaberActive"));
}
}
@Override
public boolean showDurabilityBar(ItemStack stack) {
return true;
}
@Override
public ActionResult<ItemStack> onItemRightClick(ItemStack stack, World world, EntityPlayer player,
EnumHand hand) {
if (player.isSneaking()) {
if (!PoweredItem.canUseEnergy(cost, stack)) {
ChatUtils.sendNoSpamMessages(MessageIDs.nanosaberID, new TextComponentString(
TextFormatting.GRAY + I18n.translateToLocal("techreborn.message.nanosaberEnergyErrorTo") + " "
+ TextFormatting.GOLD + I18n
.translateToLocal("techreborn.message.nanosaberActivate")));
} else {
if (stack.getTagCompound() == null || !stack.getTagCompound().getBoolean("isActive")) {
if (stack.getTagCompound() == null) {
stack.setTagCompound(new NBTTagCompound());
}
stack.getTagCompound().setBoolean("isActive", true);
if (!world.isRemote && ConfigTechReborn.NanosaberChat) {
ChatUtils.sendNoSpamMessages(MessageIDs.nanosaberID, new TextComponentString(
TextFormatting.GRAY + I18n.translateToLocal("techreborn.message.setTo") + " "
+ TextFormatting.GOLD + I18n
.translateToLocal("techreborn.message.nanosaberActive")));
}
} else {
stack.getTagCompound().setBoolean("isActive", false);
if (!world.isRemote && ConfigTechReborn.NanosaberChat) {
ChatUtils.sendNoSpamMessages(MessageIDs.nanosaberID, new TextComponentString(
TextFormatting.GRAY + I18n.translateToLocal("techreborn.message.setTo") + " "
+ TextFormatting.GOLD + I18n
.translateToLocal("techreborn.message.nanosaberInactive")));
}
}
}
return new ActionResult<>(EnumActionResult.SUCCESS, stack);
}
return new ActionResult<>(EnumActionResult.PASS, stack);
}
@Override
public void onUpdate(ItemStack stack, World worldIn, Entity entityIn, int itemSlot, boolean isSelected) {
if (stack.getTagCompound() != null && stack.getTagCompound().getBoolean("isActive") && !PoweredItem.canUseEnergy(cost, stack)) {
ChatUtils.sendNoSpamMessages(MessageIDs.nanosaberID, new TextComponentString(
TextFormatting.GRAY + I18n.translateToLocal("techreborn.message.nanosaberEnergyError") + " "
+ TextFormatting.GOLD + I18n
.translateToLocal("techreborn.message.nanosaberDeactivating")));
stack.getTagCompound().setBoolean("isActive", false);
}
}
@Override
public double getDurabilityForDisplay(ItemStack stack) {
if (PoweredItem.getEnergy(stack) > getMaxPower(stack)) {
return 0;
}
double charge = (PoweredItem.getEnergy(stack) / getMaxPower(stack));
return 1 - charge;
}
@Override
public boolean isRepairable() {
return false;
}
@Override
public double getMaxPower(ItemStack stack) {
return 100000;
}
@Override
public boolean canAcceptEnergy(ItemStack stack) {
return true;
}
@Override
public boolean canProvideEnergy(ItemStack stack) {
return false;
}
@Override
public double getMaxTransfer(ItemStack stack) {
return 512;
}
@Override
public int getStackTier(ItemStack stack) {
return 2;
}
}
| src/main/java/techreborn/items/tools/ItemNanosaber.java | package techreborn.items.tools;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.IItemPropertyGetter;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.translation.I18n;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import reborncore.api.power.IEnergyItemInfo;
import reborncore.common.powerSystem.PoweredItem;
import reborncore.common.util.ChatUtils;
import techreborn.client.TechRebornCreativeTab;
import techreborn.config.ConfigTechReborn;
import techreborn.init.ModItems;
import techreborn.lib.MessageIDs;
import javax.annotation.Nullable;
import java.util.List;
public class ItemNanosaber extends ItemSword implements IEnergyItemInfo {
public int cost = 250;
public ItemNanosaber() {
super(ToolMaterial.DIAMOND);
setNoRepair();
setCreativeTab(TechRebornCreativeTab.instance);
setMaxStackSize(1);
setMaxDamage(1);
setUnlocalizedName("techreborn.nanosaber");
this.addPropertyOverride(new ResourceLocation("techreborn:active"), new IItemPropertyGetter() {
@SideOnly(Side.CLIENT)
public float apply(ItemStack stack,
@Nullable
World worldIn,
@Nullable
EntityLivingBase entityIn) {
if (stack != null && stack.getTagCompound().getBoolean("isActive")) {
return 1.0F;
}
return 0.0F;
}
});
}
@Override
public Multimap<String, AttributeModifier> getAttributeModifiers(EntityEquipmentSlot slot,
ItemStack stack) {
Multimap<String, AttributeModifier> multimap = HashMultimap.<String, AttributeModifier>create();
int modifier = 0;
if (stack.getTagCompound().getBoolean("isActive"))
modifier = 9;
if (slot == EntityEquipmentSlot.MAINHAND) {
multimap.put(SharedMonsterAttributes.ATTACK_DAMAGE.getAttributeUnlocalizedName(),
new AttributeModifier(ATTACK_DAMAGE_MODIFIER, "Weapon modifier", (double) modifier, 0));
multimap.put(SharedMonsterAttributes.ATTACK_SPEED.getAttributeUnlocalizedName(),
new AttributeModifier(ATTACK_SPEED_MODIFIER, "Weapon modifier", -2.4000000953674316D, 0));
}
return multimap;
}
@Override
public boolean hitEntity(ItemStack itemstack, EntityLivingBase entityliving,
EntityLivingBase entityliving1) {
if (PoweredItem.canUseEnergy(cost, itemstack)) {
PoweredItem.useEnergy(cost, itemstack);
return true;
} else {
return false;
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@SideOnly(Side.CLIENT)
public void getSubItems(Item item,
CreativeTabs par2CreativeTabs, List itemList) {
ItemStack inactiveUncharged = new ItemStack(ModItems.nanosaber);
inactiveUncharged.setTagCompound(new NBTTagCompound());
inactiveUncharged.getTagCompound().setBoolean("isActive", false);
ItemStack inactiveCharged = new ItemStack(ModItems.nanosaber);
inactiveCharged.setTagCompound(new NBTTagCompound());
inactiveCharged.getTagCompound().setBoolean("isActive", false);
PoweredItem.setEnergy(getMaxPower(inactiveCharged), inactiveCharged);
ItemStack activeUncharged = new ItemStack(ModItems.nanosaber);
activeUncharged.setTagCompound(new NBTTagCompound());
activeUncharged.getTagCompound().setBoolean("isActive", true);
ItemStack activeCharged = new ItemStack(ModItems.nanosaber);
activeCharged.setTagCompound(new NBTTagCompound());
activeCharged.getTagCompound().setBoolean("isActive", true);
PoweredItem.setEnergy(getMaxPower(activeCharged), activeCharged);
itemList.add(inactiveUncharged);
itemList.add(inactiveCharged);
itemList.add(activeUncharged);
itemList.add(activeCharged);
}
public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean par4) {
if (stack.getTagCompound() == null || !stack.getTagCompound().getBoolean("isActive")) {
list.add(TextFormatting.GRAY + I18n.translateToLocal("techreborn.message.nanosaberInactive"));
} else {
list.add(TextFormatting.GRAY + I18n.translateToLocal("techreborn.message.nanosaberActive"));
}
}
@Override
public boolean showDurabilityBar(ItemStack stack) {
return true;
}
@Override
public ActionResult<ItemStack> onItemRightClick(ItemStack stack, World world, EntityPlayer player,
EnumHand hand) {
if (player.isSneaking()) {
if (stack.getTagCompound() == null || !stack.getTagCompound().getBoolean("isActive")) {
stack.setTagCompound(new NBTTagCompound());
stack.getTagCompound().setBoolean("isActive", true);
if (!world.isRemote && ConfigTechReborn.NanosaberChat) {
ChatUtils.sendNoSpamMessages(MessageIDs.nanosaberID, new TextComponentString(
TextFormatting.GRAY + I18n.translateToLocal("techreborn.message.setTo") + " "
+ TextFormatting.GOLD + I18n
.translateToLocal("techreborn.message.nanosaberActive")));
}
} else {
stack.getTagCompound().setBoolean("isActive", false);
if (!world.isRemote && ConfigTechReborn.NanosaberChat) {
ChatUtils.sendNoSpamMessages(MessageIDs.nanosaberID, new TextComponentString(
TextFormatting.GRAY + I18n.translateToLocal("techreborn.message.setTo") + " "
+ TextFormatting.GOLD + I18n
.translateToLocal("techreborn.message.nanosaberInactive")));
}
}
}
return new ActionResult<>(EnumActionResult.SUCCESS, stack);
}
@Override
public double getDurabilityForDisplay(ItemStack stack) {
if (PoweredItem.getEnergy(stack) > getMaxPower(stack)) {
return 0;
}
double charge = (PoweredItem.getEnergy(stack) / getMaxPower(stack));
return 1 - charge;
}
@Override
public boolean isRepairable() {
return false;
}
@Override
public double getMaxPower(ItemStack stack) {
return 100000;
}
@Override
public boolean canAcceptEnergy(ItemStack stack) {
return true;
}
@Override
public boolean canProvideEnergy(ItemStack stack) {
return false;
}
@Override
public double getMaxTransfer(ItemStack stack) {
return 512;
}
@Override
public int getStackTier(ItemStack stack) {
return 2;
}
}
| Manually apply: 4fe5b68aaa100eeca675a596fcad9329403ecab8
| src/main/java/techreborn/items/tools/ItemNanosaber.java | Manually apply: 4fe5b68aaa100eeca675a596fcad9329403ecab8 | <ide><path>rc/main/java/techreborn/items/tools/ItemNanosaber.java
<ide> import com.google.common.collect.HashMultimap;
<ide> import com.google.common.collect.Multimap;
<ide> import net.minecraft.creativetab.CreativeTabs;
<add>import net.minecraft.entity.Entity;
<ide> import net.minecraft.entity.EntityLivingBase;
<ide> import net.minecraft.entity.SharedMonsterAttributes;
<ide> import net.minecraft.entity.ai.attributes.AttributeModifier;
<ide> public ActionResult<ItemStack> onItemRightClick(ItemStack stack, World world, EntityPlayer player,
<ide> EnumHand hand) {
<ide> if (player.isSneaking()) {
<del> if (stack.getTagCompound() == null || !stack.getTagCompound().getBoolean("isActive")) {
<del> stack.setTagCompound(new NBTTagCompound());
<del> stack.getTagCompound().setBoolean("isActive", true);
<del> if (!world.isRemote && ConfigTechReborn.NanosaberChat) {
<del> ChatUtils.sendNoSpamMessages(MessageIDs.nanosaberID, new TextComponentString(
<del> TextFormatting.GRAY + I18n.translateToLocal("techreborn.message.setTo") + " "
<del> + TextFormatting.GOLD + I18n
<del> .translateToLocal("techreborn.message.nanosaberActive")));
<del> }
<add> if (!PoweredItem.canUseEnergy(cost, stack)) {
<add> ChatUtils.sendNoSpamMessages(MessageIDs.nanosaberID, new TextComponentString(
<add> TextFormatting.GRAY + I18n.translateToLocal("techreborn.message.nanosaberEnergyErrorTo") + " "
<add> + TextFormatting.GOLD + I18n
<add> .translateToLocal("techreborn.message.nanosaberActivate")));
<ide> } else {
<del> stack.getTagCompound().setBoolean("isActive", false);
<del> if (!world.isRemote && ConfigTechReborn.NanosaberChat) {
<del> ChatUtils.sendNoSpamMessages(MessageIDs.nanosaberID, new TextComponentString(
<del> TextFormatting.GRAY + I18n.translateToLocal("techreborn.message.setTo") + " "
<del> + TextFormatting.GOLD + I18n
<del> .translateToLocal("techreborn.message.nanosaberInactive")));
<add> if (stack.getTagCompound() == null || !stack.getTagCompound().getBoolean("isActive")) {
<add> if (stack.getTagCompound() == null) {
<add> stack.setTagCompound(new NBTTagCompound());
<add> }
<add> stack.getTagCompound().setBoolean("isActive", true);
<add> if (!world.isRemote && ConfigTechReborn.NanosaberChat) {
<add> ChatUtils.sendNoSpamMessages(MessageIDs.nanosaberID, new TextComponentString(
<add> TextFormatting.GRAY + I18n.translateToLocal("techreborn.message.setTo") + " "
<add> + TextFormatting.GOLD + I18n
<add> .translateToLocal("techreborn.message.nanosaberActive")));
<add> }
<add> } else {
<add> stack.getTagCompound().setBoolean("isActive", false);
<add> if (!world.isRemote && ConfigTechReborn.NanosaberChat) {
<add> ChatUtils.sendNoSpamMessages(MessageIDs.nanosaberID, new TextComponentString(
<add> TextFormatting.GRAY + I18n.translateToLocal("techreborn.message.setTo") + " "
<add> + TextFormatting.GOLD + I18n
<add> .translateToLocal("techreborn.message.nanosaberInactive")));
<add> }
<ide> }
<ide> }
<del> }
<del> return new ActionResult<>(EnumActionResult.SUCCESS, stack);
<add> return new ActionResult<>(EnumActionResult.SUCCESS, stack);
<add> }
<add> return new ActionResult<>(EnumActionResult.PASS, stack);
<add> }
<add>
<add> @Override
<add> public void onUpdate(ItemStack stack, World worldIn, Entity entityIn, int itemSlot, boolean isSelected) {
<add> if (stack.getTagCompound() != null && stack.getTagCompound().getBoolean("isActive") && !PoweredItem.canUseEnergy(cost, stack)) {
<add> ChatUtils.sendNoSpamMessages(MessageIDs.nanosaberID, new TextComponentString(
<add> TextFormatting.GRAY + I18n.translateToLocal("techreborn.message.nanosaberEnergyError") + " "
<add> + TextFormatting.GOLD + I18n
<add> .translateToLocal("techreborn.message.nanosaberDeactivating")));
<add> stack.getTagCompound().setBoolean("isActive", false);
<add> }
<ide> }
<ide>
<ide> @Override |
|
Java | bsd-3-clause | 99477d9d36e13ab25a4e54d9391b4181843ad111 | 0 | NCIP/rembrandt,NCIP/rembrandt,NCIP/rembrandt,NCIP/rembrandt,NCIP/rembrandt,NCIP/rembrandt | package gov.nih.nci.caintegrator.ui.graphing.legend;
import java.awt.Color;
import org.jfree.chart.LegendItemCollection;
public class LegendCreator {
/**
* creates and HTML legend and returns a string of HTML
* @param lic - a jFreechart LegendItemCollection
* @return
*/
public static String buildLegend(LegendItemCollection lic, String legendTitle) {
//TODO: take annotation link as a string param
String html = new String();
Color p = null;
html = "<fieldset style='display:table;width:600; border:1px solid gray; text-align:left; padding:5px;'>";
html += "<legend>Legend: "+ legendTitle+"</legend>";
for(int i=0; i<lic.getItemCount(); i++) {
p = (Color) lic.get(i).getFillPaint();
//html += "<div style='margin:10px; padding:10px;border:1px solid red;'><label style='width:30px; height:10px; background-color: "+ c2hex(p)+"; border:1px solid black;'> </label><b style='color: "+ c2hex(p)+"'>"+lic.get(i).getLabel()+"</b></div>\n";
html += "<table style=\"display:inline;\"><tr><td style=\"width:10px; height:10px; background-color: "+ c2hex(p)+"; border:1px solid black;\"> </td><td><a style=\"text-decoration:none\" href=\"javascript:alert(\'some annotation for:"+lic.get(i).getLabel()+"\');\"><b style=\"color: "+ c2hex(p)+"\">"+lic.get(i).getLabel()+"</b></a></td></tr></table>";
}
html += "</fieldset>";
String js="";
//js = "<script language=\"javascript\">document.getElementById('legend').innerHTML = \""+ html +" \"; </script>";
return html;
}
/**
* converts an awt.Color to a hex color string
* in the format: #zzzzzz for use in HTML
* @param c
* @return
*/
public static String c2hex(Color c) {
//http://rsb.info.nih.gov/ij/developer/source/index.html
final char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
int i = c.getRGB();
char[] buf7 = new char[7];
buf7[0] = '#';
for (int pos=6; pos>=1; pos--) {
buf7[pos] = hexDigits[i&0xf];
i >>>= 4;
}
return new String(buf7);
}
}
| src/gov/nih/nci/caintegrator/ui/graphing/legend/LegendCreator.java | package gov.nih.nci.caintegrator.ui.graphing.legend;
import java.awt.Color;
import org.jfree.chart.LegendItemCollection;
public class LegendCreator {
/**
* creates and HTML legend and returns a string of HTML
* @param lic - a jFreechart LegendItemCollection
* @return
*/
public static String buildLegend(LegendItemCollection lic, String legendTitle) {
String html = new String();
Color p = null;
html = "<fieldset style='display:table;width:600; border:1px solid gray; text-align:left; padding:5px;'>";
html += "<legend>Legend: "+ legendTitle+"</legend>";
for(int i=0; i<lic.getItemCount(); i++) {
p = (Color) lic.get(i).getFillPaint();
//html += "<div style='margin:10px; padding:10px;border:1px solid red;'><label style='width:30px; height:10px; background-color: "+ c2hex(p)+"; border:1px solid black;'> </label><b style='color: "+ c2hex(p)+"'>"+lic.get(i).getLabel()+"</b></div>\n";
html += "<table style=\"display:inline;\"><tr><td style=\"width:10px; height:10px; background-color: "+ c2hex(p)+"; border:1px solid black;\"> </td><td><a style=\"text-decoration:none\" href=\"javascript:alert(\'some annotation for:"+lic.get(i).getLabel()+"\');\"><b style=\"color: "+ c2hex(p)+"\">"+lic.get(i).getLabel()+"</b></a></td></tr></table>";
}
html += "</fieldset>";
String js="";
//js = "<script language=\"javascript\">document.getElementById('legend').innerHTML = \""+ html +" \"; </script>";
return html;
}
/**
* converts an awt.Color to a hex color string
* in the format: #zzzzzz for use in HTML
* @param c
* @return
*/
public static String c2hex(Color c) {
//http://rsb.info.nih.gov/ij/developer/source/index.html
final char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
int i = c.getRGB();
char[] buf7 = new char[7];
buf7[0] = '#';
for (int pos=6; pos>=1; pos--) {
buf7[pos] = hexDigits[i&0xf];
i >>>= 4;
}
return new String(buf7);
}
}
| *** empty log message ***
SVN-Revision: 1668
| src/gov/nih/nci/caintegrator/ui/graphing/legend/LegendCreator.java | *** empty log message *** | <ide><path>rc/gov/nih/nci/caintegrator/ui/graphing/legend/LegendCreator.java
<ide> * @return
<ide> */
<ide> public static String buildLegend(LegendItemCollection lic, String legendTitle) {
<add>
<add> //TODO: take annotation link as a string param
<add>
<ide> String html = new String();
<ide> Color p = null;
<ide> html = "<fieldset style='display:table;width:600; border:1px solid gray; text-align:left; padding:5px;'>"; |
|
Java | apache-2.0 | 1247e66da2c11bc7bc6103252dc55c7367bd67ce | 0 | twalthr/flink,rmetzger/flink,lincoln-lil/flink,xccui/flink,clarkyzl/flink,wwjiang007/flink,greghogan/flink,xccui/flink,gyfora/flink,StephanEwen/incubator-flink,jinglining/flink,clarkyzl/flink,rmetzger/flink,wwjiang007/flink,lincoln-lil/flink,kl0u/flink,tillrohrmann/flink,clarkyzl/flink,aljoscha/flink,godfreyhe/flink,sunjincheng121/flink,rmetzger/flink,GJL/flink,tillrohrmann/flink,tony810430/flink,GJL/flink,twalthr/flink,StephanEwen/incubator-flink,rmetzger/flink,tillrohrmann/flink,twalthr/flink,hequn8128/flink,apache/flink,apache/flink,clarkyzl/flink,wwjiang007/flink,bowenli86/flink,sunjincheng121/flink,zjureel/flink,bowenli86/flink,lincoln-lil/flink,zentol/flink,jinglining/flink,aljoscha/flink,bowenli86/flink,zentol/flink,kaibozhou/flink,StephanEwen/incubator-flink,apache/flink,greghogan/flink,zentol/flink,xccui/flink,hequn8128/flink,tony810430/flink,gyfora/flink,GJL/flink,tillrohrmann/flink,hequn8128/flink,wwjiang007/flink,rmetzger/flink,jinglining/flink,tony810430/flink,zjureel/flink,StephanEwen/incubator-flink,sunjincheng121/flink,sunjincheng121/flink,twalthr/flink,kaibozhou/flink,aljoscha/flink,aljoscha/flink,xccui/flink,sunjincheng121/flink,godfreyhe/flink,godfreyhe/flink,apache/flink,godfreyhe/flink,kl0u/flink,tony810430/flink,zjureel/flink,zentol/flink,rmetzger/flink,godfreyhe/flink,apache/flink,kl0u/flink,sunjincheng121/flink,darionyaphet/flink,godfreyhe/flink,zjureel/flink,bowenli86/flink,gyfora/flink,greghogan/flink,gyfora/flink,tillrohrmann/flink,darionyaphet/flink,zentol/flink,jinglining/flink,bowenli86/flink,wwjiang007/flink,apache/flink,tillrohrmann/flink,kaibozhou/flink,godfreyhe/flink,kaibozhou/flink,zentol/flink,twalthr/flink,twalthr/flink,aljoscha/flink,kl0u/flink,clarkyzl/flink,xccui/flink,jinglining/flink,wwjiang007/flink,jinglining/flink,zjureel/flink,GJL/flink,rmetzger/flink,tzulitai/flink,tzulitai/flink,kaibozhou/flink,tony810430/flink,darionyaphet/flink,lincoln-lil/flink,tzulitai/flink,zjureel/flink,bowenli86/flink,darionyaphet/flink,apache/flink,twalthr/flink,darionyaphet/flink,tzulitai/flink,zjureel/flink,zentol/flink,StephanEwen/incubator-flink,GJL/flink,lincoln-lil/flink,xccui/flink,StephanEwen/incubator-flink,xccui/flink,GJL/flink,kl0u/flink,hequn8128/flink,lincoln-lil/flink,hequn8128/flink,greghogan/flink,tillrohrmann/flink,tzulitai/flink,tony810430/flink,tony810430/flink,aljoscha/flink,lincoln-lil/flink,gyfora/flink,kl0u/flink,wwjiang007/flink,gyfora/flink,kaibozhou/flink,gyfora/flink,tzulitai/flink,greghogan/flink,hequn8128/flink,greghogan/flink | /*
* 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.flink.api.common.typeutils;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.core.memory.DataInputDeserializer;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputSerializer;
import org.apache.flink.testutils.migration.MigrationVersion;
import org.apache.flink.util.TestLogger;
import org.hamcrest.Matcher;
import org.junit.Test;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Supplier;
import static org.apache.flink.api.common.typeutils.TypeSerializerMatchers.hasSameCompatibilityAs;
import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* A test base for verifying {@link TypeSerializerSnapshot} migration.
*
* @param <ElementT> the element being serialized.
*
* @deprecated please use the newer {@link TypeSerializerUpgradeTestBase}
*/
@Deprecated
public abstract class TypeSerializerSnapshotMigrationTestBase<ElementT> extends TestLogger {
private final TestSpecification<ElementT> testSpecification;
protected TypeSerializerSnapshotMigrationTestBase(TestSpecification<ElementT> testSpecification) {
this.testSpecification = checkNotNull(testSpecification);
}
@Test
public void serializerSnapshotIsSuccessfullyRead() {
TypeSerializerSnapshot<ElementT> snapshot = snapshotUnderTest();
assertThat(snapshot, allOf(
notNullValue(),
instanceOf(TypeSerializerSnapshot.class)
));
}
@Test
public void specifiedNewSerializerHasExpectedCompatibilityResultsWithSnapshot() {
TypeSerializerSnapshot<ElementT> snapshot = snapshotUnderTest();
TypeSerializerSchemaCompatibility<ElementT> result = snapshot.resolveSchemaCompatibility(testSpecification.createSerializer());
assertThat(result, testSpecification.schemaCompatibilityMatcher);
}
@Test
public void restoredSerializerIsAbleToDeserializePreviousData() throws IOException {
TypeSerializerSnapshot<ElementT> snapshot = snapshotUnderTest();
TypeSerializer<ElementT> serializer = snapshot.restoreSerializer();
assertSerializerIsAbleToReadOldData(serializer);
}
@Test
public void reconfiguredSerializerIsAbleToDeserializePreviousData() throws IOException {
TypeSerializerSnapshot<ElementT> snapshot = snapshotUnderTest();
TypeSerializerSchemaCompatibility<ElementT> compatibility = snapshot.resolveSchemaCompatibility(testSpecification.createSerializer());
if (!compatibility.isCompatibleWithReconfiguredSerializer()) {
// this test only applies for reconfigured serializers.
return;
}
TypeSerializer<ElementT> serializer = compatibility.getReconfiguredSerializer();
assertSerializerIsAbleToReadOldData(serializer);
}
@SuppressWarnings("deprecation")
@Test
public void movingForward() throws IOException {
TypeSerializerSnapshot<ElementT> previousSnapshot = snapshotUnderTest();
TypeSerializer<ElementT> restoredSerializer = previousSnapshot.restoreSerializer();
TypeSerializerSnapshot<ElementT> nextSnapshot = restoredSerializer.snapshotConfiguration();
assertThat(nextSnapshot, instanceOf(testSpecification.snapshotClass));
TypeSerializerSnapshot<ElementT> nextSnapshotDeserialized = writeAndThenReadTheSnapshot(restoredSerializer, nextSnapshot);
assertThat(nextSnapshotDeserialized, allOf(
notNullValue(),
not(instanceOf(TypeSerializerConfigSnapshot.class))
));
}
@Test
public void restoreSerializerFromNewSerializerSnapshotIsAbleToDeserializePreviousData() throws IOException {
TypeSerializer<ElementT> newSerializer = testSpecification.createSerializer();
TypeSerializerSchemaCompatibility<ElementT> compatibility =
snapshotUnderTest().resolveSchemaCompatibility(newSerializer);
final TypeSerializer<ElementT> nextSerializer;
if (compatibility.isCompatibleWithReconfiguredSerializer()) {
nextSerializer = compatibility.getReconfiguredSerializer();
} else if (compatibility.isCompatibleAsIs()) {
nextSerializer = newSerializer;
} else {
// this test does not apply.
return;
}
TypeSerializerSnapshot<ElementT> nextSnapshot = nextSerializer.snapshotConfiguration();
assertSerializerIsAbleToReadOldData(nextSnapshot.restoreSerializer());
}
// --------------------------------------------------------------------------------------------------------------
// Test Helpers
// --------------------------------------------------------------------------------------------------------------
private TypeSerializerSnapshot<ElementT> writeAndThenReadTheSnapshot(
TypeSerializer<ElementT> serializer,
TypeSerializerSnapshot<ElementT> newSnapshot) throws IOException {
DataOutputSerializer out = new DataOutputSerializer(128);
TypeSerializerSnapshotSerializationUtil.writeSerializerSnapshot(out, newSnapshot, serializer);
DataInputView in = new DataInputDeserializer(out.wrapAsByteBuffer());
return readSnapshot(in);
}
private TypeSerializerSnapshot<ElementT> snapshotUnderTest() {
DataInputView input = contentsOf(testSpecification.getSnapshotDataLocation());
try {
if (!testSpecification.getTestMigrationVersion().isNewerVersionThan(MigrationVersion.v1_6)) {
return readPre17SnapshotFormat(input);
} else {
return readSnapshot(input);
}
}
catch (IOException e) {
throw new RuntimeException("Unable to read " + testSpecification.getSnapshotDataLocation(), e);
}
}
@SuppressWarnings({"unchecked", "deprecation"})
private TypeSerializerSnapshot<ElementT> readPre17SnapshotFormat(DataInputView input) throws IOException {
final ClassLoader cl = Thread.currentThread().getContextClassLoader();
List<Tuple2<TypeSerializer<?>, TypeSerializerSnapshot<?>>> serializers =
TypeSerializerSerializationUtil.readSerializersAndConfigsWithResilience(input, cl);
return (TypeSerializerSnapshot<ElementT>) serializers.get(0).f1;
}
private TypeSerializerSnapshot<ElementT> readSnapshot(DataInputView in) throws IOException {
return TypeSerializerSnapshotSerializationUtil.readSerializerSnapshot(
in, Thread.currentThread().getContextClassLoader(), null);
}
private DataInputView dataUnderTest() {
return contentsOf(testSpecification.getTestDataLocation());
}
private void assertSerializerIsAbleToReadOldData(TypeSerializer<ElementT> serializer) throws IOException {
DataInputView input = dataUnderTest();
final Matcher<ElementT> matcher = testSpecification.testDataElementMatcher;
for (int i = 0; i < testSpecification.testDataCount; i++) {
final ElementT result = serializer.deserialize(input);
assertThat(result, matcher);
}
}
// --------------------------------------------------------------------------------------------------------------
// Static Helpers
// --------------------------------------------------------------------------------------------------------------
private static DataInputView contentsOf(Path path) {
try {
byte[] bytes = Files.readAllBytes(path);
return new DataInputDeserializer(bytes);
}
catch (IOException e) {
throw new RuntimeException("Failed to read " + path, e);
}
}
private static Path resourcePath(String resourceName) {
checkNotNull(resourceName, "resource name can not be NULL");
try {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
URL resource = cl.getResource(resourceName);
if (resource == null) {
throw new IllegalArgumentException("unable locate test data " + resourceName);
}
return Paths.get(resource.toURI());
}
catch (URISyntaxException e) {
throw new RuntimeException("unable", e);
}
}
// --------------------------------------------------------------------------------------------------------------
// Test Specification
// --------------------------------------------------------------------------------------------------------------
/**
* Test Specification.
*/
@SuppressWarnings("WeakerAccess")
public static final class TestSpecification<T> {
private final Class<? extends TypeSerializer<T>> serializerType;
private final Class<? extends TypeSerializerSnapshot<T>> snapshotClass;
private final String name;
private final MigrationVersion testMigrationVersion;
private Supplier<? extends TypeSerializer<T>> serializerProvider;
private Matcher<TypeSerializerSchemaCompatibility<T>> schemaCompatibilityMatcher;
private String snapshotDataLocation;
private String testDataLocation;
private int testDataCount;
@SuppressWarnings("unchecked")
private Matcher<T> testDataElementMatcher = (Matcher<T>) notNullValue();
@SuppressWarnings("unchecked")
public static <T> TestSpecification<T> builder(
String name,
Class<? extends TypeSerializer> serializerClass,
Class<? extends TypeSerializerSnapshot> snapshotClass,
MigrationVersion testMigrationVersion) {
return new TestSpecification<>(
name,
(Class<? extends TypeSerializer<T>>) serializerClass,
(Class<? extends TypeSerializerSnapshot<T>>) snapshotClass,
testMigrationVersion);
}
private TestSpecification(
String name,
Class<? extends TypeSerializer<T>> serializerType,
Class<? extends TypeSerializerSnapshot<T>> snapshotClass,
MigrationVersion testMigrationVersion) {
this.name = name;
this.serializerType = serializerType;
this.snapshotClass = snapshotClass;
this.testMigrationVersion = testMigrationVersion;
}
public TestSpecification<T> withNewSerializerProvider(Supplier<? extends TypeSerializer<T>> serializerProvider) {
return withNewSerializerProvider(serializerProvider, TypeSerializerSchemaCompatibility.compatibleAsIs());
}
public TestSpecification<T> withNewSerializerProvider(
Supplier<? extends TypeSerializer<T>> serializerProvider,
TypeSerializerSchemaCompatibility<T> expectedCompatibilityResult) {
this.serializerProvider = serializerProvider;
this.schemaCompatibilityMatcher = hasSameCompatibilityAs(expectedCompatibilityResult);
return this;
}
public TestSpecification<T> withSchemaCompatibilityMatcher(
Matcher<TypeSerializerSchemaCompatibility<T>> schemaCompatibilityMatcher) {
this.schemaCompatibilityMatcher = schemaCompatibilityMatcher;
return this;
}
public TestSpecification<T> withSnapshotDataLocation(String snapshotDataLocation) {
this.snapshotDataLocation = snapshotDataLocation;
return this;
}
public TestSpecification<T> withTestData(String testDataLocation, int testDataCount) {
this.testDataLocation = testDataLocation;
this.testDataCount = testDataCount;
return this;
}
public TestSpecification<T> withTestDataMatcher(Matcher<T> matcher) {
testDataElementMatcher = matcher;
return this;
}
public TestSpecification<T> withTestDataCount(int expectedDataItmes) {
this.testDataCount = expectedDataItmes;
return this;
}
private TypeSerializer<T> createSerializer() {
try {
return (serializerProvider == null) ? serializerType.newInstance() : serializerProvider.get();
}
catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException("serializer provider was not set, and creating the serializer reflectively failed.", e);
}
}
private Path getTestDataLocation() {
return resourcePath(this.testDataLocation);
}
private Path getSnapshotDataLocation() {
return resourcePath(this.snapshotDataLocation);
}
private MigrationVersion getTestMigrationVersion() {
return testMigrationVersion;
}
@Override
public String toString() {
return String.format("%s , %s, %s", name, serializerType.getSimpleName(), snapshotClass.getSimpleName());
}
}
/**
* Utility class to help build a collection of {@link TestSpecification} for
* multiple test migration versions. For each test specification added,
* an entry will be added for each specified migration version.
*/
public static final class TestSpecifications {
private static final int DEFAULT_TEST_DATA_COUNT = 10;
private static final String DEFAULT_SNAPSHOT_FILENAME_FORMAT = "flink-%s-%s-snapshot";
private static final String DEFAULT_TEST_DATA_FILENAME_FORMAT = "flink-%s-%s-data";
private final Collection<TestSpecification<?>> testSpecifications = new LinkedList<>();
private final MigrationVersion[] testVersions;
public TestSpecifications(MigrationVersion... testVersions) {
checkArgument(
testVersions.length > 0,
"At least one test migration version should be specified.");
this.testVersions = testVersions;
}
/**
* Adds a test specification to be tested for all specified test versions.
*
* <p>This method adds the specification with pre-defined snapshot and data filenames,
* with the format "flink-<testVersion>-<specName>-<data/snapshot>",
* and each specification's test data count is assumed to always be 10.
*
* @param name test specification name.
* @param serializerClass class of the current serializer.
* @param snapshotClass class of the current serializer snapshot class.
* @param serializerProvider provider for an instance of the current serializer.
*
* @param <T> type of the test data.
*/
public <T> void add(
String name,
Class<? extends TypeSerializer> serializerClass,
Class<? extends TypeSerializerSnapshot> snapshotClass,
Supplier<? extends TypeSerializer<T>> serializerProvider) {
for (MigrationVersion testVersion : testVersions) {
testSpecifications.add(
TestSpecification.<T>builder(
getSpecNameForVersion(name, testVersion),
serializerClass,
snapshotClass,
testVersion)
.withNewSerializerProvider(serializerProvider)
.withSnapshotDataLocation(
String.format(DEFAULT_SNAPSHOT_FILENAME_FORMAT, testVersion, name))
.withTestData(
String.format(DEFAULT_TEST_DATA_FILENAME_FORMAT, testVersion, name),
DEFAULT_TEST_DATA_COUNT)
);
}
}
/**
* Adds a test specification to be tested for all specified test versions.
*
* <p>This method adds the specification with pre-defined snapshot and data filenames,
* with the format "flink-<testVersion>-<specName>-<data/snapshot>",
* and each specification's test data count is assumed to always be 10.
*
* @param <T> type of the test data.
*/
public <T> void addWithCompatibilityMatcher(
String name,
Class<? extends TypeSerializer> serializerClass,
Class<? extends TypeSerializerSnapshot> snapshotClass,
Supplier<? extends TypeSerializer<T>> serializerProvider,
Matcher<TypeSerializerSchemaCompatibility<T>> schemaCompatibilityMatcher) {
for (MigrationVersion testVersion : testVersions) {
testSpecifications.add(
TestSpecification.<T>builder(
getSpecNameForVersion(name, testVersion),
serializerClass,
snapshotClass,
testVersion)
.withNewSerializerProvider(serializerProvider)
.withSchemaCompatibilityMatcher(schemaCompatibilityMatcher)
.withSnapshotDataLocation(
String.format(DEFAULT_SNAPSHOT_FILENAME_FORMAT, testVersion, name))
.withTestData(
String.format(DEFAULT_TEST_DATA_FILENAME_FORMAT, testVersion, name),
DEFAULT_TEST_DATA_COUNT)
);
}
}
/**
* Adds a test specification to be tested for all specified test versions.
*
* <p>This method adds the specification with pre-defined snapshot and data filenames,
* with the format "flink-<testVersion>-<specName>-<data/snapshot>",
* and each specification's test data count is assumed to always be 10.
*
* @param name test specification name.
* @param serializerClass class of the current serializer.
* @param snapshotClass class of the current serializer snapshot class.
* @param serializerProvider provider for an instance of the current serializer.
* @param elementMatcher an {@code hamcrest} matcher to match test data.
*
* @param <T> type of the test data.
*/
public <T> void add(
String name,
Class<? extends TypeSerializer> serializerClass,
Class<? extends TypeSerializerSnapshot> snapshotClass,
Supplier<? extends TypeSerializer<T>> serializerProvider,
Matcher<T> elementMatcher) {
for (MigrationVersion testVersion : testVersions) {
testSpecifications.add(
TestSpecification.<T>builder(
getSpecNameForVersion(name, testVersion),
serializerClass,
snapshotClass,
testVersion)
.withNewSerializerProvider(serializerProvider)
.withSnapshotDataLocation(
String.format(DEFAULT_SNAPSHOT_FILENAME_FORMAT, testVersion, name))
.withTestData(
String.format(DEFAULT_TEST_DATA_FILENAME_FORMAT, testVersion, name),
DEFAULT_TEST_DATA_COUNT)
.withTestDataMatcher(elementMatcher)
);
}
}
/**
* Adds a test specification to be tested for all specified test versions.
*
* @param name test specification name.
* @param serializerClass class of the current serializer.
* @param snapshotClass class of the current serializer snapshot class.
* @param serializerProvider provider for an instance of the current serializer.
* @param testSnapshotFilenameProvider provider for the filename of the test snapshot.
* @param testDataFilenameProvider provider for the filename of the test data.
* @param testDataCount expected number of records to be read in the test data files.
*
* @param <T> type of the test data.
*/
public <T> void add(
String name,
Class<? extends TypeSerializer> serializerClass,
Class<? extends TypeSerializerSnapshot> snapshotClass,
Supplier<? extends TypeSerializer<T>> serializerProvider,
TestResourceFilenameSupplier testSnapshotFilenameProvider,
TestResourceFilenameSupplier testDataFilenameProvider,
int testDataCount) {
for (MigrationVersion testVersion : testVersions) {
testSpecifications.add(
TestSpecification.<T>builder(
getSpecNameForVersion(name, testVersion),
serializerClass,
snapshotClass,
testVersion)
.withNewSerializerProvider(serializerProvider)
.withSnapshotDataLocation(testSnapshotFilenameProvider.get(testVersion))
.withTestData(testDataFilenameProvider.get(testVersion), testDataCount)
);
}
}
public Collection<TestSpecification<?>> get() {
return Collections.unmodifiableCollection(testSpecifications);
}
private static String getSpecNameForVersion(String baseName, MigrationVersion testVersion) {
return testVersion + "-" + baseName;
}
}
/**
* Supplier of paths based on {@link MigrationVersion}.
*/
protected interface TestResourceFilenameSupplier {
String get(MigrationVersion testVersion);
}
}
| flink-core/src/test/java/org/apache/flink/api/common/typeutils/TypeSerializerSnapshotMigrationTestBase.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.flink.api.common.typeutils;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.core.memory.DataInputDeserializer;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputSerializer;
import org.apache.flink.testutils.migration.MigrationVersion;
import org.apache.flink.util.TestLogger;
import org.hamcrest.Matcher;
import org.junit.Test;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Supplier;
import static org.apache.flink.api.common.typeutils.TypeSerializerMatchers.hasSameCompatibilityAs;
import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* A test base for verifying {@link TypeSerializerSnapshot} migration.
*
* @param <ElementT> the element being serialized.
*/
public abstract class TypeSerializerSnapshotMigrationTestBase<ElementT> extends TestLogger {
private final TestSpecification<ElementT> testSpecification;
protected TypeSerializerSnapshotMigrationTestBase(TestSpecification<ElementT> testSpecification) {
this.testSpecification = checkNotNull(testSpecification);
}
@Test
public void serializerSnapshotIsSuccessfullyRead() {
TypeSerializerSnapshot<ElementT> snapshot = snapshotUnderTest();
assertThat(snapshot, allOf(
notNullValue(),
instanceOf(TypeSerializerSnapshot.class)
));
}
@Test
public void specifiedNewSerializerHasExpectedCompatibilityResultsWithSnapshot() {
TypeSerializerSnapshot<ElementT> snapshot = snapshotUnderTest();
TypeSerializerSchemaCompatibility<ElementT> result = snapshot.resolveSchemaCompatibility(testSpecification.createSerializer());
assertThat(result, testSpecification.schemaCompatibilityMatcher);
}
@Test
public void restoredSerializerIsAbleToDeserializePreviousData() throws IOException {
TypeSerializerSnapshot<ElementT> snapshot = snapshotUnderTest();
TypeSerializer<ElementT> serializer = snapshot.restoreSerializer();
assertSerializerIsAbleToReadOldData(serializer);
}
@Test
public void reconfiguredSerializerIsAbleToDeserializePreviousData() throws IOException {
TypeSerializerSnapshot<ElementT> snapshot = snapshotUnderTest();
TypeSerializerSchemaCompatibility<ElementT> compatibility = snapshot.resolveSchemaCompatibility(testSpecification.createSerializer());
if (!compatibility.isCompatibleWithReconfiguredSerializer()) {
// this test only applies for reconfigured serializers.
return;
}
TypeSerializer<ElementT> serializer = compatibility.getReconfiguredSerializer();
assertSerializerIsAbleToReadOldData(serializer);
}
@SuppressWarnings("deprecation")
@Test
public void movingForward() throws IOException {
TypeSerializerSnapshot<ElementT> previousSnapshot = snapshotUnderTest();
TypeSerializer<ElementT> restoredSerializer = previousSnapshot.restoreSerializer();
TypeSerializerSnapshot<ElementT> nextSnapshot = restoredSerializer.snapshotConfiguration();
assertThat(nextSnapshot, instanceOf(testSpecification.snapshotClass));
TypeSerializerSnapshot<ElementT> nextSnapshotDeserialized = writeAndThenReadTheSnapshot(restoredSerializer, nextSnapshot);
assertThat(nextSnapshotDeserialized, allOf(
notNullValue(),
not(instanceOf(TypeSerializerConfigSnapshot.class))
));
}
@Test
public void restoreSerializerFromNewSerializerSnapshotIsAbleToDeserializePreviousData() throws IOException {
TypeSerializer<ElementT> newSerializer = testSpecification.createSerializer();
TypeSerializerSchemaCompatibility<ElementT> compatibility =
snapshotUnderTest().resolveSchemaCompatibility(newSerializer);
final TypeSerializer<ElementT> nextSerializer;
if (compatibility.isCompatibleWithReconfiguredSerializer()) {
nextSerializer = compatibility.getReconfiguredSerializer();
} else if (compatibility.isCompatibleAsIs()) {
nextSerializer = newSerializer;
} else {
// this test does not apply.
return;
}
TypeSerializerSnapshot<ElementT> nextSnapshot = nextSerializer.snapshotConfiguration();
assertSerializerIsAbleToReadOldData(nextSnapshot.restoreSerializer());
}
// --------------------------------------------------------------------------------------------------------------
// Test Helpers
// --------------------------------------------------------------------------------------------------------------
private TypeSerializerSnapshot<ElementT> writeAndThenReadTheSnapshot(
TypeSerializer<ElementT> serializer,
TypeSerializerSnapshot<ElementT> newSnapshot) throws IOException {
DataOutputSerializer out = new DataOutputSerializer(128);
TypeSerializerSnapshotSerializationUtil.writeSerializerSnapshot(out, newSnapshot, serializer);
DataInputView in = new DataInputDeserializer(out.wrapAsByteBuffer());
return readSnapshot(in);
}
private TypeSerializerSnapshot<ElementT> snapshotUnderTest() {
DataInputView input = contentsOf(testSpecification.getSnapshotDataLocation());
try {
if (!testSpecification.getTestMigrationVersion().isNewerVersionThan(MigrationVersion.v1_6)) {
return readPre17SnapshotFormat(input);
} else {
return readSnapshot(input);
}
}
catch (IOException e) {
throw new RuntimeException("Unable to read " + testSpecification.getSnapshotDataLocation(), e);
}
}
@SuppressWarnings({"unchecked", "deprecation"})
private TypeSerializerSnapshot<ElementT> readPre17SnapshotFormat(DataInputView input) throws IOException {
final ClassLoader cl = Thread.currentThread().getContextClassLoader();
List<Tuple2<TypeSerializer<?>, TypeSerializerSnapshot<?>>> serializers =
TypeSerializerSerializationUtil.readSerializersAndConfigsWithResilience(input, cl);
return (TypeSerializerSnapshot<ElementT>) serializers.get(0).f1;
}
private TypeSerializerSnapshot<ElementT> readSnapshot(DataInputView in) throws IOException {
return TypeSerializerSnapshotSerializationUtil.readSerializerSnapshot(
in, Thread.currentThread().getContextClassLoader(), null);
}
private DataInputView dataUnderTest() {
return contentsOf(testSpecification.getTestDataLocation());
}
private void assertSerializerIsAbleToReadOldData(TypeSerializer<ElementT> serializer) throws IOException {
DataInputView input = dataUnderTest();
final Matcher<ElementT> matcher = testSpecification.testDataElementMatcher;
for (int i = 0; i < testSpecification.testDataCount; i++) {
final ElementT result = serializer.deserialize(input);
assertThat(result, matcher);
}
}
// --------------------------------------------------------------------------------------------------------------
// Static Helpers
// --------------------------------------------------------------------------------------------------------------
private static DataInputView contentsOf(Path path) {
try {
byte[] bytes = Files.readAllBytes(path);
return new DataInputDeserializer(bytes);
}
catch (IOException e) {
throw new RuntimeException("Failed to read " + path, e);
}
}
private static Path resourcePath(String resourceName) {
checkNotNull(resourceName, "resource name can not be NULL");
try {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
URL resource = cl.getResource(resourceName);
if (resource == null) {
throw new IllegalArgumentException("unable locate test data " + resourceName);
}
return Paths.get(resource.toURI());
}
catch (URISyntaxException e) {
throw new RuntimeException("unable", e);
}
}
// --------------------------------------------------------------------------------------------------------------
// Test Specification
// --------------------------------------------------------------------------------------------------------------
/**
* Test Specification.
*/
@SuppressWarnings("WeakerAccess")
public static final class TestSpecification<T> {
private final Class<? extends TypeSerializer<T>> serializerType;
private final Class<? extends TypeSerializerSnapshot<T>> snapshotClass;
private final String name;
private final MigrationVersion testMigrationVersion;
private Supplier<? extends TypeSerializer<T>> serializerProvider;
private Matcher<TypeSerializerSchemaCompatibility<T>> schemaCompatibilityMatcher;
private String snapshotDataLocation;
private String testDataLocation;
private int testDataCount;
@SuppressWarnings("unchecked")
private Matcher<T> testDataElementMatcher = (Matcher<T>) notNullValue();
@SuppressWarnings("unchecked")
public static <T> TestSpecification<T> builder(
String name,
Class<? extends TypeSerializer> serializerClass,
Class<? extends TypeSerializerSnapshot> snapshotClass,
MigrationVersion testMigrationVersion) {
return new TestSpecification<>(
name,
(Class<? extends TypeSerializer<T>>) serializerClass,
(Class<? extends TypeSerializerSnapshot<T>>) snapshotClass,
testMigrationVersion);
}
private TestSpecification(
String name,
Class<? extends TypeSerializer<T>> serializerType,
Class<? extends TypeSerializerSnapshot<T>> snapshotClass,
MigrationVersion testMigrationVersion) {
this.name = name;
this.serializerType = serializerType;
this.snapshotClass = snapshotClass;
this.testMigrationVersion = testMigrationVersion;
}
public TestSpecification<T> withNewSerializerProvider(Supplier<? extends TypeSerializer<T>> serializerProvider) {
return withNewSerializerProvider(serializerProvider, TypeSerializerSchemaCompatibility.compatibleAsIs());
}
public TestSpecification<T> withNewSerializerProvider(
Supplier<? extends TypeSerializer<T>> serializerProvider,
TypeSerializerSchemaCompatibility<T> expectedCompatibilityResult) {
this.serializerProvider = serializerProvider;
this.schemaCompatibilityMatcher = hasSameCompatibilityAs(expectedCompatibilityResult);
return this;
}
public TestSpecification<T> withSchemaCompatibilityMatcher(
Matcher<TypeSerializerSchemaCompatibility<T>> schemaCompatibilityMatcher) {
this.schemaCompatibilityMatcher = schemaCompatibilityMatcher;
return this;
}
public TestSpecification<T> withSnapshotDataLocation(String snapshotDataLocation) {
this.snapshotDataLocation = snapshotDataLocation;
return this;
}
public TestSpecification<T> withTestData(String testDataLocation, int testDataCount) {
this.testDataLocation = testDataLocation;
this.testDataCount = testDataCount;
return this;
}
public TestSpecification<T> withTestDataMatcher(Matcher<T> matcher) {
testDataElementMatcher = matcher;
return this;
}
public TestSpecification<T> withTestDataCount(int expectedDataItmes) {
this.testDataCount = expectedDataItmes;
return this;
}
private TypeSerializer<T> createSerializer() {
try {
return (serializerProvider == null) ? serializerType.newInstance() : serializerProvider.get();
}
catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException("serializer provider was not set, and creating the serializer reflectively failed.", e);
}
}
private Path getTestDataLocation() {
return resourcePath(this.testDataLocation);
}
private Path getSnapshotDataLocation() {
return resourcePath(this.snapshotDataLocation);
}
private MigrationVersion getTestMigrationVersion() {
return testMigrationVersion;
}
@Override
public String toString() {
return String.format("%s , %s, %s", name, serializerType.getSimpleName(), snapshotClass.getSimpleName());
}
}
/**
* Utility class to help build a collection of {@link TestSpecification} for
* multiple test migration versions. For each test specification added,
* an entry will be added for each specified migration version.
*/
public static final class TestSpecifications {
private static final int DEFAULT_TEST_DATA_COUNT = 10;
private static final String DEFAULT_SNAPSHOT_FILENAME_FORMAT = "flink-%s-%s-snapshot";
private static final String DEFAULT_TEST_DATA_FILENAME_FORMAT = "flink-%s-%s-data";
private final Collection<TestSpecification<?>> testSpecifications = new LinkedList<>();
private final MigrationVersion[] testVersions;
public TestSpecifications(MigrationVersion... testVersions) {
checkArgument(
testVersions.length > 0,
"At least one test migration version should be specified.");
this.testVersions = testVersions;
}
/**
* Adds a test specification to be tested for all specified test versions.
*
* <p>This method adds the specification with pre-defined snapshot and data filenames,
* with the format "flink-<testVersion>-<specName>-<data/snapshot>",
* and each specification's test data count is assumed to always be 10.
*
* @param name test specification name.
* @param serializerClass class of the current serializer.
* @param snapshotClass class of the current serializer snapshot class.
* @param serializerProvider provider for an instance of the current serializer.
*
* @param <T> type of the test data.
*/
public <T> void add(
String name,
Class<? extends TypeSerializer> serializerClass,
Class<? extends TypeSerializerSnapshot> snapshotClass,
Supplier<? extends TypeSerializer<T>> serializerProvider) {
for (MigrationVersion testVersion : testVersions) {
testSpecifications.add(
TestSpecification.<T>builder(
getSpecNameForVersion(name, testVersion),
serializerClass,
snapshotClass,
testVersion)
.withNewSerializerProvider(serializerProvider)
.withSnapshotDataLocation(
String.format(DEFAULT_SNAPSHOT_FILENAME_FORMAT, testVersion, name))
.withTestData(
String.format(DEFAULT_TEST_DATA_FILENAME_FORMAT, testVersion, name),
DEFAULT_TEST_DATA_COUNT)
);
}
}
/**
* Adds a test specification to be tested for all specified test versions.
*
* <p>This method adds the specification with pre-defined snapshot and data filenames,
* with the format "flink-<testVersion>-<specName>-<data/snapshot>",
* and each specification's test data count is assumed to always be 10.
*
* @param <T> type of the test data.
*/
public <T> void addWithCompatibilityMatcher(
String name,
Class<? extends TypeSerializer> serializerClass,
Class<? extends TypeSerializerSnapshot> snapshotClass,
Supplier<? extends TypeSerializer<T>> serializerProvider,
Matcher<TypeSerializerSchemaCompatibility<T>> schemaCompatibilityMatcher) {
for (MigrationVersion testVersion : testVersions) {
testSpecifications.add(
TestSpecification.<T>builder(
getSpecNameForVersion(name, testVersion),
serializerClass,
snapshotClass,
testVersion)
.withNewSerializerProvider(serializerProvider)
.withSchemaCompatibilityMatcher(schemaCompatibilityMatcher)
.withSnapshotDataLocation(
String.format(DEFAULT_SNAPSHOT_FILENAME_FORMAT, testVersion, name))
.withTestData(
String.format(DEFAULT_TEST_DATA_FILENAME_FORMAT, testVersion, name),
DEFAULT_TEST_DATA_COUNT)
);
}
}
/**
* Adds a test specification to be tested for all specified test versions.
*
* <p>This method adds the specification with pre-defined snapshot and data filenames,
* with the format "flink-<testVersion>-<specName>-<data/snapshot>",
* and each specification's test data count is assumed to always be 10.
*
* @param name test specification name.
* @param serializerClass class of the current serializer.
* @param snapshotClass class of the current serializer snapshot class.
* @param serializerProvider provider for an instance of the current serializer.
* @param elementMatcher an {@code hamcrest} matcher to match test data.
*
* @param <T> type of the test data.
*/
public <T> void add(
String name,
Class<? extends TypeSerializer> serializerClass,
Class<? extends TypeSerializerSnapshot> snapshotClass,
Supplier<? extends TypeSerializer<T>> serializerProvider,
Matcher<T> elementMatcher) {
for (MigrationVersion testVersion : testVersions) {
testSpecifications.add(
TestSpecification.<T>builder(
getSpecNameForVersion(name, testVersion),
serializerClass,
snapshotClass,
testVersion)
.withNewSerializerProvider(serializerProvider)
.withSnapshotDataLocation(
String.format(DEFAULT_SNAPSHOT_FILENAME_FORMAT, testVersion, name))
.withTestData(
String.format(DEFAULT_TEST_DATA_FILENAME_FORMAT, testVersion, name),
DEFAULT_TEST_DATA_COUNT)
.withTestDataMatcher(elementMatcher)
);
}
}
/**
* Adds a test specification to be tested for all specified test versions.
*
* @param name test specification name.
* @param serializerClass class of the current serializer.
* @param snapshotClass class of the current serializer snapshot class.
* @param serializerProvider provider for an instance of the current serializer.
* @param testSnapshotFilenameProvider provider for the filename of the test snapshot.
* @param testDataFilenameProvider provider for the filename of the test data.
* @param testDataCount expected number of records to be read in the test data files.
*
* @param <T> type of the test data.
*/
public <T> void add(
String name,
Class<? extends TypeSerializer> serializerClass,
Class<? extends TypeSerializerSnapshot> snapshotClass,
Supplier<? extends TypeSerializer<T>> serializerProvider,
TestResourceFilenameSupplier testSnapshotFilenameProvider,
TestResourceFilenameSupplier testDataFilenameProvider,
int testDataCount) {
for (MigrationVersion testVersion : testVersions) {
testSpecifications.add(
TestSpecification.<T>builder(
getSpecNameForVersion(name, testVersion),
serializerClass,
snapshotClass,
testVersion)
.withNewSerializerProvider(serializerProvider)
.withSnapshotDataLocation(testSnapshotFilenameProvider.get(testVersion))
.withTestData(testDataFilenameProvider.get(testVersion), testDataCount)
);
}
}
public Collection<TestSpecification<?>> get() {
return Collections.unmodifiableCollection(testSpecifications);
}
private static String getSpecNameForVersion(String baseName, MigrationVersion testVersion) {
return testVersion + "-" + baseName;
}
}
/**
* Supplier of paths based on {@link MigrationVersion}.
*/
protected interface TestResourceFilenameSupplier {
String get(MigrationVersion testVersion);
}
}
| [FLINK-11767] Deprecate TypeSerializerSnapshotMigrationTestBase in favour of TypeSerializerUpgradeTestBase
There are still a lot of tests that need to be ported, but we should not
add new tests using the old test base.
| flink-core/src/test/java/org/apache/flink/api/common/typeutils/TypeSerializerSnapshotMigrationTestBase.java | [FLINK-11767] Deprecate TypeSerializerSnapshotMigrationTestBase in favour of TypeSerializerUpgradeTestBase | <ide><path>link-core/src/test/java/org/apache/flink/api/common/typeutils/TypeSerializerSnapshotMigrationTestBase.java
<ide> * A test base for verifying {@link TypeSerializerSnapshot} migration.
<ide> *
<ide> * @param <ElementT> the element being serialized.
<add> *
<add> * @deprecated please use the newer {@link TypeSerializerUpgradeTestBase}
<ide> */
<add>@Deprecated
<ide> public abstract class TypeSerializerSnapshotMigrationTestBase<ElementT> extends TestLogger {
<ide>
<ide> private final TestSpecification<ElementT> testSpecification; |
|
Java | bsd-3-clause | 622245432b23ec34246bf4acce18a6852541192d | 0 | troyel/dhis2-core,uonafya/jphes-core,uonafya/jphes-core,jason-p-pickering/dhis2-persian-calendar,jason-p-pickering/dhis2-core,vmluan/dhis2-core,msf-oca-his/dhis2-core,troyel/dhis2-core,msf-oca-his/dhis2-core,troyel/dhis2-core,dhis2/dhis2-core,vietnguyen/dhis2-core,vmluan/dhis2-core,dhis2/dhis2-core,msf-oca-his/dhis2-core,HRHR-project/palestine,HRHR-project/palestine,vmluan/dhis2-core,HRHR-project/palestine,uonafya/jphes-core,hispindia/dhis2-Core,jason-p-pickering/dhis2-persian-calendar,troyel/dhis2-core,jason-p-pickering/dhis2-core,msf-oca-his/dhis-core,vietnguyen/dhis2-core,hispindia/dhis2-Core,vietnguyen/dhis2-core,msf-oca-his/dhis-core,troyel/dhis2-core,jason-p-pickering/dhis2-persian-calendar,HRHR-project/palestine,msf-oca-his/dhis-core,vietnguyen/dhis2-core,msf-oca-his/dhis-core,uonafya/jphes-core,uonafya/jphes-core,jason-p-pickering/dhis2-persian-calendar,vmluan/dhis2-core,dhis2/dhis2-core,jason-p-pickering/dhis2-core,jason-p-pickering/dhis2-core,jason-p-pickering/dhis2-core,hispindia/dhis2-Core,hispindia/dhis2-Core,jason-p-pickering/dhis2-persian-calendar,vmluan/dhis2-core,vietnguyen/dhis2-core,dhis2/dhis2-core,msf-oca-his/dhis2-core,msf-oca-his/dhis2-core,HRHR-project/palestine,hispindia/dhis2-Core,dhis2/dhis2-core,msf-oca-his/dhis-core | package org.hisp.dhis.pushanalysis;
/*
* Copyright (c) 2004-2016, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 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.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
*/
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import org.hisp.dhis.common.BaseIdentifiableObject;
import org.hisp.dhis.common.DxfNamespaces;
import org.hisp.dhis.common.IdentifiableObject;
import org.hisp.dhis.common.MergeMode;
import org.hisp.dhis.dashboard.Dashboard;
import org.hisp.dhis.user.UserGroup;
import java.util.Date;
import java.util.Set;
/**
* PushAnalysis generates reports based on a Dashboard, and sends them to UserGroups
* at given Intervals.
*
* @author Stian Sandvold
*/
@JacksonXmlRootElement( localName = "pushanalysis", namespace = DxfNamespaces.DXF_2_0 )
public class PushAnalysis
extends BaseIdentifiableObject
{
/**
* PushAnalysis uses a dashboard to base it's reports on
*/
private Dashboard dashboard;
/**
* Title of the report. Will be at the top of each report
*/
private String title;
/**
* The message will be written in the report. Used to explain or describe reports to users
*/
private String message;
/**
* PushAnalysis reports are sent to one or more userGroups
*/
private Set<UserGroup> recipientUserGroups;
/**
* Indicates whether or not reports should be generated and sent to users automatically at given intervals
*/
private boolean enabled;
/**
* The Date of the last successful run
*/
private Date lastRun;
/**
* The frequency of which the push analysis should run (daily, weekly, monthly)
*/
private SchedulingFrequency schedulingFrequency;
/**
* Which day in the frequency the job should run
*/
private Integer schedulingDayOfFrequency;
public PushAnalysis()
{
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public Date getLastRun()
{
return lastRun;
}
public void setLastRun( Date lastRun )
{
this.lastRun = lastRun;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public Dashboard getDashboard()
{
return dashboard;
}
public void setDashboard( Dashboard dashboard )
{
this.dashboard = dashboard;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public Set<UserGroup> getRecipientUserGroups()
{
return recipientUserGroups;
}
public void setRecipientUserGroups( Set<UserGroup> recipientUserGroups )
{
this.recipientUserGroups = recipientUserGroups;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public String getName()
{
return name;
}
public void setName( String name )
{
this.name = name;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public String getMessage()
{
return message;
}
public void setMessage( String message )
{
this.message = message;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean getEnabled()
{
return this.enabled;
}
public void setEnabled( boolean enabled )
{
this.enabled = enabled;
}
public String getSchedulingKey()
{
return "PushAnalysis:" + getUid();
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public SchedulingFrequency getSchedulingFrequency()
{
return schedulingFrequency;
}
public void setSchedulingFrequency( SchedulingFrequency schedulingFrequency )
{
this.schedulingFrequency = schedulingFrequency;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public Integer getSchedulingDayOfFrequency()
{
return schedulingDayOfFrequency;
}
public void setSchedulingDayOfFrequency( Integer schedulingDayOfFrequency )
{
this.schedulingDayOfFrequency = schedulingDayOfFrequency;
}
public boolean canSchedule()
{
return (schedulingFrequency != null && enabled);
}
@Override
public boolean haveUniqueNames()
{
return false;
}
@Override
public void mergeWith( IdentifiableObject other, MergeMode mergeMode )
{
super.mergeWith( other, mergeMode );
if ( other.getClass().isInstance( this ) )
{
PushAnalysis pushAnalysis = (PushAnalysis) other;
if ( mergeMode.isReplace() )
{
dashboard = pushAnalysis.getDashboard();
recipientUserGroups = pushAnalysis.getRecipientUserGroups();
name = pushAnalysis.getName();
message = pushAnalysis.getMessage();
enabled = pushAnalysis.getEnabled();
schedulingDayOfFrequency = pushAnalysis.getSchedulingDayOfFrequency();
schedulingFrequency = pushAnalysis.getSchedulingFrequency();
}
if ( mergeMode.isMerge() )
{
dashboard = pushAnalysis.getDashboard() == null ? dashboard : pushAnalysis.getDashboard();
recipientUserGroups = pushAnalysis.getRecipientUserGroups() == null ?
recipientUserGroups :
pushAnalysis.getRecipientUserGroups();
name = pushAnalysis.getName() == null ? name : pushAnalysis.getName();
message = pushAnalysis.getMessage() == null ? message : pushAnalysis.getMessage();
enabled = pushAnalysis.getEnabled();
schedulingDayOfFrequency = pushAnalysis.getSchedulingDayOfFrequency() == null ?
schedulingDayOfFrequency :
pushAnalysis.getSchedulingDayOfFrequency();
schedulingFrequency = pushAnalysis.getSchedulingFrequency() == null ?
schedulingFrequency :
pushAnalysis.getSchedulingFrequency();
}
}
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public String getTitle()
{
return title;
}
public void setTitle( String title )
{
this.title = title;
}
}
| dhis-2/dhis-api/src/main/java/org/hisp/dhis/pushanalysis/PushAnalysis.java | package org.hisp.dhis.pushanalysis;
/*
* Copyright (c) 2004-2016, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 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.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
*/
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import org.hisp.dhis.common.BaseIdentifiableObject;
import org.hisp.dhis.common.DxfNamespaces;
import org.hisp.dhis.common.IdentifiableObject;
import org.hisp.dhis.common.MergeMode;
import org.hisp.dhis.dashboard.Dashboard;
import org.hisp.dhis.user.UserGroup;
import java.util.Date;
import java.util.Set;
/**
* PushAnalysis generates reports based on a Dashboard, and sends them to UserGroups
* at given Intervals.
*
* @author Stian Sandvold
*/
@JacksonXmlRootElement( localName = "pushanalysis", namespace = DxfNamespaces.DXF_2_0 )
public class PushAnalysis
extends BaseIdentifiableObject
{
/**
* PushAnalysis uses a dashboard to base it's reports on
*/
private Dashboard dashboard;
/**
* Title of the report. Will be at the top of each report
*/
private String title;
/**
* The message will be written in the report. Used to explain or describe reports to users
*/
private String message;
/**
* PushAnalysis reports are sent to one or more userGroups
*/
private Set<UserGroup> recipientUserGroups;
/**
* Indicates whether or not reports should be generated and sent to users automatically at given intervals
*/
private boolean enabled;
/**
* The Date of the last successful run
*/
private Date lastRun;
/**
* The frequency of which the push analysis should run (daily, weekly, monthly)
*/
private SchedulingFrequency schedulingFrequency;
/**
* Which day in the frequency the job should run
*/
private Integer schedulingDayOfFrequency;
public PushAnalysis()
{
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public Date getLastRun()
{
return lastRun;
}
public void setLastRun( Date lastRun )
{
this.lastRun = lastRun;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public Dashboard getDashboard()
{
return dashboard;
}
public void setDashboard( Dashboard dashboard )
{
this.dashboard = dashboard;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public Set<UserGroup> getRecipientUserGroups()
{
return recipientUserGroups;
}
public void setRecipientUserGroups( Set<UserGroup> recipientUserGroups )
{
this.recipientUserGroups = recipientUserGroups;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public String getName()
{
return name;
}
public void setName( String name )
{
this.name = name;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public String getMessage()
{
return message;
}
public void setMessage( String message )
{
this.message = message;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean getEnabled()
{
return this.enabled;
}
public void setEnabled( boolean enabled )
{
this.enabled = enabled;
}
public String getSchedulingKey()
{
return "PushAnalysis:" + getUid();
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public SchedulingFrequency getSchedulingFrequency()
{
return schedulingFrequency;
}
public void setSchedulingFrequency( SchedulingFrequency schedulingFrequency )
{
this.schedulingFrequency = schedulingFrequency;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public Integer getSchedulingDayOfFrequency()
{
return schedulingDayOfFrequency;
}
public void setSchedulingDayOfFrequency( Integer schedulingDayOfFrequency )
{
this.schedulingDayOfFrequency = schedulingDayOfFrequency;
}
public boolean canSchedule()
{
return (schedulingFrequency != null && enabled);
}
@Override
public boolean haveUniqueNames()
{
return false;
}
@Override
public void mergeWith( IdentifiableObject other, MergeMode mergeMode )
{
super.mergeWith( other, mergeMode );
if ( other.getClass().isInstance( this ) )
{
PushAnalysis pushAnalysis = (PushAnalysis) other;
if ( mergeMode.isReplace() )
{
dashboard = pushAnalysis.getDashboard();
recipientUserGroups = pushAnalysis.getRecipientUserGroups();
name = pushAnalysis.getName();
message = pushAnalysis.getMessage();
schedulingDayOfFrequency = pushAnalysis.getSchedulingDayOfFrequency();
schedulingFrequency = pushAnalysis.getSchedulingFrequency();
}
if ( mergeMode.isMerge() )
{
dashboard = pushAnalysis.getDashboard() == null ? dashboard : pushAnalysis.getDashboard();
recipientUserGroups = pushAnalysis.getRecipientUserGroups() == null ?
recipientUserGroups :
pushAnalysis.getRecipientUserGroups();
name = pushAnalysis.getName() == null ? name : pushAnalysis.getName();
message = pushAnalysis.getMessage() == null ? message : pushAnalysis.getMessage();
schedulingDayOfFrequency = pushAnalysis.getSchedulingDayOfFrequency() == null ?
schedulingDayOfFrequency :
pushAnalysis.getSchedulingDayOfFrequency();
schedulingFrequency = pushAnalysis.getSchedulingFrequency() == null ?
schedulingFrequency :
pushAnalysis.getSchedulingFrequency();
}
}
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public String getTitle()
{
return title;
}
public void setTitle( String title )
{
this.title = title;
}
}
| Minor fix for mergeWith for PushAnalysis; Had forgotten to set enabled
| dhis-2/dhis-api/src/main/java/org/hisp/dhis/pushanalysis/PushAnalysis.java | Minor fix for mergeWith for PushAnalysis; Had forgotten to set enabled | <ide><path>his-2/dhis-api/src/main/java/org/hisp/dhis/pushanalysis/PushAnalysis.java
<ide> recipientUserGroups = pushAnalysis.getRecipientUserGroups();
<ide> name = pushAnalysis.getName();
<ide> message = pushAnalysis.getMessage();
<add> enabled = pushAnalysis.getEnabled();
<ide> schedulingDayOfFrequency = pushAnalysis.getSchedulingDayOfFrequency();
<ide> schedulingFrequency = pushAnalysis.getSchedulingFrequency();
<ide> }
<ide> pushAnalysis.getRecipientUserGroups();
<ide> name = pushAnalysis.getName() == null ? name : pushAnalysis.getName();
<ide> message = pushAnalysis.getMessage() == null ? message : pushAnalysis.getMessage();
<add> enabled = pushAnalysis.getEnabled();
<ide> schedulingDayOfFrequency = pushAnalysis.getSchedulingDayOfFrequency() == null ?
<ide> schedulingDayOfFrequency :
<ide> pushAnalysis.getSchedulingDayOfFrequency(); |
|
Java | apache-2.0 | cacdd90bb4722943cea2569a5efeab93c32646d0 | 0 | xujun10110/crawljax,fivejjs/crawljax,cschroed-usgs/crawljax,adini121/crawljax,bigplus/crawljax,adini121/crawljax,aminmf/crawljax,ntatsumi/crawljax,robertzas/crawljax,xujun10110/crawljax,bigplus/crawljax,crawljax/crawljax,aminmf/crawljax,fivejjs/crawljax,xujun10110/crawljax,cschroed-usgs/crawljax,crawljax/crawljax,aminmf/crawljax,fivejjs/crawljax,fivejjs/crawljax,robertzas/crawljax,adini121/crawljax,crawljax/crawljax,ntatsumi/crawljax,saltlab/crawljax-graphdb,ntatsumi/crawljax,crawljax/crawljax,bigplus/crawljax,robertzas/crawljax,bigplus/crawljax,cschroed-usgs/crawljax,adini121/crawljax,xujun10110/crawljax,aminmf/crawljax,saltlab/crawljax-graphdb,cschroed-usgs/crawljax,ntatsumi/crawljax,robertzas/crawljax | package com.crawljax.core;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.configuration.ConfigurationException;
import org.junit.BeforeClass;
import org.junit.Test;
import com.crawljax.browser.BrowserFactory;
import com.crawljax.core.configuration.CrawlSpecification;
import com.crawljax.core.configuration.CrawljaxConfiguration;
import com.crawljax.util.PropertyHelper;
public class CandidateElementExtractorTest {
private static String url = "http://spci.st.ewi.tudelft.nl/demo/crawljax/";
@BeforeClass
public static void startup() {
}
@Test
public void testExtract() {
CrawljaxConfiguration config = new CrawljaxConfiguration();
CrawlSpecification spec = new CrawlSpecification(url);
config.setCrawlSpecification(spec);
Crawler crawler = null;
try {
CrawljaxController controller = new CrawljaxController(config);
crawler = controller.getCrawler();
} catch (ConfigurationException e1) {
e1.printStackTrace();
fail(e1.getMessage());
}
assertNotNull(crawler);
try {
crawler.goToInitialURL();
} catch (CrawljaxException e1) {
e1.printStackTrace();
fail(e1.getMessage());
}
try {
Thread.sleep(400);
} catch (InterruptedException e) {
e.printStackTrace();
fail(e.getMessage());
}
CandidateElementExtractor extractor = new CandidateElementExtractor(crawler);
assertNotNull(extractor);
try {
String inc = "a:{}";
TagElement tagElementInc = PropertyHelper.parseTagElements(inc);
List<TagElement> includes = new ArrayList<TagElement>();
includes.add(tagElementInc);
List<CandidateElement> candidates =
extractor.extract(includes, new ArrayList<TagElement>(), true);
assertNotNull(candidates);
assertEquals(15, candidates.size());
} catch (CrawljaxException e) {
e.printStackTrace();
fail(e.getMessage());
}
BrowserFactory.close();
}
@Test
public void testExtractExclude() {
CrawljaxConfiguration config = new CrawljaxConfiguration();
CrawlSpecification spec = new CrawlSpecification(url);
config.setCrawlSpecification(spec);
Crawler crawler = null;
try {
CrawljaxController controller = new CrawljaxController(config);
crawler = controller.getCrawler();
} catch (ConfigurationException e1) {
e1.printStackTrace();
fail(e1.getMessage());
}
assertNotNull(crawler);
try {
crawler.goToInitialURL();
} catch (CrawljaxException e1) {
e1.printStackTrace();
fail(e1.getMessage());
}
try {
Thread.sleep(400);
} catch (InterruptedException e) {
e.printStackTrace();
fail(e.getMessage());
}
CandidateElementExtractor extractor = new CandidateElementExtractor(crawler);
assertNotNull(extractor);
try {
String inc = "a:{}";
TagElement tagElementInc = PropertyHelper.parseTagElements(inc);
List<TagElement> includes = new ArrayList<TagElement>();
includes.add(tagElementInc);
// now exclude some elements
String exc = "div:{id=menubar}";
List<TagElement> excludes = new ArrayList<TagElement>();
TagElement tagElementExc = PropertyHelper.parseTagElements(exc);
excludes.add(tagElementExc);
List<CandidateElement> candidates = extractor.extract(includes, excludes, true);
assertNotNull(candidates);
assertEquals(11, candidates.size());
} catch (CrawljaxException e) {
e.printStackTrace();
fail(e.getMessage());
}
BrowserFactory.close();
}
}
| src/test/java/com/crawljax/core/CandidateElementExtractorTest.java | package com.crawljax.core;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.configuration.ConfigurationException;
import org.junit.BeforeClass;
import org.junit.Test;
import com.crawljax.browser.BrowserFactory;
import com.crawljax.core.configuration.CrawlSpecification;
import com.crawljax.core.configuration.CrawljaxConfiguration;
import com.crawljax.util.PropertyHelper;
public class CandidateElementExtractorTest {
private static String url = "http://spci.st.ewi.tudelft.nl/demo/crawljax/";
@BeforeClass
public static void startup() {
}
@Test
public void testExtract() {
CrawljaxConfiguration config = new CrawljaxConfiguration();
CrawlSpecification spec = new CrawlSpecification(url);
config.setCrawlSpecification(spec);
Crawler crawler = null;
try {
CrawljaxController controller = new CrawljaxController(config);
crawler = controller.getCrawler();
} catch (ConfigurationException e1) {
e1.printStackTrace();
fail(e1.getMessage());
}
try {
Thread.sleep(400);
} catch (InterruptedException e) {
e.printStackTrace();
fail(e.getMessage());
}
CandidateElementExtractor extractor = new CandidateElementExtractor(crawler);
assertNotNull(extractor);
try {
String inc = "a:{}";
TagElement tagElementInc = PropertyHelper.parseTagElements(inc);
List<TagElement> includes = new ArrayList<TagElement>();
includes.add(tagElementInc);
List<CandidateElement> candidates =
extractor.extract(includes, new ArrayList<TagElement>(), true);
assertNotNull(candidates);
assertEquals(15, candidates.size());
} catch (CrawljaxException e) {
e.printStackTrace();
fail(e.getMessage());
}
BrowserFactory.close();
}
@Test
public void testExtractExclude() {
CrawljaxConfiguration config = new CrawljaxConfiguration();
CrawlSpecification spec = new CrawlSpecification(url);
config.setCrawlSpecification(spec);
Crawler crawler = null;
try {
CrawljaxController controller = new CrawljaxController(config);
crawler = controller.getCrawler();
} catch (ConfigurationException e1) {
e1.printStackTrace();
fail(e1.getMessage());
}
assertNotNull(crawler);
try {
Thread.sleep(400);
} catch (InterruptedException e) {
e.printStackTrace();
fail(e.getMessage());
}
CandidateElementExtractor extractor = new CandidateElementExtractor(crawler);
assertNotNull(extractor);
try {
String inc = "a:{}";
TagElement tagElementInc = PropertyHelper.parseTagElements(inc);
List<TagElement> includes = new ArrayList<TagElement>();
includes.add(tagElementInc);
// now exclude some elements
String exc = "div:{id=menubar}";
List<TagElement> excludes = new ArrayList<TagElement>();
TagElement tagElementExc = PropertyHelper.parseTagElements(exc);
excludes.add(tagElementExc);
List<CandidateElement> candidates = extractor.extract(includes, excludes, true);
assertNotNull(candidates);
assertEquals(11, candidates.size());
} catch (CrawljaxException e) {
e.printStackTrace();
fail(e.getMessage());
}
BrowserFactory.close();
}
}
| Fixed failed test after not having the initial url loaded directly
| src/test/java/com/crawljax/core/CandidateElementExtractorTest.java | Fixed failed test after not having the initial url loaded directly | <ide><path>rc/test/java/com/crawljax/core/CandidateElementExtractorTest.java
<ide> CrawljaxController controller = new CrawljaxController(config);
<ide> crawler = controller.getCrawler();
<ide> } catch (ConfigurationException e1) {
<add> e1.printStackTrace();
<add> fail(e1.getMessage());
<add> }
<add>
<add> assertNotNull(crawler);
<add>
<add> try {
<add> crawler.goToInitialURL();
<add> } catch (CrawljaxException e1) {
<ide> e1.printStackTrace();
<ide> fail(e1.getMessage());
<ide> }
<ide> assertNotNull(crawler);
<ide>
<ide> try {
<add> crawler.goToInitialURL();
<add> } catch (CrawljaxException e1) {
<add> e1.printStackTrace();
<add> fail(e1.getMessage());
<add> }
<add>
<add> try {
<ide> Thread.sleep(400);
<ide> } catch (InterruptedException e) {
<ide> e.printStackTrace(); |
|
Java | apache-2.0 | 1fc58abb7a833ec2701f4b388285346bf268a122 | 0 | CARENTA/CARENTA | import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ArrayList;
/* This is a simple test class used for testing that all the methods work! */
public class Controller {
static DateFormat dateFormat = new SimpleDateFormat("YYYY/M/D"); // Gets the current date!
static Date date = new Date();
static String currentDate = dateFormat.format(date);
static int orderNbr = 0;
static int customerNbr = 0;
static int productNbr = 0;
static int currentDiscount = 0; // Current over all discount level, could be seasonal...
static String enteredDate; // Variable containing entered rental date for order...
static Warehouse selectedWarehouse; // Variable containing selected warehouse...
static String selectedType; // Variable containing selected vehicle type...
public static CustomerRegistry customerRegistry = new CustomerRegistry(); // Creates registers!
static WarehouseRegistry warehouseRegistry = new WarehouseRegistry();
public static OrderRegistry orderRegistry = new OrderRegistry();
static VehicleRegistry vehicleRegistry = new VehicleRegistry();
public static AccessoryRegistry accessoryRegistry = new AccessoryRegistry();
public static EmployeeRegistry employeeRegistry = new EmployeeRegistry();
public static void main(String[] args) {
customerRegistry = createCustomers(customerRegistry);
warehouseRegistry = createWarehouses(warehouseRegistry);
vehicleRegistry = createVehicles(vehicleRegistry, warehouseRegistry); // Creates objects and stores them in the registers!
accessoryRegistry = createAccessories(accessoryRegistry);
employeeRegistry = createEmployees(employeeRegistry);
orderRegistry = createOrders(orderRegistry);
MainGUI mainGUI = new MainGUI(); // Creates the GUI!
}
/* -----------------------------------------------------------------------*/
/* ----------------CALCULATE VEHICLE AVAILABILITY-------------------------*/
/* -----------------------------------------------------------------------*/
public ArrayList<Vehicle> calculateVehicleAvailability(String enteredDate, String selectedWarehouse, String selectedType) {
ArrayList<Vehicle> availableVehicles = new ArrayList<Vehicle>(); // Create a list which will contain the available vehicles...
Vehicle vehicle;
String vehicleWarehouse;
String vehicleType;
for(int a = 0; a < vehicleRegistry.getVehicles().size(); a++) { // Search the entire vehicle registry...
vehicle = vehicleRegistry.getVehicle(a);
vehicleWarehouse = vehicle.getWarehouse().getCity();
vehicleType = vehicle.getType();
if(selectedWarehouse.equals(vehicleWarehouse) && selectedType.equals(vehicleType) && vehicle.isBookable(enteredDate)) { // If the vehicle matches desired warehouse, type and if it's bookable...
availableVehicles.add(vehicle); // Add it to the list!
}
}
return availableVehicles; // Return the list!
}
/* -----------------------------------------------------------------------*/
/* --------------GET CURRENT VEHICLE TYPES -------------------------------*/
/* -----------------------------------------------------------------------*/
public ArrayList<String> getCurrentVehicleTypes() {
ArrayList<String> vehicleTypes = new ArrayList<String>(10);
vehicleTypes.add("Personbil");
vehicleTypes.add("Sportbil");
vehicleTypes.add("Minibuss");
vehicleTypes.add("Lastbil");
return vehicleTypes;
}
/* -----------------------------------------------------------------------*/
/* ---------------------GET WAREHOUSE NAMES ------------------------------*/
/* -----------------------------------------------------------------------*/
public static ArrayList<String> getWarehouseNames () {
ArrayList<String> warehouseNames = new ArrayList<String>();
for(int a = 0; a < warehouseRegistry.getWarehouses().size(); a++) {
Warehouse warehouse = warehouseRegistry.getWarehouse(a);
warehouseNames.add(warehouse.getCity());
}
return warehouseNames;
}
/* -----------------------------------------------------------------------*/
/* --------------GET SELECTED WAREHOUSE ----------------------------------*/
/* -----------------------------------------------------------------------*/
public static Warehouse getSelectedWarehouse (String warehouseChoice) {
for(int a = 0; a < warehouseRegistry.getWarehouses().size(); a++) {
Warehouse warehouse = warehouseRegistry.getWarehouse(a);
if(warehouseChoice.equals(warehouse.getCity())) {
return warehouse;
}
}
return null;
}
/* -----------------------------------------------------------------------*/
/* ---------------FIND ACCESSORY------------------------------------------*/
/* -----------------------------------------------------------------------*/
public Accessory findAccessory(int enteredProductNbr) {
for(int a = 0; a < accessoryRegistry.getAccessories().size(); a++) { // Searching thru the registry
Accessory accessory = accessoryRegistry.getAccessory(a); // Put the current accessory in an own variable...
if(accessory.getProductNbr() == (enteredProductNbr)) { // If the given product number is equal to an existing accessories product number
return accessory;
}
}
return null;
}
/* -----------------------------------------------------------------------*/
/* ------------------------------CREATE ACCESSORY-------------------------*/
/* -----------------------------------------------------------------------*/
public static void createAccessory(String inputName, int inputPrice, String inputInfo) {
productNbr = productNbr+1;
Accessory accessory = new Accessory(productNbr, inputName, inputPrice, inputInfo);
accessoryRegistry.addAccessory(accessory); // Adds the accessory to the registry!
}
/* -----------------------------------------------------------------------*/
/* --------------CREATE PRIVATE CUSTOMER --------------------------------*/
/* -----------------------------------------------------------------------*/
public void createPrivateCustomer(String personalNbr, String firstName, String lastName, String address,
String city, String areaCode, String telephoneNbr, String mail) {
customerNbr = customerNbr + 1;
PrivateCustomer newCustomer = new PrivateCustomer(customerNbr, personalNbr, firstName, lastName, address,
city, areaCode, telephoneNbr, mail, 1);
customerRegistry.addCustomer(newCustomer);
}
/* -----------------------------------------------------------------------*/
/* --------------CREATE COMPANY CUSTOMER ------------------------------------------*/
/* -----------------------------------------------------------------------*/
public void createCompanyCustomer(String orgNbr, String name, String adress, String city,
String areaCode, String phoneNbr, String mailAdress) {
customerNbr = customerNbr + 1;
CompanyCustomer newCustomer = new CompanyCustomer(customerNbr, orgNbr, name, adress, city, areaCode, phoneNbr, mailAdress, 1);
customerRegistry.addCustomer(newCustomer);
}
/* -----------------------------------------------------------------------*/
/* ---------------FIND CUSTOMER ------------------------------------------*/
/* -----------------------------------------------------------------------*/
/* public String findCustomer(String enteredCustomerNbr) {
for(int a = 0; a < customerRegistry.getCustomers().size(); a++) { // Check the entire registry...
Customer customer = customerRegistry.getCustomer(a); // Put the current customer in an own variable...
if(customer.getCustomerNbr().equals(enteredCustomerNbr)) { // If the given customer number is equal to an existing customers customer number...
String customerResult = "Förnamn: " + customer.getFirstName() + "\n\n" + // Retrieve the customers information, put it together nicely and...
"Efternamn: " + customer.getLastName() + "\n\n" +
"Kundnummer: " + customer.getCustomerNbr() + "\n\n" +
"Adress: " + customer.getAdress() + "\n\n" +
"Stad: " + customer.getCity() + "\n\n" +
"Postnummer: " + customer.getAreaCode() + "\n\n" +
"Telefonnummer: " + customer.getPhoneNbr() + "\n\n" +
"E-mail-adress: " + customer.getMailAdress() + "\n\n" +
"Rabattnivå: " + customer.getDiscountLevel();
return customerResult; // ... send it back!
}
}
return "Kunden kunde inte hittas!"; // If there was no matching customer number!
} */
/* -----------------------------------------------------------------------*/
/* ----------------------CREATE ORDER NOT COMPLETED-----------------------*/
/* -----------------------------------------------------------------------*/
public static void createOrder(Customer customer, ArrayList<Product> shoppingCart,
Employee employee) {
orderNbr = orderNbr + 1;
int totalPrice = 0;
Product product;
boolean isAppropriate = true; // MUST BE FIXED!!!!!
boolean wasSatisfied = true; // MUST BE FIXED!!!!
String latestUpdate = currentDate;
int discount = currentDiscount;
for(int a = 0; a < shoppingCart.size(); a++) {
product = shoppingCart.get(a);
totalPrice = totalPrice + product.getPrice();
}
Order order = new Order(orderNbr, customer,
shoppingCart, employee, totalPrice,
discount, isAppropriate, wasSatisfied, latestUpdate);
orderRegistry.addOrder(order);
customer.addPreviousOrder(order);
}
/* -----------------------------------------------------------------------*/
/* ------------------------CREATE CUSTOMERS-----------------------------*/
/* -----------------------------------------------------------------------*/
public static CustomerRegistry createCustomers (CustomerRegistry customerRegistry) {
CompanyCustomer companyCustomer1 = new CompanyCustomer(1, "123", "Itab AB", "Hejgatan 2", "Linköping", "45357", "070734958", "[email protected]", 2); // Creates the customers...
CompanyCustomer companyCustomer2 = new CompanyCustomer(2, "354", "Kaffesump AB", "Högersvängen 7", "Lund", "22200", "0702332434", "[email protected]", 3);
CompanyCustomer companyCustomer3 = new CompanyCustomer(3, "623","Vågade Pojkar INC", "Genvägen 2B", "Göteborg", "45692", "0703748294", "[email protected]", 1);
CompanyCustomer companyCustomer4 = new CompanyCustomer(4, "477","Skånepartiet", "Slottsgatan 6", "Linköpig", "58000", "07347283939", "[email protected]", 5);
CompanyCustomer companyCustomer5 = new CompanyCustomer(5, "333","Odd & Nicklas INC", "Gårdsvägen 9A", "Lund", "23422", "0704221122", "[email protected]", 10);
PrivateCustomer privateCustomer6 = new PrivateCustomer(6, "8906453434", "Joachim","Karlsson", "Nissevägen 2A", "Linköping", "58343", "0704532326", "[email protected]", 1);
PrivateCustomer privateCustomer7 = new PrivateCustomer(7, "8805032323", "Alexander","Steen", "Rakavägen 4", "Linköping", "58343", "0704532326", "[email protected]", 2);
PrivateCustomer privateCustomer8 = new PrivateCustomer(8, "9205053434", "Peter","Forsberg", "Rakavägen 4", "Linköping", "58343", "0704532326", "[email protected]", 3);
PrivateCustomer privateCustomer9 = new PrivateCustomer(9, "9111233114", "Mats","Sundin", "Rakavägen 4", "Linköping", "58343", "0704532326", "[email protected]", 2);
PrivateCustomer privateCustomer10 = new PrivateCustomer(10, "7201014455", "Robert","Svensson", "Rakavägen 4", "Linköping", "58343", "0704532326", "[email protected]", 1);
customerRegistry.addCustomer(companyCustomer1); // Adds the customers to the registry...
customerRegistry.addCustomer(companyCustomer2);
customerRegistry.addCustomer(companyCustomer3);
customerRegistry.addCustomer(companyCustomer4);
customerRegistry.addCustomer(companyCustomer5);
customerRegistry.addCustomer(privateCustomer6);
customerRegistry.addCustomer(privateCustomer7);
customerRegistry.addCustomer(privateCustomer8);
customerRegistry.addCustomer(privateCustomer9);
customerRegistry.addCustomer(privateCustomer10);
return customerRegistry;
}
/* -----------------------------------------------------------------------*/
/* ---------------------------CREATE WAREHOUSES--------------------------------*/
/* -----------------------------------------------------------------------*/
public static WarehouseRegistry createWarehouses (WarehouseRegistry warehouseRegistry) {
Warehouse warehouse1 = new Warehouse("Storgatan 1", "Lund", "22363"); // Creates warehouses!
Warehouse warehouse2 = new Warehouse("Kråkvägen 2", "Linköping", "58437");
Warehouse warehouse3 = new Warehouse("Plogvägen 4", "Göteborg", "40225");
warehouseRegistry.addWarehouse(warehouse1);
warehouseRegistry.addWarehouse(warehouse2);
warehouseRegistry.addWarehouse(warehouse3);
return warehouseRegistry;
}
/* -----------------------------------------------------------------------*/
/* ---------------------------CREATE VEHICLES----------------------------*/
/* -----------------------------------------------------------------------*/
public static VehicleRegistry createVehicles (VehicleRegistry vehicleRegistry, WarehouseRegistry warehouseRegistry) {
Vehicle vehicle1 = new Vehicle("ABC123", "Volvo V70", "Personbil", "B", 800,"5-sittsig och plats för 5 väskor i bagageluckan", true, "2014-13-12", warehouseRegistry.getWarehouse(2)); // Creates the vehicles...
Vehicle vehicle2 = new Vehicle("GBY234", "Volvo V40", "Sportbil", "B", 700,"5-sittsig och plats för 3 väskor i bagageluckan", true, "2014-13-12", warehouseRegistry.getWarehouse(2));
Vehicle vehicle3 = new Vehicle("JER456", "Volvo S80", "Personbil", "B", 700,"5-sittsig och plats för 2 väskor i bagageluckan", true, "2014-13-12", warehouseRegistry.getWarehouse(0));
Vehicle vehicle4 = new Vehicle("SJF856", "Volvo V60", "Minibuss", "B", 700,"5-sittsig och plats för 4 väskor i bagageluckan", true, "2014-13-12", warehouseRegistry.getWarehouse(1));
Vehicle vehicle5 = new Vehicle("HFY345", "Volvo S40", "Personbil", "B", 600,"5-sittsig och plats för 3 väskor i bagageluckan", true, "2014-13-12", warehouseRegistry.getWarehouse(2));
Vehicle vehicle6 = new Vehicle("GJH876", "Volvo C30", "Personbil", "B", 600,"4-sittsig och plats för 2 väskor i bagageluckan", true, "2014-13-12", warehouseRegistry.getWarehouse(0));
Vehicle vehicle7 = new Vehicle("SHD786", "Volvo V50", "Lastbil", "B", 600,"5-sittsig och plats för 4 väskor i bagageluckan", true, "2014-13-12", warehouseRegistry.getWarehouse(0));
Vehicle vehicle8 = new Vehicle("DCG349", "Volvo XC90", "Lastbil", "B", 900,"7-sittsig och plats för 5 väskor i bagageluckan", true, "2014-13-12", warehouseRegistry.getWarehouse(1));
Vehicle vehicle9 = new Vehicle("DVT234", "Volvo XC60", "Personbil", "B", 800,"5-sittsig och plats för 5 väskor i bagageluckan", true, "2014-13-12", warehouseRegistry.getWarehouse(1));
Vehicle vehicle10 = new Vehicle("LOI765", "Volvo V70XC", "Sportbil", "B", 300,"5-sittsig och plats för 5 väskor i bagageluckan", true, "2014-13-12", warehouseRegistry.getWarehouse(2));
vehicleRegistry.addVehicle(vehicle1); // Adds the created vehicle to the registry!
vehicleRegistry.addVehicle(vehicle2);
vehicleRegistry.addVehicle(vehicle3);
vehicleRegistry.addVehicle(vehicle4);
vehicleRegistry.addVehicle(vehicle5);
vehicleRegistry.addVehicle(vehicle6);
vehicleRegistry.addVehicle(vehicle7);
vehicleRegistry.addVehicle(vehicle8);
vehicleRegistry.addVehicle(vehicle9);
vehicleRegistry.addVehicle(vehicle10);
return vehicleRegistry;
}
/* -----------------------------------------------------------------------*/
/* ------------------------------CREATE ACCESSORY----------------------*/
/* -----------------------------------------------------------------------*/
public static AccessoryRegistry createAccessories (AccessoryRegistry accessoryRegistry) {
Accessory accessory1 = new Accessory(1, "Vajer", 100, "Bra att ha!"); // Creates the accessories...
Accessory accessory2 = new Accessory(2, "Prasselpresenning", 200, "3x4 meter och Passar till stort släp");
Accessory accessory3 = new Accessory(3, "Prasselpresenning", 150, "1,5x2 meter, Passar till litet släp!");
Accessory accessory4 = new Accessory(4, "Spännband", 150, "4 meter");
Accessory accessory5 = new Accessory(5, "Spännband", 100, "2 meter");
Accessory accessory6 = new Accessory(6, "Stödhjul", 200, "Passar till alla släp");
Accessory accessory7 = new Accessory(7, "Stänkskärm", 300, "Passar alla personbilar och säljes 4 st");
Accessory accessory8 = new Accessory(8, "Oljefilter", 200, "Till volvomotorer");
Accessory accessory9 = new Accessory(9, "Kopplingkabel", 100, "Passar alla fordon");
Accessory accessory10 = new Accessory(10, "Luftfilter motor", 150, "Passar alla Volvo");
accessoryRegistry.addAccessory(accessory1); // Adds the accessory to the registry!
accessoryRegistry.addAccessory(accessory2);
accessoryRegistry.addAccessory(accessory3);
accessoryRegistry.addAccessory(accessory4);
accessoryRegistry.addAccessory(accessory5);
accessoryRegistry.addAccessory(accessory6);
accessoryRegistry.addAccessory(accessory7);
accessoryRegistry.addAccessory(accessory8);
accessoryRegistry.addAccessory(accessory9);
accessoryRegistry.addAccessory(accessory10);
return accessoryRegistry;
}
/* -----------------------------------------------------------------------*/
/* --------------------CREATE EMPLOYEES---------------------------------*/
/* -----------------------------------------------------------------------*/
public static EmployeeRegistry createEmployees (EmployeeRegistry employeeRegistry) {
PermanentEmployee employee1 = new PermanentEmployee(1, "8904304455", "Jonas", "Mellström", "0703435223", "[email protected]", 20000); // Creates the employees...
PermanentEmployee employee2 = new PermanentEmployee(2, "8804304455", "Malin", "Mellström", "0703435221", "[email protected]", 20000);
PermanentEmployee employee3 = new PermanentEmployee(3, "8604304455", "Swante", "Mellström", "0703435222", "[email protected]", 20000);
employeeRegistry.addEmployee(employee1); // Adds the employee to the registry!
employeeRegistry.addEmployee(employee2);
employeeRegistry.addEmployee(employee3);
return employeeRegistry;
}
/* -----------------------------------------------------------------------*/
/* --------------------CREATE ORDERS--------------------------------------*/
/* -----------------------------------------------------------------------*/
public static OrderRegistry createOrders (OrderRegistry orderRegistry) {
ArrayList<Product> productsTemplate = new ArrayList<Product>();
productsTemplate.add(accessoryRegistry.getAccessory(0));
Order order1 = new Order(orderNbr = orderNbr + 1, customerRegistry.getCustomer(3), productsTemplate, employeeRegistry.getEmployee(1), 1100, 0, true, true, currentDate);
Order order2 = new Order(orderNbr = orderNbr + 1, customerRegistry.getCustomer(1), productsTemplate, employeeRegistry.getEmployee(2), 5000, 0, true, true, currentDate);
Order order3 = new Order(orderNbr = orderNbr + 1, customerRegistry.getCustomer(9), productsTemplate, employeeRegistry.getEmployee(0), 300, 0, true, true, currentDate);
Order order4 = new Order(orderNbr = orderNbr + 1, customerRegistry.getCustomer(3), productsTemplate, employeeRegistry.getEmployee(1), 1100, 0, true, true, currentDate);
Order order5 = new Order(orderNbr = orderNbr + 1, customerRegistry.getCustomer(3), productsTemplate, employeeRegistry.getEmployee(2), 21100, 0, true, true, currentDate);
orderRegistry.addOrder(order1);
orderRegistry.addOrder(order2);
orderRegistry.addOrder(order3);
orderRegistry.addOrder(order4);
orderRegistry.addOrder(order5);
return orderRegistry;
}
/* -----------------------------------------------------------------------*/
/* -----------------------------------------------------------------------*/
/* -----------------------------------------------------------------------*/
}
| Source-files/Controller.java | import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ArrayList;
/* This is a simple test class used for testing that all the methods work! */
public class Controller {
static DateFormat dateFormat = new SimpleDateFormat("YYYY/M/D"); // Gets the current date!
static Date date = new Date();
static String currentDate = dateFormat.format(date);
static int orderNbr = 0;
static int customerNbr = 0;
static int currentDiscount = 0; // Current over all discount level, could be seasonal...
static String enteredDate; // Variable containing entered rental date for order...
static Warehouse selectedWarehouse; // Variable containing selected warehouse...
static String selectedType; // Variable containing selected vehicle type...
public static CustomerRegistry customerRegistry = new CustomerRegistry(); // Creates registers!
static WarehouseRegistry warehouseRegistry = new WarehouseRegistry();
public static OrderRegistry orderRegistry = new OrderRegistry();
static VehicleRegistry vehicleRegistry = new VehicleRegistry();
public static AccessoryRegistry accessoryRegistry = new AccessoryRegistry();
public static EmployeeRegistry employeeRegistry = new EmployeeRegistry();
public static void main(String[] args) {
customerRegistry = createCustomers(customerRegistry);
warehouseRegistry = createWarehouses(warehouseRegistry);
vehicleRegistry = createVehicles(vehicleRegistry, warehouseRegistry); // Creates objects and stores them in the registers!
accessoryRegistry = createAccessories(accessoryRegistry);
employeeRegistry = createEmployees(employeeRegistry);
orderRegistry = createOrders(orderRegistry);
MainGUI mainGUI = new MainGUI(); // Creates the GUI!
}
/* -----------------------------------------------------------------------*/
/* ----------------CALCULATE VEHICLE AVAILABILITY-------------------------*/
/* -----------------------------------------------------------------------*/
public ArrayList<Vehicle> calculateVehicleAvailability(String enteredDate, String selectedWarehouse, String selectedType) {
ArrayList<Vehicle> availableVehicles = new ArrayList<Vehicle>(); // Create a list which will contain the available vehicles...
Vehicle vehicle;
String vehicleWarehouse;
String vehicleType;
for(int a = 0; a < vehicleRegistry.getVehicles().size(); a++) { // Search the entire vehicle registry...
vehicle = vehicleRegistry.getVehicle(a);
vehicleWarehouse = vehicle.getWarehouse().getCity();
vehicleType = vehicle.getType();
if(selectedWarehouse.equals(vehicleWarehouse) && selectedType.equals(vehicleType) && vehicle.isBookable(enteredDate)) { // If the vehicle matches desired warehouse, type and if it's bookable...
availableVehicles.add(vehicle); // Add it to the list!
}
}
return availableVehicles; // Return the list!
}
/* -----------------------------------------------------------------------*/
/* --------------GET CURRENT VEHICLE TYPES -------------------------------*/
/* -----------------------------------------------------------------------*/
public ArrayList<String> getCurrentVehicleTypes() {
ArrayList<String> vehicleTypes = new ArrayList<String>(10);
vehicleTypes.add("Personbil");
vehicleTypes.add("Sportbil");
vehicleTypes.add("Minibuss");
vehicleTypes.add("Lastbil");
return vehicleTypes;
}
/* -----------------------------------------------------------------------*/
/* ---------------------GET WAREHOUSE NAMES ------------------------------*/
/* -----------------------------------------------------------------------*/
public static ArrayList<String> getWarehouseNames () {
ArrayList<String> warehouseNames = new ArrayList<String>();
for(int a = 0; a < warehouseRegistry.getWarehouses().size(); a++) {
Warehouse warehouse = warehouseRegistry.getWarehouse(a);
warehouseNames.add(warehouse.getCity());
}
return warehouseNames;
}
/* -----------------------------------------------------------------------*/
/* --------------GET SELECTED WAREHOUSE ----------------------------------*/
/* -----------------------------------------------------------------------*/
public static Warehouse getSelectedWarehouse (String warehouseChoice) {
for(int a = 0; a < warehouseRegistry.getWarehouses().size(); a++) {
Warehouse warehouse = warehouseRegistry.getWarehouse(a);
if(warehouseChoice.equals(warehouse.getCity())) {
return warehouse;
}
}
return null;
}
/* -----------------------------------------------------------------------*/
/* ---------------FIND ACCESSORY------------------------------------------*/
/* -----------------------------------------------------------------------*/
public Accessory findAccessory(int enteredProductNbr) {
for(int a = 0; a < accessoryRegistry.getAccessories().size(); a++) { // Searching thru the registry
Accessory accessory = accessoryRegistry.getAccessory(a); // Put the current accessory in an own variable...
if(accessory.getProductNbr() == (enteredProductNbr)) { // If the given product number is equal to an existing accessories product number
return accessory;
}
}
return null;
}
/* -----------------------------------------------------------------------*/
/* ------------------------------CREATE ACCESSORY-------------------------*/
/* -----------------------------------------------------------------------*/
public static void createAccessory(String inputName, int inputPrice, String inputInfo) {
productNbr = productNbr+1;
Accessory accessory = new Accessory(productNbr, inputName, inputPrice, inputInfo);
accessoryRegistry.addAccessory(accessory); // Adds the accessory to the registry!
}
/* -----------------------------------------------------------------------*/
/* --------------CREATE PRIVATE CUSTOMER --------------------------------*/
/* -----------------------------------------------------------------------*/
public void createPrivateCustomer(String personalNbr, String firstName, String lastName, String address,
String city, String areaCode, String telephoneNbr, String mail) {
customerNbr = customerNbr + 1;
PrivateCustomer newCustomer = new PrivateCustomer(customerNbr, personalNbr, firstName, lastName, address,
city, areaCode, telephoneNbr, mail, 1);
customerRegistry.addCustomer(newCustomer);
}
/* -----------------------------------------------------------------------*/
/* --------------CREATE COMPANY CUSTOMER ------------------------------------------*/
/* -----------------------------------------------------------------------*/
public void createCompanyCustomer(String orgNbr, String name, String adress, String city,
String areaCode, String phoneNbr, String mailAdress) {
customerNbr = customerNbr + 1;
CompanyCustomer newCustomer = new CompanyCustomer(customerNbr, orgNbr, name, adress, city, areaCode, phoneNbr, mailAdress, 1);
customerRegistry.addCustomer(newCustomer);
}
/* -----------------------------------------------------------------------*/
/* ---------------FIND CUSTOMER ------------------------------------------*/
/* -----------------------------------------------------------------------*/
/* public String findCustomer(String enteredCustomerNbr) {
for(int a = 0; a < customerRegistry.getCustomers().size(); a++) { // Check the entire registry...
Customer customer = customerRegistry.getCustomer(a); // Put the current customer in an own variable...
if(customer.getCustomerNbr().equals(enteredCustomerNbr)) { // If the given customer number is equal to an existing customers customer number...
String customerResult = "Förnamn: " + customer.getFirstName() + "\n\n" + // Retrieve the customers information, put it together nicely and...
"Efternamn: " + customer.getLastName() + "\n\n" +
"Kundnummer: " + customer.getCustomerNbr() + "\n\n" +
"Adress: " + customer.getAdress() + "\n\n" +
"Stad: " + customer.getCity() + "\n\n" +
"Postnummer: " + customer.getAreaCode() + "\n\n" +
"Telefonnummer: " + customer.getPhoneNbr() + "\n\n" +
"E-mail-adress: " + customer.getMailAdress() + "\n\n" +
"Rabattnivå: " + customer.getDiscountLevel();
return customerResult; // ... send it back!
}
}
return "Kunden kunde inte hittas!"; // If there was no matching customer number!
} */
/* -----------------------------------------------------------------------*/
/* ----------------------CREATE ORDER NOT COMPLETED-----------------------*/
/* -----------------------------------------------------------------------*/
public static void createOrder(Customer customer, ArrayList<Product> shoppingCart,
Employee employee) {
orderNbr = orderNbr + 1;
int totalPrice = 0;
Product product;
boolean isAppropriate = true; // MUST BE FIXED!!!!!
boolean wasSatisfied = true; // MUST BE FIXED!!!!
String latestUpdate = currentDate;
int discount = currentDiscount;
for(int a = 0; a < shoppingCart.size(); a++) {
product = shoppingCart.get(a);
totalPrice = totalPrice + product.getPrice();
}
Order order = new Order(orderNbr, customer,
shoppingCart, employee, totalPrice,
discount, isAppropriate, wasSatisfied, latestUpdate);
orderRegistry.addOrder(order);
customer.addPreviousOrder(order);
}
/* -----------------------------------------------------------------------*/
/* ------------------------CREATE CUSTOMERS-----------------------------*/
/* -----------------------------------------------------------------------*/
public static CustomerRegistry createCustomers (CustomerRegistry customerRegistry) {
CompanyCustomer companyCustomer1 = new CompanyCustomer(1, "123", "Itab AB", "Hejgatan 2", "Linköping", "45357", "070734958", "[email protected]", 2); // Creates the customers...
CompanyCustomer companyCustomer2 = new CompanyCustomer(2, "354", "Kaffesump AB", "Högersvängen 7", "Lund", "22200", "0702332434", "[email protected]", 3);
CompanyCustomer companyCustomer3 = new CompanyCustomer(3, "623","Vågade Pojkar INC", "Genvägen 2B", "Göteborg", "45692", "0703748294", "[email protected]", 1);
CompanyCustomer companyCustomer4 = new CompanyCustomer(4, "477","Skånepartiet", "Slottsgatan 6", "Linköpig", "58000", "07347283939", "[email protected]", 5);
CompanyCustomer companyCustomer5 = new CompanyCustomer(5, "333","Odd & Nicklas INC", "Gårdsvägen 9A", "Lund", "23422", "0704221122", "[email protected]", 10);
PrivateCustomer privateCustomer6 = new PrivateCustomer(6, "8906453434", "Joachim","Karlsson", "Nissevägen 2A", "Linköping", "58343", "0704532326", "[email protected]", 1);
PrivateCustomer privateCustomer7 = new PrivateCustomer(7, "8805032323", "Alexander","Steen", "Rakavägen 4", "Linköping", "58343", "0704532326", "[email protected]", 2);
PrivateCustomer privateCustomer8 = new PrivateCustomer(8, "9205053434", "Peter","Forsberg", "Rakavägen 4", "Linköping", "58343", "0704532326", "[email protected]", 3);
PrivateCustomer privateCustomer9 = new PrivateCustomer(9, "9111233114", "Mats","Sundin", "Rakavägen 4", "Linköping", "58343", "0704532326", "[email protected]", 2);
PrivateCustomer privateCustomer10 = new PrivateCustomer(10, "7201014455", "Robert","Svensson", "Rakavägen 4", "Linköping", "58343", "0704532326", "[email protected]", 1);
customerRegistry.addCustomer(companyCustomer1); // Adds the customers to the registry...
customerRegistry.addCustomer(companyCustomer2);
customerRegistry.addCustomer(companyCustomer3);
customerRegistry.addCustomer(companyCustomer4);
customerRegistry.addCustomer(companyCustomer5);
customerRegistry.addCustomer(privateCustomer6);
customerRegistry.addCustomer(privateCustomer7);
customerRegistry.addCustomer(privateCustomer8);
customerRegistry.addCustomer(privateCustomer9);
customerRegistry.addCustomer(privateCustomer10);
return customerRegistry;
}
/* -----------------------------------------------------------------------*/
/* ---------------------------CREATE WAREHOUSES--------------------------------*/
/* -----------------------------------------------------------------------*/
public static WarehouseRegistry createWarehouses (WarehouseRegistry warehouseRegistry) {
Warehouse warehouse1 = new Warehouse("Storgatan 1", "Lund", "22363"); // Creates warehouses!
Warehouse warehouse2 = new Warehouse("Kråkvägen 2", "Linköping", "58437");
Warehouse warehouse3 = new Warehouse("Plogvägen 4", "Göteborg", "40225");
warehouseRegistry.addWarehouse(warehouse1);
warehouseRegistry.addWarehouse(warehouse2);
warehouseRegistry.addWarehouse(warehouse3);
return warehouseRegistry;
}
/* -----------------------------------------------------------------------*/
/* ---------------------------CREATE VEHICLES----------------------------*/
/* -----------------------------------------------------------------------*/
public static VehicleRegistry createVehicles (VehicleRegistry vehicleRegistry, WarehouseRegistry warehouseRegistry) {
Vehicle vehicle1 = new Vehicle("ABC123", "Volvo V70", "Personbil", "B", 800,"5-sittsig och plats för 5 väskor i bagageluckan", true, "2014-13-12", warehouseRegistry.getWarehouse(2)); // Creates the vehicles...
Vehicle vehicle2 = new Vehicle("GBY234", "Volvo V40", "Sportbil", "B", 700,"5-sittsig och plats för 3 väskor i bagageluckan", true, "2014-13-12", warehouseRegistry.getWarehouse(2));
Vehicle vehicle3 = new Vehicle("JER456", "Volvo S80", "Personbil", "B", 700,"5-sittsig och plats för 2 väskor i bagageluckan", true, "2014-13-12", warehouseRegistry.getWarehouse(0));
Vehicle vehicle4 = new Vehicle("SJF856", "Volvo V60", "Minibuss", "B", 700,"5-sittsig och plats för 4 väskor i bagageluckan", true, "2014-13-12", warehouseRegistry.getWarehouse(1));
Vehicle vehicle5 = new Vehicle("HFY345", "Volvo S40", "Personbil", "B", 600,"5-sittsig och plats för 3 väskor i bagageluckan", true, "2014-13-12", warehouseRegistry.getWarehouse(2));
Vehicle vehicle6 = new Vehicle("GJH876", "Volvo C30", "Personbil", "B", 600,"4-sittsig och plats för 2 väskor i bagageluckan", true, "2014-13-12", warehouseRegistry.getWarehouse(0));
Vehicle vehicle7 = new Vehicle("SHD786", "Volvo V50", "Lastbil", "B", 600,"5-sittsig och plats för 4 väskor i bagageluckan", true, "2014-13-12", warehouseRegistry.getWarehouse(0));
Vehicle vehicle8 = new Vehicle("DCG349", "Volvo XC90", "Lastbil", "B", 900,"7-sittsig och plats för 5 väskor i bagageluckan", true, "2014-13-12", warehouseRegistry.getWarehouse(1));
Vehicle vehicle9 = new Vehicle("DVT234", "Volvo XC60", "Personbil", "B", 800,"5-sittsig och plats för 5 väskor i bagageluckan", true, "2014-13-12", warehouseRegistry.getWarehouse(1));
Vehicle vehicle10 = new Vehicle("LOI765", "Volvo V70XC", "Sportbil", "B", 300,"5-sittsig och plats för 5 väskor i bagageluckan", true, "2014-13-12", warehouseRegistry.getWarehouse(2));
vehicleRegistry.addVehicle(vehicle1); // Adds the created vehicle to the registry!
vehicleRegistry.addVehicle(vehicle2);
vehicleRegistry.addVehicle(vehicle3);
vehicleRegistry.addVehicle(vehicle4);
vehicleRegistry.addVehicle(vehicle5);
vehicleRegistry.addVehicle(vehicle6);
vehicleRegistry.addVehicle(vehicle7);
vehicleRegistry.addVehicle(vehicle8);
vehicleRegistry.addVehicle(vehicle9);
vehicleRegistry.addVehicle(vehicle10);
return vehicleRegistry;
}
/* -----------------------------------------------------------------------*/
/* ------------------------------CREATE ACCESSORY----------------------*/
/* -----------------------------------------------------------------------*/
public static AccessoryRegistry createAccessories (AccessoryRegistry accessoryRegistry) {
Accessory accessory1 = new Accessory(1, "Vajer", 100, "Bra att ha!"); // Creates the accessories...
Accessory accessory2 = new Accessory(2, "Prasselpresenning", 200, "3x4 meter och Passar till stort släp");
Accessory accessory3 = new Accessory(3, "Prasselpresenning", 150, "1,5x2 meter, Passar till litet släp!");
Accessory accessory4 = new Accessory(4, "Spännband", 150, "4 meter");
Accessory accessory5 = new Accessory(5, "Spännband", 100, "2 meter");
Accessory accessory6 = new Accessory(6, "Stödhjul", 200, "Passar till alla släp");
Accessory accessory7 = new Accessory(7, "Stänkskärm", 300, "Passar alla personbilar och säljes 4 st");
Accessory accessory8 = new Accessory(8, "Oljefilter", 200, "Till volvomotorer");
Accessory accessory9 = new Accessory(9, "Kopplingkabel", 100, "Passar alla fordon");
Accessory accessory10 = new Accessory(10, "Luftfilter motor", 150, "Passar alla Volvo");
accessoryRegistry.addAccessory(accessory1); // Adds the accessory to the registry!
accessoryRegistry.addAccessory(accessory2);
accessoryRegistry.addAccessory(accessory3);
accessoryRegistry.addAccessory(accessory4);
accessoryRegistry.addAccessory(accessory5);
accessoryRegistry.addAccessory(accessory6);
accessoryRegistry.addAccessory(accessory7);
accessoryRegistry.addAccessory(accessory8);
accessoryRegistry.addAccessory(accessory9);
accessoryRegistry.addAccessory(accessory10);
return accessoryRegistry;
}
/* -----------------------------------------------------------------------*/
/* --------------------CREATE EMPLOYEES---------------------------------*/
/* -----------------------------------------------------------------------*/
public static EmployeeRegistry createEmployees (EmployeeRegistry employeeRegistry) {
PermanentEmployee employee1 = new PermanentEmployee(1, "8904304455", "Jonas", "Mellström", "0703435223", "[email protected]", 20000); // Creates the employees...
PermanentEmployee employee2 = new PermanentEmployee(2, "8804304455", "Malin", "Mellström", "0703435221", "[email protected]", 20000);
PermanentEmployee employee3 = new PermanentEmployee(3, "8604304455", "Swante", "Mellström", "0703435222", "[email protected]", 20000);
employeeRegistry.addEmployee(employee1); // Adds the employee to the registry!
employeeRegistry.addEmployee(employee2);
employeeRegistry.addEmployee(employee3);
return employeeRegistry;
}
/* -----------------------------------------------------------------------*/
/* --------------------CREATE ORDERS--------------------------------------*/
/* -----------------------------------------------------------------------*/
public static OrderRegistry createOrders (OrderRegistry orderRegistry) {
ArrayList<Product> productsTemplate = new ArrayList<Product>();
productsTemplate.add(accessoryRegistry.getAccessory(0));
Order order1 = new Order(orderNbr = orderNbr + 1, customerRegistry.getCustomer(3), productsTemplate, employeeRegistry.getEmployee(1), 1100, 0, true, true, currentDate);
Order order2 = new Order(orderNbr = orderNbr + 1, customerRegistry.getCustomer(1), productsTemplate, employeeRegistry.getEmployee(2), 5000, 0, true, true, currentDate);
Order order3 = new Order(orderNbr = orderNbr + 1, customerRegistry.getCustomer(9), productsTemplate, employeeRegistry.getEmployee(0), 300, 0, true, true, currentDate);
Order order4 = new Order(orderNbr = orderNbr + 1, customerRegistry.getCustomer(3), productsTemplate, employeeRegistry.getEmployee(1), 1100, 0, true, true, currentDate);
Order order5 = new Order(orderNbr = orderNbr + 1, customerRegistry.getCustomer(3), productsTemplate, employeeRegistry.getEmployee(2), 21100, 0, true, true, currentDate);
orderRegistry.addOrder(order1);
orderRegistry.addOrder(order2);
orderRegistry.addOrder(order3);
orderRegistry.addOrder(order4);
orderRegistry.addOrder(order5);
return orderRegistry;
}
/* -----------------------------------------------------------------------*/
/* -----------------------------------------------------------------------*/
/* -----------------------------------------------------------------------*/
}
| Update Controller.java | Source-files/Controller.java | Update Controller.java | <ide><path>ource-files/Controller.java
<ide>
<ide> static int orderNbr = 0;
<ide> static int customerNbr = 0;
<add> static int productNbr = 0;
<add>
<ide>
<ide> static int currentDiscount = 0; // Current over all discount level, could be seasonal...
<ide> |
|
Java | apache-2.0 | 5bda7c0982613c4bfff7b893d5daf8b917feef99 | 0 | sul-dlss/openwayback,MohammedElsayyed/openwayback,zubairkhatri/openwayback,nlnwa/openwayback,zubairkhatri/openwayback,nlnwa/openwayback,SpiralsSeminaire/openwayback,MohammedElsayyed/openwayback,emijrp/openwayback,chasehd/openwayback,nlnwa/openwayback,bitzl/openwayback,zubairkhatri/openwayback,ukwa/openwayback,efundamentals/openwayback,JesseWeinstein/openwayback,JesseWeinstein/openwayback,SpiralsSeminaire/openwayback,ukwa/openwayback,iipc/openwayback,nlnwa/openwayback,sul-dlss/openwayback,iipc/openwayback,emijrp/openwayback,kris-sigur/openwayback,nlnwa/openwayback,nla/openwayback,kris-sigur/openwayback,iipc/openwayback,sul-dlss/openwayback,JesseWeinstein/openwayback,efundamentals/openwayback,JesseWeinstein/openwayback,bitzl/openwayback,kris-sigur/openwayback,SpiralsSeminaire/openwayback,nla/openwayback,JesseWeinstein/openwayback,SpiralsSeminaire/openwayback,MohammedElsayyed/openwayback,bitzl/openwayback,bitzl/openwayback,bitzl/openwayback,SpiralsSeminaire/openwayback,chasehd/openwayback,emijrp/openwayback,efundamentals/openwayback,efundamentals/openwayback,emijrp/openwayback,nla/openwayback,emijrp/openwayback,efundamentals/openwayback,nla/openwayback,chasehd/openwayback,zubairkhatri/openwayback,nla/openwayback,kris-sigur/openwayback,kris-sigur/openwayback,ukwa/openwayback | /*
* This file is part of the Wayback archival access software
* (http://archive-access.sourceforge.net/projects/wayback/).
*
* Licensed to the Internet Archive (IA) by one or more individual
* contributors.
*
* The IA 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.archive.wayback.resourcestore.resourcefile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.URL;
import org.archive.io.ArchiveReader;
import org.archive.io.ArchiveRecord;
import org.archive.io.arc.ARCReader;
import org.archive.io.arc.ARCReaderFactory;
import org.archive.io.arc.ARCRecord;
import org.archive.io.warc.WARCReader;
import org.archive.io.warc.WARCReaderFactory;
import org.archive.io.warc.WARCRecord;
import org.archive.wayback.core.Resource;
import org.archive.wayback.exception.ResourceNotAvailableException;
import org.archive.wayback.webapp.PerformanceLogger;
/**
* Static factory class for constructing ARC/WARC Resources from
* File/URL + offset.
*
* @author brad
* @version $Date$, $Revision$
*/
public class ResourceFactory {
public static Resource getResource(String urlOrPath, long offset)
throws IOException, ResourceNotAvailableException {
if(urlOrPath.startsWith("http://")) {
return getResource(new URL(urlOrPath), offset);
} else {
// assume local path:
return getResource(new File(urlOrPath), offset);
}
}
public static Resource getResource(File file, long offset)
throws IOException, ResourceNotAvailableException {
Resource r = null;
String name = file.getName();
if (name.endsWith(ArcWarcFilenameFilter.OPEN_SUFFIX)) {
name = name.substring(0, name.length()
- ArcWarcFilenameFilter.OPEN_SUFFIX.length());
}
RandomAccessFile raf = new RandomAccessFile(file, "r");
raf.seek(offset);
InputStream is = new FileInputStream(raf.getFD());
String fPath = file.getAbsolutePath();
if (isArc(name)) {
ArchiveReader reader = ARCReaderFactory.get(fPath, is, false);
r = ARCArchiveRecordToResource(reader.get(), reader);
} else if (isWarc(name)) {
ArchiveReader reader = WARCReaderFactory.get(fPath, is, false);
r = WARCArchiveRecordToResource(reader.get(), reader);
} else {
throw new ResourceNotAvailableException("Unknown extension");
}
return r;
}
public static Resource getResource(URL url, long offset)
throws IOException, ResourceNotAvailableException {
Resource r = null;
// TODO: allow configuration of timeouts -- now using defaults..
long start = System.currentTimeMillis();
TimeoutArchiveReaderFactory tarf = new TimeoutArchiveReaderFactory();
ArchiveReader reader = tarf.getArchiveReader(url,offset);
if(reader instanceof ARCReader) {
ARCReader areader = (ARCReader) reader;
r = ARCArchiveRecordToResource(areader.get(),areader);
} else if(reader instanceof WARCReader) {
WARCReader wreader = (WARCReader) reader;
r = WARCArchiveRecordToResource(wreader.get(),wreader);
} else {
throw new ResourceNotAvailableException("Unknown ArchiveReader");
}
long elapsed = System.currentTimeMillis() - start;
PerformanceLogger.noteElapsed("Http11Resource", elapsed, url.toExternalForm());
return r;
}
private static boolean isArc(final String name) {
return (name.endsWith(ArcWarcFilenameFilter.ARC_SUFFIX)
|| name.endsWith(ArcWarcFilenameFilter.ARC_GZ_SUFFIX));
}
private static boolean isWarc(final String name) {
return (name.endsWith(ArcWarcFilenameFilter.WARC_SUFFIX)
|| name.endsWith(ArcWarcFilenameFilter.WARC_GZ_SUFFIX));
}
public static Resource ARCArchiveRecordToResource(ArchiveRecord rec,
ArchiveReader reader) throws ResourceNotAvailableException, IOException {
if (!(rec instanceof ARCRecord)) {
throw new ResourceNotAvailableException("Bad ARCRecord format");
}
ArcResource ar = new ArcResource((ARCRecord) rec, reader);
ar.parseHeaders();
return ar;
}
public static Resource WARCArchiveRecordToResource(ArchiveRecord rec,
ArchiveReader reader) throws ResourceNotAvailableException, IOException {
if (!(rec instanceof WARCRecord)) {
throw new ResourceNotAvailableException("Bad WARCRecord format");
}
WarcResource wr = new WarcResource((WARCRecord) rec, reader);
wr.parseHeaders();
return wr;
}
}
| wayback-core/src/main/java/org/archive/wayback/resourcestore/resourcefile/ResourceFactory.java | /*
* This file is part of the Wayback archival access software
* (http://archive-access.sourceforge.net/projects/wayback/).
*
* Licensed to the Internet Archive (IA) by one or more individual
* contributors.
*
* The IA 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.archive.wayback.resourcestore.resourcefile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.URL;
import org.archive.io.ArchiveReader;
import org.archive.io.ArchiveRecord;
import org.archive.io.arc.ARCReader;
import org.archive.io.arc.ARCReaderFactory;
import org.archive.io.arc.ARCRecord;
import org.archive.io.warc.WARCReader;
import org.archive.io.warc.WARCReaderFactory;
import org.archive.io.warc.WARCRecord;
import org.archive.wayback.core.Resource;
import org.archive.wayback.exception.ResourceNotAvailableException;
/**
* Static factory class for constructing ARC/WARC Resources from
* File/URL + offset.
*
* @author brad
* @version $Date$, $Revision$
*/
public class ResourceFactory {
public static Resource getResource(String urlOrPath, long offset)
throws IOException, ResourceNotAvailableException {
if(urlOrPath.startsWith("http://")) {
return getResource(new URL(urlOrPath), offset);
} else {
// assume local path:
return getResource(new File(urlOrPath), offset);
}
}
public static Resource getResource(File file, long offset)
throws IOException, ResourceNotAvailableException {
Resource r = null;
String name = file.getName();
if (name.endsWith(ArcWarcFilenameFilter.OPEN_SUFFIX)) {
name = name.substring(0, name.length()
- ArcWarcFilenameFilter.OPEN_SUFFIX.length());
}
RandomAccessFile raf = new RandomAccessFile(file, "r");
raf.seek(offset);
InputStream is = new FileInputStream(raf.getFD());
String fPath = file.getAbsolutePath();
if (isArc(name)) {
ArchiveReader reader = ARCReaderFactory.get(fPath, is, false);
r = ARCArchiveRecordToResource(reader.get(), reader);
} else if (isWarc(name)) {
ArchiveReader reader = WARCReaderFactory.get(fPath, is, false);
r = WARCArchiveRecordToResource(reader.get(), reader);
} else {
throw new ResourceNotAvailableException("Unknown extension");
}
return r;
}
public static Resource getResource(URL url, long offset)
throws IOException, ResourceNotAvailableException {
Resource r = null;
// TODO: allow configuration of timeouts -- now using defaults..
TimeoutArchiveReaderFactory tarf = new TimeoutArchiveReaderFactory();
ArchiveReader reader = tarf.getArchiveReader(url,offset);
if(reader instanceof ARCReader) {
ARCReader areader = (ARCReader) reader;
r = ARCArchiveRecordToResource(areader.get(),areader);
} else if(reader instanceof WARCReader) {
WARCReader wreader = (WARCReader) reader;
r = WARCArchiveRecordToResource(wreader.get(),wreader);
} else {
throw new ResourceNotAvailableException("Unknown ArchiveReader");
}
return r;
}
private static boolean isArc(final String name) {
return (name.endsWith(ArcWarcFilenameFilter.ARC_SUFFIX)
|| name.endsWith(ArcWarcFilenameFilter.ARC_GZ_SUFFIX));
}
private static boolean isWarc(final String name) {
return (name.endsWith(ArcWarcFilenameFilter.WARC_SUFFIX)
|| name.endsWith(ArcWarcFilenameFilter.WARC_GZ_SUFFIX));
}
public static Resource ARCArchiveRecordToResource(ArchiveRecord rec,
ArchiveReader reader) throws ResourceNotAvailableException, IOException {
if (!(rec instanceof ARCRecord)) {
throw new ResourceNotAvailableException("Bad ARCRecord format");
}
ArcResource ar = new ArcResource((ARCRecord) rec, reader);
ar.parseHeaders();
return ar;
}
public static Resource WARCArchiveRecordToResource(ArchiveRecord rec,
ArchiveReader reader) throws ResourceNotAvailableException, IOException {
if (!(rec instanceof WARCRecord)) {
throw new ResourceNotAvailableException("Bad WARCRecord format");
}
WarcResource wr = new WarcResource((WARCRecord) rec, reader);
wr.parseHeaders();
return wr;
}
}
| FEATURE: added performance logging of HTTP 1.1 resource requests
git-svn-id: ca6d9ebf75caaf710f0e3a4ee74a890c456d4c90@3467 69e27eb3-6e27-0410-b9c6-fffd7e226fab
| wayback-core/src/main/java/org/archive/wayback/resourcestore/resourcefile/ResourceFactory.java | FEATURE: added performance logging of HTTP 1.1 resource requests | <ide><path>ayback-core/src/main/java/org/archive/wayback/resourcestore/resourcefile/ResourceFactory.java
<ide> import org.archive.io.warc.WARCRecord;
<ide> import org.archive.wayback.core.Resource;
<ide> import org.archive.wayback.exception.ResourceNotAvailableException;
<add>import org.archive.wayback.webapp.PerformanceLogger;
<ide>
<ide> /**
<ide> * Static factory class for constructing ARC/WARC Resources from
<ide>
<ide> Resource r = null;
<ide> // TODO: allow configuration of timeouts -- now using defaults..
<add> long start = System.currentTimeMillis();
<ide> TimeoutArchiveReaderFactory tarf = new TimeoutArchiveReaderFactory();
<ide> ArchiveReader reader = tarf.getArchiveReader(url,offset);
<ide> if(reader instanceof ARCReader) {
<ide> } else {
<ide> throw new ResourceNotAvailableException("Unknown ArchiveReader");
<ide> }
<add> long elapsed = System.currentTimeMillis() - start;
<add> PerformanceLogger.noteElapsed("Http11Resource", elapsed, url.toExternalForm());
<ide> return r;
<ide> }
<ide> |
|
JavaScript | bsd-3-clause | 542f72815657186aa50d75b8b86352c24d5766b3 | 0 | Becklyn/mojave,Becklyn/mojave,Becklyn/mojave | import "../polyfill/dom";
import {isElement} from "./utils";
/**
* Returns whether the given element is - in fact - an HTMLElement and
* it matches the optional selector
*
* @param {Node|HTMLElement} element
* @param {?string} selector
* @return {boolean}
*/
function elementMatches (element, selector)
{
return isElement(element) && (null === selector || element.matches(selector));
}
/**
*
* @param {HTMLElement} element
* @param {?string} selector
* @param {string} method
* @param {boolean} onlyFirst
* @return {HTMLElement[]|HTMLElement}
*/
function fetchSiblings (element, selector, method, onlyFirst)
{
let sibling = element[method];
const list = [];
while (sibling)
{
if (elementMatches(sibling, selector))
{
if (onlyFirst)
{
return sibling;
}
list.push(sibling);
}
sibling = sibling[method];
}
return onlyFirst ? null : list;
}
/**
* Finds all DOM elements matching the selector
*
* @param {string} selector
* @param {Document|HTMLElement} context
* @return {HTMLElement[]}
*/
export function find (selector, context = document)
{
return Array.prototype.slice.call(context.querySelectorAll(selector));
}
/**
* Finds a single DOM node matching the selector
*
* @param {string} selector
* @param {Document|HTMLElement} context
* @return {?HTMLElement}
*/
export function findOne (selector, context = document)
{
return context.querySelector(selector);
}
/**
* Filters a list of DOM elements that match the given selector
*
* @param {HTMLElement[]} list
* @param {string} selector
* @return {HTMLElement[]}
*/
export function filter (list, selector)
{
return list.filter(
(e) => e.matches(selector)
);
}
/**
* Filters a list of DOM elements that DO NOT match the given selector
*
* @param {HTMLElement[]} list
* @param {string} selector
* @return {HTMLElement[]}
*/
export function not (list, selector)
{
return list.filter(
(e) => !e.matches(selector)
);
}
/**
* Returns all children
*
* @param {HTMLElement} parent
* @param {?string} selector
* @return {HTMLElement[]}
*/
export function children (parent, selector = null)
{
const list = [];
let child = parent.firstChild;
while (child)
{
if (elementMatches(child, selector))
{
list.push(child);
}
child = child.nextSibling;
}
return list;
}
/**
* Returns the nearest previous sibling matching
* (optionally matching the given selector)
*
* @param {HTMLElement} element
* @param {?string} selector
* @return {?HTMLElement}
*/
export function prev (element, selector = null)
{
return fetchSiblings(element, selector, "previousSibling", true);
}
/**
* Returns the nearest following sibling
* (optionally matching the given selector)
*
* @param {HTMLElement} element
* @param {?string} selector
* @return {?HTMLElement}
*/
export function next (element, selector = null)
{
return fetchSiblings(element, selector, "nextSibling", true);
}
/**
* Returns all previous siblings
* (optionally matching the given selector)
*
* The nearest sibling is the first element in the list.
*
* @param {HTMLElement} element
* @param {?string} selector
* @return {HTMLElement[]}
*/
export function prevAll (element, selector = null)
{
return fetchSiblings(element, selector, "previousSibling", false);
}
/**
* Returns all following siblings
* (optionally matching the given selector)
*
* The nearest sibling is the first element in the list.
*
* @param {HTMLElement} element
* @param {?string} selector
* @return {HTMLElement[]}
*/
export function nextAll (element, selector = null)
{
return fetchSiblings(element, selector, "nextSibling", false);
}
/**
* Returns all siblings
* (optionally matching the given selector)
*
* @param {HTMLElement} element
* @param {?string} selector
* @return {HTMLElement[]}
*/
export function siblings (element, selector = null)
{
let sibling = element.parentNode.firstChild;
const list = [];
while (sibling)
{
if (sibling !== element && elementMatches(sibling, selector))
{
list.push(element);
}
sibling = sibling.nextSibling;
}
return list;
}
/**
* Returns the closest parent that matches the selector
*
* @param {HTMLElement} element
* @param {string} selector
* @return {?HTMLElement}
*/
export function closest (element, selector)
{
let parent = element.parentNode;
/** @type {HTMLElement} node */
while (parent)
{
if (parent.matches(selector))
{
return parent;
}
parent = parent.parentNode;
}
return null;
}
| dom/traverse.js | import "../polyfill/dom";
import {isElement} from "./utils";
/**
* Returns whether the given element is - in fact - an HTMLElement and
* it matches the optional selector
*
* @param {Node|HTMLElement} element
* @param {?string} selector
* @return {boolean}
*/
function elementMatches (element, selector)
{
return isElement(element) && (null === selector || element.matches(selector));
}
/**
*
* @param {HTMLElement} element
* @param {?string} selector
* @param {string} method
* @param {boolean} onlyFirst
* @return {HTMLElement[]|HTMLElement}
*/
function fetchSiblings (element, selector, method, onlyFirst)
{
let sibling = element[method];
const list = [];
while (sibling)
{
if (elementMatches(sibling, selector))
{
if (onlyFirst)
{
return sibling;
}
list.push(sibling);
}
sibling = element[method];
}
return onlyFirst ? null : list;
}
/**
* Finds all DOM elements matching the selector
*
* @param {string} selector
* @param {Document|HTMLElement} context
* @return {HTMLElement[]}
*/
export function find (selector, context = document)
{
return Array.prototype.slice.call(context.querySelectorAll(selector));
}
/**
* Finds a single DOM node matching the selector
*
* @param {string} selector
* @param {Document|HTMLElement} context
* @return {?HTMLElement}
*/
export function findOne (selector, context = document)
{
return context.querySelector(selector);
}
/**
* Filters a list of DOM elements that match the given selector
*
* @param {HTMLElement[]} list
* @param {string} selector
* @return {HTMLElement[]}
*/
export function filter (list, selector)
{
return list.filter(
(e) => e.matches(selector)
);
}
/**
* Filters a list of DOM elements that DO NOT match the given selector
*
* @param {HTMLElement[]} list
* @param {string} selector
* @return {HTMLElement[]}
*/
export function not (list, selector)
{
return list.filter(
(e) => !e.matches(selector)
);
}
/**
* Returns all children
*
* @param {HTMLElement} parent
* @param {?string} selector
* @return {HTMLElement[]}
*/
export function children (parent, selector = null)
{
const list = [];
let child = parent.firstChild;
while (child)
{
if (elementMatches(child, selector))
{
list.push(child);
}
child = child.nextSibling;
}
return list;
}
/**
* Returns the nearest previous sibling matching
* (optionally matching the given selector)
*
* @param {HTMLElement} element
* @param {?string} selector
* @return {?HTMLElement}
*/
export function prev (element, selector = null)
{
return fetchSiblings(element, selector, "previousSibling", true);
}
/**
* Returns the nearest following sibling
* (optionally matching the given selector)
*
* @param {HTMLElement} element
* @param {?string} selector
* @return {?HTMLElement}
*/
export function next (element, selector = null)
{
return fetchSiblings(element, selector, "nextSibling", true);
}
/**
* Returns all previous siblings
* (optionally matching the given selector)
*
* The nearest sibling is the first element in the list.
*
* @param {HTMLElement} element
* @param {?string} selector
* @return {HTMLElement[]}
*/
export function prevAll (element, selector = null)
{
return fetchSiblings(element, selector, "previousSibling", false);
}
/**
* Returns all following siblings
* (optionally matching the given selector)
*
* The nearest sibling is the first element in the list.
*
* @param {HTMLElement} element
* @param {?string} selector
* @return {HTMLElement[]}
*/
export function nextAll (element, selector = null)
{
return fetchSiblings(element, selector, "nextSibling", false);
}
/**
* Returns all siblings
* (optionally matching the given selector)
*
* @param {HTMLElement} element
* @param {?string} selector
* @return {HTMLElement[]}
*/
export function siblings (element, selector = null)
{
let sibling = element.parentNode.firstChild;
const list = [];
while (sibling)
{
if (sibling !== element && elementMatches(sibling, selector))
{
list.push(element);
}
sibling = element.nextSibling;
}
return list;
}
/**
* Returns the closest parent that matches the selector
*
* @param {HTMLElement} element
* @param {string} selector
* @return {?HTMLElement}
*/
export function closest (element, selector)
{
let parent = element.parentNode;
/** @type {HTMLElement} node */
while (parent)
{
if (parent.matches(selector))
{
return parent;
}
parent = parent.parentNode;
}
return null;
}
| Use correct variable in traverse methods
| dom/traverse.js | Use correct variable in traverse methods | <ide><path>om/traverse.js
<ide> list.push(sibling);
<ide> }
<ide>
<del> sibling = element[method];
<add> sibling = sibling[method];
<ide> }
<ide>
<ide> return onlyFirst ? null : list;
<ide> list.push(element);
<ide> }
<ide>
<del> sibling = element.nextSibling;
<add> sibling = sibling.nextSibling;
<ide> }
<ide>
<ide> return list; |
|
Java | mpl-2.0 | b2956bd8da95249b61aefd2a4508585115747708 | 0 | Skelril/Skree | /*
* 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 com.skelril.skree.content.registry.item.zone;
import com.skelril.nitro.registry.Craftable;
import com.skelril.nitro.registry.item.CustomItem;
import com.skelril.nitro.selector.EventAwareContent;
import com.skelril.skree.SkreePlugin;
import com.skelril.skree.content.registry.item.CustomItemTypes;
import com.skelril.skree.content.world.instance.InstanceWorldWrapper;
import com.skelril.skree.content.world.main.MainWorldWrapper;
import com.skelril.skree.service.RespawnService;
import com.skelril.skree.service.WorldService;
import com.skelril.skree.service.ZoneService;
import com.skelril.skree.service.internal.world.WorldEffectWrapper;
import com.skelril.skree.service.internal.zone.ZoneStatus;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.type.HandTypes;
import org.spongepowered.api.entity.EntityTypes;
import org.spongepowered.api.entity.Item;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.weather.Lightning;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.block.InteractBlockEvent;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.entity.spawn.SpawnCause;
import org.spongepowered.api.event.cause.entity.spawn.SpawnTypes;
import org.spongepowered.api.event.entity.InteractEntityEvent;
import org.spongepowered.api.event.filter.Getter;
import org.spongepowered.api.event.filter.cause.First;
import org.spongepowered.api.event.item.inventory.DropItemEvent;
import org.spongepowered.api.event.network.ClientConnectionEvent;
import org.spongepowered.api.scheduler.Task;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.util.Tristate;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static com.skelril.nitro.item.ItemStackFactory.newItemStack;
import static com.skelril.nitro.transformer.ForgeTransformer.tf;
import static com.skelril.skree.content.registry.item.zone.ZoneItemUtil.*;
public class ZoneMasterOrb extends CustomItem implements EventAwareContent, Craftable {
@Override
public String __getId() {
return "zone_master_orb";
}
@Override
public List<String> __getMeshDefinitions() {
List<String> baseList = super.__getMeshDefinitions();
baseList.add("zone_master_orb_active");
return baseList;
}
@Override
public int __getMaxStackSize() {
return 1;
}
@Override
public CreativeTabs __getCreativeTab() {
return CreativeTabs.MATERIALS;
}
@Override
public void registerRecipes() {
GameRegistry.addRecipe(
new ItemStack(this, 3),
"BBB",
"BAB",
"BBB",
'A', newItemStack("skree:fairy_dust"),
'B', new ItemStack(Blocks.GLASS)
);
GameRegistry.addRecipe(new ZoneMasterOrbRecipie(
"Shnuggles Prime",
new ItemStack(this),
new ItemStack(Items.ROTTEN_FLESH)
));
GameRegistry.addRecipe(new ZoneMasterOrbRecipie(
"Patient X",
new ItemStack(this),
new ItemStack(CustomItemTypes.PHANTOM_HYMN)
));
GameRegistry.addRecipe(new ZoneMasterOrbRecipie(
"Gold Rush",
new ItemStack(this),
new ItemStack(Items.GOLD_INGOT)
));
GameRegistry.addRecipe(new ZoneMasterOrbRecipie(
"Cursed Mine",
new ItemStack(this),
new ItemStack(Items.IRON_PICKAXE)
));
GameRegistry.addRecipe(new ZoneMasterOrbRecipie(
"Temple of Fate",
new ItemStack(this),
new ItemStack(Items.FEATHER)
));
GameRegistry.addRecipe(new ZoneMasterOrbRecipie(
"Catacombs",
new ItemStack(this),
new ItemStack(Items.BONE)
));
GameRegistry.addRecipe(new ZoneMasterOrbRecipie(
"Jungle Raid",
new ItemStack(this),
new ItemStack(Items.DYE, 1, 3)
));
GameRegistry.addRecipe(new ZoneMasterOrbRecipie(
"Sky Wars",
new ItemStack(this),
new ItemStack(Items.FEATHER),
(ItemStack) (Object) newItemStack("skree:fairy_dust")
));
GameRegistry.addRecipe(new ZoneMasterOrbRecipie(
"The Forge",
new ItemStack(this),
new ItemStack(Blocks.IRON_BLOCK)
));
}
@Override
@SideOnly(Side.CLIENT)
public void getSubItems(net.minecraft.item.Item itemIn, CreativeTabs tab, List subItems) {
subItems.add(new ItemStack(itemIn, 1, 0));
}
@Override
public String getHighlightTip(ItemStack item, String displayName) {
Optional<String> optContained = getZone(item);
return optContained.isPresent() ? optContained.get() + " " + displayName : displayName;
}
@Listener
public void onLogout(ClientConnectionEvent.Disconnect event) {
purgeZoneItems(event.getTargetEntity(), null);
}
@Listener
public void onBlockInteract(InteractBlockEvent.Secondary.MainHand event, @First Player player) {
Optional<org.spongepowered.api.item.inventory.ItemStack> optItemStack = player.getItemInHand(HandTypes.MAIN_HAND);
if (!optItemStack.isPresent()) {
return;
}
ItemStack itemStack = tf(optItemStack.get());
if (!isZoneMasterItem(itemStack)) {
return;
}
if (isAttuned(itemStack)) {
if (isInInstanceWorld(player)) {
player.sendMessage(Text.of(TextColors.RED, "You cannot start an instance from within an instance."));
event.setCancelled(true);
return;
}
Optional<ZoneService> optService = Sponge.getServiceManager().provide(ZoneService.class);
if (optService.isPresent()) {
Task.builder().execute(() -> {
ZoneService service = optService.get();
List<Player> group = new ArrayList<>();
group.add(player);
for (Player aPlayer : Sponge.getServer().getOnlinePlayers()) {
NonNullList<ItemStack> itemStacks = tf(aPlayer).inventory.mainInventory;
for (ItemStack aStack : itemStacks) {
if (!hasSameZoneID(itemStack, aStack)) {
continue;
}
if (isAttuned(aStack) && isZoneSlaveItem(aStack)) {
Optional<Player> optZoneOwner = getGroupOwner(aStack);
if (optZoneOwner.isPresent()) {
group.add(aPlayer);
break;
}
}
}
}
for (int i = group.size() - 1; i >= 0; --i) {
purgeZoneItems(group.get(i), itemStack);
// createLightningStrike(group.get(i)); SpongeCommon/420
saveLocation(group.get(i));
getMainWorldWrapper().getLobby().add(group.get(i));
}
service.requestZone(getZone(itemStack).get(), group,
() -> {
getMainWorldWrapper().getLobby().remove(group);
},
result -> {
if (result.isPresent()) {
result.get().stream().filter(entry -> entry.getValue() != ZoneStatus.ADDED).forEach(entry -> {
player.setLocation(getRespawnLocation(player));
player.sendMessage(Text.of(TextColors.RED, "You could not be added to the zone."));
});
}
}
);
}).delayTicks(1).submit(SkreePlugin.inst());
}
}
event.setUseBlockResult(Tristate.FALSE);
}
private void saveLocation(Player player) {
RespawnService respawnService = Sponge.getServiceManager().provideUnchecked(RespawnService.class);
respawnService.push(player, player.getLocation());
}
private Location<World> getRespawnLocation(Player player) {
RespawnService respawnService = Sponge.getServiceManager().provideUnchecked(RespawnService.class);
return respawnService.pop(player).orElse(respawnService.getDefault(player));
}
private void createLightningStrike(Player player) {
Location<World> loc = player.getLocation();
Lightning lightning = (Lightning) loc.getExtent().createEntity(EntityTypes.LIGHTNING, loc.getPosition());
lightning.setEffect(true);
loc.getExtent().spawnEntity(lightning, Cause.source(SpawnCause.builder().type(SpawnTypes.PLUGIN).build()).build());
}
private MainWorldWrapper getMainWorldWrapper() {
WorldService service = Sponge.getServiceManager().provideUnchecked(WorldService.class);
return service.getEffectWrapper(MainWorldWrapper.class).get();
}
private World getMainWorld() {
return getMainWorldWrapper().getWorlds().iterator().next();
}
private boolean isInInstanceWorld(Player player) {
Optional<WorldService> optWorldService = Sponge.getServiceManager().provide(WorldService.class);
if (optWorldService.isPresent()) {
WorldService worldService = optWorldService.get();
WorldEffectWrapper wrapper = worldService.getEffectWrapper(InstanceWorldWrapper.class).get();
if (wrapper.getWorlds().contains(player.getLocation().getExtent())) {
return true;
}
}
return false;
}
@Listener
public void onEntityInteract(InteractEntityEvent.Primary event, @First Player player, @Getter("getTargetEntity") Player targetPlayer) {
Optional<org.spongepowered.api.item.inventory.ItemStack> optItemStack = player.getItemInHand(HandTypes.MAIN_HAND);
if (!optItemStack.isPresent()) {
return;
}
org.spongepowered.api.item.inventory.ItemStack itemStack = optItemStack.get();
if (this.equals(itemStack.getItem()) && isAttuned(itemStack)) {
if (playerAlreadyHasInvite(itemStack, targetPlayer)) {
player.sendMessage(
Text.of(TextColors.RED, targetPlayer.getName() + " already has an invite.")
);
} else {
org.spongepowered.api.item.inventory.ItemStack newStack = createForMaster(itemStack, player);
tf(targetPlayer).inventory.addItemStackToInventory(tf(newStack));
targetPlayer.sendMessage(
Text.of(TextColors.GOLD, player.getName() + " has invited you to " + getZone(itemStack).get() + ".")
);
player.sendMessage(
Text.of(TextColors.GOLD, targetPlayer.getName() + " has been given invite.")
);
}
event.setCancelled(true);
}
}
@Listener
public void onDropItem(DropItemEvent.Dispense event) {
event.getEntities().stream().filter(entity -> entity instanceof Item).forEach(entity -> {
ItemStack stack = ((EntityItem) entity).getEntityItem();
if (isZoneMasterItem(stack) && isAttuned(stack)) {
rescindGroupInvite(stack);
ItemStack reset = new ItemStack(CustomItemTypes.ZONE_MASTER_ORB);
setMasterToZone(reset, getZone(stack).get());
entity.offer(Keys.REPRESENTED_ITEM, tf(reset).createSnapshot());
}
});
}
// Modified Native Item methods
@SuppressWarnings("unchecked")
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack stack, EntityPlayer playerIn, List tooltip, boolean advanced) {
Optional<String> optZoneName = getZone(tf(stack));
if (optZoneName.isPresent()) {
tooltip.add("Zone: " + optZoneName.get());
Optional<Integer> playerCount = getGroupSize(stack);
if (playerCount.isPresent()) {
Optional<Integer> maxPlayerCount = getMaxGroupSize(stack);
tooltip.add("Players: " + playerCount.get() + " / " + (!maxPlayerCount.isPresent() ? "Unlimited" : maxPlayerCount.get()));
}
}
}
}
| src/main/java/com/skelril/skree/content/registry/item/zone/ZoneMasterOrb.java | /*
* 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 com.skelril.skree.content.registry.item.zone;
import com.skelril.nitro.registry.Craftable;
import com.skelril.nitro.registry.item.CustomItem;
import com.skelril.nitro.selector.EventAwareContent;
import com.skelril.skree.SkreePlugin;
import com.skelril.skree.content.registry.item.CustomItemTypes;
import com.skelril.skree.content.world.instance.InstanceWorldWrapper;
import com.skelril.skree.content.world.main.MainWorldWrapper;
import com.skelril.skree.service.RespawnService;
import com.skelril.skree.service.WorldService;
import com.skelril.skree.service.ZoneService;
import com.skelril.skree.service.internal.world.WorldEffectWrapper;
import com.skelril.skree.service.internal.zone.ZoneStatus;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.type.HandTypes;
import org.spongepowered.api.entity.EntityTypes;
import org.spongepowered.api.entity.Item;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.weather.Lightning;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.block.InteractBlockEvent;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.entity.spawn.SpawnCause;
import org.spongepowered.api.event.cause.entity.spawn.SpawnTypes;
import org.spongepowered.api.event.entity.InteractEntityEvent;
import org.spongepowered.api.event.filter.Getter;
import org.spongepowered.api.event.filter.cause.First;
import org.spongepowered.api.event.item.inventory.DropItemEvent;
import org.spongepowered.api.event.network.ClientConnectionEvent;
import org.spongepowered.api.scheduler.Task;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.util.Tristate;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static com.skelril.nitro.item.ItemStackFactory.newItemStack;
import static com.skelril.nitro.transformer.ForgeTransformer.tf;
import static com.skelril.skree.content.registry.item.zone.ZoneItemUtil.*;
public class ZoneMasterOrb extends CustomItem implements EventAwareContent, Craftable {
@Override
public String __getId() {
return "zone_master_orb";
}
@Override
public List<String> __getMeshDefinitions() {
List<String> baseList = super.__getMeshDefinitions();
baseList.add("zone_master_orb_active");
return baseList;
}
@Override
public int __getMaxStackSize() {
return 1;
}
@Override
public CreativeTabs __getCreativeTab() {
return CreativeTabs.MATERIALS;
}
@Override
public void registerRecipes() {
GameRegistry.addRecipe(
new ItemStack(this, 3),
"BBB",
"BAB",
"BBB",
'A', newItemStack("skree:fairy_dust"),
'B', new ItemStack(Blocks.GLASS)
);
GameRegistry.addRecipe(new ZoneMasterOrbRecipie(
"Shnuggles Prime",
new ItemStack(this),
new ItemStack(Items.ROTTEN_FLESH)
));
GameRegistry.addRecipe(new ZoneMasterOrbRecipie(
"Patient X",
new ItemStack(this),
new ItemStack(CustomItemTypes.PHANTOM_HYMN)
));
GameRegistry.addRecipe(new ZoneMasterOrbRecipie(
"Gold Rush",
new ItemStack(this),
new ItemStack(Items.GOLD_INGOT)
));
GameRegistry.addRecipe(new ZoneMasterOrbRecipie(
"Cursed Mine",
new ItemStack(this),
new ItemStack(Items.IRON_PICKAXE)
));
GameRegistry.addRecipe(new ZoneMasterOrbRecipie(
"Temple of Fate",
new ItemStack(this),
new ItemStack(Items.FEATHER)
));
GameRegistry.addRecipe(new ZoneMasterOrbRecipie(
"Catacombs",
new ItemStack(this),
new ItemStack(Items.BONE)
));
GameRegistry.addRecipe(new ZoneMasterOrbRecipie(
"Jungle Raid",
new ItemStack(this),
new ItemStack(Items.DYE, 1, 3)
));
GameRegistry.addRecipe(new ZoneMasterOrbRecipie(
"Sky Wars",
new ItemStack(this),
new ItemStack(Items.FEATHER),
(ItemStack) (Object) newItemStack("skree:fairy_dust")
));
GameRegistry.addRecipe(new ZoneMasterOrbRecipie(
"The Forge",
new ItemStack(this),
new ItemStack(Blocks.IRON_BLOCK)
));
}
@Override
@SideOnly(Side.CLIENT)
public void getSubItems(net.minecraft.item.Item itemIn, CreativeTabs tab, List subItems) {
subItems.add(new ItemStack(itemIn, 1, 0));
}
@Override
public String getHighlightTip(ItemStack item, String displayName) {
Optional<String> optContained = getZone(item);
return optContained.isPresent() ? optContained.get() + " " + displayName : displayName;
}
@Listener
public void onLogout(ClientConnectionEvent.Disconnect event) {
purgeZoneItems(event.getTargetEntity(), null);
}
@Listener
public void onBlockInteract(InteractBlockEvent.Secondary.MainHand event, @First Player player) {
Optional<org.spongepowered.api.item.inventory.ItemStack> optItemStack = player.getItemInHand(HandTypes.MAIN_HAND);
if (!optItemStack.isPresent()) {
return;
}
ItemStack itemStack = tf(optItemStack.get());
if (!isZoneMasterItem(itemStack)) {
return;
}
if (isAttuned(itemStack)) {
if (isInInstanceWorld(player)) {
player.sendMessage(Text.of(TextColors.RED, "You cannot start an instance from within an instance."));
event.setCancelled(true);
return;
}
Optional<ZoneService> optService = Sponge.getServiceManager().provide(ZoneService.class);
if (optService.isPresent()) {
Task.builder().execute(() -> {
ZoneService service = optService.get();
List<Player> group = new ArrayList<>();
group.add(player);
for (Player aPlayer : Sponge.getServer().getOnlinePlayers()) {
NonNullList<ItemStack> itemStacks = tf(aPlayer).inventory.mainInventory;
for (ItemStack aStack : itemStacks) {
if (!hasSameZoneID(itemStack, aStack)) {
continue;
}
if (isAttuned(aStack) && isZoneSlaveItem(aStack)) {
Optional<Player> optZoneOwner = getGroupOwner(aStack);
if (optZoneOwner.isPresent()) {
group.add(aPlayer);
break;
}
}
}
}
for (int i = group.size() - 1; i >= 0; --i) {
purgeZoneItems(group.get(i), itemStack);
// createLightningStrike(group.get(i)); SpongeCommon/420
saveLocation(group.get(i));
getMainWorldWrapper().getLobby().add(group.get(i));
}
service.requestZone(getZone(itemStack).get(), group,
() -> {
getMainWorldWrapper().getLobby().remove(group);
},
result -> {
if (result.isPresent()) {
result.get().stream().filter(entry -> entry.getValue() != ZoneStatus.ADDED).forEach(entry -> {
player.setLocation(getRespawnLocation(player));
player.sendMessage(Text.of(TextColors.RED, "You could not be added to the zone."));
});
}
}
);
}).delayTicks(1).submit(SkreePlugin.inst());
}
}
event.setUseBlockResult(Tristate.FALSE);
}
private void saveLocation(Player player) {
RespawnService respawnService = Sponge.getServiceManager().provideUnchecked(RespawnService.class);
respawnService.push(player, player.getLocation());
}
private Location<World> getRespawnLocation(Player player) {
RespawnService respawnService = Sponge.getServiceManager().provideUnchecked(RespawnService.class);
return respawnService.pop(player).orElse(respawnService.getDefault(player));
}
private void createLightningStrike(Player player) {
Location<World> loc = player.getLocation();
Lightning lightning = (Lightning) loc.getExtent().createEntity(EntityTypes.LIGHTNING, loc.getPosition());
lightning.setEffect(true);
loc.getExtent().spawnEntity(lightning, Cause.source(SpawnCause.builder().type(SpawnTypes.PLUGIN).build()).build());
}
private MainWorldWrapper getMainWorldWrapper() {
WorldService service = Sponge.getServiceManager().provideUnchecked(WorldService.class);
return service.getEffectWrapper(MainWorldWrapper.class).get();
}
private World getMainWorld() {
return getMainWorldWrapper().getWorlds().iterator().next();
}
private boolean isInInstanceWorld(Player player) {
Optional<WorldService> optWorldService = Sponge.getServiceManager().provide(WorldService.class);
if (optWorldService.isPresent()) {
WorldService worldService = optWorldService.get();
WorldEffectWrapper wrapper = worldService.getEffectWrapper(InstanceWorldWrapper.class).get();
if (wrapper.getWorlds().contains(player.getLocation().getExtent())) {
return true;
}
}
return false;
}
@Listener
public void onEntityInteract(InteractEntityEvent.Primary event, @First Player player, @Getter("getTargetEntity") Player targetPlayer) {
Optional<org.spongepowered.api.item.inventory.ItemStack> optItemStack = player.getItemInHand(HandTypes.MAIN_HAND);
if (!optItemStack.isPresent()) {
return;
}
org.spongepowered.api.item.inventory.ItemStack itemStack = optItemStack.get();
if (this.equals(itemStack.getItem()) && isAttuned(itemStack)) {
if (playerAlreadyHasInvite(itemStack, targetPlayer)) {
player.sendMessage(
Text.of(TextColors.RED, targetPlayer.getName() + " already has an invite.")
);
} else {
org.spongepowered.api.item.inventory.ItemStack newStack = createForMaster(itemStack, player);
tf(targetPlayer).inventory.addItemStackToInventory(tf(newStack));
player.sendMessage(
Text.of(TextColors.GOLD, targetPlayer.getName() + " has been given invite.")
);
}
event.setCancelled(true);
}
}
@Listener
public void onDropItem(DropItemEvent.Dispense event) {
event.getEntities().stream().filter(entity -> entity instanceof Item).forEach(entity -> {
ItemStack stack = ((EntityItem) entity).getEntityItem();
if (isZoneMasterItem(stack) && isAttuned(stack)) {
rescindGroupInvite(stack);
ItemStack reset = new ItemStack(CustomItemTypes.ZONE_MASTER_ORB);
setMasterToZone(reset, getZone(stack).get());
entity.offer(Keys.REPRESENTED_ITEM, tf(reset).createSnapshot());
}
});
}
// Modified Native Item methods
@SuppressWarnings("unchecked")
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack stack, EntityPlayer playerIn, List tooltip, boolean advanced) {
Optional<String> optZoneName = getZone(tf(stack));
if (optZoneName.isPresent()) {
tooltip.add("Zone: " + optZoneName.get());
Optional<Integer> playerCount = getGroupSize(stack);
if (playerCount.isPresent()) {
Optional<Integer> maxPlayerCount = getMaxGroupSize(stack);
tooltip.add("Players: " + playerCount.get() + " / " + (!maxPlayerCount.isPresent() ? "Unlimited" : maxPlayerCount.get()));
}
}
}
}
| Added an notification that's received when you get a zone slave orb
| src/main/java/com/skelril/skree/content/registry/item/zone/ZoneMasterOrb.java | Added an notification that's received when you get a zone slave orb | <ide><path>rc/main/java/com/skelril/skree/content/registry/item/zone/ZoneMasterOrb.java
<ide> } else {
<ide> org.spongepowered.api.item.inventory.ItemStack newStack = createForMaster(itemStack, player);
<ide> tf(targetPlayer).inventory.addItemStackToInventory(tf(newStack));
<add> targetPlayer.sendMessage(
<add> Text.of(TextColors.GOLD, player.getName() + " has invited you to " + getZone(itemStack).get() + ".")
<add> );
<ide> player.sendMessage(
<ide> Text.of(TextColors.GOLD, targetPlayer.getName() + " has been given invite.")
<ide> ); |
|
JavaScript | apache-2.0 | f544bdba071bd60a1a6477dd2708ad7b374e61e2 | 0 | Orodan/3akai-ux-jitsi-fork,ets-berkeley-edu/3akai-ux,rhollow/MYB-1615,stuartf/3akai-ux,Orodan/3akai-ux,jonmhays/3akai-ux,stuartf/3akai-ux,Orodan/3akai-ux,rhollow/MYB-1615,Ultimedia/3akai-UX-Vanilla,mrvisser/3akai-ux,ets-berkeley-edu/3akai-ux,Coenego/avocet-ui,Coenego/avocet-ui,nicolaasmatthijs/3akai-ux,rhollow/MYB-1615,jonmhays/3akai-ux,Ultimedia/3akai-UX-Vanilla,mrvisser/3akai-ux,ets-berkeley-edu/3akai-ux,nicolaasmatthijs/3akai-ux,mrvisser/3akai-ux,timdegroote/3akai-ux,Orodan/3akai-ux-jitsi-fork,Ultimedia/3akai-UX-Vanilla,Orodan/3akai-ux,stuartf/3akai-ux,Coenego/3akai-ux,timdegroote/3akai-ux,Coenego/3akai-ux,jfederico/3akai-ux,timdegroote/3akai-ux,simong/3akai-ux,nicolaasmatthijs/3akai-ux,simong/3akai-ux,Orodan/3akai-ux-jitsi-fork,jonmhays/3akai-ux,jfederico/3akai-ux,simong/3akai-ux,jfederico/3akai-ux | /*
* Licensed to the Sakai Foundation (SF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The SF 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.
*/
/*
* Dependencies
*
* /dev/lib/jquery/plugins/jqmodal.sakai-edited.js
* /dev/lib/misc/trimpath.template.js (TrimpathTemplates)
* /dev/lib/jquery/plugins/jquery.threedots.js (ThreeDots)
*/
/*global $ */
require(["jquery", "sakai/sakai.api.core", "/dev/javascript/content_profile.js"], function($, sakai){
/**
* @name sakai_global.contentmetadata
*
* @class contentmetadata
*
* @description
* Initialize the contentmetadata widget
*
* @version 0.0.1
* @param {String} tuid Unique id of the widget
* @param {Boolean} showSettings Show the settings of the widget or not
*/
sakai_global.contentmetadata = function(tuid, showSettings){
////////////////////////
////// VARIABLES ///////
////////////////////////
// Containers
var $contentmetadataDescriptionContainer = $("#contentmetadata_description_container");
var $contentmetadataTagsContainer = $("#contentmetadata_tags_container");
var $contentmetadataUrlContainer = $("#contentmetadata_url_container");
var $contentmetadataCopyrightContainer = $("#contentmetadata_copyright_container");
var $contentmetadataDetailsContainer = $("#contentmetadata_details_container");
var $contentmetadataLocationsContainer = $("#contentmetadata_locations_container");
// Elements
var contentmetadataDescriptionDisplay = "#contentmetadata_description_display";
var $collapsibleContainers = $(".collapsible_container");
var contentmetadataViewRevisions = "#contentmetadata_view_revisions";
var $contentmetadataEditable = $(".contentmetadata_editable");
var contentmetadataCancelSave = ".contentmetadata_cancel_save";
var contentmetadataSave = ".contentmetadata_save";
var contentmetadataInputEdit = ".contentmetadata_edit_input";
// See more
var $contentmetadataShowMore = $("#contentmetadata_show_more");
var $contentmetadataSeeMore = $("#contentmetadata_see_more");
var $contentmetadataSeeLess = $("#contentmetadata_see_less");
// Templates
var contentmetadataDescriptionTemplate = "contentmetadata_description_template";
var contentmetadataTagsTemplate = "contentmetadata_tags_template";
var contentmetadataUrlTemplate = "contentmetadata_url_template";
var contentmetadataCopyrightTemplate = "contentmetadata_copyright_template";
var contentmetadataDetailsTemplate = "contentmetadata_details_template";
var contentmetadataLocationsTemplate = "contentmetadata_locations_template";
// i18n
var $contentmetadataUpdatedCopyright = $("#contentmetadata_updated_copyright");
// Edit vars
// Parent DIV that handles the hover and click to edit
var editTarget = "";
// ID of Input element that's focused, defines what to update
var edittingElement = "";
var directoryJSON = {};
////////////////////////
////// RENDERING ///////
////////////////////////
/**
* Add binding to the input elements that allow editting
* @param {String|Boolean} mode Can be false or 'edit' depending on the mode you want to be in
*/
var addEditBinding = function(mode){
if (mode === "edit") {
if ($(".contentmetadata_edit_input")[0] !== undefined) {
$(".contentmetadata_edit_input")[0].focus();
}
$(contentmetadataInputEdit).blur(editInputBlur);
}
};
/**
* Render the Description template
* @param {String|Boolean} mode Can be false or 'edit' depending on the mode you want to be in
*/
var renderDescription = function(mode){
sakai_global.content_profile.content_data.mode = mode;
var json = {
data: sakai_global.content_profile.content_data,
sakai: sakai
};
if (mode === "edit") {
$contentmetadataDescriptionContainer.addClass("contentmetadata_editing");
} else {
$contentmetadataDescriptionContainer.removeClass("contentmetadata_editing");
}
$contentmetadataDescriptionContainer.html(sakai.api.Util.TemplateRenderer(contentmetadataDescriptionTemplate, json));
addEditBinding(mode);
};
/**
* Render the URL template
* @param {String|Boolean} mode Can be false or 'edit' depending on the mode you want to be in
*/
var renderUrl = function(mode){
sakai_global.content_profile.content_data.mode = mode;
var mimeType = sakai.api.Content.getMimeType(sakai_global.content_profile.content_data.data);
if(mimeType === "x-sakai/link") {
var json = {
data: sakai_global.content_profile.content_data,
sakai: sakai
};
sakai.api.Util.TemplateRenderer(contentmetadataUrlTemplate, json, $contentmetadataUrlContainer);
$contentmetadataUrlContainer.show();
} else {
$contentmetadataUrlContainer.hide();
}
addEditBinding(mode);
};
var renderName = function(mode){
if (mode === "edit") {
$("#entity_name").hide();
$("#entity_name_text").val($.trim($("#entity_name").text()));
$("#entity_name_edit").show();
$("#entity_name_text").focus();
}
$("#entity_name_text").unbind("blur");
$("#entity_name_text").bind("blur", function(){
$("#entity_name_edit").hide();
if ($.trim($("#entity_name_text").val())) {
$("#entity_name").text($("#entity_name_text").val());
$("#entity_name").show();
$.ajax({
url: "/p/" + sakai_global.content_profile.content_data.data["_path"] + ".html",
type: "POST",
cache: false,
data: {
"sakai:pooled-content-file-name": sakai.api.Security.escapeHTML($("#entity_name_text").val())
},
success: function(){
sakai_global.content_profile.content_data.data["sakai:pooled-content-file-name"] = sakai.api.Security.escapeHTML($("#entity_name_text").val());
$("#contentpreview_download_button").attr("href", sakai_global.content_profile.content_data.smallPath + "/" + encodeURIComponent(sakai_global.content_profile.content_data.data["sakai:pooled-content-file-name"]));
}
});
}
else {
$("#entity_name").show();
$(".entity_editable").live("click", editData);
}
});
};
/**
* Render the Tags template
* @param {String|Boolean} mode Can be false or 'edit' depending on the mode you want to be in
*/
var renderTags = function(mode){
sakai_global.content_profile.content_data.mode = mode;
var json = {
data: sakai_global.content_profile.content_data,
sakai: sakai,
tags: sakai.api.Util.formatTagsExcludeLocation(sakai_global.content_profile.content_data.data["sakai:tags"])
};
if (mode === "edit") {
$contentmetadataTagsContainer.addClass("contentmetadata_editing");
} else {
$contentmetadataTagsContainer.removeClass("contentmetadata_editing");
}
$contentmetadataTagsContainer.html(sakai.api.Util.TemplateRenderer(contentmetadataTagsTemplate, json));
addEditBinding(mode);
};
/**
* Render the Copyright template
* @param {String|Boolean} mode Can be false or 'edit' depending on the mode you want to be in
*/
var renderCopyright = function(mode){
sakai_global.content_profile.content_data.mode = mode;
var json = {
data: sakai_global.content_profile.content_data,
sakai: sakai
};
if (mode === "edit") {
$contentmetadataCopyrightContainer.addClass("contentmetadata_editing");
} else {
$contentmetadataCopyrightContainer.removeClass("contentmetadata_editing");
}
$contentmetadataCopyrightContainer.html(sakai.api.Util.TemplateRenderer(contentmetadataCopyrightTemplate, json));
addEditBinding(mode);
};
/**
* Render the Details template
* @param {String|Boolean} mode Can be false or 'edit' depending on the mode you want to be in
*/
var renderDetails = function(mode){
sakai_global.content_profile.content_data.mode = mode;
sakai.api.Content.getCreatorProfile(sakai_global.content_profile.content_data.data, function(success, profile) {
var json = {
data: sakai_global.content_profile.content_data,
sakai: sakai,
creator: profile
};
sakai.api.Util.TemplateRenderer(contentmetadataDetailsTemplate, json, $contentmetadataDetailsContainer);
addEditBinding(mode);
});
};
var createActivity = function(activityMessage){
var activityData = {
"sakai:activityMessage": activityMessage
};
sakai.api.Activity.createActivity("/p/" + sakai_global.content_profile.content_data.data["_path"], "content", "default", activityData, function(responseData, success){
if (success) {
// update the entity widget with the new activity
$(window).trigger("updateContentActivity.entity.sakai", activityMessage);
}
});
};
//////////////////////////////////
/////// DIRECTORY EDITTING ///////
var renderLocationsEdit = function(){
$("#assignlocation_container").jqmShow();
};
/**
* Render the Locations template
* @param {String|Boolean} mode Can be false or 'edit' depending on the mode you want to be in
*/
var renderLocations = function(mode){
if (mode === "edit") {
renderLocationsEdit();
}
else {
$contentmetadataLocationsContainer.html("");
sakai_global.content_profile.content_data.mode = mode;
var json = {
data: sakai_global.content_profile.content_data,
sakai: sakai
};
var directorylocations = [];
for(var dir in json.data.saveddirectory){
if(json.data.saveddirectory.hasOwnProperty(dir)){
var dirString = "";
for (var dirPiece in json.data.saveddirectory[dir]){
if(json.data.saveddirectory[dir].hasOwnProperty(dirPiece)){
dirString += sakai.api.Util.getValueForDirectoryKey(json.data.saveddirectory[dir][dirPiece]);
if(dirPiece < json.data.saveddirectory[dir].length - 1){
dirString += " » ";
}
}
}
directorylocations.push(sakai.api.Util.applyThreeDots(dirString, $("#contentmetadata_locations_container").width() - 120, {max_rows: 1,whole_word: false}, "s3d-bold"));
}
}
json["directorylocations"] = directorylocations;
$contentmetadataLocationsContainer.html(sakai.api.Util.TemplateRenderer(contentmetadataLocationsTemplate, json));
}
};
////////////////////////
/////// EDITTING ///////
////////////////////////
var updateTags = function(){
var tags = sakai.api.Util.formatTags($("#contentmetadata_tags_tags").val());
// Since directory tags are filtered out of the textarea we should put them back to save them
$(sakai_global.content_profile.content_data.data["sakai:tags"]).each(function(index, tag){
if (tag.split("/")[0] === "directory") {
tags.push(tag);
}
});
for(var tag in tags){
if (tags.hasOwnProperty(tag)) {
tags[tag] = tags[tag].replace(/\s+/g, " ");
}
}
sakai.api.Util.tagEntity("/p/" + sakai_global.content_profile.content_data.data["_path"], tags, sakai_global.content_profile.content_data.data["sakai:tags"], function(){
sakai_global.content_profile.content_data.data["sakai:tags"] = tags;
renderTags(false);
// Create an activity
createActivity("UPDATED_TAGS");
});
};
/**
* Update the description of the content
*/
var updateDescription = function(){
var description = $("#contentmetadata_description_description").val();
sakai_global.content_profile.content_data.data["sakai:description"] = description;
renderDescription(false);
$.ajax({
url: "/p/" + sakai_global.content_profile.content_data.data["_path"] + ".html",
type: "POST",
cache: false,
data: {
"sakai:description": description
},
success: function(){
createActivity("UPDATED_DESCRIPTION");
}
});
};
/**
* Update the description of the content
*/
var updateUrl = function(){
var url = $("#contentmetadata_url_url").val();
var preview = sakai.api.Content.getPreviewUrl(url);
sakai_global.content_profile.content_data.data["sakai:pooled-content-url"] = url;
sakai_global.content_profile.content_data.data["sakai:pooled-content-revurl"] = url;
sakai_global.content_profile.content_data.data["sakai:preview-url"] = preview.url;
sakai_global.content_profile.content_data.data["sakai:preview-type"] = preview.type;
sakai_global.content_profile.content_data.data["sakai:preview-avatar"] = preview.avatar;
sakai_global.content_profile.content_data.data["length"] = url.length;
renderUrl(false);
$.ajax({
url: "/p/" + sakai_global.content_profile.content_data.data["_path"] + ".html",
type: "POST",
cache: false,
data: {
"sakai:pooled-content-url": url,
"sakai:pooled-content-revurl": url,
"sakai:preview-url": preview.url,
"sakai:preview-type": preview.type,
"sakai:preview-avatar": preview.avatar,
"length": url.length
},
success: function(){
createActivity("UPDATED_URL");
$(window).trigger("updated.version.content.sakai");
}
});
};
/**
* Update the copyright of the content
*/
var updateCopyright = function(){
var copyright = $("#contentmetadata_copyright_copyright").val();
sakai_global.content_profile.content_data.data["sakai:copyright"] = copyright;
renderCopyright(false);
$.ajax({
url: "/p/" + sakai_global.content_profile.content_data.data["_path"] + ".html",
type: "POST",
cache: false,
data: {
"sakai:copyright": copyright
},
success: function(){
createActivity("UPDATED_COPYRIGHT");
}
});
};
/**
* Trigger the template to render the edit mode
* @param {Object} ev Trigger event
*/
var editData = function(ev){
var dataToEdit = "";
if (ev.target.nodeName.toLowerCase() !== "a" && ev.target.nodeName.toLowerCase() !== "select" && ev.target.nodeName.toLowerCase() !== "option" && ev.target.nodeName.toLowerCase() !== "textarea") {
target = $(ev.target).closest(".contentmetadata_editable");
if (target[0] !== undefined) {
editTarget = target;
dataToEdit = editTarget[0].id.split("_")[1];
switch (dataToEdit) {
case "description":
renderDescription("edit");
break;
case "tags":
renderTags("edit");
break;
case "url":
renderUrl("edit");
break;
case "locations":
renderLocations("edit");
break;
case "copyright":
renderCopyright("edit");
break;
case "name":
renderName("edit");
break;
}
}
}
};
/**
* Handle losing of focus on an input element
* @param {Object} el Element that lost the focus
*/
var editInputBlur = function(el){
edittingElement = $(el.target)[0].id.split("_")[2];
switch (edittingElement) {
case "description":
updateDescription();
break;
case "tags":
updateTags();
break;
case "url":
updateUrl();
break;
case "copyright":
updateCopyright();
break;
}
};
////////////////////////
//////// SET-UP ////////
////////////////////////
/**
* Animate the hidden or shown data containers
*/
var animateData = function(){
$collapsibleContainers.animate({
'margin-bottom': 'toggle',
opacity: 'toggle',
'padding-top': 'toggle',
'padding-bottom': 'toggle',
height: 'toggle'
}, 400);
$("#contentmetadata_show_more > div").toggle();
};
/**
* Add binding/events to the elements in the widget
*/
var addBinding = function(){
$(".contentmetadata_editable_for_maintainers").removeClass("contentmetadata_editable");
if (sakai_global.content_profile.content_data.isManager) {
$(".contentmetadata_editable_for_maintainers").addClass("contentmetadata_editable");
}
$contentmetadataShowMore.unbind("click", animateData);
$contentmetadataShowMore.bind("click", animateData);
$(".contentmetadata_editable").die("click", editData);
$(".contentmetadata_editable").live("click", editData);
$(contentmetadataViewRevisions).die("click");
$(contentmetadataViewRevisions).live("click", function(){
$(window).trigger("initialize.filerevisions.sakai", sakai_global.content_profile.content_data);
});
};
/**
* Initialize the widget
*/
var doInit = function(){
// Render all information
renderDescription(false);
renderTags(false);
renderUrl(false);
renderCopyright(false);
renderLocations(false);
renderDetails(false);
// Add binding
addBinding();
};
$(window).bind("complete.fileupload.sakai", function(){
$(window).trigger("load.content_profile.sakai", renderDetails);
});
$(window).bind("renderlocations.contentmetadata.sakai", function(ev){
renderLocations(false);
});
// Bind Enter key to input fields to save on keyup
$("input").bind("keyup", function(ev){
if (ev.keyCode == 13) {
$(this).blur();
}
});
/**
* Initialize the widget from outside of the widget
*/
$(window).bind("render.contentmetadata.sakai", function(){
doInit();
});
sakai_global.contentmetadata.isReady = true;
$(window).trigger("ready.contentmetadata.sakai");
};
sakai.api.Widgets.widgetLoader.informOnLoad("contentmetadata");
});
| devwidgets/contentmetadata/javascript/contentmetadata.js | /*
* Licensed to the Sakai Foundation (SF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The SF 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.
*/
/*
* Dependencies
*
* /dev/lib/jquery/plugins/jqmodal.sakai-edited.js
* /dev/lib/misc/trimpath.template.js (TrimpathTemplates)
* /dev/lib/jquery/plugins/jquery.threedots.js (ThreeDots)
*/
/*global $ */
require(["jquery", "sakai/sakai.api.core", "/dev/javascript/content_profile.js"], function($, sakai){
/**
* @name sakai_global.contentmetadata
*
* @class contentmetadata
*
* @description
* Initialize the contentmetadata widget
*
* @version 0.0.1
* @param {String} tuid Unique id of the widget
* @param {Boolean} showSettings Show the settings of the widget or not
*/
sakai_global.contentmetadata = function(tuid, showSettings){
////////////////////////
////// VARIABLES ///////
////////////////////////
// Containers
var $contentmetadataDescriptionContainer = $("#contentmetadata_description_container");
var $contentmetadataTagsContainer = $("#contentmetadata_tags_container");
var $contentmetadataUrlContainer = $("#contentmetadata_url_container");
var $contentmetadataCopyrightContainer = $("#contentmetadata_copyright_container");
var $contentmetadataDetailsContainer = $("#contentmetadata_details_container");
var $contentmetadataLocationsContainer = $("#contentmetadata_locations_container");
// Elements
var contentmetadataDescriptionDisplay = "#contentmetadata_description_display";
var $collapsibleContainers = $(".collapsible_container");
var contentmetadataViewRevisions = "#contentmetadata_view_revisions";
var $contentmetadataEditable = $(".contentmetadata_editable");
var contentmetadataCancelSave = ".contentmetadata_cancel_save";
var contentmetadataSave = ".contentmetadata_save";
var contentmetadataInputEdit = ".contentmetadata_edit_input";
// See more
var $contentmetadataShowMore = $("#contentmetadata_show_more");
var $contentmetadataSeeMore = $("#contentmetadata_see_more");
var $contentmetadataSeeLess = $("#contentmetadata_see_less");
// Templates
var contentmetadataDescriptionTemplate = "contentmetadata_description_template";
var contentmetadataTagsTemplate = "contentmetadata_tags_template";
var contentmetadataUrlTemplate = "contentmetadata_url_template";
var contentmetadataCopyrightTemplate = "contentmetadata_copyright_template";
var contentmetadataDetailsTemplate = "contentmetadata_details_template";
var contentmetadataLocationsTemplate = "contentmetadata_locations_template";
// i18n
var $contentmetadataUpdatedCopyright = $("#contentmetadata_updated_copyright");
// Edit vars
// Parent DIV that handles the hover and click to edit
var editTarget = "";
// ID of Input element that's focused, defines what to update
var edittingElement = "";
var directoryJSON = {};
////////////////////////
////// RENDERING ///////
////////////////////////
/**
* Add binding to the input elements that allow editting
* @param {String|Boolean} mode Can be false or 'edit' depending on the mode you want to be in
*/
var addEditBinding = function(mode){
if (mode === "edit") {
if ($(".contentmetadata_edit_input")[0] !== undefined) {
$(".contentmetadata_edit_input")[0].focus();
}
$(contentmetadataInputEdit).blur(editInputBlur);
}
};
/**
* Render the Description template
* @param {String|Boolean} mode Can be false or 'edit' depending on the mode you want to be in
*/
var renderDescription = function(mode){
sakai_global.content_profile.content_data.mode = mode;
var json = {
data: sakai_global.content_profile.content_data,
sakai: sakai
};
if (mode === "edit") {
$contentmetadataDescriptionContainer.addClass("contentmetadata_editing");
} else {
$contentmetadataDescriptionContainer.removeClass("contentmetadata_editing");
}
$contentmetadataDescriptionContainer.html(sakai.api.Util.TemplateRenderer(contentmetadataDescriptionTemplate, json));
addEditBinding(mode);
};
/**
* Render the URL template
* @param {String|Boolean} mode Can be false or 'edit' depending on the mode you want to be in
*/
var renderUrl = function(mode){
sakai_global.content_profile.content_data.mode = mode;
var mimeType = sakai.api.Content.getMimeType(sakai_global.content_profile.content_data.data);
if(mimeType === "x-sakai/link") {
var json = {
data: sakai_global.content_profile.content_data,
sakai: sakai
};
sakai.api.Util.TemplateRenderer(contentmetadataUrlTemplate, json, $contentmetadataUrlContainer);
$contentmetadataUrlContainer.show();
} else {
$contentmetadataUrlContainer.hide();
}
addEditBinding(mode);
};
var renderName = function(mode){
if (mode === "edit") {
$("#entity_name").hide();
$("#entity_name_text").val($.trim($("#entity_name").text()));
$("#entity_name_edit").show();
$("#entity_name_text").focus();
}
$("#entity_name_text").unbind("blur");
$("#entity_name_text").bind("blur", function(){
$("#entity_name_edit").hide();
if ($.trim($("#entity_name_text").val())) {
$("#entity_name").text($("#entity_name_text").val());
$("#entity_name").show();
$.ajax({
url: "/p/" + sakai_global.content_profile.content_data.data["_path"] + ".html",
type: "POST",
cache: false,
data: {
"sakai:pooled-content-file-name": sakai.api.Security.escapeHTML($("#entity_name_text").val())
},
success: function(){
sakai_global.content_profile.content_data.data["sakai:pooled-content-file-name"] = sakai.api.Security.escapeHTML($("#entity_name_text").val());
$("#contentpreview_download_button").attr("href", sakai_global.content_profile.content_data.smallPath + "/" + encodeURIComponent(sakai_global.content_profile.content_data.data["sakai:pooled-content-file-name"]));
}
});
}
else {
$("#entity_name").show();
$(".entity_editable").live("click", editData);
}
});
};
/**
* Render the Tags template
* @param {String|Boolean} mode Can be false or 'edit' depending on the mode you want to be in
*/
var renderTags = function(mode){
sakai_global.content_profile.content_data.mode = mode;
var json = {
data: sakai_global.content_profile.content_data,
sakai: sakai,
tags: sakai.api.Util.formatTagsExcludeLocation(sakai_global.content_profile.content_data.data["sakai:tags"])
};
if (mode === "edit") {
$contentmetadataTagsContainer.addClass("contentmetadata_editing");
} else {
$contentmetadataTagsContainer.removeClass("contentmetadata_editing");
}
$contentmetadataTagsContainer.html(sakai.api.Util.TemplateRenderer(contentmetadataTagsTemplate, json));
addEditBinding(mode);
};
/**
* Render the Copyright template
* @param {String|Boolean} mode Can be false or 'edit' depending on the mode you want to be in
*/
var renderCopyright = function(mode){
sakai_global.content_profile.content_data.mode = mode;
var json = {
data: sakai_global.content_profile.content_data,
sakai: sakai
};
if (mode === "edit") {
$contentmetadataCopyrightContainer.addClass("contentmetadata_editing");
} else {
$contentmetadataCopyrightContainer.removeClass("contentmetadata_editing");
}
$contentmetadataCopyrightContainer.html(sakai.api.Util.TemplateRenderer(contentmetadataCopyrightTemplate, json));
addEditBinding(mode);
};
/**
* Render the Details template
* @param {String|Boolean} mode Can be false or 'edit' depending on the mode you want to be in
*/
var renderDetails = function(mode){
sakai_global.content_profile.content_data.mode = mode;
sakai.api.Content.getCreatorProfile(sakai_global.content_profile.content_data.data, function(success, profile) {
var json = {
data: sakai_global.content_profile.content_data,
sakai: sakai,
creator: profile
};
sakai.api.Util.TemplateRenderer(contentmetadataDetailsTemplate, json, $contentmetadataDetailsContainer);
addEditBinding(mode);
});
};
var createActivity = function(activityMessage){
var activityData = {
"sakai:activityMessage": activityMessage
};
sakai.api.Activity.createActivity("/p/" + sakai_global.content_profile.content_data.data["_path"], "content", "default", activityData, function(responseData, success){
if (success) {
// update the entity widget with the new activity
$(window).trigger("updateContentActivity.entity.sakai", activityMessage);
}
});
};
//////////////////////////////////
/////// DIRECTORY EDITTING ///////
var renderLocationsEdit = function(){
$("#assignlocation_container").jqmShow();
};
/**
* Render the Locations template
* @param {String|Boolean} mode Can be false or 'edit' depending on the mode you want to be in
*/
var renderLocations = function(mode){
if (mode === "edit") {
renderLocationsEdit();
}
else {
$contentmetadataLocationsContainer.html("");
sakai_global.content_profile.content_data.mode = mode;
var json = {
data: sakai_global.content_profile.content_data,
sakai: sakai
};
var directorylocations = [];
for(var dir in json.data.saveddirectory){
if(json.data.saveddirectory.hasOwnProperty(dir)){
var dirString = "";
for (var dirPiece in json.data.saveddirectory[dir]){
if(json.data.saveddirectory[dir].hasOwnProperty(dirPiece)){
dirString += sakai.api.Util.getValueForDirectoryKey(json.data.saveddirectory[dir][dirPiece]);
if(dirPiece < json.data.saveddirectory[dir].length - 1){
dirString += " » ";
}
}
}
directorylocations.push(sakai.api.Util.applyThreeDots(dirString, $("#contentmetadata_locations_container").width() - 120, {max_rows: 1,whole_word: false}, "s3d-bold"));
}
}
json["directorylocations"] = directorylocations;
$contentmetadataLocationsContainer.html(sakai.api.Util.TemplateRenderer(contentmetadataLocationsTemplate, json));
}
};
////////////////////////
/////// EDITTING ///////
////////////////////////
var updateTags = function(){
var tags = sakai.api.Util.formatTags($("#contentmetadata_tags_tags").val());
// Since directory tags are filtered out of the textarea we should put them back to save them
$(sakai_global.content_profile.content_data.data["sakai:tags"]).each(function(index, tag){
if (tag.split("/")[0] === "directory") {
tags.push(tag);
}
});
for(var tag in tags){
if (tags.hasOwnProperty(tag)) {
tags[tag] = tags[tag].replace(/\s+/g, " ");
}
}
sakai.api.Util.tagEntity("/p/" + sakai_global.content_profile.content_data.data["_path"], tags, sakai_global.content_profile.content_data.data["sakai:tags"], function(){
sakai_global.content_profile.content_data.data["sakai:tags"] = tags;
renderTags(false);
// Create an activity
createActivity("UPDATED_TAGS");
});
};
/**
* Update the description of the content
*/
var updateDescription = function(){
var description = $("#contentmetadata_description_description").val();
sakai_global.content_profile.content_data.data["sakai:description"] = description;
renderDescription(false);
$.ajax({
url: "/p/" + sakai_global.content_profile.content_data.data["_path"] + ".html",
type: "POST",
cache: false,
data: {
"sakai:description": description
},
success: function(){
createActivity("UPDATED_DESCRIPTION");
}
});
};
/**
* Update the description of the content
*/
var updateUrl = function(){
var url = $("#contentmetadata_url_url").val();
var preview = sakai.api.Content.getPreviewUrl(url);
sakai_global.content_profile.content_data.data["sakai:pooled-content-url"] = url;
sakai_global.content_profile.content_data.data["sakai:pooled-content-revurl"] = url;
sakai_global.content_profile.content_data.data["sakai:preview-url"] = preview.url;
sakai_global.content_profile.content_data.data["sakai:preview-type"] = preview.type;
sakai_global.content_profile.content_data.data["sakai:preview-avatar"] = preview.avatar;
sakai_global.content_profile.content_data.data["length"] = url.length;
renderUrl(false);
$.ajax({
url: "/p/" + sakai_global.content_profile.content_data.data["_path"] + ".html",
type: "POST",
cache: false,
data: {
"sakai:pooled-content-url": url,
"sakai:pooled-content-revurl": url,
"sakai:preview-url": preview.url,
"sakai:preview-type": preview.type,
"sakai:preview-avatar": preview.avatar,
"length": url.length
},
success: function(){
createActivity("UPDATED_URL");
$(window).trigger("updated.version.content.sakai");
}
});
};
/**
* Update the copyright of the content
*/
var updateCopyright = function(){
var copyright = $("#contentmetadata_copyright_copyright").val();
sakai_global.content_profile.content_data.data["sakai:copyright"] = copyright;
renderCopyright(false);
$.ajax({
url: "/p/" + sakai_global.content_profile.content_data.data["_path"] + ".html",
type: "POST",
cache: false,
data: {
"sakai:copyright": $("#contentmetadata_copyright_copyright").val()
},
success: function(){
createActivity("UPDATED_COPYRIGHT");
}
});
};
/**
* Trigger the template to render the edit mode
* @param {Object} ev Trigger event
*/
var editData = function(ev){
var dataToEdit = "";
if (ev.target.nodeName.toLowerCase() !== "a" && ev.target.nodeName.toLowerCase() !== "select" && ev.target.nodeName.toLowerCase() !== "option" && ev.target.nodeName.toLowerCase() !== "textarea") {
target = $(ev.target).closest(".contentmetadata_editable");
if (target[0] !== undefined) {
editTarget = target;
dataToEdit = editTarget[0].id.split("_")[1];
switch (dataToEdit) {
case "description":
renderDescription("edit");
break;
case "tags":
renderTags("edit");
break;
case "url":
renderUrl("edit");
break;
case "locations":
renderLocations("edit");
break;
case "copyright":
renderCopyright("edit");
break;
case "name":
renderName("edit");
break;
}
}
}
};
/**
* Handle losing of focus on an input element
* @param {Object} el Element that lost the focus
*/
var editInputBlur = function(el){
edittingElement = $(el.target)[0].id.split("_")[2];
switch (edittingElement) {
case "description":
updateDescription();
break;
case "tags":
updateTags();
break;
case "url":
updateUrl();
break;
case "copyright":
updateCopyright();
break;
}
};
////////////////////////
//////// SET-UP ////////
////////////////////////
/**
* Animate the hidden or shown data containers
*/
var animateData = function(){
$collapsibleContainers.animate({
'margin-bottom': 'toggle',
opacity: 'toggle',
'padding-top': 'toggle',
'padding-bottom': 'toggle',
height: 'toggle'
}, 400);
$("#contentmetadata_show_more > div").toggle();
};
/**
* Add binding/events to the elements in the widget
*/
var addBinding = function(){
$(".contentmetadata_editable_for_maintainers").removeClass("contentmetadata_editable");
if (sakai_global.content_profile.content_data.isManager) {
$(".contentmetadata_editable_for_maintainers").addClass("contentmetadata_editable");
}
$contentmetadataShowMore.unbind("click", animateData);
$contentmetadataShowMore.bind("click", animateData);
$(".contentmetadata_editable").die("click", editData);
$(".contentmetadata_editable").live("click", editData);
$(contentmetadataViewRevisions).die("click");
$(contentmetadataViewRevisions).live("click", function(){
$(window).trigger("initialize.filerevisions.sakai", sakai_global.content_profile.content_data);
});
};
/**
* Initialize the widget
*/
var doInit = function(){
// Render all information
renderDescription(false);
renderTags(false);
renderUrl(false);
renderCopyright(false);
renderLocations(false);
renderDetails(false);
// Add binding
addBinding();
};
$(window).bind("complete.fileupload.sakai", function(){
$(window).trigger("load.content_profile.sakai", renderDetails);
});
$(window).bind("renderlocations.contentmetadata.sakai", function(ev){
renderLocations(false);
});
// Bind Enter key to input fields to save on keyup
$("input").bind("keyup", function(ev){
if (ev.keyCode == 13) {
$(this).blur();
}
});
/**
* Initialize the widget from outside of the widget
*/
$(window).bind("render.contentmetadata.sakai", function(){
doInit();
});
sakai_global.contentmetadata.isReady = true;
$(window).trigger("ready.contentmetadata.sakai");
};
sakai.api.Widgets.widgetLoader.informOnLoad("contentmetadata");
});
| SAKIII-3680 - Description and tags inline-edit fields overflow yellow background
| devwidgets/contentmetadata/javascript/contentmetadata.js | SAKIII-3680 - Description and tags inline-edit fields overflow yellow background | <ide><path>evwidgets/contentmetadata/javascript/contentmetadata.js
<ide> type: "POST",
<ide> cache: false,
<ide> data: {
<del> "sakai:copyright": $("#contentmetadata_copyright_copyright").val()
<add> "sakai:copyright": copyright
<ide> },
<ide> success: function(){
<ide> createActivity("UPDATED_COPYRIGHT"); |
|
Java | apache-2.0 | b62f2c0c438cac09e10ba44ae879fdf708c5e43f | 0 | garethahealy/loadbalancer-healthchecks | /*
* #%L
* GarethHealy :: LoadBalancer HealthChecks :: Fabric8 Gateway AMQP
* %%
* Copyright (C) 2013 - 2016 Gareth Healy
* %%
* 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.
* #L%
*/
package com.garethahealy.loadbalancer.healthchecks.fabric8.gateway.amqp;
import org.apache.camel.test.blueprint.CamelBlueprintTestSupport;
import org.junit.Assert;
import org.junit.Test;
public class CamelContextTest extends CamelBlueprintTestSupport {
@Override
protected String getBlueprintDescriptor() {
return "OSGI-INF/blueprint/camel-context.xml";
}
@Test
public void canStart() {
Assert.assertNotNull(context);
}
}
| fabric8-gateway-amqp/src/test/java/com/garethahealy/loadbalancer/healthchecks/fabric8/gateway/amqp/CamelContextTest.java | /*
* #%L
* GarethHealy :: LoadBalancer HealthChecks :: Fabric8 Gateway AMQP
* %%
* Copyright (C) 2013 - 2016 Gareth Healy
* %%
* 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.
* #L%
*/
package com.garethahealy.loadbalancer.healthchecks.fabric8.gateway.amqp;
import junit.framework.Assert;
import org.apache.camel.test.blueprint.CamelBlueprintTestSupport;
import org.junit.Test;
public class CamelContextTest extends CamelBlueprintTestSupport {
@Override
protected String getBlueprintDescriptor() {
return "OSGI-INF/blueprint/camel-context.xml";
}
@Test
public void canStart() {
Assert.assertNotNull(context);
}
}
| Fixed deprecated warning
| fabric8-gateway-amqp/src/test/java/com/garethahealy/loadbalancer/healthchecks/fabric8/gateway/amqp/CamelContextTest.java | Fixed deprecated warning | <ide><path>abric8-gateway-amqp/src/test/java/com/garethahealy/loadbalancer/healthchecks/fabric8/gateway/amqp/CamelContextTest.java
<ide> */
<ide> package com.garethahealy.loadbalancer.healthchecks.fabric8.gateway.amqp;
<ide>
<del>import junit.framework.Assert;
<ide> import org.apache.camel.test.blueprint.CamelBlueprintTestSupport;
<add>import org.junit.Assert;
<ide> import org.junit.Test;
<ide>
<ide> public class CamelContextTest extends CamelBlueprintTestSupport { |
|
Java | apache-2.0 | 5826411b1bf440a77b526c8b414ddcf1c6f11a34 | 0 | HanSolo/Medusa | /*
* Copyright (c) 2016 by Gerrit Grunwald
*
* 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 eu.hansolo.medusa;
import eu.hansolo.medusa.Clock.ClockSkinType;
import eu.hansolo.medusa.Gauge.SkinType;
import eu.hansolo.medusa.Section.SectionEvent;
import eu.hansolo.medusa.events.UpdateEvent;
import eu.hansolo.medusa.events.UpdateEvent.EventType;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.stage.Stage;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Random;
/**
* User: hansolo
* Date: 04.01.16
* Time: 06:31
*/
public class Test extends Application {
private static final Random RND = new Random();
private static int noOfNodes = 0;
private FGauge fgauge;
private Gauge gauge;
private Clock clock;
private long lastTimerCall;
private AnimationTimer timer;
private DoubleProperty value;
private long epochSeconds;
private BooleanProperty toggle;
@Override public void init() {
NumberFormat numberFormat = NumberFormat.getInstance(new Locale("da", "DK"));
numberFormat.setRoundingMode(RoundingMode.HALF_DOWN);
numberFormat.setMinimumIntegerDigits(3);
numberFormat.setMaximumIntegerDigits(3);
numberFormat.setMinimumFractionDigits(0);
numberFormat.setMaximumFractionDigits(0);
value = new SimpleDoubleProperty(0);
toggle = new SimpleBooleanProperty(false);
fgauge = FGaugeBuilder.create()
.gaugeDesign(GaugeDesign.NONE)
.build();
gauge = GaugeBuilder.create()
.skinType(SkinType.TILE_KPI)
.prefSize(400, 400)
.minValue(-20)
.maxValue(50)
.animated(true)
//.checkThreshold(true)
//.onThresholdExceeded(e -> System.out.println("threshold exceeded"))
//.lcdVisible(true)
//.locale(Locale.GERMANY)
//.numberFormat(numberFormat)
.title("Title")
.unit("\u00B0C")
.subTitle("SubTitle")
//.interactive(true)
//.onButtonPressed(o -> System.out.println("Button pressed"))
.sections(new Section(-20, 0, Color.BLUE),
new Section(0, 25, Color.YELLOW),
new Section(25, 50, Color.RED))
.sectionsVisible(true)
.highlightSections(true)
.autoScale(false)
.averagingEnabled(true)
.averagingPeriod(10)
.averageVisible(true)
.build();
//gauge.setAlert(true);
// Calling bind() directly sets a value to gauge
gauge.valueProperty().bind(value);
gauge.getSections().forEach(section -> section.setOnSectionUpdate(sectionEvent -> gauge.fireUpdateEvent(new UpdateEvent(Test.this, EventType.REDRAW))));
//gauge.valueVisibleProperty().bind(toggle);
epochSeconds = Instant.now().getEpochSecond();
clock = ClockBuilder.create()
.skinType(ClockSkinType.INDUSTRIAL)
.locale(Locale.GERMANY)
.shadowsEnabled(true)
//.discreteSeconds(false)
//.discreteMinutes(false)
.running(true)
//.backgroundPaint(Color.web("#1f1e23"))
//.hourColor(Color.web("#dad9db"))
//.minuteColor(Color.web("#dad9db"))
//.secondColor(Color.web("#d1222b"))
//.hourTickMarkColor(Color.web("#9f9fa1"))
//.minuteTickMarkColor(Color.web("#9f9fa1"))
.build();
lastTimerCall = System.nanoTime();
timer = new AnimationTimer() {
@Override public void handle(long now) {
if (now > lastTimerCall + 3_000_000_000l) {
double v = RND.nextDouble() * gauge.getRange() + gauge.getMinValue();
value.set(v);
System.out.println(v);
//gauge.setValue(v);
//System.out.println("MovingAverage over " + gauge.getAveragingWindow().size() + " values: " + gauge.getAverage() + " last value = " + v);
//toggle.set(!toggle.get());
//System.out.println(gauge.isValueVisible());
//gauge.setValue(v);
//epochSeconds+=20;
//clock.setTime(epochSeconds);
lastTimerCall = now;
}
}
};
}
@Override public void start(Stage stage) {
StackPane pane = new StackPane(gauge);
pane.setPadding(new Insets(20));
LinearGradient gradient = new LinearGradient(0, 0, 0, pane.getLayoutBounds().getHeight(),
false, CycleMethod.NO_CYCLE,
new Stop(0.0, Color.rgb(38, 38, 38)),
new Stop(1.0, Color.rgb(15, 15, 15)));
//pane.setBackground(new Background(new BackgroundFill(gradient, CornerRadii.EMPTY, Insets.EMPTY)));
//pane.setBackground(new Background(new BackgroundFill(Color.rgb(39,44,50), CornerRadii.EMPTY, Insets.EMPTY)));
//pane.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
//pane.setBackground(new Background(new BackgroundFill(Gauge.DARK_COLOR, CornerRadii.EMPTY, Insets.EMPTY)));
Scene scene = new Scene(pane);
stage.setTitle("Medusa");
stage.setScene(scene);
stage.show();
//gauge.setValue(105);
// Calculate number of nodes
calcNoOfNodes(pane);
System.out.println(noOfNodes + " Nodes in SceneGraph");
timer.start();
//gauge.getSections().get(0).setStart(10);
//gauge.getSections().get(0).setStop(90);
}
@Override public void stop() {
System.exit(0);
}
// ******************** Misc **********************************************
private static void calcNoOfNodes(Node node) {
if (node instanceof Parent) {
if (((Parent) node).getChildrenUnmodifiable().size() != 0) {
ObservableList<Node> tempChildren = ((Parent) node).getChildrenUnmodifiable();
noOfNodes += tempChildren.size();
for (Node n : tempChildren) { calcNoOfNodes(n); }
}
}
}
public static void main(String[] args) {
launch(args);
}
}
| src/main/java/eu/hansolo/medusa/Test.java | /*
* Copyright (c) 2016 by Gerrit Grunwald
*
* 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 eu.hansolo.medusa;
import eu.hansolo.medusa.Clock.ClockSkinType;
import eu.hansolo.medusa.Gauge.SkinType;
import eu.hansolo.medusa.Section.SectionEvent;
import eu.hansolo.medusa.events.UpdateEvent;
import eu.hansolo.medusa.events.UpdateEvent.EventType;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.stage.Stage;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Random;
/**
* User: hansolo
* Date: 04.01.16
* Time: 06:31
*/
public class Test extends Application {
private static final Random RND = new Random();
private static int noOfNodes = 0;
private FGauge fgauge;
private Gauge gauge;
private Clock clock;
private long lastTimerCall;
private AnimationTimer timer;
private DoubleProperty value;
private long epochSeconds;
private BooleanProperty toggle;
@Override public void init() {
NumberFormat numberFormat = NumberFormat.getInstance(new Locale("da", "DK"));
numberFormat.setRoundingMode(RoundingMode.HALF_DOWN);
numberFormat.setMinimumIntegerDigits(3);
numberFormat.setMaximumIntegerDigits(3);
numberFormat.setMinimumFractionDigits(0);
numberFormat.setMaximumFractionDigits(0);
value = new SimpleDoubleProperty(0);
toggle = new SimpleBooleanProperty(false);
fgauge = FGaugeBuilder.create()
.gaugeDesign(GaugeDesign.NONE)
.build();
gauge = GaugeBuilder.create()
.skinType(SkinType.TILE_KPI)
.prefSize(400, 400)
.minValue(-20)
.maxValue(50)
.animated(true)
//.checkThreshold(true)
//.onThresholdExceeded(e -> System.out.println("threshold exceeded"))
//.lcdVisible(true)
//.locale(Locale.GERMANY)
//.numberFormat(numberFormat)
.title("Title")
.unit("°C")
.subTitle("SubTitle")
//.interactive(true)
//.onButtonPressed(o -> System.out.println("Button pressed"))
.sections(new Section(-20, 0, Color.BLUE),
new Section(0, 25, Color.YELLOW),
new Section(25, 50, Color.RED))
.sectionsVisible(true)
.highlightSections(true)
.autoScale(false)
.averagingEnabled(true)
.averagingPeriod(10)
.averageVisible(true)
.build();
//gauge.setAlert(true);
// Calling bind() directly sets a value to gauge
gauge.valueProperty().bind(value);
gauge.getSections().forEach(section -> section.setOnSectionUpdate(sectionEvent -> gauge.fireUpdateEvent(new UpdateEvent(Test.this, EventType.REDRAW))));
//gauge.valueVisibleProperty().bind(toggle);
epochSeconds = Instant.now().getEpochSecond();
clock = ClockBuilder.create()
.skinType(ClockSkinType.INDUSTRIAL)
.locale(Locale.GERMANY)
.shadowsEnabled(true)
//.discreteSeconds(false)
//.discreteMinutes(false)
.running(true)
//.backgroundPaint(Color.web("#1f1e23"))
//.hourColor(Color.web("#dad9db"))
//.minuteColor(Color.web("#dad9db"))
//.secondColor(Color.web("#d1222b"))
//.hourTickMarkColor(Color.web("#9f9fa1"))
//.minuteTickMarkColor(Color.web("#9f9fa1"))
.build();
lastTimerCall = System.nanoTime();
timer = new AnimationTimer() {
@Override public void handle(long now) {
if (now > lastTimerCall + 3_000_000_000l) {
double v = RND.nextDouble() * gauge.getRange() + gauge.getMinValue();
value.set(v);
System.out.println(v);
//gauge.setValue(v);
//System.out.println("MovingAverage over " + gauge.getAveragingWindow().size() + " values: " + gauge.getAverage() + " last value = " + v);
//toggle.set(!toggle.get());
//System.out.println(gauge.isValueVisible());
//gauge.setValue(v);
//epochSeconds+=20;
//clock.setTime(epochSeconds);
lastTimerCall = now;
}
}
};
}
@Override public void start(Stage stage) {
StackPane pane = new StackPane(gauge);
pane.setPadding(new Insets(20));
LinearGradient gradient = new LinearGradient(0, 0, 0, pane.getLayoutBounds().getHeight(),
false, CycleMethod.NO_CYCLE,
new Stop(0.0, Color.rgb(38, 38, 38)),
new Stop(1.0, Color.rgb(15, 15, 15)));
//pane.setBackground(new Background(new BackgroundFill(gradient, CornerRadii.EMPTY, Insets.EMPTY)));
//pane.setBackground(new Background(new BackgroundFill(Color.rgb(39,44,50), CornerRadii.EMPTY, Insets.EMPTY)));
//pane.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
//pane.setBackground(new Background(new BackgroundFill(Gauge.DARK_COLOR, CornerRadii.EMPTY, Insets.EMPTY)));
Scene scene = new Scene(pane);
stage.setTitle("Medusa");
stage.setScene(scene);
stage.show();
//gauge.setValue(105);
// Calculate number of nodes
calcNoOfNodes(pane);
System.out.println(noOfNodes + " Nodes in SceneGraph");
timer.start();
//gauge.getSections().get(0).setStart(10);
//gauge.getSections().get(0).setStop(90);
}
@Override public void stop() {
System.exit(0);
}
// ******************** Misc **********************************************
private static void calcNoOfNodes(Node node) {
if (node instanceof Parent) {
if (((Parent) node).getChildrenUnmodifiable().size() != 0) {
ObservableList<Node> tempChildren = ((Parent) node).getChildrenUnmodifiable();
noOfNodes += tempChildren.size();
for (Node n : tempChildren) { calcNoOfNodes(n); }
}
}
}
public static void main(String[] args) {
launch(args);
}
}
| Cosmetics
| src/main/java/eu/hansolo/medusa/Test.java | Cosmetics | <ide><path>rc/main/java/eu/hansolo/medusa/Test.java
<ide> //.locale(Locale.GERMANY)
<ide> //.numberFormat(numberFormat)
<ide> .title("Title")
<del> .unit("°C")
<add> .unit("\u00B0C")
<ide> .subTitle("SubTitle")
<ide> //.interactive(true)
<ide> //.onButtonPressed(o -> System.out.println("Button pressed"))
<ide>
<ide> Scene scene = new Scene(pane);
<ide>
<del>
<ide> stage.setTitle("Medusa");
<ide> stage.setScene(scene);
<ide> stage.show(); |
|
JavaScript | agpl-3.0 | 68e06303a4eaf68d56934d2151a90c70dd3ff5d5 | 0 | vatesfr/xo-web,lmcro/xo-web,lmcro/xo-web,vatesfr/xo-web,lmcro/xo-web | /* eslint-disable camelcase */
import concurrency from 'limit-concurrency-decorator'
import deferrable from 'golike-defer'
import fatfs from 'fatfs'
import synchronized from 'decorator-synchronized'
import tarStream from 'tar-stream'
import vmdkToVhd from 'xo-vmdk-to-vhd'
import {
cancelable,
catchPlus as pCatch,
defer,
fromEvent,
ignoreErrors,
} from 'promise-toolbox'
import { PassThrough } from 'stream'
import { forbiddenOperation } from 'xo-common/api-errors'
import { Xapi as XapiBase } from 'xen-api'
import {
every,
find,
filter,
flatten,
groupBy,
includes,
isEmpty,
omit,
startsWith,
uniq,
} from 'lodash'
import { satisfies as versionSatisfies } from 'semver'
import createSizeStream from '../size-stream'
import fatfsBuffer, { init as fatfsBufferInit } from '../fatfs-buffer'
import { mixin } from '../decorators'
import {
asyncMap,
camelToSnakeCase,
createRawObject,
ensureArray,
forEach,
isFunction,
map,
mapToArray,
pAll,
parseSize,
pDelay,
pFinally,
promisifyAll,
pSettle,
} from '../utils'
import mixins from './mixins'
import OTHER_CONFIG_TEMPLATE from './other-config-template'
import {
asBoolean,
asInteger,
debug,
extractOpaqueRef,
filterUndefineds,
getNamespaceForType,
getVmDisks,
canSrHaveNewVdiOfSize,
isVmHvm,
isVmRunning,
NULL_REF,
optional,
prepareXapiParam,
} from './utils'
// ===================================================================
const TAG_BASE_DELTA = 'xo:base_delta'
const TAG_COPY_SRC = 'xo:copy_of'
// ===================================================================
// FIXME: remove this work around when fixed, https://phabricator.babeljs.io/T2877
// export * from './utils'
require('lodash/assign')(module.exports, require('./utils'))
// VDI formats. (Raw is not available for delta vdi.)
export const VDI_FORMAT_VHD = 'vhd'
export const VDI_FORMAT_RAW = 'raw'
export const IPV4_CONFIG_MODES = ['None', 'DHCP', 'Static']
export const IPV6_CONFIG_MODES = ['None', 'DHCP', 'Static', 'Autoconf']
// ===================================================================
@mixin(mapToArray(mixins))
export default class Xapi extends XapiBase {
constructor (...args) {
super(...args)
// Patch getObject to resolve _xapiId property.
this.getObject = (getObject => (...args) => {
let tmp
if ((tmp = args[0]) != null && (tmp = tmp._xapiId) != null) {
args[0] = tmp
}
return getObject.apply(this, args)
})(this.getObject)
const genericWatchers = (this._genericWatchers = createRawObject())
const objectsWatchers = (this._objectWatchers = createRawObject())
const onAddOrUpdate = objects => {
forEach(objects, object => {
const { $id: id, $ref: ref } = object
// Run generic watchers.
for (const watcherId in genericWatchers) {
genericWatchers[watcherId](object)
}
// Watched object.
if (id in objectsWatchers) {
objectsWatchers[id].resolve(object)
delete objectsWatchers[id]
}
if (ref in objectsWatchers) {
objectsWatchers[ref].resolve(object)
delete objectsWatchers[ref]
}
})
}
this.objects.on('add', onAddOrUpdate)
this.objects.on('update', onAddOrUpdate)
}
call (...args) {
const fn = super.call
const loop = () =>
fn.apply(this, args)::pCatch(
{
code: 'TOO_MANY_PENDING_TASKS',
},
() => pDelay(5e3).then(loop)
)
return loop()
}
createTask (name = 'untitled task', description) {
return super.createTask(`[XO] ${name}`, description)
}
// =================================================================
_registerGenericWatcher (fn) {
const watchers = this._genericWatchers
const id = String(Math.random())
watchers[id] = fn
return () => {
delete watchers[id]
}
}
// Wait for an object to appear or to be updated.
//
// Predicate can be either an id, a UUID, an opaque reference or a
// function.
//
// TODO: implements a timeout.
_waitObject (predicate) {
if (isFunction(predicate)) {
const { promise, resolve } = defer()
const unregister = this._registerGenericWatcher(obj => {
if (predicate(obj)) {
unregister()
resolve(obj)
}
})
return promise
}
let watcher = this._objectWatchers[predicate]
if (!watcher) {
const { promise, resolve } = defer()
// Register the watcher.
watcher = this._objectWatchers[predicate] = {
promise,
resolve,
}
}
return watcher.promise
}
// Wait for an object to be in a given state.
//
// Faster than _waitObject() with a function.
_waitObjectState (idOrUuidOrRef, predicate) {
const object = this.getObject(idOrUuidOrRef, null)
if (object && predicate(object)) {
return object
}
const loop = () =>
this._waitObject(idOrUuidOrRef).then(
object => (predicate(object) ? object : loop())
)
return loop()
}
// Returns the objects if already presents or waits for it.
async _getOrWaitObject (idOrUuidOrRef) {
return (
this.getObject(idOrUuidOrRef, null) || this._waitObject(idOrUuidOrRef)
)
}
// =================================================================
_setObjectProperty (object, name, value) {
return this.call(
`${getNamespaceForType(object.$type)}.set_${camelToSnakeCase(name)}`,
object.$ref,
prepareXapiParam(value)
)
}
_setObjectProperties (object, props) {
const { $ref: ref, $type: type } = object
const namespace = getNamespaceForType(type)
// TODO: the thrown error should contain the name of the
// properties that failed to be set.
return Promise.all(
mapToArray(props, (value, name) => {
if (value != null) {
return this.call(
`${namespace}.set_${camelToSnakeCase(name)}`,
ref,
prepareXapiParam(value)
)
}
})
)::ignoreErrors()
}
async _updateObjectMapProperty (object, prop, values) {
const { $ref: ref, $type: type } = object
prop = camelToSnakeCase(prop)
const namespace = getNamespaceForType(type)
const add = `${namespace}.add_to_${prop}`
const remove = `${namespace}.remove_from_${prop}`
await Promise.all(
mapToArray(values, (value, name) => {
if (value !== undefined) {
name = camelToSnakeCase(name)
const removal = this.call(remove, ref, name)
return value === null
? removal
: removal
::ignoreErrors()
.then(() => this.call(add, ref, name, prepareXapiParam(value)))
}
})
)
}
async setHostProperties (id, { nameLabel, nameDescription }) {
await this._setObjectProperties(this.getObject(id), {
nameLabel,
nameDescription,
})
}
async setPoolProperties ({ autoPoweron, nameLabel, nameDescription }) {
const { pool } = this
await Promise.all([
this._setObjectProperties(pool, {
nameLabel,
nameDescription,
}),
autoPoweron != null &&
this._updateObjectMapProperty(pool, 'other_config', {
autoPoweron: autoPoweron ? 'true' : null,
}),
])
}
async setSrProperties (id, { nameLabel, nameDescription }) {
await this._setObjectProperties(this.getObject(id), {
nameLabel,
nameDescription,
})
}
async setNetworkProperties (
id,
{ nameLabel, nameDescription, defaultIsLocked }
) {
let defaultLockingMode
if (defaultIsLocked != null) {
defaultLockingMode = defaultIsLocked ? 'disabled' : 'unlocked'
}
await this._setObjectProperties(this.getObject(id), {
nameLabel,
nameDescription,
defaultLockingMode,
})
}
// =================================================================
async addTag (id, tag) {
const { $ref: ref, $type: type } = this.getObject(id)
const namespace = getNamespaceForType(type)
await this.call(`${namespace}.add_tags`, ref, tag)
}
async removeTag (id, tag) {
const { $ref: ref, $type: type } = this.getObject(id)
const namespace = getNamespaceForType(type)
await this.call(`${namespace}.remove_tags`, ref, tag)
}
// =================================================================
async setDefaultSr (srId) {
this._setObjectProperties(this.pool, {
default_SR: this.getObject(srId).$ref,
})
}
// =================================================================
async setPoolMaster (hostId) {
await this.call('pool.designate_new_master', this.getObject(hostId).$ref)
}
// =================================================================
async joinPool (masterAddress, masterUsername, masterPassword, force = false) {
await this.call(
force ? 'pool.join_force' : 'pool.join',
masterAddress,
masterUsername,
masterPassword
)
}
// =================================================================
async emergencyShutdownHost (hostId) {
const host = this.getObject(hostId)
const vms = host.$resident_VMs
debug(`Emergency shutdown: ${host.name_label}`)
await pSettle(
mapToArray(vms, vm => {
if (!vm.is_control_domain) {
return this.call('VM.suspend', vm.$ref)
}
})
)
await this.call('host.disable', host.$ref)
await this.call('host.shutdown', host.$ref)
}
// =================================================================
// Disable the host and evacuate all its VMs.
//
// If `force` is false and the evacuation failed, the host is re-
// enabled and the error is thrown.
async _clearHost ({ $ref: ref }, force) {
await this.call('host.disable', ref)
try {
await this.call('host.evacuate', ref)
} catch (error) {
if (!force) {
await this.call('host.enable', ref)
throw error
}
}
}
async disableHost (hostId) {
await this.call('host.disable', this.getObject(hostId).$ref)
}
async forgetHost (hostId) {
await this.call('host.destroy', this.getObject(hostId).$ref)
}
async ejectHostFromPool (hostId) {
await this.call('pool.eject', this.getObject(hostId).$ref)
}
async enableHost (hostId) {
await this.call('host.enable', this.getObject(hostId).$ref)
}
async powerOnHost (hostId) {
await this.call('host.power_on', this.getObject(hostId).$ref)
}
async rebootHost (hostId, force = false) {
const host = this.getObject(hostId)
await this._clearHost(host, force)
await this.call('host.reboot', host.$ref)
}
async restartHostAgent (hostId) {
await this.call('host.restart_agent', this.getObject(hostId).$ref)
}
async shutdownHost (hostId, force = false) {
const host = this.getObject(hostId)
await this._clearHost(host, force)
await this.call('host.shutdown', host.$ref)
}
// =================================================================
// Clone a VM: make a fast copy by fast copying each of its VDIs
// (using snapshots where possible) on the same SRs.
_cloneVm (vm, nameLabel = vm.name_label) {
debug(
`Cloning VM ${vm.name_label}${
nameLabel !== vm.name_label ? ` as ${nameLabel}` : ''
}`
)
return this.call('VM.clone', vm.$ref, nameLabel)
}
// Copy a VM: make a normal copy of a VM and all its VDIs.
//
// If a SR is specified, it will contains the copies of the VDIs,
// otherwise they will use the SRs they are on.
async _copyVm (vm, nameLabel = vm.name_label, sr = undefined) {
let snapshot
if (isVmRunning(vm)) {
snapshot = await this._snapshotVm(vm)
}
debug(
`Copying VM ${vm.name_label}${
nameLabel !== vm.name_label ? ` as ${nameLabel}` : ''
}${sr ? ` on ${sr.name_label}` : ''}`
)
try {
return await this.call(
'VM.copy',
snapshot ? snapshot.$ref : vm.$ref,
nameLabel,
sr ? sr.$ref : ''
)
} finally {
if (snapshot) {
await this._deleteVm(snapshot)
}
}
}
async cloneVm (vmId, { nameLabel = undefined, fast = true } = {}) {
const vm = this.getObject(vmId)
const cloneRef = await (fast
? this._cloneVm(vm, nameLabel)
: this._copyVm(vm, nameLabel))
return /* await */ this._getOrWaitObject(cloneRef)
}
async copyVm (vmId, srId, { nameLabel = undefined } = {}) {
return /* await */ this._getOrWaitObject(
await this._copyVm(this.getObject(vmId), nameLabel, this.getObject(srId))
)
}
async remoteCopyVm (
vmId,
targetXapi,
targetSrId,
{ compress = true, nameLabel = undefined } = {}
) {
// Fall back on local copy if possible.
if (targetXapi === this) {
return {
vm: await this.copyVm(vmId, targetSrId, { nameLabel }),
}
}
const sr = targetXapi.getObject(targetSrId)
let stream = await this.exportVm(vmId, {
compress,
})
const sizeStream = createSizeStream()
stream = stream.pipe(sizeStream)
const onVmCreation =
nameLabel !== undefined
? vm =>
targetXapi._setObjectProperties(vm, {
nameLabel,
})
: null
const vm = await targetXapi._getOrWaitObject(
await targetXapi._importVm(stream, sr, onVmCreation)
)
return {
size: sizeStream.size,
vm,
}
}
// Low level create VM.
_createVmRecord ({
actions_after_crash,
actions_after_reboot,
actions_after_shutdown,
affinity,
// appliance,
blocked_operations,
generation_id,
ha_always_run,
ha_restart_priority,
has_vendor_device = false, // Avoid issue with some Dundee builds.
hardware_platform_version,
HVM_boot_params,
HVM_boot_policy,
HVM_shadow_multiplier,
is_a_template,
memory_dynamic_max,
memory_dynamic_min,
memory_static_max,
memory_static_min,
name_description,
name_label,
order,
other_config,
PCI_bus,
platform,
protection_policy,
PV_args,
PV_bootloader,
PV_bootloader_args,
PV_kernel,
PV_legacy_args,
PV_ramdisk,
recommendations,
shutdown_delay,
start_delay,
// suspend_SR,
tags,
user_version,
VCPUs_at_startup,
VCPUs_max,
VCPUs_params,
version,
xenstore_data,
}) {
debug(`Creating VM ${name_label}`)
return this.call(
'VM.create',
filterUndefineds({
actions_after_crash,
actions_after_reboot,
actions_after_shutdown,
affinity: affinity == null ? NULL_REF : affinity,
HVM_boot_params,
HVM_boot_policy,
is_a_template: asBoolean(is_a_template),
memory_dynamic_max: asInteger(memory_dynamic_max),
memory_dynamic_min: asInteger(memory_dynamic_min),
memory_static_max: asInteger(memory_static_max),
memory_static_min: asInteger(memory_static_min),
other_config,
PCI_bus,
platform,
PV_args,
PV_bootloader,
PV_bootloader_args,
PV_kernel,
PV_legacy_args,
PV_ramdisk,
recommendations,
user_version: asInteger(user_version),
VCPUs_at_startup: asInteger(VCPUs_at_startup),
VCPUs_max: asInteger(VCPUs_max),
VCPUs_params,
// Optional fields.
blocked_operations,
generation_id,
ha_always_run: asBoolean(ha_always_run),
ha_restart_priority,
has_vendor_device,
hardware_platform_version: optional(
hardware_platform_version,
asInteger
),
// HVM_shadow_multiplier: asFloat(HVM_shadow_multiplier), // FIXME: does not work FIELD_TYPE_ERROR(hVM_shadow_multiplier)
name_description,
name_label,
order: optional(order, asInteger),
protection_policy,
shutdown_delay: asInteger(shutdown_delay),
start_delay: asInteger(start_delay),
tags,
version: asInteger(version),
xenstore_data,
})
)
}
async _deleteVm (vm, deleteDisks = true, force = false) {
debug(`Deleting VM ${vm.name_label}`)
const { $ref } = vm
// It is necessary for suspended VMs to be shut down
// to be able to delete their VDIs.
if (vm.power_state !== 'Halted') {
await this.call('VM.hard_shutdown', $ref)
}
if (force) {
await this._updateObjectMapProperty(vm, 'blocked_operations', {
destroy: null,
})
}
// ensure the vm record is up-to-date
vm = await this.barrier('VM', $ref)
return Promise.all([
this.call('VM.destroy', $ref),
asyncMap(vm.$snapshots, snapshot =>
this._deleteVm(snapshot)
)::ignoreErrors(),
deleteDisks &&
asyncMap(getVmDisks(vm), ({ $ref: vdiRef }) => {
let onFailure = () => {
onFailure = vdi => {
console.error(
`cannot delete VDI ${vdi.name_label} (from VM ${vm.name_label})`
)
forEach(vdi.$VBDs, vbd => {
if (vbd.VM !== $ref) {
const vm = vbd.$VM
console.error('- %s (%s)', vm.name_label, vm.uuid)
}
})
}
// maybe the control domain has not yet unmounted the VDI,
// check and retry after 5 seconds
return pDelay(5e3).then(test)
}
const test = () => {
const vdi = this.getObjectByRef(vdiRef)
return (
// Only remove VBDs not attached to other VMs.
vdi.VBDs.length < 2 || every(vdi.$VBDs, vbd => vbd.VM === $ref)
? this._deleteVdi(vdi)
: onFailure(vdi)
)
}
return test()
})::ignoreErrors(),
])
}
async deleteVm (vmId, deleteDisks, force) {
return /* await */ this._deleteVm(this.getObject(vmId), deleteDisks, force)
}
getVmConsole (vmId) {
const vm = this.getObject(vmId)
const console = find(vm.$consoles, { protocol: 'rfb' })
if (!console) {
throw new Error('no RFB console found')
}
return console
}
// Returns a stream to the exported VM.
@concurrency(2, stream => stream.then(stream => fromEvent(stream, 'end')))
@cancelable
async exportVm ($cancelToken, vmId, { compress = true } = {}) {
const vm = this.getObject(vmId)
let host
let snapshotRef
if (isVmRunning(vm)) {
host = vm.$resident_on
snapshotRef = (await this._snapshotVm(
$cancelToken,
vm,
`[XO Export] ${vm.name_label}`
)).$ref
}
const promise = this.getResource($cancelToken, '/export/', {
host,
query: {
ref: snapshotRef || vm.$ref,
use_compression: compress ? 'true' : 'false',
},
task: this.createTask('VM export', vm.name_label),
})
if (snapshotRef !== undefined) {
promise.then(_ =>
_.task::pFinally(() => this.deleteVm(snapshotRef)::ignoreErrors())
)
}
return promise
}
_assertHealthyVdiChain (vdi, cache) {
if (vdi == null) {
return
}
if (!vdi.managed) {
const { SR } = vdi
let childrenMap = cache[SR]
if (childrenMap === undefined) {
childrenMap = cache[SR] = groupBy(
vdi.$SR.$VDIs,
_ => _.sm_config['vhd-parent']
)
}
// an unmanaged VDI should not have exactly one child: they
// should coalesce
const children = childrenMap[vdi.uuid]
if (
children.length === 1 &&
!children[0].managed // some SRs do not coalesce the leaf
) {
throw new Error('unhealthy VDI chain')
}
}
this._assertHealthyVdiChain(
this.getObjectByUuid(vdi.sm_config['vhd-parent'], null),
cache
)
}
_assertHealthyVdiChains (vm) {
const cache = createRawObject()
forEach(vm.$VBDs, ({ $VDI }) => {
this._assertHealthyVdiChain($VDI, cache)
})
}
// Create a snapshot of the VM and returns a delta export object.
@cancelable
@deferrable
async exportDeltaVm (
$defer,
$cancelToken,
vmId,
baseVmId = undefined,
{
bypassVdiChainsCheck = false,
// Contains a vdi.$id set of vmId.
fullVdisRequired = [],
disableBaseTags = false,
snapshotNameLabel = undefined,
} = {}
) {
if (!bypassVdiChainsCheck) {
this._assertHealthyVdiChains(this.getObject(vmId))
}
const vm = await this.snapshotVm(vmId)
$defer.onFailure(() => this._deleteVm(vm))
if (snapshotNameLabel) {
;this._setObjectProperties(vm, {
nameLabel: snapshotNameLabel,
})::ignoreErrors()
}
const baseVm = baseVmId && this.getObject(baseVmId)
// refs of VM's VDIs → base's VDIs.
const baseVdis = {}
baseVm &&
forEach(baseVm.$VBDs, vbd => {
let vdi, snapshotOf
if (
(vdi = vbd.$VDI) &&
(snapshotOf = vdi.$snapshot_of) &&
!find(fullVdisRequired, id => snapshotOf.$id === id)
) {
baseVdis[vdi.snapshot_of] = vdi
}
})
const streams = {}
const vdis = {}
const vbds = {}
forEach(vm.$VBDs, vbd => {
let vdi
if (vbd.type !== 'Disk' || !(vdi = vbd.$VDI)) {
// Ignore this VBD.
return
}
// If the VDI name start with `[NOBAK]`, do not export it.
if (startsWith(vdi.name_label, '[NOBAK]')) {
// FIXME: find a way to not create the VDI snapshot in the
// first time.
//
// The snapshot must not exist otherwise it could break the
// next export.
;this._deleteVdi(vdi)::ignoreErrors()
return
}
vbds[vbd.$ref] = vbd
const vdiRef = vdi.$ref
if (vdiRef in vdis) {
// This VDI has already been managed.
return
}
// Look for a snapshot of this vdi in the base VM.
const baseVdi = baseVdis[vdi.snapshot_of]
vdis[vdiRef] =
baseVdi && !disableBaseTags
? {
...vdi,
other_config: {
...vdi.other_config,
[TAG_BASE_DELTA]: baseVdi.uuid,
},
$SR$uuid: vdi.$SR.uuid,
}
: {
...vdi,
$SR$uuid: vdi.$SR.uuid,
}
streams[`${vdiRef}.vhd`] = () =>
this._exportVdi($cancelToken, vdi, baseVdi, VDI_FORMAT_VHD)
})
const vifs = {}
forEach(vm.$VIFs, vif => {
vifs[vif.$ref] = {
...vif,
$network$uuid: vif.$network.uuid,
}
})
return Object.defineProperty(
{
version: '1.1.0',
vbds,
vdis,
vifs,
vm: {
...vm,
other_config:
baseVm && !disableBaseTags
? {
...vm.other_config,
[TAG_BASE_DELTA]: baseVm.uuid,
}
: omit(vm.other_config, TAG_BASE_DELTA),
},
},
'streams',
{
value: streams,
}
)
}
@deferrable
async importDeltaVm (
$defer,
delta,
{
deleteBase = false,
disableStartAfterImport = true,
mapVdisSrs = {},
name_label = delta.vm.name_label,
srId = this.pool.default_SR,
} = {}
) {
const { version } = delta
if (!versionSatisfies(version, '^1')) {
throw new Error(`Unsupported delta backup version: ${version}`)
}
const remoteBaseVmUuid = delta.vm.other_config[TAG_BASE_DELTA]
let baseVm
if (remoteBaseVmUuid) {
baseVm = find(
this.objects.all,
obj =>
(obj = obj.other_config) && obj[TAG_COPY_SRC] === remoteBaseVmUuid
)
if (!baseVm) {
throw new Error('could not find the base VM')
}
}
const baseVdis = {}
baseVm &&
forEach(baseVm.$VBDs, vbd => {
baseVdis[vbd.VDI] = vbd.$VDI
})
// 1. Create the VMs.
const vm = await this._getOrWaitObject(
await this._createVmRecord({
...delta.vm,
affinity: null,
is_a_template: false,
})
)
$defer.onFailure(() => this._deleteVm(vm))
await Promise.all([
this._setObjectProperties(vm, {
name_label: `[Importing…] ${name_label}`,
}),
this._updateObjectMapProperty(vm, 'blocked_operations', {
start: 'Importing…',
}),
this._updateObjectMapProperty(vm, 'other_config', {
[TAG_COPY_SRC]: delta.vm.uuid,
}),
])
// 2. Delete all VBDs which may have been created by the import.
await asyncMap(vm.$VBDs, vbd => this._deleteVbd(vbd))::ignoreErrors()
// 3. Create VDIs.
const newVdis = await map(delta.vdis, async vdi => {
const remoteBaseVdiUuid = vdi.other_config[TAG_BASE_DELTA]
if (!remoteBaseVdiUuid) {
const newVdi = await this.createVdi({
...vdi,
other_config: {
...vdi.other_config,
[TAG_BASE_DELTA]: undefined,
[TAG_COPY_SRC]: vdi.uuid,
},
sr: mapVdisSrs[vdi.uuid] || srId,
})
$defer.onFailure(() => this._deleteVdi(newVdi))
return newVdi
}
const baseVdi = find(
baseVdis,
vdi => vdi.other_config[TAG_COPY_SRC] === remoteBaseVdiUuid
)
if (!baseVdi) {
throw new Error(`missing base VDI (copy of ${remoteBaseVdiUuid})`)
}
const newVdi = await this._getOrWaitObject(await this._cloneVdi(baseVdi))
$defer.onFailure(() => this._deleteVdi(newVdi))
await this._updateObjectMapProperty(newVdi, 'other_config', {
[TAG_COPY_SRC]: vdi.uuid,
})
return newVdi
})::pAll()
const networksOnPoolMasterByDevice = {}
let defaultNetwork
forEach(this.pool.$master.$PIFs, pif => {
defaultNetwork = networksOnPoolMasterByDevice[pif.device] = pif.$network
})
const { streams } = delta
let transferSize = 0
await Promise.all([
// Create VBDs.
asyncMap(delta.vbds, vbd =>
this.createVbd({
...vbd,
vdi: newVdis[vbd.VDI],
vm,
})
),
// Import VDI contents.
asyncMap(newVdis, async (vdi, id) => {
for (let stream of ensureArray(streams[`${id}.vhd`])) {
if (typeof stream === 'function') {
stream = await stream()
}
const sizeStream = stream
.pipe(createSizeStream())
.once('finish', () => {
transferSize += sizeStream.size
})
stream.task = sizeStream.task
await this._importVdiContent(vdi, sizeStream, VDI_FORMAT_VHD)
}
}),
// Wait for VDI export tasks (if any) termination.
asyncMap(streams, stream => stream.task),
// Create VIFs.
asyncMap(delta.vifs, vif => {
const network =
(vif.$network$uuid && this.getObject(vif.$network$uuid, null)) ||
networksOnPoolMasterByDevice[vif.device] ||
defaultNetwork
if (network) {
return this._createVif(vm, network, vif)
}
}),
])
if (deleteBase && baseVm) {
;this._deleteVm(baseVm)::ignoreErrors()
}
await Promise.all([
this._setObjectProperties(vm, {
name_label,
}),
// FIXME: move
this._updateObjectMapProperty(vm, 'blocked_operations', {
start: disableStartAfterImport
? 'Do not start this VM, clone it if you want to use it.'
: null,
}),
])
return { transferSize, vm }
}
async _migrateVmWithStorageMotion (
vm,
hostXapi,
host,
{
migrationNetwork = find(host.$PIFs, pif => pif.management).$network, // TODO: handle not found
sr,
mapVdisSrs,
mapVifsNetworks,
}
) {
// VDIs/SRs mapping
const vdis = {}
const defaultSr = host.$pool.$default_SR
for (const vbd of vm.$VBDs) {
const vdi = vbd.$VDI
if (vbd.type === 'Disk') {
vdis[vdi.$ref] =
mapVdisSrs && mapVdisSrs[vdi.$id]
? hostXapi.getObject(mapVdisSrs[vdi.$id]).$ref
: sr !== undefined ? hostXapi.getObject(sr).$ref : defaultSr.$ref // Will error if there are no default SR.
}
}
// VIFs/Networks mapping
const vifsMap = {}
if (vm.$pool !== host.$pool) {
const defaultNetworkRef = find(host.$PIFs, pif => pif.management).$network
.$ref
for (const vif of vm.$VIFs) {
vifsMap[vif.$ref] =
mapVifsNetworks && mapVifsNetworks[vif.$id]
? hostXapi.getObject(mapVifsNetworks[vif.$id]).$ref
: defaultNetworkRef
}
}
const token = await hostXapi.call(
'host.migrate_receive',
host.$ref,
migrationNetwork.$ref,
{}
)
const loop = () =>
this.call(
'VM.migrate_send',
vm.$ref,
token,
true, // Live migration.
vdis,
vifsMap,
{
force: 'true',
}
)::pCatch({ code: 'TOO_MANY_STORAGE_MIGRATES' }, () =>
pDelay(1e4).then(loop)
)
return loop()
}
@synchronized
_callInstallationPlugin (hostRef, vdi) {
return this.call(
'host.call_plugin',
hostRef,
'install-supp-pack',
'install',
{ vdi }
).catch(error => {
if (error.code !== 'XENAPI_PLUGIN_FAILURE') {
console.warn('_callInstallationPlugin', error)
throw error
}
})
}
@deferrable
async installSupplementalPack ($defer, stream, { hostId }) {
if (!stream.length) {
throw new Error('stream must have a length')
}
const vdi = await this.createTemporaryVdiOnHost(
stream,
hostId,
'[XO] Supplemental pack ISO',
'small temporary VDI to store a supplemental pack ISO'
)
$defer(() => this._deleteVdi(vdi))
await this._callInstallationPlugin(this.getObject(hostId).$ref, vdi.uuid)
}
@deferrable
async installSupplementalPackOnAllHosts ($defer, stream) {
if (!stream.length) {
throw new Error('stream must have a length')
}
const isSrAvailable = sr =>
sr &&
sr.content_type === 'user' &&
sr.physical_size - sr.physical_utilisation >= stream.length
const hosts = filter(this.objects.all, { $type: 'host' })
const sr = this.findAvailableSharedSr(stream.length)
// Shared SR available: create only 1 VDI for all the installations
if (sr) {
const vdi = await this.createTemporaryVdiOnSr(
stream,
sr,
'[XO] Supplemental pack ISO',
'small temporary VDI to store a supplemental pack ISO'
)
$defer(() => this._deleteVdi(vdi))
// Install pack sequentially to prevent concurrent access to the unique VDI
for (const host of hosts) {
await this._callInstallationPlugin(host.$ref, vdi.uuid)
}
return
}
// No shared SR available: find an available local SR on each host
return Promise.all(
mapToArray(
hosts,
deferrable(async ($defer, host) => {
// pipe stream synchronously to several PassThroughs to be able to pipe them asynchronously later
const pt = stream.pipe(new PassThrough())
pt.length = stream.length
const sr = find(mapToArray(host.$PBDs, '$SR'), isSrAvailable)
if (!sr) {
throw new Error('no SR available to store installation file')
}
const vdi = await this.createTemporaryVdiOnSr(
pt,
sr,
'[XO] Supplemental pack ISO',
'small temporary VDI to store a supplemental pack ISO'
)
$defer(() => this._deleteVdi(vdi))
await this._callInstallationPlugin(host.$ref, vdi.uuid)
})
)
)
}
@cancelable
async _importVm ($cancelToken, stream, sr, onVmCreation = undefined) {
const taskRef = await this.createTask('VM import')
const query = {}
let host
if (sr != null) {
host = sr.$PBDs[0].$host
query.sr_id = sr.$ref
}
if (onVmCreation != null) {
;this._waitObject(
obj =>
obj != null &&
obj.current_operations != null &&
taskRef in obj.current_operations
)
.then(onVmCreation)
::ignoreErrors()
}
const vmRef = await this.putResource($cancelToken, stream, '/import/', {
host,
query,
task: taskRef,
}).then(extractOpaqueRef)
return vmRef
}
@deferrable
async _importOvaVm (
$defer,
stream,
{ descriptionLabel, disks, memory, nameLabel, networks, nCpus },
sr
) {
// 1. Create VM.
const vm = await this._getOrWaitObject(
await this._createVmRecord({
...OTHER_CONFIG_TEMPLATE,
memory_dynamic_max: memory,
memory_dynamic_min: memory,
memory_static_max: memory,
name_description: descriptionLabel,
name_label: nameLabel,
VCPUs_at_startup: nCpus,
VCPUs_max: nCpus,
})
)
$defer.onFailure(() => this._deleteVm(vm))
// Disable start and change the VM name label during import.
await Promise.all([
this.addForbiddenOperationToVm(
vm.$id,
'start',
'OVA import in progress...'
),
this._setObjectProperties(vm, {
name_label: `[Importing...] ${nameLabel}`,
}),
])
// 2. Create VDIs & Vifs.
const vdis = {}
const vifDevices = await this.call('VM.get_allowed_VIF_devices', vm.$ref)
await Promise.all(
map(disks, async disk => {
const vdi = (vdis[disk.path] = await this.createVdi({
name_description: disk.descriptionLabel,
name_label: disk.nameLabel,
size: disk.capacity,
sr: sr.$ref,
}))
$defer.onFailure(() => this._deleteVdi(vdi))
return this.createVbd({
userdevice: disk.position,
vdi,
vm,
})
}).concat(
map(networks, (networkId, i) =>
this._createVif(vm, this.getObject(networkId), {
device: vifDevices[i],
})
)
)
)
// 3. Import VDIs contents.
await new Promise((resolve, reject) => {
const extract = tarStream.extract()
stream.on('error', reject)
extract.on('finish', resolve)
extract.on('error', reject)
extract.on('entry', async (entry, stream, cb) => {
// Not a disk to import.
const vdi = vdis[entry.name]
if (!vdi) {
stream.on('end', cb)
stream.resume()
return
}
const vhdStream = await vmdkToVhd(stream)
await this._importVdiContent(vdi, vhdStream, VDI_FORMAT_RAW)
// See: https://github.com/mafintosh/tar-stream#extracting
// No import parallelization.
cb()
})
stream.pipe(extract)
})
// Enable start and restore the VM name label after import.
await Promise.all([
this.removeForbiddenOperationFromVm(vm.$id, 'start'),
this._setObjectProperties(vm, { name_label: nameLabel }),
])
return vm
}
// TODO: an XVA can contain multiple VMs
async importVm (stream, { data, srId, type = 'xva' } = {}) {
const sr = srId && this.getObject(srId)
if (type === 'xva') {
return /* await */ this._getOrWaitObject(await this._importVm(stream, sr))
}
if (type === 'ova') {
return this._getOrWaitObject(await this._importOvaVm(stream, data, sr))
}
throw new Error(`unsupported type: '${type}'`)
}
async migrateVm (
vmId,
hostXapi,
hostId,
{ sr, migrationNetworkId, mapVifsNetworks, mapVdisSrs } = {}
) {
const vm = this.getObject(vmId)
const host = hostXapi.getObject(hostId)
const accrossPools = vm.$pool !== host.$pool
const useStorageMotion =
accrossPools ||
sr !== undefined ||
migrationNetworkId !== undefined ||
!isEmpty(mapVifsNetworks) ||
!isEmpty(mapVdisSrs)
if (useStorageMotion) {
await this._migrateVmWithStorageMotion(vm, hostXapi, host, {
migrationNetwork:
migrationNetworkId && hostXapi.getObject(migrationNetworkId),
sr,
mapVdisSrs,
mapVifsNetworks,
})
} else {
try {
await this.call('VM.pool_migrate', vm.$ref, host.$ref, {
force: 'true',
})
} catch (error) {
if (error.code !== 'VM_REQUIRES_SR') {
throw error
}
// Retry using motion storage.
await this._migrateVmWithStorageMotion(vm, hostXapi, host, {})
}
}
}
@synchronized() // like @concurrency(1) but more efficient
@cancelable
async _snapshotVm ($cancelToken, vm, nameLabel = vm.name_label) {
debug(
`Snapshotting VM ${vm.name_label}${
nameLabel !== vm.name_label ? ` as ${nameLabel}` : ''
}`
)
let ref
try {
ref = await this.callAsync(
$cancelToken,
'VM.snapshot_with_quiesce',
vm.$ref,
nameLabel
)
this.addTag(ref, 'quiesce')::ignoreErrors()
await this._waitObjectState(ref, vm => includes(vm.tags, 'quiesce'))
} catch (error) {
const { code } = error
if (
code !== 'VM_SNAPSHOT_WITH_QUIESCE_NOT_SUPPORTED' &&
// quiesce only work on a running VM
code !== 'VM_BAD_POWER_STATE' &&
// quiesce failed, fallback on standard snapshot
// TODO: emit warning
code !== 'VM_SNAPSHOT_WITH_QUIESCE_FAILED'
) {
throw error
}
ref = await this.callAsync(
$cancelToken,
'VM.snapshot',
vm.$ref,
nameLabel
)
}
// Convert the template to a VM and wait to have receive the up-
// to-date object.
const [, snapshot] = await Promise.all([
this.call('VM.set_is_a_template', ref, false),
this._waitObjectState(ref, snapshot => !snapshot.is_a_template),
])
return snapshot
}
async snapshotVm (vmId, nameLabel = undefined) {
return /* await */ this._snapshotVm(this.getObject(vmId), nameLabel)
}
async setVcpuWeight (vmId, weight) {
weight = weight || null // Take all falsy values as a removal (0 included)
const vm = this.getObject(vmId)
await this._updateObjectMapProperty(vm, 'VCPUs_params', { weight })
}
async _startVm (vm, force) {
debug(`Starting VM ${vm.name_label}`)
if (force) {
await this._updateObjectMapProperty(vm, 'blocked_operations', {
start: null,
})
}
return this.call(
'VM.start',
vm.$ref,
false, // Start paused?
false // Skip pre-boot checks?
)
}
async startVm (vmId, force) {
try {
await this._startVm(this.getObject(vmId), force)
} catch (e) {
if (e.code === 'OPERATION_BLOCKED') {
throw forbiddenOperation('Start', e.params[1])
}
if (e.code === 'VM_BAD_POWER_STATE') {
return this.resumeVm(vmId)
}
throw e
}
}
async startVmOnCd (vmId) {
const vm = this.getObject(vmId)
if (isVmHvm(vm)) {
const { order } = vm.HVM_boot_params
await this._updateObjectMapProperty(vm, 'HVM_boot_params', {
order: 'd',
})
try {
await this._startVm(vm)
} finally {
await this._updateObjectMapProperty(vm, 'HVM_boot_params', {
order,
})
}
} else {
// Find the original template by name (*sigh*).
const templateNameLabel = vm.other_config['base_template_name']
const template =
templateNameLabel &&
find(
this.objects.all,
obj =>
obj.$type === 'vm' &&
obj.is_a_template &&
obj.name_label === templateNameLabel
)
const bootloader = vm.PV_bootloader
const bootables = []
try {
const promises = []
const cdDrive = this._getVmCdDrive(vm)
forEach(vm.$VBDs, vbd => {
promises.push(
this._setObjectProperties(vbd, {
bootable: vbd === cdDrive,
})
)
bootables.push([vbd, Boolean(vbd.bootable)])
})
promises.push(
this._setObjectProperties(vm, {
PV_bootloader: 'eliloader',
}),
this._updateObjectMapProperty(vm, 'other_config', {
'install-distro':
template && template.other_config['install-distro'],
'install-repository': 'cdrom',
})
)
await Promise.all(promises)
await this._startVm(vm)
} finally {
;this._setObjectProperties(vm, {
PV_bootloader: bootloader,
})::ignoreErrors()
forEach(bootables, ([vbd, bootable]) => {
;this._setObjectProperties(vbd, { bootable })::ignoreErrors()
})
}
}
}
// vm_operations: http://xapi-project.github.io/xen-api/classes/vm.html
async addForbiddenOperationToVm (vmId, operation, reason) {
await this.call(
'VM.add_to_blocked_operations',
this.getObject(vmId).$ref,
operation,
`[XO] ${reason}`
)
}
async removeForbiddenOperationFromVm (vmId, operation) {
await this.call(
'VM.remove_from_blocked_operations',
this.getObject(vmId).$ref,
operation
)
}
// =================================================================
async createVbd ({
bootable = false,
other_config = {},
qos_algorithm_params = {},
qos_algorithm_type = '',
type = 'Disk',
unpluggable = false,
userdevice,
VDI,
VM,
vdi = VDI,
empty = vdi === undefined,
mode = type === 'Disk' ? 'RW' : 'RO',
vm = VM,
}) {
vdi = this.getObject(vdi)
vm = this.getObject(vm)
debug(`Creating VBD for VDI ${vdi.name_label} on VM ${vm.name_label}`)
if (userdevice == null) {
const allowed = await this.call('VM.get_allowed_VBD_devices', vm.$ref)
const { length } = allowed
if (length === 0) {
throw new Error('no allowed VBD devices')
}
if (type === 'CD') {
// Choose position 3 if allowed.
userdevice = includes(allowed, '3') ? '3' : allowed[0]
} else {
userdevice = allowed[0]
// Avoid userdevice 3 if possible.
if (userdevice === '3' && length > 1) {
userdevice = allowed[1]
}
}
}
// By default a VBD is unpluggable.
const vbdRef = await this.call('VBD.create', {
bootable: Boolean(bootable),
empty: Boolean(empty),
mode,
other_config,
qos_algorithm_params,
qos_algorithm_type,
type,
unpluggable: Boolean(unpluggable),
userdevice,
VDI: vdi && vdi.$ref,
VM: vm.$ref,
})
if (isVmRunning(vm)) {
await this.call('VBD.plug', vbdRef)
}
}
_cloneVdi (vdi) {
debug(`Cloning VDI ${vdi.name_label}`)
return this.call('VDI.clone', vdi.$ref)
}
async createVdi ({
name_description,
name_label,
other_config = {},
read_only = false,
sharable = false,
sm_config,
SR,
tags,
type = 'user',
virtual_size,
xenstore_data,
size,
sr = SR !== undefined && SR !== NULL_REF ? SR : this.pool.default_SR,
}) {
sr = this.getObject(sr)
debug(`Creating VDI ${name_label} on ${sr.name_label}`)
return this._getOrWaitObject(
await this.call('VDI.create', {
name_description,
name_label,
other_config,
read_only: Boolean(read_only),
sharable: Boolean(sharable),
sm_config,
SR: sr.$ref,
tags,
type,
virtual_size: size !== undefined ? parseSize(size) : virtual_size,
xenstore_data,
})
)
}
async moveVdi (vdiId, srId) {
const vdi = this.getObject(vdiId)
const sr = this.getObject(srId)
if (vdi.SR === sr.$ref) {
return // nothing to do
}
debug(
`Moving VDI ${vdi.name_label} from ${vdi.$SR.name_label} to ${
sr.name_label
}`
)
try {
await this.call('VDI.pool_migrate', vdi.$ref, sr.$ref, {})
} catch (error) {
const { code } = error
if (
code !== 'LICENCE_RESTRICTION' &&
code !== 'VDI_NEEDS_VM_FOR_MIGRATE'
) {
throw error
}
const newVdi = await this.barrier(
await this.call('VDI.copy', vdi.$ref, sr.$ref)
)
await asyncMap(vdi.$VBDs, vbd =>
Promise.all([
this.call('VBD.destroy', vbd.$ref),
this.createVbd({
...vbd,
vdi: newVdi,
}),
])
)
await this._deleteVdi(vdi)
}
}
// TODO: check whether the VDI is attached.
async _deleteVdi (vdi) {
debug(`Deleting VDI ${vdi.name_label}`)
await this.call('VDI.destroy', vdi.$ref)
}
_resizeVdi (vdi, size) {
debug(`Resizing VDI ${vdi.name_label} from ${vdi.virtual_size} to ${size}`)
return this.call('VDI.resize', vdi.$ref, size)
}
_getVmCdDrive (vm) {
for (const vbd of vm.$VBDs) {
if (vbd.type === 'CD') {
return vbd
}
}
}
async _ejectCdFromVm (vm) {
const cdDrive = this._getVmCdDrive(vm)
if (cdDrive) {
await this.call('VBD.eject', cdDrive.$ref)
}
}
async _insertCdIntoVm (cd, vm, { bootable = false, force = false } = {}) {
const cdDrive = await this._getVmCdDrive(vm)
if (cdDrive) {
try {
await this.call('VBD.insert', cdDrive.$ref, cd.$ref)
} catch (error) {
if (!force || error.code !== 'VBD_NOT_EMPTY') {
throw error
}
await this.call('VBD.eject', cdDrive.$ref)::ignoreErrors()
// Retry.
await this.call('VBD.insert', cdDrive.$ref, cd.$ref)
}
if (bootable !== Boolean(cdDrive.bootable)) {
await this._setObjectProperties(cdDrive, { bootable })
}
} else {
await this.createVbd({
bootable,
type: 'CD',
vdi: cd,
vm,
})
}
}
async connectVbd (vbdId) {
await this.call('VBD.plug', vbdId)
}
async _disconnectVbd (vbd) {
// TODO: check if VBD is attached before
try {
await this.call('VBD.unplug_force', vbd.$ref)
} catch (error) {
if (error.code === 'VBD_NOT_UNPLUGGABLE') {
await this.call('VBD.set_unpluggable', vbd.$ref, true)
return this.call('VBD.unplug_force', vbd.$ref)
}
}
}
async disconnectVbd (vbdId) {
await this._disconnectVbd(this.getObject(vbdId))
}
async _deleteVbd (vbd) {
await this._disconnectVbd(vbd)::ignoreErrors()
await this.call('VBD.destroy', vbd.$ref)
}
deleteVbd (vbdId) {
return this._deleteVbd(this.getObject(vbdId))
}
// TODO: remove when no longer used.
async destroyVbdsFromVm (vmId) {
await Promise.all(
mapToArray(this.getObject(vmId).$VBDs, async vbd => {
await this.disconnectVbd(vbd.$ref)::ignoreErrors()
return this.call('VBD.destroy', vbd.$ref)
})
)
}
async deleteVdi (vdiId) {
await this._deleteVdi(this.getObject(vdiId))
}
async resizeVdi (vdiId, size) {
await this._resizeVdi(this.getObject(vdiId), size)
}
async ejectCdFromVm (vmId) {
await this._ejectCdFromVm(this.getObject(vmId))
}
async insertCdIntoVm (cdId, vmId, opts = undefined) {
await this._insertCdIntoVm(this.getObject(cdId), this.getObject(vmId), opts)
}
// -----------------------------------------------------------------
async snapshotVdi (vdiId, nameLabel) {
const vdi = this.getObject(vdiId)
const snap = await this._getOrWaitObject(
await this.call('VDI.snapshot', vdi.$ref)
)
if (nameLabel) {
await this.call('VDI.set_name_label', snap.$ref, nameLabel)
}
return snap
}
@concurrency(12, stream => stream.then(stream => fromEvent(stream, 'end')))
@cancelable
_exportVdi ($cancelToken, vdi, base, format = VDI_FORMAT_VHD) {
const host = vdi.$SR.$PBDs[0].$host
const query = {
format,
vdi: vdi.$ref,
}
if (base) {
query.base = base.$ref
}
debug(
`exporting VDI ${vdi.name_label}${
base ? ` (from base ${vdi.name_label})` : ''
}`
)
return this.getResource($cancelToken, '/export_raw_vdi/', {
host,
query,
task: this.createTask('VDI Export', vdi.name_label),
})
}
// -----------------------------------------------------------------
async _importVdiContent (vdi, body, format = VDI_FORMAT_VHD) {
const pbd = find(vdi.$SR.$PBDs, 'currently_attached')
if (pbd === undefined) {
throw new Error('no valid PBDs found')
}
await Promise.all([
body.task,
body.checksumVerified,
this.putResource(body, '/import_raw_vdi/', {
host: pbd.host,
query: {
format,
vdi: vdi.$ref,
},
task: this.createTask('VDI Content Import', vdi.name_label),
}),
])
}
importVdiContent (vdiId, body, { format } = {}) {
return this._importVdiContent(this.getObject(vdiId), body, format)
}
// =================================================================
async _createVif (
vm,
network,
{
mac = '',
position = undefined,
currently_attached = true,
device = position != null ? String(position) : undefined,
ipv4_allowed = undefined,
ipv6_allowed = undefined,
locking_mode = undefined,
MAC = mac,
other_config = {},
qos_algorithm_params = {},
qos_algorithm_type = '',
} = {}
) {
debug(
`Creating VIF for VM ${vm.name_label} on network ${network.name_label}`
)
if (device == null) {
device = (await this.call('VM.get_allowed_VIF_devices', vm.$ref))[0]
}
const vifRef = await this.call(
'VIF.create',
filterUndefineds({
device,
ipv4_allowed,
ipv6_allowed,
locking_mode,
MAC,
MTU: asInteger(network.MTU),
network: network.$ref,
other_config,
qos_algorithm_params,
qos_algorithm_type,
VM: vm.$ref,
})
)
if (currently_attached && isVmRunning(vm)) {
await this.call('VIF.plug', vifRef)
}
return vifRef
}
async createVif (vmId, networkId, opts = undefined) {
return /* await */ this._getOrWaitObject(
await this._createVif(
this.getObject(vmId),
this.getObject(networkId),
opts
)
)
}
@deferrable
async createNetwork (
$defer,
{ name, description = 'Created with Xen Orchestra', pifId, mtu, vlan }
) {
const networkRef = await this.call('network.create', {
name_label: name,
name_description: description,
MTU: asInteger(mtu),
other_config: {},
})
$defer.onFailure(() => this.call('network.destroy', networkRef))
if (pifId) {
await this.call(
'pool.create_VLAN_from_PIF',
this.getObject(pifId).$ref,
networkRef,
asInteger(vlan)
)
}
return this._getOrWaitObject(networkRef)
}
async editPif (pifId, { vlan }) {
const pif = this.getObject(pifId)
const physPif = find(
this.objects.all,
obj =>
obj.$type === 'pif' &&
(obj.physical || !isEmpty(obj.bond_master_of)) &&
obj.$pool === pif.$pool &&
obj.device === pif.device
)
if (!physPif) {
throw new Error('PIF not found')
}
const pifs = this.getObject(pif.network).$PIFs
const wasAttached = {}
forEach(pifs, pif => {
wasAttached[pif.host] = pif.currently_attached
})
const vlans = uniq(mapToArray(pifs, pif => pif.VLAN_master_of))
await Promise.all(
mapToArray(
vlans,
vlan => vlan !== NULL_REF && this.call('VLAN.destroy', vlan)
)
)
const newPifs = await this.call(
'pool.create_VLAN_from_PIF',
physPif.$ref,
pif.network,
asInteger(vlan)
)
await Promise.all(
mapToArray(
newPifs,
pifRef =>
!wasAttached[this.getObject(pifRef).host] &&
this.call('PIF.unplug', pifRef)::ignoreErrors()
)
)
}
@deferrable
async createBondedNetwork ($defer, { bondMode, mac = '', pifIds, ...params }) {
const network = await this.createNetwork(params)
$defer.onFailure(() => this.deleteNetwork(network))
// TODO: test and confirm:
// Bond.create is called here with PIFs from one host but XAPI should then replicate the
// bond on each host in the same pool with the corresponding PIFs (ie same interface names?).
await this.call(
'Bond.create',
network.$ref,
map(pifIds, pifId => this.getObject(pifId).$ref),
mac,
bondMode
)
return network
}
async deleteNetwork (networkId) {
const network = this.getObject(networkId)
const pifs = network.$PIFs
const vlans = uniq(mapToArray(pifs, pif => pif.VLAN_master_of))
await Promise.all(
mapToArray(
vlans,
vlan => vlan !== NULL_REF && this.call('VLAN.destroy', vlan)
)
)
const bonds = uniq(flatten(mapToArray(pifs, pif => pif.bond_master_of)))
await Promise.all(
mapToArray(bonds, bond => this.call('Bond.destroy', bond))
)
await this.call('network.destroy', network.$ref)
}
// =================================================================
async _doDockerAction (vmId, action, containerId) {
const vm = this.getObject(vmId)
const host = vm.$resident_on || this.pool.$master
return /* await */ this.call(
'host.call_plugin',
host.$ref,
'xscontainer',
action,
{
vmuuid: vm.uuid,
container: containerId,
}
)
}
async registerDockerContainer (vmId) {
await this._doDockerAction(vmId, 'register')
}
async deregisterDockerContainer (vmId) {
await this._doDockerAction(vmId, 'deregister')
}
async startDockerContainer (vmId, containerId) {
await this._doDockerAction(vmId, 'start', containerId)
}
async stopDockerContainer (vmId, containerId) {
await this._doDockerAction(vmId, 'stop', containerId)
}
async restartDockerContainer (vmId, containerId) {
await this._doDockerAction(vmId, 'restart', containerId)
}
async pauseDockerContainer (vmId, containerId) {
await this._doDockerAction(vmId, 'pause', containerId)
}
async unpauseDockerContainer (vmId, containerId) {
await this._doDockerAction(vmId, 'unpause', containerId)
}
async getCloudInitConfig (templateId) {
const template = this.getObject(templateId)
const host = this.pool.$master
const config = await this.call(
'host.call_plugin',
host.$ref,
'xscontainer',
'get_config_drive_default',
{
templateuuid: template.uuid,
}
)
return config.slice(4) // FIXME remove the "True" string on the begining
}
// Specific CoreOS Config Drive
async createCoreOsCloudInitConfigDrive (vmId, srId, config) {
const vm = this.getObject(vmId)
const host = this.pool.$master
const sr = this.getObject(srId)
await this.call(
'host.call_plugin',
host.$ref,
'xscontainer',
'create_config_drive',
{
vmuuid: vm.uuid,
sruuid: sr.uuid,
configuration: config,
}
)
await this.registerDockerContainer(vmId)
}
// Generic Config Drive
@deferrable
async createCloudInitConfigDrive ($defer, vmId, srId, config) {
const vm = this.getObject(vmId)
const sr = this.getObject(srId)
// First, create a small VDI (10MB) which will become the ConfigDrive
const buffer = fatfsBufferInit()
const vdi = await this.createVdi({
name_label: 'XO CloudConfigDrive',
size: buffer.length,
sr: sr.$ref,
})
$defer.onFailure(() => this._deleteVdi(vdi))
// Then, generate a FAT fs
const fs = promisifyAll(fatfs.createFileSystem(fatfsBuffer(buffer)))
await fs.mkdir('openstack')
await fs.mkdir('openstack/latest')
await Promise.all([
fs.writeFile(
'openstack/latest/meta_data.json',
'{\n "uuid": "' + vm.uuid + '"\n}\n'
),
fs.writeFile('openstack/latest/user_data', config),
])
// ignore errors, I (JFT) don't understand why they are emitted
// because it works
await this._importVdiContent(vdi, buffer, VDI_FORMAT_RAW).catch(
console.warn
)
await this.createVbd({ vdi, vm })
}
@deferrable
async createTemporaryVdiOnSr (
$defer,
stream,
sr,
name_label,
name_description
) {
const vdi = await this.createVdi({
name_description,
name_label,
size: stream.length,
sr: sr.$ref,
})
$defer.onFailure(() => this._deleteVdi(vdi))
await this.importVdiContent(vdi.$id, stream, { format: VDI_FORMAT_RAW })
return vdi
}
// Create VDI on an adequate local SR
async createTemporaryVdiOnHost (stream, hostId, name_label, name_description) {
const pbd = find(this.getObject(hostId).$PBDs, pbd =>
canSrHaveNewVdiOfSize(pbd.$SR, stream.length)
)
if (pbd == null) {
throw new Error('no SR available')
}
return this.createTemporaryVdiOnSr(
stream,
pbd.SR,
name_label,
name_description
)
}
findAvailableSharedSr (minSize) {
return find(
this.objects.all,
obj =>
obj.$type === 'sr' && obj.shared && canSrHaveNewVdiOfSize(obj, minSize)
)
}
// =================================================================
}
| packages/xo-server/src/xapi/index.js | /* eslint-disable camelcase */
import concurrency from 'limit-concurrency-decorator'
import deferrable from 'golike-defer'
import fatfs from 'fatfs'
import synchronized from 'decorator-synchronized'
import tarStream from 'tar-stream'
import vmdkToVhd from 'xo-vmdk-to-vhd'
import {
cancellable,
catchPlus as pCatch,
defer,
fromEvent,
ignoreErrors,
} from 'promise-toolbox'
import { PassThrough } from 'stream'
import { forbiddenOperation } from 'xo-common/api-errors'
import { Xapi as XapiBase } from 'xen-api'
import {
every,
find,
filter,
flatten,
groupBy,
includes,
isEmpty,
omit,
startsWith,
uniq,
} from 'lodash'
import { satisfies as versionSatisfies } from 'semver'
import createSizeStream from '../size-stream'
import fatfsBuffer, { init as fatfsBufferInit } from '../fatfs-buffer'
import { mixin } from '../decorators'
import {
asyncMap,
camelToSnakeCase,
createRawObject,
ensureArray,
forEach,
isFunction,
map,
mapToArray,
pAll,
parseSize,
pDelay,
pFinally,
promisifyAll,
pSettle,
} from '../utils'
import mixins from './mixins'
import OTHER_CONFIG_TEMPLATE from './other-config-template'
import {
asBoolean,
asInteger,
debug,
extractOpaqueRef,
filterUndefineds,
getNamespaceForType,
getVmDisks,
canSrHaveNewVdiOfSize,
isVmHvm,
isVmRunning,
NULL_REF,
optional,
prepareXapiParam,
} from './utils'
// ===================================================================
const TAG_BASE_DELTA = 'xo:base_delta'
const TAG_COPY_SRC = 'xo:copy_of'
// ===================================================================
// FIXME: remove this work around when fixed, https://phabricator.babeljs.io/T2877
// export * from './utils'
require('lodash/assign')(module.exports, require('./utils'))
// VDI formats. (Raw is not available for delta vdi.)
export const VDI_FORMAT_VHD = 'vhd'
export const VDI_FORMAT_RAW = 'raw'
export const IPV4_CONFIG_MODES = ['None', 'DHCP', 'Static']
export const IPV6_CONFIG_MODES = ['None', 'DHCP', 'Static', 'Autoconf']
// ===================================================================
@mixin(mapToArray(mixins))
export default class Xapi extends XapiBase {
constructor (...args) {
super(...args)
// Patch getObject to resolve _xapiId property.
this.getObject = (getObject => (...args) => {
let tmp
if ((tmp = args[0]) != null && (tmp = tmp._xapiId) != null) {
args[0] = tmp
}
return getObject.apply(this, args)
})(this.getObject)
const genericWatchers = (this._genericWatchers = createRawObject())
const objectsWatchers = (this._objectWatchers = createRawObject())
const onAddOrUpdate = objects => {
forEach(objects, object => {
const { $id: id, $ref: ref } = object
// Run generic watchers.
for (const watcherId in genericWatchers) {
genericWatchers[watcherId](object)
}
// Watched object.
if (id in objectsWatchers) {
objectsWatchers[id].resolve(object)
delete objectsWatchers[id]
}
if (ref in objectsWatchers) {
objectsWatchers[ref].resolve(object)
delete objectsWatchers[ref]
}
})
}
this.objects.on('add', onAddOrUpdate)
this.objects.on('update', onAddOrUpdate)
}
call (...args) {
const fn = super.call
const loop = () =>
fn.apply(this, args)::pCatch(
{
code: 'TOO_MANY_PENDING_TASKS',
},
() => pDelay(5e3).then(loop)
)
return loop()
}
createTask (name = 'untitled task', description) {
return super.createTask(`[XO] ${name}`, description)
}
// =================================================================
_registerGenericWatcher (fn) {
const watchers = this._genericWatchers
const id = String(Math.random())
watchers[id] = fn
return () => {
delete watchers[id]
}
}
// Wait for an object to appear or to be updated.
//
// Predicate can be either an id, a UUID, an opaque reference or a
// function.
//
// TODO: implements a timeout.
_waitObject (predicate) {
if (isFunction(predicate)) {
const { promise, resolve } = defer()
const unregister = this._registerGenericWatcher(obj => {
if (predicate(obj)) {
unregister()
resolve(obj)
}
})
return promise
}
let watcher = this._objectWatchers[predicate]
if (!watcher) {
const { promise, resolve } = defer()
// Register the watcher.
watcher = this._objectWatchers[predicate] = {
promise,
resolve,
}
}
return watcher.promise
}
// Wait for an object to be in a given state.
//
// Faster than _waitObject() with a function.
_waitObjectState (idOrUuidOrRef, predicate) {
const object = this.getObject(idOrUuidOrRef, null)
if (object && predicate(object)) {
return object
}
const loop = () =>
this._waitObject(idOrUuidOrRef).then(
object => (predicate(object) ? object : loop())
)
return loop()
}
// Returns the objects if already presents or waits for it.
async _getOrWaitObject (idOrUuidOrRef) {
return (
this.getObject(idOrUuidOrRef, null) || this._waitObject(idOrUuidOrRef)
)
}
// =================================================================
_setObjectProperty (object, name, value) {
return this.call(
`${getNamespaceForType(object.$type)}.set_${camelToSnakeCase(name)}`,
object.$ref,
prepareXapiParam(value)
)
}
_setObjectProperties (object, props) {
const { $ref: ref, $type: type } = object
const namespace = getNamespaceForType(type)
// TODO: the thrown error should contain the name of the
// properties that failed to be set.
return Promise.all(
mapToArray(props, (value, name) => {
if (value != null) {
return this.call(
`${namespace}.set_${camelToSnakeCase(name)}`,
ref,
prepareXapiParam(value)
)
}
})
)::ignoreErrors()
}
async _updateObjectMapProperty (object, prop, values) {
const { $ref: ref, $type: type } = object
prop = camelToSnakeCase(prop)
const namespace = getNamespaceForType(type)
const add = `${namespace}.add_to_${prop}`
const remove = `${namespace}.remove_from_${prop}`
await Promise.all(
mapToArray(values, (value, name) => {
if (value !== undefined) {
name = camelToSnakeCase(name)
const removal = this.call(remove, ref, name)
return value === null
? removal
: removal
::ignoreErrors()
.then(() => this.call(add, ref, name, prepareXapiParam(value)))
}
})
)
}
async setHostProperties (id, { nameLabel, nameDescription }) {
await this._setObjectProperties(this.getObject(id), {
nameLabel,
nameDescription,
})
}
async setPoolProperties ({ autoPoweron, nameLabel, nameDescription }) {
const { pool } = this
await Promise.all([
this._setObjectProperties(pool, {
nameLabel,
nameDescription,
}),
autoPoweron != null &&
this._updateObjectMapProperty(pool, 'other_config', {
autoPoweron: autoPoweron ? 'true' : null,
}),
])
}
async setSrProperties (id, { nameLabel, nameDescription }) {
await this._setObjectProperties(this.getObject(id), {
nameLabel,
nameDescription,
})
}
async setNetworkProperties (
id,
{ nameLabel, nameDescription, defaultIsLocked }
) {
let defaultLockingMode
if (defaultIsLocked != null) {
defaultLockingMode = defaultIsLocked ? 'disabled' : 'unlocked'
}
await this._setObjectProperties(this.getObject(id), {
nameLabel,
nameDescription,
defaultLockingMode,
})
}
// =================================================================
async addTag (id, tag) {
const { $ref: ref, $type: type } = this.getObject(id)
const namespace = getNamespaceForType(type)
await this.call(`${namespace}.add_tags`, ref, tag)
}
async removeTag (id, tag) {
const { $ref: ref, $type: type } = this.getObject(id)
const namespace = getNamespaceForType(type)
await this.call(`${namespace}.remove_tags`, ref, tag)
}
// =================================================================
async setDefaultSr (srId) {
this._setObjectProperties(this.pool, {
default_SR: this.getObject(srId).$ref,
})
}
// =================================================================
async setPoolMaster (hostId) {
await this.call('pool.designate_new_master', this.getObject(hostId).$ref)
}
// =================================================================
async joinPool (masterAddress, masterUsername, masterPassword, force = false) {
await this.call(
force ? 'pool.join_force' : 'pool.join',
masterAddress,
masterUsername,
masterPassword
)
}
// =================================================================
async emergencyShutdownHost (hostId) {
const host = this.getObject(hostId)
const vms = host.$resident_VMs
debug(`Emergency shutdown: ${host.name_label}`)
await pSettle(
mapToArray(vms, vm => {
if (!vm.is_control_domain) {
return this.call('VM.suspend', vm.$ref)
}
})
)
await this.call('host.disable', host.$ref)
await this.call('host.shutdown', host.$ref)
}
// =================================================================
// Disable the host and evacuate all its VMs.
//
// If `force` is false and the evacuation failed, the host is re-
// enabled and the error is thrown.
async _clearHost ({ $ref: ref }, force) {
await this.call('host.disable', ref)
try {
await this.call('host.evacuate', ref)
} catch (error) {
if (!force) {
await this.call('host.enable', ref)
throw error
}
}
}
async disableHost (hostId) {
await this.call('host.disable', this.getObject(hostId).$ref)
}
async forgetHost (hostId) {
await this.call('host.destroy', this.getObject(hostId).$ref)
}
async ejectHostFromPool (hostId) {
await this.call('pool.eject', this.getObject(hostId).$ref)
}
async enableHost (hostId) {
await this.call('host.enable', this.getObject(hostId).$ref)
}
async powerOnHost (hostId) {
await this.call('host.power_on', this.getObject(hostId).$ref)
}
async rebootHost (hostId, force = false) {
const host = this.getObject(hostId)
await this._clearHost(host, force)
await this.call('host.reboot', host.$ref)
}
async restartHostAgent (hostId) {
await this.call('host.restart_agent', this.getObject(hostId).$ref)
}
async shutdownHost (hostId, force = false) {
const host = this.getObject(hostId)
await this._clearHost(host, force)
await this.call('host.shutdown', host.$ref)
}
// =================================================================
// Clone a VM: make a fast copy by fast copying each of its VDIs
// (using snapshots where possible) on the same SRs.
_cloneVm (vm, nameLabel = vm.name_label) {
debug(
`Cloning VM ${vm.name_label}${
nameLabel !== vm.name_label ? ` as ${nameLabel}` : ''
}`
)
return this.call('VM.clone', vm.$ref, nameLabel)
}
// Copy a VM: make a normal copy of a VM and all its VDIs.
//
// If a SR is specified, it will contains the copies of the VDIs,
// otherwise they will use the SRs they are on.
async _copyVm (vm, nameLabel = vm.name_label, sr = undefined) {
let snapshot
if (isVmRunning(vm)) {
snapshot = await this._snapshotVm(vm)
}
debug(
`Copying VM ${vm.name_label}${
nameLabel !== vm.name_label ? ` as ${nameLabel}` : ''
}${sr ? ` on ${sr.name_label}` : ''}`
)
try {
return await this.call(
'VM.copy',
snapshot ? snapshot.$ref : vm.$ref,
nameLabel,
sr ? sr.$ref : ''
)
} finally {
if (snapshot) {
await this._deleteVm(snapshot)
}
}
}
async cloneVm (vmId, { nameLabel = undefined, fast = true } = {}) {
const vm = this.getObject(vmId)
const cloneRef = await (fast
? this._cloneVm(vm, nameLabel)
: this._copyVm(vm, nameLabel))
return /* await */ this._getOrWaitObject(cloneRef)
}
async copyVm (vmId, srId, { nameLabel = undefined } = {}) {
return /* await */ this._getOrWaitObject(
await this._copyVm(this.getObject(vmId), nameLabel, this.getObject(srId))
)
}
async remoteCopyVm (
vmId,
targetXapi,
targetSrId,
{ compress = true, nameLabel = undefined } = {}
) {
// Fall back on local copy if possible.
if (targetXapi === this) {
return {
vm: await this.copyVm(vmId, targetSrId, { nameLabel }),
}
}
const sr = targetXapi.getObject(targetSrId)
let stream = await this.exportVm(vmId, {
compress,
})
const sizeStream = createSizeStream()
stream = stream.pipe(sizeStream)
const onVmCreation =
nameLabel !== undefined
? vm =>
targetXapi._setObjectProperties(vm, {
nameLabel,
})
: null
const vm = await targetXapi._getOrWaitObject(
await targetXapi._importVm(stream, sr, onVmCreation)
)
return {
size: sizeStream.size,
vm,
}
}
// Low level create VM.
_createVmRecord ({
actions_after_crash,
actions_after_reboot,
actions_after_shutdown,
affinity,
// appliance,
blocked_operations,
generation_id,
ha_always_run,
ha_restart_priority,
has_vendor_device = false, // Avoid issue with some Dundee builds.
hardware_platform_version,
HVM_boot_params,
HVM_boot_policy,
HVM_shadow_multiplier,
is_a_template,
memory_dynamic_max,
memory_dynamic_min,
memory_static_max,
memory_static_min,
name_description,
name_label,
order,
other_config,
PCI_bus,
platform,
protection_policy,
PV_args,
PV_bootloader,
PV_bootloader_args,
PV_kernel,
PV_legacy_args,
PV_ramdisk,
recommendations,
shutdown_delay,
start_delay,
// suspend_SR,
tags,
user_version,
VCPUs_at_startup,
VCPUs_max,
VCPUs_params,
version,
xenstore_data,
}) {
debug(`Creating VM ${name_label}`)
return this.call(
'VM.create',
filterUndefineds({
actions_after_crash,
actions_after_reboot,
actions_after_shutdown,
affinity: affinity == null ? NULL_REF : affinity,
HVM_boot_params,
HVM_boot_policy,
is_a_template: asBoolean(is_a_template),
memory_dynamic_max: asInteger(memory_dynamic_max),
memory_dynamic_min: asInteger(memory_dynamic_min),
memory_static_max: asInteger(memory_static_max),
memory_static_min: asInteger(memory_static_min),
other_config,
PCI_bus,
platform,
PV_args,
PV_bootloader,
PV_bootloader_args,
PV_kernel,
PV_legacy_args,
PV_ramdisk,
recommendations,
user_version: asInteger(user_version),
VCPUs_at_startup: asInteger(VCPUs_at_startup),
VCPUs_max: asInteger(VCPUs_max),
VCPUs_params,
// Optional fields.
blocked_operations,
generation_id,
ha_always_run: asBoolean(ha_always_run),
ha_restart_priority,
has_vendor_device,
hardware_platform_version: optional(
hardware_platform_version,
asInteger
),
// HVM_shadow_multiplier: asFloat(HVM_shadow_multiplier), // FIXME: does not work FIELD_TYPE_ERROR(hVM_shadow_multiplier)
name_description,
name_label,
order: optional(order, asInteger),
protection_policy,
shutdown_delay: asInteger(shutdown_delay),
start_delay: asInteger(start_delay),
tags,
version: asInteger(version),
xenstore_data,
})
)
}
async _deleteVm (vm, deleteDisks = true, force = false) {
debug(`Deleting VM ${vm.name_label}`)
const { $ref } = vm
// It is necessary for suspended VMs to be shut down
// to be able to delete their VDIs.
if (vm.power_state !== 'Halted') {
await this.call('VM.hard_shutdown', $ref)
}
if (force) {
await this._updateObjectMapProperty(vm, 'blocked_operations', {
destroy: null,
})
}
// ensure the vm record is up-to-date
vm = await this.barrier('VM', $ref)
return Promise.all([
this.call('VM.destroy', $ref),
asyncMap(vm.$snapshots, snapshot =>
this._deleteVm(snapshot)
)::ignoreErrors(),
deleteDisks &&
asyncMap(getVmDisks(vm), ({ $ref: vdiRef }) => {
let onFailure = () => {
onFailure = vdi => {
console.error(
`cannot delete VDI ${vdi.name_label} (from VM ${vm.name_label})`
)
forEach(vdi.$VBDs, vbd => {
if (vbd.VM !== $ref) {
const vm = vbd.$VM
console.error('- %s (%s)', vm.name_label, vm.uuid)
}
})
}
// maybe the control domain has not yet unmounted the VDI,
// check and retry after 5 seconds
return pDelay(5e3).then(test)
}
const test = () => {
const vdi = this.getObjectByRef(vdiRef)
return (
// Only remove VBDs not attached to other VMs.
vdi.VBDs.length < 2 || every(vdi.$VBDs, vbd => vbd.VM === $ref)
? this._deleteVdi(vdi)
: onFailure(vdi)
)
}
return test()
})::ignoreErrors(),
])
}
async deleteVm (vmId, deleteDisks, force) {
return /* await */ this._deleteVm(this.getObject(vmId), deleteDisks, force)
}
getVmConsole (vmId) {
const vm = this.getObject(vmId)
const console = find(vm.$consoles, { protocol: 'rfb' })
if (!console) {
throw new Error('no RFB console found')
}
return console
}
// Returns a stream to the exported VM.
@concurrency(2, stream => stream.then(stream => fromEvent(stream, 'end')))
async exportVm (vmId, { compress = true } = {}) {
const vm = this.getObject(vmId)
let host
let snapshotRef
if (isVmRunning(vm)) {
host = vm.$resident_on
snapshotRef = (await this._snapshotVm(vm, `[XO Export] ${vm.name_label}`))
.$ref
}
const promise = this.getResource('/export/', {
host,
query: {
ref: snapshotRef || vm.$ref,
use_compression: compress ? 'true' : 'false',
},
task: this.createTask('VM export', vm.name_label),
})
if (snapshotRef !== undefined) {
promise.then(_ =>
_.task::pFinally(() => this.deleteVm(snapshotRef)::ignoreErrors())
)
}
return promise
}
_assertHealthyVdiChain (vdi, cache) {
if (vdi == null) {
return
}
if (!vdi.managed) {
const { SR } = vdi
let childrenMap = cache[SR]
if (childrenMap === undefined) {
childrenMap = cache[SR] = groupBy(
vdi.$SR.$VDIs,
_ => _.sm_config['vhd-parent']
)
}
// an unmanaged VDI should not have exactly one child: they
// should coalesce
const children = childrenMap[vdi.uuid]
if (
children.length === 1 &&
!children[0].managed // some SRs do not coalesce the leaf
) {
throw new Error('unhealthy VDI chain')
}
}
this._assertHealthyVdiChain(
this.getObjectByUuid(vdi.sm_config['vhd-parent'], null),
cache
)
}
_assertHealthyVdiChains (vm) {
const cache = createRawObject()
forEach(vm.$VBDs, ({ $VDI }) => {
this._assertHealthyVdiChain($VDI, cache)
})
}
// Create a snapshot of the VM and returns a delta export object.
@cancellable
@deferrable
async exportDeltaVm (
$defer,
$cancelToken,
vmId,
baseVmId = undefined,
{
bypassVdiChainsCheck = false,
// Contains a vdi.$id set of vmId.
fullVdisRequired = [],
disableBaseTags = false,
snapshotNameLabel = undefined,
} = {}
) {
if (!bypassVdiChainsCheck) {
this._assertHealthyVdiChains(this.getObject(vmId))
}
const vm = await this.snapshotVm(vmId)
$defer.onFailure(() => this._deleteVm(vm))
if (snapshotNameLabel) {
;this._setObjectProperties(vm, {
nameLabel: snapshotNameLabel,
})::ignoreErrors()
}
const baseVm = baseVmId && this.getObject(baseVmId)
// refs of VM's VDIs → base's VDIs.
const baseVdis = {}
baseVm &&
forEach(baseVm.$VBDs, vbd => {
let vdi, snapshotOf
if (
(vdi = vbd.$VDI) &&
(snapshotOf = vdi.$snapshot_of) &&
!find(fullVdisRequired, id => snapshotOf.$id === id)
) {
baseVdis[vdi.snapshot_of] = vdi
}
})
const streams = {}
const vdis = {}
const vbds = {}
forEach(vm.$VBDs, vbd => {
let vdi
if (vbd.type !== 'Disk' || !(vdi = vbd.$VDI)) {
// Ignore this VBD.
return
}
// If the VDI name start with `[NOBAK]`, do not export it.
if (startsWith(vdi.name_label, '[NOBAK]')) {
// FIXME: find a way to not create the VDI snapshot in the
// first time.
//
// The snapshot must not exist otherwise it could break the
// next export.
;this._deleteVdi(vdi)::ignoreErrors()
return
}
vbds[vbd.$ref] = vbd
const vdiRef = vdi.$ref
if (vdiRef in vdis) {
// This VDI has already been managed.
return
}
// Look for a snapshot of this vdi in the base VM.
const baseVdi = baseVdis[vdi.snapshot_of]
vdis[vdiRef] =
baseVdi && !disableBaseTags
? {
...vdi,
other_config: {
...vdi.other_config,
[TAG_BASE_DELTA]: baseVdi.uuid,
},
$SR$uuid: vdi.$SR.uuid,
}
: {
...vdi,
$SR$uuid: vdi.$SR.uuid,
}
streams[`${vdiRef}.vhd`] = () =>
this._exportVdi($cancelToken, vdi, baseVdi, VDI_FORMAT_VHD)
})
const vifs = {}
forEach(vm.$VIFs, vif => {
vifs[vif.$ref] = {
...vif,
$network$uuid: vif.$network.uuid,
}
})
return Object.defineProperty(
{
version: '1.1.0',
vbds,
vdis,
vifs,
vm: {
...vm,
other_config:
baseVm && !disableBaseTags
? {
...vm.other_config,
[TAG_BASE_DELTA]: baseVm.uuid,
}
: omit(vm.other_config, TAG_BASE_DELTA),
},
},
'streams',
{
value: streams,
}
)
}
@deferrable
async importDeltaVm (
$defer,
delta,
{
deleteBase = false,
disableStartAfterImport = true,
mapVdisSrs = {},
name_label = delta.vm.name_label,
srId = this.pool.default_SR,
} = {}
) {
const { version } = delta
if (!versionSatisfies(version, '^1')) {
throw new Error(`Unsupported delta backup version: ${version}`)
}
const remoteBaseVmUuid = delta.vm.other_config[TAG_BASE_DELTA]
let baseVm
if (remoteBaseVmUuid) {
baseVm = find(
this.objects.all,
obj =>
(obj = obj.other_config) && obj[TAG_COPY_SRC] === remoteBaseVmUuid
)
if (!baseVm) {
throw new Error('could not find the base VM')
}
}
const baseVdis = {}
baseVm &&
forEach(baseVm.$VBDs, vbd => {
baseVdis[vbd.VDI] = vbd.$VDI
})
// 1. Create the VMs.
const vm = await this._getOrWaitObject(
await this._createVmRecord({
...delta.vm,
affinity: null,
is_a_template: false,
})
)
$defer.onFailure(() => this._deleteVm(vm))
await Promise.all([
this._setObjectProperties(vm, {
name_label: `[Importing…] ${name_label}`,
}),
this._updateObjectMapProperty(vm, 'blocked_operations', {
start: 'Importing…',
}),
this._updateObjectMapProperty(vm, 'other_config', {
[TAG_COPY_SRC]: delta.vm.uuid,
}),
])
// 2. Delete all VBDs which may have been created by the import.
await asyncMap(vm.$VBDs, vbd => this._deleteVbd(vbd))::ignoreErrors()
// 3. Create VDIs.
const newVdis = await map(delta.vdis, async vdi => {
const remoteBaseVdiUuid = vdi.other_config[TAG_BASE_DELTA]
if (!remoteBaseVdiUuid) {
const newVdi = await this.createVdi({
...vdi,
other_config: {
...vdi.other_config,
[TAG_BASE_DELTA]: undefined,
[TAG_COPY_SRC]: vdi.uuid,
},
sr: mapVdisSrs[vdi.uuid] || srId,
})
$defer.onFailure(() => this._deleteVdi(newVdi))
return newVdi
}
const baseVdi = find(
baseVdis,
vdi => vdi.other_config[TAG_COPY_SRC] === remoteBaseVdiUuid
)
if (!baseVdi) {
throw new Error(`missing base VDI (copy of ${remoteBaseVdiUuid})`)
}
const newVdi = await this._getOrWaitObject(await this._cloneVdi(baseVdi))
$defer.onFailure(() => this._deleteVdi(newVdi))
await this._updateObjectMapProperty(newVdi, 'other_config', {
[TAG_COPY_SRC]: vdi.uuid,
})
return newVdi
})::pAll()
const networksOnPoolMasterByDevice = {}
let defaultNetwork
forEach(this.pool.$master.$PIFs, pif => {
defaultNetwork = networksOnPoolMasterByDevice[pif.device] = pif.$network
})
const { streams } = delta
let transferSize = 0
await Promise.all([
// Create VBDs.
asyncMap(delta.vbds, vbd =>
this.createVbd({
...vbd,
vdi: newVdis[vbd.VDI],
vm,
})
),
// Import VDI contents.
asyncMap(newVdis, async (vdi, id) => {
for (let stream of ensureArray(streams[`${id}.vhd`])) {
if (typeof stream === 'function') {
stream = await stream()
}
const sizeStream = stream
.pipe(createSizeStream())
.once('finish', () => {
transferSize += sizeStream.size
})
stream.task = sizeStream.task
await this._importVdiContent(vdi, sizeStream, VDI_FORMAT_VHD)
}
}),
// Wait for VDI export tasks (if any) termination.
asyncMap(streams, stream => stream.task),
// Create VIFs.
asyncMap(delta.vifs, vif => {
const network =
(vif.$network$uuid && this.getObject(vif.$network$uuid, null)) ||
networksOnPoolMasterByDevice[vif.device] ||
defaultNetwork
if (network) {
return this._createVif(vm, network, vif)
}
}),
])
if (deleteBase && baseVm) {
;this._deleteVm(baseVm)::ignoreErrors()
}
await Promise.all([
this._setObjectProperties(vm, {
name_label,
}),
// FIXME: move
this._updateObjectMapProperty(vm, 'blocked_operations', {
start: disableStartAfterImport
? 'Do not start this VM, clone it if you want to use it.'
: null,
}),
])
return { transferSize, vm }
}
async _migrateVmWithStorageMotion (
vm,
hostXapi,
host,
{
migrationNetwork = find(host.$PIFs, pif => pif.management).$network, // TODO: handle not found
sr,
mapVdisSrs,
mapVifsNetworks,
}
) {
// VDIs/SRs mapping
const vdis = {}
const defaultSr = host.$pool.$default_SR
for (const vbd of vm.$VBDs) {
const vdi = vbd.$VDI
if (vbd.type === 'Disk') {
vdis[vdi.$ref] =
mapVdisSrs && mapVdisSrs[vdi.$id]
? hostXapi.getObject(mapVdisSrs[vdi.$id]).$ref
: sr !== undefined ? hostXapi.getObject(sr).$ref : defaultSr.$ref // Will error if there are no default SR.
}
}
// VIFs/Networks mapping
const vifsMap = {}
if (vm.$pool !== host.$pool) {
const defaultNetworkRef = find(host.$PIFs, pif => pif.management).$network
.$ref
for (const vif of vm.$VIFs) {
vifsMap[vif.$ref] =
mapVifsNetworks && mapVifsNetworks[vif.$id]
? hostXapi.getObject(mapVifsNetworks[vif.$id]).$ref
: defaultNetworkRef
}
}
const token = await hostXapi.call(
'host.migrate_receive',
host.$ref,
migrationNetwork.$ref,
{}
)
const loop = () =>
this.call(
'VM.migrate_send',
vm.$ref,
token,
true, // Live migration.
vdis,
vifsMap,
{
force: 'true',
}
)::pCatch({ code: 'TOO_MANY_STORAGE_MIGRATES' }, () =>
pDelay(1e4).then(loop)
)
return loop()
}
@synchronized
_callInstallationPlugin (hostRef, vdi) {
return this.call(
'host.call_plugin',
hostRef,
'install-supp-pack',
'install',
{ vdi }
).catch(error => {
if (error.code !== 'XENAPI_PLUGIN_FAILURE') {
console.warn('_callInstallationPlugin', error)
throw error
}
})
}
@deferrable
async installSupplementalPack ($defer, stream, { hostId }) {
if (!stream.length) {
throw new Error('stream must have a length')
}
const vdi = await this.createTemporaryVdiOnHost(
stream,
hostId,
'[XO] Supplemental pack ISO',
'small temporary VDI to store a supplemental pack ISO'
)
$defer(() => this._deleteVdi(vdi))
await this._callInstallationPlugin(this.getObject(hostId).$ref, vdi.uuid)
}
@deferrable
async installSupplementalPackOnAllHosts ($defer, stream) {
if (!stream.length) {
throw new Error('stream must have a length')
}
const isSrAvailable = sr =>
sr &&
sr.content_type === 'user' &&
sr.physical_size - sr.physical_utilisation >= stream.length
const hosts = filter(this.objects.all, { $type: 'host' })
const sr = this.findAvailableSharedSr(stream.length)
// Shared SR available: create only 1 VDI for all the installations
if (sr) {
const vdi = await this.createTemporaryVdiOnSr(
stream,
sr,
'[XO] Supplemental pack ISO',
'small temporary VDI to store a supplemental pack ISO'
)
$defer(() => this._deleteVdi(vdi))
// Install pack sequentially to prevent concurrent access to the unique VDI
for (const host of hosts) {
await this._callInstallationPlugin(host.$ref, vdi.uuid)
}
return
}
// No shared SR available: find an available local SR on each host
return Promise.all(
mapToArray(
hosts,
deferrable(async ($defer, host) => {
// pipe stream synchronously to several PassThroughs to be able to pipe them asynchronously later
const pt = stream.pipe(new PassThrough())
pt.length = stream.length
const sr = find(mapToArray(host.$PBDs, '$SR'), isSrAvailable)
if (!sr) {
throw new Error('no SR available to store installation file')
}
const vdi = await this.createTemporaryVdiOnSr(
pt,
sr,
'[XO] Supplemental pack ISO',
'small temporary VDI to store a supplemental pack ISO'
)
$defer(() => this._deleteVdi(vdi))
await this._callInstallationPlugin(host.$ref, vdi.uuid)
})
)
)
}
async _importVm (stream, sr, onVmCreation = undefined) {
const taskRef = await this.createTask('VM import')
const query = {}
let host
if (sr != null) {
host = sr.$PBDs[0].$host
query.sr_id = sr.$ref
}
if (onVmCreation) {
;this._waitObject(
obj =>
obj && obj.current_operations && taskRef in obj.current_operations
)
.then(onVmCreation)
::ignoreErrors()
}
const vmRef = await this.putResource(stream, '/import/', {
host,
query,
task: taskRef,
}).then(extractOpaqueRef)
return vmRef
}
@deferrable
async _importOvaVm (
$defer,
stream,
{ descriptionLabel, disks, memory, nameLabel, networks, nCpus },
sr
) {
// 1. Create VM.
const vm = await this._getOrWaitObject(
await this._createVmRecord({
...OTHER_CONFIG_TEMPLATE,
memory_dynamic_max: memory,
memory_dynamic_min: memory,
memory_static_max: memory,
name_description: descriptionLabel,
name_label: nameLabel,
VCPUs_at_startup: nCpus,
VCPUs_max: nCpus,
})
)
$defer.onFailure(() => this._deleteVm(vm))
// Disable start and change the VM name label during import.
await Promise.all([
this.addForbiddenOperationToVm(
vm.$id,
'start',
'OVA import in progress...'
),
this._setObjectProperties(vm, {
name_label: `[Importing...] ${nameLabel}`,
}),
])
// 2. Create VDIs & Vifs.
const vdis = {}
const vifDevices = await this.call('VM.get_allowed_VIF_devices', vm.$ref)
await Promise.all(
map(disks, async disk => {
const vdi = (vdis[disk.path] = await this.createVdi({
name_description: disk.descriptionLabel,
name_label: disk.nameLabel,
size: disk.capacity,
sr: sr.$ref,
}))
$defer.onFailure(() => this._deleteVdi(vdi))
return this.createVbd({
userdevice: disk.position,
vdi,
vm,
})
}).concat(
map(networks, (networkId, i) =>
this._createVif(vm, this.getObject(networkId), {
device: vifDevices[i],
})
)
)
)
// 3. Import VDIs contents.
await new Promise((resolve, reject) => {
const extract = tarStream.extract()
stream.on('error', reject)
extract.on('finish', resolve)
extract.on('error', reject)
extract.on('entry', async (entry, stream, cb) => {
// Not a disk to import.
const vdi = vdis[entry.name]
if (!vdi) {
stream.on('end', cb)
stream.resume()
return
}
const vhdStream = await vmdkToVhd(stream)
await this._importVdiContent(vdi, vhdStream, VDI_FORMAT_RAW)
// See: https://github.com/mafintosh/tar-stream#extracting
// No import parallelization.
cb()
})
stream.pipe(extract)
})
// Enable start and restore the VM name label after import.
await Promise.all([
this.removeForbiddenOperationFromVm(vm.$id, 'start'),
this._setObjectProperties(vm, { name_label: nameLabel }),
])
return vm
}
// TODO: an XVA can contain multiple VMs
async importVm (stream, { data, srId, type = 'xva' } = {}) {
const sr = srId && this.getObject(srId)
if (type === 'xva') {
return /* await */ this._getOrWaitObject(await this._importVm(stream, sr))
}
if (type === 'ova') {
return this._getOrWaitObject(await this._importOvaVm(stream, data, sr))
}
throw new Error(`unsupported type: '${type}'`)
}
async migrateVm (
vmId,
hostXapi,
hostId,
{ sr, migrationNetworkId, mapVifsNetworks, mapVdisSrs } = {}
) {
const vm = this.getObject(vmId)
const host = hostXapi.getObject(hostId)
const accrossPools = vm.$pool !== host.$pool
const useStorageMotion =
accrossPools ||
sr !== undefined ||
migrationNetworkId !== undefined ||
!isEmpty(mapVifsNetworks) ||
!isEmpty(mapVdisSrs)
if (useStorageMotion) {
await this._migrateVmWithStorageMotion(vm, hostXapi, host, {
migrationNetwork:
migrationNetworkId && hostXapi.getObject(migrationNetworkId),
sr,
mapVdisSrs,
mapVifsNetworks,
})
} else {
try {
await this.call('VM.pool_migrate', vm.$ref, host.$ref, {
force: 'true',
})
} catch (error) {
if (error.code !== 'VM_REQUIRES_SR') {
throw error
}
// Retry using motion storage.
await this._migrateVmWithStorageMotion(vm, hostXapi, host, {})
}
}
}
@synchronized() // like @concurrency(1) but more efficient
async _snapshotVm (vm, nameLabel = vm.name_label) {
debug(
`Snapshotting VM ${vm.name_label}${
nameLabel !== vm.name_label ? ` as ${nameLabel}` : ''
}`
)
let ref
try {
ref = await this.call('VM.snapshot_with_quiesce', vm.$ref, nameLabel)
this.addTag(ref, 'quiesce')::ignoreErrors()
await this._waitObjectState(ref, vm => includes(vm.tags, 'quiesce'))
} catch (error) {
const { code } = error
if (
code !== 'VM_SNAPSHOT_WITH_QUIESCE_NOT_SUPPORTED' &&
// quiesce only work on a running VM
code !== 'VM_BAD_POWER_STATE' &&
// quiesce failed, fallback on standard snapshot
// TODO: emit warning
code !== 'VM_SNAPSHOT_WITH_QUIESCE_FAILED'
) {
throw error
}
ref = await this.call('VM.snapshot', vm.$ref, nameLabel)
}
// Convert the template to a VM and wait to have receive the up-
// to-date object.
const [, snapshot] = await Promise.all([
this.call('VM.set_is_a_template', ref, false),
this._waitObjectState(ref, snapshot => !snapshot.is_a_template),
])
return snapshot
}
async snapshotVm (vmId, nameLabel = undefined) {
return /* await */ this._snapshotVm(this.getObject(vmId), nameLabel)
}
async setVcpuWeight (vmId, weight) {
weight = weight || null // Take all falsy values as a removal (0 included)
const vm = this.getObject(vmId)
await this._updateObjectMapProperty(vm, 'VCPUs_params', { weight })
}
async _startVm (vm, force) {
debug(`Starting VM ${vm.name_label}`)
if (force) {
await this._updateObjectMapProperty(vm, 'blocked_operations', {
start: null,
})
}
return this.call(
'VM.start',
vm.$ref,
false, // Start paused?
false // Skip pre-boot checks?
)
}
async startVm (vmId, force) {
try {
await this._startVm(this.getObject(vmId), force)
} catch (e) {
if (e.code === 'OPERATION_BLOCKED') {
throw forbiddenOperation('Start', e.params[1])
}
if (e.code === 'VM_BAD_POWER_STATE') {
return this.resumeVm(vmId)
}
throw e
}
}
async startVmOnCd (vmId) {
const vm = this.getObject(vmId)
if (isVmHvm(vm)) {
const { order } = vm.HVM_boot_params
await this._updateObjectMapProperty(vm, 'HVM_boot_params', {
order: 'd',
})
try {
await this._startVm(vm)
} finally {
await this._updateObjectMapProperty(vm, 'HVM_boot_params', {
order,
})
}
} else {
// Find the original template by name (*sigh*).
const templateNameLabel = vm.other_config['base_template_name']
const template =
templateNameLabel &&
find(
this.objects.all,
obj =>
obj.$type === 'vm' &&
obj.is_a_template &&
obj.name_label === templateNameLabel
)
const bootloader = vm.PV_bootloader
const bootables = []
try {
const promises = []
const cdDrive = this._getVmCdDrive(vm)
forEach(vm.$VBDs, vbd => {
promises.push(
this._setObjectProperties(vbd, {
bootable: vbd === cdDrive,
})
)
bootables.push([vbd, Boolean(vbd.bootable)])
})
promises.push(
this._setObjectProperties(vm, {
PV_bootloader: 'eliloader',
}),
this._updateObjectMapProperty(vm, 'other_config', {
'install-distro':
template && template.other_config['install-distro'],
'install-repository': 'cdrom',
})
)
await Promise.all(promises)
await this._startVm(vm)
} finally {
;this._setObjectProperties(vm, {
PV_bootloader: bootloader,
})::ignoreErrors()
forEach(bootables, ([vbd, bootable]) => {
;this._setObjectProperties(vbd, { bootable })::ignoreErrors()
})
}
}
}
// vm_operations: http://xapi-project.github.io/xen-api/classes/vm.html
async addForbiddenOperationToVm (vmId, operation, reason) {
await this.call(
'VM.add_to_blocked_operations',
this.getObject(vmId).$ref,
operation,
`[XO] ${reason}`
)
}
async removeForbiddenOperationFromVm (vmId, operation) {
await this.call(
'VM.remove_from_blocked_operations',
this.getObject(vmId).$ref,
operation
)
}
// =================================================================
async createVbd ({
bootable = false,
other_config = {},
qos_algorithm_params = {},
qos_algorithm_type = '',
type = 'Disk',
unpluggable = false,
userdevice,
VDI,
VM,
vdi = VDI,
empty = vdi === undefined,
mode = type === 'Disk' ? 'RW' : 'RO',
vm = VM,
}) {
vdi = this.getObject(vdi)
vm = this.getObject(vm)
debug(`Creating VBD for VDI ${vdi.name_label} on VM ${vm.name_label}`)
if (userdevice == null) {
const allowed = await this.call('VM.get_allowed_VBD_devices', vm.$ref)
const { length } = allowed
if (length === 0) {
throw new Error('no allowed VBD devices')
}
if (type === 'CD') {
// Choose position 3 if allowed.
userdevice = includes(allowed, '3') ? '3' : allowed[0]
} else {
userdevice = allowed[0]
// Avoid userdevice 3 if possible.
if (userdevice === '3' && length > 1) {
userdevice = allowed[1]
}
}
}
// By default a VBD is unpluggable.
const vbdRef = await this.call('VBD.create', {
bootable: Boolean(bootable),
empty: Boolean(empty),
mode,
other_config,
qos_algorithm_params,
qos_algorithm_type,
type,
unpluggable: Boolean(unpluggable),
userdevice,
VDI: vdi && vdi.$ref,
VM: vm.$ref,
})
if (isVmRunning(vm)) {
await this.call('VBD.plug', vbdRef)
}
}
_cloneVdi (vdi) {
debug(`Cloning VDI ${vdi.name_label}`)
return this.call('VDI.clone', vdi.$ref)
}
async createVdi ({
name_description,
name_label,
other_config = {},
read_only = false,
sharable = false,
sm_config,
SR,
tags,
type = 'user',
virtual_size,
xenstore_data,
size,
sr = SR !== undefined && SR !== NULL_REF ? SR : this.pool.default_SR,
}) {
sr = this.getObject(sr)
debug(`Creating VDI ${name_label} on ${sr.name_label}`)
return this._getOrWaitObject(
await this.call('VDI.create', {
name_description,
name_label,
other_config,
read_only: Boolean(read_only),
sharable: Boolean(sharable),
sm_config,
SR: sr.$ref,
tags,
type,
virtual_size: size !== undefined ? parseSize(size) : virtual_size,
xenstore_data,
})
)
}
async moveVdi (vdiId, srId) {
const vdi = this.getObject(vdiId)
const sr = this.getObject(srId)
if (vdi.SR === sr.$ref) {
return // nothing to do
}
debug(
`Moving VDI ${vdi.name_label} from ${vdi.$SR.name_label} to ${
sr.name_label
}`
)
try {
await this.call('VDI.pool_migrate', vdi.$ref, sr.$ref, {})
} catch (error) {
const { code } = error
if (
code !== 'LICENCE_RESTRICTION' &&
code !== 'VDI_NEEDS_VM_FOR_MIGRATE'
) {
throw error
}
const newVdi = await this.barrier(
await this.call('VDI.copy', vdi.$ref, sr.$ref)
)
await asyncMap(vdi.$VBDs, vbd =>
Promise.all([
this.call('VBD.destroy', vbd.$ref),
this.createVbd({
...vbd,
vdi: newVdi,
}),
])
)
await this._deleteVdi(vdi)
}
}
// TODO: check whether the VDI is attached.
async _deleteVdi (vdi) {
debug(`Deleting VDI ${vdi.name_label}`)
await this.call('VDI.destroy', vdi.$ref)
}
_resizeVdi (vdi, size) {
debug(`Resizing VDI ${vdi.name_label} from ${vdi.virtual_size} to ${size}`)
return this.call('VDI.resize', vdi.$ref, size)
}
_getVmCdDrive (vm) {
for (const vbd of vm.$VBDs) {
if (vbd.type === 'CD') {
return vbd
}
}
}
async _ejectCdFromVm (vm) {
const cdDrive = this._getVmCdDrive(vm)
if (cdDrive) {
await this.call('VBD.eject', cdDrive.$ref)
}
}
async _insertCdIntoVm (cd, vm, { bootable = false, force = false } = {}) {
const cdDrive = await this._getVmCdDrive(vm)
if (cdDrive) {
try {
await this.call('VBD.insert', cdDrive.$ref, cd.$ref)
} catch (error) {
if (!force || error.code !== 'VBD_NOT_EMPTY') {
throw error
}
await this.call('VBD.eject', cdDrive.$ref)::ignoreErrors()
// Retry.
await this.call('VBD.insert', cdDrive.$ref, cd.$ref)
}
if (bootable !== Boolean(cdDrive.bootable)) {
await this._setObjectProperties(cdDrive, { bootable })
}
} else {
await this.createVbd({
bootable,
type: 'CD',
vdi: cd,
vm,
})
}
}
async connectVbd (vbdId) {
await this.call('VBD.plug', vbdId)
}
async _disconnectVbd (vbd) {
// TODO: check if VBD is attached before
try {
await this.call('VBD.unplug_force', vbd.$ref)
} catch (error) {
if (error.code === 'VBD_NOT_UNPLUGGABLE') {
await this.call('VBD.set_unpluggable', vbd.$ref, true)
return this.call('VBD.unplug_force', vbd.$ref)
}
}
}
async disconnectVbd (vbdId) {
await this._disconnectVbd(this.getObject(vbdId))
}
async _deleteVbd (vbd) {
await this._disconnectVbd(vbd)::ignoreErrors()
await this.call('VBD.destroy', vbd.$ref)
}
deleteVbd (vbdId) {
return this._deleteVbd(this.getObject(vbdId))
}
// TODO: remove when no longer used.
async destroyVbdsFromVm (vmId) {
await Promise.all(
mapToArray(this.getObject(vmId).$VBDs, async vbd => {
await this.disconnectVbd(vbd.$ref)::ignoreErrors()
return this.call('VBD.destroy', vbd.$ref)
})
)
}
async deleteVdi (vdiId) {
await this._deleteVdi(this.getObject(vdiId))
}
async resizeVdi (vdiId, size) {
await this._resizeVdi(this.getObject(vdiId), size)
}
async ejectCdFromVm (vmId) {
await this._ejectCdFromVm(this.getObject(vmId))
}
async insertCdIntoVm (cdId, vmId, opts = undefined) {
await this._insertCdIntoVm(this.getObject(cdId), this.getObject(vmId), opts)
}
// -----------------------------------------------------------------
async snapshotVdi (vdiId, nameLabel) {
const vdi = this.getObject(vdiId)
const snap = await this._getOrWaitObject(
await this.call('VDI.snapshot', vdi.$ref)
)
if (nameLabel) {
await this.call('VDI.set_name_label', snap.$ref, nameLabel)
}
return snap
}
@concurrency(12, stream => stream.then(stream => fromEvent(stream, 'end')))
@cancellable
_exportVdi ($cancelToken, vdi, base, format = VDI_FORMAT_VHD) {
const host = vdi.$SR.$PBDs[0].$host
const query = {
format,
vdi: vdi.$ref,
}
if (base) {
query.base = base.$ref
}
debug(
`exporting VDI ${vdi.name_label}${
base ? ` (from base ${vdi.name_label})` : ''
}`
)
return this.getResource($cancelToken, '/export_raw_vdi/', {
host,
query,
task: this.createTask('VDI Export', vdi.name_label),
})
}
// -----------------------------------------------------------------
async _importVdiContent (vdi, body, format = VDI_FORMAT_VHD) {
const pbd = find(vdi.$SR.$PBDs, 'currently_attached')
if (pbd === undefined) {
throw new Error('no valid PBDs found')
}
await Promise.all([
body.task,
body.checksumVerified,
this.putResource(body, '/import_raw_vdi/', {
host: pbd.host,
query: {
format,
vdi: vdi.$ref,
},
task: this.createTask('VDI Content Import', vdi.name_label),
}),
])
}
importVdiContent (vdiId, body, { format } = {}) {
return this._importVdiContent(this.getObject(vdiId), body, format)
}
// =================================================================
async _createVif (
vm,
network,
{
mac = '',
position = undefined,
currently_attached = true,
device = position != null ? String(position) : undefined,
ipv4_allowed = undefined,
ipv6_allowed = undefined,
locking_mode = undefined,
MAC = mac,
other_config = {},
qos_algorithm_params = {},
qos_algorithm_type = '',
} = {}
) {
debug(
`Creating VIF for VM ${vm.name_label} on network ${network.name_label}`
)
if (device == null) {
device = (await this.call('VM.get_allowed_VIF_devices', vm.$ref))[0]
}
const vifRef = await this.call(
'VIF.create',
filterUndefineds({
device,
ipv4_allowed,
ipv6_allowed,
locking_mode,
MAC,
MTU: asInteger(network.MTU),
network: network.$ref,
other_config,
qos_algorithm_params,
qos_algorithm_type,
VM: vm.$ref,
})
)
if (currently_attached && isVmRunning(vm)) {
await this.call('VIF.plug', vifRef)
}
return vifRef
}
async createVif (vmId, networkId, opts = undefined) {
return /* await */ this._getOrWaitObject(
await this._createVif(
this.getObject(vmId),
this.getObject(networkId),
opts
)
)
}
@deferrable
async createNetwork (
$defer,
{ name, description = 'Created with Xen Orchestra', pifId, mtu, vlan }
) {
const networkRef = await this.call('network.create', {
name_label: name,
name_description: description,
MTU: asInteger(mtu),
other_config: {},
})
$defer.onFailure(() => this.call('network.destroy', networkRef))
if (pifId) {
await this.call(
'pool.create_VLAN_from_PIF',
this.getObject(pifId).$ref,
networkRef,
asInteger(vlan)
)
}
return this._getOrWaitObject(networkRef)
}
async editPif (pifId, { vlan }) {
const pif = this.getObject(pifId)
const physPif = find(
this.objects.all,
obj =>
obj.$type === 'pif' &&
(obj.physical || !isEmpty(obj.bond_master_of)) &&
obj.$pool === pif.$pool &&
obj.device === pif.device
)
if (!physPif) {
throw new Error('PIF not found')
}
const pifs = this.getObject(pif.network).$PIFs
const wasAttached = {}
forEach(pifs, pif => {
wasAttached[pif.host] = pif.currently_attached
})
const vlans = uniq(mapToArray(pifs, pif => pif.VLAN_master_of))
await Promise.all(
mapToArray(
vlans,
vlan => vlan !== NULL_REF && this.call('VLAN.destroy', vlan)
)
)
const newPifs = await this.call(
'pool.create_VLAN_from_PIF',
physPif.$ref,
pif.network,
asInteger(vlan)
)
await Promise.all(
mapToArray(
newPifs,
pifRef =>
!wasAttached[this.getObject(pifRef).host] &&
this.call('PIF.unplug', pifRef)::ignoreErrors()
)
)
}
@deferrable
async createBondedNetwork ($defer, { bondMode, mac = '', pifIds, ...params }) {
const network = await this.createNetwork(params)
$defer.onFailure(() => this.deleteNetwork(network))
// TODO: test and confirm:
// Bond.create is called here with PIFs from one host but XAPI should then replicate the
// bond on each host in the same pool with the corresponding PIFs (ie same interface names?).
await this.call(
'Bond.create',
network.$ref,
map(pifIds, pifId => this.getObject(pifId).$ref),
mac,
bondMode
)
return network
}
async deleteNetwork (networkId) {
const network = this.getObject(networkId)
const pifs = network.$PIFs
const vlans = uniq(mapToArray(pifs, pif => pif.VLAN_master_of))
await Promise.all(
mapToArray(
vlans,
vlan => vlan !== NULL_REF && this.call('VLAN.destroy', vlan)
)
)
const bonds = uniq(flatten(mapToArray(pifs, pif => pif.bond_master_of)))
await Promise.all(
mapToArray(bonds, bond => this.call('Bond.destroy', bond))
)
await this.call('network.destroy', network.$ref)
}
// =================================================================
async _doDockerAction (vmId, action, containerId) {
const vm = this.getObject(vmId)
const host = vm.$resident_on || this.pool.$master
return /* await */ this.call(
'host.call_plugin',
host.$ref,
'xscontainer',
action,
{
vmuuid: vm.uuid,
container: containerId,
}
)
}
async registerDockerContainer (vmId) {
await this._doDockerAction(vmId, 'register')
}
async deregisterDockerContainer (vmId) {
await this._doDockerAction(vmId, 'deregister')
}
async startDockerContainer (vmId, containerId) {
await this._doDockerAction(vmId, 'start', containerId)
}
async stopDockerContainer (vmId, containerId) {
await this._doDockerAction(vmId, 'stop', containerId)
}
async restartDockerContainer (vmId, containerId) {
await this._doDockerAction(vmId, 'restart', containerId)
}
async pauseDockerContainer (vmId, containerId) {
await this._doDockerAction(vmId, 'pause', containerId)
}
async unpauseDockerContainer (vmId, containerId) {
await this._doDockerAction(vmId, 'unpause', containerId)
}
async getCloudInitConfig (templateId) {
const template = this.getObject(templateId)
const host = this.pool.$master
const config = await this.call(
'host.call_plugin',
host.$ref,
'xscontainer',
'get_config_drive_default',
{
templateuuid: template.uuid,
}
)
return config.slice(4) // FIXME remove the "True" string on the begining
}
// Specific CoreOS Config Drive
async createCoreOsCloudInitConfigDrive (vmId, srId, config) {
const vm = this.getObject(vmId)
const host = this.pool.$master
const sr = this.getObject(srId)
await this.call(
'host.call_plugin',
host.$ref,
'xscontainer',
'create_config_drive',
{
vmuuid: vm.uuid,
sruuid: sr.uuid,
configuration: config,
}
)
await this.registerDockerContainer(vmId)
}
// Generic Config Drive
@deferrable
async createCloudInitConfigDrive ($defer, vmId, srId, config) {
const vm = this.getObject(vmId)
const sr = this.getObject(srId)
// First, create a small VDI (10MB) which will become the ConfigDrive
const buffer = fatfsBufferInit()
const vdi = await this.createVdi({
name_label: 'XO CloudConfigDrive',
size: buffer.length,
sr: sr.$ref,
})
$defer.onFailure(() => this._deleteVdi(vdi))
// Then, generate a FAT fs
const fs = promisifyAll(fatfs.createFileSystem(fatfsBuffer(buffer)))
await fs.mkdir('openstack')
await fs.mkdir('openstack/latest')
await Promise.all([
fs.writeFile(
'openstack/latest/meta_data.json',
'{\n "uuid": "' + vm.uuid + '"\n}\n'
),
fs.writeFile('openstack/latest/user_data', config),
])
// ignore errors, I (JFT) don't understand why they are emitted
// because it works
await this._importVdiContent(vdi, buffer, VDI_FORMAT_RAW).catch(
console.warn
)
await this.createVbd({ vdi, vm })
}
@deferrable
async createTemporaryVdiOnSr (
$defer,
stream,
sr,
name_label,
name_description
) {
const vdi = await this.createVdi({
name_description,
name_label,
size: stream.length,
sr: sr.$ref,
})
$defer.onFailure(() => this._deleteVdi(vdi))
await this.importVdiContent(vdi.$id, stream, { format: VDI_FORMAT_RAW })
return vdi
}
// Create VDI on an adequate local SR
async createTemporaryVdiOnHost (stream, hostId, name_label, name_description) {
const pbd = find(this.getObject(hostId).$PBDs, pbd =>
canSrHaveNewVdiOfSize(pbd.$SR, stream.length)
)
if (pbd == null) {
throw new Error('no SR available')
}
return this.createTemporaryVdiOnSr(
stream,
pbd.SR,
name_label,
name_description
)
}
findAvailableSharedSr (minSize) {
return find(
this.objects.all,
obj =>
obj.$type === 'sr' && obj.shared && canSrHaveNewVdiOfSize(obj, minSize)
)
}
// =================================================================
}
| chore(xo-server): more cancelable Xapi methods (#2701)
| packages/xo-server/src/xapi/index.js | chore(xo-server): more cancelable Xapi methods (#2701) | <ide><path>ackages/xo-server/src/xapi/index.js
<ide> import tarStream from 'tar-stream'
<ide> import vmdkToVhd from 'xo-vmdk-to-vhd'
<ide> import {
<del> cancellable,
<add> cancelable,
<ide> catchPlus as pCatch,
<ide> defer,
<ide> fromEvent,
<ide>
<ide> // Returns a stream to the exported VM.
<ide> @concurrency(2, stream => stream.then(stream => fromEvent(stream, 'end')))
<del> async exportVm (vmId, { compress = true } = {}) {
<add> @cancelable
<add> async exportVm ($cancelToken, vmId, { compress = true } = {}) {
<ide> const vm = this.getObject(vmId)
<ide>
<ide> let host
<ide> let snapshotRef
<ide> if (isVmRunning(vm)) {
<ide> host = vm.$resident_on
<del> snapshotRef = (await this._snapshotVm(vm, `[XO Export] ${vm.name_label}`))
<del> .$ref
<del> }
<del>
<del> const promise = this.getResource('/export/', {
<add> snapshotRef = (await this._snapshotVm(
<add> $cancelToken,
<add> vm,
<add> `[XO Export] ${vm.name_label}`
<add> )).$ref
<add> }
<add>
<add> const promise = this.getResource($cancelToken, '/export/', {
<ide> host,
<ide> query: {
<ide> ref: snapshotRef || vm.$ref,
<ide> }
<ide>
<ide> // Create a snapshot of the VM and returns a delta export object.
<del> @cancellable
<add> @cancelable
<ide> @deferrable
<ide> async exportDeltaVm (
<ide> $defer,
<ide> )
<ide> }
<ide>
<del> async _importVm (stream, sr, onVmCreation = undefined) {
<add> @cancelable
<add> async _importVm ($cancelToken, stream, sr, onVmCreation = undefined) {
<ide> const taskRef = await this.createTask('VM import')
<ide> const query = {}
<ide>
<ide> query.sr_id = sr.$ref
<ide> }
<ide>
<del> if (onVmCreation) {
<add> if (onVmCreation != null) {
<ide> ;this._waitObject(
<ide> obj =>
<del> obj && obj.current_operations && taskRef in obj.current_operations
<add> obj != null &&
<add> obj.current_operations != null &&
<add> taskRef in obj.current_operations
<ide> )
<ide> .then(onVmCreation)
<ide> ::ignoreErrors()
<ide> }
<ide>
<del> const vmRef = await this.putResource(stream, '/import/', {
<add> const vmRef = await this.putResource($cancelToken, stream, '/import/', {
<ide> host,
<ide> query,
<ide> task: taskRef,
<ide> }
<ide>
<ide> @synchronized() // like @concurrency(1) but more efficient
<del> async _snapshotVm (vm, nameLabel = vm.name_label) {
<add> @cancelable
<add> async _snapshotVm ($cancelToken, vm, nameLabel = vm.name_label) {
<ide> debug(
<ide> `Snapshotting VM ${vm.name_label}${
<ide> nameLabel !== vm.name_label ? ` as ${nameLabel}` : ''
<ide>
<ide> let ref
<ide> try {
<del> ref = await this.call('VM.snapshot_with_quiesce', vm.$ref, nameLabel)
<add> ref = await this.callAsync(
<add> $cancelToken,
<add> 'VM.snapshot_with_quiesce',
<add> vm.$ref,
<add> nameLabel
<add> )
<ide> this.addTag(ref, 'quiesce')::ignoreErrors()
<ide>
<ide> await this._waitObjectState(ref, vm => includes(vm.tags, 'quiesce'))
<ide> ) {
<ide> throw error
<ide> }
<del> ref = await this.call('VM.snapshot', vm.$ref, nameLabel)
<add> ref = await this.callAsync(
<add> $cancelToken,
<add> 'VM.snapshot',
<add> vm.$ref,
<add> nameLabel
<add> )
<ide> }
<ide> // Convert the template to a VM and wait to have receive the up-
<ide> // to-date object.
<ide> }
<ide>
<ide> @concurrency(12, stream => stream.then(stream => fromEvent(stream, 'end')))
<del> @cancellable
<add> @cancelable
<ide> _exportVdi ($cancelToken, vdi, base, format = VDI_FORMAT_VHD) {
<ide> const host = vdi.$SR.$PBDs[0].$host
<ide> |
|
JavaScript | mit | 6f06f623d264a1b11471c2727360c675753dda66 | 0 | atomar-php/node-atomar-cli,atomar-php/node-atomar-cli,atomar-php/node-atomar-cli | 'use strict';
var shell = require('shelljs');
var path = require('path');
var fs = require('fs');
var store = require('./module_store');
var mkdirp = require('mkdirp');
// TODO: set the appropriate path for the os
var modules_dir = '/usr/local/lib/atomar_modules';
var spec = {
controllers_dir: 'controllers',
views_dir: 'views',
package_file: 'atomar.json'
};
/**
* Converts a string into a class name
* @param string
*/
function className(string) {
return string.replace(/[^a-zA-Z0-9]+/g, '');
}
/**
* Converts a string to a machine safe name
* @param string
*/
function machineName(string) {
return string.replace(/[^a-zA-Z]+/g, '_').replace(/(^_|_$)/g, '').toLowerCase();
}
/**
* Injects a template
* @param source {string}
* @param destination {string}
* @param values {{}} a map of values to be replaced in the template
*/
function injectTemplate(source, destination, values) {
values = values || {};
var data = fs.readFileSync(source, 'utf8');
for(var key of Object.keys(values)) {
var match = new RegExp('\{\{' + key + '\}\}', 'g');
data = data.replace(match, values[key]);
}
mkdirp(path.dirname(destination));
if(fileExists(destination)) throw new Error('The path already exists', destination);
fs.writeFileSync(destination, data, 'utf8');
}
/**
* Loads the package in the current dir
*
* @returns {{}|null} null if the package does not exist
*/
function loadPackage() {
try {
var data = fs.readFileSync(path.join(process.cwd(), spec.package_file));
return JSON.parse(data);
} catch (err) {
console.error(err);
}
return null;
}
/**
* Checks if the file exists
* @param file
* @returns {boolean}
*/
function fileExists(file) {
try {
fs.statSync(file);
return true;
} catch(err) {
return false;
}
}
/**
* Replaces a matched string in a file
* @param filePath
* @param matcher regex
* @param replacement string
*/
function replaceInFile(filePath, matcher, replacement) {
var data = fs.readFileSync(filePath, 'utf8');
data = data.replace(matcher, replacement);
fs.writeFileSync(filePath, data, 'utf8');
}
/**
* Installs an atomar module
* @param module_name
* @param install_path if left null the module will be installed globally
* @param clone_with_ssh
*/
function install_module(module_name, install_path, clone_with_ssh) {
var remote;
var module = store.lookup_module(module_name, '*');
var global_install = false;
if(module) {
if(clone_with_ssh) {
remote = '[email protected]:' + module.owner + '/' + module.repo;
} else {
remote = 'https://github.com/' + module.owner + '/' + module.repo;
}
if(!install_path) {
global_install = true;
install_path = path.join(modules_dir, module_name);
} else {
install_path = path.join(install_path, module_name);
}
var cmd;
if(fileExists(install_path)) {
console.log('Updating ' + module_name + '...');
cmd = 'git pull origin master';
if(global_install) {
cmd = 'sudo ' + cmd;
}
cmd = 'cd ' + install_path + ' && ' + cmd;
} else {
console.log('Installing ' + module_name + '...');
cmd = 'git clone ' + remote + ' ' + install_path;
if(global_install) {
shell.exec('sudo mkdir -p ' + modules_dir);
cmd = 'sudo ' + cmd;
}
}
console.log('Cloning ' + remote + ' into ' + install_path);
shell.exec(cmd);
} else {
throw new Error('The module "' + module_name + '" does not exist.');
}
}
/**
* Returns the path to a module if it exists in the global path
* @param name
* @returns string
*/
function lookup_module(name) {
var dir = path.join(modules_dir, name);
try {
if (fs.statSync(dir).isDirectory()) {
return dir;
}
} catch(err) {}
return null;
}
/**
* Turns a standard callback method into a promise-style method.
* Assumes standard node.js style:
* someFunction(arg1, arg2, function(err, data) { ... })
*
* This will pass the proper number of arguments and convert
* the callback structure to a Promise.
*
* e.g. var readdir = promisify(fs, 'readdir'),
* readdir('something').then(someFunction);
*
* var rm = promisify(rimraf),
* rm('something').then(someFunction);
*
* @param module
* @param fn
* @returns {function.<Promise>} a new function that returns a promise
*/
function promisify(module, fn) {
var hasModule = typeof module !== 'function',
f = hasModule ? module[fn] : module,
mod = hasModule ? module : null;
return function () {
var args = [],
i = arguments.length - 1;
/**
* Don't pass an arguments list that has undefined values at the end.
* This is so the callback for function gets passed in the right slot.
*
* If the function gets passed:
* f(arg1, arg2, undefined, cb)
*
* ...it will think it got an undefined cb.
*
* We instead want it to get passed:
* f(arg1, arg2, cb)
*
* Before: [arg1, null, undefined, arg2, undefined, undefined]
* After: [arg1, null, undefined, arg2]
*/
while (i >= 0 && typeof arguments[i] === 'undefined') {
--i;
}
while (i >= 0) {
args.unshift(arguments[i]);
--i;
}
return new Promise(function (resolve, reject) {
try {
resolve(f.apply(mod, args));
} catch (err) {
reject(err);
}
});
};
}
module.exports = {
injectTemplate: injectTemplate,
loadPackage: loadPackage,
lookup_module: lookup_module,
install_module: install_module,
replaceInFile: replaceInFile,
fileExists: fileExists,
promisify: promisify,
machineName: machineName,
className: className,
get spec() { return spec }
}; | lib.js | 'use strict';
var shell = require('shelljs');
var path = require('path');
var fs = require('fs');
var store = require('./module_store');
var mkdirp = require('mkdirp');
// TODO: set the appropriate path for the os
var modules_dir = '/usr/local/lib/atomar_modules';
var spec = {
controllers_dir: 'controllers',
views_dir: 'views',
package_file: 'atomar.json'
};
/**
* Converts a string into a class name
* @param string
*/
function className(string) {
return string.replace(/[^a-zA-Z0-9]+/g, '');
}
/**
* Converts a string to a machine safe name
* @param string
*/
function machineName(string) {
return string.replace(/[^a-zA-Z]+/g, '_').replace(/(^_|_$)/g, '').toLowerCase();
}
/**
* Injects a template
* @param source {string}
* @param destination {string}
* @param values {{}} a map of values to be replaced in the template
*/
function injectTemplate(source, destination, values) {
values = values || {};
var data = fs.readFileSync(source, 'utf8');
for(var key of Object.keys(values)) {
var match = new RegExp('\{\{' + key + '\}\}', 'g');
data = data.replace(match, values[key]);
}
mkdirp(path.dirname(destination));
if(fileExists(destination)) throw new Error('The path already exists', destination);
fs.writeFileSync(destination, data, 'utf8');
}
/**
* Loads the package in the current dir
*
* @returns {{}|null} null if the package does not exist
*/
function loadPackage() {
try {
var data = fs.readFileSync(path.join(process.cwd(), spec.package_file));
return JSON.parse(data);
} catch (err) {
console.error(err);
}
return null;
}
/**
* Checks if the file exists
* @param file
* @returns {boolean}
*/
function fileExists(file) {
try {
fs.statSync(file);
return true;
} catch(err) {
return false;
}
}
/**
* Replaces a matched string in a file
* @param filePath
* @param matcher regex
* @param replacement string
*/
function replaceInFile(filePath, matcher, replacement) {
var data = fs.readFileSync(filePath, 'utf8');
data = data.replace(matcher, replacement);
fs.writeFileSync(filePath, data, 'utf8');
}
/**
* Installs an atomar module
* @param module_name
* @param install_path if left null the module will be installed globally
* @param clone_with_ssh
*/
function install_module(module_name, install_path, clone_with_ssh) {
var remote;
var module = store.lookup_module(module_name, '*');
var global_install = false;
if(module) {
if(clone_with_ssh) {
remote = '[email protected]:' + module.owner + '/' + module.repo;
} else {
remote = 'https://github.com/' + module.owner + '/' + module.repo;
}
if(!install_path) {
global_install = true;
install_path = path.join(modules_dir, module_name);
} else {
install_path = path.join(install_path, module_name);
}
var cmd;
if(fileExists(install_path)) {
console.log('Updating ' + module_name + '...');
cmd = 'git pull origin master';
if(global_install) {
cmd = 'sudo ' + cmd;
}
cmd = 'cd ' + install_path + ' && ' + cmd;
} else {
console.log('Installing ' + module_name + '...');
cmd = 'git clone ' + remote + ' ' + install_path;
if(global_install) {
shell.exec('sudo mkdir -p ' + modules_dir);
cmd = 'sudo ' + cmd;
}
}
shell.exec(cmd);
} else {
throw new Error('The module "' + module_name + '" does not exist.');
}
}
/**
* Returns the path to a module if it exists in the global path
* @param name
* @returns string
*/
function lookup_module(name) {
var dir = path.join(modules_dir, name);
try {
if (fs.statSync(dir).isDirectory()) {
return dir;
}
} catch(err) {}
return null;
}
/**
* Turns a standard callback method into a promise-style method.
* Assumes standard node.js style:
* someFunction(arg1, arg2, function(err, data) { ... })
*
* This will pass the proper number of arguments and convert
* the callback structure to a Promise.
*
* e.g. var readdir = promisify(fs, 'readdir'),
* readdir('something').then(someFunction);
*
* var rm = promisify(rimraf),
* rm('something').then(someFunction);
*
* @param module
* @param fn
* @returns {function.<Promise>} a new function that returns a promise
*/
function promisify(module, fn) {
var hasModule = typeof module !== 'function',
f = hasModule ? module[fn] : module,
mod = hasModule ? module : null;
return function () {
var args = [],
i = arguments.length - 1;
/**
* Don't pass an arguments list that has undefined values at the end.
* This is so the callback for function gets passed in the right slot.
*
* If the function gets passed:
* f(arg1, arg2, undefined, cb)
*
* ...it will think it got an undefined cb.
*
* We instead want it to get passed:
* f(arg1, arg2, cb)
*
* Before: [arg1, null, undefined, arg2, undefined, undefined]
* After: [arg1, null, undefined, arg2]
*/
while (i >= 0 && typeof arguments[i] === 'undefined') {
--i;
}
while (i >= 0) {
args.unshift(arguments[i]);
--i;
}
return new Promise(function (resolve, reject) {
try {
resolve(f.apply(mod, args));
} catch (err) {
reject(err);
}
});
};
}
module.exports = {
injectTemplate: injectTemplate,
loadPackage: loadPackage,
lookup_module: lookup_module,
install_module: install_module,
replaceInFile: replaceInFile,
fileExists: fileExists,
promisify: promisify,
machineName: machineName,
className: className,
get spec() { return spec }
}; | added some better logging
| lib.js | added some better logging | <ide><path>ib.js
<ide> cmd = 'sudo ' + cmd;
<ide> }
<ide> }
<add> console.log('Cloning ' + remote + ' into ' + install_path);
<ide> shell.exec(cmd);
<ide> } else {
<ide> throw new Error('The module "' + module_name + '" does not exist.'); |
|
JavaScript | agpl-3.0 | 7bcece7f76f954f9f1508b91fb812b421e5b4ed4 | 0 | lmcro/xo-web,lmcro/xo-web,lmcro/xo-web,vatesfr/xo-web,vatesfr/xo-web | /* eslint-disable camelcase */
import deferrable from 'golike-defer'
import fatfs from 'fatfs'
import synchronized from 'decorator-synchronized'
import tarStream from 'tar-stream'
import vmdkToVhd from 'xo-vmdk-to-vhd'
import { cancellable, defer } from 'promise-toolbox'
import { PassThrough } from 'stream'
import { forbiddenOperation } from 'xo-common/api-errors'
import {
every,
find,
filter,
flatten,
groupBy,
includes,
isEmpty,
omit,
startsWith,
uniq
} from 'lodash'
import {
Xapi as XapiBase
} from 'xen-api'
import {
satisfies as versionSatisfies
} from 'semver'
import createSizeStream from '../size-stream'
import fatfsBuffer, { init as fatfsBufferInit } from '../fatfs-buffer'
import { mixin } from '../decorators'
import {
camelToSnakeCase,
createRawObject,
ensureArray,
forEach,
isFunction,
map,
mapToArray,
noop,
pAll,
pCatch,
pDelay,
pFinally,
promisifyAll,
pSettle
} from '../utils'
import mixins from './mixins'
import OTHER_CONFIG_TEMPLATE from './other-config-template'
import {
asBoolean,
asInteger,
debug,
extractOpaqueRef,
filterUndefineds,
getNamespaceForType,
canSrHaveNewVdiOfSize,
isVmHvm,
isVmRunning,
NULL_REF,
optional,
prepareXapiParam
} from './utils'
// ===================================================================
const TAG_BASE_DELTA = 'xo:base_delta'
const TAG_COPY_SRC = 'xo:copy_of'
// ===================================================================
// FIXME: remove this work around when fixed, https://phabricator.babeljs.io/T2877
// export * from './utils'
require('lodash/assign')(module.exports, require('./utils'))
// VDI formats. (Raw is not available for delta vdi.)
export const VDI_FORMAT_VHD = 'vhd'
export const VDI_FORMAT_RAW = 'raw'
export const IPV4_CONFIG_MODES = ['None', 'DHCP', 'Static']
export const IPV6_CONFIG_MODES = ['None', 'DHCP', 'Static', 'Autoconf']
// ===================================================================
@mixin(mapToArray(mixins))
export default class Xapi extends XapiBase {
constructor (...args) {
super(...args)
// Patch getObject to resolve _xapiId property.
this.getObject = (getObject => (...args) => {
let tmp
if ((tmp = args[0]) != null && (tmp = tmp._xapiId) != null) {
args[0] = tmp
}
return getObject.apply(this, args)
})(this.getObject)
const genericWatchers = this._genericWatchers = createRawObject()
const objectsWatchers = this._objectWatchers = createRawObject()
const onAddOrUpdate = objects => {
forEach(objects, object => {
const {
$id: id,
$ref: ref
} = object
// Run generic watchers.
for (const watcherId in genericWatchers) {
genericWatchers[watcherId](object)
}
// Watched object.
if (id in objectsWatchers) {
objectsWatchers[id].resolve(object)
delete objectsWatchers[id]
}
if (ref in objectsWatchers) {
objectsWatchers[ref].resolve(object)
delete objectsWatchers[ref]
}
})
}
this.objects.on('add', onAddOrUpdate)
this.objects.on('update', onAddOrUpdate)
}
call (...args) {
const fn = super.call
const loop = () => fn.apply(this, args)::pCatch({
code: 'TOO_MANY_PENDING_TASKS'
}, () => pDelay(5e3).then(loop))
return loop()
}
createTask (name = 'untitled task', description) {
return super.createTask(`[XO] ${name}`, description)
}
// =================================================================
_registerGenericWatcher (fn) {
const watchers = this._genericWatchers
const id = String(Math.random())
watchers[id] = fn
return () => {
delete watchers[id]
}
}
// Wait for an object to appear or to be updated.
//
// Predicate can be either an id, a UUID, an opaque reference or a
// function.
//
// TODO: implements a timeout.
_waitObject (predicate) {
if (isFunction(predicate)) {
const { promise, resolve } = defer()
const unregister = this._registerGenericWatcher(obj => {
if (predicate(obj)) {
unregister()
resolve(obj)
}
})
return promise
}
let watcher = this._objectWatchers[predicate]
if (!watcher) {
const { promise, resolve } = defer()
// Register the watcher.
watcher = this._objectWatchers[predicate] = {
promise,
resolve
}
}
return watcher.promise
}
// Wait for an object to be in a given state.
//
// Faster than _waitObject() with a function.
_waitObjectState (idOrUuidOrRef, predicate) {
const object = this.getObject(idOrUuidOrRef, null)
if (object && predicate(object)) {
return object
}
const loop = () => this._waitObject(idOrUuidOrRef).then(
(object) => predicate(object) ? object : loop()
)
return loop()
}
// Returns the objects if already presents or waits for it.
async _getOrWaitObject (idOrUuidOrRef) {
return (
this.getObject(idOrUuidOrRef, null) ||
this._waitObject(idOrUuidOrRef)
)
}
// =================================================================
_setObjectProperty (object, name, value) {
return this.call(
`${getNamespaceForType(object.$type)}.set_${camelToSnakeCase(name)}`,
object.$ref,
prepareXapiParam(value)
)
}
_setObjectProperties (object, props) {
const {
$ref: ref,
$type: type
} = object
const namespace = getNamespaceForType(type)
// TODO: the thrown error should contain the name of the
// properties that failed to be set.
return Promise.all(mapToArray(props, (value, name) => {
if (value != null) {
return this.call(`${namespace}.set_${camelToSnakeCase(name)}`, ref, prepareXapiParam(value))
}
}))::pCatch(noop)
}
async _updateObjectMapProperty (object, prop, values) {
const {
$ref: ref,
$type: type
} = object
prop = camelToSnakeCase(prop)
const namespace = getNamespaceForType(type)
const add = `${namespace}.add_to_${prop}`
const remove = `${namespace}.remove_from_${prop}`
await Promise.all(mapToArray(values, (value, name) => {
if (value !== undefined) {
name = camelToSnakeCase(name)
const removal = this.call(remove, ref, name)
return value === null
? removal
: removal::pCatch(noop).then(() => this.call(add, ref, name, prepareXapiParam(value)))
}
}))
}
async setHostProperties (id, {
nameLabel,
nameDescription
}) {
await this._setObjectProperties(this.getObject(id), {
nameLabel,
nameDescription
})
}
async setPoolProperties ({
autoPoweron,
nameLabel,
nameDescription
}) {
const { pool } = this
await Promise.all([
this._setObjectProperties(pool, {
nameLabel,
nameDescription
}),
autoPoweron != null && this._updateObjectMapProperty(pool, 'other_config', {
autoPoweron: autoPoweron ? 'true' : null
})
])
}
async setSrProperties (id, {
nameLabel,
nameDescription
}) {
await this._setObjectProperties(this.getObject(id), {
nameLabel,
nameDescription
})
}
async setNetworkProperties (id, {
nameLabel,
nameDescription,
defaultIsLocked
}) {
let defaultLockingMode
if (defaultIsLocked != null) {
defaultLockingMode = defaultIsLocked ? 'disabled' : 'unlocked'
}
await this._setObjectProperties(this.getObject(id), {
nameLabel,
nameDescription,
defaultLockingMode
})
}
// =================================================================
async addTag (id, tag) {
const {
$ref: ref,
$type: type
} = this.getObject(id)
const namespace = getNamespaceForType(type)
await this.call(`${namespace}.add_tags`, ref, tag)
}
async removeTag (id, tag) {
const {
$ref: ref,
$type: type
} = this.getObject(id)
const namespace = getNamespaceForType(type)
await this.call(`${namespace}.remove_tags`, ref, tag)
}
// =================================================================
async setDefaultSr (srId) {
this._setObjectProperties(this.pool, {
default_SR: this.getObject(srId).$ref
})
}
// =================================================================
async joinPool (masterAddress, masterUsername, masterPassword, force = false) {
await this.call(
force ? 'pool.join_force' : 'pool.join',
masterAddress,
masterUsername,
masterPassword
)
}
// =================================================================
async emergencyShutdownHost (hostId) {
const host = this.getObject(hostId)
const vms = host.$resident_VMs
debug(`Emergency shutdown: ${host.name_label}`)
await pSettle(
mapToArray(vms, vm => {
if (!vm.is_control_domain) {
return this.call('VM.suspend', vm.$ref)
}
})
)
await this.call('host.disable', host.$ref)
await this.call('host.shutdown', host.$ref)
}
// =================================================================
// Disable the host and evacuate all its VMs.
//
// If `force` is false and the evacuation failed, the host is re-
// enabled and the error is thrown.
async _clearHost ({ $ref: ref }, force) {
await this.call('host.disable', ref)
try {
await this.call('host.evacuate', ref)
} catch (error) {
if (!force) {
await this.call('host.enable', ref)
throw error
}
}
}
async disableHost (hostId) {
await this.call('host.disable', this.getObject(hostId).$ref)
}
async ejectHostFromPool (hostId) {
await this.call('pool.eject', this.getObject(hostId).$ref)
}
async enableHost (hostId) {
await this.call('host.enable', this.getObject(hostId).$ref)
}
async powerOnHost (hostId) {
await this.call('host.power_on', this.getObject(hostId).$ref)
}
async rebootHost (hostId, force = false) {
const host = this.getObject(hostId)
await this._clearHost(host, force)
await this.call('host.reboot', host.$ref)
}
async restartHostAgent (hostId) {
await this.call('host.restart_agent', this.getObject(hostId).$ref)
}
async shutdownHost (hostId, force = false) {
const host = this.getObject(hostId)
await this._clearHost(host, force)
await this.call('host.shutdown', host.$ref)
}
// =================================================================
// Clone a VM: make a fast copy by fast copying each of its VDIs
// (using snapshots where possible) on the same SRs.
_cloneVm (vm, nameLabel = vm.name_label) {
debug(`Cloning VM ${vm.name_label}${
nameLabel !== vm.name_label
? ` as ${nameLabel}`
: ''
}`)
return this.call('VM.clone', vm.$ref, nameLabel)
}
// Copy a VM: make a normal copy of a VM and all its VDIs.
//
// If a SR is specified, it will contains the copies of the VDIs,
// otherwise they will use the SRs they are on.
async _copyVm (vm, nameLabel = vm.name_label, sr = undefined) {
let snapshot
if (isVmRunning(vm)) {
snapshot = await this._snapshotVm(vm)
}
debug(`Copying VM ${vm.name_label}${
nameLabel !== vm.name_label
? ` as ${nameLabel}`
: ''
}${
sr
? ` on ${sr.name_label}`
: ''
}`)
try {
return await this.call(
'VM.copy',
snapshot ? snapshot.$ref : vm.$ref,
nameLabel,
sr ? sr.$ref : ''
)
} finally {
if (snapshot) {
await this._deleteVm(snapshot)
}
}
}
async cloneVm (vmId, {
nameLabel = undefined,
fast = true
} = {}) {
const vm = this.getObject(vmId)
const cloneRef = await (
fast
? this._cloneVm(vm, nameLabel)
: this._copyVm(vm, nameLabel)
)
return /* await */ this._getOrWaitObject(cloneRef)
}
async copyVm (vmId, srId, {
nameLabel = undefined
} = {}) {
return /* await */ this._getOrWaitObject(
await this._copyVm(
this.getObject(vmId),
nameLabel,
this.getObject(srId)
)
)
}
async remoteCopyVm (vmId, targetXapi, targetSrId, {
compress = true,
nameLabel = undefined
} = {}) {
// Fall back on local copy if possible.
if (targetXapi === this) {
return {
vm: await this.copyVm(vmId, targetSrId, { nameLabel })
}
}
const sr = targetXapi.getObject(targetSrId)
let stream = await this.exportVm(vmId, {
compress,
onlyMetadata: false
})
const sizeStream = createSizeStream()
stream = stream.pipe(sizeStream)
const onVmCreation = nameLabel !== undefined
? vm => targetXapi._setObjectProperties(vm, {
nameLabel
})
: null
const vm = await targetXapi._getOrWaitObject(
await targetXapi._importVm(
stream,
sr,
false,
onVmCreation
)
)
return {
size: sizeStream.size,
vm
}
}
// Low level create VM.
_createVmRecord ({
actions_after_crash,
actions_after_reboot,
actions_after_shutdown,
affinity,
// appliance,
blocked_operations,
generation_id,
ha_always_run,
ha_restart_priority,
has_vendor_device = false, // Avoid issue with some Dundee builds.
hardware_platform_version,
HVM_boot_params,
HVM_boot_policy,
HVM_shadow_multiplier,
is_a_template,
memory_dynamic_max,
memory_dynamic_min,
memory_static_max,
memory_static_min,
name_description,
name_label,
order,
other_config,
PCI_bus,
platform,
protection_policy,
PV_args,
PV_bootloader,
PV_bootloader_args,
PV_kernel,
PV_legacy_args,
PV_ramdisk,
recommendations,
shutdown_delay,
start_delay,
// suspend_SR,
tags,
user_version,
VCPUs_at_startup,
VCPUs_max,
VCPUs_params,
version,
xenstore_data
}) {
debug(`Creating VM ${name_label}`)
return this.call('VM.create', filterUndefineds({
actions_after_crash,
actions_after_reboot,
actions_after_shutdown,
affinity: affinity == null ? NULL_REF : affinity,
HVM_boot_params,
HVM_boot_policy,
is_a_template: asBoolean(is_a_template),
memory_dynamic_max: asInteger(memory_dynamic_max),
memory_dynamic_min: asInteger(memory_dynamic_min),
memory_static_max: asInteger(memory_static_max),
memory_static_min: asInteger(memory_static_min),
other_config,
PCI_bus,
platform,
PV_args,
PV_bootloader,
PV_bootloader_args,
PV_kernel,
PV_legacy_args,
PV_ramdisk,
recommendations,
user_version: asInteger(user_version),
VCPUs_at_startup: asInteger(VCPUs_at_startup),
VCPUs_max: asInteger(VCPUs_max),
VCPUs_params,
// Optional fields.
blocked_operations,
generation_id,
ha_always_run: asBoolean(ha_always_run),
ha_restart_priority,
has_vendor_device,
hardware_platform_version: optional(hardware_platform_version, asInteger),
// HVM_shadow_multiplier: asFloat(HVM_shadow_multiplier), // FIXME: does not work FIELD_TYPE_ERROR(hVM_shadow_multiplier)
name_description,
name_label,
order: optional(order, asInteger),
protection_policy,
shutdown_delay: asInteger(shutdown_delay),
start_delay: asInteger(start_delay),
tags,
version: asInteger(version),
xenstore_data
}))
}
async _deleteVm (vm, deleteDisks = true) {
debug(`Deleting VM ${vm.name_label}`)
// It is necessary for suspended VMs to be shut down
// to be able to delete their VDIs.
if (vm.power_state !== 'Halted') {
await this.call('VM.hard_shutdown', vm.$ref)
}
if (deleteDisks) {
// Compute the VDIs list without duplicates.
const vdis = {}
forEach(vm.$VBDs, vbd => {
let vdi
if (
// Do not remove CDs and Floppies.
vbd.type === 'Disk' &&
// Ignore VBD without VDI.
(vdi = vbd.$VDI)
) {
vdis[vdi.$id] = vdi
}
})
await Promise.all(mapToArray(vdis, vdi => {
if (
// Do not remove VBDs attached to other VMs.
vdi.VBDs.length < 2 ||
every(vdi.$VBDs, vbd => vbd.VM === vm.$ref)
) {
return this._deleteVdi(vdi)::pCatch(noop)
}
console.error(`cannot delete VDI ${vdi.name_label} (from VM ${vm.name_label})`)
}))
}
await Promise.all(mapToArray(vm.$snapshots, snapshot =>
this.deleteVm(snapshot.$id)::pCatch(noop)
))
await this.call('VM.destroy', vm.$ref)
}
async deleteVm (vmId, deleteDisks) {
return /* await */ this._deleteVm(
this.getObject(vmId),
deleteDisks
)
}
getVmConsole (vmId) {
const vm = this.getObject(vmId)
const console = find(vm.$consoles, { protocol: 'rfb' })
if (!console) {
throw new Error('no RFB console found')
}
return console
}
// Returns a stream to the exported VM.
async exportVm (vmId, {
compress = true,
onlyMetadata = false
} = {}) {
const vm = this.getObject(vmId)
let host
let snapshotRef
// It's not needed to snapshot the VM to get the metadata
if (isVmRunning(vm) && !onlyMetadata) {
host = vm.$resident_on
snapshotRef = (await this._snapshotVm(vm)).$ref
}
const promise = this.getResource(onlyMetadata ? '/export_metadata/' : '/export/', {
host,
query: {
ref: snapshotRef || vm.$ref,
use_compression: compress ? 'true' : 'false'
},
task: this.createTask('VM export', vm.name_label)
})
if (snapshotRef !== undefined) {
promise.then(_ => _.task::pFinally(() =>
this.deleteVm(snapshotRef)::pCatch(noop)
))
}
return promise
}
_assertHealthyVdiChain (vdi, childrenMap) {
if (vdi == null) {
return
}
if (!vdi.managed) {
if (childrenMap === undefined) {
childrenMap = groupBy(vdi.$SR.$VDIs, _ => _.sm_config['vhd-parent'])
}
// an unmanaged VDI should not have exactly one child: they
// should coalesce
const children = childrenMap[vdi.uuid]
if (
children.length === 1 &&
!children[0].managed // some SRs do not coalesce the leaf
) {
throw new Error('unhealthy VDI chain')
}
}
this._assertHealthyVdiChain(
this.getObjectByUuid(vdi.sm_config['vhd-parent'], null),
childrenMap
)
}
_assertHealthyVdiChains (vm) {
forEach(vm.$VBDs, ({ $VDI }) => {
this._assertHealthyVdiChain($VDI)
})
}
// Create a snapshot of the VM and returns a delta export object.
@deferrable.onFailure
async exportDeltaVm ($onFailure, vmId, baseVmId = undefined, {
snapshotNameLabel = undefined,
// Contains a vdi.$id set of vmId.
fullVdisRequired = [],
disableBaseTags = false
} = {}) {
this._assertHealthyVdiChains(this.getObject(vmId))
const vm = await this.snapshotVm(vmId)
$onFailure(() => this._deleteVm(vm))
if (snapshotNameLabel) {
this._setObjectProperties(vm, {
nameLabel: snapshotNameLabel
})::pCatch(noop)
}
const baseVm = baseVmId && this.getObject(baseVmId)
// refs of VM's VDIs → base's VDIs.
const baseVdis = {}
baseVm && forEach(baseVm.$VBDs, vbd => {
let vdi, snapshotOf
if (
(vdi = vbd.$VDI) &&
(snapshotOf = vdi.$snapshot_of) &&
!find(fullVdisRequired, id => snapshotOf.$id === id)
) {
baseVdis[vdi.snapshot_of] = vdi
}
})
const streams = {}
const vdis = {}
const vbds = {}
forEach(vm.$VBDs, vbd => {
let vdi
if (
vbd.type !== 'Disk' ||
!(vdi = vbd.$VDI)
) {
// Ignore this VBD.
return
}
// If the VDI name start with `[NOBAK]`, do not export it.
if (startsWith(vdi.name_label, '[NOBAK]')) {
// FIXME: find a way to not create the VDI snapshot in the
// first time.
//
// The snapshot must not exist otherwise it could break the
// next export.
this._deleteVdi(vdi)::pCatch(noop)
return
}
vbds[vbd.$ref] = vbd
const vdiRef = vdi.$ref
if (vdiRef in vdis) {
// This VDI has already been managed.
return
}
// Look for a snapshot of this vdi in the base VM.
const baseVdi = baseVdis[vdi.snapshot_of]
vdis[vdiRef] = baseVdi && !disableBaseTags
? {
...vdi,
other_config: {
...vdi.other_config,
[TAG_BASE_DELTA]: baseVdi.uuid
},
$SR$uuid: vdi.$SR.uuid
}
: {
...vdi,
$SR$uuid: vdi.$SR.uuid
}
const stream = streams[`${vdiRef}.vhd`] = this._exportVdi($cancelToken, vdi, baseVdi, VDI_FORMAT_VHD)
$onFailure(stream.cancel)
})
const vifs = {}
forEach(vm.$VIFs, vif => {
vifs[vif.$ref] = {
...vif,
$network$uuid: vif.$network.uuid
}
})
return Object.defineProperty({
version: '1.1.0',
vbds,
vdis,
vifs,
vm: baseVm && !disableBaseTags
? {
...vm,
other_config: {
...vm.other_config,
[TAG_BASE_DELTA]: baseVm.uuid
}
}
: {
...vm,
other_config: omit(vm.other_config, TAG_BASE_DELTA)
}
}, 'streams', {
value: await streams::pAll()
})
}
@deferrable.onFailure
async importDeltaVm ($onFailure, delta, {
deleteBase = false,
name_label = delta.vm.name_label,
srId = this.pool.default_SR,
disableStartAfterImport = true
} = {}) {
const { version } = delta
if (!versionSatisfies(version, '^1')) {
throw new Error(`Unsupported delta backup version: ${version}`)
}
const remoteBaseVmUuid = delta.vm.other_config[TAG_BASE_DELTA]
let baseVm
if (remoteBaseVmUuid) {
baseVm = find(this.objects.all, obj => (
(obj = obj.other_config) &&
obj[TAG_COPY_SRC] === remoteBaseVmUuid
))
if (!baseVm) {
throw new Error('could not find the base VM')
}
}
const sr = this.getObject(srId)
const baseVdis = {}
baseVm && forEach(baseVm.$VBDs, vbd => {
baseVdis[vbd.VDI] = vbd.$VDI
})
const { streams } = delta
// 1. Create the VMs.
const vm = await this._getOrWaitObject(
await this._createVmRecord({
...delta.vm,
affinity: null,
is_a_template: false
})
)
$onFailure(() => this._deleteVm(vm))
await Promise.all([
this._setObjectProperties(vm, {
name_label: `[Importing…] ${name_label}`
}),
this._updateObjectMapProperty(vm, 'blocked_operations', {
start: 'Importing…'
}),
this._updateObjectMapProperty(vm, 'other_config', {
[TAG_COPY_SRC]: delta.vm.uuid
})
])
// 2. Delete all VBDs which may have been created by the import.
await Promise.all(mapToArray(
vm.$VBDs,
vbd => this._deleteVbd(vbd)::pCatch(noop)
))
// 3. Create VDIs.
const newVdis = await map(delta.vdis, async vdi => {
const remoteBaseVdiUuid = vdi.other_config[TAG_BASE_DELTA]
if (!remoteBaseVdiUuid) {
const newVdi = await this.createVdi(vdi.virtual_size, {
...vdi,
other_config: {
...vdi.other_config,
[TAG_BASE_DELTA]: undefined,
[TAG_COPY_SRC]: vdi.uuid
},
sr: sr.$id
})
$onFailure(() => this._deleteVdi(newVdi))
return newVdi
}
const baseVdi = find(
baseVdis,
vdi => vdi.other_config[TAG_COPY_SRC] === remoteBaseVdiUuid
)
if (!baseVdi) {
throw new Error(`missing base VDI (copy of ${remoteBaseVdiUuid})`)
}
const newVdi = await this._getOrWaitObject(
await this._cloneVdi(baseVdi)
)
$onFailure(() => this._deleteVdi(newVdi))
await this._updateObjectMapProperty(newVdi, 'other_config', {
[TAG_COPY_SRC]: vdi.uuid
})
return newVdi
})::pAll()
const networksOnPoolMasterByDevice = {}
let defaultNetwork
forEach(this.pool.$master.$PIFs, pif => {
defaultNetwork = networksOnPoolMasterByDevice[pif.device] = pif.$network
})
await Promise.all([
// Create VBDs.
Promise.all(mapToArray(
delta.vbds,
vbd => this._createVbd(vm, newVdis[vbd.VDI], vbd)
)),
// Import VDI contents.
Promise.all(mapToArray(
newVdis,
async (vdi, id) => {
for (const stream of ensureArray(streams[`${id}.vhd`])) {
await this._importVdiContent(vdi, stream, VDI_FORMAT_VHD)
}
}
)),
// Wait for VDI export tasks (if any) termination.
Promise.all(mapToArray(
streams,
stream => stream.task
)),
// Create VIFs.
Promise.all(mapToArray(delta.vifs, vif => {
const network =
(vif.$network$uuid && this.getObject(vif.$network$uuid, null)) ||
networksOnPoolMasterByDevice[vif.device] ||
defaultNetwork
if (network) {
return this._createVif(
vm,
network,
vif
)
}
}))
])
if (deleteBase && baseVm) {
this._deleteVm(baseVm)::pCatch(noop)
}
await Promise.all([
this._setObjectProperties(vm, {
name_label
}),
// FIXME: move
this._updateObjectMapProperty(vm, 'blocked_operations', {
start: disableStartAfterImport
? 'Do not start this VM, clone it if you want to use it.'
: null
})
])
return vm
}
async _migrateVmWithStorageMotion (vm, hostXapi, host, {
migrationNetwork = find(host.$PIFs, pif => pif.management).$network, // TODO: handle not found
mapVdisSrs,
mapVifsNetworks
}) {
// VDIs/SRs mapping
const vdis = {}
const defaultSr = host.$pool.$default_SR
for (const vbd of vm.$VBDs) {
const vdi = vbd.$VDI
if (vbd.type === 'Disk') {
vdis[vdi.$ref] = mapVdisSrs && mapVdisSrs[vdi.$id]
? hostXapi.getObject(mapVdisSrs[vdi.$id]).$ref
: defaultSr.$ref // Will error if there are no default SR.
}
}
// VIFs/Networks mapping
let vifsMap = {}
if (vm.$pool !== host.$pool) {
const defaultNetworkRef = find(host.$PIFs, pif => pif.management).$network.$ref
for (const vif of vm.$VIFs) {
vifsMap[vif.$ref] = mapVifsNetworks && mapVifsNetworks[vif.$id]
? hostXapi.getObject(mapVifsNetworks[vif.$id]).$ref
: defaultNetworkRef
}
}
const token = await hostXapi.call(
'host.migrate_receive',
host.$ref,
migrationNetwork.$ref,
{}
)
const loop = () => this.call(
'VM.migrate_send',
vm.$ref,
token,
true, // Live migration.
vdis,
vifsMap,
{
force: 'true'
}
)::pCatch(
{ code: 'TOO_MANY_STORAGE_MIGRATES' },
() => pDelay(1e4).then(loop)
)
return loop()
}
@synchronized
_callInstallationPlugin (hostRef, vdi) {
return this.call('host.call_plugin', hostRef, 'install-supp-pack', 'install', { vdi }).catch(error => {
if (error.code !== 'XENAPI_PLUGIN_FAILURE') {
console.warn('_callInstallationPlugin', error)
throw error
}
})
}
@deferrable
async installSupplementalPack ($defer, stream, { hostId }) {
if (!stream.length) {
throw new Error('stream must have a length')
}
const vdi = await this.createTemporaryVdiOnHost(stream, hostId, '[XO] Supplemental pack ISO', 'small temporary VDI to store a supplemental pack ISO')
$defer(() => this._deleteVdi(vdi))
await this._callInstallationPlugin(this.getObject(hostId).$ref, vdi.uuid)
}
@deferrable
async installSupplementalPackOnAllHosts ($defer, stream) {
if (!stream.length) {
throw new Error('stream must have a length')
}
const isSrAvailable = sr =>
sr && sr.content_type === 'user' && sr.physical_size - sr.physical_utilisation >= stream.length
const hosts = filter(this.objects.all, { $type: 'host' })
const sr = this.findAvailableSharedSr(stream.length)
// Shared SR available: create only 1 VDI for all the installations
if (sr) {
const vdi = await this.createTemporaryVdiOnSr(stream, sr, '[XO] Supplemental pack ISO', 'small temporary VDI to store a supplemental pack ISO')
$defer(() => this._deleteVdi(vdi))
// Install pack sequentially to prevent concurrent access to the unique VDI
for (const host of hosts) {
await this._callInstallationPlugin(host.$ref, vdi.uuid)
}
return
}
// No shared SR available: find an available local SR on each host
return Promise.all(mapToArray(hosts, deferrable(async ($defer, host) => {
// pipe stream synchronously to several PassThroughs to be able to pipe them asynchronously later
const pt = stream.pipe(new PassThrough())
pt.length = stream.length
const sr = find(
mapToArray(host.$PBDs, '$SR'),
isSrAvailable
)
if (!sr) {
throw new Error('no SR available to store installation file')
}
const vdi = await this.createTemporaryVdiOnSr(pt, sr, '[XO] Supplemental pack ISO', 'small temporary VDI to store a supplemental pack ISO')
$defer(() => this._deleteVdi(vdi))
await this._callInstallationPlugin(host.$ref, vdi.uuid)
})))
}
async _importVm (stream, sr, onlyMetadata = false, onVmCreation = undefined) {
const taskRef = await this.createTask('VM import')
const query = {
force: onlyMetadata
}
let host
if (sr != null) {
host = sr.$PBDs[0].$host
query.sr_id = sr.$ref
}
if (onVmCreation) {
this._waitObject(
obj => obj && obj.current_operations && taskRef in obj.current_operations
).then(onVmCreation)::pCatch(noop)
}
const vmRef = await this.putResource(
stream,
onlyMetadata ? '/import_metadata/' : '/import/',
{
host,
query,
task: taskRef
}
).then(extractOpaqueRef)
// Importing a metadata archive of running VMs is currently
// broken: its VBDs are incorrectly seen as attached.
//
// A call to VM.power_state_reset fixes this problem.
if (onlyMetadata) {
await this.call('VM.power_state_reset', vmRef)
}
return vmRef
}
@deferrable.onFailure
async _importOvaVm ($onFailure, stream, {
descriptionLabel,
disks,
memory,
nameLabel,
networks,
nCpus
}, sr) {
// 1. Create VM.
const vm = await this._getOrWaitObject(
await this._createVmRecord({
...OTHER_CONFIG_TEMPLATE,
memory_dynamic_max: memory,
memory_dynamic_min: memory,
memory_static_max: memory,
name_description: descriptionLabel,
name_label: nameLabel,
VCPUs_at_startup: nCpus,
VCPUs_max: nCpus
})
)
$onFailure(() => this._deleteVm(vm))
// Disable start and change the VM name label during import.
await Promise.all([
this.addForbiddenOperationToVm(vm.$id, 'start', 'OVA import in progress...'),
this._setObjectProperties(vm, { name_label: `[Importing...] ${nameLabel}` })
])
// 2. Create VDIs & Vifs.
const vdis = {}
const vifDevices = await this.call('VM.get_allowed_VIF_devices', vm.$ref)
await Promise.all(
map(disks, async disk => {
const vdi = vdis[disk.path] = await this.createVdi(disk.capacity, {
name_description: disk.descriptionLabel,
name_label: disk.nameLabel,
sr: sr.$ref
})
$onFailure(() => this._deleteVdi(vdi))
return this._createVbd(vm, vdi, { position: disk.position })
}).concat(map(networks, (networkId, i) => (
this._createVif(vm, this.getObject(networkId), {
device: vifDevices[i]
})
)))
)
// 3. Import VDIs contents.
await new Promise((resolve, reject) => {
const extract = tarStream.extract()
stream.on('error', reject)
extract.on('finish', resolve)
extract.on('error', reject)
extract.on('entry', async (entry, stream, cb) => {
// Not a disk to import.
const vdi = vdis[entry.name]
if (!vdi) {
stream.on('end', cb)
stream.resume()
return
}
const vhdStream = await vmdkToVhd(stream)
await this._importVdiContent(vdi, vhdStream, VDI_FORMAT_RAW)
// See: https://github.com/mafintosh/tar-stream#extracting
// No import parallelization.
cb()
})
stream.pipe(extract)
})
// Enable start and restore the VM name label after import.
await Promise.all([
this.removeForbiddenOperationFromVm(vm.$id, 'start'),
this._setObjectProperties(vm, { name_label: nameLabel })
])
return vm
}
// TODO: an XVA can contain multiple VMs
async importVm (stream, {
data,
onlyMetadata = false,
srId,
type = 'xva'
} = {}) {
const sr = srId && this.getObject(srId)
if (type === 'xva') {
return /* await */ this._getOrWaitObject(await this._importVm(
stream,
sr,
onlyMetadata
))
}
if (type === 'ova') {
return this._getOrWaitObject(await this._importOvaVm(stream, data, sr))
}
throw new Error(`unsupported type: '${type}'`)
}
async migrateVm (vmId, hostXapi, hostId, {
migrationNetworkId,
mapVifsNetworks,
mapVdisSrs
} = {}) {
const vm = this.getObject(vmId)
const host = hostXapi.getObject(hostId)
const accrossPools = vm.$pool !== host.$pool
const useStorageMotion = (
accrossPools ||
migrationNetworkId ||
mapVifsNetworks ||
mapVdisSrs
)
if (useStorageMotion) {
await this._migrateVmWithStorageMotion(vm, hostXapi, host, {
migrationNetwork: migrationNetworkId && hostXapi.getObject(migrationNetworkId),
mapVdisSrs,
mapVifsNetworks
})
} else {
try {
await this.call('VM.pool_migrate', vm.$ref, host.$ref, { force: 'true' })
} catch (error) {
if (error.code !== 'VM_REQUIRES_SR') {
throw error
}
// Retry using motion storage.
await this._migrateVmWithStorageMotion(vm, hostXapi, host, {})
}
}
}
async _snapshotVm (vm, nameLabel = vm.name_label) {
debug(`Snapshotting VM ${vm.name_label}${
nameLabel !== vm.name_label
? ` as ${nameLabel}`
: ''
}`)
let ref
try {
ref = await this.call('VM.snapshot_with_quiesce', vm.$ref, nameLabel)
this.addTag(ref, 'quiesce')::pCatch(noop) // ignore any failures
await this._waitObjectState(ref, vm => includes(vm.tags, 'quiesce'))
} catch (error) {
const { code } = error
if (
code !== 'VM_SNAPSHOT_WITH_QUIESCE_NOT_SUPPORTED' &&
// quiesce only work on a running VM
code !== 'VM_BAD_POWER_STATE' &&
// quiesce failed, fallback on standard snapshot
// TODO: emit warning
code !== 'VM_SNAPSHOT_WITH_QUIESCE_FAILED'
) {
throw error
}
ref = await this.call('VM.snapshot', vm.$ref, nameLabel)
}
// Convert the template to a VM and wait to have receive the up-
// to-date object.
const [ , snapshot ] = await Promise.all([
this.call('VM.set_is_a_template', ref, false),
this._waitObjectState(ref, snapshot => !snapshot.is_a_template)
])
return snapshot
}
async snapshotVm (vmId, nameLabel = undefined) {
return /* await */ this._snapshotVm(
this.getObject(vmId),
nameLabel
)
}
async setVcpuWeight (vmId, weight) {
weight = weight || null // Take all falsy values as a removal (0 included)
const vm = this.getObject(vmId)
await this._updateObjectMapProperty(vm, 'VCPUs_params', {weight})
}
async _startVm (vm, force) {
debug(`Starting VM ${vm.name_label}`)
if (force) {
await this._updateObjectMapProperty(vm, 'blocked_operations', {
start: null
})
}
return this.call(
'VM.start',
vm.$ref,
false, // Start paused?
false // Skip pre-boot checks?
)
}
async startVm (vmId, force) {
try {
await this._startVm(this.getObject(vmId), force)
} catch (e) {
if (e.code === 'OPERATION_BLOCKED') {
throw forbiddenOperation('Start', e.params[1])
}
throw e
}
}
async startVmOnCd (vmId) {
const vm = this.getObject(vmId)
if (isVmHvm(vm)) {
const { order } = vm.HVM_boot_params
await this._updateObjectMapProperty(vm, 'HVM_boot_params', {
order: 'd'
})
try {
await this._startVm(vm)
} finally {
await this._updateObjectMapProperty(vm, 'HVM_boot_params', {
order
})
}
} else {
// Find the original template by name (*sigh*).
const templateNameLabel = vm.other_config['base_template_name']
const template = templateNameLabel &&
find(this.objects.all, obj => (
obj.$type === 'vm' &&
obj.is_a_template &&
obj.name_label === templateNameLabel
))
const bootloader = vm.PV_bootloader
const bootables = []
try {
const promises = []
const cdDrive = this._getVmCdDrive(vm)
forEach(vm.$VBDs, vbd => {
promises.push(
this._setObjectProperties(vbd, {
bootable: vbd === cdDrive
})
)
bootables.push([ vbd, Boolean(vbd.bootable) ])
})
promises.push(
this._setObjectProperties(vm, {
PV_bootloader: 'eliloader'
}),
this._updateObjectMapProperty(vm, 'other_config', {
'install-distro': template && template.other_config['install-distro'],
'install-repository': 'cdrom'
})
)
await Promise.all(promises)
await this._startVm(vm)
} finally {
this._setObjectProperties(vm, {
PV_bootloader: bootloader
})::pCatch(noop)
forEach(bootables, ([ vbd, bootable ]) => {
this._setObjectProperties(vbd, { bootable })::pCatch(noop)
})
}
}
}
// vm_operations: http://xapi-project.github.io/xen-api/classes/vm.html
async addForbiddenOperationToVm (vmId, operation, reason) {
await this.call('VM.add_to_blocked_operations', this.getObject(vmId).$ref, operation, `[XO] ${reason}`)
}
async removeForbiddenOperationFromVm (vmId, operation) {
await this.call('VM.remove_from_blocked_operations', this.getObject(vmId).$ref, operation)
}
// =================================================================
async _createVbd (vm, vdi, {
bootable = false,
empty = !vdi,
type = 'Disk',
unpluggable = false,
userdevice = undefined,
mode = (type === 'Disk') ? 'RW' : 'RO',
position = userdevice,
readOnly = (mode === 'RO')
} = {}) {
debug(`Creating VBD for VDI ${vdi.name_label} on VM ${vm.name_label}`)
if (position == null) {
const allowed = await this.call('VM.get_allowed_VBD_devices', vm.$ref)
const {length} = allowed
if (!length) {
throw new Error('no allowed VBD positions (devices)')
}
if (type === 'CD') {
// Choose position 3 if allowed.
position = includes(allowed, '3')
? '3'
: allowed[0]
} else {
position = allowed[0]
// Avoid position 3 if possible.
if (position === '3' && length > 1) {
position = allowed[1]
}
}
}
// By default a VBD is unpluggable.
const vbdRef = await this.call('VBD.create', {
bootable: Boolean(bootable),
empty: Boolean(empty),
mode: readOnly ? 'RO' : 'RW',
other_config: {},
qos_algorithm_params: {},
qos_algorithm_type: '',
type,
unpluggable: Boolean(unpluggable),
userdevice: String(position),
VDI: vdi.$ref,
VM: vm.$ref
})
if (isVmRunning(vm)) {
await this.call('VBD.plug', vbdRef)
}
return vbdRef
}
_cloneVdi (vdi) {
debug(`Cloning VDI ${vdi.name_label}`)
return this.call('VDI.clone', vdi.$ref)
}
async _createVdi (size, {
name_description = undefined,
name_label = '',
other_config = {},
read_only = false,
sharable = false,
// FIXME: should be named srId or an object.
sr = this.pool.default_SR,
tags = [],
type = 'user',
xenstore_data = undefined
} = {}) {
sr = this.getObject(sr)
debug(`Creating VDI ${name_label} on ${sr.name_label}`)
sharable = Boolean(sharable)
read_only = Boolean(read_only)
const data = {
name_description,
name_label,
other_config,
read_only,
sharable,
tags,
type,
virtual_size: String(size),
SR: sr.$ref
}
if (xenstore_data) {
data.xenstore_data = xenstore_data
}
return /* await */ this.call('VDI.create', data)
}
async moveVdi (vdiId, srId) {
const vdi = this.getObject(vdiId)
const sr = this.getObject(srId)
if (vdi.SR === sr.$ref) {
return // nothing to do
}
debug(`Moving VDI ${vdi.name_label} from ${vdi.$SR.name_label} to ${sr.name_label}`)
try {
await this.call('VDI.pool_migrate', vdi.$ref, sr.$ref, {})
} catch (error) {
if (error.code !== 'VDI_NEEDS_VM_FOR_MIGRATE') {
throw error
}
const newVdiref = await this.call('VDI.copy', vdi.$ref, sr.$ref)
const newVdi = await this._getOrWaitObject(newVdiref)
await Promise.all(mapToArray(vdi.$VBDs, async vbd => {
// Remove the old VBD
await this.call('VBD.destroy', vbd.$ref)
// Attach the new VDI to the VM with old VBD settings
await this._createVbd(vbd.$VM, newVdi, {
bootable: vbd.bootable,
position: vbd.userdevice,
type: vbd.type,
readOnly: vbd.mode === 'RO'
})
// Remove the old VDI
await this._deleteVdi(vdi)
}))
}
}
// TODO: check whether the VDI is attached.
async _deleteVdi (vdi) {
debug(`Deleting VDI ${vdi.name_label}`)
await this.call('VDI.destroy', vdi.$ref)
}
async _resizeVdi (vdi, size) {
debug(`Resizing VDI ${vdi.name_label} from ${vdi.virtual_size} to ${size}`)
try {
await this.call('VDI.resize_online', vdi.$ref, String(size))
} catch (error) {
if (error.code !== 'SR_OPERATION_NOT_SUPPORTED') {
throw error
}
await this.call('VDI.resize', vdi.$ref, String(size))
}
}
_getVmCdDrive (vm) {
for (const vbd of vm.$VBDs) {
if (vbd.type === 'CD') {
return vbd
}
}
}
async _ejectCdFromVm (vm) {
const cdDrive = this._getVmCdDrive(vm)
if (cdDrive) {
await this.call('VBD.eject', cdDrive.$ref)
}
}
async _insertCdIntoVm (cd, vm, {
bootable = false,
force = false
} = {}) {
const cdDrive = await this._getVmCdDrive(vm)
if (cdDrive) {
try {
await this.call('VBD.insert', cdDrive.$ref, cd.$ref)
} catch (error) {
if (!force || error.code !== 'VBD_NOT_EMPTY') {
throw error
}
await this.call('VBD.eject', cdDrive.$ref)::pCatch(noop)
// Retry.
await this.call('VBD.insert', cdDrive.$ref, cd.$ref)
}
if (bootable !== Boolean(cdDrive.bootable)) {
await this._setObjectProperties(cdDrive, {bootable})
}
} else {
await this._createVbd(vm, cd, {
bootable,
type: 'CD'
})
}
}
async attachVdiToVm (vdiId, vmId, opts = undefined) {
await this._createVbd(
this.getObject(vmId),
this.getObject(vdiId),
opts
)
}
async connectVbd (vbdId) {
await this.call('VBD.plug', vbdId)
}
async _disconnectVbd (vbd) {
// TODO: check if VBD is attached before
try {
await this.call('VBD.unplug_force', vbd.$ref)
} catch (error) {
if (error.code === 'VBD_NOT_UNPLUGGABLE') {
await this.call('VBD.set_unpluggable', vbd.$ref, true)
return this.call('VBD.unplug_force', vbd.$ref)
}
}
}
async disconnectVbd (vbdId) {
await this._disconnectVbd(this.getObject(vbdId))
}
async _deleteVbd (vbd) {
await this._disconnectVbd(vbd)::pCatch(noop)
await this.call('VBD.destroy', vbd.$ref)
}
deleteVbd (vbdId) {
return this._deleteVbd(this.getObject(vbdId))
}
// TODO: remove when no longer used.
async destroyVbdsFromVm (vmId) {
await Promise.all(
mapToArray(this.getObject(vmId).$VBDs, async vbd => {
await this.disconnectVbd(vbd.$ref)::pCatch(noop)
return this.call('VBD.destroy', vbd.$ref)
})
)
}
async createVdi (size, opts) {
return /* await */ this._getOrWaitObject(
await this._createVdi(size, opts)
)
}
async deleteVdi (vdiId) {
await this._deleteVdi(this.getObject(vdiId))
}
async resizeVdi (vdiId, size) {
await this._resizeVdi(this.getObject(vdiId), size)
}
async ejectCdFromVm (vmId) {
await this._ejectCdFromVm(this.getObject(vmId))
}
async insertCdIntoVm (cdId, vmId, opts = undefined) {
await this._insertCdIntoVm(
this.getObject(cdId),
this.getObject(vmId),
opts
)
}
// -----------------------------------------------------------------
async snapshotVdi (vdiId, nameLabel) {
const vdi = this.getObject(vdiId)
const snap = await this._getOrWaitObject(
await this.call('VDI.snapshot', vdi.$ref)
)
if (nameLabel) {
await this.call('VDI.set_name_label', snap.$ref, nameLabel)
}
return snap
}
@cancellable
_exportVdi ($cancelToken, vdi, base, format = VDI_FORMAT_VHD) {
const host = vdi.$SR.$PBDs[0].$host
const query = {
format,
vdi: vdi.$ref
}
if (base) {
query.base = base.$ref
}
debug(`exporting VDI ${vdi.name_label}${base
? ` (from base ${vdi.name_label})`
: ''
}`)
return this.getResource($cancelToken, '/export_raw_vdi/', {
host,
query,
task: this.createTask('VDI Export', vdi.name_label)
})
}
// Returns a stream to the exported VDI.
exportVdi (vdiId, {
baseId,
format
} = {}) {
return this._exportVdi(
this.getObject(vdiId),
baseId && this.getObject(baseId),
format
)
}
// -----------------------------------------------------------------
async _importVdiContent (vdi, body, format = VDI_FORMAT_VHD) {
const pbd = find(vdi.$SR.$PBDs, 'currently_attached')
if (pbd === undefined) {
throw new Error('no valid PBDs found')
}
await Promise.all([
body.checksumVerified,
this.putResource(body, '/import_raw_vdi/', {
host: pbd.host,
query: {
format,
vdi: vdi.$ref
},
task: this.createTask('VDI Content Import', vdi.name_label)
})
])
}
importVdiContent (vdiId, body, {
format
} = {}) {
return this._importVdiContent(
this.getObject(vdiId),
body,
format
)
}
// =================================================================
async _createVif (vm, network, {
mac = '',
position = undefined,
currently_attached = true,
device = position != null ? String(position) : undefined,
ipv4_allowed = undefined,
ipv6_allowed = undefined,
locking_mode = undefined,
MAC = mac,
other_config = {},
qos_algorithm_params = {},
qos_algorithm_type = ''
} = {}) {
debug(`Creating VIF for VM ${vm.name_label} on network ${network.name_label}`)
if (device == null) {
device = (await this.call('VM.get_allowed_VIF_devices', vm.$ref))[0]
}
const vifRef = await this.call('VIF.create', filterUndefineds({
device,
ipv4_allowed,
ipv6_allowed,
locking_mode,
MAC,
MTU: asInteger(network.MTU),
network: network.$ref,
other_config,
qos_algorithm_params,
qos_algorithm_type,
VM: vm.$ref
}))
if (currently_attached && isVmRunning(vm)) {
await this.call('VIF.plug', vifRef)
}
return vifRef
}
async createVif (vmId, networkId, opts = undefined) {
return /* await */ this._getOrWaitObject(
await this._createVif(
this.getObject(vmId),
this.getObject(networkId),
opts
)
)
}
async createNetwork ({
name,
description = 'Created with Xen Orchestra',
pifId,
mtu,
vlan
}) {
const networkRef = await this.call('network.create', {
name_label: name,
name_description: description,
MTU: asInteger(mtu),
other_config: {}
})
if (pifId) {
await this.call('pool.create_VLAN_from_PIF', this.getObject(pifId).$ref, networkRef, asInteger(vlan))
}
return this._getOrWaitObject(networkRef)
}
async editPif (
pifId,
{ vlan }
) {
const pif = this.getObject(pifId)
const physPif = find(this.objects.all, obj => (
obj.$type === 'pif' &&
(obj.physical || !isEmpty(obj.bond_master_of)) &&
obj.$pool === pif.$pool &&
obj.device === pif.device
))
if (!physPif) {
throw new Error('PIF not found')
}
const pifs = this.getObject(pif.network).$PIFs
const wasAttached = {}
forEach(pifs, pif => {
wasAttached[pif.host] = pif.currently_attached
})
const vlans = uniq(mapToArray(pifs, pif => pif.VLAN_master_of))
await Promise.all(
mapToArray(vlans, vlan => vlan !== NULL_REF && this.call('VLAN.destroy', vlan))
)
const newPifs = await this.call('pool.create_VLAN_from_PIF', physPif.$ref, pif.network, asInteger(vlan))
await Promise.all(
mapToArray(newPifs, pifRef =>
!wasAttached[this.getObject(pifRef).host] && this.call('PIF.unplug', pifRef)::pCatch(noop)
)
)
}
async createBondedNetwork ({
bondMode,
mac,
pifIds,
...params
}) {
const network = await this.createNetwork(params)
// TODO: test and confirm:
// Bond.create is called here with PIFs from one host but XAPI should then replicate the
// bond on each host in the same pool with the corresponding PIFs (ie same interface names?).
await this.call('Bond.create', network.$ref, map(pifIds, pifId => this.getObject(pifId).$ref), mac, bondMode)
return network
}
async deleteNetwork (networkId) {
const network = this.getObject(networkId)
const pifs = network.$PIFs
const vlans = uniq(mapToArray(pifs, pif => pif.VLAN_master_of))
await Promise.all(
mapToArray(vlans, vlan => vlan !== NULL_REF && this.call('VLAN.destroy', vlan))
)
const bonds = uniq(flatten(mapToArray(pifs, pif => pif.bond_master_of)))
await Promise.all(
mapToArray(bonds, bond => this.call('Bond.destroy', bond))
)
await this.call('network.destroy', network.$ref)
}
// =================================================================
async _doDockerAction (vmId, action, containerId) {
const vm = this.getObject(vmId)
const host = vm.$resident_on || this.pool.$master
return /* await */ this.call('host.call_plugin', host.$ref, 'xscontainer', action, {
vmuuid: vm.uuid,
container: containerId
})
}
async registerDockerContainer (vmId) {
await this._doDockerAction(vmId, 'register')
}
async deregisterDockerContainer (vmId) {
await this._doDockerAction(vmId, 'deregister')
}
async startDockerContainer (vmId, containerId) {
await this._doDockerAction(vmId, 'start', containerId)
}
async stopDockerContainer (vmId, containerId) {
await this._doDockerAction(vmId, 'stop', containerId)
}
async restartDockerContainer (vmId, containerId) {
await this._doDockerAction(vmId, 'restart', containerId)
}
async pauseDockerContainer (vmId, containerId) {
await this._doDockerAction(vmId, 'pause', containerId)
}
async unpauseDockerContainer (vmId, containerId) {
await this._doDockerAction(vmId, 'unpause', containerId)
}
async getCloudInitConfig (templateId) {
const template = this.getObject(templateId)
const host = this.pool.$master
let config = await this.call('host.call_plugin', host.$ref, 'xscontainer', 'get_config_drive_default', {
templateuuid: template.uuid
})
return config.slice(4) // FIXME remove the "True" string on the begining
}
// Specific CoreOS Config Drive
async createCoreOsCloudInitConfigDrive (vmId, srId, config) {
const vm = this.getObject(vmId)
const host = this.pool.$master
const sr = this.getObject(srId)
await this.call('host.call_plugin', host.$ref, 'xscontainer', 'create_config_drive', {
vmuuid: vm.uuid,
sruuid: sr.uuid,
configuration: config
})
await this.registerDockerContainer(vmId)
}
// Generic Config Drive
@deferrable.onFailure
async createCloudInitConfigDrive ($onFailure, vmId, srId, config) {
const vm = this.getObject(vmId)
const sr = this.getObject(srId)
// First, create a small VDI (10MB) which will become the ConfigDrive
const buffer = fatfsBufferInit()
const vdi = await this.createVdi(buffer.length, { name_label: 'XO CloudConfigDrive', name_description: undefined, sr: sr.$ref })
$onFailure(() => this._deleteVdi(vdi))
// Then, generate a FAT fs
const fs = promisifyAll(fatfs.createFileSystem(fatfsBuffer(buffer)))
await fs.mkdir('openstack')
await fs.mkdir('openstack/latest')
await Promise.all([
fs.writeFile(
'openstack/latest/meta_data.json',
'{\n "uuid": "' + vm.uuid + '"\n}\n'
),
fs.writeFile('openstack/latest/user_data', config)
])
// ignore VDI_IO_ERROR errors, I (JFT) don't understand why they
// are emitted because it works
await this._importVdiContent(vdi, buffer, VDI_FORMAT_RAW)::pCatch(
{ code: 'VDI_IO_ERROR' },
console.warn
)
await this._createVbd(vm, vdi)
}
@deferrable.onFailure
async createTemporaryVdiOnSr ($onFailure, stream, sr, name_label, name_description) {
const vdi = await this.createVdi(stream.length, {
sr: sr.$ref,
name_label,
name_description
})
$onFailure(() => this._deleteVdi(vdi))
await this.importVdiContent(vdi.$id, stream, { format: VDI_FORMAT_RAW })
return vdi
}
// Create VDI on an adequate local SR
async createTemporaryVdiOnHost (stream, hostId, name_label, name_description) {
const pbd = find(
this.getObject(hostId).$PBDs,
pbd => canSrHaveNewVdiOfSize(pbd.$SR, stream.length)
)
if (pbd == null) {
throw new Error('no SR available')
}
return this.createTemporaryVdiOnSr(stream, pbd.SR, name_label, name_description)
}
async findAvailableSharedSr (minSize) {
return find(
this.objects.all,
obj => obj.$type === 'sr' && obj.shared && canSrHaveNewVdiOfSize(obj, minSize)
)
}
// =================================================================
}
| src/xapi/index.js | /* eslint-disable camelcase */
import deferrable from 'golike-defer'
import fatfs from 'fatfs'
import synchronized from 'decorator-synchronized'
import tarStream from 'tar-stream'
import vmdkToVhd from 'xo-vmdk-to-vhd'
import { cancellable, defer } from 'promise-toolbox'
import { PassThrough } from 'stream'
import { forbiddenOperation } from 'xo-common/api-errors'
import {
every,
find,
filter,
flatten,
groupBy,
includes,
isEmpty,
omit,
startsWith,
uniq
} from 'lodash'
import {
Xapi as XapiBase
} from 'xen-api'
import {
satisfies as versionSatisfies
} from 'semver'
import createSizeStream from '../size-stream'
import fatfsBuffer, { init as fatfsBufferInit } from '../fatfs-buffer'
import { mixin } from '../decorators'
import {
camelToSnakeCase,
createRawObject,
ensureArray,
forEach,
isFunction,
map,
mapToArray,
noop,
pAll,
pCatch,
pDelay,
pFinally,
promisifyAll,
pSettle
} from '../utils'
import mixins from './mixins'
import OTHER_CONFIG_TEMPLATE from './other-config-template'
import {
asBoolean,
asInteger,
debug,
extractOpaqueRef,
filterUndefineds,
getNamespaceForType,
canSrHaveNewVdiOfSize,
isVmHvm,
isVmRunning,
NULL_REF,
optional,
prepareXapiParam
} from './utils'
// ===================================================================
const TAG_BASE_DELTA = 'xo:base_delta'
const TAG_COPY_SRC = 'xo:copy_of'
// ===================================================================
// FIXME: remove this work around when fixed, https://phabricator.babeljs.io/T2877
// export * from './utils'
require('lodash/assign')(module.exports, require('./utils'))
// VDI formats. (Raw is not available for delta vdi.)
export const VDI_FORMAT_VHD = 'vhd'
export const VDI_FORMAT_RAW = 'raw'
export const IPV4_CONFIG_MODES = ['None', 'DHCP', 'Static']
export const IPV6_CONFIG_MODES = ['None', 'DHCP', 'Static', 'Autoconf']
// ===================================================================
@mixin(mapToArray(mixins))
export default class Xapi extends XapiBase {
constructor (...args) {
super(...args)
// Patch getObject to resolve _xapiId property.
this.getObject = (getObject => (...args) => {
let tmp
if ((tmp = args[0]) != null && (tmp = tmp._xapiId) != null) {
args[0] = tmp
}
return getObject.apply(this, args)
})(this.getObject)
const genericWatchers = this._genericWatchers = createRawObject()
const objectsWatchers = this._objectWatchers = createRawObject()
const onAddOrUpdate = objects => {
forEach(objects, object => {
const {
$id: id,
$ref: ref
} = object
// Run generic watchers.
for (const watcherId in genericWatchers) {
genericWatchers[watcherId](object)
}
// Watched object.
if (id in objectsWatchers) {
objectsWatchers[id].resolve(object)
delete objectsWatchers[id]
}
if (ref in objectsWatchers) {
objectsWatchers[ref].resolve(object)
delete objectsWatchers[ref]
}
})
}
this.objects.on('add', onAddOrUpdate)
this.objects.on('update', onAddOrUpdate)
}
call (...args) {
const fn = super.call
const loop = () => fn.apply(this, args)::pCatch({
code: 'TOO_MANY_PENDING_TASKS'
}, () => pDelay(5e3).then(loop))
return loop()
}
createTask (name = 'untitled task', description) {
return super.createTask(`[XO] ${name}`, description)
}
// =================================================================
_registerGenericWatcher (fn) {
const watchers = this._genericWatchers
const id = String(Math.random())
watchers[id] = fn
return () => {
delete watchers[id]
}
}
// Wait for an object to appear or to be updated.
//
// Predicate can be either an id, a UUID, an opaque reference or a
// function.
//
// TODO: implements a timeout.
_waitObject (predicate) {
if (isFunction(predicate)) {
const { promise, resolve } = defer()
const unregister = this._registerGenericWatcher(obj => {
if (predicate(obj)) {
unregister()
resolve(obj)
}
})
return promise
}
let watcher = this._objectWatchers[predicate]
if (!watcher) {
const { promise, resolve } = defer()
// Register the watcher.
watcher = this._objectWatchers[predicate] = {
promise,
resolve
}
}
return watcher.promise
}
// Wait for an object to be in a given state.
//
// Faster than _waitObject() with a function.
_waitObjectState (idOrUuidOrRef, predicate) {
const object = this.getObject(idOrUuidOrRef, null)
if (object && predicate(object)) {
return object
}
const loop = () => this._waitObject(idOrUuidOrRef).then(
(object) => predicate(object) ? object : loop()
)
return loop()
}
// Returns the objects if already presents or waits for it.
async _getOrWaitObject (idOrUuidOrRef) {
return (
this.getObject(idOrUuidOrRef, null) ||
this._waitObject(idOrUuidOrRef)
)
}
// =================================================================
_setObjectProperty (object, name, value) {
return this.call(
`${getNamespaceForType(object.$type)}.set_${camelToSnakeCase(name)}`,
object.$ref,
prepareXapiParam(value)
)
}
_setObjectProperties (object, props) {
const {
$ref: ref,
$type: type
} = object
const namespace = getNamespaceForType(type)
// TODO: the thrown error should contain the name of the
// properties that failed to be set.
return Promise.all(mapToArray(props, (value, name) => {
if (value != null) {
return this.call(`${namespace}.set_${camelToSnakeCase(name)}`, ref, prepareXapiParam(value))
}
}))::pCatch(noop)
}
async _updateObjectMapProperty (object, prop, values) {
const {
$ref: ref,
$type: type
} = object
prop = camelToSnakeCase(prop)
const namespace = getNamespaceForType(type)
const add = `${namespace}.add_to_${prop}`
const remove = `${namespace}.remove_from_${prop}`
await Promise.all(mapToArray(values, (value, name) => {
if (value !== undefined) {
name = camelToSnakeCase(name)
const removal = this.call(remove, ref, name)
return value === null
? removal
: removal::pCatch(noop).then(() => this.call(add, ref, name, prepareXapiParam(value)))
}
}))
}
async setHostProperties (id, {
nameLabel,
nameDescription
}) {
await this._setObjectProperties(this.getObject(id), {
nameLabel,
nameDescription
})
}
async setPoolProperties ({
autoPoweron,
nameLabel,
nameDescription
}) {
const { pool } = this
await Promise.all([
this._setObjectProperties(pool, {
nameLabel,
nameDescription
}),
autoPoweron != null && this._updateObjectMapProperty(pool, 'other_config', {
autoPoweron: autoPoweron ? 'true' : null
})
])
}
async setSrProperties (id, {
nameLabel,
nameDescription
}) {
await this._setObjectProperties(this.getObject(id), {
nameLabel,
nameDescription
})
}
async setNetworkProperties (id, {
nameLabel,
nameDescription,
defaultIsLocked
}) {
let defaultLockingMode
if (defaultIsLocked != null) {
defaultLockingMode = defaultIsLocked ? 'disabled' : 'unlocked'
}
await this._setObjectProperties(this.getObject(id), {
nameLabel,
nameDescription,
defaultLockingMode
})
}
// =================================================================
async addTag (id, tag) {
const {
$ref: ref,
$type: type
} = this.getObject(id)
const namespace = getNamespaceForType(type)
await this.call(`${namespace}.add_tags`, ref, tag)
}
async removeTag (id, tag) {
const {
$ref: ref,
$type: type
} = this.getObject(id)
const namespace = getNamespaceForType(type)
await this.call(`${namespace}.remove_tags`, ref, tag)
}
// =================================================================
async setDefaultSr (srId) {
this._setObjectProperties(this.pool, {
default_SR: this.getObject(srId).$ref
})
}
// =================================================================
async joinPool (masterAddress, masterUsername, masterPassword, force = false) {
await this.call(
force ? 'pool.join_force' : 'pool.join',
masterAddress,
masterUsername,
masterPassword
)
}
// =================================================================
async emergencyShutdownHost (hostId) {
const host = this.getObject(hostId)
const vms = host.$resident_VMs
debug(`Emergency shutdown: ${host.name_label}`)
await pSettle(
mapToArray(vms, vm => {
if (!vm.is_control_domain) {
return this.call('VM.suspend', vm.$ref)
}
})
)
await this.call('host.disable', host.$ref)
await this.call('host.shutdown', host.$ref)
}
// =================================================================
// Disable the host and evacuate all its VMs.
//
// If `force` is false and the evacuation failed, the host is re-
// enabled and the error is thrown.
async _clearHost ({ $ref: ref }, force) {
await this.call('host.disable', ref)
try {
await this.call('host.evacuate', ref)
} catch (error) {
if (!force) {
await this.call('host.enable', ref)
throw error
}
}
}
async disableHost (hostId) {
await this.call('host.disable', this.getObject(hostId).$ref)
}
async ejectHostFromPool (hostId) {
await this.call('pool.eject', this.getObject(hostId).$ref)
}
async enableHost (hostId) {
await this.call('host.enable', this.getObject(hostId).$ref)
}
async powerOnHost (hostId) {
await this.call('host.power_on', this.getObject(hostId).$ref)
}
async rebootHost (hostId, force = false) {
const host = this.getObject(hostId)
await this._clearHost(host, force)
await this.call('host.reboot', host.$ref)
}
async restartHostAgent (hostId) {
await this.call('host.restart_agent', this.getObject(hostId).$ref)
}
async shutdownHost (hostId, force = false) {
const host = this.getObject(hostId)
await this._clearHost(host, force)
await this.call('host.shutdown', host.$ref)
}
// =================================================================
// Clone a VM: make a fast copy by fast copying each of its VDIs
// (using snapshots where possible) on the same SRs.
_cloneVm (vm, nameLabel = vm.name_label) {
debug(`Cloning VM ${vm.name_label}${
nameLabel !== vm.name_label
? ` as ${nameLabel}`
: ''
}`)
return this.call('VM.clone', vm.$ref, nameLabel)
}
// Copy a VM: make a normal copy of a VM and all its VDIs.
//
// If a SR is specified, it will contains the copies of the VDIs,
// otherwise they will use the SRs they are on.
async _copyVm (vm, nameLabel = vm.name_label, sr = undefined) {
let snapshot
if (isVmRunning(vm)) {
snapshot = await this._snapshotVm(vm)
}
debug(`Copying VM ${vm.name_label}${
nameLabel !== vm.name_label
? ` as ${nameLabel}`
: ''
}${
sr
? ` on ${sr.name_label}`
: ''
}`)
try {
return await this.call(
'VM.copy',
snapshot ? snapshot.$ref : vm.$ref,
nameLabel,
sr ? sr.$ref : ''
)
} finally {
if (snapshot) {
await this._deleteVm(snapshot)
}
}
}
async cloneVm (vmId, {
nameLabel = undefined,
fast = true
} = {}) {
const vm = this.getObject(vmId)
const cloneRef = await (
fast
? this._cloneVm(vm, nameLabel)
: this._copyVm(vm, nameLabel)
)
return /* await */ this._getOrWaitObject(cloneRef)
}
async copyVm (vmId, srId, {
nameLabel = undefined
} = {}) {
return /* await */ this._getOrWaitObject(
await this._copyVm(
this.getObject(vmId),
nameLabel,
this.getObject(srId)
)
)
}
async remoteCopyVm (vmId, targetXapi, targetSrId, {
compress = true,
nameLabel = undefined
} = {}) {
// Fall back on local copy if possible.
if (targetXapi === this) {
return {
vm: await this.copyVm(vmId, targetSrId, { nameLabel })
}
}
const sr = targetXapi.getObject(targetSrId)
let stream = await this.exportVm(vmId, {
compress,
onlyMetadata: false
})
const sizeStream = createSizeStream()
stream = stream.pipe(sizeStream)
const onVmCreation = nameLabel !== undefined
? vm => targetXapi._setObjectProperties(vm, {
nameLabel
})
: null
const vm = await targetXapi._getOrWaitObject(
await targetXapi._importVm(
stream,
sr,
false,
onVmCreation
)
)
return {
size: sizeStream.size,
vm
}
}
// Low level create VM.
_createVmRecord ({
actions_after_crash,
actions_after_reboot,
actions_after_shutdown,
affinity,
// appliance,
blocked_operations,
generation_id,
ha_always_run,
ha_restart_priority,
has_vendor_device = false, // Avoid issue with some Dundee builds.
hardware_platform_version,
HVM_boot_params,
HVM_boot_policy,
HVM_shadow_multiplier,
is_a_template,
memory_dynamic_max,
memory_dynamic_min,
memory_static_max,
memory_static_min,
name_description,
name_label,
order,
other_config,
PCI_bus,
platform,
protection_policy,
PV_args,
PV_bootloader,
PV_bootloader_args,
PV_kernel,
PV_legacy_args,
PV_ramdisk,
recommendations,
shutdown_delay,
start_delay,
// suspend_SR,
tags,
user_version,
VCPUs_at_startup,
VCPUs_max,
VCPUs_params,
version,
xenstore_data
}) {
debug(`Creating VM ${name_label}`)
return this.call('VM.create', filterUndefineds({
actions_after_crash,
actions_after_reboot,
actions_after_shutdown,
affinity: affinity == null ? NULL_REF : affinity,
HVM_boot_params,
HVM_boot_policy,
is_a_template: asBoolean(is_a_template),
memory_dynamic_max: asInteger(memory_dynamic_max),
memory_dynamic_min: asInteger(memory_dynamic_min),
memory_static_max: asInteger(memory_static_max),
memory_static_min: asInteger(memory_static_min),
other_config,
PCI_bus,
platform,
PV_args,
PV_bootloader,
PV_bootloader_args,
PV_kernel,
PV_legacy_args,
PV_ramdisk,
recommendations,
user_version: asInteger(user_version),
VCPUs_at_startup: asInteger(VCPUs_at_startup),
VCPUs_max: asInteger(VCPUs_max),
VCPUs_params,
// Optional fields.
blocked_operations,
generation_id,
ha_always_run: asBoolean(ha_always_run),
ha_restart_priority,
has_vendor_device,
hardware_platform_version: optional(hardware_platform_version, asInteger),
// HVM_shadow_multiplier: asFloat(HVM_shadow_multiplier), // FIXME: does not work FIELD_TYPE_ERROR(hVM_shadow_multiplier)
name_description,
name_label,
order: optional(order, asInteger),
protection_policy,
shutdown_delay: asInteger(shutdown_delay),
start_delay: asInteger(start_delay),
tags,
version: asInteger(version),
xenstore_data
}))
}
async _deleteVm (vm, deleteDisks = true) {
debug(`Deleting VM ${vm.name_label}`)
// It is necessary for suspended VMs to be shut down
// to be able to delete their VDIs.
if (vm.power_state !== 'Halted') {
await this.call('VM.hard_shutdown', vm.$ref)
}
if (deleteDisks) {
// Compute the VDIs list without duplicates.
const vdis = {}
forEach(vm.$VBDs, vbd => {
let vdi
if (
// Do not remove CDs and Floppies.
vbd.type === 'Disk' &&
// Ignore VBD without VDI.
(vdi = vbd.$VDI)
) {
vdis[vdi.$id] = vdi
}
})
await Promise.all(mapToArray(vdis, vdi => {
if (
// Do not remove VBDs attached to other VMs.
vdi.VBDs.length < 2 ||
every(vdi.$VBDs, vbd => vbd.VM === vm.$ref)
) {
return this._deleteVdi(vdi)::pCatch(noop)
}
console.error(`cannot delete VDI ${vdi.name_label} (from VM ${vm.name_label})`)
}))
}
await Promise.all(mapToArray(vm.$snapshots, snapshot =>
this.deleteVm(snapshot.$id)::pCatch(noop)
))
await this.call('VM.destroy', vm.$ref)
}
async deleteVm (vmId, deleteDisks) {
return /* await */ this._deleteVm(
this.getObject(vmId),
deleteDisks
)
}
getVmConsole (vmId) {
const vm = this.getObject(vmId)
const console = find(vm.$consoles, { protocol: 'rfb' })
if (!console) {
throw new Error('no RFB console found')
}
return console
}
// Returns a stream to the exported VM.
async exportVm (vmId, {
compress = true,
onlyMetadata = false
} = {}) {
const vm = this.getObject(vmId)
let host
let snapshotRef
// It's not needed to snapshot the VM to get the metadata
if (isVmRunning(vm) && !onlyMetadata) {
host = vm.$resident_on
snapshotRef = (await this._snapshotVm(vm)).$ref
}
const promise = this.getResource(onlyMetadata ? '/export_metadata/' : '/export/', {
host,
query: {
ref: snapshotRef || vm.$ref,
use_compression: compress ? 'true' : 'false'
},
task: this.createTask('VM export', vm.name_label)
})
if (snapshotRef !== undefined) {
promise.then(_ => _.task::pFinally(() =>
this.deleteVm(snapshotRef)::pCatch(noop)
))
}
return promise
}
_assertHealthyVdiChain (vdi, childrenMap) {
if (vdi == null) {
return
}
if (!vdi.managed) {
if (childrenMap === undefined) {
childrenMap = groupBy(vdi.$SR.$VDIs, _ => _.sm_config['vhd-parent'])
}
// an unmanaged VDI should not have exactly one child: they
// should coalesce
const children = childrenMap[vdi.uuid]
if (
children.length === 1 &&
!children[0].managed // some SRs do not coalesce the leaf
) {
throw new Error('unhealthy VDI chain')
}
}
this._assertHealthyVdiChain(
this.getObjectByUuid(vdi.sm_config['vhd-parent'], null),
childrenMap
)
}
_assertHealthyVdiChains (vm) {
forEach(vm.$VBDs, ({ $VDI }) => {
this._assertHealthyVdiChain($VDI)
})
}
// Create a snapshot of the VM and returns a delta export object.
@deferrable.onFailure
async exportDeltaVm ($onFailure, vmId, baseVmId = undefined, {
snapshotNameLabel = undefined,
// Contains a vdi.$id set of vmId.
fullVdisRequired = [],
disableBaseTags = false
} = {}) {
this._assertHealthyVdiChains(this.getObject(vmId))
const vm = await this.snapshotVm(vmId)
$onFailure(() => this._deleteVm(vm))
if (snapshotNameLabel) {
this._setObjectProperties(vm, {
nameLabel: snapshotNameLabel
})::pCatch(noop)
}
const baseVm = baseVmId && this.getObject(baseVmId)
// refs of VM's VDIs → base's VDIs.
const baseVdis = {}
baseVm && forEach(baseVm.$VBDs, vbd => {
let vdi, snapshotOf
if (
(vdi = vbd.$VDI) &&
(snapshotOf = vdi.$snapshot_of) &&
!find(fullVdisRequired, id => snapshotOf.$id === id)
) {
baseVdis[vdi.snapshot_of] = vdi
}
})
const streams = {}
const vdis = {}
const vbds = {}
forEach(vm.$VBDs, vbd => {
let vdi
if (
vbd.type !== 'Disk' ||
!(vdi = vbd.$VDI)
) {
// Ignore this VBD.
return
}
// If the VDI name start with `[NOBAK]`, do not export it.
if (startsWith(vdi.name_label, '[NOBAK]')) {
// FIXME: find a way to not create the VDI snapshot in the
// first time.
//
// The snapshot must not exist otherwise it could break the
// next export.
this._deleteVdi(vdi)::pCatch(noop)
return
}
vbds[vbd.$ref] = vbd
const vdiRef = vdi.$ref
if (vdiRef in vdis) {
// This VDI has already been managed.
return
}
// Look for a snapshot of this vdi in the base VM.
const baseVdi = baseVdis[vdi.snapshot_of]
vdis[vdiRef] = baseVdi && !disableBaseTags
? {
...vdi,
other_config: {
...vdi.other_config,
[TAG_BASE_DELTA]: baseVdi.uuid
},
$SR$uuid: vdi.$SR.uuid
}
: {
...vdi,
$SR$uuid: vdi.$SR.uuid
}
const stream = streams[`${vdiRef}.vhd`] = this._exportVdi(vdi, baseVdi, VDI_FORMAT_VHD)
$onFailure(() => stream.cancel())
})
const vifs = {}
forEach(vm.$VIFs, vif => {
vifs[vif.$ref] = {
...vif,
$network$uuid: vif.$network.uuid
}
})
return Object.defineProperty({
version: '1.1.0',
vbds,
vdis,
vifs,
vm: baseVm && !disableBaseTags
? {
...vm,
other_config: {
...vm.other_config,
[TAG_BASE_DELTA]: baseVm.uuid
}
}
: {
...vm,
other_config: omit(vm.other_config, TAG_BASE_DELTA)
}
}, 'streams', {
value: await streams::pAll()
})
}
@deferrable.onFailure
async importDeltaVm ($onFailure, delta, {
deleteBase = false,
name_label = delta.vm.name_label,
srId = this.pool.default_SR,
disableStartAfterImport = true
} = {}) {
const { version } = delta
if (!versionSatisfies(version, '^1')) {
throw new Error(`Unsupported delta backup version: ${version}`)
}
const remoteBaseVmUuid = delta.vm.other_config[TAG_BASE_DELTA]
let baseVm
if (remoteBaseVmUuid) {
baseVm = find(this.objects.all, obj => (
(obj = obj.other_config) &&
obj[TAG_COPY_SRC] === remoteBaseVmUuid
))
if (!baseVm) {
throw new Error('could not find the base VM')
}
}
const sr = this.getObject(srId)
const baseVdis = {}
baseVm && forEach(baseVm.$VBDs, vbd => {
baseVdis[vbd.VDI] = vbd.$VDI
})
const { streams } = delta
// 1. Create the VMs.
const vm = await this._getOrWaitObject(
await this._createVmRecord({
...delta.vm,
affinity: null,
is_a_template: false
})
)
$onFailure(() => this._deleteVm(vm))
await Promise.all([
this._setObjectProperties(vm, {
name_label: `[Importing…] ${name_label}`
}),
this._updateObjectMapProperty(vm, 'blocked_operations', {
start: 'Importing…'
}),
this._updateObjectMapProperty(vm, 'other_config', {
[TAG_COPY_SRC]: delta.vm.uuid
})
])
// 2. Delete all VBDs which may have been created by the import.
await Promise.all(mapToArray(
vm.$VBDs,
vbd => this._deleteVbd(vbd)::pCatch(noop)
))
// 3. Create VDIs.
const newVdis = await map(delta.vdis, async vdi => {
const remoteBaseVdiUuid = vdi.other_config[TAG_BASE_DELTA]
if (!remoteBaseVdiUuid) {
const newVdi = await this.createVdi(vdi.virtual_size, {
...vdi,
other_config: {
...vdi.other_config,
[TAG_BASE_DELTA]: undefined,
[TAG_COPY_SRC]: vdi.uuid
},
sr: sr.$id
})
$onFailure(() => this._deleteVdi(newVdi))
return newVdi
}
const baseVdi = find(
baseVdis,
vdi => vdi.other_config[TAG_COPY_SRC] === remoteBaseVdiUuid
)
if (!baseVdi) {
throw new Error(`missing base VDI (copy of ${remoteBaseVdiUuid})`)
}
const newVdi = await this._getOrWaitObject(
await this._cloneVdi(baseVdi)
)
$onFailure(() => this._deleteVdi(newVdi))
await this._updateObjectMapProperty(newVdi, 'other_config', {
[TAG_COPY_SRC]: vdi.uuid
})
return newVdi
})::pAll()
const networksOnPoolMasterByDevice = {}
let defaultNetwork
forEach(this.pool.$master.$PIFs, pif => {
defaultNetwork = networksOnPoolMasterByDevice[pif.device] = pif.$network
})
await Promise.all([
// Create VBDs.
Promise.all(mapToArray(
delta.vbds,
vbd => this._createVbd(vm, newVdis[vbd.VDI], vbd)
)),
// Import VDI contents.
Promise.all(mapToArray(
newVdis,
async (vdi, id) => {
for (const stream of ensureArray(streams[`${id}.vhd`])) {
await this._importVdiContent(vdi, stream, VDI_FORMAT_VHD)
}
}
)),
// Wait for VDI export tasks (if any) termination.
Promise.all(mapToArray(
streams,
stream => stream.task
)),
// Create VIFs.
Promise.all(mapToArray(delta.vifs, vif => {
const network =
(vif.$network$uuid && this.getObject(vif.$network$uuid, null)) ||
networksOnPoolMasterByDevice[vif.device] ||
defaultNetwork
if (network) {
return this._createVif(
vm,
network,
vif
)
}
}))
])
if (deleteBase && baseVm) {
this._deleteVm(baseVm)::pCatch(noop)
}
await Promise.all([
this._setObjectProperties(vm, {
name_label
}),
// FIXME: move
this._updateObjectMapProperty(vm, 'blocked_operations', {
start: disableStartAfterImport
? 'Do not start this VM, clone it if you want to use it.'
: null
})
])
return vm
}
async _migrateVmWithStorageMotion (vm, hostXapi, host, {
migrationNetwork = find(host.$PIFs, pif => pif.management).$network, // TODO: handle not found
mapVdisSrs,
mapVifsNetworks
}) {
// VDIs/SRs mapping
const vdis = {}
const defaultSr = host.$pool.$default_SR
for (const vbd of vm.$VBDs) {
const vdi = vbd.$VDI
if (vbd.type === 'Disk') {
vdis[vdi.$ref] = mapVdisSrs && mapVdisSrs[vdi.$id]
? hostXapi.getObject(mapVdisSrs[vdi.$id]).$ref
: defaultSr.$ref // Will error if there are no default SR.
}
}
// VIFs/Networks mapping
let vifsMap = {}
if (vm.$pool !== host.$pool) {
const defaultNetworkRef = find(host.$PIFs, pif => pif.management).$network.$ref
for (const vif of vm.$VIFs) {
vifsMap[vif.$ref] = mapVifsNetworks && mapVifsNetworks[vif.$id]
? hostXapi.getObject(mapVifsNetworks[vif.$id]).$ref
: defaultNetworkRef
}
}
const token = await hostXapi.call(
'host.migrate_receive',
host.$ref,
migrationNetwork.$ref,
{}
)
const loop = () => this.call(
'VM.migrate_send',
vm.$ref,
token,
true, // Live migration.
vdis,
vifsMap,
{
force: 'true'
}
)::pCatch(
{ code: 'TOO_MANY_STORAGE_MIGRATES' },
() => pDelay(1e4).then(loop)
)
return loop()
}
@synchronized
_callInstallationPlugin (hostRef, vdi) {
return this.call('host.call_plugin', hostRef, 'install-supp-pack', 'install', { vdi }).catch(error => {
if (error.code !== 'XENAPI_PLUGIN_FAILURE') {
console.warn('_callInstallationPlugin', error)
throw error
}
})
}
@deferrable
async installSupplementalPack ($defer, stream, { hostId }) {
if (!stream.length) {
throw new Error('stream must have a length')
}
const vdi = await this.createTemporaryVdiOnHost(stream, hostId, '[XO] Supplemental pack ISO', 'small temporary VDI to store a supplemental pack ISO')
$defer(() => this._deleteVdi(vdi))
await this._callInstallationPlugin(this.getObject(hostId).$ref, vdi.uuid)
}
@deferrable
async installSupplementalPackOnAllHosts ($defer, stream) {
if (!stream.length) {
throw new Error('stream must have a length')
}
const isSrAvailable = sr =>
sr && sr.content_type === 'user' && sr.physical_size - sr.physical_utilisation >= stream.length
const hosts = filter(this.objects.all, { $type: 'host' })
const sr = this.findAvailableSharedSr(stream.length)
// Shared SR available: create only 1 VDI for all the installations
if (sr) {
const vdi = await this.createTemporaryVdiOnSr(stream, sr, '[XO] Supplemental pack ISO', 'small temporary VDI to store a supplemental pack ISO')
$defer(() => this._deleteVdi(vdi))
// Install pack sequentially to prevent concurrent access to the unique VDI
for (const host of hosts) {
await this._callInstallationPlugin(host.$ref, vdi.uuid)
}
return
}
// No shared SR available: find an available local SR on each host
return Promise.all(mapToArray(hosts, deferrable(async ($defer, host) => {
// pipe stream synchronously to several PassThroughs to be able to pipe them asynchronously later
const pt = stream.pipe(new PassThrough())
pt.length = stream.length
const sr = find(
mapToArray(host.$PBDs, '$SR'),
isSrAvailable
)
if (!sr) {
throw new Error('no SR available to store installation file')
}
const vdi = await this.createTemporaryVdiOnSr(pt, sr, '[XO] Supplemental pack ISO', 'small temporary VDI to store a supplemental pack ISO')
$defer(() => this._deleteVdi(vdi))
await this._callInstallationPlugin(host.$ref, vdi.uuid)
})))
}
async _importVm (stream, sr, onlyMetadata = false, onVmCreation = undefined) {
const taskRef = await this.createTask('VM import')
const query = {
force: onlyMetadata
}
let host
if (sr != null) {
host = sr.$PBDs[0].$host
query.sr_id = sr.$ref
}
if (onVmCreation) {
this._waitObject(
obj => obj && obj.current_operations && taskRef in obj.current_operations
).then(onVmCreation)::pCatch(noop)
}
const vmRef = await this.putResource(
stream,
onlyMetadata ? '/import_metadata/' : '/import/',
{
host,
query,
task: taskRef
}
).then(extractOpaqueRef)
// Importing a metadata archive of running VMs is currently
// broken: its VBDs are incorrectly seen as attached.
//
// A call to VM.power_state_reset fixes this problem.
if (onlyMetadata) {
await this.call('VM.power_state_reset', vmRef)
}
return vmRef
}
@deferrable.onFailure
async _importOvaVm ($onFailure, stream, {
descriptionLabel,
disks,
memory,
nameLabel,
networks,
nCpus
}, sr) {
// 1. Create VM.
const vm = await this._getOrWaitObject(
await this._createVmRecord({
...OTHER_CONFIG_TEMPLATE,
memory_dynamic_max: memory,
memory_dynamic_min: memory,
memory_static_max: memory,
name_description: descriptionLabel,
name_label: nameLabel,
VCPUs_at_startup: nCpus,
VCPUs_max: nCpus
})
)
$onFailure(() => this._deleteVm(vm))
// Disable start and change the VM name label during import.
await Promise.all([
this.addForbiddenOperationToVm(vm.$id, 'start', 'OVA import in progress...'),
this._setObjectProperties(vm, { name_label: `[Importing...] ${nameLabel}` })
])
// 2. Create VDIs & Vifs.
const vdis = {}
const vifDevices = await this.call('VM.get_allowed_VIF_devices', vm.$ref)
await Promise.all(
map(disks, async disk => {
const vdi = vdis[disk.path] = await this.createVdi(disk.capacity, {
name_description: disk.descriptionLabel,
name_label: disk.nameLabel,
sr: sr.$ref
})
$onFailure(() => this._deleteVdi(vdi))
return this._createVbd(vm, vdi, { position: disk.position })
}).concat(map(networks, (networkId, i) => (
this._createVif(vm, this.getObject(networkId), {
device: vifDevices[i]
})
)))
)
// 3. Import VDIs contents.
await new Promise((resolve, reject) => {
const extract = tarStream.extract()
stream.on('error', reject)
extract.on('finish', resolve)
extract.on('error', reject)
extract.on('entry', async (entry, stream, cb) => {
// Not a disk to import.
const vdi = vdis[entry.name]
if (!vdi) {
stream.on('end', cb)
stream.resume()
return
}
const vhdStream = await vmdkToVhd(stream)
await this._importVdiContent(vdi, vhdStream, VDI_FORMAT_RAW)
// See: https://github.com/mafintosh/tar-stream#extracting
// No import parallelization.
cb()
})
stream.pipe(extract)
})
// Enable start and restore the VM name label after import.
await Promise.all([
this.removeForbiddenOperationFromVm(vm.$id, 'start'),
this._setObjectProperties(vm, { name_label: nameLabel })
])
return vm
}
// TODO: an XVA can contain multiple VMs
async importVm (stream, {
data,
onlyMetadata = false,
srId,
type = 'xva'
} = {}) {
const sr = srId && this.getObject(srId)
if (type === 'xva') {
return /* await */ this._getOrWaitObject(await this._importVm(
stream,
sr,
onlyMetadata
))
}
if (type === 'ova') {
return this._getOrWaitObject(await this._importOvaVm(stream, data, sr))
}
throw new Error(`unsupported type: '${type}'`)
}
async migrateVm (vmId, hostXapi, hostId, {
migrationNetworkId,
mapVifsNetworks,
mapVdisSrs
} = {}) {
const vm = this.getObject(vmId)
const host = hostXapi.getObject(hostId)
const accrossPools = vm.$pool !== host.$pool
const useStorageMotion = (
accrossPools ||
migrationNetworkId ||
mapVifsNetworks ||
mapVdisSrs
)
if (useStorageMotion) {
await this._migrateVmWithStorageMotion(vm, hostXapi, host, {
migrationNetwork: migrationNetworkId && hostXapi.getObject(migrationNetworkId),
mapVdisSrs,
mapVifsNetworks
})
} else {
try {
await this.call('VM.pool_migrate', vm.$ref, host.$ref, { force: 'true' })
} catch (error) {
if (error.code !== 'VM_REQUIRES_SR') {
throw error
}
// Retry using motion storage.
await this._migrateVmWithStorageMotion(vm, hostXapi, host, {})
}
}
}
async _snapshotVm (vm, nameLabel = vm.name_label) {
debug(`Snapshotting VM ${vm.name_label}${
nameLabel !== vm.name_label
? ` as ${nameLabel}`
: ''
}`)
let ref
try {
ref = await this.call('VM.snapshot_with_quiesce', vm.$ref, nameLabel)
this.addTag(ref, 'quiesce')::pCatch(noop) // ignore any failures
await this._waitObjectState(ref, vm => includes(vm.tags, 'quiesce'))
} catch (error) {
const { code } = error
if (
code !== 'VM_SNAPSHOT_WITH_QUIESCE_NOT_SUPPORTED' &&
// quiesce only work on a running VM
code !== 'VM_BAD_POWER_STATE' &&
// quiesce failed, fallback on standard snapshot
// TODO: emit warning
code !== 'VM_SNAPSHOT_WITH_QUIESCE_FAILED'
) {
throw error
}
ref = await this.call('VM.snapshot', vm.$ref, nameLabel)
}
// Convert the template to a VM and wait to have receive the up-
// to-date object.
const [ , snapshot ] = await Promise.all([
this.call('VM.set_is_a_template', ref, false),
this._waitObjectState(ref, snapshot => !snapshot.is_a_template)
])
return snapshot
}
async snapshotVm (vmId, nameLabel = undefined) {
return /* await */ this._snapshotVm(
this.getObject(vmId),
nameLabel
)
}
async setVcpuWeight (vmId, weight) {
weight = weight || null // Take all falsy values as a removal (0 included)
const vm = this.getObject(vmId)
await this._updateObjectMapProperty(vm, 'VCPUs_params', {weight})
}
async _startVm (vm, force) {
debug(`Starting VM ${vm.name_label}`)
if (force) {
await this._updateObjectMapProperty(vm, 'blocked_operations', {
start: null
})
}
return this.call(
'VM.start',
vm.$ref,
false, // Start paused?
false // Skip pre-boot checks?
)
}
async startVm (vmId, force) {
try {
await this._startVm(this.getObject(vmId), force)
} catch (e) {
if (e.code === 'OPERATION_BLOCKED') {
throw forbiddenOperation('Start', e.params[1])
}
throw e
}
}
async startVmOnCd (vmId) {
const vm = this.getObject(vmId)
if (isVmHvm(vm)) {
const { order } = vm.HVM_boot_params
await this._updateObjectMapProperty(vm, 'HVM_boot_params', {
order: 'd'
})
try {
await this._startVm(vm)
} finally {
await this._updateObjectMapProperty(vm, 'HVM_boot_params', {
order
})
}
} else {
// Find the original template by name (*sigh*).
const templateNameLabel = vm.other_config['base_template_name']
const template = templateNameLabel &&
find(this.objects.all, obj => (
obj.$type === 'vm' &&
obj.is_a_template &&
obj.name_label === templateNameLabel
))
const bootloader = vm.PV_bootloader
const bootables = []
try {
const promises = []
const cdDrive = this._getVmCdDrive(vm)
forEach(vm.$VBDs, vbd => {
promises.push(
this._setObjectProperties(vbd, {
bootable: vbd === cdDrive
})
)
bootables.push([ vbd, Boolean(vbd.bootable) ])
})
promises.push(
this._setObjectProperties(vm, {
PV_bootloader: 'eliloader'
}),
this._updateObjectMapProperty(vm, 'other_config', {
'install-distro': template && template.other_config['install-distro'],
'install-repository': 'cdrom'
})
)
await Promise.all(promises)
await this._startVm(vm)
} finally {
this._setObjectProperties(vm, {
PV_bootloader: bootloader
})::pCatch(noop)
forEach(bootables, ([ vbd, bootable ]) => {
this._setObjectProperties(vbd, { bootable })::pCatch(noop)
})
}
}
}
// vm_operations: http://xapi-project.github.io/xen-api/classes/vm.html
async addForbiddenOperationToVm (vmId, operation, reason) {
await this.call('VM.add_to_blocked_operations', this.getObject(vmId).$ref, operation, `[XO] ${reason}`)
}
async removeForbiddenOperationFromVm (vmId, operation) {
await this.call('VM.remove_from_blocked_operations', this.getObject(vmId).$ref, operation)
}
// =================================================================
async _createVbd (vm, vdi, {
bootable = false,
empty = !vdi,
type = 'Disk',
unpluggable = false,
userdevice = undefined,
mode = (type === 'Disk') ? 'RW' : 'RO',
position = userdevice,
readOnly = (mode === 'RO')
} = {}) {
debug(`Creating VBD for VDI ${vdi.name_label} on VM ${vm.name_label}`)
if (position == null) {
const allowed = await this.call('VM.get_allowed_VBD_devices', vm.$ref)
const {length} = allowed
if (!length) {
throw new Error('no allowed VBD positions (devices)')
}
if (type === 'CD') {
// Choose position 3 if allowed.
position = includes(allowed, '3')
? '3'
: allowed[0]
} else {
position = allowed[0]
// Avoid position 3 if possible.
if (position === '3' && length > 1) {
position = allowed[1]
}
}
}
// By default a VBD is unpluggable.
const vbdRef = await this.call('VBD.create', {
bootable: Boolean(bootable),
empty: Boolean(empty),
mode: readOnly ? 'RO' : 'RW',
other_config: {},
qos_algorithm_params: {},
qos_algorithm_type: '',
type,
unpluggable: Boolean(unpluggable),
userdevice: String(position),
VDI: vdi.$ref,
VM: vm.$ref
})
if (isVmRunning(vm)) {
await this.call('VBD.plug', vbdRef)
}
return vbdRef
}
_cloneVdi (vdi) {
debug(`Cloning VDI ${vdi.name_label}`)
return this.call('VDI.clone', vdi.$ref)
}
async _createVdi (size, {
name_description = undefined,
name_label = '',
other_config = {},
read_only = false,
sharable = false,
// FIXME: should be named srId or an object.
sr = this.pool.default_SR,
tags = [],
type = 'user',
xenstore_data = undefined
} = {}) {
sr = this.getObject(sr)
debug(`Creating VDI ${name_label} on ${sr.name_label}`)
sharable = Boolean(sharable)
read_only = Boolean(read_only)
const data = {
name_description,
name_label,
other_config,
read_only,
sharable,
tags,
type,
virtual_size: String(size),
SR: sr.$ref
}
if (xenstore_data) {
data.xenstore_data = xenstore_data
}
return /* await */ this.call('VDI.create', data)
}
async moveVdi (vdiId, srId) {
const vdi = this.getObject(vdiId)
const sr = this.getObject(srId)
if (vdi.SR === sr.$ref) {
return // nothing to do
}
debug(`Moving VDI ${vdi.name_label} from ${vdi.$SR.name_label} to ${sr.name_label}`)
try {
await this.call('VDI.pool_migrate', vdi.$ref, sr.$ref, {})
} catch (error) {
if (error.code !== 'VDI_NEEDS_VM_FOR_MIGRATE') {
throw error
}
const newVdiref = await this.call('VDI.copy', vdi.$ref, sr.$ref)
const newVdi = await this._getOrWaitObject(newVdiref)
await Promise.all(mapToArray(vdi.$VBDs, async vbd => {
// Remove the old VBD
await this.call('VBD.destroy', vbd.$ref)
// Attach the new VDI to the VM with old VBD settings
await this._createVbd(vbd.$VM, newVdi, {
bootable: vbd.bootable,
position: vbd.userdevice,
type: vbd.type,
readOnly: vbd.mode === 'RO'
})
// Remove the old VDI
await this._deleteVdi(vdi)
}))
}
}
// TODO: check whether the VDI is attached.
async _deleteVdi (vdi) {
debug(`Deleting VDI ${vdi.name_label}`)
await this.call('VDI.destroy', vdi.$ref)
}
async _resizeVdi (vdi, size) {
debug(`Resizing VDI ${vdi.name_label} from ${vdi.virtual_size} to ${size}`)
try {
await this.call('VDI.resize_online', vdi.$ref, String(size))
} catch (error) {
if (error.code !== 'SR_OPERATION_NOT_SUPPORTED') {
throw error
}
await this.call('VDI.resize', vdi.$ref, String(size))
}
}
_getVmCdDrive (vm) {
for (const vbd of vm.$VBDs) {
if (vbd.type === 'CD') {
return vbd
}
}
}
async _ejectCdFromVm (vm) {
const cdDrive = this._getVmCdDrive(vm)
if (cdDrive) {
await this.call('VBD.eject', cdDrive.$ref)
}
}
async _insertCdIntoVm (cd, vm, {
bootable = false,
force = false
} = {}) {
const cdDrive = await this._getVmCdDrive(vm)
if (cdDrive) {
try {
await this.call('VBD.insert', cdDrive.$ref, cd.$ref)
} catch (error) {
if (!force || error.code !== 'VBD_NOT_EMPTY') {
throw error
}
await this.call('VBD.eject', cdDrive.$ref)::pCatch(noop)
// Retry.
await this.call('VBD.insert', cdDrive.$ref, cd.$ref)
}
if (bootable !== Boolean(cdDrive.bootable)) {
await this._setObjectProperties(cdDrive, {bootable})
}
} else {
await this._createVbd(vm, cd, {
bootable,
type: 'CD'
})
}
}
async attachVdiToVm (vdiId, vmId, opts = undefined) {
await this._createVbd(
this.getObject(vmId),
this.getObject(vdiId),
opts
)
}
async connectVbd (vbdId) {
await this.call('VBD.plug', vbdId)
}
async _disconnectVbd (vbd) {
// TODO: check if VBD is attached before
try {
await this.call('VBD.unplug_force', vbd.$ref)
} catch (error) {
if (error.code === 'VBD_NOT_UNPLUGGABLE') {
await this.call('VBD.set_unpluggable', vbd.$ref, true)
return this.call('VBD.unplug_force', vbd.$ref)
}
}
}
async disconnectVbd (vbdId) {
await this._disconnectVbd(this.getObject(vbdId))
}
async _deleteVbd (vbd) {
await this._disconnectVbd(vbd)::pCatch(noop)
await this.call('VBD.destroy', vbd.$ref)
}
deleteVbd (vbdId) {
return this._deleteVbd(this.getObject(vbdId))
}
// TODO: remove when no longer used.
async destroyVbdsFromVm (vmId) {
await Promise.all(
mapToArray(this.getObject(vmId).$VBDs, async vbd => {
await this.disconnectVbd(vbd.$ref)::pCatch(noop)
return this.call('VBD.destroy', vbd.$ref)
})
)
}
async createVdi (size, opts) {
return /* await */ this._getOrWaitObject(
await this._createVdi(size, opts)
)
}
async deleteVdi (vdiId) {
await this._deleteVdi(this.getObject(vdiId))
}
async resizeVdi (vdiId, size) {
await this._resizeVdi(this.getObject(vdiId), size)
}
async ejectCdFromVm (vmId) {
await this._ejectCdFromVm(this.getObject(vmId))
}
async insertCdIntoVm (cdId, vmId, opts = undefined) {
await this._insertCdIntoVm(
this.getObject(cdId),
this.getObject(vmId),
opts
)
}
// -----------------------------------------------------------------
async snapshotVdi (vdiId, nameLabel) {
const vdi = this.getObject(vdiId)
const snap = await this._getOrWaitObject(
await this.call('VDI.snapshot', vdi.$ref)
)
if (nameLabel) {
await this.call('VDI.set_name_label', snap.$ref, nameLabel)
}
return snap
}
@cancellable
_exportVdi ($cancelToken, vdi, base, format = VDI_FORMAT_VHD) {
const host = vdi.$SR.$PBDs[0].$host
const query = {
format,
vdi: vdi.$ref
}
if (base) {
query.base = base.$ref
}
debug(`exporting VDI ${vdi.name_label}${base
? ` (from base ${vdi.name_label})`
: ''
}`)
return this.getResource($cancelToken, '/export_raw_vdi/', {
host,
query,
task: this.createTask('VDI Export', vdi.name_label)
})
}
// Returns a stream to the exported VDI.
exportVdi (vdiId, {
baseId,
format
} = {}) {
return this._exportVdi(
this.getObject(vdiId),
baseId && this.getObject(baseId),
format
)
}
// -----------------------------------------------------------------
async _importVdiContent (vdi, body, format = VDI_FORMAT_VHD) {
const pbd = find(vdi.$SR.$PBDs, 'currently_attached')
if (pbd === undefined) {
throw new Error('no valid PBDs found')
}
await Promise.all([
body.checksumVerified,
this.putResource(body, '/import_raw_vdi/', {
host: pbd.host,
query: {
format,
vdi: vdi.$ref
},
task: this.createTask('VDI Content Import', vdi.name_label)
})
])
}
importVdiContent (vdiId, body, {
format
} = {}) {
return this._importVdiContent(
this.getObject(vdiId),
body,
format
)
}
// =================================================================
async _createVif (vm, network, {
mac = '',
position = undefined,
currently_attached = true,
device = position != null ? String(position) : undefined,
ipv4_allowed = undefined,
ipv6_allowed = undefined,
locking_mode = undefined,
MAC = mac,
other_config = {},
qos_algorithm_params = {},
qos_algorithm_type = ''
} = {}) {
debug(`Creating VIF for VM ${vm.name_label} on network ${network.name_label}`)
if (device == null) {
device = (await this.call('VM.get_allowed_VIF_devices', vm.$ref))[0]
}
const vifRef = await this.call('VIF.create', filterUndefineds({
device,
ipv4_allowed,
ipv6_allowed,
locking_mode,
MAC,
MTU: asInteger(network.MTU),
network: network.$ref,
other_config,
qos_algorithm_params,
qos_algorithm_type,
VM: vm.$ref
}))
if (currently_attached && isVmRunning(vm)) {
await this.call('VIF.plug', vifRef)
}
return vifRef
}
async createVif (vmId, networkId, opts = undefined) {
return /* await */ this._getOrWaitObject(
await this._createVif(
this.getObject(vmId),
this.getObject(networkId),
opts
)
)
}
async createNetwork ({
name,
description = 'Created with Xen Orchestra',
pifId,
mtu,
vlan
}) {
const networkRef = await this.call('network.create', {
name_label: name,
name_description: description,
MTU: asInteger(mtu),
other_config: {}
})
if (pifId) {
await this.call('pool.create_VLAN_from_PIF', this.getObject(pifId).$ref, networkRef, asInteger(vlan))
}
return this._getOrWaitObject(networkRef)
}
async editPif (
pifId,
{ vlan }
) {
const pif = this.getObject(pifId)
const physPif = find(this.objects.all, obj => (
obj.$type === 'pif' &&
(obj.physical || !isEmpty(obj.bond_master_of)) &&
obj.$pool === pif.$pool &&
obj.device === pif.device
))
if (!physPif) {
throw new Error('PIF not found')
}
const pifs = this.getObject(pif.network).$PIFs
const wasAttached = {}
forEach(pifs, pif => {
wasAttached[pif.host] = pif.currently_attached
})
const vlans = uniq(mapToArray(pifs, pif => pif.VLAN_master_of))
await Promise.all(
mapToArray(vlans, vlan => vlan !== NULL_REF && this.call('VLAN.destroy', vlan))
)
const newPifs = await this.call('pool.create_VLAN_from_PIF', physPif.$ref, pif.network, asInteger(vlan))
await Promise.all(
mapToArray(newPifs, pifRef =>
!wasAttached[this.getObject(pifRef).host] && this.call('PIF.unplug', pifRef)::pCatch(noop)
)
)
}
async createBondedNetwork ({
bondMode,
mac,
pifIds,
...params
}) {
const network = await this.createNetwork(params)
// TODO: test and confirm:
// Bond.create is called here with PIFs from one host but XAPI should then replicate the
// bond on each host in the same pool with the corresponding PIFs (ie same interface names?).
await this.call('Bond.create', network.$ref, map(pifIds, pifId => this.getObject(pifId).$ref), mac, bondMode)
return network
}
async deleteNetwork (networkId) {
const network = this.getObject(networkId)
const pifs = network.$PIFs
const vlans = uniq(mapToArray(pifs, pif => pif.VLAN_master_of))
await Promise.all(
mapToArray(vlans, vlan => vlan !== NULL_REF && this.call('VLAN.destroy', vlan))
)
const bonds = uniq(flatten(mapToArray(pifs, pif => pif.bond_master_of)))
await Promise.all(
mapToArray(bonds, bond => this.call('Bond.destroy', bond))
)
await this.call('network.destroy', network.$ref)
}
// =================================================================
async _doDockerAction (vmId, action, containerId) {
const vm = this.getObject(vmId)
const host = vm.$resident_on || this.pool.$master
return /* await */ this.call('host.call_plugin', host.$ref, 'xscontainer', action, {
vmuuid: vm.uuid,
container: containerId
})
}
async registerDockerContainer (vmId) {
await this._doDockerAction(vmId, 'register')
}
async deregisterDockerContainer (vmId) {
await this._doDockerAction(vmId, 'deregister')
}
async startDockerContainer (vmId, containerId) {
await this._doDockerAction(vmId, 'start', containerId)
}
async stopDockerContainer (vmId, containerId) {
await this._doDockerAction(vmId, 'stop', containerId)
}
async restartDockerContainer (vmId, containerId) {
await this._doDockerAction(vmId, 'restart', containerId)
}
async pauseDockerContainer (vmId, containerId) {
await this._doDockerAction(vmId, 'pause', containerId)
}
async unpauseDockerContainer (vmId, containerId) {
await this._doDockerAction(vmId, 'unpause', containerId)
}
async getCloudInitConfig (templateId) {
const template = this.getObject(templateId)
const host = this.pool.$master
let config = await this.call('host.call_plugin', host.$ref, 'xscontainer', 'get_config_drive_default', {
templateuuid: template.uuid
})
return config.slice(4) // FIXME remove the "True" string on the begining
}
// Specific CoreOS Config Drive
async createCoreOsCloudInitConfigDrive (vmId, srId, config) {
const vm = this.getObject(vmId)
const host = this.pool.$master
const sr = this.getObject(srId)
await this.call('host.call_plugin', host.$ref, 'xscontainer', 'create_config_drive', {
vmuuid: vm.uuid,
sruuid: sr.uuid,
configuration: config
})
await this.registerDockerContainer(vmId)
}
// Generic Config Drive
@deferrable.onFailure
async createCloudInitConfigDrive ($onFailure, vmId, srId, config) {
const vm = this.getObject(vmId)
const sr = this.getObject(srId)
// First, create a small VDI (10MB) which will become the ConfigDrive
const buffer = fatfsBufferInit()
const vdi = await this.createVdi(buffer.length, { name_label: 'XO CloudConfigDrive', name_description: undefined, sr: sr.$ref })
$onFailure(() => this._deleteVdi(vdi))
// Then, generate a FAT fs
const fs = promisifyAll(fatfs.createFileSystem(fatfsBuffer(buffer)))
await fs.mkdir('openstack')
await fs.mkdir('openstack/latest')
await Promise.all([
fs.writeFile(
'openstack/latest/meta_data.json',
'{\n "uuid": "' + vm.uuid + '"\n}\n'
),
fs.writeFile('openstack/latest/user_data', config)
])
// ignore VDI_IO_ERROR errors, I (JFT) don't understand why they
// are emitted because it works
await this._importVdiContent(vdi, buffer, VDI_FORMAT_RAW)::pCatch(
{ code: 'VDI_IO_ERROR' },
console.warn
)
await this._createVbd(vm, vdi)
}
@deferrable.onFailure
async createTemporaryVdiOnSr ($onFailure, stream, sr, name_label, name_description) {
const vdi = await this.createVdi(stream.length, {
sr: sr.$ref,
name_label,
name_description
})
$onFailure(() => this._deleteVdi(vdi))
await this.importVdiContent(vdi.$id, stream, { format: VDI_FORMAT_RAW })
return vdi
}
// Create VDI on an adequate local SR
async createTemporaryVdiOnHost (stream, hostId, name_label, name_description) {
const pbd = find(
this.getObject(hostId).$PBDs,
pbd => canSrHaveNewVdiOfSize(pbd.$SR, stream.length)
)
if (pbd == null) {
throw new Error('no SR available')
}
return this.createTemporaryVdiOnSr(stream, pbd.SR, name_label, name_description)
}
async findAvailableSharedSr (minSize) {
return find(
this.objects.all,
obj => obj.$type === 'sr' && obj.shared && canSrHaveNewVdiOfSize(obj, minSize)
)
}
// =================================================================
}
| chore(Xapi#exportDeltaVm): remove unnecessary function
| src/xapi/index.js | chore(Xapi#exportDeltaVm): remove unnecessary function | <ide><path>rc/xapi/index.js
<ide> ...vdi,
<ide> $SR$uuid: vdi.$SR.uuid
<ide> }
<del> const stream = streams[`${vdiRef}.vhd`] = this._exportVdi(vdi, baseVdi, VDI_FORMAT_VHD)
<del> $onFailure(() => stream.cancel())
<add> const stream = streams[`${vdiRef}.vhd`] = this._exportVdi($cancelToken, vdi, baseVdi, VDI_FORMAT_VHD)
<add> $onFailure(stream.cancel)
<ide> })
<ide>
<ide> const vifs = {} |
|
Java | apache-2.0 | 1c3a9f0b04f009651aca5857adf5e7a956039064 | 0 | kiereleaseuser/guvnor,nmirasch/guvnor,porcelli-forks/guvnor,mbiarnes/guvnor,baldimir/guvnor,etirelli/guvnor,etirelli/guvnor,porcelli-forks/guvnor,adrielparedes/guvnor,hxf0801/guvnor,adrielparedes/guvnor,hxf0801/guvnor,wmedvede/guvnor,hxf0801/guvnor,adrielparedes/guvnor,nmirasch/guvnor,Rikkola/guvnor,etirelli/guvnor,baldimir/guvnor,psiroky/guvnor,mswiderski/guvnor,mbiarnes/guvnor,yurloc/guvnor,cristianonicolai/guvnor,nmirasch/guvnor,kiereleaseuser/guvnor,porcelli-forks/guvnor,droolsjbpm/guvnor,droolsjbpm/guvnor,yurloc/guvnor,Rikkola/guvnor,wmedvede/guvnor,cristianonicolai/guvnor,kiereleaseuser/guvnor,baldimir/guvnor,mbiarnes/guvnor,psiroky/guvnor,cristianonicolai/guvnor,wmedvede/guvnor,droolsjbpm/guvnor,psiroky/guvnor,Rikkola/guvnor | package org.drools.repository;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import junit.framework.TestCase;
public class RulesRepositoryTest extends TestCase {
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testDefaultPackage() throws Exception {
RulesRepository repo = RepositorySessionUtil.getRepository();
Iterator it = repo.listPackages();
boolean foundDefault = false;
while(it.hasNext()) {
PackageItem item = (PackageItem) it.next();
if (item.getName().equals( RulesRepository.DEFAULT_PACKAGE )) {
foundDefault = true;
}
}
assertTrue(foundDefault);
PackageItem def = repo.loadDefaultPackage();
assertNotNull(def);
assertEquals("default", def.getName());
}
public void testAddVersionARule() throws Exception {
RulesRepository repo = RepositorySessionUtil.getRepository();
PackageItem pack = repo.createPackage( "testAddVersionARule", "description" );
repo.save();
AssetItem rule = pack.addAsset( "my rule", "foobar" );
assertEquals("my rule", rule.getName());
rule.updateContent( "foo foo" );
rule.checkin( "version0" );
pack.addAsset( "other rule", "description" );
rule.updateContent( "foo bar" );
rule.checkin( "version1" );
PackageItem pack2 = repo.loadPackage( "testAddVersionARule" );
Iterator it = pack2.getAssets();
it.next();
it.next();
assertFalse(it.hasNext());
AssetItem prev = (AssetItem) rule.getPrecedingVersion();
assertEquals("foo bar", rule.getContent());
assertEquals("foo foo", prev.getContent());
}
public void testLoadRuleByUUID() throws Exception {
RulesRepository repo = RepositorySessionUtil.getRepository();
PackageItem rulePackageItem = repo.loadDefaultPackage();
AssetItem rule = rulePackageItem.addAsset( "testLoadRuleByUUID", "this is a description");
repo.save();
String uuid = rule.getNode().getUUID();
AssetItem loaded = repo.loadAssetByUUID(uuid);
assertNotNull(loaded);
assertEquals("testLoadRuleByUUID", loaded.getName());
assertEquals( "this is a description", loaded.getDescription());
String oldVersionNumber = loaded.getVersionNumber();
loaded.updateContent( "xxx" );
loaded.checkin( "woo" );
AssetItem reload = repo.loadAssetByUUID( uuid );
assertEquals("testLoadRuleByUUID", reload.getName());
assertEquals("xxx", reload.getContent());
System.out.println(reload.getVersionNumber());
System.out.println(loaded.getVersionNumber());
assertFalse(reload.getVersionNumber().equals( oldVersionNumber ));
// try loading rule package that was not created
try {
repo.loadAssetByUUID("01010101-0101-0101-0101-010101010101");
fail("Exception not thrown loading rule package that was not created.");
} catch (RulesRepositoryException e) {
// that is OK!
assertNotNull(e.getMessage());
}
//now test concurrent session access...
AssetItem asset1 = repo.loadDefaultPackage().addAsset( "testMultiSession", "description" );
asset1.updateContent( "yeah" );
asset1.checkin( "boo" );
uuid = asset1.getUUID();
Session s2 = repo.getSession().getRepository().login(new SimpleCredentials("fdd", "password".toCharArray()));
RulesRepository repo2 = new RulesRepository(s2);
AssetItem asset2 = repo2.loadAssetByUUID( uuid );
asset2.updateContent( "yeah 42" );
asset2.checkin( "yeah" );
asset1 = repo.loadAssetByUUID( uuid );
assertEquals("yeah 42", asset1.getContent());
asset1.updateContent( "yeah 43" );
asset1.checkin( "la" );
asset2 = repo2.loadAssetByUUID( uuid );
assertEquals( "yeah 43", asset2.getContent() );
}
public void testAddRuleCalendarWithDates() {
RulesRepository rulesRepository = RepositorySessionUtil.getRepository();
Calendar effectiveDate = Calendar.getInstance();
Calendar expiredDate = Calendar.getInstance();
expiredDate.setTimeInMillis(effectiveDate.getTimeInMillis() + (1000 * 60 * 60 * 24));
AssetItem ruleItem1 = rulesRepository.loadDefaultPackage().addAsset("testAddRuleCalendarCalendar", "desc");
ruleItem1.updateDateEffective( effectiveDate );
ruleItem1.updateDateExpired( expiredDate );
assertNotNull(ruleItem1);
assertNotNull(ruleItem1.getNode());
assertEquals(effectiveDate, ruleItem1.getDateEffective());
assertEquals(expiredDate, ruleItem1.getDateExpired());
ruleItem1.checkin( "ho " );
}
public void testGetState() {
RulesRepository rulesRepository = RepositorySessionUtil.getRepository();
StateItem state0 = rulesRepository.createState( "testGetState" );
assertNotNull(state0);
assertEquals("testGetState", state0.getName());
StateItem stateItem1 = rulesRepository.getState("testGetState");
assertNotNull(stateItem1);
assertEquals("testGetState", stateItem1.getName());
StateItem stateItem2 = rulesRepository.getState("testGetState");
assertNotNull(stateItem2);
assertEquals("testGetState", stateItem2.getName());
assertEquals(stateItem1, stateItem2);
}
public void testGetTag() {
RulesRepository rulesRepository = RepositorySessionUtil.getRepository();
CategoryItem root = rulesRepository.loadCategory( "/" );
CategoryItem tagItem1 = root.addCategory( "testGetTag", "ho");
assertNotNull(tagItem1);
assertEquals("testGetTag", tagItem1.getName());
assertEquals("testGetTag", tagItem1.getFullPath());
CategoryItem tagItem2 = rulesRepository.loadCategory("testGetTag");
assertNotNull(tagItem2);
assertEquals("testGetTag", tagItem2.getName());
assertEquals(tagItem1, tagItem2);
//now test getting a tag down in the tag hierarchy
CategoryItem tagItem3 = tagItem2.addCategory( "TestChildTag1", "ka");
assertNotNull(tagItem3);
assertEquals("TestChildTag1", tagItem3.getName());
assertEquals("testGetTag/TestChildTag1", tagItem3.getFullPath());
}
public void testListPackages() {
RulesRepository rulesRepository = RepositorySessionUtil.getRepository();
PackageItem rulePackageItem1 = rulesRepository.createPackage("testListPackages", "desc");
assertTrue(rulesRepository.containsPackage( "testListPackages" ));
assertFalse(rulesRepository.containsPackage( "XXXXXXX" ));
Iterator it = rulesRepository.listPackages();
assertTrue(it.hasNext());
boolean found = false;
while ( it.hasNext() ) {
PackageItem element = (PackageItem) it.next();
if (element.getName().equals( "testListPackages" ))
{
found = true;
break;
}
}
assertTrue(found);
}
public void testMoveRulePackage() throws Exception {
RulesRepository repo = RepositorySessionUtil.getRepository();
PackageItem pkg = repo.createPackage( "testMove", "description" );
AssetItem r = pkg.addAsset( "testMove", "description" );
r.checkin( "version0" );
assertEquals("testMove", r.getPackageName());
repo.save();
assertEquals(1, iteratorToList( pkg.getAssets()).size());
repo.createPackage( "testMove2", "description" );
repo.moveRuleItemPackage( "testMove2", r.node.getUUID(), "explanation" );
pkg = repo.loadPackage( "testMove" );
assertEquals(0, iteratorToList( pkg.getAssets() ).size());
pkg = repo.loadPackage( "testMove2" );
assertEquals(1, iteratorToList( pkg.getAssets() ).size());
r = (AssetItem) pkg.getAssets().next();
assertEquals("testMove", r.getName());
assertEquals("testMove2", r.getPackageName());
assertEquals("explanation", r.getCheckinComment());
AssetItem p = (AssetItem) r.getPrecedingVersion();
assertEquals("testMove", p.getPackageName());
assertEquals("version0", p.getCheckinComment());
}
public void testListStates() {
RulesRepository repo = RepositorySessionUtil.getRepository();
StateItem[] items = repo.listStates();
assertTrue(items.length > 0);
repo.createState( "testListStates" );
StateItem[] items2 = repo.listStates();
assertEquals(items.length + 1, items2.length);
}
List iteratorToList(Iterator it) {
List list = new ArrayList();
while(it.hasNext()) {
list.add( it.next() );
}
return list;
}
}
| drools-repository/src/test/java/org/drools/repository/RulesRepositoryTest.java | package org.drools.repository;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
public class RulesRepositoryTest extends TestCase {
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testDefaultPackage() throws Exception {
RulesRepository repo = RepositorySessionUtil.getRepository();
Iterator it = repo.listPackages();
boolean foundDefault = false;
while(it.hasNext()) {
PackageItem item = (PackageItem) it.next();
if (item.getName().equals( RulesRepository.DEFAULT_PACKAGE )) {
foundDefault = true;
}
}
assertTrue(foundDefault);
PackageItem def = repo.loadDefaultPackage();
assertNotNull(def);
assertEquals("default", def.getName());
}
public void testAddVersionARule() throws Exception {
RulesRepository repo = RepositorySessionUtil.getRepository();
PackageItem pack = repo.createPackage( "testAddVersionARule", "description" );
repo.save();
AssetItem rule = pack.addAsset( "my rule", "foobar" );
assertEquals("my rule", rule.getName());
rule.updateContent( "foo foo" );
rule.checkin( "version0" );
pack.addAsset( "other rule", "description" );
rule.updateContent( "foo bar" );
rule.checkin( "version1" );
PackageItem pack2 = repo.loadPackage( "testAddVersionARule" );
Iterator it = pack2.getAssets();
it.next();
it.next();
assertFalse(it.hasNext());
AssetItem prev = (AssetItem) rule.getPrecedingVersion();
assertEquals("foo bar", rule.getContent());
assertEquals("foo foo", prev.getContent());
}
public void testLoadRuleByUUID() throws Exception {
RulesRepository repo = RepositorySessionUtil.getRepository();
PackageItem rulePackageItem = repo.loadDefaultPackage();
AssetItem rule = rulePackageItem.addAsset( "testLoadRuleByUUID", "this is a description");
repo.save();
String uuid = rule.getNode().getUUID();
AssetItem loaded = repo.loadAssetByUUID(uuid);
assertNotNull(loaded);
assertEquals("testLoadRuleByUUID", loaded.getName());
assertEquals( "this is a description", loaded.getDescription());
String oldVersionNumber = loaded.getVersionNumber();
loaded.updateContent( "xxx" );
loaded.checkin( "woo" );
AssetItem reload = repo.loadAssetByUUID( uuid );
assertEquals("testLoadRuleByUUID", reload.getName());
assertEquals("xxx", reload.getContent());
System.out.println(reload.getVersionNumber());
System.out.println(loaded.getVersionNumber());
assertFalse(reload.getVersionNumber().equals( oldVersionNumber ));
// try loading rule package that was not created
try {
repo.loadAssetByUUID("01010101-0101-0101-0101-010101010101");
fail("Exception not thrown loading rule package that was not created.");
} catch (RulesRepositoryException e) {
// that is OK!
assertNotNull(e.getMessage());
}
}
public void testAddRuleCalendarWithDates() {
RulesRepository rulesRepository = RepositorySessionUtil.getRepository();
Calendar effectiveDate = Calendar.getInstance();
Calendar expiredDate = Calendar.getInstance();
expiredDate.setTimeInMillis(effectiveDate.getTimeInMillis() + (1000 * 60 * 60 * 24));
AssetItem ruleItem1 = rulesRepository.loadDefaultPackage().addAsset("testAddRuleCalendarCalendar", "desc");
ruleItem1.updateDateEffective( effectiveDate );
ruleItem1.updateDateExpired( expiredDate );
assertNotNull(ruleItem1);
assertNotNull(ruleItem1.getNode());
assertEquals(effectiveDate, ruleItem1.getDateEffective());
assertEquals(expiredDate, ruleItem1.getDateExpired());
ruleItem1.checkin( "ho " );
}
public void testGetState() {
RulesRepository rulesRepository = RepositorySessionUtil.getRepository();
StateItem state0 = rulesRepository.createState( "testGetState" );
assertNotNull(state0);
assertEquals("testGetState", state0.getName());
StateItem stateItem1 = rulesRepository.getState("testGetState");
assertNotNull(stateItem1);
assertEquals("testGetState", stateItem1.getName());
StateItem stateItem2 = rulesRepository.getState("testGetState");
assertNotNull(stateItem2);
assertEquals("testGetState", stateItem2.getName());
assertEquals(stateItem1, stateItem2);
}
public void testGetTag() {
RulesRepository rulesRepository = RepositorySessionUtil.getRepository();
CategoryItem root = rulesRepository.loadCategory( "/" );
CategoryItem tagItem1 = root.addCategory( "testGetTag", "ho");
assertNotNull(tagItem1);
assertEquals("testGetTag", tagItem1.getName());
assertEquals("testGetTag", tagItem1.getFullPath());
CategoryItem tagItem2 = rulesRepository.loadCategory("testGetTag");
assertNotNull(tagItem2);
assertEquals("testGetTag", tagItem2.getName());
assertEquals(tagItem1, tagItem2);
//now test getting a tag down in the tag hierarchy
CategoryItem tagItem3 = tagItem2.addCategory( "TestChildTag1", "ka");
assertNotNull(tagItem3);
assertEquals("TestChildTag1", tagItem3.getName());
assertEquals("testGetTag/TestChildTag1", tagItem3.getFullPath());
}
public void testListPackages() {
RulesRepository rulesRepository = RepositorySessionUtil.getRepository();
PackageItem rulePackageItem1 = rulesRepository.createPackage("testListPackages", "desc");
assertTrue(rulesRepository.containsPackage( "testListPackages" ));
assertFalse(rulesRepository.containsPackage( "XXXXXXX" ));
Iterator it = rulesRepository.listPackages();
assertTrue(it.hasNext());
boolean found = false;
while ( it.hasNext() ) {
PackageItem element = (PackageItem) it.next();
if (element.getName().equals( "testListPackages" ))
{
found = true;
break;
}
}
assertTrue(found);
}
public void testMoveRulePackage() throws Exception {
RulesRepository repo = RepositorySessionUtil.getRepository();
PackageItem pkg = repo.createPackage( "testMove", "description" );
AssetItem r = pkg.addAsset( "testMove", "description" );
r.checkin( "version0" );
assertEquals("testMove", r.getPackageName());
repo.save();
assertEquals(1, iteratorToList( pkg.getAssets()).size());
repo.createPackage( "testMove2", "description" );
repo.moveRuleItemPackage( "testMove2", r.node.getUUID(), "explanation" );
pkg = repo.loadPackage( "testMove" );
assertEquals(0, iteratorToList( pkg.getAssets() ).size());
pkg = repo.loadPackage( "testMove2" );
assertEquals(1, iteratorToList( pkg.getAssets() ).size());
r = (AssetItem) pkg.getAssets().next();
assertEquals("testMove", r.getName());
assertEquals("testMove2", r.getPackageName());
assertEquals("explanation", r.getCheckinComment());
AssetItem p = (AssetItem) r.getPrecedingVersion();
assertEquals("testMove", p.getPackageName());
assertEquals("version0", p.getCheckinComment());
}
public void testListStates() {
RulesRepository repo = RepositorySessionUtil.getRepository();
StateItem[] items = repo.listStates();
assertTrue(items.length > 0);
repo.createState( "testListStates" );
StateItem[] items2 = repo.listStates();
assertEquals(items.length + 1, items2.length);
}
List iteratorToList(Iterator it) {
List list = new ArrayList();
while(it.hasNext()) {
list.add( it.next() );
}
return list;
}
}
| concurrent test
git-svn-id: a243bed356d289ca0d1b6d299a0597bdc4ecaa09@9666 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70
| drools-repository/src/test/java/org/drools/repository/RulesRepositoryTest.java | concurrent test | <ide><path>rools-repository/src/test/java/org/drools/repository/RulesRepositoryTest.java
<ide> import java.util.Calendar;
<ide> import java.util.Iterator;
<ide> import java.util.List;
<add>
<add>import javax.jcr.Session;
<add>import javax.jcr.SimpleCredentials;
<ide>
<ide> import junit.framework.TestCase;
<ide>
<ide> } catch (RulesRepositoryException e) {
<ide> // that is OK!
<ide> assertNotNull(e.getMessage());
<del> }
<add> }
<add>
<add> //now test concurrent session access...
<add>
<add> AssetItem asset1 = repo.loadDefaultPackage().addAsset( "testMultiSession", "description" );
<add> asset1.updateContent( "yeah" );
<add> asset1.checkin( "boo" );
<add> uuid = asset1.getUUID();
<add>
<add> Session s2 = repo.getSession().getRepository().login(new SimpleCredentials("fdd", "password".toCharArray()));
<add>
<add> RulesRepository repo2 = new RulesRepository(s2);
<add>
<add> AssetItem asset2 = repo2.loadAssetByUUID( uuid );
<add> asset2.updateContent( "yeah 42" );
<add> asset2.checkin( "yeah" );
<add>
<add> asset1 = repo.loadAssetByUUID( uuid );
<add> assertEquals("yeah 42", asset1.getContent());
<add> asset1.updateContent( "yeah 43" );
<add> asset1.checkin( "la" );
<add>
<add> asset2 = repo2.loadAssetByUUID( uuid );
<add> assertEquals( "yeah 43", asset2.getContent() );
<ide> }
<ide>
<ide> public void testAddRuleCalendarWithDates() { |
|
Java | epl-1.0 | e63450cdd0cf5e77278cc3ecfd2c1277f2880cc8 | 0 | jtrfp/terminal-recall,jtrfp/terminal-recall,jtrfp/terminal-recall | /*******************************************************************************
* This file is part of TERMINAL RECALL
* Copyright (c) 2012, 2013 Chuck Ritola.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the COPYING and CREDITS files for more details.
*
* Contributors:
* chuck - initial API and implementation
******************************************************************************/
package org.jtrfp.trcl.beh;
import org.jtrfp.trcl.Submitter;
import org.jtrfp.trcl.obj.WorldObject;
public abstract class Behavior
{
private WorldObject parent;
private Behavior wrapped;
private boolean enable=true;
public WorldObject getParent(){return parent;}
public <T> T probeForBehavior(Class<T> type)
{if(type.isAssignableFrom(this.getClass())){return (T)this;}
if(wrapped!=null)return wrapped.probeForBehavior(type);
throw new BehaviorNotFoundException("Cannot find behavior of type "+type.getName()+" in behavior sandwich owned by "+parent);
}
protected void _proposeCollision(WorldObject other){}
public final void proposeCollision(WorldObject other)
{if(enable)_proposeCollision(other);
if(wrapped!=null)wrapped.proposeCollision(other);
}
protected void _tick(long tickTimeInMillis){}
public final void tick(long tickTimeInMillis)
{if(enable)_tick(tickTimeInMillis);
if(wrapped!=null)wrapped.tick(tickTimeInMillis);
}
public void setParent(WorldObject newParent)
{this.parent=newParent;if(wrapped!=null){wrapped.setParent(newParent);}}
public void setDelegate(Behavior delegate){wrapped=delegate;}
public <T> void probeForBehaviors(Submitter<T> sub, Class<T> type) {
if(type.isAssignableFrom(this.getClass())){sub.submit((T)this);}
if(wrapped!=null)wrapped.probeForBehaviors(sub,type);
}
public void setEnable(boolean doIt){enable=true;}
}//end ObjectBehavior
| src/main/java/org/jtrfp/trcl/beh/Behavior.java | /*******************************************************************************
* This file is part of TERMINAL RECALL
* Copyright (c) 2012, 2013 Chuck Ritola.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the COPYING and CREDITS files for more details.
*
* Contributors:
* chuck - initial API and implementation
******************************************************************************/
package org.jtrfp.trcl.beh;
import org.jtrfp.trcl.Submitter;
import org.jtrfp.trcl.obj.WorldObject;
public abstract class Behavior
{
private WorldObject parent;
private Behavior wrapped;
private boolean enable=true;
public WorldObject getParent(){return parent;}
public <T> T probeForBehavior(Class<T> type)
{if(type.isAssignableFrom(this.getClass())){return (T)this;}
if(wrapped!=null)return wrapped.probeForBehavior(type);
throw new BehaviorNotFoundException("Cannot find behavior of type "+type.getName()+" in behavior sandwich owned by "+parent);
}
protected void _proposeCollision(WorldObject other){}
public final void proposeCollision(WorldObject other)
{if(enable)_proposeCollision(other);
if(wrapped!=null)wrapped.proposeCollision(other);
}
protected void _tick(long tickTimeInMillis){}
public final void tick(long tickTimeInMillis)
{if(enable)_tick(tickTimeInMillis);
if(wrapped!=null)wrapped.tick(tickTimeInMillis);
}
public void setParent(WorldObject newParent)
{this.parent=newParent;if(wrapped!=null){wrapped.setParent(newParent);}}
public void setDelegate(Behavior delegate){wrapped=delegate;}
public <T> void probeForBehaviors(Submitter<T> sub, Class<T> type) {
if(type.isAssignableFrom(this.getClass())){sub.submit((T)this);return;}
if(wrapped!=null){wrapped.probeForBehavior(type);return;}
throw new BehaviorNotFoundException("Cannot find behavior of type "+type.getName()+" in behavior sandwich owned by "+parent);
}
public void setEnable(boolean doIt){enable=true;}
}//end ObjectBehavior
| Fixed missed-behavior probing bug. | src/main/java/org/jtrfp/trcl/beh/Behavior.java | Fixed missed-behavior probing bug. | <ide><path>rc/main/java/org/jtrfp/trcl/beh/Behavior.java
<ide>
<ide> public void setDelegate(Behavior delegate){wrapped=delegate;}
<ide> public <T> void probeForBehaviors(Submitter<T> sub, Class<T> type) {
<del> if(type.isAssignableFrom(this.getClass())){sub.submit((T)this);return;}
<del> if(wrapped!=null){wrapped.probeForBehavior(type);return;}
<del> throw new BehaviorNotFoundException("Cannot find behavior of type "+type.getName()+" in behavior sandwich owned by "+parent);
<add> if(type.isAssignableFrom(this.getClass())){sub.submit((T)this);}
<add> if(wrapped!=null)wrapped.probeForBehaviors(sub,type);
<ide> }
<ide> public void setEnable(boolean doIt){enable=true;}
<ide> }//end ObjectBehavior |
|
Java | mit | ac390785232c9441f1a015e002af901e745c333e | 0 | Peter-Maximilian/settlers-remake,andreasb242/settlers-remake,andreas-eberle/settlers-remake,jsettlers/settlers-remake,jsettlers/settlers-remake,jsettlers/settlers-remake,JKatzwinkel/settlers-remake,andreasb242/settlers-remake,andreasb242/settlers-remake,andreas-eberle/settlers-remake,andreas-eberle/settlers-remake,phirschbeck/settlers-remake,phirschbeck/settlers-remake,phirschbeck/settlers-remake | package networklib.server.exceptions;
/**
*
* @author Andreas Eberle
*
*/
public class NotAllPlayersReadyException extends Exception {
private static final long serialVersionUID = -4442557133757056985L;
public NotAllPlayersReadyException() {
super();
}
public NotAllPlayersReadyException(String message, Throwable cause) {
super(message, cause);
}
public NotAllPlayersReadyException(String message) {
super(message);
}
public NotAllPlayersReadyException(Throwable cause) {
super(cause);
}
}
| networklib/networklib/server/exceptions/NotAllPlayersReadyException.java | package networklib.server.exceptions;
/**
*
* @author Andreas Eberle
*
*/
public class NotAllPlayersReadyException extends Exception {
private static final long serialVersionUID = -4442557133757056985L;
public NotAllPlayersReadyException() {
super();
}
public NotAllPlayersReadyException(String message, Throwable cause, boolean arg2, boolean arg3) {
super(message, cause, arg2, arg3);
}
public NotAllPlayersReadyException(String message, Throwable cause) {
super(message, cause);
}
public NotAllPlayersReadyException(String message) {
super(message);
}
public NotAllPlayersReadyException(Throwable cause) {
super(cause);
}
}
| - fixed bild path warning
| networklib/networklib/server/exceptions/NotAllPlayersReadyException.java | - fixed bild path warning | <ide><path>etworklib/networklib/server/exceptions/NotAllPlayersReadyException.java
<ide> super();
<ide> }
<ide>
<del> public NotAllPlayersReadyException(String message, Throwable cause, boolean arg2, boolean arg3) {
<del> super(message, cause, arg2, arg3);
<del> }
<del>
<ide> public NotAllPlayersReadyException(String message, Throwable cause) {
<ide> super(message, cause);
<ide> } |
|
JavaScript | mit | 67a904d17dc7f4221ce5a4a1a47ae078a5b3676c | 0 | comindware/core-ui,comindware/core-ui,comindware/core-ui,comindware/core-ui | //@flow
import '../resources/styles/bootstrap-datetimepicker.css';
import '../resources/styles/fonts.css';
import '../resources/styles/common.css';
import '../resources/styles/services/messageService.css';
import '../resources/styles/services/windowService.css';
import '../resources/styles/form.css';
import '../resources/styles/dropdown.css';
import '../resources/styles/popout.css';
import '../resources/styles/list.css';
import '../resources/styles/codemirror.css';
import '../resources/styles/layout-designer.css';
import '../resources/styles/notifications.css';
import '../node_modules/spectrum-colorpicker/spectrum.css';
import libApi from 'lib';
import utilsApi from 'utils';
import dropdownApi from 'dropdown';
import * as layoutApi from './layout';
import formApi from 'form';
import listApi from 'list';
import meta_ from './Meta';
import Controller from './controller/Controller';
import Application from './Application';
import LoadingView from './views/LoadingView';
import LoadingBehavior from './views/behaviors/LoadingBehavior';
import SearchBarView from './views/SearchBarView';
import SplitPanelView from './views/SplitPanelView';
import RoutingService from './services/RoutingService';
import ToastNotifications from './services/ToastNotificationService';
import MessageService from './services/MessageService';
import WindowService from './services/WindowService';
import GlobalEventService from './services/GlobalEventService';
import LocalizationService from './services/LocalizationService';
import AjaxService from './services/AjaxService';
import PromiseService from './services/PromiseService';
import UserService from './services/UserService';
import InterfaceErrorMessageService from './services/InterfaceErrorMessageService';
import ThemeService from './services/ThemeService';
import SlidingWindowCollection from './collections/SlidingWindowCollection';
import VirtualCollection from './collections/VirtualCollection';
import CollectionHighlightableBehavior from './collections/behaviors/HighlightableBehavior';
import CollapsibleBehavior from './models/behaviors/CollapsibleBehavior';
import HighlightableBehavior from './models/behaviors/HighlightableBehavior';
import SelectableBehavior from './models/behaviors/SelectableBehavior';
import CheckableBehavior from './models/behaviors/CheckableBehavior';
import MobileService from './services/MobileService';
import NavigationDrawer from './components/navigationDrawer/NavigationDrawer';
import BreadCrumbs from './components/breadCrumbs/BreadCrumbs';
import Toolbar from './components/toolbar/ToolbarView';
import LayoutDesigner from './components/layoutDesigner';
import VideoChat from './components/videoChat/VideoChat';
/**
* Core UI components: основные компоненты для построение веб-интерфейса Comindware.
* @name module:core
* */
const core = {
Controller,
Application,
RoutingService,
ToastNotifications,
lib: libApi,
InterfaceError: InterfaceErrorMessageService,
/**
* Services of general use the UI is built on.
* @namespace
* @memberof module:core
* */
services: {
MessageService,
/**
* The service is responsible for displaying global windows. For example, modal dialogs (popups).
* @namespace
* @memberof module:core.services
* */
WindowService,
LocalizationService,
AjaxService,
/**
* The services provides an interface to global window events, so you could easily subscribe
* to them through <code>this.listenTo(GlobalEventService, ...)</code> in you views.
* @namespace
* @memberof module:core.services
* */
GlobalEventService,
PromiseService,
UserService,
MobileService,
ThemeService
},
/**
* Backbone collections of general use.
* @namespace
* @memberof module:core
* */
collections: {
/**
* Backbone collection behaviors of general use.
* @namespace
* @memberof module:core.collections
* */
behaviors: {
HighlightableBehavior: CollectionHighlightableBehavior
},
SlidingWindowCollection,
VirtualCollection
},
/**
* Backbone models of general use.
* @namespace
* @memberof module:core
* */
models: {
behaviors: {
CollapsibleBehavior,
HighlightableBehavior,
SelectableBehavior,
CheckableBehavior
}
},
views: {
behaviors: {
LoadingBehavior
},
LoadingView,
SearchBarView,
SplitPanelView
},
/**
* Dropdown components of general use. It may be used in menus, dropdown lists and more complex cases like displaying some fancy about-me panel.
* @namespace
* @memberof module:core
* */
dropdown: dropdownApi,
layout: layoutApi,
/**
* A large set of editors and related classes built on top of [Backbone.Form](https://github.com/powmedia/backbone-forms) library.
* @namespace
* @memberof module:core
* */
form: formApi,
/**
* List and Grid components with data virtualization.
* @namespace
* @memberof module:core
* */
list: listApi,
/**
* Combines useful helper classes, functions and constants.
* @namespace
* @memberof module:core
* */
utils: utilsApi,
/**
* Constants used inside the library.
* @namespace
* @memberof module:core
* */
meta: meta_,
components: {
NavigationDrawer,
Toolbar,
BreadCrumbs,
LayoutDesigner,
VideoChat
}
};
window.Core = core;
export default core;
export const lib = core.lib;
export const layout = core.layout;
export const services = core.services;
export const collections = core.collections;
export const models = core.models;
export const views = core.views;
export const dropdown = core.dropdown;
export const form = core.form;
export const list = core.list;
export const utils = core.utils;
export const meta = core.meta;
| src/coreApi.js | //@flow
import '../resources/styles/bootstrap-datetimepicker.css';
import '../resources/styles/fonts.css';
import '../resources/styles/common.css';
import '../resources/styles/services/messageService.css';
import '../resources/styles/services/windowService.css';
import '../resources/styles/form.css';
import '../resources/styles/dropdown.css';
import '../resources/styles/popout.css';
import '../resources/styles/list.css';
import '../resources/styles/codemirror.css';
import '../resources/styles/layout-designer.css';
import '../resources/styles/notifications.css';
import '../node_modules/spectrum-colorpicker/spectrum.css';
import libApi from 'lib';
import utilsApi from 'utils';
import dropdownApi from 'dropdown';
import * as layoutApi from './layout';
import formApi from 'form';
import listApi from 'list';
import meta_ from './Meta';
import Controller from './controller/Controller';
import Application from './Application';
import LoadingView from './views/LoadingView';
import LoadingBehavior from './views/behaviors/LoadingBehavior';
import SearchBarView from './views/SearchBarView';
import SplitPanelView from './views/SplitPanelView';
import RoutingService from './services/RoutingService';
import ToastNotifications from './services/ToastNotificationService';
import MessageService from './services/MessageService';
import WindowService from './services/WindowService';
import GlobalEventService from './services/GlobalEventService';
import LocalizationService from './services/LocalizationService';
import AjaxService from './services/AjaxService';
import PromiseService from './services/PromiseService';
import UserService from './services/UserService';
import InterfaceErrorMessageService from './services/InterfaceErrorMessageService';
import ThemeService from './services/ThemeService';
import SlidingWindowCollection from './collections/SlidingWindowCollection';
import VirtualCollection from './collections/VirtualCollection';
import CollectionHighlightableBehavior from './collections/behaviors/HighlightableBehavior';
import CollapsibleBehavior from './models/behaviors/CollapsibleBehavior';
import HighlightableBehavior from './models/behaviors/HighlightableBehavior';
import SelectableBehavior from './models/behaviors/SelectableBehavior';
import CheckableBehavior from './models/behaviors/CheckableBehavior';
import MobileService from './services/MobileService';
import NavigationDrawer from './components/navigationDrawer/NavigationDrawer';
import BreadCrumbs from './components/breadCrumbs/BreadCrumbs';
import Toolbar from './components/toolbar/ToolbarView';
import LayoutDesigner from './components/layoutDesigner';
import VideoChat from './components/VideoChat/VideoChat';
/**
* Core UI components: основные компоненты для построение веб-интерфейса Comindware.
* @name module:core
* */
const core = {
Controller,
Application,
RoutingService,
ToastNotifications,
lib: libApi,
InterfaceError: InterfaceErrorMessageService,
/**
* Services of general use the UI is built on.
* @namespace
* @memberof module:core
* */
services: {
MessageService,
/**
* The service is responsible for displaying global windows. For example, modal dialogs (popups).
* @namespace
* @memberof module:core.services
* */
WindowService,
LocalizationService,
AjaxService,
/**
* The services provides an interface to global window events, so you could easily subscribe
* to them through <code>this.listenTo(GlobalEventService, ...)</code> in you views.
* @namespace
* @memberof module:core.services
* */
GlobalEventService,
PromiseService,
UserService,
MobileService,
ThemeService
},
/**
* Backbone collections of general use.
* @namespace
* @memberof module:core
* */
collections: {
/**
* Backbone collection behaviors of general use.
* @namespace
* @memberof module:core.collections
* */
behaviors: {
HighlightableBehavior: CollectionHighlightableBehavior
},
SlidingWindowCollection,
VirtualCollection
},
/**
* Backbone models of general use.
* @namespace
* @memberof module:core
* */
models: {
behaviors: {
CollapsibleBehavior,
HighlightableBehavior,
SelectableBehavior,
CheckableBehavior
}
},
views: {
behaviors: {
LoadingBehavior
},
LoadingView,
SearchBarView,
SplitPanelView
},
/**
* Dropdown components of general use. It may be used in menus, dropdown lists and more complex cases like displaying some fancy about-me panel.
* @namespace
* @memberof module:core
* */
dropdown: dropdownApi,
layout: layoutApi,
/**
* A large set of editors and related classes built on top of [Backbone.Form](https://github.com/powmedia/backbone-forms) library.
* @namespace
* @memberof module:core
* */
form: formApi,
/**
* List and Grid components with data virtualization.
* @namespace
* @memberof module:core
* */
list: listApi,
/**
* Combines useful helper classes, functions and constants.
* @namespace
* @memberof module:core
* */
utils: utilsApi,
/**
* Constants used inside the library.
* @namespace
* @memberof module:core
* */
meta: meta_,
components: {
NavigationDrawer,
Toolbar,
BreadCrumbs,
LayoutDesigner,
VideoChat
}
};
window.Core = core;
export default core;
export const lib = core.lib;
export const layout = core.layout;
export const services = core.services;
export const collections = core.collections;
export const models = core.models;
export const views = core.views;
export const dropdown = core.dropdown;
export const form = core.form;
export const list = core.list;
export const utils = core.utils;
export const meta = core.meta;
| Fix oh so craze bug.
| src/coreApi.js | Fix oh so craze bug. | <ide><path>rc/coreApi.js
<ide> import BreadCrumbs from './components/breadCrumbs/BreadCrumbs';
<ide> import Toolbar from './components/toolbar/ToolbarView';
<ide> import LayoutDesigner from './components/layoutDesigner';
<del>import VideoChat from './components/VideoChat/VideoChat';
<add>import VideoChat from './components/videoChat/VideoChat';
<ide>
<ide> /**
<ide> * Core UI components: основные компоненты для построение веб-интерфейса Comindware. |
|
Java | bsd-3-clause | error: pathspec 'bench/spellcheck/spellcheck.java-2.java' did not match any file(s) known to git
| 954a62f6dd5c7130f3096ed3a665d8a407d09659 | 1 | kragen/shootout,kragen/shootout,kragen/shootout,kragen/shootout,kragen/shootout,kragen/shootout,kragen/shootout,kragen/shootout,kragen/shootout,kragen/shootout,kragen/shootout | /*
* The Great Computer Language Shootout
* http://shootout.alioth.debian.org/
*
* modified by Mehmet D. AKIN
*
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
public class SpellCheck {
static HashMap dict = new HashMap(1024);
static String word;
public static void main(String args[]) throws IOException {
try {
BufferedReader in = new BufferedReader(new FileReader("Usr.Dict.Words"));
while ((word = in.readLine()) != null) {
dict.put(word, null);
}
in.close();
in = new BufferedReader(new InputStreamReader(System.in));
while ((word = in.readLine()) != null) {
if (!dict.containsKey(word)) {
System.out.println(word);
}
}
} catch (IOException e) {
System.err.println(e);
return;
}
}
}
| bench/spellcheck/spellcheck.java-2.java | *** empty log message ***
| bench/spellcheck/spellcheck.java-2.java | *** empty log message *** | <ide><path>ench/spellcheck/spellcheck.java-2.java
<add>/*
<add> * The Great Computer Language Shootout
<add> * http://shootout.alioth.debian.org/
<add> *
<add> * modified by Mehmet D. AKIN
<add> *
<add> */
<add>
<add>import java.io.BufferedReader;
<add>import java.io.FileReader;
<add>import java.io.IOException;
<add>import java.io.InputStreamReader;
<add>import java.util.HashMap;
<add>
<add>public class SpellCheck {
<add>
<add> static HashMap dict = new HashMap(1024);
<add> static String word;
<add>
<add> public static void main(String args[]) throws IOException {
<add> try {
<add> BufferedReader in = new BufferedReader(new FileReader("Usr.Dict.Words"));
<add> while ((word = in.readLine()) != null) {
<add> dict.put(word, null);
<add> }
<add> in.close();
<add> in = new BufferedReader(new InputStreamReader(System.in));
<add> while ((word = in.readLine()) != null) {
<add> if (!dict.containsKey(word)) {
<add> System.out.println(word);
<add> }
<add> }
<add> } catch (IOException e) {
<add> System.err.println(e);
<add> return;
<add> }
<add> }
<add>} |
|
JavaScript | apache-2.0 | d0e42af6919721f1ff6eb5dc4dd330843b933866 | 0 | racker/node-cassandra-client,racker/node-cassandra-client | /*
* Copyright 2011 Rackspace
*
* 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.
*
*/
/** node.js driver for Cassandra-CQL. */
var log = require('logmagic').local('node-cassandra-client.driver');
var sys = require('sys');
var Buffer = require('buffer').Buffer;
var EventEmitter = require('events').EventEmitter;
var thrift = require('thrift');
var Cassandra = require('./gen-nodejs/Cassandra');
var ttypes = require('./gen-nodejs/cassandra_types');
var genericPool = require('generic-pool');
var Decoder = require('./decoder').Decoder;
// used to parse the CF name out of a select statement.
var selectRe = /\s*SELECT\s+.+\s+FROM\s+[\']?(\w+)/im;
var appExceptions = ['InvalidRequestException', 'TimedOutException', 'UnavailableException',
'SchemaDisagreementException'];
var nullBindError = {
message: 'null/undefined query parameter'
};
/** converts object to a string using toString() method if it exists. */
function stringify(x) {
if (x.toString) {
return x.toString();
} else {
return x;
}
}
/** wraps in quotes */
function quote(x) {
return '\'' + x + '\'';
}
/** replaces single quotes with double quotes */
function fixQuotes(x) {
return x.replace(/\'/img, '\'\'');
}
/**
* binds arguments to a query. e.g: bind('select ?, ? from MyCf where key=?', ['arg0', 'arg1', 'arg2']);
* quoting is handled for you. so is converting the parameters to a string, preparatory to being sent up to cassandra.
* @param query
* @param args array of arguments. falsy values are never acceptable.
* @return a buffer suitable for cassandra.execute_cql_query().
*/
function bind(query, args) {
if (args.length === 0) {
return query;
}
var q = 0;
var a = 0;
var str = '';
while (q >= 0) {
var oldq = q;
q = query.indexOf('?', q);
if (q >= 0) {
str += query.substr(oldq, q-oldq);
if (args[a] === null) {
return nullBindError;
}
str += quote(fixQuotes(stringify(args[a++])));
q += 1;
} else {
str += query.substr(oldq);
}
}
return new Buffer(str);
}
/** returns true if obj is in the array */
function contains(a, obj) {
var i = a.length;
while (i > 0) {
if (a[i-1] === obj) {
return true;
}
i--;
}
return false;
}
System = module.exports.System = require('./system').System;
KsDef = module.exports.KsDef = require('./system').KsDef;
CfDef = module.exports.CfDef = require('./system').CfDef;
ColumnDef = module.exports.ColumnDef = require('./system').ColumnDef;
BigInteger = module.exports.BigInteger = require('./bigint').BigInteger;
UUID = module.exports.UUID = require('./uuid').UUID;
/** abstraction of a single row. */
Row = module.exports.Row = function(row, decoder) {
// decoded key.
this.key = decoder.decode(row.key, 'key');
// cols, all names and values are decoded.
this.cols = []; // list of hashes of {name, value};
this.colHash = {}; // hash of name->value
var count = 0;
for (var i = 0; i < row.columns.length; i++) {
if (row.columns[i].value) {
var decodedName = decoder.decode(row.columns[i].name, 'comparator');
var decodedValue = decoder.decode(row.columns[i].value, 'validator', row.columns[i].name);
this.cols[count] = {
name: decodedName,
value: decodedValue
};
this.colHash[decodedName] = decodedValue;
count += 1;
}
}
this._colCount = count;
};
/** @returns the number of columns in this row. */
Row.prototype.colCount = function() {
return this._colCount;
};
/**
* Perform queries against a pool of open connections.
*
* Accepts a single argument of an object used to configure the new PooledConnection
* instance. The config object supports the following attributes:
*
* hosts : List of strings in host:port format.
* keyspace : Keyspace name.
* user : User for authentication (optional).
* pass : Password for authentication (optional).
* maxSize : Maximum number of connection to pool (optional).
* idleMillis : Idle connection timeout in milliseconds (optional).
*
* Example:
*
* var pool = new PooledConnection({
* hosts : ['host1:9160', 'host2:9170', 'host3', 'host4'],
* keyspace : 'database',
* user : 'mary',
* pass : 'qwerty',
* maxSize : 25,
* idleMillis : 30000
* });
*
* @param config an object used to control the creation of new instances.
*/
PooledConnection = module.exports.PooledConnection = function(config) {
this.nodes = [];
this.holdFor = 10000;
this.current_node = 0;
this.use_bigints = config.use_bigints ? true : false;
// Construct a list of nodes from hosts in <host>:<port> form
for (var i = 0; i < config.hosts.length; i++) {
hostSpec = config.hosts[i];
if (!hostSpec) { continue; }
host = hostSpec.split(':');
if (host.length > 2) {
log.warn('malformed host entry "' + hostSpec + '" (skipping)');
}
log.debug("adding " + hostSpec + " to working node list");
this.nodes.push([host[0], (isNaN(host[1])) ? 9160 : host[1]]);
}
var self = this;
var maxSize = isNaN(config.maxSize) ? 25 : config.maxsize;
var idleMillis = isNaN(config.idleMillis) ? 30000 : config.idleMillis;
this.pool = genericPool.Pool({
name : 'Connection',
create : function(callback) {
// Advance through the set of configured nodes
if ((self.current_node + 1) >= self.nodes.length) {
self.current_node = 0;
} else {
self.current_node++;
}
var tries = self.nodes.length;
function retry(curNode) {
tries--;
if ((curNode + 1) >= self.nodes.length) {
curNode = 0;
} else {
curNode++;
}
var node = self.nodes[curNode];
// Skip over any nodes known to be bad
if (node.holdUntil > (new Date().getTime())) {
return retry(curNode);
}
var conn = new Connection({host: node[0],
port: node[1],
keyspace: config.keyspace,
user: config.user,
pass: config.pass,
use_bigints: self.use_bigints});
conn.connect(function(err) {
if (!err) { // Success, we're connected
callback(conn);
} else if (tries > 0) { // Fail, mark node inactive and retry
log.err("Unabled to connect to " + node[0] + ":" + node[1] + " (skipping)");
node.holdUntil = new Date().getTime() + self.holdFor;
retry(curNode);
} else { // Exhausted all options
callback(null);
}
});
}
retry(self.current_node);
},
destroy : function(conn) { conn.close(); },
max : maxSize,
idleTimeoutMillis : idleMillis,
log : false
});
};
/**
* executes any query
* @param query any CQL statement with '?' placeholders.
* @param args array of arguments that will be bound to the query.
* @param callback executed when the query returns. the callback takes a different number of arguments depending on the
* type of query:
* SELECT (single row): callback(err, row)
* SELECT (mult rows) : callback(err, rows)
* SELECT (count) : callback(err, count)
* UPDATE : callback(err)
* DELETE : callback(err)
*/
PooledConnection.prototype.execute = function(query, args, callback) {
var self = this;
var seen = false;
var exe = function(errback) {
self.pool.acquire(function(conn) {
if (!conn) {
callback(Error('Unable to acquire an open connection from the pool!'));
} else {
conn.execute(query, args, function(err, res) {
if (err) {
if (contains(appExceptions, err.name)) {
self.pool.release(conn);
callback(err, null);
} else {
if (!seen) {
errback();
} else {
self.pool.release(conn);
callback(err, null);
}
}
} else {
self.pool.release(conn);
callback(err, res);
}
});
}
});
};
var retry = function() {
seen = true;
exe(retry);
};
exe(retry);
};
/**
* Signal the pool to shutdown. Once called, no new requests (read: execute())
* can be made. When all pending requests have terminated, the callback is run.
*
* @param callback called when the pool is fully shutdown
*/
PooledConnection.prototype.shutdown = function(callback) {
var self = this;
this.pool.drain(function() {
self.pool.destroyAllNow(callback);
});
};
/**
* @param options: valid parts are:
* user, pass, host, port, keyspace, use_bigints
*/
Connection = module.exports.Connection = function(options) {
log.info('connecting ' + options.host + ':' + options.port);
this.validators = {};
this.con = thrift.createConnection(options.host, options.port);
this.client = null;
this.connectionInfo = options;
};
/**
* makes the connection.
* @param callback called when connection is successful or ultimately fails (err will be present).
*/
Connection.prototype.connect = function(callback) {
var self = this;
this.con.on('error', function(err) {
callback(err);
});
this.con.on('close', function() {
log.info(self.connectionInfo.host + ':' + self.connectionInfo.port + ' is closed');
});
this.con.on('connect', function() {
// preparing the conneciton is a 3-step process.
// 1) login
var login = function(cb) {
if (self.connectionInfo.user || self.connectionInfo.pass) {
var creds = new ttypes.AuthenticationRequest({user: self.connectionInfo.user, password: self.connectionInfo.pass});
self.client.login(creds, function(err) {
cb(err);
});
} else {
cb(null);
}
};
// 2) login.
var learn = function(cb) {
self.client.describe_keyspace(self.connectionInfo.keyspace, function(err, def) {
if (err) {
cb(err);
} else {
for (var i = 0; i < def.cf_defs.length; i++) {
var validators = {
key: def.cf_defs[i].key_validation_class,
comparator: def.cf_defs[i].comparator_type,
defaultValidator: def.cf_defs[i].default_validation_class,
specificValidators: {}
};
for (var j = 0; j < def.cf_defs[i].column_metadata.length; j++) {
// todo: verify that the name we use as the key represents the raw-bytes version of the column name, not
// the stringified version.
validators.specificValidators[def.cf_defs[i].column_metadata[j].name] = def.cf_defs[i].column_metadata[j].validation_class;
}
self.validators[def.cf_defs[i].name] = validators;
}
cb(null); // no errors.
}
});
};
// 3) set the keyspace on the server.
var use = function(cb) {
self.client.set_keyspace(self.connectionInfo.keyspace, function(err) {
cb(err);
});
};
// put it all together, checking for errors along the way.
login(function(loginErr) {
if (loginErr) {
callback(loginErr);
self.close();
} else {
learn(function(learnErr) {
if (learnErr) {
callback(learnErr);
self.close();
} else {
use(function(useErr) {
if (useErr) {
callback(useErr);
self.close();
} else {
// this connection is finally ready to use.
callback(null);
}
});
}
});
}
});
});
// kicks off the connection process.
this.client = thrift.createClient(Cassandra, this.con);
};
Connection.prototype.close = function() {
this.con.end();
this.con = null;
this.client = null;
};
/**
* executes any query
* @param query any cql statement with '?' placeholders.
* @param args array of arguments that will be bound to the query.
* @param callback executed when the query returns. the callback takes a different number of arguments depending on the
* type of query:
* SELECT (single row): callback(err, row)
* SELECT (mult rows) : callback(err, rows)
* SELECT (count) : callback(err, count)
* UPDATE : callback(err)
* DELETE : callback(err)
*/
Connection.prototype.execute = function(query, args, callback) {
var cql = bind(query, args);
if (cql === nullBindError) {
callback(new Error(nullBindError.message));
} else {
var self = this;
this.client.execute_cql_query(cql, ttypes.Compression.NONE, function(err, res) {
if (err) {
callback(err, null);
} else if (!res) {
callback(new Error('No results'), null);
} else {
if (res.type === ttypes.CqlResultType.ROWS) {
var cfName = selectRe.exec(cql)[1];
var decoder = new Decoder(self.validators[cfName], {use_bigints: self.connectionInfo.use_bigints});
// for now, return results.
var rows = [];
for (var i = 0; i < res.rows.length; i++) {
var row = new Row(res.rows[i], decoder);
rows.push(row);
}
rows.rowCount = function() {
return res.rows.length;
};
callback(null, rows);
} else if (res.type === ttypes.CqlResultType.INT) {
callback(null, res.num);
} else if (res.type === ttypes.CqlResultType.VOID) {
callback(null);
}
}
});
}
};
| lib/driver.js | /*
* Copyright 2011 Rackspace
*
* 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.
*
*/
/** node.js driver for Cassandra-CQL. */
var log = require('logmagic').local('node-cassandra-client.driver');
var sys = require('sys');
var EventEmitter = require('events').EventEmitter;
var thrift = require('thrift');
var Cassandra = require('./gen-nodejs/Cassandra');
var ttypes = require('./gen-nodejs/cassandra_types');
var genericPool = require('generic-pool');
var Decoder = require('./decoder').Decoder;
// used to parse the CF name out of a select statement.
var selectRe = /\s*SELECT\s+.+\s+FROM\s+[\']?(\w+)/im;
var appExceptions = ['InvalidRequestException', 'TimedOutException', 'UnavailableException',
'SchemaDisagreementException'];
var nullBindError = {
message: 'null/undefined query parameter'
};
/** converts object to a string using toString() method if it exists. */
function stringify(x) {
if (x.toString) {
return x.toString();
} else {
return x;
}
}
/** wraps in quotes */
function quote(x) {
return '\'' + x + '\'';
}
/** replaces single quotes with double quotes */
function fixQuotes(x) {
return x.replace(/\'/img, '\'\'');
}
/**
* binds arguments to a query. e.g: bind('select ?, ? from MyCf where key=?', ['arg0', 'arg1', 'arg2']);
* quoting is handled for you. so is converting the parameters to a string, preparatory to being sent up to cassandra.
* @param query
* @param args array of arguments. falsy values are never acceptable.
* @result a string suitable for cassandra.execute_cql_query().
*/
function bind(query, args) {
if (args.length === 0) {
return query;
}
var q = 0;
var a = 0;
var str = '';
while (q >= 0) {
var oldq = q;
q = query.indexOf('?', q);
if (q >= 0) {
str += query.substr(oldq, q-oldq);
if (args[a] === null) {
return nullBindError;
}
str += quote(fixQuotes(stringify(args[a++])));
q += 1;
} else {
str += query.substr(oldq);
}
}
return str;
}
/** returns true if obj is in the array */
function contains(a, obj) {
var i = a.length;
while (i > 0) {
if (a[i-1] === obj) {
return true;
}
i--;
}
return false;
}
System = module.exports.System = require('./system').System;
KsDef = module.exports.KsDef = require('./system').KsDef;
CfDef = module.exports.CfDef = require('./system').CfDef;
ColumnDef = module.exports.ColumnDef = require('./system').ColumnDef;
BigInteger = module.exports.BigInteger = require('./bigint').BigInteger;
UUID = module.exports.UUID = require('./uuid').UUID;
/** abstraction of a single row. */
Row = module.exports.Row = function(row, decoder) {
// decoded key.
this.key = decoder.decode(row.key, 'key');
// cols, all names and values are decoded.
this.cols = []; // list of hashes of {name, value};
this.colHash = {}; // hash of name->value
var count = 0;
for (var i = 0; i < row.columns.length; i++) {
if (row.columns[i].value) {
var decodedName = decoder.decode(row.columns[i].name, 'comparator');
var decodedValue = decoder.decode(row.columns[i].value, 'validator', row.columns[i].name);
this.cols[count] = {
name: decodedName,
value: decodedValue
};
this.colHash[decodedName] = decodedValue;
count += 1;
}
}
this._colCount = count;
};
/** @returns the number of columns in this row. */
Row.prototype.colCount = function() {
return this._colCount;
};
/**
* Perform queries against a pool of open connections.
*
* Accepts a single argument of an object used to configure the new PooledConnection
* instance. The config object supports the following attributes:
*
* hosts : List of strings in host:port format.
* keyspace : Keyspace name.
* user : User for authentication (optional).
* pass : Password for authentication (optional).
* maxSize : Maximum number of connection to pool (optional).
* idleMillis : Idle connection timeout in milliseconds (optional).
*
* Example:
*
* var pool = new PooledConnection({
* hosts : ['host1:9160', 'host2:9170', 'host3', 'host4'],
* keyspace : 'database',
* user : 'mary',
* pass : 'qwerty',
* maxSize : 25,
* idleMillis : 30000
* });
*
* @param config an object used to control the creation of new instances.
*/
PooledConnection = module.exports.PooledConnection = function(config) {
this.nodes = [];
this.holdFor = 10000;
this.current_node = 0;
this.use_bigints = config.use_bigints ? true : false;
// Construct a list of nodes from hosts in <host>:<port> form
for (var i = 0; i < config.hosts.length; i++) {
hostSpec = config.hosts[i];
if (!hostSpec) { continue; }
host = hostSpec.split(':');
if (host.length > 2) {
log.warn('malformed host entry "' + hostSpec + '" (skipping)');
}
log.debug("adding " + hostSpec + " to working node list");
this.nodes.push([host[0], (isNaN(host[1])) ? 9160 : host[1]]);
}
var self = this;
var maxSize = isNaN(config.maxSize) ? 25 : config.maxsize;
var idleMillis = isNaN(config.idleMillis) ? 30000 : config.idleMillis;
this.pool = genericPool.Pool({
name : 'Connection',
create : function(callback) {
// Advance through the set of configured nodes
if ((self.current_node + 1) >= self.nodes.length) {
self.current_node = 0;
} else {
self.current_node++;
}
var tries = self.nodes.length;
function retry(curNode) {
tries--;
if ((curNode + 1) >= self.nodes.length) {
curNode = 0;
} else {
curNode++;
}
var node = self.nodes[curNode];
// Skip over any nodes known to be bad
if (node.holdUntil > (new Date().getTime())) {
return retry(curNode);
}
var conn = new Connection({host: node[0],
port: node[1],
keyspace: config.keyspace,
user: config.user,
pass: config.pass,
use_bigints: self.use_bigints});
conn.connect(function(err) {
if (!err) { // Success, we're connected
callback(conn);
} else if (tries > 0) { // Fail, mark node inactive and retry
log.err("Unabled to connect to " + node[0] + ":" + node[1] + " (skipping)");
node.holdUntil = new Date().getTime() + self.holdFor;
retry(curNode);
} else { // Exhausted all options
callback(null);
}
});
}
retry(self.current_node);
},
destroy : function(conn) { conn.close(); },
max : maxSize,
idleTimeoutMillis : idleMillis,
log : false
});
};
/**
* executes any query
* @param query any CQL statement with '?' placeholders.
* @param args array of arguments that will be bound to the query.
* @param callback executed when the query returns. the callback takes a different number of arguments depending on the
* type of query:
* SELECT (single row): callback(err, row)
* SELECT (mult rows) : callback(err, rows)
* SELECT (count) : callback(err, count)
* UPDATE : callback(err)
* DELETE : callback(err)
*/
PooledConnection.prototype.execute = function(query, args, callback) {
var self = this;
var seen = false;
var exe = function(errback) {
self.pool.acquire(function(conn) {
if (!conn) {
callback(Error('Unable to acquire an open connection from the pool!'));
} else {
conn.execute(query, args, function(err, res) {
if (err) {
if (contains(appExceptions, err.name)) {
self.pool.release(conn);
callback(err, null);
} else {
if (!seen) {
errback();
} else {
self.pool.release(conn);
callback(err, null);
}
}
} else {
self.pool.release(conn);
callback(err, res);
}
});
}
});
};
var retry = function() {
seen = true;
exe(retry);
};
exe(retry);
};
/**
* Signal the pool to shutdown. Once called, no new requests (read: execute())
* can be made. When all pending requests have terminated, the callback is run.
*
* @param callback called when the pool is fully shutdown
*/
PooledConnection.prototype.shutdown = function(callback) {
var self = this;
this.pool.drain(function() {
self.pool.destroyAllNow(callback);
});
};
/**
* @param options: valid parts are:
* user, pass, host, port, keyspace, use_bigints
*/
Connection = module.exports.Connection = function(options) {
log.info('connecting ' + options.host + ':' + options.port);
this.validators = {};
this.con = thrift.createConnection(options.host, options.port);
this.client = null;
this.connectionInfo = options;
};
/**
* makes the connection.
* @param callback called when connection is successful or ultimately fails (err will be present).
*/
Connection.prototype.connect = function(callback) {
var self = this;
this.con.on('error', function(err) {
callback(err);
});
this.con.on('close', function() {
log.info(self.connectionInfo.host + ':' + self.connectionInfo.port + ' is closed');
});
this.con.on('connect', function() {
// preparing the conneciton is a 3-step process.
// 1) login
var login = function(cb) {
if (self.connectionInfo.user || self.connectionInfo.pass) {
var creds = new ttypes.AuthenticationRequest({user: self.connectionInfo.user, password: self.connectionInfo.pass});
self.client.login(creds, function(err) {
cb(err);
});
} else {
cb(null);
}
};
// 2) login.
var learn = function(cb) {
self.client.describe_keyspace(self.connectionInfo.keyspace, function(err, def) {
if (err) {
cb(err);
} else {
for (var i = 0; i < def.cf_defs.length; i++) {
var validators = {
key: def.cf_defs[i].key_validation_class,
comparator: def.cf_defs[i].comparator_type,
defaultValidator: def.cf_defs[i].default_validation_class,
specificValidators: {}
};
for (var j = 0; j < def.cf_defs[i].column_metadata.length; j++) {
// todo: verify that the name we use as the key represents the raw-bytes version of the column name, not
// the stringified version.
validators.specificValidators[def.cf_defs[i].column_metadata[j].name] = def.cf_defs[i].column_metadata[j].validation_class;
}
self.validators[def.cf_defs[i].name] = validators;
}
cb(null); // no errors.
}
});
};
// 3) set the keyspace on the server.
var use = function(cb) {
self.client.set_keyspace(self.connectionInfo.keyspace, function(err) {
cb(err);
});
};
// put it all together, checking for errors along the way.
login(function(loginErr) {
if (loginErr) {
callback(loginErr);
self.close();
} else {
learn(function(learnErr) {
if (learnErr) {
callback(learnErr);
self.close();
} else {
use(function(useErr) {
if (useErr) {
callback(useErr);
self.close();
} else {
// this connection is finally ready to use.
callback(null);
}
});
}
});
}
});
});
// kicks off the connection process.
this.client = thrift.createClient(Cassandra, this.con);
};
Connection.prototype.close = function() {
this.con.end();
this.con = null;
this.client = null;
};
/**
* executes any query
* @param query any cql statement with '?' placeholders.
* @param args array of arguments that will be bound to the query.
* @param callback executed when the query returns. the callback takes a different number of arguments depending on the
* type of query:
* SELECT (single row): callback(err, row)
* SELECT (mult rows) : callback(err, rows)
* SELECT (count) : callback(err, count)
* UPDATE : callback(err)
* DELETE : callback(err)
*/
Connection.prototype.execute = function(query, args, callback) {
var cql = bind(query, args);
if (cql === nullBindError) {
callback(new Error(nullBindError.message));
} else {
var self = this;
this.client.execute_cql_query(cql, ttypes.Compression.NONE, function(err, res) {
if (err) {
callback(err, null);
} else if (!res) {
callback(new Error('No results'), null);
} else {
if (res.type === ttypes.CqlResultType.ROWS) {
var cfName = selectRe.exec(cql)[1];
var decoder = new Decoder(self.validators[cfName], {use_bigints: self.connectionInfo.use_bigints});
// for now, return results.
var rows = [];
for (var i = 0; i < res.rows.length; i++) {
var row = new Row(res.rows[i], decoder);
rows.push(row);
}
rows.rowCount = function() {
return res.rows.length;
};
callback(null, rows);
} else if (res.type === ttypes.CqlResultType.INT) {
callback(null, res.num);
} else if (res.type === ttypes.CqlResultType.VOID) {
callback(null);
}
}
});
}
};
| Make it so it forces a UTF buffer.
| lib/driver.js | Make it so it forces a UTF buffer. | <ide><path>ib/driver.js
<ide>
<ide> var log = require('logmagic').local('node-cassandra-client.driver');
<ide> var sys = require('sys');
<add>var Buffer = require('buffer').Buffer;
<ide> var EventEmitter = require('events').EventEmitter;
<ide>
<ide> var thrift = require('thrift');
<ide> * quoting is handled for you. so is converting the parameters to a string, preparatory to being sent up to cassandra.
<ide> * @param query
<ide> * @param args array of arguments. falsy values are never acceptable.
<del> * @result a string suitable for cassandra.execute_cql_query().
<add> * @return a buffer suitable for cassandra.execute_cql_query().
<ide> */
<ide> function bind(query, args) {
<ide> if (args.length === 0) {
<ide> str += query.substr(oldq);
<ide> }
<ide> }
<del> return str;
<add> return new Buffer(str);
<ide> }
<ide>
<ide> /** returns true if obj is in the array */ |
|
JavaScript | mit | 290bd291849530bde6ddcb83478ba9f7bc84c1cf | 0 | jmjuanes/siimple,siimple/siimple,siimple/siimple,jmjuanes/siimple | let flow = require("tinyflow");
let fs = require("fs");
let path = require("path");
let sass = require("node-sass");
let autoprefixer = require("autoprefixer");
let postcss = require("postcss");
let cleanCSS = require("clean-css");
let mkdirp = require("mkdirp");
let config = require("./config.js");
//Files paths
let paths = {
input: "./scss/siimple.scss",
output: "./dist/siimple.css",
outputMin: "./dist/siimple.min.css"
};
//Create the output directory
flow.task("dist:create", function (done) {
return mkdirp("./dist", function (error) {
return done(error);
});
});
//Compile the css files
flow.task("css:compile", ["dist:create"], function (done) {
//Read the main scss file
return fs.readFile(paths.input, "utf8", function (error, content) {
if (error) {
return done(error);
}
//Compile the scss file to generate the css
let sassOptions = {data: content, includePaths: ["./scss/", "./node_modules/"]};
return sass.render(sassOptions, function (error, result) {
if (error) {
return done(error);
}
//Prefix the generated css
let prefixer = postcss(autoprefixer({ browsers: ["last 3 versions", "IE 9"], cascade: false }));
return prefixer.process(result.css).then(function (output) {
//Append the header
output.css = config.getHeader() + output.css;
//Write the colpiled css file
return fs.writeFile(paths.output, output.css, "utf8", function (error) {
return done(error);
});
}).catch(function (error) {
return done(error);
});
});
});
});
//Minify output css file
flow.task("css:minify", ["dist:create"], function (done) {
return fs.readFile(paths.output, "utf8", function (error, content) {
if (error) {
return done(error);
}
//Clean the css file
new cleanCSS({compatibility: "*"}).minify(content, function (error, output) {
if (error) {
return done(error);
}
//Append the header
output.styles = config.getHeader() + output.styles;
//Write the minified css file
return fs.writeFile(paths.outputMin, output.styles, "utf8", function (error) {
return done(error);
});
});
});
});
//Set default tasks
flow.defaultTask(["css:compile", "css:minify"]);
| scripts/build.js | let flow = require("tinyflow");
let fs = require("fs");
let path = require("path");
let sass = require("node-sass");
let autoprefixer = require("autoprefixer");
let postcss = require("postcss");
let cleanCSS = require("clean-css");
let mkdirp = require("mkdirp");
let config = require("./config.js");
//Files paths
let paths = {
input: "./scss/siimple.scss",
output: "./dist/siimple.css",
outputMin: "./dist/siimple.min.css"
};
//Create the output directory
flow.task("dist:create", function (done) {
return mkdirp("./dist", function (error) {
return done(error);
});
});
//Compile the css files
flow.task("css:compile", ["dist:create"], function (done) {
//Read the main scss file
return fs.readFile(paths.input, "utf8", function (error, content) {
if (error) {
return done(error);
}
//Compile the scss file to generate the css
let sassOptions = {data: content, includePaths: ["./scss/"]};
return sass.render(sassOptions, function (error, result) {
if (error) {
return done(error);
}
//Prefix the generated css
let prefixer = postcss(autoprefixer({ browsers: ["last 3 versions", "IE 9"], cascade: false }));
return prefixer.process(result.css).then(function (output) {
//Append the header
output.css = config.getHeader() + output.css;
//Write the colpiled css file
return fs.writeFile(paths.output, output.css, "utf8", function (error) {
return done(error);
});
}).catch(function (error) {
return done(error);
});
});
});
});
//Minify output css file
flow.task("css:minify", ["dist:create"], function (done) {
return fs.readFile(paths.output, "utf8", function (error, content) {
if (error) {
return done(error);
}
//Clean the css file
new cleanCSS({compatibility: "*"}).minify(content, function (error, output) {
if (error) {
return done(error);
}
//Append the header
output.styles = config.getHeader() + output.styles;
//Write the minified css file
return fs.writeFile(paths.outputMin, output.styles, "utf8", function (error) {
return done(error);
});
});
});
});
//Set default tasks
flow.defaultTask(["css:compile", "css:minify"]);
| Added node_modules to import paths option of SASS compiler
| scripts/build.js | Added node_modules to import paths option of SASS compiler | <ide><path>cripts/build.js
<ide> return done(error);
<ide> }
<ide> //Compile the scss file to generate the css
<del> let sassOptions = {data: content, includePaths: ["./scss/"]};
<add> let sassOptions = {data: content, includePaths: ["./scss/", "./node_modules/"]};
<ide> return sass.render(sassOptions, function (error, result) {
<ide> if (error) {
<ide> return done(error); |
|
JavaScript | agpl-3.0 | 025ea22a0e1d5bd8d0a769d06c5fd621fcaeb76a | 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 | 347c949a-2e65-11e5-9284-b827eb9e62be | helloWorld.js | 34770dfe-2e65-11e5-9284-b827eb9e62be | 347c949a-2e65-11e5-9284-b827eb9e62be | helloWorld.js | 347c949a-2e65-11e5-9284-b827eb9e62be | <ide><path>elloWorld.js
<del>34770dfe-2e65-11e5-9284-b827eb9e62be
<add>347c949a-2e65-11e5-9284-b827eb9e62be |
|
Java | mit | 914721e7f45e50d8efaee7e6b3f590038b107181 | 0 | AlphaModder/SpongeAPI,jamierocks/SpongeAPI,SpongePowered/SpongeAPI,DDoS/SpongeAPI,Kiskae/SpongeAPI,SpongePowered/SpongeAPI,boomboompower/SpongeAPI,jamierocks/SpongeAPI,kashike/SpongeAPI,boomboompower/SpongeAPI,AlphaModder/SpongeAPI,jonk1993/SpongeAPI,JBYoshi/SpongeAPI,modwizcode/SpongeAPI,kashike/SpongeAPI,modwizcode/SpongeAPI,SpongePowered/SpongeAPI,ryantheleach/SpongeAPI,JBYoshi/SpongeAPI,jonk1993/SpongeAPI,Kiskae/SpongeAPI,DDoS/SpongeAPI,ryantheleach/SpongeAPI | /*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.event.cause;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.event.Event;
import org.spongepowered.api.event.cause.entity.damage.source.DamageSource;
import org.spongepowered.api.event.cause.entity.spawn.SpawnCause;
import org.spongepowered.api.event.entity.DamageEntityEvent;
import org.spongepowered.api.event.entity.SpawnEntityEvent;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Nullable;
/**
* A cause represents the reason or initiator of an event.
*
* <p>For example, if a block of sand is placed where it drops, the block
* of sand would create a falling sand entity, which then would place another
* block of sand. The block place event for the final block of sand would have
* the cause chain of the block of sand -> falling sand entity.</p>
*
* <p>It is not possible to accurately the describe the chain of causes in
* all scenarios so a best effort approach is generally acceptable. For
* example, a player might press a lever, activating a complex Redstone
* circuit, which would then launch TNT and cause the destruction of
* some blocks, but tracing this event would be too complicated and thus
* may not be attempted.</p>
*/
@SuppressWarnings("unchecked")
public abstract class Cause {
private static final Cause EMPTY = new EmptyCause();
/**
* Gets the "empty" {@link Cause}. If a {@link Cause} is required, but
* there is no {@link Object} that can be stated as the direct "cause" of
* an {@link Event}, an "empty" {@link Cause} can be used.
*
* @return The empty cause instance
*/
public static Cause empty() {
return EMPTY;
}
/**
* Creates a new {@link Cause} of the provided {@link Object}s. Note that
* none of the provided {@link Object}s can be <code>null</code>. The order
* of the objects should represent the "priority" that the object aided in
* the "cause" of an {@link Event}. The first {@link Object} should be the
* direct "cause" of the {@link Event}.
*
* <p>Usually, in most cases, some {@link Event}s will have "helper"
* objects to interface with their direct causes, such as
* {@link DamageSource} for an {@link DamageEntityEvent}, or a
* {@link SpawnCause} for an {@link SpawnEntityEvent}.</p>
*
* @param objects The objects being the cause
* @return
*/
public static Cause of(Object... objects) {
return new PresentCause(checkNotNull(objects));
}
public static Cause fromNullable(@Nullable Object... objects) {
if (objects == null) {
return EMPTY;
} else {
return new PresentCause(objects);
}
}
Cause() {}
/**
* Gets whether this {@link Cause} is empty of any causes or not. An empty
* cause may mean the {@link Cause} is not originating from any vanilla
* interactions, or it may mean the cause is simply not known.
*
* @return True if this cause is empty, false otherwise
*/
public abstract boolean isEmpty();
/**
* Gets the root {@link Object} of this cause. The root can be anything,
* including but not limited to: {@link DamageSource}, {@link Entity},
* {@link SpawnCause}, etc.
*
* @return The root object cause for this cause
*/
public abstract Optional<?> root();
/**
* Gets the first <code>T</code> object of this {@link Cause}, if
* available.
*
* @param target The class of the target type
* @param <T> The type of object being queried for
* @return The first element of the type, if available
*/
public abstract <T> Optional<T> first(Class<T> target);
/**
* Gets the last object instance of the {@link Class} of type
* <code>T</code>.
*
* @param target The class of the target type
* @param <T> The type of object being queried for
* @return The last element of the type, if available
*/
public abstract <T> Optional<T> last(Class<T> target);
/**
* Gets an {@link ImmutableList} of all objects that are instances of the
* given {@link Class} type <code>T</code>.
*
* @param <T> The type of objects to query for
* @param target The class of the target type
* @return An immutable list of the objects queried
*/
public abstract <T> List<T> allOf(Class<T> target);
/**
* Gets an {@link List} of all causes within this {@link Cause}.
*
* @return An immutable list of all the causes
*/
public abstract List<Object> all();
/**
* Returns {@code true} if {@code object} is a {@code Cause} instance, and
* either the contained references are {@linkplain Object#equals equal} to
* each other or both are absent.
*/
@Override
public abstract boolean equals(@Nullable Object object);
/**
* Returns a hash code for this instance.
*/
@Override
public abstract int hashCode();
private static final class PresentCause extends Cause {
private final Object[] cause;
PresentCause(Object... causes) {
for (Object aCause : causes) {
checkNotNull(aCause, "Null cause element!");
}
this.cause = Arrays.copyOf(causes, causes.length);
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Optional<?> root() {
return Optional.of(this.cause[0]);
}
@Override
public <T> Optional<T> first(Class<T> target) {
for (Object aCause : this.cause) {
if (target.isInstance(aCause)) {
return Optional.of((T) aCause);
}
}
return Optional.absent();
}
@Override
public <T> List<T> allOf(Class<T> target) {
ImmutableList.Builder<T> builder = ImmutableList.builder();
for (Object aCause : this.cause) {
if (target.isInstance(aCause)) {
builder.add((T) aCause);
}
}
return builder.build();
}
@Override
public <T> Optional<T> last(Class<T> target) {
for (int i = this.cause.length - 1; i >= 0; i--) {
if (target.isInstance(this.cause[i])) {
return Optional.of((T) this.cause[i]);
}
}
return Optional.absent();
}
@Override
public List<Object> all() {
return ImmutableList.copyOf(this.cause);
}
@Override
public boolean equals(@Nullable Object object) {
if (object instanceof PresentCause) {
PresentCause cause = ((PresentCause) object);
return Arrays.equals(this.cause, cause.cause);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(this.cause);
}
}
private static final class EmptyCause extends Cause {
EmptyCause() {}
@Override
public boolean isEmpty() {
return true;
}
@Override
public Optional<?> root() {
return Optional.absent();
}
@Override
public <T> Optional<T> first(Class<T> target) {
return Optional.absent();
}
@Override
public <T> Optional<T> last(Class<T> target) {
return Optional.absent();
}
@Override
public <T> List<T> allOf(Class<T> target) {
return ImmutableList.of();
}
@Override
public List<Object> all() {
return ImmutableList.of();
}
@Override
public boolean equals(@Nullable Object object) {
return object == this;
}
@Override
public int hashCode() {
return 0x39e8a5b;
}
}
}
| src/main/java/org/spongepowered/api/event/cause/Cause.java | /*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.event.cause;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.event.Event;
import org.spongepowered.api.event.cause.entity.damage.source.DamageSource;
import org.spongepowered.api.event.cause.entity.spawn.SpawnCause;
import org.spongepowered.api.event.entity.DamageEntityEvent;
import org.spongepowered.api.event.entity.SpawnEntityEvent;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Nullable;
/**
* A cause represents the reason or initiator of an event.
*
* <p>For example, if a block of sand is placed where it drops, the block
* of sand would create a falling sand entity, which then would place another
* block of sand. The block place event for the final block of sand would have
* the cause chain of the block of sand -> falling sand entity.</p>
*
* <p>It is not possible to accurately the describe the chain of causes in
* all scenarios so a best effort approach is generally acceptable. For
* example, a player might press a lever, activating a complex Redstone
* circuit, which would then launch TNT and cause the destruction of
* some blocks, but tracing this event would be too complicated and thus
* may not be attempted.</p>
*/
@SuppressWarnings("unchecked")
public abstract class Cause {
private static final Cause EMPTY = new EmptyCause();
/**
* Gets the "empty" {@link Cause}. If a {@link Cause} is required, but
* there is no {@link Object} that can be stated as the direct "cause" of
* an {@link Event}, an "empty" {@link Cause} can be used.
*
* @return The empty cause instance
*/
public static Cause empty() {
return EMPTY;
}
/**
* Creates a new {@link Cause} of the provided {@link Object}s. Note that
* none of the provided {@link Object}s can be <code>null</code>. The order
* of the objects should represent the "priority" that the object aided in
* the "cause" of an {@link Event}. The first {@link Object} should be the
* direct "cause" of the {@link Event}.
*
* <p>Usually, in most cases, some {@link Event}s will have "helper"
* objects to interface with their direct causes, such as
* {@link DamageSource} for an {@link DamageEntityEvent}, or a
* {@link SpawnCause} for an {@link SpawnEntityEvent}.</p>
*
* @param objects The objects being the cause
* @return
*/
public static Cause of(Object... objects) {
return new PresentCause(checkNotNull(objects));
}
public static Cause fromNullable(@Nullable Object... objects) {
if (objects == null) {
return EMPTY;
} else {
return new PresentCause(objects);
}
}
Cause() {}
/**
* Gets whether this {@link Cause} is empty of any causes or not. An empty
* cause may mean the {@link Cause} is not originating from any vanilla
* interactions, or it may mean the cause is simply not known.
*
* @return True if this cause is empty, false otherwise
*/
public abstract boolean isEmpty();
/**
* Gets the root {@link Object} of this cause. The root can be anything,
* including but not limited to: {@link DamageSource}, {@link Entity},
* {@link SpawnCause}, etc.
*
* @return The root object cause for this cause
*/
public abstract Optional<?> getRoot();
/**
* Gets the first <code>T</code> object of this {@link Cause}, if
* available.
*
* @param target The class of the target type
* @param <T> The type of object being queried for
* @return The first element of the type, if available
*/
public abstract <T> Optional<T> getFirst(Class<T> target);
/**
* Gets the last object instance of the {@link Class} of type
* <code>T</code>.
*
* @param target The class of the target type
* @param <T> The type of object being queried for
* @return The last element of the type, if available
*/
public abstract <T> Optional<T> getLast(Class<T> target);
/**
* Gets an {@link ImmutableList} of all objects that are instances of the
* given {@link Class} type <code>T</code>.
*
* @param <T> The type of objects to query for
* @param target The class of the target type
* @return An immutable list of the objects queried
*/
public abstract <T> List<T> getAllOf(Class<T> target);
/**
* Gets an {@link List} of all causes within this {@link Cause}.
*
* @return An immutable list of all the causes
*/
public abstract List<Object> getAllCauses();
/**
* Returns {@code true} if {@code object} is a {@code Cause} instance, and
* either the contained references are {@linkplain Object#equals equal} to
* each other or both are absent.
*/
@Override
public abstract boolean equals(@Nullable Object object);
/**
* Returns a hash code for this instance.
*/
@Override
public abstract int hashCode();
private static final class PresentCause extends Cause {
private final Object[] cause;
PresentCause(Object... causes) {
for (Object aCause : causes) {
checkNotNull(aCause, "Null cause element!");
}
this.cause = Arrays.copyOf(causes, causes.length);
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Optional<?> getRoot() {
return Optional.of(this.cause[0]);
}
@Override
public <T> Optional<T> getFirst(Class<T> target) {
for (Object aCause : this.cause) {
if (target.isInstance(aCause)) {
return Optional.of((T) aCause);
}
}
return Optional.absent();
}
@Override
public <T> List<T> getAllOf(Class<T> target) {
ImmutableList.Builder<T> builder = ImmutableList.builder();
for (Object aCause : this.cause) {
if (target.isInstance(aCause)) {
builder.add((T) aCause);
}
}
return builder.build();
}
@Override
public <T> Optional<T> getLast(Class<T> target) {
for (int i = this.cause.length - 1; i >= 0; i--) {
if (target.isInstance(this.cause[i])) {
return Optional.of((T) this.cause[i]);
}
}
return Optional.absent();
}
@Override
public List<Object> getAllCauses() {
return ImmutableList.copyOf(this.cause);
}
@Override
public boolean equals(@Nullable Object object) {
if (object instanceof PresentCause) {
PresentCause cause = ((PresentCause) object);
return Arrays.equals(this.cause, cause.cause);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(this.cause);
}
}
private static final class EmptyCause extends Cause {
EmptyCause() {}
@Override
public boolean isEmpty() {
return true;
}
@Override
public Optional<?> getRoot() {
return Optional.absent();
}
@Override
public <T> Optional<T> getFirst(Class<T> target) {
return Optional.absent();
}
@Override
public <T> Optional<T> getLast(Class<T> target) {
return Optional.absent();
}
@Override
public <T> List<T> getAllOf(Class<T> target) {
return ImmutableList.of();
}
@Override
public List<Object> getAllCauses() {
return ImmutableList.of();
}
@Override
public boolean equals(@Nullable Object object) {
return object == this;
}
@Override
public int hashCode() {
return 0x39e8a5b;
}
}
}
| Remove un-needed method verbosity in Cause.
Signed-off-by: Chris Sanders <[email protected]>
| src/main/java/org/spongepowered/api/event/cause/Cause.java | Remove un-needed method verbosity in Cause. | <ide><path>rc/main/java/org/spongepowered/api/event/cause/Cause.java
<ide> *
<ide> * @return The root object cause for this cause
<ide> */
<del> public abstract Optional<?> getRoot();
<add> public abstract Optional<?> root();
<ide>
<ide> /**
<ide> * Gets the first <code>T</code> object of this {@link Cause}, if
<ide> * @param <T> The type of object being queried for
<ide> * @return The first element of the type, if available
<ide> */
<del> public abstract <T> Optional<T> getFirst(Class<T> target);
<add> public abstract <T> Optional<T> first(Class<T> target);
<ide>
<ide> /**
<ide> * Gets the last object instance of the {@link Class} of type
<ide> * @param <T> The type of object being queried for
<ide> * @return The last element of the type, if available
<ide> */
<del> public abstract <T> Optional<T> getLast(Class<T> target);
<add> public abstract <T> Optional<T> last(Class<T> target);
<ide>
<ide> /**
<ide> * Gets an {@link ImmutableList} of all objects that are instances of the
<ide> * @param target The class of the target type
<ide> * @return An immutable list of the objects queried
<ide> */
<del> public abstract <T> List<T> getAllOf(Class<T> target);
<add> public abstract <T> List<T> allOf(Class<T> target);
<ide>
<ide> /**
<ide> * Gets an {@link List} of all causes within this {@link Cause}.
<ide> *
<ide> * @return An immutable list of all the causes
<ide> */
<del> public abstract List<Object> getAllCauses();
<add> public abstract List<Object> all();
<ide>
<ide> /**
<ide> * Returns {@code true} if {@code object} is a {@code Cause} instance, and
<ide> }
<ide>
<ide> @Override
<del> public Optional<?> getRoot() {
<add> public Optional<?> root() {
<ide> return Optional.of(this.cause[0]);
<ide> }
<ide>
<ide> @Override
<del> public <T> Optional<T> getFirst(Class<T> target) {
<add> public <T> Optional<T> first(Class<T> target) {
<ide> for (Object aCause : this.cause) {
<ide> if (target.isInstance(aCause)) {
<ide> return Optional.of((T) aCause);
<ide> }
<ide>
<ide> @Override
<del> public <T> List<T> getAllOf(Class<T> target) {
<add> public <T> List<T> allOf(Class<T> target) {
<ide> ImmutableList.Builder<T> builder = ImmutableList.builder();
<ide> for (Object aCause : this.cause) {
<ide> if (target.isInstance(aCause)) {
<ide> }
<ide>
<ide> @Override
<del> public <T> Optional<T> getLast(Class<T> target) {
<add> public <T> Optional<T> last(Class<T> target) {
<ide> for (int i = this.cause.length - 1; i >= 0; i--) {
<ide> if (target.isInstance(this.cause[i])) {
<ide> return Optional.of((T) this.cause[i]);
<ide> }
<ide>
<ide> @Override
<del> public List<Object> getAllCauses() {
<add> public List<Object> all() {
<ide> return ImmutableList.copyOf(this.cause);
<ide> }
<ide>
<ide> }
<ide>
<ide> @Override
<del> public Optional<?> getRoot() {
<del> return Optional.absent();
<del> }
<del>
<del> @Override
<del> public <T> Optional<T> getFirst(Class<T> target) {
<del> return Optional.absent();
<del> }
<del>
<del> @Override
<del> public <T> Optional<T> getLast(Class<T> target) {
<del> return Optional.absent();
<del> }
<del>
<del> @Override
<del> public <T> List<T> getAllOf(Class<T> target) {
<add> public Optional<?> root() {
<add> return Optional.absent();
<add> }
<add>
<add> @Override
<add> public <T> Optional<T> first(Class<T> target) {
<add> return Optional.absent();
<add> }
<add>
<add> @Override
<add> public <T> Optional<T> last(Class<T> target) {
<add> return Optional.absent();
<add> }
<add>
<add> @Override
<add> public <T> List<T> allOf(Class<T> target) {
<ide> return ImmutableList.of();
<ide> }
<ide>
<ide> @Override
<del> public List<Object> getAllCauses() {
<add> public List<Object> all() {
<ide> return ImmutableList.of();
<ide> }
<ide> |
|
JavaScript | lgpl-2.1 | 50d271a0311a35e787e42b05a6e8103518d779aa | 0 | mbatchelor/pentaho-platform-plugin-reporting,mbatchelor/pentaho-platform-plugin-reporting,mbatchelor/pentaho-platform-plugin-reporting | /*!
* This program 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.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* Copyright (c) 2002-2016 Pentaho Corporation.. All rights reserved.
*/
define([ 'common-ui/util/util', 'common-ui/util/timeutil', 'common-ui/util/formatting', 'pentaho/common/Messages', "dojo/dom", "dojo/on", "dojo/_base/lang",
"dijit/registry", "dojo/has", "dojo/sniff", "dojo/dom-class", 'pentaho/reportviewer/ReportDialog', "dojo/dom-style", "dojo/query", "dojo/dom-geometry", "dojo/parser", "dojo/window", "dojo/_base/window", 'cdf/lib/jquery', 'amd!cdf/lib/jquery.ui', "common-repo/pentaho-ajax", "dijit/ProgressBar", "common-data/xhr"],
function(util, _timeutil, _formatting, _Messages, dom, on, lang, registry, has, sniff, domClass, ReportDialog, domStyle, query, geometry, parser, win, win2, $) {
return function(reportPrompt) {
if (!reportPrompt) {
alert("report prompt is required");
return;
}
/**
* ReportViewer Prompt instance
*
* @private
*/
var _reportPrompt = reportPrompt;
var v = logged({
/**
* Gets the ReportViewer Prompt object instance
*
* @returns {*}
* @readonly
*/
get reportPrompt () {
return _reportPrompt;
},
_currentReportStatus: null,
_currentReportUuid: null,
_currentStoredPagesCount: null,
_cachedReportCanceled: null,
_requestedPage: 0,
_previousPage: 0,
_reportUrl : null,
_handlerRegistration : null,
_locationPromptCancelHandlerRegistration: null,
_locationPromptOkHandlerRegistration: null,
_locationPromptFinishHandlerRegistration: null,
_locationPromptAttachHandlerRegistration: null,
_locationPromptFinished: null,
_locationOutputPath: null,
_manuallyScheduled: null,
_scheduleScreenBtnCallbacks: null,
_editModeToggledHandler: null,
_isFinished : false,
_bindPromptEvents: function() {
var baseShowGlassPane = this.reportPrompt.showGlassPane.bind(this.reportPrompt);
var baseHideGlassPane = this.reportPrompt.hideGlassPane.bind(this.reportPrompt);
this.reportPrompt.api.event.ready(this.view.promptReady.bind(this.view));
this.reportPrompt.showGlassPane = this.view.showGlassPane.bind(this.view, baseShowGlassPane);
this.reportPrompt.hideGlassPane = this.view.hideGlassPane.bind(this.view, baseHideGlassPane);
this.reportPrompt.api.event.submit(this.submitReport.bind(this));
this.reportPrompt.api.event.beforeUpdate(this.beforeUpdateCallback.bind(this));
this.reportPrompt.api.event.afterUpdate(this.afterUpdateCallback.bind(this));
this.reportPrompt.api.event.afterRender(this.view.afterRender.bind(this.view));
if (typeof parent.pho !== 'undefined' && typeof parent.pho.dashboards !== 'undefined') {
this._editModeToggledHandler = this.editModeToggledHandler.bind(this);
parent.pho.dashboards.addEditContentToggledListener(this._editModeToggledHandler);
}
},
load: function() {
_Messages.addUrlBundle('reportviewer', CONTEXT_PATH+'i18n?plugin=reporting&name=reportviewer/messages/messages');
this.view.localize();
this.createRequiredHooks();
this.view.updatePageBackground();
// Prevent blinking text cursors
// This only needs to be done once.
// Moreover, setting these properties causes browser re-layout (because of setting the style?),
// so the sooner the better.
function noUserSelect(g) {
g.setAttribute("style", "-webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none;");
// IE 9 / 8
if (typeof g.onselectstart !== 'undefined') {
g.setAttribute('unselectable', 'on');
g.onselectstart = function() { return false; };
}
}
noUserSelect(dom.byId('reportArea'));
noUserSelect(dom.byId('reportPageOutline'));
noUserSelect(dom.byId('reportContent'));
// ------------
on(registry.byId('toolbar-parameterToggle'), "click", lang.hitch( this, function() {
this.view.togglePromptPanel();
}));
on($('#notification-close'), "click", lang.hitch( this, function() {
domClass.add('notification-screen', 'hidden');
}));
var clearCache = registry.byId('toolbar-clearCache');
if(clearCache) {
on(clearCache, "click", lang.hitch(this, function () {
this.clearReportCache(this.submitReport.bind(this));
}));
}
if(window.top.mantle_addHandler){
//When slow connection there is a gap between tab glass pane and prompt glass pane
//So, let's hide tab glass pane only after widget is attached
var onAttach = function(event){
if(event.eventSubType == 'locationPromptAttached'){
this._forceHideGlassPane();
}
};
this._locationPromptAttachHandlerRegistration = window.top.mantle_addHandler('GenericEvent', onAttach.bind(this) );
}
window.onbeforeunload = function(e) {
this.cancel(this._currentReportStatus, this._currentReportUuid);
if(window.top.mantle_removeHandler) {
if(this._handlerRegistration) {
window.top.mantle_removeHandler(this._handlerRegistration);
}
if(this._locationPromptAttachHandlerRegistration) {
window.top.mantle_removeHandler(this._locationPromptAttachHandlerRegistration);
}
if(this._locationPromptCancelHandlerRegistration) {
window.top.mantle_removeHandler(this._locationPromptCancelHandlerRegistration);
}
if(this._locationPromptOkHandlerRegistration) {
window.top.mantle_removeHandler(this._locationPromptOkHandlerRegistration);
}
if(this._locationPromptFinishHandlerRegistration) {
window.top.mantle_removeHandler(this._locationPromptFinishHandlerRegistration);
}
}
return;
}.bind(this);
$("#reportContent")[0].contentWindow.onbeforeunload = function(e) {
if($("#reportContent")[0].contentWindow._isFirstIframeUrlSet == true) {
//user clicking a link in the report
this.cancel(this._currentReportStatus, this._currentReportUuid);
if(window.top.mantle_removeHandler) {
window.top.mantle_removeHandler(this._handlerRegistration);
}
} else {
//content is writing in the reportContent iframe first time
$("#reportContent")[0].contentWindow._isFirstIframeUrlSet = true;
}
return;
}.bind(this);
var boundOnReportContentLoaded = this._onReportContentLoaded.bind(this);
// Schedule the resize after the document has been rendered and CSS applied
var onFrameLoaded = logged('onFrameLoaded', function() {
setTimeout(boundOnReportContentLoaded);
});
if(has("ie")){
// When a file is downloaded, the "complete" readyState does not occur: "loading", "interactive", and stops.
on(dom.byId('reportContent'), "readystatechange", function() {
if(this.readyState === 'complete') { onFrameLoaded(); }
});
} else {
on(dom.byId('reportContent'), "load", lang.hitch( onFrameLoaded));
}
$('body')
.addClass(_isTopReportViewer ? 'topViewer leafViewer' : 'leafViewer')
.addClass(inMobile ? 'mobile' : 'nonMobile');
logger && $('body').addClass('debug');
this._bindPromptEvents();
this.reportPrompt.createPromptPanel();
var rowLimitControl = registry.byId('rowLimitControl');
if(rowLimitControl) {
rowLimitControl.bindChange(dojo.hitch(this, this._initRowLimitCallback));
rowLimitControl.bindGetMessage(function () {
return registry.byId('rowLimitMessage');
});
rowLimitControl.bindGetDialog(function () {
return registry.byId('rowLimitExceededDialog');
});
rowLimitControl.bindShowGlassPane(dojo.hitch(this, this._forceShowGlassPane));
rowLimitControl.bindHideGlassPane(dojo.hitch(this, function () {
this._forceHideGlassPane();
}));
}
var rowLimitMessage = registry.byId('rowLimitMessage');
if(rowLimitMessage) {
rowLimitMessage.bindRun(function () {
var match = window.location.href.match('.*repos\/(.*)(\.prpt).*');
if (match && match.length > 1) {
window.parent.executeCommand("RunInBackgroundCommand", {
solutionPath: decodeURIComponent(match[1] + match[2]).replace(/:/g, '/')
});
}
});
rowLimitMessage.bindSchedule(function () {
var match = window.location.href.match('.*repos\/(.*)(\.prpt).*');
if (match && match.length > 1) {
window.parent.mantle_openRepositoryFile(decodeURIComponent(match[1] + match[2]).replace(/:/g, '/'), "SCHEDULE_NEW");
}
});
}
},
view: logged({
/**
* Gets the ReportViewer Prompt object instance
*
* @returns {*}
* @readonly
*/
get reportPrompt () {
return _reportPrompt;
},
/**
* Localize the Report Viewer.
*/
localize: function() {
$('#toolbar-parameterToggle').attr('title', _Messages.getString('parameterToolbarItem_title'));
registry.byId('pageControl') && registry.byId('pageControl').registerLocalizationLookup(_Messages.getString);
registry.byId('rowLimitControl') && registry.byId('rowLimitControl').registerLocalizationLookup(_Messages.getString);
registry.byId('rowLimitExceededDialog') && registry.byId('rowLimitExceededDialog').registerLocalizationLookup(_Messages.getString);
registry.byId('rowLimitMessage') && registry.byId('rowLimitMessage').registerLocalizationLookup(_Messages.getString);
},
/**
* Update the page background when we're not in PUC or we're embedded in an
* iframe to make sure the translucent styling has some contrast.
*/
updatePageBackground: function() {
// If we're not in PUC or we're in an iframe
var inPuc;
try {
inPuc = window.top.mantle_initialized;
} catch (e) { // Ignore "Same-origin policy" violation in embedded IFrame
inPuc = false;
}
var inIFrame = top !== self;
// if we are not in PUC
if(!inSchedulerDialog && !inMobile && (!inPuc || inIFrame)) {
domClass.add(document.body, 'pentaho-page-background');
}
},
_showReportContent: function(visible, preserveSource) {
// Force not to show a blank iframe
var hasContent = this._hasReportContent();
if(!hasContent) { visible = false; }
if(this._isReportContentVisible() !== !!visible) {
// Don't touch "data-src" of an already blank iframe, or onload occurs needlessly...
if (!visible && !preserveSource && hasContent) {
logger && logger.log("Will clear content iframe.data-src");
//submit hidden form to POST data to iframe
$('#hiddenReportContentForm').attr("action", 'about:blank');
$('#hiddenReportContentForm').submit();
//set data attribute so that we know what url is currently displayed in
//the iframe without actually triggering a GET
$('#reportContent').attr("data-src", 'about:blank');
this._updatedIFrameSrc = true;
}
$('body')[visible ? 'removeClass' : 'addClass']('contentHidden');
}
},
_calcReportContentVisibility: function() {
var visible =
// Anything in the iframe to show? (PRD-4271)
this._hasReportContent() &&
// Valid data (although report content should be blank here)
!(this.reportPrompt._getStateProperty('promptNeeded')) &&
// Hide the report area when in the "New Schedule" dialog
!inSchedulerDialog &&
(this._isAutoSubmitAllowed() || this.reportPrompt._isSubmitPromptPhaseActivated);
return visible;
},
_isAutoSubmitAllowed : function() {
if(this.reportPrompt._getStateProperty('allowAutoSubmit')) { // (BISERVER-6915)
return true;
}
var iframes = document.getElementsByTagName("IFRAME");
if(iframes.length > 0) {
var src = $(iframes[0]).attr('data-src');
return src != null && src.indexOf('dashboard-mode') !== -1;
}
return false;
},
_isDashboardEditMode : function(){
try {
return window.frameElement.src.indexOf('dashboard-mode') !== -1 && parent.pho.dashboards.editMode;
} catch (e) {
return false;
}
},
_hasReportContent: function() {
var src = $('#reportContent').attr('data-src');
return src !== undefined && src !== 'about:blank';
},
_isReportContentVisible: function() {
return !$('body').hasClass('contentHidden');
},
// Called on page load and every time the prompt panel is refreshed
updateLayout: function() {
if (!this.reportPrompt._getStateProperty('showParameterUI')) {
this._hideToolbarPromptControls();
}
// The following call is important for clearing the report content when autoSubmit=false and the user has changed a value.
if(!this._calcReportContentVisibility() || this.reportPrompt._isAsync) {
this._showReportContent(false);
}
this._layoutInited = false;
this._initLayout();
},
_hideToolbarPromptControls: function() {
// Hide the toolbar elements
// When inMobile, toolbarlinner2 has another structure. See report.html.
if(!inMobile) { domClass.add('toolbar-parameter-separator', 'hidden'); }
// dijit modifies the HTML structure.
// At least in mobile, the button gets wrapped by a frame,
// that needs to be hidden.
var PARAM_TOGGLE = 'toolbar-parameterToggle';
var elem = dom.byId(PARAM_TOGGLE);
while(elem) {
if(elem.getAttribute('widgetid') === PARAM_TOGGLE) {
domClass.add(elem, 'hidden');
break;
}
elem = elem.parentNode;
}
},
showGlassPane: function(base) {
$("#glasspane")
.css("background", v.reportContentUpdating() ? "" : "transparent");
base();
},
hideGlassPane: function(base) {
if(!v.reportContentUpdating()) {
base();
}
// Activate bg.
$("#glasspane").css("background", "");
},
promptReady: function() {
this.reportPrompt.hideGlassPane();
if (inSchedulerDialog) {
// If we are rendering parameters for the "New Schedule" dialog,
// don't show the report or the submit panel, or the pages toolbar
this.showPromptPanel(true);
domClass.add('reportContent', 'hidden');
// SubmitPanel can be absent in DOM
var submitPanel = query('.submit-panel');
if (typeof submitPanel !== 'undefined' && submitPanel.length > 0) {
domClass.add(submitPanel[0], 'hidden');
}
domClass.add('toolbarlinner2', 'hidden');
domClass.remove('promptPanel', 'pentaho-rounded-panel-bottom-lr');
domClass.remove('reportControlPanel', 'pentaho-shadow');
domClass.remove('reportControlPanel', 'pentaho-rounded-panel-bottom-lr');
}
},
afterRender: function() {
if (inSchedulerDialog && typeof window.parameterValidityCallback !== 'undefined') {
var isValid = !this.reportPrompt._getStateProperty('promptNeeded');
window.parameterValidityCallback(isValid);
}
},
/**
* Initializes the report viewer's layout based on the loaded parameter definition.
*/
_initLayout: function() {
if(this._layoutInited) { return; } // reset on every navigation (see #init)
// Is it the first time, or is the parameter UI
// being refreshed due to user interaction (which causes "navigation")?
var navigating = !!this._initedOnce;
this._initedOnce = true;
var showParamUI = this.reportPrompt._getStateProperty('showParameterUI');
this.updatePageControl();
// Hide the toolbar, 'toppanel', when it would be empty and
// un-style the report so it's the only visible element
// when both the pagination controls and the parameter UI are hidden.
var isToolbarEmpty = !this.reportPrompt._getStateProperty("paginate") && !showParamUI && !this.reportPrompt._isReportHtmlPagebleOutputFormat;
domClass[isToolbarEmpty ? 'add' : 'remove']('toppanel', 'hidden');
// Don't mess with the parameters if we're "navigating".
// If the user has explicitly hidden the UI,
// and is going through several pages,
// we should not keep popping the UI again on each page init...
// PRD-4001, PRD-4102
var showOrHide;
// If not available, always respect the definition and hide
if(!showParamUI) {
showOrHide = false;
} else if(!navigating) {
// Shown or hidden by default?
// Don't show parameter panel by default unless prompt needed
showOrHide = (!inMobile && _isTopReportViewer) ||
this.reportPrompt._getStateProperty('promptNeeded') ||
!this.reportPrompt._getStateProperty('allowAutoSubmit');
}
var parameters = util.getUrlParameters();
var toggleParamName = 'toolbar-parameterToggle';
if (parameters[toggleParamName] !== undefined) {
this.showPromptPanel(parameters[toggleParamName] === 'true');
} else if (showOrHide != null) {
this.showPromptPanel(showOrHide);
}
this._layoutInited = true;
},
show: function() {
// Cleans up an issue where sometimes on show the iframe is offset
this.resize();
},
/**
*
* @param pageNumber
* @private
*/
_setAcceptedPage: function(pageNumber) {
this.reportPrompt.api.operation.setParameterValue("accepted-page", pageNumber);
},
/**
*
* @param pageNumber
* @private
*/
_getAcceptedPage: function() {
return this.reportPrompt.api.operation.getParameterValues()["accepted-page"];
},
/**
* @private
*/
_getRegistryObjectById: function(id) {
return registry.byId(id);
},
updatePageControl: function() {
var pc = this._getRegistryObjectById('pageControl');
pc.registerPageNumberChangeCallback(undefined);
if (!this.reportPrompt._getStateProperty("paginate")) {
if(this.reportPrompt._isAsync) {
this._setAcceptedPage('0');
} else {
this._setAcceptedPage('-1');
}
pc.setPageCount(1);
pc.setPageNumber(1);
// pc.disable();
} else {
var total = this.reportPrompt._getStateProperty("totalPages");
var page = this.reportPrompt._getStateProperty("page");
// We can't accept pages out of range. This can happen if we are on a page and then change a parameter value
// resulting in a new report with less pages. When this happens we'll just reduce the accepted page.
page = Math.max(0, Math.min(page, total - 1));
// add our default page, so we can keep this between selections of other parameters, otherwise it will not be on the
// set of params are default back to zero (page 1)
this._setAcceptedPage('' + page);
pc.setPageCount(total);
pc.setPageNumber(page + 1);
}
pc.registerPageNumberChangeCallback(function(pageNumber) {
this.pageChanged(pageNumber);
}.bind(this));
},
pageChanged: function(pageNumber) {
this._setAcceptedPage('' + (pageNumber - 1));
this.reportPrompt.api.operation.submit();
},
togglePromptPanel: function() {
this.showPromptPanel(registry.byId('toolbar-parameterToggle').checked);
this.resize();
},
showPromptPanel: function(visible) {
registry.byId('toolbar-parameterToggle').set('checked', !!visible);
domClass[visible ? 'remove' : 'add']('reportControlPanel', 'hidden');
},
isPageStyled: function() {
return $('body').hasClass('styled');
},
setPageStyled: function(styled) {
// normalize to boolean
styled = !!styled;
// Need to style at least the first time anyway,
// to ensure the HTML and JS are in sync.
if(!this._pageStyledOnce || this.isPageStyled() !== styled) {
this._pageStyledOnce = true;
var setClass = styled ? 'addClass' : 'removeClass';
$('body')
[setClass]('styled')
[styled ? 'removeClass' : 'addClass']('nonStyled');
if(!styled) {
// Clear style values set in JS to let class-imposed styles take effect
$('#reportArea' ).css({height: ""});
$('#reportContent').css({height: "", width: ""});
}
$('#reportPageOutline')[setClass]('pentaho-rounded-panel2-shadowed pentaho-padding-lg pentaho-background');
}
},
onViewportResize: function() {
this.resizeContentArea();
},
// called by #resize and by window.resize -> onViewportResize
resizeContentArea: function(callBefore) {
var vp = win.getBox();
var tp = geometry.getMarginBox('toppanel');
var rcpHeight = geometry.getMarginBox("rowLimitMessage");
var mb = {h: vp.h - tp.h - rcpHeight.h - 2};
logger && logger.log("viewport=(" + vp.w + "," + vp.h + ") " + " toppanel=(" + tp.w + "," + tp.h + ") ");
// Fill all available space
geometry.setMarginBox('reportArea', mb);
if(inMobile && this._isHtmlReport) {
this._resizeMobileHtmlReportHandlesScrolling(mb);
}
},
// In mobile, every report is shown unstyled.
// Mobile HTML reports handle scrolling itself.
// iOS Safari does not respect the iframe's style.overflow or the scrollable attribute
// and desperate measures had to be taken.
_resizeMobileHtmlReportHandlesScrolling: function(mb) {
// TODO: HACK: into the report content's HTML so that it handles scrolling correctly in Safari/iOS
var iframe = $('#reportContent');
var iframeDoc = iframe.contents();
var generator = iframeDoc.find('head>meta[name="generator"]').attr('content') || "";
var isReport = generator.indexOf("Reporting") >= 0;
if(isReport) {
iframe.attr('scrolling', 'no');
// TODO: HACK: Avoid a slightly clipped footer
var wh = mb.h - 15;
var scrollWrapper = iframeDoc.find('#reportTableDiv');
if(scrollWrapper.length) {
scrollWrapper.css({height: wh, width: (window.innerWidth-10) + 'px', overflow: 'auto'});
} else {
iframeDoc.find("body").css({margin: '2px'});
iframeDoc
.find("body>table")
.wrap('<div id="reportTableDiv" style="height:' + wh + 'px; width:' + (window.innerWidth-10) + 'px; overflow:auto;"/>');
}
}
},
/**
* Adjusts the report content iframe's width and height.
* The result is affected by:
* <ul>
* <li>content existing or not</li>
* <li>being in a mobile environment or not</li>
* <li>the existing content being styled</li>
* <li>the viewport size.</li>
* </ul>
*
* Finally, the {@link #resizeContentArea} method is called,
* that adjusts the report area div,
* responsible by showing up a scrollbar, when necessary.
*/
resize: function() {
if (!this._hasReportContent()) { return; }
// PRD-4000 Hide iframe before resize
// If not visible, let be so.
// If visible, hide it during the operation and show it again at the end.
var isVisible = this._isReportContentVisible();
if(isVisible) { this._showReportContent(false, /*preserveSource*/true); }
if(this.isPageStyled()) { this._pollReportContentSize(); }
this.resizeContentArea();
// PRD-4000 Show iframe after resize
if(isVisible) { this._showReportContent(true); }
},
_pollReportContentSize: function() {
var POLL_SIZE = 10;
var t = dom.byId('reportContent');
// Set the iframe size to minimum before POLLING its contents, to not affect the polled values.
// NOTE: Setting to 0 prevented IE9-Quirks from detecting the correct sizes.
// Setting here, and polling next, causes ONE resize on the iframe.
geometry.setContentSize(t, {w: POLL_SIZE, h: POLL_SIZE});
var outerDoc = document;
// It's surely HTML content, so the following is valid
win2.withDoc(t.contentWindow.document, function() {
setTimeout(function() {
// add overflow hidden to prevent scrollbars on ie9 inside the report
domStyle.set(win2.doc.getElementsByTagName("html")[0], {'overflow': 'hidden'});
var dimensions = geometry.getMarginBox(win2.doc.getElementsByTagName("body")[0]);
// changing width to jquery due to problems with dojo getting the width correcty
// although, dojo is used to get the height due to issues on ie8 and 9
dimensions.w = $('#reportContent').contents().width();
logger && logger.log("Styled page - polled dimensions = (" + dimensions.w + ", " + dimensions.h + ")");
// In case the styled report content is too small, assume 2/3 of the width.
// This may happen when there are no results.
if(dimensions.w <= POLL_SIZE) {
// Most certainly this indicates that the loaded report content
// does not have a fixed width, and, instead, adapts to the imposed size (like width: 100%).
var vp;
win2.withDoc(outerDoc, function() {
vp = win.getBox();
});
dimensions.w = Math.round(2 * vp.w / 3);
logger && logger.log("Width is too small - assuming a default width of " + dimensions.w);
}
geometry.setContentSize(t, {w: dimensions.w, h: dimensions.h});
$('#reportContent').hide().fadeIn('fast');
}, 10);
});
}
}), // end view
onTabCloseEvent: function (event) {
if(window.frameElement.src != null && window.frameElement.src.indexOf('dashboard-mode') !== -1 ){
if (event.eventSubType == 'tabClosing' && event.stringParam == window.parent.frameElement.id) {
this.cancel(this._currentReportStatus, this._currentReportUuid);
if(window.top.mantle_removeHandler) {
window.top.mantle_removeHandler(this._handlerRegistration);
}
}
}
else {
if (event.eventSubType == 'tabClosing' && event.stringParam == window.frameElement.id) {
this.cancel(this._currentReportStatus, this._currentReportUuid);
if(window.top.mantle_removeHandler) {
window.top.mantle_removeHandler(this._handlerRegistration);
}
}
}
},
cancel: function(status, uuid) {
var url = window.location.href.split('?')[0];
if( uuid && (!status || status == 'WORKING' || status == 'QUEUED' || status == 'CONTENT_AVAILABLE' || status == 'PRE_SCHEDULED') ) {
pentahoGet(url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + uuid + '/cancel', "");
}
},
createRequiredHooks: function() {
// [PIR-543] - Allow new/refreshed reports to re-attach or override instance functions in the top window object
// Top window functions may become orphaned due to content linking refresh or when a report tab in PUC is closed
/*
try {
if (window.reportViewer_openUrlInDialog || top.reportViewer_openUrlInDialog) {
return;
}
} catch(err) {
return; // [PIR-543] - IE 9.0.5 throws a Permission Denied error
}
*/
var isRunningIFrameInSameOrigin = null;
try {
var ignoredCheckCanReachOutToTop = window.top.mantle_initialized;
isRunningIFrameInSameOrigin = true;
} catch (ignoredSameOriginPolicyViolation) {
// IFrame is running embedded in a web page in another domain
isRunningIFrameInSameOrigin = false;
}
if(isRunningIFrameInSameOrigin) {
if (!top.mantle_initialized) {
top.mantle_openTab = function(name, title, url) {
window.open(url, '_blank');
}
}
if (top.mantle_initialized) {
top.reportViewer_openUrlInDialog = function(title, url, width, height) {
top.urlCommand(url, title, true, width, height);
};
} else {
top.reportViewer_openUrlInDialog = this.openUrlInDialog.bind(this);
}
window.reportViewer_openUrlInDialog = top.reportViewer_openUrlInDialog;
}
window.reportViewer_hide = this.hide.bind(this);
if(window.location.href.indexOf("/parameterUi") == -1 && window.top.mantle_addHandler) {
// only in case when report is opened in tab('/viewer')
this._handlerRegistration = window.top.mantle_addHandler("GenericEvent", this.onTabCloseEvent.bind(this));
}
var localThis = this;
if (isRunningIFrameInSameOrigin && typeof window.top.addGlassPaneListener !== 'undefined') {
window.top.addGlassPaneListener({
glassPaneHidden: function(){
localThis.view.show();
}
});
}
},
openUrlInDialog: function(title, url, width, height) {
if (this.dialog === undefined) {
this.dialog = new pentaho.reportviewer.ReportDialog();
this.dialog.setLocalizationLookupFunction(_Messages.getString);
}
this.dialog.open(title, url, width, height);
},
/**
* Hide the Report Viewer toolbar.
* TODO: In what world is this a "hide"? empty()?
* Can't find where this is called from!
*/
hide: function() {
$('#toppanel').empty();
this.view.resize();
},
beforeUpdateCallback: function() {
if(this.reportPrompt.api.operation.state().autoSubmit) {
this.reportPrompt._isUpdatingPrompting = true;
}
},
afterUpdateCallback: function() {
this.view.updateLayout();
this._updateReportContent();
},
// Called by SubmitPromptComponent#expression (the submit button's click)
// Also may be called by PromptPanel#init, when there is no submit button (independently of autoSubmit?).
submitReport: function(keyArgs) {
this.reportPrompt._isSubmitPromptPhaseActivated = true;
try {
// If we are rendering parameters for the "New Schedule" dialog,
// don't show the report, the submit panel and pages toolbar.
if (inSchedulerDialog) {
this._submitReportEnded();
return;
}
// Make sure that layout is initialized
this.view._initLayout();
// Don't do anything if we need prompting (hide report content -> clear iframe data-src)
var isValid = !this.reportPrompt._getStateProperty('promptNeeded');
if (!isValid) {
this.view._showReportContent(false);
this._submitReportEnded();
return;
}
if (!this.reportPrompt._getStateProperty("autoSubmit") ) {
if(!this.reportPrompt._isAsync){
this.reportPrompt.mode = 'MANUAL';
this.reportPrompt.api.operation.refreshPrompt();
}else{
this._updateReportContent();
}
} else if (!this.reportPrompt._isUpdatingPrompting ) { // no need updating report content during submit because we have afterUpdate event subscription
this._updateReportContent();
}
} catch(ex) {
this._submitReportEnded();
throw ex;
}
},
clearReportCache: function (callback) {
try {
var url = window.location.href.split('?')[0];
pentahoPost(url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/cache/clear', '', callback, 'text/text');
} catch (e) {
logger && logger.log("Can't clear cache.");
callback();
}
},
_updatedIFrameSrc: false,
_updateReportTimeout: -1,
reportContentUpdating: function() {
return this._updateReportTimeout >= 0;
},
_updateReportContent: function() {
//init row limit UI in any case
var options = this._buildReportContentOptions();
var requestLimit = parseInt(options['query-limit'], 0);
var systemRowLimit = parseInt(options['maximum-query-limit'], 0);
var isQueryLimitControlEnabled = this.reportPrompt._isAsync && options['query-limit-ui-enabled'] == "true";
if (isQueryLimitControlEnabled) {
var rowLimitControl = registry.byId('rowLimitControl');
if(rowLimitControl) {
rowLimitControl.apply(systemRowLimit, requestLimit, false);
domClass.remove(dom.byId("toolbar-parameter-separator-row-limit"), "hidden");
domClass.remove(dom.byId('rowLimitControl'), "hidden");
}
};
if (this.reportPrompt._isSubmitPromptPhaseActivated || this.reportPrompt._getStateProperty("autoSubmit")) {
this._updateReportContentCore();
}
},
_getFeedbackScreen: function (scheduleScreenBtnCallbacks) {
var dlg = registry.byId('feedbackScreen');
dlg.setTitle(_Messages.getString('ScreenTitle'));
dlg.setText(_Messages.getString('FeedbackScreenActivity'));
dlg.setText2(_Messages.getString('FeedbackScreenPage'));
dlg.setText3(_Messages.getString('FeedbackScreenRow'));
dlg.setCancelText(_Messages.getString('ScreenCancel'));
if(!this.view._isDashboardEditMode()){
dlg.showBackgroundBtn(_Messages.getString('FeedbackScreenBackground'));
}else {
scheduleScreenBtnCallbacks.shift();
dlg.hideBackgroundBtn();
}
dlg.callbacks = scheduleScreenBtnCallbacks;
return dlg;
},
editModeToggledHandler: function (editMode) {
var feedbackScreen = registry.byId('feedbackScreen');
var scheduleScreenBtnCallbacks = _scheduleScreenBtnCallbacks;
var feedbackScreenHideStatuses = 'CANCELED|FINISHED|SCHEDULED|CONTENT_AVAILABLE';
if (feedbackScreen) {
if (editMode) {
feedbackScreen.hide();
feedbackScreen.callbacks = [scheduleScreenBtnCallbacks[1]];
feedbackScreen.hideBackgroundBtn();
if (feedbackScreenHideStatuses.indexOf(this._currentReportStatus) == -1) {
feedbackScreen.show();
}
} else {
feedbackScreen.hide();
feedbackScreen.showBackgroundBtn(_Messages.getString('FeedbackScreenBackground'));
if (feedbackScreenHideStatuses.indexOf(this._currentReportStatus) == -1) {
feedbackScreen.show();
}
feedbackScreen.callbacks = scheduleScreenBtnCallbacks;
}
}
},
_getPageLoadingDialog: function (loadingDialogCallbacks) {
var pageIsloadingDialog = registry.byId('reportGlassPane');
pageIsloadingDialog.setTitle(_Messages.getString('ScreenTitle'));
pageIsloadingDialog.setText(_Messages.getString('LoadingPage'));
pageIsloadingDialog.setButtonText(_Messages.getString('ScreenCancel'));
pageIsloadingDialog.callbacks = loadingDialogCallbacks;
return pageIsloadingDialog;
},
_requestCacheFlush: function (url) {
var urlRequestPage = url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + this._currentReportUuid
+ '/requestPage/' + this._requestedPage;
pentahoGet(urlRequestPage, "");
var loadingDialogCallbacks = [
//Cancel navigation
function reportGlassPaneDone() {
this._requestedPage = this._previousPage;
var pageContr = registry.byId('pageControl');
pageContr.setPageNumber(this._previousPage);
this._cachedReportCanceled = true;
registry.byId('reportGlassPane').hide();
}.bind(this)];
var pageLoadingDialog = this._getPageLoadingDialog(loadingDialogCallbacks);
pageLoadingDialog.show();
},
_hideAsyncScreens: function(){
registry.byId('reportGlassPane').hide();
domClass.add('notification-screen', 'hidden');
},
_submitRowLimitUpdate: function (selectedLimit) {
var me = this;
me.cancel(me._currentReportStatus, me._currentReportUuid);
me._isFinished = true;
me._submitReportEnded(true);
me.reportPrompt.api.operation.setParameterValue("query-limit", selectedLimit);
me._hideDialogAndPane(registry.byId('feedbackScreen'));
if (window.top.mantle_removeHandler) {
window.top.mantle_removeHandler(this._handlerRegistration);
}
me.view.updatePageControl();
setTimeout(function () {
me.submitReport(true);
}, me.reportPrompt._pollingInterval);
},
_initRowLimitCallback: function (selectedLimit) {
this.reportPrompt.api.operation.setParameterValue("query-limit", selectedLimit);
registry.byId('rowLimitControl') && registry.byId('rowLimitControl').bindChange(dojo.hitch(this, this._submitRowLimitUpdate));
},
_updateReportContentCore: function() {
//no report generation in scheduling dialog ever!
if(inSchedulerDialog){
return;
}
var me = this;
// PRD-3962 - remove glass pane after 5 seconds in case iframe onload/onreadystatechange was not detected
me._updateReportTimeout = setTimeout(logged('updateReportTimeout', function() {
//BACKLOG-8070 don't show empty content in async mode
me._submitReportEnded( !me.reportPrompt._isAsync );
}), 5000);
// PRD-3962 - show glass pane on submit, hide when iframe is loaded.
// Must be done AFTER _updateReportTimeout has been set, cause it's used to know
// that the report content is being updated.
me.reportPrompt.showGlassPane();
me._updateParametersDisabledState(true);
var options = me._buildReportContentOptions();
var url = me._buildReportContentUrl(options);
var outputFormat = options['output-target'];
var isHtml = outputFormat.indexOf('html') != -1;
var isProportionalWidth = isHtml && options['htmlProportionalWidth'] == "true";
var isReportAlone = domClass.contains('toppanel', 'hidden');
var isQueryLimitControlEnabled = me.reportPrompt._isAsync && options['query-limit-ui-enabled'] == "true";
var requestLimit = parseInt(options['query-limit'], 0);
var systemRowLimit = parseInt(options['maximum-query-limit'], 0);
var styled = _isTopReportViewer && !isReportAlone &&
isHtml && !isProportionalWidth &&
!inMobile;
// If the new output format causes a pageStyle change,
// and we don't hide the iframe "now",
// Then, when the iframe loads,
// the user may temporarily see the new document
// with the previous page style.
if(me.view.isPageStyled() !== styled) {
logger &&
logger.log("Page style will change to " + (styled ? "" : "non-") +
"styled. Will hide report before iframe update.");
me.view._showReportContent(false, /*preserveSource*/true);
}
//Async report execution
//This flag is switched to false after 1st page is ready - specific for paginated html
var isFirstContAvStatus = true;
//This flags is changed when report is finished and iframe is updated/ conent is downloaded
var isIframeContentSet = false;
//This flag is switched to true after we get total page count and updated page control
var isPageCountUpdated = false;
//Report generation finished ( also includes canceled and failed cases)
me._isFinished = false;
//Hides feedback screen and glasspane
var hideDlgAndPane = this._hideDialogAndPane.bind(me);
//Tells us if report was manually scheduled from the feedback screen
me._manuallyScheduled = false;
//Current requested page - is updated if user navigates after 1st page is shown
me._requestedPage = me.view._getAcceptedPage();
me._locationPromptFinished = false;
me._locationOutputPath = me.reportPrompt._defaultOutputPath;
//We are in async mode
if (me.reportPrompt._isAsync) {
/*Async callbacks code START*/
var mainReportGeneration = dojo.hitch(me, function (result) {
var mainJobStatus = me._getAsyncJobStatus(result, hideDlgAndPane);
if (mainJobStatus && mainJobStatus.status != null) {
if (isQueryLimitControlEnabled) {
registry.byId('rowLimitControl') && registry.byId('rowLimitControl').apply(systemRowLimit, requestLimit, mainJobStatus.isQueryLimitReached);
}
me._updateFeedbackScreen(mainJobStatus, feedbackDialog);
//Configure callback for first page
var firtsPageReadyCallback = dojo.hitch(me, function (result2) {
if (!me.reportPrompt._isReportHtmlPagebleOutputFormat) {
logger && logger.log("ERROR: " + "You are in 1st page callback not for paginated HTML. Something went wrong.");
return;
}
firstPageJobStatus = JSON.parse(result2);
switch (firstPageJobStatus.status) {
case "QUEUED":
case "WORKING":
me._keepPolling(firstPageJobStatus.uuid, url, firtsPageReadyCallback);
break;
case "FINISHED" :
me._isFinished = true;
me._hideAsyncScreens();
//Let's get first page
me._getContent(firstPageJobStatus.uuid, url, function () {
isIframeContentSet = true;
});
me._previousPage = firstPageJobStatus.page;
hideDlgAndPane(registry.byId('feedbackScreen'));
//Show loading screen
$('#notification-message').html(_Messages.getString('LoadingPage'));
$('#notification-screen').css("z-index", 100);
if (me._currentReportStatus == 'CONTENT_AVAILABLE') {
domClass.remove('notification-screen', 'hidden');
}
break;
}
});
switch (mainJobStatus.status) {
case "CONTENT_AVAILABLE":
if (isFirstContAvStatus) {
me._hideAsyncScreens();
isFirstContAvStatus = false;
//1st page is ready - need to spawn another job to get it
if (me._currentStoredPagesCount > me._requestedPage) {
//Prevent double content update on 1st page
me._requestedPage = -1;
pentahoPost('reportjob', url.substring(url.lastIndexOf("/report?") + "/report?".length, url.length), firtsPageReadyCallback, 'text/text');
}
me._keepPolling(mainJobStatus.uuid, url, mainReportGeneration);
} else {
if ((me._cachedReportCanceled && me._requestedPage == 0) || ((me._requestedPage >= 0) && (me._currentStoredPagesCount > me._requestedPage))) {
//adjust accepted page in url
var newUrl = url.substring(url.lastIndexOf("/report?") + "/report?".length, url.length);
newUrl = newUrl.replace(/(accepted-page=)\d*?(&)/, '$1' + me._requestedPage + '$2');
//BACKLOG-9814 distinguish initial 1st page from going back to the 1st page
me._requestedPage = -1;
me._cachedReportCanceled = false;
pentahoPost('reportjob', newUrl, firtsPageReadyCallback, 'text/text');
registry.byId('reportGlassPane').hide();
}
//update page number
if (me.reportPrompt._isReportHtmlPagebleOutputFormat && !isPageCountUpdated) {
var pageContr = registry.byId('pageControl');
pageContr.setPageCount(mainJobStatus.totalPages);
isPageCountUpdated = true;
}
$('#notification-message').html(_Messages.getString('LoadingPage') + " " + mainJobStatus.page + " " + _Messages.getString('Of') + " " + mainJobStatus.totalPages);
registry.byId('reportGlassPane').setText(_Messages.getString('LoadingPage') + " " + mainJobStatus.page + " " + _Messages.getString('Of') + " " + mainJobStatus.totalPages);
me._keepPolling(mainJobStatus.uuid, url, mainReportGeneration);
}
break;
//note - no break here - w e need to poll
case "QUEUED":
case "WORKING":
me._hideAsyncScreens();
me._keepPolling(mainJobStatus.uuid, url, mainReportGeneration);
break;
case "FINISHED":
me._isFinished = true;
hideDlgAndPane(registry.byId('feedbackScreen'));
me._hideAsyncScreens();
//Show report
if (!isIframeContentSet) {
me._getContent(mainJobStatus.uuid, url, function () {
isIframeContentSet = true;
});
//Callback for downloadable types because they don't have iframe callback
if (me._isDownloadableFormat(mainJobStatus.mimeType)) {
setTimeout(function () {
me._submitReportEnded(true);
}, me.reportPrompt._pollingInterval);
}
}
if (me._requestedPage > 0) {
// main request finished before requested page was stored in cache but wee still need to show valif page
var newUrl = url.substring(url.lastIndexOf("/report?") + "/report?".length, url.length);
var match = newUrl.match(/(^.*accepted-page=)(\d*?)(&.*$)/);
//if not handled by another job
if (match[2] != me._requestedPage) {
newUrl = match[1] + me._requestedPage + match[3];
me._requestedPage = 0;
pentahoPost('reportjob', newUrl, firtsPageReadyCallback, 'text/text');
}
}
//Set total number of pages for paginated HTML
if (me.reportPrompt._isReportHtmlPagebleOutputFormat && !isPageCountUpdated) {
var pageContr = registry.byId('pageControl');
pageContr.setPageCount(mainJobStatus.totalPages);
isPageCountUpdated = true;
}
break;
case "FAILED":
me._isFinished = true;
me._submitReportEnded();
//Hide dialogs and show error
var errorMsg = _Messages.getString('DefaultErrorMessage');
if (mainJobStatus.errorMessage != null) {
errorMsg = mainJobStatus.errorMessage;
}
me.reportPrompt.showMessageBox(
errorMsg,
_Messages.getString('ErrorPromptTitle'));
registry.byId('feedbackScreen').hide();
me._hideAsyncScreens();
me._updateParametersDisabledState(false);
logger && logger.log("ERROR: Request status - FAILED");
break;
case "PRE_SCHEDULED":
//Could occur when auto scheduling or manual scheduling + location prompt
if(me._locationPromptFinished){
me._keepPolling(mainJobStatus.uuid, url, mainReportGeneration);
} else if (!me._manuallyScheduled){
me._isFinished = true;
var autoScheduleDlg = registry.byId('scheduleScreen');
autoScheduleDlg.setTitle(_Messages.getString('AutoScheduleTitle'));
autoScheduleDlg.setText(_Messages.getString('AutoScheduleText'));
autoScheduleDlg.setOkBtnText(_Messages.getString('FeedbackScreenBackground'));
autoScheduleDlg.setCancelBtnText(_Messages.getString('ScreenCancel'));
autoScheduleDlg.callbacks = me._getAutoScheduleScreenBtnCallbacks(mainReportGeneration, url);
registry.byId('feedbackScreen').hide();
autoScheduleDlg.show();
}
break;
case "SCHEDULED":
//Scheduling is confirmed, the task is not cancelable anymore
me._isFinished = true;
me._submitReportEnded();
me._hideAsyncScreens();
var successDlg = me._getSuccessSchedulingDlg();
registry.byId('feedbackScreen').hide(); // glasspane is still needed
successDlg.show();
break;
case "CANCELED":
me._submitReportEnded();
me._hideAsyncScreens();
break;
}
}
return mainJobStatus;
});
//Async execution manages this flag in it's own way
me.reportPrompt._isSubmitPromptPhaseActivated = false;
var scheduleScreenBtnCallbacks = me._getScheduleScreenBtnCallbacks(mainReportGeneration, url, hideDlgAndPane);
_scheduleScreenBtnCallbacks = scheduleScreenBtnCallbacks.slice();
var feedbackDialog = me._getFeedbackScreen(scheduleScreenBtnCallbacks);
//Don't show dialog if report is ready faster than threshold
setTimeout(function () {
if (!me._isFinished) {
feedbackDialog.show();
}
}, me.reportPrompt._dialogThreshold);
/*Async callbacks code END*/
//Main report job start and page requests goes below
var reportUrl = url.substring(url.lastIndexOf("/report?") + "/report?".length, url.length);
switch (me._currentReportStatus) {
case 'CONTENT_AVAILABLE':
//This section should only affect paginated HTML after 1st page is recieved
//Check if requested page is already persisted to cache
if (me._currentStoredPagesCount > me._requestedPage) {
//Page available
var current = reportUrl.match(/(^.*accepted-page=)(\d*?)(&.*$)/);
var running = me._reportUrl.match(/(^.*accepted-page=)(\d*?)(&.*$)/);
if (current && running && current[1] != running[1]) {
//Actually user changed not the page but prompts/output target - we need a new job to get it
me._reportUrl = reportUrl;
me.cancel(me._currentReportStatus, me._currentReportUuid);
pentahoPost('reportjob', reportUrl, mainReportGeneration, 'text/text');
me._hideAsyncScreens();
} else {
//Page navigation occurred - callbacks will do the job
me._isFinished = true;
}
} else {
//Need to request cache flush
me._requestCacheFlush(url);
me._isFinished = true;
}
break;
default:
me._hideAsyncScreens();
//Not started or finished
this._reportUrl = reportUrl;
var isValid = !me.reportPrompt._getStateProperty('promptNeeded');
if (isValid) {
pentahoPost(url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/reserveId', "", function (data) {
try {
me._currentReportUuid = JSON.parse(data).reservedId;
// backlog-10041 do not send GET request with overloaded parameters passed via url
pentahoPost('reportjob', reportUrl + "&reservedId=" + me._currentReportUuid, mainReportGeneration, 'text/text');
} catch (e) {
logger && logger.log("Can't reserve id");
pentahoPost('reportjob', reportUrl, mainReportGeneration, 'text/text');
}
});
} else {
me._isFinished = true;
hideDlgAndPane();
}
break;
}
} else {
me._hideAsyncScreens();
logger && logger.log("Will set iframe url to " + url.substr(0, 50) + "... ");
//submit hidden form to POST data to iframe
$('#hiddenReportContentForm').attr("action", url);
$('#hiddenReportContentForm').submit();
//set data attribute so that we know what url is currently displayed in
//the iframe without actually triggering a GET
$('#reportContent').attr("data-src", url);
me._updatedIFrameSrc = true;
}
// Continue when iframe is loaded (called by #_onReportContentLoaded)
me._submitLoadCallback = logged('_submitLoadCallback', function() {
me._isHtmlReport = me.view._isHtmlReport = isHtml;
me._outputFormat = outputFormat;
var visible = me.view._calcReportContentVisibility();
if(visible) {
// A child viewer forces changing to non-styled
me.view.setPageStyled(styled && !me._isParentViewer);
me.view.resize();
}
me.view._showReportContent(visible);
me._submitReportEnded();
});
},
_buildParameter: function (pathArray, id) {
var path;
for (var i = 0; i < pathArray.length; i++) {
if (pathArray[i].indexOf(".prpt") !== -1) {
path = decodeURIComponent(pathArray[i]).replace(/:/g, "/");
}
}
return {
solutionPath: (path == null ? "/" : path ),
jobId: id,
recalculateFinished: true == this.reportPrompt._isReportHtmlPagebleOutputFormat
};
},
_getSuccessSchedulingDlg: function () {
var me = this;
var successDlg = registry.byId('successScheduleScreen');
successDlg.setTitle(_Messages.getString('SuccessScheduleTitle'));
successDlg.setText(_Messages.getString('SuccessScheduleText', '<b><i>' + me._locationOutputPath +'</i></b>'));
successDlg.setOkBtnText(_Messages.getString('OK'));
var successScheduleDialogCallbacks = [
function hide() {
me._updateParametersDisabledState(false);
me._forceHideGlassPane();
successDlg.hide();
}.bind(me)
];
successDlg.callbacks = successScheduleDialogCallbacks;
return successDlg;
},
_forceHideGlassPane: function (){
$("#glasspane").css("background", "transparent");
$("#glasspane").css("display", "none");
},
_forceShowGlassPane: function (){
$("#glasspane").css("background", "");
$("#glasspane").css("display", "block");
},
_onLocationPromptCancel : function (mainReportGeneration, url) {
var me = this;
return function (event) {
if (event.eventSubType == 'locationPromptCanceled') {
me._locationPromptFinished = true;
//Show glass pane and feedback screen
me._forceShowGlassPane();
registry.byId('feedbackScreen').show();
var specialCaseProxy = dojo.hitch(me, function (result) {
if (me.reportPrompt._isReportHtmlPagebleOutputFormat) {
var mainJobStatus;
try {
/*If pre scheduled paginated HTML report is finished it will contain all the pages
but we need only one. So we spawn a new job and get results from cache.
*/
mainJobStatus = JSON.parse(result);
if (mainJobStatus.status == 'FINISHED') {
pentahoPost('reportjob', me._reportUrl, mainReportGeneration, 'text/text');
} else {
mainReportGeneration(result);
}
} catch (e) {
mainReportGeneration(result);
}
} else {
mainReportGeneration(result);
}
});
//Keep polling
setTimeout(function () {
pentahoGet(url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + me._currentReportUuid + '/status', "", specialCaseProxy);
}, me.reportPrompt._pollingInterval);
me._removeLocationPromptHandlers();
}
};
},
_onLocationPromptOk : function (mainReportGeneration, url) {
var me = this;
return function (event) {
if (event.eventSubType == 'locationPromptOk') {
try {
me._locationOutputPath = event.stringParam;
} catch (e) {
logger && logger.log("ERROR" + String(e));
}
me._locationPromptFinished = true;
me._forceShowGlassPane();
var waitForScheduled = dojo.hitch(me, function (result) {
try {
mainJobStatus = JSON.parse(result);
if (mainJobStatus.status == 'SCHEDULED' || mainJobStatus.status == 'FAILED') {
mainReportGeneration(result);
} else {
setTimeout(function () {
pentahoGet(url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + me._currentReportUuid + '/status', "", waitForScheduled);
}, me.reportPrompt._pollingInterval);
}
} catch (e) {
mainReportGeneration(result);
}
});
//Keep polling
setTimeout(function () {
pentahoGet(url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + me._currentReportUuid + '/status', "", waitForScheduled);
}, me.reportPrompt._pollingInterval);
me._removeLocationPromptHandlers();
}
};
},
_onLocationPromptFinish : function(){
var me = this;
return function (event) {
if (event.eventSubType == 'locationPromptFinish') {
me._currentReportUuid = event.stringParam;
if (window.top.mantle_removeHandler) {
if (me._locationPromptFinishHandlerRegistration) {
window.top.mantle_removeHandler(me._locationPromptFinishHandlerRegistration);
}
}
}
};
},
_onLocationPromptCancelAuto : function() {
var me = this;
return function (event) {
if (event.eventSubType == 'locationPromptCanceled') {
me._updateParametersDisabledState(false);
me._forceHideGlassPane();
me.cancel(me._currentReportStatus, me._currentReportUuid);
me._removeLocationPromptHandlers();
}
};
},
_onLocationPromptOkAuto : function(mainReportGeneration, url) {
var me = this;
return function (event) {
if (event.eventSubType == 'locationPromptOk') {
me._locationOutputPath = event.stringParam;
me._locationPromptFinished = true;
me._forceShowGlassPane();
var waitForScheduled = dojo.hitch(me, function (result) {
try {
mainJobStatus = JSON.parse(result);
if (mainJobStatus.status == 'SCHEDULED' || mainJobStatus.status == 'FAILED') {
mainReportGeneration(result);
} else {
setTimeout(function () {
pentahoGet(url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + me._currentReportUuid + '/status', "", waitForScheduled);
}, me.reportPrompt._pollingInterval);
}
} catch (e) {
mainReportGeneration(result);
}
});
setTimeout(function () {
pentahoGet(url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + me._currentReportUuid + '/status', "", waitForScheduled);
}, me.reportPrompt._pollingInterval);
me._removeLocationPromptHandlers();
}
};
},
_removeLocationPromptHandlers: function(){
if (window.top.mantle_removeHandler) {
if(this._locationPromptCancelHandlerRegistration) {
window.top.mantle_removeHandler(this._locationPromptCancelHandlerRegistration);
}
if(this._locationPromptOkHandlerRegistration) {
window.top.mantle_removeHandler(this._locationPromptOkHandlerRegistration);
}
}
},
_getScheduleScreenBtnCallbacks : function (mainReportGeneration, url, hideDlgAndPane) {
var me = this;
return [
//Schedule button callback
function scheduleReport() {
var urlSchedule = url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + me._currentReportUuid + '/schedule';
pentahoGet(urlSchedule, "confirm=" + !me.reportPrompt._promptForLocation);
me._manuallyScheduled = true;
registry.byId('feedbackScreen').hide();
if (me.reportPrompt._promptForLocation) {
if(window.top.mantle_addHandler) {
me._locationPromptCancelHandlerRegistration = window.top.mantle_addHandler("GenericEvent",
this._onLocationPromptCancel(mainReportGeneration, url).bind(this) );
me._locationPromptOkHandlerRegistration = window.top.mantle_addHandler("GenericEvent", this._onLocationPromptOk(mainReportGeneration, url).bind(this) );
me._locationPromptFinishHandlerRegistration = window.top.mantle_addHandler("GenericEvent", this._onLocationPromptFinish().bind(this));
}
//Open location prompt
me._locationPromptFinished = false;
window.top.executeCommand("AdhocRunInBackgroundCommand", me._buildParameter(pathArray, me._currentReportUuid));
}
}.bind(me),
//Cancel report
function feedbackscreenDone() {
me.cancel(me._currentReportStatus, me._currentReportUuid);
hideDlgAndPane(registry.byId('feedbackScreen'));
}.bind(me)
]
},
_getAutoScheduleScreenBtnCallbacks : function (mainReportGeneration, url){
var me = this;
var autoScheduleDialogCallbacks;
var autoScheduleDlg = registry.byId('scheduleScreen');
if(me.reportPrompt._promptForLocation) {
autoScheduleDialogCallbacks = [
function openPrompt() {
autoScheduleDlg.hide();
if(window.top.mantle_addHandler) {
me._locationPromptCancelHandlerRegistration = window.top.mantle_addHandler("GenericEvent", this._onLocationPromptCancelAuto().bind(this) );
me._locationPromptOkHandlerRegistration = window.top.mantle_addHandler("GenericEvent", this._onLocationPromptOkAuto(mainReportGeneration, url).bind(this) );
me._locationPromptFinishHandlerRegistration = window.top.mantle_addHandler("GenericEvent", this._onLocationPromptFinish().bind(this));
}
//Open location prompt
me._locationPromptFinished = false;
window.top.executeCommand("AdhocRunInBackgroundCommand", me._buildParameter(pathArray, me._currentReportUuid));
}.bind(me),
function cancel() {
autoScheduleDlg.hide();
me._updateParametersDisabledState(false);
me._forceHideGlassPane();
me.cancel(me._currentReportStatus, me._currentReportUuid);
}.bind(me)
];
}else{
autoScheduleDialogCallbacks = [
function confirm() {
autoScheduleDlg.hide();
var urlSchedule = url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + me._currentReportUuid + '/schedule';
pentahoGet(urlSchedule, "confirm=true");
me._locationPromptFinished = true;
me._keepPolling(me._currentReportUuid, url, mainReportGeneration);
}.bind(me),
function cancel() {
autoScheduleDlg.hide();
me._updateParametersDisabledState(false);
me._forceHideGlassPane();
me.cancel(me._currentReportStatus, me._currentReportUuid);
}.bind(me)
];
}
return autoScheduleDialogCallbacks;
},
_keepPolling : function (uuid, url, callback){
var me = this;
setTimeout(function () {
pentahoGet(url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + uuid + '/status', "", callback);
}, me.reportPrompt._pollingInterval);
},
_getContent : function (uuid, url, callback) {
var me = this;
var urlContent = url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + uuid + '/content';
logger && logger.log("Will set iframe url to " + urlContent.substr(0, 50) + "... ");
$('#hiddenReportContentForm').attr("action", urlContent);
$('#hiddenReportContentForm').submit();
$('#reportContent').attr("data-src", urlContent);
me._updatedIFrameSrc = true;
me.reportPrompt._isSubmitPromptPhaseActivated = true;
if(callback){
callback();
}
},
_getAsyncJobStatus : function(result, hideDlgAndPane){
var me = this;
var mainJobStatus;
try {
mainJobStatus = JSON.parse(result);
return mainJobStatus;
} catch (e) {
var errorMessage = _Messages.getString('DefaultErrorMessage');
this.reportPrompt.showMessageBox(
errorMessage,
_Messages.getString('ErrorPromptTitle'));
hideDlgAndPane(registry.byId('feedbackScreen'));
me._hideAsyncScreens();
logger && logger.log("ERROR" + String(e));
return;
}
},
_updateFeedbackScreen: function (mainJobStatus, feedbackDialog) {
var me = this;
//Update current values
me._currentReportStatus = mainJobStatus.status;
me._currentReportUuid = mainJobStatus.uuid;
me._currentStoredPagesCount = mainJobStatus.generatedPage;
//Update feedback screen ui
if (mainJobStatus.activity != null) {
feedbackDialog.setText(_Messages.getString(mainJobStatus.activity) + '...');
}
feedbackDialog.setText2(_Messages.getString('FeedbackScreenPage') + ': ' + mainJobStatus.page);
feedbackDialog.setText3(_Messages.getString('FeedbackScreenRow') + ': ' + mainJobStatus.row + ' / ' + mainJobStatus.totalRows);
//Set progress bar %
progressBar.set({value: mainJobStatus.progress});
},
_hideDialogAndPane: function(dlg) {
if(dlg) {
dlg.hide();
}
if(this._updateReportTimeout >= 0) {
clearTimeout(this._updateReportTimeout);
this._updateReportTimeout = -1;
}
this._forceHideGlassPane();
this._updateParametersDisabledState(false);
},
_submitReportEnded: function(isTimeout) {
// Clear submit-related control flags
delete this.reportPrompt._isSubmitPromptPhaseActivated;
delete this.reportPrompt._isUpdatingPrompting;
// Awaiting for update report response?
if(this._updateReportTimeout >= 0) {
clearTimeout(this._updateReportTimeout);
this._updateReportTimeout = -1;
if(isTimeout) {
// This happens, specifically, when the user selects a downloadable output format.
// #_onReportContentLoaded callback might not have been called.
this.view._showReportContent(false, /*preserveSource*/true);
}
}
// PRD-3962 - show glass pane on submit, hide when iframe is loaded
// Hide glass-pane, if it is visible
if(!this.reportPrompt._isAsync) {
this._updateParametersDisabledState(false);
this.reportPrompt.hideGlassPane();
}
},
_onReportContentLoaded: function() {
var hadChildViewer = this._isParentViewer;
this._detectLoadedContent();
var view = this.view;
if(!this._updatedIFrameSrc) {
if(!view._hasReportContent()) {
logger && logger.log("Empty IFrame loaded.");
} else {
// A link from within the loaded report
// caused loading something else.
// It may be a child report viewer.
if(this._isParentViewer && !hadChildViewer) {
// A child viewer forces changing to non-styled
view.setPageStyled(false);
view.resize();
} else {
logger && logger.log("Unrequested IFrame load.");
}
}
} else {
this._updatedIFrameSrc = false;
var loadCallback = this._submitLoadCallback;
if(loadCallback && view._hasReportContent()) {
delete this._submitLoadCallback;
loadCallback.call(this);
} else {
view.resize();
}
}
},
_detectLoadedContent: function() {
// TODO: Should include HTML test here as well?
var isParentViewer = false;
try {
var contentWin = dom.byId('reportContent').contentWindow;
if(contentWin) {
if(contentWin._isReportViewer) {
isParentViewer = true;
}
else {
// For testing in IPads or other clients,
// remove hardcoded localhost link urls.
$(contentWin.document)
.find('body area').each(function() {
this.href = this.href.replace("http://localhost:8080", "");
});
}
}
} catch(e) {
// Permission denied
logger && logger.log("ERROR" + String(e));
}
this._isParentViewer = isParentViewer;
$('body')
[ isParentViewer ? 'addClass' : 'removeClass']('parentViewer')
[!isParentViewer ? 'addClass' : 'removeClass']('leafViewer' );
},
_buildReportContentOptions: function() {
var options = this.reportPrompt._buildReportContentOptions('REPORT');
// SimpleReportingComponent expects name to be set
if (options['name'] === undefined) {
options['name'] = options['action'];
}
return options;
},
_buildReportContentUrl: function(options) {
var url = window.location.href.split('?')[0];
url = url.substring(0, url.lastIndexOf("/")) + "/report?";
var params = [];
var addParam = function(encodedKey, value) {
if(typeof value !== 'undefined') {
params.push(encodedKey + '=' + encodeURIComponent(value));
}
};
$.each(options, function(key, value) {
if (value == null) { return; } // continue
var encodedKey = encodeURIComponent(key);
if ($.isArray(value)) {
$.each(value, function(i, v) { addParam(encodedKey, v); });
} else {
addParam(encodedKey, value);
}
});
return url + params.join("&");
},
_updateParametersDisabledState: function(disable) {
var testElements = document.getElementsByClassName('parameter');
for(var i=0; i<testElements.length; i++) {
if(testElements[i].getElementsByTagName('select').length > 0) {
testElements[i].getElementsByTagName('select')[0].disabled = disable;
} else if(testElements[i].getElementsByTagName('input').length > 0) {
for(var j=0; j<testElements[i].getElementsByTagName('input').length; j++) {
testElements[i].getElementsByTagName('input')[0].disabled = disable;
}
} else if(testElements[i].getElementsByTagName('button').length > 0) {
for(var j=0; j<testElements[i].getElementsByTagName('button').length; j++) {
testElements[i].getElementsByTagName('button')[j].disabled = disable;
}
}
}
},
_isDownloadableFormat: function (mime) {
var mimes = ["application/rtf", "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "text/csv", "mime-message/text/html"];
return mimes.indexOf(mime) > -1;
}
}); // end of: var v = {
// Replace default prompt load
reportPrompt.load = v.load.bind(v);
return v;
};
});
| package-res/reportviewer/reportviewer.js | /*!
* This program 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.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* Copyright (c) 2002-2016 Pentaho Corporation.. All rights reserved.
*/
define([ 'common-ui/util/util', 'common-ui/util/timeutil', 'common-ui/util/formatting', 'pentaho/common/Messages', "dojo/dom", "dojo/on", "dojo/_base/lang",
"dijit/registry", "dojo/has", "dojo/sniff", "dojo/dom-class", 'pentaho/reportviewer/ReportDialog', "dojo/dom-style", "dojo/query", "dojo/dom-geometry", "dojo/parser", "dojo/window", "dojo/_base/window", 'cdf/lib/jquery', 'amd!cdf/lib/jquery.ui', "common-repo/pentaho-ajax", "dijit/ProgressBar", "common-data/xhr"],
function(util, _timeutil, _formatting, _Messages, dom, on, lang, registry, has, sniff, domClass, ReportDialog, domStyle, query, geometry, parser, win, win2, $) {
return function(reportPrompt) {
if (!reportPrompt) {
alert("report prompt is required");
return;
}
/**
* ReportViewer Prompt instance
*
* @private
*/
var _reportPrompt = reportPrompt;
var v = logged({
/**
* Gets the ReportViewer Prompt object instance
*
* @returns {*}
* @readonly
*/
get reportPrompt () {
return _reportPrompt;
},
_currentReportStatus: null,
_currentReportUuid: null,
_currentStoredPagesCount: null,
_cachedReportCanceled: null,
_requestedPage: 0,
_previousPage: 0,
_reportUrl : null,
_handlerRegistration : null,
_locationPromptCancelHandlerRegistration: null,
_locationPromptOkHandlerRegistration: null,
_locationPromptFinishHandlerRegistration: null,
_locationPromptAttachHandlerRegistration: null,
_locationPromptFinished: null,
_locationOutputPath: null,
_manuallyScheduled: null,
_scheduleScreenBtnCallbacks: null,
_editModeToggledHandler: null,
_isFinished : false,
_bindPromptEvents: function() {
var baseShowGlassPane = this.reportPrompt.showGlassPane.bind(this.reportPrompt);
var baseHideGlassPane = this.reportPrompt.hideGlassPane.bind(this.reportPrompt);
this.reportPrompt.api.event.ready(this.view.promptReady.bind(this.view));
this.reportPrompt.showGlassPane = this.view.showGlassPane.bind(this.view, baseShowGlassPane);
this.reportPrompt.hideGlassPane = this.view.hideGlassPane.bind(this.view, baseHideGlassPane);
this.reportPrompt.api.event.submit(this.submitReport.bind(this));
this.reportPrompt.api.event.beforeUpdate(this.beforeUpdateCallback.bind(this));
this.reportPrompt.api.event.afterUpdate(this.afterUpdateCallback.bind(this));
this.reportPrompt.api.event.afterRender(this.view.afterRender.bind(this.view));
if (typeof parent.pho !== 'undefined' && typeof parent.pho.dashboards !== 'undefined') {
this._editModeToggledHandler = this.editModeToggledHandler.bind(this);
parent.pho.dashboards.addEditContentToggledListener(this._editModeToggledHandler);
}
},
load: function() {
_Messages.addUrlBundle('reportviewer', CONTEXT_PATH+'i18n?plugin=reporting&name=reportviewer/messages/messages');
this.view.localize();
this.createRequiredHooks();
this.view.updatePageBackground();
// Prevent blinking text cursors
// This only needs to be done once.
// Moreover, setting these properties causes browser re-layout (because of setting the style?),
// so the sooner the better.
function noUserSelect(g) {
g.setAttribute("style", "-webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none;");
// IE 9 / 8
if (typeof g.onselectstart !== 'undefined') {
g.setAttribute('unselectable', 'on');
g.onselectstart = function() { return false; };
}
}
noUserSelect(dom.byId('reportArea'));
noUserSelect(dom.byId('reportPageOutline'));
noUserSelect(dom.byId('reportContent'));
// ------------
on(registry.byId('toolbar-parameterToggle'), "click", lang.hitch( this, function() {
this.view.togglePromptPanel();
}));
on($('#notification-close'), "click", lang.hitch( this, function() {
domClass.add('notification-screen', 'hidden');
}));
var clearCache = registry.byId('toolbar-clearCache');
if(clearCache) {
on(clearCache, "click", lang.hitch(this, function () {
this.clearReportCache(this.submitReport.bind(this));
}));
}
if(window.top.mantle_addHandler){
//When slow connection there is a gap between tab glass pane and prompt glass pane
//So, let's hide tab glass pane only after widget is attached
var onAttach = function(event){
if(event.eventSubType == 'locationPromptAttached'){
this._forceHideGlassPane();
}
};
this._locationPromptAttachHandlerRegistration = window.top.mantle_addHandler('GenericEvent', onAttach.bind(this) );
}
window.onbeforeunload = function(e) {
this.cancel(this._currentReportStatus, this._currentReportUuid);
if(window.top.mantle_removeHandler) {
if(this._handlerRegistration) {
window.top.mantle_removeHandler(this._handlerRegistration);
}
if(this._locationPromptAttachHandlerRegistration) {
window.top.mantle_removeHandler(this._locationPromptAttachHandlerRegistration);
}
if(this._locationPromptCancelHandlerRegistration) {
window.top.mantle_removeHandler(this._locationPromptCancelHandlerRegistration);
}
if(this._locationPromptOkHandlerRegistration) {
window.top.mantle_removeHandler(this._locationPromptOkHandlerRegistration);
}
if(this._locationPromptFinishHandlerRegistration) {
window.top.mantle_removeHandler(this._locationPromptFinishHandlerRegistration);
}
}
return;
}.bind(this);
$("#reportContent")[0].contentWindow.onbeforeunload = function(e) {
if($("#reportContent")[0].contentWindow._isFirstIframeUrlSet == true) {
//user clicking a link in the report
this.cancel(this._currentReportStatus, this._currentReportUuid);
if(window.top.mantle_removeHandler) {
window.top.mantle_removeHandler(this._handlerRegistration);
}
} else {
//content is writing in the reportContent iframe first time
$("#reportContent")[0].contentWindow._isFirstIframeUrlSet = true;
}
return;
}.bind(this);
var boundOnReportContentLoaded = this._onReportContentLoaded.bind(this);
// Schedule the resize after the document has been rendered and CSS applied
var onFrameLoaded = logged('onFrameLoaded', function() {
setTimeout(boundOnReportContentLoaded);
});
if(has("ie")){
// When a file is downloaded, the "complete" readyState does not occur: "loading", "interactive", and stops.
on(dom.byId('reportContent'), "readystatechange", function() {
if(this.readyState === 'complete') { onFrameLoaded(); }
});
} else {
on(dom.byId('reportContent'), "load", lang.hitch( onFrameLoaded));
}
$('body')
.addClass(_isTopReportViewer ? 'topViewer leafViewer' : 'leafViewer')
.addClass(inMobile ? 'mobile' : 'nonMobile');
logger && $('body').addClass('debug');
this._bindPromptEvents();
this.reportPrompt.createPromptPanel();
var rowLimitControl = registry.byId('rowLimitControl');
rowLimitControl.bindChange(dojo.hitch(this, this._initRowLimitCallback));
rowLimitControl.bindGetMessage(function () {
return registry.byId('rowLimitMessage');
});
rowLimitControl.bindGetDialog(function () {
return registry.byId('rowLimitExceededDialog');
});
rowLimitControl.bindShowGlassPane(dojo.hitch(this, this._forceShowGlassPane));
rowLimitControl.bindHideGlassPane(dojo.hitch(this, function(){
this._forceHideGlassPane();
}));
var rowLimitMessage = registry.byId('rowLimitMessage');
rowLimitMessage.bindRun(function () {
var match = window.location.href.match('.*repos\/(.*)(\.prpt).*');
if (match && match.length > 1) {
window.parent.executeCommand("RunInBackgroundCommand", {
solutionPath: decodeURIComponent(match[1] + match[2]).replace(/:/g, '/')
});
}
});
rowLimitMessage.bindSchedule(function () {
var match = window.location.href.match('.*repos\/(.*)(\.prpt).*');
if (match && match.length > 1) {
window.parent.mantle_openRepositoryFile(decodeURIComponent(match[1] + match[2]).replace(/:/g, '/'), "SCHEDULE_NEW");
}
});
},
view: logged({
/**
* Gets the ReportViewer Prompt object instance
*
* @returns {*}
* @readonly
*/
get reportPrompt () {
return _reportPrompt;
},
/**
* Localize the Report Viewer.
*/
localize: function() {
$('#toolbar-parameterToggle').attr('title', _Messages.getString('parameterToolbarItem_title'));
registry.byId('pageControl').registerLocalizationLookup(_Messages.getString);
registry.byId('rowLimitControl').registerLocalizationLookup(_Messages.getString);
registry.byId('rowLimitExceededDialog').registerLocalizationLookup(_Messages.getString);
registry.byId('rowLimitMessage').registerLocalizationLookup(_Messages.getString);
},
/**
* Update the page background when we're not in PUC or we're embedded in an
* iframe to make sure the translucent styling has some contrast.
*/
updatePageBackground: function() {
// If we're not in PUC or we're in an iframe
var inPuc;
try {
inPuc = window.top.mantle_initialized;
} catch (e) { // Ignore "Same-origin policy" violation in embedded IFrame
inPuc = false;
}
var inIFrame = top !== self;
// if we are not in PUC
if(!inSchedulerDialog && !inMobile && (!inPuc || inIFrame)) {
domClass.add(document.body, 'pentaho-page-background');
}
},
_showReportContent: function(visible, preserveSource) {
// Force not to show a blank iframe
var hasContent = this._hasReportContent();
if(!hasContent) { visible = false; }
if(this._isReportContentVisible() !== !!visible) {
// Don't touch "data-src" of an already blank iframe, or onload occurs needlessly...
if (!visible && !preserveSource && hasContent) {
logger && logger.log("Will clear content iframe.data-src");
//submit hidden form to POST data to iframe
$('#hiddenReportContentForm').attr("action", 'about:blank');
$('#hiddenReportContentForm').submit();
//set data attribute so that we know what url is currently displayed in
//the iframe without actually triggering a GET
$('#reportContent').attr("data-src", 'about:blank');
this._updatedIFrameSrc = true;
}
$('body')[visible ? 'removeClass' : 'addClass']('contentHidden');
}
},
_calcReportContentVisibility: function() {
var visible =
// Anything in the iframe to show? (PRD-4271)
this._hasReportContent() &&
// Valid data (although report content should be blank here)
!(this.reportPrompt._getStateProperty('promptNeeded')) &&
// Hide the report area when in the "New Schedule" dialog
!inSchedulerDialog &&
(this._isAutoSubmitAllowed() || this.reportPrompt._isSubmitPromptPhaseActivated);
return visible;
},
_isAutoSubmitAllowed : function() {
if(this.reportPrompt._getStateProperty('allowAutoSubmit')) { // (BISERVER-6915)
return true;
}
var iframes = document.getElementsByTagName("IFRAME");
if(iframes.length > 0) {
var src = $(iframes[0]).attr('data-src');
return src != null && src.indexOf('dashboard-mode') !== -1;
}
return false;
},
_isDashboardEditMode : function(){
try {
return window.frameElement.src.indexOf('dashboard-mode') !== -1 && parent.pho.dashboards.editMode;
} catch (e) {
return false;
}
},
_hasReportContent: function() {
var src = $('#reportContent').attr('data-src');
return src !== undefined && src !== 'about:blank';
},
_isReportContentVisible: function() {
return !$('body').hasClass('contentHidden');
},
// Called on page load and every time the prompt panel is refreshed
updateLayout: function() {
if (!this.reportPrompt._getStateProperty('showParameterUI')) {
this._hideToolbarPromptControls();
}
// The following call is important for clearing the report content when autoSubmit=false and the user has changed a value.
if(!this._calcReportContentVisibility() || this.reportPrompt._isAsync) {
this._showReportContent(false);
}
this._layoutInited = false;
this._initLayout();
},
_hideToolbarPromptControls: function() {
// Hide the toolbar elements
// When inMobile, toolbarlinner2 has another structure. See report.html.
if(!inMobile) { domClass.add('toolbar-parameter-separator', 'hidden'); }
// dijit modifies the HTML structure.
// At least in mobile, the button gets wrapped by a frame,
// that needs to be hidden.
var PARAM_TOGGLE = 'toolbar-parameterToggle';
var elem = dom.byId(PARAM_TOGGLE);
while(elem) {
if(elem.getAttribute('widgetid') === PARAM_TOGGLE) {
domClass.add(elem, 'hidden');
break;
}
elem = elem.parentNode;
}
},
showGlassPane: function(base) {
$("#glasspane")
.css("background", v.reportContentUpdating() ? "" : "transparent");
base();
},
hideGlassPane: function(base) {
if(!v.reportContentUpdating()) {
base();
}
// Activate bg.
$("#glasspane").css("background", "");
},
promptReady: function() {
this.reportPrompt.hideGlassPane();
if (inSchedulerDialog) {
// If we are rendering parameters for the "New Schedule" dialog,
// don't show the report or the submit panel, or the pages toolbar
this.showPromptPanel(true);
domClass.add('reportContent', 'hidden');
// SubmitPanel can be absent in DOM
var submitPanel = query('.submit-panel');
if (typeof submitPanel !== 'undefined' && submitPanel.length > 0) {
domClass.add(submitPanel[0], 'hidden');
}
domClass.add('toolbarlinner2', 'hidden');
domClass.remove('promptPanel', 'pentaho-rounded-panel-bottom-lr');
domClass.remove('reportControlPanel', 'pentaho-shadow');
domClass.remove('reportControlPanel', 'pentaho-rounded-panel-bottom-lr');
}
},
afterRender: function() {
if (inSchedulerDialog && typeof window.parameterValidityCallback !== 'undefined') {
var isValid = !this.reportPrompt._getStateProperty('promptNeeded');
window.parameterValidityCallback(isValid);
}
},
/**
* Initializes the report viewer's layout based on the loaded parameter definition.
*/
_initLayout: function() {
if(this._layoutInited) { return; } // reset on every navigation (see #init)
// Is it the first time, or is the parameter UI
// being refreshed due to user interaction (which causes "navigation")?
var navigating = !!this._initedOnce;
this._initedOnce = true;
var showParamUI = this.reportPrompt._getStateProperty('showParameterUI');
this.updatePageControl();
// Hide the toolbar, 'toppanel', when it would be empty and
// un-style the report so it's the only visible element
// when both the pagination controls and the parameter UI are hidden.
var isToolbarEmpty = !this.reportPrompt._getStateProperty("paginate") && !showParamUI && !this.reportPrompt._isReportHtmlPagebleOutputFormat;
domClass[isToolbarEmpty ? 'add' : 'remove']('toppanel', 'hidden');
// Don't mess with the parameters if we're "navigating".
// If the user has explicitly hidden the UI,
// and is going through several pages,
// we should not keep popping the UI again on each page init...
// PRD-4001, PRD-4102
var showOrHide;
// If not available, always respect the definition and hide
if(!showParamUI) {
showOrHide = false;
} else if(!navigating) {
// Shown or hidden by default?
// Don't show parameter panel by default unless prompt needed
showOrHide = (!inMobile && _isTopReportViewer) ||
this.reportPrompt._getStateProperty('promptNeeded') ||
!this.reportPrompt._getStateProperty('allowAutoSubmit');
}
var parameters = util.getUrlParameters();
var toggleParamName = 'toolbar-parameterToggle';
if (parameters[toggleParamName] !== undefined) {
this.showPromptPanel(parameters[toggleParamName] === 'true');
} else if (showOrHide != null) {
this.showPromptPanel(showOrHide);
}
this._layoutInited = true;
},
show: function() {
// Cleans up an issue where sometimes on show the iframe is offset
this.resize();
},
/**
*
* @param pageNumber
* @private
*/
_setAcceptedPage: function(pageNumber) {
this.reportPrompt.api.operation.setParameterValue("accepted-page", pageNumber);
},
/**
*
* @param pageNumber
* @private
*/
_getAcceptedPage: function() {
return this.reportPrompt.api.operation.getParameterValues()["accepted-page"];
},
/**
* @private
*/
_getRegistryObjectById: function(id) {
return registry.byId(id);
},
updatePageControl: function() {
var pc = this._getRegistryObjectById('pageControl');
pc.registerPageNumberChangeCallback(undefined);
if (!this.reportPrompt._getStateProperty("paginate")) {
if(this.reportPrompt._isAsync) {
this._setAcceptedPage('0');
} else {
this._setAcceptedPage('-1');
}
pc.setPageCount(1);
pc.setPageNumber(1);
// pc.disable();
} else {
var total = this.reportPrompt._getStateProperty("totalPages");
var page = this.reportPrompt._getStateProperty("page");
// We can't accept pages out of range. This can happen if we are on a page and then change a parameter value
// resulting in a new report with less pages. When this happens we'll just reduce the accepted page.
page = Math.max(0, Math.min(page, total - 1));
// add our default page, so we can keep this between selections of other parameters, otherwise it will not be on the
// set of params are default back to zero (page 1)
this._setAcceptedPage('' + page);
pc.setPageCount(total);
pc.setPageNumber(page + 1);
}
pc.registerPageNumberChangeCallback(function(pageNumber) {
this.pageChanged(pageNumber);
}.bind(this));
},
pageChanged: function(pageNumber) {
this._setAcceptedPage('' + (pageNumber - 1));
this.reportPrompt.api.operation.submit();
},
togglePromptPanel: function() {
this.showPromptPanel(registry.byId('toolbar-parameterToggle').checked);
this.resize();
},
showPromptPanel: function(visible) {
registry.byId('toolbar-parameterToggle').set('checked', !!visible);
domClass[visible ? 'remove' : 'add']('reportControlPanel', 'hidden');
},
isPageStyled: function() {
return $('body').hasClass('styled');
},
setPageStyled: function(styled) {
// normalize to boolean
styled = !!styled;
// Need to style at least the first time anyway,
// to ensure the HTML and JS are in sync.
if(!this._pageStyledOnce || this.isPageStyled() !== styled) {
this._pageStyledOnce = true;
var setClass = styled ? 'addClass' : 'removeClass';
$('body')
[setClass]('styled')
[styled ? 'removeClass' : 'addClass']('nonStyled');
if(!styled) {
// Clear style values set in JS to let class-imposed styles take effect
$('#reportArea' ).css({height: ""});
$('#reportContent').css({height: "", width: ""});
}
$('#reportPageOutline')[setClass]('pentaho-rounded-panel2-shadowed pentaho-padding-lg pentaho-background');
}
},
onViewportResize: function() {
this.resizeContentArea();
},
// called by #resize and by window.resize -> onViewportResize
resizeContentArea: function(callBefore) {
var vp = win.getBox();
var tp = geometry.getMarginBox('toppanel');
var rcpHeight = geometry.getMarginBox("rowLimitMessage");
var mb = {h: vp.h - tp.h - rcpHeight.h - 2};
logger && logger.log("viewport=(" + vp.w + "," + vp.h + ") " + " toppanel=(" + tp.w + "," + tp.h + ") ");
// Fill all available space
geometry.setMarginBox('reportArea', mb);
if(inMobile && this._isHtmlReport) {
this._resizeMobileHtmlReportHandlesScrolling(mb);
}
},
// In mobile, every report is shown unstyled.
// Mobile HTML reports handle scrolling itself.
// iOS Safari does not respect the iframe's style.overflow or the scrollable attribute
// and desperate measures had to be taken.
_resizeMobileHtmlReportHandlesScrolling: function(mb) {
// TODO: HACK: into the report content's HTML so that it handles scrolling correctly in Safari/iOS
var iframe = $('#reportContent');
var iframeDoc = iframe.contents();
var generator = iframeDoc.find('head>meta[name="generator"]').attr('content') || "";
var isReport = generator.indexOf("Reporting") >= 0;
if(isReport) {
iframe.attr('scrolling', 'no');
// TODO: HACK: Avoid a slightly clipped footer
var wh = mb.h - 15;
var scrollWrapper = iframeDoc.find('#reportTableDiv');
if(scrollWrapper.length) {
scrollWrapper.css({height: wh, width: (window.innerWidth-10) + 'px', overflow: 'auto'});
} else {
iframeDoc.find("body").css({margin: '2px'});
iframeDoc
.find("body>table")
.wrap('<div id="reportTableDiv" style="height:' + wh + 'px; width:' + (window.innerWidth-10) + 'px; overflow:auto;"/>');
}
}
},
/**
* Adjusts the report content iframe's width and height.
* The result is affected by:
* <ul>
* <li>content existing or not</li>
* <li>being in a mobile environment or not</li>
* <li>the existing content being styled</li>
* <li>the viewport size.</li>
* </ul>
*
* Finally, the {@link #resizeContentArea} method is called,
* that adjusts the report area div,
* responsible by showing up a scrollbar, when necessary.
*/
resize: function() {
if (!this._hasReportContent()) { return; }
// PRD-4000 Hide iframe before resize
// If not visible, let be so.
// If visible, hide it during the operation and show it again at the end.
var isVisible = this._isReportContentVisible();
if(isVisible) { this._showReportContent(false, /*preserveSource*/true); }
if(this.isPageStyled()) { this._pollReportContentSize(); }
this.resizeContentArea();
// PRD-4000 Show iframe after resize
if(isVisible) { this._showReportContent(true); }
},
_pollReportContentSize: function() {
var POLL_SIZE = 10;
var t = dom.byId('reportContent');
// Set the iframe size to minimum before POLLING its contents, to not affect the polled values.
// NOTE: Setting to 0 prevented IE9-Quirks from detecting the correct sizes.
// Setting here, and polling next, causes ONE resize on the iframe.
geometry.setContentSize(t, {w: POLL_SIZE, h: POLL_SIZE});
var outerDoc = document;
// It's surely HTML content, so the following is valid
win2.withDoc(t.contentWindow.document, function() {
setTimeout(function() {
// add overflow hidden to prevent scrollbars on ie9 inside the report
domStyle.set(win2.doc.getElementsByTagName("html")[0], {'overflow': 'hidden'});
var dimensions = geometry.getMarginBox(win2.doc.getElementsByTagName("body")[0]);
// changing width to jquery due to problems with dojo getting the width correcty
// although, dojo is used to get the height due to issues on ie8 and 9
dimensions.w = $('#reportContent').contents().width();
logger && logger.log("Styled page - polled dimensions = (" + dimensions.w + ", " + dimensions.h + ")");
// In case the styled report content is too small, assume 2/3 of the width.
// This may happen when there are no results.
if(dimensions.w <= POLL_SIZE) {
// Most certainly this indicates that the loaded report content
// does not have a fixed width, and, instead, adapts to the imposed size (like width: 100%).
var vp;
win2.withDoc(outerDoc, function() {
vp = win.getBox();
});
dimensions.w = Math.round(2 * vp.w / 3);
logger && logger.log("Width is too small - assuming a default width of " + dimensions.w);
}
geometry.setContentSize(t, {w: dimensions.w, h: dimensions.h});
$('#reportContent').hide().fadeIn('fast');
}, 10);
});
}
}), // end view
onTabCloseEvent: function (event) {
if(window.frameElement.src != null && window.frameElement.src.indexOf('dashboard-mode') !== -1 ){
if (event.eventSubType == 'tabClosing' && event.stringParam == window.parent.frameElement.id) {
this.cancel(this._currentReportStatus, this._currentReportUuid);
if(window.top.mantle_removeHandler) {
window.top.mantle_removeHandler(this._handlerRegistration);
}
}
}
else {
if (event.eventSubType == 'tabClosing' && event.stringParam == window.frameElement.id) {
this.cancel(this._currentReportStatus, this._currentReportUuid);
if(window.top.mantle_removeHandler) {
window.top.mantle_removeHandler(this._handlerRegistration);
}
}
}
},
cancel: function(status, uuid) {
var url = window.location.href.split('?')[0];
if( uuid && (!status || status == 'WORKING' || status == 'QUEUED' || status == 'CONTENT_AVAILABLE' || status == 'PRE_SCHEDULED') ) {
pentahoGet(url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + uuid + '/cancel', "");
}
},
createRequiredHooks: function() {
// [PIR-543] - Allow new/refreshed reports to re-attach or override instance functions in the top window object
// Top window functions may become orphaned due to content linking refresh or when a report tab in PUC is closed
/*
try {
if (window.reportViewer_openUrlInDialog || top.reportViewer_openUrlInDialog) {
return;
}
} catch(err) {
return; // [PIR-543] - IE 9.0.5 throws a Permission Denied error
}
*/
var isRunningIFrameInSameOrigin = null;
try {
var ignoredCheckCanReachOutToTop = window.top.mantle_initialized;
isRunningIFrameInSameOrigin = true;
} catch (ignoredSameOriginPolicyViolation) {
// IFrame is running embedded in a web page in another domain
isRunningIFrameInSameOrigin = false;
}
if(isRunningIFrameInSameOrigin) {
if (!top.mantle_initialized) {
top.mantle_openTab = function(name, title, url) {
window.open(url, '_blank');
}
}
if (top.mantle_initialized) {
top.reportViewer_openUrlInDialog = function(title, url, width, height) {
top.urlCommand(url, title, true, width, height);
};
} else {
top.reportViewer_openUrlInDialog = this.openUrlInDialog.bind(this);
}
window.reportViewer_openUrlInDialog = top.reportViewer_openUrlInDialog;
}
window.reportViewer_hide = this.hide.bind(this);
if(window.location.href.indexOf("/parameterUi") == -1 && window.top.mantle_addHandler) {
// only in case when report is opened in tab('/viewer')
this._handlerRegistration = window.top.mantle_addHandler("GenericEvent", this.onTabCloseEvent.bind(this));
}
var localThis = this;
if (isRunningIFrameInSameOrigin && typeof window.top.addGlassPaneListener !== 'undefined') {
window.top.addGlassPaneListener({
glassPaneHidden: function(){
localThis.view.show();
}
});
}
},
openUrlInDialog: function(title, url, width, height) {
if (this.dialog === undefined) {
this.dialog = new pentaho.reportviewer.ReportDialog();
this.dialog.setLocalizationLookupFunction(_Messages.getString);
}
this.dialog.open(title, url, width, height);
},
/**
* Hide the Report Viewer toolbar.
* TODO: In what world is this a "hide"? empty()?
* Can't find where this is called from!
*/
hide: function() {
$('#toppanel').empty();
this.view.resize();
},
beforeUpdateCallback: function() {
if(this.reportPrompt.api.operation.state().autoSubmit) {
this.reportPrompt._isUpdatingPrompting = true;
}
},
afterUpdateCallback: function() {
this.view.updateLayout();
this._updateReportContent();
},
// Called by SubmitPromptComponent#expression (the submit button's click)
// Also may be called by PromptPanel#init, when there is no submit button (independently of autoSubmit?).
submitReport: function(keyArgs) {
this.reportPrompt._isSubmitPromptPhaseActivated = true;
try {
// If we are rendering parameters for the "New Schedule" dialog,
// don't show the report, the submit panel and pages toolbar.
if (inSchedulerDialog) {
this._submitReportEnded();
return;
}
// Make sure that layout is initialized
this.view._initLayout();
// Don't do anything if we need prompting (hide report content -> clear iframe data-src)
var isValid = !this.reportPrompt._getStateProperty('promptNeeded');
if (!isValid) {
this.view._showReportContent(false);
this._submitReportEnded();
return;
}
if (!this.reportPrompt._getStateProperty("autoSubmit") ) {
if(!this.reportPrompt._isAsync){
this.reportPrompt.mode = 'MANUAL';
this.reportPrompt.api.operation.refreshPrompt();
}else{
this._updateReportContent();
}
} else if (!this.reportPrompt._isUpdatingPrompting ) { // no need updating report content during submit because we have afterUpdate event subscription
this._updateReportContent();
}
} catch(ex) {
this._submitReportEnded();
throw ex;
}
},
clearReportCache: function (callback) {
try {
var url = window.location.href.split('?')[0];
pentahoPost(url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/cache/clear', '', callback, 'text/text');
} catch (e) {
logger && logger.log("Can't clear cache.");
callback();
}
},
_updatedIFrameSrc: false,
_updateReportTimeout: -1,
reportContentUpdating: function() {
return this._updateReportTimeout >= 0;
},
_updateReportContent: function() {
//init row limit UI in any case
var options = this._buildReportContentOptions();
var requestLimit = parseInt(options['query-limit'], 0);
var systemRowLimit = parseInt(options['maximum-query-limit'], 0);
var isQueryLimitControlEnabled = this.reportPrompt._isAsync && options['query-limit-ui-enabled'] == "true";
if (isQueryLimitControlEnabled) {
registry.byId('rowLimitControl').apply(systemRowLimit, requestLimit, false);
domClass.remove(dom.byId("toolbar-parameter-separator-row-limit"), "hidden");
domClass.remove(dom.byId('rowLimitControl'), "hidden");
};
if (this.reportPrompt._isSubmitPromptPhaseActivated || this.reportPrompt._getStateProperty("autoSubmit")) {
this._updateReportContentCore();
}
},
_getFeedbackScreen: function (scheduleScreenBtnCallbacks) {
var dlg = registry.byId('feedbackScreen');
dlg.setTitle(_Messages.getString('ScreenTitle'));
dlg.setText(_Messages.getString('FeedbackScreenActivity'));
dlg.setText2(_Messages.getString('FeedbackScreenPage'));
dlg.setText3(_Messages.getString('FeedbackScreenRow'));
dlg.setCancelText(_Messages.getString('ScreenCancel'));
if(!this.view._isDashboardEditMode()){
dlg.showBackgroundBtn(_Messages.getString('FeedbackScreenBackground'));
}else {
scheduleScreenBtnCallbacks.shift();
dlg.hideBackgroundBtn();
}
dlg.callbacks = scheduleScreenBtnCallbacks;
return dlg;
},
editModeToggledHandler: function (editMode) {
var feedbackScreen = registry.byId('feedbackScreen');
var scheduleScreenBtnCallbacks = _scheduleScreenBtnCallbacks;
var feedbackScreenHideStatuses = 'CANCELED|FINISHED|SCHEDULED|CONTENT_AVAILABLE';
if (feedbackScreen) {
if (editMode) {
feedbackScreen.hide();
feedbackScreen.callbacks = [scheduleScreenBtnCallbacks[1]];
feedbackScreen.hideBackgroundBtn();
if (feedbackScreenHideStatuses.indexOf(this._currentReportStatus) == -1) {
feedbackScreen.show();
}
} else {
feedbackScreen.hide();
feedbackScreen.showBackgroundBtn(_Messages.getString('FeedbackScreenBackground'));
if (feedbackScreenHideStatuses.indexOf(this._currentReportStatus) == -1) {
feedbackScreen.show();
}
feedbackScreen.callbacks = scheduleScreenBtnCallbacks;
}
}
},
_getPageLoadingDialog: function (loadingDialogCallbacks) {
var pageIsloadingDialog = registry.byId('reportGlassPane');
pageIsloadingDialog.setTitle(_Messages.getString('ScreenTitle'));
pageIsloadingDialog.setText(_Messages.getString('LoadingPage'));
pageIsloadingDialog.setButtonText(_Messages.getString('ScreenCancel'));
pageIsloadingDialog.callbacks = loadingDialogCallbacks;
return pageIsloadingDialog;
},
_requestCacheFlush: function (url) {
var urlRequestPage = url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + this._currentReportUuid
+ '/requestPage/' + this._requestedPage;
pentahoGet(urlRequestPage, "");
var loadingDialogCallbacks = [
//Cancel navigation
function reportGlassPaneDone() {
this._requestedPage = this._previousPage;
var pageContr = registry.byId('pageControl');
pageContr.setPageNumber(this._previousPage);
this._cachedReportCanceled = true;
registry.byId('reportGlassPane').hide();
}.bind(this)];
var pageLoadingDialog = this._getPageLoadingDialog(loadingDialogCallbacks);
pageLoadingDialog.show();
},
_hideAsyncScreens: function(){
registry.byId('reportGlassPane').hide();
domClass.add('notification-screen', 'hidden');
},
_submitRowLimitUpdate: function (selectedLimit) {
var me = this;
me.cancel(me._currentReportStatus, me._currentReportUuid);
me._isFinished = true;
me._submitReportEnded(true);
me.reportPrompt.api.operation.setParameterValue("query-limit", selectedLimit);
me._hideDialogAndPane(registry.byId('feedbackScreen'));
if (window.top.mantle_removeHandler) {
window.top.mantle_removeHandler(this._handlerRegistration);
}
me.view.updatePageControl();
setTimeout(function () {
me.submitReport(true);
}, me.reportPrompt._pollingInterval);
},
_initRowLimitCallback: function (selectedLimit) {
this.reportPrompt.api.operation.setParameterValue("query-limit", selectedLimit);
registry.byId('rowLimitControl').bindChange(dojo.hitch(this, this._submitRowLimitUpdate));
},
_updateReportContentCore: function() {
//no report generation in scheduling dialog ever!
if(inSchedulerDialog){
return;
}
var me = this;
// PRD-3962 - remove glass pane after 5 seconds in case iframe onload/onreadystatechange was not detected
me._updateReportTimeout = setTimeout(logged('updateReportTimeout', function() {
//BACKLOG-8070 don't show empty content in async mode
me._submitReportEnded( !me.reportPrompt._isAsync );
}), 5000);
// PRD-3962 - show glass pane on submit, hide when iframe is loaded.
// Must be done AFTER _updateReportTimeout has been set, cause it's used to know
// that the report content is being updated.
me.reportPrompt.showGlassPane();
me._updateParametersDisabledState(true);
var options = me._buildReportContentOptions();
var url = me._buildReportContentUrl(options);
var outputFormat = options['output-target'];
var isHtml = outputFormat.indexOf('html') != -1;
var isProportionalWidth = isHtml && options['htmlProportionalWidth'] == "true";
var isReportAlone = domClass.contains('toppanel', 'hidden');
var isQueryLimitControlEnabled = me.reportPrompt._isAsync && options['query-limit-ui-enabled'] == "true";
var requestLimit = parseInt(options['query-limit'], 0);
var systemRowLimit = parseInt(options['maximum-query-limit'], 0);
var styled = _isTopReportViewer && !isReportAlone &&
isHtml && !isProportionalWidth &&
!inMobile;
// If the new output format causes a pageStyle change,
// and we don't hide the iframe "now",
// Then, when the iframe loads,
// the user may temporarily see the new document
// with the previous page style.
if(me.view.isPageStyled() !== styled) {
logger &&
logger.log("Page style will change to " + (styled ? "" : "non-") +
"styled. Will hide report before iframe update.");
me.view._showReportContent(false, /*preserveSource*/true);
}
//Async report execution
//This flag is switched to false after 1st page is ready - specific for paginated html
var isFirstContAvStatus = true;
//This flags is changed when report is finished and iframe is updated/ conent is downloaded
var isIframeContentSet = false;
//This flag is switched to true after we get total page count and updated page control
var isPageCountUpdated = false;
//Report generation finished ( also includes canceled and failed cases)
me._isFinished = false;
//Hides feedback screen and glasspane
var hideDlgAndPane = this._hideDialogAndPane.bind(me);
//Tells us if report was manually scheduled from the feedback screen
me._manuallyScheduled = false;
//Current requested page - is updated if user navigates after 1st page is shown
me._requestedPage = me.view._getAcceptedPage();
me._locationPromptFinished = false;
me._locationOutputPath = me.reportPrompt._defaultOutputPath;
//We are in async mode
if (me.reportPrompt._isAsync) {
/*Async callbacks code START*/
var mainReportGeneration = dojo.hitch(me, function (result) {
var mainJobStatus = me._getAsyncJobStatus(result, hideDlgAndPane);
if (mainJobStatus && mainJobStatus.status != null) {
if (isQueryLimitControlEnabled) {
registry.byId('rowLimitControl').apply(systemRowLimit, requestLimit, mainJobStatus.isQueryLimitReached);
}
me._updateFeedbackScreen(mainJobStatus, feedbackDialog);
//Configure callback for first page
var firtsPageReadyCallback = dojo.hitch(me, function (result2) {
if (!me.reportPrompt._isReportHtmlPagebleOutputFormat) {
logger && logger.log("ERROR: " + "You are in 1st page callback not for paginated HTML. Something went wrong.");
return;
}
firstPageJobStatus = JSON.parse(result2);
switch (firstPageJobStatus.status) {
case "QUEUED":
case "WORKING":
me._keepPolling(firstPageJobStatus.uuid, url, firtsPageReadyCallback);
break;
case "FINISHED" :
me._isFinished = true;
me._hideAsyncScreens();
//Let's get first page
me._getContent(firstPageJobStatus.uuid, url, function () {
isIframeContentSet = true;
});
me._previousPage = firstPageJobStatus.page;
hideDlgAndPane(registry.byId('feedbackScreen'));
//Show loading screen
$('#notification-message').html(_Messages.getString('LoadingPage'));
$('#notification-screen').css("z-index", 100);
if (me._currentReportStatus == 'CONTENT_AVAILABLE') {
domClass.remove('notification-screen', 'hidden');
}
break;
}
});
switch (mainJobStatus.status) {
case "CONTENT_AVAILABLE":
if (isFirstContAvStatus) {
me._hideAsyncScreens();
isFirstContAvStatus = false;
//1st page is ready - need to spawn another job to get it
if (me._currentStoredPagesCount > me._requestedPage) {
//Prevent double content update on 1st page
me._requestedPage = -1;
pentahoPost('reportjob', url.substring(url.lastIndexOf("/report?") + "/report?".length, url.length), firtsPageReadyCallback, 'text/text');
}
me._keepPolling(mainJobStatus.uuid, url, mainReportGeneration);
} else {
if ((me._cachedReportCanceled && me._requestedPage == 0) || ((me._requestedPage >= 0) && (me._currentStoredPagesCount > me._requestedPage))) {
//adjust accepted page in url
var newUrl = url.substring(url.lastIndexOf("/report?") + "/report?".length, url.length);
newUrl = newUrl.replace(/(accepted-page=)\d*?(&)/, '$1' + me._requestedPage + '$2');
//BACKLOG-9814 distinguish initial 1st page from going back to the 1st page
me._requestedPage = -1;
me._cachedReportCanceled = false;
pentahoPost('reportjob', newUrl, firtsPageReadyCallback, 'text/text');
registry.byId('reportGlassPane').hide();
}
//update page number
if (me.reportPrompt._isReportHtmlPagebleOutputFormat && !isPageCountUpdated) {
var pageContr = registry.byId('pageControl');
pageContr.setPageCount(mainJobStatus.totalPages);
isPageCountUpdated = true;
}
$('#notification-message').html(_Messages.getString('LoadingPage') + " " + mainJobStatus.page + " " + _Messages.getString('Of') + " " + mainJobStatus.totalPages);
registry.byId('reportGlassPane').setText(_Messages.getString('LoadingPage') + " " + mainJobStatus.page + " " + _Messages.getString('Of') + " " + mainJobStatus.totalPages);
me._keepPolling(mainJobStatus.uuid, url, mainReportGeneration);
}
break;
//note - no break here - w e need to poll
case "QUEUED":
case "WORKING":
me._hideAsyncScreens();
me._keepPolling(mainJobStatus.uuid, url, mainReportGeneration);
break;
case "FINISHED":
me._isFinished = true;
hideDlgAndPane(registry.byId('feedbackScreen'));
me._hideAsyncScreens();
//Show report
if (!isIframeContentSet) {
me._getContent(mainJobStatus.uuid, url, function () {
isIframeContentSet = true;
});
//Callback for downloadable types because they don't have iframe callback
if (me._isDownloadableFormat(mainJobStatus.mimeType)) {
setTimeout(function () {
me._submitReportEnded(true);
}, me.reportPrompt._pollingInterval);
}
}
if (me._requestedPage > 0) {
// main request finished before requested page was stored in cache but wee still need to show valif page
var newUrl = url.substring(url.lastIndexOf("/report?") + "/report?".length, url.length);
var match = newUrl.match(/(^.*accepted-page=)(\d*?)(&.*$)/);
//if not handled by another job
if (match[2] != me._requestedPage) {
newUrl = match[1] + me._requestedPage + match[3];
me._requestedPage = 0;
pentahoPost('reportjob', newUrl, firtsPageReadyCallback, 'text/text');
}
}
//Set total number of pages for paginated HTML
if (me.reportPrompt._isReportHtmlPagebleOutputFormat && !isPageCountUpdated) {
var pageContr = registry.byId('pageControl');
pageContr.setPageCount(mainJobStatus.totalPages);
isPageCountUpdated = true;
}
break;
case "FAILED":
me._isFinished = true;
me._submitReportEnded();
//Hide dialogs and show error
var errorMsg = _Messages.getString('DefaultErrorMessage');
if (mainJobStatus.errorMessage != null) {
errorMsg = mainJobStatus.errorMessage;
}
me.reportPrompt.showMessageBox(
errorMsg,
_Messages.getString('ErrorPromptTitle'));
registry.byId('feedbackScreen').hide();
me._hideAsyncScreens();
me._updateParametersDisabledState(false);
logger && logger.log("ERROR: Request status - FAILED");
break;
case "PRE_SCHEDULED":
//Could occur when auto scheduling or manual scheduling + location prompt
if(me._locationPromptFinished){
me._keepPolling(mainJobStatus.uuid, url, mainReportGeneration);
} else if (!me._manuallyScheduled){
me._isFinished = true;
var autoScheduleDlg = registry.byId('scheduleScreen');
autoScheduleDlg.setTitle(_Messages.getString('AutoScheduleTitle'));
autoScheduleDlg.setText(_Messages.getString('AutoScheduleText'));
autoScheduleDlg.setOkBtnText(_Messages.getString('FeedbackScreenBackground'));
autoScheduleDlg.setCancelBtnText(_Messages.getString('ScreenCancel'));
autoScheduleDlg.callbacks = me._getAutoScheduleScreenBtnCallbacks(mainReportGeneration, url);
registry.byId('feedbackScreen').hide();
autoScheduleDlg.show();
}
break;
case "SCHEDULED":
//Scheduling is confirmed, the task is not cancelable anymore
me._isFinished = true;
me._submitReportEnded();
me._hideAsyncScreens();
var successDlg = me._getSuccessSchedulingDlg();
registry.byId('feedbackScreen').hide(); // glasspane is still needed
successDlg.show();
break;
case "CANCELED":
me._submitReportEnded();
me._hideAsyncScreens();
break;
}
}
return mainJobStatus;
});
//Async execution manages this flag in it's own way
me.reportPrompt._isSubmitPromptPhaseActivated = false;
var scheduleScreenBtnCallbacks = me._getScheduleScreenBtnCallbacks(mainReportGeneration, url, hideDlgAndPane);
_scheduleScreenBtnCallbacks = scheduleScreenBtnCallbacks.slice();
var feedbackDialog = me._getFeedbackScreen(scheduleScreenBtnCallbacks);
//Don't show dialog if report is ready faster than threshold
setTimeout(function () {
if (!me._isFinished) {
feedbackDialog.show();
}
}, me.reportPrompt._dialogThreshold);
/*Async callbacks code END*/
//Main report job start and page requests goes below
var reportUrl = url.substring(url.lastIndexOf("/report?") + "/report?".length, url.length);
switch (me._currentReportStatus) {
case 'CONTENT_AVAILABLE':
//This section should only affect paginated HTML after 1st page is recieved
//Check if requested page is already persisted to cache
if (me._currentStoredPagesCount > me._requestedPage) {
//Page available
var current = reportUrl.match(/(^.*accepted-page=)(\d*?)(&.*$)/);
var running = me._reportUrl.match(/(^.*accepted-page=)(\d*?)(&.*$)/);
if (current && running && current[1] != running[1]) {
//Actually user changed not the page but prompts/output target - we need a new job to get it
me._reportUrl = reportUrl;
me.cancel(me._currentReportStatus, me._currentReportUuid);
pentahoPost('reportjob', reportUrl, mainReportGeneration, 'text/text');
me._hideAsyncScreens();
} else {
//Page navigation occurred - callbacks will do the job
me._isFinished = true;
}
} else {
//Need to request cache flush
me._requestCacheFlush(url);
me._isFinished = true;
}
break;
default:
me._hideAsyncScreens();
//Not started or finished
this._reportUrl = reportUrl;
var isValid = !me.reportPrompt._getStateProperty('promptNeeded');
if (isValid) {
pentahoPost(url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/reserveId', "", function (data) {
try {
me._currentReportUuid = JSON.parse(data).reservedId;
// backlog-10041 do not send GET request with overloaded parameters passed via url
pentahoPost('reportjob', reportUrl + "&reservedId=" + me._currentReportUuid, mainReportGeneration, 'text/text');
} catch (e) {
logger && logger.log("Can't reserve id");
pentahoPost('reportjob', reportUrl, mainReportGeneration, 'text/text');
}
});
} else {
me._isFinished = true;
hideDlgAndPane();
}
break;
}
} else {
me._hideAsyncScreens();
logger && logger.log("Will set iframe url to " + url.substr(0, 50) + "... ");
//submit hidden form to POST data to iframe
$('#hiddenReportContentForm').attr("action", url);
$('#hiddenReportContentForm').submit();
//set data attribute so that we know what url is currently displayed in
//the iframe without actually triggering a GET
$('#reportContent').attr("data-src", url);
me._updatedIFrameSrc = true;
}
// Continue when iframe is loaded (called by #_onReportContentLoaded)
me._submitLoadCallback = logged('_submitLoadCallback', function() {
me._isHtmlReport = me.view._isHtmlReport = isHtml;
me._outputFormat = outputFormat;
var visible = me.view._calcReportContentVisibility();
if(visible) {
// A child viewer forces changing to non-styled
me.view.setPageStyled(styled && !me._isParentViewer);
me.view.resize();
}
me.view._showReportContent(visible);
me._submitReportEnded();
});
},
_buildParameter: function (pathArray, id) {
var path;
for (var i = 0; i < pathArray.length; i++) {
if (pathArray[i].indexOf(".prpt") !== -1) {
path = decodeURIComponent(pathArray[i]).replace(/:/g, "/");
}
}
return {
solutionPath: (path == null ? "/" : path ),
jobId: id,
recalculateFinished: true == this.reportPrompt._isReportHtmlPagebleOutputFormat
};
},
_getSuccessSchedulingDlg: function () {
var me = this;
var successDlg = registry.byId('successScheduleScreen');
successDlg.setTitle(_Messages.getString('SuccessScheduleTitle'));
successDlg.setText(_Messages.getString('SuccessScheduleText', '<b><i>' + me._locationOutputPath +'</i></b>'));
successDlg.setOkBtnText(_Messages.getString('OK'));
var successScheduleDialogCallbacks = [
function hide() {
me._updateParametersDisabledState(false);
me._forceHideGlassPane();
successDlg.hide();
}.bind(me)
];
successDlg.callbacks = successScheduleDialogCallbacks;
return successDlg;
},
_forceHideGlassPane: function (){
$("#glasspane").css("background", "transparent");
$("#glasspane").css("display", "none");
},
_forceShowGlassPane: function (){
$("#glasspane").css("background", "");
$("#glasspane").css("display", "block");
},
_onLocationPromptCancel : function (mainReportGeneration, url) {
var me = this;
return function (event) {
if (event.eventSubType == 'locationPromptCanceled') {
me._locationPromptFinished = true;
//Show glass pane and feedback screen
me._forceShowGlassPane();
registry.byId('feedbackScreen').show();
var specialCaseProxy = dojo.hitch(me, function (result) {
if (me.reportPrompt._isReportHtmlPagebleOutputFormat) {
var mainJobStatus;
try {
/*If pre scheduled paginated HTML report is finished it will contain all the pages
but we need only one. So we spawn a new job and get results from cache.
*/
mainJobStatus = JSON.parse(result);
if (mainJobStatus.status == 'FINISHED') {
pentahoPost('reportjob', me._reportUrl, mainReportGeneration, 'text/text');
} else {
mainReportGeneration(result);
}
} catch (e) {
mainReportGeneration(result);
}
} else {
mainReportGeneration(result);
}
});
//Keep polling
setTimeout(function () {
pentahoGet(url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + me._currentReportUuid + '/status', "", specialCaseProxy);
}, me.reportPrompt._pollingInterval);
me._removeLocationPromptHandlers();
}
};
},
_onLocationPromptOk : function (mainReportGeneration, url) {
var me = this;
return function (event) {
if (event.eventSubType == 'locationPromptOk') {
try {
me._locationOutputPath = event.stringParam;
} catch (e) {
logger && logger.log("ERROR" + String(e));
}
me._locationPromptFinished = true;
me._forceShowGlassPane();
var waitForScheduled = dojo.hitch(me, function (result) {
try {
mainJobStatus = JSON.parse(result);
if (mainJobStatus.status == 'SCHEDULED' || mainJobStatus.status == 'FAILED') {
mainReportGeneration(result);
} else {
setTimeout(function () {
pentahoGet(url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + me._currentReportUuid + '/status', "", waitForScheduled);
}, me.reportPrompt._pollingInterval);
}
} catch (e) {
mainReportGeneration(result);
}
});
//Keep polling
setTimeout(function () {
pentahoGet(url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + me._currentReportUuid + '/status', "", waitForScheduled);
}, me.reportPrompt._pollingInterval);
me._removeLocationPromptHandlers();
}
};
},
_onLocationPromptFinish : function(){
var me = this;
return function (event) {
if (event.eventSubType == 'locationPromptFinish') {
me._currentReportUuid = event.stringParam;
if (window.top.mantle_removeHandler) {
if (me._locationPromptFinishHandlerRegistration) {
window.top.mantle_removeHandler(me._locationPromptFinishHandlerRegistration);
}
}
}
};
},
_onLocationPromptCancelAuto : function() {
var me = this;
return function (event) {
if (event.eventSubType == 'locationPromptCanceled') {
me._updateParametersDisabledState(false);
me._forceHideGlassPane();
me.cancel(me._currentReportStatus, me._currentReportUuid);
me._removeLocationPromptHandlers();
}
};
},
_onLocationPromptOkAuto : function(mainReportGeneration, url) {
var me = this;
return function (event) {
if (event.eventSubType == 'locationPromptOk') {
me._locationOutputPath = event.stringParam;
me._locationPromptFinished = true;
me._forceShowGlassPane();
var waitForScheduled = dojo.hitch(me, function (result) {
try {
mainJobStatus = JSON.parse(result);
if (mainJobStatus.status == 'SCHEDULED' || mainJobStatus.status == 'FAILED') {
mainReportGeneration(result);
} else {
setTimeout(function () {
pentahoGet(url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + me._currentReportUuid + '/status', "", waitForScheduled);
}, me.reportPrompt._pollingInterval);
}
} catch (e) {
mainReportGeneration(result);
}
});
setTimeout(function () {
pentahoGet(url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + me._currentReportUuid + '/status', "", waitForScheduled);
}, me.reportPrompt._pollingInterval);
me._removeLocationPromptHandlers();
}
};
},
_removeLocationPromptHandlers: function(){
if (window.top.mantle_removeHandler) {
if(this._locationPromptCancelHandlerRegistration) {
window.top.mantle_removeHandler(this._locationPromptCancelHandlerRegistration);
}
if(this._locationPromptOkHandlerRegistration) {
window.top.mantle_removeHandler(this._locationPromptOkHandlerRegistration);
}
}
},
_getScheduleScreenBtnCallbacks : function (mainReportGeneration, url, hideDlgAndPane) {
var me = this;
return [
//Schedule button callback
function scheduleReport() {
var urlSchedule = url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + me._currentReportUuid + '/schedule';
pentahoGet(urlSchedule, "confirm=" + !me.reportPrompt._promptForLocation);
me._manuallyScheduled = true;
registry.byId('feedbackScreen').hide();
if (me.reportPrompt._promptForLocation) {
if(window.top.mantle_addHandler) {
me._locationPromptCancelHandlerRegistration = window.top.mantle_addHandler("GenericEvent",
this._onLocationPromptCancel(mainReportGeneration, url).bind(this) );
me._locationPromptOkHandlerRegistration = window.top.mantle_addHandler("GenericEvent", this._onLocationPromptOk(mainReportGeneration, url).bind(this) );
me._locationPromptFinishHandlerRegistration = window.top.mantle_addHandler("GenericEvent", this._onLocationPromptFinish().bind(this));
}
//Open location prompt
me._locationPromptFinished = false;
window.top.executeCommand("AdhocRunInBackgroundCommand", me._buildParameter(pathArray, me._currentReportUuid));
}
}.bind(me),
//Cancel report
function feedbackscreenDone() {
me.cancel(me._currentReportStatus, me._currentReportUuid);
hideDlgAndPane(registry.byId('feedbackScreen'));
}.bind(me)
]
},
_getAutoScheduleScreenBtnCallbacks : function (mainReportGeneration, url){
var me = this;
var autoScheduleDialogCallbacks;
var autoScheduleDlg = registry.byId('scheduleScreen');
if(me.reportPrompt._promptForLocation) {
autoScheduleDialogCallbacks = [
function openPrompt() {
autoScheduleDlg.hide();
if(window.top.mantle_addHandler) {
me._locationPromptCancelHandlerRegistration = window.top.mantle_addHandler("GenericEvent", this._onLocationPromptCancelAuto().bind(this) );
me._locationPromptOkHandlerRegistration = window.top.mantle_addHandler("GenericEvent", this._onLocationPromptOkAuto(mainReportGeneration, url).bind(this) );
me._locationPromptFinishHandlerRegistration = window.top.mantle_addHandler("GenericEvent", this._onLocationPromptFinish().bind(this));
}
//Open location prompt
me._locationPromptFinished = false;
window.top.executeCommand("AdhocRunInBackgroundCommand", me._buildParameter(pathArray, me._currentReportUuid));
}.bind(me),
function cancel() {
autoScheduleDlg.hide();
me._updateParametersDisabledState(false);
me._forceHideGlassPane();
me.cancel(me._currentReportStatus, me._currentReportUuid);
}.bind(me)
];
}else{
autoScheduleDialogCallbacks = [
function confirm() {
autoScheduleDlg.hide();
var urlSchedule = url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + me._currentReportUuid + '/schedule';
pentahoGet(urlSchedule, "confirm=true");
me._locationPromptFinished = true;
me._keepPolling(me._currentReportUuid, url, mainReportGeneration);
}.bind(me),
function cancel() {
autoScheduleDlg.hide();
me._updateParametersDisabledState(false);
me._forceHideGlassPane();
me.cancel(me._currentReportStatus, me._currentReportUuid);
}.bind(me)
];
}
return autoScheduleDialogCallbacks;
},
_keepPolling : function (uuid, url, callback){
var me = this;
setTimeout(function () {
pentahoGet(url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + uuid + '/status', "", callback);
}, me.reportPrompt._pollingInterval);
},
_getContent : function (uuid, url, callback) {
var me = this;
var urlContent = url.substring(0, url.indexOf("/api/repos")) + '/plugin/reporting/api/jobs/' + uuid + '/content';
logger && logger.log("Will set iframe url to " + urlContent.substr(0, 50) + "... ");
$('#hiddenReportContentForm').attr("action", urlContent);
$('#hiddenReportContentForm').submit();
$('#reportContent').attr("data-src", urlContent);
me._updatedIFrameSrc = true;
me.reportPrompt._isSubmitPromptPhaseActivated = true;
if(callback){
callback();
}
},
_getAsyncJobStatus : function(result, hideDlgAndPane){
var me = this;
var mainJobStatus;
try {
mainJobStatus = JSON.parse(result);
return mainJobStatus;
} catch (e) {
var errorMessage = _Messages.getString('DefaultErrorMessage');
this.reportPrompt.showMessageBox(
errorMessage,
_Messages.getString('ErrorPromptTitle'));
hideDlgAndPane(registry.byId('feedbackScreen'));
me._hideAsyncScreens();
logger && logger.log("ERROR" + String(e));
return;
}
},
_updateFeedbackScreen: function (mainJobStatus, feedbackDialog) {
var me = this;
//Update current values
me._currentReportStatus = mainJobStatus.status;
me._currentReportUuid = mainJobStatus.uuid;
me._currentStoredPagesCount = mainJobStatus.generatedPage;
//Update feedback screen ui
if (mainJobStatus.activity != null) {
feedbackDialog.setText(_Messages.getString(mainJobStatus.activity) + '...');
}
feedbackDialog.setText2(_Messages.getString('FeedbackScreenPage') + ': ' + mainJobStatus.page);
feedbackDialog.setText3(_Messages.getString('FeedbackScreenRow') + ': ' + mainJobStatus.row + ' / ' + mainJobStatus.totalRows);
//Set progress bar %
progressBar.set({value: mainJobStatus.progress});
},
_hideDialogAndPane: function(dlg) {
if(dlg) {
dlg.hide();
}
if(this._updateReportTimeout >= 0) {
clearTimeout(this._updateReportTimeout);
this._updateReportTimeout = -1;
}
this._forceHideGlassPane();
this._updateParametersDisabledState(false);
},
_submitReportEnded: function(isTimeout) {
// Clear submit-related control flags
delete this.reportPrompt._isSubmitPromptPhaseActivated;
delete this.reportPrompt._isUpdatingPrompting;
// Awaiting for update report response?
if(this._updateReportTimeout >= 0) {
clearTimeout(this._updateReportTimeout);
this._updateReportTimeout = -1;
if(isTimeout) {
// This happens, specifically, when the user selects a downloadable output format.
// #_onReportContentLoaded callback might not have been called.
this.view._showReportContent(false, /*preserveSource*/true);
}
}
// PRD-3962 - show glass pane on submit, hide when iframe is loaded
// Hide glass-pane, if it is visible
if(!this.reportPrompt._isAsync) {
this._updateParametersDisabledState(false);
this.reportPrompt.hideGlassPane();
}
},
_onReportContentLoaded: function() {
var hadChildViewer = this._isParentViewer;
this._detectLoadedContent();
var view = this.view;
if(!this._updatedIFrameSrc) {
if(!view._hasReportContent()) {
logger && logger.log("Empty IFrame loaded.");
} else {
// A link from within the loaded report
// caused loading something else.
// It may be a child report viewer.
if(this._isParentViewer && !hadChildViewer) {
// A child viewer forces changing to non-styled
view.setPageStyled(false);
view.resize();
} else {
logger && logger.log("Unrequested IFrame load.");
}
}
} else {
this._updatedIFrameSrc = false;
var loadCallback = this._submitLoadCallback;
if(loadCallback && view._hasReportContent()) {
delete this._submitLoadCallback;
loadCallback.call(this);
} else {
view.resize();
}
}
},
_detectLoadedContent: function() {
// TODO: Should include HTML test here as well?
var isParentViewer = false;
try {
var contentWin = dom.byId('reportContent').contentWindow;
if(contentWin) {
if(contentWin._isReportViewer) {
isParentViewer = true;
}
else {
// For testing in IPads or other clients,
// remove hardcoded localhost link urls.
$(contentWin.document)
.find('body area').each(function() {
this.href = this.href.replace("http://localhost:8080", "");
});
}
}
} catch(e) {
// Permission denied
logger && logger.log("ERROR" + String(e));
}
this._isParentViewer = isParentViewer;
$('body')
[ isParentViewer ? 'addClass' : 'removeClass']('parentViewer')
[!isParentViewer ? 'addClass' : 'removeClass']('leafViewer' );
},
_buildReportContentOptions: function() {
var options = this.reportPrompt._buildReportContentOptions('REPORT');
// SimpleReportingComponent expects name to be set
if (options['name'] === undefined) {
options['name'] = options['action'];
}
return options;
},
_buildReportContentUrl: function(options) {
var url = window.location.href.split('?')[0];
url = url.substring(0, url.lastIndexOf("/")) + "/report?";
var params = [];
var addParam = function(encodedKey, value) {
if(typeof value !== 'undefined') {
params.push(encodedKey + '=' + encodeURIComponent(value));
}
};
$.each(options, function(key, value) {
if (value == null) { return; } // continue
var encodedKey = encodeURIComponent(key);
if ($.isArray(value)) {
$.each(value, function(i, v) { addParam(encodedKey, v); });
} else {
addParam(encodedKey, value);
}
});
return url + params.join("&");
},
_updateParametersDisabledState: function(disable) {
var testElements = document.getElementsByClassName('parameter');
for(var i=0; i<testElements.length; i++) {
if(testElements[i].getElementsByTagName('select').length > 0) {
testElements[i].getElementsByTagName('select')[0].disabled = disable;
} else if(testElements[i].getElementsByTagName('input').length > 0) {
for(var j=0; j<testElements[i].getElementsByTagName('input').length; j++) {
testElements[i].getElementsByTagName('input')[0].disabled = disable;
}
} else if(testElements[i].getElementsByTagName('button').length > 0) {
for(var j=0; j<testElements[i].getElementsByTagName('button').length; j++) {
testElements[i].getElementsByTagName('button')[j].disabled = disable;
}
}
}
},
_isDownloadableFormat: function (mime) {
var mimes = ["application/rtf", "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "text/csv", "mime-message/text/html"];
return mimes.indexOf(mime) > -1;
}
}); // end of: var v = {
// Replace default prompt load
reportPrompt.load = v.load.bind(v);
return v;
};
});
| [BACKLOG-11523]-Fix crashes on iPad
| package-res/reportviewer/reportviewer.js | [BACKLOG-11523]-Fix crashes on iPad | <ide><path>ackage-res/reportviewer/reportviewer.js
<ide>
<ide> var rowLimitControl = registry.byId('rowLimitControl');
<ide>
<del> rowLimitControl.bindChange(dojo.hitch(this, this._initRowLimitCallback));
<del> rowLimitControl.bindGetMessage(function () {
<del> return registry.byId('rowLimitMessage');
<del> });
<del> rowLimitControl.bindGetDialog(function () {
<del> return registry.byId('rowLimitExceededDialog');
<del> });
<del> rowLimitControl.bindShowGlassPane(dojo.hitch(this, this._forceShowGlassPane));
<del> rowLimitControl.bindHideGlassPane(dojo.hitch(this, function(){
<del> this._forceHideGlassPane();
<del> }));
<add> if(rowLimitControl) {
<add> rowLimitControl.bindChange(dojo.hitch(this, this._initRowLimitCallback));
<add> rowLimitControl.bindGetMessage(function () {
<add> return registry.byId('rowLimitMessage');
<add> });
<add> rowLimitControl.bindGetDialog(function () {
<add> return registry.byId('rowLimitExceededDialog');
<add> });
<add> rowLimitControl.bindShowGlassPane(dojo.hitch(this, this._forceShowGlassPane));
<add> rowLimitControl.bindHideGlassPane(dojo.hitch(this, function () {
<add> this._forceHideGlassPane();
<add> }));
<add> }
<ide> var rowLimitMessage = registry.byId('rowLimitMessage');
<del> rowLimitMessage.bindRun(function () {
<del> var match = window.location.href.match('.*repos\/(.*)(\.prpt).*');
<del> if (match && match.length > 1) {
<del> window.parent.executeCommand("RunInBackgroundCommand", {
<del> solutionPath: decodeURIComponent(match[1] + match[2]).replace(/:/g, '/')
<del> });
<del> }
<del> });
<del> rowLimitMessage.bindSchedule(function () {
<del> var match = window.location.href.match('.*repos\/(.*)(\.prpt).*');
<del> if (match && match.length > 1) {
<del> window.parent.mantle_openRepositoryFile(decodeURIComponent(match[1] + match[2]).replace(/:/g, '/'), "SCHEDULE_NEW");
<del> }
<del> });
<add> if(rowLimitMessage) {
<add> rowLimitMessage.bindRun(function () {
<add> var match = window.location.href.match('.*repos\/(.*)(\.prpt).*');
<add> if (match && match.length > 1) {
<add> window.parent.executeCommand("RunInBackgroundCommand", {
<add> solutionPath: decodeURIComponent(match[1] + match[2]).replace(/:/g, '/')
<add> });
<add> }
<add> });
<add> rowLimitMessage.bindSchedule(function () {
<add> var match = window.location.href.match('.*repos\/(.*)(\.prpt).*');
<add> if (match && match.length > 1) {
<add> window.parent.mantle_openRepositoryFile(decodeURIComponent(match[1] + match[2]).replace(/:/g, '/'), "SCHEDULE_NEW");
<add> }
<add> });
<add> }
<ide> },
<ide>
<ide> view: logged({
<ide> */
<ide> localize: function() {
<ide> $('#toolbar-parameterToggle').attr('title', _Messages.getString('parameterToolbarItem_title'));
<del> registry.byId('pageControl').registerLocalizationLookup(_Messages.getString);
<del> registry.byId('rowLimitControl').registerLocalizationLookup(_Messages.getString);
<del> registry.byId('rowLimitExceededDialog').registerLocalizationLookup(_Messages.getString);
<del> registry.byId('rowLimitMessage').registerLocalizationLookup(_Messages.getString);
<add> registry.byId('pageControl') && registry.byId('pageControl').registerLocalizationLookup(_Messages.getString);
<add> registry.byId('rowLimitControl') && registry.byId('rowLimitControl').registerLocalizationLookup(_Messages.getString);
<add> registry.byId('rowLimitExceededDialog') && registry.byId('rowLimitExceededDialog').registerLocalizationLookup(_Messages.getString);
<add> registry.byId('rowLimitMessage') && registry.byId('rowLimitMessage').registerLocalizationLookup(_Messages.getString);
<ide> },
<ide>
<ide> /**
<ide> var systemRowLimit = parseInt(options['maximum-query-limit'], 0);
<ide> var isQueryLimitControlEnabled = this.reportPrompt._isAsync && options['query-limit-ui-enabled'] == "true";
<ide> if (isQueryLimitControlEnabled) {
<del> registry.byId('rowLimitControl').apply(systemRowLimit, requestLimit, false);
<del> domClass.remove(dom.byId("toolbar-parameter-separator-row-limit"), "hidden");
<del> domClass.remove(dom.byId('rowLimitControl'), "hidden");
<add> var rowLimitControl = registry.byId('rowLimitControl');
<add> if(rowLimitControl) {
<add> rowLimitControl.apply(systemRowLimit, requestLimit, false);
<add> domClass.remove(dom.byId("toolbar-parameter-separator-row-limit"), "hidden");
<add> domClass.remove(dom.byId('rowLimitControl'), "hidden");
<add> }
<ide> };
<ide> if (this.reportPrompt._isSubmitPromptPhaseActivated || this.reportPrompt._getStateProperty("autoSubmit")) {
<ide> this._updateReportContentCore();
<ide>
<ide> _initRowLimitCallback: function (selectedLimit) {
<ide> this.reportPrompt.api.operation.setParameterValue("query-limit", selectedLimit);
<del> registry.byId('rowLimitControl').bindChange(dojo.hitch(this, this._submitRowLimitUpdate));
<add> registry.byId('rowLimitControl') && registry.byId('rowLimitControl').bindChange(dojo.hitch(this, this._submitRowLimitUpdate));
<ide> },
<ide>
<ide> _updateReportContentCore: function() {
<ide> if (mainJobStatus && mainJobStatus.status != null) {
<ide>
<ide> if (isQueryLimitControlEnabled) {
<del> registry.byId('rowLimitControl').apply(systemRowLimit, requestLimit, mainJobStatus.isQueryLimitReached);
<add> registry.byId('rowLimitControl') && registry.byId('rowLimitControl').apply(systemRowLimit, requestLimit, mainJobStatus.isQueryLimitReached);
<ide> }
<ide>
<ide> me._updateFeedbackScreen(mainJobStatus, feedbackDialog); |
|
Java | apache-2.0 | cea511d36b2dab1fb6ce38a65a78caf70f5d51dc | 0 | esteinberg/plantuml4idea,esteinberg/plantuml4idea,esteinberg/plantuml4idea | package org.plantuml.idea.rendering;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.ui.JBUI;
import net.sourceforge.plantuml.*;
import net.sourceforge.plantuml.core.Diagram;
import net.sourceforge.plantuml.cucadiagram.Display;
import net.sourceforge.plantuml.cucadiagram.DisplayPositionned;
import net.sourceforge.plantuml.error.PSystemError;
import net.sourceforge.plantuml.sequencediagram.Event;
import net.sourceforge.plantuml.sequencediagram.Newpage;
import net.sourceforge.plantuml.sequencediagram.SequenceDiagram;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.plantuml.idea.plantuml.PlantUml;
import org.plantuml.idea.util.Utils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import static org.plantuml.idea.lang.annotator.LanguageDescriptor.IDEA_PARTIAL_RENDER;
public class PlantUmlRendererUtil {
private static final Logger logger = Logger.getInstance(PlantUmlRendererUtil.class);
public static final Pattern NEW_PAGE_PATTERN = Pattern.compile("\\n\\s*@?(?i)(newpage)(\\p{Blank}+[^\\n]+|\\p{Blank}*)(?=\\n)");
private static final PlantUmlPartialRenderer PARTIAL_RENDERER = new PlantUmlPartialRenderer();
private static final PlantUmlNormalRenderer NORMAL_RENDERER = new PlantUmlNormalRenderer();
/**
* Renders source code and saves diagram images to files according to provided naming scheme
* and image format.
*
* @param source source code to be rendered
* @param baseDir base dir to set for "include" functionality
* @param format image format
* @param path path to use with first file
* @param fileNameFormat file naming scheme for further files
* @param pageNumber -1 for all pages
* @throws IOException in case of rendering or saving fails
*/
public static void renderAndSave(String source, @Nullable File baseDir, PlantUml.ImageFormat format, String path, String fileNameFormat, int zoom, int pageNumber)
throws IOException {
NORMAL_RENDERER.renderAndSave(source, baseDir, format, path, fileNameFormat, zoom, pageNumber);
}
/**
* Renders file with support of plantUML include ange paging features, setting base dir and page for plantUML
* to provided values
*/
public static RenderResult render(RenderRequest renderRequest, RenderCacheItem cachedItem) {
File baseDir = renderRequest.getBaseDir();
if (baseDir != null) {
Utils.setPlantUmlDir(baseDir);
}
long start = System.currentTimeMillis();
String source = renderRequest.getSource();
String[] sourceSplit = NEW_PAGE_PATTERN.split(source);
logger.debug("split done ", System.currentTimeMillis() - start, "ms");
boolean partialRender = sourceSplit[0].contains(IDEA_PARTIAL_RENDER);
logger.debug("partialRender ", partialRender);
RenderResult renderResult;
if (partialRender) {
renderResult = PARTIAL_RENDERER.partialRender(renderRequest, cachedItem, start, sourceSplit);
} else {
renderResult = NORMAL_RENDERER.doRender(renderRequest, cachedItem, sourceSplit);
}
return renderResult;
}
public static DiagramInfo zoomDiagram(SourceStringReader reader, int zoom) {
logger.debug("zooming diagram");
int totalPages = 0;
List<BlockUml> blocks = reader.getBlocks();
String fileOrDirname = null;
if (blocks.size() > 1) {
// logger.error("more than 1 block"); //TODO
//happens when the source is incorrectly extracted and contains multiple diagrams
}
for (int i = 0; i < blocks.size(); i++) {
BlockUml block = blocks.get(i);
long start = System.currentTimeMillis();
checkCancel();
Diagram diagram = block.getDiagram();
logger.debug("getDiagram done in ", System.currentTimeMillis() - start, " ms");
start = System.currentTimeMillis();
zoomDiagram(diagram, zoom);
logger.debug("zoom diagram done in ", System.currentTimeMillis() - start, " ms");
fileOrDirname = block.getFileOrDirname();
totalPages = totalPages + diagram.getNbImages();
break;
}
DiagramInfo.Titles titles = getTitles(totalPages, blocks);
return new DiagramInfo(totalPages, titles, fileOrDirname);
}
private static void zoomDiagram(Diagram diagram, int zoom) {
if (diagram instanceof NewpagedDiagram) {
NewpagedDiagram newpagedDiagram = (NewpagedDiagram) diagram;
for (Diagram page : newpagedDiagram.getDiagrams()) {
if (page instanceof AbstractPSystem) {
AbstractPSystem descriptionDiagram = (AbstractPSystem) page;
Scale scale = descriptionDiagram.getScale();
if (scale == null || scale instanceof ScaleSimple || zoom != 100) {
descriptionDiagram.setScale(calculateScale(zoom, scale));
}
}
}
} else if (diagram instanceof AbstractPSystem) { //gantt, salt wireframe - but has no effect
AbstractPSystem d = (AbstractPSystem) diagram;
Scale scale = d.getScale();
if (scale == null || scale instanceof ScaleSimple || zoom != 100) {
d.setScale(calculateScale(zoom, scale));
}
}
}
@NotNull
private static ScaleSimple calculateScale(int zoom, Scale scale) {
return new ScaleSimple(getPlantUmlScale(scale) * getSystemScale() * zoom / 100f);
}
private static double getPlantUmlScale(Scale scale) {
double plantUmlScale = 1.0;
if (scale instanceof ScaleSimple) {
plantUmlScale = scale.getScale(1, 1);
}
return plantUmlScale;
}
private static double getSystemScale() {
try {
return JBUI.ScaleContext.create().getScale(JBUI.ScaleType.SYS_SCALE); //TODO API change 2019/03/05
} catch (Throwable e) {
return 1;
}
}
@NotNull
protected static DiagramInfo.Titles getTitles(int totalPages, List<BlockUml> blocks) {
List<String> titles = new ArrayList<String>(totalPages);
for (BlockUml block : blocks) {
Diagram diagram = block.getDiagram();
if (diagram instanceof SequenceDiagram) {
SequenceDiagram sequenceDiagram = (SequenceDiagram) diagram;
addTitle(titles, sequenceDiagram.getTitle().getDisplay());
List<Event> events = sequenceDiagram.events();
for (Event event : events) {
if (event instanceof Newpage) {
Display title = ((Newpage) event).getTitle();
addTitle(titles, title);
}
}
} else if (diagram instanceof NewpagedDiagram) {
NewpagedDiagram newpagedDiagram = (NewpagedDiagram) diagram;
List<Diagram> diagrams = newpagedDiagram.getDiagrams();
for (Diagram diagram1 : diagrams) {
if (diagram1 instanceof UmlDiagram) {
DisplayPositionned title = ((UmlDiagram) diagram1).getTitle();
addTitle(titles, title.getDisplay());
}
}
} else if (diagram instanceof UmlDiagram) {
DisplayPositionned title = ((UmlDiagram) diagram).getTitle();
addTitle(titles, title.getDisplay());
} else if (diagram instanceof PSystemError) {
DisplayPositionned title = ((PSystemError) diagram).getTitle();
if (title == null) {
titles.add(null);
} else {
addTitle(titles, title.getDisplay());
}
}
break;
}
return new DiagramInfo.Titles(titles);
}
protected static void addTitle(List<String> titles, Display display) {
if (display.size() > 0) {
titles.add(display.toString());
} else {
titles.add(null);
}
}
public static void checkCancel() {
if (Thread.currentThread().isInterrupted()) {
throw new RenderingCancelledException();
}
}
}
| src/org/plantuml/idea/rendering/PlantUmlRendererUtil.java | package org.plantuml.idea.rendering;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.ui.JBUI;
import net.sourceforge.plantuml.*;
import net.sourceforge.plantuml.core.Diagram;
import net.sourceforge.plantuml.cucadiagram.Display;
import net.sourceforge.plantuml.cucadiagram.DisplayPositionned;
import net.sourceforge.plantuml.descdiagram.DescriptionDiagram;
import net.sourceforge.plantuml.error.PSystemError;
import net.sourceforge.plantuml.sequencediagram.Event;
import net.sourceforge.plantuml.sequencediagram.Newpage;
import net.sourceforge.plantuml.sequencediagram.SequenceDiagram;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.plantuml.idea.plantuml.PlantUml;
import org.plantuml.idea.util.Utils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import static org.plantuml.idea.lang.annotator.LanguageDescriptor.IDEA_PARTIAL_RENDER;
public class PlantUmlRendererUtil {
private static final Logger logger = Logger.getInstance(PlantUmlRendererUtil.class);
public static final Pattern NEW_PAGE_PATTERN = Pattern.compile("\\n\\s*@?(?i)(newpage)(\\p{Blank}+[^\\n]+|\\p{Blank}*)(?=\\n)");
private static final PlantUmlPartialRenderer PARTIAL_RENDERER = new PlantUmlPartialRenderer();
private static final PlantUmlNormalRenderer NORMAL_RENDERER = new PlantUmlNormalRenderer();
/**
* Renders source code and saves diagram images to files according to provided naming scheme
* and image format.
*
* @param source source code to be rendered
* @param baseDir base dir to set for "include" functionality
* @param format image format
* @param path path to use with first file
* @param fileNameFormat file naming scheme for further files
* @param pageNumber -1 for all pages
* @throws IOException in case of rendering or saving fails
*/
public static void renderAndSave(String source, @Nullable File baseDir, PlantUml.ImageFormat format, String path, String fileNameFormat, int zoom, int pageNumber)
throws IOException {
NORMAL_RENDERER.renderAndSave(source, baseDir, format, path, fileNameFormat, zoom, pageNumber);
}
/**
* Renders file with support of plantUML include ange paging features, setting base dir and page for plantUML
* to provided values
*/
public static RenderResult render(RenderRequest renderRequest, RenderCacheItem cachedItem) {
File baseDir = renderRequest.getBaseDir();
if (baseDir != null) {
Utils.setPlantUmlDir(baseDir);
}
long start = System.currentTimeMillis();
String source = renderRequest.getSource();
String[] sourceSplit = NEW_PAGE_PATTERN.split(source);
logger.debug("split done ", System.currentTimeMillis() - start, "ms");
boolean partialRender = sourceSplit[0].contains(IDEA_PARTIAL_RENDER);
logger.debug("partialRender ", partialRender);
RenderResult renderResult;
if (partialRender) {
renderResult = PARTIAL_RENDERER.partialRender(renderRequest, cachedItem, start, sourceSplit);
} else {
renderResult = NORMAL_RENDERER.doRender(renderRequest, cachedItem, sourceSplit);
}
return renderResult;
}
public static DiagramInfo zoomDiagram(SourceStringReader reader, int zoom) {
logger.debug("zooming diagram");
int totalPages = 0;
List<BlockUml> blocks = reader.getBlocks();
String fileOrDirname = null;
if (blocks.size() > 1) {
// logger.error("more than 1 block"); //TODO
//happens when the source is incorrectly extracted and contains multiple diagrams
}
for (int i = 0; i < blocks.size(); i++) {
BlockUml block = blocks.get(i);
long start = System.currentTimeMillis();
checkCancel();
Diagram diagram = block.getDiagram();
logger.debug("getDiagram done in ", System.currentTimeMillis() - start, " ms");
start = System.currentTimeMillis();
zoomDiagram(diagram, zoom);
logger.debug("zoom diagram done in ", System.currentTimeMillis() - start, " ms");
fileOrDirname = block.getFileOrDirname();
totalPages = totalPages + diagram.getNbImages();
break;
}
DiagramInfo.Titles titles = getTitles(totalPages, blocks);
return new DiagramInfo(totalPages, titles, fileOrDirname);
}
private static void zoomDiagram(Diagram diagram, int zoom) {
if (diagram instanceof UmlDiagram) {
UmlDiagram umlDiagram = (UmlDiagram) diagram;
Scale scale = umlDiagram.getScale();
if (scale == null || scale instanceof ScaleSimple || zoom != 100) {
umlDiagram.setScale(calculateScale(zoom, scale));
}
} else if (diagram instanceof NewpagedDiagram) {
NewpagedDiagram newpagedDiagram = (NewpagedDiagram) diagram;
for (Diagram page : newpagedDiagram.getDiagrams()) {
if (page instanceof DescriptionDiagram) {
DescriptionDiagram descriptionDiagram = (DescriptionDiagram) page;
Scale scale = descriptionDiagram.getScale();
if (scale == null || scale instanceof ScaleSimple || zoom != 100) {
descriptionDiagram.setScale(calculateScale(zoom, scale));
}
}
}
} else if (diagram instanceof AbstractPSystem) { //gantt, salt wireframe - but has no effect
AbstractPSystem d = (AbstractPSystem) diagram;
Scale scale = d.getScale();
if (scale == null || scale instanceof ScaleSimple || zoom != 100) {
d.setScale(calculateScale(zoom, scale));
}
}
}
@NotNull
private static ScaleSimple calculateScale(int zoom, Scale scale) {
return new ScaleSimple(getPlantUmlScale(scale) * getSystemScale() * zoom / 100f);
}
private static double getPlantUmlScale(Scale scale) {
double plantUmlScale = 1.0;
if (scale instanceof ScaleSimple) {
plantUmlScale = scale.getScale(1, 1);
}
return plantUmlScale;
}
private static double getSystemScale() {
try {
return JBUI.ScaleContext.create().getScale(JBUI.ScaleType.SYS_SCALE); //TODO API change 2019/03/05
} catch (Throwable e) {
return 1;
}
}
@NotNull
protected static DiagramInfo.Titles getTitles(int totalPages, List<BlockUml> blocks) {
List<String> titles = new ArrayList<String>(totalPages);
for (BlockUml block : blocks) {
Diagram diagram = block.getDiagram();
if (diagram instanceof SequenceDiagram) {
SequenceDiagram sequenceDiagram = (SequenceDiagram) diagram;
addTitle(titles, sequenceDiagram.getTitle().getDisplay());
List<Event> events = sequenceDiagram.events();
for (Event event : events) {
if (event instanceof Newpage) {
Display title = ((Newpage) event).getTitle();
addTitle(titles, title);
}
}
} else if (diagram instanceof NewpagedDiagram) {
NewpagedDiagram newpagedDiagram = (NewpagedDiagram) diagram;
List<Diagram> diagrams = newpagedDiagram.getDiagrams();
for (Diagram diagram1 : diagrams) {
if (diagram1 instanceof UmlDiagram) {
DisplayPositionned title = ((UmlDiagram) diagram1).getTitle();
addTitle(titles, title.getDisplay());
}
}
} else if (diagram instanceof UmlDiagram) {
DisplayPositionned title = ((UmlDiagram) diagram).getTitle();
addTitle(titles, title.getDisplay());
} else if (diagram instanceof PSystemError) {
DisplayPositionned title = ((PSystemError) diagram).getTitle();
if (title == null) {
titles.add(null);
} else {
addTitle(titles, title.getDisplay());
}
}
break;
}
return new DiagramInfo.Titles(titles);
}
protected static void addTitle(List<String> titles, Display display) {
if (display.size() > 0) {
titles.add(display.toString());
} else {
titles.add(null);
}
}
public static void checkCancel() {
if (Thread.currentThread().isInterrupted()) {
throw new RenderingCancelledException();
}
}
}
| #229 zoom fix
| src/org/plantuml/idea/rendering/PlantUmlRendererUtil.java | #229 zoom fix | <ide><path>rc/org/plantuml/idea/rendering/PlantUmlRendererUtil.java
<ide> import net.sourceforge.plantuml.core.Diagram;
<ide> import net.sourceforge.plantuml.cucadiagram.Display;
<ide> import net.sourceforge.plantuml.cucadiagram.DisplayPositionned;
<del>import net.sourceforge.plantuml.descdiagram.DescriptionDiagram;
<ide> import net.sourceforge.plantuml.error.PSystemError;
<ide> import net.sourceforge.plantuml.sequencediagram.Event;
<ide> import net.sourceforge.plantuml.sequencediagram.Newpage;
<ide> }
<ide>
<ide> private static void zoomDiagram(Diagram diagram, int zoom) {
<del> if (diagram instanceof UmlDiagram) {
<del> UmlDiagram umlDiagram = (UmlDiagram) diagram;
<del> Scale scale = umlDiagram.getScale();
<del>
<del> if (scale == null || scale instanceof ScaleSimple || zoom != 100) {
<del> umlDiagram.setScale(calculateScale(zoom, scale));
<del> }
<del> } else if (diagram instanceof NewpagedDiagram) {
<add> if (diagram instanceof NewpagedDiagram) {
<ide> NewpagedDiagram newpagedDiagram = (NewpagedDiagram) diagram;
<ide> for (Diagram page : newpagedDiagram.getDiagrams()) {
<del> if (page instanceof DescriptionDiagram) {
<del> DescriptionDiagram descriptionDiagram = (DescriptionDiagram) page;
<add> if (page instanceof AbstractPSystem) {
<add> AbstractPSystem descriptionDiagram = (AbstractPSystem) page;
<ide> Scale scale = descriptionDiagram.getScale();
<ide>
<ide> if (scale == null || scale instanceof ScaleSimple || zoom != 100) { |
|
Java | bsd-3-clause | 84101e7fcb7a613f9704c7a6db27c9b1e19de30a | 0 | mdiggory/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,rnathanday/dryad-repo,rnathanday/dryad-repo,mdiggory/dryad-repo,jamie-dryad/dryad-repo,jimallman/dryad-repo,mdiggory/dryad-repo,jamie-dryad/dryad-repo,jimallman/dryad-repo,ojacobson/dryad-repo,ojacobson/dryad-repo,ojacobson/dryad-repo,mdiggory/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,jamie-dryad/dryad-repo,jimallman/dryad-repo,ojacobson/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,ojacobson/dryad-repo,jamie-dryad/dryad-repo,ojacobson/dryad-repo,jamie-dryad/dryad-repo,mdiggory/dryad-repo,rnathanday/dryad-repo | package org.dspace.curate;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.DCDate;
import org.dspace.content.DCValue;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.content.ItemIterator;
import org.dspace.content.crosswalk.StreamIngestionCrosswalk;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.doi.CDLDataCiteService;
import org.dspace.embargo.EmbargoManager;
import org.dspace.identifier.DOIIdentifierProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
/**
* Curation task to report embargoed items without publication date
*
* @author pmidford
* created Dec 9, 2011
*
*/
@Suspendable
public class EmbargoedWithoutPubDate extends AbstractCurationTask {
private int total;
private int unpublishedCount;
private List<DatedEmbargo> embargoes;
private DatedEmbargo[] dummy = new DatedEmbargo[1];
private static Logger LOGGER = LoggerFactory.getLogger(EmbargoedWithoutPubDate.class);
@Override
public void init(Curator curator, String taskID) throws IOException{
super.init(curator, taskID);
}
@Override
public int perform(DSpaceObject dso) throws IOException{
this.report("Object is " + dso + "; handle is " + dso.getHandle());
return Curator.CURATE_FAIL;
}
@Override
public int perform(Context ctx, String id) throws IOException {
String testid = "10255/2";
DSpaceObject dso = dereference(ctx,testid);
this.report("Looking up: " + testid + " in context: " + ctx.toString());
this.report("Found an object: " + dso);
if (dso instanceof Collection){
total = 0;
unpublishedCount = 0;
embargoes = new ArrayList<DatedEmbargo>();
distribute(dso);
if (!embargoes.isEmpty()){
DatedEmbargo[] s = embargoes.toArray(dummy);
Arrays.sort(s);
this.report("Collection: " + dso.getName() + "; Total items = " + total + "; unpublished items = " + unpublishedCount);
for(DatedEmbargo d : s)
this.report(d.toString());
}
else if (total > 0)
this.report("Collection: " + dso.getName() + "; Total items = " + total + "; no unpublished items");
}
return Curator.CURATE_SUCCESS;
}
@Override
protected void performItem(Item item){
String handle = item.getHandle();
DCValue partof[] = item.getMetadata("dc.relation.ispartof");
if (handle != null){ //ignore items in workflow
total++;
boolean unpublished = false;
DCDate itemPubDate;
DCValue values[] = item.getMetadata("dc", "date", "available", Item.ANY);
if (values== null || values.length==0){ //no available date - save and report
unpublished = true;
}
DCDate itemEmbargoDate = null;
if (unpublished){
unpublishedCount++;
try { //want to continue if a problem comes up
itemEmbargoDate = EmbargoManager.getEmbargoDate(null, item);
if (itemEmbargoDate != null){
DatedEmbargo de = new DatedEmbargo(itemEmbargoDate.toDate(),item);
embargoes.add(de);
}
} catch (Exception e) {
this.report("Exception " + e + " encountered while processing " + item);
}
}
}
}
private static class DatedEmbargo implements Comparable<DatedEmbargo>{
private Date embargoDate;
private Item embargoedItem;
public DatedEmbargo(Date date, Item item) {
embargoDate = date;
embargoedItem = item;
}
@Override
public int compareTo(DatedEmbargo o) {
return embargoDate.compareTo(o.embargoDate);
}
@Override
public String toString(){
return embargoedItem.getName() + " " + embargoDate.toString();
}
}
}
| dspace/modules/api/src/main/java/org/dspace/curate/EmbargoedWithoutPubDate.java | package org.dspace.curate;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.DCDate;
import org.dspace.content.DCValue;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.content.ItemIterator;
import org.dspace.content.crosswalk.StreamIngestionCrosswalk;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.doi.CDLDataCiteService;
import org.dspace.embargo.EmbargoManager;
import org.dspace.identifier.DOIIdentifierProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
/**
* Curation task to report embargoed items without publication date
*
* @author pmidford
* created Dec 9, 2011
*
*/
@Suspendable
public class EmbargoedWithoutPubDate extends AbstractCurationTask {
private int total;
private int unpublishedCount;
private List<DatedEmbargo> embargoes;
private DatedEmbargo[] dummy = new DatedEmbargo[1];
private static Logger LOGGER = LoggerFactory.getLogger(EmbargoedWithoutPubDate.class);
@Override
public void init(Curator curator, String taskID) throws IOException{
super.init(curator, taskID);
}
@Override
public int perform(DSpaceObject dso) throws IOException{
this.report("Object is " + dso + "; handle is " + dso.getHandle());
return Curator.CURATE_FAIL;
}
@Override
public int perform(Context ctx, String id) throws IOException {
DSpaceObject dso = dereference(ctx,id);
this.report("Looking up: " + id + " in context: " + ctx.toString());
this.report("Found an object: " + dso);
if (dso instanceof Collection){
total = 0;
unpublishedCount = 0;
embargoes = new ArrayList<DatedEmbargo>();
distribute(dso);
if (!embargoes.isEmpty()){
DatedEmbargo[] s = embargoes.toArray(dummy);
Arrays.sort(s);
this.report("Collection: " + dso.getName() + "; Total items = " + total + "; unpublished items = " + unpublishedCount);
for(DatedEmbargo d : s)
this.report(d.toString());
}
else if (total > 0)
this.report("Collection: " + dso.getName() + "; Total items = " + total + "; no unpublished items");
}
return Curator.CURATE_SUCCESS;
}
@Override
protected void performItem(Item item){
String handle = item.getHandle();
DCValue partof[] = item.getMetadata("dc.relation.ispartof");
if (handle != null){ //ignore items in workflow
total++;
boolean unpublished = false;
DCDate itemPubDate;
DCValue values[] = item.getMetadata("dc", "date", "available", Item.ANY);
if (values== null || values.length==0){ //no available date - save and report
unpublished = true;
}
DCDate itemEmbargoDate = null;
if (unpublished){
unpublishedCount++;
try { //want to continue if a problem comes up
itemEmbargoDate = EmbargoManager.getEmbargoDate(null, item);
if (itemEmbargoDate != null){
DatedEmbargo de = new DatedEmbargo(itemEmbargoDate.toDate(),item);
embargoes.add(de);
}
} catch (Exception e) {
this.report("Exception " + e + " encountered while processing " + item);
}
}
}
}
private static class DatedEmbargo implements Comparable<DatedEmbargo>{
private Date embargoDate;
private Item embargoedItem;
public DatedEmbargo(Date date, Item item) {
embargoDate = date;
embargoedItem = item;
}
@Override
public int compareTo(DatedEmbargo o) {
return embargoDate.compareTo(o.embargoDate);
}
@Override
public String toString(){
return embargoedItem.getName() + " " + embargoDate.toString();
}
}
}
| Sort of works, experimenting with context and dereferencing
| dspace/modules/api/src/main/java/org/dspace/curate/EmbargoedWithoutPubDate.java | Sort of works, experimenting with context and dereferencing | <ide><path>space/modules/api/src/main/java/org/dspace/curate/EmbargoedWithoutPubDate.java
<ide>
<ide> @Override
<ide> public int perform(Context ctx, String id) throws IOException {
<del> DSpaceObject dso = dereference(ctx,id);
<del> this.report("Looking up: " + id + " in context: " + ctx.toString());
<add> String testid = "10255/2";
<add> DSpaceObject dso = dereference(ctx,testid);
<add> this.report("Looking up: " + testid + " in context: " + ctx.toString());
<ide> this.report("Found an object: " + dso);
<ide> if (dso instanceof Collection){
<ide> total = 0; |
|
JavaScript | mit | 1f872e0b32a7a1a90986eaec19f56a98f07743e3 | 0 | quintel/etmodel,quintel/etmodel,quintel/etmodel,quintel/etmodel | var PolicyGoal = Backbone.Model.extend({
initialize : function() {
window.policy_goals.add(this);
this.success_query = new Gquery({ key: this.get("success_query")});
this.value_query = new Gquery({ key: this.get("value_query")});
this.target_query = new Gquery({ key: this.get("target_query")});
this.user_value_query = new Gquery({ key: this.get("user_value_query")});
},
// goal achieved? true/false
success_value : function() {
return this.success_query.get('future_value');
},
successful : function() {
return (this.success_value() === true);
},
// numeric value
current_value : function() {
return this.value_query.get('future_value');
},
start_value: function() {
return this.value_query.get('present_value');
},
// goal, numeric value
target_value : function() {
return this.target_query.get('future_value');
},
// returns true if the user has set a goal
is_set : function() {
return this.user_value_query.get('future_value');
},
// DEBT: we could use a BB view
update_view : function() {
var success = this.successful();
if(this.is_set()) {
var check_box = this.dom_element().find(".check");
check_box.removeClass('success failure not_set');
check_box.addClass(success ? 'success' : 'failure');
var formatted = this.format_value(this.target_value());
this.dom_element().find(".target").html(formatted);
} else {
this.dom_element().find(".target").html(I18n.t('policy_goals.not_set'));
}
var current_value = this.format_value(this.current_value());
this.dom_element().find(".you").html(current_value);
this.update_score_box();
},
update_score_box: function() {
var key = this.get('key');
// update score box if present
// policy goal keys and constraint key sometimes don't match. DEBT
if (key == 'co2_emission') { key = 'co2_reduction'; }
$("#" + key + "-score").html(this.score());
},
dom_element : function() {
return $("#goal_" + this.get("goal_id"));
},
format_value : function(n) {
var out = null;
switch(this.get('display_fmt')) {
case 'percentage' :
out = Metric.ratio_as_percentage(n, false, 2);
break;
case 'number':
out = Metric.round_number(n, 2);
break;
case 'number_with_unit':
out = "" + Metric.round_number(n, 2) + " " + this.get('unit');
break;
default:
out = n;
break;
}
return out;
},
score: function() {
if (!this.is_set()) return false;
var start = this.start_value();
var current = this.current_value();
var target = this.target_value();
var ampl = 100;
var t = current - start;
if (target < start) { t = -t; }
var a = 2 * Math.abs(start - target);
var score = 2 * ampl * Math.abs( (t / a) - Math.floor( (t / a) + 0.5));
if(t > a || t < 0) { score = -score; }
if((t < -0.5 * a) || (t > 1.5 * a)) { score = -100; }
return Math.round(score);
}
});
var PolicyGoalList = Backbone.Collection.extend({
model : PolicyGoal,
// returns the number of user set goals
goals_set : function() {
return this.select(function(g){ return g.is_set();}).length;
},
// returns the number of goals achieved
goals_achieved : function() {
return this.select(function(g){ return g.is_set() && g.successful();}).length;
},
update_totals : function() {
var set = this.goals_set();
var achieved = this.goals_achieved();
var string = "" + achieved + "/" + set;
$("#constraint_7 strong").html(string);
this.update_total_score();
},
// used by watt-nu. Sums the partial scores
update_total_score: function() {
var els;
switch(App.settings.get('current_round')) {
case '1':
els = ['co2_emission'];
break;
case '2':
els = ['co2_emission', 'total_energy_cost'];
break;
case '3':
els = ['co2_emission', 'total_energy_cost', 'renewable_percentage'];
break;
default:
els = [];
break;
}
var total = 0;
var goals = this;
_.each(els, function(key){
var g = goals.find_by_key(key);
total += g.score();
});
$("#targets_met-score").html(total);
return total;
},
find_by_key: function(key) {
return this.filter(function(g){ return g.get('key') == key;})[0];
}
});
window.policy_goals = new PolicyGoalList();
| app/javascripts/lib/models/policy_goal.js | var PolicyGoal = Backbone.Model.extend({
initialize : function() {
window.policy_goals.add(this);
this.success_query = new Gquery({ key: this.get("success_query")});
this.value_query = new Gquery({ key: this.get("value_query")});
this.target_query = new Gquery({ key: this.get("target_query")});
this.user_value_query = new Gquery({ key: this.get("user_value_query")});
},
// goal achieved? true/false
success_value : function() {
return this.success_query.get('future_value');
},
successful : function() {
return (this.success_value() === true);
},
// numeric value
current_value : function() {
return this.value_query.get('future_value');
},
start_value: function() {
return this.value_query.get('present_value');
},
// goal, numeric value
target_value : function() {
return this.target_query.get('future_value');
},
// returns true if the user has set a goal
is_set : function() {
return this.user_value_query.get('future_value');
},
// DEBT: we could use a BB view
update_view : function() {
var success = this.successful();
if(this.is_set()) {
var check_box = this.dom_element().find(".check");
check_box.removeClass('success failure not_set');
check_box.addClass(success ? 'success' : 'failure');
var formatted = this.format_value(this.target_value());
this.dom_element().find(".target").html(formatted);
} else {
this.dom_element().find(".target").html(I18n.t('policy_goals.not_set'));
}
var current_value = this.format_value(this.current_value());
this.dom_element().find(".you").html(current_value);
this.update_score_box();
},
update_score_box: function() {
var key = this.get('key');
// update score box if present
// policy goal keys and constraint key sometimes don't match. DEBT
if (key == 'co2_emission') { key = 'co2_reduction'; }
$("#" + key + "-score").html(this.score());
},
dom_element : function() {
return $("#goal_" + this.get("goal_id"));
},
format_value : function(n) {
var out = null;
switch(this.get('display_fmt')) {
case 'percentage' :
out = Metric.ratio_as_percentage(n, false, 2);
break;
case 'number':
out = Metric.round_number(n, 2);
break;
case 'number_with_unit':
out = "" + Metric.round_number(n, 2) + " " + this.get('unit');
break;
default:
out = n;
break;
}
return out;
},
score: function() {
if (!this.is_set()) return false;
var start = this.start_value();
var current = this.current_value();
var target = this.target_value();
var ampl = 100;
var t = current - start;
if (target < start) { t = -t; }
var a = 2 * Math.abs(start - target);
var score = 2 * ampl * Math.abs( (t / a) - Math.floor( (t / a) + 0.5));
if(t > a || t < 0) { score = -score; }
if((t < -0.5 * a) || (t > 1.5 * a)) { score = -100; }
return Math.round(score);
}
});
var PolicyGoalList = Backbone.Collection.extend({
model : PolicyGoal,
// returns the number of user set goals
goals_set : function() {
return this.select(function(g){ return g.is_set();}).length;
},
// returns the number of goals achieved
goals_achieved : function() {
return this.select(function(g){ return g.is_set() && g.successful();}).length;
},
update_totals : function() {
var set = this.goals_set();
var achieved = this.goals_achieved();
var string = "" + achieved + "/" + set;
$("#constraint_7 strong").html(string);
this.update_total_score();
},
// used by watt-nu. Sums the partial scores
update_total_score: function() {
var els;
switch(App.settings.get('current_round')) {
case '1':
els = ['co2_emission'];
break;
case '2':
els = ['co2_emission', 'total_energy_cost'];
break;
case '3':
els = ['co2_emission', 'total_energy_cost', 'renewable_percentage'];
break;
default:
els = [];
break;
}
var total = 0;
_.each(els, function(key){ var g = this.find_by_key(key); total += g.score();});
$("#targets_met-score").html(total);
return total;
},
find_by_key: function(key) {
return this.filter(function(g){ return g.get('key') == key;})[0];
}
});
window.policy_goals = new PolicyGoalList();
| watt-nu: fixed total score
| app/javascripts/lib/models/policy_goal.js | watt-nu: fixed total score | <ide><path>pp/javascripts/lib/models/policy_goal.js
<ide> }
<ide>
<ide> var total = 0;
<del> _.each(els, function(key){ var g = this.find_by_key(key); total += g.score();});
<add> var goals = this;
<add> _.each(els, function(key){
<add> var g = goals.find_by_key(key);
<add> total += g.score();
<add> });
<ide> $("#targets_met-score").html(total);
<ide> return total;
<ide> }, |
|
Java | apache-2.0 | 8d0654797824e566953f697dd866af7a8d3100d1 | 0 | yukuku/androidbible,yukuku/androidbible,arnotixe/androidbible,infojulio/androidbible,Jaden-J/androidbible,yukuku/androidbible,Jaden-J/androidbible,yukuku/androidbible,arnotixe/androidbible,arnotixe/androidbible,yukuku/androidbible,infojulio/androidbible,infojulio/androidbible,infojulio/androidbible,infojulio/androidbible,Jaden-J/androidbible,yukuku/androidbible,yukuku/androidbible,Jaden-J/androidbible,Jaden-J/androidbible,Jaden-J/androidbible,infojulio/androidbible,arnotixe/androidbible,yukuku/androidbible,arnotixe/androidbible,infojulio/androidbible,infojulio/androidbible,Jaden-J/androidbible | package yuku.alkitab.base.widget;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import yuku.afw.storage.Preferences;
import yuku.alkitab.R;
import yuku.alkitab.base.U;
import yuku.alkitab.base.compat.Api8;
import yuku.alkitab.base.model.Book;
import yuku.alkitab.base.model.PericopeBlock;
import yuku.alkitab.base.model.SingleChapterVerses;
import yuku.alkitab.base.util.IntArrayList;
public class VersesView extends ListView implements AbsListView.OnScrollListener {
public static final String TAG = VersesView.class.getSimpleName();
// http://stackoverflow.com/questions/6369491/stop-listview-scroll-animation
static class StopListFling {
private static Field mFlingEndField = null;
private static Method mFlingEndMethod = null;
static {
try {
mFlingEndField = AbsListView.class.getDeclaredField("mFlingRunnable");
mFlingEndField.setAccessible(true);
mFlingEndMethod = mFlingEndField.getType().getDeclaredMethod("endFling");
mFlingEndMethod.setAccessible(true);
} catch (Exception e) {
mFlingEndMethod = null;
}
}
public static void stop(ListView list) {
if (mFlingEndMethod != null) {
try {
mFlingEndMethod.invoke(mFlingEndField.get(list));
} catch (Exception e) {
}
}
}
}
public enum VerseSelectionMode {
none,
multiple,
singleClick,
}
public interface SelectedVersesListener {
void onSomeVersesSelected(VersesView v);
void onNoVersesSelected(VersesView v);
void onVerseSingleClick(VersesView v, int verse_1);
}
public interface AttributeListener {
void onAttributeClick(Book book, int chapter_1, int verse_1, int kind);
}
public abstract static class XrefListener {
public abstract void onXrefClick(VersesView versesView, int ari, int which);
}
public interface OnVerseScrollListener {
void onVerseScroll(VersesView v, boolean isPericope, int verse_1, float prop);
void onScrollToTop(VersesView v);
}
private VerseAdapter adapter;
private SelectedVersesListener listener;
private VerseSelectionMode verseSelectionMode;
private Drawable originalSelector;
private OnVerseScrollListener onVerseScrollListener;
private AbsListView.OnScrollListener userOnScrollListener;
private int scrollState = 0;
private View[] scrollToVerseConvertViews;
public VersesView(Context context) {
super(context);
init();
}
public VersesView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
if (isInEditMode()) return;
originalSelector = getSelector();
setDivider(null);
setFocusable(false);
setAdapter(adapter = new VerseAdapter.Factory().create(getContext()));
setOnItemClickListener(itemClick);
setVerseSelectionMode(VerseSelectionMode.multiple);
super.setOnScrollListener(this);
}
@Override public final void setOnScrollListener(AbsListView.OnScrollListener l) {
userOnScrollListener = l;
}
@Override public VerseAdapter getAdapter() {
return adapter;
}
public void setParallelListener(CallbackSpan.OnClickListener parallelListener) {
adapter.setParallelListener(parallelListener);
}
public void setAttributeListener(VersesView.AttributeListener attributeListener) {
adapter.setAttributeListener(attributeListener);
}
public void setXrefListener(VersesView.XrefListener xrefListener) {
adapter.setXrefListener(xrefListener, this);
}
public void setVerseSelectionMode(VerseSelectionMode mode) {
this.verseSelectionMode = mode;
if (mode == VerseSelectionMode.singleClick) {
setSelector(originalSelector);
uncheckAll();
setChoiceMode(ListView.CHOICE_MODE_NONE);
} else if (mode == VerseSelectionMode.multiple) {
setSelector(new ColorDrawable(0x0));
setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
} else if (mode == VerseSelectionMode.none) {
setSelector(new ColorDrawable(0x0));
setChoiceMode(ListView.CHOICE_MODE_NONE);
}
}
public void setOnVerseScrollListener(OnVerseScrollListener onVerseScrollListener) {
this.onVerseScrollListener = onVerseScrollListener;
}
// TODO external should provide the attribute map into this widget similar to setData(),
// instead of this widget itself accessing persistent data.
// When this is done, we do not need to provide Book and chapter_1 as parameters to setData(),
// because in reality, VersesViews could contain verses taken from multiple books and chapters.
public void loadAttributeMap() {
adapter.loadAttributeMap();
}
public String getVerse(int verse_1) {
return adapter.getVerse(verse_1);
}
public void scrollToShowVerse(int mainVerse_1) {
int position = adapter.getPositionOfPericopeBeginningFromVerse(mainVerse_1);
if (Build.VERSION.SDK_INT >= 8) {
Api8.ListView_smoothScrollToPosition(this, position);
} else {
stopFling();
setSelectionFromTop(position, getVerticalFadingEdgeLength());
}
}
/**
* @return 1-based verse
*/
public int getVerseBasedOnScroll() {
return adapter.getVerseFromPosition(getPositionBasedOnScroll());
}
public int getPositionBasedOnScroll() {
int pos = getFirstVisiblePosition();
// check if the top one has been scrolled
View child = getChildAt(0);
if (child != null) {
int top = child.getTop();
if (top == 0) {
return pos;
}
int bottom = child.getBottom();
if (bottom > getVerticalFadingEdgeLength()) {
return pos;
} else {
return pos+1;
}
}
return pos;
}
public void setData(Book book, int chapter_1, SingleChapterVerses verses, int[] pericopeAris, PericopeBlock[] pericopeBlocks, int nblock, int[] xrefEntryCounts) {
adapter.setData(book, chapter_1, verses, pericopeAris, pericopeBlocks, nblock, xrefEntryCounts);
stopFling();
}
private OnItemClickListener itemClick = new OnItemClickListener() {
@Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (verseSelectionMode == VerseSelectionMode.singleClick) {
if (listener != null) listener.onVerseSingleClick(VersesView.this, adapter.getVerseFromPosition(position));
} else if (verseSelectionMode == VerseSelectionMode.multiple) {
adapter.notifyDataSetChanged();
hideOrShowContextMenuButton();
}
}
};
public void uncheckAll() {
SparseBooleanArray checkedPositions = getCheckedItemPositions();
if (checkedPositions != null && checkedPositions.size() > 0) {
for (int i = checkedPositions.size() - 1; i >= 0; i--) {
if (checkedPositions.valueAt(i)) {
setItemChecked(checkedPositions.keyAt(i), false);
}
}
}
if (listener != null) listener.onNoVersesSelected(this);
}
void hideOrShowContextMenuButton() {
if (verseSelectionMode != VerseSelectionMode.multiple) return;
SparseBooleanArray checkedPositions = getCheckedItemPositions();
boolean anyChecked = false;
for (int i = 0; i < checkedPositions.size(); i++) if (checkedPositions.valueAt(i)) {
anyChecked = true;
break;
}
if (anyChecked) {
if (listener != null) listener.onSomeVersesSelected(this);
} else {
if (listener != null) listener.onNoVersesSelected(this);
}
}
public IntArrayList getSelectedVerses_1() {
// count how many are selected
SparseBooleanArray positions = getCheckedItemPositions();
if (positions == null) {
return new IntArrayList(0);
}
IntArrayList res = new IntArrayList(positions.size());
for (int i = 0, len = positions.size(); i < len; i++) {
if (positions.valueAt(i)) {
int position = positions.keyAt(i);
int verse_1 = adapter.getVerseFromPosition(position);
if (verse_1 >= 1) res.add(verse_1);
}
}
return res;
}
@Override public Parcelable onSaveInstanceState() {
Bundle b = new Bundle();
Parcelable superState = super.onSaveInstanceState();
b.putParcelable("superState", superState);
b.putInt("verseSelectionMode", verseSelectionMode.ordinal());
return b;
}
@Override public void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
Bundle b = (Bundle) state;
super.onRestoreInstanceState(b.getParcelable("superState"));
setVerseSelectionMode(VerseSelectionMode.values()[b.getInt("verseSelectionMode")]);
}
hideOrShowContextMenuButton();
}
public boolean press(int keyCode) {
String volumeButtonsForNavigation = Preferences.getString(getContext().getString(R.string.pref_tombolVolumeBuatPindah_key), getContext().getString(R.string.pref_tombolVolumeBuatPindah_default));
if (U.equals(volumeButtonsForNavigation, "pasal" /* chapter */)) { //$NON-NLS-1$
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) keyCode = KeyEvent.KEYCODE_DPAD_RIGHT;
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) keyCode = KeyEvent.KEYCODE_DPAD_LEFT;
} else if (U.equals(volumeButtonsForNavigation, "ayat" /* verse */)) { //$NON-NLS-1$
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) keyCode = KeyEvent.KEYCODE_DPAD_DOWN;
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) keyCode = KeyEvent.KEYCODE_DPAD_UP;
}
if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
int oldPos = getPositionBasedOnScroll();
if (oldPos < adapter.getCount() - 1) {
stopFling();
setSelectionFromTop(oldPos+1, getVerticalFadingEdgeLength());
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
int oldPos = getPositionBasedOnScroll();
if (oldPos >= 1) {
int newPos = oldPos - 1;
while (newPos > 0) { // cek disabled, kalo iya, mundurin lagi
if (adapter.isEnabled(newPos)) break;
newPos--;
}
stopFling();
setSelectionFromTop(newPos, getVerticalFadingEdgeLength());
} else {
stopFling();
setSelectionFromTop(0, getVerticalFadingEdgeLength());
}
return true;
}
return false;
}
public void setDataWithRetainSelectedVerses(boolean retainSelectedVerses, Book book, int chapter_1, int[] pericope_aris, PericopeBlock[] pericope_blocks, int nblock, SingleChapterVerses verses, int[] xrefEntryCounts) {
IntArrayList selectedVerses_1 = null;
if (retainSelectedVerses) {
selectedVerses_1 = getSelectedVerses_1();
}
//# fill adapter with new data. make sure all checked states are reset
uncheckAll();
setData(book, chapter_1, verses, pericope_aris, pericope_blocks, nblock, xrefEntryCounts);
loadAttributeMap();
boolean anySelected = false;
if (selectedVerses_1 != null) {
for (int i = 0, len = selectedVerses_1.size(); i < len; i++) {
int pos = adapter.getPositionIgnoringPericopeFromVerse(selectedVerses_1.get(i));
if (pos != -1) {
setItemChecked(pos, true);
anySelected = true;
}
}
}
if (anySelected) {
if (listener != null) listener.onSomeVersesSelected(this);
}
}
public void scrollToVerse(int verse_1) {
final int position = adapter.getPositionOfPericopeBeginningFromVerse(verse_1);
if (position == -1) {
Log.w(TAG, "could not find verse=" + verse_1 + ", weird!"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
post(new Runnable() {
@Override public void run() {
// this may happen async from above, so check first if pos is still valid
if (position >= getCount()) return;
stopFling();
setSelectionFromTop(position, getVerticalFadingEdgeLength());
}
});
}
}
public void scrollToVerse(int verse_1, final float prop) {
final int position = adapter.getPositionIgnoringPericopeFromVerse(verse_1);
if (position == -1) {
Log.w(TAG, "could not find verse=" + verse_1 + ", weird!"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
post(new Runnable() {
@Override public void run() {
// this may happen async from above, so check first if pos is still valid
if (position >= getCount()) return;
boolean needMeasure = false;
int shifty = getVerticalFadingEdgeLength();
int firstPos = getFirstVisiblePosition();
if (position >= firstPos) {
int lastPos = getLastVisiblePosition();
if (position <= lastPos) {
// we have this on screen, no need to measure again
View child = getChildAt(position - firstPos);
stopFling();
setSelectionFromTop(position, shifty - (int) (prop * child.getHeight()));
} else {
needMeasure = true;
}
} else {
needMeasure = true;
}
if (needMeasure) {
// initialize scrollToVerseConvertViews if needed
if (scrollToVerseConvertViews == null) {
scrollToVerseConvertViews = new View[adapter.getViewTypeCount()];
}
int itemType = adapter.getItemViewType(position);
View convertView = scrollToVerseConvertViews[itemType];
View child = adapter.getView(position, convertView, VersesView.this);
child.measure(MeasureSpec.makeMeasureSpec(VersesView.this.getWidth() - VersesView.this.getPaddingLeft() - VersesView.this.getPaddingRight(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
scrollToVerseConvertViews[itemType] = child;
stopFling();
setSelectionFromTop(position, shifty - (int) (prop * child.getMeasuredHeight()));
}
}
});
}
}
public void scrollToTop() {
post(new Runnable() {
@Override public void run() {
setSelectionFromTop(0, 0);
}
});
}
public void setSelectedVersesListener(SelectedVersesListener listener) {
this.listener = listener;
}
@Override public void onScrollStateChanged(AbsListView view, int scrollState) {
if (userOnScrollListener != null) userOnScrollListener.onScrollStateChanged(view, scrollState);
this.scrollState = scrollState;
}
@Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (userOnScrollListener != null) userOnScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
if (onVerseScrollListener == null) return;
if (view.getChildCount() > 0) {
float prop = 0.f;
int position = -1;
View firstChild = view.getChildAt(0);
// if first child is on top, top == fading edge length
int bottom = firstChild.getBottom();
int remaining = bottom - view.getVerticalFadingEdgeLength();
if (remaining >= 0) {
position = firstVisibleItem;
prop = 1.f - (float) remaining / firstChild.getHeight();
} else { // we should have a second child
if (view.getChildCount() > 1) {
View secondChild = view.getChildAt(1);
position = firstVisibleItem + 1;
prop = (float) -remaining / secondChild.getHeight();
}
}
int verse_1 = adapter.getVerseOrPericopeFromPosition(position);
if (scrollState != AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
if (verse_1 > 0) {
onVerseScrollListener.onVerseScroll(this, false, verse_1, prop);
} else {
onVerseScrollListener.onVerseScroll(this, true, 0, 0);
}
if (position == 0 && prop == 0.f) {
onVerseScrollListener.onScrollToTop(this);
}
}
}
}
public void setDataEmpty() {
adapter.setDataEmpty();
}
public void stopFling() {
StopListFling.stop(this);
}
}
| Alkitab/src/yuku/alkitab/base/widget/VersesView.java | package yuku.alkitab.base.widget;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import yuku.afw.storage.Preferences;
import yuku.alkitab.R;
import yuku.alkitab.base.U;
import yuku.alkitab.base.compat.Api8;
import yuku.alkitab.base.model.Book;
import yuku.alkitab.base.model.PericopeBlock;
import yuku.alkitab.base.model.SingleChapterVerses;
import yuku.alkitab.base.util.IntArrayList;
public class VersesView extends ListView implements AbsListView.OnScrollListener {
public static final String TAG = VersesView.class.getSimpleName();
// http://stackoverflow.com/questions/6369491/stop-listview-scroll-animation
static class StopListFling {
private static Field mFlingEndField = null;
private static Method mFlingEndMethod = null;
static {
try {
mFlingEndField = AbsListView.class.getDeclaredField("mFlingRunnable");
mFlingEndField.setAccessible(true);
mFlingEndMethod = mFlingEndField.getType().getDeclaredMethod("endFling");
mFlingEndMethod.setAccessible(true);
} catch (Exception e) {
mFlingEndMethod = null;
}
}
public static void stop(ListView list) {
if (mFlingEndMethod != null) {
try {
mFlingEndMethod.invoke(mFlingEndField.get(list));
} catch (Exception e) {
}
}
}
}
public enum VerseSelectionMode {
none,
multiple,
singleClick,
}
public interface SelectedVersesListener {
void onSomeVersesSelected(VersesView v);
void onNoVersesSelected(VersesView v);
void onVerseSingleClick(VersesView v, int verse_1);
}
public interface AttributeListener {
void onAttributeClick(Book book, int chapter_1, int verse_1, int kind);
}
public abstract static class XrefListener {
public abstract void onXrefClick(VersesView versesView, int ari, int which);
}
public interface OnVerseScrollListener {
void onVerseScroll(VersesView v, boolean isPericope, int verse_1, float prop);
void onScrollToTop(VersesView v);
}
private VerseAdapter adapter;
private SelectedVersesListener listener;
private VerseSelectionMode verseSelectionMode;
private Drawable originalSelector;
private OnVerseScrollListener onVerseScrollListener;
private AbsListView.OnScrollListener userOnScrollListener;
private int scrollState = 0;
private View[] scrollToVerseConvertViews;
public VersesView(Context context) {
super(context);
init();
}
public VersesView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
if (isInEditMode()) return;
originalSelector = getSelector();
setDivider(null);
setFocusable(false);
setAdapter(adapter = new VerseAdapter.Factory().create(getContext()));
setOnItemClickListener(itemClick);
setVerseSelectionMode(VerseSelectionMode.multiple);
super.setOnScrollListener(this);
}
@Override public final void setOnScrollListener(AbsListView.OnScrollListener l) {
userOnScrollListener = l;
}
@Override public VerseAdapter getAdapter() {
return adapter;
}
public void setParallelListener(CallbackSpan.OnClickListener parallelListener) {
adapter.setParallelListener(parallelListener);
}
public void setAttributeListener(VersesView.AttributeListener attributeListener) {
adapter.setAttributeListener(attributeListener);
}
public void setXrefListener(VersesView.XrefListener xrefListener) {
adapter.setXrefListener(xrefListener, this);
}
public void setVerseSelectionMode(VerseSelectionMode mode) {
this.verseSelectionMode = mode;
if (mode == VerseSelectionMode.singleClick) {
setSelector(originalSelector);
uncheckAll();
setChoiceMode(ListView.CHOICE_MODE_NONE);
} else if (mode == VerseSelectionMode.multiple) {
setSelector(new ColorDrawable(0x0));
setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
} else if (mode == VerseSelectionMode.none) {
setSelector(new ColorDrawable(0x0));
setChoiceMode(ListView.CHOICE_MODE_NONE);
}
}
public void setOnVerseScrollListener(OnVerseScrollListener onVerseScrollListener) {
this.onVerseScrollListener = onVerseScrollListener;
}
// TODO external should provide the attribute map into this widget similar to setData(),
// instead of this widget itself accessing persistent data.
// When this is done, we do not need to provide Book and chapter_1 as parameters to setData(),
// because in reality, VersesViews could contain verses taken from multiple books and chapters.
public void loadAttributeMap() {
adapter.loadAttributeMap();
}
public String getVerse(int verse_1) {
return adapter.getVerse(verse_1);
}
public void scrollToShowVerse(int mainVerse_1) {
int position = adapter.getPositionOfPericopeBeginningFromVerse(mainVerse_1);
if (Build.VERSION.SDK_INT >= 8) {
Api8.ListView_smoothScrollToPosition(this, position);
} else {
stopFling();
setSelectionFromTop(position, getVerticalFadingEdgeLength());
}
}
/**
* @return 1-based verse
*/
public int getVerseBasedOnScroll() {
return adapter.getVerseFromPosition(getPositionBasedOnScroll());
}
public int getPositionBasedOnScroll() {
int pos = getFirstVisiblePosition();
// check if the top one has been scrolled
View child = getChildAt(0);
if (child != null) {
int top = child.getTop();
if (top == 0) {
return pos;
}
int bottom = child.getBottom();
if (bottom > getVerticalFadingEdgeLength()) {
return pos;
} else {
return pos+1;
}
}
return pos;
}
public void setData(Book book, int chapter_1, SingleChapterVerses verses, int[] pericopeAris, PericopeBlock[] pericopeBlocks, int nblock, int[] xrefEntryCounts) {
adapter.setData(book, chapter_1, verses, pericopeAris, pericopeBlocks, nblock, xrefEntryCounts);
stopFling();
}
private OnItemClickListener itemClick = new OnItemClickListener() {
@Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (verseSelectionMode == VerseSelectionMode.singleClick) {
if (listener != null) listener.onVerseSingleClick(VersesView.this, adapter.getVerseFromPosition(position));
} else if (verseSelectionMode == VerseSelectionMode.multiple) {
adapter.notifyDataSetChanged();
hideOrShowContextMenuButton();
}
}
};
public void uncheckAll() {
SparseBooleanArray checkedPositions = getCheckedItemPositions();
if (checkedPositions != null && checkedPositions.size() > 0) {
for (int i = checkedPositions.size() - 1; i >= 0; i--) {
if (checkedPositions.valueAt(i)) {
setItemChecked(checkedPositions.keyAt(i), false);
}
}
}
if (listener != null) listener.onNoVersesSelected(this);
}
void hideOrShowContextMenuButton() {
if (verseSelectionMode != VerseSelectionMode.multiple) return;
SparseBooleanArray checkedPositions = getCheckedItemPositions();
boolean anyChecked = false;
for (int i = 0; i < checkedPositions.size(); i++) if (checkedPositions.valueAt(i)) {
anyChecked = true;
break;
}
if (anyChecked) {
if (listener != null) listener.onSomeVersesSelected(this);
} else {
if (listener != null) listener.onNoVersesSelected(this);
}
}
public IntArrayList getSelectedVerses_1() {
// count how many are selected
SparseBooleanArray positions = getCheckedItemPositions();
if (positions == null) {
return new IntArrayList(0);
}
IntArrayList res = new IntArrayList(positions.size());
for (int i = 0, len = positions.size(); i < len; i++) {
if (positions.valueAt(i)) {
int position = positions.keyAt(i);
int verse_1 = adapter.getVerseFromPosition(position);
if (verse_1 >= 1) res.add(verse_1);
}
}
return res;
}
@Override public Parcelable onSaveInstanceState() {
Bundle b = new Bundle();
Parcelable superState = super.onSaveInstanceState();
b.putParcelable("superState", superState);
b.putInt("verseSelectionMode", verseSelectionMode.ordinal());
return b;
}
@Override public void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
Bundle b = (Bundle) state;
super.onRestoreInstanceState(b.getParcelable("superState"));
setVerseSelectionMode(VerseSelectionMode.values()[b.getInt("verseSelectionMode")]);
}
hideOrShowContextMenuButton();
}
public boolean press(int keyCode) {
String volumeButtonsForNavigation = Preferences.getString(getContext().getString(R.string.pref_tombolVolumeBuatPindah_key), getContext().getString(R.string.pref_tombolVolumeBuatPindah_default));
if (U.equals(volumeButtonsForNavigation, "pasal" /* chapter */)) { //$NON-NLS-1$
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) keyCode = KeyEvent.KEYCODE_DPAD_RIGHT;
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) keyCode = KeyEvent.KEYCODE_DPAD_LEFT;
} else if (U.equals(volumeButtonsForNavigation, "ayat" /* verse */)) { //$NON-NLS-1$
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) keyCode = KeyEvent.KEYCODE_DPAD_DOWN;
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) keyCode = KeyEvent.KEYCODE_DPAD_UP;
}
if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
int oldPos = getPositionBasedOnScroll();
if (oldPos < adapter.getCount() - 1) {
stopFling();
setSelectionFromTop(oldPos+1, getVerticalFadingEdgeLength());
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
int oldPos = getPositionBasedOnScroll();
if (oldPos >= 1) {
int newPos = oldPos - 1;
while (newPos > 0) { // cek disabled, kalo iya, mundurin lagi
if (adapter.isEnabled(newPos)) break;
newPos--;
}
stopFling();
setSelectionFromTop(newPos, getVerticalFadingEdgeLength());
} else {
stopFling();
setSelectionFromTop(0, getVerticalFadingEdgeLength());
}
return true;
}
return false;
}
public void setDataWithRetainSelectedVerses(boolean retainSelectedVerses, Book book, int chapter_1, int[] pericope_aris, PericopeBlock[] pericope_blocks, int nblock, SingleChapterVerses verses, int[] xrefEntryCounts) {
IntArrayList selectedVerses_1 = null;
if (retainSelectedVerses) {
selectedVerses_1 = getSelectedVerses_1();
}
//# fill adapter with new data. make sure all checked states are reset
uncheckAll();
setData(book, chapter_1, verses, pericope_aris, pericope_blocks, nblock, xrefEntryCounts);
loadAttributeMap();
if (selectedVerses_1 != null) {
for (int i = 0, len = selectedVerses_1.size(); i < len; i++) {
int pos = adapter.getPositionIgnoringPericopeFromVerse(selectedVerses_1.get(i));
if (pos != -1) {
setItemChecked(pos, true);
}
}
}
}
public void scrollToVerse(int verse_1) {
final int position = adapter.getPositionOfPericopeBeginningFromVerse(verse_1);
if (position == -1) {
Log.w(TAG, "could not find verse=" + verse_1 + ", weird!"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
post(new Runnable() {
@Override public void run() {
// this may happen async from above, so check first if pos is still valid
if (position >= getCount()) return;
stopFling();
setSelectionFromTop(position, getVerticalFadingEdgeLength());
}
});
}
}
public void scrollToVerse(int verse_1, final float prop) {
final int position = adapter.getPositionIgnoringPericopeFromVerse(verse_1);
if (position == -1) {
Log.w(TAG, "could not find verse=" + verse_1 + ", weird!"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
post(new Runnable() {
@Override public void run() {
// this may happen async from above, so check first if pos is still valid
if (position >= getCount()) return;
boolean needMeasure = false;
int shifty = getVerticalFadingEdgeLength();
int firstPos = getFirstVisiblePosition();
if (position >= firstPos) {
int lastPos = getLastVisiblePosition();
if (position <= lastPos) {
// we have this on screen, no need to measure again
View child = getChildAt(position - firstPos);
stopFling();
setSelectionFromTop(position, shifty - (int) (prop * child.getHeight()));
} else {
needMeasure = true;
}
} else {
needMeasure = true;
}
if (needMeasure) {
// initialize scrollToVerseConvertViews if needed
if (scrollToVerseConvertViews == null) {
scrollToVerseConvertViews = new View[adapter.getViewTypeCount()];
}
int itemType = adapter.getItemViewType(position);
View convertView = scrollToVerseConvertViews[itemType];
View child = adapter.getView(position, convertView, VersesView.this);
child.measure(MeasureSpec.makeMeasureSpec(VersesView.this.getWidth() - VersesView.this.getPaddingLeft() - VersesView.this.getPaddingRight(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
scrollToVerseConvertViews[itemType] = child;
stopFling();
setSelectionFromTop(position, shifty - (int) (prop * child.getMeasuredHeight()));
}
}
});
}
}
public void scrollToTop() {
post(new Runnable() {
@Override public void run() {
setSelectionFromTop(0, 0);
}
});
}
public void setSelectedVersesListener(SelectedVersesListener listener) {
this.listener = listener;
}
@Override public void onScrollStateChanged(AbsListView view, int scrollState) {
if (userOnScrollListener != null) userOnScrollListener.onScrollStateChanged(view, scrollState);
this.scrollState = scrollState;
}
@Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (userOnScrollListener != null) userOnScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
if (onVerseScrollListener == null) return;
if (view.getChildCount() > 0) {
float prop = 0.f;
int position = -1;
View firstChild = view.getChildAt(0);
// if first child is on top, top == fading edge length
int bottom = firstChild.getBottom();
int remaining = bottom - view.getVerticalFadingEdgeLength();
if (remaining >= 0) {
position = firstVisibleItem;
prop = 1.f - (float) remaining / firstChild.getHeight();
} else { // we should have a second child
if (view.getChildCount() > 1) {
View secondChild = view.getChildAt(1);
position = firstVisibleItem + 1;
prop = (float) -remaining / secondChild.getHeight();
}
}
int verse_1 = adapter.getVerseOrPericopeFromPosition(position);
if (scrollState != AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
if (verse_1 > 0) {
onVerseScrollListener.onVerseScroll(this, false, verse_1, prop);
} else {
onVerseScrollListener.onVerseScroll(this, true, 0, 0);
}
if (position == 0 && prop == 0.f) {
onVerseScrollListener.onScrollToTop(this);
}
}
}
}
public void setDataEmpty() {
adapter.setDataEmpty();
}
public void stopFling() {
StopListFling.stop(this);
}
}
| Open actionmode after switching version when selecting some verses
| Alkitab/src/yuku/alkitab/base/widget/VersesView.java | Open actionmode after switching version when selecting some verses | <ide><path>lkitab/src/yuku/alkitab/base/widget/VersesView.java
<ide> this.onVerseScrollListener = onVerseScrollListener;
<ide> }
<ide>
<del> // TODO external should provide the attribute map into this widget similar to setData(),
<add> // TODO external should provide the attribute map into this widget similar to setData(),
<ide> // instead of this widget itself accessing persistent data.
<ide> // When this is done, we do not need to provide Book and chapter_1 as parameters to setData(),
<ide> // because in reality, VersesViews could contain verses taken from multiple books and chapters.
<ide> public int getPositionBasedOnScroll() {
<ide> int pos = getFirstVisiblePosition();
<ide>
<del> // check if the top one has been scrolled
<del> View child = getChildAt(0);
<add> // check if the top one has been scrolled
<add> View child = getChildAt(0);
<ide> if (child != null) {
<ide> int top = child.getTop();
<ide> if (top == 0) {
<ide> SparseBooleanArray checkedPositions = getCheckedItemPositions();
<ide> boolean anyChecked = false;
<ide> for (int i = 0; i < checkedPositions.size(); i++) if (checkedPositions.valueAt(i)) {
<del> anyChecked = true;
<add> anyChecked = true;
<ide> break;
<ide> }
<ide>
<ide> setData(book, chapter_1, verses, pericope_aris, pericope_blocks, nblock, xrefEntryCounts);
<ide> loadAttributeMap();
<ide>
<add> boolean anySelected = false;
<ide> if (selectedVerses_1 != null) {
<ide> for (int i = 0, len = selectedVerses_1.size(); i < len; i++) {
<ide> int pos = adapter.getPositionIgnoringPericopeFromVerse(selectedVerses_1.get(i));
<ide> if (pos != -1) {
<ide> setItemChecked(pos, true);
<del> }
<del> }
<add> anySelected = true;
<add> }
<add> }
<add> }
<add>
<add> if (anySelected) {
<add> if (listener != null) listener.onSomeVersesSelected(this);
<ide> }
<ide> }
<ide> |
|
JavaScript | mit | ff3b174a0397fabacea2e0fe483cd57dbcc0ee3f | 0 | VishalRohra/chroma-tone,VishalRohra/chroma-tone,conundrumer/sim-seq,conundrumer/sim-seq,conundrumer/chroma-tone,conundrumer/chroma-tone | 'use strict';
var savedLinesReader = require('../saved-lines-reader');
var React = require('react');
var Display = require('./Display');
require('buffer');
var Track = require('../track').Track;
var OldTrack = require('../track').OldTrack;
var DEBUG = false;
var defaultLines = [
{
x1: 15,
y1: 180,
x2: 190,
y2: 190,
extended: 0,
flipped: false,
leftLine: null,
rightLine: null,
id: 0,
type: 0
}
];
var App = React.createClass({
getInitialState() {
return {
tracks: [],
track: new Track(defaultLines, {x: 0, y: 0}, DEBUG),
selected: '',
timer: false,
frame: 0,
grid: false,
slowmo: false,
floor: false,
accArrow: false,
snapDot: false,
color: false
};
},
onSelectTrack(e) {
let trackData = this.state.tracks[e.target.value];
let startPos = trackData.startPosition;
let version = trackData.version;
let VersionedTrack = Track;
if (version === '6.1') {
VersionedTrack = OldTrack;
}
let track = new VersionedTrack(trackData.lines, { x: startPos[0], y: startPos[1] }, DEBUG);
console.log(track)
track.label = trackData.label;
this.setState({
track: track,
selected: e.target.value
});
this.stopPlayback();
},
onTogglePlayback() {
if (!this.state.timer) {
var step = () => {
let timer = setTimeout(step, 1000 / this.getFPS());
this.setState({ frame: this.state.frame + 1, timer: timer });
};
step();
} else {
this.stopPlayback();
}
},
stopPlayback() {
clearTimeout(this.state.timer);
this.setState({ frame: 0, timer: null });
},
onPause() {
clearTimeout(this.state.timer);
this.setState({ timer: null });
},
onToggle(key) {
return () => {
let nextState = {};
nextState[key] = !this.state[key];
this.setState(nextState);
};
},
onFileInput(e) {
var reader = new FileReader();
var file = e.target.files[0];
if (!file) {
return;
}
reader.onload = (upload) => {
try {
this.setState({
tracks: savedLinesReader(new Buffer(new Uint8Array(upload.target.result))),
track: null,
selected: ''
});
this.stopPlayback();
} catch (e) {
alert(`There is something wrong with this .sol!\n${e}`);
}
};
reader.readAsArrayBuffer(file);
},
getRider() {
return this.state.track.getRiderAtFrame(this.state.frame);
},
getFPS() {
let fps = 40;
return this.state.slowmo ? fps / 8 : fps;
},
renderToggle(key) {
if (this.state[key] === undefined) {
throw new Error('Key does not exist in state, cannot toggle: ', key);
}
return (
<p key={key}>
{key}: <input type="checkbox" checked={this.state[key]} onChange={this.onToggle(key)} />
</p>
);
},
render() {
return (
<div>
<p>Input a .sol file to view your tracks.</p>
<p><input type="file" onChange={this.onFileInput} /></p>
<p>
{
this.state.tracks.length > 0 ?
<select value={this.state.selected} onChange={this.onSelectTrack}>
<option key="-1" value="" disabled>Select a track to render...</option>
{
this.state.tracks.map((track, i) =>
<option key={i} value={i}>{track.label}</option>
)
}
</select>
: null
}
</p>
{
this.state.track ?
<p>
<b>Track name:</b> { this.state.tracks[this.state.selected].label } <br/>
<b>Version:</b> { this.state.tracks[this.state.selected].version }
</p>
: null
}
{ ['grid', 'color'].map(this.renderToggle) }
{
this.state.color ?
['floor', 'accArrow', 'snapDot'].map(this.renderToggle)
: null
}
{
this.state.track ?
<div>
{ this.renderToggle('slowmo') }
<button onClick={() => {console.log(this.state.track.lines)}}>Print lines</button>
<button onClick={this.onTogglePlayback}>{ this.state.timer ? 'Stop' : 'Play'}</button>
<button onClick={this.onPause}>Pause</button>
<button onClick={() => this.setState({ frame: this.state.frame + 1 })}>Step forward</button>
<button onClick={() => this.setState({ frame: Math.max(0, this.state.frame - 1) })}>Step backward</button>
</div>
: null
}
{
this.state.track ?
<Display {...this.state} rider={this.getRider()} />
: null
}
</div>
);
}
});
module.exports = App;
| saved-lines-renderer/src/components/App.js | 'use strict';
var savedLinesReader = require('../saved-lines-reader');
var React = require('react');
var Display = require('./Display');
require('buffer');
var Track = require('../track').Track;
var OldTrack = require('../track').OldTrack;
var DEBUG = false;
var defaultLines = [
{
x1: 15,
y1: 180,
x2: 190,
y2: 190,
extended: 0,
flipped: false,
leftLine: null,
rightLine: null,
id: 0,
type: 0
}
];
var App = React.createClass({
getInitialState() {
return {
tracks: [],
track: new Track(defaultLines, {x: 0, y: 0}, DEBUG),
selected: '',
timer: false,
frame: 0,
grid: false,
slowmo: false,
floor: false,
accArrow: false,
snapDot: false,
color: false
};
},
onSelectTrack(e) {
let trackData = this.state.tracks[e.target.value];
let startPos = trackData.startPosition;
let version = trackData.version;
let VersionedTrack = Track;
if (version === '6.1') {
VersionedTrack = OldTrack;
}
let track = new VersionedTrack(trackData.lines, { x: startPos[0], y: startPos[1] }, DEBUG);
console.log(track)
track.label = trackData.label;
this.setState({
track: track,
selected: e.target.value
});
this.stopPlayback();
},
onTogglePlayback() {
if (!this.state.timer) {
var step = () => {
let timer = setTimeout(step, 1000 / this.getFPS());
this.setState({ frame: this.state.frame + 1, timer: timer });
};
step();
} else {
this.stopPlayback();
}
},
stopPlayback() {
clearTimeout(this.state.timer);
this.setState({ frame: 0, timer: null });
},
onPause() {
clearTimeout(this.state.timer);
this.setState({ timer: null });
},
onToggle(key) {
return () => {
let nextState = {};
nextState[key] = !this.state[key];
this.setState(nextState);
};
},
onFileInput(e) {
var reader = new FileReader();
var file = e.target.files[0];
if (!file) {
return;
}
reader.onload = (upload) => {
try {
this.setState({
tracks: savedLinesReader(new Buffer(new Uint8Array(upload.target.result))),
track: null,
selected: ''
});
this.stopPlayback();
} catch (e) {
alert(`There is something wrong with this .sol!\n${e}`);
}
};
reader.readAsArrayBuffer(file);
},
getRider() {
return this.state.track.getRiderAtFrame(this.state.frame);
},
getFPS() {
let fps = 40;
return this.state.slowmo ? fps / 8 : fps;
},
renderToggle(key) {
if (this.state[key] === undefined) {
throw new Error('Key does not exist in state, cannot toggle: ', key);
}
return (
<p key={key}>
{key}: <input type="checkbox" checked={this.state[key]} onChange={this.onToggle(key)} />
</p>
);
},
render() {
return (
<div>
<p>Input a .sol file to view your tracks.</p>
<p><input type="file" onChange={this.onFileInput} /></p>
<p>
{
this.state.tracks.length > 0 ?
<select value={this.state.selected} onChange={this.onSelectTrack}>
<option key="-1" value="" disabled>Select a track to render...</option>
{
this.state.tracks.map((track, i) =>
<option key={i} value={i}>{track.label}</option>
)
}
</select>
: null
}
</p>
{ ['grid', 'color'].map(this.renderToggle) }
{
this.state.color ?
['floor', 'accArrow', 'snapDot'].map(this.renderToggle)
: null
}
{
this.state.track ?
<div>
{ this.renderToggle('slowmo') }
<button onClick={() => {console.log(this.state.track.lines)}}>Print lines</button>
<button onClick={this.onTogglePlayback}>{ this.state.timer ? 'Stop' : 'Play'}</button>
<button onClick={this.onPause}>Pause</button>
<button onClick={() => this.setState({ frame: this.state.frame + 1 })}>Step forward</button>
<button onClick={() => this.setState({ frame: Math.max(0, this.state.frame - 1) })}>Step backward</button>
</div>
: null
}
{
this.state.track ?
<Display {...this.state} rider={this.getRider()} />
: null
}
</div>
);
}
});
module.exports = App;
| add track name and version labels
| saved-lines-renderer/src/components/App.js | add track name and version labels | <ide><path>aved-lines-renderer/src/components/App.js
<ide> : null
<ide> }
<ide> </p>
<add> {
<add> this.state.track ?
<add> <p>
<add> <b>Track name:</b> { this.state.tracks[this.state.selected].label } <br/>
<add> <b>Version:</b> { this.state.tracks[this.state.selected].version }
<add> </p>
<add> : null
<add> }
<ide> { ['grid', 'color'].map(this.renderToggle) }
<ide> {
<ide> this.state.color ? |
|
Java | apache-2.0 | 218c810817eb3f3cc0c82ce4bdadd88dfd41c478 | 0 | eminn/hazelcast-simulator,gAmUssA/hazelcast-simulator,fengshao0907/hazelcast-simulator,Danny-Hazelcast/hazelcast-stabilizer,fengshao0907/hazelcast-simulator,jerrinot/hazelcast-stabilizer,hazelcast/hazelcast-simulator,hasancelik/hazelcast-stabilizer,jerrinot/hazelcast-stabilizer,pveentjer/hazelcast-simulator,hasancelik/hazelcast-stabilizer,Danny-Hazelcast/hazelcast-stabilizer,hazelcast/hazelcast-simulator,pveentjer/hazelcast-simulator,Donnerbart/hazelcast-simulator,hazelcast/hazelcast-simulator,eminn/hazelcast-simulator,gAmUssA/hazelcast-simulator,Donnerbart/hazelcast-simulator | package com.hazelcast.stabilizer.coordinator;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import com.hazelcast.stabilizer.tests.Failure;
import java.io.File;
import java.util.List;
import static com.hazelcast.stabilizer.Utils.appendText;
import static com.hazelcast.stabilizer.Utils.sleepSeconds;
class FailureMonitorThread extends Thread {
private final Coordinator coordinator;
private final ILogger log = Logger.getLogger(FailureMonitorThread.class);
private final File file;
public FailureMonitorThread(Coordinator coordinator) {
super("FailureMonitorThread");
file = new File("failures-" + coordinator.testSuite.id + ".txt");
if (coordinator == null) {
throw new NullPointerException();
}
this.coordinator = coordinator;
this.setDaemon(true);
}
public void run() {
for (; ; ) {
try {
//todo: this delay should be configurable.
sleepSeconds(1);
scan();
} catch (Throwable e) {
log.severe(e);
}
}
}
private void scan() {
List<Failure> failures = coordinator.agentsClient.getFailures();
for (Failure failure : failures) {
coordinator.failureList.add(failure);
log.warning(buildMessage(failure));
appendText(failure.toString() + "\n", file);
}
}
private String buildMessage(Failure failure) {
StringBuilder sb = new StringBuilder();
sb.append("Failure #").append(coordinator.failureList.size()).append(" ");
if (failure.workerAddress != null) {
sb.append(' ');
sb.append(failure.workerAddress);
sb.append(' ');
} else if (failure.agentAddress != null) {
sb.append(' ');
sb.append(failure.agentAddress);
sb.append(' ');
}
sb.append(failure.type);
if (failure.cause != null) {
String[] lines = failure.cause.split("\n");
if (lines.length > 0) {
sb.append("[");
sb.append(lines[0]);
sb.append("]");
}
}
return sb.toString();
}
}
| stabilizer/src/main/java/com/hazelcast/stabilizer/coordinator/FailureMonitorThread.java | package com.hazelcast.stabilizer.coordinator;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import com.hazelcast.stabilizer.tests.Failure;
import java.io.File;
import java.util.List;
import static com.hazelcast.stabilizer.Utils.appendText;
import static com.hazelcast.stabilizer.Utils.sleepSeconds;
class FailureMonitorThread extends Thread {
private final Coordinator coordinator;
private final ILogger log = Logger.getLogger(FailureMonitorThread.class);
private final File file = new File("failures-" + System.currentTimeMillis() + ".txt");
public FailureMonitorThread(Coordinator coordinator) {
super("FailureMonitorThread");
if (coordinator == null) {
throw new NullPointerException();
}
this.coordinator = coordinator;
this.setDaemon(true);
}
public void run() {
for (; ; ) {
try {
//todo: this delay should be configurable.
sleepSeconds(1);
scan();
} catch (Throwable e) {
log.severe(e);
}
}
}
private void scan() {
List<Failure> failures = coordinator.agentsClient.getFailures();
for (Failure failure : failures) {
coordinator.failureList.add(failure);
log.warning(buildMessage(failure));
appendText(failure.toString() + "\n", file);
}
}
private String buildMessage(Failure failure) {
StringBuilder sb = new StringBuilder();
sb.append("Failure #").append(coordinator.failureList.size()).append(" ");
if (failure.workerAddress != null) {
sb.append(' ');
sb.append(failure.workerAddress);
sb.append(' ');
} else if (failure.agentAddress != null) {
sb.append(' ');
sb.append(failure.agentAddress);
sb.append(' ');
}
sb.append(failure.type);
if (failure.cause != null) {
String[] lines = failure.cause.split("\n");
if (lines.length > 0) {
sb.append("[");
sb.append(lines[0]);
sb.append("]");
}
}
return sb.toString();
}
}
| #169, the filename of failures-xxx.txt now matching up with the directory name worker/xxx
| stabilizer/src/main/java/com/hazelcast/stabilizer/coordinator/FailureMonitorThread.java | #169, the filename of failures-xxx.txt now matching up with the directory name worker/xxx | <ide><path>tabilizer/src/main/java/com/hazelcast/stabilizer/coordinator/FailureMonitorThread.java
<ide> class FailureMonitorThread extends Thread {
<ide> private final Coordinator coordinator;
<ide> private final ILogger log = Logger.getLogger(FailureMonitorThread.class);
<del> private final File file = new File("failures-" + System.currentTimeMillis() + ".txt");
<add> private final File file;
<ide>
<ide> public FailureMonitorThread(Coordinator coordinator) {
<ide> super("FailureMonitorThread");
<add>
<add> file = new File("failures-" + coordinator.testSuite.id + ".txt");
<ide>
<ide> if (coordinator == null) {
<ide> throw new NullPointerException(); |
|
Java | mit | f898bd28bf6758381c56898707cf3023f22f67db | 0 | jhshinn/jabref,zellerdev/jabref,mredaelli/jabref,mredaelli/jabref,sauliusg/jabref,bartsch-dev/jabref,ayanai1/jabref,shitikanth/jabref,mairdl/jabref,mairdl/jabref,jhshinn/jabref,oscargus/jabref,sauliusg/jabref,zellerdev/jabref,Mr-DLib/jabref,tobiasdiez/jabref,obraliar/jabref,Mr-DLib/jabref,Mr-DLib/jabref,tschechlovdev/jabref,bartsch-dev/jabref,oscargus/jabref,Siedlerchr/jabref,oscargus/jabref,grimes2/jabref,zellerdev/jabref,tobiasdiez/jabref,oscargus/jabref,mairdl/jabref,JabRef/jabref,tschechlovdev/jabref,tobiasdiez/jabref,obraliar/jabref,Braunch/jabref,motokito/jabref,oscargus/jabref,Siedlerchr/jabref,motokito/jabref,tschechlovdev/jabref,zellerdev/jabref,ayanai1/jabref,sauliusg/jabref,JabRef/jabref,obraliar/jabref,Braunch/jabref,mairdl/jabref,Braunch/jabref,tschechlovdev/jabref,mairdl/jabref,shitikanth/jabref,tobiasdiez/jabref,sauliusg/jabref,Braunch/jabref,motokito/jabref,obraliar/jabref,Mr-DLib/jabref,ayanai1/jabref,tschechlovdev/jabref,shitikanth/jabref,obraliar/jabref,mredaelli/jabref,jhshinn/jabref,grimes2/jabref,mredaelli/jabref,jhshinn/jabref,JabRef/jabref,shitikanth/jabref,grimes2/jabref,ayanai1/jabref,Siedlerchr/jabref,bartsch-dev/jabref,zellerdev/jabref,grimes2/jabref,shitikanth/jabref,JabRef/jabref,Siedlerchr/jabref,Mr-DLib/jabref,bartsch-dev/jabref,ayanai1/jabref,grimes2/jabref,jhshinn/jabref,mredaelli/jabref,bartsch-dev/jabref,motokito/jabref,motokito/jabref,Braunch/jabref | /*
Copyright (C) 2003 David Weitzman, Morten O. Alver
All programs in this directory and
subdirectories are published under the GNU General Public License as
described below.
This program 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 2 of the License, or (at
your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA
Further information about the GNU GPL is available at:
http://www.gnu.org/copyleft/gpl.ja.html
Note:
Modified for use in JabRef.
*/
package net.sf.jabref.model.entry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* Abstract base class for all BibTex entry types.
*/
public abstract class BibLatexEntryType implements EntryType {
private final List<String> requiredFields;
private final List<String> optionalFields;
public BibLatexEntryType() {
requiredFields = new ArrayList<>();
optionalFields = new ArrayList<>();
}
@Override
public List<String> getOptionalFields() {
return Collections.unmodifiableList(optionalFields);
}
@Override
public List<String> getRequiredFields() {
return Collections.unmodifiableList(requiredFields);
}
void addAllOptional(String... fieldNames) {
optionalFields.addAll(Arrays.asList(fieldNames));
}
void addAllRequired(String... fieldNames) {
requiredFields.addAll(Arrays.asList(fieldNames));
}
public List<String> getPrimaryOptionalFields() {
return getOptionalFields();
}
public List<String> getSecondaryOptionalFields() {
List<String> optionalFields = getOptionalFields();
if (optionalFields == null) {
return new ArrayList<>(0);
}
return optionalFields.stream().filter(field -> !isPrimary(field)).collect(Collectors.toList());
}
private boolean isPrimary(String field) {
List<String> primaryFields = getPrimaryOptionalFields();
if (primaryFields == null) {
return false;
}
return primaryFields.contains(field);
}
@Override
public int compareTo(EntryType o) {
return getName().compareTo(o.getName());
}
}
| src/main/java/net/sf/jabref/model/entry/BibLatexEntryType.java | /*
Copyright (C) 2003 David Weitzman, Morten O. Alver
All programs in this directory and
subdirectories are published under the GNU General Public License as
described below.
This program 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 2 of the License, or (at
your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA
Further information about the GNU GPL is available at:
http://www.gnu.org/copyleft/gpl.ja.html
Note:
Modified for use in JabRef.
*/
package net.sf.jabref.model.entry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* Abstract base class for all BibTex entry types.
*/
public abstract class BibLatexEntryType implements EntryType {
private final List<String> requiredFields;
private final List<String> optionalFields;
public BibLatexEntryType() {
requiredFields = new ArrayList<>();
optionalFields = new ArrayList<>();
// key is always required
requiredFields.add("bibtexkey");
}
@Override
public List<String> getOptionalFields() {
return Collections.unmodifiableList(optionalFields);
}
@Override
public List<String> getRequiredFields() {
return Collections.unmodifiableList(requiredFields);
}
void addAllOptional(String... fieldNames) {
optionalFields.addAll(Arrays.asList(fieldNames));
}
void addAllRequired(String... fieldNames) {
requiredFields.addAll(Arrays.asList(fieldNames));
}
public List<String> getPrimaryOptionalFields() {
return getOptionalFields();
}
public List<String> getSecondaryOptionalFields() {
List<String> optionalFields = getOptionalFields();
if (optionalFields == null) {
return new ArrayList<>(0);
}
return optionalFields.stream().filter(field -> !isPrimary(field)).collect(Collectors.toList());
}
private boolean isPrimary(String field) {
List<String> primaryFields = getPrimaryOptionalFields();
if (primaryFields == null) {
return false;
}
return primaryFields.contains(field);
}
@Override
public int compareTo(EntryType o) {
return getName().compareTo(o.getName());
}
}
| Key is validated independently from entry
| src/main/java/net/sf/jabref/model/entry/BibLatexEntryType.java | Key is validated independently from entry | <ide><path>rc/main/java/net/sf/jabref/model/entry/BibLatexEntryType.java
<ide> public BibLatexEntryType() {
<ide> requiredFields = new ArrayList<>();
<ide> optionalFields = new ArrayList<>();
<del>
<del> // key is always required
<del> requiredFields.add("bibtexkey");
<ide> }
<ide>
<ide> @Override |
|
Java | mit | 2cecb35b1a786bde8c207e0fefe44b419d190856 | 0 | juckele/vivarium,juckele/vivarium,juckele/vivarium | /*
* Copyright © 2015 John H Uckele. All rights reserved.
*/
package io.vivarium.visualization;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import io.vivarium.core.brain.Brain;
import io.vivarium.core.brain.RandomBrain;
public class BrainViewerDemo extends JPanel implements GraphicalController
{
private static JFrame _window;
private static final long serialVersionUID = -3105685457075818705L;
// Animation variables
private SwingGeometricGraphics _swingGraphics;
public BrainViewerDemo(Brain brain)
{
_swingGraphics = new SwingGeometricGraphics(this, this);
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// Get the graphics for the graphical delegate
Graphics2D g2 = (Graphics2D) g;
_swingGraphics.setResources(g2);
// Hand off to the graphical delegate to perform the render
_swingGraphics.executeRender();
}
public static void main(String[] args)
{
Brain brain = new RandomBrain(4);
// Create and show the window
BrainViewerDemo bv = new BrainViewerDemo(brain);
_window = new JFrame();
_window.add(bv);
_window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
_window.validate();
// Set everything to be visible
_window.setSize(100, 100);
_window.setVisible(true);
}
@Override
public void onRender(GeometricGraphics graphics)
{
graphics.drawRectangle(10, 10, 30, 30);
}
}
| vivarium-swing/src/main/java/io/vivarium/visualization/BrainViewerDemo.java | /*
* Copyright © 2015 John H Uckele. All rights reserved.
*/
package io.vivarium.visualization;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import io.vivarium.core.brain.Brain;
import io.vivarium.core.brain.RandomBrain;
import io.vivarium.visualization.animation.ThreadScheduler;
import io.vivarium.visualization.animation.Visualizer;
public class BrainViewerDemo extends JPanel implements GraphicalController
{
private static JFrame _window;
private static final long serialVersionUID = -3105685457075818705L;
// Simulation variables
private Visualizer _visualizer;
// Animation variables
private SwingGeometricGraphics _swingGraphics;
private ThreadScheduler _threadScheduler;
// UI variables
private long _lastMouseEvent = System.currentTimeMillis();
private boolean _cursorHidden = false;
public BrainViewerDemo(Brain brain)
{
_swingGraphics = new SwingGeometricGraphics(this, this);
_threadScheduler = new ThreadScheduler();
// _visualizer = new Visualizer(brain, _swingGraphics, _threadScheduler);
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// Get the graphics for the graphical delegate
Graphics2D g2 = (Graphics2D) g;
_swingGraphics.setResources(g2);
// Hand off to the graphical delegate to perform the render
_swingGraphics.executeRender();
}
public static void main(String[] args)
{
Brain brain = new RandomBrain(4);
// Create and show the window
BrainViewerDemo bv = new BrainViewerDemo(brain);
_window = new JFrame();
_window.add(bv);
_window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
_window.validate();
// Set everything to be visible
_window.setSize(100, 100);
_window.setVisible(true);
}
@Override
public void onRender(GeometricGraphics graphics)
{
graphics.drawRectangle(10, 10, 30, 30);
}
}
| Removed unused variables
| vivarium-swing/src/main/java/io/vivarium/visualization/BrainViewerDemo.java | Removed unused variables | <ide><path>ivarium-swing/src/main/java/io/vivarium/visualization/BrainViewerDemo.java
<ide>
<ide> import io.vivarium.core.brain.Brain;
<ide> import io.vivarium.core.brain.RandomBrain;
<del>import io.vivarium.visualization.animation.ThreadScheduler;
<del>import io.vivarium.visualization.animation.Visualizer;
<ide>
<ide> public class BrainViewerDemo extends JPanel implements GraphicalController
<ide> {
<ide>
<ide> private static final long serialVersionUID = -3105685457075818705L;
<ide>
<del> // Simulation variables
<del> private Visualizer _visualizer;
<del>
<ide> // Animation variables
<ide> private SwingGeometricGraphics _swingGraphics;
<del> private ThreadScheduler _threadScheduler;
<del>
<del> // UI variables
<del> private long _lastMouseEvent = System.currentTimeMillis();
<del> private boolean _cursorHidden = false;
<ide>
<ide> public BrainViewerDemo(Brain brain)
<ide> {
<ide> _swingGraphics = new SwingGeometricGraphics(this, this);
<del> _threadScheduler = new ThreadScheduler();
<del> // _visualizer = new Visualizer(brain, _swingGraphics, _threadScheduler);
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | 4bad336d6cdae087bfbe044a647f171e02b75d41 | 0 | MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim | package gcm.gui;
import gcm.parser.GCMFile;
import gcm.util.GlobalConstants;
import gcm.util.Utility;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Properties;
import javax.swing.DefaultListModel;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.sbml.libsbml.Species;
import sbmleditor.MySpecies;
import main.Gui;
public class SpeciesPanel extends JPanel implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* calls constructor to construct the panel
*
* @param selected
* @param speciesList
* @param influencesList
* @param conditionsList
* @param componentsList
* @param gcm
* @param paramsOnly
* @param refGCM
* @param gcmEditor
*/
public SpeciesPanel(String selected, PropertyList speciesList, PropertyList influencesList,
PropertyList conditionsList, PropertyList componentsList, GCMFile gcm, boolean paramsOnly,
GCMFile refGCM, GCM2SBMLEditor gcmEditor, boolean inTab){
super(new BorderLayout());
constructor(selected, speciesList, influencesList, conditionsList, componentsList, gcm,
paramsOnly, refGCM, gcmEditor, inTab);
}
/**
* constructs the species panel
*
* @param selected
* @param speciesList
* @param influencesList
* @param conditionsList
* @param componentsList
* @param gcm
* @param paramsOnly
* @param refGCM
* @param gcmEditor
*/
private void constructor(String selected, PropertyList speciesList, PropertyList influencesList,
PropertyList conditionsList, PropertyList componentsList, GCMFile gcm, boolean paramsOnly,
GCMFile refGCM, GCM2SBMLEditor gcmEditor, boolean inTab) {
JPanel grid;
//if this is in analysis mode, only show the sweepable/changeable values
if (paramsOnly)
grid = new JPanel(new GridLayout(7,1));
else {
if (gcm.getSBMLDocument().getLevel() > 2) {
if (gcm.getSBMLDocument().getModel().getNumCompartments() == 1) {
grid = new JPanel(new GridLayout(16,1));
}
else {
grid = new JPanel(new GridLayout(17,1));
}
}
else {
if (gcm.getSBMLDocument().getModel().getNumCompartments() == 1) {
grid = new JPanel(new GridLayout(15,1));
}
else {
grid = new JPanel(new GridLayout(16,1));
}
}
}
this.add(grid, BorderLayout.CENTER);
this.selected = selected;
this.speciesList = speciesList;
this.influences = influencesList;
this.conditions = conditionsList;
this.components = componentsList;
this.gcm = gcm;
this.paramsOnly = paramsOnly;
this.gcmEditor = gcmEditor;
fields = new HashMap<String, PropertyField>();
sbolFields = new HashMap<String, SbolField>();
String origString = "default";
PropertyField field = null;
// ID field
field = new PropertyField(GlobalConstants.ID, "", null, null, Utility.IDstring,
paramsOnly, "default");
fields.put(GlobalConstants.ID, field);
if (!paramsOnly) grid.add(field);
// Name field
field = new PropertyField(GlobalConstants.NAME, "", null, null, Utility.NAMEstring,
paramsOnly, "default");
fields.put(GlobalConstants.NAME, field);
if (!paramsOnly) grid.add(field);
// Type field
JPanel tempPanel = new JPanel();
JLabel tempLabel = new JLabel(GlobalConstants.TYPE);
typeBox = new JComboBox(types);
//disallow input/output types for species in an enclosed GCM
if (gcm.getIsWithinCompartment()) {
typeBox.removeItem(GlobalConstants.INPUT);
typeBox.removeItem(GlobalConstants.OUTPUT);
}
typeBox.addActionListener(this);
tempPanel.setLayout(new GridLayout(1, 2));
tempPanel.add(tempLabel);
tempPanel.add(typeBox);
if (!paramsOnly) grid.add(tempPanel);
Species species = gcm.getSBMLDocument().getModel().getSpecies(selected);
// compartment field
tempPanel = new JPanel();
tempLabel = new JLabel("Compartment");
compartBox = MySpecies.createCompartmentChoices(gcm.getSBMLDocument());
compartBox.setSelectedItem(species.getCompartment());
compartBox.addActionListener(this);
tempPanel.setLayout(new GridLayout(1, 2));
tempPanel.add(tempLabel);
tempPanel.add(compartBox);
if (gcm.getSBMLDocument().getModel().getNumCompartments() > 1) {
if (!paramsOnly) grid.add(tempPanel);
}
String[] optionsTF = { "true", "false" };
// Boundary condition field
tempPanel = new JPanel();
tempLabel = new JLabel("Boundary Condition");
specBoundary = new JComboBox(optionsTF);
if (species.getBoundaryCondition()) {
specBoundary.setSelectedItem("true");
}
else {
specBoundary.setSelectedItem("false");
}
tempPanel.setLayout(new GridLayout(1, 2));
tempPanel.add(tempLabel);
tempPanel.add(specBoundary);
if (!paramsOnly) grid.add(tempPanel);
// Constant field
tempPanel = new JPanel();
tempLabel = new JLabel("Constant");
specConstant = new JComboBox(optionsTF);
if (species.getConstant()) {
specConstant.setSelectedItem("true");
}
else {
specConstant.setSelectedItem("false");
}
tempPanel.setLayout(new GridLayout(1, 2));
tempPanel.add(tempLabel);
tempPanel.add(specConstant);
if (!paramsOnly) grid.add(tempPanel);
// Has only substance units field
tempPanel = new JPanel();
tempLabel = new JLabel("Has Only Substance Units");
specHasOnly = new JComboBox(optionsTF);
if (species.getHasOnlySubstanceUnits()) {
specHasOnly.setSelectedItem("true");
}
else {
specHasOnly.setSelectedItem("false");
}
tempPanel.setLayout(new GridLayout(1, 2));
tempPanel.add(tempLabel);
tempPanel.add(specHasOnly);
if (!paramsOnly) grid.add(tempPanel);
// Units field
tempPanel = new JPanel();
tempLabel = new JLabel("Units");
unitsBox = MySpecies.createUnitsChoices(gcm.getSBMLDocument());
if (species.isSetUnits()) {
unitsBox.setSelectedItem(species.getUnits());
}
tempPanel.setLayout(new GridLayout(1, 2));
tempPanel.add(tempLabel);
tempPanel.add(unitsBox);
if (!paramsOnly) grid.add(tempPanel);
// Conversion factor field
if (gcm.getSBMLDocument().getLevel() > 2) {
tempPanel = new JPanel();
tempLabel = new JLabel("Conversion Factor");
convBox = MySpecies.createConversionFactorChoices(gcm.getSBMLDocument());
if (species.isSetConversionFactor()) {
convBox.setSelectedItem(species.getConversionFactor());
}
tempPanel.setLayout(new GridLayout(1, 2));
tempPanel.add(tempLabel);
tempPanel.add(convBox);
if (!paramsOnly) grid.add(tempPanel);
}
//mark as interesting field
if (paramsOnly) {
String thresholdText = "";
boolean speciesMarked = false;
ArrayList<String> interestingSpecies = gcmEditor.getReb2Sac().getInterestingSpeciesAsArrayList();
//look for the selected species among the already-interesting
//if it is interesting, populate the field with its data
for (String speciesInfo : interestingSpecies) {
if (speciesInfo.split(" ")[0].equals(selected)) {
speciesMarked = true;
thresholdText = speciesInfo.replace(selected, "").trim();
break;
}
}
tempPanel = new JPanel(new GridLayout(1, 2));
specInteresting =
new JCheckBox("Mark as Interesting (Enter Comma-separated Threshold Values)");
specInteresting.addActionListener(this);
specInteresting.setSelected(speciesMarked);
tempPanel.add(specInteresting);
thresholdTextField = new JTextField(thresholdText);
tempPanel.add(thresholdTextField);
grid.add(tempPanel);
}
// Initial field
if (paramsOnly) {
String defaultValue = refGCM.getParameter(GlobalConstants.INITIAL_STRING);
if (refGCM.getSpecies().get(selected).containsKey(GlobalConstants.INITIAL_STRING)) {
defaultValue = refGCM.getSpecies().get(selected).getProperty(GlobalConstants.INITIAL_STRING);
origString = "custom";
}
else if (gcm.globalParameterIsSet(GlobalConstants.INITIAL_STRING)) {
defaultValue = gcm.getParameter(GlobalConstants.INITIAL_STRING);
}
field = new PropertyField(GlobalConstants.INITIAL_STRING,
gcm.getParameter(GlobalConstants.INITIAL_STRING), origString, defaultValue,
Utility.SWEEPstring + "|" + Utility.CONCstring, paramsOnly, origString);
}
else {
field = new PropertyField(GlobalConstants.INITIAL_STRING,
gcm.getParameter(GlobalConstants.INITIAL_STRING), origString,
gcm.getParameter(GlobalConstants.INITIAL_STRING), Utility.NUMstring + "|" + Utility.CONCstring, paramsOnly,
origString);
}
fields.put(GlobalConstants.INITIAL_STRING, field);
grid.add(field);
// Decay field
origString = "default";
if (paramsOnly) {
String defaultValue = refGCM.getParameter(GlobalConstants.KDECAY_STRING);
if (refGCM.getSpecies().get(selected).containsKey(GlobalConstants.KDECAY_STRING)) {
defaultValue = refGCM.getSpecies().get(selected).getProperty(
GlobalConstants.KDECAY_STRING);
origString = "custom";
}
else if (gcm.globalParameterIsSet(GlobalConstants.KDECAY_STRING)) {
defaultValue = gcm.getParameter(GlobalConstants.KDECAY_STRING);
}
field = new PropertyField(GlobalConstants.KDECAY_STRING, gcm
.getParameter(GlobalConstants.KDECAY_STRING), origString, defaultValue,
Utility.SWEEPstring, paramsOnly, origString);
}
else {
field = new PropertyField(GlobalConstants.KDECAY_STRING, gcm
.getParameter(GlobalConstants.KDECAY_STRING), origString, gcm
.getParameter(GlobalConstants.KDECAY_STRING), Utility.NUMstring, paramsOnly,
origString);
}
fields.put(GlobalConstants.KDECAY_STRING, field);
grid.add(field);
//Extracellular decay field
origString = "default";
if (paramsOnly) {
String defaultValue = refGCM.getParameter(GlobalConstants.KECDECAY_STRING);
if (refGCM.getSpecies().get(selected).containsKey(GlobalConstants.KECDECAY_STRING)) {
defaultValue = refGCM.getSpecies().get(selected).getProperty(
GlobalConstants.KECDECAY_STRING);
origString = "custom";
}
else if (gcm.globalParameterIsSet(GlobalConstants.KECDECAY_STRING)) {
defaultValue = gcm.getParameter(GlobalConstants.KECDECAY_STRING);
}
field = new PropertyField(GlobalConstants.KECDECAY_STRING, gcm
.getParameter(GlobalConstants.KECDECAY_STRING), origString, defaultValue,
Utility.SWEEPstring, paramsOnly, origString);
}
else {
field = new PropertyField(GlobalConstants.KECDECAY_STRING, gcm
.getParameter(GlobalConstants.KECDECAY_STRING), origString, gcm
.getParameter(GlobalConstants.KECDECAY_STRING), Utility.NUMstring, paramsOnly,
origString);
}
fields.put(GlobalConstants.KECDECAY_STRING, field);
grid.add(field);
// Complex Equilibrium Constant Field
origString = "default";
if (paramsOnly) {
String defaultValue = refGCM.getParameter(GlobalConstants.KCOMPLEX_STRING);
if (refGCM.getSpecies().get(selected).containsKey(GlobalConstants.KCOMPLEX_STRING)) {
defaultValue = refGCM.getSpecies().get(selected).getProperty(
GlobalConstants.KCOMPLEX_STRING);
origString = "custom";
}
else if (gcm.globalParameterIsSet(GlobalConstants.KCOMPLEX_STRING)) {
defaultValue = gcm.getParameter(GlobalConstants.KCOMPLEX_STRING);
}
field = new PropertyField(GlobalConstants.KCOMPLEX_STRING,
gcm.getParameter(GlobalConstants.KCOMPLEX_STRING), origString, defaultValue,
Utility.SLASHSWEEPstring, paramsOnly, origString);
}
else {
field = new PropertyField(GlobalConstants.KCOMPLEX_STRING,
gcm.getParameter(GlobalConstants.KCOMPLEX_STRING), origString,
gcm.getParameter(GlobalConstants.KCOMPLEX_STRING), Utility.SLASHstring, paramsOnly,
origString);
}
fields.put(GlobalConstants.KCOMPLEX_STRING, field);
grid.add(field);
// Membrane Diffusible Field
origString = "default";
if (paramsOnly) {
String defaultValue = refGCM.getParameter(GlobalConstants.MEMDIFF_STRING);
if (refGCM.getSpecies().get(selected).containsKey(GlobalConstants.MEMDIFF_STRING)) {
defaultValue = refGCM.getSpecies().get(selected).getProperty(
GlobalConstants.MEMDIFF_STRING);
origString = "custom";
}
else if (gcm.globalParameterIsSet(GlobalConstants.MEMDIFF_STRING)) {
defaultValue = gcm.getParameter(GlobalConstants.MEMDIFF_STRING);
}
field = new PropertyField(GlobalConstants.MEMDIFF_STRING, gcm
.getParameter(GlobalConstants.MEMDIFF_STRING), origString, defaultValue,
Utility.SLASHSWEEPstring, paramsOnly, origString);
}
else {
field = new PropertyField(GlobalConstants.MEMDIFF_STRING, gcm
.getParameter(GlobalConstants.MEMDIFF_STRING), origString, gcm
.getParameter(GlobalConstants.MEMDIFF_STRING), Utility.SLASHstring, paramsOnly,
origString);
}
fields.put(GlobalConstants.MEMDIFF_STRING, field);
grid.add(field);
//extracellular diffusion field
origString = "default";
if (paramsOnly) {
String defaultValue = refGCM.getParameter(GlobalConstants.KECDIFF_STRING);
if (refGCM.getSpecies().get(selected).containsKey(GlobalConstants.KECDIFF_STRING)) {
defaultValue = refGCM.getSpecies().get(selected).getProperty(
GlobalConstants.KECDIFF_STRING);
origString = "custom";
}
else if (gcm.globalParameterIsSet(GlobalConstants.KECDIFF_STRING)) {
defaultValue = gcm.getParameter(GlobalConstants.KECDIFF_STRING);
}
field = new PropertyField(GlobalConstants.KECDIFF_STRING, gcm
.getParameter(GlobalConstants.KECDIFF_STRING), origString, defaultValue,
Utility.SWEEPstring, paramsOnly, origString);
}
else {
field = new PropertyField(GlobalConstants.KECDIFF_STRING, gcm
.getParameter(GlobalConstants.KECDIFF_STRING), origString, gcm
.getParameter(GlobalConstants.KECDIFF_STRING), Utility.NUMstring, paramsOnly,
origString);
}
fields.put(GlobalConstants.KECDIFF_STRING, field);
grid.add(field);
if (!paramsOnly) {
// Panel for associating SBOL RBS element
SbolField sField = new SbolField(GlobalConstants.SBOL_RBS, gcmEditor);
sbolFields.put(GlobalConstants.SBOL_RBS, sField);
grid.add(sField);
// Panel for associating SBOL ORF element
sField = new SbolField(GlobalConstants.SBOL_ORF, gcmEditor);
sbolFields.put(GlobalConstants.SBOL_ORF, sField);
grid.add(sField);
}
if (selected != null) {
Properties prop = gcm.getSpecies().get(selected);
//This will generate the action command associated with changing the type combo box
typeBox.setSelectedItem(prop.getProperty(GlobalConstants.TYPE));
loadProperties(prop);
}
else {
typeBox.setSelectedItem(types[1]);
}
boolean display = false;
if (!inTab) {
while (!display) {
//show the panel; handle the data
int value = JOptionPane.showOptionDialog(Gui.frame, this, "Species Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
display = handlePanelData(value);
}
}
}
private boolean checkValues() {
for (PropertyField f : fields.values()) {
if (!f.isValidValue() /*|| f.getValue().equals("RNAP") || f.getValue().endsWith("_RNAP")
|| f.getValue().endsWith("_bound")*/) {
return false;
}
}
return true;
}
private boolean checkSbolValues() {
for (SbolField sf : sbolFields.values()) {
if (!sf.isValidText())
return false;
}
return true;
}
/**
* adds interesting species to a list in Reb2Sac.java
*
* @return whether the values were okay for adding or not
*/
private boolean addInterestingSpecies() {
if (specInteresting.isSelected()) {
String thresholdText = thresholdTextField.getText();
ArrayList<Integer> thresholdValues = new ArrayList<Integer>();
//if the threshold text is empty, don't do anything to it
if (!thresholdText.isEmpty()) {
try {
// check the threshold values for validity
for (String threshold : thresholdText.trim().split(",")) {
thresholdValues.add(Integer.parseInt(threshold.trim()));
}
}
catch (NumberFormatException e) {
Utility.createErrorMessage("Error", "Threshold values must be comma-separated integers");
return false;
}
Integer[] threshVals = thresholdValues.toArray(new Integer[0]);
Arrays.sort(threshVals);
thresholdText = "";
for (Integer thresholdVal : threshVals)
thresholdText += thresholdVal.toString() + ",";
// take off the last ", "
if (threshVals.length > 0)
thresholdText = thresholdText.substring(0, thresholdText.length() - 1);
}
// everything is okay, so add the interesting species to the list
gcmEditor.getReb2Sac().addInterestingSpecies(selected + " " + thresholdText);
}
else {
gcmEditor.getReb2Sac().removeInterestingSpecies(selected);
}
return true;
}
/**
* handles the panel data
*
* @return
*/
public boolean handlePanelData(int value) {
// the new id of the species. Will be filled in later.
String newSpeciesID = null;
// if the value is -1 (user hit escape) then set it equal to the cancel value
if(value == -1) {
for(int i=0; i<options.length; i++) {
if(options[i] == options[1])
value = i;
}
}
// "OK"
if (options[value].equals(options[0])) {
boolean sbolValueCheck = checkSbolValues();
boolean valueCheck = checkValues();
if (!valueCheck || !sbolValueCheck) {
if (!valueCheck)
Utility.createErrorMessage("Error", "Illegal values entered.");
return false;
}
if (selected == null) {
if (gcm.getUsedIDs().contains((String)fields.get(GlobalConstants.ID).getValue())) {
Utility.createErrorMessage("Error", "ID already exists.");
return false;
}
}
else if (!selected.equals(fields.get(GlobalConstants.ID).getValue())) {
if (gcm.getUsedIDs().contains((String)fields.get(GlobalConstants.ID).getValue())) {
Utility.createErrorMessage("Error", "ID already exists.");
return false;
}
}
if (selected != null
&& !gcm.editSpeciesCheck(selected, typeBox.getSelectedItem().toString())) {
Utility.createErrorMessage("Error", "Cannot change species type. "
+ "Species is used as a port in a component.");
return false;
}
if (selected != null && (typeBox.getSelectedItem().toString().equals(types[0]) ||
typeBox.getSelectedItem().toString().equals(types[3]))) {
for (String infl : gcm.getInfluences().keySet()) {
String geneProduct = GCMFile.getOutput(infl);
if (selected.equals(geneProduct)) {
Utility.createErrorMessage("Error", "There must be no connections to an input species " +
"or constitutive species.");
return false;
}
}
}
newSpeciesID = fields.get(GlobalConstants.ID).getValue();
Properties property = new Properties();
if (selected != null) {
//check and add interesting species information
if (paramsOnly) {
if (!addInterestingSpecies())
return false;
}
// preserve positioning info
for (Object s : gcm.getSpecies().get(selected).keySet()) {
String k = s.toString();
if (k.equals("graphwidth") || k.equals("graphheight") || k.equals("graphy") || k.equals("graphx")) {
String v = (gcm.getSpecies().get(selected).getProperty(k)).toString();
property.put(k, v);
}
}
if (!paramsOnly) {
Species species = gcm.getSBMLDocument().getModel().getSpecies(selected);
species.setId(fields.get(GlobalConstants.ID).getValue());
species.setName(fields.get(GlobalConstants.NAME).getValue());
if (Utility.isValid(fields.get(GlobalConstants.INITIAL_STRING).getValue(), Utility.NUMstring)) {
species.setInitialAmount(Double.parseDouble(fields.get(GlobalConstants.INITIAL_STRING).getValue()));
}
else {
String conc = fields.get(GlobalConstants.INITIAL_STRING).getValue();
species.setInitialConcentration(Double.parseDouble(conc.substring(1,conc.length()-1)));
}
if (specBoundary.getSelectedItem().equals("true")) {
species.setBoundaryCondition(true);
}
else {
species.setBoundaryCondition(false);
}
if (specConstant.getSelectedItem().equals("true")) {
species.setConstant(true);
}
else {
species.setConstant(false);
}
if (gcm.getSBMLDocument().getModel().getNumCompartments() > 1) {
species.setCompartment((String)compartBox.getSelectedItem());
}
if (specHasOnly.getSelectedItem().equals("true")) {
species.setHasOnlySubstanceUnits(true);
}
else {
species.setHasOnlySubstanceUnits(false);
}
String unit = (String) unitsBox.getSelectedItem();
if (unit.equals("( none )")) {
species.unsetUnits();
}
else {
species.setUnits(unit);
}
String convFactor = null;
if (gcm.getSBMLDocument().getLevel() > 2) {
convFactor = (String) convBox.getSelectedItem();
if (convFactor.equals("( none )")) {
species.unsetConversionFactor();
}
else {
species.setConversionFactor(convFactor);
}
}
}
}
for (PropertyField f : fields.values()) {
if (f.getState() == null || f.getState().equals(f.getStates()[1])) {
property.put(f.getKey(), f.getValue());
}
else {
property.remove(f.getKey());
}
}
property.put(GlobalConstants.TYPE, typeBox.getSelectedItem().toString());
// Add SBOL properties
for (SbolField sf : sbolFields.values()) {
if (!sf.getText().equals(""))
property.put(sf.getType(), sf.getText());
}
if (selected != null && !selected.equals(newSpeciesID)) {
while (gcm.getUsedIDs().contains(selected)) {
gcm.getUsedIDs().remove(selected);
}
gcm.changeSpeciesName(selected, newSpeciesID);
((DefaultListModel) influences.getModel()).clear();
influences.addAllItem(gcm.getInfluences().keySet());
((DefaultListModel) conditions.getModel()).clear();
conditions.addAllItem(gcm.getConditions());
((DefaultListModel) components.getModel()).clear();
for (String c : gcm.getComponents().keySet()) {
components.addItem(c + " "
+ gcm.getComponents().get(c).getProperty("gcm").replace(".gcm", "")
+ " " + gcm.getComponentPortMap(c));
}
}
if (!gcm.getUsedIDs().contains(newSpeciesID)) {
gcm.getUsedIDs().add(newSpeciesID);
}
gcm.addSpecies(newSpeciesID, property);
if (paramsOnly) {
if (fields.get(GlobalConstants.INITIAL_STRING).getState().equals(
fields.get(GlobalConstants.INITIAL_STRING).getStates()[1])
|| fields.get(GlobalConstants.KCOMPLEX_STRING).getState().equals(
fields.get(GlobalConstants.KCOMPLEX_STRING).getStates()[1])
|| fields.get(GlobalConstants.KDECAY_STRING).getState().equals(
fields.get(GlobalConstants.KDECAY_STRING).getStates()[1])
|| fields.get(GlobalConstants.MEMDIFF_STRING).getState().equals(
fields.get(GlobalConstants.MEMDIFF_STRING).getStates()[1])) {
newSpeciesID += " Modified";
}
}
speciesList.removeItem(selected);
speciesList.removeItem(selected + " Modified");
speciesList.addItem(newSpeciesID);
speciesList.setSelectedValue(newSpeciesID, true);
gcmEditor.setDirty(true);
}
// "Cancel"
if(options[value].equals(options[1])) {
// System.out.println();
return true;
}
return true;
}
public String updates() {
String updates = "";
if (paramsOnly) {
if (fields.get(GlobalConstants.INITIAL_STRING).getState().equals(
fields.get(GlobalConstants.INITIAL_STRING).getStates()[1])) {
updates += fields.get(GlobalConstants.ID).getValue() + "/"
+ GlobalConstants.INITIAL_STRING + " "
+ fields.get(GlobalConstants.INITIAL_STRING).getValue();
}
if (fields.get(GlobalConstants.KDECAY_STRING).getState().equals(
fields.get(GlobalConstants.KDECAY_STRING).getStates()[1])) {
if (!updates.equals("")) {
updates += "\n";
}
updates += fields.get(GlobalConstants.ID).getValue() + "/"
+ GlobalConstants.KDECAY_STRING + " "
+ fields.get(GlobalConstants.KDECAY_STRING).getValue();
}
if (fields.get(GlobalConstants.KCOMPLEX_STRING).getState().equals(
fields.get(GlobalConstants.KCOMPLEX_STRING).getStates()[1])) {
if (!updates.equals("")) {
updates += "\n";
}
updates += fields.get(GlobalConstants.ID).getValue() + "/"
+ GlobalConstants.KCOMPLEX_STRING + " "
+ fields.get(GlobalConstants.KCOMPLEX_STRING).getValue();
}
if (fields.get(GlobalConstants.MEMDIFF_STRING).getState().equals(
fields.get(GlobalConstants.MEMDIFF_STRING).getStates()[1])) {
if (!updates.equals("")) {
updates += "\n";
}
updates += fields.get(GlobalConstants.ID).getValue() + "/"
+ GlobalConstants.MEMDIFF_STRING + " "
+ fields.get(GlobalConstants.MEMDIFF_STRING).getValue();
}
if (updates.equals("")) {
updates += fields.get(GlobalConstants.ID).getValue() + "/";
}
}
return updates;
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("comboBoxChanged")) {
setType(typeBox.getSelectedItem().toString());
}
if (paramsOnly)
thresholdTextField.setEnabled(specInteresting.isSelected());
}
private void setType(String type) {
//input
if (type.equals(types[0])) {
fields.get(GlobalConstants.KDECAY_STRING).setEnabled(false);
fields.get(GlobalConstants.KCOMPLEX_STRING).setEnabled(false);
fields.get(GlobalConstants.MEMDIFF_STRING).setEnabled(false);
fields.get(GlobalConstants.KECDIFF_STRING).setEnabled(false);
fields.get(GlobalConstants.KECDECAY_STRING).setEnabled(false);
}
//internal
else if (type.equals(types[1])) {
fields.get(GlobalConstants.KDECAY_STRING).setEnabled(true);
fields.get(GlobalConstants.KCOMPLEX_STRING).setEnabled(true);
fields.get(GlobalConstants.MEMDIFF_STRING).setEnabled(false);
fields.get(GlobalConstants.KECDIFF_STRING).setEnabled(false);
fields.get(GlobalConstants.KECDECAY_STRING).setEnabled(false);
}
//output
else if (type.equals(types[2])) {
fields.get(GlobalConstants.KDECAY_STRING).setEnabled(true);
fields.get(GlobalConstants.KCOMPLEX_STRING).setEnabled(true);
fields.get(GlobalConstants.MEMDIFF_STRING).setEnabled(false);
fields.get(GlobalConstants.KECDIFF_STRING).setEnabled(false);
fields.get(GlobalConstants.KECDECAY_STRING).setEnabled(false);
}
//diffusible
else if (type.equals(types[4])) {
fields.get(GlobalConstants.KDECAY_STRING).setEnabled(true);
fields.get(GlobalConstants.KCOMPLEX_STRING).setEnabled(true);
fields.get(GlobalConstants.MEMDIFF_STRING).setEnabled(true);
fields.get(GlobalConstants.KECDIFF_STRING).setEnabled(true);
fields.get(GlobalConstants.KECDECAY_STRING).setEnabled(true);
}
else {
fields.get(GlobalConstants.KDECAY_STRING).setEnabled(true);
fields.get(GlobalConstants.KCOMPLEX_STRING).setEnabled(false);
fields.get(GlobalConstants.MEMDIFF_STRING).setEnabled(false);
fields.get(GlobalConstants.KECDIFF_STRING).setEnabled(false);
fields.get(GlobalConstants.KECDECAY_STRING).setEnabled(false);
}
}
private void loadProperties(Properties property) {
for (Object o : property.keySet()) {
if (fields.containsKey(o.toString())) {
fields.get(o.toString()).setValue(property.getProperty(o.toString()));
fields.get(o.toString()).setCustom();
} else if (sbolFields.containsKey(o.toString())) {
sbolFields.get(o.toString()).setText(property.getProperty(o.toString()));
}
}
}
private String selected = "";
private PropertyList speciesList = null;
private PropertyList influences = null;
private PropertyList conditions = null;
private PropertyList components = null;
private String[] options = { "Ok", "Cancel" };
private GCMFile gcm = null;
private JComboBox typeBox = null;
private JComboBox compartBox = null;
private JComboBox convBox = null;
private JComboBox unitsBox = null;
private JComboBox specBoundary = null;
private JComboBox specConstant = null;
private JComboBox specHasOnly = null;
private JCheckBox specInteresting = null;
private JTextField thresholdTextField = null;
private static final String[] types = new String[] { GlobalConstants.INPUT, GlobalConstants.INTERNAL,
GlobalConstants.OUTPUT, GlobalConstants.SPASTIC, GlobalConstants.DIFFUSIBLE};
private HashMap<String, PropertyField> fields = null;
private HashMap<String, SbolField> sbolFields;
private boolean paramsOnly;
private GCM2SBMLEditor gcmEditor;
}
| gui/src/gcm/gui/SpeciesPanel.java | package gcm.gui;
import gcm.parser.GCMFile;
import gcm.util.GlobalConstants;
import gcm.util.Utility;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Properties;
import javax.swing.DefaultListModel;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.sbml.libsbml.Species;
import sbmleditor.MySpecies;
import main.Gui;
public class SpeciesPanel extends JPanel implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* calls constructor to construct the panel
*
* @param selected
* @param speciesList
* @param influencesList
* @param conditionsList
* @param componentsList
* @param gcm
* @param paramsOnly
* @param refGCM
* @param gcmEditor
*/
public SpeciesPanel(String selected, PropertyList speciesList, PropertyList influencesList,
PropertyList conditionsList, PropertyList componentsList, GCMFile gcm, boolean paramsOnly,
GCMFile refGCM, GCM2SBMLEditor gcmEditor, boolean inTab){
super(new BorderLayout());
constructor(selected, speciesList, influencesList, conditionsList, componentsList, gcm,
paramsOnly, refGCM, gcmEditor, inTab);
}
/**
* constructs the species panel
*
* @param selected
* @param speciesList
* @param influencesList
* @param conditionsList
* @param componentsList
* @param gcm
* @param paramsOnly
* @param refGCM
* @param gcmEditor
*/
private void constructor(String selected, PropertyList speciesList, PropertyList influencesList,
PropertyList conditionsList, PropertyList componentsList, GCMFile gcm, boolean paramsOnly,
GCMFile refGCM, GCM2SBMLEditor gcmEditor, boolean inTab) {
JPanel grid;
//if this is in analysis mode, only show the sweepable/changeable values
if (paramsOnly)
grid = new JPanel(new GridLayout(7,1));
else {
if (gcm.getSBMLDocument().getLevel() > 2) {
if (gcm.getSBMLDocument().getModel().getNumCompartments() == 1) {
grid = new JPanel(new GridLayout(16,1));
}
else {
grid = new JPanel(new GridLayout(17,1));
}
}
else {
if (gcm.getSBMLDocument().getModel().getNumCompartments() == 1) {
grid = new JPanel(new GridLayout(15,1));
}
else {
grid = new JPanel(new GridLayout(16,1));
}
}
}
this.add(grid, BorderLayout.CENTER);
this.selected = selected;
this.speciesList = speciesList;
this.influences = influencesList;
this.conditions = conditionsList;
this.components = componentsList;
this.gcm = gcm;
this.paramsOnly = paramsOnly;
this.gcmEditor = gcmEditor;
fields = new HashMap<String, PropertyField>();
sbolFields = new HashMap<String, SbolField>();
String origString = "default";
PropertyField field = null;
// ID field
field = new PropertyField(GlobalConstants.ID, "", null, null, Utility.IDstring,
paramsOnly, "default");
fields.put(GlobalConstants.ID, field);
if (!paramsOnly) grid.add(field);
// Name field
field = new PropertyField(GlobalConstants.NAME, "", null, null, Utility.NAMEstring,
paramsOnly, "default");
fields.put(GlobalConstants.NAME, field);
if (!paramsOnly) grid.add(field);
// Type field
JPanel tempPanel = new JPanel();
JLabel tempLabel = new JLabel(GlobalConstants.TYPE);
typeBox = new JComboBox(types);
//disallow input/output types for species in an enclosed GCM
if (!gcm.getEnclosingCompartment().isEmpty()) {
typeBox.removeItem(GlobalConstants.INPUT);
typeBox.removeItem(GlobalConstants.OUTPUT);
}
typeBox.addActionListener(this);
tempPanel.setLayout(new GridLayout(1, 2));
tempPanel.add(tempLabel);
tempPanel.add(typeBox);
if (!paramsOnly) grid.add(tempPanel);
Species species = gcm.getSBMLDocument().getModel().getSpecies(selected);
// compartment field
tempPanel = new JPanel();
tempLabel = new JLabel("Compartment");
compartBox = MySpecies.createCompartmentChoices(gcm.getSBMLDocument());
compartBox.setSelectedItem(species.getCompartment());
compartBox.addActionListener(this);
tempPanel.setLayout(new GridLayout(1, 2));
tempPanel.add(tempLabel);
tempPanel.add(compartBox);
if (gcm.getSBMLDocument().getModel().getNumCompartments() > 1) {
if (!paramsOnly) grid.add(tempPanel);
}
String[] optionsTF = { "true", "false" };
// Boundary condition field
tempPanel = new JPanel();
tempLabel = new JLabel("Boundary Condition");
specBoundary = new JComboBox(optionsTF);
if (species.getBoundaryCondition()) {
specBoundary.setSelectedItem("true");
}
else {
specBoundary.setSelectedItem("false");
}
tempPanel.setLayout(new GridLayout(1, 2));
tempPanel.add(tempLabel);
tempPanel.add(specBoundary);
if (!paramsOnly) grid.add(tempPanel);
// Constant field
tempPanel = new JPanel();
tempLabel = new JLabel("Constant");
specConstant = new JComboBox(optionsTF);
if (species.getConstant()) {
specConstant.setSelectedItem("true");
}
else {
specConstant.setSelectedItem("false");
}
tempPanel.setLayout(new GridLayout(1, 2));
tempPanel.add(tempLabel);
tempPanel.add(specConstant);
if (!paramsOnly) grid.add(tempPanel);
// Has only substance units field
tempPanel = new JPanel();
tempLabel = new JLabel("Has Only Substance Units");
specHasOnly = new JComboBox(optionsTF);
if (species.getHasOnlySubstanceUnits()) {
specHasOnly.setSelectedItem("true");
}
else {
specHasOnly.setSelectedItem("false");
}
tempPanel.setLayout(new GridLayout(1, 2));
tempPanel.add(tempLabel);
tempPanel.add(specHasOnly);
if (!paramsOnly) grid.add(tempPanel);
// Units field
tempPanel = new JPanel();
tempLabel = new JLabel("Units");
unitsBox = MySpecies.createUnitsChoices(gcm.getSBMLDocument());
if (species.isSetUnits()) {
unitsBox.setSelectedItem(species.getUnits());
}
tempPanel.setLayout(new GridLayout(1, 2));
tempPanel.add(tempLabel);
tempPanel.add(unitsBox);
if (!paramsOnly) grid.add(tempPanel);
// Conversion factor field
if (gcm.getSBMLDocument().getLevel() > 2) {
tempPanel = new JPanel();
tempLabel = new JLabel("Conversion Factor");
convBox = MySpecies.createConversionFactorChoices(gcm.getSBMLDocument());
if (species.isSetConversionFactor()) {
convBox.setSelectedItem(species.getConversionFactor());
}
tempPanel.setLayout(new GridLayout(1, 2));
tempPanel.add(tempLabel);
tempPanel.add(convBox);
if (!paramsOnly) grid.add(tempPanel);
}
//mark as interesting field
if (paramsOnly) {
String thresholdText = "";
boolean speciesMarked = false;
ArrayList<String> interestingSpecies = gcmEditor.getReb2Sac().getInterestingSpeciesAsArrayList();
//look for the selected species among the already-interesting
//if it is interesting, populate the field with its data
for (String speciesInfo : interestingSpecies) {
if (speciesInfo.split(" ")[0].equals(selected)) {
speciesMarked = true;
thresholdText = speciesInfo.replace(selected, "").trim();
break;
}
}
tempPanel = new JPanel(new GridLayout(1, 2));
specInteresting =
new JCheckBox("Mark as Interesting (Enter Comma-separated Threshold Values)");
specInteresting.addActionListener(this);
specInteresting.setSelected(speciesMarked);
tempPanel.add(specInteresting);
thresholdTextField = new JTextField(thresholdText);
tempPanel.add(thresholdTextField);
grid.add(tempPanel);
}
// Initial field
if (paramsOnly) {
String defaultValue = refGCM.getParameter(GlobalConstants.INITIAL_STRING);
if (refGCM.getSpecies().get(selected).containsKey(GlobalConstants.INITIAL_STRING)) {
defaultValue = refGCM.getSpecies().get(selected).getProperty(GlobalConstants.INITIAL_STRING);
origString = "custom";
}
else if (gcm.globalParameterIsSet(GlobalConstants.INITIAL_STRING)) {
defaultValue = gcm.getParameter(GlobalConstants.INITIAL_STRING);
}
field = new PropertyField(GlobalConstants.INITIAL_STRING,
gcm.getParameter(GlobalConstants.INITIAL_STRING), origString, defaultValue,
Utility.SWEEPstring + "|" + Utility.CONCstring, paramsOnly, origString);
}
else {
field = new PropertyField(GlobalConstants.INITIAL_STRING,
gcm.getParameter(GlobalConstants.INITIAL_STRING), origString,
gcm.getParameter(GlobalConstants.INITIAL_STRING), Utility.NUMstring + "|" + Utility.CONCstring, paramsOnly,
origString);
}
fields.put(GlobalConstants.INITIAL_STRING, field);
grid.add(field);
// Decay field
origString = "default";
if (paramsOnly) {
String defaultValue = refGCM.getParameter(GlobalConstants.KDECAY_STRING);
if (refGCM.getSpecies().get(selected).containsKey(GlobalConstants.KDECAY_STRING)) {
defaultValue = refGCM.getSpecies().get(selected).getProperty(
GlobalConstants.KDECAY_STRING);
origString = "custom";
}
else if (gcm.globalParameterIsSet(GlobalConstants.KDECAY_STRING)) {
defaultValue = gcm.getParameter(GlobalConstants.KDECAY_STRING);
}
field = new PropertyField(GlobalConstants.KDECAY_STRING, gcm
.getParameter(GlobalConstants.KDECAY_STRING), origString, defaultValue,
Utility.SWEEPstring, paramsOnly, origString);
}
else {
field = new PropertyField(GlobalConstants.KDECAY_STRING, gcm
.getParameter(GlobalConstants.KDECAY_STRING), origString, gcm
.getParameter(GlobalConstants.KDECAY_STRING), Utility.NUMstring, paramsOnly,
origString);
}
fields.put(GlobalConstants.KDECAY_STRING, field);
grid.add(field);
//Extracellular decay field
origString = "default";
if (paramsOnly) {
String defaultValue = refGCM.getParameter(GlobalConstants.KECDECAY_STRING);
if (refGCM.getSpecies().get(selected).containsKey(GlobalConstants.KECDECAY_STRING)) {
defaultValue = refGCM.getSpecies().get(selected).getProperty(
GlobalConstants.KECDECAY_STRING);
origString = "custom";
}
else if (gcm.globalParameterIsSet(GlobalConstants.KECDECAY_STRING)) {
defaultValue = gcm.getParameter(GlobalConstants.KECDECAY_STRING);
}
field = new PropertyField(GlobalConstants.KECDECAY_STRING, gcm
.getParameter(GlobalConstants.KECDECAY_STRING), origString, defaultValue,
Utility.SWEEPstring, paramsOnly, origString);
}
else {
field = new PropertyField(GlobalConstants.KECDECAY_STRING, gcm
.getParameter(GlobalConstants.KECDECAY_STRING), origString, gcm
.getParameter(GlobalConstants.KECDECAY_STRING), Utility.NUMstring, paramsOnly,
origString);
}
fields.put(GlobalConstants.KECDECAY_STRING, field);
grid.add(field);
// Complex Equilibrium Constant Field
origString = "default";
if (paramsOnly) {
String defaultValue = refGCM.getParameter(GlobalConstants.KCOMPLEX_STRING);
if (refGCM.getSpecies().get(selected).containsKey(GlobalConstants.KCOMPLEX_STRING)) {
defaultValue = refGCM.getSpecies().get(selected).getProperty(
GlobalConstants.KCOMPLEX_STRING);
origString = "custom";
}
else if (gcm.globalParameterIsSet(GlobalConstants.KCOMPLEX_STRING)) {
defaultValue = gcm.getParameter(GlobalConstants.KCOMPLEX_STRING);
}
field = new PropertyField(GlobalConstants.KCOMPLEX_STRING,
gcm.getParameter(GlobalConstants.KCOMPLEX_STRING), origString, defaultValue,
Utility.SLASHSWEEPstring, paramsOnly, origString);
}
else {
field = new PropertyField(GlobalConstants.KCOMPLEX_STRING,
gcm.getParameter(GlobalConstants.KCOMPLEX_STRING), origString,
gcm.getParameter(GlobalConstants.KCOMPLEX_STRING), Utility.SLASHstring, paramsOnly,
origString);
}
fields.put(GlobalConstants.KCOMPLEX_STRING, field);
grid.add(field);
// Membrane Diffusible Field
origString = "default";
if (paramsOnly) {
String defaultValue = refGCM.getParameter(GlobalConstants.MEMDIFF_STRING);
if (refGCM.getSpecies().get(selected).containsKey(GlobalConstants.MEMDIFF_STRING)) {
defaultValue = refGCM.getSpecies().get(selected).getProperty(
GlobalConstants.MEMDIFF_STRING);
origString = "custom";
}
else if (gcm.globalParameterIsSet(GlobalConstants.MEMDIFF_STRING)) {
defaultValue = gcm.getParameter(GlobalConstants.MEMDIFF_STRING);
}
field = new PropertyField(GlobalConstants.MEMDIFF_STRING, gcm
.getParameter(GlobalConstants.MEMDIFF_STRING), origString, defaultValue,
Utility.SLASHSWEEPstring, paramsOnly, origString);
}
else {
field = new PropertyField(GlobalConstants.MEMDIFF_STRING, gcm
.getParameter(GlobalConstants.MEMDIFF_STRING), origString, gcm
.getParameter(GlobalConstants.MEMDIFF_STRING), Utility.SLASHstring, paramsOnly,
origString);
}
fields.put(GlobalConstants.MEMDIFF_STRING, field);
grid.add(field);
//extracellular diffusion field
origString = "default";
if (paramsOnly) {
String defaultValue = refGCM.getParameter(GlobalConstants.KECDIFF_STRING);
if (refGCM.getSpecies().get(selected).containsKey(GlobalConstants.KECDIFF_STRING)) {
defaultValue = refGCM.getSpecies().get(selected).getProperty(
GlobalConstants.KECDIFF_STRING);
origString = "custom";
}
else if (gcm.globalParameterIsSet(GlobalConstants.KECDIFF_STRING)) {
defaultValue = gcm.getParameter(GlobalConstants.KECDIFF_STRING);
}
field = new PropertyField(GlobalConstants.KECDIFF_STRING, gcm
.getParameter(GlobalConstants.KECDIFF_STRING), origString, defaultValue,
Utility.SWEEPstring, paramsOnly, origString);
}
else {
field = new PropertyField(GlobalConstants.KECDIFF_STRING, gcm
.getParameter(GlobalConstants.KECDIFF_STRING), origString, gcm
.getParameter(GlobalConstants.KECDIFF_STRING), Utility.NUMstring, paramsOnly,
origString);
}
fields.put(GlobalConstants.KECDIFF_STRING, field);
grid.add(field);
if (!paramsOnly) {
// Panel for associating SBOL RBS element
SbolField sField = new SbolField(GlobalConstants.SBOL_RBS, gcmEditor);
sbolFields.put(GlobalConstants.SBOL_RBS, sField);
grid.add(sField);
// Panel for associating SBOL ORF element
sField = new SbolField(GlobalConstants.SBOL_ORF, gcmEditor);
sbolFields.put(GlobalConstants.SBOL_ORF, sField);
grid.add(sField);
}
if (selected != null) {
Properties prop = gcm.getSpecies().get(selected);
//This will generate the action command associated with changing the type combo box
typeBox.setSelectedItem(prop.getProperty(GlobalConstants.TYPE));
loadProperties(prop);
}
else {
typeBox.setSelectedItem(types[1]);
}
boolean display = false;
if (!inTab) {
while (!display) {
//show the panel; handle the data
int value = JOptionPane.showOptionDialog(Gui.frame, this, "Species Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
display = handlePanelData(value);
}
}
}
private boolean checkValues() {
for (PropertyField f : fields.values()) {
if (!f.isValidValue() /*|| f.getValue().equals("RNAP") || f.getValue().endsWith("_RNAP")
|| f.getValue().endsWith("_bound")*/) {
return false;
}
}
return true;
}
private boolean checkSbolValues() {
for (SbolField sf : sbolFields.values()) {
if (!sf.isValidText())
return false;
}
return true;
}
/**
* adds interesting species to a list in Reb2Sac.java
*
* @return whether the values were okay for adding or not
*/
private boolean addInterestingSpecies() {
if (specInteresting.isSelected()) {
String thresholdText = thresholdTextField.getText();
ArrayList<Integer> thresholdValues = new ArrayList<Integer>();
//if the threshold text is empty, don't do anything to it
if (!thresholdText.isEmpty()) {
try {
// check the threshold values for validity
for (String threshold : thresholdText.trim().split(",")) {
thresholdValues.add(Integer.parseInt(threshold.trim()));
}
}
catch (NumberFormatException e) {
Utility.createErrorMessage("Error", "Threshold values must be comma-separated integers");
return false;
}
Integer[] threshVals = thresholdValues.toArray(new Integer[0]);
Arrays.sort(threshVals);
thresholdText = "";
for (Integer thresholdVal : threshVals)
thresholdText += thresholdVal.toString() + ",";
// take off the last ", "
if (threshVals.length > 0)
thresholdText = thresholdText.substring(0, thresholdText.length() - 1);
}
// everything is okay, so add the interesting species to the list
gcmEditor.getReb2Sac().addInterestingSpecies(selected + " " + thresholdText);
}
else {
gcmEditor.getReb2Sac().removeInterestingSpecies(selected);
}
return true;
}
/**
* handles the panel data
*
* @return
*/
public boolean handlePanelData(int value) {
// the new id of the species. Will be filled in later.
String newSpeciesID = null;
// if the value is -1 (user hit escape) then set it equal to the cancel value
if(value == -1) {
for(int i=0; i<options.length; i++) {
if(options[i] == options[1])
value = i;
}
}
// "OK"
if (options[value].equals(options[0])) {
boolean sbolValueCheck = checkSbolValues();
boolean valueCheck = checkValues();
if (!valueCheck || !sbolValueCheck) {
if (!valueCheck)
Utility.createErrorMessage("Error", "Illegal values entered.");
return false;
}
if (selected == null) {
if (gcm.getUsedIDs().contains((String)fields.get(GlobalConstants.ID).getValue())) {
Utility.createErrorMessage("Error", "ID already exists.");
return false;
}
}
else if (!selected.equals(fields.get(GlobalConstants.ID).getValue())) {
if (gcm.getUsedIDs().contains((String)fields.get(GlobalConstants.ID).getValue())) {
Utility.createErrorMessage("Error", "ID already exists.");
return false;
}
}
if (selected != null
&& !gcm.editSpeciesCheck(selected, typeBox.getSelectedItem().toString())) {
Utility.createErrorMessage("Error", "Cannot change species type. "
+ "Species is used as a port in a component.");
return false;
}
if (selected != null && (typeBox.getSelectedItem().toString().equals(types[0]) ||
typeBox.getSelectedItem().toString().equals(types[3]))) {
for (String infl : gcm.getInfluences().keySet()) {
String geneProduct = GCMFile.getOutput(infl);
if (selected.equals(geneProduct)) {
Utility.createErrorMessage("Error", "There must be no connections to an input species " +
"or constitutive species.");
return false;
}
}
}
newSpeciesID = fields.get(GlobalConstants.ID).getValue();
Properties property = new Properties();
if (selected != null) {
//check and add interesting species information
if (paramsOnly) {
if (!addInterestingSpecies())
return false;
}
// preserve positioning info
for (Object s : gcm.getSpecies().get(selected).keySet()) {
String k = s.toString();
if (k.equals("graphwidth") || k.equals("graphheight") || k.equals("graphy") || k.equals("graphx")) {
String v = (gcm.getSpecies().get(selected).getProperty(k)).toString();
property.put(k, v);
}
}
if (!paramsOnly) {
Species species = gcm.getSBMLDocument().getModel().getSpecies(selected);
species.setId(fields.get(GlobalConstants.ID).getValue());
species.setName(fields.get(GlobalConstants.NAME).getValue());
if (Utility.isValid(fields.get(GlobalConstants.INITIAL_STRING).getValue(), Utility.NUMstring)) {
species.setInitialAmount(Double.parseDouble(fields.get(GlobalConstants.INITIAL_STRING).getValue()));
}
else {
String conc = fields.get(GlobalConstants.INITIAL_STRING).getValue();
species.setInitialConcentration(Double.parseDouble(conc.substring(1,conc.length()-1)));
}
if (specBoundary.getSelectedItem().equals("true")) {
species.setBoundaryCondition(true);
}
else {
species.setBoundaryCondition(false);
}
if (specConstant.getSelectedItem().equals("true")) {
species.setConstant(true);
}
else {
species.setConstant(false);
}
if (gcm.getSBMLDocument().getModel().getNumCompartments() > 1) {
species.setCompartment((String)compartBox.getSelectedItem());
}
if (specHasOnly.getSelectedItem().equals("true")) {
species.setHasOnlySubstanceUnits(true);
}
else {
species.setHasOnlySubstanceUnits(false);
}
String unit = (String) unitsBox.getSelectedItem();
if (unit.equals("( none )")) {
species.unsetUnits();
}
else {
species.setUnits(unit);
}
String convFactor = null;
if (gcm.getSBMLDocument().getLevel() > 2) {
convFactor = (String) convBox.getSelectedItem();
if (convFactor.equals("( none )")) {
species.unsetConversionFactor();
}
else {
species.setConversionFactor(convFactor);
}
}
}
}
for (PropertyField f : fields.values()) {
if (f.getState() == null || f.getState().equals(f.getStates()[1])) {
property.put(f.getKey(), f.getValue());
}
else {
property.remove(f.getKey());
}
}
property.put(GlobalConstants.TYPE, typeBox.getSelectedItem().toString());
// Add SBOL properties
for (SbolField sf : sbolFields.values()) {
if (!sf.getText().equals(""))
property.put(sf.getType(), sf.getText());
}
if (selected != null && !selected.equals(newSpeciesID)) {
while (gcm.getUsedIDs().contains(selected)) {
gcm.getUsedIDs().remove(selected);
}
gcm.changeSpeciesName(selected, newSpeciesID);
((DefaultListModel) influences.getModel()).clear();
influences.addAllItem(gcm.getInfluences().keySet());
((DefaultListModel) conditions.getModel()).clear();
conditions.addAllItem(gcm.getConditions());
((DefaultListModel) components.getModel()).clear();
for (String c : gcm.getComponents().keySet()) {
components.addItem(c + " "
+ gcm.getComponents().get(c).getProperty("gcm").replace(".gcm", "")
+ " " + gcm.getComponentPortMap(c));
}
}
if (!gcm.getUsedIDs().contains(newSpeciesID)) {
gcm.getUsedIDs().add(newSpeciesID);
}
gcm.addSpecies(newSpeciesID, property);
if (paramsOnly) {
if (fields.get(GlobalConstants.INITIAL_STRING).getState().equals(
fields.get(GlobalConstants.INITIAL_STRING).getStates()[1])
|| fields.get(GlobalConstants.KCOMPLEX_STRING).getState().equals(
fields.get(GlobalConstants.KCOMPLEX_STRING).getStates()[1])
|| fields.get(GlobalConstants.KDECAY_STRING).getState().equals(
fields.get(GlobalConstants.KDECAY_STRING).getStates()[1])
|| fields.get(GlobalConstants.MEMDIFF_STRING).getState().equals(
fields.get(GlobalConstants.MEMDIFF_STRING).getStates()[1])) {
newSpeciesID += " Modified";
}
}
speciesList.removeItem(selected);
speciesList.removeItem(selected + " Modified");
speciesList.addItem(newSpeciesID);
speciesList.setSelectedValue(newSpeciesID, true);
gcmEditor.setDirty(true);
}
// "Cancel"
if(options[value].equals(options[1])) {
// System.out.println();
return true;
}
return true;
}
public String updates() {
String updates = "";
if (paramsOnly) {
if (fields.get(GlobalConstants.INITIAL_STRING).getState().equals(
fields.get(GlobalConstants.INITIAL_STRING).getStates()[1])) {
updates += fields.get(GlobalConstants.ID).getValue() + "/"
+ GlobalConstants.INITIAL_STRING + " "
+ fields.get(GlobalConstants.INITIAL_STRING).getValue();
}
if (fields.get(GlobalConstants.KDECAY_STRING).getState().equals(
fields.get(GlobalConstants.KDECAY_STRING).getStates()[1])) {
if (!updates.equals("")) {
updates += "\n";
}
updates += fields.get(GlobalConstants.ID).getValue() + "/"
+ GlobalConstants.KDECAY_STRING + " "
+ fields.get(GlobalConstants.KDECAY_STRING).getValue();
}
if (fields.get(GlobalConstants.KCOMPLEX_STRING).getState().equals(
fields.get(GlobalConstants.KCOMPLEX_STRING).getStates()[1])) {
if (!updates.equals("")) {
updates += "\n";
}
updates += fields.get(GlobalConstants.ID).getValue() + "/"
+ GlobalConstants.KCOMPLEX_STRING + " "
+ fields.get(GlobalConstants.KCOMPLEX_STRING).getValue();
}
if (fields.get(GlobalConstants.MEMDIFF_STRING).getState().equals(
fields.get(GlobalConstants.MEMDIFF_STRING).getStates()[1])) {
if (!updates.equals("")) {
updates += "\n";
}
updates += fields.get(GlobalConstants.ID).getValue() + "/"
+ GlobalConstants.MEMDIFF_STRING + " "
+ fields.get(GlobalConstants.MEMDIFF_STRING).getValue();
}
if (updates.equals("")) {
updates += fields.get(GlobalConstants.ID).getValue() + "/";
}
}
return updates;
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("comboBoxChanged")) {
setType(typeBox.getSelectedItem().toString());
}
if (paramsOnly)
thresholdTextField.setEnabled(specInteresting.isSelected());
}
private void setType(String type) {
//input
if (type.equals(types[0])) {
fields.get(GlobalConstants.KDECAY_STRING).setEnabled(false);
fields.get(GlobalConstants.KCOMPLEX_STRING).setEnabled(false);
fields.get(GlobalConstants.MEMDIFF_STRING).setEnabled(false);
fields.get(GlobalConstants.KECDIFF_STRING).setEnabled(false);
fields.get(GlobalConstants.KECDECAY_STRING).setEnabled(false);
}
//internal
else if (type.equals(types[1])) {
fields.get(GlobalConstants.KDECAY_STRING).setEnabled(true);
fields.get(GlobalConstants.KCOMPLEX_STRING).setEnabled(true);
fields.get(GlobalConstants.MEMDIFF_STRING).setEnabled(false);
fields.get(GlobalConstants.KECDIFF_STRING).setEnabled(false);
fields.get(GlobalConstants.KECDECAY_STRING).setEnabled(false);
}
//output
else if (type.equals(types[2])) {
fields.get(GlobalConstants.KDECAY_STRING).setEnabled(true);
fields.get(GlobalConstants.KCOMPLEX_STRING).setEnabled(true);
fields.get(GlobalConstants.MEMDIFF_STRING).setEnabled(false);
fields.get(GlobalConstants.KECDIFF_STRING).setEnabled(false);
fields.get(GlobalConstants.KECDECAY_STRING).setEnabled(false);
}
//diffusible
else if (type.equals(types[4])) {
fields.get(GlobalConstants.KDECAY_STRING).setEnabled(true);
fields.get(GlobalConstants.KCOMPLEX_STRING).setEnabled(true);
fields.get(GlobalConstants.MEMDIFF_STRING).setEnabled(true);
fields.get(GlobalConstants.KECDIFF_STRING).setEnabled(true);
fields.get(GlobalConstants.KECDECAY_STRING).setEnabled(true);
}
else {
fields.get(GlobalConstants.KDECAY_STRING).setEnabled(true);
fields.get(GlobalConstants.KCOMPLEX_STRING).setEnabled(false);
fields.get(GlobalConstants.MEMDIFF_STRING).setEnabled(false);
fields.get(GlobalConstants.KECDIFF_STRING).setEnabled(false);
fields.get(GlobalConstants.KECDECAY_STRING).setEnabled(false);
}
}
private void loadProperties(Properties property) {
for (Object o : property.keySet()) {
if (fields.containsKey(o.toString())) {
fields.get(o.toString()).setValue(property.getProperty(o.toString()));
fields.get(o.toString()).setCustom();
} else if (sbolFields.containsKey(o.toString())) {
sbolFields.get(o.toString()).setText(property.getProperty(o.toString()));
}
}
}
private String selected = "";
private PropertyList speciesList = null;
private PropertyList influences = null;
private PropertyList conditions = null;
private PropertyList components = null;
private String[] options = { "Ok", "Cancel" };
private GCMFile gcm = null;
private JComboBox typeBox = null;
private JComboBox compartBox = null;
private JComboBox convBox = null;
private JComboBox unitsBox = null;
private JComboBox specBoundary = null;
private JComboBox specConstant = null;
private JComboBox specHasOnly = null;
private JCheckBox specInteresting = null;
private JTextField thresholdTextField = null;
private static final String[] types = new String[] { GlobalConstants.INPUT, GlobalConstants.INTERNAL,
GlobalConstants.OUTPUT, GlobalConstants.SPASTIC, GlobalConstants.DIFFUSIBLE};
private HashMap<String, PropertyField> fields = null;
private HashMap<String, SbolField> sbolFields;
private boolean paramsOnly;
private GCM2SBMLEditor gcmEditor;
}
| fixed a bug related to i/o species within compartments
| gui/src/gcm/gui/SpeciesPanel.java | fixed a bug related to i/o species within compartments | <ide><path>ui/src/gcm/gui/SpeciesPanel.java
<ide> typeBox = new JComboBox(types);
<ide>
<ide> //disallow input/output types for species in an enclosed GCM
<del> if (!gcm.getEnclosingCompartment().isEmpty()) {
<add> if (gcm.getIsWithinCompartment()) {
<ide> typeBox.removeItem(GlobalConstants.INPUT);
<ide> typeBox.removeItem(GlobalConstants.OUTPUT);
<ide> } |
|
Java | agpl-3.0 | 87637b0a754bc2b1036ff5244855ce6994a7da12 | 0 | fviale/programming,jrochas/scale-proactive,acontes/programming,mnip91/programming-multiactivities,mnip91/programming-multiactivities,mnip91/proactive-component-monitoring,PaulKh/scale-proactive,ow2-proactive/programming,PaulKh/scale-proactive,PaulKh/scale-proactive,mnip91/proactive-component-monitoring,acontes/scheduling,jrochas/scale-proactive,mnip91/proactive-component-monitoring,paraita/programming,ow2-proactive/programming,lpellegr/programming,ow2-proactive/programming,lpellegr/programming,acontes/scheduling,PaulKh/scale-proactive,acontes/programming,acontes/scheduling,lpellegr/programming,paraita/programming,lpellegr/programming,acontes/scheduling,fviale/programming,acontes/programming,mnip91/programming-multiactivities,acontes/scheduling,jrochas/scale-proactive,fviale/programming,paraita/programming,acontes/programming,paraita/programming,acontes/programming,jrochas/scale-proactive,acontes/scheduling,fviale/programming,PaulKh/scale-proactive,fviale/programming,mnip91/proactive-component-monitoring,paraita/programming,jrochas/scale-proactive,ow2-proactive/programming,ow2-proactive/programming,lpellegr/programming,ow2-proactive/programming,fviale/programming,paraita/programming,lpellegr/programming,mnip91/programming-multiactivities,acontes/programming,jrochas/scale-proactive,mnip91/programming-multiactivities,acontes/scheduling,mnip91/proactive-component-monitoring,PaulKh/scale-proactive,jrochas/scale-proactive,mnip91/proactive-component-monitoring,PaulKh/scale-proactive,mnip91/programming-multiactivities,acontes/programming | /*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2006 INRIA/University of Nice-Sophia Antipolis
* Contact: [email protected]
*
* 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 any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* Initial developer(s): The ProActive Team
* http://www.inria.fr/oasis/ProActive/contacts.html
* Contributor(s):
*
* ################################################################
*/
package org.objectweb.proactive.core.util.wrapper;
import java.io.Serializable;
/**
* <p>A reifiable object for wrapping the Java type <code>Object</code>.</p>
* <p>Use this class as result for ProActive asynchronous method calls.</p>
*
* @author ProActive Team
*/
public class GenericWrapper<T extends Object> implements Serializable {
/**
*
*/
private static final long serialVersionUID = 6165789939643190366L;
private T o;
/**
* Empty no args Constructor
*
*/
public GenericWrapper() {
}
/**
* Constructor for the wrapper
* @param o the object to wrap
*/
public GenericWrapper(T o) {
this.o = o;
}
/**
* Retrieves the wrapp object
* @return the wrapped object
*/
public T getObject() {
return this.o;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object arg) {
if (arg instanceof GenericWrapper) {
return ((GenericWrapper)arg).getObject().equals(this.o);
}
return false;
}
/**
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return this.o.hashCode();
}
}
| src/org/objectweb/proactive/core/util/wrapper/GenericWrapper.java | /*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2006 INRIA/University of Nice-Sophia Antipolis
* Contact: [email protected]
*
* 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 any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* Initial developer(s): The ProActive Team
* http://www.inria.fr/oasis/ProActive/contacts.html
* Contributor(s):
*
* ################################################################
*/
package org.objectweb.proactive.core.util.wrapper;
import java.io.Serializable;
/**
* <p>A reifiable object for wrapping the Java type <code>Object</code>.</p>
* <p>Use this class as result for ProActive asynchronous method calls.</p>
*
* @author ProActive Team
*/
public class GenericWrapper<T extends Object> implements Serializable {
/**
*
*/
private static final long serialVersionUID = 6165789939643190366L;
private T o;
/**
* Empty no args Constructor
*
*/
public GenericWrapper() {
}
/**
* Constructor for the wrapper
* @param o the object to wrap
*/
public GenericWrapper(T o) {
this.o = o;
}
/**
* Retrieves the wrapp object
* @return the wrapped object
*/
public T getObject() {
return this.o;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object arg) {
if (arg instanceof GenericWrapper) {
return arg.equals(this.o);
}
return false;
}
/**
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return this.o.hashCode();
}
}
| changed ObjectWrapper in GenericWrapper
git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@4036 28e8926c-6b08-0410-baaa-805c5e19b8d6
| src/org/objectweb/proactive/core/util/wrapper/GenericWrapper.java | changed ObjectWrapper in GenericWrapper | <ide><path>rc/org/objectweb/proactive/core/util/wrapper/GenericWrapper.java
<ide> */
<ide> public boolean equals(Object arg) {
<ide> if (arg instanceof GenericWrapper) {
<del> return arg.equals(this.o);
<add> return ((GenericWrapper)arg).getObject().equals(this.o);
<ide> }
<ide> return false;
<ide> } |
|
Java | mit | 91a7572eb2c35715bb50851031c932b6657297d3 | 0 | Eluinhost/UHC | /*
* Project: UHC
* Class: gg.uhc.uhc.UHC
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Graham Howden <graham_howden1 at yahoo.co.uk>.
*
* 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 gg.uhc.uhc;
import com.google.common.base.Optional;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigResolveOptions;
import gg.uhc.flagcommands.commands.SubcommandCommand;
import gg.uhc.uhc.messages.BaseMessageTemplates;
import gg.uhc.uhc.messages.MessageTemplates;
import gg.uhc.uhc.messages.SubsectionMessageTemplates;
import gg.uhc.uhc.modules.ModuleRegistry;
import gg.uhc.uhc.modules.autorespawn.AutoRespawnModule;
import gg.uhc.uhc.modules.border.WorldBorderCommand;
import gg.uhc.uhc.modules.commands.DummyCommandFactory;
import gg.uhc.uhc.modules.commands.ModuleCommands;
import gg.uhc.uhc.modules.death.*;
import gg.uhc.uhc.modules.difficulty.DifficultyModule;
import gg.uhc.uhc.modules.difficulty.PermadayCommand;
import gg.uhc.uhc.modules.enderpearls.EnderpearlsModule;
import gg.uhc.uhc.modules.food.ExtendedSaturationModule;
import gg.uhc.uhc.modules.heads.GoldenHeadsHealthCommand;
import gg.uhc.uhc.modules.heads.GoldenHeadsModule;
import gg.uhc.uhc.modules.heads.HeadDropsModule;
import gg.uhc.uhc.modules.heads.PlayerHeadProvider;
import gg.uhc.uhc.modules.health.*;
import gg.uhc.uhc.modules.horses.HorseArmourModule;
import gg.uhc.uhc.modules.horses.HorseHealingModule;
import gg.uhc.uhc.modules.horses.HorsesModule;
import gg.uhc.uhc.modules.portals.EndModule;
import gg.uhc.uhc.modules.portals.NetherModule;
import gg.uhc.uhc.modules.potions.*;
import gg.uhc.uhc.modules.pvp.GlobalPVPModule;
import gg.uhc.uhc.modules.recipes.GlisteringMelonRecipeModule;
import gg.uhc.uhc.modules.recipes.GoldenCarrotRecipeModule;
import gg.uhc.uhc.modules.recipes.NotchApplesModule;
import gg.uhc.uhc.modules.reset.PlayerAffectingCommand;
import gg.uhc.uhc.modules.reset.resetters.*;
import gg.uhc.uhc.modules.team.*;
import gg.uhc.uhc.modules.team.requests.RequestListCommand;
import gg.uhc.uhc.modules.team.requests.RequestManager;
import gg.uhc.uhc.modules.team.requests.RequestResponseCommand;
import gg.uhc.uhc.modules.team.requests.TeamRequestCommand;
import gg.uhc.uhc.modules.teleport.TeleportCommand;
import gg.uhc.uhc.modules.timer.TimerCommand;
import gg.uhc.uhc.modules.timer.TimerModule;
import gg.uhc.uhc.modules.whitelist.WhitelistClearCommand;
import gg.uhc.uhc.modules.whitelist.WhitelistOnlineCommand;
import gg.uhc.uhc.modules.xp.NerfQuartzXPModule;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandExecutor;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scoreboard.DisplaySlot;
import java.io.File;
import java.io.IOException;
public class UHC extends JavaPlugin {
protected ModuleRegistry registry;
protected DebouncedRunnable configSaver;
protected DummyCommandFactory dummyCommands;
protected MessageTemplates baseMessages;
protected MessageTemplates baseCommandMessages;
@Override
public void onEnable() {
// setup to save the config with a debounce of 2 seconds
configSaver = new DebouncedRunnable(this, new Runnable() {
@Override
public void run() {
saveConfigNow();
}
}, 40);
FileConfiguration configuration = getConfig();
try {
baseMessages = new BaseMessageTemplates(setupMessagesConfig());
} catch (Exception e) {
e.printStackTrace();
getLogger().severe("Failed to load the messages configuration file, cannot start the plugin");
setEnabled(false);
return;
}
baseCommandMessages = new SubsectionMessageTemplates(baseMessages, "commands");
dummyCommands = new DummyCommandFactory(baseCommandMessages);
registry = new ModuleRegistry(this, baseMessages, configuration);
setupBasicModules();
setupProtocolLibModules();
setupCommand(new PlayerListHealthCommand(
commandMessages("showhealth"),
Bukkit.getScoreboardManager().getMainScoreboard(),
DisplaySlot.PLAYER_LIST,
"UHCHealth",
"Health"
), "showhealth");
PotionFuelsListener fuelsListener = new PotionFuelsListener();
registry.registerEvents(fuelsListener);
registry.register(new Tier2PotionsModule(fuelsListener));
registry.register(new SplashPotionsModule(fuelsListener));
PlayerHeadProvider headProvider = new PlayerHeadProvider();
GoldenHeadsModule gheadModule = new GoldenHeadsModule(headProvider);
boolean gheadsLoaded = registry.register(gheadModule);
setupCommand(gheadsLoaded ? new GoldenHeadsHealthCommand(commandMessages("ghead"), gheadModule) : dummyCommands.forModule(gheadModule), "ghead");
registry.register(new HeadDropsModule(headProvider));
registry.register(new DeathStandsModule());
setupTeamCommands();
setupCommand(new WorldBorderCommand(commandMessages("border")), "border");
setupCommand(new ModuleCommands(commandMessages("uhc"), registry), "uhc");
setupCommand(new PermadayCommand(commandMessages("permaday")), "permaday");
long cacheTicks = 30 * 20;
setupCommand(new PlayerAffectingCommand(commandMessages("heal"), new PlayerHealthResetter(this, cacheTicks)), "heal");
setupCommand(new PlayerAffectingCommand(commandMessages("feed"), new PlayerFoodResetter(this, cacheTicks)), "feed");
setupCommand(new PlayerAffectingCommand(commandMessages("clearxp"), new PlayerXPResetter(this, cacheTicks)), "clearxp");
setupCommand(new PlayerAffectingCommand(commandMessages("ci"), new PlayerInventoryResetter(this, cacheTicks)), "ci");
setupCommand(new PlayerAffectingCommand(commandMessages("cleareffects"), new PlayerPotionsResetter(this, cacheTicks)), "cleareffects");
setupCommand(new PlayerAffectingCommand(commandMessages("reset"), new FullPlayerResetter(this, cacheTicks)), "reset");
setupCommand(new TeleportCommand(commandMessages("tpp")), "tpp");
setupCommand(new HealthCommand(commandMessages("h")), "h");
SubcommandCommand wlist = new SubcommandCommand();
MessageTemplates forWlist = commandMessages("wlist");
wlist.registerSubcommand("clear", new WhitelistClearCommand(forWlist));
wlist.registerSubcommand(SubcommandCommand.NO_ARG_SPECIAL, new WhitelistOnlineCommand(forWlist));
setupCommand(wlist, "wlist");
// save config just to make sure at the end
saveConfig();
}
protected void setupTeamCommands() {
Optional<TeamModule> teamModuleOptional = registry.get(TeamModule.class);
if (!teamModuleOptional.isPresent()) {
getLogger().info("Skipping registering team commands as the team module is not loaded");
setupCommand(dummyCommands.forModule("TeamModule"), "teams", "team", "noteam", "pmt", "randomteams", "clearteams", "tc", "teamrequest");
}
TeamModule teamModule = teamModuleOptional.get();
setupCommand(new ListTeamsCommand(commandMessages("teams"), teamModule), "teams");
setupCommand(new NoTeamCommand(commandMessages("noteam"), teamModule), "noteam");
setupCommand(new TeamPMCommand(commandMessages("pmt"), teamModule), "pmt");
setupCommand(new RandomTeamsCommand(commandMessages("randomteams"), teamModule), "randomteams");
setupCommand(new ClearTeamsCommand(commandMessages("clearteams"), teamModule), "clearteams");
setupCommand(new TeamCoordinatesCommand(commandMessages("tc"), teamModule), "tc");
SubcommandCommand team = new SubcommandCommand();
team.registerSubcommand("teamup", new TeamupCommand(commandMessages("team.teamup"), teamModule));
team.registerSubcommand("add", new TeamAddCommand(commandMessages("team.add"), teamModule));
team.registerSubcommand("remove", new TeamRemoveCommand(commandMessages("team.remove"), teamModule));
setupCommand(team , "team");
MessageTemplates requestMessages = commandMessages("team.teamrequest");
RequestManager requestManager = new RequestManager(this, requestMessages, teamModule, 20 * 120);
SubcommandCommand teamrequest = new SubcommandCommand();
teamrequest.registerSubcommand("accept", new RequestResponseCommand(requestMessages, requestManager, RequestManager.AcceptState.ACCEPT));
teamrequest.registerSubcommand("deny", new RequestResponseCommand(requestMessages, requestManager, RequestManager.AcceptState.DENY));
teamrequest.registerSubcommand("request", new TeamRequestCommand(requestMessages, requestManager));
teamrequest.registerSubcommand("list", new RequestListCommand(requestMessages, requestManager));
setupCommand(teamrequest, "teamrequest");
}
protected void setupProtocolLibModules() {
if (getServer().getPluginManager().getPlugin("ProtocolLib") == null) {
getLogger().info("Skipping timer and hardcore hearts modules because protocollib is not installed");
return;
}
TimerModule timer = new TimerModule();
setupCommand(registry.register(timer) ? new TimerCommand(commandMessages("timer"), timer) : dummyCommands.forModule(timer), "timer");
Optional<AutoRespawnModule> respawn = registry.get(AutoRespawnModule.class);
if (!respawn.isPresent()) {
getLogger().info("Skipping hardcore hearts module because auto respawn is not enabled");
return;
}
registry.register(new HardcoreHeartsModule(respawn.get()));
}
protected void setupBasicModules() {
registry.register(new DifficultyModule());
registry.register(new HealthRegenerationModule());
registry.register(new GhastTearDropsModule());
registry.register(new GoldenCarrotRecipeModule());
registry.register(new GlisteringMelonRecipeModule());
registry.register(new NotchApplesModule());
registry.register(new AbsorptionModule());
registry.register(new ExtendedSaturationModule());
registry.register(new GlobalPVPModule());
registry.register(new EnderpearlsModule());
registry.register(new WitchesModule());
registry.register(new NetherModule());
registry.register(new EndModule());
registry.register(new DeathBansModule());
registry.register(new HorsesModule());
registry.register(new HorseHealingModule());
registry.register(new HorseArmourModule());
registry.register(new DeathLightningModule());
registry.register(new ModifiedDeathMessagesModule());
registry.register(new DeathItemsModule());
registry.register(new ChatHealthPrependModule());
registry.register(new NerfQuartzXPModule());
registry.register(new AutoRespawnModule());
registry.register(new PercentHealthObjectiveModule());
registry.register(new TeamModule());
}
protected void setupCommand(CommandExecutor executor, String... commands) {
for (String command : commands) {
getCommand(command).setExecutor(executor);
}
}
private MessageTemplates commandMessages(String command) {
return new SubsectionMessageTemplates(baseCommandMessages, command);
}
@Override
public void saveConfig() {
configSaver.trigger();
}
public void saveConfigNow() {
super.saveConfig();
getLogger().info("Saved configuration changes");
}
public ModuleRegistry getRegistry() {
return registry;
}
protected Config setupMessagesConfig() throws IOException {
// copy reference across
saveResource("messages.reference.conf", true);
// parse fallback config
File reference = new File(getDataFolder(), "messages.reference.conf");
Config fallback = ConfigFactory.parseFile(reference);
// parse user provided config
File regular = new File(getDataFolder(), "messages.conf");
Config user;
if (regular.exists()) {
user = ConfigFactory.parseFile(regular);
} else {
user = ConfigFactory.empty();
}
return user.withFallback(fallback).resolve(ConfigResolveOptions.noSystem());
}
}
| src/main/java/gg/uhc/uhc/UHC.java | /*
* Project: UHC
* Class: gg.uhc.uhc.UHC
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Graham Howden <graham_howden1 at yahoo.co.uk>.
*
* 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 gg.uhc.uhc;
import com.google.common.base.Optional;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigResolveOptions;
import gg.uhc.flagcommands.commands.SubcommandCommand;
import gg.uhc.uhc.messages.BaseMessageTemplates;
import gg.uhc.uhc.messages.MessageTemplates;
import gg.uhc.uhc.messages.SubsectionMessageTemplates;
import gg.uhc.uhc.modules.ModuleRegistry;
import gg.uhc.uhc.modules.autorespawn.AutoRespawnModule;
import gg.uhc.uhc.modules.border.WorldBorderCommand;
import gg.uhc.uhc.modules.commands.DummyCommandFactory;
import gg.uhc.uhc.modules.commands.ModuleCommands;
import gg.uhc.uhc.modules.death.*;
import gg.uhc.uhc.modules.difficulty.DifficultyModule;
import gg.uhc.uhc.modules.difficulty.PermadayCommand;
import gg.uhc.uhc.modules.enderpearls.EnderpearlsModule;
import gg.uhc.uhc.modules.food.ExtendedSaturationModule;
import gg.uhc.uhc.modules.heads.GoldenHeadsHealthCommand;
import gg.uhc.uhc.modules.heads.GoldenHeadsModule;
import gg.uhc.uhc.modules.heads.HeadDropsModule;
import gg.uhc.uhc.modules.heads.PlayerHeadProvider;
import gg.uhc.uhc.modules.health.*;
import gg.uhc.uhc.modules.horses.HorseArmourModule;
import gg.uhc.uhc.modules.horses.HorseHealingModule;
import gg.uhc.uhc.modules.horses.HorsesModule;
import gg.uhc.uhc.modules.portals.EndModule;
import gg.uhc.uhc.modules.portals.NetherModule;
import gg.uhc.uhc.modules.potions.*;
import gg.uhc.uhc.modules.pvp.GlobalPVPModule;
import gg.uhc.uhc.modules.recipes.GlisteringMelonRecipeModule;
import gg.uhc.uhc.modules.recipes.GoldenCarrotRecipeModule;
import gg.uhc.uhc.modules.recipes.NotchApplesModule;
import gg.uhc.uhc.modules.reset.PlayerAffectingCommand;
import gg.uhc.uhc.modules.reset.resetters.*;
import gg.uhc.uhc.modules.team.*;
import gg.uhc.uhc.modules.team.requests.RequestListCommand;
import gg.uhc.uhc.modules.team.requests.RequestManager;
import gg.uhc.uhc.modules.team.requests.RequestResponseCommand;
import gg.uhc.uhc.modules.team.requests.TeamRequestCommand;
import gg.uhc.uhc.modules.teleport.TeleportCommand;
import gg.uhc.uhc.modules.timer.TimerCommand;
import gg.uhc.uhc.modules.timer.TimerModule;
import gg.uhc.uhc.modules.whitelist.WhitelistClearCommand;
import gg.uhc.uhc.modules.whitelist.WhitelistOnlineCommand;
import gg.uhc.uhc.modules.xp.NerfQuartzXPModule;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandExecutor;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scoreboard.DisplaySlot;
import java.io.File;
import java.io.IOException;
public class UHC extends JavaPlugin {
protected ModuleRegistry registry;
protected DebouncedRunnable configSaver;
protected DummyCommandFactory dummyCommands;
protected MessageTemplates baseMessages;
protected MessageTemplates baseCommandMessages;
@Override
public void onEnable() {
// setup to save the config with a debounce of 2 seconds
configSaver = new DebouncedRunnable(this, new Runnable() {
@Override
public void run() {
saveConfigNow();
}
}, 40);
FileConfiguration configuration = getConfig();
try {
baseMessages = new BaseMessageTemplates(setupMessagesConfig());
} catch (Exception e) {
e.printStackTrace();
getLogger().severe("Failed to load the messages configuration file, cannot start the plugin");
setEnabled(false);
return;
}
baseCommandMessages = new SubsectionMessageTemplates(baseMessages, "commands");
dummyCommands = new DummyCommandFactory(baseCommandMessages);
registry = new ModuleRegistry(this, baseMessages, configuration);
setupBasicModules();
setupProtocolLibModules();
setupCommand(new PlayerListHealthCommand(
commandMessages("showhealth"),
Bukkit.getScoreboardManager().getMainScoreboard(),
DisplaySlot.PLAYER_LIST,
"UHCHealth",
"Health"
), "showhealth");
PotionFuelsListener fuelsListener = new PotionFuelsListener();
registry.registerEvents(fuelsListener);
registry.register(new Tier2PotionsModule(fuelsListener));
registry.register(new SplashPotionsModule(fuelsListener));
PlayerHeadProvider headProvider = new PlayerHeadProvider();
GoldenHeadsModule gheadModule = new GoldenHeadsModule(headProvider);
boolean gheadsLoaded = registry.register(gheadModule);
setupCommand(gheadsLoaded ? new GoldenHeadsHealthCommand(commandMessages("ghead"), gheadModule) : dummyCommands.forModule(gheadModule), "ghead");
registry.register(new HeadDropsModule(headProvider));
registry.register(new DeathStandsModule());
setupTeamCommands();
setupCommand(new WorldBorderCommand(commandMessages("border")), "border");
setupCommand(new ModuleCommands(commandMessages("uhc"), registry), "uhc");
setupCommand(new PermadayCommand(commandMessages("permaday")), "permaday");
long cacheTicks = 30 * 20;
setupCommand(new PlayerAffectingCommand(commandMessages("heal"), new PlayerHealthResetter(this, cacheTicks)), "heal");
setupCommand(new PlayerAffectingCommand(commandMessages("feed"), new PlayerFoodResetter(this, cacheTicks)), "feed");
setupCommand(new PlayerAffectingCommand(commandMessages("clearxp"), new PlayerXPResetter(this, cacheTicks)), "clearxp");
setupCommand(new PlayerAffectingCommand(commandMessages("ci"), new PlayerInventoryResetter(this, cacheTicks)), "ci");
setupCommand(new PlayerAffectingCommand(commandMessages("cleareffects"), new PlayerPotionsResetter(this, cacheTicks)), "cleareffects");
setupCommand(new PlayerAffectingCommand(commandMessages("reset"), new FullPlayerResetter(this, cacheTicks)), "reset");
setupCommand(new TeleportCommand(commandMessages("tpp")), "tpp");
setupCommand(new HealthCommand(commandMessages("h")), "h");
SubcommandCommand wlist = new SubcommandCommand();
MessageTemplates forWlist = commandMessages("wlist");
wlist.registerSubcommand("clear", new WhitelistClearCommand(forWlist));
wlist.registerSubcommand(SubcommandCommand.NO_ARG_SPECIAL, new WhitelistOnlineCommand(forWlist));
setupCommand(wlist, "wlist");
// save config just to make sure at the end
saveConfig();
}
protected void setupTeamCommands() {
Optional<TeamModule> teamModuleOptional = registry.get(TeamModule.class);
if (!teamModuleOptional.isPresent()) {
getLogger().info("Skipping registering team commands as the team module is not loaded");
setupCommand(dummyCommands.forModule("TeamModule"), "teams", "team", "noteam", "pmt", "randomteams", "clearteams", "tc", "teamrequest");
}
TeamModule teamModule = teamModuleOptional.get();
setupCommand(new ListTeamsCommand(commandMessages("teams"), teamModule), "teams");
setupCommand(new NoTeamCommand(commandMessages("noteam"), teamModule), "noteam");
setupCommand(new TeamPMCommand(commandMessages("pmt"), teamModule), "pmt");
setupCommand(new RandomTeamsCommand(commandMessages("randomteams"), teamModule), "randomteams");
setupCommand(new ClearTeamsCommand(commandMessages("clearteams"), teamModule), "clearteams");
setupCommand(new TeamCoordinatesCommand(commandMessages("tc"), teamModule), "tc");
SubcommandCommand team = new SubcommandCommand();
team.registerSubcommand("teamup", new TeamupCommand(commandMessages("team.teamup"), teamModule));
team.registerSubcommand("add", new TeamAddCommand(commandMessages("team.add"), teamModule));
team.registerSubcommand("remove", new TeamRemoveCommand(commandMessages("team.remove"), teamModule));
setupCommand(team , "team");
MessageTemplates requestMessages = commandMessages("teamrequest");
RequestManager requestManager = new RequestManager(this, requestMessages, teamModule, 20 * 120);
SubcommandCommand teamrequest = new SubcommandCommand();
teamrequest.registerSubcommand("accept", new RequestResponseCommand(requestMessages, requestManager, RequestManager.AcceptState.ACCEPT));
teamrequest.registerSubcommand("deny", new RequestResponseCommand(requestMessages, requestManager, RequestManager.AcceptState.DENY));
teamrequest.registerSubcommand("request", new TeamRequestCommand(requestMessages, requestManager));
teamrequest.registerSubcommand("list", new RequestListCommand(requestMessages, requestManager));
setupCommand(teamrequest, "teamrequest");
}
protected void setupProtocolLibModules() {
if (getServer().getPluginManager().getPlugin("ProtocolLib") == null) {
getLogger().info("Skipping timer and hardcore hearts modules because protocollib is not installed");
return;
}
TimerModule timer = new TimerModule();
setupCommand(registry.register(timer) ? new TimerCommand(commandMessages("timer"), timer) : dummyCommands.forModule(timer), "timer");
Optional<AutoRespawnModule> respawn = registry.get(AutoRespawnModule.class);
if (!respawn.isPresent()) {
getLogger().info("Skipping hardcore hearts module because auto respawn is not enabled");
return;
}
registry.register(new HardcoreHeartsModule(respawn.get()));
}
protected void setupBasicModules() {
registry.register(new DifficultyModule());
registry.register(new HealthRegenerationModule());
registry.register(new GhastTearDropsModule());
registry.register(new GoldenCarrotRecipeModule());
registry.register(new GlisteringMelonRecipeModule());
registry.register(new NotchApplesModule());
registry.register(new AbsorptionModule());
registry.register(new ExtendedSaturationModule());
registry.register(new GlobalPVPModule());
registry.register(new EnderpearlsModule());
registry.register(new WitchesModule());
registry.register(new NetherModule());
registry.register(new EndModule());
registry.register(new DeathBansModule());
registry.register(new HorsesModule());
registry.register(new HorseHealingModule());
registry.register(new HorseArmourModule());
registry.register(new DeathLightningModule());
registry.register(new ModifiedDeathMessagesModule());
registry.register(new DeathItemsModule());
registry.register(new ChatHealthPrependModule());
registry.register(new NerfQuartzXPModule());
registry.register(new AutoRespawnModule());
registry.register(new PercentHealthObjectiveModule());
registry.register(new TeamModule());
}
protected void setupCommand(CommandExecutor executor, String... commands) {
for (String command : commands) {
getCommand(command).setExecutor(executor);
}
}
private MessageTemplates commandMessages(String command) {
return new SubsectionMessageTemplates(baseCommandMessages, command);
}
@Override
public void saveConfig() {
configSaver.trigger();
}
public void saveConfigNow() {
super.saveConfig();
getLogger().info("Saved configuration changes");
}
public ModuleRegistry getRegistry() {
return registry;
}
protected Config setupMessagesConfig() throws IOException {
// copy reference across
saveResource("messages.reference.conf", true);
// parse fallback config
File reference = new File(getDataFolder(), "messages.reference.conf");
Config fallback = ConfigFactory.parseFile(reference);
// parse user provided config
File regular = new File(getDataFolder(), "messages.conf");
Config user;
if (regular.exists()) {
user = ConfigFactory.parseFile(regular);
} else {
user = ConfigFactory.empty();
}
return user.withFallback(fallback).resolve(ConfigResolveOptions.noSystem());
}
}
| fix /team request error with config key
| src/main/java/gg/uhc/uhc/UHC.java | fix /team request error with config key | <ide><path>rc/main/java/gg/uhc/uhc/UHC.java
<ide> team.registerSubcommand("remove", new TeamRemoveCommand(commandMessages("team.remove"), teamModule));
<ide> setupCommand(team , "team");
<ide>
<del> MessageTemplates requestMessages = commandMessages("teamrequest");
<add> MessageTemplates requestMessages = commandMessages("team.teamrequest");
<ide> RequestManager requestManager = new RequestManager(this, requestMessages, teamModule, 20 * 120);
<ide>
<ide> SubcommandCommand teamrequest = new SubcommandCommand(); |
|
JavaScript | mpl-2.0 | 76112516e4da3c733c18636ab015b542a8f2d3d9 | 0 | ewasm/evm2wasm,ewasm/evm2wasm | const fs = require('fs')
const tape = require('tape')
const Kernel = require('ewasm-kernel')
const KernelInterface = require('ewasm-kernel/interface.js')
const KernelEnvironment = require('ewasm-kernel/environment.js')
const ethUtil = require('ethereumjs-util')
const compiler = require('../index.js')
const dir = `${__dirname}/opcode`
let testFiles = fs.readdirSync(dir).filter((name) => name.endsWith('.json'))
tape('testing EVM1 Ops', (t) => {
testFiles.forEach((path) => {
let opTest = require(`${dir}/${path}`)
opTest.forEach((test) => {
const testEnvironment = new KernelEnvironment()
const testInterface = new KernelInterface(testEnvironment)
const testInstance = buildTest(test.op)
t.comment(`testing ${test.description}`)
// populate the stack with predefined values
test.stack.in.reverse().forEach((item, index) => {
item = hexToUint8Array(item)
setMemory(testInstance, item, index * 32)
})
// populate the memory
if (test.memory) {
Object.keys(test.memory.in).forEach((offset) => {
test.memory.in[offset].forEach((item, index) => {
offset |= 0
item = hexToUint8Array(item)
setMemory(testInstance, item, offset + index * 32)
})
})
}
// Runs the opcode. An empty stack must start with the stack pointer at -8.
// also we have to add 8 to the resulting sp to accommodate for the fact
// that the sp is pointing to memory segment holding the last stack item
let sp = testInstance.exports[test.op](test.stack.in.length * 32 - 8) + 8
t.equal(sp / 32, test.stack.out.length, 'should have corrent number of items on the stack')
sp = 0
// compare the output stack against the predefined values
test.stack.out.forEach((item, index) => {
const expectedItem = hexToUint8Array(item)
const result = getMemory(testInstance, sp, sp = sp + 32)
t.equals(result.toString(), expectedItem.toString(), 'should have correct item on stack')
})
// check the memory
if (test.memory) {
Object.keys(test.memory.out).forEach((offset) => {
test.memory.out[offset].forEach((item, index) => {
offset |= 0
const expectedItem = hexToUint8Array(item)
const result = getMemory(testInstance, offset + index * 32, offset + index * 32 + expectedItem.length)
t.equals(result.toString(), expectedItem.toString(), `should have the correct memory slot at ${offset}:${index}`)
})
})
}
// check for EVM return value
if (test.return) {
const expectedItem = hexToUint8Array(test.return)
//const result = testEnvironment.returnValue
const result = testInterface.env.returnValue
t.equals(result.toString(), expectedItem.toString(), 'should have correct return value')
}
})
})
t.end()
})
function buildTest (op, interface) {
const funcs = compiler.resolveFunctions(new Set([op]))
const linked = compiler.buildModule(funcs, [], [op])
const wasm = compiler.compileWAST(linked)
return Kernel.codeHandler(wasm, interface)
}
function hexToUint8Array(item, length) {
return new Uint8Array(ethUtil.setLength(new Buffer(item.slice(2), 'hex'), 32)).reverse()
}
function setMemory(instance, value, start) {
new Uint8Array(instance.exports.memory).set(value, start)
}
function getMemory(instance, start, end) {
return new Uint8Array(instance.exports.memory).slice(start, end)
}
| tests/opcodeRunner.js | const fs = require('fs')
const tape = require('tape')
const Kernel = require('ewasm-kernel')
const KernelInterface = require('ewasm-kernel/interface.js')
const KernelEnvironment = require('ewasm-kernel/environment.js')
const ethUtil = require('ethereumjs-util')
const compiler = require('../index.js')
const dir = `${__dirname}/opcode`
let testFiles = fs.readdirSync(dir).filter((name) => name.endsWith('.json'))
tape('testing EVM1 Ops', (t) => {
testFiles.forEach((path) => {
let opTest = require(`${dir}/${path}`)
opTest.forEach((test) => {
const testEnvironment = new KernelEnvironment()
const testInterface = new KernelInterface(testEnvironment)
const testInstance = buildTest(test.op)
t.comment(`testing ${test.description}`)
// populate the stack with predefined values
test.stack.in.reverse().forEach((item, index) => {
item = hexToUint8Array(item)
setMemory(testInstance, item, index * 32)
})
// populate the memory
if (test.memory) {
Object.keys(test.memory.in).forEach((offset) => {
test.memory.in[offset].forEach((item, index) => {
offset |= 0
item = hexToUint8Array(item)
setMemory(testInstance, item, offset + index * 32)
})
})
}
// Runs the opcode. An empty stack must start with the stack pointer at -8.
// also we have to add 8 to the resulting sp to accommodate for the fact
// that the sp is pointing to memory segment holding the last stack item
let sp = testInstance.exports[test.op](test.stack.in.length * 32 - 8) + 8
t.equal(sp / 32, test.stack.out.length, 'should have corrent number of items on the stack')
sp = 0
// compare the output stack against the predefined values
test.stack.out.forEach((item, index) => {
const expectedItem = hexToUint8Array(item)
const result = getMemory(testInstance, sp, sp = sp + 32)
t.equals(result.toString(), expectedItem.toString(), 'should have correct item on stack')
})
// check the memory
if (test.memory) {
Object.keys(test.memory.out).forEach((offset) => {
test.memory.out[offset].forEach((item, index) => {
offset |= 0
const expectedItem = hexToUint8Array(item)
const result = getMemory(testInstance, offset + index * 32, offset + index * 32 + expectedItem.length)
t.equals(result.toString(), expectedItem.toString(), `should have the correct memory slot at ${offset}:${index}`)
})
})
}
})
})
t.end()
})
function buildTest (op, interface) {
const funcs = compiler.resolveFunctions(new Set([op]))
const linked = compiler.buildModule(funcs, [], [op])
const wasm = compiler.compileWAST(linked)
return Kernel.codeHandler(wasm, interface)
}
function hexToUint8Array(item, length) {
return new Uint8Array(ethUtil.setLength(new Buffer(item.slice(2), 'hex'), 32)).reverse()
}
function setMemory(instance, value, start) {
new Uint8Array(instance.exports.memory).set(value, start)
}
function getMemory(instance, start, end) {
return new Uint8Array(instance.exports.memory).slice(start, end)
}
| opcodeRunner: compare return value
| tests/opcodeRunner.js | opcodeRunner: compare return value | <ide><path>ests/opcodeRunner.js
<ide> })
<ide> }
<ide>
<add> // check for EVM return value
<add> if (test.return) {
<add> const expectedItem = hexToUint8Array(test.return)
<add> //const result = testEnvironment.returnValue
<add> const result = testInterface.env.returnValue
<add> t.equals(result.toString(), expectedItem.toString(), 'should have correct return value')
<add> }
<ide> })
<ide> })
<ide> t.end() |
|
JavaScript | agpl-3.0 | 41376467ac79769da485534a0f5662cf275bfb47 | 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 | 2988ad32-2e63-11e5-9284-b827eb9e62be | helloWorld.js | 298331c2-2e63-11e5-9284-b827eb9e62be | 2988ad32-2e63-11e5-9284-b827eb9e62be | helloWorld.js | 2988ad32-2e63-11e5-9284-b827eb9e62be | <ide><path>elloWorld.js
<del>298331c2-2e63-11e5-9284-b827eb9e62be
<add>2988ad32-2e63-11e5-9284-b827eb9e62be |
|
Java | apache-2.0 | 459b28d52ca952d9f28ecea5dc7fcfb6c06aa579 | 0 | tempbottle/jsimpledb,archiecobbs/jsimpledb,permazen/permazen,permazen/permazen,permazen/permazen,archiecobbs/jsimpledb,archiecobbs/jsimpledb,tempbottle/jsimpledb,tempbottle/jsimpledb |
/*
* Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
*
* $Id$
*/
package org.dellroad.stuff.jibx;
import java.util.Iterator;
import java.util.Map;
import org.jibx.runtime.JiBXParseException;
/**
* Utility class for modeling {@link Map} properties in JiBX.
*
* <p>
* For example, suppose you have a class {@code Company} with a property named {@code directory} that has
* type {@code Map<String, Person>}. Then you would define these methods in {@code Company.java}:
*
* <blockquote><pre>
* // Getter and setter
* public Map<String, Person> getDirectory() {
* return this.directory;
* }
* public void setDirectory(Map<String, Person> directory) {
* this.directory = directory;
* }
*
* // JiBX "add-method"
* public void addDirectoryEntry(MapEntry<String, Person> direntry) {
* MapEntry.add(this.directory, direntry);
* }
*
* // JiBX "iter-method"
* public Iterator<MapEntry<String, Person>> iterateDirectory() {
* return MapEntry.iterate(this.directory);
* }
* </pre></blockquote>
*
* <p>
* Then in your JiBX binding definition, you would do something like this:
*
* <blockquote><pre>
* <binding package="com.example">
*
* <!-- Include XML mapping definition for a Person object with type-name "person" -->
* <include path="person.xml"/>
*
* <!-- Define XML mapping for one entry in the directory map -->
* <mapping abstract="true" type-name="directory_entry" class="org.dellroad.stuff.jibx.MapEntry">
* <value name="name" field="key" type="java.lang.String" style="attribute"/>
* <structure name="Person" field="value" map-as="person"/>
* </mapping>
*
* <!-- Define XML mapping for a Company object -->
* <mapping abstract="true" type-name="company" class="com.example.Company">
* <collection name="Directory" item-type="org.dellroad.stuff.jibx.MapEntry"
* add-method="addDirectoryEntry" iter-method="iterateDirectory">
* <structure name="DirectoryEntry" map-as="directory_entry"/>
* </collection>
* <!-- other properties... -->
* </mapping>
* </binding>
* </pre></blockquote>
*
* Then the resulting XML would look something like this:
* <blockquote><pre>
* <Company>
* <Directory>
* <DirectoryEntry name="George Washington">
* <Person>
* <!-- properties of George Washington... -->
* </Person>
* </DirectoryEntry>
* <DirectoryEntry name="Besty Ross">
* <Person>
* <!-- properties of Besty Ross... -->
* </Person>
* </DirectoryEntry>
* </Directory>
* <!-- other properties... -->
* </Company>
* </pre></blockquote>
*/
public class MapEntry<K, V> {
private K key;
private V value;
/**
* Default constructor. Initializes both key and value to {@code null}.
*/
public MapEntry() {
}
/**
* Primary constructor.
*
* @param key map entry key
* @param value map entry value
*/
public MapEntry(K key, V value) {
this.key = key;
this.value = value;
}
/**
* Get this map entry's key.
*/
public K getKey() {
return this.key;
}
public void setKey(K key) {
this.key = key;
}
/**
* Get this map entry's value.
*/
public V getValue() {
return this.value;
}
public void setValue(V value) {
this.value = value;
}
/**
* Helper method intended to be used by a custom JiBX "iter-method".
* This method returns an iterator that iterates over all entries in the given map.
*
* @param map map to iterate
* @return map entry iterator
*/
public static <K, V> Iterator<MapEntry<K, V>> iterate(Map<K, V> map) {
final Iterator<Map.Entry<K, V>> entryIterator = map.entrySet().iterator();
return new Iterator<MapEntry<K, V>>() {
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public MapEntry<K, V> next() {
Map.Entry<K, V> entry = entryIterator.next();
return new MapEntry<K, V>(entry.getKey(), entry.getValue());
}
@Override
public void remove() {
entryIterator.remove();
}
};
}
/**
* Helper method intended to be used by a custom JiBX "add-method".
* If there is an existing entry with the same key, a {@link JiBXParseException} is thrown.
*
* @param map map to which to add an new entry
* @param entry new entry to add
* @throws JiBXParseException if the map already contains an entry with the given key
*/
public static <K, V> void add(Map<K, V> map, MapEntry<? extends K, ? extends V> entry) throws JiBXParseException {
MapEntry.add(map, entry, false);
}
/**
* Helper method intended to be used by a custom JiBX "add-method".
*
* @param map map to which to add an new entry
* @param entry new entry to add
* @param allowDuplicate {@code true} to replace any existing entry having the same key,
* or {@code false} to throw a {@link JiBXParseException} if there is an existing entry
* @throws JiBXParseException if {@code allowDuplicate} is {@code false} and an entry
* with the same key already exists in {@code map}
*/
public static <K, V> void add(Map<K, V> map, MapEntry<? extends K, ? extends V> entry, boolean allowDuplicate)
throws JiBXParseException {
K key = entry.getKey();
V value = entry.getValue();
if (!allowDuplicate && map.containsKey(key))
throw new JiBXParseException("duplicate key in map", "" + key);
map.put(key, value);
}
}
| src/java/org/dellroad/stuff/jibx/MapEntry.java |
/*
* Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
*
* $Id$
*/
package org.dellroad.stuff.jibx;
import java.util.Iterator;
import java.util.Map;
/**
* Utility class for modeling {@link Map} properties in JiBX.
*
* <p>
* For example, suppose you have a class {@code Company} with a property named {@code directory} that has
* type {@code Map<String, Person>}. Then you would define these methods in {@code Company.java}:
*
* <blockquote><code>
* // Getter and setter
* public Map<String, Person> getDirectory() {
* return this.directory;
* }
* public void setDirectory(Map<String, Person> directory) {
* this.directory = directory;
* }
*
* // JiBX "add-method"
* public void addDirectoryEntry(MapEntry<String, Person> entry) {
* MapEntry.add(this.directory, entry);
* }
*
* // JiBX "iter-method"
* public Iterator<MapEntry<String, Person> iterateDirectory() {
* return MapEntry.iterate(this.directory);
* }
* </code></blockquote>
*
* <p>
* Then in your JiBX binding definition, you would do something like this:
*
* <blockquote><code>
* <binding package="com.example">
*
* <!-- Include XML mapping definition for a Person object -->
* <include path="person.xml"/>
*
* <!-- Define XML mapping for one entry in the directory map -->
* <mapping abstract="true" type-name="directory_entry" class="org.dellroad.stuff.jibx.MapEntry">
* <value name="name" field="key" type="java.lang.String" style="attribute"/>
* <structure name="person" map-as="person"/>
* </mapping>
*
* <!-- Define XML mapping for a Company object -->
* <mapping abstract="true" type-name="company" class="com.example.Company">
* <collection name="directory" item-type="org.dellroad.stuff.jibx.MapEntry"
* add-method="addDirectoryEntry" iter-method="iterateDirectory">
* <structure name="entry" map-as="directory_entry"/>
* </collection>
* <!-- other properties... -->
* </mapping>
* </binding>
* </code></blockquote>
*
* The resulting XML would look like this:
* <blockquote><code>
* <company>
* <directory>
* <entry name="George Washington">
* <person>
* <!-- properties of George Washington... -->
* </person>
* </entry>
* <entry name="Besty Ross">
* <person>
* <!-- properties of Besty Ross... -->
* </person>
* </entry>
* </directory>
* <!-- other properties... -->
* </company>
*/
public class MapEntry<K, V> {
private K key;
private V value;
/**
* Default constructor. Initializes both key and value to {@code null}.
*/
public MapEntry() {
}
/**
* Primary constructor.
*
* @param key map entry key
* @param value map entry value
*/
public MapEntry(K key, V value) {
this.key = key;
this.value = value;
}
/**
* Get this map entry's key.
*/
public K getKey() {
return this.key;
}
public void setKey(K key) {
this.key = key;
}
/**
* Get this map entry's value.
*/
public V getValue() {
return this.value;
}
public void setValue(V value) {
this.value = value;
}
/**
* Helper method intended to be used by a custom JiBX "iter-method".
* This method returns an iterator that iterates over all entries in the given map.
*
* @param map map to iterate
* @return map entry iterator
*/
public static <K, V> Iterator<MapEntry<K, V>> iterate(Map<K, V> map) {
final Iterator<Map.Entry<K, V>> entryIterator = map.entrySet().iterator();
return new Iterator<MapEntry<K, V>>() {
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public MapEntry<K, V> next() {
Map.Entry<K, V> entry = entryIterator.next();
return new MapEntry<K, V>(entry.getKey(), entry.getValue());
}
@Override
public void remove() {
entryIterator.remove();
}
};
}
/**
* Helper method intended to be used by a custom JiBX "add-method".
* The new entry is added to the map, replacing any existing entry with the same key.
*
* @param map map to which to add an new entry
* @param entry new entry to add
*/
public static <K, V> void add(Map<K, V> map, MapEntry<? extends K, ? extends V> entry) {
map.put(entry.getKey(), entry.getValue());
}
}
| - Add "allowDuplicates" parameter to add() and throw JiBXParseException if not.
- Fix Javadoc.
| src/java/org/dellroad/stuff/jibx/MapEntry.java | - Add "allowDuplicates" parameter to add() and throw JiBXParseException if not. - Fix Javadoc. | <ide><path>rc/java/org/dellroad/stuff/jibx/MapEntry.java
<ide> import java.util.Iterator;
<ide> import java.util.Map;
<ide>
<add>import org.jibx.runtime.JiBXParseException;
<add>
<ide> /**
<ide> * Utility class for modeling {@link Map} properties in JiBX.
<ide> *
<ide> * For example, suppose you have a class {@code Company} with a property named {@code directory} that has
<ide> * type {@code Map<String, Person>}. Then you would define these methods in {@code Company.java}:
<ide> *
<del> * <blockquote><code>
<add> * <blockquote><pre>
<ide> * // Getter and setter
<del> * public Map<String, Person> getDirectory() {
<add> * public Map<String, Person> getDirectory() {
<ide> * return this.directory;
<ide> * }
<del> * public void setDirectory(Map<String, Person> directory) {
<add> * public void setDirectory(Map<String, Person> directory) {
<ide> * this.directory = directory;
<ide> * }
<ide> *
<ide> * // JiBX "add-method"
<del> * public void addDirectoryEntry(MapEntry<String, Person> entry) {
<del> * MapEntry.add(this.directory, entry);
<add> * public void addDirectoryEntry(MapEntry<String, Person> direntry) {
<add> * MapEntry.add(this.directory, direntry);
<ide> * }
<ide> *
<ide> * // JiBX "iter-method"
<del> * public Iterator<MapEntry<String, Person> iterateDirectory() {
<add> * public Iterator<MapEntry<String, Person>> iterateDirectory() {
<ide> * return MapEntry.iterate(this.directory);
<ide> * }
<del> * </code></blockquote>
<add> * </pre></blockquote>
<ide> *
<ide> * <p>
<ide> * Then in your JiBX binding definition, you would do something like this:
<ide> *
<del> * <blockquote><code>
<add> * <blockquote><pre>
<ide> * <binding package="com.example">
<ide> *
<del> * <!-- Include XML mapping definition for a Person object -->
<add> * <!-- Include XML mapping definition for a Person object with type-name "person" -->
<ide> * <include path="person.xml"/>
<ide> *
<ide> * <!-- Define XML mapping for one entry in the directory map -->
<ide> * <mapping abstract="true" type-name="directory_entry" class="org.dellroad.stuff.jibx.MapEntry">
<ide> * <value name="name" field="key" type="java.lang.String" style="attribute"/>
<del> * <structure name="person" map-as="person"/>
<add> * <structure name="Person" field="value" map-as="person"/>
<ide> * </mapping>
<ide> *
<ide> * <!-- Define XML mapping for a Company object -->
<ide> * <mapping abstract="true" type-name="company" class="com.example.Company">
<del> * <collection name="directory" item-type="org.dellroad.stuff.jibx.MapEntry"
<add> * <collection name="Directory" item-type="org.dellroad.stuff.jibx.MapEntry"
<ide> * add-method="addDirectoryEntry" iter-method="iterateDirectory">
<del> * <structure name="entry" map-as="directory_entry"/>
<add> * <structure name="DirectoryEntry" map-as="directory_entry"/>
<ide> * </collection>
<ide> * <!-- other properties... -->
<ide> * </mapping>
<ide> * </binding>
<del> * </code></blockquote>
<add> * </pre></blockquote>
<ide> *
<del> * The resulting XML would look like this:
<del> * <blockquote><code>
<del> * <company>
<del> * <directory>
<del> * <entry name="George Washington">
<del> * <person>
<add> * Then the resulting XML would look something like this:
<add> * <blockquote><pre>
<add> * <Company>
<add> * <Directory>
<add> * <DirectoryEntry name="George Washington">
<add> * <Person>
<ide> * <!-- properties of George Washington... -->
<del> * </person>
<del> * </entry>
<del> * <entry name="Besty Ross">
<del> * <person>
<add> * </Person>
<add> * </DirectoryEntry>
<add> * <DirectoryEntry name="Besty Ross">
<add> * <Person>
<ide> * <!-- properties of Besty Ross... -->
<del> * </person>
<del> * </entry>
<del> * </directory>
<add> * </Person>
<add> * </DirectoryEntry>
<add> * </Directory>
<ide> * <!-- other properties... -->
<del> * </company>
<add> * </Company>
<add> * </pre></blockquote>
<ide> */
<ide> public class MapEntry<K, V> {
<ide>
<ide>
<ide> /**
<ide> * Helper method intended to be used by a custom JiBX "add-method".
<del> * The new entry is added to the map, replacing any existing entry with the same key.
<add> * If there is an existing entry with the same key, a {@link JiBXParseException} is thrown.
<ide> *
<ide> * @param map map to which to add an new entry
<ide> * @param entry new entry to add
<add> * @throws JiBXParseException if the map already contains an entry with the given key
<ide> */
<del> public static <K, V> void add(Map<K, V> map, MapEntry<? extends K, ? extends V> entry) {
<del> map.put(entry.getKey(), entry.getValue());
<add> public static <K, V> void add(Map<K, V> map, MapEntry<? extends K, ? extends V> entry) throws JiBXParseException {
<add> MapEntry.add(map, entry, false);
<add> }
<add>
<add> /**
<add> * Helper method intended to be used by a custom JiBX "add-method".
<add> *
<add> * @param map map to which to add an new entry
<add> * @param entry new entry to add
<add> * @param allowDuplicate {@code true} to replace any existing entry having the same key,
<add> * or {@code false} to throw a {@link JiBXParseException} if there is an existing entry
<add> * @throws JiBXParseException if {@code allowDuplicate} is {@code false} and an entry
<add> * with the same key already exists in {@code map}
<add> */
<add> public static <K, V> void add(Map<K, V> map, MapEntry<? extends K, ? extends V> entry, boolean allowDuplicate)
<add> throws JiBXParseException {
<add> K key = entry.getKey();
<add> V value = entry.getValue();
<add> if (!allowDuplicate && map.containsKey(key))
<add> throw new JiBXParseException("duplicate key in map", "" + key);
<add> map.put(key, value);
<ide> }
<ide> }
<ide> |
|
JavaScript | unlicense | aad8311b87da9b56f563b685128832b04e4b55f6 | 0 | Babazka/youtube-html-playlister,Babazka/youtube-html-playlister | function MyYoutubePlayer() {
var that = this;
this.playlist_collection = [];
this.now_playing_list = [];
this.now_playing_video_id = '';
this.current_playlist = '';
this.undo_context = null;
this.localSave = function() {
this.undo_context = localStorage.getItem('my_youtube_data_context');
var context = {
'collection': this.playlist_collection,
'now_playing_list': this.now_playing_list
};
var dump = JSON.stringify(context);
localStorage.setItem('my_youtube_data_context', dump);
};
this.localLoad = function() {
var dump = localStorage.getItem('my_youtube_data_context');
if (!!dump) {
var context = JSON.parse(dump);
this.playlist_collection = context.collection;
this.now_playing_list = context.now_playing_list;
}
this.updateView();
};
this.stashUrl = 'http://a-kr.ru/stash/?key=tube';
this.mustGetStashKeySuffix = function() {
var suffix = localStorage.getItem('my_youtube_stash_suffix');
if (!suffix) {
suffix = prompt("Please enter your email", "[email protected]");
if (!suffix) {
throw 'empty email';
}
localStorage.setItem('my_youtube_stash_suffix', suffix)
}
return encodeURIComponent(suffix);
};
this.stash = function() {
var that = this;
var stashKeySuffix = that.mustGetStashKeySuffix();
var url = that.stashUrl + stashKeySuffix;
var dump = localStorage.getItem('my_youtube_data_context');
$.ajax(url, {
success: function() {
alert("Stashed at: " + url);
},
error: function(xhr, httpStatus) {
alert("Stash error: " + httpStatus);
},
data: dump,
headers: {
'Content-Type': 'text/plain'
},
method: 'POST'
});
};
this.stashPop = function() {
var that = this;
var dump = localStorage.getItem('my_youtube_data_context');
var stashKeySuffix = that.mustGetStashKeySuffix();
var url = that.stashUrl + stashKeySuffix;
localStorage.setItem('my_youtube_data_context_before_stash_pop', dump);
$.ajax(url, {
success: function(data) {
if (!!data) {
localStorage.setItem('my_youtube_data_context', data);
that.localLoad();
alert("Stash restored");
} else {
alert("Empty data restored from " + url);
}
},
error: function(xhr, httpStatus) {
alert("Stash pop error: " + httpStatus);
},
method: 'GET'
});
};
this.undoStashPop = function() {
var dump = localStorage.getItem('my_youtube_data_context_before_stash_pop');
if (!!dump) {
localStorage.setItem('my_youtube_data_context', dump);
that.localLoad();
alert("Stash pop rolled back");
} else {
alert("No saved data before stash pop");
}
};
this.undoChanges = function() {
var dump = this.undo_context;
if (!!dump) {
var context = JSON.parse(dump);
this.playlist_collection = context.collection;
this.now_playing_list = context.now_playing_list;
this.localSave();
} else {
this.alert('Cannot undo further');
return;
}
this.updateView();
};
this.reorderVideoList = function(list, id_order) {
var dict = {};
while (list.length > 0) {
var video = list.pop();
dict[video.id] = video;
}
for (var i = 0; i < id_order.length; i++) {
var video = dict[id_order[i]];
list.push(video);
}
};
this.shuffleNowPlaying = function() {
var new_now_playing = [];
while (this.now_playing_list.length > 0) {
var i = Math.trunc(Math.random() * this.now_playing_list.length);
new_now_playing.push(this.now_playing_list[i]);
this.now_playing_list.splice(i, 1);
}
this.now_playing_list = new_now_playing;
this.updateView();
};
this.createPlaylist = function(title, videos) {
if (!title) {
that.alert('Cannot create playlist without a title');
return false;
}
for (var i = 0; i < this.playlist_collection.length; i++) {
if (this.playlist_collection.title == title) {
that.alert('Playlist with this title already exists');
return false;
}
}
var new_videos = [];
for (var i = 0; i < videos.length; i++) {
new_videos.push(videos[i]);
}
var playlist = {
'title': title,
'videos': new_videos
};
this.playlist_collection.push(playlist);
this.current_playlist = title;
this.localSave();
this.updateView();
};
this.getCurrentPlaylist = function() {
for (var i = 0; i < this.playlist_collection.length; i++) {
var playlist = this.playlist_collection[i];
if (playlist.title == this.current_playlist) {
return playlist;
}
}
};
this.deleteCurrentPlaylist = function() {
if (this.playlist_collection.length <= 1) {
this.alert('Cannot delete last playlist');
return;
}
var new_collection = [];
for (var i = 0; i < this.playlist_collection.length; i++) {
var playlist = this.playlist_collection[i];
if (playlist.title != this.current_playlist) {
new_collection.push(playlist);
}
};
this.playlist_collection = new_collection;
this.current_playlist = new_collection[0].title;
this.localSave();
this.updateView();
};
this.playNowPlaying = function() {
if (this.now_playing_list.length == 0) {
return;
}
this.now_playing_video_id = this.now_playing_list[0].id;
var selected_id = $('input[name="now_playing"]:checked').val();
if (!!selected_id) {
this.now_playing_video_id = selected_id;
} else {
$('input.now_playing_radio[value="' + this.now_playing_video_id + '"]').attr('checked', 'checked');
}
this.setPlayerToNextTrack(this.now_playing_video_id);
};
this.setPlayerToNextTrack = function(video_id) {
if (video_id.endsWith('.mp3')) {
window.ytplayer.stopVideo();
window.auplayer.src = video_id;
window.auplayer.play();
} else {
window.auplayer.pause();
window.ytplayer.loadVideoById(video_id, 0);
}
};
this.getNextVideo = function() {
var mode = ($('#rd_mode_list').is(':checked')) ? 'list' : 'loop';
for (var i = 0; i < this.now_playing_list.length; i++) {
var el_id = '#now_video_' + i;
if ($(el_id).is(':checked')) {
var j;
if (mode == 'loop') {
j = i;
} else {
if (this.now_playing_list[i].id == this.now_playing_video_id) {
j = (i + 1) % this.now_playing_list.length;
} else {
j = i;
}
}
this.now_playing_video_id = this.now_playing_list[j].id;
var new_el_id = '#now_video_' + j;
$(new_el_id).attr('checked', 'checked');
$(new_el_id).prop('checked', true);
return this.now_playing_video_id;
}
}
};
this.getCurrentPlaylistVideo = function(video_id) {
var playlist = this.getCurrentPlaylist();
for (var i = 0; i < playlist.videos.length; i++) {
if (playlist.videos[i].id == video_id) {
return playlist.videos[i];
}
}
};
this.getNowPlayingVideo = function(video_id) {
var list = this.now_playing_list;
for (var i = 0; i < list.length; i++) {
if (list[i].id == video_id) {
return list[i];
}
}
};
this.removeFromNowPlaying = function(video_id) {
var new_now_playing = [];
for (var i = 0; i < this.now_playing_list.length; i++) {
if (this.now_playing_list[i].id == video_id) {
continue;
}
new_now_playing.push(this.now_playing_list[i]);
}
this.now_playing_list = new_now_playing;
this.localSave();
this.updateView();
};
this.removeFromCurrentPlaylist = function(video_id) {
var new_list = [];
var playlist = this.getCurrentPlaylist();
for (var i = 0; i < playlist.videos.length; i++) {
if (playlist.videos[i].id == video_id) {
continue;
}
new_list.push(playlist.videos[i]);
}
playlist.videos = new_list;
this.localSave();
this.updateView();
};
this.addToCurrentPlaylist = function(video) {
if (!video) {
return;
}
var playlist = this.getCurrentPlaylist();
for (var i = 0; i < playlist.videos.length; i++) {
if (playlist.videos[i].id == video.id) {
that.alert('This video is already in the playlist');
return false;
}
}
playlist.videos.push(video);
this.localSave();
this.updateView();
};
this.appendToCurrentPlaylist = function(list) {
if (!list) {
return;
}
var playlist = this.getCurrentPlaylist();
var playlist_length = playlist.videos.length;
for (var j = 0; j < list.length; j++) {
var video = list[j];
for (var i = 0; i < playlist_length; i++) {
if (playlist.videos[i].id == video.id) {
that.alert('This video is already in the playlist');
return false;
}
}
playlist.videos.push(video);
}
this.localSave();
this.updateView();
};
this.playlistToNowPlaying = function() {
var now_playing_length = this.now_playing_list.length;
var playlist = this.getCurrentPlaylist();
for (var i = 0; i < playlist.videos.length; i++) {
var video = playlist.videos[i];
var existing_index = null;
for (var j = 0; j < now_playing_length; j++) {
if (video.id == this.now_playing_list[j].id) {
existing_index = j;
break;
}
}
if (existing_index !== null) {
continue;
}
this.now_playing_list.push(video);
}
this.localSave();
this.updateView();
};
this.addToNowPlaying = function(video) {
if (!video) {
return;
}
for (var i = 0; i < this.now_playing_list.length; i++) {
if (this.now_playing_list[i].id == video.id) {
that.alert('This video is already in Now Playing');
return false;
}
}
this.now_playing_list.push(video);
this.localSave();
this.updateView();
};
this.alert = function(text) {
var el = $('#alert_div');
el.removeClass('okay');
el.addClass('warning');
el.text(text);
};
this.clearAlert = function(text) {
var el = $('#alert_div');
el.removeClass('warning');
el.addClass('okay');
el.text('Everything is OK');
};
this.updateView = function() {
this.clearAlert();
if (this.playlist_collection.length == 0) {
this.createPlaylist('Misc', []);
}
if (!this.current_playlist) {
this.current_playlist = this.playlist_collection[0].title;
}
/* displaying playlist collection */
var pc_el = $('#playlist_collection');
var html = '';
var selected_playlist = null;
for (var i = 0; i < this.playlist_collection.length; i++) {
var playlist = this.playlist_collection[i];
var id = "plt_" + i;
var checked = '';
if (playlist.title == this.current_playlist) {
checked = 'checked';
selected_playlist = playlist;
}
var el = '<label class="collection-item" for="' + id + '">';
el += '<input type="radio" group="p_collection" name="p_collection" value="' +
playlist.title + '" id="' + id +'" ' + checked + '>';
el += playlist.title +
' (' + playlist.videos.length + ')</label><br/>';
html += el;
}
pc_el.html(html);
/* displaying playlist contents */
pc_el = $('#playlist_contents');
html = '';
for (var i = 0; i < selected_playlist.videos.length; i++) {
var video = selected_playlist.videos[i];
var id = "plt_video_" + i;
var checked = '';
var el = '<div><label class="playlist-item" data-video_id="' + video.id + '" for="' + id + '">';
el += '<input type="radio" group="p_playlist" name="playlist" value="' +
video.id + '" id="' + id +'" ' + checked + '>';
el += '<a href="#" title="Rename track" data-video_id="' + video.id + '" class="jsa a-rename-track">R</a> '
el += '<a href="#" title="Delete track" data-video_id="' + video.id + '" class="jsa a-remove-track">X</a> '
el += video.title + '</label></div>';
html += el;
}
pc_el.html(html);
/* displaying now playing */
pc_el = $('#now_playing');
html = '';
for (var i = 0; i < this.now_playing_list.length; i++) {
var video = this.now_playing_list[i];
var id = "now_video_" + i;
var checked = '';
if (video.id == this.now_playing_video_id) {
checked = 'checked';
}
var el = '<div><label class="now-playing-item" data-video_id="' + video.id + '" for="' + id + '">';
el += '<input type="radio" class="now_playing_radio" group="p_now_playing" name="now_playing" value="' +
video.id + '" id="' + id +'" ' + checked + '>';
el += '<a href="#" title="Remove track" data-video_id="' + video.id + '" class="jsa a-remove-from-now-playing">X</a> '
el += '<a href="#" title="Add to current playlist" data-video_id="' + video.id + '" class="jsa a-from-now-playing-to-current-playlist">P</a> '
el += video.title + '</label></div>';
html += el;
}
pc_el.html(html);
};
this.parseUrlForVideoId = function(url) {
// https://www.youtube.com/watch?v=lPM2NLRdtOg&list=PL7C183EA1B833B690
var match = /\?v=([^&]+)/.exec(url);
if (!match || match.length < 2) {
return null;
}
return match[1];
};
this.parseUrlForPlaylistId = function(url) {
// https://www.youtube.com/watch?v=lPM2NLRdtOg&list=PL7C183EA1B833B690
var match = /[\?&]list=([^&]+)/.exec(url);
if (!match || match.length < 2) {
return null;
}
return match[1];
};
this.importVideoByUrl = function(url) {
if (url.endsWith('.mp3')) {
var video = {
'id': url,
'title': url.match(/[^\/]+$/)[0]
};
that.addToCurrentPlaylist(video);
that.addToNowPlaying(video);
return;
}
var video_id = this.parseUrlForVideoId(url);
if (!video_id) {
that.alert('URL does not look like YouTube video url');
return;
}
$.get("https://www.googleapis.com/youtube/v3/videos?part=snippet&id=" + video_id + "&key=AIzaSyABdTdueRpC67F1aplCb1kccFhevFScI48", function(data) {
if (data['items'].length == 0) {
that.alert('Video not found');
return;
}
var video = {
'id': video_id,
'title': data['items'][0]['snippet']['title']
};
that.addToCurrentPlaylist(video);
that.addToNowPlaying(video);
});
};
this.importPlaylistByUrl = function(url, title, page_token) {
var playlist_id = this.parseUrlForPlaylistId(url);
if (!playlist_id) {
that.alert('URL does not seem to contain YouTube playlist id');
return;
}
var apiurl;
if (!title) {
$.get("https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=" + playlist_id + "&key=AIzaSyABdTdueRpC67F1aplCb1kccFhevFScI48", function(data) {
if (data['items'].length == 0) {
that.alert('Playlist not found');
return;
};
var title = data['items'][0]['snippet']['title'];
if (!title) {
that.alert('Cannot determine playlist title');
return;
}
that.importPlaylistByUrl(url, title);
});
return;
}
apiurl = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=" + playlist_id + "&key=AIzaSyABdTdueRpC67F1aplCb1kccFhevFScI48";
if (!!page_token) {
apiurl += "&pageToken=" + page_token;
}
$.get(apiurl, function(data) {
var playlist = {
'title': title,
'videos': []
};
for (var i = 0; i < data['items'].length; i++) {
var entry = data['items'][i]['snippet'];
var video_id = entry['resourceId']['videoId'];
if (!video_id) {
console.log('cannot extract video_id from this thing:');
console.log(entry);
continue;
}
var video = {
'id': video_id,
'title': entry['title']
};
playlist.videos.push(video);
}
var next_page_token = data['nextPageToken'];
if (!page_token) {
that.createPlaylist(playlist.title, playlist.videos);
} else {
that.appendToCurrentPlaylist(playlist.videos);
}
if (!!next_page_token) {
that.importPlaylistByUrl(url, title, next_page_token);
}
});
};
this.bindHandlers = function() {
$('#do_import_video_by_url').click(function(e) {
var url = $('#import_video_by_url_input').val();
that.importVideoByUrl(url);
return false;
});
$('#do_import_playlist_by_url').click(function(e) {
var url = $('#import_playlist_by_url_input').val();
that.importPlaylistByUrl(url);
return false;
});
$('#refresh_view_btn').click(function() {
that.updateView();
});
$('#stash_btn').click(function() {
that.stash();
});
$('#stash_pop_btn').click(function() {
that.stashPop();
});
$('#undo_stash_pop').click(function() {
that.undoStashPop();
});
$('#clear_now_playing').click(function() {
that.now_playing_list = [];
that.localSave();
that.updateView();
});
$('#playlist_to_now_playing').click(function() {
that.playlistToNowPlaying();
});
$('#play_now_playing').click(function() {
that.playNowPlaying();
});
$('#undo').click(function() {
that.undoChanges();
});
$('#playlist_collection').on('click', '.collection-item', function() {
var selected_playlist = $('.collection-item input[type="radio"]:checked').val();
that.current_playlist = selected_playlist;
that.updateView();
});
$('#playlist_contents').on('click', '.playlist-item', function() {
var selected_video_id = $('.playlist-item input[type="radio"]:checked').val();
var video = that.getCurrentPlaylistVideo(selected_video_id);
that.addToNowPlaying(video);
that.updateView();
});
$('#playlist_contents').on('click', '.a-rename-track', function() {
var selected_video_id = $(this).data('video_id');
var video = that.getCurrentPlaylistVideo(selected_video_id);
video.title = window.prompt('Rename track', video.title) || video.title;
that.localSave();
that.updateView();
return false;
});
$('#playlist_contents').on('click', '.a-remove-track', function() {
var selected_video_id = $(this).data('video_id');
that.removeFromCurrentPlaylist(selected_video_id);
return false;
});
$('#now_playing').on('dblclick', '.now-playing-item', function() {
that.playNowPlaying();
});
$('#now_playing').on('click', '.a-remove-from-now-playing', function() {
var selected_video_id = $(this).data('video_id');
that.removeFromNowPlaying(selected_video_id);
return false;
});
$('#now_playing').on('click', '.a-from-now-playing-to-current-playlist', function() {
var selected_video_id = $(this).data('video_id');
var video = that.getNowPlayingVideo(selected_video_id);
that.addToCurrentPlaylist(video);
return false;
});
$('#now_playing').sortable({
stop: function() {
var new_id_order = [];
$('#now_playing label').each(function(i, el) {
var video_id = $(el).data('video_id');
new_id_order.push(video_id);
});
that.reorderVideoList(that.now_playing_list, new_id_order);
that.localSave();
that.updateView();
}
});
$('#now_playing').disableSelection();
$('#btn_shuffle').click(function() {
that.shuffleNowPlaying();
});
$('#playlist_contents').sortable({
stop: function() {
var new_id_order = [];
$('#playlist_contents label').each(function(i, el) {
var video_id = $(el).data('video_id');
new_id_order.push(video_id);
});
var playlist = that.getCurrentPlaylist();
that.reorderVideoList(playlist.videos, new_id_order);
that.localSave();
that.updateView();
}
});
$('#playlist_contents').disableSelection();
$('#del_current_playlist').click(function() {
that.deleteCurrentPlaylist();
return false;
});
$('#add_playlist').click(function() {
var title = window.prompt('Create playlist', 'New playlist');
if (!title) {
return;
}
that.createPlaylist(title, []);
return false;
});
$('#save_now_playing_as').click(function() {
var title = window.prompt('Save Now playing list as', 'New playlist');
if (!title) {
return;
}
that.createPlaylist(title, that.now_playing_list);
return false;
});
};
this.bindHandlers();
this.localLoad();
}
| tube.js | function MyYoutubePlayer() {
var that = this;
this.playlist_collection = [];
this.now_playing_list = [];
this.now_playing_video_id = '';
this.current_playlist = '';
this.undo_context = null;
this.localSave = function() {
this.undo_context = localStorage.getItem('my_youtube_data_context');
var context = {
'collection': this.playlist_collection,
'now_playing_list': this.now_playing_list
};
var dump = JSON.stringify(context);
localStorage.setItem('my_youtube_data_context', dump);
};
this.localLoad = function() {
var dump = localStorage.getItem('my_youtube_data_context');
if (!!dump) {
var context = JSON.parse(dump);
this.playlist_collection = context.collection;
this.now_playing_list = context.now_playing_list;
}
this.updateView();
};
this.stashUrl = 'http://a-kr.ru/stash/?key=tube';
this.stash = function() {
var that = this;
var dump = localStorage.getItem('my_youtube_data_context');
$.ajax(this.stashUrl, {
success: function() {
alert("Stashed at: " + that.stashUrl);
},
error: function(xhr, httpStatus) {
alert("Stash error: " + httpStatus);
},
data: dump,
headers: {
'Content-Type': 'text/plain'
},
method: 'POST'
});
};
this.stashPop = function() {
var that = this;
var dump = localStorage.getItem('my_youtube_data_context');
localStorage.setItem('my_youtube_data_context_before_stash_pop', dump);
$.ajax(this.stashUrl, {
success: function(data) {
if (!!data) {
localStorage.setItem('my_youtube_data_context', data);
that.localLoad();
alert("Stash restored");
} else {
alert("Empty data restored from " + that.stashUrl);
}
},
error: function(xhr, httpStatus) {
alert("Stash pop error: " + httpStatus);
},
method: 'GET'
});
};
this.undoStashPop = function() {
var dump = localStorage.getItem('my_youtube_data_context_before_stash_pop');
if (!!dump) {
localStorage.setItem('my_youtube_data_context', dump);
that.localLoad();
alert("Stash pop rolled back");
} else {
alert("No saved data before stash pop");
}
};
this.undoChanges = function() {
var dump = this.undo_context;
if (!!dump) {
var context = JSON.parse(dump);
this.playlist_collection = context.collection;
this.now_playing_list = context.now_playing_list;
this.localSave();
} else {
this.alert('Cannot undo further');
return;
}
this.updateView();
};
this.reorderVideoList = function(list, id_order) {
var dict = {};
while (list.length > 0) {
var video = list.pop();
dict[video.id] = video;
}
for (var i = 0; i < id_order.length; i++) {
var video = dict[id_order[i]];
list.push(video);
}
};
this.shuffleNowPlaying = function() {
var new_now_playing = [];
while (this.now_playing_list.length > 0) {
var i = Math.trunc(Math.random() * this.now_playing_list.length);
new_now_playing.push(this.now_playing_list[i]);
this.now_playing_list.splice(i, 1);
}
this.now_playing_list = new_now_playing;
this.updateView();
};
this.createPlaylist = function(title, videos) {
if (!title) {
that.alert('Cannot create playlist without a title');
return false;
}
for (var i = 0; i < this.playlist_collection.length; i++) {
if (this.playlist_collection.title == title) {
that.alert('Playlist with this title already exists');
return false;
}
}
var new_videos = [];
for (var i = 0; i < videos.length; i++) {
new_videos.push(videos[i]);
}
var playlist = {
'title': title,
'videos': new_videos
};
this.playlist_collection.push(playlist);
this.current_playlist = title;
this.localSave();
this.updateView();
};
this.getCurrentPlaylist = function() {
for (var i = 0; i < this.playlist_collection.length; i++) {
var playlist = this.playlist_collection[i];
if (playlist.title == this.current_playlist) {
return playlist;
}
}
};
this.deleteCurrentPlaylist = function() {
if (this.playlist_collection.length <= 1) {
this.alert('Cannot delete last playlist');
return;
}
var new_collection = [];
for (var i = 0; i < this.playlist_collection.length; i++) {
var playlist = this.playlist_collection[i];
if (playlist.title != this.current_playlist) {
new_collection.push(playlist);
}
};
this.playlist_collection = new_collection;
this.current_playlist = new_collection[0].title;
this.localSave();
this.updateView();
};
this.playNowPlaying = function() {
if (this.now_playing_list.length == 0) {
return;
}
this.now_playing_video_id = this.now_playing_list[0].id;
var selected_id = $('input[name="now_playing"]:checked').val();
if (!!selected_id) {
this.now_playing_video_id = selected_id;
} else {
$('input.now_playing_radio[value="' + this.now_playing_video_id + '"]').attr('checked', 'checked');
}
this.setPlayerToNextTrack(this.now_playing_video_id);
};
this.setPlayerToNextTrack = function(video_id) {
if (video_id.endsWith('.mp3')) {
window.ytplayer.stopVideo();
window.auplayer.src = video_id;
window.auplayer.play();
} else {
window.auplayer.pause();
window.ytplayer.loadVideoById(video_id, 0);
}
};
this.getNextVideo = function() {
var mode = ($('#rd_mode_list').is(':checked')) ? 'list' : 'loop';
for (var i = 0; i < this.now_playing_list.length; i++) {
var el_id = '#now_video_' + i;
if ($(el_id).is(':checked')) {
var j;
if (mode == 'loop') {
j = i;
} else {
if (this.now_playing_list[i].id == this.now_playing_video_id) {
j = (i + 1) % this.now_playing_list.length;
} else {
j = i;
}
}
this.now_playing_video_id = this.now_playing_list[j].id;
var new_el_id = '#now_video_' + j;
$(new_el_id).attr('checked', 'checked');
$(new_el_id).prop('checked', true);
return this.now_playing_video_id;
}
}
};
this.getCurrentPlaylistVideo = function(video_id) {
var playlist = this.getCurrentPlaylist();
for (var i = 0; i < playlist.videos.length; i++) {
if (playlist.videos[i].id == video_id) {
return playlist.videos[i];
}
}
};
this.getNowPlayingVideo = function(video_id) {
var list = this.now_playing_list;
for (var i = 0; i < list.length; i++) {
if (list[i].id == video_id) {
return list[i];
}
}
};
this.removeFromNowPlaying = function(video_id) {
var new_now_playing = [];
for (var i = 0; i < this.now_playing_list.length; i++) {
if (this.now_playing_list[i].id == video_id) {
continue;
}
new_now_playing.push(this.now_playing_list[i]);
}
this.now_playing_list = new_now_playing;
this.localSave();
this.updateView();
};
this.removeFromCurrentPlaylist = function(video_id) {
var new_list = [];
var playlist = this.getCurrentPlaylist();
for (var i = 0; i < playlist.videos.length; i++) {
if (playlist.videos[i].id == video_id) {
continue;
}
new_list.push(playlist.videos[i]);
}
playlist.videos = new_list;
this.localSave();
this.updateView();
};
this.addToCurrentPlaylist = function(video) {
if (!video) {
return;
}
var playlist = this.getCurrentPlaylist();
for (var i = 0; i < playlist.videos.length; i++) {
if (playlist.videos[i].id == video.id) {
that.alert('This video is already in the playlist');
return false;
}
}
playlist.videos.push(video);
this.localSave();
this.updateView();
};
this.appendToCurrentPlaylist = function(list) {
if (!list) {
return;
}
var playlist = this.getCurrentPlaylist();
var playlist_length = playlist.videos.length;
for (var j = 0; j < list.length; j++) {
var video = list[j];
for (var i = 0; i < playlist_length; i++) {
if (playlist.videos[i].id == video.id) {
that.alert('This video is already in the playlist');
return false;
}
}
playlist.videos.push(video);
}
this.localSave();
this.updateView();
};
this.playlistToNowPlaying = function() {
var now_playing_length = this.now_playing_list.length;
var playlist = this.getCurrentPlaylist();
for (var i = 0; i < playlist.videos.length; i++) {
var video = playlist.videos[i];
var existing_index = null;
for (var j = 0; j < now_playing_length; j++) {
if (video.id == this.now_playing_list[j].id) {
existing_index = j;
break;
}
}
if (existing_index !== null) {
continue;
}
this.now_playing_list.push(video);
}
this.localSave();
this.updateView();
};
this.addToNowPlaying = function(video) {
if (!video) {
return;
}
for (var i = 0; i < this.now_playing_list.length; i++) {
if (this.now_playing_list[i].id == video.id) {
that.alert('This video is already in Now Playing');
return false;
}
}
this.now_playing_list.push(video);
this.localSave();
this.updateView();
};
this.alert = function(text) {
var el = $('#alert_div');
el.removeClass('okay');
el.addClass('warning');
el.text(text);
};
this.clearAlert = function(text) {
var el = $('#alert_div');
el.removeClass('warning');
el.addClass('okay');
el.text('Everything is OK');
};
this.updateView = function() {
this.clearAlert();
if (this.playlist_collection.length == 0) {
this.createPlaylist('Misc', []);
}
if (!this.current_playlist) {
this.current_playlist = this.playlist_collection[0].title;
}
/* displaying playlist collection */
var pc_el = $('#playlist_collection');
var html = '';
var selected_playlist = null;
for (var i = 0; i < this.playlist_collection.length; i++) {
var playlist = this.playlist_collection[i];
var id = "plt_" + i;
var checked = '';
if (playlist.title == this.current_playlist) {
checked = 'checked';
selected_playlist = playlist;
}
var el = '<label class="collection-item" for="' + id + '">';
el += '<input type="radio" group="p_collection" name="p_collection" value="' +
playlist.title + '" id="' + id +'" ' + checked + '>';
el += playlist.title +
' (' + playlist.videos.length + ')</label><br/>';
html += el;
}
pc_el.html(html);
/* displaying playlist contents */
pc_el = $('#playlist_contents');
html = '';
for (var i = 0; i < selected_playlist.videos.length; i++) {
var video = selected_playlist.videos[i];
var id = "plt_video_" + i;
var checked = '';
var el = '<div><label class="playlist-item" data-video_id="' + video.id + '" for="' + id + '">';
el += '<input type="radio" group="p_playlist" name="playlist" value="' +
video.id + '" id="' + id +'" ' + checked + '>';
el += '<a href="#" title="Rename track" data-video_id="' + video.id + '" class="jsa a-rename-track">R</a> '
el += '<a href="#" title="Delete track" data-video_id="' + video.id + '" class="jsa a-remove-track">X</a> '
el += video.title + '</label></div>';
html += el;
}
pc_el.html(html);
/* displaying now playing */
pc_el = $('#now_playing');
html = '';
for (var i = 0; i < this.now_playing_list.length; i++) {
var video = this.now_playing_list[i];
var id = "now_video_" + i;
var checked = '';
if (video.id == this.now_playing_video_id) {
checked = 'checked';
}
var el = '<div><label class="now-playing-item" data-video_id="' + video.id + '" for="' + id + '">';
el += '<input type="radio" class="now_playing_radio" group="p_now_playing" name="now_playing" value="' +
video.id + '" id="' + id +'" ' + checked + '>';
el += '<a href="#" title="Remove track" data-video_id="' + video.id + '" class="jsa a-remove-from-now-playing">X</a> '
el += '<a href="#" title="Add to current playlist" data-video_id="' + video.id + '" class="jsa a-from-now-playing-to-current-playlist">P</a> '
el += video.title + '</label></div>';
html += el;
}
pc_el.html(html);
};
this.parseUrlForVideoId = function(url) {
// https://www.youtube.com/watch?v=lPM2NLRdtOg&list=PL7C183EA1B833B690
var match = /\?v=([^&]+)/.exec(url);
if (!match || match.length < 2) {
return null;
}
return match[1];
};
this.parseUrlForPlaylistId = function(url) {
// https://www.youtube.com/watch?v=lPM2NLRdtOg&list=PL7C183EA1B833B690
var match = /[\?&]list=([^&]+)/.exec(url);
if (!match || match.length < 2) {
return null;
}
return match[1];
};
this.importVideoByUrl = function(url) {
if (url.endsWith('.mp3')) {
var video = {
'id': url,
'title': url.match(/[^\/]+$/)[0]
};
that.addToCurrentPlaylist(video);
that.addToNowPlaying(video);
return;
}
var video_id = this.parseUrlForVideoId(url);
if (!video_id) {
that.alert('URL does not look like YouTube video url');
return;
}
$.get("https://www.googleapis.com/youtube/v3/videos?part=snippet&id=" + video_id + "&key=AIzaSyABdTdueRpC67F1aplCb1kccFhevFScI48", function(data) {
if (data['items'].length == 0) {
that.alert('Video not found');
return;
}
var video = {
'id': video_id,
'title': data['items'][0]['snippet']['title']
};
that.addToCurrentPlaylist(video);
that.addToNowPlaying(video);
});
};
this.importPlaylistByUrl = function(url, title, page_token) {
var playlist_id = this.parseUrlForPlaylistId(url);
if (!playlist_id) {
that.alert('URL does not seem to contain YouTube playlist id');
return;
}
var apiurl;
if (!title) {
$.get("https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=" + playlist_id + "&key=AIzaSyABdTdueRpC67F1aplCb1kccFhevFScI48", function(data) {
if (data['items'].length == 0) {
that.alert('Playlist not found');
return;
};
var title = data['items'][0]['snippet']['title'];
if (!title) {
that.alert('Cannot determine playlist title');
return;
}
that.importPlaylistByUrl(url, title);
});
return;
}
apiurl = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=" + playlist_id + "&key=AIzaSyABdTdueRpC67F1aplCb1kccFhevFScI48";
if (!!page_token) {
apiurl += "&pageToken=" + page_token;
}
$.get(apiurl, function(data) {
var playlist = {
'title': title,
'videos': []
};
for (var i = 0; i < data['items'].length; i++) {
var entry = data['items'][i]['snippet'];
var video_id = entry['resourceId']['videoId'];
if (!video_id) {
console.log('cannot extract video_id from this thing:');
console.log(entry);
continue;
}
var video = {
'id': video_id,
'title': entry['title']
};
playlist.videos.push(video);
}
var next_page_token = data['nextPageToken'];
if (!page_token) {
that.createPlaylist(playlist.title, playlist.videos);
} else {
that.appendToCurrentPlaylist(playlist.videos);
}
if (!!next_page_token) {
that.importPlaylistByUrl(url, title, next_page_token);
}
});
};
this.bindHandlers = function() {
$('#do_import_video_by_url').click(function(e) {
var url = $('#import_video_by_url_input').val();
that.importVideoByUrl(url);
return false;
});
$('#do_import_playlist_by_url').click(function(e) {
var url = $('#import_playlist_by_url_input').val();
that.importPlaylistByUrl(url);
return false;
});
$('#refresh_view_btn').click(function() {
that.updateView();
});
$('#stash_btn').click(function() {
that.stash();
});
$('#stash_pop_btn').click(function() {
that.stashPop();
});
$('#undo_stash_pop').click(function() {
that.undoStashPop();
});
$('#clear_now_playing').click(function() {
that.now_playing_list = [];
that.localSave();
that.updateView();
});
$('#playlist_to_now_playing').click(function() {
that.playlistToNowPlaying();
});
$('#play_now_playing').click(function() {
that.playNowPlaying();
});
$('#undo').click(function() {
that.undoChanges();
});
$('#playlist_collection').on('click', '.collection-item', function() {
var selected_playlist = $('.collection-item input[type="radio"]:checked').val();
that.current_playlist = selected_playlist;
that.updateView();
});
$('#playlist_contents').on('click', '.playlist-item', function() {
var selected_video_id = $('.playlist-item input[type="radio"]:checked').val();
var video = that.getCurrentPlaylistVideo(selected_video_id);
that.addToNowPlaying(video);
that.updateView();
});
$('#playlist_contents').on('click', '.a-rename-track', function() {
var selected_video_id = $(this).data('video_id');
var video = that.getCurrentPlaylistVideo(selected_video_id);
video.title = window.prompt('Rename track', video.title) || video.title;
that.localSave();
that.updateView();
return false;
});
$('#playlist_contents').on('click', '.a-remove-track', function() {
var selected_video_id = $(this).data('video_id');
that.removeFromCurrentPlaylist(selected_video_id);
return false;
});
$('#now_playing').on('dblclick', '.now-playing-item', function() {
that.playNowPlaying();
});
$('#now_playing').on('click', '.a-remove-from-now-playing', function() {
var selected_video_id = $(this).data('video_id');
that.removeFromNowPlaying(selected_video_id);
return false;
});
$('#now_playing').on('click', '.a-from-now-playing-to-current-playlist', function() {
var selected_video_id = $(this).data('video_id');
var video = that.getNowPlayingVideo(selected_video_id);
that.addToCurrentPlaylist(video);
return false;
});
$('#now_playing').sortable({
stop: function() {
var new_id_order = [];
$('#now_playing label').each(function(i, el) {
var video_id = $(el).data('video_id');
new_id_order.push(video_id);
});
that.reorderVideoList(that.now_playing_list, new_id_order);
that.localSave();
that.updateView();
}
});
$('#now_playing').disableSelection();
$('#btn_shuffle').click(function() {
that.shuffleNowPlaying();
});
$('#playlist_contents').sortable({
stop: function() {
var new_id_order = [];
$('#playlist_contents label').each(function(i, el) {
var video_id = $(el).data('video_id');
new_id_order.push(video_id);
});
var playlist = that.getCurrentPlaylist();
that.reorderVideoList(playlist.videos, new_id_order);
that.localSave();
that.updateView();
}
});
$('#playlist_contents').disableSelection();
$('#del_current_playlist').click(function() {
that.deleteCurrentPlaylist();
return false;
});
$('#add_playlist').click(function() {
var title = window.prompt('Create playlist', 'New playlist');
if (!title) {
return;
}
that.createPlaylist(title, []);
return false;
});
$('#save_now_playing_as').click(function() {
var title = window.prompt('Save Now playing list as', 'New playlist');
if (!title) {
return;
}
that.createPlaylist(title, that.now_playing_list);
return false;
});
};
this.bindHandlers();
this.localLoad();
}
| custom stash urls
| tube.js | custom stash urls | <ide><path>ube.js
<ide> }
<ide> this.updateView();
<ide> };
<add>
<ide> this.stashUrl = 'http://a-kr.ru/stash/?key=tube';
<add>
<add> this.mustGetStashKeySuffix = function() {
<add> var suffix = localStorage.getItem('my_youtube_stash_suffix');
<add> if (!suffix) {
<add> suffix = prompt("Please enter your email", "[email protected]");
<add> if (!suffix) {
<add> throw 'empty email';
<add> }
<add> localStorage.setItem('my_youtube_stash_suffix', suffix)
<add> }
<add> return encodeURIComponent(suffix);
<add> };
<add>
<ide> this.stash = function() {
<ide> var that = this;
<add> var stashKeySuffix = that.mustGetStashKeySuffix();
<add> var url = that.stashUrl + stashKeySuffix;
<ide> var dump = localStorage.getItem('my_youtube_data_context');
<del> $.ajax(this.stashUrl, {
<add> $.ajax(url, {
<ide> success: function() {
<del> alert("Stashed at: " + that.stashUrl);
<add> alert("Stashed at: " + url);
<ide> },
<ide> error: function(xhr, httpStatus) {
<ide> alert("Stash error: " + httpStatus);
<ide> this.stashPop = function() {
<ide> var that = this;
<ide> var dump = localStorage.getItem('my_youtube_data_context');
<add> var stashKeySuffix = that.mustGetStashKeySuffix();
<add> var url = that.stashUrl + stashKeySuffix;
<ide> localStorage.setItem('my_youtube_data_context_before_stash_pop', dump);
<del> $.ajax(this.stashUrl, {
<add> $.ajax(url, {
<ide> success: function(data) {
<ide> if (!!data) {
<ide> localStorage.setItem('my_youtube_data_context', data);
<ide> that.localLoad();
<ide> alert("Stash restored");
<ide> } else {
<del> alert("Empty data restored from " + that.stashUrl);
<add> alert("Empty data restored from " + url);
<ide> }
<ide> },
<ide> error: function(xhr, httpStatus) { |
|
JavaScript | bsd-3-clause | d3ff9003563e3c2cc10c8828a12f05e0f3267ca7 | 0 | CartoDB/cartodb,CartoDB/cartodb,splashblot/dronedb,splashblot/dronedb,CartoDB/cartodb,splashblot/dronedb,splashblot/dronedb,splashblot/dronedb,CartoDB/cartodb,CartoDB/cartodb | var CoreView = require('backbone/core-view');
var template = require('./custom-carousel-item.tpl');
module.exports = CoreView.extend({
className: 'Carousel-item',
tagName: 'li',
events: {
'mouseenter': '_onMouseEnter',
'mouseleave': '_onMouseLeave',
'click': '_onClick'
},
initialize: function () {
this._initBinds();
},
render: function () {
this.$el.html(
template({
name: this.model.getName(),
template: this.model.get('template')()
})
);
this.$el.addClass('js-' + this.model.getValue());
this.$el.toggleClass('is-selected', !!this.model.get('selected'));
return this;
},
_initBinds: function () {
this.model.bind('change:selected', this.render, this);
},
_onMouseEnter: function () {
this.model.set('highlighted', true);
},
_onMouseLeave: function () {
this.model.set('highlighted', false);
},
_onClick: function () {
this.model.set('selected', true);
}
});
| lib/assets/javascripts/cartodb3/components/custom-carousel/custom-carousel-item-view.js | var CoreView = require('backbone/core-view');
var template = require('./custom-carousel-item.tpl');
module.exports = CoreView.extend({
className: 'Carousel-item',
tagName: 'li',
events: {
'mouseenter': '_onMouseEnter',
'mouseleave': '_onMouseLeave',
'click': '_onClick'
},
initialize: function () {
this._initBinds();
},
render: function () {
this.$el.html(
template({
name: this.model.getName(),
template: this.model.get('template')()
})
);
this.$el.toggleClass('is-selected', !!this.model.get('selected'));
return this;
},
_initBinds: function () {
this.model.bind('change:selected', this.render, this);
},
_onMouseEnter: function () {
this.model.set('highlighted', true);
},
_onMouseLeave: function () {
this.model.set('highlighted', false);
},
_onClick: function () {
this.model.set('selected', true);
}
});
| popups: selected
| lib/assets/javascripts/cartodb3/components/custom-carousel/custom-carousel-item-view.js | popups: selected | <ide><path>ib/assets/javascripts/cartodb3/components/custom-carousel/custom-carousel-item-view.js
<ide> template: this.model.get('template')()
<ide> })
<ide> );
<add> this.$el.addClass('js-' + this.model.getValue());
<ide> this.$el.toggleClass('is-selected', !!this.model.get('selected'));
<ide> return this;
<ide> }, |
|
Java | mit | 5c68a026d885eaba1c388095ca97729a5183b80f | 0 | mozack/abra2,mozack/abra2,mozack/abra2,mozack/abra2 | package abra;
import htsjdk.samtools.AlignmentBlock;
import htsjdk.samtools.CigarElement;
import htsjdk.samtools.CigarOperator;
import htsjdk.samtools.SAMRecord;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class AltContigGenerator {
// TODO: Multiple arbitrary cutoffs here, need to optimize
private static int SOFT_CLIPPING_MIN_BASE_QUAL = 13;
// Return true if read contains a soft clip element >= 5 bases long with 80% or more of bases exceeding min base qual
private boolean hasHighQualitySoftClipping(SAMRecord read) {
for (int i=0; i<read.getCigarLength(); i++) {
CigarElement elem = read.getCigar().getCigarElement(i);
if (elem.getOperator() == CigarOperator.S && elem.getLength() >= 5) {
AlignmentBlock readBlock = read.getAlignmentBlocks().get(i);
int numHighQualBases = 0;
for (int bq = readBlock.getReadStart()-1; bq< readBlock.getReadStart()-1 + elem.getLength(); bq++) {
if (read.getBaseQualities()[bq] >= SOFT_CLIPPING_MIN_BASE_QUAL) {
numHighQualBases += 1;
if (numHighQualBases >= .8 * elem.getLength()) {
return true;
}
}
}
}
}
return false;
}
public Collection<String> getAltContigs(List<List<SAMRecordWrapper>> readsList, CompareToReference2 c2r, int readLength) {
Set<String> contigs = new HashSet<String>();
HashSet<Indel> indels = new HashSet<Indel>();
for (List<SAMRecordWrapper> reads : readsList) {
for (SAMRecordWrapper readWrapper : reads) {
SAMRecord read = readWrapper.getSamRecord();
// TODO: Any other filters here. Higher MQ threshold?
if (read.getMappingQuality() > 0) {
// For now only use indels bracketed by 2 M elements
// TODO: Handle clipping / complex indels
List<CigarElement> elems = read.getCigar().getCigarElements();
if (elems.size() == 3 &&
elems.get(0).getOperator() == CigarOperator.M &&
elems.get(2).getOperator() == CigarOperator.M &&
(elems.get(1).getOperator() == CigarOperator.D || elems.get(1).getOperator() == CigarOperator.I)) {
String insertBases = null;
char type = '0';
if (elems.get(1).getOperator() == CigarOperator.D) {
type = 'D';
} else if (elems.get(1).getOperator() == CigarOperator.I) {
type = 'I';
// System.out.println("read: " + read.getSAMString() + ", elem0: " + elems.get(0).getLength() + ", elem1: " + elems.get(1).getLength());
int start = elems.get(0).getLength();
int stop = start + elems.get(1).getLength();
insertBases = read.getReadString().substring(start, stop);
}
Indel indel = new Indel(type, read.getReferenceName(), read.getAlignmentStart() + elems.get(0).getLength(), elems.get(1).getLength(), insertBases);
indels.add(indel);
}
// Add high quality soft clipped reads
if (hasHighQualitySoftClipping(readWrapper.getSamRecord())) {
System.err.println("SOFT_SEQ: " + readWrapper.getSamRecord());
contigs.add(read.getReadString());
}
}
}
}
for (Indel indel : indels) {
if (indel.type == 'D') {
// Pull in read length sequence from both sides of deletion.
int leftStart = indel.pos - readLength;
int rightStart = indel.pos + indel.length;
String leftSeq = c2r.getSequence(indel.chr, leftStart, readLength);
String rightSeq = c2r.getSequence(indel.chr, rightStart, readLength);
String seq = leftSeq + rightSeq;
System.err.println("INDEL_SEQ: chr: " + indel.chr + " pos: " + indel.pos + " type: " + indel.type + " length: " + indel.length + " bases: " + indel.insert + " seq: [" + seq + "]");
contigs.add(seq);
} else if (indel.type == 'I') {
// Pull in read length sequence on both sides of insertion
int leftStart = indel.pos - readLength;
int rightStart = indel.pos;
String leftSeq = c2r.getSequence(indel.chr, leftStart, readLength);
String rightSeq = c2r.getSequence(indel.chr, rightStart, readLength);
String seq = leftSeq + indel.insert + rightSeq;
System.err.println("INDEL_SEQ: chr: " + indel.chr + " pos: " + indel.pos + " type: " + indel.type + " length: " + indel.length + " bases: " + indel.insert + " seq: [" + seq + "]");
contigs.add(seq);
}
}
return contigs;
}
static class Indel {
char type;
String chr;
int pos;
int length;
String insert;
Indel(char type, String chr, int pos, int length, String insert) {
this.type = type;
this.chr = chr;
this.pos = pos;
this.length = length;
this.insert = insert;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((chr == null) ? 0 : chr.hashCode());
result = prime * result
+ ((insert == null) ? 0 : insert.hashCode());
result = prime * result + length;
result = prime * result + pos;
result = prime * result + type;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Indel other = (Indel) obj;
if (chr == null) {
if (other.chr != null)
return false;
} else if (!chr.equals(other.chr))
return false;
if (insert == null) {
if (other.insert != null)
return false;
} else if (!insert.equals(other.insert))
return false;
if (length != other.length)
return false;
if (pos != other.pos)
return false;
if (type != other.type)
return false;
return true;
}
}
}
| src/main/java/abra/AltContigGenerator.java | package abra;
import htsjdk.samtools.CigarElement;
import htsjdk.samtools.CigarOperator;
import htsjdk.samtools.SAMRecord;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class AltContigGenerator {
private boolean hasHighQualitySoftClipping(SAMRecordWrapper read) {
boolean hasHighQualitySoftClipping = false;
for (CigarElement elem : read.getSamRecord().getCigar().getCigarElements()) {
if (elem.getOperator() == CigarOperator.S && elem.getLength() >= 5) {
hasHighQualitySoftClipping = true;
for (byte bq : read.getSamRecord().getBaseQualities()) {
if (bq < 20) {
hasHighQualitySoftClipping = false;
break;
}
}
}
}
return hasHighQualitySoftClipping;
}
public Collection<String> getAltContigs(List<List<SAMRecordWrapper>> readsList, CompareToReference2 c2r, int readLength) {
Set<String> contigs = new HashSet<String>();
HashSet<Indel> indels = new HashSet<Indel>();
for (List<SAMRecordWrapper> reads : readsList) {
for (SAMRecordWrapper readWrapper : reads) {
SAMRecord read = readWrapper.getSamRecord();
// TODO: Any other filters here. Higher MQ threshold?
if (read.getMappingQuality() > 0) {
// For now only use indels bracketed by 2 M elements
// TODO: Handle clipping / complex indels
List<CigarElement> elems = read.getCigar().getCigarElements();
if (elems.size() == 3 &&
elems.get(0).getOperator() == CigarOperator.M &&
elems.get(2).getOperator() == CigarOperator.M &&
(elems.get(1).getOperator() == CigarOperator.D || elems.get(1).getOperator() == CigarOperator.I)) {
String insertBases = null;
char type = '0';
if (elems.get(1).getOperator() == CigarOperator.D) {
type = 'D';
} else if (elems.get(1).getOperator() == CigarOperator.I) {
type = 'I';
// System.out.println("read: " + read.getSAMString() + ", elem0: " + elems.get(0).getLength() + ", elem1: " + elems.get(1).getLength());
int start = elems.get(0).getLength();
int stop = start + elems.get(1).getLength();
insertBases = read.getReadString().substring(start, stop);
}
Indel indel = new Indel(type, read.getReferenceName(), read.getAlignmentStart() + elems.get(0).getLength(), elems.get(1).getLength(), insertBases);
indels.add(indel);
}
// Add high quality soft clipped reads
if (hasHighQualitySoftClipping(readWrapper)) {
contigs.add(read.getReadString());
}
}
}
}
for (Indel indel : indels) {
if (indel.type == 'D') {
// Pull in read length sequence from both sides of deletion.
int leftStart = indel.pos - readLength;
int rightStart = indel.pos + indel.length;
String leftSeq = c2r.getSequence(indel.chr, leftStart, readLength);
String rightSeq = c2r.getSequence(indel.chr, rightStart, readLength);
String seq = leftSeq + rightSeq;
System.err.println("INDEL_SEQ: chr: " + indel.chr + " pos: " + indel.pos + " type: " + indel.type + " length: " + indel.length + " bases: " + indel.insert + " seq: [" + seq + "]");
contigs.add(seq);
} else if (indel.type == 'I') {
// Pull in read length sequence on both sides of insertion
int leftStart = indel.pos - readLength;
int rightStart = indel.pos;
String leftSeq = c2r.getSequence(indel.chr, leftStart, readLength);
String rightSeq = c2r.getSequence(indel.chr, rightStart, readLength);
String seq = leftSeq + indel.insert + rightSeq;
System.err.println("INDEL_SEQ: chr: " + indel.chr + " pos: " + indel.pos + " type: " + indel.type + " length: " + indel.length + " bases: " + indel.insert + " seq: [" + seq + "]");
contigs.add(seq);
}
}
return contigs;
}
static class Indel {
char type;
String chr;
int pos;
int length;
String insert;
Indel(char type, String chr, int pos, int length, String insert) {
this.type = type;
this.chr = chr;
this.pos = pos;
this.length = length;
this.insert = insert;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((chr == null) ? 0 : chr.hashCode());
result = prime * result
+ ((insert == null) ? 0 : insert.hashCode());
result = prime * result + length;
result = prime * result + pos;
result = prime * result + type;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Indel other = (Indel) obj;
if (chr == null) {
if (other.chr != null)
return false;
} else if (!chr.equals(other.chr))
return false;
if (insert == null) {
if (other.insert != null)
return false;
} else if (!insert.equals(other.insert))
return false;
if (length != other.length)
return false;
if (pos != other.pos)
return false;
if (type != other.type)
return false;
return true;
}
}
}
| Tweaking alternate contig selection due to soft clipping. | src/main/java/abra/AltContigGenerator.java | Tweaking alternate contig selection due to soft clipping. | <ide><path>rc/main/java/abra/AltContigGenerator.java
<ide> package abra;
<ide>
<add>import htsjdk.samtools.AlignmentBlock;
<ide> import htsjdk.samtools.CigarElement;
<ide> import htsjdk.samtools.CigarOperator;
<ide> import htsjdk.samtools.SAMRecord;
<ide>
<ide> public class AltContigGenerator {
<ide>
<del> private boolean hasHighQualitySoftClipping(SAMRecordWrapper read) {
<add> // TODO: Multiple arbitrary cutoffs here, need to optimize
<add> private static int SOFT_CLIPPING_MIN_BASE_QUAL = 13;
<add>
<add> // Return true if read contains a soft clip element >= 5 bases long with 80% or more of bases exceeding min base qual
<add> private boolean hasHighQualitySoftClipping(SAMRecord read) {
<ide>
<del> boolean hasHighQualitySoftClipping = false;
<del>
<del> for (CigarElement elem : read.getSamRecord().getCigar().getCigarElements()) {
<add> for (int i=0; i<read.getCigarLength(); i++) {
<add> CigarElement elem = read.getCigar().getCigarElement(i);
<ide> if (elem.getOperator() == CigarOperator.S && elem.getLength() >= 5) {
<del> hasHighQualitySoftClipping = true;
<del>
<del> for (byte bq : read.getSamRecord().getBaseQualities()) {
<del> if (bq < 20) {
<del> hasHighQualitySoftClipping = false;
<del> break;
<add> AlignmentBlock readBlock = read.getAlignmentBlocks().get(i);
<add> int numHighQualBases = 0;
<add> for (int bq = readBlock.getReadStart()-1; bq< readBlock.getReadStart()-1 + elem.getLength(); bq++) {
<add> if (read.getBaseQualities()[bq] >= SOFT_CLIPPING_MIN_BASE_QUAL) {
<add> numHighQualBases += 1;
<add>
<add> if (numHighQualBases >= .8 * elem.getLength()) {
<add> return true;
<add> }
<ide> }
<del> }
<add> }
<ide> }
<ide> }
<del>
<del> return hasHighQualitySoftClipping;
<add>
<add> return false;
<ide> }
<ide>
<ide> public Collection<String> getAltContigs(List<List<SAMRecordWrapper>> readsList, CompareToReference2 c2r, int readLength) {
<ide> }
<ide>
<ide> // Add high quality soft clipped reads
<del> if (hasHighQualitySoftClipping(readWrapper)) {
<add> if (hasHighQualitySoftClipping(readWrapper.getSamRecord())) {
<add> System.err.println("SOFT_SEQ: " + readWrapper.getSamRecord());
<ide> contigs.add(read.getReadString());
<ide> }
<ide> } |
|
JavaScript | apache-2.0 | b078493caca7971d0bbbf37c92da6b597304ed1d | 0 | akiellor/selenium,virajs/selenium-1,akiellor/selenium,winhamwr/selenium,akiellor/selenium,virajs/selenium-1,akiellor/selenium,winhamwr/selenium,virajs/selenium-1,winhamwr/selenium,virajs/selenium-1,akiellor/selenium,akiellor/selenium,virajs/selenium-1,akiellor/selenium,winhamwr/selenium,akiellor/selenium,virajs/selenium-1,virajs/selenium-1,winhamwr/selenium,winhamwr/selenium,winhamwr/selenium,virajs/selenium-1,winhamwr/selenium,virajs/selenium-1 | /*
* Copyright 2005 Shinya Kasatani
*
* 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.
*/
/*
* FormatCollection: manages collection of formats.
*/
function FormatCollection(options) {
this.options = options;
this.presetFormats = [new InternalFormat(options, "default", "HTML", "html.js", true),
new InternalFormat(options, "java-rc", "Java (JUnit 3) - Selenium RC", "java-rc.js", false),
new InternalFormat(options, "java-rc-junit4", "Java (JUnit 4) - Selenium RC", "java-rc-junit4.js", false),
new InternalFormat(options, "java-rc-testng", "Java (TestNG) - Selenium RC", "java-rc-testng.js", false),
new InternalFormat(options, "groovy-rc", "Groovy (JUnit) - Selenium RC", "groovy-rc.js", false),
new InternalFormat(options, "perl-rc", "Perl - Selenium RC", "perl-rc.js", false),
new InternalFormat(options, "php-rc", "PHP - Selenium RC", "php-rc.js", false),
new InternalFormat(options, "ruby-rc", "Ruby (Test/Unit) - Selenium RC", "ruby-rc.js", false),
new InternalFormat(options, "ruby-rc-rspec", "Ruby (RSpec) - Selenium RC", "ruby-rc-rspec.js", false)
];
this.reloadFormats();
}
FormatCollection.log = FormatCollection.prototype.log = new Log('FormatCollection');
FormatCollection.getFormatDir = function() {
var formatDir = FileUtils.getProfileDir();
formatDir.append("selenium-ide-scripts");
if (!formatDir.exists()) {
formatDir.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0755);
}
formatDir.append("formats");
if (!formatDir.exists()) {
formatDir.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0755);
}
return formatDir;
}
FormatCollection.loadUserFormats = function(options) {
var formatFile = FormatCollection.getFormatDir();
formatFile.append("index.txt");
if (!formatFile.exists()) {
return [];
}
var text = FileUtils.readFile(formatFile);
var conv = FileUtils.getUnicodeConverter(SeleniumIDE.Preferences.getString("encoding", "UTF-8"));
text = conv.ConvertToUnicode(text);
var formats = [];
while (text.length > 0) {
var r = /^(\d+),(.*)\n?/.exec(text);
if (r) {
formats.push(new UserFormat(options, r[1], r[2]));
text = text.substr(r[0].length);
} else {
break;
}
}
return formats;
}
FormatCollection.saveUserFormats = function(formats) {
var text = '';
for (var i = 0; i < formats.length; i++) {
text += formats[i].id + ',' + formats[i].name + "\n";
}
var conv = FileUtils.getUnicodeConverter(SeleniumIDE.Preferences.getString("encoding", "UTF-8"));
text = conv.ConvertFromUnicode(text);
var formatFile = FormatCollection.getFormatDir();
formatFile.append("index.txt");
var stream = FileUtils.openFileOutputStream(formatFile);
stream.write(text, text.length);
var fin = conv.Finish();
if (fin.length > 0) {
stream.write(fin, fin.length);
}
stream.close();
}
// this is called on se-ide startup for the current formatter, or when you change formatters
FormatCollection.loadFormatter = function(url) {
const subScriptLoader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
.getService(Components.interfaces.mozIJSSubScriptLoader);
var format = {};
format.options = {};
format.configForm = '';
format.log = new Log("Format");
format.playable = true;
format.remoteControl = false;
format.load = function(file){
if (file.startsWith('chrome://')) {
//extensions may load in their own files so allow an absolute URL
subScriptLoader.loadSubScript(file, format);
} else {
//otherwise assume this is a packaged format file
subScriptLoader.loadSubScript('chrome://selenium-ide/content/formats/' + file, format);
}
}
for (prop in StringUtils) {
// copy functions from StringUtils
format[prop] = StringUtils[prop];
}
this.log.debug('loading format from ' + url);
subScriptLoader.loadSubScript(url, format);
if (format.configForm && format.configForm.length > 0) {
function copyElement(doc, element) {
var copy = doc.createElement(element.nodeName.toLowerCase());
var atts = element.attributes;
var i;
for (i = 0; atts != null && i < atts.length; i++) {
copy.setAttribute(atts[i].name, atts[i].value);
}
var childNodes = element.childNodes;
for (i = 0; i < childNodes.length; i++) {
if (childNodes[i].nodeType == 1) { // element
copy.appendChild(copyElement(doc, childNodes[i]));
} else if (childNodes[i].nodeType == 3) { // text
copy.appendChild(doc.createTextNode(childNodes[i].nodeValue));
}
}
return copy;
}
format.createConfigForm = function(document) {
var xml = '<vbox id="format-config" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">' + format.configForm + '</vbox>';
var parser = new DOMParser();
var element = parser.parseFromString(xml, "text/xml").documentElement;
// If we directly return this element, "permission denied" exception occurs
// when the user clicks on the buttons or textboxes. I haven't figured out the reason,
// but as a workaround I'll just re-create the element and make a deep copy.
return copyElement(document, element);
}
}
return format;
}
FormatCollection.prototype.reloadFormats = function() {
// user formats
this.userFormats = FormatCollection.loadUserFormats(this.options);
this.formats = this.presetFormats.concat(this.userFormats);
// plugin formats
this.pluginFormats = FormatCollection.loadPluginFormats(this.options);
this.formats = this.formats.concat(this.pluginFormats);
}
FormatCollection.prototype.removeUserFormatAt = function(index) {
this.userFormats.splice(index, 1);
this.formats = this.presetFormats.concat(this.userFormats);
// plugin formats need adding in here too
this.formats = this.formats.concat(this.pluginFormats);
}
FormatCollection.prototype.saveFormats = function() {
FormatCollection.saveUserFormats(this.userFormats);
}
FormatCollection.prototype.selectFormat = function(id) {
var info = this.findFormat(id);
if (info) {
try {
return info;
} catch (error) {
this.log.error("failed to select format: " + id + ", error=" + error);
return this.formats[0];
}
} else {
//this.log.error("failed to select format: " + id);
return this.formats[0];
}
}
FormatCollection.prototype.findFormat = function(id) {
for (var i = 0; i < this.formats.length; i++) {
if (id == this.formats[i].id) {
return this.formats[i];
}
}
return null;
}
FormatCollection.prototype.getDefaultFormat = function() {
return this.findFormat("default");
}
FormatCollection.loadPluginFormats = function(options) {
var formats = [];
var pluginProvided = SeleniumIDE.Preferences.getString("pluginProvidedFormatters");
if (pluginProvided) {
var split_pluginProvided = pluginProvided.split(",");
for (var ppf = 0; ppf < split_pluginProvided.length; ppf++) {
var split_ppf = split_pluginProvided[ppf].split(";");
formats.push(new PluginFormat(options, split_ppf[0], split_ppf[1], split_ppf[2]));
}
}
return formats;
}
/*
* Format
*/
function Format() {
}
Format.TEST_CASE_DIRECTORY_PREF = "testCaseDirectory";
Format.TEST_CASE_EXPORT_DIRECTORY_PREF = "testCaseExportDirectory";
Format.prototype.log = Format.log = new Log('Format');
Format.prototype.getUnicodeConverter = function() {
return FileUtils.getUnicodeConverter(this.options.encoding);
}
Format.prototype.getFormatter = function() {
if (!this.formatterCache) {
this.formatterCache = this.loadFormatter();
for (name in this.options) {
var r = new RegExp('formats\.' + this.id + '\.(.*)').exec(name);
if (r) {
this.formatterCache.options[r[1]] = this.options[name];
} else if (name.indexOf('.') < 0) {
this.formatterCache.options["global." + name] = this.options[name];
}
}
}
return this.formatterCache;
}
Format.prototype.save = function(testCase) {
return this.saveAs(testCase, testCase.file && testCase.file.path, false);
};
Format.prototype.saveAsNew = function(testCase, exportTest) {
return this.saveAs(testCase, null, exportTest);
};
Format.prototype.saveAs = function(testCase, filename, exportTest) {
//log.debug("saveAs: filename=" + filename);
try {
var file = null;
if (filename == null) {
file = showFilePicker(window, "Save test case as...",
Components.interfaces.nsIFilePicker.modeSave,
exportTest ? Format.TEST_CASE_EXPORT_DIRECTORY_PREF : Format.TEST_CASE_DIRECTORY_PREF,
function(fp) {return fp.file;});
} else {
file = FileUtils.getFile(filename);
}
if (file != null) {
testCase.file = file;
// save the directory so we can continue to load/save files from the current suite?
var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance( Components.interfaces.nsIFileOutputStream);
outputStream.init(file, 0x02 | 0x08 | 0x20, 0644, 0);
var converter = this.getUnicodeConverter();
var text = converter.ConvertFromUnicode(this.getFormatter().format(testCase, testCase.getTitle()));
outputStream.write(text, text.length);
var fin = converter.Finish();
if (fin.length > 0) {
outputStream.write(fin, fin.length);
}
outputStream.close();
this.log.info("saved " + file.path);
testCase.lastModifiedTime = file.lastModifiedTime;
testCase.clearModified();
return true;
} else {
return false;
}
} catch (err) {
alert("error: " + err);
return false;
}
};
/**
* Displays a filepicker so the user can select where to export the test suite,
* and saves the exported file there. Returns true on success, and false
* otherwise.
*
* @param testSuite the test suite to export
* @param exportTest ???
*/
Format.prototype.saveSuiteAsNew = function(testSuite, exportTest) {
var formatter = this.getFormatter();
if (typeof(formatter.formatSuite) != 'function') {
var name = formatter.name ? formatter.name : 'default'
alert('Suite export not implemented for the ' + name + ' formatter');
return false
}
try {
var file = null;
file = showFilePicker(window, "Export TestSuite as...",
Components.interfaces.nsIFilePicker.modeSave,
TestSuite.TEST_SUITE_DIRECTORY_PREF,
function(fp) {return fp.file;});
if (file != null) {
var filepath = [];
filepath = FileUtils.splitPath(file);
var filename = filepath[filepath.length -1];
var output = FileUtils.openFileOutputStream(file);
var converter = FileUtils.getUnicodeConverter(SeleniumIDE.Preferences.getString("encoding", "UTF-8"));
var text = converter.ConvertFromUnicode(formatter
.formatSuite(testSuite, filename));
output.write(text, text.length);
var fin = converter.Finish();
if (fin.length > 0) {
output.write(fin, fin.length);
}
output.close();
return true;
}
}
catch (err) {
alert("error: " + err);
}
return false;
};
Format.prototype.getSourceForTestCase = function(testCase) {
return this.getFormatter().format(testCase, "New Test");
}
Format.prototype.getSourceForCommands = function(commands) {
return this.getFormatter().formatCommands(commands);
}
Format.prototype.setSource = function(testCase, source) {
try {
this.getFormatter().parse(testCase, source);
testCase.setModified();
} catch (err) {
alert("error: " + err);
}
}
Format.prototype.load = function() {
var self = this;
return showFilePicker(window, "Select a File",
Components.interfaces.nsIFilePicker.modeOpen,
Format.TEST_CASE_DIRECTORY_PREF,
function(fp) {return self.loadFile(fp.file);});
}
Format.prototype.loadFile = function(file, isURL) {
this.log.debug("start loading: file=" + file);
var sis;
if (isURL) {
sis = FileUtils.openURLInputStream(file);
} else {
sis = FileUtils.openFileInputStream(file);
}
var text = this.getUnicodeConverter().ConvertToUnicode(sis.read(sis.available()));
var testCase = new TestCase();
this.getFormatter().parse(testCase, text);
sis.close();
testCase.recordModifiedInCommands();
testCase.file = file;
if (!isURL) {
testCase.lastModifiedTime = file.lastModifiedTime;
}
return testCase;
}
/**
* Format for preset formats
*/
function InternalFormat(options, id, name, file, reversible) {
this.options = options;
this.id = id;
this.name = name;
this.url = 'chrome://selenium-ide/content/formats/' + file;
//use to determine if this format implements the parse method
//and can switch to another format
this.reversible = reversible;
}
InternalFormat.prototype = new Format;
InternalFormat.prototype.loadFormatter = function() {
return FormatCollection.loadFormatter(this.url);
}
InternalFormat.prototype.getSource = function() {
return FileUtils.readURL(this.url);
}
InternalFormat.prototype.getFormatURI = function() {
return this.url;
}
/**
* called to know if the format implements the parse method
* @return true if it implements the parse method, false if nots
*/
InternalFormat.prototype.isReversible = function(){
return this.reversible;
}
/**
* Format created by users
*/
function UserFormat(options, id, name) {
this.options = options;
if (id && name) {
this.id = id;
this.name = name;
} else {
this.id = null;
this.name = '';
}
}
UserFormat.prototype = new Format;
UserFormat.prototype.saveFormat = function(source) {
var formatDir = FormatCollection.getFormatDir();
var formats = FormatCollection.loadUserFormats(this.options);
if (!this.id) {
var entries = formatDir.directoryEntries;
var max = 0;
while (entries.hasMoreElements()) {
var file = entries.getNext().QueryInterface(Components.interfaces.nsIFile);
var r;
if ((r = /^(\d+)\.js$/.exec(file.leafName)) != null) {
var id = parseInt(r[1]);
if (id > max) max = id;
}
}
max++;
this.id = '' + max;
formats.push(this);
}
var formatFile = formatDir.clone();
formatFile.append(this.id + ".js");
var stream = FileUtils.openFileOutputStream(formatFile);
stream.write(source, source.length);
stream.close();
FormatCollection.saveUserFormats(formats);
}
UserFormat.prototype.getFormatFile = function() {
var formatDir = FormatCollection.getFormatDir();
var formatFile = formatDir.clone();
formatFile.append(this.id + ".js");
return formatFile;
}
UserFormat.prototype.getFormatURI = function() {
return FileUtils.fileURI(this.getFormatFile());
}
UserFormat.prototype.loadFormatter = function() {
return FormatCollection.loadFormatter(FileUtils.fileURI(this.getFormatFile()));
}
UserFormat.prototype.getSource = function() {
if (this.id) {
return FileUtils.readFile(this.getFormatFile());
} else {
return FileUtils.readURL('chrome://selenium-ide/content/formats/blank.js');
}
}
/**
* called to know if the user format implements the parse method
* @return true if it implements the parse method, false if not
*/
UserFormat.prototype.isReversible = function(){
if (this.id) {
var parseRegExp = new RegExp("function parse\\(", 'g');
return parseRegExp.test(FileUtils.readFile(this.getFormatFile()));
} else {
return false;
}
}
/**
* Format for plugin provided formats
*/
function PluginFormat(options, id, name, url) {
this.options = options;
this.id = id;
this.name = name;
this.url = url;
}
PluginFormat.prototype = new Format;
PluginFormat.prototype.loadFormatter = function() {
return FormatCollection.loadFormatter(this.url);
}
PluginFormat.prototype.getSource = function() {
return FileUtils.readURL(this.url);
}
PluginFormat.prototype.getFormatURI = function() {
return this.url;
}
/**
* called to know if the plugin format implements the parse method
* @return true if it implements the parse method, false if not
*/
PluginFormat.prototype.isReversible = function(){
var parseRegExp = new RegExp("function parse\\(", 'g');
return parseRegExp.test(this.getSource());
}
| ide/src/extension/content/format.js | /*
* Copyright 2005 Shinya Kasatani
*
* 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.
*/
/*
* FormatCollection: manages collection of formats.
*/
function FormatCollection(options) {
this.options = options;
this.presetFormats = [new InternalFormat(options, "default", "HTML", "html.js", true),
new InternalFormat(options, "java-rc", "Java (JUnit 3) - Selenium RC", "java-rc.js", false),
new InternalFormat(options, "java-rc-junit4", "Java (JUnit 4) - Selenium RC", "java-rc-junit4.js", false),
new InternalFormat(options, "java-rc-testng", "Java (TestNG) - Selenium RC", "java-rc-testng.js", false),
new InternalFormat(options, "groovy-rc", "Groovy (JUnit) - Selenium RC", "groovy-rc.js", false),
new InternalFormat(options, "cs-rc", "C# - Selenium RC", "cs-rc.js", false),
new InternalFormat(options, "perl-rc", "Perl - Selenium RC", "perl-rc.js", false),
new InternalFormat(options, "php-rc", "PHP - Selenium RC", "php-rc.js", false),
new InternalFormat(options, "python-rc", "Python - Selenium RC", "python-rc.js", false),
new InternalFormat(options, "ruby-rc", "Ruby (Test/Unit) - Selenium RC", "ruby-rc.js", false),
new InternalFormat(options, "ruby-rc-rspec", "Ruby (RSpec) - Selenium RC", "ruby-rc-rspec.js", false)
];
this.reloadFormats();
}
FormatCollection.log = FormatCollection.prototype.log = new Log('FormatCollection');
FormatCollection.getFormatDir = function() {
var formatDir = FileUtils.getProfileDir();
formatDir.append("selenium-ide-scripts");
if (!formatDir.exists()) {
formatDir.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0755);
}
formatDir.append("formats");
if (!formatDir.exists()) {
formatDir.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0755);
}
return formatDir;
}
FormatCollection.loadUserFormats = function(options) {
var formatFile = FormatCollection.getFormatDir();
formatFile.append("index.txt");
if (!formatFile.exists()) {
return [];
}
var text = FileUtils.readFile(formatFile);
var conv = FileUtils.getUnicodeConverter(SeleniumIDE.Preferences.getString("encoding", "UTF-8"));
text = conv.ConvertToUnicode(text);
var formats = [];
while (text.length > 0) {
var r = /^(\d+),(.*)\n?/.exec(text);
if (r) {
formats.push(new UserFormat(options, r[1], r[2]));
text = text.substr(r[0].length);
} else {
break;
}
}
return formats;
}
FormatCollection.saveUserFormats = function(formats) {
var text = '';
for (var i = 0; i < formats.length; i++) {
text += formats[i].id + ',' + formats[i].name + "\n";
}
var conv = FileUtils.getUnicodeConverter(SeleniumIDE.Preferences.getString("encoding", "UTF-8"));
text = conv.ConvertFromUnicode(text);
var formatFile = FormatCollection.getFormatDir();
formatFile.append("index.txt");
var stream = FileUtils.openFileOutputStream(formatFile);
stream.write(text, text.length);
var fin = conv.Finish();
if (fin.length > 0) {
stream.write(fin, fin.length);
}
stream.close();
}
// this is called on se-ide startup for the current formatter, or when you change formatters
FormatCollection.loadFormatter = function(url) {
const subScriptLoader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
.getService(Components.interfaces.mozIJSSubScriptLoader);
var format = {};
format.options = {};
format.configForm = '';
format.log = new Log("Format");
format.playable = true;
format.remoteControl = false;
format.load = function(file){
if (file.startsWith('chrome://')) {
//extensions may load in their own files so allow an absolute URL
subScriptLoader.loadSubScript(file, format);
} else {
//otherwise assume this is a packaged format file
subScriptLoader.loadSubScript('chrome://selenium-ide/content/formats/' + file, format);
}
}
for (prop in StringUtils) {
// copy functions from StringUtils
format[prop] = StringUtils[prop];
}
this.log.debug('loading format from ' + url);
subScriptLoader.loadSubScript(url, format);
if (format.configForm && format.configForm.length > 0) {
function copyElement(doc, element) {
var copy = doc.createElement(element.nodeName.toLowerCase());
var atts = element.attributes;
var i;
for (i = 0; atts != null && i < atts.length; i++) {
copy.setAttribute(atts[i].name, atts[i].value);
}
var childNodes = element.childNodes;
for (i = 0; i < childNodes.length; i++) {
if (childNodes[i].nodeType == 1) { // element
copy.appendChild(copyElement(doc, childNodes[i]));
} else if (childNodes[i].nodeType == 3) { // text
copy.appendChild(doc.createTextNode(childNodes[i].nodeValue));
}
}
return copy;
}
format.createConfigForm = function(document) {
var xml = '<vbox id="format-config" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">' + format.configForm + '</vbox>';
var parser = new DOMParser();
var element = parser.parseFromString(xml, "text/xml").documentElement;
// If we directly return this element, "permission denied" exception occurs
// when the user clicks on the buttons or textboxes. I haven't figured out the reason,
// but as a workaround I'll just re-create the element and make a deep copy.
return copyElement(document, element);
}
}
return format;
}
FormatCollection.prototype.reloadFormats = function() {
// user formats
this.userFormats = FormatCollection.loadUserFormats(this.options);
this.formats = this.presetFormats.concat(this.userFormats);
// plugin formats
this.pluginFormats = FormatCollection.loadPluginFormats(this.options);
this.formats = this.formats.concat(this.pluginFormats);
}
FormatCollection.prototype.removeUserFormatAt = function(index) {
this.userFormats.splice(index, 1);
this.formats = this.presetFormats.concat(this.userFormats);
// plugin formats need adding in here too
this.formats = this.formats.concat(this.pluginFormats);
}
FormatCollection.prototype.saveFormats = function() {
FormatCollection.saveUserFormats(this.userFormats);
}
FormatCollection.prototype.selectFormat = function(id) {
var info = this.findFormat(id);
if (info) {
try {
return info;
} catch (error) {
this.log.error("failed to select format: " + id + ", error=" + error);
return this.formats[0];
}
} else {
//this.log.error("failed to select format: " + id);
return this.formats[0];
}
}
FormatCollection.prototype.findFormat = function(id) {
for (var i = 0; i < this.formats.length; i++) {
if (id == this.formats[i].id) {
return this.formats[i];
}
}
return null;
}
FormatCollection.prototype.getDefaultFormat = function() {
return this.findFormat("default");
}
FormatCollection.loadPluginFormats = function(options) {
var formats = [];
var pluginProvided = SeleniumIDE.Preferences.getString("pluginProvidedFormatters");
if (pluginProvided) {
var split_pluginProvided = pluginProvided.split(",");
for (var ppf = 0; ppf < split_pluginProvided.length; ppf++) {
var split_ppf = split_pluginProvided[ppf].split(";");
formats.push(new PluginFormat(options, split_ppf[0], split_ppf[1], split_ppf[2]));
}
}
return formats;
}
/*
* Format
*/
function Format() {
}
Format.TEST_CASE_DIRECTORY_PREF = "testCaseDirectory";
Format.TEST_CASE_EXPORT_DIRECTORY_PREF = "testCaseExportDirectory";
Format.prototype.log = Format.log = new Log('Format');
Format.prototype.getUnicodeConverter = function() {
return FileUtils.getUnicodeConverter(this.options.encoding);
}
Format.prototype.getFormatter = function() {
if (!this.formatterCache) {
this.formatterCache = this.loadFormatter();
for (name in this.options) {
var r = new RegExp('formats\.' + this.id + '\.(.*)').exec(name);
if (r) {
this.formatterCache.options[r[1]] = this.options[name];
} else if (name.indexOf('.') < 0) {
this.formatterCache.options["global." + name] = this.options[name];
}
}
}
return this.formatterCache;
}
Format.prototype.save = function(testCase) {
return this.saveAs(testCase, testCase.file && testCase.file.path, false);
};
Format.prototype.saveAsNew = function(testCase, exportTest) {
return this.saveAs(testCase, null, exportTest);
};
Format.prototype.saveAs = function(testCase, filename, exportTest) {
//log.debug("saveAs: filename=" + filename);
try {
var file = null;
if (filename == null) {
file = showFilePicker(window, "Save test case as...",
Components.interfaces.nsIFilePicker.modeSave,
exportTest ? Format.TEST_CASE_EXPORT_DIRECTORY_PREF : Format.TEST_CASE_DIRECTORY_PREF,
function(fp) {return fp.file;});
} else {
file = FileUtils.getFile(filename);
}
if (file != null) {
testCase.file = file;
// save the directory so we can continue to load/save files from the current suite?
var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance( Components.interfaces.nsIFileOutputStream);
outputStream.init(file, 0x02 | 0x08 | 0x20, 0644, 0);
var converter = this.getUnicodeConverter();
var text = converter.ConvertFromUnicode(this.getFormatter().format(testCase, testCase.getTitle()));
outputStream.write(text, text.length);
var fin = converter.Finish();
if (fin.length > 0) {
outputStream.write(fin, fin.length);
}
outputStream.close();
this.log.info("saved " + file.path);
testCase.lastModifiedTime = file.lastModifiedTime;
testCase.clearModified();
return true;
} else {
return false;
}
} catch (err) {
alert("error: " + err);
return false;
}
};
/**
* Displays a filepicker so the user can select where to export the test suite,
* and saves the exported file there. Returns true on success, and false
* otherwise.
*
* @param testSuite the test suite to export
* @param exportTest ???
*/
Format.prototype.saveSuiteAsNew = function(testSuite, exportTest) {
var formatter = this.getFormatter();
if (typeof(formatter.formatSuite) != 'function') {
var name = formatter.name ? formatter.name : 'default'
alert('Suite export not implemented for the ' + name + ' formatter');
return false
}
try {
var file = null;
file = showFilePicker(window, "Export TestSuite as...",
Components.interfaces.nsIFilePicker.modeSave,
TestSuite.TEST_SUITE_DIRECTORY_PREF,
function(fp) {return fp.file;});
if (file != null) {
var filepath = [];
filepath = FileUtils.splitPath(file);
var filename = filepath[filepath.length -1];
var output = FileUtils.openFileOutputStream(file);
var converter = FileUtils.getUnicodeConverter(SeleniumIDE.Preferences.getString("encoding", "UTF-8"));
var text = converter.ConvertFromUnicode(formatter
.formatSuite(testSuite, filename));
output.write(text, text.length);
var fin = converter.Finish();
if (fin.length > 0) {
output.write(fin, fin.length);
}
output.close();
return true;
}
}
catch (err) {
alert("error: " + err);
}
return false;
};
Format.prototype.getSourceForTestCase = function(testCase) {
return this.getFormatter().format(testCase, "New Test");
}
Format.prototype.getSourceForCommands = function(commands) {
return this.getFormatter().formatCommands(commands);
}
Format.prototype.setSource = function(testCase, source) {
try {
this.getFormatter().parse(testCase, source);
testCase.setModified();
} catch (err) {
alert("error: " + err);
}
}
Format.prototype.load = function() {
var self = this;
return showFilePicker(window, "Select a File",
Components.interfaces.nsIFilePicker.modeOpen,
Format.TEST_CASE_DIRECTORY_PREF,
function(fp) {return self.loadFile(fp.file);});
}
Format.prototype.loadFile = function(file, isURL) {
this.log.debug("start loading: file=" + file);
var sis;
if (isURL) {
sis = FileUtils.openURLInputStream(file);
} else {
sis = FileUtils.openFileInputStream(file);
}
var text = this.getUnicodeConverter().ConvertToUnicode(sis.read(sis.available()));
var testCase = new TestCase();
this.getFormatter().parse(testCase, text);
sis.close();
testCase.recordModifiedInCommands();
testCase.file = file;
if (!isURL) {
testCase.lastModifiedTime = file.lastModifiedTime;
}
return testCase;
}
/**
* Format for preset formats
*/
function InternalFormat(options, id, name, file, reversible) {
this.options = options;
this.id = id;
this.name = name;
this.url = 'chrome://selenium-ide/content/formats/' + file;
//use to determine if this format implements the parse method
//and can switch to another format
this.reversible = reversible;
}
InternalFormat.prototype = new Format;
InternalFormat.prototype.loadFormatter = function() {
return FormatCollection.loadFormatter(this.url);
}
InternalFormat.prototype.getSource = function() {
return FileUtils.readURL(this.url);
}
InternalFormat.prototype.getFormatURI = function() {
return this.url;
}
/**
* called to know if the format implements the parse method
* @return true if it implements the parse method, false if nots
*/
InternalFormat.prototype.isReversible = function(){
return this.reversible;
}
/**
* Format created by users
*/
function UserFormat(options, id, name) {
this.options = options;
if (id && name) {
this.id = id;
this.name = name;
} else {
this.id = null;
this.name = '';
}
}
UserFormat.prototype = new Format;
UserFormat.prototype.saveFormat = function(source) {
var formatDir = FormatCollection.getFormatDir();
var formats = FormatCollection.loadUserFormats(this.options);
if (!this.id) {
var entries = formatDir.directoryEntries;
var max = 0;
while (entries.hasMoreElements()) {
var file = entries.getNext().QueryInterface(Components.interfaces.nsIFile);
var r;
if ((r = /^(\d+)\.js$/.exec(file.leafName)) != null) {
var id = parseInt(r[1]);
if (id > max) max = id;
}
}
max++;
this.id = '' + max;
formats.push(this);
}
var formatFile = formatDir.clone();
formatFile.append(this.id + ".js");
var stream = FileUtils.openFileOutputStream(formatFile);
stream.write(source, source.length);
stream.close();
FormatCollection.saveUserFormats(formats);
}
UserFormat.prototype.getFormatFile = function() {
var formatDir = FormatCollection.getFormatDir();
var formatFile = formatDir.clone();
formatFile.append(this.id + ".js");
return formatFile;
}
UserFormat.prototype.getFormatURI = function() {
return FileUtils.fileURI(this.getFormatFile());
}
UserFormat.prototype.loadFormatter = function() {
return FormatCollection.loadFormatter(FileUtils.fileURI(this.getFormatFile()));
}
UserFormat.prototype.getSource = function() {
if (this.id) {
return FileUtils.readFile(this.getFormatFile());
} else {
return FileUtils.readURL('chrome://selenium-ide/content/formats/blank.js');
}
}
/**
* called to know if the user format implements the parse method
* @return true if it implements the parse method, false if not
*/
UserFormat.prototype.isReversible = function(){
if (this.id) {
var parseRegExp = new RegExp("function parse\\(", 'g');
return parseRegExp.test(FileUtils.readFile(this.getFormatFile()));
} else {
return false;
}
}
/**
* Format for plugin provided formats
*/
function PluginFormat(options, id, name, url) {
this.options = options;
this.id = id;
this.name = name;
this.url = url;
}
PluginFormat.prototype = new Format;
PluginFormat.prototype.loadFormatter = function() {
return FormatCollection.loadFormatter(this.url);
}
PluginFormat.prototype.getSource = function() {
return FileUtils.readURL(this.url);
}
PluginFormat.prototype.getFormatURI = function() {
return this.url;
}
/**
* called to know if the plugin format implements the parse method
* @return true if it implements the parse method, false if not
*/
PluginFormat.prototype.isReversible = function(){
var parseRegExp = new RegExp("function parse\\(", 'g');
return parseRegExp.test(this.getSource());
}
| AdamGoucher - removing the two pluginized formats from the main ide
git-svn-id: 4179480af2c2519a5eb5e1e9b541cbdf5cf27696@10233 07704840-8298-11de-bf8c-fd130f914ac9
| ide/src/extension/content/format.js | AdamGoucher - removing the two pluginized formats from the main ide | <ide><path>de/src/extension/content/format.js
<ide> new InternalFormat(options, "java-rc-junit4", "Java (JUnit 4) - Selenium RC", "java-rc-junit4.js", false),
<ide> new InternalFormat(options, "java-rc-testng", "Java (TestNG) - Selenium RC", "java-rc-testng.js", false),
<ide> new InternalFormat(options, "groovy-rc", "Groovy (JUnit) - Selenium RC", "groovy-rc.js", false),
<del> new InternalFormat(options, "cs-rc", "C# - Selenium RC", "cs-rc.js", false),
<ide> new InternalFormat(options, "perl-rc", "Perl - Selenium RC", "perl-rc.js", false),
<ide> new InternalFormat(options, "php-rc", "PHP - Selenium RC", "php-rc.js", false),
<del> new InternalFormat(options, "python-rc", "Python - Selenium RC", "python-rc.js", false),
<ide> new InternalFormat(options, "ruby-rc", "Ruby (Test/Unit) - Selenium RC", "ruby-rc.js", false),
<ide> new InternalFormat(options, "ruby-rc-rspec", "Ruby (RSpec) - Selenium RC", "ruby-rc-rspec.js", false)
<ide> ]; |
|
Java | apache-2.0 | 648387077694ba3a185dc1bc84b6a24270e244e8 | 0 | b2ihealthcare/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl | /*
* Copyright 2017-2021 B2i Healthcare Pte Ltd, http://b2i.sg
*
* 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.b2international.snowowl.identity.ldap;
import org.hibernate.validator.constraints.NotEmpty;
import com.b2international.commons.TokenReplacer;
import com.b2international.snowowl.core.identity.IdentityProviderConfig;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
/**
* @since 5.11
*/
@JsonTypeName("ldap")
public class LdapIdentityProviderConfig implements IdentityProviderConfig {
@NotEmpty private String uri;
@NotEmpty private String baseDn = "dc=snowowl,dc=b2international,dc=com";
@NotEmpty private String roleBaseDn = "{baseDn}";
@NotEmpty private String bindDn = "cn=admin,dc=snowowl,dc=b2international,dc=com";
@NotEmpty private String bindDnPassword;
@NotEmpty private String userFilter = "(objectClass={userObjectClass})";
@NotEmpty private String roleFilter = "(objectClass={roleObjectClass})";
// Customizable objectClasses
@NotEmpty private String userObjectClass = "inetOrgPerson";
@NotEmpty private String roleObjectClass = "groupOfUniqueNames";
// Customizable attributes
@NotEmpty private String userIdProperty = "uid";
@NotEmpty private String permissionProperty = "description";
@NotEmpty private String memberProperty = "uniqueMember";
private boolean connectionPoolEnabled = false;
public String getBaseDn() {
return baseDn;
}
public void setBaseDn(String baseDn) {
this.baseDn = baseDn;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getBindDn() {
return bindDn;
}
public void setBindDn(String bindDn) {
this.bindDn = bindDn;
}
public String getBindDnPassword() {
return bindDnPassword;
}
public void setBindDnPassword(String bindDnPassword) {
this.bindDnPassword = bindDnPassword;
}
public String getUserIdProperty() {
return userIdProperty;
}
public void setUserIdProperty(String userIdProperty) {
this.userIdProperty = userIdProperty;
}
@JsonProperty("usePool")
public boolean isConnectionPoolEnabled() {
return connectionPoolEnabled;
}
@JsonProperty("usePool")
public void setConnectionPoolEnabled(boolean connectionPoolEnabled) {
this.connectionPoolEnabled = connectionPoolEnabled;
}
public String getUserObjectClass() {
return userObjectClass;
}
public void setUserObjectClass(String userObjectClass) {
this.userObjectClass = userObjectClass;
}
public String getRoleObjectClass() {
return roleObjectClass;
}
public void setRoleObjectClass(String roleObjectClass) {
this.roleObjectClass = roleObjectClass;
}
public String getMemberProperty() {
return memberProperty;
}
public void setMemberProperty(String memberProperty) {
this.memberProperty = memberProperty;
}
public String getPermissionProperty() {
return permissionProperty;
}
public void setPermissionProperty(String permissionProperty) {
this.permissionProperty = permissionProperty;
}
public String getRoleBaseDn() {
return new TokenReplacer().register("baseDn", baseDn).substitute(roleBaseDn);
}
public void setRoleBaseDn(String roleBaseDn) {
this.roleBaseDn = roleBaseDn;
}
public String getUserFilter() {
return new TokenReplacer().register("userObjectClass", userObjectClass).substitute(userFilter);
}
public void setUserFilter(String userFilter) {
this.userFilter = userFilter;
}
public String getRoleFilter() {
return new TokenReplacer().register("roleObjectClass", roleObjectClass).substitute(roleFilter);
}
public void setRoleFilter(String roleFilter) {
this.roleFilter = roleFilter;
}
}
| core/com.b2international.snowowl.identity.ldap/src/com/b2international/snowowl/identity/ldap/LdapIdentityProviderConfig.java | /*
* Copyright 2017-2020 B2i Healthcare Pte Ltd, http://b2i.sg
*
* 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.b2international.snowowl.identity.ldap;
import org.hibernate.validator.constraints.NotEmpty;
import com.b2international.commons.TokenReplacer;
import com.b2international.snowowl.core.identity.IdentityProviderConfig;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
/**
* @since 5.11
*/
@JsonTypeName("ldap")
public class LdapIdentityProviderConfig implements IdentityProviderConfig {
@NotEmpty private String uri;
@NotEmpty private String baseDn = "dc=snowowl,dc=b2international,dc=com";
@NotEmpty private String roleBaseDn = "{baseDn}";
@NotEmpty private String bindDn = "cn=admin,dc=snowowl,dc=b2international,dc=com";
@NotEmpty private String bindDnPassword;
@NotEmpty private String userFilter = "(objectClass={userObjectClass})";
@NotEmpty private String roleFilter = "(objectClass={roleObjectClass})";
// Customizable objectClasses
@NotEmpty private String userObjectClass = "inetOrgPerson";
@NotEmpty private String roleObjectClass = "groupOfUniqueNames";
// Customizable attributes
@NotEmpty private String userIdProperty = "uid";
@NotEmpty private String permissionProperty = "description";
@NotEmpty private String memberProperty = "uniqueMember";
private boolean connectionPoolEnabled = false;
public String getBaseDn() {
return baseDn;
}
public void setBaseDn(String baseDn) {
this.baseDn = baseDn;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getBindDn() {
return bindDn;
}
/**
* @param rootDn
* @deprecated - replaced by {@link #setBindDn(String)}, will be removed in 8.0
*/
public void setRootDn(String rootDn) {
setBindDn(rootDn);
}
public void setBindDn(String bindDn) {
this.bindDn = bindDn;
}
public String getBindDnPassword() {
return bindDnPassword;
}
/**
* @param rootDnPassword
* @deprecated - replaced by {@link #setBindDnPassword(String)}, will be removed in 8.0
*/
public void setRootDnPassword(String rootDnPassword) {
setBindDnPassword(rootDnPassword);
}
public void setBindDnPassword(String bindDnPassword) {
this.bindDnPassword = bindDnPassword;
}
public String getUserIdProperty() {
return userIdProperty;
}
public void setUserIdProperty(String userIdProperty) {
this.userIdProperty = userIdProperty;
}
@JsonProperty("usePool")
public boolean isConnectionPoolEnabled() {
return connectionPoolEnabled;
}
@JsonProperty("usePool")
public void setConnectionPoolEnabled(boolean connectionPoolEnabled) {
this.connectionPoolEnabled = connectionPoolEnabled;
}
public String getUserObjectClass() {
return userObjectClass;
}
public void setUserObjectClass(String userObjectClass) {
this.userObjectClass = userObjectClass;
}
public String getRoleObjectClass() {
return roleObjectClass;
}
public void setRoleObjectClass(String roleObjectClass) {
this.roleObjectClass = roleObjectClass;
}
public String getMemberProperty() {
return memberProperty;
}
public void setMemberProperty(String memberProperty) {
this.memberProperty = memberProperty;
}
public String getPermissionProperty() {
return permissionProperty;
}
public void setPermissionProperty(String permissionProperty) {
this.permissionProperty = permissionProperty;
}
public String getRoleBaseDn() {
return new TokenReplacer().register("baseDn", baseDn).substitute(roleBaseDn);
}
public void setRoleBaseDn(String roleBaseDn) {
this.roleBaseDn = roleBaseDn;
}
public String getUserFilter() {
return new TokenReplacer().register("userObjectClass", userObjectClass).substitute(userFilter);
}
public void setUserFilter(String userFilter) {
this.userFilter = userFilter;
}
public String getRoleFilter() {
return new TokenReplacer().register("roleObjectClass", roleObjectClass).substitute(roleFilter);
}
public void setRoleFilter(String roleFilter) {
this.roleFilter = roleFilter;
}
}
| refactor!: remove rootDn and rootDnPassword support from ldap config | core/com.b2international.snowowl.identity.ldap/src/com/b2international/snowowl/identity/ldap/LdapIdentityProviderConfig.java | refactor!: remove rootDn and rootDnPassword support from ldap config | <ide><path>ore/com.b2international.snowowl.identity.ldap/src/com/b2international/snowowl/identity/ldap/LdapIdentityProviderConfig.java
<ide> /*
<del> * Copyright 2017-2020 B2i Healthcare Pte Ltd, http://b2i.sg
<add> * Copyright 2017-2021 B2i Healthcare Pte Ltd, http://b2i.sg
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> return bindDn;
<ide> }
<ide>
<del> /**
<del> * @param rootDn
<del> * @deprecated - replaced by {@link #setBindDn(String)}, will be removed in 8.0
<del> */
<del> public void setRootDn(String rootDn) {
<del> setBindDn(rootDn);
<del> }
<del>
<ide> public void setBindDn(String bindDn) {
<ide> this.bindDn = bindDn;
<ide> }
<ide>
<ide> public String getBindDnPassword() {
<ide> return bindDnPassword;
<del> }
<del>
<del> /**
<del> * @param rootDnPassword
<del> * @deprecated - replaced by {@link #setBindDnPassword(String)}, will be removed in 8.0
<del> */
<del> public void setRootDnPassword(String rootDnPassword) {
<del> setBindDnPassword(rootDnPassword);
<ide> }
<ide>
<ide> public void setBindDnPassword(String bindDnPassword) { |
|
Java | agpl-3.0 | 987a77cc5d32b79e42f98895ee7c5d8398dd1740 | 0 | jaytaylor/sql-layer,relateiq/sql-layer,shunwang/sql-layer-1,wfxiang08/sql-layer-1,ngaut/sql-layer,wfxiang08/sql-layer-1,jaytaylor/sql-layer,ngaut/sql-layer,relateiq/sql-layer,wfxiang08/sql-layer-1,relateiq/sql-layer,ngaut/sql-layer,ngaut/sql-layer,wfxiang08/sql-layer-1,qiuyesuifeng/sql-layer,qiuyesuifeng/sql-layer,relateiq/sql-layer,shunwang/sql-layer-1,jaytaylor/sql-layer,qiuyesuifeng/sql-layer,qiuyesuifeng/sql-layer,jaytaylor/sql-layer,shunwang/sql-layer-1,shunwang/sql-layer-1 | /**
* Copyright (C) 2009-2013 FoundationDB, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.foundationdb.sql.optimizer.rule.join_enum;
import com.foundationdb.sql.optimizer.rule.EquivalenceFinder;
import com.foundationdb.sql.optimizer.rule.PlanContext;
import com.foundationdb.sql.optimizer.rule.SchemaRulesContext;
import com.foundationdb.sql.optimizer.rule.cost.CostEstimator.SelectivityConditions;
import com.foundationdb.sql.optimizer.rule.cost.PlanCostEstimator;
import com.foundationdb.sql.optimizer.rule.join_enum.DPhyp.JoinOperator;
import com.foundationdb.sql.optimizer.rule.range.ColumnRanges;
import com.foundationdb.sql.optimizer.plan.*;
import com.foundationdb.sql.optimizer.plan.Sort.OrderByExpression;
import com.foundationdb.sql.optimizer.plan.TableGroupJoinTree.TableGroupJoinNode;
import com.foundationdb.ais.model.*;
import com.foundationdb.ais.model.Index.JoinType;
import com.foundationdb.server.error.UnsupportedSQLException;
import com.foundationdb.server.geophile.Space;
import com.foundationdb.server.service.text.FullTextQueryBuilder;
import com.foundationdb.server.types.TInstance;
import com.foundationdb.server.types.texpressions.Comparison;
import com.foundationdb.sql.types.DataTypeDescriptor;
import com.foundationdb.sql.types.TypeId;
import com.google.common.base.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Types;
import java.util.*;
/** The goal of a indexes within a group. */
public class GroupIndexGoal implements Comparator<BaseScan>
{
private static final Logger logger = LoggerFactory.getLogger(GroupIndexGoal.class);
static volatile Function<? super IndexScan,Void> intersectionEnumerationHook = null;
// The overall goal.
private QueryIndexGoal queryGoal;
// The grouped tables.
private TableGroupJoinTree tables;
// All the conditions that might be indexable.
private List<ConditionExpression> conditions;
// Where they came from.
private List<ConditionList> conditionSources;
// All the columns besides those in conditions that will be needed.
private RequiredColumns requiredColumns;
// Tables already bound outside.
private Set<ColumnSource> boundTables;
// Can an index be used to take care of sorting.
// TODO: Make this a subset of queryGoal's sorting, based on what
// tables are in what join, rather than an all or nothing.
private boolean sortAllowed;
// Mapping of Range-expressible conditions, by their column. lazy loaded.
private Map<ColumnExpression,ColumnRanges> columnsToRanges;
private PlanContext queryContext;
public GroupIndexGoal(QueryIndexGoal queryGoal, TableGroupJoinTree tables, PlanContext queryContext) {
this.queryGoal = queryGoal;
this.tables = tables;
this.queryContext = queryContext;
if (queryGoal.getWhereConditions() != null) {
conditionSources = Collections.singletonList(queryGoal.getWhereConditions());
conditions = queryGoal.getWhereConditions();
}
else {
conditionSources = Collections.emptyList();
conditions = Collections.emptyList();
}
requiredColumns = new RequiredColumns(tables);
boundTables = queryGoal.getQuery().getOuterTables();
sortAllowed = true;
}
public QueryIndexGoal getQueryGoal() {
return queryGoal;
}
public TableGroupJoinTree getTables() {
return tables;
}
/**
* @param boundTables Tables already bound by the outside
* @param queryJoins Joins that come from the query, or part of the query, that an index is being searched for.
* Will generally, but not in the case of a sub-query, match <code>joins</code>.
* @param joins Joins that apply to this part of the query.
* @param outsideJoins All joins for this query.
* @param sortAllowed <code>true</code> if sorting is allowed
*
* @return Full list of all usable condition sources.
*/
public List<ConditionList> updateContext(Set<ColumnSource> boundTables,
Collection<JoinOperator> queryJoins,
Collection<JoinOperator> joins,
Collection<JoinOperator> outsideJoins,
boolean sortAllowed,
ConditionList extraConditions) {
setBoundTables(boundTables);
this.sortAllowed = sortAllowed;
setJoinConditions(queryJoins, joins, extraConditions);
updateRequiredColumns(joins, outsideJoins);
return conditionSources;
}
public void setBoundTables(Set<ColumnSource> boundTables) {
this.boundTables = boundTables;
}
private static boolean hasOuterJoin(Collection<JoinOperator> joins) {
for (JoinOperator joinOp : joins) {
switch (joinOp.getJoinType()) {
case LEFT:
case RIGHT:
case FULL_OUTER:
return true;
}
}
return false;
}
public void setJoinConditions(Collection<JoinOperator> queryJoins, Collection<JoinOperator> joins, ConditionList extraConditions) {
conditionSources = new ArrayList<>();
if ((queryGoal.getWhereConditions() != null) && !hasOuterJoin(queryJoins)) {
conditionSources.add(queryGoal.getWhereConditions());
}
for (JoinOperator join : joins) {
ConditionList joinConditions = join.getJoinConditions();
if (joinConditions != null)
conditionSources.add(joinConditions);
}
if (extraConditions != null) {
conditionSources.add(extraConditions);
}
switch (conditionSources.size()) {
case 0:
conditions = Collections.emptyList();
break;
case 1:
conditions = conditionSources.get(0);
break;
default:
conditions = new ArrayList<>();
for (ConditionList conditionSource : conditionSources) {
conditions.addAll(conditionSource);
}
}
columnsToRanges = null;
}
public void updateRequiredColumns(Collection<JoinOperator> joins,
Collection<JoinOperator> outsideJoins) {
requiredColumns.clear();
Collection<PlanNode> orderings = (queryGoal.getOrdering() == null) ?
Collections.<PlanNode>emptyList() :
Collections.<PlanNode>singletonList(queryGoal.getOrdering());
RequiredColumnsFiller filler = new RequiredColumnsFiller(requiredColumns,
orderings, conditions);
queryGoal.getQuery().accept(filler);
for (JoinOperator join : outsideJoins) {
if (joins.contains(join)) continue;
ConditionList joinConditions = join.getJoinConditions();
if (joinConditions != null) {
for (ConditionExpression condition : joinConditions) {
condition.accept(filler);
}
}
}
}
/** Given a semi-join to a VALUES, see whether it can be turned
* into a predicate on some column in this group, in which case it
* can possibly be indexed.
*/
public InListCondition semiJoinToInList(ExpressionsSource values,
Collection<JoinOperator> joins) {
if (values.nFields() != 1)
return null;
ComparisonCondition ccond = null;
boolean found = false;
ConditionExpression joinCondition = onlyJoinCondition(joins);
if (joinCondition instanceof ComparisonCondition) {
ccond = (ComparisonCondition)joinCondition;
if ((ccond.getOperation() == Comparison.EQ) &&
(ccond.getRight() instanceof ColumnExpression)) {
ColumnExpression rcol = (ColumnExpression)ccond.getRight();
if ((rcol.getTable() == values) &&
(rcol.getPosition() == 0) &&
(ccond.getLeft() instanceof ColumnExpression)) {
ColumnExpression lcol = (ColumnExpression)ccond.getLeft();
for (TableGroupJoinNode table : tables) {
if (table.getTable() == lcol.getTable()) {
found = true;
break;
}
}
}
}
}
if (!found) return null;
return semiJoinToInList(values, ccond, queryGoal.getRulesContext());
}
protected static ConditionExpression onlyJoinCondition(Collection<JoinOperator> joins) {
ConditionExpression result = null;
for (JoinOperator join : joins) {
if (join.getJoinConditions() != null) {
for (ConditionExpression cond : join.getJoinConditions()) {
if (result == null)
result = cond;
else
return null;
}
}
}
return result;
}
public static InListCondition semiJoinToInList(ExpressionsSource values,
ComparisonCondition ccond,
SchemaRulesContext rulesContext) {
List<ExpressionNode> expressions = new ArrayList<>(values.getExpressions().size());
for (List<ExpressionNode> row : values.getExpressions()) {
expressions.add(row.get(0));
}
DataTypeDescriptor sqlType = new DataTypeDescriptor(TypeId.BOOLEAN_ID, true);
TInstance type = rulesContext.getTypesTranslator().typeForSQLType(sqlType);
InListCondition cond = new InListCondition(ccond.getLeft(), expressions,
sqlType, null, type);
cond.setComparison(ccond);
//cond.setPreptimeValue(new TPreptimeValue(AkBool.INSTANCE.instance(true)));
return cond;
}
/** Populate given index usage according to goal.
* @return <code>false</code> if the index is useless.
*/
public boolean usable(SingleIndexScan index) {
setColumnsAndOrdering(index);
int nequals = insertLeadingEqualities(index, conditions);
if (index.getIndex().isSpatial()) return spatialUsable(index, nequals);
List<ExpressionNode> indexExpressions = index.getColumns();
if (nequals < indexExpressions.size()) {
ExpressionNode indexExpression = indexExpressions.get(nequals);
if (indexExpression != null) {
boolean foundInequalityCondition = false;
for (ConditionExpression condition : conditions) {
if (condition instanceof ComparisonCondition) {
ComparisonCondition ccond = (ComparisonCondition)condition;
if (ccond.getOperation() == Comparison.NE)
continue; // ranges are better suited for !=
ExpressionNode otherComparand = matchingComparand(indexExpression, ccond);
if (otherComparand != null) {
Comparison op = ccond.getOperation();
if (otherComparand == ccond.getLeft())
op = ComparisonCondition.reverseComparison(op);
index.addInequalityCondition(condition, op, otherComparand);
foundInequalityCondition = true;
}
}
}
if (!foundInequalityCondition) {
ColumnRanges range = rangeForIndex(indexExpression);
if (range != null)
index.addRangeCondition(range);
}
}
}
index.setOrderEffectiveness(determineOrderEffectiveness(index));
index.setCovering(determineCovering(index));
if ((index.getOrderEffectiveness() == IndexScan.OrderEffectiveness.NONE) &&
!index.hasConditions() &&
!index.isCovering())
return false;
index.setCostEstimate(estimateCost(index));
return true;
}
private int insertLeadingEqualities(EqualityColumnsScan index, List<ConditionExpression> localConds) {
int nequals = 0;
List<ExpressionNode> indexExpressions = index.getColumns();
int ncols = indexExpressions.size();
while (nequals < ncols) {
ExpressionNode indexExpression = indexExpressions.get(nequals);
if (indexExpression == null) break;
ConditionExpression equalityCondition = null;
ExpressionNode otherComparand = null;
for (ConditionExpression condition : localConds) {
if (condition instanceof ComparisonCondition) {
ComparisonCondition ccond = (ComparisonCondition)condition;
if (ccond.getOperation() != Comparison.EQ)
continue; // only doing equalities
ExpressionNode comparand = matchingComparand(indexExpression, ccond);
if (comparand != null) {
equalityCondition = condition;
otherComparand = comparand;
break;
}
}
else if (condition instanceof FunctionCondition) {
FunctionCondition fcond = (FunctionCondition)condition;
if (fcond.getFunction().equals("isNull") &&
(fcond.getOperands().size() == 1) &&
indexExpressionMatches(indexExpression,
fcond.getOperands().get(0))) {
ExpressionNode foperand = fcond.getOperands().get(0);
equalityCondition = condition;
otherComparand = new IsNullIndexKey(foperand.getSQLtype(),
fcond.getSQLsource(),
foperand.getType());
break;
}
}
}
if (equalityCondition == null)
break;
index.addEqualityCondition(equalityCondition, otherComparand);
nequals++;
}
return nequals;
}
private ExpressionNode matchingComparand(ExpressionNode indexExpression,
ComparisonCondition ccond) {
ExpressionNode comparand;
if (indexExpressionMatches(indexExpression, ccond.getLeft())) {
comparand = ccond.getRight();
if (constantOrBound(comparand))
return comparand;
}
if (indexExpressionMatches(indexExpression, ccond.getRight())) {
comparand = ccond.getLeft();
if (constantOrBound(comparand))
return comparand;
}
return null;
}
private static void setColumnsAndOrdering(SingleIndexScan index) {
List<IndexColumn> indexColumns = index.getAllColumns();
int ncols = indexColumns.size();
int firstSpatialColumn, dimensions;
SpecialIndexExpression.Function spatialFunction;
if (index.getIndex().isSpatial()) {
Index spatialIndex = index.getIndex();
firstSpatialColumn = spatialIndex.firstSpatialArgument();
dimensions = spatialIndex.dimensions();
assert (dimensions == Space.LAT_LON_DIMENSIONS);
spatialFunction = SpecialIndexExpression.Function.Z_ORDER_LAT_LON;
}
else {
firstSpatialColumn = Integer.MAX_VALUE;
dimensions = 0;
spatialFunction = null;
}
List<OrderByExpression> orderBy = new ArrayList<>(ncols);
List<ExpressionNode> indexExpressions = new ArrayList<>(ncols);
int i = 0;
while (i < ncols) {
ExpressionNode indexExpression;
boolean ascending;
if (i == firstSpatialColumn) {
List<ExpressionNode> operands = new ArrayList<>(dimensions);
for (int j = 0; j < dimensions; j++) {
operands.add(getIndexExpression(index, indexColumns.get(i++)));
}
indexExpression = new SpecialIndexExpression(spatialFunction, operands);
ascending = true;
}
else {
IndexColumn indexColumn = indexColumns.get(i++);
indexExpression = getIndexExpression(index, indexColumn);
ascending = indexColumn.isAscending();
}
indexExpressions.add(indexExpression);
orderBy.add(new OrderByExpression(indexExpression, ascending));
}
index.setColumns(indexExpressions);
index.setOrdering(orderBy);
}
// Take ordering from output index and adjust ordering of others to match.
private static void installOrdering(IndexScan index,
List<OrderByExpression> outputOrdering,
int outputPeggedCount, int comparisonFields) {
if (index instanceof SingleIndexScan) {
List<OrderByExpression> indexOrdering = index.getOrdering();
if ((indexOrdering != null) && (indexOrdering != outputOrdering)) {
// Order comparison fields the same way as output.
// Try to avoid mixed mode: initial columns ordered
// like first comparison, trailing columns ordered
// like last comparison.
int i = 0;
while (i < index.getPeggedCount()) {
indexOrdering.get(i++).setAscending(outputOrdering.get(outputPeggedCount).isAscending());
}
for (int j = 0; j < comparisonFields; j++) {
indexOrdering.get(i++).setAscending(outputOrdering.get(outputPeggedCount + j).isAscending());
}
while (i < indexOrdering.size()) {
indexOrdering.get(i++).setAscending(outputOrdering.get(outputPeggedCount + comparisonFields - 1).isAscending());
}
}
}
else if (index instanceof MultiIndexIntersectScan) {
MultiIndexIntersectScan multiIndex = (MultiIndexIntersectScan)index;
installOrdering(multiIndex.getOutputIndexScan(),
outputOrdering, outputPeggedCount, comparisonFields);
installOrdering(multiIndex.getSelectorIndexScan(),
outputOrdering, outputPeggedCount, comparisonFields);
}
}
// Determine how well this index does against the target.
// Also, correct traversal order to match sort if possible.
protected IndexScan.OrderEffectiveness
determineOrderEffectiveness(SingleIndexScan index) {
IndexScan.OrderEffectiveness result = IndexScan.OrderEffectiveness.NONE;
if (!sortAllowed) return result;
List<OrderByExpression> indexOrdering = index.getOrdering();
if (indexOrdering == null) return result;
BitSet reverse = new BitSet(indexOrdering.size());
int nequals = index.getNEquality();
List<ExpressionNode> equalityColumns = null;
if (nequals > 0) {
equalityColumns = index.getColumns().subList(0, nequals);
}
try_sorted:
if (queryGoal.getOrdering() != null) {
int idx = nequals;
for (OrderByExpression targetColumn : queryGoal.getOrdering().getOrderBy()) {
// Get the expression by which this is ordering, recognizing the
// special cases where the Sort is fed by GROUP BY or feeds DISTINCT.
ExpressionNode targetExpression = targetColumn.getExpression();
if (targetExpression.isColumn()) {
ColumnExpression column = (ColumnExpression)targetExpression;
ColumnSource table = column.getTable();
if (table == queryGoal.getGrouping()) {
targetExpression = queryGoal.getGrouping()
.getField(column.getPosition());
}
else if (table instanceof Project) {
// Cf. ASTStatementLoader.sortsForDistinct().
Project project = (Project)table;
if ((project.getOutput() == queryGoal.getOrdering()) &&
(queryGoal.getOrdering().getOutput() instanceof Distinct)) {
targetExpression = project.getFields()
.get(column.getPosition());
}
}
}
OrderByExpression indexColumn = null;
if (idx < indexOrdering.size()) {
indexColumn = indexOrdering.get(idx);
if (indexColumn.getExpression() == null)
indexColumn = null; // Index sorts by unknown column.
}
if ((indexColumn != null) &&
orderingExpressionMatches(indexColumn, targetExpression)) {
if (indexColumn.isAscending() != targetColumn.isAscending()) {
// To avoid mixed mode as much as possible,
// defer changing the index order until
// certain it will be effective.
reverse.set(idx, true);
if (idx == nequals)
// Likewise reverse the initial equals segment.
reverse.set(0, nequals, true);
}
if (idx >= index.getNKeyColumns())
index.setUsesAllColumns(true);
idx++;
continue;
}
if (equalityColumns != null) {
// Another possibility is that target ordering is
// in fact unchanged due to equality condition.
// TODO: Should this have been noticed earlier on
// so that it can be taken out of the sort?
if (equalityColumns.contains(targetExpression))
continue;
}
break try_sorted;
}
if ((idx > 0) && (idx < indexOrdering.size()) && reverse.get(idx-1))
// Reverse after ORDER BY if reversed last one.
reverse.set(idx, indexOrdering.size(), true);
for (int i = 0; i < reverse.size(); i++) {
if (reverse.get(i)) {
OrderByExpression indexColumn = indexOrdering.get(i);
indexColumn.setAscending(!indexColumn.isAscending());
}
}
result = IndexScan.OrderEffectiveness.SORTED;
}
if (queryGoal.getGrouping() != null) {
boolean anyFound = false, allFound = true;
List<ExpressionNode> groupBy = queryGoal.getGrouping().getGroupBy();
for (ExpressionNode targetExpression : groupBy) {
int found = -1;
for (int i = nequals; i < indexOrdering.size(); i++) {
if (orderingExpressionMatches(indexOrdering.get(i), targetExpression)) {
found = i - nequals;
break;
}
}
if (found < 0) {
allFound = false;
if ((equalityColumns == null) ||
!equalityColumns.contains(targetExpression))
continue;
}
else if (found >= groupBy.size()) {
// Ordered by this column, but after some other
// stuff which will break up the group. Only
// partially grouped.
allFound = false;
}
if (found >= index.getNKeyColumns()) {
index.setUsesAllColumns(true);
}
anyFound = true;
}
if (anyFound) {
if (!allFound)
return IndexScan.OrderEffectiveness.PARTIAL_GROUPED;
else if (result == IndexScan.OrderEffectiveness.SORTED)
return result;
else
return IndexScan.OrderEffectiveness.GROUPED;
}
}
else if (queryGoal.getProjectDistinct() != null) {
assert (queryGoal.getOrdering() == null);
if (orderedForDistinct(index, queryGoal.getProjectDistinct(),
indexOrdering, nequals)) {
return IndexScan.OrderEffectiveness.SORTED;
}
}
return result;
}
/** For use with a Distinct that gets added later. */
public boolean orderedForDistinct(Project projectDistinct, IndexScan index) {
List<OrderByExpression> indexOrdering = index.getOrdering();
if (indexOrdering == null) return false;
int nequals = index.getNEquality();
return orderedForDistinct(index, projectDistinct, indexOrdering, nequals);
}
protected boolean orderedForDistinct(IndexScan index, Project projectDistinct,
List<OrderByExpression> indexOrdering,
int nequals) {
List<ExpressionNode> distinct = projectDistinct.getFields();
for (ExpressionNode targetExpression : distinct) {
int found = -1;
for (int i = nequals; i < indexOrdering.size(); i++) {
if (orderingExpressionMatches(indexOrdering.get(i), targetExpression)) {
found = i - nequals;
break;
}
}
if ((found < 0) || (found >= distinct.size())) {
return false;
}
if (found >= index.getNKeyColumns()) {
index.setUsesAllColumns(true);
}
}
return true;
}
// Does the column expression coming from the index match the ORDER BY target,
// allowing for column equivalences?
protected boolean orderingExpressionMatches(OrderByExpression orderByExpression,
ExpressionNode targetExpression) {
ExpressionNode columnExpression = orderByExpression.getExpression();
if (columnExpression == null)
return false;
if (columnExpression.equals(targetExpression))
return true;
if (!(columnExpression instanceof ColumnExpression) ||
!(targetExpression instanceof ColumnExpression))
return false;
return getColumnEquivalencies().areEquivalent((ColumnExpression)columnExpression,
(ColumnExpression)targetExpression);
}
protected EquivalenceFinder<ColumnExpression> getColumnEquivalencies() {
return queryGoal.getQuery().getColumnEquivalencies();
}
protected class UnboundFinder implements ExpressionVisitor {
boolean found = false;
public UnboundFinder() {
}
@Override
public boolean visitEnter(ExpressionNode n) {
return visit(n);
}
@Override
public boolean visitLeave(ExpressionNode n) {
return !found;
}
@Override
public boolean visit(ExpressionNode n) {
if (n instanceof ColumnExpression) {
ColumnExpression columnExpression = (ColumnExpression)n;
if (!boundTables.contains(columnExpression.getTable())) {
found = true;
return false;
}
}
else if (n instanceof SubqueryExpression) {
for (ColumnSource used : ((SubqueryExpression)n).getSubquery().getOuterTables()) {
// Tables defined inside the subquery are okay, but ones from outside
// need to be bound to eval as an expression.
if (!boundTables.contains(used)) {
found = true;
return false;
}
}
}
return true;
}
}
/** Does the given expression have references to tables that aren't bound? */
protected boolean constantOrBound(ExpressionNode expression) {
UnboundFinder f = new UnboundFinder();
expression.accept(f);
return !f.found;
}
/** Get an expression form of the given index column. */
protected static ExpressionNode getIndexExpression(IndexScan index,
IndexColumn indexColumn) {
return getColumnExpression(index.getLeafMostTable(), indexColumn.getColumn());
}
/** Get an expression form of the given group column. */
protected static ExpressionNode getColumnExpression(TableSource leafMostTable,
Column column) {
Table indexTable = column.getTable();
for (TableSource table = leafMostTable;
null != table;
table = table.getParentTable()) {
if (table.getTable().getTable() == indexTable) {
return new ColumnExpression(table, column);
}
}
return null;
}
/** Is the comparison operand what the index indexes? */
protected boolean indexExpressionMatches(ExpressionNode indexExpression,
ExpressionNode comparisonOperand) {
if (indexExpression.equals(comparisonOperand))
return true;
if (!(indexExpression instanceof ColumnExpression) ||
!(comparisonOperand instanceof ColumnExpression))
return false;
if (getColumnEquivalencies().areEquivalent((ColumnExpression)indexExpression,
(ColumnExpression)comparisonOperand))
return true;
// See if comparing against a result column of the subquery,
// that is, a join to the subquery that we can push down.
ColumnExpression comparisonColumn = (ColumnExpression)comparisonOperand;
ColumnSource comparisonTable = comparisonColumn.getTable();
if (!(comparisonTable instanceof SubquerySource))
return false;
Subquery subquery = ((SubquerySource)comparisonTable).getSubquery();
if (subquery != queryGoal.getQuery())
return false;
PlanNode input = subquery.getQuery();
if (input instanceof ResultSet)
input = ((ResultSet)input).getInput();
if (!(input instanceof Project))
return false;
Project project = (Project)input;
ExpressionNode insideExpression = project.getFields().get(comparisonColumn.getPosition());
return indexExpressionMatches(indexExpression, insideExpression);
}
/** Find the best index among the branches. */
public BaseScan pickBestScan() {
logger.debug("Picking for {}", this);
BaseScan bestScan = null;
bestScan = pickFullText();
if (bestScan != null) {
return bestScan; // TODO: Always wins for now.
}
if (tables.getGroup().getRejectedJoins() != null) {
bestScan = pickBestGroupLoop();
}
IntersectionEnumerator intersections = new IntersectionEnumerator();
Set<TableSource> required = tables.getRequired();
for (TableGroupJoinNode table : tables) {
IndexScan tableIndex = pickBestIndex(table, required, intersections);
if ((tableIndex != null) &&
((bestScan == null) || (compare(tableIndex, bestScan) > 0)))
bestScan = tableIndex;
ExpressionsHKeyScan hKeyRow = pickHKeyRow(table, required);
if ((hKeyRow != null) &&
((bestScan == null) || (compare(hKeyRow, bestScan) > 0)))
bestScan = hKeyRow;
}
bestScan = pickBestIntersection(bestScan, intersections);
if (bestScan == null) {
GroupScan groupScan = new GroupScan(tables.getGroup());
groupScan.setCostEstimate(estimateCost(groupScan));
bestScan = groupScan;
}
return bestScan;
}
private BaseScan pickBestIntersection(BaseScan previousBest, IntersectionEnumerator enumerator) {
// filter out all leaves which are obviously bad
if (previousBest != null) {
CostEstimate previousBestCost = previousBest.getCostEstimate();
for (Iterator<SingleIndexScan> iter = enumerator.leavesIterator(); iter.hasNext(); ) {
SingleIndexScan scan = iter.next();
CostEstimate scanCost = estimateIntersectionCost(scan);
if (scanCost.compareTo(previousBestCost) > 0) {
logger.debug("Not intersecting {} {}", scan, scanCost);
iter.remove();
}
}
}
Function<? super IndexScan,Void> hook = intersectionEnumerationHook;
for (Iterator<IndexScan> iterator = enumerator.iterator(); iterator.hasNext(); ) {
IndexScan intersectedIndex = iterator.next();
if (hook != null)
hook.apply(intersectedIndex);
setIntersectionConditions(intersectedIndex);
intersectedIndex.setCovering(determineCovering(intersectedIndex));
intersectedIndex.setCostEstimate(estimateCost(intersectedIndex));
if (previousBest == null) {
logger.debug("Selecting {}", intersectedIndex);
previousBest = intersectedIndex;
}
else if (compare(intersectedIndex, previousBest) > 0) {
logger.debug("Preferring {}", intersectedIndex);
previousBest = intersectedIndex;
}
else {
logger.debug("Rejecting {}", intersectedIndex);
// If the scan costs alone are higher than the previous best cost, there's no way this scan or
// any scan that uses it will be the best. Just remove the whole branch.
if (intersectedIndex.getScanCostEstimate().compareTo(previousBest.getCostEstimate()) > 0)
iterator.remove();
}
}
return previousBest;
}
private void setIntersectionConditions(IndexScan rawScan) {
MultiIndexIntersectScan scan = (MultiIndexIntersectScan) rawScan;
if (isAncestor(scan.getOutputIndexScan().getLeafMostTable(),
scan.getSelectorIndexScan().getLeafMostTable())) {
// More conditions up the same branch are safely implied by the output row.
ConditionsCounter<ConditionExpression> counter = new ConditionsCounter<>(conditions.size());
scan.incrementConditionsCounter(counter);
scan.setConditions(new ArrayList<>(counter.getCountedConditions()));
}
else {
// Otherwise only those for the output row are safe and
// conditions on another branch need to be checked again;
scan.setConditions(scan.getOutputIndexScan().getConditions());
}
}
/** Is the given <code>rootTable</code> an ancestor of <code>leafTable</code>? */
private static boolean isAncestor(TableSource leafTable, TableSource rootTable) {
do {
if (leafTable == rootTable)
return true;
leafTable = leafTable.getParentTable();
} while (leafTable != null);
return false;
}
private class IntersectionEnumerator extends MultiIndexEnumerator<ConditionExpression,IndexScan,SingleIndexScan> {
@Override
protected Collection<ConditionExpression> getLeafConditions(SingleIndexScan scan) {
int skips = scan.getPeggedCount();
List<ConditionExpression> conditions = scan.getConditions();
if (conditions == null)
return null;
int nconds = conditions.size();
return ((skips) > 0 && (skips == nconds)) ? conditions : null;
}
@Override
protected IndexScan intersect(IndexScan first, IndexScan second, int comparisons) {
return new MultiIndexIntersectScan(first, second, comparisons);
}
@Override
protected List<Column> getComparisonColumns(IndexScan first, IndexScan second) {
EquivalenceFinder<ColumnExpression> equivs = getColumnEquivalencies();
List<ExpressionNode> firstOrdering = orderingCols(first);
List<ExpressionNode> secondOrdering = orderingCols(second);
int ncols = Math.min(firstOrdering.size(), secondOrdering.size());
List<Column> result = new ArrayList<>(ncols);
for (int i=0; i < ncols; ++i) {
ExpressionNode firstCol = firstOrdering.get(i);
ExpressionNode secondCol = secondOrdering.get(i);
if (!(firstCol instanceof ColumnExpression) || !(secondCol instanceof ColumnExpression))
break;
if (!equivs.areEquivalent((ColumnExpression) firstCol, (ColumnExpression) secondCol))
break;
result.add(((ColumnExpression)firstCol).getColumn());
}
return result;
}
private List<ExpressionNode> orderingCols(IndexScan index) {
List<ExpressionNode> result = index.getColumns();
return result.subList(index.getPeggedCount(), result.size());
}
}
/** Find the best index on the given table.
* @param required Tables reachable from root via INNER joins and hence not nullable.
*/
public IndexScan pickBestIndex(TableGroupJoinNode node, Set<TableSource> required, IntersectionEnumerator enumerator) {
TableSource table = node.getTable();
IndexScan bestIndex = null;
// Can only consider single table indexes when table is not
// nullable (required). If table is the optional part of a
// LEFT join, can still consider compatible LEFT / RIGHT group
// indexes, below. WHERE conditions are removed before this is
// called, see GroupIndexGoal#setJoinConditions().
if (required.contains(table)) {
for (TableIndex index : table.getTable().getTable().getIndexes()) {
SingleIndexScan candidate = new SingleIndexScan(index, table, queryContext);
bestIndex = betterIndex(bestIndex, candidate, enumerator);
}
}
if ((table.getGroup() != null) && !hasOuterJoinNonGroupConditions(node)) {
for (GroupIndex index : table.getGroup().getGroup().getIndexes()) {
// The leaf must be used or else we'll get duplicates from a
// scan (the indexed columns need not be root to leaf, making
// ancestors discontiguous and duplicates hard to eliminate).
if (index.leafMostTable() != table.getTable().getTable())
continue;
TableSource rootTable = table;
TableSource rootRequired = null, leafRequired = null;
if (index.getJoinType() == JoinType.LEFT) {
while (rootTable != null) {
if (required.contains(rootTable)) {
rootRequired = rootTable;
if (leafRequired == null)
leafRequired = rootTable;
}
else {
if (leafRequired != null) {
// Optional above required, not LEFT join compatible.
leafRequired = null;
break;
}
}
if (index.rootMostTable() == rootTable.getTable().getTable())
break;
rootTable = rootTable.getParentTable();
}
// The root must be present, since a LEFT index
// does not contain orphans.
if ((rootTable == null) ||
(rootRequired != rootTable) ||
(leafRequired == null))
continue;
}
else {
if (!required.contains(table))
continue;
leafRequired = table;
boolean optionalSeen = false;
while (rootTable != null) {
if (required.contains(rootTable)) {
if (optionalSeen) {
// Required above optional, not RIGHT join compatible.
rootRequired = null;
break;
}
rootRequired = rootTable;
}
else {
optionalSeen = true;
}
if (index.rootMostTable() == rootTable.getTable().getTable())
break;
rootTable = rootTable.getParentTable();
}
// TODO: There are no INNER JOIN group indexes,
// but this would support them.
/*
if (optionalSeen && (index.getJoinType() == JoinType.INNER))
continue;
*/
if ((rootTable == null) ||
(rootRequired == null))
continue;
}
SingleIndexScan candidate = new SingleIndexScan(index, rootTable,
rootRequired, leafRequired,
table, queryContext);
bestIndex = betterIndex(bestIndex, candidate, enumerator);
}
}
return bestIndex;
}
// If a LEFT join has more conditions, they won't be included in an index, so
// can't use it.
protected boolean hasOuterJoinNonGroupConditions(TableGroupJoinNode node) {
if (node.getTable().isRequired())
return false;
ConditionList conditions = node.getJoinConditions();
if (conditions != null) {
for (ConditionExpression cond : conditions) {
if (cond.getImplementation() != ConditionExpression.Implementation.GROUP_JOIN) {
return true;
}
}
}
return false;
}
protected IndexScan betterIndex(IndexScan bestIndex, SingleIndexScan candidate, IntersectionEnumerator enumerator) {
if (usable(candidate)) {
enumerator.addLeaf(candidate);
if (bestIndex == null) {
logger.debug("Selecting {}", candidate);
return candidate;
}
else if (compare(candidate, bestIndex) > 0) {
logger.debug("Preferring {}", candidate);
return candidate;
}
else {
logger.debug("Rejecting {}", candidate);
}
}
return bestIndex;
}
private GroupLoopScan pickBestGroupLoop() {
GroupLoopScan bestScan = null;
Set<TableSource> outsideSameGroup = new HashSet<>(tables.getGroup().getTables());
outsideSameGroup.retainAll(boundTables);
for (TableGroupJoin join : tables.getGroup().getRejectedJoins()) {
TableSource parent = join.getParent();
TableSource child = join.getChild();
TableSource inside, outside;
boolean insideIsParent;
if (outsideSameGroup.contains(parent) && tables.containsTable(child)) {
inside = child;
outside = parent;
insideIsParent = false;
}
else if (outsideSameGroup.contains(child) && tables.containsTable(parent)) {
inside = parent;
outside = child;
insideIsParent = true;
}
else {
continue;
}
if (mightFlattenOrSort(outside)) {
continue; // Lookup_Nested won't be allowed.
}
GroupLoopScan forJoin = new GroupLoopScan(inside, outside, insideIsParent,
join.getConditions());
determineRequiredTables(forJoin);
forJoin.setCostEstimate(estimateCost(forJoin));
if (bestScan == null) {
logger.debug("Selecting {}", forJoin);
bestScan = forJoin;
}
else if (compare(forJoin, bestScan) > 0) {
logger.debug("Preferring {}", forJoin);
bestScan = forJoin;
}
else {
logger.debug("Rejecting {}", forJoin);
}
}
return bestScan;
}
private boolean mightFlattenOrSort(TableSource table) {
if (!(table.getOutput() instanceof TableGroupJoinTree))
return true; // Don't know; be conservative.
TableGroupJoinTree tree = (TableGroupJoinTree)table.getOutput();
TableGroupJoinNode root = tree.getRoot();
if (root.getTable() != table)
return true;
if (root.getFirstChild() != null)
return true;
// Only table in this join tree, shouldn't flatten.
PlanNode output = tree;
do {
output = output.getOutput();
if (output instanceof Sort)
return true;
if (output instanceof ResultSet)
break;
} while (output != null);
return false; // No Sort, either.
}
private ExpressionsHKeyScan pickHKeyRow(TableGroupJoinNode node, Set<TableSource> required) {
TableSource table = node.getTable();
if (!required.contains(table)) return null;
ExpressionsHKeyScan scan = new ExpressionsHKeyScan(table);
HKey hKey = scan.getHKey();
int ncols = hKey.nColumns();
List<ExpressionNode> columns = new ArrayList<>(ncols);
for (int i = 0; i < ncols; i++) {
ExpressionNode column = getColumnExpression(table, hKey.column(i));
if (column == null) return null;
columns.add(column);
}
scan.setColumns(columns);
int nequals = insertLeadingEqualities(scan, conditions);
if (nequals != ncols) return null;
required = new HashSet<>(required);
// We do not handle any actual data columns.
required.addAll(requiredColumns.getTables());
scan.setRequiredTables(required);
scan.setCostEstimate(estimateCost(scan));
logger.debug("Selecting {}", scan);
return scan;
}
public int compare(BaseScan i1, BaseScan i2) {
return i2.getCostEstimate().compareTo(i1.getCostEstimate());
}
protected boolean determineCovering(IndexScan index) {
// Include the non-condition requirements.
RequiredColumns requiredAfter = new RequiredColumns(requiredColumns);
RequiredColumnsFiller filler = new RequiredColumnsFiller(requiredAfter);
// Add in any conditions not handled by the index.
for (ConditionExpression condition : conditions) {
boolean found = false;
if (index.getConditions() != null) {
for (ConditionExpression indexCondition : index.getConditions()) {
if (indexCondition == condition) {
found = true;
break;
}
}
}
if (!found)
condition.accept(filler);
}
// Add sort if not handled by the index.
if ((queryGoal.getOrdering() != null) &&
(index.getOrderEffectiveness() != IndexScan.OrderEffectiveness.SORTED)) {
// Only this node, not its inputs.
filler.setIncludedPlanNodes(Collections.<PlanNode>singletonList(queryGoal.getOrdering()));
queryGoal.getOrdering().accept(filler);
}
// Record what tables are required: within the index if any
// columns still needed, others if joined at all. Do this
// before taking account of columns from a covering index,
// since may not use it that way.
{
Collection<TableSource> joined = index.getTables();
Set<TableSource> required = new HashSet<>();
boolean moreTables = false;
for (TableSource table : requiredAfter.getTables()) {
if (!joined.contains(table)) {
moreTables = true;
required.add(table);
}
else if (requiredAfter.hasColumns(table) ||
(table == queryGoal.getUpdateTarget())) {
required.add(table);
}
}
index.setRequiredTables(required);
if (moreTables)
// Need to join up last the index; index might point
// to an orphan.
return false;
}
if (queryGoal.getUpdateTarget() != null) {
// UPDATE statements need the whole target row and are thus never
// covering for their group.
for (TableGroupJoinNode table : tables) {
if (table.getTable() == queryGoal.getUpdateTarget())
return false;
}
}
// Remove the columns we do have from the index.
int ncols = index.getColumns().size();
for (int i = 0; i < ncols; i++) {
ExpressionNode column = index.getColumns().get(i);
if ((column instanceof ColumnExpression) && index.isRecoverableAt(i)) {
if (requiredAfter.have((ColumnExpression)column) &&
(i >= index.getNKeyColumns())) {
index.setUsesAllColumns(true);
}
}
}
return requiredAfter.isEmpty();
}
protected void determineRequiredTables(GroupLoopScan scan) {
// Include the non-condition requirements.
RequiredColumns requiredAfter = new RequiredColumns(requiredColumns);
RequiredColumnsFiller filler = new RequiredColumnsFiller(requiredAfter);
// Add in any non-join conditions.
for (ConditionExpression condition : conditions) {
boolean found = false;
for (ConditionExpression joinCondition : scan.getJoinConditions()) {
if (joinCondition == condition) {
found = true;
break;
}
}
if (!found)
condition.accept(filler);
}
// Does not sort.
if (queryGoal.getOrdering() != null) {
// Only this node, not its inputs.
filler.setIncludedPlanNodes(Collections.<PlanNode>singletonList(queryGoal.getOrdering()));
queryGoal.getOrdering().accept(filler);
}
// The only table we can exclude is the one initially joined to, in the case
// where all the data comes from elsewhere on that branch.
Set<TableSource> required = new HashSet<>(requiredAfter.getTables());
if ((required.size() > 1) &&
!requiredAfter.hasColumns(scan.getInsideTable()))
required.remove(scan.getInsideTable());
scan.setRequiredTables(required);
}
public CostEstimate estimateCost(IndexScan index) {
return estimateCost(index, queryGoal.getLimit());
}
public CostEstimate estimateCost(IndexScan index, long limit) {
PlanCostEstimator estimator = newEstimator();
Set<TableSource> requiredTables = index.getRequiredTables();
estimator.indexScan(index);
if (!index.isCovering()) {
estimator.flatten(tables,
index.getLeafMostTable(), requiredTables);
}
Collection<ConditionExpression> unhandledConditions =
new HashSet<>(conditions);
if (index.getConditions() != null)
unhandledConditions.removeAll(index.getConditions());
if (!unhandledConditions.isEmpty()) {
estimator.select(unhandledConditions,
selectivityConditions(unhandledConditions, requiredTables));
}
if (queryGoal.needSort(index.getOrderEffectiveness())) {
estimator.sort(queryGoal.sortFields());
}
estimator.setLimit(limit);
return estimator.getCostEstimate();
}
public CostEstimate estimateIntersectionCost(IndexScan index) {
if (index.getOrderEffectiveness() == IndexScan.OrderEffectiveness.NONE)
return index.getScanCostEstimate();
long limit = queryGoal.getLimit();
if (limit < 0)
return index.getScanCostEstimate();
// There is a limit and this index looks to be sorted, so adjust for that
// limit. Otherwise, the scan only cost, which includes all rows, will appear
// too large compared to a limit-aware best plan.
PlanCostEstimator estimator = newEstimator();
estimator.indexScan(index);
estimator.setLimit(limit);
return estimator.getCostEstimate();
}
public CostEstimate estimateCost(GroupScan scan) {
PlanCostEstimator estimator = newEstimator();
Set<TableSource> requiredTables = requiredColumns.getTables();
estimator.groupScan(scan, tables, requiredTables);
if (!conditions.isEmpty()) {
estimator.select(conditions,
selectivityConditions(conditions, requiredTables));
}
estimator.setLimit(queryGoal.getLimit());
return estimator.getCostEstimate();
}
public CostEstimate estimateCost(GroupLoopScan scan) {
PlanCostEstimator estimator = newEstimator();
Set<TableSource> requiredTables = scan.getRequiredTables();
estimator.groupLoop(scan, tables, requiredTables);
Collection<ConditionExpression> unhandledConditions =
new HashSet<>(conditions);
unhandledConditions.removeAll(scan.getJoinConditions());
if (!unhandledConditions.isEmpty()) {
estimator.select(unhandledConditions,
selectivityConditions(unhandledConditions, requiredTables));
}
if (queryGoal.needSort(IndexScan.OrderEffectiveness.NONE)) {
estimator.sort(queryGoal.sortFields());
}
estimator.setLimit(queryGoal.getLimit());
return estimator.getCostEstimate();
}
public CostEstimate estimateCost(ExpressionsHKeyScan scan) {
PlanCostEstimator estimator = newEstimator();
Set<TableSource> requiredTables = scan.getRequiredTables();
estimator.hKeyRow(scan);
estimator.flatten(tables, scan.getTable(), requiredTables);
Collection<ConditionExpression> unhandledConditions =
new HashSet<>(conditions);
unhandledConditions.removeAll(scan.getConditions());
if (!unhandledConditions.isEmpty()) {
estimator.select(unhandledConditions,
selectivityConditions(unhandledConditions, requiredTables));
}
if (queryGoal.needSort(IndexScan.OrderEffectiveness.NONE)) {
estimator.sort(queryGoal.sortFields());
}
estimator.setLimit(queryGoal.getLimit());
return estimator.getCostEstimate();
}
public double estimateSelectivity(IndexScan index) {
return queryGoal.getCostEstimator().conditionsSelectivity(selectivityConditions(index.getConditions(), index.getTables()));
}
// Conditions that might have a recognizable selectivity.
protected SelectivityConditions selectivityConditions(Collection<ConditionExpression> conditions, Collection<TableSource> requiredTables) {
SelectivityConditions result = new SelectivityConditions();
for (ConditionExpression condition : conditions) {
if (condition instanceof ComparisonCondition) {
ComparisonCondition ccond = (ComparisonCondition)condition;
if (ccond.getLeft() instanceof ColumnExpression) {
ColumnExpression column = (ColumnExpression)ccond.getLeft();
if ((column.getColumn() != null) &&
requiredTables.contains(column.getTable()) &&
constantOrBound(ccond.getRight())) {
result.addCondition(column, condition);
}
}
}
else if (condition instanceof InListCondition) {
InListCondition incond = (InListCondition)condition;
if (incond.getOperand() instanceof ColumnExpression) {
ColumnExpression column = (ColumnExpression)incond.getOperand();
if ((column.getColumn() != null) &&
requiredTables.contains(column.getTable())) {
boolean allConstant = true;
for (ExpressionNode expr : incond.getExpressions()) {
if (!constantOrBound(expr)) {
allConstant = false;
break;
}
}
if (allConstant) {
result.addCondition(column, condition);
}
}
}
}
}
return result;
}
// Recognize the case of a join that is only used for predication.
// TODO: This is only covers the simplest case, namely an index that is unique
// none of whose columns are actually used.
public boolean semiJoinEquivalent(BaseScan scan) {
if (scan instanceof SingleIndexScan) {
SingleIndexScan indexScan = (SingleIndexScan)scan;
if (indexScan.isCovering() && isUnique(indexScan) &&
requiredColumns.isEmpty()) {
return true;
}
}
return false;
}
// Does this scan return at most one row?
protected boolean isUnique(SingleIndexScan indexScan) {
List<ExpressionNode> equalityComparands = indexScan.getEqualityComparands();
if (equalityComparands == null)
return false;
int nequals = equalityComparands.size();
Index index = indexScan.getIndex();
if (index.isUnique() && (nequals >= index.getKeyColumns().size()))
return true;
if (index.isGroupIndex())
return false;
Set<Column> equalityColumns = new HashSet<>(nequals);
for (int i = 0; i < nequals; i++) {
ExpressionNode equalityExpr = indexScan.getColumns().get(i);
if (equalityExpr instanceof ColumnExpression) {
equalityColumns.add(((ColumnExpression)equalityExpr).getColumn());
}
}
TableIndex tableIndex = (TableIndex)index;
find_index: // Find a unique index all of whose columns are equaled.
for (TableIndex otherIndex : tableIndex.getTable().getIndexes()) {
if (!otherIndex.isUnique()) continue;
for (IndexColumn otherColumn : otherIndex.getKeyColumns()) {
if (!equalityColumns.contains(otherColumn.getColumn()))
continue find_index;
}
return true;
}
return false;
}
public TableGroupJoinTree install(BaseScan scan,
List<ConditionList> conditionSources,
boolean sortAllowed, boolean copy) {
TableGroupJoinTree result = tables;
// Need to have more than one copy of this tree in the final result.
if (copy) result = new TableGroupJoinTree(result.getRoot());
result.setScan(scan);
this.sortAllowed = sortAllowed;
if (scan instanceof IndexScan) {
IndexScan indexScan = (IndexScan)scan;
if (indexScan instanceof MultiIndexIntersectScan) {
MultiIndexIntersectScan multiScan = (MultiIndexIntersectScan)indexScan;
installOrdering(indexScan, multiScan.getOrdering(), multiScan.getPeggedCount(), multiScan.getComparisonFields());
}
installConditions(indexScan.getConditions(), conditionSources);
if (sortAllowed)
queryGoal.installOrderEffectiveness(indexScan.getOrderEffectiveness());
}
else {
if (scan instanceof GroupLoopScan) {
installConditions(((GroupLoopScan)scan).getJoinConditions(),
conditionSources);
}
else if (scan instanceof FullTextScan) {
FullTextScan textScan = (FullTextScan)scan;
installConditions(textScan.getConditions(), conditionSources);
if (conditions.isEmpty()) {
textScan.setLimit((int)queryGoal.getLimit());
}
}
else if (scan instanceof ExpressionsHKeyScan) {
installConditions(((ExpressionsHKeyScan)scan).getConditions(),
conditionSources);
}
if (sortAllowed)
queryGoal.installOrderEffectiveness(IndexScan.OrderEffectiveness.NONE);
}
return result;
}
/** Change WHERE as a consequence of <code>index</code> being
* used, using either the sources returned by {@link updateContext} or the
* current ones if nothing has been changed.
*/
public void installConditions(Collection<? extends ConditionExpression> conditions,
List<ConditionList> conditionSources) {
if (conditions != null) {
if (conditionSources == null)
conditionSources = this.conditionSources;
for (ConditionExpression condition : conditions) {
for (ConditionList conditionSource : conditionSources) {
if (conditionSource.remove(condition))
break;
}
}
}
}
@Override
public String toString() {
StringBuilder str = new StringBuilder();
str.append(tables.summaryString());
str.append("\n");
str.append(conditions);
str.append("\n[");
boolean first = true;
for (ColumnSource bound : boundTables) {
if (first)
first = false;
else
str.append(", ");
str.append(bound.getName());
}
str.append("]");
return str.toString();
}
// Too-many-way UNION can consume too many resources (and overflow
// the stack explaining).
protected static int COLUMN_RANGE_MAX_SEGMENTS_DEFAULT = 16;
// Get Range-expressible conditions for given column.
protected ColumnRanges rangeForIndex(ExpressionNode expressionNode) {
if (expressionNode instanceof ColumnExpression) {
if (columnsToRanges == null) {
columnsToRanges = new HashMap<>();
for (ConditionExpression condition : conditions) {
ColumnRanges range = ColumnRanges.rangeAtNode(condition);
if (range != null) {
ColumnExpression rangeColumn = range.getColumnExpression();
ColumnRanges oldRange = columnsToRanges.get(rangeColumn);
if (oldRange != null)
range = ColumnRanges.andRanges(range, oldRange);
columnsToRanges.put(rangeColumn, range);
}
}
if (!columnsToRanges.isEmpty()) {
int maxSegments;
String prop = queryGoal.getRulesContext().getProperty("columnRangeMaxSegments");
if (prop != null)
maxSegments = Integer.parseInt(prop);
else
maxSegments = COLUMN_RANGE_MAX_SEGMENTS_DEFAULT;
Iterator<ColumnRanges> iter = columnsToRanges.values().iterator();
while (iter.hasNext()) {
if (iter.next().getSegments().size() > maxSegments) {
iter.remove();
}
}
}
}
ColumnExpression columnExpression = (ColumnExpression)expressionNode;
return columnsToRanges.get(columnExpression);
}
return null;
}
static class RequiredColumns {
private Map<TableSource,Set<ColumnExpression>> map;
public RequiredColumns(TableGroupJoinTree tables) {
map = new HashMap<>();
for (TableGroupJoinNode table : tables) {
map.put(table.getTable(), new HashSet<ColumnExpression>());
}
}
public RequiredColumns(RequiredColumns other) {
map = new HashMap<>(other.map.size());
for (Map.Entry<TableSource,Set<ColumnExpression>> entry : other.map.entrySet()) {
map.put(entry.getKey(), new HashSet<>(entry.getValue()));
}
}
public Set<TableSource> getTables() {
return map.keySet();
}
public boolean hasColumns(TableSource table) {
Set<ColumnExpression> entry = map.get(table);
if (entry == null) return false;
return !entry.isEmpty();
}
public boolean isEmpty() {
boolean empty = true;
for (Set<ColumnExpression> entry : map.values())
if (!entry.isEmpty())
return false;
return empty;
}
public void require(ColumnExpression expr) {
Set<ColumnExpression> entry = map.get(expr.getTable());
if (entry != null)
entry.add(expr);
}
/** Opposite of {@link require}: note that we have a source for this column. */
public boolean have(ColumnExpression expr) {
Set<ColumnExpression> entry = map.get(expr.getTable());
if (entry != null)
return entry.remove(expr);
else
return false;
}
public void clear() {
for (Set<ColumnExpression> entry : map.values())
entry.clear();
}
}
static class RequiredColumnsFiller implements PlanVisitor, ExpressionVisitor {
private RequiredColumns requiredColumns;
private Map<PlanNode,Void> excludedPlanNodes, includedPlanNodes;
private Map<ExpressionNode,Void> excludedExpressions;
private Deque<Boolean> excludeNodeStack = new ArrayDeque<>();
private boolean excludeNode = false;
private int excludeDepth = 0;
private int subqueryDepth = 0;
public RequiredColumnsFiller(RequiredColumns requiredColumns) {
this.requiredColumns = requiredColumns;
}
public RequiredColumnsFiller(RequiredColumns requiredColumns,
Collection<PlanNode> excludedPlanNodes,
Collection<ConditionExpression> excludedExpressions) {
this.requiredColumns = requiredColumns;
this.excludedPlanNodes = new IdentityHashMap<>();
for (PlanNode planNode : excludedPlanNodes)
this.excludedPlanNodes.put(planNode, null);
this.excludedExpressions = new IdentityHashMap<>();
for (ConditionExpression condition : excludedExpressions)
this.excludedExpressions.put(condition, null);
}
public void setIncludedPlanNodes(Collection<PlanNode> includedPlanNodes) {
this.includedPlanNodes = new IdentityHashMap<>();
for (PlanNode planNode : includedPlanNodes)
this.includedPlanNodes.put(planNode, null);
}
@Override
public boolean visitEnter(PlanNode n) {
// Input nodes are called within the context of their output.
// We want to know whether just this node is excluded, not
// it and all its inputs.
excludeNodeStack.push(excludeNode);
excludeNode = exclude(n);
if ((n instanceof Subquery) &&
!((Subquery)n).getOuterTables().isEmpty())
// TODO: Might be accessing tables from outer query as
// group joins, which we don't support currently. Make
// sure those aren't excluded.
subqueryDepth++;
return visit(n);
}
@Override
public boolean visitLeave(PlanNode n) {
excludeNode = excludeNodeStack.pop();
if ((n instanceof Subquery) &&
!((Subquery)n).getOuterTables().isEmpty())
subqueryDepth--;
return true;
}
@Override
public boolean visit(PlanNode n) {
return true;
}
@Override
public boolean visitEnter(ExpressionNode n) {
if (!excludeNode && exclude(n))
excludeDepth++;
return visit(n);
}
@Override
public boolean visitLeave(ExpressionNode n) {
if (!excludeNode && exclude(n))
excludeDepth--;
return true;
}
@Override
public boolean visit(ExpressionNode n) {
if (!excludeNode && (excludeDepth == 0)) {
if (n instanceof ColumnExpression)
requiredColumns.require((ColumnExpression)n);
}
return true;
}
// Should this plan node be excluded from the requirement?
protected boolean exclude(PlanNode node) {
if (includedPlanNodes != null)
return !includedPlanNodes.containsKey(node);
else if (excludedPlanNodes != null)
return excludedPlanNodes.containsKey(node);
else
return false;
}
// Should this expression be excluded from requirement?
protected boolean exclude(ExpressionNode expr) {
return (((excludedExpressions != null) &&
excludedExpressions.containsKey(expr)) ||
// Group join conditions are handled specially.
((expr instanceof ConditionExpression) &&
(((ConditionExpression)expr).getImplementation() ==
ConditionExpression.Implementation.GROUP_JOIN) &&
// Include expressions in subqueries until do joins across them.
(subqueryDepth == 0)));
}
}
/* Spatial indexes */
/** For now, a spatial index is a special kind of table index on
* Z-order of two coordinates.
*/
public boolean spatialUsable(SingleIndexScan index, int nequals) {
// There are two cases to recognize:
// ORDER BY znear(column_lat, column_lon, start_lat, start_lon), which
// means fan out from that center in Z-order.
// WHERE distance_lat_lon(column_lat, column_lon, start_lat, start_lon) <= radius
ExpressionNode nextColumn = index.getColumns().get(nequals);
if (!(nextColumn instanceof SpecialIndexExpression))
return false; // Did not have enough equalities to get to spatial part.
SpecialIndexExpression indexExpression = (SpecialIndexExpression)nextColumn;
assert (indexExpression.getFunction() == SpecialIndexExpression.Function.Z_ORDER_LAT_LON);
List<ExpressionNode> operands = indexExpression.getOperands();
boolean matched = false;
for (ConditionExpression condition : conditions) {
if (condition instanceof ComparisonCondition) {
ComparisonCondition ccond = (ComparisonCondition)condition;
ExpressionNode centerRadius = null;
switch (ccond.getOperation()) {
case LE:
case LT:
centerRadius = matchDistanceLatLon(operands,
ccond.getLeft(),
ccond.getRight());
break;
case GE:
case GT:
centerRadius = matchDistanceLatLon(operands,
ccond.getRight(),
ccond.getLeft());
break;
}
if (centerRadius != null) {
index.setLowComparand(centerRadius, true);
index.setOrderEffectiveness(IndexScan.OrderEffectiveness.NONE);
matched = true;
break;
}
}
}
if (!matched) {
if (sortAllowed && (queryGoal.getOrdering() != null)) {
List<OrderByExpression> orderBy = queryGoal.getOrdering().getOrderBy();
if (orderBy.size() == 1) {
ExpressionNode center = matchZnear(operands,
orderBy.get(0));
if (center != null) {
index.setLowComparand(center, true);
index.setOrderEffectiveness(IndexScan.OrderEffectiveness.SORTED);
matched = true;
}
}
}
if (!matched)
return false;
}
index.setCovering(determineCovering(index));
index.setCostEstimate(estimateCostSpatial(index));
return true;
}
private ExpressionNode matchDistanceLatLon(List<ExpressionNode> indexExpressions,
ExpressionNode left, ExpressionNode right) {
if (!((left instanceof FunctionExpression) &&
((FunctionExpression)left).getFunction().equalsIgnoreCase("distance_lat_lon") &&
constantOrBound(right)))
return null;
ExpressionNode col1 = indexExpressions.get(0);
ExpressionNode col2 = indexExpressions.get(1);
List<ExpressionNode> operands = ((FunctionExpression)left).getOperands();
if (operands.size() != 4) return null; // TODO: Would error here be better?
ExpressionNode op1 = operands.get(0);
ExpressionNode op2 = operands.get(1);
ExpressionNode op3 = operands.get(2);
ExpressionNode op4 = operands.get(3);
if ((right.getType() != null) &&
(right.getType().typeClass().jdbcType() != Types.DECIMAL)) {
DataTypeDescriptor sqlType =
new DataTypeDescriptor(TypeId.DECIMAL_ID, 10, 6, true, 12);
TInstance type = queryGoal.getRulesContext()
.getTypesTranslator().typeForSQLType(sqlType);
right = new CastExpression(right, sqlType, right.getSQLsource(), type);
}
if (columnMatches(col1, op1) && columnMatches(col2, op2) &&
constantOrBound(op3) && constantOrBound(op4)) {
return new FunctionExpression("_center_radius",
Arrays.asList(op3, op4, right),
null, null, null);
}
if (columnMatches(col1, op3) && columnMatches(col2, op4) &&
constantOrBound(op1) && constantOrBound(op2)) {
return new FunctionExpression("_center_radius",
Arrays.asList(op1, op2, right),
null, null, null);
}
return null;
}
private ExpressionNode matchZnear(List<ExpressionNode> indexExpressions,
OrderByExpression orderBy) {
if (!orderBy.isAscending()) return null;
ExpressionNode orderExpr = orderBy.getExpression();
if (!((orderExpr instanceof FunctionExpression) &&
((FunctionExpression)orderExpr).getFunction().equalsIgnoreCase("znear")))
return null;
ExpressionNode col1 = indexExpressions.get(0);
ExpressionNode col2 = indexExpressions.get(1);
List<ExpressionNode> operands = ((FunctionExpression)orderExpr).getOperands();
if (operands.size() != 4) return null; // TODO: Would error here be better?
ExpressionNode op1 = operands.get(0);
ExpressionNode op2 = operands.get(1);
ExpressionNode op3 = operands.get(2);
ExpressionNode op4 = operands.get(3);
if (columnMatches(col1, op1) && columnMatches(col2, op2) &&
constantOrBound(op3) && constantOrBound(op4))
return new FunctionExpression("_center",
Arrays.asList(op3, op4),
null, null, null);
if (columnMatches(col1, op3) && columnMatches(col2, op4) &&
constantOrBound(op1) && constantOrBound(op2))
return new FunctionExpression("_center",
Arrays.asList(op1, op2),
null, null, null);
return null;
}
private static boolean columnMatches(ExpressionNode col, ExpressionNode op) {
if (op instanceof CastExpression)
op = ((CastExpression)op).getOperand();
return col.equals(op);
}
public CostEstimate estimateCostSpatial(SingleIndexScan index) {
PlanCostEstimator estimator = newEstimator();
Set<TableSource> requiredTables = requiredColumns.getTables();
estimator.spatialIndex(index);
if (!index.isCovering()) {
estimator.flatten(tables, index.getLeafMostTable(), requiredTables);
}
Collection<ConditionExpression> unhandledConditions = new HashSet<>(conditions);
if (index.getConditions() != null)
unhandledConditions.removeAll(index.getConditions());
if (!unhandledConditions.isEmpty()) {
estimator.select(unhandledConditions,
selectivityConditions(unhandledConditions, requiredTables));
}
if (queryGoal.needSort(index.getOrderEffectiveness())) {
estimator.sort(queryGoal.sortFields());
}
estimator.setLimit(queryGoal.getLimit());
return estimator.getCostEstimate();
}
protected FullTextScan pickFullText() {
List<ConditionExpression> textConditions = new ArrayList<>(0);
for (ConditionExpression condition : conditions) {
if ((condition instanceof FunctionExpression) &&
((FunctionExpression)condition).getFunction().equalsIgnoreCase("full_text_search")) {
textConditions.add(condition);
}
}
if (textConditions.isEmpty())
return null;
List<FullTextField> textFields = new ArrayList<>(0);
FullTextQuery query = null;
for (ConditionExpression condition : textConditions) {
List<ExpressionNode> operands = ((FunctionExpression)condition).getOperands();
FullTextQuery clause = null;
switch (operands.size()) {
case 1:
clause = fullTextBoolean(operands.get(0), textFields);
if (clause == null) continue;
break;
case 2:
if ((operands.get(0) instanceof ColumnExpression) &&
constantOrBound(operands.get(1))) {
ColumnExpression column = (ColumnExpression)operands.get(0);
if (column.getTable() instanceof TableSource) {
if (!tables.containsTable((TableSource)column.getTable()))
continue;
FullTextField field = new FullTextField(column,
FullTextField.Type.PARSE,
operands.get(1));
textFields.add(field);
clause = field;
}
}
break;
}
if (clause == null)
throw new UnsupportedSQLException("Unrecognized FULL_TEXT_SEARCH call",
condition.getSQLsource());
if (query == null) {
query = clause;
}
else {
query = fullTextBoolean(Arrays.asList(query, clause),
Arrays.asList(FullTextQueryBuilder.BooleanType.MUST,
FullTextQueryBuilder.BooleanType.MUST));
}
}
if (query == null)
return null;
FullTextIndex foundIndex = null;
TableSource foundTable = null;
find_index:
for (FullTextIndex index : textFields.get(0).getColumn().getColumn().getTable().getFullTextIndexes()) {
TableSource indexTable = null;
for (FullTextField textField : textFields) {
Column column = textField.getColumn().getColumn();
boolean found = false;
for (IndexColumn indexColumn : index.getKeyColumns()) {
if (indexColumn.getColumn() == column) {
if (foundIndex == null) {
textField.setIndexColumn(indexColumn);
}
found = true;
if ((indexTable == null) &&
(indexColumn.getColumn().getTable() == index.getIndexedTable())) {
indexTable = (TableSource)textField.getColumn().getTable();
}
break;
}
}
if (!found) {
continue find_index;
}
}
if (foundIndex == null) {
foundIndex = index;
foundTable = indexTable;
}
else {
throw new UnsupportedSQLException("Ambiguous full text index: " +
foundIndex + " and " + index);
}
}
if (foundIndex == null) {
StringBuilder str = new StringBuilder("No full text index for: ");
boolean first = true;
for (FullTextField textField : textFields) {
if (first)
first = false;
else
str.append(", ");
str.append(textField.getColumn());
}
throw new UnsupportedSQLException(str.toString());
}
if (foundTable == null) {
for (TableGroupJoinNode node : tables) {
if (node.getTable().getTable().getTable() == foundIndex.getIndexedTable()) {
foundTable = node.getTable();
break;
}
}
}
query = normalizeFullTextQuery(query);
FullTextScan scan = new FullTextScan(foundIndex, query,
foundTable, textConditions);
determineRequiredTables(scan);
scan.setCostEstimate(estimateCostFullText(scan));
return scan;
}
protected FullTextQuery fullTextBoolean(ExpressionNode condition,
List<FullTextField> textFields) {
if (condition instanceof ComparisonCondition) {
ComparisonCondition ccond = (ComparisonCondition)condition;
if ((ccond.getLeft() instanceof ColumnExpression) &&
constantOrBound(ccond.getRight())) {
ColumnExpression column = (ColumnExpression)ccond.getLeft();
if (column.getTable() instanceof TableSource) {
if (!tables.containsTable((TableSource)column.getTable()))
return null;
FullTextField field = new FullTextField(column,
FullTextField.Type.MATCH,
ccond.getRight());
textFields.add(field);
switch (ccond.getOperation()) {
case EQ:
return field;
case NE:
return fullTextBoolean(Arrays.<FullTextQuery>asList(field),
Arrays.asList(FullTextQueryBuilder.BooleanType.NOT));
}
}
}
}
else if (condition instanceof LogicalFunctionCondition) {
LogicalFunctionCondition lcond = (LogicalFunctionCondition)condition;
String op = lcond.getFunction();
if ("and".equals(op)) {
FullTextQuery left = fullTextBoolean(lcond.getLeft(), textFields);
FullTextQuery right = fullTextBoolean(lcond.getRight(), textFields);
if ((left == null) && (right == null)) return null;
if ((left != null) && (right != null))
return fullTextBoolean(Arrays.asList(left, right),
Arrays.asList(FullTextQueryBuilder.BooleanType.MUST,
FullTextQueryBuilder.BooleanType.MUST));
}
else if ("or".equals(op)) {
FullTextQuery left = fullTextBoolean(lcond.getLeft(), textFields);
FullTextQuery right = fullTextBoolean(lcond.getRight(), textFields);
if ((left == null) && (right == null)) return null;
if ((left != null) && (right != null))
return fullTextBoolean(Arrays.asList(left, right),
Arrays.asList(FullTextQueryBuilder.BooleanType.SHOULD,
FullTextQueryBuilder.BooleanType.SHOULD));
}
else if ("not".equals(op)) {
FullTextQuery inner = fullTextBoolean(lcond.getOperand(), textFields);
if (inner == null)
return null;
else
return fullTextBoolean(Arrays.asList(inner),
Arrays.asList(FullTextQueryBuilder.BooleanType.NOT));
}
}
// TODO: LIKE
throw new UnsupportedSQLException("Cannot convert to full text query" +
condition);
}
protected FullTextQuery fullTextBoolean(List<FullTextQuery> operands,
List<FullTextQueryBuilder.BooleanType> types) {
// Make modifiable copies for normalize.
return new FullTextBoolean(new ArrayList<>(operands),
new ArrayList<>(types));
}
protected FullTextQuery normalizeFullTextQuery(FullTextQuery query) {
if (query instanceof FullTextBoolean) {
FullTextBoolean bquery = (FullTextBoolean)query;
List<FullTextQuery> operands = bquery.getOperands();
List<FullTextQueryBuilder.BooleanType> types = bquery.getTypes();
int i = 0;
while (i < operands.size()) {
FullTextQuery opQuery = operands.get(i);
opQuery = normalizeFullTextQuery(opQuery);
if (opQuery instanceof FullTextBoolean) {
FullTextBoolean opbquery = (FullTextBoolean)opQuery;
List<FullTextQuery> opOperands = opbquery.getOperands();
List<FullTextQueryBuilder.BooleanType> opTypes = opbquery.getTypes();
// Fold in the simplest cases:
// [MUST(x), [MUST(y), MUST(z)]] -> [MUST(x), MUST(y), MUST(z)]
// [MUST(x), [NOT(y)]] -> [MUST(x), NOT(y)]
// [SHOULD(x), [SHOULD(y), SHOULD(z)]] -> [SHOULD(x), SHOULD(y), SHOULD(z)]
boolean fold = true;
switch (types.get(i)) {
case MUST:
check_must:
for (FullTextQueryBuilder.BooleanType opType : opTypes) {
switch (opType) {
case MUST:
case NOT:
break;
default:
fold = false;
break check_must;
}
}
break;
case SHOULD:
check_should:
for (FullTextQueryBuilder.BooleanType opType : opTypes) {
switch (opType) {
case SHOULD:
break;
default:
fold = false;
break check_should;
}
}
break;
default:
fold = false;
break;
}
if (fold) {
for (int j = 0; j < opOperands.size(); j++) {
FullTextQuery opOperand = opOperands.get(j);
FullTextQueryBuilder.BooleanType opType = opTypes.get(j);
if (j == 0) {
operands.set(i, opOperand);
types.set(i, opType);
}
else {
operands.add(i, opOperand);
types.add(i, opType);
}
i++;
}
continue;
}
}
operands.set(i, opQuery);
i++;
}
}
return query;
}
protected void determineRequiredTables(FullTextScan scan) {
// Include the non-condition requirements.
RequiredColumns requiredAfter = new RequiredColumns(requiredColumns);
RequiredColumnsFiller filler = new RequiredColumnsFiller(requiredAfter);
// Add in any non-full-text conditions.
for (ConditionExpression condition : conditions) {
boolean found = false;
for (ConditionExpression scanCondition : scan.getConditions()) {
if (scanCondition == condition) {
found = true;
break;
}
}
if (!found)
condition.accept(filler);
}
// Does not sort.
if (queryGoal.getOrdering() != null) {
// Only this node, not its inputs.
filler.setIncludedPlanNodes(Collections.<PlanNode>singletonList(queryGoal.getOrdering()));
queryGoal.getOrdering().accept(filler);
}
Set<TableSource> required = new HashSet<>(requiredAfter.getTables());
scan.setRequiredTables(required);
}
public CostEstimate estimateCostFullText(FullTextScan scan) {
PlanCostEstimator estimator = newEstimator();
estimator.fullTextScan(scan);
return estimator.getCostEstimate();
}
protected PlanCostEstimator newEstimator() {
return new PlanCostEstimator(queryGoal.getCostEstimator());
}
}
| src/main/java/com/foundationdb/sql/optimizer/rule/join_enum/GroupIndexGoal.java | /**
* Copyright (C) 2009-2013 FoundationDB, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.foundationdb.sql.optimizer.rule.join_enum;
import com.foundationdb.sql.optimizer.rule.EquivalenceFinder;
import com.foundationdb.sql.optimizer.rule.PlanContext;
import com.foundationdb.sql.optimizer.rule.SchemaRulesContext;
import com.foundationdb.sql.optimizer.rule.cost.CostEstimator.SelectivityConditions;
import com.foundationdb.sql.optimizer.rule.cost.PlanCostEstimator;
import com.foundationdb.sql.optimizer.rule.join_enum.DPhyp.JoinOperator;
import com.foundationdb.sql.optimizer.rule.range.ColumnRanges;
import com.foundationdb.sql.optimizer.plan.*;
import com.foundationdb.sql.optimizer.plan.Sort.OrderByExpression;
import com.foundationdb.sql.optimizer.plan.TableGroupJoinTree.TableGroupJoinNode;
import com.foundationdb.ais.model.*;
import com.foundationdb.ais.model.Index.JoinType;
import com.foundationdb.server.error.UnsupportedSQLException;
import com.foundationdb.server.geophile.Space;
import com.foundationdb.server.service.text.FullTextQueryBuilder;
import com.foundationdb.server.types.TInstance;
import com.foundationdb.server.types.texpressions.Comparison;
import com.foundationdb.sql.types.DataTypeDescriptor;
import com.foundationdb.sql.types.TypeId;
import com.google.common.base.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Types;
import java.util.*;
/** The goal of a indexes within a group. */
public class GroupIndexGoal implements Comparator<BaseScan>
{
private static final Logger logger = LoggerFactory.getLogger(GroupIndexGoal.class);
static volatile Function<? super IndexScan,Void> intersectionEnumerationHook = null;
// The overall goal.
private QueryIndexGoal queryGoal;
// The grouped tables.
private TableGroupJoinTree tables;
// All the conditions that might be indexable.
private List<ConditionExpression> conditions;
// Where they came from.
private List<ConditionList> conditionSources;
// All the columns besides those in conditions that will be needed.
private RequiredColumns requiredColumns;
// Tables already bound outside.
private Set<ColumnSource> boundTables;
// Can an index be used to take care of sorting.
// TODO: Make this a subset of queryGoal's sorting, based on what
// tables are in what join, rather than an all or nothing.
private boolean sortAllowed;
// Mapping of Range-expressible conditions, by their column. lazy loaded.
private Map<ColumnExpression,ColumnRanges> columnsToRanges;
private PlanContext queryContext;
public GroupIndexGoal(QueryIndexGoal queryGoal, TableGroupJoinTree tables, PlanContext queryContext) {
this.queryGoal = queryGoal;
this.tables = tables;
this.queryContext = queryContext;
if (queryGoal.getWhereConditions() != null) {
conditionSources = Collections.singletonList(queryGoal.getWhereConditions());
conditions = queryGoal.getWhereConditions();
}
else {
conditionSources = Collections.emptyList();
conditions = Collections.emptyList();
}
requiredColumns = new RequiredColumns(tables);
boundTables = queryGoal.getQuery().getOuterTables();
sortAllowed = true;
}
public QueryIndexGoal getQueryGoal() {
return queryGoal;
}
public TableGroupJoinTree getTables() {
return tables;
}
/**
* @param boundTables Tables already bound by the outside
* @param queryJoins Joins that come from the query, or part of the query, that an index is being searched for.
* Will generally, but not in the case of a sub-query, match <code>joins</code>.
* @param joins Joins that apply to this part of the query.
* @param outsideJoins All joins for this query.
* @param sortAllowed <code>true</code> if sorting is allowed
*
* @return Full list of all usable condition sources.
*/
public List<ConditionList> updateContext(Set<ColumnSource> boundTables,
Collection<JoinOperator> queryJoins,
Collection<JoinOperator> joins,
Collection<JoinOperator> outsideJoins,
boolean sortAllowed,
ConditionList extraConditions) {
setBoundTables(boundTables);
this.sortAllowed = sortAllowed;
setJoinConditions(queryJoins, joins, extraConditions);
updateRequiredColumns(joins, outsideJoins);
return conditionSources;
}
public void setBoundTables(Set<ColumnSource> boundTables) {
this.boundTables = boundTables;
}
private static boolean hasOuterJoin(Collection<JoinOperator> joins) {
for (JoinOperator joinOp : joins) {
switch (joinOp.getJoinType()) {
case LEFT:
case RIGHT:
case FULL_OUTER:
return true;
}
}
return false;
}
public void setJoinConditions(Collection<JoinOperator> queryJoins, Collection<JoinOperator> joins, ConditionList extraConditions) {
conditionSources = new ArrayList<>();
if ((queryGoal.getWhereConditions() != null) && !hasOuterJoin(queryJoins)) {
conditionSources.add(queryGoal.getWhereConditions());
}
for (JoinOperator join : joins) {
ConditionList joinConditions = join.getJoinConditions();
if (joinConditions != null)
conditionSources.add(joinConditions);
}
if (extraConditions != null) {
conditionSources.add(extraConditions);
}
switch (conditionSources.size()) {
case 0:
conditions = Collections.emptyList();
break;
case 1:
conditions = conditionSources.get(0);
break;
default:
conditions = new ArrayList<>();
for (ConditionList conditionSource : conditionSources) {
conditions.addAll(conditionSource);
}
}
columnsToRanges = null;
}
public void updateRequiredColumns(Collection<JoinOperator> joins,
Collection<JoinOperator> outsideJoins) {
requiredColumns.clear();
Collection<PlanNode> orderings = (queryGoal.getOrdering() == null) ?
Collections.<PlanNode>emptyList() :
Collections.<PlanNode>singletonList(queryGoal.getOrdering());
RequiredColumnsFiller filler = new RequiredColumnsFiller(requiredColumns,
orderings, conditions);
queryGoal.getQuery().accept(filler);
for (JoinOperator join : outsideJoins) {
if (joins.contains(join)) continue;
ConditionList joinConditions = join.getJoinConditions();
if (joinConditions != null) {
for (ConditionExpression condition : joinConditions) {
condition.accept(filler);
}
}
}
}
/** Given a semi-join to a VALUES, see whether it can be turned
* into a predicate on some column in this group, in which case it
* can possibly be indexed.
*/
public InListCondition semiJoinToInList(ExpressionsSource values,
Collection<JoinOperator> joins) {
if (values.nFields() != 1)
return null;
ComparisonCondition ccond = null;
boolean found = false;
ConditionExpression joinCondition = onlyJoinCondition(joins);
if (joinCondition instanceof ComparisonCondition) {
ccond = (ComparisonCondition)joinCondition;
if ((ccond.getOperation() == Comparison.EQ) &&
(ccond.getRight() instanceof ColumnExpression)) {
ColumnExpression rcol = (ColumnExpression)ccond.getRight();
if ((rcol.getTable() == values) &&
(rcol.getPosition() == 0) &&
(ccond.getLeft() instanceof ColumnExpression)) {
ColumnExpression lcol = (ColumnExpression)ccond.getLeft();
for (TableGroupJoinNode table : tables) {
if (table.getTable() == lcol.getTable()) {
found = true;
break;
}
}
}
}
}
if (!found) return null;
return semiJoinToInList(values, ccond, queryGoal.getRulesContext());
}
protected static ConditionExpression onlyJoinCondition(Collection<JoinOperator> joins) {
ConditionExpression result = null;
for (JoinOperator join : joins) {
if (join.getJoinConditions() != null) {
for (ConditionExpression cond : join.getJoinConditions()) {
if (result == null)
result = cond;
else
return null;
}
}
}
return result;
}
public static InListCondition semiJoinToInList(ExpressionsSource values,
ComparisonCondition ccond,
SchemaRulesContext rulesContext) {
List<ExpressionNode> expressions = new ArrayList<>(values.getExpressions().size());
for (List<ExpressionNode> row : values.getExpressions()) {
expressions.add(row.get(0));
}
DataTypeDescriptor sqlType = new DataTypeDescriptor(TypeId.BOOLEAN_ID, true);
TInstance type = rulesContext.getTypesTranslator().typeForSQLType(sqlType);
InListCondition cond = new InListCondition(ccond.getLeft(), expressions,
sqlType, null, type);
cond.setComparison(ccond);
//cond.setPreptimeValue(new TPreptimeValue(AkBool.INSTANCE.instance(true)));
return cond;
}
/** Populate given index usage according to goal.
* @return <code>false</code> if the index is useless.
*/
public boolean usable(SingleIndexScan index) {
setColumnsAndOrdering(index);
int nequals = insertLeadingEqualities(index, conditions);
if (index.getIndex().isSpatial()) return spatialUsable(index, nequals);
List<ExpressionNode> indexExpressions = index.getColumns();
if (nequals < indexExpressions.size()) {
ExpressionNode indexExpression = indexExpressions.get(nequals);
if (indexExpression != null) {
boolean foundInequalityCondition = false;
for (ConditionExpression condition : conditions) {
if (condition instanceof ComparisonCondition) {
ComparisonCondition ccond = (ComparisonCondition)condition;
if (ccond.getOperation() == Comparison.NE)
continue; // ranges are better suited for !=
ExpressionNode otherComparand = matchingComparand(indexExpression, ccond);
if (otherComparand != null) {
Comparison op = ccond.getOperation();
if (otherComparand == ccond.getLeft())
op = ComparisonCondition.reverseComparison(op);
index.addInequalityCondition(condition, op, otherComparand);
foundInequalityCondition = true;
}
}
}
if (!foundInequalityCondition) {
ColumnRanges range = rangeForIndex(indexExpression);
if (range != null)
index.addRangeCondition(range);
}
}
}
index.setOrderEffectiveness(determineOrderEffectiveness(index));
index.setCovering(determineCovering(index));
if ((index.getOrderEffectiveness() == IndexScan.OrderEffectiveness.NONE) &&
!index.hasConditions() &&
!index.isCovering())
return false;
index.setCostEstimate(estimateCost(index));
return true;
}
private int insertLeadingEqualities(EqualityColumnsScan index, List<ConditionExpression> localConds) {
int nequals = 0;
List<ExpressionNode> indexExpressions = index.getColumns();
int ncols = indexExpressions.size();
while (nequals < ncols) {
ExpressionNode indexExpression = indexExpressions.get(nequals);
if (indexExpression == null) break;
ConditionExpression equalityCondition = null;
ExpressionNode otherComparand = null;
for (ConditionExpression condition : localConds) {
if (condition instanceof ComparisonCondition) {
ComparisonCondition ccond = (ComparisonCondition)condition;
if (ccond.getOperation() != Comparison.EQ)
continue; // only doing equalities
ExpressionNode comparand = matchingComparand(indexExpression, ccond);
if (comparand != null) {
equalityCondition = condition;
otherComparand = comparand;
break;
}
}
else if (condition instanceof FunctionCondition) {
FunctionCondition fcond = (FunctionCondition)condition;
if (fcond.getFunction().equals("isNull") &&
(fcond.getOperands().size() == 1) &&
indexExpressionMatches(indexExpression,
fcond.getOperands().get(0))) {
ExpressionNode foperand = fcond.getOperands().get(0);
equalityCondition = condition;
otherComparand = new IsNullIndexKey(foperand.getSQLtype(),
fcond.getSQLsource(),
foperand.getType());
break;
}
}
}
if (equalityCondition == null)
break;
index.addEqualityCondition(equalityCondition, otherComparand);
nequals++;
}
return nequals;
}
private ExpressionNode matchingComparand(ExpressionNode indexExpression,
ComparisonCondition ccond) {
ExpressionNode comparand;
if (indexExpressionMatches(indexExpression, ccond.getLeft())) {
comparand = ccond.getRight();
if (constantOrBound(comparand))
return comparand;
}
if (indexExpressionMatches(indexExpression, ccond.getRight())) {
comparand = ccond.getLeft();
if (constantOrBound(comparand))
return comparand;
}
return null;
}
private static void setColumnsAndOrdering(SingleIndexScan index) {
List<IndexColumn> indexColumns = index.getAllColumns();
int ncols = indexColumns.size();
int firstSpatialColumn, dimensions;
SpecialIndexExpression.Function spatialFunction;
if (index.getIndex().isSpatial()) {
Index spatialIndex = index.getIndex();
firstSpatialColumn = spatialIndex.firstSpatialArgument();
dimensions = spatialIndex.dimensions();
assert (dimensions == Space.LAT_LON_DIMENSIONS);
spatialFunction = SpecialIndexExpression.Function.Z_ORDER_LAT_LON;
}
else {
firstSpatialColumn = Integer.MAX_VALUE;
dimensions = 0;
spatialFunction = null;
}
List<OrderByExpression> orderBy = new ArrayList<>(ncols);
List<ExpressionNode> indexExpressions = new ArrayList<>(ncols);
int i = 0;
while (i < ncols) {
ExpressionNode indexExpression;
boolean ascending;
if (i == firstSpatialColumn) {
List<ExpressionNode> operands = new ArrayList<>(dimensions);
for (int j = 0; j < dimensions; j++) {
operands.add(getIndexExpression(index, indexColumns.get(i++)));
}
indexExpression = new SpecialIndexExpression(spatialFunction, operands);
ascending = true;
}
else {
IndexColumn indexColumn = indexColumns.get(i++);
indexExpression = getIndexExpression(index, indexColumn);
ascending = indexColumn.isAscending();
}
indexExpressions.add(indexExpression);
orderBy.add(new OrderByExpression(indexExpression, ascending));
}
index.setColumns(indexExpressions);
index.setOrdering(orderBy);
}
// Take ordering from output index and adjust ordering of others to match.
private static void installOrdering(IndexScan index,
List<OrderByExpression> outputOrdering,
int outputPeggedCount, int comparisonFields) {
if (index instanceof SingleIndexScan) {
List<OrderByExpression> indexOrdering = index.getOrdering();
if ((indexOrdering != null) && (indexOrdering != outputOrdering)) {
// Order comparison fields the same way as output.
// Try to avoid mixed mode: initial columns ordered
// like first comparison, trailing columns ordered
// like last comparison.
int i = 0;
while (i < index.getPeggedCount()) {
indexOrdering.get(i++).setAscending(outputOrdering.get(outputPeggedCount).isAscending());
}
for (int j = 0; j < comparisonFields; j++) {
indexOrdering.get(i++).setAscending(outputOrdering.get(outputPeggedCount + j).isAscending());
}
while (i < indexOrdering.size()) {
indexOrdering.get(i++).setAscending(outputOrdering.get(outputPeggedCount + comparisonFields - 1).isAscending());
}
}
}
else if (index instanceof MultiIndexIntersectScan) {
MultiIndexIntersectScan multiIndex = (MultiIndexIntersectScan)index;
installOrdering(multiIndex.getOutputIndexScan(),
outputOrdering, outputPeggedCount, comparisonFields);
installOrdering(multiIndex.getSelectorIndexScan(),
outputOrdering, outputPeggedCount, comparisonFields);
}
}
// Determine how well this index does against the target.
// Also, correct traversal order to match sort if possible.
protected IndexScan.OrderEffectiveness
determineOrderEffectiveness(SingleIndexScan index) {
IndexScan.OrderEffectiveness result = IndexScan.OrderEffectiveness.NONE;
if (!sortAllowed) return result;
List<OrderByExpression> indexOrdering = index.getOrdering();
if (indexOrdering == null) return result;
BitSet reverse = new BitSet(indexOrdering.size());
int nequals = index.getNEquality();
List<ExpressionNode> equalityColumns = null;
if (nequals > 0) {
equalityColumns = index.getColumns().subList(0, nequals);
}
try_sorted:
if (queryGoal.getOrdering() != null) {
int idx = nequals;
for (OrderByExpression targetColumn : queryGoal.getOrdering().getOrderBy()) {
// Get the expression by which this is ordering, recognizing the
// special cases where the Sort is fed by GROUP BY or feeds DISTINCT.
ExpressionNode targetExpression = targetColumn.getExpression();
if (targetExpression.isColumn()) {
ColumnExpression column = (ColumnExpression)targetExpression;
ColumnSource table = column.getTable();
if (table == queryGoal.getGrouping()) {
targetExpression = queryGoal.getGrouping()
.getField(column.getPosition());
}
else if (table instanceof Project) {
// Cf. ASTStatementLoader.sortsForDistinct().
Project project = (Project)table;
if ((project.getOutput() == queryGoal.getOrdering()) &&
(queryGoal.getOrdering().getOutput() instanceof Distinct)) {
targetExpression = project.getFields()
.get(column.getPosition());
}
}
}
OrderByExpression indexColumn = null;
if (idx < indexOrdering.size()) {
indexColumn = indexOrdering.get(idx);
if (indexColumn.getExpression() == null)
indexColumn = null; // Index sorts by unknown column.
}
if ((indexColumn != null) &&
orderingExpressionMatches(indexColumn, targetExpression)) {
if (indexColumn.isAscending() != targetColumn.isAscending()) {
// To avoid mixed mode as much as possible,
// defer changing the index order until
// certain it will be effective.
reverse.set(idx, true);
if (idx == nequals)
// Likewise reverse the initial equals segment.
reverse.set(0, nequals, true);
}
if (idx >= index.getNKeyColumns())
index.setUsesAllColumns(true);
idx++;
continue;
}
if (equalityColumns != null) {
// Another possibility is that target ordering is
// in fact unchanged due to equality condition.
// TODO: Should this have been noticed earlier on
// so that it can be taken out of the sort?
if (equalityColumns.contains(targetExpression))
continue;
}
break try_sorted;
}
if ((idx > 0) && (idx < indexOrdering.size()) && reverse.get(idx-1))
// Reverse after ORDER BY if reversed last one.
reverse.set(idx, indexOrdering.size(), true);
for (int i = 0; i < reverse.size(); i++) {
if (reverse.get(i)) {
OrderByExpression indexColumn = indexOrdering.get(i);
indexColumn.setAscending(!indexColumn.isAscending());
}
}
result = IndexScan.OrderEffectiveness.SORTED;
}
if (queryGoal.getGrouping() != null) {
boolean anyFound = false, allFound = true;
List<ExpressionNode> groupBy = queryGoal.getGrouping().getGroupBy();
for (ExpressionNode targetExpression : groupBy) {
int found = -1;
for (int i = nequals; i < indexOrdering.size(); i++) {
if (orderingExpressionMatches(indexOrdering.get(i), targetExpression)) {
found = i - nequals;
break;
}
}
if (found < 0) {
allFound = false;
if ((equalityColumns == null) ||
!equalityColumns.contains(targetExpression))
continue;
}
else if (found >= groupBy.size()) {
// Ordered by this column, but after some other
// stuff which will break up the group. Only
// partially grouped.
allFound = false;
}
if (found >= index.getNKeyColumns()) {
index.setUsesAllColumns(true);
}
anyFound = true;
}
if (anyFound) {
if (!allFound)
return IndexScan.OrderEffectiveness.PARTIAL_GROUPED;
else if (result == IndexScan.OrderEffectiveness.SORTED)
return result;
else
return IndexScan.OrderEffectiveness.GROUPED;
}
}
else if (queryGoal.getProjectDistinct() != null) {
assert (queryGoal.getOrdering() == null);
if (orderedForDistinct(index, queryGoal.getProjectDistinct(),
indexOrdering, nequals)) {
return IndexScan.OrderEffectiveness.SORTED;
}
}
return result;
}
/** For use with a Distinct that gets added later. */
public boolean orderedForDistinct(Project projectDistinct, IndexScan index) {
List<OrderByExpression> indexOrdering = index.getOrdering();
if (indexOrdering == null) return false;
int nequals = index.getNEquality();
return orderedForDistinct(index, projectDistinct, indexOrdering, nequals);
}
protected boolean orderedForDistinct(IndexScan index, Project projectDistinct,
List<OrderByExpression> indexOrdering,
int nequals) {
List<ExpressionNode> distinct = projectDistinct.getFields();
for (ExpressionNode targetExpression : distinct) {
int found = -1;
for (int i = nequals; i < indexOrdering.size(); i++) {
if (orderingExpressionMatches(indexOrdering.get(i), targetExpression)) {
found = i - nequals;
break;
}
}
if ((found < 0) || (found >= distinct.size())) {
return false;
}
if (found >= index.getNKeyColumns()) {
index.setUsesAllColumns(true);
}
}
return true;
}
// Does the column expression coming from the index match the ORDER BY target,
// allowing for column equivalences?
protected boolean orderingExpressionMatches(OrderByExpression orderByExpression,
ExpressionNode targetExpression) {
ExpressionNode columnExpression = orderByExpression.getExpression();
if (columnExpression == null)
return false;
if (columnExpression.equals(targetExpression))
return true;
if (!(columnExpression instanceof ColumnExpression) ||
!(targetExpression instanceof ColumnExpression))
return false;
return getColumnEquivalencies().areEquivalent((ColumnExpression)columnExpression,
(ColumnExpression)targetExpression);
}
protected EquivalenceFinder<ColumnExpression> getColumnEquivalencies() {
return queryGoal.getQuery().getColumnEquivalencies();
}
protected class UnboundFinder implements ExpressionVisitor {
boolean found = false;
public UnboundFinder() {
}
@Override
public boolean visitEnter(ExpressionNode n) {
return visit(n);
}
@Override
public boolean visitLeave(ExpressionNode n) {
return !found;
}
@Override
public boolean visit(ExpressionNode n) {
if (n instanceof ColumnExpression) {
ColumnExpression columnExpression = (ColumnExpression)n;
if (!boundTables.contains(columnExpression.getTable())) {
found = true;
return false;
}
}
else if (n instanceof SubqueryExpression) {
for (ColumnSource used : ((SubqueryExpression)n).getSubquery().getOuterTables()) {
// Tables defined inside the subquery are okay, but ones from outside
// need to be bound to eval as an expression.
if (!boundTables.contains(used)) {
found = true;
return false;
}
}
}
return true;
}
}
/** Does the given expression have references to tables that aren't bound? */
protected boolean constantOrBound(ExpressionNode expression) {
UnboundFinder f = new UnboundFinder();
expression.accept(f);
return !f.found;
}
/** Get an expression form of the given index column. */
protected static ExpressionNode getIndexExpression(IndexScan index,
IndexColumn indexColumn) {
return getColumnExpression(index.getLeafMostTable(), indexColumn.getColumn());
}
/** Get an expression form of the given group column. */
protected static ExpressionNode getColumnExpression(TableSource leafMostTable,
Column column) {
Table indexTable = column.getTable();
for (TableSource table = leafMostTable;
null != table;
table = table.getParentTable()) {
if (table.getTable().getTable() == indexTable) {
return new ColumnExpression(table, column);
}
}
return null;
}
/** Is the comparison operand what the index indexes? */
protected boolean indexExpressionMatches(ExpressionNode indexExpression,
ExpressionNode comparisonOperand) {
if (indexExpression.equals(comparisonOperand))
return true;
if (!(indexExpression instanceof ColumnExpression) ||
!(comparisonOperand instanceof ColumnExpression))
return false;
if (getColumnEquivalencies().areEquivalent((ColumnExpression)indexExpression,
(ColumnExpression)comparisonOperand))
return true;
// See if comparing against a result column of the subquery,
// that is, a join to the subquery that we can push down.
ColumnExpression comparisonColumn = (ColumnExpression)comparisonOperand;
ColumnSource comparisonTable = comparisonColumn.getTable();
if (!(comparisonTable instanceof SubquerySource))
return false;
Subquery subquery = ((SubquerySource)comparisonTable).getSubquery();
if (subquery != queryGoal.getQuery())
return false;
PlanNode input = subquery.getQuery();
if (input instanceof ResultSet)
input = ((ResultSet)input).getInput();
if (!(input instanceof Project))
return false;
Project project = (Project)input;
ExpressionNode insideExpression = project.getFields().get(comparisonColumn.getPosition());
return indexExpressionMatches(indexExpression, insideExpression);
}
/** Find the best index among the branches. */
public BaseScan pickBestScan() {
logger.debug("Picking for {}", this);
BaseScan bestScan = null;
bestScan = pickFullText();
if (bestScan != null) {
return bestScan; // TODO: Always wins for now.
}
if (tables.getGroup().getRejectedJoins() != null) {
bestScan = pickBestGroupLoop();
}
IntersectionEnumerator intersections = new IntersectionEnumerator();
Set<TableSource> required = tables.getRequired();
for (TableGroupJoinNode table : tables) {
IndexScan tableIndex = pickBestIndex(table, required, intersections);
if ((tableIndex != null) &&
((bestScan == null) || (compare(tableIndex, bestScan) > 0)))
bestScan = tableIndex;
ExpressionsHKeyScan hKeyRow = pickHKeyRow(table, required);
if ((hKeyRow != null) &&
((bestScan == null) || (compare(hKeyRow, bestScan) > 0)))
bestScan = hKeyRow;
}
bestScan = pickBestIntersection(bestScan, intersections);
if (bestScan == null) {
GroupScan groupScan = new GroupScan(tables.getGroup());
groupScan.setCostEstimate(estimateCost(groupScan));
bestScan = groupScan;
}
return bestScan;
}
private BaseScan pickBestIntersection(BaseScan previousBest, IntersectionEnumerator enumerator) {
// filter out all leaves which are obviously bad
if (previousBest != null) {
CostEstimate previousBestCost = previousBest.getCostEstimate();
for (Iterator<SingleIndexScan> iter = enumerator.leavesIterator(); iter.hasNext(); ) {
SingleIndexScan scan = iter.next();
CostEstimate scanCost = estimateIntersectionCost(scan);
if (scanCost.compareTo(previousBestCost) > 0) {
logger.debug("Not intersecting {} {}", scan, scanCost);
iter.remove();
}
}
}
Function<? super IndexScan,Void> hook = intersectionEnumerationHook;
for (Iterator<IndexScan> iterator = enumerator.iterator(); iterator.hasNext(); ) {
IndexScan intersectedIndex = iterator.next();
if (hook != null)
hook.apply(intersectedIndex);
setIntersectionConditions(intersectedIndex);
intersectedIndex.setCovering(determineCovering(intersectedIndex));
intersectedIndex.setCostEstimate(estimateCost(intersectedIndex));
if (previousBest == null) {
logger.debug("Selecting {}", intersectedIndex);
previousBest = intersectedIndex;
}
else if (compare(intersectedIndex, previousBest) > 0) {
logger.debug("Preferring {}", intersectedIndex);
previousBest = intersectedIndex;
}
else {
logger.debug("Rejecting {}", intersectedIndex);
// If the scan costs alone are higher than the previous best cost, there's no way this scan or
// any scan that uses it will be the best. Just remove the whole branch.
if (intersectedIndex.getScanCostEstimate().compareTo(previousBest.getCostEstimate()) > 0)
iterator.remove();
}
}
return previousBest;
}
private void setIntersectionConditions(IndexScan rawScan) {
MultiIndexIntersectScan scan = (MultiIndexIntersectScan) rawScan;
if (isAncestor(scan.getOutputIndexScan().getLeafMostTable(),
scan.getSelectorIndexScan().getLeafMostTable())) {
// More conditions up the same branch are safely implied by the output row.
ConditionsCounter<ConditionExpression> counter = new ConditionsCounter<>(conditions.size());
scan.incrementConditionsCounter(counter);
scan.setConditions(new ArrayList<>(counter.getCountedConditions()));
}
else {
// Otherwise only those for the output row are safe and
// conditions on another branch need to be checked again;
scan.setConditions(scan.getOutputIndexScan().getConditions());
}
}
/** Is the given <code>rootTable</code> an ancestor of <code>leafTable</code>? */
private static boolean isAncestor(TableSource leafTable, TableSource rootTable) {
do {
if (leafTable == rootTable)
return true;
leafTable = leafTable.getParentTable();
} while (leafTable != null);
return false;
}
private class IntersectionEnumerator extends MultiIndexEnumerator<ConditionExpression,IndexScan,SingleIndexScan> {
@Override
protected Collection<ConditionExpression> getLeafConditions(SingleIndexScan scan) {
int skips = scan.getPeggedCount();
List<ConditionExpression> conditions = scan.getConditions();
if (conditions == null)
return null;
int nconds = conditions.size();
return ((skips) > 0 && (skips == nconds)) ? conditions : null;
}
@Override
protected IndexScan intersect(IndexScan first, IndexScan second, int comparisons) {
return new MultiIndexIntersectScan(first, second, comparisons);
}
@Override
protected List<Column> getComparisonColumns(IndexScan first, IndexScan second) {
EquivalenceFinder<ColumnExpression> equivs = getColumnEquivalencies();
List<ExpressionNode> firstOrdering = orderingCols(first);
List<ExpressionNode> secondOrdering = orderingCols(second);
int ncols = Math.min(firstOrdering.size(), secondOrdering.size());
List<Column> result = new ArrayList<>(ncols);
for (int i=0; i < ncols; ++i) {
ExpressionNode firstCol = firstOrdering.get(i);
ExpressionNode secondCol = secondOrdering.get(i);
if (!(firstCol instanceof ColumnExpression) || !(secondCol instanceof ColumnExpression))
break;
if (!equivs.areEquivalent((ColumnExpression) firstCol, (ColumnExpression) secondCol))
break;
result.add(((ColumnExpression)firstCol).getColumn());
}
return result;
}
private List<ExpressionNode> orderingCols(IndexScan index) {
List<ExpressionNode> result = index.getColumns();
return result.subList(index.getPeggedCount(), result.size());
}
}
/** Find the best index on the given table.
* @param required Tables reachable from root via INNER joins and hence not nullable.
*/
public IndexScan pickBestIndex(TableGroupJoinNode node, Set<TableSource> required, IntersectionEnumerator enumerator) {
TableSource table = node.getTable();
IndexScan bestIndex = null;
// Can only consider single table indexes when table is not
// nullable (required). If table is the optional part of a
// LEFT join, can still consider compatible LEFT / RIGHT group
// indexes, below. WHERE conditions are removed before this is
// called, see GroupIndexGoal#setJoinConditions().
if (required.contains(table)) {
for (TableIndex index : table.getTable().getTable().getIndexes()) {
SingleIndexScan candidate = new SingleIndexScan(index, table, queryContext);
bestIndex = betterIndex(bestIndex, candidate, enumerator);
}
}
if ((table.getGroup() != null) && !hasOuterJoinNonGroupConditions(node)) {
for (GroupIndex index : table.getGroup().getGroup().getIndexes()) {
// The leaf must be used or else we'll get duplicates from a
// scan (the indexed columns need not be root to leaf, making
// ancestors discontiguous and duplicates hard to eliminate).
if (index.leafMostTable() != table.getTable().getTable())
continue;
TableSource rootTable = table;
TableSource rootRequired = null, leafRequired = null;
if (index.getJoinType() == JoinType.LEFT) {
while (rootTable != null) {
if (required.contains(rootTable)) {
rootRequired = rootTable;
if (leafRequired == null)
leafRequired = rootTable;
}
else {
if (leafRequired != null) {
// Optional above required, not LEFT join compatible.
leafRequired = null;
break;
}
}
if (index.rootMostTable() == rootTable.getTable().getTable())
break;
rootTable = rootTable.getParentTable();
}
// The root must be present, since a LEFT index
// does not contain orphans.
if ((rootTable == null) ||
(rootRequired != rootTable) ||
(leafRequired == null))
continue;
}
else {
if (!required.contains(table))
continue;
leafRequired = table;
boolean optionalSeen = false;
while (rootTable != null) {
if (required.contains(rootTable)) {
if (optionalSeen) {
// Required above optional, not RIGHT join compatible.
rootRequired = null;
break;
}
rootRequired = rootTable;
}
else {
optionalSeen = true;
}
if (index.rootMostTable() == rootTable.getTable().getTable())
break;
rootTable = rootTable.getParentTable();
}
// TODO: There are no INNER JOIN group indexes,
// but this would support them.
/*
if (optionalSeen && (index.getJoinType() == JoinType.INNER))
continue;
*/
if ((rootTable == null) ||
(rootRequired == null))
continue;
}
SingleIndexScan candidate = new SingleIndexScan(index, rootTable,
rootRequired, leafRequired,
table, queryContext);
bestIndex = betterIndex(bestIndex, candidate, enumerator);
}
}
return bestIndex;
}
// If a LEFT join has more conditions, they won't be included in an index, so
// can't use it.
protected boolean hasOuterJoinNonGroupConditions(TableGroupJoinNode node) {
if (node.getTable().isRequired())
return false;
ConditionList conditions = node.getJoinConditions();
if (conditions != null) {
for (ConditionExpression cond : conditions) {
if (cond.getImplementation() != ConditionExpression.Implementation.GROUP_JOIN) {
return true;
}
}
}
return false;
}
protected IndexScan betterIndex(IndexScan bestIndex, SingleIndexScan candidate, IntersectionEnumerator enumerator) {
if (usable(candidate)) {
enumerator.addLeaf(candidate);
if (bestIndex == null) {
logger.debug("Selecting {}", candidate);
return candidate;
}
else if (compare(candidate, bestIndex) > 0) {
logger.debug("Preferring {}", candidate);
return candidate;
}
else {
logger.debug("Rejecting {}", candidate);
}
}
return bestIndex;
}
private GroupLoopScan pickBestGroupLoop() {
GroupLoopScan bestScan = null;
Set<TableSource> outsideSameGroup = new HashSet<>(tables.getGroup().getTables());
outsideSameGroup.retainAll(boundTables);
for (TableGroupJoin join : tables.getGroup().getRejectedJoins()) {
TableSource parent = join.getParent();
TableSource child = join.getChild();
TableSource inside, outside;
boolean insideIsParent;
if (outsideSameGroup.contains(parent) && tables.containsTable(child)) {
inside = child;
outside = parent;
insideIsParent = false;
}
else if (outsideSameGroup.contains(child) && tables.containsTable(parent)) {
inside = parent;
outside = child;
insideIsParent = true;
}
else {
continue;
}
if (mightFlattenOrSort(outside)) {
continue; // Lookup_Nested won't be allowed.
}
GroupLoopScan forJoin = new GroupLoopScan(inside, outside, insideIsParent,
join.getConditions());
determineRequiredTables(forJoin);
forJoin.setCostEstimate(estimateCost(forJoin));
if (bestScan == null) {
logger.debug("Selecting {}", forJoin);
bestScan = forJoin;
}
else if (compare(forJoin, bestScan) > 0) {
logger.debug("Preferring {}", forJoin);
bestScan = forJoin;
}
else {
logger.debug("Rejecting {}", forJoin);
}
}
return bestScan;
}
private boolean mightFlattenOrSort(TableSource table) {
if (!(table.getOutput() instanceof TableGroupJoinTree))
return true; // Don't know; be conservative.
TableGroupJoinTree tree = (TableGroupJoinTree)table.getOutput();
TableGroupJoinNode root = tree.getRoot();
if (root.getTable() != table)
return true;
if (root.getFirstChild() != null)
return true;
// Only table in this join tree, shouldn't flatten.
PlanNode output = tree;
do {
output = output.getOutput();
if (output instanceof Sort)
return true;
if (output instanceof ResultSet)
break;
} while (output != null);
return false; // No Sort, either.
}
private ExpressionsHKeyScan pickHKeyRow(TableGroupJoinNode node, Set<TableSource> required) {
TableSource table = node.getTable();
if (!required.contains(table)) return null;
ExpressionsHKeyScan scan = new ExpressionsHKeyScan(table);
HKey hKey = scan.getHKey();
int ncols = hKey.nColumns();
List<ExpressionNode> columns = new ArrayList<>(ncols);
for (int i = 0; i < ncols; i++) {
ExpressionNode column = getColumnExpression(table, hKey.column(i));
if (column == null) return null;
columns.add(column);
}
scan.setColumns(columns);
int nequals = insertLeadingEqualities(scan, conditions);
if (nequals != ncols) return null;
required = new HashSet<>(required);
// We do not handle any actual data columns.
required.addAll(requiredColumns.getTables());
scan.setRequiredTables(required);
scan.setCostEstimate(estimateCost(scan));
logger.debug("Selecting {}", scan);
return scan;
}
public int compare(BaseScan i1, BaseScan i2) {
return i2.getCostEstimate().compareTo(i1.getCostEstimate());
}
protected boolean determineCovering(IndexScan index) {
// Include the non-condition requirements.
RequiredColumns requiredAfter = new RequiredColumns(requiredColumns);
RequiredColumnsFiller filler = new RequiredColumnsFiller(requiredAfter);
// Add in any conditions not handled by the index.
for (ConditionExpression condition : conditions) {
boolean found = false;
if (index.getConditions() != null) {
for (ConditionExpression indexCondition : index.getConditions()) {
if (indexCondition == condition) {
found = true;
break;
}
}
}
if (!found)
condition.accept(filler);
}
// Add sort if not handled by the index.
if ((queryGoal.getOrdering() != null) &&
(index.getOrderEffectiveness() != IndexScan.OrderEffectiveness.SORTED)) {
// Only this node, not its inputs.
filler.setIncludedPlanNodes(Collections.<PlanNode>singletonList(queryGoal.getOrdering()));
queryGoal.getOrdering().accept(filler);
}
// Record what tables are required: within the index if any
// columns still needed, others if joined at all. Do this
// before taking account of columns from a covering index,
// since may not use it that way.
{
Collection<TableSource> joined = index.getTables();
Set<TableSource> required = new HashSet<>();
boolean moreTables = false;
for (TableSource table : requiredAfter.getTables()) {
if (!joined.contains(table)) {
moreTables = true;
required.add(table);
}
else if (requiredAfter.hasColumns(table) ||
(table == queryGoal.getUpdateTarget())) {
required.add(table);
}
}
index.setRequiredTables(required);
if (moreTables)
// Need to join up last the index; index might point
// to an orphan.
return false;
}
if (queryGoal.getUpdateTarget() != null) {
// UPDATE statements need the whole target row and are thus never
// covering for their group.
for (TableGroupJoinNode table : tables) {
if (table.getTable() == queryGoal.getUpdateTarget())
return false;
}
}
// Remove the columns we do have from the index.
int ncols = index.getColumns().size();
for (int i = 0; i < ncols; i++) {
ExpressionNode column = index.getColumns().get(i);
if ((column instanceof ColumnExpression) && index.isRecoverableAt(i)) {
if (requiredAfter.have((ColumnExpression)column) &&
(i >= index.getNKeyColumns())) {
index.setUsesAllColumns(true);
}
}
}
return requiredAfter.isEmpty();
}
protected void determineRequiredTables(GroupLoopScan scan) {
// Include the non-condition requirements.
RequiredColumns requiredAfter = new RequiredColumns(requiredColumns);
RequiredColumnsFiller filler = new RequiredColumnsFiller(requiredAfter);
// Add in any non-join conditions.
for (ConditionExpression condition : conditions) {
boolean found = false;
for (ConditionExpression joinCondition : scan.getJoinConditions()) {
if (joinCondition == condition) {
found = true;
break;
}
}
if (!found)
condition.accept(filler);
}
// Does not sort.
if (queryGoal.getOrdering() != null) {
// Only this node, not its inputs.
filler.setIncludedPlanNodes(Collections.<PlanNode>singletonList(queryGoal.getOrdering()));
queryGoal.getOrdering().accept(filler);
}
// The only table we can exclude is the one initially joined to, in the case
// where all the data comes from elsewhere on that branch.
Set<TableSource> required = new HashSet<>(requiredAfter.getTables());
if (!requiredAfter.hasColumns(scan.getInsideTable()))
required.remove(scan.getInsideTable());
scan.setRequiredTables(required);
}
public CostEstimate estimateCost(IndexScan index) {
return estimateCost(index, queryGoal.getLimit());
}
public CostEstimate estimateCost(IndexScan index, long limit) {
PlanCostEstimator estimator = newEstimator();
Set<TableSource> requiredTables = index.getRequiredTables();
estimator.indexScan(index);
if (!index.isCovering()) {
estimator.flatten(tables,
index.getLeafMostTable(), requiredTables);
}
Collection<ConditionExpression> unhandledConditions =
new HashSet<>(conditions);
if (index.getConditions() != null)
unhandledConditions.removeAll(index.getConditions());
if (!unhandledConditions.isEmpty()) {
estimator.select(unhandledConditions,
selectivityConditions(unhandledConditions, requiredTables));
}
if (queryGoal.needSort(index.getOrderEffectiveness())) {
estimator.sort(queryGoal.sortFields());
}
estimator.setLimit(limit);
return estimator.getCostEstimate();
}
public CostEstimate estimateIntersectionCost(IndexScan index) {
if (index.getOrderEffectiveness() == IndexScan.OrderEffectiveness.NONE)
return index.getScanCostEstimate();
long limit = queryGoal.getLimit();
if (limit < 0)
return index.getScanCostEstimate();
// There is a limit and this index looks to be sorted, so adjust for that
// limit. Otherwise, the scan only cost, which includes all rows, will appear
// too large compared to a limit-aware best plan.
PlanCostEstimator estimator = newEstimator();
estimator.indexScan(index);
estimator.setLimit(limit);
return estimator.getCostEstimate();
}
public CostEstimate estimateCost(GroupScan scan) {
PlanCostEstimator estimator = newEstimator();
Set<TableSource> requiredTables = requiredColumns.getTables();
estimator.groupScan(scan, tables, requiredTables);
if (!conditions.isEmpty()) {
estimator.select(conditions,
selectivityConditions(conditions, requiredTables));
}
estimator.setLimit(queryGoal.getLimit());
return estimator.getCostEstimate();
}
public CostEstimate estimateCost(GroupLoopScan scan) {
PlanCostEstimator estimator = newEstimator();
Set<TableSource> requiredTables = scan.getRequiredTables();
estimator.groupLoop(scan, tables, requiredTables);
Collection<ConditionExpression> unhandledConditions =
new HashSet<>(conditions);
unhandledConditions.removeAll(scan.getJoinConditions());
if (!unhandledConditions.isEmpty()) {
estimator.select(unhandledConditions,
selectivityConditions(unhandledConditions, requiredTables));
}
if (queryGoal.needSort(IndexScan.OrderEffectiveness.NONE)) {
estimator.sort(queryGoal.sortFields());
}
estimator.setLimit(queryGoal.getLimit());
return estimator.getCostEstimate();
}
public CostEstimate estimateCost(ExpressionsHKeyScan scan) {
PlanCostEstimator estimator = newEstimator();
Set<TableSource> requiredTables = scan.getRequiredTables();
estimator.hKeyRow(scan);
estimator.flatten(tables, scan.getTable(), requiredTables);
Collection<ConditionExpression> unhandledConditions =
new HashSet<>(conditions);
unhandledConditions.removeAll(scan.getConditions());
if (!unhandledConditions.isEmpty()) {
estimator.select(unhandledConditions,
selectivityConditions(unhandledConditions, requiredTables));
}
if (queryGoal.needSort(IndexScan.OrderEffectiveness.NONE)) {
estimator.sort(queryGoal.sortFields());
}
estimator.setLimit(queryGoal.getLimit());
return estimator.getCostEstimate();
}
public double estimateSelectivity(IndexScan index) {
return queryGoal.getCostEstimator().conditionsSelectivity(selectivityConditions(index.getConditions(), index.getTables()));
}
// Conditions that might have a recognizable selectivity.
protected SelectivityConditions selectivityConditions(Collection<ConditionExpression> conditions, Collection<TableSource> requiredTables) {
SelectivityConditions result = new SelectivityConditions();
for (ConditionExpression condition : conditions) {
if (condition instanceof ComparisonCondition) {
ComparisonCondition ccond = (ComparisonCondition)condition;
if (ccond.getLeft() instanceof ColumnExpression) {
ColumnExpression column = (ColumnExpression)ccond.getLeft();
if ((column.getColumn() != null) &&
requiredTables.contains(column.getTable()) &&
constantOrBound(ccond.getRight())) {
result.addCondition(column, condition);
}
}
}
else if (condition instanceof InListCondition) {
InListCondition incond = (InListCondition)condition;
if (incond.getOperand() instanceof ColumnExpression) {
ColumnExpression column = (ColumnExpression)incond.getOperand();
if ((column.getColumn() != null) &&
requiredTables.contains(column.getTable())) {
boolean allConstant = true;
for (ExpressionNode expr : incond.getExpressions()) {
if (!constantOrBound(expr)) {
allConstant = false;
break;
}
}
if (allConstant) {
result.addCondition(column, condition);
}
}
}
}
}
return result;
}
// Recognize the case of a join that is only used for predication.
// TODO: This is only covers the simplest case, namely an index that is unique
// none of whose columns are actually used.
public boolean semiJoinEquivalent(BaseScan scan) {
if (scan instanceof SingleIndexScan) {
SingleIndexScan indexScan = (SingleIndexScan)scan;
if (indexScan.isCovering() && isUnique(indexScan) &&
requiredColumns.isEmpty()) {
return true;
}
}
return false;
}
// Does this scan return at most one row?
protected boolean isUnique(SingleIndexScan indexScan) {
List<ExpressionNode> equalityComparands = indexScan.getEqualityComparands();
if (equalityComparands == null)
return false;
int nequals = equalityComparands.size();
Index index = indexScan.getIndex();
if (index.isUnique() && (nequals >= index.getKeyColumns().size()))
return true;
if (index.isGroupIndex())
return false;
Set<Column> equalityColumns = new HashSet<>(nequals);
for (int i = 0; i < nequals; i++) {
ExpressionNode equalityExpr = indexScan.getColumns().get(i);
if (equalityExpr instanceof ColumnExpression) {
equalityColumns.add(((ColumnExpression)equalityExpr).getColumn());
}
}
TableIndex tableIndex = (TableIndex)index;
find_index: // Find a unique index all of whose columns are equaled.
for (TableIndex otherIndex : tableIndex.getTable().getIndexes()) {
if (!otherIndex.isUnique()) continue;
for (IndexColumn otherColumn : otherIndex.getKeyColumns()) {
if (!equalityColumns.contains(otherColumn.getColumn()))
continue find_index;
}
return true;
}
return false;
}
public TableGroupJoinTree install(BaseScan scan,
List<ConditionList> conditionSources,
boolean sortAllowed, boolean copy) {
TableGroupJoinTree result = tables;
// Need to have more than one copy of this tree in the final result.
if (copy) result = new TableGroupJoinTree(result.getRoot());
result.setScan(scan);
this.sortAllowed = sortAllowed;
if (scan instanceof IndexScan) {
IndexScan indexScan = (IndexScan)scan;
if (indexScan instanceof MultiIndexIntersectScan) {
MultiIndexIntersectScan multiScan = (MultiIndexIntersectScan)indexScan;
installOrdering(indexScan, multiScan.getOrdering(), multiScan.getPeggedCount(), multiScan.getComparisonFields());
}
installConditions(indexScan.getConditions(), conditionSources);
if (sortAllowed)
queryGoal.installOrderEffectiveness(indexScan.getOrderEffectiveness());
}
else {
if (scan instanceof GroupLoopScan) {
installConditions(((GroupLoopScan)scan).getJoinConditions(),
conditionSources);
}
else if (scan instanceof FullTextScan) {
FullTextScan textScan = (FullTextScan)scan;
installConditions(textScan.getConditions(), conditionSources);
if (conditions.isEmpty()) {
textScan.setLimit((int)queryGoal.getLimit());
}
}
else if (scan instanceof ExpressionsHKeyScan) {
installConditions(((ExpressionsHKeyScan)scan).getConditions(),
conditionSources);
}
if (sortAllowed)
queryGoal.installOrderEffectiveness(IndexScan.OrderEffectiveness.NONE);
}
return result;
}
/** Change WHERE as a consequence of <code>index</code> being
* used, using either the sources returned by {@link updateContext} or the
* current ones if nothing has been changed.
*/
public void installConditions(Collection<? extends ConditionExpression> conditions,
List<ConditionList> conditionSources) {
if (conditions != null) {
if (conditionSources == null)
conditionSources = this.conditionSources;
for (ConditionExpression condition : conditions) {
for (ConditionList conditionSource : conditionSources) {
if (conditionSource.remove(condition))
break;
}
}
}
}
@Override
public String toString() {
StringBuilder str = new StringBuilder();
str.append(tables.summaryString());
str.append("\n");
str.append(conditions);
str.append("\n[");
boolean first = true;
for (ColumnSource bound : boundTables) {
if (first)
first = false;
else
str.append(", ");
str.append(bound.getName());
}
str.append("]");
return str.toString();
}
// Too-many-way UNION can consume too many resources (and overflow
// the stack explaining).
protected static int COLUMN_RANGE_MAX_SEGMENTS_DEFAULT = 16;
// Get Range-expressible conditions for given column.
protected ColumnRanges rangeForIndex(ExpressionNode expressionNode) {
if (expressionNode instanceof ColumnExpression) {
if (columnsToRanges == null) {
columnsToRanges = new HashMap<>();
for (ConditionExpression condition : conditions) {
ColumnRanges range = ColumnRanges.rangeAtNode(condition);
if (range != null) {
ColumnExpression rangeColumn = range.getColumnExpression();
ColumnRanges oldRange = columnsToRanges.get(rangeColumn);
if (oldRange != null)
range = ColumnRanges.andRanges(range, oldRange);
columnsToRanges.put(rangeColumn, range);
}
}
if (!columnsToRanges.isEmpty()) {
int maxSegments;
String prop = queryGoal.getRulesContext().getProperty("columnRangeMaxSegments");
if (prop != null)
maxSegments = Integer.parseInt(prop);
else
maxSegments = COLUMN_RANGE_MAX_SEGMENTS_DEFAULT;
Iterator<ColumnRanges> iter = columnsToRanges.values().iterator();
while (iter.hasNext()) {
if (iter.next().getSegments().size() > maxSegments) {
iter.remove();
}
}
}
}
ColumnExpression columnExpression = (ColumnExpression)expressionNode;
return columnsToRanges.get(columnExpression);
}
return null;
}
static class RequiredColumns {
private Map<TableSource,Set<ColumnExpression>> map;
public RequiredColumns(TableGroupJoinTree tables) {
map = new HashMap<>();
for (TableGroupJoinNode table : tables) {
map.put(table.getTable(), new HashSet<ColumnExpression>());
}
}
public RequiredColumns(RequiredColumns other) {
map = new HashMap<>(other.map.size());
for (Map.Entry<TableSource,Set<ColumnExpression>> entry : other.map.entrySet()) {
map.put(entry.getKey(), new HashSet<>(entry.getValue()));
}
}
public Set<TableSource> getTables() {
return map.keySet();
}
public boolean hasColumns(TableSource table) {
Set<ColumnExpression> entry = map.get(table);
if (entry == null) return false;
return !entry.isEmpty();
}
public boolean isEmpty() {
boolean empty = true;
for (Set<ColumnExpression> entry : map.values())
if (!entry.isEmpty())
return false;
return empty;
}
public void require(ColumnExpression expr) {
Set<ColumnExpression> entry = map.get(expr.getTable());
if (entry != null)
entry.add(expr);
}
/** Opposite of {@link require}: note that we have a source for this column. */
public boolean have(ColumnExpression expr) {
Set<ColumnExpression> entry = map.get(expr.getTable());
if (entry != null)
return entry.remove(expr);
else
return false;
}
public void clear() {
for (Set<ColumnExpression> entry : map.values())
entry.clear();
}
}
static class RequiredColumnsFiller implements PlanVisitor, ExpressionVisitor {
private RequiredColumns requiredColumns;
private Map<PlanNode,Void> excludedPlanNodes, includedPlanNodes;
private Map<ExpressionNode,Void> excludedExpressions;
private Deque<Boolean> excludeNodeStack = new ArrayDeque<>();
private boolean excludeNode = false;
private int excludeDepth = 0;
private int subqueryDepth = 0;
public RequiredColumnsFiller(RequiredColumns requiredColumns) {
this.requiredColumns = requiredColumns;
}
public RequiredColumnsFiller(RequiredColumns requiredColumns,
Collection<PlanNode> excludedPlanNodes,
Collection<ConditionExpression> excludedExpressions) {
this.requiredColumns = requiredColumns;
this.excludedPlanNodes = new IdentityHashMap<>();
for (PlanNode planNode : excludedPlanNodes)
this.excludedPlanNodes.put(planNode, null);
this.excludedExpressions = new IdentityHashMap<>();
for (ConditionExpression condition : excludedExpressions)
this.excludedExpressions.put(condition, null);
}
public void setIncludedPlanNodes(Collection<PlanNode> includedPlanNodes) {
this.includedPlanNodes = new IdentityHashMap<>();
for (PlanNode planNode : includedPlanNodes)
this.includedPlanNodes.put(planNode, null);
}
@Override
public boolean visitEnter(PlanNode n) {
// Input nodes are called within the context of their output.
// We want to know whether just this node is excluded, not
// it and all its inputs.
excludeNodeStack.push(excludeNode);
excludeNode = exclude(n);
if ((n instanceof Subquery) &&
!((Subquery)n).getOuterTables().isEmpty())
// TODO: Might be accessing tables from outer query as
// group joins, which we don't support currently. Make
// sure those aren't excluded.
subqueryDepth++;
return visit(n);
}
@Override
public boolean visitLeave(PlanNode n) {
excludeNode = excludeNodeStack.pop();
if ((n instanceof Subquery) &&
!((Subquery)n).getOuterTables().isEmpty())
subqueryDepth--;
return true;
}
@Override
public boolean visit(PlanNode n) {
return true;
}
@Override
public boolean visitEnter(ExpressionNode n) {
if (!excludeNode && exclude(n))
excludeDepth++;
return visit(n);
}
@Override
public boolean visitLeave(ExpressionNode n) {
if (!excludeNode && exclude(n))
excludeDepth--;
return true;
}
@Override
public boolean visit(ExpressionNode n) {
if (!excludeNode && (excludeDepth == 0)) {
if (n instanceof ColumnExpression)
requiredColumns.require((ColumnExpression)n);
}
return true;
}
// Should this plan node be excluded from the requirement?
protected boolean exclude(PlanNode node) {
if (includedPlanNodes != null)
return !includedPlanNodes.containsKey(node);
else if (excludedPlanNodes != null)
return excludedPlanNodes.containsKey(node);
else
return false;
}
// Should this expression be excluded from requirement?
protected boolean exclude(ExpressionNode expr) {
return (((excludedExpressions != null) &&
excludedExpressions.containsKey(expr)) ||
// Group join conditions are handled specially.
((expr instanceof ConditionExpression) &&
(((ConditionExpression)expr).getImplementation() ==
ConditionExpression.Implementation.GROUP_JOIN) &&
// Include expressions in subqueries until do joins across them.
(subqueryDepth == 0)));
}
}
/* Spatial indexes */
/** For now, a spatial index is a special kind of table index on
* Z-order of two coordinates.
*/
public boolean spatialUsable(SingleIndexScan index, int nequals) {
// There are two cases to recognize:
// ORDER BY znear(column_lat, column_lon, start_lat, start_lon), which
// means fan out from that center in Z-order.
// WHERE distance_lat_lon(column_lat, column_lon, start_lat, start_lon) <= radius
ExpressionNode nextColumn = index.getColumns().get(nequals);
if (!(nextColumn instanceof SpecialIndexExpression))
return false; // Did not have enough equalities to get to spatial part.
SpecialIndexExpression indexExpression = (SpecialIndexExpression)nextColumn;
assert (indexExpression.getFunction() == SpecialIndexExpression.Function.Z_ORDER_LAT_LON);
List<ExpressionNode> operands = indexExpression.getOperands();
boolean matched = false;
for (ConditionExpression condition : conditions) {
if (condition instanceof ComparisonCondition) {
ComparisonCondition ccond = (ComparisonCondition)condition;
ExpressionNode centerRadius = null;
switch (ccond.getOperation()) {
case LE:
case LT:
centerRadius = matchDistanceLatLon(operands,
ccond.getLeft(),
ccond.getRight());
break;
case GE:
case GT:
centerRadius = matchDistanceLatLon(operands,
ccond.getRight(),
ccond.getLeft());
break;
}
if (centerRadius != null) {
index.setLowComparand(centerRadius, true);
index.setOrderEffectiveness(IndexScan.OrderEffectiveness.NONE);
matched = true;
break;
}
}
}
if (!matched) {
if (sortAllowed && (queryGoal.getOrdering() != null)) {
List<OrderByExpression> orderBy = queryGoal.getOrdering().getOrderBy();
if (orderBy.size() == 1) {
ExpressionNode center = matchZnear(operands,
orderBy.get(0));
if (center != null) {
index.setLowComparand(center, true);
index.setOrderEffectiveness(IndexScan.OrderEffectiveness.SORTED);
matched = true;
}
}
}
if (!matched)
return false;
}
index.setCovering(determineCovering(index));
index.setCostEstimate(estimateCostSpatial(index));
return true;
}
private ExpressionNode matchDistanceLatLon(List<ExpressionNode> indexExpressions,
ExpressionNode left, ExpressionNode right) {
if (!((left instanceof FunctionExpression) &&
((FunctionExpression)left).getFunction().equalsIgnoreCase("distance_lat_lon") &&
constantOrBound(right)))
return null;
ExpressionNode col1 = indexExpressions.get(0);
ExpressionNode col2 = indexExpressions.get(1);
List<ExpressionNode> operands = ((FunctionExpression)left).getOperands();
if (operands.size() != 4) return null; // TODO: Would error here be better?
ExpressionNode op1 = operands.get(0);
ExpressionNode op2 = operands.get(1);
ExpressionNode op3 = operands.get(2);
ExpressionNode op4 = operands.get(3);
if ((right.getType() != null) &&
(right.getType().typeClass().jdbcType() != Types.DECIMAL)) {
DataTypeDescriptor sqlType =
new DataTypeDescriptor(TypeId.DECIMAL_ID, 10, 6, true, 12);
TInstance type = queryGoal.getRulesContext()
.getTypesTranslator().typeForSQLType(sqlType);
right = new CastExpression(right, sqlType, right.getSQLsource(), type);
}
if (columnMatches(col1, op1) && columnMatches(col2, op2) &&
constantOrBound(op3) && constantOrBound(op4)) {
return new FunctionExpression("_center_radius",
Arrays.asList(op3, op4, right),
null, null, null);
}
if (columnMatches(col1, op3) && columnMatches(col2, op4) &&
constantOrBound(op1) && constantOrBound(op2)) {
return new FunctionExpression("_center_radius",
Arrays.asList(op1, op2, right),
null, null, null);
}
return null;
}
private ExpressionNode matchZnear(List<ExpressionNode> indexExpressions,
OrderByExpression orderBy) {
if (!orderBy.isAscending()) return null;
ExpressionNode orderExpr = orderBy.getExpression();
if (!((orderExpr instanceof FunctionExpression) &&
((FunctionExpression)orderExpr).getFunction().equalsIgnoreCase("znear")))
return null;
ExpressionNode col1 = indexExpressions.get(0);
ExpressionNode col2 = indexExpressions.get(1);
List<ExpressionNode> operands = ((FunctionExpression)orderExpr).getOperands();
if (operands.size() != 4) return null; // TODO: Would error here be better?
ExpressionNode op1 = operands.get(0);
ExpressionNode op2 = operands.get(1);
ExpressionNode op3 = operands.get(2);
ExpressionNode op4 = operands.get(3);
if (columnMatches(col1, op1) && columnMatches(col2, op2) &&
constantOrBound(op3) && constantOrBound(op4))
return new FunctionExpression("_center",
Arrays.asList(op3, op4),
null, null, null);
if (columnMatches(col1, op3) && columnMatches(col2, op4) &&
constantOrBound(op1) && constantOrBound(op2))
return new FunctionExpression("_center",
Arrays.asList(op1, op2),
null, null, null);
return null;
}
private static boolean columnMatches(ExpressionNode col, ExpressionNode op) {
if (op instanceof CastExpression)
op = ((CastExpression)op).getOperand();
return col.equals(op);
}
public CostEstimate estimateCostSpatial(SingleIndexScan index) {
PlanCostEstimator estimator = newEstimator();
Set<TableSource> requiredTables = requiredColumns.getTables();
estimator.spatialIndex(index);
if (!index.isCovering()) {
estimator.flatten(tables, index.getLeafMostTable(), requiredTables);
}
Collection<ConditionExpression> unhandledConditions = new HashSet<>(conditions);
if (index.getConditions() != null)
unhandledConditions.removeAll(index.getConditions());
if (!unhandledConditions.isEmpty()) {
estimator.select(unhandledConditions,
selectivityConditions(unhandledConditions, requiredTables));
}
if (queryGoal.needSort(index.getOrderEffectiveness())) {
estimator.sort(queryGoal.sortFields());
}
estimator.setLimit(queryGoal.getLimit());
return estimator.getCostEstimate();
}
protected FullTextScan pickFullText() {
List<ConditionExpression> textConditions = new ArrayList<>(0);
for (ConditionExpression condition : conditions) {
if ((condition instanceof FunctionExpression) &&
((FunctionExpression)condition).getFunction().equalsIgnoreCase("full_text_search")) {
textConditions.add(condition);
}
}
if (textConditions.isEmpty())
return null;
List<FullTextField> textFields = new ArrayList<>(0);
FullTextQuery query = null;
for (ConditionExpression condition : textConditions) {
List<ExpressionNode> operands = ((FunctionExpression)condition).getOperands();
FullTextQuery clause = null;
switch (operands.size()) {
case 1:
clause = fullTextBoolean(operands.get(0), textFields);
if (clause == null) continue;
break;
case 2:
if ((operands.get(0) instanceof ColumnExpression) &&
constantOrBound(operands.get(1))) {
ColumnExpression column = (ColumnExpression)operands.get(0);
if (column.getTable() instanceof TableSource) {
if (!tables.containsTable((TableSource)column.getTable()))
continue;
FullTextField field = new FullTextField(column,
FullTextField.Type.PARSE,
operands.get(1));
textFields.add(field);
clause = field;
}
}
break;
}
if (clause == null)
throw new UnsupportedSQLException("Unrecognized FULL_TEXT_SEARCH call",
condition.getSQLsource());
if (query == null) {
query = clause;
}
else {
query = fullTextBoolean(Arrays.asList(query, clause),
Arrays.asList(FullTextQueryBuilder.BooleanType.MUST,
FullTextQueryBuilder.BooleanType.MUST));
}
}
if (query == null)
return null;
FullTextIndex foundIndex = null;
TableSource foundTable = null;
find_index:
for (FullTextIndex index : textFields.get(0).getColumn().getColumn().getTable().getFullTextIndexes()) {
TableSource indexTable = null;
for (FullTextField textField : textFields) {
Column column = textField.getColumn().getColumn();
boolean found = false;
for (IndexColumn indexColumn : index.getKeyColumns()) {
if (indexColumn.getColumn() == column) {
if (foundIndex == null) {
textField.setIndexColumn(indexColumn);
}
found = true;
if ((indexTable == null) &&
(indexColumn.getColumn().getTable() == index.getIndexedTable())) {
indexTable = (TableSource)textField.getColumn().getTable();
}
break;
}
}
if (!found) {
continue find_index;
}
}
if (foundIndex == null) {
foundIndex = index;
foundTable = indexTable;
}
else {
throw new UnsupportedSQLException("Ambiguous full text index: " +
foundIndex + " and " + index);
}
}
if (foundIndex == null) {
StringBuilder str = new StringBuilder("No full text index for: ");
boolean first = true;
for (FullTextField textField : textFields) {
if (first)
first = false;
else
str.append(", ");
str.append(textField.getColumn());
}
throw new UnsupportedSQLException(str.toString());
}
if (foundTable == null) {
for (TableGroupJoinNode node : tables) {
if (node.getTable().getTable().getTable() == foundIndex.getIndexedTable()) {
foundTable = node.getTable();
break;
}
}
}
query = normalizeFullTextQuery(query);
FullTextScan scan = new FullTextScan(foundIndex, query,
foundTable, textConditions);
determineRequiredTables(scan);
scan.setCostEstimate(estimateCostFullText(scan));
return scan;
}
protected FullTextQuery fullTextBoolean(ExpressionNode condition,
List<FullTextField> textFields) {
if (condition instanceof ComparisonCondition) {
ComparisonCondition ccond = (ComparisonCondition)condition;
if ((ccond.getLeft() instanceof ColumnExpression) &&
constantOrBound(ccond.getRight())) {
ColumnExpression column = (ColumnExpression)ccond.getLeft();
if (column.getTable() instanceof TableSource) {
if (!tables.containsTable((TableSource)column.getTable()))
return null;
FullTextField field = new FullTextField(column,
FullTextField.Type.MATCH,
ccond.getRight());
textFields.add(field);
switch (ccond.getOperation()) {
case EQ:
return field;
case NE:
return fullTextBoolean(Arrays.<FullTextQuery>asList(field),
Arrays.asList(FullTextQueryBuilder.BooleanType.NOT));
}
}
}
}
else if (condition instanceof LogicalFunctionCondition) {
LogicalFunctionCondition lcond = (LogicalFunctionCondition)condition;
String op = lcond.getFunction();
if ("and".equals(op)) {
FullTextQuery left = fullTextBoolean(lcond.getLeft(), textFields);
FullTextQuery right = fullTextBoolean(lcond.getRight(), textFields);
if ((left == null) && (right == null)) return null;
if ((left != null) && (right != null))
return fullTextBoolean(Arrays.asList(left, right),
Arrays.asList(FullTextQueryBuilder.BooleanType.MUST,
FullTextQueryBuilder.BooleanType.MUST));
}
else if ("or".equals(op)) {
FullTextQuery left = fullTextBoolean(lcond.getLeft(), textFields);
FullTextQuery right = fullTextBoolean(lcond.getRight(), textFields);
if ((left == null) && (right == null)) return null;
if ((left != null) && (right != null))
return fullTextBoolean(Arrays.asList(left, right),
Arrays.asList(FullTextQueryBuilder.BooleanType.SHOULD,
FullTextQueryBuilder.BooleanType.SHOULD));
}
else if ("not".equals(op)) {
FullTextQuery inner = fullTextBoolean(lcond.getOperand(), textFields);
if (inner == null)
return null;
else
return fullTextBoolean(Arrays.asList(inner),
Arrays.asList(FullTextQueryBuilder.BooleanType.NOT));
}
}
// TODO: LIKE
throw new UnsupportedSQLException("Cannot convert to full text query" +
condition);
}
protected FullTextQuery fullTextBoolean(List<FullTextQuery> operands,
List<FullTextQueryBuilder.BooleanType> types) {
// Make modifiable copies for normalize.
return new FullTextBoolean(new ArrayList<>(operands),
new ArrayList<>(types));
}
protected FullTextQuery normalizeFullTextQuery(FullTextQuery query) {
if (query instanceof FullTextBoolean) {
FullTextBoolean bquery = (FullTextBoolean)query;
List<FullTextQuery> operands = bquery.getOperands();
List<FullTextQueryBuilder.BooleanType> types = bquery.getTypes();
int i = 0;
while (i < operands.size()) {
FullTextQuery opQuery = operands.get(i);
opQuery = normalizeFullTextQuery(opQuery);
if (opQuery instanceof FullTextBoolean) {
FullTextBoolean opbquery = (FullTextBoolean)opQuery;
List<FullTextQuery> opOperands = opbquery.getOperands();
List<FullTextQueryBuilder.BooleanType> opTypes = opbquery.getTypes();
// Fold in the simplest cases:
// [MUST(x), [MUST(y), MUST(z)]] -> [MUST(x), MUST(y), MUST(z)]
// [MUST(x), [NOT(y)]] -> [MUST(x), NOT(y)]
// [SHOULD(x), [SHOULD(y), SHOULD(z)]] -> [SHOULD(x), SHOULD(y), SHOULD(z)]
boolean fold = true;
switch (types.get(i)) {
case MUST:
check_must:
for (FullTextQueryBuilder.BooleanType opType : opTypes) {
switch (opType) {
case MUST:
case NOT:
break;
default:
fold = false;
break check_must;
}
}
break;
case SHOULD:
check_should:
for (FullTextQueryBuilder.BooleanType opType : opTypes) {
switch (opType) {
case SHOULD:
break;
default:
fold = false;
break check_should;
}
}
break;
default:
fold = false;
break;
}
if (fold) {
for (int j = 0; j < opOperands.size(); j++) {
FullTextQuery opOperand = opOperands.get(j);
FullTextQueryBuilder.BooleanType opType = opTypes.get(j);
if (j == 0) {
operands.set(i, opOperand);
types.set(i, opType);
}
else {
operands.add(i, opOperand);
types.add(i, opType);
}
i++;
}
continue;
}
}
operands.set(i, opQuery);
i++;
}
}
return query;
}
protected void determineRequiredTables(FullTextScan scan) {
// Include the non-condition requirements.
RequiredColumns requiredAfter = new RequiredColumns(requiredColumns);
RequiredColumnsFiller filler = new RequiredColumnsFiller(requiredAfter);
// Add in any non-full-text conditions.
for (ConditionExpression condition : conditions) {
boolean found = false;
for (ConditionExpression scanCondition : scan.getConditions()) {
if (scanCondition == condition) {
found = true;
break;
}
}
if (!found)
condition.accept(filler);
}
// Does not sort.
if (queryGoal.getOrdering() != null) {
// Only this node, not its inputs.
filler.setIncludedPlanNodes(Collections.<PlanNode>singletonList(queryGoal.getOrdering()));
queryGoal.getOrdering().accept(filler);
}
Set<TableSource> required = new HashSet<>(requiredAfter.getTables());
scan.setRequiredTables(required);
}
public CostEstimate estimateCostFullText(FullTextScan scan) {
PlanCostEstimator estimator = newEstimator();
estimator.fullTextScan(scan);
return estimator.getCostEstimate();
}
protected PlanCostEstimator newEstimator() {
return new PlanCostEstimator(queryGoal.getCostEstimator());
}
}
| Cannot remove group loop initial table if it's the only one, even if columns unused. Its rows determine cardinality.
Fixes #1315
| src/main/java/com/foundationdb/sql/optimizer/rule/join_enum/GroupIndexGoal.java | Cannot remove group loop initial table if it's the only one, even if columns unused. Its rows determine cardinality. | <ide><path>rc/main/java/com/foundationdb/sql/optimizer/rule/join_enum/GroupIndexGoal.java
<ide> // The only table we can exclude is the one initially joined to, in the case
<ide> // where all the data comes from elsewhere on that branch.
<ide> Set<TableSource> required = new HashSet<>(requiredAfter.getTables());
<del> if (!requiredAfter.hasColumns(scan.getInsideTable()))
<add> if ((required.size() > 1) &&
<add> !requiredAfter.hasColumns(scan.getInsideTable()))
<ide> required.remove(scan.getInsideTable());
<ide> scan.setRequiredTables(required);
<ide> } |
|
Java | mit | 44df0ee55ee63605e5ac96aedd963d74d6c0315e | 0 | hazendaz/oshi,dbwiddis/oshi | /**
* MIT License
*
* Copyright (c) 2010 - 2020 The OSHI Project Contributors: https://github.com/oshi/oshi/graphs/contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package oshi.hardware.common;
import static oshi.util.Memoizer.memoize;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import oshi.annotation.concurrent.ThreadSafe;
import oshi.hardware.NetworkIF;
import oshi.util.FileUtil;
import oshi.util.FormatUtil;
/**
* Network interfaces implementation.
*/
@ThreadSafe
public abstract class AbstractNetworkIF implements NetworkIF {
private static final Logger LOG = LoggerFactory.getLogger(AbstractNetworkIF.class);
private static final String OSHI_VM_MAC_ADDR_PROPERTIES = "oshi.vmmacaddr.properties";
private NetworkInterface networkInterface;
private int mtu;
private String mac;
private String[] ipv4;
private Short[] subnetMasks;
private String[] ipv6;
private Short[] prefixLengths;
private final Supplier<Properties> vmMacAddrProps = memoize(AbstractNetworkIF::queryVmMacAddrProps);
/**
* Construct a {@link NetworkIF} object backed by the specified
* {@link NetworkInterface}.
*
* @param netint
* The core java {@link NetworkInterface} backing this object.
*/
protected AbstractNetworkIF(NetworkInterface netint) {
this.networkInterface = netint;
try {
// Set MTU
this.mtu = networkInterface.getMTU();
// Set MAC
byte[] hwmac = networkInterface.getHardwareAddress();
if (hwmac != null) {
List<String> octets = new ArrayList<>(6);
for (byte b : hwmac) {
octets.add(String.format("%02x", b));
}
this.mac = String.join(":", octets);
} else {
this.mac = "Unknown";
}
// Set IP arrays
ArrayList<String> ipv4list = new ArrayList<>();
ArrayList<Short> subnetMaskList = new ArrayList<>();
ArrayList<String> ipv6list = new ArrayList<>();
ArrayList<Short> prefixLengthList = new ArrayList<>();
for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
InetAddress address = interfaceAddress.getAddress();
if (address.getHostAddress().length() > 0) {
if (address.getHostAddress().contains(":")) {
ipv6list.add(address.getHostAddress().split("%")[0]);
prefixLengthList.add(interfaceAddress.getNetworkPrefixLength());
} else {
ipv4list.add(address.getHostAddress());
subnetMaskList.add(interfaceAddress.getNetworkPrefixLength());
}
}
}
this.ipv4 = ipv4list.toArray(new String[0]);
this.subnetMasks = subnetMaskList.toArray(new Short[0]);
this.ipv6 = ipv6list.toArray(new String[0]);
this.prefixLengths = prefixLengthList.toArray(new Short[0]);
} catch (SocketException e) {
LOG.error("Socket exception: {}", e.getMessage());
}
}
/**
* Returns network interfaces that are not Loopback, and have a hardware
* address.
*
* @return A list of network interfaces
*/
protected static List<NetworkInterface> getNetworkInterfaces() {
List<NetworkInterface> result = new ArrayList<>();
Enumeration<NetworkInterface> interfaces = null;
try {
interfaces = NetworkInterface.getNetworkInterfaces(); // can return null
} catch (SocketException ex) {
LOG.error("Socket exception when retrieving interfaces: {}", ex.getMessage());
}
if (interfaces != null) {
while (interfaces.hasMoreElements()) {
NetworkInterface netint = interfaces.nextElement();
try {
if (!netint.isLoopback() && netint.getHardwareAddress() != null) {
result.add(netint);
}
} catch (SocketException ex) {
LOG.error("Socket exception when retrieving interface \"{}\": {}", netint.getName(),
ex.getMessage());
}
}
}
return result;
}
@Override
public NetworkInterface queryNetworkInterface() {
return this.networkInterface;
}
@Override
public String getName() {
return this.networkInterface.getName();
}
@Override
public String getDisplayName() {
return this.networkInterface.getDisplayName();
}
@Override
public int getMTU() {
return this.mtu;
}
@Override
public String getMacaddr() {
return this.mac;
}
@Override
public String[] getIPv4addr() {
return Arrays.copyOf(this.ipv4, this.ipv4.length);
}
@Override
public Short[] getSubnetMasks() {
return Arrays.copyOf(this.subnetMasks, this.subnetMasks.length);
}
@Override
public String[] getIPv6addr() {
return Arrays.copyOf(this.ipv6, this.ipv6.length);
}
@Override
public Short[] getPrefixLengths() {
return Arrays.copyOf(this.prefixLengths, this.prefixLengths.length);
}
@Override
public boolean isKnownVmMacAddr() {
String oui = getMacaddr().length() > 7 ? getMacaddr().substring(0, 8) : getMacaddr();
return this.vmMacAddrProps.get().containsKey(oui.toUpperCase());
}
@Override
public int getIfType() {
// default
return 0;
}
@Override
public int getNdisPhysicalMediumType() {
// default
return 0;
}
@Override
public boolean isConnectorPresent() {
// default
return false;
}
private static Properties queryVmMacAddrProps() {
return FileUtil.readPropertiesFromFilename(OSHI_VM_MAC_ADDR_PROPERTIES);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Name: ").append(getName()).append(" ").append("(").append(getDisplayName()).append(")").append("\n");
sb.append(" MAC Address: ").append(getMacaddr()).append("\n");
sb.append(" MTU: ").append(getMTU()).append(", ").append("Speed: ").append(getSpeed()).append("\n");
String[] ipv4withmask = getIPv4addr();
if (this.ipv4.length == this.subnetMasks.length) {
for (int i = 0; i < this.subnetMasks.length; i++) {
ipv4withmask[i] += "/" + this.subnetMasks[i];
}
}
sb.append(" IPv4: ").append(Arrays.toString(ipv4withmask)).append("\n");
String[] ipv6withprefixlength = getIPv6addr();
if (this.ipv6.length == this.prefixLengths.length) {
for (int j = 0; j < this.prefixLengths.length; j++) {
ipv6withprefixlength[j] += "/" + this.prefixLengths[j];
}
}
sb.append(" IPv6: ").append(Arrays.toString(ipv6withprefixlength)).append("\n");
sb.append(" Traffic: received ").append(getPacketsRecv()).append(" packets/")
.append(FormatUtil.formatBytes(getBytesRecv())).append(" (" + getInErrors() + " err, ")
.append(getInDrops() + " drop);");
sb.append(" transmitted ").append(getPacketsSent()).append(" packets/")
.append(FormatUtil.formatBytes(getBytesSent())).append(" (" + getOutErrors() + " err, ")
.append(getCollisions() + " coll);");
return sb.toString();
}
}
| oshi-core/src/main/java/oshi/hardware/common/AbstractNetworkIF.java | /**
* MIT License
*
* Copyright (c) 2010 - 2020 The OSHI Project Contributors: https://github.com/oshi/oshi/graphs/contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package oshi.hardware.common;
import static oshi.util.Memoizer.memoize;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import oshi.annotation.concurrent.ThreadSafe;
import oshi.hardware.NetworkIF;
import oshi.util.FileUtil;
import oshi.util.FormatUtil;
/**
* Network interfaces implementation.
*/
@ThreadSafe
public abstract class AbstractNetworkIF implements NetworkIF {
private static final Logger LOG = LoggerFactory.getLogger(AbstractNetworkIF.class);
private static final String OSHI_VM_MAC_ADDR_PROPERTIES = "oshi.vmmacaddr.properties";
private NetworkInterface networkInterface;
private int mtu;
private String mac;
private String[] ipv4;
private Short[] subnetMasks;
private String[] ipv6;
private Short[] prefixLengths;
private final Supplier<Properties> vmMacAddrProps = memoize(AbstractNetworkIF::queryVmMacAddrProps);
/**
* Construct a {@link NetworkIF} object backed by the specified
* {@link NetworkInterface}.
*
* @param netint
* The core java {@link NetworkInterface} backing this object.
*/
protected AbstractNetworkIF(NetworkInterface netint) {
this.networkInterface = netint;
try {
// Set MTU
this.mtu = networkInterface.getMTU();
// Set MAC
byte[] hwmac = networkInterface.getHardwareAddress();
if (hwmac != null) {
List<String> octets = new ArrayList<>(6);
for (byte b : hwmac) {
octets.add(String.format("%02x", b));
}
this.mac = String.join(":", octets);
} else {
this.mac = "Unknown";
}
// Set IP arrays
ArrayList<String> ipv4list = new ArrayList<>();
ArrayList<Short> subnetMaskList = new ArrayList<>();
ArrayList<String> ipv6list = new ArrayList<>();
ArrayList<Short> prefixLengthList = new ArrayList<>();
for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
InetAddress address = interfaceAddress.getAddress();
if (address.getHostAddress().length() > 0) {
if (address.getHostAddress().contains(":")) {
ipv6list.add(address.getHostAddress().split("%")[0]);
prefixLengthList.add(interfaceAddress.getNetworkPrefixLength());
} else {
ipv4list.add(address.getHostAddress());
subnetMaskList.add(interfaceAddress.getNetworkPrefixLength());
}
}
}
this.ipv4 = ipv4list.toArray(new String[0]);
this.subnetMasks = subnetMaskList.toArray(new Short[0]);
this.ipv6 = ipv6list.toArray(new String[0]);
this.prefixLengths = prefixLengthList.toArray(new Short[0]);
} catch (SocketException e) {
LOG.error("Socket exception: {}", e.getMessage());
}
}
/**
* Returns network interfaces that are not Loopback, and have a hardware
* address.
*
* @return A list of network interfaces
*/
protected static List<NetworkInterface> getNetworkInterfaces() {
List<NetworkInterface> result = new ArrayList<>();
Enumeration<NetworkInterface> interfaces = null;
try {
interfaces = NetworkInterface.getNetworkInterfaces(); // can return null
} catch (SocketException ex) {
LOG.error("Socket exception when retrieving interfaces: {}", ex.getMessage());
}
if (interfaces != null) {
while (interfaces.hasMoreElements()) {
NetworkInterface netint = interfaces.nextElement();
try {
if (!netint.isLoopback() && netint.getHardwareAddress() != null) {
result.add(netint);
}
} catch (SocketException ex) {
LOG.error("Socket exception when retrieving interface \"{}\": {}", netint.getName(),
ex.getMessage());
}
}
}
return result;
}
@Override
public NetworkInterface queryNetworkInterface() {
return this.networkInterface;
}
@Override
public String getName() {
return this.networkInterface.getName();
}
@Override
public String getDisplayName() {
return this.networkInterface.getDisplayName();
}
@Override
public int getMTU() {
return this.mtu;
}
@Override
public String getMacaddr() {
return this.mac;
}
@Override
public String[] getIPv4addr() {
return Arrays.copyOf(this.ipv4, this.ipv4.length);
}
@Override
public Short[] getSubnetMasks() {
return Arrays.copyOf(this.subnetMasks, this.subnetMasks.length);
}
@Override
public String[] getIPv6addr() {
return Arrays.copyOf(this.ipv6, this.ipv6.length);
}
@Override
public Short[] getPrefixLengths() {
return Arrays.copyOf(this.prefixLengths, this.prefixLengths.length);
}
@Override
public boolean isKnownVmMacAddr() {
String oui = getMacaddr().length() > 7 ? getMacaddr().substring(0, 8) : getMacaddr();
return this.vmMacAddrProps.get().containsKey(oui.toUpperCase());
}
@Override
public int getIfType() {
// default
return 0;
}
@Override
public int getNdisPhysicalMediumType() {
// default
return 0;
}
@Override
public boolean isConnectorPresent() {
// default
return false;
}
private static Properties queryVmMacAddrProps() {
return FileUtil.readPropertiesFromFilename(OSHI_VM_MAC_ADDR_PROPERTIES);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Name: ").append(getName()).append(" ").append("(").append(getDisplayName()).append(")").append("\n");
sb.append(" MAC Address: ").append(getMacaddr()).append("\n");
sb.append(" MTU: ").append(getMTU()).append(", ").append("Speed: ").append(getSpeed()).append("\n");
sb.append(" IPv4: ").append(Arrays.toString(getIPv4addr())).append("\n");
sb.append(" Netmask: ").append(Arrays.toString(getSubnetMasks())).append("\n");
sb.append(" IPv6: ").append(Arrays.toString(getIPv6addr())).append("\n");
sb.append(" Prefix Lengths: ").append(Arrays.toString(getPrefixLengths())).append("\n");
sb.append(" Traffic: received ").append(getPacketsRecv()).append(" packets/")
.append(FormatUtil.formatBytes(getBytesRecv())).append(" (" + getInErrors() + " err, ")
.append(getInDrops() + " drop);");
sb.append(" transmitted ").append(getPacketsSent()).append(" packets/")
.append(FormatUtil.formatBytes(getBytesSent())).append(" (" + getOutErrors() + " err, ")
.append(getCollisions() + " coll);");
return sb.toString();
}
}
| Outputs for IPv4 & subnetMask and IPv6 & prefix lengths combined (#1261)
| oshi-core/src/main/java/oshi/hardware/common/AbstractNetworkIF.java | Outputs for IPv4 & subnetMask and IPv6 & prefix lengths combined (#1261) | <ide><path>shi-core/src/main/java/oshi/hardware/common/AbstractNetworkIF.java
<ide> sb.append("Name: ").append(getName()).append(" ").append("(").append(getDisplayName()).append(")").append("\n");
<ide> sb.append(" MAC Address: ").append(getMacaddr()).append("\n");
<ide> sb.append(" MTU: ").append(getMTU()).append(", ").append("Speed: ").append(getSpeed()).append("\n");
<del> sb.append(" IPv4: ").append(Arrays.toString(getIPv4addr())).append("\n");
<del> sb.append(" Netmask: ").append(Arrays.toString(getSubnetMasks())).append("\n");
<del> sb.append(" IPv6: ").append(Arrays.toString(getIPv6addr())).append("\n");
<del> sb.append(" Prefix Lengths: ").append(Arrays.toString(getPrefixLengths())).append("\n");
<add> String[] ipv4withmask = getIPv4addr();
<add> if (this.ipv4.length == this.subnetMasks.length) {
<add> for (int i = 0; i < this.subnetMasks.length; i++) {
<add> ipv4withmask[i] += "/" + this.subnetMasks[i];
<add> }
<add> }
<add> sb.append(" IPv4: ").append(Arrays.toString(ipv4withmask)).append("\n");
<add> String[] ipv6withprefixlength = getIPv6addr();
<add> if (this.ipv6.length == this.prefixLengths.length) {
<add> for (int j = 0; j < this.prefixLengths.length; j++) {
<add> ipv6withprefixlength[j] += "/" + this.prefixLengths[j];
<add> }
<add> }
<add> sb.append(" IPv6: ").append(Arrays.toString(ipv6withprefixlength)).append("\n");
<ide> sb.append(" Traffic: received ").append(getPacketsRecv()).append(" packets/")
<ide> .append(FormatUtil.formatBytes(getBytesRecv())).append(" (" + getInErrors() + " err, ")
<ide> .append(getInDrops() + " drop);"); |
|
Java | apache-2.0 | 1b89c6828994a354812317f2411842eacbe4590c | 0 | mglukhikh/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,mglukhikh/intellij-community | // Copyright 2000-2017 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.structuralsearch;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.structuralsearch.plugin.replace.ReplaceOptions;
import com.intellij.structuralsearch.plugin.replace.ReplacementInfo;
import com.intellij.util.containers.HashMap;
import java.util.Map;
/**
* @author Eugene.Kudelevsky
*/
public class DocumentBasedReplaceHandler extends StructuralReplaceHandler {
private final Project myProject;
private final Map<ReplacementInfo, RangeMarker> myRangeMarkers = new HashMap<>();
public DocumentBasedReplaceHandler(Project project) {
myProject = project;
}
public void replace(ReplacementInfo info, ReplaceOptions options) {
if (info.getMatchesCount() == 0) return;
RangeMarker rangeMarker = myRangeMarkers.get(info);
Document document = rangeMarker.getDocument();
document.replaceString(rangeMarker.getStartOffset(), rangeMarker.getEndOffset(), info.getReplacement());
PsiDocumentManager.getInstance(myProject).commitDocument(document);
}
@Override
public void prepare(ReplacementInfo info) {
MatchResult result = info.getMatchResult();
PsiElement element = result.getMatch();
PsiFile file = element instanceof PsiFile ? (PsiFile)element : element.getContainingFile();
Document document = PsiDocumentManager.getInstance(myProject).getDocument(file);
assert document != null;
RangeMarker rangeMarker = document.createRangeMarker(element.getTextRange());
rangeMarker.setGreedyToLeft(true);
rangeMarker.setGreedyToRight(true);
myRangeMarkers.put(info, rangeMarker);
}
}
| platform/structuralsearch/source/com/intellij/structuralsearch/DocumentBasedReplaceHandler.java | // Copyright 2000-2017 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.structuralsearch;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.structuralsearch.plugin.replace.ReplaceOptions;
import com.intellij.structuralsearch.plugin.replace.ReplacementInfo;
import com.intellij.util.containers.HashMap;
import java.util.Map;
/**
* @author Eugene.Kudelevsky
*/
public class DocumentBasedReplaceHandler extends StructuralReplaceHandler {
private final Project myProject;
private final Map<ReplacementInfo, RangeMarker> myRangeMarkers = new HashMap<>();
public DocumentBasedReplaceHandler(Project project) {
myProject = project;
}
public void replace(ReplacementInfo info, ReplaceOptions options) {
if (info.getMatchesCount() == 0) return;
PsiElement element = info.getMatch(0);
if (element == null) return;
PsiFile file = element instanceof PsiFile ? (PsiFile)element : element.getContainingFile();
assert file != null;
RangeMarker rangeMarker = myRangeMarkers.get(info);
Document document = rangeMarker.getDocument();
document.replaceString(rangeMarker.getStartOffset(), rangeMarker.getEndOffset(), info.getReplacement());
PsiDocumentManager.getInstance(element.getProject()).commitDocument(document);
}
@Override
public void prepare(ReplacementInfo info) {
MatchResult result = info.getMatchResult();
PsiElement element = result.getMatch();
PsiFile file = element instanceof PsiFile ? (PsiFile)element : element.getContainingFile();
Document document = PsiDocumentManager.getInstance(myProject).getDocument(file);
TextRange textRange = result.getMatch().getTextRange();
assert textRange != null;
RangeMarker rangeMarker = document.createRangeMarker(textRange);
rangeMarker.setGreedyToLeft(true);
rangeMarker.setGreedyToRight(true);
myRangeMarkers.put(info, rangeMarker);
}
}
| SSR: simplification
| platform/structuralsearch/source/com/intellij/structuralsearch/DocumentBasedReplaceHandler.java | SSR: simplification | <ide><path>latform/structuralsearch/source/com/intellij/structuralsearch/DocumentBasedReplaceHandler.java
<ide> import com.intellij.openapi.editor.Document;
<ide> import com.intellij.openapi.editor.RangeMarker;
<ide> import com.intellij.openapi.project.Project;
<del>import com.intellij.openapi.util.TextRange;
<ide> import com.intellij.psi.PsiDocumentManager;
<ide> import com.intellij.psi.PsiElement;
<ide> import com.intellij.psi.PsiFile;
<ide>
<ide> public void replace(ReplacementInfo info, ReplaceOptions options) {
<ide> if (info.getMatchesCount() == 0) return;
<del> PsiElement element = info.getMatch(0);
<del> if (element == null) return;
<del> PsiFile file = element instanceof PsiFile ? (PsiFile)element : element.getContainingFile();
<del> assert file != null;
<ide> RangeMarker rangeMarker = myRangeMarkers.get(info);
<ide> Document document = rangeMarker.getDocument();
<ide> document.replaceString(rangeMarker.getStartOffset(), rangeMarker.getEndOffset(), info.getReplacement());
<del> PsiDocumentManager.getInstance(element.getProject()).commitDocument(document);
<add> PsiDocumentManager.getInstance(myProject).commitDocument(document);
<ide> }
<ide>
<ide> @Override
<ide> public void prepare(ReplacementInfo info) {
<del> MatchResult result = info.getMatchResult();
<add> MatchResult result = info.getMatchResult();
<ide> PsiElement element = result.getMatch();
<ide> PsiFile file = element instanceof PsiFile ? (PsiFile)element : element.getContainingFile();
<ide> Document document = PsiDocumentManager.getInstance(myProject).getDocument(file);
<del> TextRange textRange = result.getMatch().getTextRange();
<del> assert textRange != null;
<del> RangeMarker rangeMarker = document.createRangeMarker(textRange);
<add> assert document != null;
<add> RangeMarker rangeMarker = document.createRangeMarker(element.getTextRange());
<ide> rangeMarker.setGreedyToLeft(true);
<ide> rangeMarker.setGreedyToRight(true);
<ide> myRangeMarkers.put(info, rangeMarker); |
|
Java | apache-2.0 | 410affeb5f7dea1a45aa71662009db13dc733820 | 0 | idea4bsd/idea4bsd,FHannes/intellij-community,vvv1559/intellij-community,da1z/intellij-community,semonte/intellij-community,xfournet/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,apixandru/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,da1z/intellij-community,da1z/intellij-community,asedunov/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,da1z/intellij-community,signed/intellij-community,ibinti/intellij-community,allotria/intellij-community,youdonghai/intellij-community,signed/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,semonte/intellij-community,FHannes/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,allotria/intellij-community,semonte/intellij-community,FHannes/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,signed/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,FHannes/intellij-community,signed/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,signed/intellij-community,apixandru/intellij-community,da1z/intellij-community,ibinti/intellij-community,da1z/intellij-community,allotria/intellij-community,asedunov/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,semonte/intellij-community,xfournet/intellij-community,da1z/intellij-community,FHannes/intellij-community,apixandru/intellij-community,semonte/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,asedunov/intellij-community,asedunov/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,FHannes/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,apixandru/intellij-community,signed/intellij-community,apixandru/intellij-community,FHannes/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,xfournet/intellij-community,xfournet/intellij-community,apixandru/intellij-community,allotria/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,signed/intellij-community,xfournet/intellij-community,da1z/intellij-community,signed/intellij-community,apixandru/intellij-community,semonte/intellij-community,ibinti/intellij-community,allotria/intellij-community,semonte/intellij-community,allotria/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,allotria/intellij-community,ibinti/intellij-community,apixandru/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,signed/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,allotria/intellij-community,ibinti/intellij-community,da1z/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,semonte/intellij-community,FHannes/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,ibinti/intellij-community,ibinti/intellij-community,allotria/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.copy;
import com.intellij.codeInsight.actions.OptimizeImportsProcessor;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.ide.util.EditorHelper;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.JavaProjectRootsUtil;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.refactoring.MoveDestination;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.move.moveClassesOrPackages.MoveDirectoryWithClassesProcessor;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.*;
public class CopyClassesHandler extends CopyHandlerDelegateBase {
private static final Logger LOG = Logger.getInstance("#" + CopyClassesHandler.class.getName());
@Override
public boolean forbidToClone(PsiElement[] elements, boolean fromUpdate) {
final Map<PsiFile, PsiClass[]> fileMap = convertToTopLevelClasses(elements, fromUpdate, null, null);
if (fileMap != null && fileMap.size() == 1) {
final PsiClass[] psiClasses = fileMap.values().iterator().next();
return psiClasses != null && psiClasses.length > 1;
}
return true;
}
@Override
public boolean canCopy(PsiElement[] elements, boolean fromUpdate) {
return canCopyClass(fromUpdate, elements);
}
public static boolean canCopyClass(PsiElement... elements) {
return canCopyClass(false, elements);
}
public static boolean canCopyClass(boolean fromUpdate, PsiElement... elements) {
if (fromUpdate && elements.length > 0 && elements[0] instanceof PsiDirectory) return true;
return convertToTopLevelClasses(elements, fromUpdate, null, null) != null;
}
@Nullable
private static Map<PsiFile, PsiClass[]> convertToTopLevelClasses(final PsiElement[] elements,
final boolean fromUpdate,
String relativePath,
Map<PsiFile, String> relativeMap) {
final Map<PsiFile, PsiClass[]> result = new HashMap<>();
for (PsiElement element : elements) {
final PsiElement navigationElement = element.getNavigationElement();
LOG.assertTrue(navigationElement != null, element);
final PsiFile containingFile = navigationElement.getContainingFile();
if (!(containingFile instanceof PsiClassOwner &&
JavaProjectRootsUtil.isOutsideJavaSourceRoot(containingFile))) {
PsiClass[] topLevelClasses = getTopLevelClasses(element);
if (topLevelClasses == null) {
if (element instanceof PsiDirectory) {
if (!fromUpdate) {
final String name = ((PsiDirectory)element).getName();
final String path = relativePath != null ? (relativePath.length() > 0 ? (relativePath + "/") : "") + name : null;
final Map<PsiFile, PsiClass[]> map = convertToTopLevelClasses(element.getChildren(), fromUpdate, path, relativeMap);
if (map == null) return null;
for (Map.Entry<PsiFile, PsiClass[]> entry : map.entrySet()) {
fillResultsMap(result, entry.getKey(), entry.getValue());
}
}
continue;
}
if (!(element instanceof PsiFileSystemItem)) return null;
}
fillResultsMap(result, containingFile, topLevelClasses);
if (relativeMap != null) {
relativeMap.put(containingFile, relativePath);
}
}
}
if (result.isEmpty()) {
return null;
}
else {
boolean hasClasses = false;
for (PsiClass[] classes : result.values()) {
if (classes != null) {
hasClasses = true;
break;
}
}
return hasClasses ? result : null;
}
}
@Nullable
private static String normalizeRelativeMap(Map<PsiFile, String> relativeMap) {
String vector = null;
for (String relativePath : relativeMap.values()) {
if (vector == null) {
vector = relativePath;
} else if (vector.startsWith(relativePath + "/")) {
vector = relativePath;
} else if (!relativePath.startsWith(vector + "/") && !relativePath.equals(vector)) {
return null;
}
}
if (vector != null) {
for (PsiFile psiFile : relativeMap.keySet()) {
final String path = relativeMap.get(psiFile);
relativeMap.put(psiFile, path.equals(vector) ? "" : path.substring(vector.length() + 1));
}
}
return vector;
}
private static void fillResultsMap(Map<PsiFile, PsiClass[]> result, PsiFile containingFile, PsiClass[] topLevelClasses) {
PsiClass[] classes = result.get(containingFile);
if (topLevelClasses != null) {
if (classes != null) {
topLevelClasses = ArrayUtil.mergeArrays(classes, topLevelClasses, PsiClass.ARRAY_FACTORY);
}
result.put(containingFile, topLevelClasses);
} else {
result.put(containingFile, classes);
}
}
public void doCopy(PsiElement[] elements, PsiDirectory defaultTargetDirectory) {
FeatureUsageTracker.getInstance().triggerFeatureUsed("refactoring.copyClass");
final HashMap<PsiFile, String> relativePathsMap = new HashMap<>();
final Map<PsiFile, PsiClass[]> classes = convertToTopLevelClasses(elements, false, "", relativePathsMap);
assert classes != null;
if (defaultTargetDirectory == null) {
final PsiFile psiFile = classes.keySet().iterator().next();
defaultTargetDirectory = psiFile.getContainingDirectory();
LOG.assertTrue(defaultTargetDirectory != null, psiFile);
}
Project project = defaultTargetDirectory.getProject();
VirtualFile sourceRootForFile = ProjectRootManager.getInstance(project).getFileIndex().getSourceRootForFile(defaultTargetDirectory.getVirtualFile());
if (sourceRootForFile == null) {
final List<PsiElement> files = new ArrayList<>();
for (PsiElement element : elements) {
PsiFile containingFile = element.getContainingFile();
if (containingFile != null) {
files.add(containingFile);
}
else if (element instanceof PsiDirectory) {
files.add(element);
}
}
CopyFilesOrDirectoriesHandler.copyAsFiles(files.toArray(new PsiElement[files.size()]), defaultTargetDirectory, project);
return;
}
Object targetDirectory = null;
String className = null;
boolean openInEditor = true;
if (copyOneClass(classes)) {
final String commonPath =
ArrayUtilRt.find(elements, classes.values().iterator().next()) == -1 ? normalizeRelativeMap(relativePathsMap) : null;
CopyClassDialog dialog = new CopyClassDialog(classes.values().iterator().next()[0], defaultTargetDirectory, project, false) {
@Override
protected String getQualifiedName() {
final String qualifiedName = super.getQualifiedName();
if (commonPath != null && !commonPath.isEmpty() && !qualifiedName.endsWith(commonPath)) {
return StringUtil.getQualifiedName(qualifiedName, commonPath.replaceAll("/", "."));
}
return qualifiedName;
}
};
dialog.setTitle(RefactoringBundle.message("copy.handler.copy.class"));
if (dialog.showAndGet()) {
openInEditor = dialog.openInEditor();
targetDirectory = dialog.getTargetDirectory();
className = dialog.getClassName();
if (className == null || className.length() == 0) return;
}
} else {
if (ApplicationManager.getApplication().isUnitTestMode()) {
targetDirectory = defaultTargetDirectory;
} else {
defaultTargetDirectory = CopyFilesOrDirectoriesHandler.resolveDirectory(defaultTargetDirectory);
if (defaultTargetDirectory == null) return;
PsiElement[] files = PsiUtilCore.toPsiFileArray(classes.keySet());
if (classes.keySet().size() == 1) {
//do not choose a new name for a file when multiple classes exist in one file
final PsiClass[] psiClasses = classes.values().iterator().next();
if (psiClasses != null) {
files = psiClasses;
}
}
final CopyFilesOrDirectoriesDialog dialog = new CopyFilesOrDirectoriesDialog(files, defaultTargetDirectory, project, false);
if (dialog.showAndGet()) {
targetDirectory = dialog.getTargetDirectory();
className = dialog.getNewName();
openInEditor = dialog.openInEditor();
}
}
}
if (targetDirectory != null) {
copyClassesImpl(className, project, classes, relativePathsMap, targetDirectory, defaultTargetDirectory, RefactoringBundle.message(
"copy.handler.copy.class"), false, openInEditor);
}
}
private static boolean copyOneClass(Map<PsiFile, PsiClass[]> classes) {
if (classes.size() == 1){
final PsiClass[] psiClasses = classes.values().iterator().next();
return psiClasses != null && psiClasses.length == 1;
}
return false;
}
public void doClone(PsiElement element) {
FeatureUsageTracker.getInstance().triggerFeatureUsed("refactoring.copyClass");
PsiClass[] classes = getTopLevelClasses(element);
if (classes == null) {
CopyFilesOrDirectoriesHandler.doCloneFile(element);
return;
}
Project project = element.getProject();
CopyClassDialog dialog = new CopyClassDialog(classes[0], null, project, true);
dialog.setTitle(RefactoringBundle.message("copy.handler.clone.class"));
if (dialog.showAndGet()) {
String className = dialog.getClassName();
PsiDirectory targetDirectory = element.getContainingFile().getContainingDirectory();
copyClassesImpl(className, project, Collections.singletonMap(classes[0].getContainingFile(), classes), null, targetDirectory,
targetDirectory, RefactoringBundle.message("copy.handler.clone.class"), true, true);
}
}
private static void copyClassesImpl(final String copyClassName,
final Project project,
final Map<PsiFile, PsiClass[]> classes,
final HashMap<PsiFile, String> map,
final Object targetDirectory,
final PsiDirectory defaultTargetDirectory,
final String commandName,
final boolean selectInActivePanel,
final boolean openInEditor) {
final boolean[] result = new boolean[] {false};
Runnable command = () -> {
final Runnable action = () -> {
try {
PsiDirectory target;
if (targetDirectory instanceof PsiDirectory) {
target = (PsiDirectory)targetDirectory;
} else {
target = ((MoveDestination)targetDirectory).getTargetDirectory(defaultTargetDirectory);
}
Collection<PsiFile> files = doCopyClasses(classes, map, copyClassName, target, project);
if (files != null) {
if (openInEditor) {
for (PsiFile file : files) {
CopyHandler.updateSelectionInActiveProjectView(file, project, selectInActivePanel);
}
EditorHelper.openFilesInEditor(files.toArray(new PsiFile[files.size()]));
}
result[0] = true;
}
}
catch (final IncorrectOperationException ex) {
ApplicationManager.getApplication().invokeLater(
() -> Messages.showMessageDialog(project, ex.getMessage(), RefactoringBundle.message("error.title"), Messages.getErrorIcon()));
}
};
ApplicationManager.getApplication().runWriteAction(action);
};
CommandProcessor processor = CommandProcessor.getInstance();
processor.executeCommand(project, command, commandName, null);
if (result[0]) {
ToolWindowManager.getInstance(project).invokeLater(() -> ToolWindowManager.getInstance(project).activateEditorComponent());
}
}
@Nullable
public static Collection<PsiFile> doCopyClasses(final Map<PsiFile, PsiClass[]> fileToClasses,
final String copyClassName,
final PsiDirectory targetDirectory,
final Project project) throws IncorrectOperationException {
return doCopyClasses(fileToClasses, null, copyClassName, targetDirectory, project);
}
@Nullable
public static Collection<PsiFile> doCopyClasses(final Map<PsiFile, PsiClass[]> fileToClasses,
@Nullable HashMap<PsiFile, String> map, final String copyClassName,
final PsiDirectory targetDirectory,
final Project project) throws IncorrectOperationException {
PsiElement newElement = null;
final Map<PsiClass, PsiElement> oldToNewMap = new HashMap<>();
for (final PsiClass[] psiClasses : fileToClasses.values()) {
if (psiClasses != null) {
for (PsiClass aClass : psiClasses) {
if (isSynthetic(aClass)) {
continue;
}
oldToNewMap.put(aClass, null);
}
}
}
final List<PsiFile> createdFiles = new ArrayList<>(fileToClasses.size());
int[] choice = fileToClasses.size() > 1 ? new int[]{-1} : null;
List<PsiFile> files = new ArrayList<>();
for (final Map.Entry<PsiFile, PsiClass[]> entry : fileToClasses.entrySet()) {
final PsiFile psiFile = entry.getKey();
final PsiClass[] sources = entry.getValue();
if (psiFile instanceof PsiClassOwner && sources != null) {
final PsiFile createdFile = copy(psiFile, targetDirectory, copyClassName, map == null ? null : map.get(psiFile), choice);
if (createdFile == null) {
//do not touch unmodified classes
for (PsiClass aClass : ((PsiClassOwner)psiFile).getClasses()) {
oldToNewMap.remove(aClass);
}
continue;
}
for (final PsiClass destination : ((PsiClassOwner)createdFile).getClasses()) {
if (isSynthetic(destination)) {
continue;
}
PsiClass source = findByName(sources, destination.getName());
if (source != null) {
final PsiClass copy = copy(source, copyClassName);
newElement = destination.replace(copy);
oldToNewMap.put(source, newElement);
}
else {
destination.delete();
}
}
createdFiles.add(createdFile);
} else {
files.add(psiFile);
}
}
for (PsiFile file : files) {
try {
PsiDirectory finalTarget = targetDirectory;
final String relativePath = map != null ? map.get(file) : null;
if (relativePath != null && !relativePath.isEmpty()) {
finalTarget = buildRelativeDir(targetDirectory, relativePath).findOrCreateTargetDirectory();
}
final PsiFile fileCopy = CopyFilesOrDirectoriesHandler.copyToDirectory(file, getNewFileName(file, copyClassName), finalTarget, choice);
if (fileCopy != null) {
createdFiles.add(fileCopy);
}
}
catch (IOException e) {
throw new IncorrectOperationException(e.getMessage());
}
}
final Set<PsiElement> rebindExpressions = new HashSet<>();
for (PsiElement element : oldToNewMap.values()) {
if (element == null) {
LOG.error(oldToNewMap.keySet());
continue;
}
decodeRefs(element, oldToNewMap, rebindExpressions);
}
final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
for (PsiFile psiFile : createdFiles) {
if (psiFile instanceof PsiJavaFile) {
codeStyleManager.removeRedundantImports((PsiJavaFile)psiFile);
}
}
for (PsiElement expression : rebindExpressions) {
//filter out invalid elements which are produced by nested elements:
//new expressions/type elements, like: List<List<String>>; new Foo(new Foo()), etc
if (expression.isValid()){
codeStyleManager.shortenClassReferences(expression);
}
}
new OptimizeImportsProcessor(project, createdFiles.toArray(new PsiFile[createdFiles.size()]), null).run();
return createdFiles;
}
protected static boolean isSynthetic(PsiClass aClass) {
return aClass instanceof SyntheticElement || !aClass.isPhysical();
}
private static PsiFile copy(@NotNull PsiFile file, PsiDirectory directory, String name, String relativePath, int[] choice) {
final String fileName = getNewFileName(file, name);
if (relativePath != null && !relativePath.isEmpty()) {
return buildRelativeDir(directory, relativePath).findOrCreateTargetDirectory().copyFileFrom(fileName, file);
}
if (CopyFilesOrDirectoriesHandler.checkFileExist(directory, choice, file, fileName, "Copy")) return null;
return directory.copyFileFrom(fileName, file);
}
private static String getNewFileName(PsiFile file, String name) {
if (name != null) {
if (file instanceof PsiClassOwner) {
for (final PsiClass psiClass : ((PsiClassOwner)file).getClasses()) {
if (!isSynthetic(psiClass)) {
return name + "." + file.getViewProvider().getVirtualFile().getExtension();
}
}
}
return name;
}
return file.getName();
}
@NotNull
private static MoveDirectoryWithClassesProcessor.TargetDirectoryWrapper buildRelativeDir(final @NotNull PsiDirectory directory,
final @NotNull String relativePath) {
MoveDirectoryWithClassesProcessor.TargetDirectoryWrapper current = null;
for (String pathElement : relativePath.split("/")) {
if (current == null) {
current = new MoveDirectoryWithClassesProcessor.TargetDirectoryWrapper(directory, pathElement);
} else {
current = new MoveDirectoryWithClassesProcessor.TargetDirectoryWrapper(current, pathElement);
}
}
LOG.assertTrue(current != null);
return current;
}
private static PsiClass copy(PsiClass aClass, String name) {
final PsiClass classNavigationElement = (PsiClass)aClass.getNavigationElement();
final PsiClass classCopy = (PsiClass)classNavigationElement.copy();
if (name != null) {
classCopy.setName(name);
}
return classCopy;
}
@Nullable
private static PsiClass findByName(PsiClass[] classes, String name) {
if (name != null) {
for (PsiClass aClass : classes) {
if (name.equals(aClass.getName())) {
return aClass;
}
}
}
return null;
}
private static void rebindExternalReferences(PsiElement element,
Map<PsiClass, PsiElement> oldToNewMap,
Set<PsiElement> rebindExpressions) {
final LocalSearchScope searchScope = new LocalSearchScope(element);
for (PsiClass aClass : oldToNewMap.keySet()) {
final PsiElement newClass = oldToNewMap.get(aClass);
for (PsiReference reference : ReferencesSearch.search(aClass, searchScope)) {
rebindExpressions.add(reference.bindToElement(newClass));
}
}
}
private static void decodeRefs(@NotNull PsiElement element, final Map<PsiClass, PsiElement> oldToNewMap, final Set<PsiElement> rebindExpressions) {
final Map<PsiJavaCodeReferenceElement, PsiElement> rebindMap = new LinkedHashMap<>();
element.accept(new JavaRecursiveElementVisitor(){
@Override
public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
super.visitReferenceElement(reference);
decodeRef(reference, oldToNewMap, rebindMap);
}
});
for (Map.Entry<PsiJavaCodeReferenceElement, PsiElement> entry : rebindMap.entrySet()) {
rebindExpressions.add(entry.getKey().bindToElement(entry.getValue()));
}
rebindExternalReferences(element, oldToNewMap, rebindExpressions);
}
private static void decodeRef(final PsiJavaCodeReferenceElement expression,
final Map<PsiClass, PsiElement> oldToNewMap,
Map<PsiJavaCodeReferenceElement, PsiElement> rebindExpressions) {
final PsiElement resolved = expression.resolve();
if (resolved instanceof PsiClass) {
final PsiClass psiClass = (PsiClass)resolved;
if (oldToNewMap.containsKey(psiClass)) {
rebindExpressions.put(expression, oldToNewMap.get(psiClass));
}
}
}
@Nullable
private static PsiClass[] getTopLevelClasses(PsiElement element) {
while (true) {
if (element == null || element instanceof PsiFile) break;
if (element instanceof PsiClass && element.getParent() != null && ((PsiClass)element).getContainingClass() == null && !(element instanceof PsiAnonymousClass)) break;
element = element.getParent();
}
//if (element instanceof PsiCompiledElement) return null;
if (element instanceof PsiClassOwner) {
PsiClass[] classes = ((PsiClassOwner)element).getClasses();
ArrayList<PsiClass> buffer = new ArrayList<>();
for (final PsiClass aClass : classes) {
if (isSynthetic(aClass)) {
return null;
}
buffer.add(aClass);
}
return buffer.toArray(new PsiClass[buffer.size()]);
}
return element instanceof PsiClass ? new PsiClass[]{(PsiClass)element} : null;
}
}
| java/java-impl/src/com/intellij/refactoring/copy/CopyClassesHandler.java | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.copy;
import com.intellij.codeInsight.actions.OptimizeImportsProcessor;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.ide.util.EditorHelper;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.JavaProjectRootsUtil;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.refactoring.MoveDestination;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.move.moveClassesOrPackages.MoveDirectoryWithClassesProcessor;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.*;
public class CopyClassesHandler extends CopyHandlerDelegateBase {
private static final Logger LOG = Logger.getInstance("#" + CopyClassesHandler.class.getName());
@Override
public boolean forbidToClone(PsiElement[] elements, boolean fromUpdate) {
final Map<PsiFile, PsiClass[]> fileMap = convertToTopLevelClasses(elements, fromUpdate, null, null);
if (fileMap != null && fileMap.size() == 1) {
final PsiClass[] psiClasses = fileMap.values().iterator().next();
return psiClasses != null && psiClasses.length > 1;
}
return true;
}
@Override
public boolean canCopy(PsiElement[] elements, boolean fromUpdate) {
return canCopyClass(fromUpdate, elements);
}
public static boolean canCopyClass(PsiElement... elements) {
return canCopyClass(false, elements);
}
public static boolean canCopyClass(boolean fromUpdate, PsiElement... elements) {
if (fromUpdate && elements.length > 0 && elements[0] instanceof PsiDirectory) return true;
return convertToTopLevelClasses(elements, fromUpdate, null, null) != null;
}
@Nullable
private static Map<PsiFile, PsiClass[]> convertToTopLevelClasses(final PsiElement[] elements,
final boolean fromUpdate,
String relativePath,
Map<PsiFile, String> relativeMap) {
final Map<PsiFile, PsiClass[]> result = new HashMap<>();
for (PsiElement element : elements) {
final PsiElement navigationElement = element.getNavigationElement();
LOG.assertTrue(navigationElement != null, element);
final PsiFile containingFile = navigationElement.getContainingFile();
if (!(containingFile instanceof PsiClassOwner &&
JavaProjectRootsUtil.isOutsideJavaSourceRoot(containingFile))) {
PsiClass[] topLevelClasses = getTopLevelClasses(element);
if (topLevelClasses == null) {
if (element instanceof PsiDirectory) {
if (!fromUpdate) {
final String name = ((PsiDirectory)element).getName();
final String path = relativePath != null ? (relativePath.length() > 0 ? (relativePath + "/") : "") + name : null;
final Map<PsiFile, PsiClass[]> map = convertToTopLevelClasses(element.getChildren(), fromUpdate, path, relativeMap);
if (map == null) return null;
for (Map.Entry<PsiFile, PsiClass[]> entry : map.entrySet()) {
fillResultsMap(result, entry.getKey(), entry.getValue());
}
}
continue;
}
if (!(element instanceof PsiFileSystemItem)) return null;
}
fillResultsMap(result, containingFile, topLevelClasses);
if (relativeMap != null) {
relativeMap.put(containingFile, relativePath);
}
}
}
if (result.isEmpty()) {
return null;
}
else {
boolean hasClasses = false;
for (PsiClass[] classes : result.values()) {
if (classes != null) {
hasClasses = true;
break;
}
}
return hasClasses ? result : null;
}
}
@Nullable
private static String normalizeRelativeMap(Map<PsiFile, String> relativeMap) {
String vector = null;
for (String relativePath : relativeMap.values()) {
if (vector == null) {
vector = relativePath;
} else if (vector.startsWith(relativePath + "/")) {
vector = relativePath;
} else if (!relativePath.startsWith(vector + "/") && !relativePath.equals(vector)) {
return null;
}
}
if (vector != null) {
for (PsiFile psiFile : relativeMap.keySet()) {
final String path = relativeMap.get(psiFile);
relativeMap.put(psiFile, path.equals(vector) ? "" : path.substring(vector.length() + 1));
}
}
return vector;
}
private static void fillResultsMap(Map<PsiFile, PsiClass[]> result, PsiFile containingFile, PsiClass[] topLevelClasses) {
PsiClass[] classes = result.get(containingFile);
if (topLevelClasses != null) {
if (classes != null) {
topLevelClasses = ArrayUtil.mergeArrays(classes, topLevelClasses, PsiClass.ARRAY_FACTORY);
}
result.put(containingFile, topLevelClasses);
} else {
result.put(containingFile, classes);
}
}
public void doCopy(PsiElement[] elements, PsiDirectory defaultTargetDirectory) {
FeatureUsageTracker.getInstance().triggerFeatureUsed("refactoring.copyClass");
final HashMap<PsiFile, String> relativePathsMap = new HashMap<>();
final Map<PsiFile, PsiClass[]> classes = convertToTopLevelClasses(elements, false, "", relativePathsMap);
assert classes != null;
if (defaultTargetDirectory == null) {
final PsiFile psiFile = classes.keySet().iterator().next();
defaultTargetDirectory = psiFile.getContainingDirectory();
LOG.assertTrue(defaultTargetDirectory != null, psiFile);
} else {
Project project = defaultTargetDirectory.getProject();
VirtualFile sourceRootForFile = ProjectRootManager.getInstance(project).getFileIndex()
.getSourceRootForFile(defaultTargetDirectory.getVirtualFile());
if (sourceRootForFile == null) {
final List<PsiElement> files = new ArrayList<>();
for (int i = 0, elementsLength = elements.length; i < elementsLength; i++) {
PsiFile containingFile = elements[i].getContainingFile();
if (containingFile != null) {
files.add(containingFile);
} else if (elements[i] instanceof PsiDirectory) {
files.add(elements[i]);
}
}
CopyFilesOrDirectoriesHandler.copyAsFiles(files.toArray(new PsiElement[files.size()]), defaultTargetDirectory, project);
return;
}
}
Project project = defaultTargetDirectory.getProject();
Object targetDirectory = null;
String className = null;
boolean openInEditor = true;
if (copyOneClass(classes)) {
final String commonPath =
ArrayUtilRt.find(elements, classes.values().iterator().next()) == -1 ? normalizeRelativeMap(relativePathsMap) : null;
CopyClassDialog dialog = new CopyClassDialog(classes.values().iterator().next()[0], defaultTargetDirectory, project, false) {
@Override
protected String getQualifiedName() {
final String qualifiedName = super.getQualifiedName();
if (commonPath != null && !commonPath.isEmpty() && !qualifiedName.endsWith(commonPath)) {
return StringUtil.getQualifiedName(qualifiedName, commonPath.replaceAll("/", "."));
}
return qualifiedName;
}
};
dialog.setTitle(RefactoringBundle.message("copy.handler.copy.class"));
if (dialog.showAndGet()) {
openInEditor = dialog.openInEditor();
targetDirectory = dialog.getTargetDirectory();
className = dialog.getClassName();
if (className == null || className.length() == 0) return;
}
} else {
if (ApplicationManager.getApplication().isUnitTestMode()) {
targetDirectory = defaultTargetDirectory;
} else {
defaultTargetDirectory = CopyFilesOrDirectoriesHandler.resolveDirectory(defaultTargetDirectory);
if (defaultTargetDirectory == null) return;
PsiElement[] files = PsiUtilCore.toPsiFileArray(classes.keySet());
if (classes.keySet().size() == 1) {
//do not choose a new name for a file when multiple classes exist in one file
final PsiClass[] psiClasses = classes.values().iterator().next();
if (psiClasses != null) {
files = psiClasses;
}
}
final CopyFilesOrDirectoriesDialog dialog = new CopyFilesOrDirectoriesDialog(files, defaultTargetDirectory, project, false);
if (dialog.showAndGet()) {
targetDirectory = dialog.getTargetDirectory();
className = dialog.getNewName();
openInEditor = dialog.openInEditor();
}
}
}
if (targetDirectory != null) {
copyClassesImpl(className, project, classes, relativePathsMap, targetDirectory, defaultTargetDirectory, RefactoringBundle.message(
"copy.handler.copy.class"), false, openInEditor);
}
}
private static boolean copyOneClass(Map<PsiFile, PsiClass[]> classes) {
if (classes.size() == 1){
final PsiClass[] psiClasses = classes.values().iterator().next();
return psiClasses != null && psiClasses.length == 1;
}
return false;
}
public void doClone(PsiElement element) {
FeatureUsageTracker.getInstance().triggerFeatureUsed("refactoring.copyClass");
PsiClass[] classes = getTopLevelClasses(element);
if (classes == null) {
CopyFilesOrDirectoriesHandler.doCloneFile(element);
return;
}
Project project = element.getProject();
CopyClassDialog dialog = new CopyClassDialog(classes[0], null, project, true);
dialog.setTitle(RefactoringBundle.message("copy.handler.clone.class"));
if (dialog.showAndGet()) {
String className = dialog.getClassName();
PsiDirectory targetDirectory = element.getContainingFile().getContainingDirectory();
copyClassesImpl(className, project, Collections.singletonMap(classes[0].getContainingFile(), classes), null, targetDirectory,
targetDirectory, RefactoringBundle.message("copy.handler.clone.class"), true, true);
}
}
private static void copyClassesImpl(final String copyClassName,
final Project project,
final Map<PsiFile, PsiClass[]> classes,
final HashMap<PsiFile, String> map,
final Object targetDirectory,
final PsiDirectory defaultTargetDirectory,
final String commandName,
final boolean selectInActivePanel,
final boolean openInEditor) {
final boolean[] result = new boolean[] {false};
Runnable command = () -> {
final Runnable action = () -> {
try {
PsiDirectory target;
if (targetDirectory instanceof PsiDirectory) {
target = (PsiDirectory)targetDirectory;
} else {
target = ((MoveDestination)targetDirectory).getTargetDirectory(defaultTargetDirectory);
}
Collection<PsiFile> files = doCopyClasses(classes, map, copyClassName, target, project);
if (files != null) {
if (openInEditor) {
for (PsiFile file : files) {
CopyHandler.updateSelectionInActiveProjectView(file, project, selectInActivePanel);
}
EditorHelper.openFilesInEditor(files.toArray(new PsiFile[files.size()]));
}
result[0] = true;
}
}
catch (final IncorrectOperationException ex) {
ApplicationManager.getApplication().invokeLater(
() -> Messages.showMessageDialog(project, ex.getMessage(), RefactoringBundle.message("error.title"), Messages.getErrorIcon()));
}
};
ApplicationManager.getApplication().runWriteAction(action);
};
CommandProcessor processor = CommandProcessor.getInstance();
processor.executeCommand(project, command, commandName, null);
if (result[0]) {
ToolWindowManager.getInstance(project).invokeLater(() -> ToolWindowManager.getInstance(project).activateEditorComponent());
}
}
@Nullable
public static Collection<PsiFile> doCopyClasses(final Map<PsiFile, PsiClass[]> fileToClasses,
final String copyClassName,
final PsiDirectory targetDirectory,
final Project project) throws IncorrectOperationException {
return doCopyClasses(fileToClasses, null, copyClassName, targetDirectory, project);
}
@Nullable
public static Collection<PsiFile> doCopyClasses(final Map<PsiFile, PsiClass[]> fileToClasses,
@Nullable HashMap<PsiFile, String> map, final String copyClassName,
final PsiDirectory targetDirectory,
final Project project) throws IncorrectOperationException {
PsiElement newElement = null;
final Map<PsiClass, PsiElement> oldToNewMap = new HashMap<>();
for (final PsiClass[] psiClasses : fileToClasses.values()) {
if (psiClasses != null) {
for (PsiClass aClass : psiClasses) {
if (isSynthetic(aClass)) {
continue;
}
oldToNewMap.put(aClass, null);
}
}
}
final List<PsiFile> createdFiles = new ArrayList<>(fileToClasses.size());
int[] choice = fileToClasses.size() > 1 ? new int[]{-1} : null;
List<PsiFile> files = new ArrayList<>();
for (final Map.Entry<PsiFile, PsiClass[]> entry : fileToClasses.entrySet()) {
final PsiFile psiFile = entry.getKey();
final PsiClass[] sources = entry.getValue();
if (psiFile instanceof PsiClassOwner && sources != null) {
final PsiFile createdFile = copy(psiFile, targetDirectory, copyClassName, map == null ? null : map.get(psiFile), choice);
if (createdFile == null) {
//do not touch unmodified classes
for (PsiClass aClass : ((PsiClassOwner)psiFile).getClasses()) {
oldToNewMap.remove(aClass);
}
continue;
}
for (final PsiClass destination : ((PsiClassOwner)createdFile).getClasses()) {
if (isSynthetic(destination)) {
continue;
}
PsiClass source = findByName(sources, destination.getName());
if (source != null) {
final PsiClass copy = copy(source, copyClassName);
newElement = destination.replace(copy);
oldToNewMap.put(source, newElement);
}
else {
destination.delete();
}
}
createdFiles.add(createdFile);
} else {
files.add(psiFile);
}
}
for (PsiFile file : files) {
try {
PsiDirectory finalTarget = targetDirectory;
final String relativePath = map != null ? map.get(file) : null;
if (relativePath != null && !relativePath.isEmpty()) {
finalTarget = buildRelativeDir(targetDirectory, relativePath).findOrCreateTargetDirectory();
}
final PsiFile fileCopy = CopyFilesOrDirectoriesHandler.copyToDirectory(file, getNewFileName(file, copyClassName), finalTarget, choice);
if (fileCopy != null) {
createdFiles.add(fileCopy);
}
}
catch (IOException e) {
throw new IncorrectOperationException(e.getMessage());
}
}
final Set<PsiElement> rebindExpressions = new HashSet<>();
for (PsiElement element : oldToNewMap.values()) {
if (element == null) {
LOG.error(oldToNewMap.keySet());
continue;
}
decodeRefs(element, oldToNewMap, rebindExpressions);
}
final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
for (PsiFile psiFile : createdFiles) {
if (psiFile instanceof PsiJavaFile) {
codeStyleManager.removeRedundantImports((PsiJavaFile)psiFile);
}
}
for (PsiElement expression : rebindExpressions) {
//filter out invalid elements which are produced by nested elements:
//new expressions/type elements, like: List<List<String>>; new Foo(new Foo()), etc
if (expression.isValid()){
codeStyleManager.shortenClassReferences(expression);
}
}
new OptimizeImportsProcessor(project, createdFiles.toArray(new PsiFile[createdFiles.size()]), null).run();
return createdFiles;
}
protected static boolean isSynthetic(PsiClass aClass) {
return aClass instanceof SyntheticElement || !aClass.isPhysical();
}
private static PsiFile copy(@NotNull PsiFile file, PsiDirectory directory, String name, String relativePath, int[] choice) {
final String fileName = getNewFileName(file, name);
if (relativePath != null && !relativePath.isEmpty()) {
return buildRelativeDir(directory, relativePath).findOrCreateTargetDirectory().copyFileFrom(fileName, file);
}
if (CopyFilesOrDirectoriesHandler.checkFileExist(directory, choice, file, fileName, "Copy")) return null;
return directory.copyFileFrom(fileName, file);
}
private static String getNewFileName(PsiFile file, String name) {
if (name != null) {
if (file instanceof PsiClassOwner) {
for (final PsiClass psiClass : ((PsiClassOwner)file).getClasses()) {
if (!isSynthetic(psiClass)) {
return name + "." + file.getViewProvider().getVirtualFile().getExtension();
}
}
}
return name;
}
return file.getName();
}
@NotNull
private static MoveDirectoryWithClassesProcessor.TargetDirectoryWrapper buildRelativeDir(final @NotNull PsiDirectory directory,
final @NotNull String relativePath) {
MoveDirectoryWithClassesProcessor.TargetDirectoryWrapper current = null;
for (String pathElement : relativePath.split("/")) {
if (current == null) {
current = new MoveDirectoryWithClassesProcessor.TargetDirectoryWrapper(directory, pathElement);
} else {
current = new MoveDirectoryWithClassesProcessor.TargetDirectoryWrapper(current, pathElement);
}
}
LOG.assertTrue(current != null);
return current;
}
private static PsiClass copy(PsiClass aClass, String name) {
final PsiClass classNavigationElement = (PsiClass)aClass.getNavigationElement();
final PsiClass classCopy = (PsiClass)classNavigationElement.copy();
if (name != null) {
classCopy.setName(name);
}
return classCopy;
}
@Nullable
private static PsiClass findByName(PsiClass[] classes, String name) {
if (name != null) {
for (PsiClass aClass : classes) {
if (name.equals(aClass.getName())) {
return aClass;
}
}
}
return null;
}
private static void rebindExternalReferences(PsiElement element,
Map<PsiClass, PsiElement> oldToNewMap,
Set<PsiElement> rebindExpressions) {
final LocalSearchScope searchScope = new LocalSearchScope(element);
for (PsiClass aClass : oldToNewMap.keySet()) {
final PsiElement newClass = oldToNewMap.get(aClass);
for (PsiReference reference : ReferencesSearch.search(aClass, searchScope)) {
rebindExpressions.add(reference.bindToElement(newClass));
}
}
}
private static void decodeRefs(@NotNull PsiElement element, final Map<PsiClass, PsiElement> oldToNewMap, final Set<PsiElement> rebindExpressions) {
final Map<PsiJavaCodeReferenceElement, PsiElement> rebindMap = new LinkedHashMap<>();
element.accept(new JavaRecursiveElementVisitor(){
@Override
public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
super.visitReferenceElement(reference);
decodeRef(reference, oldToNewMap, rebindMap);
}
});
for (Map.Entry<PsiJavaCodeReferenceElement, PsiElement> entry : rebindMap.entrySet()) {
rebindExpressions.add(entry.getKey().bindToElement(entry.getValue()));
}
rebindExternalReferences(element, oldToNewMap, rebindExpressions);
}
private static void decodeRef(final PsiJavaCodeReferenceElement expression,
final Map<PsiClass, PsiElement> oldToNewMap,
Map<PsiJavaCodeReferenceElement, PsiElement> rebindExpressions) {
final PsiElement resolved = expression.resolve();
if (resolved instanceof PsiClass) {
final PsiClass psiClass = (PsiClass)resolved;
if (oldToNewMap.containsKey(psiClass)) {
rebindExpressions.put(expression, oldToNewMap.get(psiClass));
}
}
}
@Nullable
private static PsiClass[] getTopLevelClasses(PsiElement element) {
while (true) {
if (element == null || element instanceof PsiFile) break;
if (element instanceof PsiClass && element.getParent() != null && ((PsiClass)element).getContainingClass() == null && !(element instanceof PsiAnonymousClass)) break;
element = element.getParent();
}
//if (element instanceof PsiCompiledElement) return null;
if (element instanceof PsiClassOwner) {
PsiClass[] classes = ((PsiClassOwner)element).getClasses();
ArrayList<PsiClass> buffer = new ArrayList<>();
for (final PsiClass aClass : classes) {
if (isSynthetic(aClass)) {
return null;
}
buffer.add(aClass);
}
return buffer.toArray(new PsiClass[buffer.size()]);
}
return element instanceof PsiClass ? new PsiClass[]{(PsiClass)element} : null;
}
}
| disable copy classes outside source roots
| java/java-impl/src/com/intellij/refactoring/copy/CopyClassesHandler.java | disable copy classes outside source roots | <ide><path>ava/java-impl/src/com/intellij/refactoring/copy/CopyClassesHandler.java
<ide> final PsiFile psiFile = classes.keySet().iterator().next();
<ide> defaultTargetDirectory = psiFile.getContainingDirectory();
<ide> LOG.assertTrue(defaultTargetDirectory != null, psiFile);
<del> } else {
<del> Project project = defaultTargetDirectory.getProject();
<del> VirtualFile sourceRootForFile = ProjectRootManager.getInstance(project).getFileIndex()
<del> .getSourceRootForFile(defaultTargetDirectory.getVirtualFile());
<del> if (sourceRootForFile == null) {
<del> final List<PsiElement> files = new ArrayList<>();
<del> for (int i = 0, elementsLength = elements.length; i < elementsLength; i++) {
<del> PsiFile containingFile = elements[i].getContainingFile();
<del> if (containingFile != null) {
<del> files.add(containingFile);
<del> } else if (elements[i] instanceof PsiDirectory) {
<del> files.add(elements[i]);
<del> }
<del> }
<del> CopyFilesOrDirectoriesHandler.copyAsFiles(files.toArray(new PsiElement[files.size()]), defaultTargetDirectory, project);
<del> return;
<del> }
<ide> }
<ide> Project project = defaultTargetDirectory.getProject();
<add> VirtualFile sourceRootForFile = ProjectRootManager.getInstance(project).getFileIndex().getSourceRootForFile(defaultTargetDirectory.getVirtualFile());
<add> if (sourceRootForFile == null) {
<add> final List<PsiElement> files = new ArrayList<>();
<add> for (PsiElement element : elements) {
<add> PsiFile containingFile = element.getContainingFile();
<add> if (containingFile != null) {
<add> files.add(containingFile);
<add> }
<add> else if (element instanceof PsiDirectory) {
<add> files.add(element);
<add> }
<add> }
<add> CopyFilesOrDirectoriesHandler.copyAsFiles(files.toArray(new PsiElement[files.size()]), defaultTargetDirectory, project);
<add> return;
<add> }
<ide> Object targetDirectory = null;
<ide> String className = null;
<ide> boolean openInEditor = true; |
|
Java | apache-2.0 | 5e114029b0ea8580aa5102cc68c1386aa36ba9ed | 0 | apache/solr,apache/solr,apache/solr,apache/solr,apache/solr | package org.apache.lucene.document;
/**
* 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.io.Reader;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.NumericTokenStream;
import org.apache.lucene.util.NumericUtils;
import org.apache.lucene.search.NumericRangeQuery; // javadocs
import org.apache.lucene.search.NumericRangeFilter; // javadocs
import org.apache.lucene.search.SortField; // javadocs
import org.apache.lucene.search.FieldCache; // javadocs
/**
* <p>This class provides a {@link Field} that enables indexing
* of numeric values for efficient range filtering and
* sorting. Here's an example usage, adding an int value:
* <pre>
* document.add(new NumericField(name).setIntValue(value));
* </pre>
*
* For optimal performance, re-use the
* <code>NumericField</code> and {@link Document} instance for more than
* one document:
*
* <pre>
* NumericField field = new NumericField(name);
* Document document = new Document();
* document.add(field);
*
* for(all documents) {
* ...
* field.setIntValue(value)
* writer.addDocument(document);
* ...
* }
* </pre>
*
* <p>The java native types <code>int</code>, <code>long</code>,
* <code>float</code> and <code>double</code> are
* directly supported. However, any value that can be
* converted into these native types can also be indexed.
* For example, date/time values represented by a
* {@link java.util.Date} can be translated into a long
* value using the {@link java.util.Date#getTime} method. If you
* don't need millisecond precision, you can quantize the
* value, either by dividing the result of
* {@link java.util.Date#getTime} or using the separate getters
* (for year, month, etc.) to construct an <code>int</code> or
* <code>long</code> value.</p>
*
* <p>To perform range querying or filtering against a
* <code>NumericField</code>, use {@link NumericRangeQuery} or {@link
* NumericRangeFilter}. To sort according to a
* <code>NumericField</code>, use the normal numeric sort types, eg
* {@link SortField#INT} (note that {@link SortField#AUTO}
* will not work with these fields). <code>NumericField</code> values
* can also be loaded directly from {@link FieldCache}.</p>
*
* <p>By default, a <code>NumericField</code>'s value is not stored but
* is indexed for range filtering and sorting. You can use
* the {@link #NumericField(String,Field.Store,boolean)}
* constructor if you need to change these defaults.</p>
*
* <p>You may add the same field name as a <code>NumericField</code> to
* the same document more than once. Range querying and
* filtering will be the logical OR of all values; so a range query
* will hit all documents that have at least one value in
* the range. However sort behavior is not defined. If you need to sort,
* you should separately index a single-valued <code>NumericField</code>.</p>
*
* <p>A <code>NumericField</code> will consume somewhat more disk space
* in the index than an ordinary single-valued field.
* However, for a typical index that includes substantial
* textual content per document, this increase will likely
* be in the noise. </p>
*
* <p>Within Lucene, each numeric value is indexed as a
* <em>trie</em> structure, where each term is logically
* assigned to larger and larger pre-defined brackets (which
* are simply lower-precision representations of the value).
* The step size between each successive bracket is called the
* <code>precisionStep</code>, measured in bits. Smaller
* <code>precisionStep</code> values result in larger number
* of brackets, which consumes more disk space in the index
* but may result in faster range search performance. The
* default value, 4, was selected for a reasonable tradeoff
* of disk space consumption versus performance. You can
* use the expert constructor {@link
* #NumericField(String,int,Field.Store,boolean)} if you'd
* like to change the value. Note that you must also
* specify a congruent value when creating {@link
* NumericRangeQuery} or {@link NumericRangeFilter}.
* For low cardinality fields larger precision steps are good.
* If the cardinality is < 100, it is fair
* to use {@link Integer#MAX_VALUE}, which produces one
* term per value.
*
* <p>For more information on the internals of numeric trie
* indexing, including the <a
* href="../search/NumericRangeQuery.html#precisionStepDesc"><code>precisionStep</code></a>
* configuration, see {@link NumericRangeQuery}. The format of
* indexed values is described in {@link NumericUtils}.
*
* <p>If you only need to sort by numeric value, and never
* run range querying/filtering, you can index using a
* <code>precisionStep</code> of {@link Integer#MAX_VALUE}.
* This will minimize disk space consumed. </p>
*
* <p>More advanced users can instead use {@link
* NumericTokenStream} directly, when indexing numbers. This
* class is a wrapper around this token stream type for
* easier, more intuitive usage.</p>
*
* <p><b>NOTE:</b> This class is only used during
* indexing. When retrieving the stored field value from a
* {@link Document} instance after search, you will get a
* conventional {@link Fieldable} instance where the numeric
* values are returned as {@link String}s (according to
* <code>toString(value)</code> of the used data type).
*
* <p><font color="red"><b>NOTE:</b> This API is
* experimental and might change in incompatible ways in the
* next release.</font>
*
* @since 2.9
*/
public final class NumericField extends AbstractField {
private final NumericTokenStream tokenStream;
/**
* Creates a field for numeric values using the default <code>precisionStep</code>
* {@link NumericUtils#PRECISION_STEP_DEFAULT} (4). The instance is not yet initialized with
* a numeric value, before indexing a document containing this field,
* set a value using the various set<em>???</em>Value() methods.
* This constructor creates an indexed, but not stored field.
* @param name the field name
*/
public NumericField(String name) {
this(name, NumericUtils.PRECISION_STEP_DEFAULT, Field.Store.NO, true);
}
/**
* Creates a field for numeric values using the default <code>precisionStep</code>
* {@link NumericUtils#PRECISION_STEP_DEFAULT} (4). The instance is not yet initialized with
* a numeric value, before indexing a document containing this field,
* set a value using the various set<em>???</em>Value() methods.
* @param name the field name
* @param store if the field should be stored in plain text form
* (according to <code>toString(value)</code> of the used data type)
* @param index if the field should be indexed using {@link NumericTokenStream}
*/
public NumericField(String name, Field.Store store, boolean index) {
this(name, NumericUtils.PRECISION_STEP_DEFAULT, store, index);
}
/**
* Creates a field for numeric values with the specified
* <code>precisionStep</code>. The instance is not yet initialized with
* a numeric value, before indexing a document containing this field,
* set a value using the various set<em>???</em>Value() methods.
* This constructor creates an indexed, but not stored field.
* @param name the field name
* @param precisionStep the used <a href="../search/NumericRangeQuery.html#precisionStepDesc">precision step</a>
*/
public NumericField(String name, int precisionStep) {
this(name, precisionStep, Field.Store.NO, true);
}
/**
* Creates a field for numeric values with the specified
* <code>precisionStep</code>. The instance is not yet initialized with
* a numeric value, before indexing a document containing this field,
* set a value using the various set<em>???</em>Value() methods.
* @param name the field name
* @param precisionStep the used <a href="../search/NumericRangeQuery.html#precisionStepDesc">precision step</a>
* @param store if the field should be stored in plain text form
* (according to <code>toString(value)</code> of the used data type)
* @param index if the field should be indexed using {@link NumericTokenStream}
*/
public NumericField(String name, int precisionStep, Field.Store store, boolean index) {
super(name, store, index ? Field.Index.ANALYZED_NO_NORMS : Field.Index.NO, Field.TermVector.NO);
setOmitTermFreqAndPositions(true);
tokenStream = new NumericTokenStream(precisionStep);
}
/** Returns a {@link NumericTokenStream} for indexing the numeric value. */
public TokenStream tokenStreamValue() {
return isIndexed() ? tokenStream : null;
}
/** Returns always <code>null</code> for numeric fields */
public byte[] binaryValue() {
return null;
}
/** Returns always <code>null</code> for numeric fields */
@Override
public byte[] getBinaryValue(byte[] result){
return null;
}
/** Returns always <code>null</code> for numeric fields */
public Reader readerValue() {
return null;
}
/** Returns the numeric value as a string (how it is stored, when {@link Field.Store#YES} is chosen). */
public String stringValue() {
return (fieldsData == null) ? null : fieldsData.toString();
}
/** Returns the current numeric value as a subclass of {@link Number}, <code>null</code> if not yet initialized. */
public Number getNumericValue() {
return (Number) fieldsData;
}
/**
* Initializes the field with the supplied <code>long</code> value.
* @param value the numeric value
* @return this instance, because of this you can use it the following way:
* <code>document.add(new NumericField(name, precisionStep).setLongValue(value))</code>
*/
public NumericField setLongValue(final long value) {
tokenStream.setLongValue(value);
fieldsData = Long.valueOf(value);
return this;
}
/**
* Initializes the field with the supplied <code>int</code> value.
* @param value the numeric value
* @return this instance, because of this you can use it the following way:
* <code>document.add(new NumericField(name, precisionStep).setIntValue(value))</code>
*/
public NumericField setIntValue(final int value) {
tokenStream.setIntValue(value);
fieldsData = Integer.valueOf(value);
return this;
}
/**
* Initializes the field with the supplied <code>double</code> value.
* @param value the numeric value
* @return this instance, because of this you can use it the following way:
* <code>document.add(new NumericField(name, precisionStep).setDoubleValue(value))</code>
*/
public NumericField setDoubleValue(final double value) {
tokenStream.setDoubleValue(value);
fieldsData = Double.valueOf(value);
return this;
}
/**
* Initializes the field with the supplied <code>float</code> value.
* @param value the numeric value
* @return this instance, because of this you can use it the following way:
* <code>document.add(new NumericField(name, precisionStep).setFloatValue(value))</code>
*/
public NumericField setFloatValue(final float value) {
tokenStream.setFloatValue(value);
fieldsData = Float.valueOf(value);
return this;
}
}
| src/java/org/apache/lucene/document/NumericField.java | package org.apache.lucene.document;
/**
* 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.io.Reader;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.NumericTokenStream;
import org.apache.lucene.util.NumericUtils;
import org.apache.lucene.search.NumericRangeQuery; // javadocs
import org.apache.lucene.search.NumericRangeFilter; // javadocs
import org.apache.lucene.search.SortField; // javadocs
import org.apache.lucene.search.FieldCache; // javadocs
/**
* <p>This class provides a {@link Field} that enables indexing
* of numeric values for efficient range filtering and
* sorting. Here's an example usage, adding an int value:
* <pre>
* document.add(new NumericField(name).setIntValue(value));
* </pre>
*
* For optimal performance, re-use the
* <code>NumericField</code> and {@link Document} instance for more than
* one document:
*
* <pre>
* NumericField field = new NumericField(name);
* Document document = new Document();
* document.add(field);
*
* for(all documents) {
* ...
* field.setIntValue(value)
* writer.addDocument(document);
* ...
* }
* </pre>
*
* <p>The java native types <code>int</code>, <code>long</code>,
* <code>float</code> and <code>double</code> are
* directly supported. However, any value that can be
* converted into these native types can also be indexed.
* For example, date/time values represented by a
* {@link java.util.Date} can be translated into a long
* value using the {@link java.util.Date#getTime} method. If you
* don't need millisecond precision, you can quantize the
* value, either by dividing the result of
* {@link java.util.Date#getTime} or using the separate getters
* (for year, month, etc.) to construct an <code>int</code> or
* <code>long</code> value.</p>
*
* <p>To perform range querying or filtering against a
* <code>NumericField</code>, use {@link NumericRangeQuery} or {@link
* NumericRangeFilter}. To sort according to a
* <code>NumericField</code>, use the normal numeric sort types, eg
* {@link SortField#INT} (note that {@link SortField#AUTO}
* will not work with these fields). <code>NumericField</code> values
* can also be loaded directly from {@link FieldCache}.</p>
*
* <p>By default, a <code>NumericField</code>'s value is not stored but
* is indexed for range filtering and sorting. You can use
* the {@link #NumericField(String,Field.Store,boolean)}
* constructor if you need to change these defaults.</p>
*
* <p>You may add the same field name as a <code>NumericField</code> to
* the same document more than once. Range querying and
* filtering will be the logical OR of all values; so a range query
* will hit all documents that have at least one value in
* the range. However sort behavior is not defined. If you need to sort,
* you should separately index a single-valued <code>NumericField</code>.</p>
*
* <p>A <code>NumericField</code> will consume somewhat more disk space
* in the index than an ordinary single-valued field.
* However, for a typical index that includes substantial
* textual content per document, this increase will likely
* be in the noise. </p>
*
* <p>Within Lucene, each numeric value is indexed as a
* <em>trie</em> structure, where each term is logically
* assigned to larger and larger pre-defined brackets (which
* are simply lower-precision representations of the value).
* The step size between each successive bracket is called the
* <code>precisionStep</code>, measured in bits. Smaller
* <code>precisionStep</code> values result in larger number
* of brackets, which consumes more disk space in the index
* but may result in faster range search performance. The
* default value, 4, was selected for a reasonable tradeoff
* of disk space consumption versus performance. You can
* use the expert constructor {@link
* #NumericField(String,int,Field.Store,boolean)} if you'd
* like to change the value. Note that you must also
* specify a congruent value when creating {@link
* NumericRangeQuery} or {@link NumericRangeFilter}.
* For low cardinality fields larger precision steps are good.
* If the cardinality is < 100, it is fair
* to use {@link Integer#MAX_VALUE}, which produces one
* term per value.
*
* <p>For more information on the internals of numeric trie
* indexing, including the <a
* href="../search/NumericRangeQuery.html#precisionStepDesc"><code>precisionStep</code></a>
* configuration, see {@link NumericRangeQuery}. The format of
* indexed values is described in {@link NumericUtils}.
*
* <p>If you only need to sort by numeric value, and never
* run range querying/filtering, you can index using a
* <code>precisionStep</code> of {@link Integer#MAX_VALUE}.
* This will minimize disk space consumed. </p>
*
* <p>More advanced users can instead use {@link
* NumericTokenStream} directly, when indexing numbers. This
* class is a wrapper around this token stream type for
* easier, more intuitive usage.</p>
*
* <p><b>NOTE:</b> This class is only used during
* indexing. When retrieving the stored field value from a
* {@link Document} instance after search, you will get a
* conventional {@link Fieldable} instance where the numeric
* values are returned as {@link String}s (according to
* <code>toString(value)</code> of the used data type).
*
* <p><font color="red"><b>NOTE:</b> This API is
* experimental and might change in incompatible ways in the
* next release.</font>
*
* @since 2.9
*/
public final class NumericField extends AbstractField {
private final NumericTokenStream tokenStream;
/**
* Creates a field for numeric values using the default <code>precisionStep</code>
* {@link NumericUtils#PRECISION_STEP_DEFAULT} (4). The instance is not yet initialized with
* a numeric value, before indexing a document containing this field,
* set a value using the various set<em>???</em>Value() methods.
* This constructor creates an indexed, but not stored field.
* @param name the field name
*/
public NumericField(String name) {
this(name, NumericUtils.PRECISION_STEP_DEFAULT, Field.Store.NO, true);
}
/**
* Creates a field for numeric values using the default <code>precisionStep</code>
* {@link NumericUtils#PRECISION_STEP_DEFAULT} (4). The instance is not yet initialized with
* a numeric value, before indexing a document containing this field,
* set a value using the various set<em>???</em>Value() methods.
* @param name the field name
* @param store if the field should be stored in plain text form
* (according to <code>toString(value)</code> of the used data type)
* @param index if the field should be indexed using {@link NumericTokenStream}
*/
public NumericField(String name, Field.Store store, boolean index) {
this(name, NumericUtils.PRECISION_STEP_DEFAULT, store, index);
}
/**
* Creates a field for numeric values with the specified
* <code>precisionStep</code>. The instance is not yet initialized with
* a numeric value, before indexing a document containing this field,
* set a value using the various set<em>???</em>Value() methods.
* This constructor creates an indexed, but not stored field.
* @param name the field name
* @param precisionStep the used <a href="../search/NumericRangeQuery.html#precisionStepDesc">precision step</a>
*/
public NumericField(String name, int precisionStep) {
this(name, precisionStep, Field.Store.NO, true);
}
/**
* Creates a field for numeric values with the specified
* <code>precisionStep</code>. The instance is not yet initialized with
* a numeric value, before indexing a document containing this field,
* set a value using the various set<em>???</em>Value() methods.
* @param name the field name
* @param precisionStep the used <a href="../search/NumericRangeQuery.html#precisionStepDesc">precision step</a>
* @param store if the field should be stored in plain text form
* (according to <code>toString(value)</code> of the used data type)
* @param index if the field should be indexed using {@link NumericTokenStream}
*/
public NumericField(String name, int precisionStep, Field.Store store, boolean index) {
super(name, store, index ? Field.Index.ANALYZED_NO_NORMS : Field.Index.NO, Field.TermVector.NO);
setOmitTermFreqAndPositions(true);
tokenStream = new NumericTokenStream(precisionStep);
}
/** Returns a {@link NumericTokenStream} for indexing the numeric value. */
public TokenStream tokenStreamValue() {
return isIndexed() ? tokenStream : null;
}
/** Returns always <code>null</code> for numeric fields */
public byte[] binaryValue() {
return null;
}
/** Returns always <code>null</code> for numeric fields */
@Override
public byte[] getBinaryValue(byte[] result){
return null;
}
/** Returns always <code>null</code> for numeric fields */
public Reader readerValue() {
return null;
}
/** Returns the numeric value as a string (how it is stored, when {@link Field.Store#YES} is chosen). */
public String stringValue() {
return (fieldsData == null) ? null : fieldsData.toString();
}
/** Returns the current numeric value as a subclass of {@link Number}, <code>null</code> if not yet initialized. */
public Number getNumericValue() {
return (Number) fieldsData;
}
/**
* Initializes the field with the supplied <code>long</code> value.
* @param value the numeric value
* @return this instance, because of this you can use it the following way:
* <code>document.add(new NumericField(name, precisionStep).setLongValue(value))</code>
*/
public NumericField setLongValue(final long value) {
tokenStream.setLongValue(value);
fieldsData = new Long(value);
return this;
}
/**
* Initializes the field with the supplied <code>int</code> value.
* @param value the numeric value
* @return this instance, because of this you can use it the following way:
* <code>document.add(new NumericField(name, precisionStep).setIntValue(value))</code>
*/
public NumericField setIntValue(final int value) {
tokenStream.setIntValue(value);
fieldsData = Integer.valueOf(value);
return this;
}
/**
* Initializes the field with the supplied <code>double</code> value.
* @param value the numeric value
* @return this instance, because of this you can use it the following way:
* <code>document.add(new NumericField(name, precisionStep).setDoubleValue(value))</code>
*/
public NumericField setDoubleValue(final double value) {
tokenStream.setDoubleValue(value);
fieldsData = Double.valueOf(value);
return this;
}
/**
* Initializes the field with the supplied <code>float</code> value.
* @param value the numeric value
* @return this instance, because of this you can use it the following way:
* <code>document.add(new NumericField(name, precisionStep).setFloatValue(value))</code>
*/
public NumericField setFloatValue(final float value) {
tokenStream.setFloatValue(value);
fieldsData = Float.valueOf(value);
return this;
}
}
| LUCENE-1857: Missed one valueOf conversion
git-svn-id: 4c5078813df38efa56971a28e09a55254294f104@820795 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/lucene/document/NumericField.java | LUCENE-1857: Missed one valueOf conversion | <ide><path>rc/java/org/apache/lucene/document/NumericField.java
<ide> */
<ide> public NumericField setLongValue(final long value) {
<ide> tokenStream.setLongValue(value);
<del> fieldsData = new Long(value);
<add> fieldsData = Long.valueOf(value);
<ide> return this;
<ide> }
<ide> |
|
Java | apache-2.0 | 1815f9e9dc878bc0d96880de3dd1ef122e72de7a | 0 | ConSol/sakuli,ConSol/sakuli,ConSol/sakuli,ConSol/sakuli,ConSol/sakuli,ConSol/sakuli | /*
* Sakuli - Testing and Monitoring-Tool for Websites and common UIs.
*
* Copyright 2013 - 2014 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 de.consol.sakuli.actions.screenbased;
import de.consol.sakuli.actions.settings.ScreenBasedSettings;
import de.consol.sakuli.aop.AopBaseTest;
import de.consol.sakuli.datamodel.actions.LogLevel;
import de.consol.sakuli.loader.BeanLoader;
import de.consol.sakuli.utils.LoggerInitializer;
import org.sikuli.basics.Debug;
import org.testng.annotations.Test;
public class ScreenBasedSettingsSikuliLogSystemOutTest extends AopBaseTest {
@Test
public void testDoHandleSikuliLog() throws Throwable {
ScreenBasedSettings testling = BeanLoader.loadBean(ScreenBasedSettings.class);
testling.setDefaults();
BeanLoader.loadBean(LoggerInitializer.class).initLoggerContext();
System.out.println("LOG-FOLDER: " + logFile);
//errors
Debug.error("SIKULI-ERROR-message");
assertLastLine(logFile, "SIKULI-", LogLevel.INFO, "[error] SIKULI-ERROR-message");
//enter message like for typing
Debug.enter("SIKULI-ENTER-message");
assertLastLine(logFile, "SIKULI-", LogLevel.INFO, "[profile] entering: SIKULI-ENTER-message");
//info messages
Debug.info("SIKULI-INFO-message");
assertLastLine(logFile, "SIKULI-", LogLevel.INFO, "[info] SIKULI-INFO-message");
//debug messages
Debug.log(-3, "SIKULI-DEBUG-message");
assertLastLine(logFile, "SIKULI-", LogLevel.INFO, "[debug] SIKULI-DEBUG-message");
}
} | core/src/test/java/de/consol/sakuli/actions/screenbased/ScreenBasedSettingsSikuliLogSystemOutTest.java | /*
* Sakuli - Testing and Monitoring-Tool for Websites and common UIs.
*
* Copyright 2013 - 2014 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 de.consol.sakuli.actions.screenbased;
import de.consol.sakuli.actions.settings.ScreenBasedSettings;
import de.consol.sakuli.aop.AopBaseTest;
import de.consol.sakuli.datamodel.actions.LogLevel;
import de.consol.sakuli.loader.BeanLoader;
import de.consol.sakuli.utils.LoggerInitializer;
import org.sikuli.basics.Debug;
import org.testng.annotations.Test;
public class ScreenBasedSettingsSikuliLogSystemOutTest extends AopBaseTest {
@Test
public void testDoHandleSikuliLog() throws Throwable {
ScreenBasedSettings testling = BeanLoader.loadBean(ScreenBasedSettings.class);
testling.setDefaults();
BeanLoader.loadBean(LoggerInitializer.class).initLoggerContext();
System.out.println("LOG-FOLDER: " + logFile);
//errors
Debug.error("SAKULI-ERROR-message");
assertLastLine(logFile, "SAKULI-", LogLevel.INFO, "[error] SAKULI-ERROR-message");
//enter message like for typing
Debug.enter("SAKULI-ENTER-message");
assertLastLine(logFile, "SAKULI-", LogLevel.INFO, "[profile] entering: SAKULI-ENTER-message");
//info messages
Debug.info("SAKULI-INFO-message");
assertLastLine(logFile, "SAKULI-", LogLevel.INFO, "[info] SAKULI-INFO-message");
//debug messages
Debug.log(-3, "SAKULI-DEBUG-message");
assertLastLine(logFile, "SAKULI-", LogLevel.INFO, "[debug] SAKULI-DEBUG-message");
}
} | renaming
| core/src/test/java/de/consol/sakuli/actions/screenbased/ScreenBasedSettingsSikuliLogSystemOutTest.java | renaming | <ide><path>ore/src/test/java/de/consol/sakuli/actions/screenbased/ScreenBasedSettingsSikuliLogSystemOutTest.java
<ide> System.out.println("LOG-FOLDER: " + logFile);
<ide>
<ide> //errors
<del> Debug.error("SAKULI-ERROR-message");
<del> assertLastLine(logFile, "SAKULI-", LogLevel.INFO, "[error] SAKULI-ERROR-message");
<add> Debug.error("SIKULI-ERROR-message");
<add> assertLastLine(logFile, "SIKULI-", LogLevel.INFO, "[error] SIKULI-ERROR-message");
<ide>
<ide> //enter message like for typing
<del> Debug.enter("SAKULI-ENTER-message");
<del> assertLastLine(logFile, "SAKULI-", LogLevel.INFO, "[profile] entering: SAKULI-ENTER-message");
<add> Debug.enter("SIKULI-ENTER-message");
<add> assertLastLine(logFile, "SIKULI-", LogLevel.INFO, "[profile] entering: SIKULI-ENTER-message");
<ide>
<ide> //info messages
<del> Debug.info("SAKULI-INFO-message");
<del> assertLastLine(logFile, "SAKULI-", LogLevel.INFO, "[info] SAKULI-INFO-message");
<add> Debug.info("SIKULI-INFO-message");
<add> assertLastLine(logFile, "SIKULI-", LogLevel.INFO, "[info] SIKULI-INFO-message");
<ide>
<ide> //debug messages
<del> Debug.log(-3, "SAKULI-DEBUG-message");
<del> assertLastLine(logFile, "SAKULI-", LogLevel.INFO, "[debug] SAKULI-DEBUG-message");
<add> Debug.log(-3, "SIKULI-DEBUG-message");
<add> assertLastLine(logFile, "SIKULI-", LogLevel.INFO, "[debug] SIKULI-DEBUG-message");
<ide> }
<ide> } |
|
Java | agpl-3.0 | ac1f6743a36719f0e2f90ce6a3b2305c9d444ba9 | 0 | lp0/cursus-ui,lp0/cursus-core | /*
cursus - Race series management program
Copyright 2011 Simon Arlott
This program 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
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU 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 eu.lp0.cursus.db.data;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
@MappedSuperclass
public abstract class AbstractEntity implements Cloneable {
private Long id;
@Id
@GeneratedValue
@Column(nullable = false)
public Long getId() {
return id;
}
@SuppressWarnings("unused")
private void setId(long id) {
this.id = id;
}
@Transient
public boolean isTransient() {
return getId() == null;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (o == this) {
return true;
}
if (!getClass().equals(o.getClass())) {
return false;
}
AbstractEntity e = (AbstractEntity)o;
if (isTransient() || e.isTransient()) {
return false;
}
return getId().equals(e.getId());
}
@Override
public int hashCode() {
if (isTransient()) {
return super.hashCode();
}
return (int)(id ^ (id >>> 32));
}
@Override
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
} | src/main/java/eu/lp0/cursus/db/data/AbstractEntity.java | /*
cursus - Race series management program
Copyright 2011 Simon Arlott
This program 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
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU 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 eu.lp0.cursus.db.data;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
@MappedSuperclass
public abstract class AbstractEntity implements Cloneable {
private Long id;
@Id
@GeneratedValue
@Column(nullable = false)
public Long getId() {
return id;
}
@SuppressWarnings("unused")
private void setId(long id) {
this.id = id;
}
@Transient
public boolean isTransient() {
return getId() == null;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (o == this) {
return true;
}
if (!getClass().equals(o.getClass())) {
return false;
}
AbstractEntity e = (AbstractEntity)o;
if (isTransient() || e.isTransient()) {
return false;
}
return getId().equals(e.getId());
}
@Override
public int hashCode() {
return (int)(id ^ (id >>> 32));
}
@Override
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
} | fix hashcode calculation on transient entities | src/main/java/eu/lp0/cursus/db/data/AbstractEntity.java | fix hashcode calculation on transient entities | <ide><path>rc/main/java/eu/lp0/cursus/db/data/AbstractEntity.java
<ide>
<ide> @Override
<ide> public int hashCode() {
<add> if (isTransient()) {
<add> return super.hashCode();
<add> }
<ide> return (int)(id ^ (id >>> 32));
<ide> }
<ide> |
|
Java | mit | 45531f45f650009f58eb81d17d252da80b9d0399 | 0 | fluorine/JavaProgrammingExercises | package com.github.fluorine.funclist;
import java.math.BigInteger;
import javarepl.REPL;
import com.github.fluorine.funclist.FuncList;
/**
* More functional programming for sorting, appending and merging lists.
*
* @author [email protected]
*
*/
public class FuncList3 {
public static void main(String[] args) {
// Get values
System.out.println("Insert two list of integers, separated by space.");
Integer[] aa = REPL.getIntArray("List A: ");
Integer[] bb = REPL.getIntArray("List B: ");
// Produce lists
FuncList<Integer> a = ArrayToList(aa);
FuncList<Integer> b = ArrayToList(bb);
// Sort lists
a = sortList(a);
b = sortList(b);
// Display sorted lists
System.out.println();
System.out.println(" Sorted list A:\n " + a.toString());
System.out.println(" Sorted list B:\n " + b.toString());
// Create new list appending A and B and
// then display it.
FuncList<Integer> ab = appendLists(a, b);
System.out.println(" Appended list:\n " + ab.toString());
// Create a new list merging A and B
// into a new sorted list. Then display it.
FuncList<Integer> merged = mergeLists(a, b);
System.out.println(" Merged list:\n " + merged.toString());
// Produce a list of Fibonacci numbers
System.out.println(" List of fibonacci numbers:\n ");
FuncList<BigInteger> fibo = produceFibonacci();
for (BigInteger i : fibo) {
System.out.print(i + " ");
}
}
/**
* This function produces a linked list from an array.
*
* @param <T>
* Type of items in array in list.
* @param a
* Input array
* @return Linked list of items in array
*/
public static <T> FuncList<T> ArrayToList(T[] a) {
if (a == null || a.length == 0)
return null;
FuncList<T> list = new FuncList<T>(a[0]);
for (int i = 1; i < a.length; i++) {
list = new FuncList<T>(a[i], list);
}
return list;
}
/**
* A function to sort a linked list using insertion sort.
*
* @param <T>
* @param list
* @return
*/
public static <T extends Comparable<T>> FuncList<T> sortList(
FuncList<T> list) {
return sortList(list, null);
}
private static <T extends Comparable<T>> FuncList<T> sortList(
FuncList<T> list, FuncList<T> sorted) {
if (list == null) {
return sorted;
} else {
return sortList(list.tail, insertItem(list.head, sorted));
}
}
/**
* Insert item into ascending linked list.
*
* @param <T>
* Comparable<T> type
* @param item
* Item to insert into sorted list.
* @param list
* Sorted list
* @return New sorted list with new item inside.
*/
public static <T extends Comparable<T>> FuncList<T> insertItem(T item,
FuncList<T> list) {
if (list == null) {
return new FuncList<T>(item);
} else if (item.compareTo(list.head) == -1) {
return new FuncList<T>(item, list);
} else {
if (list.tail == null) {
return new FuncList<T>(list.head, new FuncList<T>(item));
} else {
return new FuncList<T>(list.head, insertItem(item, list.tail));
}
}
}
/**
* This function appends two lists to produce a new one.
*
* @param <T>
* @param a
* @param b
* @return The new list
*/
public static <T> FuncList<T> appendLists(FuncList<T> a, FuncList<T> b) {
if (a == null) {
return b;
} else {
return new FuncList<T>(a.head, appendLists(a.tail, b));
}
}
/**
* This recursive function merges two sorted lists into a new sorted list.
*
* @param <T>
* @param a
* @param b
* @return New sorted list from merging two lists.
*/
public static <T extends Comparable<T>> FuncList<T> mergeLists(
FuncList<T> a, FuncList<T> b) {
if (a == null) {
return b;
} else if (b == null) {
return a;
} else {
if (a.head.compareTo(b.head) == -1) {
return new FuncList<T>(a.head, mergeLists(a.tail, b));
} else {
return new FuncList<T>(b.head, mergeLists(b.tail, a));
}
}
}
/**
* @return List of Fibonacci numbers.
*/
public static FuncList<BigInteger> produceFibonacci() {
return new FuncList<BigInteger>(new BigInteger("1"),
new FuncList<BigInteger>(new BigInteger("1"), produceFibonacci(
new BigInteger("1"), new BigInteger("1"), 3)));
}
public static FuncList<BigInteger> produceFibonacci(BigInteger a,
BigInteger b, int count) {
if (count >= 100) {
return new FuncList<BigInteger>(a.add(b));
} else {
BigInteger total = a.add(b);
return new FuncList<BigInteger>(total, produceFibonacci(b, total,
count + 1));
}
}
}
| FuncList3/src/com/github/fluorine/funclist/FuncList3.java | package com.github.fluorine.funclist;
import javarepl.REPL;
import com.github.fluorine.funclist.FuncList;
/**
* More functional programming for sorting, appending and merging lists.
*
* @author [email protected]
*
*/
public class FuncList3 {
public static void main(String[] args) {
// Get values
System.out.println("Insert two list of integers, separated by space.");
Integer[] aa = REPL.getIntArray("List A: ");
Integer[] bb = REPL.getIntArray("List B: ");
// Produce lists
FuncList<Integer> a = ArrayToList(aa);
FuncList<Integer> b = ArrayToList(bb);
// Sort lists
a = sortList(a);
b = sortList(b);
// Display sorted lists
System.out.println();
System.out.println(" Sorted list A:\n " + a.toString());
System.out.println(" Sorted list B:\n " + b.toString());
// Create new list appending A and B and
// then display it.
FuncList<Integer> ab = appendLists(a, b);
System.out.println(" Appended list:\n " + ab.toString());
// Create a new list merging A and B
// into a new sorted list. Then display it.
FuncList<Integer> merged = mergeLists(a, b);
System.out.println(" Merged list:\n " + merged.toString());
}
/**
* This function produces a linked list from an array.
*
* @param <T>
* Type of items in array in list.
* @param a
* Input array
* @return Linked list of items in array
*/
public static <T> FuncList<T> ArrayToList(T[] a) {
if (a == null || a.length == 0)
return null;
FuncList<T> list = new FuncList<T>(a[0]);
for (int i = 1; i < a.length; i++) {
list = new FuncList<T>(a[i], list);
}
return list;
}
/**
* A function to sort a linked list using insertion sort.
*
* @param <T>
* @param list
* @return
*/
public static <T extends Comparable<T>> FuncList<T> sortList(
FuncList<T> list) {
return sortList(list, null);
}
private static <T extends Comparable<T>> FuncList<T> sortList(
FuncList<T> list, FuncList<T> sorted) {
if (list == null) {
return sorted;
} else {
return sortList(list.tail, insertItem(list.head, sorted));
}
}
/**
* Insert item into ascending linked list.
*
* @param <T>
* Comparable<T> type
* @param item
* Item to insert into sorted list.
* @param list
* Sorted list
* @return New sorted list with new item inside.
*/
public static <T extends Comparable<T>> FuncList<T> insertItem(T item,
FuncList<T> list) {
if (list == null) {
return new FuncList<T>(item);
} else if (item.compareTo(list.head) == -1) {
return new FuncList<T>(item, list);
} else {
if (list.tail == null) {
return new FuncList<T>(list.head, new FuncList<T>(item));
} else {
return new FuncList<T>(list.head, insertItem(item, list.tail));
}
}
}
/**
* This function appends two lists to produce a new one.
*
* @param <T>
* @param a
* @param b
* @return The new list
*/
public static <T> FuncList<T> appendLists(FuncList<T> a, FuncList<T> b) {
if (a == null) {
return b;
} else {
return new FuncList<T>(a.head, appendLists(a.tail, b));
}
}
/**
* This recursive function merges two sorted lists into a new sorted list.
*
* @param <T>
* @param a
* @param b
* @return New sorted list from merging two lists.
*/
public static <T extends Comparable<T>> FuncList<T> mergeLists(
FuncList<T> a, FuncList<T> b) {
if (a == null) {
return b;
} else if (b == null) {
return a;
} else {
if (a.head.compareTo(b.head) == -1) {
return new FuncList<T>(a.head, mergeLists(a.tail, b));
} else {
return new FuncList<T>(b.head, mergeLists(b.tail, a));
}
}
}
}
| A new function to produce a linked list of Fibonacci values.
| FuncList3/src/com/github/fluorine/funclist/FuncList3.java | A new function to produce a linked list of Fibonacci values. | <ide><path>uncList3/src/com/github/fluorine/funclist/FuncList3.java
<ide> package com.github.fluorine.funclist;
<add>
<add>import java.math.BigInteger;
<ide>
<ide> import javarepl.REPL;
<ide> import com.github.fluorine.funclist.FuncList;
<ide> // into a new sorted list. Then display it.
<ide> FuncList<Integer> merged = mergeLists(a, b);
<ide> System.out.println(" Merged list:\n " + merged.toString());
<add>
<add> // Produce a list of Fibonacci numbers
<add> System.out.println(" List of fibonacci numbers:\n ");
<add> FuncList<BigInteger> fibo = produceFibonacci();
<add> for (BigInteger i : fibo) {
<add> System.out.print(i + " ");
<add> }
<ide> }
<ide>
<ide> /**
<ide> }
<ide> }
<ide> }
<add>
<add> /**
<add> * @return List of Fibonacci numbers.
<add> */
<add> public static FuncList<BigInteger> produceFibonacci() {
<add> return new FuncList<BigInteger>(new BigInteger("1"),
<add> new FuncList<BigInteger>(new BigInteger("1"), produceFibonacci(
<add> new BigInteger("1"), new BigInteger("1"), 3)));
<add> }
<add>
<add> public static FuncList<BigInteger> produceFibonacci(BigInteger a,
<add> BigInteger b, int count) {
<add> if (count >= 100) {
<add> return new FuncList<BigInteger>(a.add(b));
<add> } else {
<add> BigInteger total = a.add(b);
<add> return new FuncList<BigInteger>(total, produceFibonacci(b, total,
<add> count + 1));
<add> }
<add> }
<ide> } |
|
JavaScript | mit | cba37c90d96f50adc3930b263a12eed8e9fbf453 | 0 | math-foo/cloudpebble,pebble/cloudpebble,pebble/cloudpebble,thunsaker/cloudpebble,thunsaker/cloudpebble,thunsaker/cloudpebble,math-foo/cloudpebble,pebble/cloudpebble,thunsaker/cloudpebble,math-foo/cloudpebble,pebble/cloudpebble,math-foo/cloudpebble,pebble/cloudpebble | (function() {
var PROXY_SERVER = LIBPEBBLE_PROXY;
window.PebbleProxySocket = function(token) {
var self = this;
var mToken = token;
var mSocket = null;
var mConnected = false;
var mIsConnected = false;
var mIsAuthenticated = false;
_.extend(this, Backbone.Events);
this.connect = function() {
if(!PROXY_SERVER) {
_.defer(function() {
self.trigger('error', "Websocket proxy not specified.");
});
return;
}
mSocket = new WebSocket(PROXY_SERVER);
mSocket.binaryType = "arraybuffer";
mSocket.onerror = handle_socket_error;
mSocket.onerror = handle_socket_close;
mSocket.onmessage = handle_socket_message;
mSocket.onopen = handle_socket_open;
console.log("Connecting to " + PROXY_SERVER);
};
this.close = function() {
mSocket.close();
cleanup();
};
this.send = function(data) {
mSocket.send(data);
};
this.isOpen = function() {
return mIsConnected;
};
function cleanup() {
mSocket = null;
mIsConnected = false;
mIsAuthenticated = false;
}
function handle_socket_error(e) {
console.log("socket error", e);
self.trigger('error', e);
}
function handle_socket_open(e) {
console.log("socket open; authenticating...");
self.send(new Uint8Array([0x09, mToken.length].concat(_.invoke(mToken, 'charCodeAt', 0))));
}
function handle_socket_message(e) {
var data = new Uint8Array(e.data);
if(data[0] == 0x09) {
if(data[1] == 0x00) {
console.log("Authenticated successfully.");
mIsAuthenticated = true;
} else {
console.log("Authentication failed.");
self.trigger('error', "Proxy rejected authentication token.");
}
} else if(data[0] == 0x08) {
if(data[1] == 0xFF) {
console.log("Connected successfully.");
mIsConnected = true;
self.trigger('open');
} else if(data[1] == 0x00) {
console.log("Connection closed remotely.");
self.trigger('close', {wasClean: true});
}
} else {
self.trigger('message', data);
}
}
function handle_socket_close(e) {
console.log("Socket closed.");
self.trigger('close', e);
cleanup();
}
}
})();
| ide/static/ide/js/libpebble/proxysocket.js | (function() {
var PROXY_SERVER = LIBPEBBLE_PROXY;
window.PebbleProxySocket = function(token) {
var self = this;
var mToken = token;
var mSocket = null;
var mConnected = false;
var mIsConnected = false;
var mIsAuthenticated = false;
_.extend(this, Backbone.Events);
this.connect = function() {
if(!PROXY_SERVER) {
_.defer(function() {
self.trigger('error', "Websocket proxy not specified.");
});
return;
}
mSocket = new WebSocket(PROXY_SERVER);
mSocket.binaryType = "arraybuffer";
mSocket.onerror = handle_socket_error;
mSocket.onerror = handle_socket_close;
mSocket.onmessage = handle_socket_message;
mSocket.onopen = handle_socket_open;
console.log("Connecting to " + PROXY_SERVER);
};
this.close = function() {
mSocket.close();
cleanup();
};
this.send = function(data) {
console.log("Sending data:", data);
mSocket.send(data);
};
this.isOpen = function() {
return mIsConnected;
};
function cleanup() {
mSocket = null;
mIsConnected = false;
mIsAuthenticated = false;
}
function handle_socket_error(e) {
console.log("socket error", e);
self.trigger('error', e);
}
function handle_socket_open(e) {
console.log("socket open; authenticating...");
self.send(new Uint8Array([0x09, mToken.length].concat(_.invoke(mToken, 'charCodeAt', 0))));
}
function handle_socket_message(e) {
var data = new Uint8Array(e.data);
console.log("Received socket message", data);
if(data[0] == 0x09) {
if(data[1] == 0x00) {
console.log("Authenticated successfully.");
mIsAuthenticated = true;
} else {
console.log("Authentication failed.");
self.trigger('error', "Proxy rejected authentication token.");
}
} else if(data[0] == 0x08) {
if(data[1] == 0xFF) {
console.log("Connected successfully.");
mIsConnected = true;
self.trigger('open');
} else if(data[1] == 0x00) {
console.log("Connection closed remotely.");
self.trigger('close', {wasClean: true});
}
} else {
self.trigger('message', data);
}
}
function handle_socket_close(e) {
console.log("Socket closed.");
self.trigger('close', e);
cleanup();
}
}
})();
| Remove message dumps.
| ide/static/ide/js/libpebble/proxysocket.js | Remove message dumps. | <ide><path>de/static/ide/js/libpebble/proxysocket.js
<ide> };
<ide>
<ide> this.send = function(data) {
<del> console.log("Sending data:", data);
<ide> mSocket.send(data);
<ide> };
<ide>
<ide>
<ide> function handle_socket_message(e) {
<ide> var data = new Uint8Array(e.data);
<del> console.log("Received socket message", data);
<ide> if(data[0] == 0x09) {
<ide> if(data[1] == 0x00) {
<ide> console.log("Authenticated successfully."); |
|
Java | mit | 0630c2a74a5b0d014de7714012697d74fc96217d | 0 | sunyifan112358/pvis | package com.logistics.pvis.event.mouseevent;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import processing.core.PConstants;
public class MouseEventTest {
processing.event.MouseEvent nativeEvent = null;
@Before
public void setUp() throws Exception {
nativeEvent = mock(processing.event.MouseEvent.class);
when(nativeEvent.getAction()).thenReturn(
processing.event.MouseEvent.CLICK);
when(nativeEvent.getButton()).thenReturn(PConstants.LEFT);
when(nativeEvent.getCount()).thenReturn(1);
when(nativeEvent.getX()).thenReturn(0);
when(nativeEvent.getY()).thenReturn(0);
}
@After
public void tearDown() throws Exception {
}
@Test
public void testMouseEvent() {
MouseEvent event = new MouseEvent(nativeEvent);
assertEquals(MouseEventAction.CLICK, event.getMouseEventAction());
assertEquals(MouseButton.LEFT, event.getMouseButton());
assertEquals(0.0, event.getMousePosition().getX(), 1e-5);
assertEquals(0.0, event.getMousePosition().getY(), 1e-5);
assertEquals(1, event.getCount());
}
@Test
public void testIsPropagatingAtTheBeginning() {
MouseEvent event = new MouseEvent(nativeEvent);
assertTrue(event.isPropagating());
}
@Test
public void testStopPropagation() {
MouseEvent event = new MouseEvent(nativeEvent);
event.stopPropagation();
assertFalse(event.isPropagating());
}
}
| src/main/com/logistics/pvis/event/mouseevent/MouseEventTest.java | package com.logistics.pvis.event.mouseevent;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import processing.core.PConstants;
public class MouseEventTest {
processing.event.MouseEvent nativeEvent = null;
@Before
public void setUp() throws Exception {
nativeEvent = mock(processing.event.MouseEvent.class);
when(nativeEvent.getAction()).thenReturn(
processing.event.MouseEvent.CLICK);
when(nativeEvent.getButton()).thenReturn(PConstants.LEFT);
when(nativeEvent.getCount()).thenReturn(1);
when(nativeEvent.getX()).thenReturn(0);
when(nativeEvent.getY()).thenReturn(0);
}
@After
public void tearDown() throws Exception {
}
@Test
public void testMouseEvent() {
MouseEvent event = new MouseEvent(nativeEvent);
assertEquals(MouseEventAction.CLICK, event.getMouseEventAction());
assertEquals(MouseButton.LEFT, event.getMouseButton());
assertEquals(0, event.getMousePosition().getX(), 1e-5);
assertEquals(0, event.getMousePosition().getY(), 1e-5);
assertEquals(1, event.getCount());
}
@Test
public void testIsPropagatingAtTheBeginning() {
MouseEvent event = new MouseEvent(nativeEvent);
assertTrue(event.isPropagating());
}
@Test
public void testStopPropagation() {
MouseEvent event = new MouseEvent(nativeEvent);
event.stopPropagation();
assertFalse(event.isPropagating());
}
}
| Error fix
| src/main/com/logistics/pvis/event/mouseevent/MouseEventTest.java | Error fix | <ide><path>rc/main/com/logistics/pvis/event/mouseevent/MouseEventTest.java
<ide> MouseEvent event = new MouseEvent(nativeEvent);
<ide> assertEquals(MouseEventAction.CLICK, event.getMouseEventAction());
<ide> assertEquals(MouseButton.LEFT, event.getMouseButton());
<del> assertEquals(0, event.getMousePosition().getX(), 1e-5);
<del> assertEquals(0, event.getMousePosition().getY(), 1e-5);
<add> assertEquals(0.0, event.getMousePosition().getX(), 1e-5);
<add> assertEquals(0.0, event.getMousePosition().getY(), 1e-5);
<ide> assertEquals(1, event.getCount());
<ide> }
<ide> |
|
Java | apache-2.0 | c274c0d962254c532af7b2087e985f4047d1197d | 0 | sutaakar/drools,rajashekharmunthakewill/drools,romartin/drools,jomarko/drools,liupugong/drools,mrietveld/drools,kedzie/drools-android,liupugong/drools,pwachira/droolsexamples,ChallenHB/drools,jomarko/drools,prabasn/drools,iambic69/drools,prabasn/drools,ngs-mtech/drools,prabasn/drools,HHzzhz/drools,romartin/drools,sotty/drools,ChallenHB/drools,jomarko/drools,reynoldsm88/drools,ngs-mtech/drools,mrietveld/drools,sutaakar/drools,kevinpeterson/drools,ThomasLau/drools,TonnyFeng/drools,winklerm/drools,rajashekharmunthakewill/drools,ngs-mtech/drools,manstis/drools,jiripetrlik/drools,292388900/drools,OnePaaS/drools,mrietveld/drools,sotty/drools,manstis/drools,iambic69/drools,vinodkiran/drools,kedzie/drools-android,OnePaaS/drools,winklerm/drools,TonnyFeng/drools,manstis/drools,ThiagoGarciaAlves/drools,HHzzhz/drools,mrrodriguez/drools,droolsjbpm/drools,292388900/drools,ThomasLau/drools,Buble1981/MyDroolsFork,kedzie/drools-android,droolsjbpm/drools,292388900/drools,kevinpeterson/drools,liupugong/drools,amckee23/drools,ChallenHB/drools,292388900/drools,mrrodriguez/drools,Buble1981/MyDroolsFork,vinodkiran/drools,jomarko/drools,mrrodriguez/drools,prabasn/drools,HHzzhz/drools,lanceleverich/drools,jomarko/drools,kevinpeterson/drools,mrietveld/drools,sutaakar/drools,ThiagoGarciaAlves/drools,jiripetrlik/drools,vinodkiran/drools,OnePaaS/drools,iambic69/drools,lanceleverich/drools,liupugong/drools,liupugong/drools,292388900/drools,ThiagoGarciaAlves/drools,vinodkiran/drools,reynoldsm88/drools,rajashekharmunthakewill/drools,jiripetrlik/drools,ngs-mtech/drools,kevinpeterson/drools,ThiagoGarciaAlves/drools,Buble1981/MyDroolsFork,rajashekharmunthakewill/drools,reynoldsm88/drools,lanceleverich/drools,sutaakar/drools,droolsjbpm/drools,amckee23/drools,HHzzhz/drools,manstis/drools,amckee23/drools,sotty/drools,ThiagoGarciaAlves/drools,kedzie/drools-android,sotty/drools,reynoldsm88/drools,ThomasLau/drools,ThomasLau/drools,OnePaaS/drools,amckee23/drools,lanceleverich/drools,HHzzhz/drools,jiripetrlik/drools,winklerm/drools,manstis/drools,vinodkiran/drools,romartin/drools,mrrodriguez/drools,sotty/drools,rajashekharmunthakewill/drools,winklerm/drools,sutaakar/drools,mrietveld/drools,iambic69/drools,Buble1981/MyDroolsFork,romartin/drools,droolsjbpm/drools,romartin/drools,TonnyFeng/drools,lanceleverich/drools,ChallenHB/drools,amckee23/drools,TonnyFeng/drools,iambic69/drools,kedzie/drools-android,winklerm/drools,ngs-mtech/drools,OnePaaS/drools,TonnyFeng/drools,reynoldsm88/drools,ThomasLau/drools,mrrodriguez/drools,ChallenHB/drools,prabasn/drools,jiripetrlik/drools,droolsjbpm/drools,kevinpeterson/drools | /*
* Copyright 2010 JBoss Inc
*
* 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.drools.io.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.Future;
import org.drools.io.internal.InternalResource;
import org.kie.ChangeSet;
import org.kie.SystemEventListener;
import org.kie.concurrent.ExecutorProviderFactory;
import org.kie.io.Resource;
import org.kie.io.ResourceChangeNotifier;
import org.kie.io.ResourceChangeScanner;
import org.kie.io.ResourceChangeScannerConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResourceChangeScannerImpl
implements
ResourceChangeScanner {
private final Logger logger = LoggerFactory.getLogger( ResourceChangeScanner.class );
private final Map<Resource, Set<ResourceChangeNotifier>> resources;
private final Set<Resource> directories;
private int interval;
private Future<Boolean> scannerSchedulerExecutor;
private ProcessChangeSet scannerScheduler;
public ResourceChangeScannerImpl() {
this.resources = new HashMap<Resource, Set<ResourceChangeNotifier>>();
this.directories = new HashSet<Resource>();
this.setInterval( 60 );
logger.info( "ResourceChangeScanner created with default interval=60" );
}
public void configure(ResourceChangeScannerConfiguration configuration) {
this.setInterval( ((ResourceChangeScannerConfigurationImpl) configuration).getInterval() );
logger.info( "ResourceChangeScanner reconfigured with interval=" + getInterval() );
// restart it if it's already running.
if ( this.scannerScheduler != null && this.scannerScheduler.isRunning() ) {
stop();
start();
}
}
public ResourceChangeScannerConfiguration newResourceChangeScannerConfiguration() {
return new ResourceChangeScannerConfigurationImpl();
}
public ResourceChangeScannerConfiguration newResourceChangeScannerConfiguration(Properties properties) {
return new ResourceChangeScannerConfigurationImpl( properties );
}
public void subscribeNotifier(ResourceChangeNotifier notifier,
Resource resource) {
synchronized ( this.resources ) {
if ( ((InternalResource) resource).isDirectory() ) {
this.directories.add( resource );
}
Set<ResourceChangeNotifier> notifiers = this.resources.get( resource );
if ( notifiers == null ) {
notifiers = new HashSet<ResourceChangeNotifier>();
this.resources.put( resource,
notifiers );
}
logger.debug( "ResourceChangeScanner subcribing notifier=" + notifier + " to resource=" + resource );
notifiers.add( notifier );
}
}
public void unsubscribeNotifier(ResourceChangeNotifier notifier,
Resource resource) {
synchronized ( this.resources ) {
Set<ResourceChangeNotifier> notifiers = this.resources.get( resource );
if ( notifiers == null ) {
return;
}
logger.debug( "ResourceChangeScanner unsubcribing notifier=" + notifier + " to resource=" + resource );
notifiers.remove( notifier );
if ( notifiers.isEmpty() ) {
logger.debug( "ResourceChangeScanner resource=" + resource + " now has no subscribers" );
this.resources.remove( resource );
this.directories.remove( resource ); // don't bother with
// isDirectory check, as
// doing a remove is
// harmless if it doesn't
// exist
}
}
}
public Map<Resource, Set<ResourceChangeNotifier>> getResources() {
return resources;
}
public void scan() {
logger.debug( "ResourceChangeScanner attempt to scan " + this.resources.size() + " resources" );
synchronized ( this.resources ) {
Map<ResourceChangeNotifier, ChangeSet> notifications = new HashMap<ResourceChangeNotifier, ChangeSet>();
List<Resource> removed = new ArrayList<Resource>();
// detect modified and added
for ( Resource resource : this.directories ) {
logger.debug( "ResourceChangeScanner scanning directory=" + resource );
for ( Resource child : ((InternalResource) resource).listResources() ) {
if ( ((InternalResource) child).isDirectory() ) {
continue; // ignore sub directories
}
if ( !this.resources.containsKey( child ) ) {
logger.debug( "ResourceChangeScanner new resource=" + child );
// child is new
((InternalResource) child).setResourceType( ((InternalResource) resource).getResourceType() );
Set<ResourceChangeNotifier> notifiers = this.resources.get( resource ); // get notifiers for this
// directory
for ( ResourceChangeNotifier notifier : notifiers ) {
ChangeSetImpl changeSet = (ChangeSetImpl) notifications.get( notifier );
if ( changeSet == null ) {
// lazy initialise changeSet
changeSet = new ChangeSetImpl();
notifications.put( notifier,
changeSet );
}
if ( changeSet.getResourcesAdded().isEmpty() ) {
changeSet.setResourcesAdded( new ArrayList<Resource>() );
}
changeSet.getResourcesAdded().add( child );
notifier.subscribeChildResource( resource,
child );
}
}
}
}
for ( Entry<Resource, Set<ResourceChangeNotifier>> entry : this.resources.entrySet() ) {
Resource resource = entry.getKey();
Set<ResourceChangeNotifier> notifiers = entry.getValue();
if ( !((InternalResource) resource).isDirectory() ) {
// detect if Resource has been removed
long lastModified = ((InternalResource) resource).getLastModified();
long lastRead = ((InternalResource) resource).getLastRead();
if ( lastModified == 0 ) {
logger.debug( "ResourceChangeScanner removed resource=" + resource );
removed.add( resource );
// resource is no longer present
// iterate notifiers for this resource and add to each
// removed
for ( ResourceChangeNotifier notifier : notifiers ) {
ChangeSetImpl changeSet = (ChangeSetImpl) notifications.get( notifier );
if ( changeSet == null ) {
// lazy initialise changeSet
changeSet = new ChangeSetImpl();
notifications.put( notifier,
changeSet );
}
if ( changeSet.getResourcesRemoved().isEmpty() ) {
changeSet.setResourcesRemoved( new ArrayList<Resource>() );
}
changeSet.getResourcesRemoved().add( resource );
}
} else if ( lastRead < lastModified ) {
logger.debug( "ResourceChangeScanner modified resource=" + resource + " : " + lastRead + " : " + lastModified );
// it's modified
// iterate notifiers for this resource and add to each
// modified
for ( ResourceChangeNotifier notifier : notifiers ) {
ChangeSetImpl changeSet = (ChangeSetImpl) notifications.get( notifier );
if ( changeSet == null ) {
// lazy initialise changeSet
changeSet = new ChangeSetImpl();
notifications.put( notifier,
changeSet );
}
if ( changeSet.getResourcesModified().isEmpty() ) {
changeSet.setResourcesModified( new ArrayList<Resource>() );
}
changeSet.getResourcesModified().add( resource );
}
}
}
}
// now iterate and removed the removed resources, we do this so as
// not to mutate the foreach loop while iterating
for ( Resource resource : removed ) {
this.resources.remove( resource );
}
for ( Entry<ResourceChangeNotifier, ChangeSet> entry : notifications.entrySet() ) {
ResourceChangeNotifier notifier = entry.getKey();
ChangeSet changeSet = entry.getValue();
notifier.publishChangeSet( changeSet );
}
}
}
public void setInterval(int interval) {
if ( interval <= 0 ) {
throw new IllegalArgumentException( "Invalid interval time: " + interval + ". It should be a positive number bigger than 0" );
}
this.interval = interval;
logger.info( "ResourceChangeScanner reconfigured with interval=" + getInterval() );
if ( this.scannerScheduler != null && this.scannerScheduler.isRunning() ) {
stop();
start();
}
}
public int getInterval() {
return this.interval;
}
public void start() {
this.scannerScheduler = new ProcessChangeSet( this.resources,
this,
this.interval );
this.scannerSchedulerExecutor =
ExecutorProviderFactory.getExecutorProvider().<Boolean>getCompletionService()
.submit(this.scannerScheduler, true);
}
public void stop() {
if ( this.scannerScheduler != null && this.scannerScheduler.isRunning() ) {
this.scannerScheduler.stop();
this.scannerSchedulerExecutor.cancel(true);
this.scannerScheduler = null;
}
}
public void reset() {
this.resources.clear();
this.directories.clear();
}
public static class ProcessChangeSet
implements
Runnable {
private final Logger logger = LoggerFactory.getLogger( ProcessChangeSet.class );
private volatile boolean scan;
private final ResourceChangeScannerImpl scanner;
private final long interval;
private final Map<Resource, Set<ResourceChangeNotifier>> resources;
ProcessChangeSet(Map<Resource, Set<ResourceChangeNotifier>> resources,
ResourceChangeScannerImpl scanner,
int interval) {
this.resources = resources;
this.scanner = scanner;
this.interval = interval;
this.scan = true;
}
public int getInterval() {
return (int) this.interval;
}
public void stop() {
this.scan = false;
}
public boolean isRunning() {
return this.scan;
}
public void run() {
synchronized ( this ) {
if ( this.scan ) {
this.logger.info( "ResourceChangeNotification scanner has started" );
}
while ( this.scan ) {
try {
// logger.trace( "BEFORE : sync this.resources" );
synchronized ( this.resources ) {
// logger.trace( "DURING : sync this.resources" );
// lock the resources, as we don't want this modified
// while processing
this.scanner.scan();
}
// logger.trace( "AFTER : SCAN" );
} catch (RuntimeException e) {
this.logger.error( e.getMessage(), e );
} catch (Error e) {
this.logger.error( e.getMessage(), e );
}
try {
this.logger.debug( "ResourceChangeScanner thread is waiting for " + this.interval + " seconds." );
wait( this.interval * 1000 );
} catch ( InterruptedException e ) {
if ( this.scan ) {
this.logger.error( e.getMessage(), new RuntimeException( "ResourceChangeNotification ChangeSet scanning thread was interrupted, but shutdown was not requested",
e ) );
}
}
}
this.logger.info( "ResourceChangeNotification scanner has stopped" );
}
}
}
public void setSystemEventListener(SystemEventListener listener) {
// TODO Auto-generated method stub
}
}
| drools-core/src/main/java/org/drools/io/impl/ResourceChangeScannerImpl.java | /*
* Copyright 2010 JBoss Inc
*
* 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.drools.io.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.Future;
import org.drools.io.internal.InternalResource;
import org.kie.ChangeSet;
import org.kie.SystemEventListener;
import org.kie.concurrent.ExecutorProviderFactory;
import org.kie.io.Resource;
import org.kie.io.ResourceChangeNotifier;
import org.kie.io.ResourceChangeScanner;
import org.kie.io.ResourceChangeScannerConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResourceChangeScannerImpl
implements
ResourceChangeScanner {
private final Logger logger = LoggerFactory.getLogger( ResourceChangeScanner.class );
private final Map<Resource, Set<ResourceChangeNotifier>> resources;
private final Set<Resource> directories;
private int interval;
private Future<Boolean> scannerSchedulerExecutor;
private ProcessChangeSet scannerScheduler;
public ResourceChangeScannerImpl() {
this.resources = new HashMap<Resource, Set<ResourceChangeNotifier>>();
this.directories = new HashSet<Resource>();
this.setInterval( 60 );
logger.info( "ResourceChangeScanner created with default interval=60" );
}
public void configure(ResourceChangeScannerConfiguration configuration) {
this.setInterval( ((ResourceChangeScannerConfigurationImpl) configuration).getInterval() );
logger.info( "ResourceChangeScanner reconfigured with interval=" + getInterval() );
// restart it if it's already running.
if ( this.scannerScheduler != null && this.scannerScheduler.isRunning() ) {
stop();
start();
}
}
public ResourceChangeScannerConfiguration newResourceChangeScannerConfiguration() {
return new ResourceChangeScannerConfigurationImpl();
}
public ResourceChangeScannerConfiguration newResourceChangeScannerConfiguration(Properties properties) {
return new ResourceChangeScannerConfigurationImpl( properties );
}
public void subscribeNotifier(ResourceChangeNotifier notifier,
Resource resource) {
synchronized ( this.resources ) {
if ( ((InternalResource) resource).isDirectory() ) {
this.directories.add( resource );
}
Set<ResourceChangeNotifier> notifiers = this.resources.get( resource );
if ( notifiers == null ) {
notifiers = new HashSet<ResourceChangeNotifier>();
this.resources.put( resource,
notifiers );
}
logger.debug( "ResourceChangeScanner subcribing notifier=" + notifier + " to resource=" + resource );
notifiers.add( notifier );
}
}
public void unsubscribeNotifier(ResourceChangeNotifier notifier,
Resource resource) {
synchronized ( this.resources ) {
Set<ResourceChangeNotifier> notifiers = this.resources.get( resource );
if ( notifiers == null ) {
return;
}
logger.debug( "ResourceChangeScanner unsubcribing notifier=" + notifier + " to resource=" + resource );
notifiers.remove( notifier );
if ( notifiers.isEmpty() ) {
logger.debug( "ResourceChangeScanner resource=" + resource + " now has no subscribers" );
this.resources.remove( resource );
this.directories.remove( resource ); // don't bother with
// isDirectory check, as
// doing a remove is
// harmless if it doesn't
// exist
}
}
}
public Map<Resource, Set<ResourceChangeNotifier>> getResources() {
return resources;
}
public void scan() {
logger.debug( "ResourceChangeScanner attempt to scan " + this.resources.size() + " resources" );
synchronized ( this.resources ) {
Map<ResourceChangeNotifier, ChangeSet> notifications = new HashMap<ResourceChangeNotifier, ChangeSet>();
List<Resource> removed = new ArrayList<Resource>();
// detect modified and added
for ( Resource resource : this.directories ) {
logger.debug( "ResourceChangeScanner scanning directory=" + resource );
for ( Resource child : ((InternalResource) resource).listResources() ) {
if ( ((InternalResource) child).isDirectory() ) {
continue; // ignore sub directories
}
if ( !this.resources.containsKey( child ) ) {
logger.debug( "ResourceChangeScanner new resource=" + child );
// child is new
((InternalResource) child).setResourceType( ((InternalResource) resource).getResourceType() );
Set<ResourceChangeNotifier> notifiers = this.resources.get( resource ); // get notifiers for this
// directory
for ( ResourceChangeNotifier notifier : notifiers ) {
ChangeSetImpl changeSet = (ChangeSetImpl) notifications.get( notifier );
if ( changeSet == null ) {
// lazy initialise changeSet
changeSet = new ChangeSetImpl();
notifications.put( notifier,
changeSet );
}
if ( changeSet.getResourcesAdded().isEmpty() ) {
changeSet.setResourcesAdded( new ArrayList<Resource>() );
}
changeSet.getResourcesAdded().add( child );
notifier.subscribeChildResource( resource,
child );
}
}
}
}
for ( Entry<Resource, Set<ResourceChangeNotifier>> entry : this.resources.entrySet() ) {
Resource resource = entry.getKey();
Set<ResourceChangeNotifier> notifiers = entry.getValue();
if ( !((InternalResource) resource).isDirectory() ) {
// detect if Resource has been removed
long lastModified = ((InternalResource) resource).getLastModified();
long lastRead = ((InternalResource) resource).getLastRead();
if ( lastModified == 0 ) {
logger.debug( "ResourceChangeScanner removed resource=" + resource );
removed.add( resource );
// resource is no longer present
// iterate notifiers for this resource and add to each
// removed
for ( ResourceChangeNotifier notifier : notifiers ) {
ChangeSetImpl changeSet = (ChangeSetImpl) notifications.get( notifier );
if ( changeSet == null ) {
// lazy initialise changeSet
changeSet = new ChangeSetImpl();
notifications.put( notifier,
changeSet );
}
if ( changeSet.getResourcesRemoved().isEmpty() ) {
changeSet.setResourcesRemoved( new ArrayList<Resource>() );
}
changeSet.getResourcesRemoved().add( resource );
}
} else if ( lastRead < lastModified && lastRead >= 0 ) {
logger.debug( "ResourceChangeScanner modified resource=" + resource + " : " + lastRead + " : " + lastModified );
// it's modified
// iterate notifiers for this resource and add to each
// modified
for ( ResourceChangeNotifier notifier : notifiers ) {
ChangeSetImpl changeSet = (ChangeSetImpl) notifications.get( notifier );
if ( changeSet == null ) {
// lazy initialise changeSet
changeSet = new ChangeSetImpl();
notifications.put( notifier,
changeSet );
}
if ( changeSet.getResourcesModified().isEmpty() ) {
changeSet.setResourcesModified( new ArrayList<Resource>() );
}
changeSet.getResourcesModified().add( resource );
}
}
}
}
// now iterate and removed the removed resources, we do this so as
// not to mutate the foreach loop while iterating
for ( Resource resource : removed ) {
this.resources.remove( resource );
}
for ( Entry<ResourceChangeNotifier, ChangeSet> entry : notifications.entrySet() ) {
ResourceChangeNotifier notifier = entry.getKey();
ChangeSet changeSet = entry.getValue();
notifier.publishChangeSet( changeSet );
}
}
}
public void setInterval(int interval) {
if ( interval <= 0 ) {
throw new IllegalArgumentException( "Invalid interval time: " + interval + ". It should be a positive number bigger than 0" );
}
this.interval = interval;
logger.info( "ResourceChangeScanner reconfigured with interval=" + getInterval() );
if ( this.scannerScheduler != null && this.scannerScheduler.isRunning() ) {
stop();
start();
}
}
public int getInterval() {
return this.interval;
}
public void start() {
this.scannerScheduler = new ProcessChangeSet( this.resources,
this,
this.interval );
this.scannerSchedulerExecutor =
ExecutorProviderFactory.getExecutorProvider().<Boolean>getCompletionService()
.submit(this.scannerScheduler, true);
}
public void stop() {
if ( this.scannerScheduler != null && this.scannerScheduler.isRunning() ) {
this.scannerScheduler.stop();
this.scannerSchedulerExecutor.cancel(true);
this.scannerScheduler = null;
}
}
public void reset() {
this.resources.clear();
this.directories.clear();
}
public static class ProcessChangeSet
implements
Runnable {
private final Logger logger = LoggerFactory.getLogger( ProcessChangeSet.class );
private volatile boolean scan;
private final ResourceChangeScannerImpl scanner;
private final long interval;
private final Map<Resource, Set<ResourceChangeNotifier>> resources;
ProcessChangeSet(Map<Resource, Set<ResourceChangeNotifier>> resources,
ResourceChangeScannerImpl scanner,
int interval) {
this.resources = resources;
this.scanner = scanner;
this.interval = interval;
this.scan = true;
}
public int getInterval() {
return (int) this.interval;
}
public void stop() {
this.scan = false;
}
public boolean isRunning() {
return this.scan;
}
public void run() {
synchronized ( this ) {
if ( this.scan ) {
this.logger.info( "ResourceChangeNotification scanner has started" );
}
while ( this.scan ) {
try {
// logger.trace( "BEFORE : sync this.resources" );
synchronized ( this.resources ) {
// logger.trace( "DURING : sync this.resources" );
// lock the resources, as we don't want this modified
// while processing
this.scanner.scan();
}
// logger.trace( "AFTER : SCAN" );
} catch (RuntimeException e) {
this.logger.error( e.getMessage(), e );
} catch (Error e) {
this.logger.error( e.getMessage(), e );
}
try {
this.logger.debug( "ResourceChangeScanner thread is waiting for " + this.interval + " seconds." );
wait( this.interval * 1000 );
} catch ( InterruptedException e ) {
if ( this.scan ) {
this.logger.error( e.getMessage(), new RuntimeException( "ResourceChangeNotification ChangeSet scanning thread was interrupted, but shutdown was not requested",
e ) );
}
}
}
this.logger.info( "ResourceChangeNotification scanner has stopped" );
}
}
}
public void setSystemEventListener(SystemEventListener listener) {
// TODO Auto-generated method stub
}
}
| DROOLS-65,BZ917787: fixing conditional to allow cache update altough client is restarted
(cherry picked from commit 133058fd496fe002781ce533145a108520b6933d)
Conflicts:
drools-core/src/main/java/org/drools/io/impl/ResourceChangeScannerImpl.java
| drools-core/src/main/java/org/drools/io/impl/ResourceChangeScannerImpl.java | DROOLS-65,BZ917787: fixing conditional to allow cache update altough client is restarted (cherry picked from commit 133058fd496fe002781ce533145a108520b6933d) | <ide><path>rools-core/src/main/java/org/drools/io/impl/ResourceChangeScannerImpl.java
<ide> }
<ide> changeSet.getResourcesRemoved().add( resource );
<ide> }
<del> } else if ( lastRead < lastModified && lastRead >= 0 ) {
<add> } else if ( lastRead < lastModified ) {
<ide> logger.debug( "ResourceChangeScanner modified resource=" + resource + " : " + lastRead + " : " + lastModified );
<ide> // it's modified
<ide> // iterate notifiers for this resource and add to each |
|
JavaScript | agpl-3.0 | 116dbbf5326aed20589bf0c72b06cb1bd6742b2e | 0 | OpenLMIS/open-lmis,kelvinmbwilo/vims,OpenLMIS/open-lmis,kelvinmbwilo/vims,USAID-DELIVER-PROJECT/elmis,USAID-DELIVER-PROJECT/elmis,OpenLMIS/open-lmis,kelvinmbwilo/vims,USAID-DELIVER-PROJECT/elmis,OpenLMIS/open-lmis,kelvinmbwilo/vims,USAID-DELIVER-PROJECT/elmis | /*
* This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public License for more details.
*
* You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/
*/
function EquipmentInventoryController($scope, UserFacilityList, EquipmentInventories, ManageEquipmentInventoryProgramList, ManageEquipmentInventoryFacilityProgramList, EquipmentInventoryFacilities, EquipmentTypesByProgram, EquipmentOperationalStatus, navigateBackService, $routeParams, messageService) {
$scope.loadFacilitiesAndPrograms = function (selectedType) {
if (selectedType === "0") { // My facility
// Get facility first, then programs through facility
UserFacilityList.get({}, function (data) {
$scope.facilities = data.facilityList;
$scope.myFacility = data.facilityList[0];
if ($scope.myFacility) {
$scope.facilityDisplayName = $scope.myFacility.code + ' - ' + $scope.myFacility.name;
ManageEquipmentInventoryFacilityProgramList.get({facilityId: $scope.myFacility.id}, function (data) {
$scope.programs = data.programs;
}, {});
} else {
$scope.facilityDisplayName = messageService.get("label.none.assigned");
$scope.programs = undefined;
}
}, {});
} else if (selectedType === "1") { // Supervised facility
// Get programs first through supervisory nodes/requisition groups, then get facilities through programs
ManageEquipmentInventoryProgramList.get({}, function (data) {
$scope.programs = data.programs;
}, {});
}
$scope.equipmentTypes = undefined;
$scope.selectedEquipmentType = undefined;
};
$scope.loadFacilitiesAndEquipmentTypes = function () {
$scope.loadFacilitiesForProgram();
$scope.loadEquipmentTypesForProgram();
};
$scope.loadFacilitiesForProgram = function () {
if ($scope.selectedProgram.id && $scope.selectedType === "1") {
EquipmentInventoryFacilities.get({programId: $scope.selectedProgram.id}, function (data) {
$scope.facilities = data.facilities;
}, {});
}
};
$scope.loadEquipmentTypesForProgram = function () {
EquipmentTypesByProgram.get({programId: $scope.selectedProgram.id}, function (data) {
$scope.equipmentTypes = data.equipment_types;
}, {});
};
$scope.loadEquipments = function () {
for (var i = 0; i < $scope.equipmentTypes.length; i++) {
if ($scope.equipmentTypes[i].id.toString() === $scope.selectedEquipmentType.id) {
$scope.selectedEquipmentType = $scope.equipmentTypes[i];
}
}
if ($scope.facilities && $scope.selectedProgram && $scope.selectedEquipmentType) {
EquipmentInventories.get({
programId: $scope.selectedProgram.id,
facilityId: $scope.myFacility.id
}, function (data) {
$scope.inventory = data.inventory;
});
}
};
// $scope.$on('$viewContentLoaded', function () {
$scope.selectedType = $routeParams.selectedType || "0";
/*
$scope.$watch('programs', function () {
if ($scope.programs && !isUndefined($routeParams.program)) {
$scope.selectedProgram = _.where($scope.programs, {id: $routeParams.program})[0];
}
});
*/
$scope.loadFacilitiesAndPrograms($scope.selectedType);
// });
EquipmentOperationalStatus.get(function(data){
$scope.operationalStatusList = data.status;
});
$scope.getStatusName = function (statusId) {
for (var i = 0; i < $scope.operationalStatusList.length; i++) {
if ($scope.operationalStatusList[i].id === statusId) {
return $scope.operationalStatusList[i].name;
}
}
};
$scope.getAge = function (yearOfInstallation) {
return (new Date().getFullYear()) - yearOfInstallation;
};
} | modules/openlmis-web/src/main/webapp/public/js/admin/equipment/inventory/controller/equipment-inventory-controller.js | /*
* This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public License for more details.
*
* You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/
*/
function EquipmentInventoryController($scope, UserFacilityList, EquipmentInventories, ManageEquipmentInventoryProgramList, ManageEquipmentInventoryFacilityProgramList, EquipmentInventoryFacilities, EquipmentTypesByProgram, EquipmentOperationalStatus, navigateBackService, $routeParams, messageService) {
$scope.loadFacilitiesAndPrograms = function (selectedType) {
if (selectedType === "0") { // My facility
// Get facility first, then programs through facility
UserFacilityList.get({}, function (data) {
$scope.facilities = data.facilityList;
$scope.myFacility = data.facilityList[0];
if ($scope.myFacility) {
$scope.facilityDisplayName = $scope.myFacility.code + ' - ' + $scope.myFacility.name;
ManageEquipmentInventoryFacilityProgramList.get({facilityId: $scope.myFacility.id}, function (data) {
$scope.programs = data.programs;
}, {});
} else {
$scope.facilityDisplayName = messageService.get("label.none.assigned");
$scope.programs = undefined;
}
}, {});
} else if (selectedType === "1") { // Supervised facility
// Get programs first through supervisory nodes/requisition groups, then get facilities through programs
ManageEquipmentInventoryProgramList.get({}, function (data) {
$scope.programs = data.programs;
}, {});
}
$scope.equipmentTypes = undefined;
$scope.selectedEquipmentType = undefined;
};
$scope.loadFacilitiesAndEquipmentTypes = function () {
$scope.loadFacilitiesForProgram();
$scope.loadEquipmentTypesForProgram();
};
$scope.loadFacilitiesForProgram = function () {
if ($scope.selectedProgram.id && $scope.selectedType === "1") {
EquipmentInventoryFacilities.get({programId: $scope.selectedProgram.id}, function (data) {
$scope.facilities = data.facilities;
}, {});
}
};
$scope.loadEquipmentTypesForProgram = function () {
EquipmentTypesByProgram.get({programId: $scope.selectedProgram.id}, function (data) {
$scope.equipmentTypes = data.equipment_types;
}, {});
};
$scope.loadEquipments = function () {
for (var i = 0; i < $scope.equipmentTypes.length; i++) {
if ($scope.equipmentTypes[i].id.toString() === $scope.selectedEquipmentType.id) {
$scope.selectedEquipmentType = $scope.equipmentTypes[i];
}
}
if ($scope.facilities && $scope.selectedProgram && $scope.selectedEquipmentType) {
EquipmentInventories.get({
programId: $scope.selectedProgram.id,
facilityId: $scope.myFacility.id
}, function (data) {
$scope.inventory = data.inventory;
});
}
};
// $scope.$on('$viewContentLoaded', function () {
$scope.selectedType = $routeParams.selectedType || "0";
/*
$scope.$watch('programs', function () {
if ($scope.programs && !isUndefined($routeParams.program)) {
$scope.selectedProgram = _.where($scope.programs, {id: $routeParams.program})[0];
}
});
*/
$scope.loadFacilitiesAndPrograms($scope.selectedType);
// });
EquipmentOperationalStatus.get(function(data){
$scope.operationalStatusList = data.status;
});
$scope.getStatusName = function (statusId) {
for (var i = 0; i < $scope.operationalStatusList.length; i++) {
if ($scope.operationalStatusList[i].id === statusId) {
return $scope.operationalStatusList[i].name;
}
}
};
$scope.getAge = function (yearOfInstallation) {
return (new Date().getFullYear()) - yearOfInstallation;
}
} | Fix jsHint error
| modules/openlmis-web/src/main/webapp/public/js/admin/equipment/inventory/controller/equipment-inventory-controller.js | Fix jsHint error | <ide><path>odules/openlmis-web/src/main/webapp/public/js/admin/equipment/inventory/controller/equipment-inventory-controller.js
<ide>
<ide> $scope.getAge = function (yearOfInstallation) {
<ide> return (new Date().getFullYear()) - yearOfInstallation;
<del> }
<add> };
<ide>
<ide> } |
|
Java | mit | 98cae612055b822708e6e4ca75a437062081e455 | 0 | fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg | package ua.com.fielden.platform.dao;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchAndInstrument;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.from;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.select;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.function.Function;
import com.google.inject.Inject;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.AbstractFunctionalEntityForCollectionModification;
import ua.com.fielden.platform.entity.factory.EntityFactory;
import ua.com.fielden.platform.entity.factory.ICompanionObjectFinder;
import ua.com.fielden.platform.entity.query.fluent.fetch;
import ua.com.fielden.platform.error.Result;
import ua.com.fielden.platform.reflection.PropertyTypeDeterminator;
import ua.com.fielden.platform.web.centre.CentreContext;
/**
* A base producer for {@link AbstractFunctionalEntityForCollectionModification} descendants.
* <p>
* Implementors should implement method {@link #provideCurrentlyAssociatedValues(AbstractFunctionalEntityForCollectionModification, AbstractEntity)} to initialise
* the properties for this functional action.
* <p>
* This producer also initialises the master entity for this action. The master entity gets assigned into 'key'. To get properly fetched instance of
* master entity there is a need to implement method {@link #fetchModelForMasterEntity()}. To specify, how to get the master entity from context, method {@link #getMasterEntityFromContext(CentreContext)}
* needs to be implemented.
*
* @author TG Team
*
*/
public abstract class AbstractFunctionalEntityProducerForCollectionModification<MASTER_TYPE extends AbstractEntity<?>, T extends AbstractFunctionalEntityForCollectionModification<MASTER_TYPE, ?>> extends DefaultEntityProducerWithContext<T, T> implements IEntityProducer<T> {
private final IEntityDao<T> companion;
private final ICompanionObjectFinder companionFinder;
private final Class<MASTER_TYPE> masterEntityType;
private static final String TRY_AGAIN_MSG = "Please cancel this action and try again!";
@Inject
public AbstractFunctionalEntityProducerForCollectionModification(final EntityFactory factory, final Class<T> actionType, final ICompanionObjectFinder companionFinder) {
super(factory, actionType, companionFinder);
this.masterEntityType = (Class<MASTER_TYPE>) PropertyTypeDeterminator.determinePropertyType(actionType, AbstractEntity.KEY);
this.companion = companionFinder.find(actionType);
this.companionFinder = companionFinder;
}
/**
* Retrieves master entity from context. Need to implement this for concrete action. Most likely the master entity is <code>context.getCurrEntity()</code> or <code>context.getMasterEntity()</code>.
*
* @return
*/
protected abstract AbstractEntity<?> getMasterEntityFromContext(final CentreContext<?, ?> context);
protected abstract fetch<MASTER_TYPE> fetchModelForMasterEntity();
@Override
protected final T provideDefaultValues(final T entity) {
if (getCentreContext() == null) {
return entity; // this is used for Cancel button (no context is needed)
}
entity.setContext(getCentreContext());
final AbstractEntity<?> masterEntityFromContext = getMasterEntityFromContext(entity.getContext());
if (masterEntityFromContext == null) {
throw Result.failure("The master entity for collection modification is not provided in the context.");
}
if (masterEntityFromContext.isDirty()) {
throw Result.failure("This action is applicable only to a saved entity! Please save entity and try again!");
}
// TODO
// TODO There is a need to have more customizable way to re-retrieve masterEntity, in some cases, without re-retrieval at all
// TODO
final MASTER_TYPE masterEntity = (MASTER_TYPE) masterEntityFromContext; // companionFinder.find(masterEntityType).findById(masterEntityFromContext.getId(), fetchModelForMasterEntity());
if (masterEntity == null) {
throw Result.failure("The master entity has been deleted. " + TRY_AGAIN_MSG);
}
// IMPORTANT: it is necessary to reset state for "key" property after its change.
// This is necessary to make the property marked as 'not changed from original' (origVal == val == 'DEMO') to be able not to re-apply afterwards
// the initial value against "key" property
entity.setKey(masterEntity);
entity.getProperty(AbstractEntity.KEY).resetState();
// TODO
// TODO There is a need to have ability to use non-persistent master functional entities, without surrogate ids:
// TODO
// final T previouslyPersistedAction = retrieveActionFor(masterEntity, companion, entityType);
// IMPORTANT: it is necessary not to reset state for "surrogateVersion" property after its change.
// This is necessary to leave the property marked as 'changed from original' (origVal == null) to be able to apply afterwards
// the initial value against '"surrogateVersion", that was possibly changed by another user'
// entity.setSurrogateVersion(surrogateVersion(previouslyPersistedAction));
entity.setSurrogateVersion(new Random().nextLong());
return provideCurrentlyAssociatedValues(entity, masterEntity);
}
/**
* Implement this method to initialise 1) 'chosenIds' 2) collection of all available entities.
* <p>
* 'chosenIds' property needs to be filled in with ids of those entities, that are present in master entity collection in concrete moment. The order of this ids might be relevant or not,
* depending on the relevance of the order in master entity collection.
* <p>
* 'all available entities' property should be filled in with the fully-fledged entities (with their keys and descriptions etc), that can be chosen as collection items.
*
* @param entity
* @param masterEntity
*
* @return
*/
protected abstract T provideCurrentlyAssociatedValues(final T entity, final MASTER_TYPE masterEntity);
private static <T extends AbstractEntity<?>> Long surrogateVersion(final T persistedEntity) {
return persistedEntity == null ? 99L : (persistedEntity.getVersion() + 100L);
}
private static <MASTER_TYPE extends AbstractEntity<?>, T extends AbstractFunctionalEntityForCollectionModification<MASTER_TYPE, ?>> T retrieveActionFor(final MASTER_TYPE masterEntity, final IEntityDao<T> companion, final Class<T> actionType) {
return companion.getEntity(
from(select(actionType).where().prop(AbstractEntity.KEY).eq().val(masterEntity).model())
.with(fetchAndInstrument(actionType).with(AbstractEntity.KEY)).model()
);
}
/**
* Validates restored action (it was "produced" by corresponding producer) on subject of 1) removal of available collectional items 2) concurrent modification of the same collection for the same master entity.
* After the validation has
*
* @param action
* @param availableEntitiesGetter
* @param companion
* @param factory
* @return
*/
public static <MASTER_TYPE extends AbstractEntity<?>, ITEM extends AbstractEntity<?>, T extends AbstractFunctionalEntityForCollectionModification<MASTER_TYPE, ID_TYPE>, ID_TYPE> T validateAction(final T action, final Function<T, Collection<ITEM>> availableEntitiesGetter, final IEntityDao<T> companion, final EntityFactory factory, final Class<ID_TYPE> idType) {
final Result res = action.isValid();
// throw validation result of the action if it is not successful:
if (!res.isSuccessful()) {
throw res;
}
final MASTER_TYPE masterEntityBeingUpdated = action.getKey(); // existence of master entity is checked during "producing" of functional action
final Map<Object, ITEM> availableEntities = mapById(availableEntitiesGetter.apply(action), idType);
for (final ID_TYPE addedId : action.getAddedIds()) {
if (!availableEntities.containsKey(addedId)) {
throw Result.failure("Another user has deleted the item, that you're trying to choose. " + TRY_AGAIN_MSG);
}
}
for (final ID_TYPE removedId : action.getRemovedIds()) {
if (!availableEntities.containsKey(removedId)) {
throw Result.failure("Another user has deleted the item, that you're trying to un-tick. " + TRY_AGAIN_MSG);
}
}
final Class<T> actionType = (Class<T>) action.getType();
final T persistedEntity = retrieveActionFor(masterEntityBeingUpdated, companion, actionType);
if (surrogateVersion(persistedEntity) > action.getSurrogateVersion()) {
throw Result.failure("Another user has changed the chosen items. " + TRY_AGAIN_MSG);
}
final T entityToSave;
// the next block of code is intended to mark entityToSave as 'dirty' to be properly saved and to increase its db-related version. New entity (persistedEntity == null) is always dirty - no need to do anything.
if (persistedEntity != null) {
entityToSave = persistedEntity;
entityToSave.setSurrogateVersion(persistedEntity.getVersion() + 1L);
} else {
entityToSave = factory.newEntity(actionType, null);
entityToSave.setKey(masterEntityBeingUpdated);
}
return entityToSave;
}
/**
* Returns the map between id and the entity with that id.
*
* @param entities
* @return
*/
public static <T extends AbstractEntity<?>> Map<Object, T> mapById(final Collection<T> entities, final Class<?> idType) {
final Map<Object, T> map = new HashMap<>();
final boolean isLongId = Long.class.isAssignableFrom(idType);
for (final T entity : entities) {
if (isLongId) {
map.put(entity.getId(), entity);
} else {
map.put(entity.getKey(), entity);
}
}
return map;
}
} | platform-pojo-bl/src/main/java/ua/com/fielden/platform/dao/AbstractFunctionalEntityProducerForCollectionModification.java | package ua.com.fielden.platform.dao;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchAndInstrument;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.from;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.select;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import com.google.inject.Inject;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.AbstractFunctionalEntityForCollectionModification;
import ua.com.fielden.platform.entity.factory.EntityFactory;
import ua.com.fielden.platform.entity.factory.ICompanionObjectFinder;
import ua.com.fielden.platform.entity.query.fluent.fetch;
import ua.com.fielden.platform.error.Result;
import ua.com.fielden.platform.reflection.PropertyTypeDeterminator;
import ua.com.fielden.platform.web.centre.CentreContext;
/**
* A base producer for {@link AbstractFunctionalEntityForCollectionModification} descendants.
* <p>
* Implementors should implement method {@link #provideCurrentlyAssociatedValues(AbstractFunctionalEntityForCollectionModification, AbstractEntity)} to initialise
* the properties for this functional action.
* <p>
* This producer also initialises the master entity for this action. The master entity gets assigned into 'key'. To get properly fetched instance of
* master entity there is a need to implement method {@link #fetchModelForMasterEntity()}. To specify, how to get the master entity from context, method {@link #getMasterEntityFromContext(CentreContext)}
* needs to be implemented.
*
* @author TG Team
*
*/
public abstract class AbstractFunctionalEntityProducerForCollectionModification<MASTER_TYPE extends AbstractEntity<?>, T extends AbstractFunctionalEntityForCollectionModification<MASTER_TYPE, ?>> extends DefaultEntityProducerWithContext<T, T> implements IEntityProducer<T> {
private final IEntityDao<T> companion;
private final ICompanionObjectFinder companionFinder;
private final Class<MASTER_TYPE> masterEntityType;
private static final String TRY_AGAIN_MSG = "Please cancel this action and try again!";
@Inject
public AbstractFunctionalEntityProducerForCollectionModification(final EntityFactory factory, final Class<T> actionType, final ICompanionObjectFinder companionFinder) {
super(factory, actionType, companionFinder);
this.masterEntityType = (Class<MASTER_TYPE>) PropertyTypeDeterminator.determinePropertyType(actionType, AbstractEntity.KEY);
this.companion = companionFinder.find(actionType);
this.companionFinder = companionFinder;
}
/**
* Retrieves master entity from context. Need to implement this for concrete action. Most likely the master entity is <code>context.getCurrEntity()</code> or <code>context.getMasterEntity()</code>.
*
* @return
*/
protected abstract AbstractEntity<?> getMasterEntityFromContext(final CentreContext<?, ?> context);
protected abstract fetch<MASTER_TYPE> fetchModelForMasterEntity();
@Override
protected final T provideDefaultValues(final T entity) {
if (getCentreContext() == null) {
return entity; // this is used for Cancel button (no context is needed)
}
entity.setContext(getCentreContext());
final AbstractEntity<?> masterEntityFromContext = getMasterEntityFromContext(entity.getContext());
if (masterEntityFromContext == null) {
throw Result.failure("The master entity for collection modification is not provided in the context.");
}
if (masterEntityFromContext.isDirty()) {
throw Result.failure("This action is applicable only to a saved entity! Please save entity and try again!");
}
final MASTER_TYPE masterEntity = companionFinder.find(masterEntityType).findById(masterEntityFromContext.getId(), fetchModelForMasterEntity());
if (masterEntity == null) {
throw Result.failure("The master entity has been deleted. " + TRY_AGAIN_MSG);
}
// IMPORTANT: it is necessary to reset state for "key" property after its change.
// This is necessary to make the property marked as 'not changed from original' (origVal == val == 'DEMO') to be able not to re-apply afterwards
// the initial value against "key" property
entity.setKey(masterEntity);
entity.getProperty(AbstractEntity.KEY).resetState();
final T previouslyPersistedAction = retrieveActionFor(masterEntity, companion, entityType);
// IMPORTANT: it is necessary not to reset state for "surrogateVersion" property after its change.
// This is necessary to leave the property marked as 'changed from original' (origVal == null) to be able to apply afterwards
// the initial value against '"surrogateVersion", that was possibly changed by another user'
entity.setSurrogateVersion(surrogateVersion(previouslyPersistedAction));
return provideCurrentlyAssociatedValues(entity, masterEntity);
}
/**
* Implement this method to initialise 1) 'chosenIds' 2) collection of all available entities.
* <p>
* 'chosenIds' property needs to be filled in with ids of those entities, that are present in master entity collection in concrete moment. The order of this ids might be relevant or not,
* depending on the relevance of the order in master entity collection.
* <p>
* 'all available entities' property should be filled in with the fully-fledged entities (with their keys and descriptions etc), that can be chosen as collection items.
*
* @param entity
* @param masterEntity
*
* @return
*/
protected abstract T provideCurrentlyAssociatedValues(final T entity, final MASTER_TYPE masterEntity);
private static <T extends AbstractEntity<?>> Long surrogateVersion(final T persistedEntity) {
return persistedEntity == null ? 99L : (persistedEntity.getVersion() + 100L);
}
private static <MASTER_TYPE extends AbstractEntity<?>, T extends AbstractFunctionalEntityForCollectionModification<MASTER_TYPE, ?>> T retrieveActionFor(final MASTER_TYPE masterEntity, final IEntityDao<T> companion, final Class<T> actionType) {
return companion.getEntity(
from(select(actionType).where().prop(AbstractEntity.KEY).eq().val(masterEntity).model())
.with(fetchAndInstrument(actionType).with(AbstractEntity.KEY)).model()
);
}
/**
* Validates restored action (it was "produced" by corresponding producer) on subject of 1) removal of available collectional items 2) concurrent modification of the same collection for the same master entity.
* After the validation has
*
* @param action
* @param availableEntitiesGetter
* @param companion
* @param factory
* @return
*/
public static <MASTER_TYPE extends AbstractEntity<?>, ITEM extends AbstractEntity<?>, T extends AbstractFunctionalEntityForCollectionModification<MASTER_TYPE, ID_TYPE>, ID_TYPE> T validateAction(final T action, final Function<T, Collection<ITEM>> availableEntitiesGetter, final IEntityDao<T> companion, final EntityFactory factory, final Class<ID_TYPE> idType) {
final Result res = action.isValid();
// throw validation result of the action if it is not successful:
if (!res.isSuccessful()) {
throw res;
}
final MASTER_TYPE masterEntityBeingUpdated = action.getKey(); // existence of master entity is checked during "producing" of functional action
final Map<Object, ITEM> availableEntities = mapById(availableEntitiesGetter.apply(action), idType);
for (final ID_TYPE addedId : action.getAddedIds()) {
if (!availableEntities.containsKey(addedId)) {
throw Result.failure("Another user has deleted the item, that you're trying to choose. " + TRY_AGAIN_MSG);
}
}
for (final ID_TYPE removedId : action.getRemovedIds()) {
if (!availableEntities.containsKey(removedId)) {
throw Result.failure("Another user has deleted the item, that you're trying to un-tick. " + TRY_AGAIN_MSG);
}
}
final Class<T> actionType = (Class<T>) action.getType();
final T persistedEntity = retrieveActionFor(masterEntityBeingUpdated, companion, actionType);
if (surrogateVersion(persistedEntity) > action.getSurrogateVersion()) {
throw Result.failure("Another user has changed the chosen items. " + TRY_AGAIN_MSG);
}
final T entityToSave;
// the next block of code is intended to mark entityToSave as 'dirty' to be properly saved and to increase its db-related version. New entity (persistedEntity == null) is always dirty - no need to do anything.
if (persistedEntity != null) {
entityToSave = persistedEntity;
entityToSave.setSurrogateVersion(persistedEntity.getVersion() + 1L);
} else {
entityToSave = factory.newEntity(actionType, null);
entityToSave.setKey(masterEntityBeingUpdated);
}
return entityToSave;
}
/**
* Returns the map between id and the entity with that id.
*
* @param entities
* @return
*/
public static <T extends AbstractEntity<?>> Map<Object, T> mapById(final Collection<T> entities, final Class<?> idType) {
final Map<Object, T> map = new HashMap<>();
final boolean isLongId = Long.class.isAssignableFrom(idType);
for (final T entity : entities) {
if (isLongId) {
map.put(entity.getId(), entity);
} else {
map.put(entity.getKey(), entity);
}
}
return map;
}
} | #334 Added some initial changes to base producer of 'collection modification func entity' to support: 1) better customisation of master func entity re-retrieval 2) support non-persistent types for func entity.
| platform-pojo-bl/src/main/java/ua/com/fielden/platform/dao/AbstractFunctionalEntityProducerForCollectionModification.java | #334 Added some initial changes to base producer of 'collection modification func entity' to support: 1) better customisation of master func entity re-retrieval 2) support non-persistent types for func entity. | <ide><path>latform-pojo-bl/src/main/java/ua/com/fielden/platform/dao/AbstractFunctionalEntityProducerForCollectionModification.java
<ide> import java.util.Collection;
<ide> import java.util.HashMap;
<ide> import java.util.Map;
<add>import java.util.Random;
<ide> import java.util.function.Function;
<ide>
<ide> import com.google.inject.Inject;
<ide> if (masterEntityFromContext.isDirty()) {
<ide> throw Result.failure("This action is applicable only to a saved entity! Please save entity and try again!");
<ide> }
<del> final MASTER_TYPE masterEntity = companionFinder.find(masterEntityType).findById(masterEntityFromContext.getId(), fetchModelForMasterEntity());
<add> // TODO
<add> // TODO There is a need to have more customizable way to re-retrieve masterEntity, in some cases, without re-retrieval at all
<add> // TODO
<add> final MASTER_TYPE masterEntity = (MASTER_TYPE) masterEntityFromContext; // companionFinder.find(masterEntityType).findById(masterEntityFromContext.getId(), fetchModelForMasterEntity());
<ide> if (masterEntity == null) {
<ide> throw Result.failure("The master entity has been deleted. " + TRY_AGAIN_MSG);
<ide> }
<ide> entity.setKey(masterEntity);
<ide> entity.getProperty(AbstractEntity.KEY).resetState();
<ide>
<del> final T previouslyPersistedAction = retrieveActionFor(masterEntity, companion, entityType);
<add> // TODO
<add> // TODO There is a need to have ability to use non-persistent master functional entities, without surrogate ids:
<add> // TODO
<add> // final T previouslyPersistedAction = retrieveActionFor(masterEntity, companion, entityType);
<ide>
<ide> // IMPORTANT: it is necessary not to reset state for "surrogateVersion" property after its change.
<ide> // This is necessary to leave the property marked as 'changed from original' (origVal == null) to be able to apply afterwards
<ide> // the initial value against '"surrogateVersion", that was possibly changed by another user'
<del> entity.setSurrogateVersion(surrogateVersion(previouslyPersistedAction));
<add> // entity.setSurrogateVersion(surrogateVersion(previouslyPersistedAction));
<add> entity.setSurrogateVersion(new Random().nextLong());
<ide>
<ide> return provideCurrentlyAssociatedValues(entity, masterEntity);
<ide> } |
|
Java | mit | 301662d11ff2dda9df845a28286c57f0a0a2f914 | 0 | joshua-decoder/thrax,tdomhan/thrax,tdomhan/thrax,jweese/thrax,tdomhan/thrax,joshua-decoder/thrax,jweese/thrax,jweese/thrax,joshua-decoder/thrax,joshua-decoder/thrax | package edu.jhu.thrax.hadoop.jobs;
import edu.jhu.thrax.hadoop.features.mapred.*;
public class FeatureJobFactory {
public static MapReduceFeature get(String name) {
if (name.equals("e2fphrase"))
return new SourcePhraseGivenTargetFeature();
else if (name.equals("f2ephrase"))
return new TargetPhraseGivenSourceFeature();
else if (name.equals("rarity"))
return new RarityPenaltyFeature();
else if (name.equals("lexprob"))
return new LexicalProbabilityFeature();
else if (name.equals("f_given_lhs"))
return new SourcePhraseGivenLHSFeature();
else if (name.equals("lhs_given_f"))
return new LhsGivenSourcePhraseFeature();
else if (name.equals("f_given_e_and_lhs"))
return new SourcePhraseGivenTargetandLHSFeature();
else if (name.equals("e_given_lhs"))
return new TargetPhraseGivenLHSFeature();
else if (name.equals("lhs_given_e"))
return new LhsGivenTargetPhraseFeature();
else if (name.equals("e_inv_given_lhs"))
return new TargetPhraseGivenLHSFeature();
else if (name.equals("lhs_given_e_inv"))
return new LhsGivenTargetPhraseFeature();
else if (name.equals("e_given_f_and_lhs")) return new TargetPhraseGivenSourceandLHSFeature();
return null;
}
}
| src/edu/jhu/thrax/hadoop/jobs/FeatureJobFactory.java | package edu.jhu.thrax.hadoop.jobs;
import edu.jhu.thrax.hadoop.features.mapred.*;
public class FeatureJobFactory {
public static MapReduceFeature get(String name) {
if (name.equals("e2fphrase"))
return new SourcePhraseGivenTargetFeature();
else if (name.equals("f2ephrase"))
return new TargetPhraseGivenSourceFeature();
else if (name.equals("rarity"))
return new RarityPenaltyFeature();
else if (name.equals("lexprob"))
return new LexicalProbabilityFeature();
else if (name.equals("f_given_lhs"))
return new SourcePhraseGivenLHSFeature();
else if (name.equals("lhs_given_f"))
return new LhsGivenSourcePhraseFeature();
else if (name.equals("f_given_e_and_lhs"))
return new SourcePhraseGivenTargetandLHSFeature();
else if (name.equals("e_given_lhs"))
return new TargetPhraseGivenLHSFeature();
else if (name.equals("lhs_given_e"))
return new LhsGivenTargetPhraseFeature();
else if (name.equals("e_given_f_and_lhs"))
return new TargetPhraseGivenSourceandLHSFeature();
return null;
}
}
| Added new features to job factory.
| src/edu/jhu/thrax/hadoop/jobs/FeatureJobFactory.java | Added new features to job factory. | <ide><path>rc/edu/jhu/thrax/hadoop/jobs/FeatureJobFactory.java
<ide>
<ide> public class FeatureJobFactory {
<ide>
<del> public static MapReduceFeature get(String name) {
<del> if (name.equals("e2fphrase"))
<del> return new SourcePhraseGivenTargetFeature();
<del> else if (name.equals("f2ephrase"))
<del> return new TargetPhraseGivenSourceFeature();
<del> else if (name.equals("rarity"))
<del> return new RarityPenaltyFeature();
<del> else if (name.equals("lexprob"))
<del> return new LexicalProbabilityFeature();
<del> else if (name.equals("f_given_lhs"))
<del> return new SourcePhraseGivenLHSFeature();
<del> else if (name.equals("lhs_given_f"))
<del> return new LhsGivenSourcePhraseFeature();
<del> else if (name.equals("f_given_e_and_lhs"))
<del> return new SourcePhraseGivenTargetandLHSFeature();
<del> else if (name.equals("e_given_lhs"))
<del> return new TargetPhraseGivenLHSFeature();
<del> else if (name.equals("lhs_given_e"))
<del> return new LhsGivenTargetPhraseFeature();
<del> else if (name.equals("e_given_f_and_lhs"))
<del> return new TargetPhraseGivenSourceandLHSFeature();
<add> public static MapReduceFeature get(String name) {
<add> if (name.equals("e2fphrase"))
<add> return new SourcePhraseGivenTargetFeature();
<add> else if (name.equals("f2ephrase"))
<add> return new TargetPhraseGivenSourceFeature();
<add> else if (name.equals("rarity"))
<add> return new RarityPenaltyFeature();
<add> else if (name.equals("lexprob"))
<add> return new LexicalProbabilityFeature();
<add> else if (name.equals("f_given_lhs"))
<add> return new SourcePhraseGivenLHSFeature();
<add> else if (name.equals("lhs_given_f"))
<add> return new LhsGivenSourcePhraseFeature();
<add> else if (name.equals("f_given_e_and_lhs"))
<add> return new SourcePhraseGivenTargetandLHSFeature();
<add> else if (name.equals("e_given_lhs"))
<add> return new TargetPhraseGivenLHSFeature();
<add> else if (name.equals("lhs_given_e"))
<add> return new LhsGivenTargetPhraseFeature();
<add> else if (name.equals("e_inv_given_lhs"))
<add> return new TargetPhraseGivenLHSFeature();
<add> else if (name.equals("lhs_given_e_inv"))
<add> return new LhsGivenTargetPhraseFeature();
<add> else if (name.equals("e_given_f_and_lhs")) return new TargetPhraseGivenSourceandLHSFeature();
<ide>
<del> return null;
<del> }
<add> return null;
<add> }
<ide> } |
|
Java | apache-2.0 | error: pathspec 'enhanced/classlib/trunk/modules/tools/src/main/java/com/sun/tools/javac/Main.java' did not match any file(s) known to git
| 363078ef25bded7d9f82d8ce3a29dec8d10463e6 | 1 | freeVM/freeVM,freeVM/freeVM,freeVM/freeVM,freeVM/freeVM,freeVM/freeVM | /*
* 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.sun.tools.javac;
public class Main {
public Main() {
super();
}
public int compile(String[] args) {
org.apache.harmony.tools.javac.Main hyMain = new org.apache.harmony.tools.javac.Main();
return hyMain.compile(args) ? 0 : 1;
}
}
| enhanced/classlib/trunk/modules/tools/src/main/java/com/sun/tools/javac/Main.java | Mini compatibility adapter for tools.jar compiler entry point.
svn path=/harmony/; revision=492114
| enhanced/classlib/trunk/modules/tools/src/main/java/com/sun/tools/javac/Main.java | Mini compatibility adapter for tools.jar compiler entry point. | <ide><path>nhanced/classlib/trunk/modules/tools/src/main/java/com/sun/tools/javac/Main.java
<add>/*
<add> * Licensed to the Apache Software Foundation (ASF) under one or more
<add> * contributor license agreements. See the NOTICE file distributed with
<add> * this work for additional information regarding copyright ownership.
<add> * The ASF licenses this file to You under the Apache License, Version 2.0
<add> * (the "License"); you may not use this file except in compliance with
<add> * the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package com.sun.tools.javac;
<add>
<add>public class Main {
<add>
<add> public Main() {
<add> super();
<add> }
<add>
<add> public int compile(String[] args) {
<add> org.apache.harmony.tools.javac.Main hyMain = new org.apache.harmony.tools.javac.Main();
<add> return hyMain.compile(args) ? 0 : 1;
<add> }
<add>} |
|
Java | apache-2.0 | 38cea9786bc0d5b6fb9d657d6aa6e77d9bee6951 | 0 | okornev/oneops,lkhusid/oneops,gauravlall/oneops,gauravlall/oneops,gauravlall/oneops,okornev/oneops,okornev/oneops,lkhusid/oneops,gauravlall/oneops,okornev/oneops,okornev/oneops,lkhusid/oneops,lkhusid/oneops,gauravlall/oneops,okornev/oneops,gauravlall/oneops,lkhusid/oneops,lkhusid/oneops | /*******************************************************************************
*
* Copyright 2015 Walmart, Inc.
*
* 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.oneops.cms.dj.service;
import com.google.gson.Gson;
import com.oneops.cms.cm.domain.CmsCI;
import com.oneops.cms.cm.domain.CmsCIRelation;
import com.oneops.cms.cm.domain.CmsCIRelationBasic;
import com.oneops.cms.cm.service.CmsCmProcessor;
import com.oneops.cms.dj.dal.DJDpmtMapper;
import com.oneops.cms.dj.domain.*;
import com.oneops.cms.exceptions.DJException;
import com.oneops.cms.ns.dal.NSMapper;
import com.oneops.cms.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.dao.DuplicateKeyException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* The Class CmsDpmtProcessor.
*/
public class CmsDpmtProcessor {
public static final String OPEN_DEPLOYMENT_REGEXP = "active|failed|paused";
static Logger logger = Logger.getLogger(CmsDpmtProcessor.class);
private DJDpmtMapper dpmtMapper;
private NSMapper nsMapper;
private CmsCmProcessor cmProcessor;
private CmsRfcProcessor rfcProcessor;
private Gson gson = new Gson();
private static final String DPMT_STATE_PENDING = "pending";
private static final String DPMT_STATE_ACTIVE = "active";
private static final String DPMT_STATE_CANCELED = "canceled";
private static final String DPMT_STATE_FAILED = "failed";
private static final String DPMT_STATE_PAUSED = "paused";
private static final String DPMT_STATE_COMPLETE = "complete";
private static final String APPROVAL_STATE_PENDING = "pending";
private static final String APPROVAL_STATE_APPROVED = "approved";
private static final String APPROVAL_STATE_REJECTED = "rejected";
//private static final String APPROVAL_STATE_EXPIRED = "expired";
private static final String DPMT_RECORD_STATE_INPROGRESS = "inprogress";
private static final String RELEASE_STATE_OPEN = "open";
private static final String MANIFEST_PLATFORM_CLASS = "manifest.Platform";
private static final String ONEOPS_AUTOREPLACE_USER = "oneops-autoreplace";
private static final int BOM_RELASE_NSPATH_LENGTH = 5;
private static final String ZONES_SELECTED = "ZONES_SELECTED";
/**
* Sets the cm processor.
*
* @param cmProcessor the new cm processor
*/
public void setCmProcessor(CmsCmProcessor cmProcessor) {
this.cmProcessor = cmProcessor;
}
/**
* Sets the dpmt mapper.
*
* @param dpmtMapper the new dpmt mapper
*/
public void setDpmtMapper(DJDpmtMapper dpmtMapper) {
this.dpmtMapper = dpmtMapper;
}
public void setNsMapper(NSMapper nsMapper) {
this.nsMapper = nsMapper;
}
public void setRfcProcessor(CmsRfcProcessor rfcProcessor) {
this.rfcProcessor = rfcProcessor;
}
/**
* Deploy release.
*
* @param dpmt the dpmt
* @return the cms deployment
*/
public CmsDeployment deployRelease(CmsDeployment dpmt) {
validateReleaseForDpmt(dpmt.getReleaseId());
List<CmsDeployment> existingDpmts = dpmtMapper.findLatestDeploymentByReleaseId(dpmt.getReleaseId(), null);
for (CmsDeployment existingDpmt : existingDpmts){
if (DPMT_STATE_ACTIVE.equalsIgnoreCase(existingDpmt.getDeploymentState())
|| DPMT_STATE_FAILED.equalsIgnoreCase(existingDpmt.getDeploymentState())
|| DPMT_STATE_PENDING.equalsIgnoreCase(existingDpmt.getDeploymentState())
|| DPMT_STATE_PAUSED.equalsIgnoreCase(existingDpmt.getDeploymentState())) {
String errMsg = "There is an " + existingDpmt.getDeploymentState() + " deployment already, returning this. dpmtId = " + existingDpmt.getDeploymentId();
logger.error(errMsg);
throw new DJException(CmsError.DJ_STATE_ALREADY_DEPLOYMENT_ERROR, errMsg);
}
}
updateAutoDeployExecOrders(dpmt);
if (ONEOPS_AUTOREPLACE_USER.equals(dpmt.getCreatedBy())) {
dpmt.setDeploymentState(DPMT_STATE_ACTIVE);
createDeployment(dpmt);
} else {
if (needApprovalForNewDpmt(dpmt)) {
dpmt.setDeploymentState(DPMT_STATE_PENDING);
createDeployment(dpmt);
needApproval(dpmt); // to cerate approval for this deployment
} else {
dpmt.setDeploymentState(DPMT_STATE_ACTIVE);
createDeployment(dpmt);
}
}
logger.info("Created new deployment, dpmtId = " + dpmt.getDeploymentId());
return dpmtMapper.getDeployment(dpmt.getDeploymentId());
}
private void createDeployment(CmsDeployment dpmt) {
try {
dpmtMapper.createDeployment(dpmt);
} catch (DuplicateKeyException e) {
logger.error("DuplicateKeyException while creating deployment", e);
String errMsg = "There is a deployment already in one of pending/active/paused/failed state, returning this";
throw new DJException(CmsError.DJ_STATE_ALREADY_DEPLOYMENT_ERROR, errMsg);
}
}
private void validateReleaseForDpmt(long releaseId) {
CmsRelease release = rfcProcessor.getReleaseById(releaseId);
if (!release.getReleaseState().equals(RELEASE_STATE_OPEN)) {
String errMsg = "The release with id " + releaseId + " is not open, Can't create deployment for it!";
logger.error(errMsg);
throw new DJException(CmsError.DJ_RFC_RELEASE_NOT_OPEN_ERROR, errMsg);
}
String[] nsParts = release.getNsPath().split("/");
if (nsParts.length < BOM_RELASE_NSPATH_LENGTH || !"bom".equals(nsParts[nsParts.length-1])) {
String errMsg = "The release with id " + releaseId + " is not a BOM release, Can't create deployment for it!";
logger.error(errMsg);
throw new DJException(CmsError.DJ_OPEN_RELEASE_FOR_NAMESPACE_ERROR, errMsg);
}
}
private void updateAutoDeployExecOrders(CmsDeployment dpmt) {
Set<Integer> autoPauseExecOrders = dpmt.getAutoPauseExecOrders();
if (autoPauseExecOrders != null) {
dpmt.setAutoPauseExecOrdersVal(StringUtils.join(autoPauseExecOrders, ","), false);
}
}
public List<CmsDpmtApproval> updateApprovalList(List<CmsDpmtApproval> approvals) {
List<CmsDpmtApproval> result = new ArrayList<>();
ListUtils<Long> lu = new ListUtils<>();
try {
Map<Long, List<CmsDpmtApproval>> approvalMap = lu.toMapOfList(approvals, "deploymentId");
for (Map.Entry<Long, List<CmsDpmtApproval>> dpmtApprovals : approvalMap.entrySet()) {
long dpmtId = dpmtApprovals.getKey();
String userId = null;
String rejectComments = null;
boolean rejected = false;
for (CmsDpmtApproval approval : dpmtApprovals.getValue()) {
userId = approval.getUpdatedBy();
if (approval.getExpiresIn() == 0) {
approval.setExpiresIn(1);
}
dpmtMapper.updDpmtApproval(approval);
result.add(dpmtMapper.getDpmtApproval(approval.getApprovalId()));
if (approval.getState().equals(APPROVAL_STATE_REJECTED)) {
rejected = true;
rejectComments = approval.getComments();
}
}
CmsDeployment dpmt = new CmsDeployment();
dpmt.setDeploymentId(dpmtId);
dpmt.setUpdatedBy(userId);
if (rejected) {
dpmt.setDeploymentState(DPMT_STATE_CANCELED);
dpmt.setComments(rejectComments);
} else {
dpmt.setDeploymentState(DPMT_STATE_ACTIVE);
}
updateDeployment(dpmt);
}
return result;
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
throw new DJException(CmsError.DJ_EXCEPTION, e.getMessage());
}
}
private boolean needApproval(CmsDeployment dpmt) {
boolean needApproval = false;
List<Long> cloudIds = dpmtMapper.getToCiIdsForDeployment(dpmt.getDeploymentId(), "pending", "base.DeployedTo");
List<CmsDpmtApproval> approvals = dpmtMapper.getDpmtApprovals(dpmt.getDeploymentId());
//convert to map
Map<Long,List<CmsDpmtApproval>> approvalMap = new HashMap<>();
for (CmsDpmtApproval approval : approvals) {
if (!approvalMap.containsKey(approval.getGovernCiId())) {
approvalMap.put(approval.getGovernCiId(), new ArrayList<>());
}
approvalMap.get(approval.getGovernCiId()).add(approval);
}
List<CmsCI> governCIs = new ArrayList<>();
for (long cloudId : cloudIds) {
for (CmsCIRelation supportRel : cmProcessor.getFromCIRelations(cloudId, "base.SupportedBy", null)) {
governCIs.add(supportRel.getToCi());
}
}
for (long cloudId : cloudIds) {
for (CmsCIRelation complianceRel : cmProcessor.getFromCIRelations(cloudId, "base.CompliesWith", null)) {
governCIs.add(complianceRel.getToCi());
}
}
for (CmsCI governCi : governCIs) {
if (governCi.getAttribute("enabled") != null
&& Boolean.TRUE.toString().equals(governCi.getAttribute("enabled").getDjValue())
&& governCi.getAttribute("approval") != null
&& Boolean.TRUE.toString().equals(governCi.getAttribute("approval").getDjValue())) {
if (!approvalMap.containsKey(governCi.getCiId())) {
createDpmtApproval(dpmt.getDeploymentId(), governCi);
needApproval= true;
} else {
CmsDpmtApproval approval = getLatestApproval(approvalMap.get(governCi.getCiId()));
if (approval == null) {
createDpmtApproval(dpmt.getDeploymentId(), governCi);
needApproval=true;
} else if (approval.getState().equals(APPROVAL_STATE_PENDING)) {
needApproval=true;
} else if (approval.getIsExpired() && approval.getState().equals(APPROVAL_STATE_APPROVED)){
//approval.setState(APPROVAL_STATE_EXPIRED);
//dpmtMapper.updDpmtApproval(approval);
createDpmtApproval(dpmt.getDeploymentId(), governCi);
needApproval=true;
}
}
}
}
return needApproval;
}
private CmsDpmtApproval getLatestApproval(List<CmsDpmtApproval> approvals) {
if (approvals.size() == 0) {
return null;
} else {
Collections.sort(approvals, (a1, a2) -> {
//Sorts by 'ApprovalId' property desc
return (int) (a2.getApprovalId() - a1.getApprovalId());
});
return approvals.get(0);
}
}
private boolean needApprovalForNewDpmt(CmsDeployment dpmt) {
List<Long> cloudIds = dpmtMapper.getToCiIdsForReleasePending(dpmt.getReleaseId(), "base.DeployedTo");
List<CmsCI> governCIs = new ArrayList<>();
for (long cloudId : cloudIds) {
for (CmsCIRelation supportRel : cmProcessor.getFromCIRelations(cloudId, "base.SupportedBy", null)) {
governCIs.add(supportRel.getToCi());
}
}
for (long cloudId : cloudIds) {
for (CmsCIRelation complianceRel : cmProcessor.getFromCIRelations(cloudId, "base.CompliesWith", null)) {
governCIs.add(complianceRel.getToCi());
}
}
for (CmsCI governCi : governCIs) {
if (governCi.getAttribute("enabled") != null
&& Boolean.TRUE.toString().equals(governCi.getAttribute("enabled").getDjValue())
&& governCi.getAttribute("approval") != null
&& Boolean.TRUE.toString().equals(governCi.getAttribute("approval").getDjValue())) {
return true; //this domt need approval
}
}
return false;
}
private void createDpmtApproval(long dpmtId, CmsCI governCi) {
CmsDpmtApproval approval = new CmsDpmtApproval();
approval.setDeploymentId(dpmtId);
approval.setGovernCiId(governCi.getCiId());
approval.setGovernCiJson(gson.toJson(governCi));
dpmtMapper.createDpmtApproval(approval);
logger.info("Created approval for dpmtId = " + dpmtId + " : " + approval.getGovernCiJson());
}
/**
* Update deployment.
*
* @param dpmt the dpmt
* @return the cms deployment
*/
public CmsDeployment updateDeployment(CmsDeployment dpmt) {
CmsDeployment existingDpmt = dpmtMapper.getDeployment(dpmt.getDeploymentId());
updateAutoDeployExecOrders(dpmt);
//in case the new state = old state just update the comments and timestamp CMS_ALL event will not be generated
if (existingDpmt.getDeploymentState().equals(dpmt.getDeploymentState())) {
String currentState = dpmt.getDeploymentState();
dpmt.setDeploymentState(null);
dpmtMapper.updDeployment(dpmt);
logger.info("Updated dpmtId = " + dpmt.getDeploymentId() + " kept the old state ");
dpmt.setDeploymentState(currentState);
} else if (DPMT_STATE_CANCELED.equalsIgnoreCase(dpmt.getDeploymentState())) {
if (dpmtMapper.getDeploymentRecordsCountByState(dpmt.getDeploymentId(), DPMT_RECORD_STATE_INPROGRESS, null) > 0) {
String errMsg = "The deployment still have active work orders!";
logger.error(errMsg);
throw new DJException(CmsError.DJ_DEPLOYMENT_NOT_ACTIVE_FAILED_ERROR, errMsg);
}
if (DPMT_STATE_FAILED.equalsIgnoreCase(existingDpmt.getDeploymentState())
|| DPMT_STATE_PAUSED.equalsIgnoreCase(existingDpmt.getDeploymentState())
|| DPMT_STATE_PENDING.equalsIgnoreCase(existingDpmt.getDeploymentState())) {
dpmtMapper.cancelDeployment(dpmt);
logger.info("Updated dpmtId = " + dpmt.getDeploymentId() + " with new state " + dpmt.getDeploymentState());
} else {
String errMsg = "The deployment is not in failed/active state - " + existingDpmt.getDeploymentState();
logger.error(errMsg);
throw new DJException(CmsError.DJ_DEPLOYMENT_NOT_ACTIVE_FAILED_ERROR, errMsg);
}
} else if (DPMT_STATE_ACTIVE.equalsIgnoreCase(dpmt.getDeploymentState())) {
if (DPMT_STATE_PENDING.equalsIgnoreCase(existingDpmt.getDeploymentState())) {
if (!needApproval(dpmt)) {
dpmtMapper.updDeployment(dpmt);
logger.info("Updated dpmtId = " + dpmt.getDeploymentId() + " with new state " + dpmt.getDeploymentState());
}
} else if (DPMT_STATE_FAILED.equalsIgnoreCase(existingDpmt.getDeploymentState())) {
dpmtMapper.resetFailedRecords(dpmt);
if (needApproval(dpmt)) {
dpmt.setDeploymentState(DPMT_STATE_PENDING);
dpmtMapper.updDeployment(dpmt);
logger.info("Updated dpmtId = " + dpmt.getDeploymentId() + " with new state " + dpmt.getDeploymentState());
} else {
dpmtMapper.retryDeployment(dpmt);
}
} else if(DPMT_STATE_PAUSED.equalsIgnoreCase(existingDpmt.getDeploymentState())) {
if (needApproval(dpmt)) {
dpmt.setDeploymentState(DPMT_STATE_PENDING);
}
dpmtMapper.updDeployment(dpmt);
logger.info("Updated dpmtId = " + dpmt.getDeploymentId() + " with new state " + dpmt.getDeploymentState());
} else {
String errMsg = "The deployment is not in failed state - " + existingDpmt.getDeploymentState();
logger.error(errMsg);
throw new DJException(CmsError.DJ_DEPLOYMENT_NOT_FAILED_ERROR, errMsg);
}
} else if (DPMT_STATE_COMPLETE.equalsIgnoreCase(dpmt.getDeploymentState())) {
if (DPMT_STATE_ACTIVE.equalsIgnoreCase(existingDpmt.getDeploymentState())
|| DPMT_STATE_PAUSED.equalsIgnoreCase(existingDpmt.getDeploymentState())) {
//dpmtMapper.completeDeployment(dpmt);
completeDeployment(dpmt);
logger.info("Updated dpmtId = " + dpmt.getDeploymentId() + " with new state " + dpmt.getDeploymentState());
} else {
String errMsg = "The deployment is not in active state - " + existingDpmt.getDeploymentState();
logger.warn(errMsg);
//throw new DJException(errMsg);
}
} else if (DPMT_STATE_FAILED.equalsIgnoreCase(dpmt.getDeploymentState())) {
if (DPMT_STATE_ACTIVE.equalsIgnoreCase(existingDpmt.getDeploymentState())
|| DPMT_STATE_PAUSED.equalsIgnoreCase(existingDpmt.getDeploymentState())) {
dpmtMapper.updDeployment(dpmt);
logger.info("Updated dpmtId = " + dpmt.getDeploymentId() + " with new state " + dpmt.getDeploymentState());
} else {
String errMsg = "The deployment is not in active state - " + existingDpmt.getDeploymentState();
logger.error(errMsg);
throw new DJException(CmsError.DJ_DEPLOYMENT_NOT_ACTIVE_ERROR, errMsg);
}
} else if (DPMT_STATE_PAUSED.equalsIgnoreCase(dpmt.getDeploymentState())) {
if (DPMT_STATE_ACTIVE.equalsIgnoreCase(existingDpmt.getDeploymentState())) {
dpmtMapper.updDeployment(dpmt);
logger.info("Updated dpmtId = " + dpmt.getDeploymentId() + " with new state " + dpmt.getDeploymentState());
} else {
String errMsg = "The deployment is not in active state - " + existingDpmt.getDeploymentState();
logger.error(errMsg);
throw new DJException(CmsError.DJ_DEPLOYMENT_NOT_ACTIVE_ERROR, errMsg);
}
} else {
String errMsg = "This state is not supported - " + dpmt.getDeploymentState();
logger.error(errMsg);
throw new DJException(CmsError.DJ_NOT_SUPPORTED_STATE_ERROR, errMsg);
}
return dpmtMapper.getDeployment(dpmt.getDeploymentId());
}
private void completeDeployment(CmsDeployment dpmt) {
dpmtMapper.completeDeployment(dpmt);
CmsRelease bomRelease = rfcProcessor.getReleaseById(dpmt.getReleaseId());
CmsRelease manifestRelease = rfcProcessor.getReleaseById(bomRelease.getParentReleaseId());
List<CmsCI> platforms = cmProcessor.getCiBy3NsLike(manifestRelease.getNsPath(), MANIFEST_PLATFORM_CLASS, null);
for (CmsCI plat : platforms) {
boolean vacuumAllowed = true;
List<CmsCI> monitorCiList = new ArrayList<>();
Set<Long> monitors4DeletedComponents = new HashSet<>();
List<CmsCIRelation> platformCloudRels = cmProcessor.getFromCIRelationsNaked(plat.getCiId(), "base.Consumes", "account.Cloud");
for (CmsCIRelation platformCloudRel : platformCloudRels) {
if (platformCloudRel.getAttribute("adminstatus") != null
&& !CmsConstants.CLOUD_STATE_ACTIVE.equals(platformCloudRel.getAttribute("adminstatus").getDjValue())) {
String platBomNs = plat.getNsPath().replace("/manifest/", "/bom/");
List<CmsCIRelation> deployedToRels = cmProcessor.getToCIRelationsByNsNaked(platformCloudRel.getToCiId(), "base.DeployedTo", null, null, platBomNs);
if (deployedToRels.size() >0) {
vacuumAllowed = false;
break;
}
} else {
List<CmsCI> componentsToDelet = cmProcessor.getCiByNsLikeByStateNaked(plat.getNsPath(), null, "pending_deletion");
for (CmsCI component : componentsToDelet) {
long ciId = component.getCiId();
if (CmsConstants.MONITOR_CLASS.equals(component.getCiClassName())) {
monitorCiList.add(component);
continue;
}
List<CmsCIRelation> realizedAsRels = cmProcessor.getFromCIRelationsNakedNoAttrs(ciId, "base.RealizedAs", null, null);
if (realizedAsRels.size() > 0) {
vacuumAllowed = false;
break;
}
List<CmsCIRelation> monitorRels = cmProcessor.getFromCIRelationsNakedNoAttrs(ciId, CmsConstants.MANIFEST_WATCHED_BY,
null, CmsConstants.MONITOR_CLASS);
if (monitorRels.size() > 0) {
monitors4DeletedComponents.addAll(monitorRels.stream().map(CmsCIRelationBasic::getToCiId).collect(Collectors.toList()));
}
}
if (!vacuumAllowed) {
break;
}
}
}
if (vacuumAllowed) {
//if there are monitors to be deleted, then make sure it satisfies one of these two
// 1. the monitors have corresponding parent CIs that are also marked pending_deletion, these would be in monitors4DeletedComponents
// 2. all the bom CIs for this manifest are updated for this manifest release
monitorCiList.removeIf(monitor -> monitors4DeletedComponents.contains(monitor.getCiId()));
List<CmsCI> monitorsEligible4Del = getMonitorsEligible4Del(monitorCiList);
if (monitorsEligible4Del.size() == monitorCiList.size()) {
nsMapper.vacuumNamespace(plat.getNsId(), dpmt.getCreatedBy());
}
else {
monitorsEligible4Del.forEach(monitor -> cmProcessor.deleteCI(monitor.getCiId(), dpmt.getCreatedBy()));
}
}
}
deleteGlobalVars(manifestRelease.getNsPath(), dpmt.getCreatedBy());
}
/**
* Delete global variables in pending_delete state
*
*/
private void deleteGlobalVars(String envNsPath, String userId) {
List <CmsCI> toDelComponents = cmProcessor.getCiByNsLikeByStateNaked(envNsPath + "/", null, "pending_deletion");
//if no components are marked for deletion then delete the global variables in pending_deletion state
if(toDelComponents.isEmpty()){
//delete global vars in pending_delete state
for (CmsCI globalVar : cmProcessor.getCiByNsLikeByStateNaked(envNsPath, "manifest.Globalvar", "pending_deletion")) {
cmProcessor.deleteCI(globalVar.getCiId(), true, userId);
}
}
}
private List<CmsCI> getMonitorsEligible4Del(List<CmsCI> monitorCiList) {
List<CmsCI> monitorsEligible4Del = new ArrayList<>();
if (!monitorCiList.isEmpty()) {
monitorsEligible4Del.addAll(monitorCiList.stream().
filter(monitor -> {
long monitorRfcId = monitor.getLastAppliedRfcId();
logger.info("monitor ci : " + monitor.getCiId() + ", last applied rfc id : " + monitorRfcId);
List<CmsCIRelation> parentRelation = cmProcessor.getToCIRelationsNakedNoAttrs(monitor.getCiId(),
CmsConstants.MANIFEST_WATCHED_BY, null, null);
if (parentRelation.size() > 0) {
long baseRfcId = monitorRfcId;
long parentCiId = parentRelation.get(0).getFromCiId();
//get the parent ci rfcId from the same release and use that to compare with bom instances
CmsRfcCI monitorRfc = rfcProcessor.getRfcCIById(monitorRfcId);
List<CmsRfcCI> parentRfcs = rfcProcessor.getRfcCIBy3(monitorRfc.getReleaseId(), true, parentCiId);
if (!parentRfcs.isEmpty()) {
baseRfcId = parentRfcs.get(0).getRfcId();
logger.info("component ci rfc id : " + baseRfcId);
}
//get count of boms that are not updated by this manifest rfc
long count = rfcProcessor.getCiCountNotUpdatedByRfc(parentCiId, CmsConstants.BASE_REALIZED_AS, null, baseRfcId);
logger.info("ci not deployed count " + count);
if (count > 0) {
//there are some bom CIs that are not deployed, so this monitor cannot be removed
return false;
}
}
return true;
}).
collect(Collectors.toList()));
}
return monitorsEligible4Del;
}
/**
* Update dpmt record.
*
* @param rec the rec
* @return the cms dpmt record
*/
public CmsDpmtRecord updateDpmtRecord(CmsDpmtRecord rec) {
dpmtMapper.updDpmtRecordState(rec);
return dpmtMapper.getDeploymentRecord(rec.getDpmtRecordId());
}
/**
* Complete work order.
*
* @param wo the wo
*/
public void completeWorkOrder(CmsWorkOrder wo) {
dpmtMapper.updDpmtRecordState(wo);
if (!wo.getRfcCi().getRfcAction().equalsIgnoreCase("delete") && wo.getResultCi() != null) {
wo.getResultCi().setUpdatedBy(wo.getRfcCi().getCreatedBy() + ":controller");
cmProcessor.updateCI(wo.getResultCi());
}
//return dpmtMapper.getDeploymentRecord(wo.getDpmtRecordId());
processAdditionalInfo(wo);
}
private void processAdditionalInfo(CmsWorkOrder wo) {
Map<String, String> additionalInfo = wo.getAdditionalInfo();
if (additionalInfo != null && !additionalInfo.isEmpty()) {
additionalInfo.entrySet().forEach(entry -> {
String key = entry.getKey();
if (ZONES_SELECTED.equalsIgnoreCase(key)) {
processSelectedZones(wo, entry);
}
});
}
}
private void processSelectedZones(CmsWorkOrder wo, Entry<String, String> entry) {
List<CmsCIRelation> existingRelations = cmProcessor.getFromCIRelations(wo.getResultCi().getCiId(),
CmsConstants.BASE_PLACED_IN, CmsConstants.ZONE_CLASS);
Map<String, CmsCIRelation> relationsMap = existingRelations.stream().
collect(Collectors.toMap(relation -> relation.getToCi().getCiName(), Function.identity()));
String values = entry.getValue();
if (values != null) {
String[] zones = values.split(",");
logger.info("selected zones for this ciId [" + wo.getResultCi().getCiId() + "] : " + values);
logger.info("existing zones : " + relationsMap.keySet());
Set<String> selectedZones = Collections.emptySet();
if (zones.length > 0) {
selectedZones = Stream.of(zones).map(String::trim).collect(Collectors.toSet());
createPlacedInRelations(selectedZones, relationsMap, wo);
}
removeOldRelations(selectedZones, relationsMap);
}
}
private void createPlacedInRelations(Set<String> zones, Map<String, CmsCIRelation> relationsMap, CmsWorkOrder wo) {
List<CmsCIRelation> deployedToRels = cmProcessor.getFromCIRelations(wo.getResultCi().getCiId(), CmsConstants.DEPLOYED_TO, CmsConstants.CLOUD_CLASS);
if (deployedToRels != null && !deployedToRels.isEmpty()) {
zones.stream().
filter(zone -> (zone.length() > 0 && !(relationsMap.containsKey(zone)))).
forEach(zone -> {
if (logger.isDebugEnabled()) {
logger.debug("creating base.PlacedIn relation to zone : " + zone);
}
CmsCI cloudCi = deployedToRels.get(0).getToCi();
String zoneNs = formZoneNsPath(cloudCi.getNsPath(), cloudCi.getCiName());
List<CmsCI> cis = cmProcessor.getCiBy3(zoneNs, CmsConstants.ZONE_CLASS, zone);
if (cis == null || cis.isEmpty()) {
logger.error("zone ci not found " + zone + ", nsPath : " + zoneNs);
}
else {
CmsCI zoneCi = cis.get(0);
CmsCI resultCi = wo.getResultCi();
CmsRfcCI rfcCi = wo.getRfcCi();
resultCi.setCiName(rfcCi.getCiName());
resultCi.setCiClassName(rfcCi.getCiClassName());
CmsCIRelation placedInRel = cmProcessor.bootstrapRelation(resultCi, zoneCi, CmsConstants.BASE_PLACED_IN, rfcCi.getNsPath(),
rfcCi.getCreatedBy(), rfcCi.getCreated());
cmProcessor.createRelation(placedInRel);
}
});
}
else {
logger.error("no base.DeployedTo relation found for ci " + wo.getResultCi().getCiId());
}
}
private void removeOldRelations(Set<String> zones, Map<String, CmsCIRelation> relationsMap) {
relationsMap.entrySet().stream().filter(entry -> !zones.contains(entry.getKey())).forEach(entry -> {
if (logger.isDebugEnabled()) {
logger.debug("removing base.PlacedIn relation to zone : " + entry.getKey());
}
cmProcessor.deleteRelation(entry.getValue().getCiRelationId(), true);
});
}
private String formZoneNsPath(String cloudNsPath, String cloudName) {
return cloudNsPath + "/" + cloudName;
}
/**
* Gets the deployment.
*
* @param dpmtId the dpmt id
* @return the deployment
*/
public CmsDeployment getDeployment(long dpmtId) {
return dpmtMapper.getDeployment(dpmtId);
}
/**
* Find deployment.
*
* @param nsPath the ns path
* @param state the state
* @param recursive the recursive
* @return the list
*/
public List<CmsDeployment> findDeployment(String nsPath, String state, Boolean recursive) {
if (recursive != null && recursive) {
String nsLike = CmsUtil.likefyNsPath(nsPath);
return dpmtMapper.findDeploymentRecursive(nsPath, nsLike, state);
} else {
return dpmtMapper.findDeployment(nsPath, state);
}
}
/**
* Find latest deployment.
*
* @param nsPath the ns path
* @param state the state
* @param recursive the recursive
* @return the list
*/
public List<CmsDeployment> findLatestDeployment(String nsPath, String state, Boolean recursive) {
if (recursive != null && recursive ) {
String nsLike = CmsUtil.likefyNsPath(nsPath);
return dpmtMapper.findLatestDeploymentRecursive(nsPath,nsLike, state);
} else {
return dpmtMapper.findLatestDeployment(nsPath, state);
}
}
/**
* Count deployment.
*
* @param nsPath the ns path
* @param state the state
* @param recursive the recursive
* @return the long
*/
public long countDeployment(String nsPath, String state, Boolean recursive) {
if (recursive != null && recursive ) {
String nsLike = CmsUtil.likefyNsPath(nsPath);
return dpmtMapper.countDeploymentRecursive(nsPath, nsLike, state);
} else {
return dpmtMapper.countDeployment(nsPath, state);
}
}
/**
* Count deployment group by.
*
* @param nsPath the ns path
* @param state the state
* @return the map
*/
public Map<String, Long> countDeploymentGroupBy(String nsPath, String state) {
Map<String, Long> result = new HashMap<>();
String nsLike = CmsUtil.likefyNsPath(nsPath);
List<Map<String,Object>> stats = dpmtMapper.countDeploymentGroupByNs(nsPath, nsLike, state);
for (Map<String,Object> row : stats) {
String nspath = (String)row.get("path");
Long cnt = (Long)row.get("cnt");
result.put(nspath, cnt);
}
return result;
}
/**
* Find deployment by release id.
*
* @param releaseId the release id
* @param state the state
* @return the list
*/
public List<CmsDeployment> findDeploymentByReleaseId(long releaseId, String state) {
return dpmtMapper.findDeploymentByReleaseId(releaseId, state);
}
/**
* Find latest deployment by release id.
*
* @param releaseId the release id
* @param state the state
* @return the list
*/
public List<CmsDeployment> findLatestDeploymentByReleaseId(long releaseId, String state) {
return dpmtMapper.findLatestDeploymentByReleaseId(releaseId, state);
}
/**
* Gets the deployment records.
*
* @param dpmtId the dpmt id
* @return the deployment records
*/
public List<CmsDpmtRecord> getDeploymentRecords(long dpmtId) {
return dpmtMapper.getDeploymentRecords(dpmtId);
}
/**
* Gets the deployment approvals.
*
* @param dpmtId the dpmt id
* @return the deployment approvals
*/
public List<CmsDpmtApproval> getDeploymentApprovals(long dpmtId) {
return dpmtMapper.getDpmtApprovals(dpmtId);
}
/**
* Gets the deployment approval.
*
* @param approvalId the approval id
* @return the deployment approval
*/
public CmsDpmtApproval getDeploymentApproval(long approvalId) {
return dpmtMapper.getDpmtApproval(approvalId);
}
/**
* Gets the deployment record by dpmtRfcId.
*
* @param dpmtRecordId the dpmtRfcId
* @return the deployment records
*/
public CmsDpmtRecord getDeploymentRecord(long dpmtRecordId) {
return dpmtMapper.getDeploymentRecord(dpmtRecordId);
}
/**
* Gets the deployment record cis.
*
* @param dpmtId the dpmt id
* @return the deployment record cis
*/
public List<CmsDpmtRecord> getDeploymentRecordCis(long dpmtId) {
return dpmtMapper.getDeploymentRecordCis(dpmtId);
}
/**
* Gets the deployment record cis.
*
* @param list of dpt record ids
* @return the deployment record cis
*/
public List<CmsDpmtRecord> getDeploymentRecordCis(long dpmtId, List<Long> list) {
return dpmtMapper.getDeploymentRecordCisByListOfIds(dpmtId, list);
}
/**
* Gets the deployment record cis.
*
* @param ciId the ciId
* @return the deployment record cis
*/
public List<CmsDpmtRecord> getDeploymentRecordByCiId(long ciId, String state) {
return dpmtMapper.getDeploymentRecordsByCiId(ciId, state);
}
/**
* Gets the deployment record cis by state.
*
* @param dpmtId the dpmt id
* @return the deployment record cis
*/
public List<CmsDpmtRecord> getDeploymentRecordCisByState(long dpmtId, String state, Integer execOrder) {
return dpmtMapper.getDeploymentRecordsByState(dpmtId, state, execOrder);
}
/**
* Gets the deployment record cis updated after a given timestamp.
*
* @param dpmtId the dpmt id
* @param timestamp udpated timestamp
* @return the deployment record cis
*/
public List<CmsDpmtRecord> getDeploymentRecordsUpdatedAfter(long dpmtId, Date timestamp) {
return dpmtMapper.getDeploymentRecordsUpdatedAfter(dpmtId, timestamp);
}
/**
* Gets the deployment record relations.
*
* @param dpmtId the dpmt id
* @return the deployment record relations
*/
public List<CmsDpmtRecord> getDeploymentRecordRelations(long dpmtId) {
return dpmtMapper.getDeploymentRecordRelations(dpmtId);
}
public long getDeploymentRecordCount(long dpmtId, String state, Integer execOrder) {
return dpmtMapper.getDeploymentRecordsCountByState(dpmtId, state, execOrder);
}
public List<CmsDpmtStateChangeEvent> getDeploymentStateHist(long deploymentId) {
return dpmtMapper.getDeploymentStateHist(deploymentId);
}
/**
* Gets the current deployments in progress for environment.
* @param nsPath The path to search for open deployments .
* @return will return *Null* if no deployment is found in |active|failed|paused| ,else return first deployment
* found in matching state
*/
public CmsDeployment getOpenDeployments(String nsPath) {
List<CmsDeployment> currentDeployments = findLatestDeployment(nsPath, null, false);
List<CmsDeployment> openDeployments = currentDeployments.stream().filter(cmsDeployment -> cmsDeployment.getDeploymentState().matches(OPEN_DEPLOYMENT_REGEXP)).collect(Collectors.toList());
if (openDeployments != null) {
if (openDeployments.size() > 0) {
return openDeployments.get(0);
}
}
return null;
}
public List<TimelineDeployment> getDeploymentsByFilter(TimelineQueryParam queryParam) {
String envNsPath = queryParam.getNsPath();
String filter = queryParam.getWildcardFilter();
List<TimelineDeployment> deployments = null;
if (!StringUtils.isBlank(filter)) {
queryParam.setDpmtNsLike(CmsUtil.likefyNsPathWithFilter(envNsPath, CmsConstants.BOM, null));
queryParam.setDpmtNsLikeWithFilter(CmsUtil.likefyNsPathWithFilter(envNsPath, CmsConstants.BOM, filter));
queryParam.setDpmtClassFilter(CmsConstants.BOM + "." + filter);
deployments = dpmtMapper.getDeploymentsByFilter(queryParam);
}
else {
deployments = getDeployments4NsPathLike(queryParam);
}
return deployments;
}
private List<TimelineDeployment> getDeployments4NsPathLike(TimelineQueryParam queryParam) {
queryParam.setDpmtNsLike(CmsUtil.likefyNsPathWithTypeNoEndingSlash(queryParam.getNsPath(), CmsConstants.BOM));
return dpmtMapper.getDeploymentsByNsPath(queryParam);
}
} | src/main/java/com/oneops/cms/dj/service/CmsDpmtProcessor.java | /*******************************************************************************
*
* Copyright 2015 Walmart, Inc.
*
* 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.oneops.cms.dj.service;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.oneops.cms.cm.domain.CmsCIRelationBasic;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import com.google.gson.Gson;
import com.oneops.cms.cm.domain.CmsCI;
import com.oneops.cms.cm.domain.CmsCIRelation;
import com.oneops.cms.cm.service.CmsCmProcessor;
import com.oneops.cms.dj.dal.DJDpmtMapper;
import com.oneops.cms.dj.domain.CmsDeployment;
import com.oneops.cms.dj.domain.TimelineDeployment;
import com.oneops.cms.dj.domain.CmsDpmtApproval;
import com.oneops.cms.dj.domain.CmsDpmtRecord;
import com.oneops.cms.dj.domain.CmsDpmtStateChangeEvent;
import com.oneops.cms.dj.domain.CmsRelease;
import com.oneops.cms.dj.domain.CmsRfcCI;
import com.oneops.cms.dj.domain.CmsWorkOrder;
import com.oneops.cms.exceptions.DJException;
import com.oneops.cms.ns.dal.NSMapper;
import com.oneops.cms.util.CmsConstants;
import com.oneops.cms.util.CmsError;
import com.oneops.cms.util.CmsUtil;
import com.oneops.cms.util.ListUtils;
import com.oneops.cms.util.TimelineQueryParam;
/**
* The Class CmsDpmtProcessor.
*/
public class CmsDpmtProcessor {
public static final String OPEN_DEPLOYMENT_REGEXP = "active|failed|paused";
static Logger logger = Logger.getLogger(CmsDpmtProcessor.class);
private DJDpmtMapper dpmtMapper;
private NSMapper nsMapper;
private CmsCmProcessor cmProcessor;
private CmsRfcProcessor rfcProcessor;
private Gson gson = new Gson();
private static final String DPMT_STATE_PENDING = "pending";
private static final String DPMT_STATE_ACTIVE = "active";
private static final String DPMT_STATE_CANCELED = "canceled";
private static final String DPMT_STATE_FAILED = "failed";
private static final String DPMT_STATE_PAUSED = "paused";
private static final String DPMT_STATE_COMPLETE = "complete";
private static final String APPROVAL_STATE_PENDING = "pending";
private static final String APPROVAL_STATE_APPROVED = "approved";
private static final String APPROVAL_STATE_REJECTED = "rejected";
//private static final String APPROVAL_STATE_EXPIRED = "expired";
private static final String DPMT_RECORD_STATE_INPROGRESS = "inprogress";
private static final String RELEASE_STATE_OPEN = "open";
private static final String MANIFEST_PLATFORM_CLASS = "manifest.Platform";
private static final String ONEOPS_AUTOREPLACE_USER = "oneops-autoreplace";
private static final int BOM_RELASE_NSPATH_LENGTH = 5;
private static final String ZONES_SELECTED = "ZONES_SELECTED";
/**
* Sets the cm processor.
*
* @param cmProcessor the new cm processor
*/
public void setCmProcessor(CmsCmProcessor cmProcessor) {
this.cmProcessor = cmProcessor;
}
/**
* Sets the dpmt mapper.
*
* @param dpmtMapper the new dpmt mapper
*/
public void setDpmtMapper(DJDpmtMapper dpmtMapper) {
this.dpmtMapper = dpmtMapper;
}
public void setNsMapper(NSMapper nsMapper) {
this.nsMapper = nsMapper;
}
public void setRfcProcessor(CmsRfcProcessor rfcProcessor) {
this.rfcProcessor = rfcProcessor;
}
/**
* Deploy release.
*
* @param dpmt the dpmt
* @return the cms deployment
*/
public CmsDeployment deployRelease(CmsDeployment dpmt) {
validateReleaseForDpmt(dpmt.getReleaseId());
List<CmsDeployment> existingDpmts = dpmtMapper.findLatestDeploymentByReleaseId(dpmt.getReleaseId(), null);
for (CmsDeployment existingDpmt : existingDpmts){
if (DPMT_STATE_ACTIVE.equalsIgnoreCase(existingDpmt.getDeploymentState())
|| DPMT_STATE_FAILED.equalsIgnoreCase(existingDpmt.getDeploymentState())
|| DPMT_STATE_PENDING.equalsIgnoreCase(existingDpmt.getDeploymentState())
|| DPMT_STATE_PAUSED.equalsIgnoreCase(existingDpmt.getDeploymentState())) {
String errMsg = "There is an " + existingDpmt.getDeploymentState() + " deployment already, returning this. dpmtId = " + existingDpmt.getDeploymentId();
logger.error(errMsg);
throw new DJException(CmsError.DJ_STATE_ALREADY_DEPLOYMENT_ERROR, errMsg);
}
}
updateAutoDeployExecOrders(dpmt);
if (ONEOPS_AUTOREPLACE_USER.equals(dpmt.getCreatedBy())) {
dpmt.setDeploymentState(DPMT_STATE_ACTIVE);
createDeployment(dpmt);
} else {
if (needApprovalForNewDpmt(dpmt)) {
dpmt.setDeploymentState(DPMT_STATE_PENDING);
createDeployment(dpmt);
needApproval(dpmt); // to cerate approval for this deployment
} else {
dpmt.setDeploymentState(DPMT_STATE_ACTIVE);
createDeployment(dpmt);
}
}
logger.info("Created new deployment, dpmtId = " + dpmt.getDeploymentId());
return dpmtMapper.getDeployment(dpmt.getDeploymentId());
}
private void createDeployment(CmsDeployment dpmt) {
try {
dpmtMapper.createDeployment(dpmt);
} catch (DuplicateKeyException e) {
logger.error("DuplicateKeyException while creating deployment", e);
String errMsg = "There is a deployment already in one of pending/active/paused/failed state, returning this";
throw new DJException(CmsError.DJ_STATE_ALREADY_DEPLOYMENT_ERROR, errMsg);
}
}
private void validateReleaseForDpmt(long releaseId) {
CmsRelease release = rfcProcessor.getReleaseById(releaseId);
if (!release.getReleaseState().equals(RELEASE_STATE_OPEN)) {
String errMsg = "The release with id " + releaseId + " is not open, Can't create deployment for it!";
logger.error(errMsg);
throw new DJException(CmsError.DJ_RFC_RELEASE_NOT_OPEN_ERROR, errMsg);
}
String[] nsParts = release.getNsPath().split("/");
if (nsParts.length < BOM_RELASE_NSPATH_LENGTH || !"bom".equals(nsParts[nsParts.length-1])) {
String errMsg = "The release with id " + releaseId + " is not a BOM release, Can't create deployment for it!";
logger.error(errMsg);
throw new DJException(CmsError.DJ_OPEN_RELEASE_FOR_NAMESPACE_ERROR, errMsg);
}
}
private void updateAutoDeployExecOrders(CmsDeployment dpmt) {
Set<Integer> autoPauseExecOrders = dpmt.getAutoPauseExecOrders();
if (autoPauseExecOrders != null) {
dpmt.setAutoPauseExecOrdersVal(StringUtils.join(autoPauseExecOrders, ","), false);
}
}
public List<CmsDpmtApproval> updateApprovalList(List<CmsDpmtApproval> approvals) {
List<CmsDpmtApproval> result = new ArrayList<>();
ListUtils<Long> lu = new ListUtils<>();
try {
Map<Long, List<CmsDpmtApproval>> approvalMap = lu.toMapOfList(approvals, "deploymentId");
for (Map.Entry<Long, List<CmsDpmtApproval>> dpmtApprovals : approvalMap.entrySet()) {
long dpmtId = dpmtApprovals.getKey();
String userId = null;
String rejectComments = null;
boolean rejected = false;
for (CmsDpmtApproval approval : dpmtApprovals.getValue()) {
userId = approval.getUpdatedBy();
if (approval.getExpiresIn() == 0) {
approval.setExpiresIn(1);
}
dpmtMapper.updDpmtApproval(approval);
result.add(dpmtMapper.getDpmtApproval(approval.getApprovalId()));
if (approval.getState().equals(APPROVAL_STATE_REJECTED)) {
rejected = true;
rejectComments = approval.getComments();
}
}
CmsDeployment dpmt = new CmsDeployment();
dpmt.setDeploymentId(dpmtId);
dpmt.setUpdatedBy(userId);
if (rejected) {
dpmt.setDeploymentState(DPMT_STATE_CANCELED);
dpmt.setComments(rejectComments);
} else {
dpmt.setDeploymentState(DPMT_STATE_ACTIVE);
}
updateDeployment(dpmt);
}
return result;
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
throw new DJException(CmsError.DJ_EXCEPTION, e.getMessage());
}
}
private boolean needApproval(CmsDeployment dpmt) {
boolean needApproval = false;
List<Long> cloudIds = dpmtMapper.getToCiIdsForDeployment(dpmt.getDeploymentId(), "pending", "base.DeployedTo");
List<CmsDpmtApproval> approvals = dpmtMapper.getDpmtApprovals(dpmt.getDeploymentId());
//convert to map
Map<Long,List<CmsDpmtApproval>> approvalMap = new HashMap<>();
for (CmsDpmtApproval approval : approvals) {
if (!approvalMap.containsKey(approval.getGovernCiId())) {
approvalMap.put(approval.getGovernCiId(), new ArrayList<>());
}
approvalMap.get(approval.getGovernCiId()).add(approval);
}
List<CmsCI> governCIs = new ArrayList<>();
for (long cloudId : cloudIds) {
for (CmsCIRelation supportRel : cmProcessor.getFromCIRelations(cloudId, "base.SupportedBy", null)) {
governCIs.add(supportRel.getToCi());
}
}
for (long cloudId : cloudIds) {
for (CmsCIRelation complianceRel : cmProcessor.getFromCIRelations(cloudId, "base.CompliesWith", null)) {
governCIs.add(complianceRel.getToCi());
}
}
for (CmsCI governCi : governCIs) {
if (governCi.getAttribute("enabled") != null
&& Boolean.TRUE.toString().equals(governCi.getAttribute("enabled").getDjValue())
&& governCi.getAttribute("approval") != null
&& Boolean.TRUE.toString().equals(governCi.getAttribute("approval").getDjValue())) {
if (!approvalMap.containsKey(governCi.getCiId())) {
createDpmtApproval(dpmt.getDeploymentId(), governCi);
needApproval= true;
} else {
CmsDpmtApproval approval = getLatestApproval(approvalMap.get(governCi.getCiId()));
if (approval == null) {
createDpmtApproval(dpmt.getDeploymentId(), governCi);
needApproval=true;
} else if (approval.getState().equals(APPROVAL_STATE_PENDING)) {
needApproval=true;
} else if (approval.getIsExpired() && approval.getState().equals(APPROVAL_STATE_APPROVED)){
//approval.setState(APPROVAL_STATE_EXPIRED);
//dpmtMapper.updDpmtApproval(approval);
createDpmtApproval(dpmt.getDeploymentId(), governCi);
needApproval=true;
}
}
}
}
return needApproval;
}
private CmsDpmtApproval getLatestApproval(List<CmsDpmtApproval> approvals) {
if (approvals.size() == 0) {
return null;
} else {
Collections.sort(approvals, (a1, a2) -> {
//Sorts by 'ApprovalId' property desc
return (int) (a2.getApprovalId() - a1.getApprovalId());
});
return approvals.get(0);
}
}
private boolean needApprovalForNewDpmt(CmsDeployment dpmt) {
List<Long> cloudIds = dpmtMapper.getToCiIdsForReleasePending(dpmt.getReleaseId(), "base.DeployedTo");
List<CmsCI> governCIs = new ArrayList<>();
for (long cloudId : cloudIds) {
for (CmsCIRelation supportRel : cmProcessor.getFromCIRelations(cloudId, "base.SupportedBy", null)) {
governCIs.add(supportRel.getToCi());
}
}
for (long cloudId : cloudIds) {
for (CmsCIRelation complianceRel : cmProcessor.getFromCIRelations(cloudId, "base.CompliesWith", null)) {
governCIs.add(complianceRel.getToCi());
}
}
for (CmsCI governCi : governCIs) {
if (governCi.getAttribute("enabled") != null
&& Boolean.TRUE.toString().equals(governCi.getAttribute("enabled").getDjValue())
&& governCi.getAttribute("approval") != null
&& Boolean.TRUE.toString().equals(governCi.getAttribute("approval").getDjValue())) {
return true; //this domt need approval
}
}
return false;
}
private void createDpmtApproval(long dpmtId, CmsCI governCi) {
CmsDpmtApproval approval = new CmsDpmtApproval();
approval.setDeploymentId(dpmtId);
approval.setGovernCiId(governCi.getCiId());
approval.setGovernCiJson(gson.toJson(governCi));
dpmtMapper.createDpmtApproval(approval);
logger.info("Created approval for dpmtId = " + dpmtId + " : " + approval.getGovernCiJson());
}
/**
* Update deployment.
*
* @param dpmt the dpmt
* @return the cms deployment
*/
public CmsDeployment updateDeployment(CmsDeployment dpmt) {
CmsDeployment existingDpmt = dpmtMapper.getDeployment(dpmt.getDeploymentId());
//in case the new stae = old state just update the comments and timestamp
//CMS_ALL event will not be generated
if (existingDpmt.getDeploymentState().equals(dpmt.getDeploymentState())) {
CmsDeployment clone = new CmsDeployment();
BeanUtils.copyProperties(dpmt, clone);
dpmt = clone; // need to clone deployment before resetting the status, to prevent cached deployment corruption
dpmt.setDeploymentState(null);
}
updateAutoDeployExecOrders(dpmt);
if (DPMT_STATE_CANCELED.equalsIgnoreCase(dpmt.getDeploymentState())) {
if (dpmtMapper.getDeploymentRecordsCountByState(dpmt.getDeploymentId(), DPMT_RECORD_STATE_INPROGRESS, null) > 0) {
String errMsg = "The deployment still have active work orders!";
logger.error(errMsg);
throw new DJException(CmsError.DJ_DEPLOYMENT_NOT_ACTIVE_FAILED_ERROR, errMsg);
}
if (DPMT_STATE_FAILED.equalsIgnoreCase(existingDpmt.getDeploymentState())
|| DPMT_STATE_PAUSED.equalsIgnoreCase(existingDpmt.getDeploymentState())
|| DPMT_STATE_PENDING.equalsIgnoreCase(existingDpmt.getDeploymentState())) {
dpmtMapper.cancelDeployment(dpmt);
logger.info("Updated dpmtId = " + dpmt.getDeploymentId() + " with new state " + dpmt.getDeploymentState());
} else {
String errMsg = "The deployment is not in failed/active state - " + existingDpmt.getDeploymentState();
logger.error(errMsg);
throw new DJException(CmsError.DJ_DEPLOYMENT_NOT_ACTIVE_FAILED_ERROR, errMsg);
}
} else if (DPMT_STATE_ACTIVE.equalsIgnoreCase(dpmt.getDeploymentState())) {
if (DPMT_STATE_PENDING.equalsIgnoreCase(existingDpmt.getDeploymentState())) {
if (!needApproval(dpmt)) {
dpmtMapper.updDeployment(dpmt);
logger.info("Updated dpmtId = " + dpmt.getDeploymentId() + " with new state " + dpmt.getDeploymentState());
}
} else if (DPMT_STATE_FAILED.equalsIgnoreCase(existingDpmt.getDeploymentState())) {
dpmtMapper.resetFailedRecords(dpmt);
if (needApproval(dpmt)) {
dpmt.setDeploymentState(DPMT_STATE_PENDING);
dpmtMapper.updDeployment(dpmt);
logger.info("Updated dpmtId = " + dpmt.getDeploymentId() + " with new state " + dpmt.getDeploymentState());
} else {
dpmtMapper.retryDeployment(dpmt);
}
} else if(DPMT_STATE_PAUSED.equalsIgnoreCase(existingDpmt.getDeploymentState())) {
if (needApproval(dpmt)) {
dpmt.setDeploymentState(DPMT_STATE_PENDING);
}
dpmtMapper.updDeployment(dpmt);
logger.info("Updated dpmtId = " + dpmt.getDeploymentId() + " with new state " + dpmt.getDeploymentState());
} else {
String errMsg = "The deployment is not in failed state - " + existingDpmt.getDeploymentState();
logger.error(errMsg);
throw new DJException(CmsError.DJ_DEPLOYMENT_NOT_FAILED_ERROR, errMsg);
}
} else if (DPMT_STATE_COMPLETE.equalsIgnoreCase(dpmt.getDeploymentState())) {
if (DPMT_STATE_ACTIVE.equalsIgnoreCase(existingDpmt.getDeploymentState())
|| DPMT_STATE_PAUSED.equalsIgnoreCase(existingDpmt.getDeploymentState())) {
//dpmtMapper.completeDeployment(dpmt);
completeDeployment(dpmt);
logger.info("Updated dpmtId = " + dpmt.getDeploymentId() + " with new state " + dpmt.getDeploymentState());
} else {
String errMsg = "The deployment is not in active state - " + existingDpmt.getDeploymentState();
logger.warn(errMsg);
//throw new DJException(errMsg);
}
} else if (DPMT_STATE_FAILED.equalsIgnoreCase(dpmt.getDeploymentState())) {
if (DPMT_STATE_ACTIVE.equalsIgnoreCase(existingDpmt.getDeploymentState())
|| DPMT_STATE_PAUSED.equalsIgnoreCase(existingDpmt.getDeploymentState())) {
dpmtMapper.updDeployment(dpmt);
logger.info("Updated dpmtId = " + dpmt.getDeploymentId() + " with new state " + dpmt.getDeploymentState());
} else {
String errMsg = "The deployment is not in active state - " + existingDpmt.getDeploymentState();
logger.error(errMsg);
throw new DJException(CmsError.DJ_DEPLOYMENT_NOT_ACTIVE_ERROR, errMsg);
}
} else if (DPMT_STATE_PAUSED.equalsIgnoreCase(dpmt.getDeploymentState())) {
if (DPMT_STATE_ACTIVE.equalsIgnoreCase(existingDpmt.getDeploymentState())) {
dpmtMapper.updDeployment(dpmt);
logger.info("Updated dpmtId = " + dpmt.getDeploymentId() + " with new state " + dpmt.getDeploymentState());
} else {
String errMsg = "The deployment is not in active state - " + existingDpmt.getDeploymentState();
logger.error(errMsg);
throw new DJException(CmsError.DJ_DEPLOYMENT_NOT_ACTIVE_ERROR, errMsg);
}
} else if (dpmt.getDeploymentState() == null) {
dpmtMapper.updDeployment(dpmt);
logger.info("Updated dpmtId = " + dpmt.getDeploymentId() + " with new state " + dpmt.getDeploymentState());
}
else {
String errMsg = "This state is not supported - " + dpmt.getDeploymentState();
logger.error(errMsg);
throw new DJException(CmsError.DJ_NOT_SUPPORTED_STATE_ERROR, errMsg);
}
return dpmtMapper.getDeployment(dpmt.getDeploymentId());
}
private void completeDeployment(CmsDeployment dpmt) {
dpmtMapper.completeDeployment(dpmt);
CmsRelease bomRelease = rfcProcessor.getReleaseById(dpmt.getReleaseId());
CmsRelease manifestRelease = rfcProcessor.getReleaseById(bomRelease.getParentReleaseId());
List<CmsCI> platforms = cmProcessor.getCiBy3NsLike(manifestRelease.getNsPath(), MANIFEST_PLATFORM_CLASS, null);
for (CmsCI plat : platforms) {
boolean vacuumAllowed = true;
List<CmsCI> monitorCiList = new ArrayList<>();
Set<Long> monitors4DeletedComponents = new HashSet<>();
List<CmsCIRelation> platformCloudRels = cmProcessor.getFromCIRelationsNaked(plat.getCiId(), "base.Consumes", "account.Cloud");
for (CmsCIRelation platformCloudRel : platformCloudRels) {
if (platformCloudRel.getAttribute("adminstatus") != null
&& !CmsConstants.CLOUD_STATE_ACTIVE.equals(platformCloudRel.getAttribute("adminstatus").getDjValue())) {
String platBomNs = plat.getNsPath().replace("/manifest/", "/bom/");
List<CmsCIRelation> deployedToRels = cmProcessor.getToCIRelationsByNsNaked(platformCloudRel.getToCiId(), "base.DeployedTo", null, null, platBomNs);
if (deployedToRels.size() >0) {
vacuumAllowed = false;
break;
}
} else {
List<CmsCI> componentsToDelet = cmProcessor.getCiByNsLikeByStateNaked(plat.getNsPath(), null, "pending_deletion");
for (CmsCI component : componentsToDelet) {
long ciId = component.getCiId();
if (CmsConstants.MONITOR_CLASS.equals(component.getCiClassName())) {
monitorCiList.add(component);
continue;
}
List<CmsCIRelation> realizedAsRels = cmProcessor.getFromCIRelationsNakedNoAttrs(ciId, "base.RealizedAs", null, null);
if (realizedAsRels.size() > 0) {
vacuumAllowed = false;
break;
}
List<CmsCIRelation> monitorRels = cmProcessor.getFromCIRelationsNakedNoAttrs(ciId, CmsConstants.MANIFEST_WATCHED_BY,
null, CmsConstants.MONITOR_CLASS);
if (monitorRels.size() > 0) {
monitors4DeletedComponents.addAll(monitorRels.stream().map(CmsCIRelationBasic::getToCiId).collect(Collectors.toList()));
}
}
if (!vacuumAllowed) {
break;
}
}
}
if (vacuumAllowed) {
//if there are monitors to be deleted, then make sure it satisfies one of these two
// 1. the monitors have corresponding parent CIs that are also marked pending_deletion, these would be in monitors4DeletedComponents
// 2. all the bom CIs for this manifest are updated for this manifest release
monitorCiList.removeIf(monitor -> monitors4DeletedComponents.contains(monitor.getCiId()));
List<CmsCI> monitorsEligible4Del = getMonitorsEligible4Del(monitorCiList);
if (monitorsEligible4Del.size() == monitorCiList.size()) {
nsMapper.vacuumNamespace(plat.getNsId(), dpmt.getCreatedBy());
}
else {
monitorsEligible4Del.forEach(monitor -> cmProcessor.deleteCI(monitor.getCiId(), dpmt.getCreatedBy()));
}
}
}
deleteGlobalVars(manifestRelease.getNsPath(), dpmt.getCreatedBy());
}
/**
* Delete global variables in pending_delete state
*
*/
private void deleteGlobalVars(String envNsPath, String userId) {
List <CmsCI> toDelComponents = cmProcessor.getCiByNsLikeByStateNaked(envNsPath + "/", null, "pending_deletion");
//if no components are marked for deletion then delete the global variables in pending_deletion state
if(toDelComponents.isEmpty()){
//delete global vars in pending_delete state
for (CmsCI globalVar : cmProcessor.getCiByNsLikeByStateNaked(envNsPath, "manifest.Globalvar", "pending_deletion")) {
cmProcessor.deleteCI(globalVar.getCiId(), true, userId);
}
}
}
private List<CmsCI> getMonitorsEligible4Del(List<CmsCI> monitorCiList) {
List<CmsCI> monitorsEligible4Del = new ArrayList<>();
if (!monitorCiList.isEmpty()) {
monitorsEligible4Del.addAll(monitorCiList.stream().
filter(monitor -> {
long monitorRfcId = monitor.getLastAppliedRfcId();
logger.info("monitor ci : " + monitor.getCiId() + ", last applied rfc id : " + monitorRfcId);
List<CmsCIRelation> parentRelation = cmProcessor.getToCIRelationsNakedNoAttrs(monitor.getCiId(),
CmsConstants.MANIFEST_WATCHED_BY, null, null);
if (parentRelation.size() > 0) {
long baseRfcId = monitorRfcId;
long parentCiId = parentRelation.get(0).getFromCiId();
//get the parent ci rfcId from the same release and use that to compare with bom instances
CmsRfcCI monitorRfc = rfcProcessor.getRfcCIById(monitorRfcId);
List<CmsRfcCI> parentRfcs = rfcProcessor.getRfcCIBy3(monitorRfc.getReleaseId(), true, parentCiId);
if (!parentRfcs.isEmpty()) {
baseRfcId = parentRfcs.get(0).getRfcId();
logger.info("component ci rfc id : " + baseRfcId);
}
//get count of boms that are not updated by this manifest rfc
long count = rfcProcessor.getCiCountNotUpdatedByRfc(parentCiId, CmsConstants.BASE_REALIZED_AS, null, baseRfcId);
logger.info("ci not deployed count " + count);
if (count > 0) {
//there are some bom CIs that are not deployed, so this monitor cannot be removed
return false;
}
}
return true;
}).
collect(Collectors.toList()));
}
return monitorsEligible4Del;
}
/**
* Update dpmt record.
*
* @param rec the rec
* @return the cms dpmt record
*/
public CmsDpmtRecord updateDpmtRecord(CmsDpmtRecord rec) {
dpmtMapper.updDpmtRecordState(rec);
return dpmtMapper.getDeploymentRecord(rec.getDpmtRecordId());
}
/**
* Complete work order.
*
* @param wo the wo
*/
public void completeWorkOrder(CmsWorkOrder wo) {
dpmtMapper.updDpmtRecordState(wo);
if (!wo.getRfcCi().getRfcAction().equalsIgnoreCase("delete") && wo.getResultCi() != null) {
wo.getResultCi().setUpdatedBy(wo.getRfcCi().getCreatedBy() + ":controller");
cmProcessor.updateCI(wo.getResultCi());
}
//return dpmtMapper.getDeploymentRecord(wo.getDpmtRecordId());
processAdditionalInfo(wo);
}
private void processAdditionalInfo(CmsWorkOrder wo) {
Map<String, String> additionalInfo = wo.getAdditionalInfo();
if (additionalInfo != null && !additionalInfo.isEmpty()) {
additionalInfo.entrySet().forEach(entry -> {
String key = entry.getKey();
if (ZONES_SELECTED.equalsIgnoreCase(key)) {
processSelectedZones(wo, entry);
}
});
}
}
private void processSelectedZones(CmsWorkOrder wo, Entry<String, String> entry) {
List<CmsCIRelation> existingRelations = cmProcessor.getFromCIRelations(wo.getResultCi().getCiId(),
CmsConstants.BASE_PLACED_IN, CmsConstants.ZONE_CLASS);
Map<String, CmsCIRelation> relationsMap = existingRelations.stream().
collect(Collectors.toMap(relation -> relation.getToCi().getCiName(), Function.identity()));
String values = entry.getValue();
if (values != null) {
String[] zones = values.split(",");
logger.info("selected zones for this ciId [" + wo.getResultCi().getCiId() + "] : " + values);
logger.info("existing zones : " + relationsMap.keySet());
Set<String> selectedZones = Collections.emptySet();
if (zones.length > 0) {
selectedZones = Stream.of(zones).map(String::trim).collect(Collectors.toSet());
createPlacedInRelations(selectedZones, relationsMap, wo);
}
removeOldRelations(selectedZones, relationsMap);
}
}
private void createPlacedInRelations(Set<String> zones, Map<String, CmsCIRelation> relationsMap, CmsWorkOrder wo) {
List<CmsCIRelation> deployedToRels = cmProcessor.getFromCIRelations(wo.getResultCi().getCiId(), CmsConstants.DEPLOYED_TO, CmsConstants.CLOUD_CLASS);
if (deployedToRels != null && !deployedToRels.isEmpty()) {
zones.stream().
filter(zone -> (zone.length() > 0 && !(relationsMap.containsKey(zone)))).
forEach(zone -> {
if (logger.isDebugEnabled()) {
logger.debug("creating base.PlacedIn relation to zone : " + zone);
}
CmsCI cloudCi = deployedToRels.get(0).getToCi();
String zoneNs = formZoneNsPath(cloudCi.getNsPath(), cloudCi.getCiName());
List<CmsCI> cis = cmProcessor.getCiBy3(zoneNs, CmsConstants.ZONE_CLASS, zone);
if (cis == null || cis.isEmpty()) {
logger.error("zone ci not found " + zone + ", nsPath : " + zoneNs);
}
else {
CmsCI zoneCi = cis.get(0);
CmsCI resultCi = wo.getResultCi();
CmsRfcCI rfcCi = wo.getRfcCi();
resultCi.setCiName(rfcCi.getCiName());
resultCi.setCiClassName(rfcCi.getCiClassName());
CmsCIRelation placedInRel = cmProcessor.bootstrapRelation(resultCi, zoneCi, CmsConstants.BASE_PLACED_IN, rfcCi.getNsPath(),
rfcCi.getCreatedBy(), rfcCi.getCreated());
cmProcessor.createRelation(placedInRel);
}
});
}
else {
logger.error("no base.DeployedTo relation found for ci " + wo.getResultCi().getCiId());
}
}
private void removeOldRelations(Set<String> zones, Map<String, CmsCIRelation> relationsMap) {
relationsMap.entrySet().stream().filter(entry -> !zones.contains(entry.getKey())).forEach(entry -> {
if (logger.isDebugEnabled()) {
logger.debug("removing base.PlacedIn relation to zone : " + entry.getKey());
}
cmProcessor.deleteRelation(entry.getValue().getCiRelationId(), true);
});
}
private String formZoneNsPath(String cloudNsPath, String cloudName) {
return cloudNsPath + "/" + cloudName;
}
/**
* Gets the deployment.
*
* @param dpmtId the dpmt id
* @return the deployment
*/
public CmsDeployment getDeployment(long dpmtId) {
return dpmtMapper.getDeployment(dpmtId);
}
/**
* Find deployment.
*
* @param nsPath the ns path
* @param state the state
* @param recursive the recursive
* @return the list
*/
public List<CmsDeployment> findDeployment(String nsPath, String state, Boolean recursive) {
if (recursive != null && recursive) {
String nsLike = CmsUtil.likefyNsPath(nsPath);
return dpmtMapper.findDeploymentRecursive(nsPath, nsLike, state);
} else {
return dpmtMapper.findDeployment(nsPath, state);
}
}
/**
* Find latest deployment.
*
* @param nsPath the ns path
* @param state the state
* @param recursive the recursive
* @return the list
*/
public List<CmsDeployment> findLatestDeployment(String nsPath, String state, Boolean recursive) {
if (recursive != null && recursive ) {
String nsLike = CmsUtil.likefyNsPath(nsPath);
return dpmtMapper.findLatestDeploymentRecursive(nsPath,nsLike, state);
} else {
return dpmtMapper.findLatestDeployment(nsPath, state);
}
}
/**
* Count deployment.
*
* @param nsPath the ns path
* @param state the state
* @param recursive the recursive
* @return the long
*/
public long countDeployment(String nsPath, String state, Boolean recursive) {
if (recursive != null && recursive ) {
String nsLike = CmsUtil.likefyNsPath(nsPath);
return dpmtMapper.countDeploymentRecursive(nsPath, nsLike, state);
} else {
return dpmtMapper.countDeployment(nsPath, state);
}
}
/**
* Count deployment group by.
*
* @param nsPath the ns path
* @param state the state
* @return the map
*/
public Map<String, Long> countDeploymentGroupBy(String nsPath, String state) {
Map<String, Long> result = new HashMap<>();
String nsLike = CmsUtil.likefyNsPath(nsPath);
List<Map<String,Object>> stats = dpmtMapper.countDeploymentGroupByNs(nsPath, nsLike, state);
for (Map<String,Object> row : stats) {
String nspath = (String)row.get("path");
Long cnt = (Long)row.get("cnt");
result.put(nspath, cnt);
}
return result;
}
/**
* Find deployment by release id.
*
* @param releaseId the release id
* @param state the state
* @return the list
*/
public List<CmsDeployment> findDeploymentByReleaseId(long releaseId, String state) {
return dpmtMapper.findDeploymentByReleaseId(releaseId, state);
}
/**
* Find latest deployment by release id.
*
* @param releaseId the release id
* @param state the state
* @return the list
*/
public List<CmsDeployment> findLatestDeploymentByReleaseId(long releaseId, String state) {
return dpmtMapper.findLatestDeploymentByReleaseId(releaseId, state);
}
/**
* Gets the deployment records.
*
* @param dpmtId the dpmt id
* @return the deployment records
*/
public List<CmsDpmtRecord> getDeploymentRecords(long dpmtId) {
return dpmtMapper.getDeploymentRecords(dpmtId);
}
/**
* Gets the deployment approvals.
*
* @param dpmtId the dpmt id
* @return the deployment approvals
*/
public List<CmsDpmtApproval> getDeploymentApprovals(long dpmtId) {
return dpmtMapper.getDpmtApprovals(dpmtId);
}
/**
* Gets the deployment approval.
*
* @param approvalId the approval id
* @return the deployment approval
*/
public CmsDpmtApproval getDeploymentApproval(long approvalId) {
return dpmtMapper.getDpmtApproval(approvalId);
}
/**
* Gets the deployment record by dpmtRfcId.
*
* @param dpmtRecordId the dpmtRfcId
* @return the deployment records
*/
public CmsDpmtRecord getDeploymentRecord(long dpmtRecordId) {
return dpmtMapper.getDeploymentRecord(dpmtRecordId);
}
/**
* Gets the deployment record cis.
*
* @param dpmtId the dpmt id
* @return the deployment record cis
*/
public List<CmsDpmtRecord> getDeploymentRecordCis(long dpmtId) {
return dpmtMapper.getDeploymentRecordCis(dpmtId);
}
/**
* Gets the deployment record cis.
*
* @param list of dpt record ids
* @return the deployment record cis
*/
public List<CmsDpmtRecord> getDeploymentRecordCis(long dpmtId, List<Long> list) {
return dpmtMapper.getDeploymentRecordCisByListOfIds(dpmtId, list);
}
/**
* Gets the deployment record cis.
*
* @param ciId the ciId
* @return the deployment record cis
*/
public List<CmsDpmtRecord> getDeploymentRecordByCiId(long ciId, String state) {
return dpmtMapper.getDeploymentRecordsByCiId(ciId, state);
}
/**
* Gets the deployment record cis by state.
*
* @param dpmtId the dpmt id
* @return the deployment record cis
*/
public List<CmsDpmtRecord> getDeploymentRecordCisByState(long dpmtId, String state, Integer execOrder) {
return dpmtMapper.getDeploymentRecordsByState(dpmtId, state, execOrder);
}
/**
* Gets the deployment record cis updated after a given timestamp.
*
* @param dpmtId the dpmt id
* @param timestamp udpated timestamp
* @return the deployment record cis
*/
public List<CmsDpmtRecord> getDeploymentRecordsUpdatedAfter(long dpmtId, Date timestamp) {
return dpmtMapper.getDeploymentRecordsUpdatedAfter(dpmtId, timestamp);
}
/**
* Gets the deployment record relations.
*
* @param dpmtId the dpmt id
* @return the deployment record relations
*/
public List<CmsDpmtRecord> getDeploymentRecordRelations(long dpmtId) {
return dpmtMapper.getDeploymentRecordRelations(dpmtId);
}
public long getDeploymentRecordCount(long dpmtId, String state, Integer execOrder) {
return dpmtMapper.getDeploymentRecordsCountByState(dpmtId, state, execOrder);
}
public List<CmsDpmtStateChangeEvent> getDeploymentStateHist(long deploymentId) {
return dpmtMapper.getDeploymentStateHist(deploymentId);
}
/**
* Gets the current deployments in progress for environment.
* @param nsPath The path to search for open deployments .
* @return will return *Null* if no deployment is found in |active|failed|paused| ,else return first deployment
* found in matching state
*/
public CmsDeployment getOpenDeployments(String nsPath) {
List<CmsDeployment> currentDeployments = findLatestDeployment(nsPath, null, false);
List<CmsDeployment> openDeployments = currentDeployments.stream().filter(cmsDeployment -> cmsDeployment.getDeploymentState().matches(OPEN_DEPLOYMENT_REGEXP)).collect(Collectors.toList());
if (openDeployments != null) {
if (openDeployments.size() > 0) {
return openDeployments.get(0);
}
}
return null;
}
public List<TimelineDeployment> getDeploymentsByFilter(TimelineQueryParam queryParam) {
String envNsPath = queryParam.getNsPath();
String filter = queryParam.getWildcardFilter();
List<TimelineDeployment> deployments = null;
if (!StringUtils.isBlank(filter)) {
queryParam.setDpmtNsLike(CmsUtil.likefyNsPathWithFilter(envNsPath, CmsConstants.BOM, null));
queryParam.setDpmtNsLikeWithFilter(CmsUtil.likefyNsPathWithFilter(envNsPath, CmsConstants.BOM, filter));
queryParam.setDpmtClassFilter(CmsConstants.BOM + "." + filter);
deployments = dpmtMapper.getDeploymentsByFilter(queryParam);
}
else {
deployments = getDeployments4NsPathLike(queryParam);
}
return deployments;
}
private List<TimelineDeployment> getDeployments4NsPathLike(TimelineQueryParam queryParam) {
queryParam.setDpmtNsLike(CmsUtil.likefyNsPathWithTypeNoEndingSlash(queryParam.getNsPath(), CmsConstants.BOM));
return dpmtMapper.getDeploymentsByNsPath(queryParam);
}
} | update function fix
| src/main/java/com/oneops/cms/dj/service/CmsDpmtProcessor.java | update function fix | <ide><path>rc/main/java/com/oneops/cms/dj/service/CmsDpmtProcessor.java
<ide> *******************************************************************************/
<ide> package com.oneops.cms.dj.service;
<ide>
<add>import com.google.gson.Gson;
<add>import com.oneops.cms.cm.domain.CmsCI;
<add>import com.oneops.cms.cm.domain.CmsCIRelation;
<add>import com.oneops.cms.cm.domain.CmsCIRelationBasic;
<add>import com.oneops.cms.cm.service.CmsCmProcessor;
<add>import com.oneops.cms.dj.dal.DJDpmtMapper;
<add>import com.oneops.cms.dj.domain.*;
<add>import com.oneops.cms.exceptions.DJException;
<add>import com.oneops.cms.ns.dal.NSMapper;
<add>import com.oneops.cms.util.*;
<add>import org.apache.commons.lang3.StringUtils;
<add>import org.apache.log4j.Logger;
<add>import org.springframework.dao.DuplicateKeyException;
<add>
<ide> import java.lang.reflect.InvocationTargetException;
<del>import java.util.ArrayList;
<del>import java.util.Date;
<del>import java.util.Collections;
<del>import java.util.HashMap;
<del>import java.util.HashSet;
<del>import java.util.List;
<del>import java.util.Map;
<add>import java.util.*;
<ide> import java.util.Map.Entry;
<del>import java.util.Set;
<ide> import java.util.function.Function;
<ide> import java.util.stream.Collectors;
<ide> import java.util.stream.Stream;
<del>
<del>import com.oneops.cms.cm.domain.CmsCIRelationBasic;
<del>import org.apache.commons.lang3.StringUtils;
<del>import org.apache.log4j.Logger;
<del>import org.springframework.beans.BeanUtils;
<del>import org.springframework.dao.DuplicateKeyException;
<del>
<del>import com.google.gson.Gson;
<del>import com.oneops.cms.cm.domain.CmsCI;
<del>import com.oneops.cms.cm.domain.CmsCIRelation;
<del>import com.oneops.cms.cm.service.CmsCmProcessor;
<del>import com.oneops.cms.dj.dal.DJDpmtMapper;
<del>import com.oneops.cms.dj.domain.CmsDeployment;
<del>import com.oneops.cms.dj.domain.TimelineDeployment;
<del>import com.oneops.cms.dj.domain.CmsDpmtApproval;
<del>import com.oneops.cms.dj.domain.CmsDpmtRecord;
<del>import com.oneops.cms.dj.domain.CmsDpmtStateChangeEvent;
<del>import com.oneops.cms.dj.domain.CmsRelease;
<del>import com.oneops.cms.dj.domain.CmsRfcCI;
<del>import com.oneops.cms.dj.domain.CmsWorkOrder;
<del>import com.oneops.cms.exceptions.DJException;
<del>import com.oneops.cms.ns.dal.NSMapper;
<del>import com.oneops.cms.util.CmsConstants;
<del>import com.oneops.cms.util.CmsError;
<del>import com.oneops.cms.util.CmsUtil;
<del>import com.oneops.cms.util.ListUtils;
<del>import com.oneops.cms.util.TimelineQueryParam;
<ide>
<ide> /**
<ide> * The Class CmsDpmtProcessor.
<ide> */
<ide> public CmsDeployment updateDeployment(CmsDeployment dpmt) {
<ide> CmsDeployment existingDpmt = dpmtMapper.getDeployment(dpmt.getDeploymentId());
<del> //in case the new stae = old state just update the comments and timestamp
<del> //CMS_ALL event will not be generated
<del> if (existingDpmt.getDeploymentState().equals(dpmt.getDeploymentState())) {
<del> CmsDeployment clone = new CmsDeployment();
<del> BeanUtils.copyProperties(dpmt, clone);
<del> dpmt = clone; // need to clone deployment before resetting the status, to prevent cached deployment corruption
<del> dpmt.setDeploymentState(null);
<del> }
<ide>
<ide> updateAutoDeployExecOrders(dpmt);
<ide>
<del> if (DPMT_STATE_CANCELED.equalsIgnoreCase(dpmt.getDeploymentState())) {
<add> //in case the new state = old state just update the comments and timestamp CMS_ALL event will not be generated
<add> if (existingDpmt.getDeploymentState().equals(dpmt.getDeploymentState())) {
<add> String currentState = dpmt.getDeploymentState();
<add> dpmt.setDeploymentState(null);
<add> dpmtMapper.updDeployment(dpmt);
<add> logger.info("Updated dpmtId = " + dpmt.getDeploymentId() + " kept the old state ");
<add> dpmt.setDeploymentState(currentState);
<add> } else if (DPMT_STATE_CANCELED.equalsIgnoreCase(dpmt.getDeploymentState())) {
<ide> if (dpmtMapper.getDeploymentRecordsCountByState(dpmt.getDeploymentId(), DPMT_RECORD_STATE_INPROGRESS, null) > 0) {
<ide> String errMsg = "The deployment still have active work orders!";
<ide> logger.error(errMsg);
<ide> logger.error(errMsg);
<ide> throw new DJException(CmsError.DJ_DEPLOYMENT_NOT_ACTIVE_ERROR, errMsg);
<ide> }
<del> } else if (dpmt.getDeploymentState() == null) {
<del> dpmtMapper.updDeployment(dpmt);
<del> logger.info("Updated dpmtId = " + dpmt.getDeploymentId() + " with new state " + dpmt.getDeploymentState());
<del> }
<del> else {
<add> } else {
<ide> String errMsg = "This state is not supported - " + dpmt.getDeploymentState();
<ide> logger.error(errMsg);
<ide> throw new DJException(CmsError.DJ_NOT_SUPPORTED_STATE_ERROR, errMsg); |
|
Java | apache-2.0 | 61ab3209b230cb2171945cdf8326a49d942cabd7 | 0 | fengyie007/dubbo,bpzhang/dubbo,wuwen5/dubbo,yuyijq/dubbo,qtvbwfn/dubbo,fengyie007/dubbo,qtvbwfn/dubbo,bpzhang/dubbo,yuyijq/dubbo,qtvbwfn/dubbo,qtvbwfn/dubbo,wuwen5/dubbo,lovepoem/dubbo,lovepoem/dubbo,lovepoem/dubbo,wuwen5/dubbo,fengyie007/dubbo,bpzhang/dubbo | /*
* 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.dubbo.common.config;
/**
* Configuration interface, to fetch the value for the specified key.
*/
public interface Configuration {
/**
* Get a string associated with the given configuration key.
*
* @param key The configuration key.
* @return The associated string.
*/
default String getString(String key) {
return convert(String.class, key, null);
}
/**
* Get a string associated with the given configuration key.
* If the key doesn't map to an existing object, the default value
* is returned.
*
* @param key The configuration key.
* @param defaultValue The default value.
* @return The associated string if key is found and has valid
* format, default value otherwise.
*/
default String getString(String key, String defaultValue) {
return convert(String.class, key, defaultValue);
}
/**
* Gets a property from the configuration. This is the most basic get
* method for retrieving values of properties. In a typical implementation
* of the {@code Configuration} interface the other get methods (that
* return specific data types) will internally make use of this method. On
* this level variable substitution is not yet performed. The returned
* object is an internal representation of the property value for the passed
* in key. It is owned by the {@code Configuration} object. So a caller
* should not modify this object. It cannot be guaranteed that this object
* will stay constant over time (i.e. further update operations on the
* configuration may change its internal state).
*
* @param key property to retrieve
* @return the value to which this configuration maps the specified key, or
* null if the configuration contains no mapping for this key.
*/
default Object getProperty(String key) {
return getProperty(key, null);
}
/**
* Gets a property from the configuration. The default value will return if the configuration doesn't contain
* the mapping for the specified key.
*
* @param key property to retrieve
* @param defaultValue default value
* @return the value to which this configuration maps the specified key, or default value if the configuration
* contains no mapping for this key.
*/
default Object getProperty(String key, Object defaultValue) {
Object value = getInternalProperty(key);
return value != null ? value : defaultValue;
}
Object getInternalProperty(String key);
/**
* Check if the configuration contains the specified key.
*
* @param key the key whose presence in this configuration is to be tested
* @return {@code true} if the configuration contains a value for this
* key, {@code false} otherwise
*/
default boolean containsKey(String key) {
return getProperty(key) != null;
}
default <T> T convert(Class<T> cls, String key, T defaultValue) {
// we only process String properties for now
String value = (String) getProperty(key);
if (value == null) {
return defaultValue;
}
Object obj = value;
if (cls.isInstance(value)) {
return cls.cast(value);
}
if (Boolean.class.equals(cls) || Boolean.TYPE.equals(cls)) {
obj = Boolean.valueOf(value);
} else if (Number.class.isAssignableFrom(cls) || cls.isPrimitive()) {
if (Integer.class.equals(cls) || Integer.TYPE.equals(cls)) {
obj = Integer.valueOf(value);
} else if (Long.class.equals(cls) || Long.TYPE.equals(cls)) {
obj = Long.valueOf(value);
} else if (Byte.class.equals(cls) || Byte.TYPE.equals(cls)) {
obj = Byte.valueOf(value);
} else if (Short.class.equals(cls) || Short.TYPE.equals(cls)) {
obj = Short.valueOf(value);
} else if (Float.class.equals(cls) || Float.TYPE.equals(cls)) {
obj = Float.valueOf(value);
} else if (Double.class.equals(cls) || Double.TYPE.equals(cls)) {
obj = Double.valueOf(value);
}
} else if (cls.isEnum()) {
obj = Enum.valueOf(cls.asSubclass(Enum.class), value);
}
return cls.cast(obj);
}
}
| dubbo-common/src/main/java/org/apache/dubbo/common/config/Configuration.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.dubbo.common.config;
/**
* Configuration interface, to fetch the value for the specified key.
*/
public interface Configuration {
/**
* Get a string associated with the given configuration key.
*
* @param key The configuration key.
* @return The associated string.
*/
default String getString(String key) {
return convert(String.class, key, null);
}
/**
* Get a string associated with the given configuration key.
* If the key doesn't map to an existing object, the default value
* is returned.
*
* @param key The configuration key.
* @param defaultValue The default value.
* @return The associated string if key is found and has valid
* format, default value otherwise.
*/
default String getString(String key, String defaultValue) {
return convert(String.class, key, defaultValue);
}
/**
* Gets a property from the configuration. This is the most basic get
* method for retrieving values of properties. In a typical implementation
* of the {@code Configuration} interface the other get methods (that
* return specific data types) will internally make use of this method. On
* this level variable substitution is not yet performed. The returned
* object is an internal representation of the property value for the passed
* in key. It is owned by the {@code Configuration} object. So a caller
* should not modify this object. It cannot be guaranteed that this object
* will stay constant over time (i.e. further update operations on the
* configuration may change its internal state).
*
* @param key property to retrieve
* @return the value to which this configuration maps the specified key, or
* null if the configuration contains no mapping for this key.
*/
default Object getProperty(String key) {
return getProperty(key, null);
}
/**
* Gets a property from the configuration. The default value will return if the configuration doesn't contain
* the mapping for the specified key.
*
* @param key property to retrieve
* @param defaultValue default value
* @return the value to which this configuration maps the specified key, or default value if the configuration
* contains no mapping for this key.
*/
default Object getProperty(String key, Object defaultValue) {
Object value = getInternalProperty(key);
return value != null ? value : defaultValue;
}
Object getInternalProperty(String key);
/**
* Check if the configuration contains the specified key.
*
* @param key the key whose presence in this configuration is to be tested
* @return {@code true} if the configuration contains a value for this
* key, {@code false} otherwise
*/
default boolean containsKey(String key) {
return getProperty(key) != null;
}
default <T> T convert(Class<T> cls, String key, T defaultValue) {
// we only process String properties for now
String value = (String) getProperty(key);
if (value == null) {
return defaultValue;
}
Object obj = value;
if (cls.isInstance(value)) {
return cls.cast(value);
}
if (String.class.equals(cls)) {
return cls.cast(value);
}
if (Boolean.class.equals(cls) || Boolean.TYPE.equals(cls)) {
obj = Boolean.valueOf(value);
} else if (Number.class.isAssignableFrom(cls) || cls.isPrimitive()) {
if (Integer.class.equals(cls) || Integer.TYPE.equals(cls)) {
obj = Integer.valueOf(value);
} else if (Long.class.equals(cls) || Long.TYPE.equals(cls)) {
obj = Long.valueOf(value);
} else if (Byte.class.equals(cls) || Byte.TYPE.equals(cls)) {
obj = Byte.valueOf(value);
} else if (Short.class.equals(cls) || Short.TYPE.equals(cls)) {
obj = Short.valueOf(value);
} else if (Float.class.equals(cls) || Float.TYPE.equals(cls)) {
obj = Float.valueOf(value);
} else if (Double.class.equals(cls) || Double.TYPE.equals(cls)) {
obj = Double.valueOf(value);
}
} else if (cls.isEnum()) {
obj = Enum.valueOf(cls.asSubclass(Enum.class), value);
}
return cls.cast(obj);
}
}
| Delete dead code (#4189)
| dubbo-common/src/main/java/org/apache/dubbo/common/config/Configuration.java | Delete dead code (#4189) | <ide><path>ubbo-common/src/main/java/org/apache/dubbo/common/config/Configuration.java
<ide> return cls.cast(value);
<ide> }
<ide>
<del> if (String.class.equals(cls)) {
<del> return cls.cast(value);
<del> }
<del>
<ide> if (Boolean.class.equals(cls) || Boolean.TYPE.equals(cls)) {
<ide> obj = Boolean.valueOf(value);
<ide> } else if (Number.class.isAssignableFrom(cls) || cls.isPrimitive()) { |
|
Java | epl-1.0 | 4e59d4d007a122419e505946595ebb7193fe0792 | 0 | julianapaz/LP2-5M | package com.senac.algoritmos;
import java.util.Scanner;
import static java.lang.System.*;
import com.senac.estruturas.PilhaCheia;
import com.senac.estruturas.PilhaOperador;
import com.senac.estruturas.PilhaOperando;
import com.senac.estruturas.PilhaVazia;
public class AvaliadorRPN {
public static double avalia(String expressao) throws PilhaCheia,
PilhaVazia, InvalidOperator {
PilhaOperando pilha = new PilhaOperando(50);
Scanner sc = new Scanner(expressao);
while (sc.hasNext()) {
if (sc.hasNextInt()) {
pilha.push(sc.nextInt());
} else {
String op = sc.next();
double rhs = pilha.pop();
double lhs = pilha.pop();
pilha.push(executaOperador(op.charAt(0), lhs, rhs));
}
}
return pilha.pop();
}
public static double inversorPosFixo(String expressao)throws PilhaCheia, PilhaVazia, InvalidOperator{
Scanner entrada= new Scanner(expressao);
PilhaOperador pilha = new PilhaOperador(50);
String saida = "";
while (entrada.hasNext())
{
if (entrada.hasNextInt())
{
saida +=" " + entrada.next();
}
else
{
String opLido = entrada.next();
if ( ehFechaParentes(opLido) ){
do{
saida += " " + pilha.pop();
}while( !ehAbreParenteses(pilha.peek()) );
pilha.pop();
}
else
{
if ( pilha.isEmpty() || ehAbreParenteses(pilha.peek()) )
{
pilha.push(opLido);
}
else if ( prioridade(opLido)>prioridade(pilha.peek()) )
pilha.push(opLido);
else
{
while ( !pilha.isEmpty() && prioridade(opLido)<prioridade(pilha.peek()) && !ehAbreParenteses(pilha.peek()) )
{
saida +=" "+pilha.pop();
}
pilha.push(opLido);
}
}
}
}
while ( !pilha.isEmpty() )
{
saida += " "+pilha.pop();
}
return avalia(saida);
}
public static boolean ehAbreParenteses(String op) {
return op.equals("(");
}
public static boolean ehFechaParentes(String op) {
return op.equals(")");
}
public static int prioridade(String operador) throws InvalidOperator {
int precedencia = 0;
switch (operador.charAt(0)) {
case '(':
precedencia = 3;
break;
case '*':
precedencia = 2;
break;
case '/':
precedencia = 2;
break;
case '+':
precedencia = 1;
break;
case '-':
precedencia = 1;
break;
default:
throw new InvalidOperator(operador.charAt(0));
}
return precedencia;
}
private static double executaOperador(char op, double lhs, double rhs)
throws InvalidOperator {
switch (op) {
case '+':
return lhs + rhs;
case '-':
return lhs - rhs;
case '*':
return lhs * rhs;
case '/':
return lhs / rhs;
default:
throw new InvalidOperator(op);
}
}
}
| TrabalhoPilha/src/com/senac/algoritmos/AvaliadorRPN.java | package com.senac.algoritmos;
import java.util.Scanner;
import com.senac.estruturas.PilhaCheia;
import com.senac.estruturas.PilhaOperador;
import com.senac.estruturas.PilhaOperando;
import com.senac.estruturas.PilhaVazia;
public class AvaliadorRPN {
public static double avalia(String expressao) throws PilhaCheia,
PilhaVazia, InvalidOperator {
PilhaOperando pilha = new PilhaOperando(50);
Scanner sc = new Scanner(expressao);
while (sc.hasNext()) {
if (sc.hasNextInt()) {
pilha.push(sc.nextInt());
} else {
String op = sc.next();
double rhs = pilha.pop();
double lhs = pilha.pop();
pilha.push(executaOperador(op.charAt(0), lhs, rhs));
}
}
return pilha.pop();
}
public static void inversorPosFixo(String expressao)throws PilhaCheia, PilhaVazia, InvalidOperator{
Scanner entrada= new Scanner(expressao);
PilhaOperador pilha = new PilhaOperador(50);
String saida = "";
while (entrada.hasNext())
{
if (entrada.hasNextInt())
{
saida +=" " + entrada.next();
}
else
{
String opLido = entrada.next();
/*Se for o operador ")", desempilhar ate que o
operador "(" seja o operador "desempilhado";
a cada operador desempilhado, enviar para a
sa’da (com excecao do "(").*/
if (ehFechaParentes(opLido)){
do{
// if(ehAbreParenteses(pilha.peek()))
// pilha.pop();
//else
saida += " " + pilha.pop();
}while(!ehAbreParenteses(pilha.peek()));
}
/*Sen‹o, se o operador tiver prioridade MAIOR
que o operador do topo da pilha, ou se a pilha
estiver vazia, ou o operador do topo da pilha
for "(", empilhar o operador.*/
else
{
if ( pilha.isEmpty() || ehAbreParenteses(pilha.peek()) )
{
//if(prioridade(opLido)>prioridade(pilha.peek()))
pilha.push(opLido);
/*Sen‹o, dempilhar (enviando para a sa’da) os
operadores da pilha atŽ que o operador tenha
prioridade MAIOR que o operador do topo, ou
que o operador do topo da pilha seja "(",
ou que a pilha esteja vazia. Empilhar o operador.*/
}
else if (prioridade(opLido)>prioridade(pilha.peek()))
pilha.push(opLido);
else
{
while (prioridade(opLido)<prioridade(pilha.peek()) || !ehAbreParenteses(pilha.peek()) || !pilha.isEmpty())
{
if (ehAbreParenteses(pilha.peek()))
pilha.pop();
else
saida +=" "+pilha.pop();
}
//Empilhar o operador.
pilha.push(opLido);
}
}
}
}
/* Desempilhar os operadores da pilha enviando para a sa’da atŽ
que a pilha fique vazia. Nenhum desse operadores pode ser o "(".*/
while (!pilha.isEmpty())
{
if (ehAbreParenteses(pilha.peek()))
pilha.pop();
else
saida += " "+pilha.pop();
}
System.out.print("Notação"+saida+"\n");
System.out.print(AvaliadorRPN.avalia(saida));
}
public static boolean ehAbreParenteses(String op) {
return op.equals("(");
}
public static boolean ehFechaParentes(String op) {
return op.equals(")");
}
public static int prioridade(String operador) throws InvalidOperator {
int precedencia = 0;
switch (operador.charAt(0)) {
case '(':
precedencia = 3;
break;
case '*':
precedencia = 2;
break;
case '/':
precedencia = 2;
break;
case '+':
precedencia = 1;
break;
case '-':
precedencia = 1;
break;
//n precisa
case ')':
precedencia = 0;
break;
default:
throw new InvalidOperator(operador.charAt(0));
}
return precedencia;
}
private static double executaOperador(char op, double lhs, double rhs)
throws InvalidOperator {
switch (op) {
case '+':
return lhs + rhs;
case '-':
return lhs - rhs;
case '*':
return lhs * rhs;
case '/':
return lhs / rhs;
default:
throw new InvalidOperator(op);
}
}
}
| Update AvaliadorRPN.java | TrabalhoPilha/src/com/senac/algoritmos/AvaliadorRPN.java | Update AvaliadorRPN.java | <ide><path>rabalhoPilha/src/com/senac/algoritmos/AvaliadorRPN.java
<ide> package com.senac.algoritmos;
<ide>
<ide> import java.util.Scanner;
<del>
<add>import static java.lang.System.*;
<ide> import com.senac.estruturas.PilhaCheia;
<ide> import com.senac.estruturas.PilhaOperador;
<ide> import com.senac.estruturas.PilhaOperando;
<ide> return pilha.pop();
<ide> }
<ide>
<del>
<del>
<del> public static void inversorPosFixo(String expressao)throws PilhaCheia, PilhaVazia, InvalidOperator{
<add> public static double inversorPosFixo(String expressao)throws PilhaCheia, PilhaVazia, InvalidOperator{
<ide> Scanner entrada= new Scanner(expressao);
<ide>
<ide> PilhaOperador pilha = new PilhaOperador(50);
<ide> String saida = "";
<del>
<ide>
<ide> while (entrada.hasNext())
<ide> {
<ide> {
<ide> String opLido = entrada.next();
<ide>
<del> /*Se for o operador ")", desempilhar ate que o
<del> operador "(" seja o operador "desempilhado";
<del> a cada operador desempilhado, enviar para a
<del> sa’da (com excecao do "(").*/
<del> if (ehFechaParentes(opLido)){
<add> if ( ehFechaParentes(opLido) ){
<ide> do{
<del> // if(ehAbreParenteses(pilha.peek()))
<del> // pilha.pop();
<del> //else
<add>
<ide> saida += " " + pilha.pop();
<ide>
<del> }while(!ehAbreParenteses(pilha.peek()));
<add> }while( !ehAbreParenteses(pilha.peek()) );
<add>
<add> pilha.pop();
<ide> }
<del>
<del> /*Sen‹o, se o operador tiver prioridade MAIOR
<del> que o operador do topo da pilha, ou se a pilha
<del> estiver vazia, ou o operador do topo da pilha
<del> for "(", empilhar o operador.*/
<ide>
<ide> else
<ide> {
<ide> if ( pilha.isEmpty() || ehAbreParenteses(pilha.peek()) )
<del> {
<add> {
<add> pilha.push(opLido);
<add> }
<ide>
<del> //if(prioridade(opLido)>prioridade(pilha.peek()))
<add> else if ( prioridade(opLido)>prioridade(pilha.peek()) )
<ide> pilha.push(opLido);
<ide>
<del> /*Sen‹o, dempilhar (enviando para a sa’da) os
<del> operadores da pilha atŽ que o operador tenha
<del> prioridade MAIOR que o operador do topo, ou
<del> que o operador do topo da pilha seja "(",
<del> ou que a pilha esteja vazia. Empilhar o operador.*/
<del> }
<del> else if (prioridade(opLido)>prioridade(pilha.peek()))
<del> pilha.push(opLido);
<add> else
<add> {
<add> while ( !pilha.isEmpty() && prioridade(opLido)<prioridade(pilha.peek()) && !ehAbreParenteses(pilha.peek()) )
<add> {
<add> saida +=" "+pilha.pop();
<add> }
<ide>
<del> else
<del> {
<del> while (prioridade(opLido)<prioridade(pilha.peek()) || !ehAbreParenteses(pilha.peek()) || !pilha.isEmpty())
<del> {
<del> if (ehAbreParenteses(pilha.peek()))
<del> pilha.pop();
<del> else
<del> saida +=" "+pilha.pop();
<del> }
<del> //Empilhar o operador.
<ide> pilha.push(opLido);
<ide> }
<add> }
<ide> }
<ide> }
<del> }
<add> while ( !pilha.isEmpty() )
<add> {
<add> saida += " "+pilha.pop();
<add> }
<ide>
<del>
<del>
<del> /* Desempilhar os operadores da pilha enviando para a sa’da atŽ
<del> que a pilha fique vazia. Nenhum desse operadores pode ser o "(".*/
<del>
<del>
<del> while (!pilha.isEmpty())
<del> {
<del> if (ehAbreParenteses(pilha.peek()))
<del> pilha.pop();
<del> else
<del> saida += " "+pilha.pop();
<del> }
<del>
<del> System.out.print("Notação"+saida+"\n");
<del> System.out.print(AvaliadorRPN.avalia(saida));
<del>}
<del>
<del>public static boolean ehAbreParenteses(String op) {
<del> return op.equals("(");
<del>}
<del>
<del>public static boolean ehFechaParentes(String op) {
<del> return op.equals(")");
<del>
<del>}
<del>
<del>public static int prioridade(String operador) throws InvalidOperator {
<del> int precedencia = 0;
<del> switch (operador.charAt(0)) {
<del> case '(':
<del> precedencia = 3;
<del> break;
<del>
<del> case '*':
<del> precedencia = 2;
<del> break;
<del>
<del> case '/':
<del> precedencia = 2;
<del> break;
<del>
<del> case '+':
<del> precedencia = 1;
<del> break;
<del>
<del> case '-':
<del> precedencia = 1;
<del> break;
<del>
<del> //n precisa
<del> case ')':
<del> precedencia = 0;
<del> break;
<del>
<del> default:
<del> throw new InvalidOperator(operador.charAt(0));
<add> return avalia(saida);
<ide> }
<ide>
<del> return precedencia;
<del>}
<add> public static boolean ehAbreParenteses(String op) {
<add> return op.equals("(");
<add> }
<ide>
<del>private static double executaOperador(char op, double lhs, double rhs)
<del> throws InvalidOperator {
<del> switch (op) {
<del> case '+':
<del> return lhs + rhs;
<del> case '-':
<del> return lhs - rhs;
<del> case '*':
<del> return lhs * rhs;
<del> case '/':
<del> return lhs / rhs;
<del> default:
<del> throw new InvalidOperator(op);
<add> public static boolean ehFechaParentes(String op) {
<add> return op.equals(")");
<add>
<add> }
<add>
<add> public static int prioridade(String operador) throws InvalidOperator {
<add> int precedencia = 0;
<add> switch (operador.charAt(0)) {
<add> case '(':
<add> precedencia = 3;
<add> break;
<add>
<add> case '*':
<add> precedencia = 2;
<add> break;
<add>
<add> case '/':
<add> precedencia = 2;
<add> break;
<add>
<add> case '+':
<add> precedencia = 1;
<add> break;
<add>
<add> case '-':
<add> precedencia = 1;
<add> break;
<add>
<add> default:
<add> throw new InvalidOperator(operador.charAt(0));
<add> }
<add>
<add> return precedencia;
<add> }
<add>
<add> private static double executaOperador(char op, double lhs, double rhs)
<add> throws InvalidOperator {
<add> switch (op) {
<add> case '+':
<add> return lhs + rhs;
<add> case '-':
<add> return lhs - rhs;
<add> case '*':
<add> return lhs * rhs;
<add> case '/':
<add> return lhs / rhs;
<add> default:
<add> throw new InvalidOperator(op);
<add> }
<ide> }
<ide> }
<del>} |
|
Java | apache-2.0 | 2a983d8efc511251b6e3eed4f0514a46e72230f0 | 0 | hakan42/sync-for-xing | package com.gurkensalat.android.xingsync;
import java.util.List;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.TextView;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.Click;
import com.googlecode.androidannotations.annotations.EActivity;
import com.googlecode.androidannotations.annotations.ViewById;
import com.googlecode.androidannotations.annotations.sharedpreferences.Pref;
import com.gurkensalat.android.xingsync.api.ContactsCall;
import com.gurkensalat.android.xingsync.api.MeCall;
import com.gurkensalat.android.xingsync.api.User;
import com.gurkensalat.android.xingsync.preferences.SyncPrefs_;
import com.gurkensalat.android.xingsync.sync.AccountAuthenticatorService;
@EActivity
public class HelloAndroidActivity extends Activity
{
private static Logger LOG = LoggerFactory.getLogger(HelloAndroidActivity.class);
@ViewById(R.id.oauth_api_call_result)
TextView oauth_api_call_result;
@Bean
ContactsCall contactsCall;
@Bean
MeCall meCall;
@Pref
SyncPrefs_ syncPrefs;
@Override
public void onCreate(Bundle savedInstanceState)
{
LOG.info("onCreate");
super.onCreate(savedInstanceState);
// if (AccountAuthenticatorService.hasAccount(getApplicationContext()))
// {
// setContentView(R.layout.main);
// }
// else
{
Intent intent = new Intent(Settings.ACTION_SYNC_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
// To show only our own accounts
// intent.putExtra(Settings.EXTRA_AUTHORITIES, new String[] {
// getResources().getString(R.string.ACCOUNT_TYPE) });
startActivity(intent);
}
}
@Click(R.id.btn_perform_contacts_call)
void performContactsCall(View clickedView)
{
LOG.info("About to call 'contacts' api method");
if (contactsCall != null)
{
String text = "Call 'Contacts'";
text = text + "\n";
JSONObject json = contactsCall.perform();
displayResults(text, json);
List<User> users = contactsCall.parse(json);
if (users != null)
{
displayAdditionalString(users.toString());
}
}
}
@Click(R.id.btn_perform_me_call)
void performMeCall(View clickedView)
{
LOG.info("About to call 'me' api method");
if (meCall != null)
{
String text = "Call 'Me'";
text = text + "\n";
JSONObject json = meCall.perform();
displayResults(text, json);
User user = meCall.performAndParse();
if (user != null)
{
displayAdditionalString(user.toString());
}
}
}
@Click(R.id.btn_clear_credentials)
void clearCredentials(View clickedView)
{
LOG.info("About to clear credentials");
syncPrefs.edit().oauth_token().put("").apply();
syncPrefs.edit().oauth_token_secret().put("").apply();
}
private void displayResults(String text, JSONObject json)
{
if (json != null)
{
text = text + json.toString();
text = text + "\n";
}
oauth_api_call_result.setText(text);
}
private void displayAdditionalString(String additionalText)
{
if (additionalText != null)
{
oauth_api_call_result.setText(oauth_api_call_result.getText() + "\n" + additionalText);
}
}
}
| xing-sync-app/src/main/java/com/gurkensalat/android/xingsync/HelloAndroidActivity.java | package com.gurkensalat.android.xingsync;
import java.util.List;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.TextView;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.Click;
import com.googlecode.androidannotations.annotations.EActivity;
import com.googlecode.androidannotations.annotations.ViewById;
import com.googlecode.androidannotations.annotations.sharedpreferences.Pref;
import com.gurkensalat.android.xingsync.api.ContactsCall;
import com.gurkensalat.android.xingsync.api.MeCall;
import com.gurkensalat.android.xingsync.api.User;
import com.gurkensalat.android.xingsync.preferences.SyncPrefs_;
import com.gurkensalat.android.xingsync.sync.AccountAuthenticatorService;
@EActivity
public class HelloAndroidActivity extends Activity
{
private static Logger LOG = LoggerFactory.getLogger(HelloAndroidActivity.class);
@ViewById(R.id.oauth_api_call_result)
TextView oauth_api_call_result;
@Bean
ContactsCall contactsCall;
@Bean
MeCall meCall;
@Pref
SyncPrefs_ syncPrefs;
@Override
public void onCreate(Bundle savedInstanceState)
{
LOG.info("onCreate");
super.onCreate(savedInstanceState);
// if (AccountAuthenticatorService.hasAccount(getApplicationContext()))
// {
// setContentView(R.layout.main);
// }
// else
{
Intent intent = new Intent(Settings.ACTION_SYNC_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
// To show only our own accounts
intent.putExtra(Settings.EXTRA_AUTHORITIES, new String[] { getResources().getString(R.string.ACCOUNT_TYPE) });
startActivity(intent);
}
}
@Click(R.id.btn_perform_contacts_call)
void performContactsCall(View clickedView)
{
LOG.info("About to call 'contacts' api method");
if (contactsCall != null)
{
String text = "Call 'Contacts'";
text = text + "\n";
JSONObject json = contactsCall.perform();
displayResults(text, json);
List<User> users = contactsCall.parse(json);
if (users != null)
{
displayAdditionalString(users.toString());
}
}
}
@Click(R.id.btn_perform_me_call)
void performMeCall(View clickedView)
{
LOG.info("About to call 'me' api method");
if (meCall != null)
{
String text = "Call 'Me'";
text = text + "\n";
JSONObject json = meCall.perform();
displayResults(text, json);
User user = meCall.performAndParse();
if (user != null)
{
displayAdditionalString(user.toString());
}
}
}
@Click(R.id.btn_clear_credentials)
void clearCredentials(View clickedView)
{
LOG.info("About to clear credentials");
syncPrefs.edit().oauth_token().put("").apply();
syncPrefs.edit().oauth_token_secret().put("").apply();
}
private void displayResults(String text, JSONObject json)
{
if (json != null)
{
text = text + json.toString();
text = text + "\n";
}
oauth_api_call_result.setText(text);
}
private void displayAdditionalString(String additionalText)
{
if (additionalText != null)
{
oauth_api_call_result.setText(oauth_api_call_result.getText() + "\n" + additionalText);
}
}
}
| Always jump to Accounts preferences
| xing-sync-app/src/main/java/com/gurkensalat/android/xingsync/HelloAndroidActivity.java | Always jump to Accounts preferences | <ide><path>ing-sync-app/src/main/java/com/gurkensalat/android/xingsync/HelloAndroidActivity.java
<ide> intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
<ide>
<ide> // To show only our own accounts
<del> intent.putExtra(Settings.EXTRA_AUTHORITIES, new String[] { getResources().getString(R.string.ACCOUNT_TYPE) });
<add> // intent.putExtra(Settings.EXTRA_AUTHORITIES, new String[] {
<add> // getResources().getString(R.string.ACCOUNT_TYPE) });
<ide>
<ide> startActivity(intent);
<ide> } |
|
JavaScript | bsd-3-clause | 2c4966b50d5a923607d6860f015c2a79822a353c | 0 | LocalData/localdata-dashboard,LocalData/localdata-dashboard | /*jslint nomen: true */
/*globals define: true */
define([
'jquery',
'lib/lodash',
'backbone',
'moment',
'settings',
'api'
],
function($, _, Backbone, moment, settings, api) {
'use strict';
var Responses = {};
Responses.Model = Backbone.Model.extend({
defaults: {
responses: {}
},
url: function() {
return settings.api.baseurl + '/surveys/' + this.get('survey') + '/responses/' + this.get('id');
},
toJSON: function() {
// This is the backbone implementation, which does clone attributes.
// We've added the date humanization.
var json = _.clone(this.attributes);
json.createdHumanized = moment(json.created, "YYYY-MM-DDThh:mm:ss.SSSZ").format("MMM Do YYYY - h:mma");
return json;
}
});
Responses.Collection = Backbone.Collection.extend({
model: Responses.Model,
filters: null,
unfilteredModels: null,
initialize: function(options) {
if (options !== undefined) {
console.log("Getting responses", options);
this.surveyId = options.surveyId;
this.objectId = options.objectId;
this.fetch();
}
},
url: function() {
var url = settings.api.baseurl + '/surveys/' + this.surveyId + '/responses';
if (this.objectId) {
return url + '?objectId=' + this.objectId;
}
return url;
},
parse: function(response) {
return response.responses;
},
/**
* Check regularly for new results
*/
update: function() {
this.updating = true;
this.fetchChunks(this.models.length);
this.lastUpdate = new Date();
this.trigger('updated', this.lastUpdate);
},
/**
* Returns a list of strings of all questions that have been recorded
* so far.
* @return {Array} Array of alphabetically sorted response keys.
*/
getResponseKeys: function() {
this.responseKeys = [];
// Look at every submitted response
_.each(this.models, function(response) {
var responseJSON = response.toJSON();
// Some responses don't have a responses key (legacy)
if (_.has(responseJSON, 'responses')) {
this.responseKeys = _.union(this.responseKeys, _.keys(responseJSON.responses));
}
}, this);
return this.responseKeys.sort();
},
/**
* Gets
* @param {String} question The key of the question
* @return {Array} A list of answers as strings
*/
getUniqueAnswersForQuestion: function(question) {
var answers = _.map(this.models, function(response){
// Make sure the model has data (some don't)
if(_.has(response.attributes, 'responses')) {
// Check if it has a response for the given question
if (_.has(response.attributes.responses, question)) {
// Return that answer
return response.attributes.responses[question];
}
}
});
// Count each answer
var counts = _.countBy(answers);
// Make sure we have unique answers
var uniqueAnswers = _.unique(answers).sort();
// Build the response object
var breakdown = {};
_.each(uniqueAnswers, function(answer, index) {
var details = {
name: answer,
count: counts[answer],
color: settings.colorRange[index + 1]
};
// Handle empty answers
if(!answer) {
details.name = 'no answer';
details.color = settings.colorRange[0];
}
// Add the details for this answer to the breakdown
breakdown[answer] = details;
});
// Replace `undefined` answers with a string for nice rendering
//var idxOfUndefinedToReplace = _.indexOf(uniqueAnswers, undefined);
//uniqueAnswers[idxOfUndefinedToReplace] = '[empty]';
return breakdown;
},
// Filter the items in the collection
setFilter: function (question, answer) {
console.log("Filtering the responses", question, answer);
// Make a shallow clone of the unfiltered models array.
//
// TODO: if someone calls reset or update, we need to toss out the
// unfilteredModels array. That should happen before anyone else gets the
// reset, add, etc. events.
if (this.unfilteredModels === null) {
this.unfilteredModels = _.clone(this.models);
}
// Record the filter for future use
this.filters = {
question: question,
answer: answer
};
if(answer === 'no response') {
answer = undefined;
}
// Select the correct responses
this.reset(this.filter(function (item) {
var resps = item.get('responses');
return resps !== undefined && (resps[question] === answer);
}));
},
clearFilter: function (options) {
console.log("Clearing filter");
this.filters = null;
if (this.unfilteredModels !== null) {
this.reset(this.unfilteredModels, options);
}
}
});
return Responses;
}); // End Responses module
| src/js/models/responses.js | /*jslint nomen: true */
/*globals define: true */
define([
'jquery',
'lib/lodash',
'backbone',
'moment',
'settings',
'api'
],
function($, _, Backbone, moment, settings, api) {
'use strict';
var Responses = {};
Responses.Model = Backbone.Model.extend({
defaults: {
responses: {}
},
url: function() {
return settings.api.baseurl + '/surveys/' + this.get('survey') + '/responses/' + this.get('id');
},
toJSON: function() {
// This is the backbone implementation, which does clone attributes.
// We've added the date humanization.
var json = _.clone(this.attributes);
json.createdHumanized = moment(json.created, "YYYY-MM-DDThh:mm:ss.SSSZ").format("MMM Do h:mma");
return json;
}
});
Responses.Collection = Backbone.Collection.extend({
model: Responses.Model,
filters: null,
unfilteredModels: null,
initialize: function(options) {
if (options !== undefined) {
console.log("Getting responses", options);
this.surveyId = options.surveyId;
this.objectId = options.objectId;
this.fetch();
}
},
url: function() {
var url = settings.api.baseurl + '/surveys/' + this.surveyId + '/responses';
if (this.objectId) {
return url + '?objectId=' + this.objectId;
}
return url;
},
parse: function(response) {
return response.responses;
},
/**
* Check regularly for new results
*/
update: function() {
this.updating = true;
this.fetchChunks(this.models.length);
this.lastUpdate = new Date();
this.trigger('updated', this.lastUpdate);
},
/**
* Returns a list of strings of all questions that have been recorded
* so far.
* @return {Array} Array of alphabetically sorted response keys.
*/
getResponseKeys: function() {
this.responseKeys = [];
// Look at every submitted response
_.each(this.models, function(response) {
var responseJSON = response.toJSON();
// Some responses don't have a responses key (legacy)
if (_.has(responseJSON, 'responses')) {
this.responseKeys = _.union(this.responseKeys, _.keys(responseJSON.responses));
}
}, this);
return this.responseKeys.sort();
},
/**
* Gets
* @param {String} question The key of the question
* @return {Array} A list of answers as strings
*/
getUniqueAnswersForQuestion: function(question) {
var answers = _.map(this.models, function(response){
// Make sure the model has data (some don't)
if(_.has(response.attributes, 'responses')) {
// Check if it has a response for the given question
if (_.has(response.attributes.responses, question)) {
// Return that answer
return response.attributes.responses[question];
}
}
});
// Count each answer
var counts = _.countBy(answers);
// Make sure we have unique answers
var uniqueAnswers = _.unique(answers).sort();
// Build the response object
var breakdown = {};
_.each(uniqueAnswers, function(answer, index) {
var details = {
name: answer,
count: counts[answer],
color: settings.colorRange[index + 1]
};
// Handle empty answers
if(!answer) {
details.name = 'no answer';
details.color = settings.colorRange[0];
}
// Add the details for this answer to the breakdown
breakdown[answer] = details;
});
// Replace `undefined` answers with a string for nice rendering
//var idxOfUndefinedToReplace = _.indexOf(uniqueAnswers, undefined);
//uniqueAnswers[idxOfUndefinedToReplace] = '[empty]';
return breakdown;
},
// Filter the items in the collection
setFilter: function (question, answer) {
console.log("Filtering the responses", question, answer);
// Make a shallow clone of the unfiltered models array.
//
// TODO: if someone calls reset or update, we need to toss out the
// unfilteredModels array. That should happen before anyone else gets the
// reset, add, etc. events.
if (this.unfilteredModels === null) {
this.unfilteredModels = _.clone(this.models);
}
// Record the filter for future use
this.filters = {
question: question,
answer: answer
};
if(answer === 'no response') {
answer = undefined;
}
// Select the correct responses
this.reset(this.filter(function (item) {
var resps = item.get('responses');
return resps !== undefined && (resps[question] === answer);
}));
},
clearFilter: function (options) {
console.log("Clearing filter");
this.filters = null;
if (this.unfilteredModels !== null) {
this.reset(this.unfilteredModels, options);
}
}
});
return Responses;
}); // End Responses module
| Add date to year display
| src/js/models/responses.js | Add date to year display | <ide><path>rc/js/models/responses.js
<ide> // This is the backbone implementation, which does clone attributes.
<ide> // We've added the date humanization.
<ide> var json = _.clone(this.attributes);
<del> json.createdHumanized = moment(json.created, "YYYY-MM-DDThh:mm:ss.SSSZ").format("MMM Do h:mma");
<add> json.createdHumanized = moment(json.created, "YYYY-MM-DDThh:mm:ss.SSSZ").format("MMM Do YYYY - h:mma");
<ide> return json;
<ide> }
<ide> }); |
|
Java | bsd-2-clause | 053e3a42389f40ac8780cdff73b23720ad6d0dc0 | 0 | chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio | /*
* Copyright (c) 2003-2005 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 com.jme.renderer.lwjgl;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.Arrays;
import java.util.logging.Level;
import javax.imageio.ImageIO;
import org.lwjgl.opengl.ARBVertexBufferObject;
import org.lwjgl.opengl.ContextCapabilities;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.EXTCompiledVertexArray;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GLContext;
import org.lwjgl.opengl.glu.GLU;
import com.jme.curve.Curve;
import com.jme.math.FastMath;
import com.jme.math.Quaternion;
import com.jme.math.Vector3f;
import com.jme.renderer.Camera;
import com.jme.renderer.ColorRGBA;
import com.jme.renderer.RenderQueue;
import com.jme.renderer.Renderer;
import com.jme.scene.CompositeMesh;
import com.jme.scene.Geometry;
import com.jme.scene.Line;
import com.jme.scene.Point;
import com.jme.scene.Spatial;
import com.jme.scene.Text;
import com.jme.scene.TriMesh;
import com.jme.scene.VBOInfo;
import com.jme.scene.state.AlphaState;
import com.jme.scene.state.AttributeState;
import com.jme.scene.state.ColorMaskState;
import com.jme.scene.state.CullState;
import com.jme.scene.state.DitherState;
import com.jme.scene.state.FogState;
import com.jme.scene.state.FragmentProgramState;
import com.jme.scene.state.GLSLShaderObjectsState;
import com.jme.scene.state.LightState;
import com.jme.scene.state.MaterialState;
import com.jme.scene.state.RenderState;
import com.jme.scene.state.ShadeState;
import com.jme.scene.state.StencilState;
import com.jme.scene.state.TextureState;
import com.jme.scene.state.VertexProgramState;
import com.jme.scene.state.WireframeState;
import com.jme.scene.state.ZBufferState;
import com.jme.scene.state.lwjgl.LWJGLAlphaState;
import com.jme.scene.state.lwjgl.LWJGLAttributeState;
import com.jme.scene.state.lwjgl.LWJGLColorMaskState;
import com.jme.scene.state.lwjgl.LWJGLCullState;
import com.jme.scene.state.lwjgl.LWJGLDitherState;
import com.jme.scene.state.lwjgl.LWJGLFogState;
import com.jme.scene.state.lwjgl.LWJGLFragmentProgramState;
import com.jme.scene.state.lwjgl.LWJGLLightState;
import com.jme.scene.state.lwjgl.LWJGLMaterialState;
import com.jme.scene.state.lwjgl.LWJGLShadeState;
import com.jme.scene.state.lwjgl.LWJGLShaderObjectsState;
import com.jme.scene.state.lwjgl.LWJGLStencilState;
import com.jme.scene.state.lwjgl.LWJGLTextureState;
import com.jme.scene.state.lwjgl.LWJGLVertexProgramState;
import com.jme.scene.state.lwjgl.LWJGLWireframeState;
import com.jme.scene.state.lwjgl.LWJGLZBufferState;
import com.jme.system.JmeException;
import com.jme.util.LoggingSystem;
/**
* <code>LWJGLRenderer</code> provides an implementation of the
* <code>Renderer</code> interface using the LWJGL API.
*
* @see com.jme.renderer.Renderer
* @author Mark Powell
* @author Joshua Slack - Optimizations and Headless rendering
* @author Tijl Houtbeckers - Small optimizations
* @version $Id: LWJGLRenderer.java,v 1.93 2005-12-20 00:35:07 renanse Exp $
*/
public class LWJGLRenderer extends Renderer {
private Vector3f vRot = new Vector3f();
private LWJGLFont font;
private boolean usingVBO = false;
private boolean ignoreVBO = false;
private boolean inOrthoMode;
private Vector3f tempVa = new Vector3f();
private DisplayMode mode = Display.getDisplayMode();
private FloatBuffer prevVerts;
private FloatBuffer prevNorms;
private FloatBuffer prevColor;
private FloatBuffer[] prevTex;
private ContextCapabilities capabilities;
private int prevTextureNumber = 0;
/**
* Constructor instantiates a new <code>LWJGLRenderer</code> object. The
* size of the rendering window is passed during construction.
*
* @param width
* the width of the rendering context.
* @param height
* the height of the rendering context.
*/
public LWJGLRenderer(int width, int height) {
if (width <= 0 || height <= 0) {
LoggingSystem.getLogger().log(Level.WARNING,
"Invalid width " + "and/or height values.");
throw new JmeException("Invalid width and/or height values.");
}
this.width = width;
this.height = height;
LoggingSystem.getLogger().log(Level.INFO,
"LWJGLRenderer created. W: " + width + "H: " + height);
capabilities = GLContext.getCapabilities();
queue = new RenderQueue(this);
if (TextureState.getNumberOfUnits() == -1) createTextureState(); // force units population
prevTex = new FloatBuffer[TextureState.getNumberOfUnits()];
}
/**
* Reinitialize the renderer with the given width/height. Also calls resize
* on the attached camera if present.
*
* @param width
* int
* @param height
* int
*/
public void reinit(int width, int height) {
if (width <= 0 || height <= 0) {
LoggingSystem.getLogger().log(Level.WARNING,
"Invalid width " + "and/or height values.");
throw new JmeException("Invalid width and/or height values.");
}
this.width = width;
this.height = height;
if (camera != null)
camera.resize(width, height);
mode = Display.getDisplayMode();
capabilities = GLContext.getCapabilities();
}
/**
* <code>setCamera</code> sets the camera this renderer is using. It
* asserts that the camera is of type <code>LWJGLCamera</code>.
*
* @see com.jme.renderer.Renderer#setCamera(com.jme.renderer.Camera)
*/
public void setCamera(Camera camera) {
if (camera instanceof LWJGLCamera) {
this.camera = (LWJGLCamera) camera;
}
}
/**
* <code>createCamera</code> returns a default camera for use with the
* LWJGL renderer.
*
* @param width
* the width of the frame.
* @param height
* the height of the frame.
* @return a default LWJGL camera.
*/
public Camera createCamera(int width, int height) {
return new LWJGLCamera(width, height, this);
}
/**
* <code>createAlphaState</code> returns a new LWJGLAlphaState object as a
* regular AlphaState.
*
* @return an AlphaState object.
*/
public AlphaState createAlphaState() {
return new LWJGLAlphaState();
}
/**
* <code>createAttributeState</code> returns a new LWJGLAttributeState
* object as a regular AttributeState.
*
* @return an AttributeState object.
*/
public AttributeState createAttributeState() {
return new LWJGLAttributeState();
}
/**
* <code>createCullState</code> returns a new LWJGLCullState object as a
* regular CullState.
*
* @return a CullState object.
* @see com.jme.renderer.Renderer#createCullState()
*/
public CullState createCullState() {
return new LWJGLCullState();
}
/**
* <code>createDitherState</code> returns a new LWJGLDitherState object as
* a regular DitherState.
*
* @return an DitherState object.
*/
public DitherState createDitherState() {
return new LWJGLDitherState();
}
/**
* <code>createFogState</code> returns a new LWJGLFogState object as a
* regular FogState.
*
* @return an FogState object.
*/
public FogState createFogState() {
return new LWJGLFogState();
}
/**
* <code>createLightState</code> returns a new LWJGLLightState object as a
* regular LightState.
*
* @return an LightState object.
*/
public LightState createLightState() {
return new LWJGLLightState();
}
/**
* <code>createMaterialState</code> returns a new LWJGLMaterialState
* object as a regular MaterialState.
*
* @return an MaterialState object.
*/
public MaterialState createMaterialState() {
return new LWJGLMaterialState();
}
/**
* <code>createShadeState</code> returns a new LWJGLShadeState object as a
* regular ShadeState.
*
* @return an ShadeState object.
*/
public ShadeState createShadeState() {
return new LWJGLShadeState();
}
/**
* <code>createTextureState</code> returns a new LWJGLTextureState object
* as a regular TextureState.
*
* @return an TextureState object.
*/
public TextureState createTextureState() {
return new LWJGLTextureState();
}
/**
* <code>createWireframeState</code> returns a new LWJGLWireframeState
* object as a regular WireframeState.
*
* @return an WireframeState object.
*/
public WireframeState createWireframeState() {
return new LWJGLWireframeState();
}
/**
* <code>createZBufferState</code> returns a new LWJGLZBufferState object
* as a regular ZBufferState.
*
* @return a ZBufferState object.
*/
public ZBufferState createZBufferState() {
return new LWJGLZBufferState();
}
/**
* <code>createVertexProgramState</code> returns a new
* LWJGLVertexProgramState object as a regular VertexProgramState.
*
* @return a LWJGLVertexProgramState object.
*/
public VertexProgramState createVertexProgramState() {
return new LWJGLVertexProgramState();
}
/**
* <code>createFragmentProgramState</code> returns a new
* LWJGLFragmentProgramState object as a regular FragmentProgramState.
*
* @return a LWJGLFragmentProgramState object.
*/
public FragmentProgramState createFragmentProgramState() {
return new LWJGLFragmentProgramState();
}
/**
* <code>createShaderObjectsState</code> returns a new
* LWJGLShaderObjectsState object as a regular ShaderObjectsState.
*
* @return an ShaderObjectsState object.
*/
public GLSLShaderObjectsState createGLSLShaderObjectsState() {
return new LWJGLShaderObjectsState();
}
/**
* <code>createStencilState</code> returns a new LWJGLStencilState object
* as a regular StencilState.
*
* @return a StencilState object.
*/
public StencilState createStencilState() {
return new LWJGLStencilState();
}
/**
* <code>createColorMaskState</code> returns a new LWJGLColorMaskState object
* as a regular ColorMaskState.
*
* @return a ColorMaskState object.
*/
public ColorMaskState createColorMaskState() {
return new LWJGLColorMaskState();
}
/**
* <code>setBackgroundColor</code> sets the OpenGL clear color to the
* color specified.
*
* @see com.jme.renderer.Renderer#setBackgroundColor(com.jme.renderer.ColorRGBA)
* @param c
* the color to set the background color to.
*/
public void setBackgroundColor(ColorRGBA c) {
// if color is null set background to white.
if (c == null) {
backgroundColor.a = 1.0f;
backgroundColor.b = 1.0f;
backgroundColor.g = 1.0f;
backgroundColor.r = 1.0f;
} else {
backgroundColor = c;
}
GL11.glClearColor(backgroundColor.r, backgroundColor.g,
backgroundColor.b, backgroundColor.a);
}
/**
* <code>clearZBuffer</code> clears the OpenGL depth buffer.
*
* @see com.jme.renderer.Renderer#clearZBuffer()
*/
public void clearZBuffer() {
Spatial.clearCurrentState( RenderState.RS_ZBUFFER );
if (Spatial.defaultStateList[RenderState.RS_ZBUFFER] != null)
Spatial.defaultStateList[RenderState.RS_ZBUFFER].apply();
GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT);
}
/**
* <code>clearBackBuffer</code> clears the OpenGL color buffer.
*
* @see com.jme.renderer.Renderer#clearColorBuffer()
*/
public void clearColorBuffer() {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
}
/**
* <code>clearStencilBuffer</code>
*
* @see com.jme.renderer.Renderer#clearStencilBuffer()
*/
public void clearStencilBuffer()
{
// Clear the stencil buffer
GL11.glClearStencil(0);
GL11.glStencilMask(~0);
GL11.glDisable(GL11.GL_DITHER);
GL11.glEnable(GL11.GL_SCISSOR_TEST);
GL11.glScissor(0, 0, getWidth(), getHeight());
GL11.glClear(GL11.GL_STENCIL_BUFFER_BIT);
GL11.glDisable(GL11.GL_SCISSOR_TEST);
}
/**
* <code>clearBuffers</code> clears both the color and the depth buffer.
*
* @see com.jme.renderer.Renderer#clearBuffers()
*/
public void clearBuffers() {
clearColorBuffer();
clearZBuffer();
}
/**
* <code>clearBuffers</code> clears both the color and the depth buffer
* for only the part of the buffer defined by the renderer width/height.
*
* @see com.jme.renderer.Renderer#clearBuffers()
*/
public void clearStrictBuffers() {
GL11.glDisable(GL11.GL_DITHER);
GL11.glEnable(GL11.GL_SCISSOR_TEST);
GL11.glScissor(0, 0, width, height);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
GL11.glDisable(GL11.GL_SCISSOR_TEST);
GL11.glEnable(GL11.GL_DITHER);
}
/**
* <code>displayBackBuffer</code> renders any queued items then flips the
* rendered buffer (back) with the currently displayed buffer.
*
* @see com.jme.renderer.Renderer#displayBackBuffer()
*/
public void displayBackBuffer() {
renderQueue();
if (Spatial.getCurrentState(RenderState.RS_ZBUFFER) != null
&& !((ZBufferState) Spatial
.getCurrentState(RenderState.RS_ZBUFFER)).isWritable()) {
if (Spatial.defaultStateList[RenderState.RS_ZBUFFER] != null)
Spatial.defaultStateList[RenderState.RS_ZBUFFER].apply();
Spatial.clearCurrentState(RenderState.RS_ZBUFFER);
}
prevColor = prevNorms = prevVerts = null;
Arrays.fill(prevTex, null);
Spatial.clearCurrentStates();
GL11.glFlush();
if (!isHeadless())
Display.update();
}
/**
*
* <code>setOrtho</code> sets the display system to be in orthographic
* mode. If the system has already been set to orthographic mode a
* <code>JmeException</code> is thrown. The origin (0,0) is the bottom
* left of the screen.
*
*/
public void setOrtho() {
if (inOrthoMode) {
throw new JmeException("Already in Orthographic mode.");
}
// set up ortho mode
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPushMatrix();
GL11.glLoadIdentity();
GLU.gluOrtho2D(0, mode.getWidth(), 0, mode.getHeight());
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glLoadIdentity();
inOrthoMode = true;
}
public void setOrthoCenter() {
if (inOrthoMode) {
throw new JmeException("Already in Orthographic mode.");
}
// set up ortho mode
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPushMatrix();
GL11.glLoadIdentity();
GLU.gluOrtho2D(-mode.getWidth() / 2, mode.getWidth() / 2, -mode
.getHeight() / 2, mode.getHeight() / 2);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glLoadIdentity();
inOrthoMode = true;
}
/**
*
* <code>setOrthoCenter</code> sets the display system to be in
* orthographic mode. If the system has already been set to orthographic
* mode a <code>JmeException</code> is thrown. The origin (0,0) is the
* center of the screen.
*
*/
public void unsetOrtho() {
if (!inOrthoMode) {
throw new JmeException("Not in Orthographic mode.");
}
// remove ortho mode, and go back to original
// state
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPopMatrix();
postdrawGeometry(null);
inOrthoMode = false;
}
/**
* <code>takeScreenShot</code> saves the current buffer to a file. The
* file name is provided, and .png will be appended. True is returned if the
* capture was successful, false otherwise.
*
* @param filename
* the name of the file to save.
* @return true if successful, false otherwise.
*/
public boolean takeScreenShot(String filename) {
if (null == filename) {
throw new JmeException("Screenshot filename cannot be null");
}
LoggingSystem.getLogger().log(Level.INFO,
"Taking screenshot: " + filename + ".png");
// Create a pointer to the image info and create a buffered image to
// hold it.
IntBuffer buff = ByteBuffer.allocateDirect(width * height * 4).order(
ByteOrder.LITTLE_ENDIAN).asIntBuffer();
grabScreenContents(buff, 0, 0, width, height);
BufferedImage img = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// Grab each pixel information and set it to the BufferedImage info.
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
img.setRGB(x, y, buff.get((height - y - 1) * width + x));
}
}
// write out the screenshot image to a file.
try {
File out = new File(filename + ".png");
return ImageIO.write(img, "png", out);
} catch (IOException e) {
LoggingSystem.getLogger().log(Level.WARNING,
"Could not create file: " + filename + ".png");
return false;
}
}
/**
* <code>grabScreenContents</code> reads a block of pixels from the
* current framebuffer.
*
* @param buff
* a buffer to store contents in.
* @param x -
* x starting point of block
* @param y -
* y starting point of block
* @param w -
* width of block
* @param h -
* height of block
*/
public void grabScreenContents(IntBuffer buff, int x, int y, int w, int h) {
GL11.glReadPixels(x, y, w, h, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE,
buff);
}
/**
* <code>draw</code> draws a point object where a point contains a
* collection of vertices, normals, colors and texture coordinates.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.Point)
* @param p
* the point object to render.
*/
public void draw(Point p) {
predrawGeometry(p);
IntBuffer indices = p.getIndexBuffer();
indices.rewind();
int verts = p.getVertQuantity();
if (statisticsOn) {
numberOfVerts += verts;
}
GL11.glPointSize(p.getPointSize());
if (p.isAntialiased()) {
GL11.glEnable(GL11.GL_POINT_SMOOTH);
GL11.glHint(GL11.GL_POINT_SMOOTH_HINT, GL11.GL_NICEST);
}
GL11.glDrawElements(GL11.GL_POINTS, indices);
if (p.isAntialiased()) {
GL11.glDisable(GL11.GL_POINT_SMOOTH);
}
postdrawGeometry(p);
}
/**
* <code>draw</code> draws a line object where a line contains a
* collection of vertices, normals, colors and texture coordinates.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.Line)
* @param l
* the line object to render.
*/
public void draw(Line l) {
predrawGeometry(l);
IntBuffer indices = l.getIndexBuffer();
indices.rewind();
int verts = l.getVertQuantity();
if (statisticsOn) {
numberOfVerts += verts;
}
GL11.glLineWidth(l.getLineWidth());
if (l.getStippleFactor() != (short)0xFFFF) {
GL11.glEnable(GL11.GL_LINE_STIPPLE);
GL11.glLineStipple(l.getStippleFactor(), l.getStipplePattern());
}
if (l.isAntialiased()) {
GL11.glEnable(GL11.GL_LINE_SMOOTH);
GL11.glHint(GL11.GL_LINE_SMOOTH_HINT, GL11.GL_NICEST);
}
switch (l.getMode()) {
case Line.SEGMENTS:
GL11.glDrawElements(GL11.GL_LINES, indices);
break;
case Line.CONNECTED:
GL11.glDrawElements(GL11.GL_LINE_STRIP, indices);
break;
case Line.LOOP:
GL11.glDrawElements(GL11.GL_LINE_LOOP, indices);
break;
}
if (l.getStippleFactor() != (short)0xFFFF) {
GL11.glDisable(GL11.GL_LINE_STIPPLE);
}
if (l.isAntialiased()) {
GL11.glDisable(GL11.GL_LINE_SMOOTH);
}
postdrawGeometry(l);
}
/**
* <code>draw</code> renders a curve object.
*
* @param c
* the curve object to render.
*/
public void draw(Curve c) {
// set world matrix
Quaternion rotation = c.getWorldRotation();
Vector3f translation = c.getWorldTranslation();
Vector3f scale = c.getWorldScale();
float rot = rotation.toAngleAxis(vRot) * FastMath.RAD_TO_DEG;
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glTranslatef(translation.x, translation.y, translation.z);
GL11.glRotatef(rot, vRot.x, vRot.y, vRot.z);
GL11.glScalef(scale.x, scale.y, scale.z);
// render the object
GL11.glBegin(GL11.GL_LINE_STRIP);
FloatBuffer color = c.getColorBuffer();
if (color != null) color.rewind();
float colorInterval = 0;
float colorModifier = 0;
int colorCounter = 0;
if (null != color) {
GL11.glColor4f(color.get(), color.get(), color.get(), color.get());
colorInterval = 4f / color.capacity() ;
colorModifier = colorInterval;
colorCounter = 0;
color.rewind();
}
Vector3f point;
float limit = (1 + (1.0f / c.getSteps()));
for (float t = 0; t <= limit; t += 1.0f / c.getSteps()) {
if (t >= colorInterval && color != null) {
colorInterval += colorModifier;
GL11.glColor4f(color.get(), color.get(), color.get(), color.get());
colorCounter++;
}
point = c.getPoint(t, tempVa);
GL11.glVertex3f(point.x, point.y, point.z);
}
if (statisticsOn) {
numberOfVerts += limit;
}
GL11.glEnd();
postdrawGeometry(c);
}
/**
* <code>draw</code> renders a <code>TriMesh</code> object including
* it's normals, colors, textures and vertices.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.TriMesh)
* @param t
* the mesh to render.
*/
public void draw(TriMesh t) {
predrawGeometry(t);
IntBuffer indices = t.getIndexBuffer();
indices.rewind();
if (statisticsOn) {
int verts = t.getVertQuantity();
numberOfTris += t.getTriangleQuantity();
numberOfVerts += verts;
}
indices.limit(t.getTriangleQuantity()*3); // make sure only the necessary indices are sent through on old cards.
if (capabilities.GL_EXT_compiled_vertex_array) EXTCompiledVertexArray.glLockArraysEXT(0, t.getVertQuantity());
GL11.glDrawElements(GL11.GL_TRIANGLES, indices);
if (capabilities.GL_EXT_compiled_vertex_array) EXTCompiledVertexArray.glUnlockArraysEXT();
indices.clear();
postdrawGeometry(t);
}
/**
* <code>draw</code> renders a <code>CompositeMesh</code> object
* including it's normals, colors, textures and vertices.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.CompositeMesh)
* @param t
* the mesh to render.
*/
public void draw(CompositeMesh t) {
predrawGeometry(t);
IntBuffer indices = t.getIndexBuffer().duplicate(); // returns secondary pointer to same data
CompositeMesh.IndexRange[] ranges = t.getIndexRanges();
if (statisticsOn) {
int verts = t.getVertQuantity();
numberOfVerts += verts;
numberOfTris += t.getTriangleQuantity();
}
indices.position(0);
for (int i = 0; i < ranges.length; i++) {
int mode;
switch (ranges[i].getKind()) {
case CompositeMesh.IndexRange.TRIANGLES:
mode = GL11.GL_TRIANGLES;
break;
case CompositeMesh.IndexRange.TRIANGLE_STRIP:
mode = GL11.GL_TRIANGLE_STRIP;
break;
case CompositeMesh.IndexRange.TRIANGLE_FAN:
mode = GL11.GL_TRIANGLE_FAN;
break;
case CompositeMesh.IndexRange.QUADS:
mode = GL11.GL_QUADS;
break;
case CompositeMesh.IndexRange.QUAD_STRIP:
mode = GL11.GL_QUAD_STRIP;
break;
default:
throw new JmeException("Unknown index range type "
+ ranges[i].getKind());
}
indices.limit(indices.position() + ranges[i].getCount());
GL11.glDrawElements(mode, indices);
indices.position(indices.limit());
}
postdrawGeometry(t);
}
protected IntBuffer buf = org.lwjgl.BufferUtils.createIntBuffer(16);
/**
* <code>prepVBO</code> binds the geometry data to a vbo buffer and
* sends it to the GPU if necessary. The vbo id is stored in the
* geometry's VBOInfo class.
* @param g the geometry to initialize VBO for.
*/
public void prepVBO(Geometry g) {
if (!capabilities.GL_ARB_vertex_buffer_object)
return;
VBOInfo vbo = g.getVBOInfo();
if (vbo.isVBOVertexEnabled() && vbo.getVBOVertexID() <= 0) {
if (g.getVertexBuffer() != null) {
g.getVertexBuffer().rewind();
buf.rewind();
ARBVertexBufferObject.glGenBuffersARB(buf);
vbo.setVBOVertexID(buf.get(0));
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, vbo.getVBOVertexID());
ARBVertexBufferObject.glBufferDataARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, g.getVertexBuffer(),
ARBVertexBufferObject.GL_STATIC_DRAW_ARB);
}
}
if (vbo.isVBONormalEnabled() && vbo.getVBONormalID() <= 0) {
if (g.getNormalBuffer() != null) {
g.getNormalBuffer().rewind();
buf.rewind();
ARBVertexBufferObject.glGenBuffersARB(buf);
vbo.setVBONormalID(buf.get(0));
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, vbo.getVBONormalID());
ARBVertexBufferObject.glBufferDataARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, g.getNormalBuffer(),
ARBVertexBufferObject.GL_STATIC_DRAW_ARB);
}
}
if (vbo.isVBOColorEnabled() && vbo.getVBOColorID() <= 0) {
if (g.getColorBuffer() != null) {
g.getColorBuffer().rewind();
buf.rewind();
ARBVertexBufferObject.glGenBuffersARB(buf);
vbo.setVBOColorID(buf.get(0));
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, vbo.getVBOColorID());
ARBVertexBufferObject.glBufferDataARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, g.getColorBuffer(),
ARBVertexBufferObject.GL_STATIC_DRAW_ARB);
}
}
if (vbo.isVBOTextureEnabled()) {
for (int i = 0; i < g.getNumberOfUnits(); i++) {
if (vbo.getVBOTextureID(i) <= 0
&& g.getTextureBuffer(i) != null) {
if (g.getTextureBuffer(i) != null) {
g.getTextureBuffer(i).rewind();
buf.rewind();
ARBVertexBufferObject.glGenBuffersARB(buf);
vbo.setVBOTextureID(i, buf.get(0));
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, vbo.getVBOTextureID(i));
ARBVertexBufferObject.glBufferDataARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, g.getTextureBuffer(i),
ARBVertexBufferObject.GL_STATIC_DRAW_ARB);
}
}
}
}
buf.clear();
}
/**
* <code>draw</code> renders a scene by calling the nodes
* <code>onDraw</code> method.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.Spatial)
*/
public void draw(Spatial s) {
if (s != null) {
s.onDraw(this);
}
}
/**
* <code>draw</code> renders a text object using a predefined font.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.Text)
*/
public void draw(Text t) {
if (font == null) {
font = new LWJGLFont();
}
font.setColor(t.getTextColor());
font.print((int) t.getWorldTranslation().x, (int) t
.getWorldTranslation().y, t.getWorldScale(), t.getText(), 0);
}
/**
* checkAndAdd is used to process the spatial for the render queue. It's
* queue mode is checked, and it is added to the proper queue. If the
* queue mode is QUEUE_SKIP, false is returned.
*
* @return true if the spatial was added to a queue, false otherwise.
*/
public boolean checkAndAdd(Spatial s) {
int rqMode = s.getRenderQueueMode();
if (rqMode != Renderer.QUEUE_SKIP) {
getQueue().addToQueue(s, rqMode);
return true;
}
return false;
}
/**
* Return true if the system running this supports VBO
*
* @return boolean true if VBO supported
*/
public boolean supportsVBO() {
return capabilities.OpenGL15;
}
/**
* re-initializes the GL context for rendering of another piece of geometry.
*/
private void postdrawGeometry(Geometry t) {
VBOInfo vbo = t != null ? t.getVBOInfo() : null;
if (vbo != null && capabilities.GL_ARB_vertex_buffer_object) {
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, 0);
}
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPopMatrix();
}
/**
* <code>flush</code> tells opengl to finish all currently waiting
* commands in the buffer.
*/
public void flush() {
GL11.glFlush();
}
/**
* prepares the GL Context for rendering this geometry. This involves
* setting the rotation, translation, and scale, initializing VBO, and
* obtaining the buffer data.
* @param t the geometry to process.
*/
private void predrawGeometry(Geometry t) {
// set world matrix
Quaternion rotation = t.getWorldRotation();
Vector3f translation = t.getWorldTranslation();
Vector3f scale = t.getWorldScale();
float rot = rotation.toAngleAxis(vRot) * FastMath.RAD_TO_DEG;
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glTranslatef(translation.x, translation.y, translation.z);
GL11.glRotatef(rot, vRot.x, vRot.y, vRot.z);
GL11.glScalef(scale.x, scale.y, scale.z);
if (!(scale.x == 1 && scale.y == 1 && scale.z == 1))
GL11.glEnable(GL11.GL_NORMALIZE); // since we are using
// glScalef, we should enable
// this to keep normals
// working.
VBOInfo vbo = t.getVBOInfo();
if (vbo != null && capabilities.GL_ARB_vertex_buffer_object) {
prepVBO(t);
ignoreVBO = false;
} else
ignoreVBO = true;
// render the object
int oldLimit = -1;
FloatBuffer verticies = t.getVertexBuffer();
if (verticies != null) {
oldLimit = verticies.limit();
verticies.limit(t.getVertQuantity()*3); // make sure only the necessary verts are sent through on old cards.
}
if ((!ignoreVBO && vbo.getVBOVertexID() > 0)) { // use VBO
usingVBO = true;
GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, vbo.getVBOVertexID());
GL11.glVertexPointer(3, GL11.GL_FLOAT, 0, 0);
} else if (verticies == null) {
GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
} else if (prevVerts != verticies) {
// textures have changed
GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
if (usingVBO)
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, 0);
verticies.rewind();
GL11.glVertexPointer(3, 0, verticies);
}
if (oldLimit != -1)
verticies.limit(oldLimit);
prevVerts = verticies;
FloatBuffer normals = t.getNormalBuffer();
oldLimit = -1;
if (normals != null) {
oldLimit = normals.limit();
normals.limit(t.getVertQuantity()*3); // make sure only the necessary normals are sent through on old cards.
}
if ((!ignoreVBO && vbo.getVBONormalID() > 0)) { // use VBO
usingVBO = true;
GL11.glEnableClientState(GL11.GL_NORMAL_ARRAY);
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, vbo.getVBONormalID());
GL11.glNormalPointer(GL11.GL_FLOAT, 0, 0);
} else if (normals == null) {
GL11.glDisableClientState(GL11.GL_NORMAL_ARRAY);
} else if (prevNorms != normals) {
// textures have changed
GL11.glEnableClientState(GL11.GL_NORMAL_ARRAY);
if (usingVBO)
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, 0);
normals.rewind();
GL11.glNormalPointer(0, normals);
}
if (oldLimit != -1)
normals.limit(oldLimit);
prevNorms = normals;
FloatBuffer colors = t.getColorBuffer();
oldLimit = -1;
if (colors != null) {
oldLimit = colors.limit();
colors.limit(t.getVertQuantity()*3); // make sure only the necessary colors are sent through on old cards.
}
if ((!ignoreVBO && vbo.getVBOColorID() > 0)) { // use VBO
usingVBO = true;
GL11.glEnableClientState(GL11.GL_COLOR_ARRAY);
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, vbo.getVBOColorID());
GL11.glColorPointer(4, GL11.GL_FLOAT, 0, 0);
} else if (colors == null) {
GL11.glDisableClientState(GL11.GL_COLOR_ARRAY);
ColorRGBA defCol = t.getDefaultColor();
if (defCol != null)
GL11.glColor4f(defCol.r, defCol.g, defCol.b, defCol.a);
} else if (prevColor != colors) {
// textures have changed
GL11.glEnableClientState(GL11.GL_COLOR_ARRAY);
if (usingVBO)
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, 0);
colors.rewind();
GL11.glColorPointer(4, 0, colors);
}
if (oldLimit != -1)
colors.limit(oldLimit);
prevColor = colors;
TextureState ts = (TextureState)Spatial.getCurrentState(RenderState.RS_TEXTURE);
int offset = 0;
if(ts != null) {
offset = ts.getTextureCoordinateOffset();
for(int i = 0; i < ts.getNumberOfSetTextures(); i++) {
FloatBuffer textures = t.getTextureBuffer(i + offset);
oldLimit = -1;
if (textures != null) {
oldLimit = textures.limit();
textures.limit(t.getVertQuantity()*2); // make sure only the necessary texture coords are sent through on old cards.
}
//todo: multitexture is in GL13 - according to forum post: topic=2000
if (capabilities.GL_ARB_multitexture && capabilities.OpenGL13) {
GL13.glClientActiveTexture(GL13.GL_TEXTURE0 + i);
}
if ((!ignoreVBO && vbo.getVBOTextureID(i) > 0)) { // use VBO
usingVBO = true;
GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, vbo.getVBOTextureID(i));
GL11.glTexCoordPointer(2, GL11.GL_FLOAT, 0, 0);
} else if (textures == null) {
GL11.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
} else if (prevTex[i] != textures) {
// textures have changed
GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
if (usingVBO)
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, 0);
textures.rewind();
GL11.glTexCoordPointer(2, 0, textures);
}
prevTex[i] = textures;
if (oldLimit != -1)
textures.limit(oldLimit);
}
if(ts.getNumberOfSetTextures() < prevTextureNumber) {
for(int i = ts.getNumberOfSetTextures(); i < prevTextureNumber; i++) {
GL13.glClientActiveTexture(GL13.GL_TEXTURE0 + i);
GL11.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
}
}
prevTextureNumber = ts.getNumberOfSetTextures();
}
}
} | src/com/jme/renderer/lwjgl/LWJGLRenderer.java | /*
* Copyright (c) 2003-2005 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 com.jme.renderer.lwjgl;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.Arrays;
import java.util.logging.Level;
import javax.imageio.ImageIO;
import org.lwjgl.opengl.ARBVertexBufferObject;
import org.lwjgl.opengl.ContextCapabilities;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GLContext;
import org.lwjgl.opengl.glu.GLU;
import com.jme.curve.Curve;
import com.jme.math.FastMath;
import com.jme.math.Quaternion;
import com.jme.math.Vector3f;
import com.jme.renderer.Camera;
import com.jme.renderer.ColorRGBA;
import com.jme.renderer.RenderQueue;
import com.jme.renderer.Renderer;
import com.jme.scene.CompositeMesh;
import com.jme.scene.Geometry;
import com.jme.scene.Line;
import com.jme.scene.Point;
import com.jme.scene.Spatial;
import com.jme.scene.Text;
import com.jme.scene.TriMesh;
import com.jme.scene.VBOInfo;
import com.jme.scene.state.AlphaState;
import com.jme.scene.state.AttributeState;
import com.jme.scene.state.ColorMaskState;
import com.jme.scene.state.CullState;
import com.jme.scene.state.DitherState;
import com.jme.scene.state.FogState;
import com.jme.scene.state.FragmentProgramState;
import com.jme.scene.state.GLSLShaderObjectsState;
import com.jme.scene.state.LightState;
import com.jme.scene.state.MaterialState;
import com.jme.scene.state.RenderState;
import com.jme.scene.state.ShadeState;
import com.jme.scene.state.StencilState;
import com.jme.scene.state.TextureState;
import com.jme.scene.state.VertexProgramState;
import com.jme.scene.state.WireframeState;
import com.jme.scene.state.ZBufferState;
import com.jme.scene.state.lwjgl.LWJGLAlphaState;
import com.jme.scene.state.lwjgl.LWJGLAttributeState;
import com.jme.scene.state.lwjgl.LWJGLColorMaskState;
import com.jme.scene.state.lwjgl.LWJGLCullState;
import com.jme.scene.state.lwjgl.LWJGLDitherState;
import com.jme.scene.state.lwjgl.LWJGLFogState;
import com.jme.scene.state.lwjgl.LWJGLFragmentProgramState;
import com.jme.scene.state.lwjgl.LWJGLLightState;
import com.jme.scene.state.lwjgl.LWJGLMaterialState;
import com.jme.scene.state.lwjgl.LWJGLShadeState;
import com.jme.scene.state.lwjgl.LWJGLShaderObjectsState;
import com.jme.scene.state.lwjgl.LWJGLStencilState;
import com.jme.scene.state.lwjgl.LWJGLTextureState;
import com.jme.scene.state.lwjgl.LWJGLVertexProgramState;
import com.jme.scene.state.lwjgl.LWJGLWireframeState;
import com.jme.scene.state.lwjgl.LWJGLZBufferState;
import com.jme.system.JmeException;
import com.jme.util.LoggingSystem;
/**
* <code>LWJGLRenderer</code> provides an implementation of the
* <code>Renderer</code> interface using the LWJGL API.
*
* @see com.jme.renderer.Renderer
* @author Mark Powell
* @author Joshua Slack - Optimizations and Headless rendering
* @author Tijl Houtbeckers - Small optimizations
* @version $Id: LWJGLRenderer.java,v 1.92 2005-12-12 18:42:41 Mojomonkey Exp $
*/
public class LWJGLRenderer extends Renderer {
private Vector3f vRot = new Vector3f();
private LWJGLFont font;
private boolean usingVBO = false;
private boolean ignoreVBO = false;
private boolean inOrthoMode;
private Vector3f tempVa = new Vector3f();
private DisplayMode mode = Display.getDisplayMode();
private FloatBuffer prevVerts;
private FloatBuffer prevNorms;
private FloatBuffer prevColor;
private FloatBuffer[] prevTex;
private ContextCapabilities capabilities;
private int prevTextureNumber = 0;
/**
* Constructor instantiates a new <code>LWJGLRenderer</code> object. The
* size of the rendering window is passed during construction.
*
* @param width
* the width of the rendering context.
* @param height
* the height of the rendering context.
*/
public LWJGLRenderer(int width, int height) {
if (width <= 0 || height <= 0) {
LoggingSystem.getLogger().log(Level.WARNING,
"Invalid width " + "and/or height values.");
throw new JmeException("Invalid width and/or height values.");
}
this.width = width;
this.height = height;
LoggingSystem.getLogger().log(Level.INFO,
"LWJGLRenderer created. W: " + width + "H: " + height);
capabilities = GLContext.getCapabilities();
queue = new RenderQueue(this);
if (TextureState.getNumberOfUnits() == -1) createTextureState(); // force units population
prevTex = new FloatBuffer[TextureState.getNumberOfUnits()];
}
/**
* Reinitialize the renderer with the given width/height. Also calls resize
* on the attached camera if present.
*
* @param width
* int
* @param height
* int
*/
public void reinit(int width, int height) {
if (width <= 0 || height <= 0) {
LoggingSystem.getLogger().log(Level.WARNING,
"Invalid width " + "and/or height values.");
throw new JmeException("Invalid width and/or height values.");
}
this.width = width;
this.height = height;
if (camera != null)
camera.resize(width, height);
mode = Display.getDisplayMode();
capabilities = GLContext.getCapabilities();
}
/**
* <code>setCamera</code> sets the camera this renderer is using. It
* asserts that the camera is of type <code>LWJGLCamera</code>.
*
* @see com.jme.renderer.Renderer#setCamera(com.jme.renderer.Camera)
*/
public void setCamera(Camera camera) {
if (camera instanceof LWJGLCamera) {
this.camera = (LWJGLCamera) camera;
}
}
/**
* <code>createCamera</code> returns a default camera for use with the
* LWJGL renderer.
*
* @param width
* the width of the frame.
* @param height
* the height of the frame.
* @return a default LWJGL camera.
*/
public Camera createCamera(int width, int height) {
return new LWJGLCamera(width, height, this);
}
/**
* <code>createAlphaState</code> returns a new LWJGLAlphaState object as a
* regular AlphaState.
*
* @return an AlphaState object.
*/
public AlphaState createAlphaState() {
return new LWJGLAlphaState();
}
/**
* <code>createAttributeState</code> returns a new LWJGLAttributeState
* object as a regular AttributeState.
*
* @return an AttributeState object.
*/
public AttributeState createAttributeState() {
return new LWJGLAttributeState();
}
/**
* <code>createCullState</code> returns a new LWJGLCullState object as a
* regular CullState.
*
* @return a CullState object.
* @see com.jme.renderer.Renderer#createCullState()
*/
public CullState createCullState() {
return new LWJGLCullState();
}
/**
* <code>createDitherState</code> returns a new LWJGLDitherState object as
* a regular DitherState.
*
* @return an DitherState object.
*/
public DitherState createDitherState() {
return new LWJGLDitherState();
}
/**
* <code>createFogState</code> returns a new LWJGLFogState object as a
* regular FogState.
*
* @return an FogState object.
*/
public FogState createFogState() {
return new LWJGLFogState();
}
/**
* <code>createLightState</code> returns a new LWJGLLightState object as a
* regular LightState.
*
* @return an LightState object.
*/
public LightState createLightState() {
return new LWJGLLightState();
}
/**
* <code>createMaterialState</code> returns a new LWJGLMaterialState
* object as a regular MaterialState.
*
* @return an MaterialState object.
*/
public MaterialState createMaterialState() {
return new LWJGLMaterialState();
}
/**
* <code>createShadeState</code> returns a new LWJGLShadeState object as a
* regular ShadeState.
*
* @return an ShadeState object.
*/
public ShadeState createShadeState() {
return new LWJGLShadeState();
}
/**
* <code>createTextureState</code> returns a new LWJGLTextureState object
* as a regular TextureState.
*
* @return an TextureState object.
*/
public TextureState createTextureState() {
return new LWJGLTextureState();
}
/**
* <code>createWireframeState</code> returns a new LWJGLWireframeState
* object as a regular WireframeState.
*
* @return an WireframeState object.
*/
public WireframeState createWireframeState() {
return new LWJGLWireframeState();
}
/**
* <code>createZBufferState</code> returns a new LWJGLZBufferState object
* as a regular ZBufferState.
*
* @return a ZBufferState object.
*/
public ZBufferState createZBufferState() {
return new LWJGLZBufferState();
}
/**
* <code>createVertexProgramState</code> returns a new
* LWJGLVertexProgramState object as a regular VertexProgramState.
*
* @return a LWJGLVertexProgramState object.
*/
public VertexProgramState createVertexProgramState() {
return new LWJGLVertexProgramState();
}
/**
* <code>createFragmentProgramState</code> returns a new
* LWJGLFragmentProgramState object as a regular FragmentProgramState.
*
* @return a LWJGLFragmentProgramState object.
*/
public FragmentProgramState createFragmentProgramState() {
return new LWJGLFragmentProgramState();
}
/**
* <code>createShaderObjectsState</code> returns a new
* LWJGLShaderObjectsState object as a regular ShaderObjectsState.
*
* @return an ShaderObjectsState object.
*/
public GLSLShaderObjectsState createGLSLShaderObjectsState() {
return new LWJGLShaderObjectsState();
}
/**
* <code>createStencilState</code> returns a new LWJGLStencilState object
* as a regular StencilState.
*
* @return a StencilState object.
*/
public StencilState createStencilState() {
return new LWJGLStencilState();
}
/**
* <code>createColorMaskState</code> returns a new LWJGLColorMaskState object
* as a regular ColorMaskState.
*
* @return a ColorMaskState object.
*/
public ColorMaskState createColorMaskState() {
return new LWJGLColorMaskState();
}
/**
* <code>setBackgroundColor</code> sets the OpenGL clear color to the
* color specified.
*
* @see com.jme.renderer.Renderer#setBackgroundColor(com.jme.renderer.ColorRGBA)
* @param c
* the color to set the background color to.
*/
public void setBackgroundColor(ColorRGBA c) {
// if color is null set background to white.
if (c == null) {
backgroundColor.a = 1.0f;
backgroundColor.b = 1.0f;
backgroundColor.g = 1.0f;
backgroundColor.r = 1.0f;
} else {
backgroundColor = c;
}
GL11.glClearColor(backgroundColor.r, backgroundColor.g,
backgroundColor.b, backgroundColor.a);
}
/**
* <code>clearZBuffer</code> clears the OpenGL depth buffer.
*
* @see com.jme.renderer.Renderer#clearZBuffer()
*/
public void clearZBuffer() {
Spatial.clearCurrentState( RenderState.RS_ZBUFFER );
if (Spatial.defaultStateList[RenderState.RS_ZBUFFER] != null)
Spatial.defaultStateList[RenderState.RS_ZBUFFER].apply();
GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT);
}
/**
* <code>clearBackBuffer</code> clears the OpenGL color buffer.
*
* @see com.jme.renderer.Renderer#clearColorBuffer()
*/
public void clearColorBuffer() {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
}
/**
* <code>clearStencilBuffer</code>
*
* @see com.jme.renderer.Renderer#clearStencilBuffer()
*/
public void clearStencilBuffer()
{
// Clear the stencil buffer
GL11.glClearStencil(0);
GL11.glStencilMask(~0);
GL11.glDisable(GL11.GL_DITHER);
GL11.glEnable(GL11.GL_SCISSOR_TEST);
GL11.glScissor(0, 0, getWidth(), getHeight());
GL11.glClear(GL11.GL_STENCIL_BUFFER_BIT);
GL11.glDisable(GL11.GL_SCISSOR_TEST);
}
/**
* <code>clearBuffers</code> clears both the color and the depth buffer.
*
* @see com.jme.renderer.Renderer#clearBuffers()
*/
public void clearBuffers() {
clearColorBuffer();
clearZBuffer();
}
/**
* <code>clearBuffers</code> clears both the color and the depth buffer
* for only the part of the buffer defined by the renderer width/height.
*
* @see com.jme.renderer.Renderer#clearBuffers()
*/
public void clearStrictBuffers() {
GL11.glDisable(GL11.GL_DITHER);
GL11.glEnable(GL11.GL_SCISSOR_TEST);
GL11.glScissor(0, 0, width, height);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
GL11.glDisable(GL11.GL_SCISSOR_TEST);
GL11.glEnable(GL11.GL_DITHER);
}
/**
* <code>displayBackBuffer</code> renders any queued items then flips the
* rendered buffer (back) with the currently displayed buffer.
*
* @see com.jme.renderer.Renderer#displayBackBuffer()
*/
public void displayBackBuffer() {
renderQueue();
if (Spatial.getCurrentState(RenderState.RS_ZBUFFER) != null
&& !((ZBufferState) Spatial
.getCurrentState(RenderState.RS_ZBUFFER)).isWritable()) {
if (Spatial.defaultStateList[RenderState.RS_ZBUFFER] != null)
Spatial.defaultStateList[RenderState.RS_ZBUFFER].apply();
Spatial.clearCurrentState(RenderState.RS_ZBUFFER);
}
prevColor = prevNorms = prevVerts = null;
Arrays.fill(prevTex, null);
Spatial.clearCurrentStates();
GL11.glFlush();
if (!isHeadless())
Display.update();
}
/**
*
* <code>setOrtho</code> sets the display system to be in orthographic
* mode. If the system has already been set to orthographic mode a
* <code>JmeException</code> is thrown. The origin (0,0) is the bottom
* left of the screen.
*
*/
public void setOrtho() {
if (inOrthoMode) {
throw new JmeException("Already in Orthographic mode.");
}
// set up ortho mode
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPushMatrix();
GL11.glLoadIdentity();
GLU.gluOrtho2D(0, mode.getWidth(), 0, mode.getHeight());
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glLoadIdentity();
inOrthoMode = true;
}
public void setOrthoCenter() {
if (inOrthoMode) {
throw new JmeException("Already in Orthographic mode.");
}
// set up ortho mode
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPushMatrix();
GL11.glLoadIdentity();
GLU.gluOrtho2D(-mode.getWidth() / 2, mode.getWidth() / 2, -mode
.getHeight() / 2, mode.getHeight() / 2);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glLoadIdentity();
inOrthoMode = true;
}
/**
*
* <code>setOrthoCenter</code> sets the display system to be in
* orthographic mode. If the system has already been set to orthographic
* mode a <code>JmeException</code> is thrown. The origin (0,0) is the
* center of the screen.
*
*/
public void unsetOrtho() {
if (!inOrthoMode) {
throw new JmeException("Not in Orthographic mode.");
}
// remove ortho mode, and go back to original
// state
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPopMatrix();
postdrawGeometry(null);
inOrthoMode = false;
}
/**
* <code>takeScreenShot</code> saves the current buffer to a file. The
* file name is provided, and .png will be appended. True is returned if the
* capture was successful, false otherwise.
*
* @param filename
* the name of the file to save.
* @return true if successful, false otherwise.
*/
public boolean takeScreenShot(String filename) {
if (null == filename) {
throw new JmeException("Screenshot filename cannot be null");
}
LoggingSystem.getLogger().log(Level.INFO,
"Taking screenshot: " + filename + ".png");
// Create a pointer to the image info and create a buffered image to
// hold it.
IntBuffer buff = ByteBuffer.allocateDirect(width * height * 4).order(
ByteOrder.LITTLE_ENDIAN).asIntBuffer();
grabScreenContents(buff, 0, 0, width, height);
BufferedImage img = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// Grab each pixel information and set it to the BufferedImage info.
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
img.setRGB(x, y, buff.get((height - y - 1) * width + x));
}
}
// write out the screenshot image to a file.
try {
File out = new File(filename + ".png");
return ImageIO.write(img, "png", out);
} catch (IOException e) {
LoggingSystem.getLogger().log(Level.WARNING,
"Could not create file: " + filename + ".png");
return false;
}
}
/**
* <code>grabScreenContents</code> reads a block of pixels from the
* current framebuffer.
*
* @param buff
* a buffer to store contents in.
* @param x -
* x starting point of block
* @param y -
* y starting point of block
* @param w -
* width of block
* @param h -
* height of block
*/
public void grabScreenContents(IntBuffer buff, int x, int y, int w, int h) {
GL11.glReadPixels(x, y, w, h, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE,
buff);
}
/**
* <code>draw</code> draws a point object where a point contains a
* collection of vertices, normals, colors and texture coordinates.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.Point)
* @param p
* the point object to render.
*/
public void draw(Point p) {
predrawGeometry(p);
IntBuffer indices = p.getIndexBuffer();
indices.rewind();
int verts = p.getVertQuantity();
if (statisticsOn) {
numberOfVerts += verts;
}
GL11.glPointSize(p.getPointSize());
if (p.isAntialiased()) {
GL11.glEnable(GL11.GL_POINT_SMOOTH);
GL11.glHint(GL11.GL_POINT_SMOOTH_HINT, GL11.GL_NICEST);
}
GL11.glDrawElements(GL11.GL_POINTS, indices);
if (p.isAntialiased()) {
GL11.glDisable(GL11.GL_POINT_SMOOTH);
}
postdrawGeometry(p);
}
/**
* <code>draw</code> draws a line object where a line contains a
* collection of vertices, normals, colors and texture coordinates.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.Line)
* @param l
* the line object to render.
*/
public void draw(Line l) {
predrawGeometry(l);
IntBuffer indices = l.getIndexBuffer();
indices.rewind();
int verts = l.getVertQuantity();
if (statisticsOn) {
numberOfVerts += verts;
}
GL11.glLineWidth(l.getLineWidth());
if (l.getStippleFactor() != (short)0xFFFF) {
GL11.glEnable(GL11.GL_LINE_STIPPLE);
GL11.glLineStipple(l.getStippleFactor(), l.getStipplePattern());
}
if (l.isAntialiased()) {
GL11.glEnable(GL11.GL_LINE_SMOOTH);
GL11.glHint(GL11.GL_LINE_SMOOTH_HINT, GL11.GL_NICEST);
}
switch (l.getMode()) {
case Line.SEGMENTS:
GL11.glDrawElements(GL11.GL_LINES, indices);
break;
case Line.CONNECTED:
GL11.glDrawElements(GL11.GL_LINE_STRIP, indices);
break;
case Line.LOOP:
GL11.glDrawElements(GL11.GL_LINE_LOOP, indices);
break;
}
if (l.getStippleFactor() != (short)0xFFFF) {
GL11.glDisable(GL11.GL_LINE_STIPPLE);
}
if (l.isAntialiased()) {
GL11.glDisable(GL11.GL_LINE_SMOOTH);
}
postdrawGeometry(l);
}
/**
* <code>draw</code> renders a curve object.
*
* @param c
* the curve object to render.
*/
public void draw(Curve c) {
// set world matrix
Quaternion rotation = c.getWorldRotation();
Vector3f translation = c.getWorldTranslation();
Vector3f scale = c.getWorldScale();
float rot = rotation.toAngleAxis(vRot) * FastMath.RAD_TO_DEG;
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glTranslatef(translation.x, translation.y, translation.z);
GL11.glRotatef(rot, vRot.x, vRot.y, vRot.z);
GL11.glScalef(scale.x, scale.y, scale.z);
// render the object
GL11.glBegin(GL11.GL_LINE_STRIP);
FloatBuffer color = c.getColorBuffer();
if (color != null) color.rewind();
float colorInterval = 0;
float colorModifier = 0;
int colorCounter = 0;
if (null != color) {
GL11.glColor4f(color.get(), color.get(), color.get(), color.get());
colorInterval = 4f / color.capacity() ;
colorModifier = colorInterval;
colorCounter = 0;
color.rewind();
}
Vector3f point;
float limit = (1 + (1.0f / c.getSteps()));
for (float t = 0; t <= limit; t += 1.0f / c.getSteps()) {
if (t >= colorInterval && color != null) {
colorInterval += colorModifier;
GL11.glColor4f(color.get(), color.get(), color.get(), color.get());
colorCounter++;
}
point = c.getPoint(t, tempVa);
GL11.glVertex3f(point.x, point.y, point.z);
}
if (statisticsOn) {
numberOfVerts += limit;
}
GL11.glEnd();
postdrawGeometry(c);
}
/**
* <code>draw</code> renders a <code>TriMesh</code> object including
* it's normals, colors, textures and vertices.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.TriMesh)
* @param t
* the mesh to render.
*/
public void draw(TriMesh t) {
predrawGeometry(t);
IntBuffer indices = t.getIndexBuffer();
indices.rewind();
if (statisticsOn) {
int verts = t.getVertQuantity();
numberOfTris += t.getTriangleQuantity();
numberOfVerts += verts;
}
indices.limit(t.getTriangleQuantity()*3); // make sure only the necessary indices are sent through on old cards.
GL11.glDrawElements(GL11.GL_TRIANGLES, indices);
indices.clear();
postdrawGeometry(t);
}
/**
* <code>draw</code> renders a <code>CompositeMesh</code> object
* including it's normals, colors, textures and vertices.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.CompositeMesh)
* @param t
* the mesh to render.
*/
public void draw(CompositeMesh t) {
predrawGeometry(t);
IntBuffer indices = t.getIndexBuffer().duplicate(); // returns secondary pointer to same data
CompositeMesh.IndexRange[] ranges = t.getIndexRanges();
if (statisticsOn) {
int verts = t.getVertQuantity();
numberOfVerts += verts;
numberOfTris += t.getTriangleQuantity();
}
indices.position(0);
for (int i = 0; i < ranges.length; i++) {
int mode;
switch (ranges[i].getKind()) {
case CompositeMesh.IndexRange.TRIANGLES:
mode = GL11.GL_TRIANGLES;
break;
case CompositeMesh.IndexRange.TRIANGLE_STRIP:
mode = GL11.GL_TRIANGLE_STRIP;
break;
case CompositeMesh.IndexRange.TRIANGLE_FAN:
mode = GL11.GL_TRIANGLE_FAN;
break;
case CompositeMesh.IndexRange.QUADS:
mode = GL11.GL_QUADS;
break;
case CompositeMesh.IndexRange.QUAD_STRIP:
mode = GL11.GL_QUAD_STRIP;
break;
default:
throw new JmeException("Unknown index range type "
+ ranges[i].getKind());
}
indices.limit(indices.position() + ranges[i].getCount());
GL11.glDrawElements(mode, indices);
indices.position(indices.limit());
}
postdrawGeometry(t);
}
protected IntBuffer buf = org.lwjgl.BufferUtils.createIntBuffer(16);
/**
* <code>prepVBO</code> binds the geometry data to a vbo buffer and
* sends it to the GPU if necessary. The vbo id is stored in the
* geometry's VBOInfo class.
* @param g the geometry to initialize VBO for.
*/
public void prepVBO(Geometry g) {
if (!capabilities.GL_ARB_vertex_buffer_object)
return;
VBOInfo vbo = g.getVBOInfo();
if (vbo.isVBOVertexEnabled() && vbo.getVBOVertexID() <= 0) {
if (g.getVertexBuffer() != null) {
g.getVertexBuffer().rewind();
buf.rewind();
ARBVertexBufferObject.glGenBuffersARB(buf);
vbo.setVBOVertexID(buf.get(0));
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, vbo.getVBOVertexID());
ARBVertexBufferObject.glBufferDataARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, g.getVertexBuffer(),
ARBVertexBufferObject.GL_STATIC_DRAW_ARB);
}
}
if (vbo.isVBONormalEnabled() && vbo.getVBONormalID() <= 0) {
if (g.getNormalBuffer() != null) {
g.getNormalBuffer().rewind();
buf.rewind();
ARBVertexBufferObject.glGenBuffersARB(buf);
vbo.setVBONormalID(buf.get(0));
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, vbo.getVBONormalID());
ARBVertexBufferObject.glBufferDataARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, g.getNormalBuffer(),
ARBVertexBufferObject.GL_STATIC_DRAW_ARB);
}
}
if (vbo.isVBOColorEnabled() && vbo.getVBOColorID() <= 0) {
if (g.getColorBuffer() != null) {
g.getColorBuffer().rewind();
buf.rewind();
ARBVertexBufferObject.glGenBuffersARB(buf);
vbo.setVBOColorID(buf.get(0));
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, vbo.getVBOColorID());
ARBVertexBufferObject.glBufferDataARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, g.getColorBuffer(),
ARBVertexBufferObject.GL_STATIC_DRAW_ARB);
}
}
if (vbo.isVBOTextureEnabled()) {
for (int i = 0; i < g.getNumberOfUnits(); i++) {
if (vbo.getVBOTextureID(i) <= 0
&& g.getTextureBuffer(i) != null) {
if (g.getTextureBuffer(i) != null) {
g.getTextureBuffer(i).rewind();
buf.rewind();
ARBVertexBufferObject.glGenBuffersARB(buf);
vbo.setVBOTextureID(i, buf.get(0));
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, vbo.getVBOTextureID(i));
ARBVertexBufferObject.glBufferDataARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, g.getTextureBuffer(i),
ARBVertexBufferObject.GL_STATIC_DRAW_ARB);
}
}
}
}
buf.clear();
}
/**
* <code>draw</code> renders a scene by calling the nodes
* <code>onDraw</code> method.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.Spatial)
*/
public void draw(Spatial s) {
if (s != null) {
s.onDraw(this);
}
}
/**
* <code>draw</code> renders a text object using a predefined font.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.Text)
*/
public void draw(Text t) {
if (font == null) {
font = new LWJGLFont();
}
font.setColor(t.getTextColor());
font.print((int) t.getWorldTranslation().x, (int) t
.getWorldTranslation().y, t.getWorldScale(), t.getText(), 0);
}
/**
* checkAndAdd is used to process the spatial for the render queue. It's
* queue mode is checked, and it is added to the proper queue. If the
* queue mode is QUEUE_SKIP, false is returned.
*
* @return true if the spatial was added to a queue, false otherwise.
*/
public boolean checkAndAdd(Spatial s) {
int rqMode = s.getRenderQueueMode();
if (rqMode != Renderer.QUEUE_SKIP) {
getQueue().addToQueue(s, rqMode);
return true;
}
return false;
}
/**
* Return true if the system running this supports VBO
*
* @return boolean true if VBO supported
*/
public boolean supportsVBO() {
return capabilities.OpenGL15;
}
/**
* re-initializes the GL context for rendering of another piece of geometry.
*/
private void postdrawGeometry(Geometry t) {
VBOInfo vbo = t != null ? t.getVBOInfo() : null;
if (vbo != null && capabilities.GL_ARB_vertex_buffer_object) {
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, 0);
}
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPopMatrix();
}
/**
* <code>flush</code> tells opengl to finish all currently waiting
* commands in the buffer.
*/
public void flush() {
GL11.glFlush();
}
/**
* prepares the GL Context for rendering this geometry. This involves
* setting the rotation, translation, and scale, initializing VBO, and
* obtaining the buffer data.
* @param t the geometry to process.
*/
private void predrawGeometry(Geometry t) {
// set world matrix
Quaternion rotation = t.getWorldRotation();
Vector3f translation = t.getWorldTranslation();
Vector3f scale = t.getWorldScale();
float rot = rotation.toAngleAxis(vRot) * FastMath.RAD_TO_DEG;
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glTranslatef(translation.x, translation.y, translation.z);
GL11.glRotatef(rot, vRot.x, vRot.y, vRot.z);
GL11.glScalef(scale.x, scale.y, scale.z);
if (!(scale.x == 1 && scale.y == 1 && scale.z == 1))
GL11.glEnable(GL11.GL_NORMALIZE); // since we are using
// glScalef, we should enable
// this to keep normals
// working.
VBOInfo vbo = t.getVBOInfo();
if (vbo != null && capabilities.GL_ARB_vertex_buffer_object) {
prepVBO(t);
ignoreVBO = false;
} else
ignoreVBO = true;
// render the object
int oldLimit = -1;
FloatBuffer verticies = t.getVertexBuffer();
if (verticies != null) {
oldLimit = verticies.limit();
verticies.limit(t.getVertQuantity()*3); // make sure only the necessary verts are sent through on old cards.
}
if ((!ignoreVBO && vbo.getVBOVertexID() > 0)) { // use VBO
usingVBO = true;
GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, vbo.getVBOVertexID());
GL11.glVertexPointer(3, GL11.GL_FLOAT, 0, 0);
} else if (verticies == null) {
GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
} else if (prevVerts != verticies) {
// textures have changed
GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
if (usingVBO)
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, 0);
verticies.rewind();
GL11.glVertexPointer(3, 0, verticies);
}
if (oldLimit != -1)
verticies.limit(oldLimit);
prevVerts = verticies;
FloatBuffer normals = t.getNormalBuffer();
oldLimit = -1;
if (normals != null) {
oldLimit = normals.limit();
normals.limit(t.getVertQuantity()*3); // make sure only the necessary normals are sent through on old cards.
}
if ((!ignoreVBO && vbo.getVBONormalID() > 0)) { // use VBO
usingVBO = true;
GL11.glEnableClientState(GL11.GL_NORMAL_ARRAY);
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, vbo.getVBONormalID());
GL11.glNormalPointer(GL11.GL_FLOAT, 0, 0);
} else if (normals == null) {
GL11.glDisableClientState(GL11.GL_NORMAL_ARRAY);
} else if (prevNorms != normals) {
// textures have changed
GL11.glEnableClientState(GL11.GL_NORMAL_ARRAY);
if (usingVBO)
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, 0);
normals.rewind();
GL11.glNormalPointer(0, normals);
}
if (oldLimit != -1)
normals.limit(oldLimit);
prevNorms = normals;
FloatBuffer colors = t.getColorBuffer();
oldLimit = -1;
if (colors != null) {
oldLimit = colors.limit();
colors.limit(t.getVertQuantity()*3); // make sure only the necessary colors are sent through on old cards.
}
if ((!ignoreVBO && vbo.getVBOColorID() > 0)) { // use VBO
usingVBO = true;
GL11.glEnableClientState(GL11.GL_COLOR_ARRAY);
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, vbo.getVBOColorID());
GL11.glColorPointer(4, GL11.GL_FLOAT, 0, 0);
} else if (colors == null) {
GL11.glDisableClientState(GL11.GL_COLOR_ARRAY);
ColorRGBA defCol = t.getDefaultColor();
if (defCol != null)
GL11.glColor4f(defCol.r, defCol.g, defCol.b, defCol.a);
} else if (prevColor != colors) {
// textures have changed
GL11.glEnableClientState(GL11.GL_COLOR_ARRAY);
if (usingVBO)
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, 0);
colors.rewind();
GL11.glColorPointer(4, 0, colors);
}
if (oldLimit != -1)
colors.limit(oldLimit);
prevColor = colors;
TextureState ts = (TextureState)Spatial.getCurrentState(RenderState.RS_TEXTURE);
int offset = 0;
if(ts != null) {
offset = ts.getTextureCoordinateOffset();
for(int i = 0; i < ts.getNumberOfSetTextures(); i++) {
FloatBuffer textures = t.getTextureBuffer(i + offset);
oldLimit = -1;
if (textures != null) {
oldLimit = textures.limit();
textures.limit(t.getVertQuantity()*2); // make sure only the necessary texture coords are sent through on old cards.
}
//todo: multitexture is in GL13 - according to forum post: topic=2000
if (capabilities.GL_ARB_multitexture && capabilities.OpenGL13) {
GL13.glClientActiveTexture(GL13.GL_TEXTURE0 + i);
}
if ((!ignoreVBO && vbo.getVBOTextureID(i) > 0)) { // use VBO
usingVBO = true;
GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, vbo.getVBOTextureID(i));
GL11.glTexCoordPointer(2, GL11.GL_FLOAT, 0, 0);
} else if (textures == null) {
GL11.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
} else if (prevTex[i] != textures) {
// textures have changed
GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
if (usingVBO)
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, 0);
textures.rewind();
GL11.glTexCoordPointer(2, 0, textures);
}
prevTex[i] = textures;
if (oldLimit != -1)
textures.limit(oldLimit);
}
if(ts.getNumberOfSetTextures() < prevTextureNumber) {
for(int i = ts.getNumberOfSetTextures(); i < prevTextureNumber; i++) {
GL13.glClientActiveTexture(GL13.GL_TEXTURE0 + i);
GL11.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
}
}
prevTextureNumber = ts.getNumberOfSetTextures();
}
}
} | MINOR: Added support for compiled arrays.
git-svn-id: 5afc437a751a4ff2ced778146f5faadda0b504ab@2682 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
| src/com/jme/renderer/lwjgl/LWJGLRenderer.java | MINOR: Added support for compiled arrays. | <ide><path>rc/com/jme/renderer/lwjgl/LWJGLRenderer.java
<ide> import org.lwjgl.opengl.ContextCapabilities;
<ide> import org.lwjgl.opengl.Display;
<ide> import org.lwjgl.opengl.DisplayMode;
<add>import org.lwjgl.opengl.EXTCompiledVertexArray;
<ide> import org.lwjgl.opengl.GL11;
<ide> import org.lwjgl.opengl.GL12;
<ide> import org.lwjgl.opengl.GL13;
<ide> * @author Mark Powell
<ide> * @author Joshua Slack - Optimizations and Headless rendering
<ide> * @author Tijl Houtbeckers - Small optimizations
<del> * @version $Id: LWJGLRenderer.java,v 1.92 2005-12-12 18:42:41 Mojomonkey Exp $
<add> * @version $Id: LWJGLRenderer.java,v 1.93 2005-12-20 00:35:07 renanse Exp $
<ide> */
<ide> public class LWJGLRenderer extends Renderer {
<ide>
<ide> }
<ide>
<ide> indices.limit(t.getTriangleQuantity()*3); // make sure only the necessary indices are sent through on old cards.
<add> if (capabilities.GL_EXT_compiled_vertex_array) EXTCompiledVertexArray.glLockArraysEXT(0, t.getVertQuantity());
<ide> GL11.glDrawElements(GL11.GL_TRIANGLES, indices);
<add> if (capabilities.GL_EXT_compiled_vertex_array) EXTCompiledVertexArray.glUnlockArraysEXT();
<ide> indices.clear();
<ide>
<ide> |
|
Java | apache-2.0 | 749c7ee1c8f6fcfefd8bacce37d9abe3025f6b8a | 0 | nezda/yawni,nezda/yawni,nezda/yawni,nezda/yawni,nezda/yawni | /*
* 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.yawni.wn;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.yawni.util.CharSequences;
import org.yawni.util.ImmutableList;
import static org.yawni.util.Utils.add;
/**
* A {@code WordSense} represents the precise lexical information related to a specific sense of a {@link Word}.
*
* <p> {@code WordSense}'s are linked by {@link Relation}s into a network of lexically related {@link Synset}s
* and {@code WordSense}s.
* {@link WordSense#getTargets WordSense.getTargets()} retrieves the targets of these links, and
* {@link WordSense#getRelations WordSense.getRelations()} retrieves the relations themselves.
*
* <p> Each {@code WordSense} has exactly one associated {@code Word} (however a given {@code Word} may have one
* or more {@code WordSense}s with different orthographic case (e.g., the nouns "CD" vs. "Cd")).
*
* @see Relation
* @see Synset
* @see Word
*/
public final class WordSense implements RelationTarget, Comparable<WordSense> {
/**
* <em>Optional</em> restrictions for the position(s) an adjective can take
* relative to the noun it modifies. aka "adjclass".
*/
public enum AdjPosition {
NONE(0),
/**
* of adjectives; relating to or occurring within the predicate of a sentence
*/
PREDICATIVE(1),
/**
* of adjectives; placed before the nouns they modify
*/
ATTRIBUTIVE(2), // synonymous with PRENOMINAL
//PRENOMINAL(2), // synonymous with ATTRIBUTIVE
IMMEDIATE_POSTNOMINAL(4),
;
final int flag;
AdjPosition(final int flag) {
this.flag = flag;
}
static boolean isActive(final AdjPosition adjPosFlag, final int flags) {
return 0 != (adjPosFlag.flag & flags);
}
} // end enum AdjPosition
//
// Instance implementation
//
private final Synset synset;
/** case sensitive lemma */
private final String lemma;
private final int lexid;
// represents up to 64 different verb frames are possible (as of now, 35 exist)
private long verbFrameFlags;
private short senseNumber;
private short sensesTaggedFrequency;
// only needs to be a byte since there are only 3 bits of flag values
private final byte adjPositionFlags;
//
// Constructor
//
WordSense(final Synset synset, final String lemma, final int lexid, final int flags) {
this.synset = synset;
this.lemma = lemma;
this.lexid = lexid;
assert flags < Byte.MAX_VALUE;
this.adjPositionFlags = (byte) flags;
this.senseNumber = -1;
this.sensesTaggedFrequency = -1;
}
void setVerbFrameFlag(final int fnum) {
verbFrameFlags |= 1L << (fnum - 1);
}
//
// Accessors
//
public Synset getSynset() {
return synset;
}
public POS getPOS() {
return synset.getPOS();
}
/**
* Returns the natural-cased lemma representation of this {@code WordSense}.
* Its lemma is its orthographic representation, for example <tt>"dog"</tt>
* or <tt>"U.S.A."</tt> or <tt>"George Washington"</tt>. Contrast to the
* canonical lemma provided by {@link Word#getLemma()}.
*/
public String getLemma() {
return lemma;
}
/** {@inheritDoc} */
public Iterator<WordSense> iterator() {
return ImmutableList.of(this).iterator();
}
String adjFlagsToString() {
if (adjPositionFlags == 0) {
return "NONE";
}
final StringBuilder flagString = new StringBuilder();
if (AdjPosition.isActive(AdjPosition.PREDICATIVE, adjPositionFlags)) {
flagString.append("predicative");
}
if (AdjPosition.isActive(AdjPosition.ATTRIBUTIVE, adjPositionFlags)) {
if (flagString.length() != 0) {
flagString.append(',');
}
// synonymous with attributive - WordNet browser seems to use this
// while the database files seem to indicate it as attributive
flagString.append("prenominal");
}
if (AdjPosition.isActive(AdjPosition.IMMEDIATE_POSTNOMINAL, adjPositionFlags)) {
if (flagString.length() != 0) {
flagString.append(',');
}
flagString.append("immediate_postnominal");
}
return flagString.toString();
}
/**
* 1-indexed value whose order is relative to its {@link Word}.
*
* <p> Note that this value often varies across WordNet versions.
* For those senses which never occurred in sense tagged corpora, it is
* arbitrarily chosen.
* @see <a href="http://wordnet.princeton.edu/wordnet/man/cntlist.5WN.html#toc4">'NOTES' in cntlist WordNet documentation</a>
*/
public int getSenseNumber() {
if (senseNumber < 1) {
// Ordering of Word's Synsets (combo(Word, Synset)=WordSense)
// is defined by sense tagged frequency (but this is implicit).
// Get Word and scan this WordSense's Synsets and
// find the one with this Synset.
final Word word = getWord();
int localSenseNumber = 0;
for (final Synset syn : word.getSynsets()) {
localSenseNumber--;
if (syn.equals(synset)) {
localSenseNumber = -localSenseNumber;
break;
}
}
assert localSenseNumber > 0 : "Word lemma: "+lemma+" "+getPOS();
assert localSenseNumber < Short.MAX_VALUE;
this.senseNumber = (short)localSenseNumber;
}
return senseNumber;
}
/**
* Uses this <code>WordSense</code>'s lemma as key to find its <code>Word</code>.
*/
// WordSense contains everything Word does - no need to expose this
Word getWord() {
final Word word = synset.fileBackedDictionary.lookupWord(lemma, getPOS());
assert word != null : "lookupWord failed for \""+lemma+"\" "+getPOS();
return word;
}
/**
* Build 'sensekey'. Used for searching <tt>cntlist.rev</tt> and <tt>sents.vrb</tt>
* @see <a href="http://wordnet.princeton.edu/wordnet/man/senseidx.5WN.html#sect3">http://wordnet.princeton.edu/wordnet/man/senseidx.5WN.html#sect3</a>
*/
//TODO cache this ? does it ever become not useful to cache this ? better to cache getSensesTaggedFrequency()
// power users might be into this: https://sourceforge.net/tracker/index.php?func=detail&aid=2009619&group_id=33824&atid=409470
CharSequence getSenseKey() {
final String searchWord;
final int headSense;
if (getSynset().isAdjectiveCluster()) {
final List<RelationTarget> adjsses = getSynset().getTargets(RelationType.SIMILAR_TO);
assert adjsses.size() == 1;
final Synset adjss = (Synset) adjsses.get(0);
// if satellite, key lemma in cntlist.rev
// is adjss's first word (no case) and
// adjss's lexid (aka lexfilenum) otherwise
searchWord = adjss.getWordSenses().get(0).getLemma();
headSense = adjss.getWordSenses().get(0).lexid;
} else {
searchWord = getLemma();
headSense = lexid;
}
final int lex_filenum = getSynset().lexfilenum();
final StringBuilder senseKey;
if (getSynset().isAdjectiveCluster()) {
// slow equivalent
// senseKey = String.format("%s%%%d:%02d:%02d:%s:%02d",
// getLemma().toLowerCase(),
// POS.SAT_ADJ.getWordNetCode(),
// lex_filenum,
// lexid,
// searchWord.toLowerCase(),
// headSense);
final int keyLength = getLemma().length() + 1 /* POS code length */ +
2 /* lex_filenum length */ + 2 /* lexid length */ +
searchWord.length() + 2 /* headSense lexid length */ + 5 /* delimiters */;
senseKey = new StringBuilder(keyLength);
for (int i = 0, n = getLemma().length(); i != n; ++i) {
senseKey.append(Character.toLowerCase(getLemma().charAt(i)));
}
senseKey.append('%');
senseKey.append(POS.SAT_ADJ.getWordNetCode());
senseKey.append(':');
if (lex_filenum < 10) {
senseKey.append('0');
}
senseKey.append(lex_filenum);
senseKey.append(':');
if (lexid < 10) {
senseKey.append('0');
}
senseKey.append(lexid);
senseKey.append(':');
for (int i = 0, n = searchWord.length(); i != n; ++i) {
senseKey.append(Character.toLowerCase(searchWord.charAt(i)));
}
senseKey.append(':');
if (headSense < 10) {
senseKey.append('0');
}
senseKey.append(headSense);
//assert oldAdjClusterSenseKey(searchWord, headSense).contentEquals(senseKey);
//assert senseKey.length() <= keyLength;
} else {
// slow equivalent
// senseKey = String.format("%s%%%d:%02d:%02d::",
// getLemma().toLowerCase(),
// getPOS().getWordNetCode(),
// lex_filenum,
// lexid
// );
final int keyLength = getLemma().length() + 1 /* POS code length */ +
2 /* lex_filenum length */ + 2 /* lexid length */ + 5 /* delimiters */;
senseKey = new StringBuilder(keyLength);
for (int i = 0, n = getLemma().length(); i != n; ++i) {
senseKey.append(Character.toLowerCase(getLemma().charAt(i)));
}
senseKey.append('%');
senseKey.append(getPOS().getWordNetCode());
senseKey.append(':');
if (lex_filenum < 10) {
senseKey.append('0');
}
senseKey.append(lex_filenum);
senseKey.append(':');
if (lexid < 10) {
senseKey.append('0');
}
senseKey.append(lexid);
senseKey.append("::");
//assert oldNonAdjClusterSenseKey().contentEquals(senseKey);
//assert senseKey.length() <= keyLength;
}
return senseKey;
}
/**
* @see <a href="http://wordnet.princeton.edu/wordnet/man/cntlist.5WN.html"><tt>cntlist</tt></a>
*/
public int getSensesTaggedFrequency() {
if (sensesTaggedFrequency < 0) {
// caching sensesTaggedFrequency requires minimal memory and provides a lot of value
// (high-level and eliminating redundant work)
// TODO we could use this Word's getTaggedSenseCount() to determine if
// there were any tagged senses for *any* sense of it (including this one)
// and really we wouldn't need to look at sense (numbers) exceeding that value
// as an optimization
final CharSequence senseKey = getSenseKey();
final FileBackedDictionary dictionary = synset.fileBackedDictionary;
final String line = dictionary.lookupCntlistDotRevLine(senseKey);
int count = 0;
if (line != null) {
// cntlist.rev line format:
// <sense_key> <sense_number> tag_cnt
final int lastSpace = line.lastIndexOf(' ');
assert lastSpace > 0;
count = CharSequences.parseInt(line, lastSpace + 1, line.length());
// sanity check final int firstSpace = line.indexOf(" ");
// sanity check assert firstSpace > 0 && firstSpace != lastSpace;
// sanity check final int mySenseNumber = getSenseNumber();
// sanity check final int foundSenseNumber =
// sanity check CharSequenceTokenizer.parseInt(line, firstSpace + 1, lastSpace);
// sanity check if (mySenseNumber != foundSenseNumber) {
// sanity check System.err.println(this+" foundSenseNumber: "+foundSenseNumber+" count: "+count);
// sanity check } else {
// sanity check //System.err.println(this+" OK");
// sanity check }
//[WordSense 9465459@[POS noun]:"unit"#5] foundSenseNumber: 7
//assert getSenseNumber() ==
// CharSequenceTokenizer.parseInt(line, firstSpace + 1, lastSpace);
assert count <= Short.MAX_VALUE;
sensesTaggedFrequency = (short) count;
} else {
sensesTaggedFrequency = 0;
}
}
return sensesTaggedFrequency;
}
/**
* Adjective position indicator.
* @see AdjPosition
*/
public AdjPosition getAdjPosition() {
if (adjPositionFlags == 0) {
return AdjPosition.NONE;
}
assert getPOS() == POS.ADJ;
if (AdjPosition.isActive(AdjPosition.PREDICATIVE, adjPositionFlags)) {
assert false == AdjPosition.isActive(AdjPosition.ATTRIBUTIVE, adjPositionFlags);
assert false == AdjPosition.isActive(AdjPosition.IMMEDIATE_POSTNOMINAL, adjPositionFlags);
return AdjPosition.PREDICATIVE;
}
if (AdjPosition.isActive(AdjPosition.ATTRIBUTIVE, adjPositionFlags)) {
assert false == AdjPosition.isActive(AdjPosition.PREDICATIVE, adjPositionFlags);
assert false == AdjPosition.isActive(AdjPosition.IMMEDIATE_POSTNOMINAL, adjPositionFlags);
return AdjPosition.ATTRIBUTIVE;
}
if (AdjPosition.isActive(AdjPosition.IMMEDIATE_POSTNOMINAL, adjPositionFlags)) {
assert false == AdjPosition.isActive(AdjPosition.ATTRIBUTIVE, adjPositionFlags);
assert false == AdjPosition.isActive(AdjPosition.PREDICATIVE, adjPositionFlags);
return AdjPosition.IMMEDIATE_POSTNOMINAL;
}
throw new IllegalStateException("invalid flags "+adjPositionFlags);
}
int getLexid() {
return lexid;
}
// published as long, stored as byte for max efficiency
long getAdjPositionFlags() {
return adjPositionFlags;
}
//TODO expert only. maybe publish as EnumSet
long getVerbFrameFlags() {
return verbFrameFlags;
}
/**
* <p> Returns illustrative sentences <em>and</em> generic verb frames. This <b>only</b> has values
* for {@link POS#VERB} {@code WordSense}s.
*
* <p> For illustrative sentences (<tt>sents.vrb</tt>), "%s" is replaced with the verb lemma
* which seems unnecessarily ineficient since you have the WordSense anyway.
*
* <pre>{@literal Example: verb "complete"#1 has 4 generic verb frames:
* 1. *> Somebody ----s
* 2. *> Somebody ----s something
* 3. *> Something ----s something
* 4. *> Somebody ----s VERB-ing
* and 1 specific verb frame:
* 1. EX: They won't %s the story
* }</pre>
*
* <p> Official WordNet 3.0 documentation indicates "specific" and generic frames
* are mutually exclusive which is not the case.
*
* @see <a href="http://wordnet.princeton.edu/wordnet/man/wndb.5WN.html#sect6">http://wordnet.princeton.edu/wordnet/man/wndb.5WN.html#sect6</a>
*/
public List<String> getVerbFrames() {
if (getPOS() != POS.VERB) {
return ImmutableList.of();
}
final CharSequence senseKey = getSenseKey();
final FileBackedDictionary dictionary = synset.fileBackedDictionary;
final String sentenceNumbers = dictionary.lookupVerbSentencesNumbers(senseKey);
List<String> frames = ImmutableList.of();
if (sentenceNumbers != null) {
frames = new ArrayList<String>();
// fetch the illustrative sentences indicated in sentenceNumbers
//TODO consider substibuting in lemma for "%s" in each
//FIXME this logic is a bit too complex/duplicated!!
int s = 0;
int e = sentenceNumbers.indexOf(',');
final int n = sentenceNumbers.length();
e = e > 0 ? e : n;
for ( ; s < n;
// e = next comma OR if no more commas, e = n
s = e + 1, e = sentenceNumbers.indexOf(',', s), e = e > 0 ? e : n) {
final String sentNum = sentenceNumbers.substring(s, e);
final String sentence = dictionary.lookupVerbSentence(sentNum);
assert sentence != null;
frames.add(sentence);
}
} else {
//assert verbFrameFlags == 0L : "not mutually exclusive for "+this;
}
if (verbFrameFlags != 0L) {
final int numGenericFrames = Long.bitCount(verbFrameFlags);
if (frames.isEmpty()) {
frames = new ArrayList<String>();
} else {
((ArrayList<String>)frames).ensureCapacity(frames.size() + numGenericFrames);
}
// fetch any generic verb frames indicated by verbFrameFlags
// numberOfLeadingZeros (leftmost), numberOfTrailingZeros (rightmost)
// 001111111111100
// ^-lead ^-trail
// simple scan between these (inclusive) should cover rest
for (int fn = Long.numberOfTrailingZeros(verbFrameFlags),
lfn = Long.SIZE - Long.numberOfLeadingZeros(verbFrameFlags);
fn < lfn;
fn++) {
if ((verbFrameFlags & (1L << fn)) != 0L) {
final String frame = dictionary.lookupGenericFrame(fn + 1);
assert frame != null :
"this: "+this+" fn: "+fn+
" shift: "+((1L << fn)+
" verbFrameFlags: "+Long.toBinaryString(verbFrameFlags))+
" verbFrameFlags: "+verbFrameFlags;
frames.add(frame);
}
}
}
return ImmutableList.copyOf(frames);
}
public String getDescription() {
if (getPOS() != POS.ADJ && getPOS() != POS.SAT_ADJ) {
return lemma;
}
final StringBuilder description = new StringBuilder(lemma);
if (adjPositionFlags != 0) {
description.append('(');
description.append(adjFlagsToString());
description.append(')');
}
final List<RelationTarget> targets = getTargets(RelationType.ANTONYM);
if (targets.isEmpty() == false) {
// adj 'acidic' has more than 1 antonym ('alkaline' and 'amphoteric')
for (final RelationTarget target : targets) {
description.append(" (vs. ");
final WordSense antonym = (WordSense)target;
description.append(antonym.getLemma());
description.append(')');
}
}
return description.toString();
}
public String getLongDescription() {
final StringBuilder buffer = new StringBuilder();
//buffer.append(getSenseNumber());
//buffer.append(". ");
//final int sensesTaggedFrequency = getSensesTaggedFrequency();
//if (sensesTaggedFrequency != 0) {
// buffer.append("(");
// buffer.append(sensesTaggedFrequency);
// buffer.append(") ");
//}
buffer.append(getLemma());
if (adjPositionFlags != 0) {
buffer.append('(');
buffer.append(adjFlagsToString());
buffer.append(')');
}
final String gloss = getSynset().getGloss();
if (gloss != null) {
buffer.append(" -- (");
buffer.append(gloss);
buffer.append(')');
}
return buffer.toString();
}
//
// Relations
//
private List<LexicalRelation> restrictRelations(final RelationType type) {
final List<Relation> relations = synset.getRelations();
List<LexicalRelation> list = null;
for (int i = 0, n = relations.size(); i < n; i++) {
final Relation relation = relations.get(i);
if (relation.getSource().equals(this) == false) {
continue;
}
if (type != null && type != relation.getType()) {
continue;
}
assert relation.getSource() == this;
final LexicalRelation lexicalRelation = (LexicalRelation) relation;
list = add(list, lexicalRelation);
}
if (list == null) {
return ImmutableList.of();
}
return ImmutableList.copyOf(list);
}
public List<LexicalRelation> getRelations() {
return restrictRelations(null);
}
public List<LexicalRelation> getRelations(final RelationType type) {
return restrictRelations(type);
}
public List<RelationTarget> getTargets() {
return Synset.collectTargets(getRelations());
}
public List<RelationTarget> getTargets(final RelationType type) {
return Synset.collectTargets(getRelations(type));
}
//
// Object methods
//
@Override
public boolean equals(Object object) {
return (object instanceof WordSense)
&& ((WordSense) object).synset.equals(synset)
&& ((WordSense) object).lemma.equals(lemma);
}
@Override
public int hashCode() {
return synset.hashCode() ^ lemma.hashCode();
}
@Override
public String toString() {
return new StringBuilder("[WordSense ").
append(synset.getOffset()).
append('@').
append(synset.getPOS()).
append(":\"").
append(getLemma()).
append("\"#").
append(getSenseNumber()).
append(']').toString();
}
/**
* {@inheritDoc}
*/
public int compareTo(final WordSense that) {
int result;
result = WordNetLexicalComparator.TO_LOWERCASE_INSTANCE.compare(this.getLemma(), that.getLemma());
if (result == 0) {
result = this.getSenseNumber() - that.getSenseNumber();
if (result == 0) {
result = this.getSynset().compareTo(that.getSynset());
}
}
return result;
}
} | core/src/main/java/org/yawni/wn/WordSense.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.yawni.wn;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.yawni.util.CharSequences;
import org.yawni.util.ImmutableList;
import static org.yawni.util.Utils.add;
/**
* A {@code WordSense} represents the precise lexical information related to a specific sense of a {@link Word}.
*
* <p> {@code WordSense}'s are linked by {@link Relation}s into a network of lexically related {@link Synset}s
* and {@code WordSense}s.
* {@link WordSense#getTargets WordSense.getTargets()} retrieves the targets of these links, and
* {@link WordSense#getRelations WordSense.getRelations()} retrieves the relations themselves.
*
* <p> Each {@code WordSense} has exactly one associated {@code Word} (however a given {@code Word} may have one
* or more {@code WordSense}s with different orthographic case (e.g., the nouns "CD" vs. "Cd")).
*
* @see Relation
* @see Synset
* @see Word
*/
public final class WordSense implements RelationTarget, Comparable<WordSense> {
/**
* <em>Optional</em> restrictions for the position(s) an adjective can take
* relative to the noun it modifies. aka "adjclass".
*/
public enum AdjPosition {
NONE(0),
/**
* of adjectives; relating to or occurring within the predicate of a sentence
*/
PREDICATIVE(1),
/**
* of adjectives; placed before the nouns they modify
*/
ATTRIBUTIVE(2), // synonymous with PRENOMINAL
//PRENOMINAL(2), // synonymous with ATTRIBUTIVE
IMMEDIATE_POSTNOMINAL(4),
;
final int flag;
AdjPosition(final int flag) {
this.flag = flag;
}
static boolean isActive(final AdjPosition adjPosFlag, final int flags) {
return 0 != (adjPosFlag.flag & flags);
}
} // end enum AdjPosition
//
// Instance implementation
//
private final Synset synset;
/** case sensitive lemma */
private final String lemma;
private final int lexid;
// represents up to 64 different verb frames are possible (as of now, 35 exist)
private long verbFrameFlags;
private short senseNumber;
private short sensesTaggedFrequency;
// only needs to be a byte since there are only 3 bits of flag values
private final byte flags;
//
// Constructor
//
WordSense(final Synset synset, final String lemma, final int lexid, final int flags) {
this.synset = synset;
this.lemma = lemma;
this.lexid = lexid;
assert flags < Byte.MAX_VALUE;
this.flags = (byte) flags;
this.senseNumber = -1;
this.sensesTaggedFrequency = -1;
}
void setVerbFrameFlag(final int fnum) {
verbFrameFlags |= 1L << (fnum - 1);
}
//
// Accessors
//
public Synset getSynset() {
return synset;
}
public POS getPOS() {
return synset.getPOS();
}
/**
* Returns the natural-cased lemma representation of this {@code WordSense}
* Its lemma is its orthographic representation, for example <tt>"dog"</tt>
* or <tt>"U.S.A."</tt> or <tt>"George Washington"</tt>. Contrast to the
* canonical lemma provided by {@link Word#getLemma()}.
*/
public String getLemma() {
return lemma;
}
/** {@inheritDoc} */
public Iterator<WordSense> iterator() {
return ImmutableList.of(this).iterator();
}
String flagsToString() {
if (flags == 0) {
return "NONE";
}
final StringBuilder flagString = new StringBuilder();
if (AdjPosition.isActive(AdjPosition.PREDICATIVE, flags)) {
flagString.append("predicative");
}
if (AdjPosition.isActive(AdjPosition.ATTRIBUTIVE, flags)) {
if (flagString.length() != 0) {
flagString.append(',');
}
// synonymous with attributive - WordNet browser seems to use this
// while the database files seem to indicate it as attributive
flagString.append("prenominal");
}
if (AdjPosition.isActive(AdjPosition.IMMEDIATE_POSTNOMINAL, flags)) {
if (flagString.length() != 0) {
flagString.append(',');
}
flagString.append("immediate_postnominal");
}
return flagString.toString();
}
/**
* 1-indexed value whose order is relative to its {@link Word}.
*
* <p> Note that this value often varies across WordNet versions.
* For those senses which never occured in sense tagged corpora, it is
* arbitrarily chosen.
* @see <a href="http://wordnet.princeton.edu/wordnet/man/cntlist.5WN.html#toc4">'NOTES' in cntlist WordNet documentation</a>
*/
public int getSenseNumber() {
if (senseNumber < 1) {
// Ordering of Word's Synsets (combo(Word, Synset)=WordSense)
// is defined by sense tagged frequency (but this is implicit).
// Get Word and scan this WordSense's Synsets and
// find the one with this Synset.
final Word word = getWord();
int localSenseNumber = 0;
for (final Synset syn : word.getSynsets()) {
localSenseNumber--;
if (syn.equals(synset)) {
localSenseNumber = -localSenseNumber;
break;
}
}
assert localSenseNumber > 0 : "Word lemma: "+lemma+" "+getPOS();
assert localSenseNumber < Short.MAX_VALUE;
this.senseNumber = (short)localSenseNumber;
}
return senseNumber;
}
/**
* Use this <code>WordSense</code>'s lemma as key to find its <code>Word</code>.
*/
// WordSense contains everything Word does - no need to expose this
Word getWord() {
final Word word = synset.fileBackedDictionary.lookupWord(lemma, getPOS());
assert word != null : "lookupWord failed for \""+lemma+"\" "+getPOS();
return word;
}
/**
* Build 'sensekey'. Used for searching <tt>cntlist.rev</tt> and <tt>sents.vrb</tt>
* @see <a href="http://wordnet.princeton.edu/wordnet/man/senseidx.5WN.html#sect3">http://wordnet.princeton.edu/wordnet/man/senseidx.5WN.html#sect3</a>
*/
//TODO cache this ? does it ever become not useful to cache this ? better to cache getSensesTaggedFrequency()
// power users might be into this: https://sourceforge.net/tracker/index.php?func=detail&aid=2009619&group_id=33824&atid=409470
CharSequence getSenseKey() {
final String searchWord;
final int headSense;
if (getSynset().isAdjectiveCluster()) {
final List<RelationTarget> adjsses = getSynset().getTargets(RelationType.SIMILAR_TO);
assert adjsses.size() == 1;
final Synset adjss = (Synset) adjsses.get(0);
// if satellite, key lemma in cntlist.rev
// is adjss's first word (no case) and
// adjss's lexid (aka lexfilenum) otherwise
searchWord = adjss.getWordSenses().get(0).getLemma();
headSense = adjss.getWordSenses().get(0).lexid;
} else {
searchWord = getLemma();
headSense = lexid;
}
final int lex_filenum = getSynset().lexfilenum();
final StringBuilder senseKey;
if (getSynset().isAdjectiveCluster()) {
// slow equivalent
// senseKey = String.format("%s%%%d:%02d:%02d:%s:%02d",
// getLemma().toLowerCase(),
// POS.SAT_ADJ.getWordNetCode(),
// lex_filenum,
// lexid,
// searchWord.toLowerCase(),
// headSense);
final int keyLength = getLemma().length() + 1 /* POS code length */ +
2 /* lex_filenum length */ + 2 /* lexid length */ +
searchWord.length() + 2 /* headSense lexid length */ + 5 /* delimiters */;
senseKey = new StringBuilder(keyLength);
for (int i = 0, n = getLemma().length(); i != n; ++i) {
senseKey.append(Character.toLowerCase(getLemma().charAt(i)));
}
senseKey.append('%');
senseKey.append(POS.SAT_ADJ.getWordNetCode());
senseKey.append(':');
if (lex_filenum < 10) {
senseKey.append('0');
}
senseKey.append(lex_filenum);
senseKey.append(':');
if (lexid < 10) {
senseKey.append('0');
}
senseKey.append(lexid);
senseKey.append(':');
for (int i = 0, n = searchWord.length(); i != n; ++i) {
senseKey.append(Character.toLowerCase(searchWord.charAt(i)));
}
senseKey.append(':');
if (headSense < 10) {
senseKey.append('0');
}
senseKey.append(headSense);
//assert oldAdjClusterSenseKey(searchWord, headSense).contentEquals(senseKey);
//assert senseKey.length() <= keyLength;
} else {
// slow equivalent
// senseKey = String.format("%s%%%d:%02d:%02d::",
// getLemma().toLowerCase(),
// getPOS().getWordNetCode(),
// lex_filenum,
// lexid
// );
final int keyLength = getLemma().length() + 1 /* POS code length */ +
2 /* lex_filenum length */ + 2 /* lexid length */ + 5 /* delimiters */;
senseKey = new StringBuilder(keyLength);
for (int i = 0, n = getLemma().length(); i != n; ++i) {
senseKey.append(Character.toLowerCase(getLemma().charAt(i)));
}
senseKey.append('%');
senseKey.append(getPOS().getWordNetCode());
senseKey.append(':');
if (lex_filenum < 10) {
senseKey.append('0');
}
senseKey.append(lex_filenum);
senseKey.append(':');
if (lexid < 10) {
senseKey.append('0');
}
senseKey.append(lexid);
senseKey.append("::");
//assert oldNonAdjClusterSenseKey().contentEquals(senseKey);
//assert senseKey.length() <= keyLength;
}
return senseKey;
}
/**
* <a href="http://wordnet.princeton.edu/wordnet/man/cntlist.5WN.html"><tt>cntlist</tt></a>
*/
public int getSensesTaggedFrequency() {
if (sensesTaggedFrequency < 0) {
// caching sensesTaggedFrequency requires minimal memory and provides a lot of value
// (high-level and eliminating redundant work)
// TODO we could use this Word's getTaggedSenseCount() to determine if
// there were any tagged senses for *any* sense of it (including this one)
// and really we wouldn't need to look at sense (numbers) exceeding that value
// as an optimization
final CharSequence senseKey = getSenseKey();
final FileBackedDictionary dictionary = synset.fileBackedDictionary;
final String line = dictionary.lookupCntlistDotRevLine(senseKey);
int count = 0;
if (line != null) {
// cntlist.rev line format:
// <sense_key> <sense_number> tag_cnt
final int lastSpace = line.lastIndexOf(' ');
assert lastSpace > 0;
count = CharSequences.parseInt(line, lastSpace + 1, line.length());
// sanity check final int firstSpace = line.indexOf(" ");
// sanity check assert firstSpace > 0 && firstSpace != lastSpace;
// sanity check final int mySenseNumber = getSenseNumber();
// sanity check final int foundSenseNumber =
// sanity check CharSequenceTokenizer.parseInt(line, firstSpace + 1, lastSpace);
// sanity check if (mySenseNumber != foundSenseNumber) {
// sanity check System.err.println(this+" foundSenseNumber: "+foundSenseNumber+" count: "+count);
// sanity check } else {
// sanity check //System.err.println(this+" OK");
// sanity check }
//[WordSense 9465459@[POS noun]:"unit"#5] foundSenseNumber: 7
//assert getSenseNumber() ==
// CharSequenceTokenizer.parseInt(line, firstSpace + 1, lastSpace);
assert count <= Short.MAX_VALUE;
sensesTaggedFrequency = (short) count;
} else {
sensesTaggedFrequency = 0;
}
}
return sensesTaggedFrequency;
}
/**
* Adjective position indicator.
* @see AdjPosition
*/
public AdjPosition getAdjPosition() {
if (flags == 0) {
return AdjPosition.NONE;
}
assert getPOS() == POS.ADJ;
if (AdjPosition.isActive(AdjPosition.PREDICATIVE, flags)) {
assert false == AdjPosition.isActive(AdjPosition.ATTRIBUTIVE, flags);
assert false == AdjPosition.isActive(AdjPosition.IMMEDIATE_POSTNOMINAL, flags);
return AdjPosition.PREDICATIVE;
}
if (AdjPosition.isActive(AdjPosition.ATTRIBUTIVE, flags)) {
assert false == AdjPosition.isActive(AdjPosition.PREDICATIVE, flags);
assert false == AdjPosition.isActive(AdjPosition.IMMEDIATE_POSTNOMINAL, flags);
return AdjPosition.ATTRIBUTIVE;
}
if (AdjPosition.isActive(AdjPosition.IMMEDIATE_POSTNOMINAL, flags)) {
assert false == AdjPosition.isActive(AdjPosition.ATTRIBUTIVE, flags);
assert false == AdjPosition.isActive(AdjPosition.PREDICATIVE, flags);
return AdjPosition.IMMEDIATE_POSTNOMINAL;
}
throw new IllegalStateException("invalid flags "+flags);
}
int getLexid() {
return lexid;
}
// published as long, stored as byte for max efficiency
long getFlags() {
return flags;
}
//TODO expert only. maybe publish as EnumSet
long getVerbFrameFlags() {
return verbFrameFlags;
}
/**
* <p> Returns illustrative sentences <em>and</em> generic verb frames. This <b>only</b> has values
* for {@link POS#VERB} {@code WordSense}s.
*
* <p> For illustrative sentences (<tt>sents.vrb</tt>), "%s" is replaced with the verb lemma
* which seems unnecessarily ineficient since you have the WordSense anyway.
*
* <pre>{@literal Example: verb "complete"#1 has 4 generic verb frames:
* 1. *> Somebody ----s
* 2. *> Somebody ----s something
* 3. *> Something ----s something
* 4. *> Somebody ----s VERB-ing
* and 1 specific verb frame:
* 1. EX: They won't %s the story
* }</pre>
*
* <p> Official WordNet 3.0 documentation indicates "specific" and generic frames
* are mutually exclusive which is not the case.
*
* @see <a href="http://wordnet.princeton.edu/wordnet/man/wndb.5WN.html#sect6">http://wordnet.princeton.edu/wordnet/man/wndb.5WN.html#sect6</a>
*/
public List<String> getVerbFrames() {
if (getPOS() != POS.VERB) {
return ImmutableList.of();
}
final CharSequence senseKey = getSenseKey();
final FileBackedDictionary dictionary = synset.fileBackedDictionary;
final String sentenceNumbers = dictionary.lookupVerbSentencesNumbers(senseKey);
List<String> frames = ImmutableList.of();
if (sentenceNumbers != null) {
frames = new ArrayList<String>();
// fetch the illustrative sentences indicated in sentenceNumbers
//TODO consider substibuting in lemma for "%s" in each
//FIXME this logic is a bit too complex/duplicated!!
int s = 0;
int e = sentenceNumbers.indexOf(',');
final int n = sentenceNumbers.length();
e = e > 0 ? e : n;
for ( ; s < n;
// e = next comma OR if no more commas, e = n
s = e + 1, e = sentenceNumbers.indexOf(',', s), e = e > 0 ? e : n) {
final String sentNum = sentenceNumbers.substring(s, e);
final String sentence = dictionary.lookupVerbSentence(sentNum);
assert sentence != null;
frames.add(sentence);
}
} else {
//assert verbFrameFlags == 0L : "not mutually exclusive for "+this;
}
if (verbFrameFlags != 0L) {
final int numGenericFrames = Long.bitCount(verbFrameFlags);
if (frames.isEmpty()) {
frames = new ArrayList<String>();
} else {
((ArrayList<String>)frames).ensureCapacity(frames.size() + numGenericFrames);
}
// fetch any generic verb frames indicated by verbFrameFlags
// numberOfLeadingZeros (leftmost), numberOfTrailingZeros (rightmost)
// 001111111111100
// ^-lead ^-trail
// simple scan between these (inclusive) should cover rest
for (int fn = Long.numberOfTrailingZeros(verbFrameFlags),
lfn = Long.SIZE - Long.numberOfLeadingZeros(verbFrameFlags);
fn < lfn;
fn++) {
if ((verbFrameFlags & (1L << fn)) != 0L) {
final String frame = dictionary.lookupGenericFrame(fn + 1);
assert frame != null :
"this: "+this+" fn: "+fn+
" shift: "+((1L << fn)+
" verbFrameFlags: "+Long.toBinaryString(verbFrameFlags))+
" verbFrameFlags: "+verbFrameFlags;
frames.add(frame);
}
}
}
return ImmutableList.copyOf(frames);
}
public String getDescription() {
if (getPOS() != POS.ADJ && getPOS() != POS.SAT_ADJ) {
return lemma;
}
final StringBuilder description = new StringBuilder(lemma);
if (flags != 0) {
description.append('(');
description.append(flagsToString());
description.append(')');
}
final List<RelationTarget> targets = getTargets(RelationType.ANTONYM);
if (targets.isEmpty() == false) {
// adj 'acidic' has more than 1 antonym ('alkaline' and 'amphoteric')
for (final RelationTarget target : targets) {
description.append(" (vs. ");
final WordSense antonym = (WordSense)target;
description.append(antonym.getLemma());
description.append(')');
}
}
return description.toString();
}
public String getLongDescription() {
final StringBuilder buffer = new StringBuilder();
//buffer.append(getSenseNumber());
//buffer.append(". ");
//final int sensesTaggedFrequency = getSensesTaggedFrequency();
//if (sensesTaggedFrequency != 0) {
// buffer.append("(");
// buffer.append(sensesTaggedFrequency);
// buffer.append(") ");
//}
buffer.append(getLemma());
if (flags != 0) {
buffer.append('(');
buffer.append(flagsToString());
buffer.append(')');
}
final String gloss = getSynset().getGloss();
if (gloss != null) {
buffer.append(" -- (");
buffer.append(gloss);
buffer.append(')');
}
return buffer.toString();
}
//
// Relations
//
private List<LexicalRelation> restrictRelations(final RelationType type) {
final List<Relation> relations = synset.getRelations();
List<LexicalRelation> list = null;
for (int i = 0, n = relations.size(); i < n; i++) {
final Relation relation = relations.get(i);
if (relation.getSource().equals(this) == false) {
continue;
}
if (type != null && type != relation.getType()) {
continue;
}
assert relation.getSource() == this;
final LexicalRelation lexicalRelation = (LexicalRelation) relation;
list = add(list, lexicalRelation);
}
if (list == null) {
return ImmutableList.of();
}
return ImmutableList.copyOf(list);
}
public List<LexicalRelation> getRelations() {
return restrictRelations(null);
}
public List<LexicalRelation> getRelations(final RelationType type) {
return restrictRelations(type);
}
public List<RelationTarget> getTargets() {
return Synset.collectTargets(getRelations());
}
public List<RelationTarget> getTargets(final RelationType type) {
return Synset.collectTargets(getRelations(type));
}
//
// Object methods
//
@Override
public boolean equals(Object object) {
return (object instanceof WordSense)
&& ((WordSense) object).synset.equals(synset)
&& ((WordSense) object).lemma.equals(lemma);
}
@Override
public int hashCode() {
return synset.hashCode() ^ lemma.hashCode();
}
@Override
public String toString() {
return new StringBuilder("[WordSense ").
append(synset.getOffset()).
append('@').
append(synset.getPOS()).
append(":\"").
append(getLemma()).
append("\"#").
append(getSenseNumber()).
append(']').toString();
}
/**
* {@inheritDoc}
*/
public int compareTo(final WordSense that) {
int result;
result = WordNetLexicalComparator.TO_LOWERCASE_INSTANCE.compare(this.getLemma(), that.getLemma());
if (result == 0) {
result = this.getSenseNumber() - that.getSenseNumber();
if (result == 0) {
result = this.getSynset().compareTo(that.getSynset());
}
}
return result;
}
} | renamed some package private stuff for clarity (flags -> adjPositionFlags)
| core/src/main/java/org/yawni/wn/WordSense.java | renamed some package private stuff for clarity (flags -> adjPositionFlags) | <ide><path>ore/src/main/java/org/yawni/wn/WordSense.java
<ide> private short senseNumber;
<ide> private short sensesTaggedFrequency;
<ide> // only needs to be a byte since there are only 3 bits of flag values
<del> private final byte flags;
<add> private final byte adjPositionFlags;
<ide>
<ide> //
<ide> // Constructor
<ide> this.lemma = lemma;
<ide> this.lexid = lexid;
<ide> assert flags < Byte.MAX_VALUE;
<del> this.flags = (byte) flags;
<add> this.adjPositionFlags = (byte) flags;
<ide> this.senseNumber = -1;
<ide> this.sensesTaggedFrequency = -1;
<ide> }
<ide> }
<ide>
<ide> /**
<del> * Returns the natural-cased lemma representation of this {@code WordSense}
<add> * Returns the natural-cased lemma representation of this {@code WordSense}.
<ide> * Its lemma is its orthographic representation, for example <tt>"dog"</tt>
<ide> * or <tt>"U.S.A."</tt> or <tt>"George Washington"</tt>. Contrast to the
<ide> * canonical lemma provided by {@link Word#getLemma()}.
<ide> return ImmutableList.of(this).iterator();
<ide> }
<ide>
<del> String flagsToString() {
<del> if (flags == 0) {
<add> String adjFlagsToString() {
<add> if (adjPositionFlags == 0) {
<ide> return "NONE";
<ide> }
<ide> final StringBuilder flagString = new StringBuilder();
<del> if (AdjPosition.isActive(AdjPosition.PREDICATIVE, flags)) {
<add> if (AdjPosition.isActive(AdjPosition.PREDICATIVE, adjPositionFlags)) {
<ide> flagString.append("predicative");
<ide> }
<del> if (AdjPosition.isActive(AdjPosition.ATTRIBUTIVE, flags)) {
<add> if (AdjPosition.isActive(AdjPosition.ATTRIBUTIVE, adjPositionFlags)) {
<ide> if (flagString.length() != 0) {
<ide> flagString.append(',');
<ide> }
<ide> // while the database files seem to indicate it as attributive
<ide> flagString.append("prenominal");
<ide> }
<del> if (AdjPosition.isActive(AdjPosition.IMMEDIATE_POSTNOMINAL, flags)) {
<add> if (AdjPosition.isActive(AdjPosition.IMMEDIATE_POSTNOMINAL, adjPositionFlags)) {
<ide> if (flagString.length() != 0) {
<ide> flagString.append(',');
<ide> }
<ide> * 1-indexed value whose order is relative to its {@link Word}.
<ide> *
<ide> * <p> Note that this value often varies across WordNet versions.
<del> * For those senses which never occured in sense tagged corpora, it is
<add> * For those senses which never occurred in sense tagged corpora, it is
<ide> * arbitrarily chosen.
<ide> * @see <a href="http://wordnet.princeton.edu/wordnet/man/cntlist.5WN.html#toc4">'NOTES' in cntlist WordNet documentation</a>
<ide> */
<ide> }
<ide>
<ide> /**
<del> * Use this <code>WordSense</code>'s lemma as key to find its <code>Word</code>.
<add> * Uses this <code>WordSense</code>'s lemma as key to find its <code>Word</code>.
<ide> */
<ide> // WordSense contains everything Word does - no need to expose this
<ide> Word getWord() {
<ide> }
<ide>
<ide> /**
<del> * <a href="http://wordnet.princeton.edu/wordnet/man/cntlist.5WN.html"><tt>cntlist</tt></a>
<add> * @see <a href="http://wordnet.princeton.edu/wordnet/man/cntlist.5WN.html"><tt>cntlist</tt></a>
<ide> */
<ide> public int getSensesTaggedFrequency() {
<ide> if (sensesTaggedFrequency < 0) {
<ide> * @see AdjPosition
<ide> */
<ide> public AdjPosition getAdjPosition() {
<del> if (flags == 0) {
<add> if (adjPositionFlags == 0) {
<ide> return AdjPosition.NONE;
<ide> }
<ide> assert getPOS() == POS.ADJ;
<del> if (AdjPosition.isActive(AdjPosition.PREDICATIVE, flags)) {
<del> assert false == AdjPosition.isActive(AdjPosition.ATTRIBUTIVE, flags);
<del> assert false == AdjPosition.isActive(AdjPosition.IMMEDIATE_POSTNOMINAL, flags);
<add> if (AdjPosition.isActive(AdjPosition.PREDICATIVE, adjPositionFlags)) {
<add> assert false == AdjPosition.isActive(AdjPosition.ATTRIBUTIVE, adjPositionFlags);
<add> assert false == AdjPosition.isActive(AdjPosition.IMMEDIATE_POSTNOMINAL, adjPositionFlags);
<ide> return AdjPosition.PREDICATIVE;
<ide> }
<del> if (AdjPosition.isActive(AdjPosition.ATTRIBUTIVE, flags)) {
<del> assert false == AdjPosition.isActive(AdjPosition.PREDICATIVE, flags);
<del> assert false == AdjPosition.isActive(AdjPosition.IMMEDIATE_POSTNOMINAL, flags);
<add> if (AdjPosition.isActive(AdjPosition.ATTRIBUTIVE, adjPositionFlags)) {
<add> assert false == AdjPosition.isActive(AdjPosition.PREDICATIVE, adjPositionFlags);
<add> assert false == AdjPosition.isActive(AdjPosition.IMMEDIATE_POSTNOMINAL, adjPositionFlags);
<ide> return AdjPosition.ATTRIBUTIVE;
<ide> }
<del> if (AdjPosition.isActive(AdjPosition.IMMEDIATE_POSTNOMINAL, flags)) {
<del> assert false == AdjPosition.isActive(AdjPosition.ATTRIBUTIVE, flags);
<del> assert false == AdjPosition.isActive(AdjPosition.PREDICATIVE, flags);
<add> if (AdjPosition.isActive(AdjPosition.IMMEDIATE_POSTNOMINAL, adjPositionFlags)) {
<add> assert false == AdjPosition.isActive(AdjPosition.ATTRIBUTIVE, adjPositionFlags);
<add> assert false == AdjPosition.isActive(AdjPosition.PREDICATIVE, adjPositionFlags);
<ide> return AdjPosition.IMMEDIATE_POSTNOMINAL;
<ide> }
<del> throw new IllegalStateException("invalid flags "+flags);
<add> throw new IllegalStateException("invalid flags "+adjPositionFlags);
<ide> }
<ide>
<ide> int getLexid() {
<ide> }
<ide>
<ide> // published as long, stored as byte for max efficiency
<del> long getFlags() {
<del> return flags;
<add> long getAdjPositionFlags() {
<add> return adjPositionFlags;
<ide> }
<ide>
<ide> //TODO expert only. maybe publish as EnumSet
<ide> return lemma;
<ide> }
<ide> final StringBuilder description = new StringBuilder(lemma);
<del> if (flags != 0) {
<add> if (adjPositionFlags != 0) {
<ide> description.append('(');
<del> description.append(flagsToString());
<add> description.append(adjFlagsToString());
<ide> description.append(')');
<ide> }
<ide> final List<RelationTarget> targets = getTargets(RelationType.ANTONYM);
<ide> // buffer.append(") ");
<ide> //}
<ide> buffer.append(getLemma());
<del> if (flags != 0) {
<add> if (adjPositionFlags != 0) {
<ide> buffer.append('(');
<del> buffer.append(flagsToString());
<add> buffer.append(adjFlagsToString());
<ide> buffer.append(')');
<ide> }
<ide> final String gloss = getSynset().getGloss(); |
|
Java | apache-2.0 | 931b55ee7e30b866d7226fd80ba550b16e8be3c0 | 0 | splunk/splunk-shuttl,splunk/splunk-shuttl,splunk/splunk-shuttl,splunk/splunk-shuttl,splunk/splunk-shuttl,splunk/splunk-shuttl | package com.splunk.shep.mapreduce.lib.rest;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import org.apache.commons.io.IOUtils;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TextInputFormat;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.splunk.Job;
import com.splunk.Service;
import com.splunk.shep.testutil.FileSystemUtils;
import com.splunk.shep.testutil.HadoopFileSystemPutter;
public class WordCountTest {
private static final String FILENAME_FOR_FILE_WITH_TEST_INPUT = "file01";
private static final String SOURCE = WordCountTest.class.getSimpleName();
private HadoopFileSystemPutter putter;
private File getLocalFileWithTestInput() {
String pathToFileWithTestInput = "test/java/com/splunk/shep/mapreduce/lib/rest"
+ "/" + FILENAME_FOR_FILE_WITH_TEST_INPUT;
return new File(pathToFileWithTestInput);
}
@BeforeMethod(groups = { "slow" })
public void setUp() {
FileSystem fileSystem = FileSystemUtils.getLocalFileSystem();
putter = HadoopFileSystemPutter.get(fileSystem);
}
@AfterMethod(groups = { "slow" })
public void tearDown() {
putter.deleteMyFiles();
}
@Parameters({ "splunk.username", "splunk.password" })
@Test(groups = { "slow" })
public void should_putDataInSplunk_when_runningAMapReduceJob_with_SplunkOutputFormat(
String splunkUsername, String splunkPassword) {
// Run hadoop
runHadoopWordCount(splunkUsername, splunkPassword);
// Verify in splunk
verifySplunk(splunkUsername, splunkPassword);
}
/**
* Hadoop MapReduce job -->
*/
private void runHadoopWordCount(String splunkUsername, String splunkPassword) {
JobConf mapReduceJob = getConfiguredJob(splunkUsername, splunkPassword);
configureJobInputAndOutputPaths(mapReduceJob);
runJob(mapReduceJob);
}
private JobConf getConfiguredJob(String splunkUsername,
String splunkPassword) {
JobConf conf = new JobConf(WordCountTest.class);
conf.setJobName(SOURCE);
SplunkConfiguration.setConnInfo(conf, "localhost", 8089,
splunkUsername, splunkPassword);
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(IntWritable.class);
conf.setMapperClass(Map.class);
conf.setCombinerClass(Reduce.class);
conf.setReducerClass(Reduce.class);
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(SplunkOutputFormat.class);
return conf;
}
private void configureJobInputAndOutputPaths(JobConf conf) {
Path inputFile = getFileOnHadoopWithTestInput();
Path outputFile = getJobOutputFile();
FileInputFormat.setInputPaths(conf, inputFile);
FileOutputFormat.setOutputPath(conf, outputFile);
}
private Path getFileOnHadoopWithTestInput() {
File localFile = getLocalFileWithTestInput();
putter.putFile(localFile);
Path remoteFile = putter.getPathForFile(localFile);
return remoteFile;
}
private Path getJobOutputFile() {
Path remoteDir = putter.getPathWhereMyFilesAreStored();
Path outputFile = new Path(remoteDir, "output");
return outputFile;
}
private void runJob(JobConf conf) {
try {
JobClient.runJob(conf);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Splunk verification -->
*/
private void verifySplunk(String splunkUsername, String splunkPassword) {
List<String> searchResults = getSearchResultsFromSplunk(splunkUsername,
splunkPassword);
assertFalse(searchResults.isEmpty());
verifyWordCountInSearchResults(searchResults);
}
private List<String> getSearchResultsFromSplunk(String splunkUsername,
String splunkPassword) {
// TODO: OMG! LOCALHOST AND PORT MUST BE CONFIGURED!
Service service = getLoggedInSplunkService(splunkUsername,
splunkPassword);
Job search = startSearch(service);
waitWhileSearchFinishes(search);
InputStream results = search.getResults();
return readResults(results);
}
private Service getLoggedInSplunkService(String splunkUsername,
String splunkPassword) {
Service service = new Service("localhost", 8089);
service.login(splunkUsername, splunkPassword);
return service;
}
private Job startSearch(Service service) {
String search = "search index=main source=\"" + SOURCE
+ "\" sourcetype=\"hadoop_event\" |"
+ " rex \"(?i)^(?:[^ ]* ){6}(?P<FIELDNAME>.+)\" |"
+ " table FIELDNAME | tail 5";
Job job = service.getJobs().create(search);
System.out.println("Splunk search: " + search);
return job;
}
private void waitWhileSearchFinishes(Job job) {
while (!job.isDone()) {
sleep(10);
job.refresh();
}
}
private List<String> readResults(InputStream results) {
try {
return IOUtils.readLines(results);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void verifyWordCountInSearchResults(List<String> searchResults) {
StringBuffer mergedLines = new StringBuffer();
for (String result : searchResults)
mergedLines.append(result);
Set<String> expectedWordCount = getExpectedWordCount();
for (String wordCount : expectedWordCount)
assertTrue(mergedLines.toString().contains(wordCount));
}
private Set<String> getExpectedWordCount() {
Set<String> expectedWordCountResults = new HashSet<String>();
expectedWordCountResults.add("Bye 1");
expectedWordCountResults.add("Goodbye 1");
expectedWordCountResults.add("Hadoop 2");
expectedWordCountResults.add("Hello 2");
expectedWordCountResults.add("World 2");
return expectedWordCountResults;
}
private void sleep(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public static class Map extends MapReduceBase implements
Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(LongWritable key, Text value,
OutputCollector<Text, IntWritable> output, Reporter reporter)
throws IOException {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
word.set(tokenizer.nextToken());
output.collect(word, one);
}
}
}
public static class Reduce extends MapReduceBase implements
Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterator<IntWritable> values,
OutputCollector<Text, IntWritable> output, Reporter reporter)
throws IOException {
int sum = 0;
while (values.hasNext()) {
sum += values.next().get();
}
output.collect(key, new IntWritable(sum));
}
}
}
| test/java/com/splunk/shep/mapreduce/lib/rest/WordCountTest.java | package com.splunk.shep.mapreduce.lib.rest;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.StringTokenizer;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TextInputFormat;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.splunk.shep.mapreduce.lib.rest.tests.WordCount;
import com.splunk.shep.testutil.FileSystemUtils;
import com.splunk.shep.testutil.HadoopFileSystemPutter;
public class WordCountTest {
private static final String FILENAME_FOR_FILE_WITH_TEST_INPUT = "file01";
private HadoopFileSystemPutter putter;
private File getLocalFileWithTestInput() {
String pathToFileWithTestInput = "test/java/com/splunk/shep/mapreduce/lib/rest"
+ "/" + FILENAME_FOR_FILE_WITH_TEST_INPUT;
return new File(pathToFileWithTestInput);
}
@BeforeMethod(groups = { "slow" })
public void setUp() {
FileSystem fileSystem = FileSystemUtils.getLocalFileSystem();
putter = HadoopFileSystemPutter.get(fileSystem);
}
@AfterMethod(groups = { "slow" })
public void tearDown() {
putter.deleteMyFiles();
}
@Parameters({ "splunk.username", "splunk.password" })
@Test(groups = { "slow" })
public void fileCheck(String splunkUsername, String splunkPassword)
throws IOException {
JobConf conf = new JobConf(WordCount.class);
conf.setJobName("hadoopunittest1");
SplunkConfiguration.setConnInfo(conf, "localhost", 8089,
splunkUsername, splunkPassword);
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(IntWritable.class);
conf.setMapperClass(Map.class);
conf.setCombinerClass(Reduce.class);
conf.setReducerClass(Reduce.class);
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(SplunkOutputFormat.class);
File localFile = getLocalFileWithTestInput();
putter.putFile(localFile);
Path remoteFile = putter.getPathForFile(localFile);
Path remoteDir = putter.getPathWhereMyFilesAreStored();
Path outputFile = new Path(remoteDir, "output");
FileInputFormat.setInputPaths(conf, remoteFile);
FileOutputFormat.setOutputPath(conf, outputFile);
JobClient.runJob(conf);
}
public static class Map extends MapReduceBase implements
Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(LongWritable key, Text value,
OutputCollector<Text, IntWritable> output, Reporter reporter)
throws IOException {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
word.set(tokenizer.nextToken());
output.collect(word, one);
}
}
}
public static class Reduce extends MapReduceBase implements
Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterator<IntWritable> values,
OutputCollector<Text, IntWritable> output, Reporter reporter)
throws IOException {
int sum = 0;
while (values.hasNext()) {
sum += values.next().get();
}
output.collect(key, new IntWritable(sum));
}
}
}
| Added Splunk verification to WordCountTest. Refactored a lot of the code too. | test/java/com/splunk/shep/mapreduce/lib/rest/WordCountTest.java | Added Splunk verification to WordCountTest. Refactored a lot of the code too. | <ide><path>est/java/com/splunk/shep/mapreduce/lib/rest/WordCountTest.java
<ide> package com.splunk.shep.mapreduce.lib.rest;
<add>
<add>import static org.testng.AssertJUnit.assertFalse;
<add>import static org.testng.AssertJUnit.assertTrue;
<ide>
<ide> import java.io.File;
<ide> import java.io.IOException;
<add>import java.io.InputStream;
<add>import java.util.HashSet;
<ide> import java.util.Iterator;
<add>import java.util.List;
<add>import java.util.Set;
<ide> import java.util.StringTokenizer;
<ide>
<add>import org.apache.commons.io.IOUtils;
<ide> import org.apache.hadoop.fs.FileSystem;
<ide> import org.apache.hadoop.fs.Path;
<ide> import org.apache.hadoop.io.IntWritable;
<ide> import org.testng.annotations.Parameters;
<ide> import org.testng.annotations.Test;
<ide>
<del>import com.splunk.shep.mapreduce.lib.rest.tests.WordCount;
<add>import com.splunk.Job;
<add>import com.splunk.Service;
<ide> import com.splunk.shep.testutil.FileSystemUtils;
<ide> import com.splunk.shep.testutil.HadoopFileSystemPutter;
<ide>
<ide> public class WordCountTest {
<ide>
<ide> private static final String FILENAME_FOR_FILE_WITH_TEST_INPUT = "file01";
<add> private static final String SOURCE = WordCountTest.class.getSimpleName();
<ide>
<ide> private HadoopFileSystemPutter putter;
<ide>
<ide>
<ide> @Parameters({ "splunk.username", "splunk.password" })
<ide> @Test(groups = { "slow" })
<del> public void fileCheck(String splunkUsername, String splunkPassword)
<del> throws IOException {
<del> JobConf conf = new JobConf(WordCount.class);
<del> conf.setJobName("hadoopunittest1");
<add> public void should_putDataInSplunk_when_runningAMapReduceJob_with_SplunkOutputFormat(
<add> String splunkUsername, String splunkPassword) {
<add> // Run hadoop
<add> runHadoopWordCount(splunkUsername, splunkPassword);
<add>
<add> // Verify in splunk
<add> verifySplunk(splunkUsername, splunkPassword);
<add> }
<add>
<add> /**
<add> * Hadoop MapReduce job -->
<add> */
<add> private void runHadoopWordCount(String splunkUsername, String splunkPassword) {
<add> JobConf mapReduceJob = getConfiguredJob(splunkUsername, splunkPassword);
<add> configureJobInputAndOutputPaths(mapReduceJob);
<add> runJob(mapReduceJob);
<add> }
<add>
<add> private JobConf getConfiguredJob(String splunkUsername,
<add> String splunkPassword) {
<add> JobConf conf = new JobConf(WordCountTest.class);
<add> conf.setJobName(SOURCE);
<ide> SplunkConfiguration.setConnInfo(conf, "localhost", 8089,
<ide> splunkUsername, splunkPassword);
<ide>
<ide> conf.setOutputKeyClass(Text.class);
<ide> conf.setOutputValueClass(IntWritable.class);
<del>
<ide> conf.setMapperClass(Map.class);
<ide> conf.setCombinerClass(Reduce.class);
<ide> conf.setReducerClass(Reduce.class);
<del>
<ide> conf.setInputFormat(TextInputFormat.class);
<ide> conf.setOutputFormat(SplunkOutputFormat.class);
<ide>
<add> return conf;
<add> }
<add>
<add> private void configureJobInputAndOutputPaths(JobConf conf) {
<add> Path inputFile = getFileOnHadoopWithTestInput();
<add> Path outputFile = getJobOutputFile();
<add>
<add> FileInputFormat.setInputPaths(conf, inputFile);
<add> FileOutputFormat.setOutputPath(conf, outputFile);
<add> }
<add>
<add> private Path getFileOnHadoopWithTestInput() {
<ide> File localFile = getLocalFileWithTestInput();
<ide> putter.putFile(localFile);
<ide> Path remoteFile = putter.getPathForFile(localFile);
<add> return remoteFile;
<add> }
<add>
<add> private Path getJobOutputFile() {
<ide> Path remoteDir = putter.getPathWhereMyFilesAreStored();
<ide> Path outputFile = new Path(remoteDir, "output");
<del>
<del> FileInputFormat.setInputPaths(conf, remoteFile);
<del> FileOutputFormat.setOutputPath(conf, outputFile);
<del>
<del> JobClient.runJob(conf);
<add> return outputFile;
<add> }
<add>
<add> private void runJob(JobConf conf) {
<add> try {
<add> JobClient.runJob(conf);
<add> } catch (IOException e) {
<add> throw new RuntimeException(e);
<add> }
<add> }
<add>
<add> /**
<add> * Splunk verification -->
<add> */
<add> private void verifySplunk(String splunkUsername, String splunkPassword) {
<add> List<String> searchResults = getSearchResultsFromSplunk(splunkUsername,
<add> splunkPassword);
<add> assertFalse(searchResults.isEmpty());
<add> verifyWordCountInSearchResults(searchResults);
<add> }
<add>
<add> private List<String> getSearchResultsFromSplunk(String splunkUsername,
<add> String splunkPassword) {
<add> // TODO: OMG! LOCALHOST AND PORT MUST BE CONFIGURED!
<add> Service service = getLoggedInSplunkService(splunkUsername,
<add> splunkPassword);
<add> Job search = startSearch(service);
<add> waitWhileSearchFinishes(search);
<add> InputStream results = search.getResults();
<add> return readResults(results);
<add> }
<add>
<add> private Service getLoggedInSplunkService(String splunkUsername,
<add> String splunkPassword) {
<add> Service service = new Service("localhost", 8089);
<add> service.login(splunkUsername, splunkPassword);
<add> return service;
<add> }
<add>
<add> private Job startSearch(Service service) {
<add> String search = "search index=main source=\"" + SOURCE
<add> + "\" sourcetype=\"hadoop_event\" |"
<add> + " rex \"(?i)^(?:[^ ]* ){6}(?P<FIELDNAME>.+)\" |"
<add> + " table FIELDNAME | tail 5";
<add> Job job = service.getJobs().create(search);
<add> System.out.println("Splunk search: " + search);
<add> return job;
<add> }
<add>
<add> private void waitWhileSearchFinishes(Job job) {
<add> while (!job.isDone()) {
<add> sleep(10);
<add> job.refresh();
<add> }
<add> }
<add>
<add> private List<String> readResults(InputStream results) {
<add> try {
<add> return IOUtils.readLines(results);
<add> } catch (IOException e) {
<add> throw new RuntimeException(e);
<add> }
<add> }
<add>
<add> private void verifyWordCountInSearchResults(List<String> searchResults) {
<add> StringBuffer mergedLines = new StringBuffer();
<add> for (String result : searchResults)
<add> mergedLines.append(result);
<add> Set<String> expectedWordCount = getExpectedWordCount();
<add> for (String wordCount : expectedWordCount)
<add> assertTrue(mergedLines.toString().contains(wordCount));
<add> }
<add>
<add> private Set<String> getExpectedWordCount() {
<add> Set<String> expectedWordCountResults = new HashSet<String>();
<add> expectedWordCountResults.add("Bye 1");
<add> expectedWordCountResults.add("Goodbye 1");
<add> expectedWordCountResults.add("Hadoop 2");
<add> expectedWordCountResults.add("Hello 2");
<add> expectedWordCountResults.add("World 2");
<add> return expectedWordCountResults;
<add> }
<add>
<add> private void sleep(int millis) {
<add> try {
<add> Thread.sleep(millis);
<add> } catch (InterruptedException e) {
<add> throw new RuntimeException(e);
<add> }
<ide> }
<ide>
<ide> public static class Map extends MapReduceBase implements |
|
Java | apache-2.0 | error: pathspec 'routelandia/src/main/java/edu/pdx/its/portal/routelandia/DownloadListofHighway.java' did not match any file(s) known to git
| db715776035a925b71a3a90b293a48728645e809 | 1 | Routelandia/routelandia-android,Routelandia/routelandia-android | /*
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 edu.pdx.its.portal.routelandia;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Created by loc on 2/6/15.
*/
public class DownloadListofHighway extends AsyncTask<String, Void, String> {
protected List<Highway> highwayList = new ArrayList<>();
/**
* Override this method to perform a computation on a background thread. The
* specified parameters are the parameters passed to {@link #execute}
* by the caller of this task.
* <p/>
* This method can call {@link #publishProgress} to publish updates
* on the UI thread.
*
* @param params The parameters of the task.
* @return A result, defined by the subclass of this task.
* @see #onPreExecute()
* @see #onPostExecute
* @see #publishProgress
*/
@Override
protected String doInBackground(String... params) {
String resultDownloadFromTheWeb = "";
try{
resultDownloadFromTheWeb = downloadListofHighwayFromTheAPI(params[0]);
} catch (IOException e) {
e.printStackTrace();
}
return resultDownloadFromTheWeb;
}
/**
* <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 s The result of the operation computed by {@link #doInBackground}.
* @see #onPreExecute
* @see #doInBackground
* @see #onCancelled(Object)
*/
// @Override
// protected void onPostExecute(String s) {
// super.onPostExecute(s);
// ParserListofHighway parserListofHighway = new ParserListofHighway();
//
// parserListofHighway.execute(s);
// }
/**
* A method to download json data from url
* @param stringURL is the URL API endpoint to download the highway information
* @return the string json
* @throws java.io.IOException
*/
private String downloadListofHighwayFromTheAPI(String stringURL) throws IOException {
String data = "";
InputStream iStream;
HttpURLConnection urlConnection;
try {
URL url = new URL(stringURL);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Create bufferedReader from input
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(iStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
//append all line from buffered Reader into string builder
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
//convert the string builder into string and update its for data
data = stringBuilder.toString();
//close the buffered reader
bufferedReader.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
}
return data;
}
}
| routelandia/src/main/java/edu/pdx/its/portal/routelandia/DownloadListofHighway.java | add class to create thread in order to download the list of json from API
| routelandia/src/main/java/edu/pdx/its/portal/routelandia/DownloadListofHighway.java | add class to create thread in order to download the list of json from API | <ide><path>outelandia/src/main/java/edu/pdx/its/portal/routelandia/DownloadListofHighway.java
<add>/*
<add> Licensed under the Apache License, Version 2.0 (the "License");
<add> you may not use this file except in compliance with the License.
<add> You may obtain a copy of the License at
<add>
<add> http://www.apache.org/licenses/LICENSE-2.0
<add>
<add> Unless required by applicable law or agreed to in writing, software
<add> distributed under the License is distributed on an "AS IS" BASIS,
<add> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> See the License for the specific language governing permissions and
<add> limitations under the License.
<add>*/
<add>
<add>package edu.pdx.its.portal.routelandia;
<add>
<add>import android.os.AsyncTask;
<add>import android.util.Log;
<add>
<add>import java.io.BufferedReader;
<add>import java.io.IOException;
<add>import java.io.InputStream;
<add>import java.io.InputStreamReader;
<add>import java.net.HttpURLConnection;
<add>import java.net.URL;
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>
<add>/**
<add> * Created by loc on 2/6/15.
<add> */
<add>public class DownloadListofHighway extends AsyncTask<String, Void, String> {
<add>
<add> protected List<Highway> highwayList = new ArrayList<>();
<add>
<add> /**
<add> * Override this method to perform a computation on a background thread. The
<add> * specified parameters are the parameters passed to {@link #execute}
<add> * by the caller of this task.
<add> * <p/>
<add> * This method can call {@link #publishProgress} to publish updates
<add> * on the UI thread.
<add> *
<add> * @param params The parameters of the task.
<add> * @return A result, defined by the subclass of this task.
<add> * @see #onPreExecute()
<add> * @see #onPostExecute
<add> * @see #publishProgress
<add> */
<add> @Override
<add> protected String doInBackground(String... params) {
<add> String resultDownloadFromTheWeb = "";
<add>
<add> try{
<add> resultDownloadFromTheWeb = downloadListofHighwayFromTheAPI(params[0]);
<add> } catch (IOException e) {
<add> e.printStackTrace();
<add> }
<add>
<add> return resultDownloadFromTheWeb;
<add> }
<add>
<add> /**
<add> * <p>Runs on the UI thread after {@link #doInBackground}. The
<add> * specified result is the value returned by {@link #doInBackground}.</p>
<add> * <p/>
<add> * <p>This method won't be invoked if the task was cancelled.</p>
<add> *
<add> * @param s The result of the operation computed by {@link #doInBackground}.
<add> * @see #onPreExecute
<add> * @see #doInBackground
<add> * @see #onCancelled(Object)
<add> */
<add>// @Override
<add>// protected void onPostExecute(String s) {
<add>// super.onPostExecute(s);
<add>// ParserListofHighway parserListofHighway = new ParserListofHighway();
<add>//
<add>// parserListofHighway.execute(s);
<add>// }
<add>
<add> /**
<add> * A method to download json data from url
<add> * @param stringURL is the URL API endpoint to download the highway information
<add> * @return the string json
<add> * @throws java.io.IOException
<add> */
<add> private String downloadListofHighwayFromTheAPI(String stringURL) throws IOException {
<add> String data = "";
<add> InputStream iStream;
<add> HttpURLConnection urlConnection;
<add>
<add> try {
<add> URL url = new URL(stringURL);
<add>
<add> // Creating an http connection to communicate with url
<add> urlConnection = (HttpURLConnection) url.openConnection();
<add>
<add> // Connecting to url
<add> urlConnection.connect();
<add>
<add> // Reading data from url
<add> iStream = urlConnection.getInputStream();
<add>
<add> // Create bufferedReader from input
<add> BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(iStream));
<add>
<add> StringBuilder stringBuilder = new StringBuilder();
<add>
<add> String line;
<add>
<add> //append all line from buffered Reader into string builder
<add> while ((line = bufferedReader.readLine()) != null) {
<add> stringBuilder.append(line);
<add> }
<add>
<add> //convert the string builder into string and update its for data
<add> data = stringBuilder.toString();
<add>
<add> //close the buffered reader
<add> bufferedReader.close();
<add>
<add> } catch (Exception e) {
<add> Log.d("Exception while downloading url", e.toString());
<add> }
<add>
<add> return data;
<add> }
<add>} |
|
Java | mit | 204892a509a179bc9858eec47b6f54e12c1c2ef6 | 0 | elimu-ai/webapp,literacyapp-org/literacyapp-web,literacyapp-org/literacyapp-web,elimu-ai/webapp,elimu-ai/webapp,literacyapp-org/literacyapp-web,literacyapp-org/literacyapp-web,elimu-ai/webapp | package ai.elimu.rest.v2.crowdsource;
import ai.elimu.dao.ContributorDao;
import ai.elimu.dao.WordContributionEventDao;
import ai.elimu.dao.WordDao;
import ai.elimu.dao.WordPeerReviewEventDao;
import ai.elimu.model.content.Word;
import ai.elimu.model.contributor.*;
import ai.elimu.model.enums.PeerReviewStatus;
import ai.elimu.model.v2.gson.crowdsource.WordContributionEventGson;
import ai.elimu.model.v2.gson.crowdsource.WordPeerReviewEventGson;
import ai.elimu.rest.v2.JpaToGsonConverter;
import ai.elimu.util.SlackHelper;
import ai.elimu.web.content.word.WordPeerReviewsController;
import ai.elimu.web.context.EnvironmentContextLoaderListener;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
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.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.List;
/**
* REST API for the Crowdsource application: https://github.com/elimu-ai/crowdsource
* <p>
* <p>
* This controller has similar functionality as the {@link WordPeerReviewsController}.
*/
@RestController
@RequestMapping(value = "/rest/v2/crowdsource/word-peer-reviews", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class WordPeerReviewsRestController {
private Logger logger = LogManager.getLogger();
@Autowired
private WordContributionEventDao wordContributionEventDao;
@Autowired
private ContributorDao contributorDao;
@Autowired
private WordPeerReviewEventDao wordPeerReviewEventDao;
@Autowired
private WordDao wordDao;
/**
* Get {@link WordContributionEvent}s pending a {@link WordPeerReviewEvent} for the current {@link Contributor}.
* <p>
* Note: Currently The list of Emojis are not delivered in this method compared to the handleGetRequest method in
* {@link WordPeerReviewsController}
*/
@RequestMapping(method = RequestMethod.GET)
public String handleGetRequest(HttpServletRequest request,
HttpServletResponse response) {
logger.info("handleGetRequest");
// Validate the Contributor.
JSONObject jsonObject = new JSONObject();
String providerIdGoogle = request.getHeader("providerIdGoogle");
logger.info("providerIdGoogle: " + providerIdGoogle);
if (StringUtils.isBlank(providerIdGoogle)) {
jsonObject.put("result", "error");
jsonObject.put("errorMessage", "Missing providerIdGoogle");
response.setStatus(HttpStatus.BAD_REQUEST.value());
String jsonResponse = jsonObject.toString();
logger.info("jsonResponse: " + jsonResponse);
return jsonResponse;
}
// Lookup the Contributor by ID
Contributor contributor = contributorDao.readByProviderIdGoogle(providerIdGoogle);
logger.info("contributor: " + contributor);
if (contributor == null) {
jsonObject.put("result", "error");
jsonObject.put("errorMessage", "The Contributor was not found.");
response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
String jsonResponse = jsonObject.toString();
logger.info("jsonResponse: " + jsonResponse);
return jsonResponse;
}
// Get the most recent WordContributionEvent for each Word, including those made by the current Contributor
List<WordContributionEvent> mostRecentWordContributionEvents = wordContributionEventDao.readMostRecentPerWord();
logger.info("mostRecentWordContributionEvents.size(): " + mostRecentWordContributionEvents.size());
// For each WordContributionEvent, check if the Contributor has already performed a peer-review.
// If not, add it to the list of pending peer reviews.
JSONArray wordContributionEventsPendingPeerReviewJsonArray = new JSONArray();
for (WordContributionEvent mostRecentWordContributionEvent : mostRecentWordContributionEvents) {
// Ignore WordContributionEvents made by the current Contributor
if (mostRecentWordContributionEvent.getContributor().getId().equals(contributor.getId())) {
continue;
}
// Check if the current Contributor has already peer-reviewed this Word contribution
List<WordPeerReviewEvent> wordPeerReviewEvents = wordPeerReviewEventDao.
readAll(mostRecentWordContributionEvent, contributor);
if (wordPeerReviewEvents.isEmpty()) {
WordContributionEventGson mostRecentWordContributionEventGson = JpaToGsonConverter.
getWordContributionEventGson(mostRecentWordContributionEvent);
String json = new Gson().toJson(mostRecentWordContributionEventGson);
wordContributionEventsPendingPeerReviewJsonArray.put(new JSONObject(json));
}
}
logger.info("wordContributionEventsPendingPeerReviewJsonArray.size(): " +
wordContributionEventsPendingPeerReviewJsonArray.length());
String jsonResponse = wordContributionEventsPendingPeerReviewJsonArray.toString();
logger.info("jsonResponse: " + jsonResponse);
return jsonResponse;
}
@RequestMapping(method = RequestMethod.POST)
public String handlePostRequest(HttpServletRequest request,
HttpServletResponse response,
@RequestBody String requestBody) {
logger.info("handlePostRequest");
// Validate the Contributor.
JSONObject jsonObject = new JSONObject();
String providerIdGoogle = request.getHeader("providerIdGoogle");
logger.info("providerIdGoogle: " + providerIdGoogle);
if (StringUtils.isBlank(providerIdGoogle)) {
jsonObject.put("result", "error");
jsonObject.put("errorMessage", "Missing providerIdGoogle");
response.setStatus(HttpStatus.BAD_REQUEST.value());
String jsonResponse = jsonObject.toString();
logger.info("jsonResponse: " + jsonResponse);
return jsonResponse;
}
// Lookup the Contributor by ID
Contributor contributor = contributorDao.readByProviderIdGoogle(providerIdGoogle);
logger.info("contributor: " + contributor);
if (contributor == null) {
jsonObject.put("result", "error");
jsonObject.put("errorMessage", "The Contributor was not found.");
response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
String jsonResponse = jsonObject.toString();
logger.info("jsonResponse: " + jsonResponse);
return jsonResponse;
}
try {
// Convert from Gson (POJO) to JPA/Hibernate
logger.info("requestBody: " + requestBody);
WordPeerReviewEventGson wordPeerReviewEventGson = new Gson().fromJson(requestBody, WordPeerReviewEventGson.class);
WordContributionEvent wordContributionEvent = wordContributionEventDao.read(wordPeerReviewEventGson
.getWordContributionEvent().getId());
WordPeerReviewEvent wordPeerReviewEvent = new WordPeerReviewEvent();
wordPeerReviewEvent.setContributor(contributor);
wordPeerReviewEvent.setWordContributionEvent(wordContributionEvent);
wordPeerReviewEvent.setApproved(wordPeerReviewEventGson.isApproved());
wordPeerReviewEvent.setComment(wordPeerReviewEventGson.getComment());
wordPeerReviewEvent.setTime(Calendar.getInstance());
wordPeerReviewEventDao.create(wordPeerReviewEvent);
String contentUrl = "http://" + EnvironmentContextLoaderListener.PROPERTIES.getProperty("content.language").toLowerCase() + ".elimu.ai/content/word/edit/" + wordContributionEvent.getWord().getId();
SlackHelper.postChatMessage("Word peer-reviewed: " + contentUrl);
// Update the word's peer review status
int approvedCount = 0;
int notApprovedCount = 0;
for (WordPeerReviewEvent peerReviewEvent : wordPeerReviewEventDao.readAll(wordContributionEvent)) {
if (peerReviewEvent.isApproved()) {
approvedCount++;
} else {
notApprovedCount++;
}
}
logger.info("approvedCount: " + approvedCount);
logger.info("notApprovedCount: " + notApprovedCount);
Word word = wordContributionEvent.getWord();
if (approvedCount >= notApprovedCount) {
word.setPeerReviewStatus(PeerReviewStatus.APPROVED);
} else {
word.setPeerReviewStatus(PeerReviewStatus.NOT_APPROVED);
}
wordDao.update(word);
} catch (Exception ex) {
logger.error(ex);
jsonObject.put("result", "error");
jsonObject.put("errorMessage", ex.getMessage());
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
}
String jsonResponse = jsonObject.toString();
logger.info("jsonResponse: " + jsonResponse);
response.setStatus(HttpStatus.CREATED.value());
return jsonResponse;
}
}
| src/main/java/ai/elimu/rest/v2/crowdsource/WordPeerReviewsRestController.java | package ai.elimu.rest.v2.crowdsource;
import ai.elimu.dao.ContributorDao;
import ai.elimu.dao.WordContributionEventDao;
import ai.elimu.dao.WordDao;
import ai.elimu.dao.WordPeerReviewEventDao;
import ai.elimu.model.content.Word;
import ai.elimu.model.contributor.*;
import ai.elimu.model.v2.enums.PeerReviewStatus;
import ai.elimu.model.v2.gson.crowdsource.WordContributionEventGson;
import ai.elimu.model.v2.gson.crowdsource.WordPeerReviewEventGson;
import ai.elimu.rest.v2.JpaToGsonConverter;
import ai.elimu.util.SlackHelper;
import ai.elimu.web.content.word.WordPeerReviewsController;
import ai.elimu.web.context.EnvironmentContextLoaderListener;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
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.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.List;
/**
* REST API for the Crowdsource application: https://github.com/elimu-ai/crowdsource
* <p>
* <p>
* This controller has similar functionality as the {@link WordPeerReviewsController}.
*/
@RestController
@RequestMapping(value = "/rest/v2/crowdsource/word-peer-reviews", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class WordPeerReviewsRestController {
private Logger logger = LogManager.getLogger();
@Autowired
private WordContributionEventDao wordContributionEventDao;
@Autowired
private ContributorDao contributorDao;
@Autowired
private WordPeerReviewEventDao wordPeerReviewEventDao;
@Autowired
private WordDao wordDao;
/**
* Get {@link WordContributionEvent}s pending a {@link WordPeerReviewEvent} for the current {@link Contributor}.
* <p>
* Note: Currently The list of Emojis are not delivered in this method compared to the handleGetRequest method in
* {@link WordPeerReviewsController}
*/
@RequestMapping(method = RequestMethod.GET)
public String handleGetRequest(HttpServletRequest request,
HttpServletResponse response) {
logger.info("handleGetRequest");
// Validate the Contributor.
JSONObject jsonObject = new JSONObject();
String providerIdGoogle = request.getHeader("providerIdGoogle");
logger.info("providerIdGoogle: " + providerIdGoogle);
if (StringUtils.isBlank(providerIdGoogle)) {
jsonObject.put("result", "error");
jsonObject.put("errorMessage", "Missing providerIdGoogle");
response.setStatus(HttpStatus.BAD_REQUEST.value());
String jsonResponse = jsonObject.toString();
logger.info("jsonResponse: " + jsonResponse);
return jsonResponse;
}
// Lookup the Contributor by ID
Contributor contributor = contributorDao.readByProviderIdGoogle(providerIdGoogle);
logger.info("contributor: " + contributor);
if (contributor == null) {
jsonObject.put("result", "error");
jsonObject.put("errorMessage", "The Contributor was not found.");
response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
String jsonResponse = jsonObject.toString();
logger.info("jsonResponse: " + jsonResponse);
return jsonResponse;
}
// Get the most recent WordContributionEvent for each Word, including those made by the current Contributor
List<WordContributionEvent> mostRecentWordContributionEvents = wordContributionEventDao.readMostRecentPerWord();
logger.info("mostRecentWordContributionEvents.size(): " + mostRecentWordContributionEvents.size());
// For each WordContributionEvent, check if the Contributor has already performed a peer-review.
// If not, add it to the list of pending peer reviews.
JSONArray wordContributionEventsPendingPeerReviewJsonArray = new JSONArray();
for (WordContributionEvent mostRecentWordContributionEvent : mostRecentWordContributionEvents) {
// Ignore WordContributionEvents made by the current Contributor
if (mostRecentWordContributionEvent.getContributor().getId().equals(contributor.getId())) {
continue;
}
// Check if the current Contributor has already peer-reviewed this Word contribution
List<WordPeerReviewEvent> wordPeerReviewEvents = wordPeerReviewEventDao.
readAll(mostRecentWordContributionEvent, contributor);
if (wordPeerReviewEvents.isEmpty()) {
WordContributionEventGson mostRecentWordContributionEventGson = JpaToGsonConverter.
getWordContributionEventGson(mostRecentWordContributionEvent);
String json = new Gson().toJson(mostRecentWordContributionEventGson);
wordContributionEventsPendingPeerReviewJsonArray.put(new JSONObject(json));
}
}
logger.info("wordContributionEventsPendingPeerReviewJsonArray.size(): " +
wordContributionEventsPendingPeerReviewJsonArray.length());
String jsonResponse = wordContributionEventsPendingPeerReviewJsonArray.toString();
logger.info("jsonResponse: " + jsonResponse);
return jsonResponse;
}
@RequestMapping(method = RequestMethod.POST)
public String handlePostRequest(HttpServletRequest request,
HttpServletResponse response,
@RequestBody String requestBody) {
logger.info("handlePostRequest");
// Validate the Contributor.
JSONObject jsonObject = new JSONObject();
String providerIdGoogle = request.getHeader("providerIdGoogle");
logger.info("providerIdGoogle: " + providerIdGoogle);
if (StringUtils.isBlank(providerIdGoogle)) {
jsonObject.put("result", "error");
jsonObject.put("errorMessage", "Missing providerIdGoogle");
response.setStatus(HttpStatus.BAD_REQUEST.value());
String jsonResponse = jsonObject.toString();
logger.info("jsonResponse: " + jsonResponse);
return jsonResponse;
}
// Lookup the Contributor by ID
Contributor contributor = contributorDao.readByProviderIdGoogle(providerIdGoogle);
logger.info("contributor: " + contributor);
if (contributor == null) {
jsonObject.put("result", "error");
jsonObject.put("errorMessage", "The Contributor was not found.");
response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
String jsonResponse = jsonObject.toString();
logger.info("jsonResponse: " + jsonResponse);
return jsonResponse;
}
try {
// Convert from Gson (POJO) to JPA/Hibernate
logger.info("requestBody: " + requestBody);
WordPeerReviewEventGson wordPeerReviewEventGson = new Gson().fromJson(requestBody, WordPeerReviewEventGson.class);
WordContributionEvent wordContributionEvent = wordContributionEventDao.read(wordPeerReviewEventGson
.getWordContributionEvent().getId());
WordPeerReviewEvent wordPeerReviewEvent = new WordPeerReviewEvent();
wordPeerReviewEvent.setContributor(contributor);
wordPeerReviewEvent.setWordContributionEvent(wordContributionEvent);
wordPeerReviewEvent.setApproved(wordPeerReviewEventGson.isApproved());
wordPeerReviewEvent.setComment(wordPeerReviewEventGson.getComment());
wordPeerReviewEvent.setTime(Calendar.getInstance());
wordPeerReviewEventDao.create(wordPeerReviewEvent);
String contentUrl = "http://" + EnvironmentContextLoaderListener.PROPERTIES.getProperty("content.language").toLowerCase() + ".elimu.ai/content/word/edit/" + wordContributionEvent.getWord().getId();
SlackHelper.postChatMessage("Word peer-reviewed: " + contentUrl);
// Update the word's peer review status
int approvedCount = 0;
int notApprovedCount = 0;
for (WordPeerReviewEvent peerReviewEvent : wordPeerReviewEventDao.readAll(wordContributionEvent)) {
if (peerReviewEvent.isApproved()) {
approvedCount++;
} else {
notApprovedCount++;
}
}
logger.info("approvedCount: " + approvedCount);
logger.info("notApprovedCount: " + notApprovedCount);
Word word = wordContributionEvent.getWord();
if (approvedCount >= notApprovedCount) {
word.setPeerReviewStatus(PeerReviewStatus.APPROVED);
} else {
word.setPeerReviewStatus(PeerReviewStatus.NOT_APPROVED);
}
wordDao.update(word);
} catch (Exception ex) {
logger.error(ex);
jsonObject.put("result", "error");
jsonObject.put("errorMessage", ex.getMessage());
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
}
String jsonResponse = jsonObject.toString();
logger.info("jsonResponse: " + jsonResponse);
response.setStatus(HttpStatus.CREATED.value());
return jsonResponse;
}
}
| fix issue with importing PeerReviewStatus
| src/main/java/ai/elimu/rest/v2/crowdsource/WordPeerReviewsRestController.java | fix issue with importing PeerReviewStatus | <ide><path>rc/main/java/ai/elimu/rest/v2/crowdsource/WordPeerReviewsRestController.java
<ide> import ai.elimu.dao.WordPeerReviewEventDao;
<ide> import ai.elimu.model.content.Word;
<ide> import ai.elimu.model.contributor.*;
<del>import ai.elimu.model.v2.enums.PeerReviewStatus;
<add>import ai.elimu.model.enums.PeerReviewStatus;
<ide> import ai.elimu.model.v2.gson.crowdsource.WordContributionEventGson;
<ide> import ai.elimu.model.v2.gson.crowdsource.WordPeerReviewEventGson;
<ide> import ai.elimu.rest.v2.JpaToGsonConverter; |
|
Java | agpl-3.0 | 2b93f2eab09ba41c515f805fbf03689b7d365f05 | 0 | USAID-DELIVER-PROJECT/elmis,USAID-DELIVER-PROJECT/elmis,USAID-DELIVER-PROJECT/elmis,USAID-DELIVER-PROJECT/elmis | /*
*
* * Copyright © 2013 VillageReach. All Rights Reserved. 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.openlmis.rnr.domain;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.openlmis.core.domain.*;
import org.openlmis.core.exception.DataException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.List;
import static java.lang.Math.floor;
import static java.lang.Math.round;
import static java.math.BigDecimal.valueOf;
import static java.math.RoundingMode.HALF_UP;
import static org.apache.commons.collections.CollectionUtils.find;
import static com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion.NON_EMPTY;
import static org.openlmis.rnr.domain.ProgramRnrTemplate.*;
import static org.openlmis.rnr.domain.Rnr.RNR_VALIDATION_ERROR;
import static org.openlmis.rnr.domain.RnrStatus.AUTHORIZED;
/**
* This class represents the data captured against a product for each Requisition and contains methods to determine
* normalisedConsumption, averageMonthlyConsumption, stockOutDays, packsToShip, orderQuantity, maxStockQuantity and
* quantityDispensed of that product.
*/
@Data
@NoArgsConstructor
@JsonSerialize(include = NON_EMPTY)
@EqualsAndHashCode(callSuper = true)
public class RnrLineItem extends LineItem {
public static final BigDecimal NUMBER_OF_DAYS = new BigDecimal(30);
public static final MathContext MATH_CONTEXT = new MathContext(12, HALF_UP);
public static final String DISPENSED_PLUS_NEW_PATIENTS = "DISPENSED_PLUS_NEW_PATIENTS";
public static final String DISPENSED_X_90 = "DISPENSED_X_90";
public static final String DEFAULT = "DEFAULT";
public static final String DISPENSED_X_2 = "DISPENSED_X_2";
public static final String CONSUMPTION_X_2 = "CONSUMPTION_X_2";
private static final Logger LOGGER = LoggerFactory.getLogger(RnrLineItem.class);
//TODO : hack to display it on UI. This is concatenated string of Product properties like name, strength, form and dosage unit
private String product;
private Integer productDisplayOrder;
private String productCode;
private String productPrimaryName;
private String productCategory;
private Integer productCategoryDisplayOrder;
private String productStrength;
private Boolean roundToZero;
private Integer packRoundingThreshold;
private Integer packSize;
private Integer dosesPerMonth;
private Integer dosesPerDispensingUnit;
private String dispensingUnit;
private Double maxMonthsOfStock;
private Boolean fullSupply;
private Integer quantityReceived;
private Integer quantityDispensed;
private Integer previousStockInHand;
private Integer beginningBalance;
private List<LossesAndAdjustments> lossesAndAdjustments = new ArrayList<>();
private Integer totalLossesAndAdjustments = 0;
private Integer stockInHand;
private Integer stockOutDays;
private Integer newPatientCount;
private Integer quantityRequested;
private String reasonForRequestedQuantity;
private Integer amc;
private Integer normalizedConsumption;
private Integer periodNormalizedConsumption;
private Integer calculatedOrderQuantity;
private Integer maxStockQuantity;
private Integer quantityApproved;
private Integer reportingDays;
private Integer packsToShip;
private String expirationDate;
private String remarks;
private List<Integer> previousNormalizedConsumptions = new ArrayList<>();
private Money price;
private Integer total;
@SuppressWarnings("unused")
private Boolean skipped = false;
public RnrLineItem(Long rnrId,
FacilityTypeApprovedProduct facilityTypeApprovedProduct,
Long modifiedBy,
Long createdBy) {
this.rnrId = rnrId;
this.maxMonthsOfStock = facilityTypeApprovedProduct.getMaxMonthsOfStock();
ProgramProduct programProduct = facilityTypeApprovedProduct.getProgramProduct();
this.price = programProduct.getCurrentPrice();
ProductCategory category = programProduct.getProductCategory();
this.productCategory = category.getName();
this.productCategoryDisplayOrder = category.getDisplayOrder();
this.populateFromProduct(programProduct);
this.dosesPerMonth = programProduct.getDosesPerMonth();
this.modifiedBy = modifiedBy;
this.createdBy = createdBy;
}
public void setFieldsForApproval() {
if (this.skipped) {
this.quantityReceived = null;
this.quantityDispensed = null;
this.beginningBalance = null;
this.lossesAndAdjustments = new ArrayList<>();
this.totalLossesAndAdjustments = 0;
this.stockInHand = null;
this.stockOutDays = null;
this.newPatientCount = null;
this.quantityRequested = null;
this.quantityApproved = null;
this.reasonForRequestedQuantity = null;
this.normalizedConsumption = null;
this.periodNormalizedConsumption = null;
this.packsToShip = null;
this.remarks = null;
this.expirationDate = null;
}
if(quantityApproved == null){
quantityApproved = (quantityRequested == null) ? calculatedOrderQuantity : quantityRequested;
}
}
public void setBeginningBalanceWhenPreviousStockInHandAvailable(RnrLineItem previousLineItem,
Boolean beginningBalanceVisible) {
if (previousLineItem == null || (!beginningBalanceVisible && previousLineItem.getSkipped())) {
this.beginningBalance = 0;
return;
}
this.beginningBalance = previousLineItem.getStockInHand();
this.previousStockInHand = previousLineItem.getStockInHand();
}
public void setSkippedValueWhenPreviousLineItemIsAvailable(RnrLineItem previousLineItem){
if(previousLineItem != null){
this.setSkipped(previousLineItem.getSkipped());
}
}
public void setLineItemFieldsAccordingToTemplate(ProgramRnrTemplate template) {
if (!template.columnsVisible(QUANTITY_RECEIVED)) quantityReceived = 0;
if (!template.columnsVisible(QUANTITY_DISPENSED)) quantityDispensed = 0;
totalLossesAndAdjustments = 0;
newPatientCount = 0;
stockOutDays = 0;
if(template.getApplyDefaultZero()){
quantityReceived = quantityDispensed = stockInHand = calculatedOrderQuantity = 0;
if(beginningBalance == null){
beginningBalance = 0;
} else{
stockInHand = beginningBalance;
}
}
totalLossesAndAdjustments = newPatientCount = stockOutDays = 0;
}
public void validateForApproval() {
if (!skipped && quantityApproved == null) throw new DataException(RNR_VALIDATION_ERROR);
}
public void validateMandatoryFields(ProgramRnrTemplate template) {
String[] nonNullableFields = {BEGINNING_BALANCE, QUANTITY_RECEIVED, STOCK_IN_HAND,
QUANTITY_DISPENSED, NEW_PATIENT_COUNT, STOCK_OUT_DAYS};
for (String fieldName : nonNullableFields) {
if (template.columnsVisible(fieldName) &&
!template.columnsCalculated(fieldName) &&
(getValueFor(fieldName) == null || (Integer) getValueFor(fieldName) < 0)) {
throw new DataException(RNR_VALIDATION_ERROR);
}
}
requestedQuantityConditionalValidation(template);
}
public void validateNonFullSupply() {
if (!(quantityRequested != null && quantityRequested >= 0 && reasonForRequestedQuantity != null)) {
throw new DataException(RNR_VALIDATION_ERROR);
}
}
public void validateCalculatedFields(ProgramRnrTemplate template) {
boolean validQuantityDispensed = true;
RnrColumn rnrColumn = (RnrColumn) template.getColumns().get(0);
if (rnrColumn.isFormulaValidationRequired()) {
validQuantityDispensed = (quantityDispensed == (beginningBalance + quantityReceived + totalLossesAndAdjustments - stockInHand));
}
boolean valid = quantityDispensed >= 0 && stockInHand >= 0 && validQuantityDispensed;
if (!valid) throw new DataException(RNR_VALIDATION_ERROR);
}
public void calculateForFullSupply(ProgramRnrTemplate template,
RnrStatus rnrStatus,
List<LossesAndAdjustmentsType> lossesAndAdjustmentsTypes, Integer numberOfMonths) {
calculateTotalLossesAndAdjustments(lossesAndAdjustmentsTypes);
if (template.columnsCalculated(STOCK_IN_HAND)) {
calculateStockInHand();
}
if (template.columnsCalculated(QUANTITY_DISPENSED)) {
calculateQuantityDispensed();
}
calculateNormalizedConsumption(template);
calculatePeriodNormalizedConsumption(numberOfMonths);
if (rnrStatus == AUTHORIZED) {
calculateAmc(numberOfMonths);
calculateMaxStockQuantity(template);
if (!(template.getRnrColumnsMap().get(CALCULATED_ORDER_QUANTITY) != null && template.columnsUserInput(CALCULATED_ORDER_QUANTITY))) {
calculateOrderQuantity();
}
}
calculatePacksToShip();
}
public void calculatePeriodNormalizedConsumption(Integer numberOfMonths) {
periodNormalizedConsumption = normalizedConsumption * numberOfMonths;
}
public void calculateAmc(Integer numberOfMonths) {
Integer sumOfNCs = normalizedConsumption;
for (Integer previousNC : previousNormalizedConsumptions) {
sumOfNCs += previousNC;
}
BigDecimal countOfNCs = new BigDecimal((previousNormalizedConsumptions.size() + 1) * numberOfMonths);
amc = new BigDecimal(sumOfNCs).divide(countOfNCs, MATH_CONTEXT).setScale(0, HALF_UP).intValue();
}
public void calculatePacksToShip() {
Integer orderQuantity = getOrderQuantity();
if (allNotNull(orderQuantity, packSize)) {
packsToShip = ((orderQuantity == 0) ? (roundToZero ? 0 : 1) : applyRoundingRules(orderQuantity));
}
}
public void calculateMaxStockQuantity( ProgramRnrTemplate template) {
RnrColumn column = template.getRnrColumnsMap().get("maxStockQuantity");
String columnOption = DEFAULT;
if(column != null){
columnOption = column.getCalculationOption();
}
if(CONSUMPTION_X_2.equalsIgnoreCase(columnOption)){
maxStockQuantity = this.normalizedConsumption * 2;
}else if(DISPENSED_X_2.equalsIgnoreCase(columnOption)){
maxStockQuantity = this.quantityDispensed * 2;
} else{
// apply the default calculation if there was no other calculation that works here
maxStockQuantity = (int) round(maxMonthsOfStock * amc);
}
}
public void calculateOrderQuantity() {
if (allNotNull(maxStockQuantity, stockInHand)) {
calculatedOrderQuantity = ((maxStockQuantity - stockInHand) < 0) ? 0 : maxStockQuantity - stockInHand;
}
}
public void calculateNormalizedConsumption(ProgramRnrTemplate template) {
prepareFieldsForCalculation();
RnrColumn column = template.getRnrColumnsMap().get("normalizedConsumption");
String selectedColumnOption = DEFAULT;
if (column != null) {
selectedColumnOption = column.getCalculationOption();
}
if (DISPENSED_PLUS_NEW_PATIENTS.equalsIgnoreCase(selectedColumnOption)) {
normalizedConsumption = quantityDispensed + newPatientCount;
} else if (DISPENSED_X_90.equalsIgnoreCase(selectedColumnOption)) {
if (stockOutDays < 90) {
normalizedConsumption = (new BigDecimal(90 * quantityDispensed)
.divide(
new BigDecimal(90 - stockOutDays)
, MATH_CONTEXT)
).intValue();
} else {
normalizedConsumption = (90 * quantityDispensed);
}
} else {
BigDecimal dosesPerDispensingUnit = new BigDecimal(Math.max(1, this.dosesPerDispensingUnit));
normalizedConsumption = calculateNormalizedConsumption(
new BigDecimal(stockOutDays),
new BigDecimal(quantityDispensed),
new BigDecimal(newPatientCount),
new BigDecimal(dosesPerMonth), dosesPerDispensingUnit, reportingDays, template);
}
}
private void prepareFieldsForCalculation() {
// prepare fields for calculation
if(stockOutDays == null){
stockOutDays = 0;
}
if(newPatientCount == null){
newPatientCount = 0;
}
}
public void calculateTotalLossesAndAdjustments(List<LossesAndAdjustmentsType> lossesAndAdjustmentsTypes) {
if (lossesAndAdjustments.isEmpty()) {
return;
}
Integer total = 0;
for (LossesAndAdjustments lossAndAdjustment : lossesAndAdjustments) {
if (getAdditive(lossAndAdjustment, lossesAndAdjustmentsTypes)) {
total += lossAndAdjustment.getQuantity();
} else {
total -= lossAndAdjustment.getQuantity();
}
}
totalLossesAndAdjustments = total;
}
public void calculateQuantityDispensed() {
if (allNotNull(beginningBalance, quantityReceived, totalLossesAndAdjustments, stockInHand)) {
quantityDispensed = beginningBalance + quantityReceived + totalLossesAndAdjustments - stockInHand;
}
}
public void calculateStockInHand() {
stockInHand = beginningBalance + quantityReceived + totalLossesAndAdjustments - quantityDispensed;
}
public Money calculateCost() {
if (packsToShip != null && price != null) {
return price.multiply(valueOf(packsToShip));
}
return new Money("0");
}
public void copyCreatorEditableFieldsForFullSupply(RnrLineItem lineItem, ProgramRnrTemplate template) {
this.previousStockInHand = lineItem.previousStockInHand;
copyTotalLossesAndAdjustments(lineItem, template);
for (Column column : template.getColumns()) {
String fieldName = column.getName();
if (fieldName.equals(QUANTITY_APPROVED)) continue;
copyField(fieldName, lineItem, template);
}
}
public void copyCreatorEditableFieldsForNonFullSupply(RnrLineItem lineItem, ProgramRnrTemplate template) {
String[] editableFields = {QUANTITY_REQUESTED, REMARKS, REASON_FOR_REQUESTED_QUANTITY};
for (String fieldName : editableFields) {
copyField(fieldName, lineItem, template);
}
}
public void copyApproverEditableFields(RnrLineItem lineItem, ProgramRnrTemplate template) {
String[] approverEditableFields = {QUANTITY_APPROVED, REMARKS, SKIPPED};
for (String fieldName : approverEditableFields) {
copyField(fieldName, lineItem, template);
}
}
public void addLossesAndAdjustments(LossesAndAdjustments lossesAndAdjustments) {
this.lossesAndAdjustments.add(lossesAndAdjustments);
}
private Integer calculateNormalizedConsumption(BigDecimal stockOutDays,
BigDecimal quantityDispensed,
BigDecimal newPatientCount,
BigDecimal dosesPerMonth,
BigDecimal dosesPerDispensingUnit,
Integer reportingDays,
ProgramRnrTemplate template) {
BigDecimal newPatientFactor;
if (template.getRnrColumnsMap().get("newPatientCount").getConfiguredOption() != null && template.getRnrColumnsMap().get("newPatientCount").getConfiguredOption().getName().equals("newPatientCount")) {
newPatientFactor = newPatientCount.multiply(dosesPerMonth.divide(dosesPerDispensingUnit, MATH_CONTEXT)
.setScale(0, HALF_UP));
} else {
newPatientFactor = newPatientCount;
}
if (reportingDays == null || stockOutDays.compareTo(new BigDecimal(reportingDays)) >= 0) {
return quantityDispensed.add(newPatientFactor).setScale(0, HALF_UP).intValue();
}
BigDecimal stockOutFactor = quantityDispensed.multiply(NUMBER_OF_DAYS
.divide((new BigDecimal(reportingDays).subtract(stockOutDays)), MATH_CONTEXT));
return stockOutFactor.add(newPatientFactor).setScale(0, HALF_UP).intValue();
}
private void copyField(String fieldName, RnrLineItem lineItem, ProgramRnrTemplate template) {
if (!template.columnsVisible(fieldName) || !template.columnsUserInput(fieldName)) {
return;
}
try {
Field field = this.getClass().getDeclaredField(fieldName);
field.set(this, field.get(lineItem));
} catch (Exception e) {
LOGGER.error("Error in copying RnrLineItem's field", e);
}
}
private void copyTotalLossesAndAdjustments(RnrLineItem item, ProgramRnrTemplate template) {
if (template.columnsVisible(LOSSES_AND_ADJUSTMENTS))
this.totalLossesAndAdjustments = item.totalLossesAndAdjustments;
}
private void populateFromProduct(ProgramProduct programProduct) {
Product product = programProduct.getProduct();
this.productCode = product.getCode();
this.dispensingUnit = product.getDispensingUnit();
this.dosesPerDispensingUnit = product.getDosesPerDispensingUnit();
this.packSize = product.getPackSize();
this.roundToZero = product.getRoundToZero();
this.packRoundingThreshold = product.getPackRoundingThreshold();
this.product = product.getName();
// use the program product setting instead of the one on the product table.
this.fullSupply = programProduct.isFullSupply();
this.productDisplayOrder = programProduct.getDisplayOrder();
}
private void requestedQuantityConditionalValidation(ProgramRnrTemplate template) {
if (template.columnsVisible(QUANTITY_REQUESTED)
&& quantityRequested != null
&& StringUtils.isEmpty(reasonForRequestedQuantity)) {
throw new DataException(RNR_VALIDATION_ERROR);
}
}
private Object getValueFor(String fieldName) {
Object value = null;
try {
Field field = this.getClass().getDeclaredField(fieldName);
value = field.get(this);
} catch (Exception e) {
LOGGER.error("Error in reading RnrLineItem's field", e);
}
return value;
}
@Override
public boolean compareCategory(LineItem lineItem) {
return this.getProductCategory().equals(((RnrLineItem) lineItem).getProductCategory());
}
@Override
public String getCategoryName() {
return this.productCategory;
}
@Override
public String getValue(String columnName) throws NoSuchFieldException, IllegalAccessException {
if (columnName.equals("lossesAndAdjustments")) {
return this.getTotalLossesAndAdjustments().toString();
}
if (columnName.equals("cost")) {
return this.calculateCost().toString();
}
if (columnName.equals("price")) {
return this.getPrice().toString();
}
if (columnName.equals("total") && this.getBeginningBalance() != null && this.getQuantityReceived() != null) {
return String.valueOf((this.getBeginningBalance() + this.getQuantityReceived()));
}
Field field = RnrLineItem.class.getDeclaredField(columnName);
field.setAccessible(true);
Object fieldValue = field.get(this);
return (fieldValue == null) ? "" : fieldValue.toString();
}
@Override
public boolean isRnrLineItem() {
return true;
}
private Integer getOrderQuantity() {
if (quantityApproved != null) return quantityApproved;
if (quantityRequested != null) return quantityRequested;
else return calculatedOrderQuantity;
}
private Integer applyRoundingRules(Integer orderQuantity) {
Double packsToShip = floor(orderQuantity / packSize);
Integer remainderQuantity = orderQuantity % packSize;
if (remainderQuantity >= packRoundingThreshold) {
packsToShip += 1;
}
if (packsToShip == 0 && !roundToZero) {
packsToShip = 1d;
}
return packsToShip.intValue();
}
private boolean allNotNull(Integer... fields) {
for (Integer field : fields) {
if (field == null) return false;
}
return true;
}
private Boolean getAdditive(final LossesAndAdjustments lossAndAdjustment,
List<LossesAndAdjustmentsType> lossesAndAdjustmentsTypes) {
Predicate predicate = new Predicate() {
@Override
public boolean evaluate(Object o) {
return lossAndAdjustment.getType().getName().equals(((LossesAndAdjustmentsType) o).getName());
}
};
LossesAndAdjustmentsType lossAndAdjustmentTypeFromList = (LossesAndAdjustmentsType) find(lossesAndAdjustmentsTypes,
predicate);
return lossAndAdjustmentTypeFromList.getAdditive();
}
}
| modules/requisition/src/main/java/org/openlmis/rnr/domain/RnrLineItem.java | /*
*
* * Copyright © 2013 VillageReach. All Rights Reserved. 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.openlmis.rnr.domain;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.openlmis.core.domain.*;
import org.openlmis.core.exception.DataException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.List;
import static java.lang.Math.floor;
import static java.lang.Math.round;
import static java.math.BigDecimal.valueOf;
import static java.math.RoundingMode.HALF_UP;
import static org.apache.commons.collections.CollectionUtils.find;
import static com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion.NON_EMPTY;
import static org.openlmis.rnr.domain.ProgramRnrTemplate.*;
import static org.openlmis.rnr.domain.Rnr.RNR_VALIDATION_ERROR;
import static org.openlmis.rnr.domain.RnrStatus.AUTHORIZED;
/**
* This class represents the data captured against a product for each Requisition and contains methods to determine
* normalisedConsumption, averageMonthlyConsumption, stockOutDays, packsToShip, orderQuantity, maxStockQuantity and
* quantityDispensed of that product.
*/
@Data
@NoArgsConstructor
@JsonSerialize(include = NON_EMPTY)
@EqualsAndHashCode(callSuper = true)
public class RnrLineItem extends LineItem {
public static final BigDecimal NUMBER_OF_DAYS = new BigDecimal(30);
public static final MathContext MATH_CONTEXT = new MathContext(12, HALF_UP);
public static final String DISPENSED_PLUS_NEW_PATIENTS = "DISPENSED_PLUS_NEW_PATIENTS";
public static final String DISPENSED_X_90 = "DISPENSED_X_90";
public static final String DEFAULT = "DEFAULT";
public static final String DISPENSED_X_2 = "DISPENSED_X_2";
public static final String CONSUMPTION_X_2 = "CONSUMPTION_X_2";
private static final Logger LOGGER = LoggerFactory.getLogger(RnrLineItem.class);
//TODO : hack to display it on UI. This is concatenated string of Product properties like name, strength, form and dosage unit
private String product;
private Integer productDisplayOrder;
private String productCode;
private String productPrimaryName;
private String productCategory;
private Integer productCategoryDisplayOrder;
private String productStrength;
private Boolean roundToZero;
private Integer packRoundingThreshold;
private Integer packSize;
private Integer dosesPerMonth;
private Integer dosesPerDispensingUnit;
private String dispensingUnit;
private Double maxMonthsOfStock;
private Boolean fullSupply;
private Integer quantityReceived;
private Integer quantityDispensed;
private Integer previousStockInHand;
private Integer beginningBalance;
private List<LossesAndAdjustments> lossesAndAdjustments = new ArrayList<>();
private Integer totalLossesAndAdjustments = 0;
private Integer stockInHand;
private Integer stockOutDays;
private Integer newPatientCount;
private Integer quantityRequested;
private String reasonForRequestedQuantity;
private Integer amc;
private Integer normalizedConsumption;
private Integer periodNormalizedConsumption;
private Integer calculatedOrderQuantity;
private Integer maxStockQuantity;
private Integer quantityApproved;
private Integer reportingDays;
private Integer packsToShip;
private String expirationDate;
private String remarks;
private List<Integer> previousNormalizedConsumptions = new ArrayList<>();
private Money price;
private Integer total;
@SuppressWarnings("unused")
private Boolean skipped = false;
public RnrLineItem(Long rnrId,
FacilityTypeApprovedProduct facilityTypeApprovedProduct,
Long modifiedBy,
Long createdBy) {
this.rnrId = rnrId;
this.maxMonthsOfStock = facilityTypeApprovedProduct.getMaxMonthsOfStock();
ProgramProduct programProduct = facilityTypeApprovedProduct.getProgramProduct();
this.price = programProduct.getCurrentPrice();
ProductCategory category = programProduct.getProductCategory();
this.productCategory = category.getName();
this.productCategoryDisplayOrder = category.getDisplayOrder();
this.populateFromProduct(programProduct);
this.dosesPerMonth = programProduct.getDosesPerMonth();
this.modifiedBy = modifiedBy;
this.createdBy = createdBy;
}
public void setFieldsForApproval() {
if (this.skipped) {
this.quantityReceived = null;
this.quantityDispensed = null;
this.beginningBalance = null;
this.lossesAndAdjustments = new ArrayList<>();
this.totalLossesAndAdjustments = 0;
this.stockInHand = null;
this.stockOutDays = null;
this.newPatientCount = null;
this.quantityRequested = null;
this.quantityApproved = null;
this.reasonForRequestedQuantity = null;
this.normalizedConsumption = null;
this.periodNormalizedConsumption = null;
this.packsToShip = null;
this.remarks = null;
this.expirationDate = null;
}
if(quantityApproved == null){
quantityApproved = (quantityRequested == null) ? calculatedOrderQuantity : quantityRequested;
}
}
public void setBeginningBalanceWhenPreviousStockInHandAvailable(RnrLineItem previousLineItem,
Boolean beginningBalanceVisible) {
if (previousLineItem == null || (!beginningBalanceVisible && previousLineItem.getSkipped())) {
this.beginningBalance = 0;
return;
}
this.beginningBalance = previousLineItem.getStockInHand();
this.previousStockInHand = previousLineItem.getStockInHand();
}
public void setSkippedValueWhenPreviousLineItemIsAvailable(RnrLineItem previousLineItem){
if(previousLineItem != null){
this.setSkipped(previousLineItem.getSkipped());
}
}
public void setLineItemFieldsAccordingToTemplate(ProgramRnrTemplate template) {
if (!template.columnsVisible(QUANTITY_RECEIVED)) quantityReceived = 0;
if (!template.columnsVisible(QUANTITY_DISPENSED)) quantityDispensed = 0;
totalLossesAndAdjustments = 0;
newPatientCount = 0;
stockOutDays = 0;
if(template.getApplyDefaultZero()){
quantityReceived = quantityDispensed = stockInHand = calculatedOrderQuantity = 0;
if(beginningBalance == null){
beginningBalance = 0;
} else{
stockInHand = beginningBalance;
}
}
totalLossesAndAdjustments = newPatientCount = stockOutDays = 0;
}
public void validateForApproval() {
if (!skipped && quantityApproved == null) throw new DataException(RNR_VALIDATION_ERROR);
}
public void validateMandatoryFields(ProgramRnrTemplate template) {
String[] nonNullableFields = {BEGINNING_BALANCE, QUANTITY_RECEIVED, STOCK_IN_HAND,
QUANTITY_DISPENSED, NEW_PATIENT_COUNT, STOCK_OUT_DAYS};
for (String fieldName : nonNullableFields) {
if (template.columnsVisible(fieldName) &&
!template.columnsCalculated(fieldName) &&
(getValueFor(fieldName) == null || (Integer) getValueFor(fieldName) < 0)) {
throw new DataException(RNR_VALIDATION_ERROR);
}
}
requestedQuantityConditionalValidation(template);
}
public void validateNonFullSupply() {
if (!(quantityRequested != null && quantityRequested >= 0 && reasonForRequestedQuantity != null)) {
throw new DataException(RNR_VALIDATION_ERROR);
}
}
public void validateCalculatedFields(ProgramRnrTemplate template) {
boolean validQuantityDispensed = true;
RnrColumn rnrColumn = (RnrColumn) template.getColumns().get(0);
if (rnrColumn.isFormulaValidationRequired()) {
validQuantityDispensed = (quantityDispensed == (beginningBalance + quantityReceived + totalLossesAndAdjustments - stockInHand));
}
boolean valid = quantityDispensed >= 0 && stockInHand >= 0 && validQuantityDispensed;
if (!valid) throw new DataException(RNR_VALIDATION_ERROR);
}
public void calculateForFullSupply(ProgramRnrTemplate template,
RnrStatus rnrStatus,
List<LossesAndAdjustmentsType> lossesAndAdjustmentsTypes, Integer numberOfMonths) {
calculateTotalLossesAndAdjustments(lossesAndAdjustmentsTypes);
if (template.columnsCalculated(STOCK_IN_HAND)) {
calculateStockInHand();
}
if (template.columnsCalculated(QUANTITY_DISPENSED)) {
calculateQuantityDispensed();
}
calculateNormalizedConsumption(template);
calculatePeriodNormalizedConsumption(numberOfMonths);
if (rnrStatus == AUTHORIZED) {
calculateAmc(numberOfMonths);
calculateMaxStockQuantity(template);
if (!(template.getRnrColumnsMap().get(CALCULATED_ORDER_QUANTITY) != null && template.columnsUserInput(CALCULATED_ORDER_QUANTITY))) {
calculateOrderQuantity();
}
}
calculatePacksToShip();
}
public void calculatePeriodNormalizedConsumption(Integer numberOfMonths) {
periodNormalizedConsumption = normalizedConsumption * numberOfMonths;
}
public void calculateAmc(Integer numberOfMonths) {
Integer sumOfNCs = normalizedConsumption;
for (Integer previousNC : previousNormalizedConsumptions) {
sumOfNCs += previousNC;
}
BigDecimal countOfNCs = new BigDecimal((previousNormalizedConsumptions.size() + 1) * numberOfMonths);
amc = new BigDecimal(sumOfNCs).divide(countOfNCs, MATH_CONTEXT).setScale(0, HALF_UP).intValue();
}
public void calculatePacksToShip() {
Integer orderQuantity = getOrderQuantity();
if (allNotNull(orderQuantity, packSize)) {
packsToShip = ((orderQuantity == 0) ? (roundToZero ? 0 : 1) : applyRoundingRules(orderQuantity));
}
}
public void calculateMaxStockQuantity( ProgramRnrTemplate template) {
RnrColumn column = template.getRnrColumnsMap().get("maxStockQuantity");
String columnOption = DEFAULT;
if(column != null){
columnOption = column.getCalculationOption();
}
if(CONSUMPTION_X_2.equalsIgnoreCase(columnOption)){
maxStockQuantity = this.normalizedConsumption * 2;
}else if(DISPENSED_X_2.equalsIgnoreCase(columnOption)){
maxStockQuantity = this.quantityDispensed * 2;
} else{
// apply the default calculation if there was no other calculation that works here
maxStockQuantity = (int) round(maxMonthsOfStock * amc);
}
}
public void calculateOrderQuantity() {
if (allNotNull(maxStockQuantity, stockInHand)) {
calculatedOrderQuantity = ((maxStockQuantity - stockInHand) < 0) ? 0 : maxStockQuantity - stockInHand;
}
}
public void calculateNormalizedConsumption(ProgramRnrTemplate template) {
prepareFieldsForCalculation();
RnrColumn column = template.getRnrColumnsMap().get("normalizedConsumption");
String selectedColumnOption = DEFAULT;
if (column != null) {
selectedColumnOption = column.getCalculationOption();
}
if (DISPENSED_PLUS_NEW_PATIENTS.equalsIgnoreCase(selectedColumnOption)) {
normalizedConsumption = quantityDispensed + newPatientCount;
} else if (DISPENSED_X_90.equalsIgnoreCase(selectedColumnOption)) {
if (stockOutDays < 90) {
normalizedConsumption = (new BigDecimal(90 * quantityDispensed)
.divide(
new BigDecimal(90 - stockOutDays)
, MATH_CONTEXT)
).intValue();
} else {
normalizedConsumption = (90 * quantityDispensed);
}
} else {
BigDecimal dosesPerDispensingUnit = new BigDecimal(Math.max(1, this.dosesPerDispensingUnit));
normalizedConsumption = calculateNormalizedConsumption(
new BigDecimal(stockOutDays),
new BigDecimal(quantityDispensed),
new BigDecimal(newPatientCount),
new BigDecimal(dosesPerMonth), dosesPerDispensingUnit, reportingDays, template);
}
}
private void prepareFieldsForCalculation() {
// prepare fields for calculation
if(stockOutDays == null){
stockOutDays = 0;
}
if(newPatientCount == null){
newPatientCount = 0;
}
}
public void calculateTotalLossesAndAdjustments(List<LossesAndAdjustmentsType> lossesAndAdjustmentsTypes) {
if (lossesAndAdjustments.isEmpty()) {
return;
}
Integer total = 0;
for (LossesAndAdjustments lossAndAdjustment : lossesAndAdjustments) {
if (getAdditive(lossAndAdjustment, lossesAndAdjustmentsTypes)) {
total += lossAndAdjustment.getQuantity();
} else {
total -= lossAndAdjustment.getQuantity();
}
}
totalLossesAndAdjustments = total;
}
public void calculateQuantityDispensed() {
if (allNotNull(beginningBalance, quantityReceived, totalLossesAndAdjustments, stockInHand)) {
quantityDispensed = beginningBalance + quantityReceived + totalLossesAndAdjustments - stockInHand;
}
}
public void calculateStockInHand() {
stockInHand = beginningBalance + quantityReceived + totalLossesAndAdjustments - quantityDispensed;
}
public Money calculateCost() {
if (packsToShip != null) {
return price.multiply(valueOf(packsToShip));
}
return new Money("0");
}
public void copyCreatorEditableFieldsForFullSupply(RnrLineItem lineItem, ProgramRnrTemplate template) {
this.previousStockInHand = lineItem.previousStockInHand;
copyTotalLossesAndAdjustments(lineItem, template);
for (Column column : template.getColumns()) {
String fieldName = column.getName();
if (fieldName.equals(QUANTITY_APPROVED)) continue;
copyField(fieldName, lineItem, template);
}
}
public void copyCreatorEditableFieldsForNonFullSupply(RnrLineItem lineItem, ProgramRnrTemplate template) {
String[] editableFields = {QUANTITY_REQUESTED, REMARKS, REASON_FOR_REQUESTED_QUANTITY};
for (String fieldName : editableFields) {
copyField(fieldName, lineItem, template);
}
}
public void copyApproverEditableFields(RnrLineItem lineItem, ProgramRnrTemplate template) {
String[] approverEditableFields = {QUANTITY_APPROVED, REMARKS, SKIPPED};
for (String fieldName : approverEditableFields) {
copyField(fieldName, lineItem, template);
}
}
public void addLossesAndAdjustments(LossesAndAdjustments lossesAndAdjustments) {
this.lossesAndAdjustments.add(lossesAndAdjustments);
}
private Integer calculateNormalizedConsumption(BigDecimal stockOutDays,
BigDecimal quantityDispensed,
BigDecimal newPatientCount,
BigDecimal dosesPerMonth,
BigDecimal dosesPerDispensingUnit,
Integer reportingDays,
ProgramRnrTemplate template) {
BigDecimal newPatientFactor;
if (template.getRnrColumnsMap().get("newPatientCount").getConfiguredOption() != null && template.getRnrColumnsMap().get("newPatientCount").getConfiguredOption().getName().equals("newPatientCount")) {
newPatientFactor = newPatientCount.multiply(dosesPerMonth.divide(dosesPerDispensingUnit, MATH_CONTEXT)
.setScale(0, HALF_UP));
} else {
newPatientFactor = newPatientCount;
}
if (reportingDays == null || stockOutDays.compareTo(new BigDecimal(reportingDays)) >= 0) {
return quantityDispensed.add(newPatientFactor).setScale(0, HALF_UP).intValue();
}
BigDecimal stockOutFactor = quantityDispensed.multiply(NUMBER_OF_DAYS
.divide((new BigDecimal(reportingDays).subtract(stockOutDays)), MATH_CONTEXT));
return stockOutFactor.add(newPatientFactor).setScale(0, HALF_UP).intValue();
}
private void copyField(String fieldName, RnrLineItem lineItem, ProgramRnrTemplate template) {
if (!template.columnsVisible(fieldName) || !template.columnsUserInput(fieldName)) {
return;
}
try {
Field field = this.getClass().getDeclaredField(fieldName);
field.set(this, field.get(lineItem));
} catch (Exception e) {
LOGGER.error("Error in copying RnrLineItem's field", e);
}
}
private void copyTotalLossesAndAdjustments(RnrLineItem item, ProgramRnrTemplate template) {
if (template.columnsVisible(LOSSES_AND_ADJUSTMENTS))
this.totalLossesAndAdjustments = item.totalLossesAndAdjustments;
}
private void populateFromProduct(ProgramProduct programProduct) {
Product product = programProduct.getProduct();
this.productCode = product.getCode();
this.dispensingUnit = product.getDispensingUnit();
this.dosesPerDispensingUnit = product.getDosesPerDispensingUnit();
this.packSize = product.getPackSize();
this.roundToZero = product.getRoundToZero();
this.packRoundingThreshold = product.getPackRoundingThreshold();
this.product = product.getName();
// use the program product setting instead of the one on the product table.
this.fullSupply = programProduct.isFullSupply();
this.productDisplayOrder = programProduct.getDisplayOrder();
}
private void requestedQuantityConditionalValidation(ProgramRnrTemplate template) {
if (template.columnsVisible(QUANTITY_REQUESTED)
&& quantityRequested != null
&& StringUtils.isEmpty(reasonForRequestedQuantity)) {
throw new DataException(RNR_VALIDATION_ERROR);
}
}
private Object getValueFor(String fieldName) {
Object value = null;
try {
Field field = this.getClass().getDeclaredField(fieldName);
value = field.get(this);
} catch (Exception e) {
LOGGER.error("Error in reading RnrLineItem's field", e);
}
return value;
}
@Override
public boolean compareCategory(LineItem lineItem) {
return this.getProductCategory().equals(((RnrLineItem) lineItem).getProductCategory());
}
@Override
public String getCategoryName() {
return this.productCategory;
}
@Override
public String getValue(String columnName) throws NoSuchFieldException, IllegalAccessException {
if (columnName.equals("lossesAndAdjustments")) {
return this.getTotalLossesAndAdjustments().toString();
}
if (columnName.equals("cost")) {
return this.calculateCost().toString();
}
if (columnName.equals("price")) {
return this.getPrice().toString();
}
if (columnName.equals("total") && this.getBeginningBalance() != null && this.getQuantityReceived() != null) {
return String.valueOf((this.getBeginningBalance() + this.getQuantityReceived()));
}
Field field = RnrLineItem.class.getDeclaredField(columnName);
field.setAccessible(true);
Object fieldValue = field.get(this);
return (fieldValue == null) ? "" : fieldValue.toString();
}
@Override
public boolean isRnrLineItem() {
return true;
}
private Integer getOrderQuantity() {
if (quantityApproved != null) return quantityApproved;
if (quantityRequested != null) return quantityRequested;
else return calculatedOrderQuantity;
}
private Integer applyRoundingRules(Integer orderQuantity) {
Double packsToShip = floor(orderQuantity / packSize);
Integer remainderQuantity = orderQuantity % packSize;
if (remainderQuantity >= packRoundingThreshold) {
packsToShip += 1;
}
if (packsToShip == 0 && !roundToZero) {
packsToShip = 1d;
}
return packsToShip.intValue();
}
private boolean allNotNull(Integer... fields) {
for (Integer field : fields) {
if (field == null) return false;
}
return true;
}
private Boolean getAdditive(final LossesAndAdjustments lossAndAdjustment,
List<LossesAndAdjustmentsType> lossesAndAdjustmentsTypes) {
Predicate predicate = new Predicate() {
@Override
public boolean evaluate(Object o) {
return lossAndAdjustment.getType().getName().equals(((LossesAndAdjustmentsType) o).getName());
}
};
LossesAndAdjustmentsType lossAndAdjustmentTypeFromList = (LossesAndAdjustmentsType) find(lossesAndAdjustmentsTypes,
predicate);
return lossAndAdjustmentTypeFromList.getAdditive();
}
}
| Fix rnr submission when price schedule is not set for a product
- When price schedule is not set correctly for a product, rnr submission fails. This commit fixes this issue.
| modules/requisition/src/main/java/org/openlmis/rnr/domain/RnrLineItem.java | Fix rnr submission when price schedule is not set for a product - When price schedule is not set correctly for a product, rnr submission fails. This commit fixes this issue. | <ide><path>odules/requisition/src/main/java/org/openlmis/rnr/domain/RnrLineItem.java
<ide> }
<ide>
<ide> public Money calculateCost() {
<del> if (packsToShip != null) {
<add> if (packsToShip != null && price != null) {
<ide> return price.multiply(valueOf(packsToShip));
<ide> }
<ide> return new Money("0"); |
|
Java | apache-2.0 | 5dd2d24854c70ebc3e2f3e41320b26f9dfab5cfd | 0 | xnx3/iw,xnx3/iw,xnx3/iw | package com.xnx3.j2ee.servlet;
import java.io.File;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.xnx3.ConfigManagerUtil;
import com.xnx3.Lang;
import com.xnx3.file.FileUtil;
import com.xnx3.j2ee.Global;
import com.xnx3.j2ee.entity.BaseEntity;
import com.xnx3.j2ee.entity.PostClass;
import com.xnx3.j2ee.generateCache.Bbs;
import com.xnx3.j2ee.generateCache.Role;
import com.xnx3.j2ee.generateCache.User;
import com.xnx3.j2ee.entity.Log;
import com.xnx3.j2ee.generateCache.Message;
import com.xnx3.j2ee.service.PostClassService;
import com.xnx3.j2ee.service.RoleService;
import com.xnx3.j2ee.service.SystemService;
/**
* 初始化项目,将使用到的一些东东加入Global以方便后续使用
* @author apple
*/
public class InitServlet extends HttpServlet {
private PostClassService postClassService;
private SystemService systemService;
private RoleService roleService;
@Override
public void init(ServletConfig servletContext) throws ServletException {
ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext.getServletContext());
postClassService = ctx.getBean("postClassService", PostClassService.class);
systemService = ctx.getBean("systemService", SystemService.class);
roleService = ctx.getBean("roleService",RoleService.class);
String path = getClass().getResource("/").getPath();
Global.projectPath = path.replace("WEB-INF/classes/", "");
initCacheFolder();
new Bbs().state();
generateCache_postClass();
new Message().state();
new Message().isdelete();
new Role().role(roleService.findAll());
new User().isfreeze();
loadLogType();
readSystemTable();
}
/**
* 初始化缓存文件夹,若根目录下没有缓存文件夹,自动创建
*/
public void initCacheFolder(){
String[] folders = Global.CACHE_FILE.split("/");
String path = Global.projectPath;
for (int i = 0; i < folders.length; i++) {
if(folders[i].length()>0&&!FileUtil.exists(path+folders[i])){
File file = new File(path+folders[i]);
file.mkdir();
}
path = path+folders[i]+"/";
}
}
/**
* 加载Log的type类型,同时将其做js文件缓存
*/
public static void loadLogType(){
Log.typeMap.clear();
List<String> list = ConfigManagerUtil.getSingleton("systemConfig.xml").getList("logTypeList.type");
new com.xnx3.j2ee.generateCache.Log().type(list);
for (int i = 0; i < list.size(); i++) {
String[] array = list.get(i).split("#");
String name = array[0];
Short value = (short) Lang.stringToInt(array[1], 0);
String description = array[2];
Log.typeMap.put(name, value);
Log.typeDescriptionMap.put(value, description);
}
}
/**
* 生成缓存数据
*/
public void generateCache_postClass(){
List<PostClass> list = postClassService.findByIsdelete(BaseEntity.ISDELETE_NORMAL);
new Bbs().postClass(list);
}
/**
* 读system表数据
*/
public void readSystemTable(){
Global.system.clear();
List<com.xnx3.j2ee.entity.System> list = systemService.findAll();
for (int i = 0; i < list.size(); i++) {
com.xnx3.j2ee.entity.System s = list.get(i);
Global.system.put(s.getName(), s.getValue());
}
}
}
| src/com/xnx3/j2ee/servlet/InitServlet.java | package com.xnx3.j2ee.servlet;
import java.io.File;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.xnx3.ConfigManagerUtil;
import com.xnx3.Lang;
import com.xnx3.file.FileUtil;
import com.xnx3.j2ee.Global;
import com.xnx3.j2ee.entity.BaseEntity;
import com.xnx3.j2ee.entity.PostClass;
import com.xnx3.j2ee.generateCache.Bbs;
import com.xnx3.j2ee.entity.Log;
import com.xnx3.j2ee.generateCache.Message;
import com.xnx3.j2ee.service.PostClassService;
import com.xnx3.j2ee.service.SystemService;
/**
* 初始化项目,将使用到的一些东东加入Global以方便后续使用
* @author apple
*/
public class InitServlet extends HttpServlet {
private PostClassService postClassService;
private SystemService systemService;
@Override
public void init(ServletConfig servletContext) throws ServletException {
ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext.getServletContext());
postClassService = ctx.getBean("postClassService", PostClassService.class);
systemService = ctx.getBean("systemService", SystemService.class);
String path = getClass().getResource("/").getPath();
Global.projectPath = path.replace("WEB-INF/classes/", "");
initCacheFolder();
new Bbs().state();
generateCache_postClass();
new Message().state();
new Message().isdelete();
loadLogType();
readSystemTable();
}
/**
* 初始化缓存文件夹,若根目录下没有缓存文件夹,自动创建
*/
public void initCacheFolder(){
String[] folders = Global.CACHE_FILE.split("/");
String path = Global.projectPath;
for (int i = 0; i < folders.length; i++) {
if(folders[i].length()>0&&!FileUtil.exists(path+folders[i])){
File file = new File(path+folders[i]);
file.mkdir();
}
path = path+folders[i]+"/";
}
}
/**
* 加载Log的type类型,同时将其做js文件缓存
*/
public static void loadLogType(){
Log.typeMap.clear();
List<String> list = ConfigManagerUtil.getSingleton("systemConfig.xml").getList("logTypeList.type");
new com.xnx3.j2ee.generateCache.Log().type(list);
for (int i = 0; i < list.size(); i++) {
String[] array = list.get(i).split("#");
String name = array[0];
Short value = (short) Lang.stringToInt(array[1], 0);
String description = array[2];
Log.typeMap.put(name, value);
Log.typeDescriptionMap.put(value, description);
}
}
/**
* 生成缓存数据
*/
public void generateCache_postClass(){
List<PostClass> list = postClassService.findByIsdelete(BaseEntity.ISDELETE_NORMAL);
// List<PostClass> list = postClassService.findAll();
new Bbs().postClass(list);
}
/**
* 读system表数据
*/
public void readSystemTable(){
Global.system.clear();
List<com.xnx3.j2ee.entity.System> list = systemService.findAll();
for (int i = 0; i < list.size(); i++) {
com.xnx3.j2ee.entity.System s = list.get(i);
Global.system.put(s.getName(), s.getValue());
}
}
}
| xnx3
开启应用时的缓存初始化生成
| src/com/xnx3/j2ee/servlet/InitServlet.java | xnx3 | <ide><path>rc/com/xnx3/j2ee/servlet/InitServlet.java
<ide> import com.xnx3.j2ee.entity.BaseEntity;
<ide> import com.xnx3.j2ee.entity.PostClass;
<ide> import com.xnx3.j2ee.generateCache.Bbs;
<add>import com.xnx3.j2ee.generateCache.Role;
<add>import com.xnx3.j2ee.generateCache.User;
<ide> import com.xnx3.j2ee.entity.Log;
<ide> import com.xnx3.j2ee.generateCache.Message;
<ide> import com.xnx3.j2ee.service.PostClassService;
<add>import com.xnx3.j2ee.service.RoleService;
<ide> import com.xnx3.j2ee.service.SystemService;
<ide>
<ide> /**
<ide> public class InitServlet extends HttpServlet {
<ide> private PostClassService postClassService;
<ide> private SystemService systemService;
<add> private RoleService roleService;
<ide>
<ide> @Override
<ide> public void init(ServletConfig servletContext) throws ServletException {
<ide> ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext.getServletContext());
<ide> postClassService = ctx.getBean("postClassService", PostClassService.class);
<ide> systemService = ctx.getBean("systemService", SystemService.class);
<add> roleService = ctx.getBean("roleService",RoleService.class);
<ide>
<ide> String path = getClass().getResource("/").getPath();
<ide> Global.projectPath = path.replace("WEB-INF/classes/", "");
<ide> generateCache_postClass();
<ide> new Message().state();
<ide> new Message().isdelete();
<add> new Role().role(roleService.findAll());
<add> new User().isfreeze();
<ide> loadLogType();
<ide>
<ide> readSystemTable();
<ide> */
<ide> public void generateCache_postClass(){
<ide> List<PostClass> list = postClassService.findByIsdelete(BaseEntity.ISDELETE_NORMAL);
<del>// List<PostClass> list = postClassService.findAll();
<ide> new Bbs().postClass(list);
<ide> }
<add>
<ide>
<ide> /**
<ide> * 读system表数据 |
|
Java | apache-2.0 | 08b67c89a49082f55c540681ed8923a54e53b3dd | 0 | AI-comp/JavaChallenge2015,AI-comp/JavaChallenge2015,AI-comp/JavaChallenge2015 | package net.javachallenge;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Bookmaker {
private static boolean DEBUG = false;
private static final int PLAYERS_NUM = 4;
private static final int MAP_WIDTH = 40;
private static final int BLOCK_WIDTH = 5;
private static final int INITIAL_LIFE = 5;// ゲーム開始時の残機
private static final int FORCED_END_TURN = 10000;// ゲームが強制終了するターン
private static final int PANEL_REBIRTH_TURN = 5 * 4;// パネルが再生するまでのターン数
public static final int PLAYER_REBIRTH_TURN = 5 * 4;// プレイヤーが再生するまでのターン数
public static final int ATTACKED_PAUSE_TURN = 5 * 4;// 攻撃後の硬直している時間
public static final int MUTEKI_TURN = 10 * 4;// 再生直後の無敵ターン数
private static final int REPULSION = 7;// プレイヤーの反発範囲
public static final int ACTION_TIME_LIMIT = 2000;
public static final String READY = "Ready";
public static final String UP = "U";
public static final String DOWN = "D";
public static final String RIGHT = "R";
public static final String LEFT = "L";
public static final String ATTACK = "A";
public static final String NONE = "N";
public static final String[] DIRECTION = { UP, LEFT, DOWN, RIGHT };
private static Player[] players;
private static Random rnd;
private static int turn;
private static int[][] board = new int[MAP_WIDTH][MAP_WIDTH];
public static void main(String[] args) throws InterruptedException {
// AIの実行コマンドを引数から読み出す
String[] execAICommands = new String[PLAYERS_NUM];
String[] pauseAICommands = new String[PLAYERS_NUM];
String[] unpauseAICommands = new String[PLAYERS_NUM];
for (int i = 0; i < PLAYERS_NUM; i++) {
execAICommands[i] = "";
pauseAICommands[i] = null;
unpauseAICommands[i] = null;
}
int cur = 0;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-ai")) {
if (cur == 4) {
continue;
}
execAICommands[cur] = args[++i];
if (!args[++i].equals("-ai")) {
pauseAICommands[cur] = args[i];
}
if (!args[++i].equals("-ai")) {
unpauseAICommands[cur] = args[i];
}
cur++;
} else if (args[i].equals("--debug")) {
DEBUG = true;
}
}
// 乱数・ターン数の初期化
rnd = new Random(System.currentTimeMillis());
turn = 0;
// AIの実行
players = new Player[PLAYERS_NUM];
for (int i = 0; i < players.length; i++) {
players[i] = new Player(INITIAL_LIFE, execAICommands[i],
pauseAICommands[i], unpauseAICommands[i]);
}
// プレイヤーを初期配置する
rebirthPhase();
// ゲーム
while (!isFinished()) {
int turnPlayer = turn % PLAYERS_NUM;
// AIに情報を渡してコマンドを受け取る
String command = infromationPhase(turnPlayer);
// 盤面の状態とAIの出したコマンドをログに出力
printLOG(command);
// DEBUGプレイ
if (DEBUG && turnPlayer == 0 && players[turnPlayer].isOnBoard()
&& !players[turnPlayer].isPausing(turn)) {
command = new Scanner(System.in).next();
}
// コマンドを実行する
actionPhase(turnPlayer, command);
// パネル・プレイヤーの落下と復活
rebirthPhase();
turn++;
}
System.out.println("Game Finished!");
}
private static void printLOG(String command) {
// ターン数の出力
System.out.println(turn);
// 残機の出力
for (Player player : players) {
System.out.print(player.life + " ");
}
System.out.println();
// ボードを表示
for (int x = 0; x < MAP_WIDTH; x++) {
outer: for (int y = 0; y < MAP_WIDTH; y++) {
if (DEBUG) {
// プレイヤーがいるならそれを表示
for (int playerID = 0; playerID < PLAYERS_NUM; playerID++) {
Player player = players[playerID];
if (player.isOnBoard() && player.x == x
&& player.y == y) {
char c = (char) (playerID + 'A');
System.out.print(c + "" + c);
continue outer;
}
}
}
System.out.print(" " + board[x][y]);
}
System.out.println();
}
// いる座標と向きを表示
for (Player player : players) {
if (player.isOnBoard()) {
System.out.println(player.x + " " + player.y + " "
+ Bookmaker.DIRECTION[player.dir]);
} else {
System.out.println((-1) + " " + (-1) + " "
+ Bookmaker.DIRECTION[player.dir]);
}
}
// そのターンに行動したプレーヤーの出すコマンドを出力
System.out.println(command);
}
// パネルやプレーヤーを落としたり復活させたりする
private static void rebirthPhase() {
// パネルを落としたり復活させたりする
for (int i = 0; i < MAP_WIDTH; i++) {
for (int j = 0; j < MAP_WIDTH; j++) {
if (board[i][j] < 0) {
board[i][j]++;
} else if (board[i][j] == 1) {
board[i][j] = -PANEL_REBIRTH_TURN;
} else if (board[i][j] > 1) {
board[i][j]--;
}
}
}
// プレイヤーを落としたり復活させたりする
for (int i = 0; i < PLAYERS_NUM; i++) {
Player p = players[i];
// 落とす
if (p.isOnBoard() && !p.isMuteki(turn)) {
if (board[p.x][p.y] < 0) {
p.drop(turn);
}
} else if (p.isAlive() && !p.isOnBoard() && p.rebirthTurn == turn) {
// 復活させる
// 復活場所を探す
search: while (true) {
int x = nextInt();
int y = nextInt();
for (int j = 0; j < PLAYERS_NUM; j++) {
if (i == j) {
continue;
}
Player other = players[j];
if (other.isOnBoard()
&& dist(x, y, other.x, other.y) <= REPULSION) {
// 敵に近過ぎたらだめ
continue search;
}
}
// x,yに復活させる
p.reBirthOn(x, y, turn);
p.dir = nextDir();
break;
}
}
}
}
// AIに情報を渡してコマンドを受け取る
private static String infromationPhase(int turnPlayer) {
if (!players[turnPlayer].isAlive()) {
return NONE;
}
// AIに渡すための情報を整形
ArrayList<Integer> lifes = new ArrayList<Integer>();
ArrayList<String> wheres = new ArrayList<String>();
for (int i = 0; i < PLAYERS_NUM; i++) {
lifes.add(players[i].life);
if (players[i].isOnBoard()) {
wheres.add(players[i].x + " " + players[i].y);
} else {
wheres.add((-1) + " " + (-1));
}
}
// 情報をAIに渡してコマンドを受け取る
String command = players[turnPlayer].getAction(turnPlayer, turn, board,
lifes, wheres);
return command;
}
// AIから受け取ったアクションを実行する
private static void actionPhase(int turnPlayer, String command) {
Player p = players[turnPlayer];
if (!p.isOnBoard() || p.isPausing(turn) || command.equals(NONE)) {
return;
}
// 攻撃を処理
if (command.equals(ATTACK)) {
// 今いるブロックを出す
int xNow = p.x / BLOCK_WIDTH;
int yNow = p.y / BLOCK_WIDTH;
for (int x = 0; x < MAP_WIDTH; x++) {
for (int y = 0; y < MAP_WIDTH; y++) {
int xBlock = x / BLOCK_WIDTH;
int yBlock = y / BLOCK_WIDTH;
if (p.dir == 0) {
// 上向きの時
// xが減っていく
// yは同じ
if (yBlock == yNow && xBlock < xNow && board[x][y] == 0) {
board[x][y] = dist(xBlock, yBlock, xNow, yNow);
}
} else if (p.dir == 1) {
// 右向きの時
// yは増えていき、xは同じ
if (xBlock == xNow && yBlock < yNow && board[x][y] == 0) {
board[x][y] = dist(xBlock, yBlock, xNow, yNow);
}
} else if (p.dir == 2) {
// 下向きの時
// xは増え、yは同じ
if (yBlock == yNow && xBlock > xNow && board[x][y] == 0) {
board[x][y] = dist(xBlock, yBlock, xNow, yNow);
}
} else if (p.dir == 3) {
// 左向きの時
if (xBlock == xNow && yBlock > yNow && board[x][y] == 0) {
board[x][y] = dist(xBlock, yBlock, xNow, yNow);
}
}
}
}
// 攻撃すると硬直する
p.attackedPause(turn);
return;
}
// 移動処理
{
int tox = -1, toy = -1;
if (command.equals(UP)) {
tox = p.x - 1;
toy = p.y;
} else if (command.equals(RIGHT)) {
tox = p.x;
toy = p.y + 1;
} else if (command.equals(DOWN)) {
tox = p.x + 1;
toy = p.y;
} else if (command.equals(LEFT)) {
tox = p.x;
toy = p.y - 1;
} else {
return;
}
// ボード外への移動を指定している場合はスルー
if (!isInside(tox, toy)) {
return;
}
p.directTo(command);
// 移動先でぶつからないかどうかチェック
for (int i = 0; i < PLAYERS_NUM; i++) {
if (!players[i].isOnBoard() || i == turnPlayer) {
continue;
}
if (dist(tox, toy, players[i].x, players[i].y) < REPULSION) {
// 移動先でぶつかる時
return;
}
}
// ぶつからなければ移動
p.moveTo(tox, toy);
}
}
// マンハッタン距離計算
private static int dist(int x1, int y1, int x2, int y2) {
return Math.abs(x1 - x2) + Math.abs(y1 - y2);
}
// ランダムな座標を返す
private static int nextInt() {
int ret = (int) (rnd.nextDouble() * MAP_WIDTH);
return ret;
}
// ランダムな向きを返す
private static int nextDir() {
int rng = rnd.nextInt(4);
return rng;
}
private static boolean isInside(int x, int y) {
return 0 <= x && x < MAP_WIDTH && 0 <= y && y < MAP_WIDTH;
}
private static boolean isFinished() {
int livingCnt = 0;
for (int i = 0; i < players.length; i++) {
if (players[i].life > 0) {
livingCnt++;
}
}
return livingCnt == 1 || turn > FORCED_END_TURN;
}
}
| src/main/java/net/javachallenge/Bookmaker.java | package net.javachallenge;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Bookmaker {
private static boolean DEBUG = false;
private static final int PLAYERS_NUM = 4;
private static final int MAP_WIDTH = 40;
private static final int BLOCK_WIDTH = 5;
private static final int INITIAL_LIFE = 5;// ゲーム開始時の残機
private static final int FORCED_END_TURN = 10000;// ゲームが強制終了するターン
private static final int PANEL_REBIRTH_TURN = 5 * 4;// パネルが再生するまでのターン数
public static final int PLAYER_REBIRTH_TURN = 5 * 4;// プレイヤーが再生するまでのターン数
public static final int ATTACKED_PAUSE_TURN = 5 * 4;// 攻撃後の硬直している時間
public static final int MUTEKI_TURN = 10 * 4;// 再生直後の無敵ターン数
private static final int REPULSION = 7;// プレイヤーの反発範囲
public static final int ACTION_TIME_LIMIT = 2000;
public static final String READY = "Ready";
public static final String UP = "U";
public static final String DOWN = "D";
public static final String RIGHT = "R";
public static final String LEFT = "L";
public static final String ATTACK = "A";
public static final String NONE = "N";
public static final String[] DIRECTION = { UP, LEFT, DOWN, RIGHT };
private static Player[] players;
private static Random rnd;
private static int turn;
private static int[][] board = new int[MAP_WIDTH][MAP_WIDTH];
public static void main(String[] args) throws InterruptedException {
// AIの実行コマンドを引数から読み出す
String[] execAICommands = new String[PLAYERS_NUM];
String[] pauseAICommands = new String[PLAYERS_NUM];
String[] unpauseAICommands = new String[PLAYERS_NUM];
for (int i = 0; i < PLAYERS_NUM; i++) {
execAICommands[i] = "";
pauseAICommands[i] = null;
unpauseAICommands[i] = null;
}
int cur = 0;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-ai")) {
if (cur == 4) {
continue;
}
execAICommands[cur] = args[++i];
if (!args[++i].equals("-ai")) {
pauseAICommands[cur] = args[i];
}
if (!args[++i].equals("-ai")) {
unpauseAICommands[cur] = args[i];
}
} else if (args[i].equals("--debug")) {
DEBUG = true;
}
}
// 乱数・ターン数の初期化
rnd = new Random(System.currentTimeMillis());
turn = 0;
// AIの実行
players = new Player[PLAYERS_NUM];
for (int i = 0; i < players.length; i++) {
players[i] = new Player(INITIAL_LIFE, execAICommands[i],
pauseAICommands[i], unpauseAICommands[i]);
}
// プレイヤーを初期配置する
rebirthPhase();
// ゲーム
while (!isFinished()) {
int turnPlayer = turn % PLAYERS_NUM;
// AIに情報を渡してコマンドを受け取る
String command = infromationPhase(turnPlayer);
// 盤面の状態とAIの出したコマンドをログに出力
printLOG(command);
// DEBUGプレイ
if (DEBUG && turnPlayer == 0 && players[turnPlayer].isOnBoard()
&& !players[turnPlayer].isPausing(turn)) {
command = new Scanner(System.in).next();
}
// コマンドを実行する
actionPhase(turnPlayer, command);
// パネル・プレイヤーの落下と復活
rebirthPhase();
turn++;
}
System.out.println("Game Finished!");
}
private static void printLOG(String command) {
// ターン数の出力
System.out.println(turn);
// 残機の出力
for (Player player : players) {
System.out.print(player.life + " ");
}
System.out.println();
// ボードを表示
for (int x = 0; x < MAP_WIDTH; x++) {
outer: for (int y = 0; y < MAP_WIDTH; y++) {
if (DEBUG) {
// プレイヤーがいるならそれを表示
for (int playerID = 0; playerID < PLAYERS_NUM; playerID++) {
Player player = players[playerID];
if (player.isOnBoard() && player.x == x
&& player.y == y) {
char c = (char) (playerID + 'A');
System.out.print(c + "" + c);
continue outer;
}
}
}
System.out.print(" " + board[x][y]);
}
System.out.println();
}
// いる座標と向きを表示
for (Player player : players) {
if (player.isOnBoard()) {
System.out.println(player.x + " " + player.y + " "
+ Bookmaker.DIRECTION[player.dir]);
} else {
System.out.println((-1) + " " + (-1) + " "
+ Bookmaker.DIRECTION[player.dir]);
}
}
// そのターンに行動したプレーヤーの出すコマンドを出力
System.out.println(command);
}
// パネルやプレーヤーを落としたり復活させたりする
private static void rebirthPhase() {
// パネルを落としたり復活させたりする
for (int i = 0; i < MAP_WIDTH; i++) {
for (int j = 0; j < MAP_WIDTH; j++) {
if (board[i][j] < 0) {
board[i][j]++;
} else if (board[i][j] == 1) {
board[i][j] = -PANEL_REBIRTH_TURN;
} else if (board[i][j] > 1) {
board[i][j]--;
}
}
}
// プレイヤーを落としたり復活させたりする
for (int i = 0; i < PLAYERS_NUM; i++) {
Player p = players[i];
// 落とす
if (p.isOnBoard() && !p.isMuteki(turn)) {
if (board[p.x][p.y] < 0) {
p.drop(turn);
}
} else if (p.isAlive() && !p.isOnBoard() && p.rebirthTurn == turn) {
// 復活させる
// 復活場所を探す
search: while (true) {
int x = nextInt();
int y = nextInt();
for (int j = 0; j < PLAYERS_NUM; j++) {
if (i == j) {
continue;
}
Player other = players[j];
if (other.isOnBoard()
&& dist(x, y, other.x, other.y) <= REPULSION) {
// 敵に近過ぎたらだめ
continue search;
}
}
// x,yに復活させる
p.reBirthOn(x, y, turn);
p.dir = nextDir();
break;
}
}
}
}
// AIに情報を渡してコマンドを受け取る
private static String infromationPhase(int turnPlayer) {
if (!players[turnPlayer].isAlive()) {
return NONE;
}
// AIに渡すための情報を整形
ArrayList<Integer> lifes = new ArrayList<Integer>();
ArrayList<String> wheres = new ArrayList<String>();
for (int i = 0; i < PLAYERS_NUM; i++) {
lifes.add(players[i].life);
if (players[i].isOnBoard()) {
wheres.add(players[i].x + " " + players[i].y);
} else {
wheres.add((-1) + " " + (-1));
}
}
// 情報をAIに渡してコマンドを受け取る
String command = players[turnPlayer].getAction(turnPlayer, turn, board,
lifes, wheres);
return command;
}
// AIから受け取ったアクションを実行する
private static void actionPhase(int turnPlayer, String command) {
Player p = players[turnPlayer];
if (!p.isOnBoard() || p.isPausing(turn) || command.equals(NONE)) {
return;
}
// 攻撃を処理
if (command.equals(ATTACK)) {
// 今いるブロックを出す
int xNow = p.x / BLOCK_WIDTH;
int yNow = p.y / BLOCK_WIDTH;
for (int x = 0; x < MAP_WIDTH; x++) {
for (int y = 0; y < MAP_WIDTH; y++) {
int xBlock = x / BLOCK_WIDTH;
int yBlock = y / BLOCK_WIDTH;
if (p.dir == 0) {
// 上向きの時
// xが減っていく
// yは同じ
if (yBlock == yNow && xBlock < xNow && board[x][y] == 0) {
board[x][y] = dist(xBlock, yBlock, xNow, yNow);
}
} else if (p.dir == 1) {
// 右向きの時
// yは増えていき、xは同じ
if (xBlock == xNow && yBlock < yNow && board[x][y] == 0) {
board[x][y] = dist(xBlock, yBlock, xNow, yNow);
}
} else if (p.dir == 2) {
// 下向きの時
// xは増え、yは同じ
if (yBlock == yNow && xBlock > xNow && board[x][y] == 0) {
board[x][y] = dist(xBlock, yBlock, xNow, yNow);
}
} else if (p.dir == 3) {
// 左向きの時
if (xBlock == xNow && yBlock > yNow && board[x][y] == 0) {
board[x][y] = dist(xBlock, yBlock, xNow, yNow);
}
}
}
}
// 攻撃すると硬直する
p.attackedPause(turn);
return;
}
// 移動処理
{
int tox = -1, toy = -1;
if (command.equals(UP)) {
tox = p.x - 1;
toy = p.y;
} else if (command.equals(RIGHT)) {
tox = p.x;
toy = p.y + 1;
} else if (command.equals(DOWN)) {
tox = p.x + 1;
toy = p.y;
} else if (command.equals(LEFT)) {
tox = p.x;
toy = p.y - 1;
} else {
return;
}
// ボード外への移動を指定している場合はスルー
if (!isInside(tox, toy)) {
return;
}
p.directTo(command);
// 移動先でぶつからないかどうかチェック
for (int i = 0; i < PLAYERS_NUM; i++) {
if (!players[i].isOnBoard() || i == turnPlayer) {
continue;
}
if (dist(tox, toy, players[i].x, players[i].y) < REPULSION) {
// 移動先でぶつかる時
return;
}
}
// ぶつからなければ移動
p.moveTo(tox, toy);
}
}
// マンハッタン距離計算
private static int dist(int x1, int y1, int x2, int y2) {
return Math.abs(x1 - x2) + Math.abs(y1 - y2);
}
// ランダムな座標を返す
private static int nextInt() {
int ret = (int) (rnd.nextDouble() * MAP_WIDTH);
return ret;
}
// ランダムな向きを返す
private static int nextDir() {
int rng = rnd.nextInt(4);
return rng;
}
private static boolean isInside(int x, int y) {
return 0 <= x && x < MAP_WIDTH && 0 <= y && y < MAP_WIDTH;
}
private static boolean isFinished() {
int livingCnt = 0;
for (int i = 0; i < players.length; i++) {
if (players[i].life > 0) {
livingCnt++;
}
}
return livingCnt == 1 || turn > FORCED_END_TURN;
}
}
| cur++ 忘れてた | src/main/java/net/javachallenge/Bookmaker.java | cur++ 忘れてた | <ide><path>rc/main/java/net/javachallenge/Bookmaker.java
<ide> if (cur == 4) {
<ide> continue;
<ide> }
<add>
<ide> execAICommands[cur] = args[++i];
<ide> if (!args[++i].equals("-ai")) {
<ide> pauseAICommands[cur] = args[i];
<ide> if (!args[++i].equals("-ai")) {
<ide> unpauseAICommands[cur] = args[i];
<ide> }
<add> cur++;
<ide> } else if (args[i].equals("--debug")) {
<ide> DEBUG = true;
<ide> } |
|
JavaScript | apache-2.0 | 65d1c5262f7007c2fbc04f42f07ae10f315453b9 | 0 | YaManicKill/flairhq,Kirzi/flairhq,YaManicKill/flairhq,Kirzi/flairhq,robertdyjas/flairhq,pokemontrades/flairhq,pokemontrades/flairhq,robertdyjas/flairhq | /*! Socket.IO.min.js build:0.9.16, production. Copyright(c) 2011 LearnBoost <[email protected]> MIT Licensed */
var io="undefined"==typeof module?{}:module.exports;(function(){(function(a,b){var c=a;c.version="0.9.16",c.protocol=1,c.transports=[],c.j=[],c.sockets={},c.connect=function(a,d){var e=c.util.parseUri(a),f,g;b&&b.location&&(e.protocol=e.protocol||b.location.protocol.slice(0,-1),e.host=e.host||(b.document?b.document.domain:b.location.hostname),e.port=e.port||b.location.port),f=c.util.uniqueUri(e);var h={host:e.host,secure:"https"==e.protocol,port:e.port||("https"==e.protocol?443:80),query:e.query||""};c.util.merge(h,d);if(h["force new connection"]||!c.sockets[f])g=new c.Socket(h);return!h["force new connection"]&&g&&(c.sockets[f]=g),g=g||c.sockets[f],g.of(e.path.length>1?e.path:"")}})("object"==typeof module?module.exports:this.io={},this),function(a,b){var c=a.util={},d=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,e=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];c.parseUri=function(a){var b=d.exec(a||""),c={},f=14;while(f--)c[e[f]]=b[f]||"";return c},c.uniqueUri=function(a){var c=a.protocol,d=a.host,e=a.port;return"document"in b?(d=d||document.domain,e=e||(c=="https"&&document.location.protocol!=="https:"?443:document.location.port)):(d=d||"localhost",!e&&c=="https"&&(e=443)),(c||"http")+"://"+d+":"+(e||80)},c.query=function(a,b){var d=c.chunkQuery(a||""),e=[];c.merge(d,c.chunkQuery(b||""));for(var f in d)d.hasOwnProperty(f)&&e.push(f+"="+d[f]);return e.length?"?"+e.join("&"):""},c.chunkQuery=function(a){var b={},c=a.split("&"),d=0,e=c.length,f;for(;d<e;++d)f=c[d].split("="),f[0]&&(b[f[0]]=f[1]);return b};var f=!1;c.load=function(a){if("document"in b&&document.readyState==="complete"||f)return a();c.on(b,"load",a,!1)},c.on=function(a,b,c,d){a.attachEvent?a.attachEvent("on"+b,c):a.addEventListener&&a.addEventListener(b,c,d)},c.request=function(a){if(a&&"undefined"!=typeof XDomainRequest&&!c.ua.hasCORS)return new XDomainRequest;if("undefined"!=typeof XMLHttpRequest&&(!a||c.ua.hasCORS))return new XMLHttpRequest;if(!a)try{return new(window[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(b){}return null},"undefined"!=typeof window&&c.load(function(){f=!0}),c.defer=function(a){if(!c.ua.webkit||"undefined"!=typeof importScripts)return a();c.load(function(){setTimeout(a,100)})},c.merge=function(b,d,e,f){var g=f||[],h=typeof e=="undefined"?2:e,i;for(i in d)d.hasOwnProperty(i)&&c.indexOf(g,i)<0&&(typeof b[i]!="object"||!h?(b[i]=d[i],g.push(d[i])):c.merge(b[i],d[i],h-1,g));return b},c.mixin=function(a,b){c.merge(a.prototype,b.prototype)},c.inherit=function(a,b){function c(){}c.prototype=b.prototype,a.prototype=new c},c.isArray=Array.isArray||function(a){return Object.prototype.toString.call(a)==="[object Array]"},c.intersect=function(a,b){var d=[],e=a.length>b.length?a:b,f=a.length>b.length?b:a;for(var g=0,h=f.length;g<h;g++)~c.indexOf(e,f[g])&&d.push(f[g]);return d},c.indexOf=function(a,b,c){for(var d=a.length,c=c<0?c+d<0?0:c+d:c||0;c<d&&a[c]!==b;c++);return d<=c?-1:c},c.toArray=function(a){var b=[];for(var c=0,d=a.length;c<d;c++)b.push(a[c]);return b},c.ua={},c.ua.hasCORS="undefined"!=typeof XMLHttpRequest&&function(){try{var a=new XMLHttpRequest}catch(b){return!1}return a.withCredentials!=undefined}(),c.ua.webkit="undefined"!=typeof navigator&&/webkit/i.test(navigator.userAgent),c.ua.iDevice="undefined"!=typeof navigator&&/iPad|iPhone|iPod/i.test(navigator.userAgent)}("undefined"!=typeof io?io:module.exports,this),function(a,b){function c(){}a.EventEmitter=c,c.prototype.on=function(a,c){return this.$events||(this.$events={}),this.$events[a]?b.util.isArray(this.$events[a])?this.$events[a].push(c):this.$events[a]=[this.$events[a],c]:this.$events[a]=c,this},c.prototype.addListener=c.prototype.on,c.prototype.once=function(a,b){function d(){c.removeListener(a,d),b.apply(this,arguments)}var c=this;return d.listener=b,this.on(a,d),this},c.prototype.removeListener=function(a,c){if(this.$events&&this.$events[a]){var d=this.$events[a];if(b.util.isArray(d)){var e=-1;for(var f=0,g=d.length;f<g;f++)if(d[f]===c||d[f].listener&&d[f].listener===c){e=f;break}if(e<0)return this;d.splice(e,1),d.length||delete this.$events[a]}else(d===c||d.listener&&d.listener===c)&&delete this.$events[a]}return this},c.prototype.removeAllListeners=function(a){return a===undefined?(this.$events={},this):(this.$events&&this.$events[a]&&(this.$events[a]=null),this)},c.prototype.listeners=function(a){return this.$events||(this.$events={}),this.$events[a]||(this.$events[a]=[]),b.util.isArray(this.$events[a])||(this.$events[a]=[this.$events[a]]),this.$events[a]},c.prototype.emit=function(a){if(!this.$events)return!1;var c=this.$events[a];if(!c)return!1;var d=Array.prototype.slice.call(arguments,1);if("function"==typeof c)c.apply(this,d);else{if(!b.util.isArray(c))return!1;var e=c.slice();for(var f=0,g=e.length;f<g;f++)e[f].apply(this,d)}return!0}}("undefined"!=typeof io?io:module.exports,"undefined"!=typeof io?io:module.parent.exports),function(exports,nativeJSON){function f(a){return a<10?"0"+a:a}function date(a,b){return isFinite(a.valueOf())?a.getUTCFullYear()+"-"+f(a.getUTCMonth()+1)+"-"+f(a.getUTCDate())+"T"+f(a.getUTCHours())+":"+f(a.getUTCMinutes())+":"+f(a.getUTCSeconds())+"Z":null}function quote(a){return escapable.lastIndex=0,escapable.test(a)?'"'+a.replace(escapable,function(a){var b=meta[a];return typeof b=="string"?b:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+a+'"'}function str(a,b){var c,d,e,f,g=gap,h,i=b[a];i instanceof Date&&(i=date(a)),typeof rep=="function"&&(i=rep.call(b,a,i));switch(typeof i){case"string":return quote(i);case"number":return isFinite(i)?String(i):"null";case"boolean":case"null":return String(i);case"object":if(!i)return"null";gap+=indent,h=[];if(Object.prototype.toString.apply(i)==="[object Array]"){f=i.length;for(c=0;c<f;c+=1)h[c]=str(c,i)||"null";return e=h.length===0?"[]":gap?"[\n"+gap+h.join(",\n"+gap)+"\n"+g+"]":"["+h.join(",")+"]",gap=g,e}if(rep&&typeof rep=="object"){f=rep.length;for(c=0;c<f;c+=1)typeof rep[c]=="string"&&(d=rep[c],e=str(d,i),e&&h.push(quote(d)+(gap?": ":":")+e))}else for(d in i)Object.prototype.hasOwnProperty.call(i,d)&&(e=str(d,i),e&&h.push(quote(d)+(gap?": ":":")+e));return e=h.length===0?"{}":gap?"{\n"+gap+h.join(",\n"+gap)+"\n"+g+"}":"{"+h.join(",")+"}",gap=g,e}}"use strict";if(nativeJSON&&nativeJSON.parse)return exports.JSON={parse:nativeJSON.parse,stringify:nativeJSON.stringify};var JSON=exports.JSON={},cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;JSON.stringify=function(a,b,c){var d;gap="",indent="";if(typeof c=="number")for(d=0;d<c;d+=1)indent+=" ";else typeof c=="string"&&(indent=c);rep=b;if(!b||typeof b=="function"||typeof b=="object"&&typeof b.length=="number")return str("",{"":a});throw new Error("JSON.stringify")},JSON.parse=function(text,reviver){function walk(a,b){var c,d,e=a[b];if(e&&typeof e=="object")for(c in e)Object.prototype.hasOwnProperty.call(e,c)&&(d=walk(e,c),d!==undefined?e[c]=d:delete e[c]);return reviver.call(a,b,e)}var j;text=String(text),cx.lastIndex=0,cx.test(text)&&(text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)}));if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return j=eval("("+text+")"),typeof reviver=="function"?walk({"":j},""):j;throw new SyntaxError("JSON.parse")}}("undefined"!=typeof io?io:module.exports,typeof JSON!="undefined"?JSON:undefined),function(a,b){var c=a.parser={},d=c.packets=["disconnect","connect","heartbeat","message","json","event","ack","error","noop"],e=c.reasons=["transport not supported","client not handshaken","unauthorized"],f=c.advice=["reconnect"],g=b.JSON,h=b.util.indexOf;c.encodePacket=function(a){var b=h(d,a.type),c=a.id||"",i=a.endpoint||"",j=a.ack,k=null;switch(a.type){case"error":var l=a.reason?h(e,a.reason):"",m=a.advice?h(f,a.advice):"";if(l!==""||m!=="")k=l+(m!==""?"+"+m:"");break;case"message":a.data!==""&&(k=a.data);break;case"event":var n={name:a.name};a.args&&a.args.length&&(n.args=a.args),k=g.stringify(n);break;case"json":k=g.stringify(a.data);break;case"connect":a.qs&&(k=a.qs);break;case"ack":k=a.ackId+(a.args&&a.args.length?"+"+g.stringify(a.args):"")}var o=[b,c+(j=="data"?"+":""),i];return k!==null&&k!==undefined&&o.push(k),o.join(":")},c.encodePayload=function(a){var b="";if(a.length==1)return a[0];for(var c=0,d=a.length;c<d;c++){var e=a[c];b+="\ufffd"+e.length+"\ufffd"+a[c]}return b};var i=/([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/;c.decodePacket=function(a){var b=a.match(i);if(!b)return{};var c=b[2]||"",a=b[5]||"",h={type:d[b[1]],endpoint:b[4]||""};c&&(h.id=c,b[3]?h.ack="data":h.ack=!0);switch(h.type){case"error":var b=a.split("+");h.reason=e[b[0]]||"",h.advice=f[b[1]]||"";break;case"message":h.data=a||"";break;case"event":try{var j=g.parse(a);h.name=j.name,h.args=j.args}catch(k){}h.args=h.args||[];break;case"json":try{h.data=g.parse(a)}catch(k){}break;case"connect":h.qs=a||"";break;case"ack":var b=a.match(/^([0-9]+)(\+)?(.*)/);if(b){h.ackId=b[1],h.args=[];if(b[3])try{h.args=b[3]?g.parse(b[3]):[]}catch(k){}}break;case"disconnect":case"heartbeat":}return h},c.decodePayload=function(a){if(a.charAt(0)=="\ufffd"){var b=[];for(var d=1,e="";d<a.length;d++)a.charAt(d)=="\ufffd"?(b.push(c.decodePacket(a.substr(d+1).substr(0,e))),d+=Number(e)+1,e=""):e+=a.charAt(d);return b}return[c.decodePacket(a)]}}("undefined"!=typeof io?io:module.exports,"undefined"!=typeof io?io:module.parent.exports),function(a,b){function c(a,b){this.socket=a,this.sessid=b}a.Transport=c,b.util.mixin(c,b.EventEmitter),c.prototype.heartbeats=function(){return!0},c.prototype.onData=function(a){this.clearCloseTimeout(),(this.socket.connected||this.socket.connecting||this.socket.reconnecting)&&this.setCloseTimeout();if(a!==""){var c=b.parser.decodePayload(a);if(c&&c.length)for(var d=0,e=c.length;d<e;d++)this.onPacket(c[d])}return this},c.prototype.onPacket=function(a){return this.socket.setHeartbeatTimeout(),a.type=="heartbeat"?this.onHeartbeat():(a.type=="connect"&&a.endpoint==""&&this.onConnect(),a.type=="error"&&a.advice=="reconnect"&&(this.isOpen=!1),this.socket.onPacket(a),this)},c.prototype.setCloseTimeout=function(){if(!this.closeTimeout){var a=this;this.closeTimeout=setTimeout(function(){a.onDisconnect()},this.socket.closeTimeout)}},c.prototype.onDisconnect=function(){return this.isOpen&&this.close(),this.clearTimeouts(),this.socket.onDisconnect(),this},c.prototype.onConnect=function(){return this.socket.onConnect(),this},c.prototype.clearCloseTimeout=function(){this.closeTimeout&&(clearTimeout(this.closeTimeout),this.closeTimeout=null)},c.prototype.clearTimeouts=function(){this.clearCloseTimeout(),this.reopenTimeout&&clearTimeout(this.reopenTimeout)},c.prototype.packet=function(a){this.send(b.parser.encodePacket(a))},c.prototype.onHeartbeat=function(a){this.packet({type:"heartbeat"})},c.prototype.onOpen=function(){this.isOpen=!0,this.clearCloseTimeout(),this.socket.onOpen()},c.prototype.onClose=function(){var a=this;this.isOpen=!1,this.socket.onClose(),this.onDisconnect()},c.prototype.prepareUrl=function(){var a=this.socket.options;return this.scheme()+"://"+a.host+":"+a.port+"/"+a.resource+"/"+b.protocol+"/"+this.name+"/"+this.sessid},c.prototype.ready=function(a,b){b.call(this)}}("undefined"!=typeof io?io:module.exports,"undefined"!=typeof io?io:module.parent.exports),function(a,b,c){function d(a){this.options={port:80,secure:!1,document:"document"in c?document:!1,resource:"socket.io",transports:b.transports,"connect timeout":1e4,"try multiple transports":!0,reconnect:!0,"reconnection delay":500,"reconnection limit":Infinity,"reopen delay":3e3,"max reconnection attempts":10,"sync disconnect on unload":!1,"auto connect":!0,"flash policy port":10843,manualFlush:!1},b.util.merge(this.options,a),this.connected=!1,this.open=!1,this.connecting=!1,this.reconnecting=!1,this.namespaces={},this.buffer=[],this.doBuffer=!1;if(this.options["sync disconnect on unload"]&&(!this.isXDomain()||b.util.ua.hasCORS)){var d=this;b.util.on(c,"beforeunload",function(){d.disconnectSync()},!1)}this.options["auto connect"]&&this.connect()}function e(){}a.Socket=d,b.util.mixin(d,b.EventEmitter),d.prototype.of=function(a){return this.namespaces[a]||(this.namespaces[a]=new b.SocketNamespace(this,a),a!==""&&this.namespaces[a].packet({type:"connect"})),this.namespaces[a]},d.prototype.publish=function(){this.emit.apply(this,arguments);var a;for(var b in this.namespaces)this.namespaces.hasOwnProperty(b)&&(a=this.of(b),a.$emit.apply(a,arguments))},d.prototype.handshake=function(a){function f(b){b instanceof Error?(c.connecting=!1,c.onError(b.message)):a.apply(null,b.split(":"))}var c=this,d=this.options,g=["http"+(d.secure?"s":"")+":/",d.host+":"+d.port,d.resource,b.protocol,b.util.query(this.options.query,"t="+ +(new Date))].join("/");if(this.isXDomain()&&!b.util.ua.hasCORS){var h=document.getElementsByTagName("script")[0],i=document.createElement("script");i.src=g+"&jsonp="+b.j.length,h.parentNode.insertBefore(i,h),b.j.push(function(a){f(a),i.parentNode.removeChild(i)})}else{var j=b.util.request();j.open("GET",g,!0),this.isXDomain()&&(j.withCredentials=!0),j.onreadystatechange=function(){j.readyState==4&&(j.onreadystatechange=e,j.status==200?f(j.responseText):j.status==403?c.onError(j.responseText):(c.connecting=!1,!c.reconnecting&&c.onError(j.responseText)))},j.send(null)}},d.prototype.getTransport=function(a){var c=a||this.transports,d;for(var e=0,f;f=c[e];e++)if(b.Transport[f]&&b.Transport[f].check(this)&&(!this.isXDomain()||b.Transport[f].xdomainCheck(this)))return new b.Transport[f](this,this.sessionid);return null},d.prototype.connect=function(a){if(this.connecting)return this;var c=this;return c.connecting=!0,this.handshake(function(d,e,f,g){function h(a){c.transport&&c.transport.clearTimeouts(),c.transport=c.getTransport(a);if(!c.transport)return c.publish("connect_failed");c.transport.ready(c,function(){c.connecting=!0,c.publish("connecting",c.transport.name),c.transport.open(),c.options["connect timeout"]&&(c.connectTimeoutTimer=setTimeout(function(){if(!c.connected){c.connecting=!1;if(c.options["try multiple transports"]){var a=c.transports;while(a.length>0&&a.splice(0,1)[0]!=c.transport.name);a.length?h(a):c.publish("connect_failed")}}},c.options["connect timeout"]))})}c.sessionid=d,c.closeTimeout=f*1e3,c.heartbeatTimeout=e*1e3,c.transports||(c.transports=c.origTransports=g?b.util.intersect(g.split(","),c.options.transports):c.options.transports),c.setHeartbeatTimeout(),h(c.transports),c.once("connect",function(){clearTimeout(c.connectTimeoutTimer),a&&typeof a=="function"&&a()})}),this},d.prototype.setHeartbeatTimeout=function(){clearTimeout(this.heartbeatTimeoutTimer);if(this.transport&&!this.transport.heartbeats())return;var a=this;this.heartbeatTimeoutTimer=setTimeout(function(){a.transport.onClose()},this.heartbeatTimeout)},d.prototype.packet=function(a){return this.connected&&!this.doBuffer?this.transport.packet(a):this.buffer.push(a),this},d.prototype.setBuffer=function(a){this.doBuffer=a,!a&&this.connected&&this.buffer.length&&(this.options.manualFlush||this.flushBuffer())},d.prototype.flushBuffer=function(){this.transport.payload(this.buffer),this.buffer=[]},d.prototype.disconnect=function(){if(this.connected||this.connecting)this.open&&this.of("").packet({type:"disconnect"}),this.onDisconnect("booted");return this},d.prototype.disconnectSync=function(){var a=b.util.request(),c=["http"+(this.options.secure?"s":"")+":/",this.options.host+":"+this.options.port,this.options.resource,b.protocol,"",this.sessionid].join("/")+"/?disconnect=1";a.open("GET",c,!1),a.send(null),this.onDisconnect("booted")},d.prototype.isXDomain=function(){var a=c.location.port||("https:"==c.location.protocol?443:80);return this.options.host!==c.location.hostname||this.options.port!=a},d.prototype.onConnect=function(){this.connected||(this.connected=!0,this.connecting=!1,this.doBuffer||this.setBuffer(!1),this.emit("connect"))},d.prototype.onOpen=function(){this.open=!0},d.prototype.onClose=function(){this.open=!1,clearTimeout(this.heartbeatTimeoutTimer)},d.prototype.onPacket=function(a){this.of(a.endpoint).onPacket(a)},d.prototype.onError=function(a){a&&a.advice&&a.advice==="reconnect"&&(this.connected||this.connecting)&&(this.disconnect(),this.options.reconnect&&this.reconnect()),this.publish("error",a&&a.reason?a.reason:a)},d.prototype.onDisconnect=function(a){var b=this.connected,c=this.connecting;this.connected=!1,this.connecting=!1,this.open=!1;if(b||c)this.transport.close(),this.transport.clearTimeouts(),b&&(this.publish("disconnect",a),"booted"!=a&&this.options.reconnect&&!this.reconnecting&&this.reconnect())},d.prototype.reconnect=function(){function e(){if(a.connected){for(var b in a.namespaces)a.namespaces.hasOwnProperty(b)&&""!==b&&a.namespaces[b].packet({type:"connect"});a.publish("reconnect",a.transport.name,a.reconnectionAttempts)}clearTimeout(a.reconnectionTimer),a.removeListener("connect_failed",f),a.removeListener("connect",f),a.reconnecting=!1,delete a.reconnectionAttempts,delete a.reconnectionDelay,delete a.reconnectionTimer,delete a.redoTransports,a.options["try multiple transports"]=c}function f(){if(!a.reconnecting)return;if(a.connected)return e();if(a.connecting&&a.reconnecting)return a.reconnectionTimer=setTimeout(f,1e3);a.reconnectionAttempts++>=b?a.redoTransports?(a.publish("reconnect_failed"),e()):(a.on("connect_failed",f),a.options["try multiple transports"]=!0,a.transports=a.origTransports,a.transport=a.getTransport(),a.redoTransports=!0,a.connect()):(a.reconnectionDelay<d&&(a.reconnectionDelay*=2),a.connect(),a.publish("reconnecting",a.reconnectionDelay,a.reconnectionAttempts),a.reconnectionTimer=setTimeout(f,a.reconnectionDelay))}this.reconnecting=!0,this.reconnectionAttempts=0,this.reconnectionDelay=this.options["reconnection delay"];var a=this,b=this.options["max reconnection attempts"],c=this.options["try multiple transports"],d=this.options["reconnection limit"];this.options["try multiple transports"]=!1,this.reconnectionTimer=setTimeout(f,this.reconnectionDelay),this.on("connect",f)}}("undefined"!=typeof io?io:module.exports,"undefined"!=typeof io?io:module.parent.exports,this),function(a,b){function c(a,b){this.socket=a,this.name=b||"",this.flags={},this.json=new d(this,"json"),this.ackPackets=0,this.acks={}}function d(a,b){this.namespace=a,this.name=b}a.SocketNamespace=c,b.util.mixin(c,b.EventEmitter),c.prototype.$emit=b.EventEmitter.prototype.emit,c.prototype.of=function(){return this.socket.of.apply(this.socket,arguments)},c.prototype.packet=function(a){return a.endpoint=this.name,this.socket.packet(a),this.flags={},this},c.prototype.send=function(a,b){var c={type:this.flags.json?"json":"message",data:a};return"function"==typeof b&&(c.id=++this.ackPackets,c.ack=!0,this.acks[c.id]=b),this.packet(c)},c.prototype.emit=function(a){var b=Array.prototype.slice.call(arguments,1),c=b[b.length-1],d={type:"event",name:a};return"function"==typeof c&&(d.id=++this.ackPackets,d.ack="data",this.acks[d.id]=c,b=b.slice(0,b.length-1)),d.args=b,this.packet(d)},c.prototype.disconnect=function(){return this.name===""?this.socket.disconnect():(this.packet({type:"disconnect"}),this.$emit("disconnect")),this},c.prototype.onPacket=function(a){function d(){c.packet({type:"ack",args:b.util.toArray(arguments),ackId:a.id})}var c=this;switch(a.type){case"connect":this.$emit("connect");break;case"disconnect":this.name===""?this.socket.onDisconnect(a.reason||"booted"):this.$emit("disconnect",a.reason);break;case"message":case"json":var e=["message",a.data];a.ack=="data"?e.push(d):a.ack&&this.packet({type:"ack",ackId:a.id}),this.$emit.apply(this,e);break;case"event":var e=[a.name].concat(a.args);a.ack=="data"&&e.push(d),this.$emit.apply(this,e);break;case"ack":this.acks[a.ackId]&&(this.acks[a.ackId].apply(this,a.args),delete this.acks[a.ackId]);break;case"error":a.advice?this.socket.onError(a):a.reason=="unauthorized"?this.$emit("connect_failed",a.reason):this.$emit("error",a.reason)}},d.prototype.send=function(){this.namespace.flags[this.name]=!0,this.namespace.send.apply(this.namespace,arguments)},d.prototype.emit=function(){this.namespace.flags[this.name]=!0,this.namespace.emit.apply(this.namespace,arguments)}}("undefined"!=typeof io?io:module.exports,"undefined"!=typeof io?io:module.parent.exports),function(a,b,c){function d(a){b.Transport.apply(this,arguments)}a.websocket=d,b.util.inherit(d,b.Transport),d.prototype.name="websocket",d.prototype.open=function(){var a=b.util.query(this.socket.options.query),d=this,e;return e||(e=c.MozWebSocket||c.WebSocket),this.websocket=new e(this.prepareUrl()+a),this.websocket.onopen=function(){d.onOpen(),d.socket.setBuffer(!1)},this.websocket.onmessage=function(a){d.onData(a.data)},this.websocket.onclose=function(){d.onClose(),d.socket.setBuffer(!0)},this.websocket.onerror=function(a){d.onError(a)},this},b.util.ua.iDevice?d.prototype.send=function(a){var b=this;return setTimeout(function(){b.websocket.send(a)},0),this}:d.prototype.send=function(a){return this.websocket.send(a),this},d.prototype.payload=function(a){for(var b=0,c=a.length;b<c;b++)this.packet(a[b]);return this},d.prototype.close=function(){return this.websocket.close(),this},d.prototype.onError=function(a){this.socket.onError(a)},d.prototype.scheme=function(){return this.socket.options.secure?"wss":"ws"},d.check=function(){return"WebSocket"in c&&!("__addTask"in WebSocket)||"MozWebSocket"in c},d.xdomainCheck=function(){return!0},b.transports.push("websocket")}("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports,this),function(a,b){function c(){b.Transport.websocket.apply(this,arguments)}a.flashsocket=c,b.util.inherit(c,b.Transport.websocket),c.prototype.name="flashsocket",c.prototype.open=function(){var a=this,c=arguments;return WebSocket.__addTask(function(){b.Transport.websocket.prototype.open.apply(a,c)}),this},c.prototype.send=function(){var a=this,c=arguments;return WebSocket.__addTask(function(){b.Transport.websocket.prototype.send.apply(a,c)}),this},c.prototype.close=function(){return WebSocket.__tasks.length=0,b.Transport.websocket.prototype.close.call(this),this},c.prototype.ready=function(a,d){function e(){var b=a.options,e=b["flash policy port"],g=["http"+(b.secure?"s":"")+":/",b.host+":"+b.port,b.resource,"static/flashsocket","WebSocketMain"+(a.isXDomain()?"Insecure":"")+".swf"];c.loaded||(typeof WEB_SOCKET_SWF_LOCATION=="undefined"&&(WEB_SOCKET_SWF_LOCATION=g.join("/")),e!==843&&WebSocket.loadFlashPolicyFile("xmlsocket://"+b.host+":"+e),WebSocket.__initialize(),c.loaded=!0),d.call(f)}var f=this;if(document.body)return e();b.util.load(e)},c.check=function(){return typeof WebSocket!="undefined"&&"__initialize"in WebSocket&&!!swfobject?swfobject.getFlashPlayerVersion().major>=10:!1},c.xdomainCheck=function(){return!0},typeof window!="undefined"&&(WEB_SOCKET_DISABLE_AUTO_INITIALIZATION=!0),b.transports.push("flashsocket")}("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports);if("undefined"!=typeof window)var swfobject=function(){function A(){if(t)return;try{var a=i.getElementsByTagName("body")[0].appendChild(Q("span"));a.parentNode.removeChild(a)}catch(b){return}t=!0;var c=l.length;for(var d=0;d<c;d++)l[d]()}function B(a){t?a():l[l.length]=a}function C(b){if(typeof h.addEventListener!=a)h.addEventListener("load",b,!1);else if(typeof i.addEventListener!=a)i.addEventListener("load",b,!1);else if(typeof h.attachEvent!=a)R(h,"onload",b);else if(typeof h.onload=="function"){var c=h.onload;h.onload=function(){c(),b()}}else h.onload=b}function D(){k?E():F()}function E(){var c=i.getElementsByTagName("body")[0],d=Q(b);d.setAttribute("type",e);var f=c.appendChild(d);if(f){var g=0;(function(){if(typeof f.GetVariable!=a){var b=f.GetVariable("$version");b&&(b=b.split(" ")[1].split(","),y.pv=[parseInt(b[0],10),parseInt(b[1],10),parseInt(b[2],10)])}else if(g<10){g++,setTimeout(arguments.callee,10);return}c.removeChild(d),f=null,F()})()}else F()}function F(){var b=m.length;if(b>0)for(var c=0;c<b;c++){var d=m[c].id,e=m[c].callbackFn,f={success:!1,id:d};if(y.pv[0]>0){var g=P(d);if(g)if(S(m[c].swfVersion)&&!(y.wk&&y.wk<312))U(d,!0),e&&(f.success=!0,f.ref=G(d),e(f));else if(m[c].expressInstall&&H()){var h={};h.data=m[c].expressInstall,h.width=g.getAttribute("width")||"0",h.height=g.getAttribute("height")||"0",g.getAttribute("class")&&(h.styleclass=g.getAttribute("class")),g.getAttribute("align")&&(h.align=g.getAttribute("align"));var i={},j=g.getElementsByTagName("param"),k=j.length;for(var l=0;l<k;l++)j[l].getAttribute("name").toLowerCase()!="movie"&&(i[j[l].getAttribute("name")]=j[l].getAttribute("value"));I(h,i,d,e)}else J(g),e&&e(f)}else{U(d,!0);if(e){var n=G(d);n&&typeof n.SetVariable!=a&&(f.success=!0,f.ref=n),e(f)}}}}function G(c){var d=null,e=P(c);if(e&&e.nodeName=="OBJECT")if(typeof e.SetVariable!=a)d=e;else{var f=e.getElementsByTagName(b)[0];f&&(d=f)}return d}function H(){return!u&&S("6.0.65")&&(y.win||y.mac)&&!(y.wk&&y.wk<312)}function I(b,c,d,e){u=!0,r=e||null,s={success:!1,id:d};var g=P(d);if(g){g.nodeName=="OBJECT"?(p=K(g),q=null):(p=g,q=d),b.id=f;if(typeof b.width==a||!/%$/.test(b.width)&&parseInt(b.width,10)<310)b.width="310";if(typeof b.height==a||!/%$/.test(b.height)&&parseInt(b.height,10)<137)b.height="137";i.title=i.title.slice(0,47)+" - Flash Player Installation";var j=y.ie&&y.win?["Active"].concat("").join("X"):"PlugIn",k="MMredirectURL="+h.location.toString().replace(/&/g,"%26")+"&MMplayerType="+j+"&MMdoctitle="+i.title;typeof c.flashvars!=a?c.flashvars+="&"+k:c.flashvars=k;if(y.ie&&y.win&&g.readyState!=4){var l=Q("div");d+="SWFObjectNew",l.setAttribute("id",d),g.parentNode.insertBefore(l,g),g.style.display="none",function(){g.readyState==4?g.parentNode.removeChild(g):setTimeout(arguments.callee,10)}()}L(b,c,d)}}function J(a){if(y.ie&&y.win&&a.readyState!=4){var b=Q("div");a.parentNode.insertBefore(b,a),b.parentNode.replaceChild(K(a),b),a.style.display="none",function(){a.readyState==4?a.parentNode.removeChild(a):setTimeout(arguments.callee,10)}()}else a.parentNode.replaceChild(K(a),a)}function K(a){var c=Q("div");if(y.win&&y.ie)c.innerHTML=a.innerHTML;else{var d=a.getElementsByTagName(b)[0];if(d){var e=d.childNodes;if(e){var f=e.length;for(var g=0;g<f;g++)(e[g].nodeType!=1||e[g].nodeName!="PARAM")&&e[g].nodeType!=8&&c.appendChild(e[g].cloneNode(!0))}}}return c}function L(c,d,f){var g,h=P(f);if(y.wk&&y.wk<312)return g;if(h){typeof c.id==a&&(c.id=f);if(y.ie&&y.win){var i="";for(var j in c)c[j]!=Object.prototype[j]&&(j.toLowerCase()=="data"?d.movie=c[j]:j.toLowerCase()=="styleclass"?i+=' class="'+c[j]+'"':j.toLowerCase()!="classid"&&(i+=" "+j+'="'+c[j]+'"'));var k="";for(var l in d)d[l]!=Object.prototype[l]&&(k+='<param name="'+l+'" value="'+d[l]+'" />');h.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+i+">"+k+"</object>",n[n.length]=c.id,g=P(c.id)}else{var m=Q(b);m.setAttribute("type",e);for(var o in c)c[o]!=Object.prototype[o]&&(o.toLowerCase()=="styleclass"?m.setAttribute("class",c[o]):o.toLowerCase()!="classid"&&m.setAttribute(o,c[o]));for(var p in d)d[p]!=Object.prototype[p]&&p.toLowerCase()!="movie"&&M(m,p,d[p]);h.parentNode.replaceChild(m,h),g=m}}return g}function M(a,b,c){var d=Q("param");d.setAttribute("name",b),d.setAttribute("value",c),a.appendChild(d)}function N(a){var b=P(a);b&&b.nodeName=="OBJECT"&&(y.ie&&y.win?(b.style.display="none",function(){b.readyState==4?O(a):setTimeout(arguments.callee,10)}()):b.parentNode.removeChild(b))}function O(a){var b=P(a);if(b){for(var c in b)typeof b[c]=="function"&&(b[c]=null);b.parentNode.removeChild(b)}}function P(a){var b=null;try{b=i.getElementById(a)}catch(c){}return b}function Q(a){return i.createElement(a)}function R(a,b,c){a.attachEvent(b,c),o[o.length]=[a,b,c]}function S(a){var b=y.pv,c=a.split(".");return c[0]=parseInt(c[0],10),c[1]=parseInt(c[1],10)||0,c[2]=parseInt(c[2],10)||0,b[0]>c[0]||b[0]==c[0]&&b[1]>c[1]||b[0]==c[0]&&b[1]==c[1]&&b[2]>=c[2]?!0:!1}function T(c,d,e,f){if(y.ie&&y.mac)return;var g=i.getElementsByTagName("head")[0];if(!g)return;var h=e&&typeof e=="string"?e:"screen";f&&(v=null,w=null);if(!v||w!=h){var j=Q("style");j.setAttribute("type","text/css"),j.setAttribute("media",h),v=g.appendChild(j),y.ie&&y.win&&typeof i.styleSheets!=a&&i.styleSheets.length>0&&(v=i.styleSheets[i.styleSheets.length-1]),w=h}y.ie&&y.win?v&&typeof v.addRule==b&&v.addRule(c,d):v&&typeof i.createTextNode!=a&&v.appendChild(i.createTextNode(c+" {"+d+"}"))}function U(a,b){if(!x)return;var c=b?"visible":"hidden";t&&P(a)?P(a).style.visibility=c:T("#"+a,"visibility:"+c)}function V(b){var c=/[\\\"<>\.;]/,d=c.exec(b)!=null;return d&&typeof encodeURIComponent!=a?encodeURIComponent(b):b}var a="undefined",b="object",c="Shockwave Flash",d="ShockwaveFlash.ShockwaveFlash",e="application/x-shockwave-flash",f="SWFObjectExprInst",g="onreadystatechange",h=window,i=document,j=navigator,k=!1,l=[D],m=[],n=[],o=[],p,q,r,s,t=!1,u=!1,v,w,x=!0,y=function(){var f=typeof i.getElementById!=a&&typeof i.getElementsByTagName!=a&&typeof i.createElement!=a,g=j.userAgent.toLowerCase(),l=j.platform.toLowerCase(),m=l?/win/.test(l):/win/.test(g),n=l?/mac/.test(l):/mac/.test(g),o=/webkit/.test(g)?parseFloat(g.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):!1,p=!1,q=[0,0,0],r=null;if(typeof j.plugins!=a&&typeof j.plugins[c]==b)r=j.plugins[c].description,r&&(typeof j.mimeTypes==a||!j.mimeTypes[e]||!!j.mimeTypes[e].enabledPlugin)&&(k=!0,p=!1,r=r.replace(/^.*\s+(\S+\s+\S+$)/,"$1"),q[0]=parseInt(r.replace(/^(.*)\..*$/,"$1"),10),q[1]=parseInt(r.replace(/^.*\.(.*)\s.*$/,"$1"),10),q[2]=/[a-zA-Z]/.test(r)?parseInt(r.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0);else if(typeof h[["Active"].concat("Object").join("X")]!=a)try{var s=new(window[["Active"].concat("Object").join("X")])(d);s&&(r=s.GetVariable("$version"),r&&(p=!0,r=r.split(" ")[1].split(","),q=[parseInt(r[0],10),parseInt(r[1],10),parseInt(r[2],10)]))}catch(t){}return{w3:f,pv:q,wk:o,ie:p,win:m,mac:n}}(),z=function(){if(!y.w3)return;(typeof i.readyState!=a&&i.readyState=="complete"||typeof i.readyState==a&&(i.getElementsByTagName("body")[0]||i.body))&&A(),t||(typeof i.addEventListener!=a&&i.addEventListener("DOMContentLoaded",A,!1),y.ie&&y.win&&(i.attachEvent(g,function(){i.readyState=="complete"&&(i.detachEvent(g,arguments.callee),A())}),h==top&&function(){if(t)return;try{i.documentElement.doScroll("left")}catch(a){setTimeout(arguments.callee,0);return}A()}()),y.wk&&function(){if(t)return;if(!/loaded|complete/.test(i.readyState)){setTimeout(arguments.callee,0);return}A()}(),C(A))}(),W=function(){y.ie&&y.win&&window.attachEvent("onunload",function(){var a=o.length;for(var b=0;b<a;b++)o[b][0].detachEvent(o[b][1],o[b][2]);var c=n.length;for(var d=0;d<c;d++)N(n[d]);for(var e in y)y[e]=null;y=null;for(var f in swfobject)swfobject[f]=null;swfobject=null})}();return{registerObject:function(a,b,c,d){if(y.w3&&a&&b){var e={};e.id=a,e.swfVersion=b,e.expressInstall=c,e.callbackFn=d,m[m.length]=e,U(a,!1)}else d&&d({success:!1,id:a})},getObjectById:function(a){if(y.w3)return G(a)},embedSWF:function(c,d,e,f,g,h,i,j,k,l){var m={success:!1,id:d};y.w3&&!(y.wk&&y.wk<312)&&c&&d&&e&&f&&g?(U(d,!1),B(function(){e+="",f+="";var n={};if(k&&typeof k===b)for(var o in k)n[o]=k[o];n.data=c,n.width=e,n.height=f;var p={};if(j&&typeof j===b)for(var q in j)p[q]=j[q];if(i&&typeof i===b)for(var r in i)typeof p.flashvars!=a?p.flashvars+="&"+r+"="+i[r]:p.flashvars=r+"="+i[r];if(S(g)){var s=L(n,p,d);n.id==d&&U(d,!0),m.success=!0,m.ref=s}else{if(h&&H()){n.data=h,I(n,p,d,l);return}U(d,!0)}l&&l(m)})):l&&l(m)},switchOffAutoHideShow:function(){x=!1},ua:y,getFlashPlayerVersion:function(){return{major:y.pv[0],minor:y.pv[1],release:y.pv[2]}},hasFlashPlayerVersion:S,createSWF:function(a,b,c){return y.w3?L(a,b,c):undefined},showExpressInstall:function(a,b,c,d){y.w3&&H()&&I(a,b,c,d)},removeSWF:function(a){y.w3&&N(a)},createCSS:function(a,b,c,d){y.w3&&T(a,b,c,d)},addDomLoadEvent:B,addLoadEvent:C,getQueryParamValue:function(a){var b=i.location.search||i.location.hash;if(b){/\?/.test(b)&&(b=b.split("?")[1]);if(a==null)return V(b);var c=b.split("&");for(var d=0;d<c.length;d++)if(c[d].substring(0,c[d].indexOf("="))==a)return V(c[d].substring(c[d].indexOf("=")+1))}return""},expressInstallCallback:function(){if(u){var a=P(f);a&&p&&(a.parentNode.replaceChild(p,a),q&&(U(q,!0),y.ie&&y.win&&(p.style.display="block")),r&&r(s)),u=!1}}}}();(function(){if("undefined"==typeof window||window.WebSocket)return;var a=window.console;if(!a||!a.log||!a.error)a={log:function(){},error:function(){}};if(!swfobject.hasFlashPlayerVersion("10.0.0")){a.error("Flash Player >= 10.0.0 is required.");return}location.protocol=="file:"&&a.error("WARNING: web-socket-js doesn't work in file:///... URL unless you set Flash Security Settings properly. Open the page via Web server i.e. http://..."),WebSocket=function(a,b,c,d,e){var f=this;f.__id=WebSocket.__nextId++,WebSocket.__instances[f.__id]=f,f.readyState=WebSocket.CONNECTING,f.bufferedAmount=0,f.__events={},b?typeof b=="string"&&(b=[b]):b=[],setTimeout(function(){WebSocket.__addTask(function(){WebSocket.__flash.create(f.__id,a,b,c||null,d||0,e||null)})},0)},WebSocket.prototype.send=function(a){if(this.readyState==WebSocket.CONNECTING)throw"INVALID_STATE_ERR: Web Socket connection has not been established";var b=WebSocket.__flash.send(this.__id,encodeURIComponent(a));return b<0?!0:(this.bufferedAmount+=b,!1)},WebSocket.prototype.close=function(){if(this.readyState==WebSocket.CLOSED||this.readyState==WebSocket.CLOSING)return;this.readyState=WebSocket.CLOSING,WebSocket.__flash.close(this.__id)},WebSocket.prototype.addEventListener=function(a,b,c){a in this.__events||(this.__events[a]=[]),this.__events[a].push(b)},WebSocket.prototype.removeEventListener=function(a,b,c){if(!(a in this.__events))return;var d=this.__events[a];for(var e=d.length-1;e>=0;--e)if(d[e]===b){d.splice(e,1);break}},WebSocket.prototype.dispatchEvent=function(a){var b=this.__events[a.type]||[];for(var c=0;c<b.length;++c)b[c](a);var d=this["on"+a.type];d&&d(a)},WebSocket.prototype.__handleEvent=function(a){"readyState"in a&&(this.readyState=a.readyState),"protocol"in a&&(this.protocol=a.protocol);var b;if(a.type=="open"||a.type=="error")b=this.__createSimpleEvent(a.type);else if(a.type=="close")b=this.__createSimpleEvent("close");else{if(a.type!="message")throw"unknown event type: "+a.type;var c=decodeURIComponent(a.message);b=this.__createMessageEvent("message",c)}this.dispatchEvent(b)},WebSocket.prototype.__createSimpleEvent=function(a){if(document.createEvent&&window.Event){var b=document.createEvent("Event");return b.initEvent(a,!1,!1),b}return{type:a,bubbles:!1,cancelable:!1}},WebSocket.prototype.__createMessageEvent=function(a,b){if(document.createEvent&&window.MessageEvent&&!window.opera){var c=document.createEvent("MessageEvent");return c.initMessageEvent("message",!1,!1,b,null,null,window,null),c}return{type:a,data:b,bubbles:!1,cancelable:!1}},WebSocket.CONNECTING=0,WebSocket.OPEN=1,WebSocket.CLOSING=2,WebSocket.CLOSED=3,WebSocket.__flash=null,WebSocket.__instances={},WebSocket.__tasks=[],WebSocket.__nextId=0,WebSocket.loadFlashPolicyFile=function(a){WebSocket.__addTask(function(){WebSocket.__flash.loadManualPolicyFile(a)})},WebSocket.__initialize=function(){if(WebSocket.__flash)return;WebSocket.__swfLocation&&(window.WEB_SOCKET_SWF_LOCATION=WebSocket.__swfLocation);if(!window.WEB_SOCKET_SWF_LOCATION){a.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");return}var b=document.createElement("div");b.id="webSocketContainer",b.style.position="absolute",WebSocket.__isFlashLite()?(b.style.left="0px",b.style.top="0px"):(b.style.left="-100px",b.style.top="-100px");var c=document.createElement("div");c.id="webSocketFlash",b.appendChild(c),document.body.appendChild(b),swfobject.embedSWF(WEB_SOCKET_SWF_LOCATION,"webSocketFlash","1","1","10.0.0",null,null,{hasPriority:!0,swliveconnect:!0,allowScriptAccess:"always"},null,function(b){b.success||a.error("[WebSocket] swfobject.embedSWF failed")})},WebSocket.__onFlashInitialized=function(){setTimeout(function(){WebSocket.__flash=document.getElementById("webSocketFlash"),WebSocket.__flash.setCallerUrl(location.href),WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);for(var a=0;a<WebSocket.__tasks.length;++a)WebSocket.__tasks[a]();WebSocket.__tasks=[]},0)},WebSocket.__onFlashEvent=function(){return setTimeout(function(){try{var b=WebSocket.__flash.receiveEvents();for(var c=0;c<b.length;++c)WebSocket.__instances[b[c].webSocketId].__handleEvent(b[c])}catch(d){a.error(d)}},0),!0},WebSocket.__log=function(b){a.log(decodeURIComponent(b))},WebSocket.__error=function(b){a.error(decodeURIComponent(b))},WebSocket.__addTask=function(a){WebSocket.__flash?a():WebSocket.__tasks.push(a)},WebSocket.__isFlashLite=function(){if(!window.navigator||!window.navigator.mimeTypes)return!1;var a=window.navigator.mimeTypes["application/x-shockwave-flash"];return!a||!a.enabledPlugin||!a.enabledPlugin.filename?!1:a.enabledPlugin.filename.match(/flashlite/i)?!0:!1},window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION||(window.addEventListener?window.addEventListener("load",function(){WebSocket.__initialize()},!1):window.attachEvent("onload",function(){WebSocket.__initialize()}))})(),function(a,b,c){function d(a){if(!a)return;b.Transport.apply(this,arguments),this.sendBuffer=[]}function e(){}a.XHR=d,b.util.inherit(d,b.Transport),d.prototype.open=function(){return this.socket.setBuffer(!1),this.onOpen(),this.get(),this.setCloseTimeout(),this},d.prototype.payload=function(a){var c=[];for(var d=0,e=a.length;d<e;d++)c.push(b.parser.encodePacket(a[d]));this.send(b.parser.encodePayload(c))},d.prototype.send=function(a){return this.post(a),this},d.prototype.post=function(a){function d(){this.readyState==4&&(this.onreadystatechange=e,b.posting=!1,this.status==200?b.socket.setBuffer(!1):b.onClose())}function f(){this.onload=e,b.socket.setBuffer(!1)}var b=this;this.socket.setBuffer(!0),this.sendXHR=this.request("POST"),c.XDomainRequest&&this.sendXHR instanceof XDomainRequest?this.sendXHR.onload=this.sendXHR.onerror=f:this.sendXHR.onreadystatechange=d,this.sendXHR.send(a)},d.prototype.close=function(){return this.onClose(),this},d.prototype.request=function(a){var c=b.util.request(this.socket.isXDomain()),d=b.util.query(this.socket.options.query,"t="+ +(new Date));c.open(a||"GET",this.prepareUrl()+d,!0);if(a=="POST")try{c.setRequestHeader?c.setRequestHeader("Content-type","text/plain;charset=UTF-8"):c.contentType="text/plain"}catch(e){}return c},d.prototype.scheme=function(){return this.socket.options.secure?"https":"http"},d.check=function(a,d){try{var e=b.util.request(d),f=c.XDomainRequest&&e instanceof XDomainRequest,g=a&&a.options&&a.options.secure?"https:":"http:",h=c.location&&g!=c.location.protocol;if(e&&(!f||!h))return!0}catch(i){}return!1},d.xdomainCheck=function(a){return d.check(a,!0)}}("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports,this),function(a,b){function c(a){b.Transport.XHR.apply(this,arguments)}a.htmlfile=c,b.util.inherit(c,b.Transport.XHR),c.prototype.name="htmlfile",c.prototype.get=function(){this.doc=new(window[["Active"].concat("Object").join("X")])("htmlfile"),this.doc.open(),this.doc.write("<html></html>"),this.doc.close(),this.doc.parentWindow.s=this;var a=this.doc.createElement("div");a.className="socketio",this.doc.body.appendChild(a),this.iframe=this.doc.createElement("iframe"),a.appendChild(this.iframe);var c=this,d=b.util.query(this.socket.options.query,"t="+ +(new Date));this.iframe.src=this.prepareUrl()+d,b.util.on(window,"unload",function(){c.destroy()})},c.prototype._=function(a,b){a=a.replace(/\\\//g,"/"),this.onData(a);try{var c=b.getElementsByTagName("script")[0];c.parentNode.removeChild(c)}catch(d){}},c.prototype.destroy=function(){if(this.iframe){try{this.iframe.src="about:blank"}catch(a){}this.doc=null,this.iframe.parentNode.removeChild(this.iframe),this.iframe=null,CollectGarbage()}},c.prototype.close=function(){return this.destroy(),b.Transport.XHR.prototype.close.call(this)},c.check=function(a){if(typeof window!="undefined"&&["Active"].concat("Object").join("X")in window)try{var c=new(window[["Active"].concat("Object").join("X")])("htmlfile");return c&&b.Transport.XHR.check(a)}catch(d){}return!1},c.xdomainCheck=function(){return!1},b.transports.push("htmlfile")}("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports),function(a,b,c){function d(){b.Transport.XHR.apply(this,arguments)}function e(){}a["xhr-polling"]=d,b.util.inherit(d,b.Transport.XHR),b.util.merge(d,b.Transport.XHR),d.prototype.name="xhr-polling",d.prototype.heartbeats=function(){return!1},d.prototype.open=function(){var a=this;return b.Transport.XHR.prototype.open.call(a),!1},d.prototype.get=function(){function b(){this.readyState==4&&(this.onreadystatechange=e,this.status==200?(a.onData(this.responseText),a.get()):a.onClose())}function d(){this.onload=e,this.onerror=e,a.retryCounter=1,a.onData(this.responseText),a.get()}function f(){a.retryCounter++,!a.retryCounter||a.retryCounter>3?a.onClose():a.get()}if(!this.isOpen)return;var a=this;this.xhr=this.request(),c.XDomainRequest&&this.xhr instanceof XDomainRequest?(this.xhr.onload=d,this.xhr.onerror=f):this.xhr.onreadystatechange=b,this.xhr.send(null)},d.prototype.onClose=function(){b.Transport.XHR.prototype.onClose.call(this);if(this.xhr){this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=e;try{this.xhr.abort()}catch(a){}this.xhr=null}},d.prototype.ready=function(a,c){var d=this;b.util.defer(function(){c.call(d)})},b.transports.push("xhr-polling")}("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports,this),function(a,b,c){function e(a){b.Transport["xhr-polling"].apply(this,arguments),this.index=b.j.length;var c=this;b.j.push(function(a){c._(a)})}var d=c.document&&"MozAppearance"in c.document.documentElement.style;a["jsonp-polling"]=e,b.util.inherit(e,b.Transport["xhr-polling"]),e.prototype.name="jsonp-polling",e.prototype.post=function(a){function i(){j(),c.socket.setBuffer(!1)}function j(){c.iframe&&c.form.removeChild(c.iframe);try{h=document.createElement('<iframe name="'+c.iframeId+'">')}catch(a){h=document.createElement("iframe"),h.name=c.iframeId}h.id=c.iframeId,c.form.appendChild(h),c.iframe=h}var c=this,d=b.util.query(this.socket.options.query,"t="+ +(new Date)+"&i="+this.index);if(!this.form){var e=document.createElement("form"),f=document.createElement("textarea"),g=this.iframeId="socketio_iframe_"+this.index,h;e.className="socketio",e.style.position="absolute",e.style.top="0px",e.style.left="0px",e.style.display="none",e.target=g,e.method="POST",e.setAttribute("accept-charset","utf-8"),f.name="d",e.appendChild(f),document.body.appendChild(e),this.form=e,this.area=f}this.form.action=this.prepareUrl()+d,j(),this.area.value=b.JSON.stringify(a);try{this.form.submit()}catch(k){}this.iframe.attachEvent?h.onreadystatechange=function(){c.iframe.readyState=="complete"&&i()}:this.iframe.onload=i,this.socket.setBuffer(!0)},e.prototype.get=function(){var a=this,c=document.createElement("script"),e=b.util.query(this.socket.options.query,"t="+ +(new Date)+"&i="+this.index);this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),c.async=!0,c.src=this.prepareUrl()+e,c.onerror=function(){a.onClose()};var f=document.getElementsByTagName("script")[0];f.parentNode.insertBefore(c,f),this.script=c,d&&setTimeout(function(){var a=document.createElement("iframe");document.body.appendChild(a),document.body.removeChild(a)},100)},e.prototype._=function(a){return this.onData(a),this.isOpen&&this.get(),this},e.prototype.ready=function(a,c){var e=this;if(!d)return c.call(this);b.util.load(function(){c.call(e)})},e.check=function(){return"document"in c},e.xdomainCheck=function(){return!0},b.transports.push("jsonp-polling")}("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports,this),typeof define=="function"&&define.amd&&define([],function(){return io})})();
/**
* sails.io.js
* ------------------------------------------------------------------------
* JavaScript Client (SDK) for communicating with Sails.
*
* Note that this script is completely optional, but it is handy if you're
* using WebSockets from the browser to talk to your Sails server.
*
* For tips and documentation, visit:
* http://sailsjs.org/#!documentation/reference/BrowserSDK/BrowserSDK.html
* ------------------------------------------------------------------------
*
* This file allows you to send and receive socket.io messages to & from Sails
* by simulating a REST client interface on top of socket.io. It models its API
* after the $.ajax pattern from jQuery you might already be familiar with.
*
* So if you're switching from using AJAX to sockets, instead of:
* `$.post( url, [data], [cb] )`
*
* You would use:
* `socket.post( url, [data], [cb] )`
*/
(function() {
// Save the URL that this script was fetched from for use below.
// (skip this if this SDK is being used outside of the DOM, i.e. in a Node process)
var urlThisScriptWasFetchedFrom = (function() {
if (
typeof window !== 'object' ||
typeof window.document !== 'object' ||
typeof window.document.getElementsByTagName !== 'function'
) {
return '';
}
// Return the URL of the last script loaded (i.e. this one)
// (this must run before nextTick; see http://stackoverflow.com/a/2976714/486547)
var allScriptsCurrentlyInDOM = window.document.getElementsByTagName('script');
var thisScript = allScriptsCurrentlyInDOM[allScriptsCurrentlyInDOM.length - 1];
return thisScript.src;
})();
// Constants
var CONNECTION_METADATA_PARAMS = {
version: '__sails_io_sdk_version',
platform: '__sails_io_sdk_platform',
language: '__sails_io_sdk_language'
};
// Current version of this SDK (sailsDK?!?!) and other metadata
// that will be sent along w/ the initial connection request.
var SDK_INFO = {
version: '0.10.0', // TODO: pull this automatically from package.json during build.
platform: typeof module === 'undefined' ? 'browser' : 'node',
language: 'javascript'
};
SDK_INFO.versionString =
CONNECTION_METADATA_PARAMS.version + '=' + SDK_INFO.version + '&' +
CONNECTION_METADATA_PARAMS.platform + '=' + SDK_INFO.platform + '&' +
CONNECTION_METADATA_PARAMS.language + '=' + SDK_INFO.language;
// In case you're wrapping the socket.io client to prevent pollution of the
// global namespace, you can pass in your own `io` to replace the global one.
// But we still grab access to the global one if it's available here:
var _io = (typeof io !== 'undefined') ? io : null;
/**
* Augment the `io` object passed in with methods for talking and listening
* to one or more Sails backend(s). Automatically connects a socket and
* exposes it on `io.socket`. If a socket tries to make requests before it
* is connected, the sails.io.js client will queue it up.
*
* @param {SocketIO} io
*/
function SailsIOClient(io) {
// Prefer the passed-in `io` instance, but also use the global one if we've got it.
io = io || _io;
// If the socket.io client is not available, none of this will work.
if (!io) throw new Error('`sails.io.js` requires a socket.io client, but `io` was not passed in.');
//////////////////////////////////////////////////////////////
///// ///////////////////////////
///// PRIVATE METHODS/CONSTRUCTORS ///////////////////////////
///// ///////////////////////////
//////////////////////////////////////////////////////////////
/**
* TmpSocket
*
* A mock Socket used for binding events before the real thing
* has been instantiated (since we need to use io.connect() to
* instantiate the real thing, which would kick off the connection
* process w/ the server, and we don't necessarily have the valid
* configuration to know WHICH SERVER to talk to yet.)
*
* @api private
* @constructor
*/
function TmpSocket() {
var boundEvents = {};
this.on = function (evName, fn) {
if (!boundEvents[evName]) boundEvents[evName] = [fn];
else boundEvents[evName].push(fn);
return this;
};
this.become = function(actualSocket) {
// Pass events and a reference to the request queue
// off to the actualSocket for consumption
for (var evName in boundEvents) {
for (var i in boundEvents[evName]) {
actualSocket.on(evName, boundEvents[evName][i]);
}
}
actualSocket.requestQueue = this.requestQueue;
// Bind a one-time function to run the request queue
// when the actualSocket connects.
if (!_isConnected(actualSocket)) {
var alreadyRanRequestQueue = false;
actualSocket.on('connect', function onActualSocketConnect() {
if (alreadyRanRequestQueue) return;
runRequestQueue(actualSocket);
alreadyRanRequestQueue = true;
});
}
// Or run it immediately if actualSocket is already connected
else {
runRequestQueue(actualSocket);
}
return actualSocket;
};
// Uses `this` instead of `TmpSocket.prototype` purely
// for convenience, since it makes more sense to attach
// our extra methods to the `Socket` prototype down below.
// This could be optimized by moving those Socket method defs
// to the top of this SDK file instead of the bottom. Will
// gladly do it if it is an issue for anyone.
this.get = Socket.prototype.get;
this.post = Socket.prototype.post;
this.put = Socket.prototype.put;
this['delete'] = Socket.prototype['delete'];
this.request = Socket.prototype.request;
this._request = Socket.prototype._request;
}
/**
* A little logger for this library to use internally.
* Basically just a wrapper around `console.log` with
* support for feature-detection.
*
* @api private
* @factory
*/
function LoggerFactory(options) {
options = options || {
prefix: true
};
// If `console.log` is not accessible, `log` is a noop.
if (
typeof console !== 'object' ||
typeof console.log !== 'function' ||
typeof console.log.bind !== 'function'
) {
return function noop() {};
}
return function log() {
var args = Array.prototype.slice.call(arguments);
// All logs are disabled when `io.sails.environment = 'production'`.
if (io.sails.environment === 'production') return;
// Add prefix to log messages (unless disabled)
var PREFIX = '';
if (options.prefix) {
args.unshift(PREFIX);
}
// Call wrapped logger
console.log
.bind(console)
.apply(this, args);
};
}
// Create a private logger instance
var consolog = LoggerFactory();
consolog.noPrefix = LoggerFactory({
prefix: false
});
/**
* _isConnected
*
* @api private
* @param {Socket} socket
* @return {Boolean} whether the socket is connected and able to
* communicate w/ the server.
*/
function _isConnected(socket) {
return socket.socket && socket.socket.connected;
}
/**
* What is the `requestQueue`?
*
* The request queue is used to simplify app-level connection logic--
* i.e. so you don't have to wait for the socket to be connected
* to start trying to synchronize data.
*
* @api private
* @param {Socket} socket
*/
function runRequestQueue (socket) {
var queue = socket.requestQueue;
if (!queue) return;
for (var i in queue) {
// Double-check that `queue[i]` will not
// inadvertently discover extra properties attached to the Object
// and/or Array prototype by other libraries/frameworks/tools.
// (e.g. Ember does this. See https://github.com/balderdashy/sails.io.js/pull/5)
var isSafeToDereference = ({}).hasOwnProperty.call(queue, i);
if (isSafeToDereference) {
// Emit the request.
_emitFrom(socket, queue[i]);
}
}
}
/**
* Send an AJAX request.
*
* @param {Object} opts [optional]
* @param {Function} cb
* @return {XMLHttpRequest}
*/
function ajax(opts, cb) {
opts = opts || {};
var xmlhttp;
if (typeof window === 'undefined') {
// TODO: refactor node usage to live in here
return cb();
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
cb(xmlhttp.responseText);
}
};
xmlhttp.open(opts.method, opts.url, true);
xmlhttp.send();
return xmlhttp;
}
/**
* The JWR (JSON WebSocket Response) received from a Sails server.
*
* @api private
* @param {Object} responseCtx
* => :body
* => :statusCode
* => :headers
* @constructor
*/
function JWR(responseCtx) {
this.body = responseCtx.body || {};
this.headers = responseCtx.headers || {};
this.statusCode = responseCtx.statusCode || 200;
}
JWR.prototype.toString = function() {
return '[ResponseFromSails]' + ' -- ' +
'Status: ' + this.statusCode + ' -- ' +
'Headers: ' + this.headers + ' -- ' +
'Body: ' + this.body;
};
JWR.prototype.toPOJO = function() {
return {
body: this.body,
headers: this.headers,
statusCode: this.statusCode
};
};
JWR.prototype.pipe = function() {
// TODO: look at substack's stuff
return new Error('Not implemented yet.');
};
/**
* @api private
* @param {Socket} socket [description]
* @param {Object} requestCtx [description]
*/
function _emitFrom(socket, requestCtx) {
// Since callback is embedded in requestCtx,
// retrieve it and delete the key before continuing.
var cb = requestCtx.cb;
delete requestCtx.cb;
// Name of socket request listener on the server
// ( === the request method, e.g. 'get', 'post', 'put', etc. )
var sailsEndpoint = requestCtx.method;
socket.emit(sailsEndpoint, requestCtx, function serverResponded(responseCtx) {
// Adds backwards-compatibility for 0.9.x projects
// If `responseCtx.body` does not exist, the entire
// `responseCtx` object must actually be the `body`.
var body;
if (!responseCtx.body) {
body = responseCtx;
} else {
body = responseCtx.body;
}
// Send back (emulatedHTTPBody, jsonWebSocketResponse)
if (cb) {
cb(body, new JWR(responseCtx));
}
});
}
//////////////////////////////////////////////////////////////
///// </PRIVATE METHODS/CONSTRUCTORS> ////////////////////////
//////////////////////////////////////////////////////////////
// We'll be adding methods to `io.SocketNamespace.prototype`, the prototype for the
// Socket instance returned when the browser connects with `io.connect()`
var Socket = io.SocketNamespace;
/**
* Simulate a GET request to sails
* e.g.
* `socket.get('/user/3', Stats.populate)`
*
* @api public
* @param {String} url :: destination URL
* @param {Object} params :: parameters to send with the request [optional]
* @param {Function} cb :: callback function to call when finished [optional]
*/
Socket.prototype.get = function(url, data, cb) {
// `data` is optional
if (typeof data === 'function') {
cb = data;
data = {};
}
return this._request({
method: 'get',
data: data,
url: url
}, cb);
};
/**
* Simulate a POST request to sails
* e.g.
* `socket.post('/event', newMeeting, $spinner.hide)`
*
* @api public
* @param {String} url :: destination URL
* @param {Object} params :: parameters to send with the request [optional]
* @param {Function} cb :: callback function to call when finished [optional]
*/
Socket.prototype.post = function(url, data, cb) {
// `data` is optional
if (typeof data === 'function') {
cb = data;
data = {};
}
return this._request({
method: 'post',
data: data,
url: url
}, cb);
};
/**
* Simulate a PUT request to sails
* e.g.
* `socket.post('/event/3', changedFields, $spinner.hide)`
*
* @api public
* @param {String} url :: destination URL
* @param {Object} params :: parameters to send with the request [optional]
* @param {Function} cb :: callback function to call when finished [optional]
*/
Socket.prototype.put = function(url, data, cb) {
// `data` is optional
if (typeof data === 'function') {
cb = data;
data = {};
}
return this._request({
method: 'put',
data: data,
url: url
}, cb);
};
/**
* Simulate a DELETE request to sails
* e.g.
* `socket.delete('/event', $spinner.hide)`
*
* @api public
* @param {String} url :: destination URL
* @param {Object} params :: parameters to send with the request [optional]
* @param {Function} cb :: callback function to call when finished [optional]
*/
Socket.prototype['delete'] = function(url, data, cb) {
// `data` is optional
if (typeof data === 'function') {
cb = data;
data = {};
}
return this._request({
method: 'delete',
data: data,
url: url
}, cb);
};
/**
* Simulate an HTTP request to sails
* e.g.
* `socket.request('/user', newUser, $spinner.hide, 'post')`
*
* @api public
* @param {String} url :: destination URL
* @param {Object} params :: parameters to send with the request [optional]
* @param {Function} cb :: callback function to call when finished [optional]
* @param {String} method :: HTTP request method [optional]
*/
Socket.prototype.request = function(url, data, cb, method) {
// `cb` is optional
if (typeof cb === 'string') {
method = cb;
cb = null;
}
// `data` is optional
if (typeof data === 'function') {
cb = data;
data = {};
}
return this._request({
method: method || 'get',
data: data,
url: url
}, cb);
};
/**
* Socket.prototype._request
*
* Simulate HTTP over Socket.io.
*
* @api private
* @param {[type]} options [description]
* @param {Function} cb [description]
*/
Socket.prototype._request = function(options, cb) {
// Sanitize options (also data & headers)
var usage = 'Usage:\n socket.' +
(options.method || 'request') +
'( destinationURL, [dataToSend], [fnToCallWhenComplete] )';
options = options || {};
options.data = options.data || {};
options.headers = options.headers || {};
// Remove trailing slashes and spaces to make packets smaller.
options.url = options.url.replace(/^(.+)\/*\s*$/, '$1');
if (typeof options.url !== 'string') {
throw new Error('Invalid or missing URL!\n' + usage);
}
// Build a simulated request object.
var request = {
method: options.method,
data: options.data,
url: options.url,
headers: options.headers,
cb: cb
};
// If this socket is not connected yet, queue up this request
// instead of sending it.
// (so it can be replayed when the socket comes online.)
if (!_isConnected(this)) {
// If no queue array exists for this socket yet, create it.
this.requestQueue = this.requestQueue || [];
this.requestQueue.push(request);
return;
}
// Otherwise, our socket is ok!
// Send the request.
_emitFrom(this, request);
};
// Set a `sails` object that may be used for configuration before the
// first socket connects (i.e. to prevent auto-connect)
io.sails = {
// Whether to automatically connect a socket and save it as `io.socket`.
autoConnect: true,
// Whether to use JSONP to get a cookie for cross-origin requests
useCORSRouteToGetCookie: true,
prodUrl: "fapp.yamanickill.com:8080",
fallbackUrl: "fapp.yamanickill.com:80",
localUrl: "127.0.0.1:1337",
// The environment we're running in.
// (logs are not displayed when this is set to 'production')
//
// Defaults to development unless this script was fetched from a URL
// that ends in `*.min.js` or '#production' (may also be manually overridden.)
//
environment: urlThisScriptWasFetchedFrom.match(/(\#production|\.min\.js)/) ? 'production' : 'development'
};
/**
* Override `io.connect` to coerce it into using the io.sails
* connection URL config, as well as sending identifying information
* (most importantly, the current version of this SDK)
*
* @param {String} url [optional]
* @param {Object} opts [optional]
* @return {Socket}
*/
io.sails._origConnectFn = io.connect;
io.connect = function(url, opts) {
opts = opts || {};
// If explicit connection url is specified, use it
url = url || (window.location.hostname === 'localhost' ? io.sails.url : (io.sails.useFallback ? io.sails.fallbackUrl : io.sails.prodUrl)) || undefined;
// Ensure URL has no trailing slash
url = url ? url.replace(/(\/)$/, '') : undefined;
// Mix the current SDK version into the query string in
// the connection request to the server:
if (typeof opts.query !== 'string') opts.query = SDK_INFO.versionString;
else opts.query += '&' + SDK_INFO.versionString;
return io.sails._origConnectFn(url, opts);
};
// io.socket
//
// The eager instance of Socket which will automatically try to connect
// using the host that this js file was served from.
//
// This can be disabled or configured by setting `io.socket.options` within the
// first cycle of the event loop.
//
// In the mean time, this eager socket will be defined as a TmpSocket
// so that events bound by the user before the first cycle of the event
// loop (using `.on()`) can be rebound on the true socket.
io.socket = new TmpSocket();
setTimeout(function() {
// If autoConnect is disabled, delete the TmpSocket and bail out.
if (!io.sails.autoConnect) {
delete io.socket;
return io;
}
// If this is an attempt at a cross-origin or cross-port
// socket connection, send an AJAX request first to ensure
// that a valid cookie is available. This can be disabled
// by setting `io.sails.useCORSRouteToGetCookie` to false.
var isXOrigin = io.sails.url && true; //url.match();
// TODO: check whether the URL is cross-domain
// var port = global.location.port || ('https:' == global.location.protocol ? 443 : 80);
// this.options.host !== global.location.hostname || this.options.port != port;
if (io.sails.useCORSRouteToGetCookie && isXOrigin) {
// Figure out the x-origin CORS route
// (Sails provides a default)
var xOriginCookieRoute = '/__getcookie';
if (typeof io.sails.useCORSRouteToGetCookie === 'string') {
xOriginCookieRoute = io.sails.useCORSRouteToGetCookie;
}
var xOriginCookieURL = io.sails.url + xOriginCookieRoute;
// Make the AJAX request (CORS)
if (typeof window !== 'undefined') {
ajax({
url: xOriginCookieURL,
method: 'GET'
}, goAheadAndActuallyConnect);
}
// If there's no `window` object, we must be running in Node.js
// so just require the request module and send the HTTP request that
// way.
else {
var mikealsReq = require('request');
mikealsReq.get(io.sails.url + xOriginCookieRoute, function(err, httpResponse, body) {
if (err) {
consolog(
'Failed to connect socket (failed to get cookie)',
'Error:', err
);
return;
}
goAheadAndActuallyConnect();
});
}
} else goAheadAndActuallyConnect();
// Start connecting after the current cycle of the event loop
// has completed.
// consolog('Auto-connecting `io.socket` to Sails... (requests will be queued in the mean-time)');
function goAheadAndActuallyConnect() {
// Initiate connection
var actualSocket = io.connect(io.sails.url);
// Replay event bindings from the existing TmpSocket
io.socket = io.socket.become(actualSocket);
/**
* 'connect' event is triggered when the socket establishes a connection
* successfully.
*/
io.socket.on('connect', function socketConnected() {
consolog.noPrefix(
'\n' +
' |> ' + '\n' +
' \\___/ '
);
consolog(
'`io.socket` connected successfully.' + '\n' +
// 'e.g. to send a GET request to Sails via WebSockets, run:'+ '\n' +
// '`io.socket.get("/foo", function serverRespondedWith (body, jwr) { console.log(body); })`'+ '\n' +
' (for help, see: http://sailsjs.org/#!documentation/reference/BrowserSDK/BrowserSDK.html)'
);
// consolog('(this app is running in development mode - log messages will be displayed)');
if (!io.socket.$events.disconnect) {
io.socket.on('disconnect', function() {
consolog('====================================');
consolog('io.socket was disconnected from Sails.');
consolog('Usually, this is due to one of the following reasons:' + '\n' +
' -> the server ' + (io.sails.url ? io.sails.url + ' ' : '') + 'was taken down' + '\n' +
' -> your browser lost internet connectivity');
consolog('====================================');
});
}
if (!io.socket.$events.reconnect) {
io.socket.on('reconnect', function(transport, numAttempts) {
var numSecsOffline = io.socket.msSinceConnectionLost / 1000;
consolog(
'io.socket reconnected successfully after being offline ' +
'for ' + numSecsOffline + ' seconds.');
});
}
if (!io.socket.$events.reconnecting) {
io.socket.on('reconnecting', function(msSinceConnectionLost, numAttempts) {
io.socket.msSinceConnectionLost = msSinceConnectionLost;
consolog(
'io.socket is trying to reconnect to Sails...' +
'(attempt #' + numAttempts + ')');
});
}
// 'error' event is triggered if connection can not be established.
// (usually because of a failed authorization, which is in turn
// usually due to a missing or invalid cookie)
if (!io.socket.$events.error) {
io.socket.on('error', function failedToConnect(err) {
// TODO:
// handle failed connections due to failed authorization
// in a smarter way (probably can listen for a different event)
// A bug in Socket.io 0.9.x causes `connect_failed`
// and `reconnect_failed` not to fire.
// Check out the discussion in github issues for details:
// https://github.com/LearnBoost/socket.io/issues/652
// io.socket.on('connect_failed', function () {
// consolog('io.socket emitted `connect_failed`');
// });
// io.socket.on('reconnect_failed', function () {
// consolog('io.socket emitted `reconnect_failed`');
// });
consolog(
'Failed to connect socket (probably due to failed authorization on server)',
'Error:', err
);
});
}
});
io.socket.on('connect_failed', function() {
io.transports = ['xhr-polling'];
io.sails.useFallback = true;
goAheadAndActuallyConnect();
});
}
// TODO:
// Listen for a special private message on any connected that allows the server
// to set the environment (giving us 100% certainty that we guessed right)
// However, note that the `console.log`s called before and after connection
// are still forced to rely on our existing heuristics (to disable, tack #production
// onto the URL used to fetch this file.)
}, 0); // </setTimeout>
// Return the `io` object.
return io;
}
// Add CommonJS support to allow this client SDK to be used from Node.js.
if (typeof module === 'object' && typeof module.exports !== 'undefined') {
module.exports = SailsIOClient;
return SailsIOClient;
}
// Otherwise, try to instantiate the client:
// In case you're wrapping the socket.io client to prevent pollution of the
// global namespace, you can replace the global `io` with your own `io` here:
return SailsIOClient();
})();
| assets/js/dependencies/sails.io.js | /*! Socket.IO.min.js build:0.9.16, production. Copyright(c) 2011 LearnBoost <[email protected]> MIT Licensed */
var io="undefined"==typeof module?{}:module.exports;(function(){(function(a,b){var c=a;c.version="0.9.16",c.protocol=1,c.transports=[],c.j=[],c.sockets={},c.connect=function(a,d){var e=c.util.parseUri(a),f,g;b&&b.location&&(e.protocol=e.protocol||b.location.protocol.slice(0,-1),e.host=e.host||(b.document?b.document.domain:b.location.hostname),e.port=e.port||b.location.port),f=c.util.uniqueUri(e);var h={host:e.host,secure:"https"==e.protocol,port:e.port||("https"==e.protocol?443:80),query:e.query||""};c.util.merge(h,d);if(h["force new connection"]||!c.sockets[f])g=new c.Socket(h);return!h["force new connection"]&&g&&(c.sockets[f]=g),g=g||c.sockets[f],g.of(e.path.length>1?e.path:"")}})("object"==typeof module?module.exports:this.io={},this),function(a,b){var c=a.util={},d=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,e=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];c.parseUri=function(a){var b=d.exec(a||""),c={},f=14;while(f--)c[e[f]]=b[f]||"";return c},c.uniqueUri=function(a){var c=a.protocol,d=a.host,e=a.port;return"document"in b?(d=d||document.domain,e=e||(c=="https"&&document.location.protocol!=="https:"?443:document.location.port)):(d=d||"localhost",!e&&c=="https"&&(e=443)),(c||"http")+"://"+d+":"+(e||80)},c.query=function(a,b){var d=c.chunkQuery(a||""),e=[];c.merge(d,c.chunkQuery(b||""));for(var f in d)d.hasOwnProperty(f)&&e.push(f+"="+d[f]);return e.length?"?"+e.join("&"):""},c.chunkQuery=function(a){var b={},c=a.split("&"),d=0,e=c.length,f;for(;d<e;++d)f=c[d].split("="),f[0]&&(b[f[0]]=f[1]);return b};var f=!1;c.load=function(a){if("document"in b&&document.readyState==="complete"||f)return a();c.on(b,"load",a,!1)},c.on=function(a,b,c,d){a.attachEvent?a.attachEvent("on"+b,c):a.addEventListener&&a.addEventListener(b,c,d)},c.request=function(a){if(a&&"undefined"!=typeof XDomainRequest&&!c.ua.hasCORS)return new XDomainRequest;if("undefined"!=typeof XMLHttpRequest&&(!a||c.ua.hasCORS))return new XMLHttpRequest;if(!a)try{return new(window[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(b){}return null},"undefined"!=typeof window&&c.load(function(){f=!0}),c.defer=function(a){if(!c.ua.webkit||"undefined"!=typeof importScripts)return a();c.load(function(){setTimeout(a,100)})},c.merge=function(b,d,e,f){var g=f||[],h=typeof e=="undefined"?2:e,i;for(i in d)d.hasOwnProperty(i)&&c.indexOf(g,i)<0&&(typeof b[i]!="object"||!h?(b[i]=d[i],g.push(d[i])):c.merge(b[i],d[i],h-1,g));return b},c.mixin=function(a,b){c.merge(a.prototype,b.prototype)},c.inherit=function(a,b){function c(){}c.prototype=b.prototype,a.prototype=new c},c.isArray=Array.isArray||function(a){return Object.prototype.toString.call(a)==="[object Array]"},c.intersect=function(a,b){var d=[],e=a.length>b.length?a:b,f=a.length>b.length?b:a;for(var g=0,h=f.length;g<h;g++)~c.indexOf(e,f[g])&&d.push(f[g]);return d},c.indexOf=function(a,b,c){for(var d=a.length,c=c<0?c+d<0?0:c+d:c||0;c<d&&a[c]!==b;c++);return d<=c?-1:c},c.toArray=function(a){var b=[];for(var c=0,d=a.length;c<d;c++)b.push(a[c]);return b},c.ua={},c.ua.hasCORS="undefined"!=typeof XMLHttpRequest&&function(){try{var a=new XMLHttpRequest}catch(b){return!1}return a.withCredentials!=undefined}(),c.ua.webkit="undefined"!=typeof navigator&&/webkit/i.test(navigator.userAgent),c.ua.iDevice="undefined"!=typeof navigator&&/iPad|iPhone|iPod/i.test(navigator.userAgent)}("undefined"!=typeof io?io:module.exports,this),function(a,b){function c(){}a.EventEmitter=c,c.prototype.on=function(a,c){return this.$events||(this.$events={}),this.$events[a]?b.util.isArray(this.$events[a])?this.$events[a].push(c):this.$events[a]=[this.$events[a],c]:this.$events[a]=c,this},c.prototype.addListener=c.prototype.on,c.prototype.once=function(a,b){function d(){c.removeListener(a,d),b.apply(this,arguments)}var c=this;return d.listener=b,this.on(a,d),this},c.prototype.removeListener=function(a,c){if(this.$events&&this.$events[a]){var d=this.$events[a];if(b.util.isArray(d)){var e=-1;for(var f=0,g=d.length;f<g;f++)if(d[f]===c||d[f].listener&&d[f].listener===c){e=f;break}if(e<0)return this;d.splice(e,1),d.length||delete this.$events[a]}else(d===c||d.listener&&d.listener===c)&&delete this.$events[a]}return this},c.prototype.removeAllListeners=function(a){return a===undefined?(this.$events={},this):(this.$events&&this.$events[a]&&(this.$events[a]=null),this)},c.prototype.listeners=function(a){return this.$events||(this.$events={}),this.$events[a]||(this.$events[a]=[]),b.util.isArray(this.$events[a])||(this.$events[a]=[this.$events[a]]),this.$events[a]},c.prototype.emit=function(a){if(!this.$events)return!1;var c=this.$events[a];if(!c)return!1;var d=Array.prototype.slice.call(arguments,1);if("function"==typeof c)c.apply(this,d);else{if(!b.util.isArray(c))return!1;var e=c.slice();for(var f=0,g=e.length;f<g;f++)e[f].apply(this,d)}return!0}}("undefined"!=typeof io?io:module.exports,"undefined"!=typeof io?io:module.parent.exports),function(exports,nativeJSON){function f(a){return a<10?"0"+a:a}function date(a,b){return isFinite(a.valueOf())?a.getUTCFullYear()+"-"+f(a.getUTCMonth()+1)+"-"+f(a.getUTCDate())+"T"+f(a.getUTCHours())+":"+f(a.getUTCMinutes())+":"+f(a.getUTCSeconds())+"Z":null}function quote(a){return escapable.lastIndex=0,escapable.test(a)?'"'+a.replace(escapable,function(a){var b=meta[a];return typeof b=="string"?b:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+a+'"'}function str(a,b){var c,d,e,f,g=gap,h,i=b[a];i instanceof Date&&(i=date(a)),typeof rep=="function"&&(i=rep.call(b,a,i));switch(typeof i){case"string":return quote(i);case"number":return isFinite(i)?String(i):"null";case"boolean":case"null":return String(i);case"object":if(!i)return"null";gap+=indent,h=[];if(Object.prototype.toString.apply(i)==="[object Array]"){f=i.length;for(c=0;c<f;c+=1)h[c]=str(c,i)||"null";return e=h.length===0?"[]":gap?"[\n"+gap+h.join(",\n"+gap)+"\n"+g+"]":"["+h.join(",")+"]",gap=g,e}if(rep&&typeof rep=="object"){f=rep.length;for(c=0;c<f;c+=1)typeof rep[c]=="string"&&(d=rep[c],e=str(d,i),e&&h.push(quote(d)+(gap?": ":":")+e))}else for(d in i)Object.prototype.hasOwnProperty.call(i,d)&&(e=str(d,i),e&&h.push(quote(d)+(gap?": ":":")+e));return e=h.length===0?"{}":gap?"{\n"+gap+h.join(",\n"+gap)+"\n"+g+"}":"{"+h.join(",")+"}",gap=g,e}}"use strict";if(nativeJSON&&nativeJSON.parse)return exports.JSON={parse:nativeJSON.parse,stringify:nativeJSON.stringify};var JSON=exports.JSON={},cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;JSON.stringify=function(a,b,c){var d;gap="",indent="";if(typeof c=="number")for(d=0;d<c;d+=1)indent+=" ";else typeof c=="string"&&(indent=c);rep=b;if(!b||typeof b=="function"||typeof b=="object"&&typeof b.length=="number")return str("",{"":a});throw new Error("JSON.stringify")},JSON.parse=function(text,reviver){function walk(a,b){var c,d,e=a[b];if(e&&typeof e=="object")for(c in e)Object.prototype.hasOwnProperty.call(e,c)&&(d=walk(e,c),d!==undefined?e[c]=d:delete e[c]);return reviver.call(a,b,e)}var j;text=String(text),cx.lastIndex=0,cx.test(text)&&(text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)}));if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return j=eval("("+text+")"),typeof reviver=="function"?walk({"":j},""):j;throw new SyntaxError("JSON.parse")}}("undefined"!=typeof io?io:module.exports,typeof JSON!="undefined"?JSON:undefined),function(a,b){var c=a.parser={},d=c.packets=["disconnect","connect","heartbeat","message","json","event","ack","error","noop"],e=c.reasons=["transport not supported","client not handshaken","unauthorized"],f=c.advice=["reconnect"],g=b.JSON,h=b.util.indexOf;c.encodePacket=function(a){var b=h(d,a.type),c=a.id||"",i=a.endpoint||"",j=a.ack,k=null;switch(a.type){case"error":var l=a.reason?h(e,a.reason):"",m=a.advice?h(f,a.advice):"";if(l!==""||m!=="")k=l+(m!==""?"+"+m:"");break;case"message":a.data!==""&&(k=a.data);break;case"event":var n={name:a.name};a.args&&a.args.length&&(n.args=a.args),k=g.stringify(n);break;case"json":k=g.stringify(a.data);break;case"connect":a.qs&&(k=a.qs);break;case"ack":k=a.ackId+(a.args&&a.args.length?"+"+g.stringify(a.args):"")}var o=[b,c+(j=="data"?"+":""),i];return k!==null&&k!==undefined&&o.push(k),o.join(":")},c.encodePayload=function(a){var b="";if(a.length==1)return a[0];for(var c=0,d=a.length;c<d;c++){var e=a[c];b+="\ufffd"+e.length+"\ufffd"+a[c]}return b};var i=/([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/;c.decodePacket=function(a){var b=a.match(i);if(!b)return{};var c=b[2]||"",a=b[5]||"",h={type:d[b[1]],endpoint:b[4]||""};c&&(h.id=c,b[3]?h.ack="data":h.ack=!0);switch(h.type){case"error":var b=a.split("+");h.reason=e[b[0]]||"",h.advice=f[b[1]]||"";break;case"message":h.data=a||"";break;case"event":try{var j=g.parse(a);h.name=j.name,h.args=j.args}catch(k){}h.args=h.args||[];break;case"json":try{h.data=g.parse(a)}catch(k){}break;case"connect":h.qs=a||"";break;case"ack":var b=a.match(/^([0-9]+)(\+)?(.*)/);if(b){h.ackId=b[1],h.args=[];if(b[3])try{h.args=b[3]?g.parse(b[3]):[]}catch(k){}}break;case"disconnect":case"heartbeat":}return h},c.decodePayload=function(a){if(a.charAt(0)=="\ufffd"){var b=[];for(var d=1,e="";d<a.length;d++)a.charAt(d)=="\ufffd"?(b.push(c.decodePacket(a.substr(d+1).substr(0,e))),d+=Number(e)+1,e=""):e+=a.charAt(d);return b}return[c.decodePacket(a)]}}("undefined"!=typeof io?io:module.exports,"undefined"!=typeof io?io:module.parent.exports),function(a,b){function c(a,b){this.socket=a,this.sessid=b}a.Transport=c,b.util.mixin(c,b.EventEmitter),c.prototype.heartbeats=function(){return!0},c.prototype.onData=function(a){this.clearCloseTimeout(),(this.socket.connected||this.socket.connecting||this.socket.reconnecting)&&this.setCloseTimeout();if(a!==""){var c=b.parser.decodePayload(a);if(c&&c.length)for(var d=0,e=c.length;d<e;d++)this.onPacket(c[d])}return this},c.prototype.onPacket=function(a){return this.socket.setHeartbeatTimeout(),a.type=="heartbeat"?this.onHeartbeat():(a.type=="connect"&&a.endpoint==""&&this.onConnect(),a.type=="error"&&a.advice=="reconnect"&&(this.isOpen=!1),this.socket.onPacket(a),this)},c.prototype.setCloseTimeout=function(){if(!this.closeTimeout){var a=this;this.closeTimeout=setTimeout(function(){a.onDisconnect()},this.socket.closeTimeout)}},c.prototype.onDisconnect=function(){return this.isOpen&&this.close(),this.clearTimeouts(),this.socket.onDisconnect(),this},c.prototype.onConnect=function(){return this.socket.onConnect(),this},c.prototype.clearCloseTimeout=function(){this.closeTimeout&&(clearTimeout(this.closeTimeout),this.closeTimeout=null)},c.prototype.clearTimeouts=function(){this.clearCloseTimeout(),this.reopenTimeout&&clearTimeout(this.reopenTimeout)},c.prototype.packet=function(a){this.send(b.parser.encodePacket(a))},c.prototype.onHeartbeat=function(a){this.packet({type:"heartbeat"})},c.prototype.onOpen=function(){this.isOpen=!0,this.clearCloseTimeout(),this.socket.onOpen()},c.prototype.onClose=function(){var a=this;this.isOpen=!1,this.socket.onClose(),this.onDisconnect()},c.prototype.prepareUrl=function(){var a=this.socket.options;return this.scheme()+"://"+a.host+":"+a.port+"/"+a.resource+"/"+b.protocol+"/"+this.name+"/"+this.sessid},c.prototype.ready=function(a,b){b.call(this)}}("undefined"!=typeof io?io:module.exports,"undefined"!=typeof io?io:module.parent.exports),function(a,b,c){function d(a){this.options={port:80,secure:!1,document:"document"in c?document:!1,resource:"socket.io",transports:b.transports,"connect timeout":1e4,"try multiple transports":!0,reconnect:!0,"reconnection delay":500,"reconnection limit":Infinity,"reopen delay":3e3,"max reconnection attempts":10,"sync disconnect on unload":!1,"auto connect":!0,"flash policy port":10843,manualFlush:!1},b.util.merge(this.options,a),this.connected=!1,this.open=!1,this.connecting=!1,this.reconnecting=!1,this.namespaces={},this.buffer=[],this.doBuffer=!1;if(this.options["sync disconnect on unload"]&&(!this.isXDomain()||b.util.ua.hasCORS)){var d=this;b.util.on(c,"beforeunload",function(){d.disconnectSync()},!1)}this.options["auto connect"]&&this.connect()}function e(){}a.Socket=d,b.util.mixin(d,b.EventEmitter),d.prototype.of=function(a){return this.namespaces[a]||(this.namespaces[a]=new b.SocketNamespace(this,a),a!==""&&this.namespaces[a].packet({type:"connect"})),this.namespaces[a]},d.prototype.publish=function(){this.emit.apply(this,arguments);var a;for(var b in this.namespaces)this.namespaces.hasOwnProperty(b)&&(a=this.of(b),a.$emit.apply(a,arguments))},d.prototype.handshake=function(a){function f(b){b instanceof Error?(c.connecting=!1,c.onError(b.message)):a.apply(null,b.split(":"))}var c=this,d=this.options,g=["http"+(d.secure?"s":"")+":/",d.host+":"+d.port,d.resource,b.protocol,b.util.query(this.options.query,"t="+ +(new Date))].join("/");if(this.isXDomain()&&!b.util.ua.hasCORS){var h=document.getElementsByTagName("script")[0],i=document.createElement("script");i.src=g+"&jsonp="+b.j.length,h.parentNode.insertBefore(i,h),b.j.push(function(a){f(a),i.parentNode.removeChild(i)})}else{var j=b.util.request();j.open("GET",g,!0),this.isXDomain()&&(j.withCredentials=!0),j.onreadystatechange=function(){j.readyState==4&&(j.onreadystatechange=e,j.status==200?f(j.responseText):j.status==403?c.onError(j.responseText):(c.connecting=!1,!c.reconnecting&&c.onError(j.responseText)))},j.send(null)}},d.prototype.getTransport=function(a){var c=a||this.transports,d;for(var e=0,f;f=c[e];e++)if(b.Transport[f]&&b.Transport[f].check(this)&&(!this.isXDomain()||b.Transport[f].xdomainCheck(this)))return new b.Transport[f](this,this.sessionid);return null},d.prototype.connect=function(a){if(this.connecting)return this;var c=this;return c.connecting=!0,this.handshake(function(d,e,f,g){function h(a){c.transport&&c.transport.clearTimeouts(),c.transport=c.getTransport(a);if(!c.transport)return c.publish("connect_failed");c.transport.ready(c,function(){c.connecting=!0,c.publish("connecting",c.transport.name),c.transport.open(),c.options["connect timeout"]&&(c.connectTimeoutTimer=setTimeout(function(){if(!c.connected){c.connecting=!1;if(c.options["try multiple transports"]){var a=c.transports;while(a.length>0&&a.splice(0,1)[0]!=c.transport.name);a.length?h(a):c.publish("connect_failed")}}},c.options["connect timeout"]))})}c.sessionid=d,c.closeTimeout=f*1e3,c.heartbeatTimeout=e*1e3,c.transports||(c.transports=c.origTransports=g?b.util.intersect(g.split(","),c.options.transports):c.options.transports),c.setHeartbeatTimeout(),h(c.transports),c.once("connect",function(){clearTimeout(c.connectTimeoutTimer),a&&typeof a=="function"&&a()})}),this},d.prototype.setHeartbeatTimeout=function(){clearTimeout(this.heartbeatTimeoutTimer);if(this.transport&&!this.transport.heartbeats())return;var a=this;this.heartbeatTimeoutTimer=setTimeout(function(){a.transport.onClose()},this.heartbeatTimeout)},d.prototype.packet=function(a){return this.connected&&!this.doBuffer?this.transport.packet(a):this.buffer.push(a),this},d.prototype.setBuffer=function(a){this.doBuffer=a,!a&&this.connected&&this.buffer.length&&(this.options.manualFlush||this.flushBuffer())},d.prototype.flushBuffer=function(){this.transport.payload(this.buffer),this.buffer=[]},d.prototype.disconnect=function(){if(this.connected||this.connecting)this.open&&this.of("").packet({type:"disconnect"}),this.onDisconnect("booted");return this},d.prototype.disconnectSync=function(){var a=b.util.request(),c=["http"+(this.options.secure?"s":"")+":/",this.options.host+":"+this.options.port,this.options.resource,b.protocol,"",this.sessionid].join("/")+"/?disconnect=1";a.open("GET",c,!1),a.send(null),this.onDisconnect("booted")},d.prototype.isXDomain=function(){var a=c.location.port||("https:"==c.location.protocol?443:80);return this.options.host!==c.location.hostname||this.options.port!=a},d.prototype.onConnect=function(){this.connected||(this.connected=!0,this.connecting=!1,this.doBuffer||this.setBuffer(!1),this.emit("connect"))},d.prototype.onOpen=function(){this.open=!0},d.prototype.onClose=function(){this.open=!1,clearTimeout(this.heartbeatTimeoutTimer)},d.prototype.onPacket=function(a){this.of(a.endpoint).onPacket(a)},d.prototype.onError=function(a){a&&a.advice&&a.advice==="reconnect"&&(this.connected||this.connecting)&&(this.disconnect(),this.options.reconnect&&this.reconnect()),this.publish("error",a&&a.reason?a.reason:a)},d.prototype.onDisconnect=function(a){var b=this.connected,c=this.connecting;this.connected=!1,this.connecting=!1,this.open=!1;if(b||c)this.transport.close(),this.transport.clearTimeouts(),b&&(this.publish("disconnect",a),"booted"!=a&&this.options.reconnect&&!this.reconnecting&&this.reconnect())},d.prototype.reconnect=function(){function e(){if(a.connected){for(var b in a.namespaces)a.namespaces.hasOwnProperty(b)&&""!==b&&a.namespaces[b].packet({type:"connect"});a.publish("reconnect",a.transport.name,a.reconnectionAttempts)}clearTimeout(a.reconnectionTimer),a.removeListener("connect_failed",f),a.removeListener("connect",f),a.reconnecting=!1,delete a.reconnectionAttempts,delete a.reconnectionDelay,delete a.reconnectionTimer,delete a.redoTransports,a.options["try multiple transports"]=c}function f(){if(!a.reconnecting)return;if(a.connected)return e();if(a.connecting&&a.reconnecting)return a.reconnectionTimer=setTimeout(f,1e3);a.reconnectionAttempts++>=b?a.redoTransports?(a.publish("reconnect_failed"),e()):(a.on("connect_failed",f),a.options["try multiple transports"]=!0,a.transports=a.origTransports,a.transport=a.getTransport(),a.redoTransports=!0,a.connect()):(a.reconnectionDelay<d&&(a.reconnectionDelay*=2),a.connect(),a.publish("reconnecting",a.reconnectionDelay,a.reconnectionAttempts),a.reconnectionTimer=setTimeout(f,a.reconnectionDelay))}this.reconnecting=!0,this.reconnectionAttempts=0,this.reconnectionDelay=this.options["reconnection delay"];var a=this,b=this.options["max reconnection attempts"],c=this.options["try multiple transports"],d=this.options["reconnection limit"];this.options["try multiple transports"]=!1,this.reconnectionTimer=setTimeout(f,this.reconnectionDelay),this.on("connect",f)}}("undefined"!=typeof io?io:module.exports,"undefined"!=typeof io?io:module.parent.exports,this),function(a,b){function c(a,b){this.socket=a,this.name=b||"",this.flags={},this.json=new d(this,"json"),this.ackPackets=0,this.acks={}}function d(a,b){this.namespace=a,this.name=b}a.SocketNamespace=c,b.util.mixin(c,b.EventEmitter),c.prototype.$emit=b.EventEmitter.prototype.emit,c.prototype.of=function(){return this.socket.of.apply(this.socket,arguments)},c.prototype.packet=function(a){return a.endpoint=this.name,this.socket.packet(a),this.flags={},this},c.prototype.send=function(a,b){var c={type:this.flags.json?"json":"message",data:a};return"function"==typeof b&&(c.id=++this.ackPackets,c.ack=!0,this.acks[c.id]=b),this.packet(c)},c.prototype.emit=function(a){var b=Array.prototype.slice.call(arguments,1),c=b[b.length-1],d={type:"event",name:a};return"function"==typeof c&&(d.id=++this.ackPackets,d.ack="data",this.acks[d.id]=c,b=b.slice(0,b.length-1)),d.args=b,this.packet(d)},c.prototype.disconnect=function(){return this.name===""?this.socket.disconnect():(this.packet({type:"disconnect"}),this.$emit("disconnect")),this},c.prototype.onPacket=function(a){function d(){c.packet({type:"ack",args:b.util.toArray(arguments),ackId:a.id})}var c=this;switch(a.type){case"connect":this.$emit("connect");break;case"disconnect":this.name===""?this.socket.onDisconnect(a.reason||"booted"):this.$emit("disconnect",a.reason);break;case"message":case"json":var e=["message",a.data];a.ack=="data"?e.push(d):a.ack&&this.packet({type:"ack",ackId:a.id}),this.$emit.apply(this,e);break;case"event":var e=[a.name].concat(a.args);a.ack=="data"&&e.push(d),this.$emit.apply(this,e);break;case"ack":this.acks[a.ackId]&&(this.acks[a.ackId].apply(this,a.args),delete this.acks[a.ackId]);break;case"error":a.advice?this.socket.onError(a):a.reason=="unauthorized"?this.$emit("connect_failed",a.reason):this.$emit("error",a.reason)}},d.prototype.send=function(){this.namespace.flags[this.name]=!0,this.namespace.send.apply(this.namespace,arguments)},d.prototype.emit=function(){this.namespace.flags[this.name]=!0,this.namespace.emit.apply(this.namespace,arguments)}}("undefined"!=typeof io?io:module.exports,"undefined"!=typeof io?io:module.parent.exports),function(a,b,c){function d(a){b.Transport.apply(this,arguments)}a.websocket=d,b.util.inherit(d,b.Transport),d.prototype.name="websocket",d.prototype.open=function(){var a=b.util.query(this.socket.options.query),d=this,e;return e||(e=c.MozWebSocket||c.WebSocket),this.websocket=new e(this.prepareUrl()+a),this.websocket.onopen=function(){d.onOpen(),d.socket.setBuffer(!1)},this.websocket.onmessage=function(a){d.onData(a.data)},this.websocket.onclose=function(){d.onClose(),d.socket.setBuffer(!0)},this.websocket.onerror=function(a){d.onError(a)},this},b.util.ua.iDevice?d.prototype.send=function(a){var b=this;return setTimeout(function(){b.websocket.send(a)},0),this}:d.prototype.send=function(a){return this.websocket.send(a),this},d.prototype.payload=function(a){for(var b=0,c=a.length;b<c;b++)this.packet(a[b]);return this},d.prototype.close=function(){return this.websocket.close(),this},d.prototype.onError=function(a){this.socket.onError(a)},d.prototype.scheme=function(){return this.socket.options.secure?"wss":"ws"},d.check=function(){return"WebSocket"in c&&!("__addTask"in WebSocket)||"MozWebSocket"in c},d.xdomainCheck=function(){return!0},b.transports.push("websocket")}("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports,this),function(a,b){function c(){b.Transport.websocket.apply(this,arguments)}a.flashsocket=c,b.util.inherit(c,b.Transport.websocket),c.prototype.name="flashsocket",c.prototype.open=function(){var a=this,c=arguments;return WebSocket.__addTask(function(){b.Transport.websocket.prototype.open.apply(a,c)}),this},c.prototype.send=function(){var a=this,c=arguments;return WebSocket.__addTask(function(){b.Transport.websocket.prototype.send.apply(a,c)}),this},c.prototype.close=function(){return WebSocket.__tasks.length=0,b.Transport.websocket.prototype.close.call(this),this},c.prototype.ready=function(a,d){function e(){var b=a.options,e=b["flash policy port"],g=["http"+(b.secure?"s":"")+":/",b.host+":"+b.port,b.resource,"static/flashsocket","WebSocketMain"+(a.isXDomain()?"Insecure":"")+".swf"];c.loaded||(typeof WEB_SOCKET_SWF_LOCATION=="undefined"&&(WEB_SOCKET_SWF_LOCATION=g.join("/")),e!==843&&WebSocket.loadFlashPolicyFile("xmlsocket://"+b.host+":"+e),WebSocket.__initialize(),c.loaded=!0),d.call(f)}var f=this;if(document.body)return e();b.util.load(e)},c.check=function(){return typeof WebSocket!="undefined"&&"__initialize"in WebSocket&&!!swfobject?swfobject.getFlashPlayerVersion().major>=10:!1},c.xdomainCheck=function(){return!0},typeof window!="undefined"&&(WEB_SOCKET_DISABLE_AUTO_INITIALIZATION=!0),b.transports.push("flashsocket")}("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports);if("undefined"!=typeof window)var swfobject=function(){function A(){if(t)return;try{var a=i.getElementsByTagName("body")[0].appendChild(Q("span"));a.parentNode.removeChild(a)}catch(b){return}t=!0;var c=l.length;for(var d=0;d<c;d++)l[d]()}function B(a){t?a():l[l.length]=a}function C(b){if(typeof h.addEventListener!=a)h.addEventListener("load",b,!1);else if(typeof i.addEventListener!=a)i.addEventListener("load",b,!1);else if(typeof h.attachEvent!=a)R(h,"onload",b);else if(typeof h.onload=="function"){var c=h.onload;h.onload=function(){c(),b()}}else h.onload=b}function D(){k?E():F()}function E(){var c=i.getElementsByTagName("body")[0],d=Q(b);d.setAttribute("type",e);var f=c.appendChild(d);if(f){var g=0;(function(){if(typeof f.GetVariable!=a){var b=f.GetVariable("$version");b&&(b=b.split(" ")[1].split(","),y.pv=[parseInt(b[0],10),parseInt(b[1],10),parseInt(b[2],10)])}else if(g<10){g++,setTimeout(arguments.callee,10);return}c.removeChild(d),f=null,F()})()}else F()}function F(){var b=m.length;if(b>0)for(var c=0;c<b;c++){var d=m[c].id,e=m[c].callbackFn,f={success:!1,id:d};if(y.pv[0]>0){var g=P(d);if(g)if(S(m[c].swfVersion)&&!(y.wk&&y.wk<312))U(d,!0),e&&(f.success=!0,f.ref=G(d),e(f));else if(m[c].expressInstall&&H()){var h={};h.data=m[c].expressInstall,h.width=g.getAttribute("width")||"0",h.height=g.getAttribute("height")||"0",g.getAttribute("class")&&(h.styleclass=g.getAttribute("class")),g.getAttribute("align")&&(h.align=g.getAttribute("align"));var i={},j=g.getElementsByTagName("param"),k=j.length;for(var l=0;l<k;l++)j[l].getAttribute("name").toLowerCase()!="movie"&&(i[j[l].getAttribute("name")]=j[l].getAttribute("value"));I(h,i,d,e)}else J(g),e&&e(f)}else{U(d,!0);if(e){var n=G(d);n&&typeof n.SetVariable!=a&&(f.success=!0,f.ref=n),e(f)}}}}function G(c){var d=null,e=P(c);if(e&&e.nodeName=="OBJECT")if(typeof e.SetVariable!=a)d=e;else{var f=e.getElementsByTagName(b)[0];f&&(d=f)}return d}function H(){return!u&&S("6.0.65")&&(y.win||y.mac)&&!(y.wk&&y.wk<312)}function I(b,c,d,e){u=!0,r=e||null,s={success:!1,id:d};var g=P(d);if(g){g.nodeName=="OBJECT"?(p=K(g),q=null):(p=g,q=d),b.id=f;if(typeof b.width==a||!/%$/.test(b.width)&&parseInt(b.width,10)<310)b.width="310";if(typeof b.height==a||!/%$/.test(b.height)&&parseInt(b.height,10)<137)b.height="137";i.title=i.title.slice(0,47)+" - Flash Player Installation";var j=y.ie&&y.win?["Active"].concat("").join("X"):"PlugIn",k="MMredirectURL="+h.location.toString().replace(/&/g,"%26")+"&MMplayerType="+j+"&MMdoctitle="+i.title;typeof c.flashvars!=a?c.flashvars+="&"+k:c.flashvars=k;if(y.ie&&y.win&&g.readyState!=4){var l=Q("div");d+="SWFObjectNew",l.setAttribute("id",d),g.parentNode.insertBefore(l,g),g.style.display="none",function(){g.readyState==4?g.parentNode.removeChild(g):setTimeout(arguments.callee,10)}()}L(b,c,d)}}function J(a){if(y.ie&&y.win&&a.readyState!=4){var b=Q("div");a.parentNode.insertBefore(b,a),b.parentNode.replaceChild(K(a),b),a.style.display="none",function(){a.readyState==4?a.parentNode.removeChild(a):setTimeout(arguments.callee,10)}()}else a.parentNode.replaceChild(K(a),a)}function K(a){var c=Q("div");if(y.win&&y.ie)c.innerHTML=a.innerHTML;else{var d=a.getElementsByTagName(b)[0];if(d){var e=d.childNodes;if(e){var f=e.length;for(var g=0;g<f;g++)(e[g].nodeType!=1||e[g].nodeName!="PARAM")&&e[g].nodeType!=8&&c.appendChild(e[g].cloneNode(!0))}}}return c}function L(c,d,f){var g,h=P(f);if(y.wk&&y.wk<312)return g;if(h){typeof c.id==a&&(c.id=f);if(y.ie&&y.win){var i="";for(var j in c)c[j]!=Object.prototype[j]&&(j.toLowerCase()=="data"?d.movie=c[j]:j.toLowerCase()=="styleclass"?i+=' class="'+c[j]+'"':j.toLowerCase()!="classid"&&(i+=" "+j+'="'+c[j]+'"'));var k="";for(var l in d)d[l]!=Object.prototype[l]&&(k+='<param name="'+l+'" value="'+d[l]+'" />');h.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+i+">"+k+"</object>",n[n.length]=c.id,g=P(c.id)}else{var m=Q(b);m.setAttribute("type",e);for(var o in c)c[o]!=Object.prototype[o]&&(o.toLowerCase()=="styleclass"?m.setAttribute("class",c[o]):o.toLowerCase()!="classid"&&m.setAttribute(o,c[o]));for(var p in d)d[p]!=Object.prototype[p]&&p.toLowerCase()!="movie"&&M(m,p,d[p]);h.parentNode.replaceChild(m,h),g=m}}return g}function M(a,b,c){var d=Q("param");d.setAttribute("name",b),d.setAttribute("value",c),a.appendChild(d)}function N(a){var b=P(a);b&&b.nodeName=="OBJECT"&&(y.ie&&y.win?(b.style.display="none",function(){b.readyState==4?O(a):setTimeout(arguments.callee,10)}()):b.parentNode.removeChild(b))}function O(a){var b=P(a);if(b){for(var c in b)typeof b[c]=="function"&&(b[c]=null);b.parentNode.removeChild(b)}}function P(a){var b=null;try{b=i.getElementById(a)}catch(c){}return b}function Q(a){return i.createElement(a)}function R(a,b,c){a.attachEvent(b,c),o[o.length]=[a,b,c]}function S(a){var b=y.pv,c=a.split(".");return c[0]=parseInt(c[0],10),c[1]=parseInt(c[1],10)||0,c[2]=parseInt(c[2],10)||0,b[0]>c[0]||b[0]==c[0]&&b[1]>c[1]||b[0]==c[0]&&b[1]==c[1]&&b[2]>=c[2]?!0:!1}function T(c,d,e,f){if(y.ie&&y.mac)return;var g=i.getElementsByTagName("head")[0];if(!g)return;var h=e&&typeof e=="string"?e:"screen";f&&(v=null,w=null);if(!v||w!=h){var j=Q("style");j.setAttribute("type","text/css"),j.setAttribute("media",h),v=g.appendChild(j),y.ie&&y.win&&typeof i.styleSheets!=a&&i.styleSheets.length>0&&(v=i.styleSheets[i.styleSheets.length-1]),w=h}y.ie&&y.win?v&&typeof v.addRule==b&&v.addRule(c,d):v&&typeof i.createTextNode!=a&&v.appendChild(i.createTextNode(c+" {"+d+"}"))}function U(a,b){if(!x)return;var c=b?"visible":"hidden";t&&P(a)?P(a).style.visibility=c:T("#"+a,"visibility:"+c)}function V(b){var c=/[\\\"<>\.;]/,d=c.exec(b)!=null;return d&&typeof encodeURIComponent!=a?encodeURIComponent(b):b}var a="undefined",b="object",c="Shockwave Flash",d="ShockwaveFlash.ShockwaveFlash",e="application/x-shockwave-flash",f="SWFObjectExprInst",g="onreadystatechange",h=window,i=document,j=navigator,k=!1,l=[D],m=[],n=[],o=[],p,q,r,s,t=!1,u=!1,v,w,x=!0,y=function(){var f=typeof i.getElementById!=a&&typeof i.getElementsByTagName!=a&&typeof i.createElement!=a,g=j.userAgent.toLowerCase(),l=j.platform.toLowerCase(),m=l?/win/.test(l):/win/.test(g),n=l?/mac/.test(l):/mac/.test(g),o=/webkit/.test(g)?parseFloat(g.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):!1,p=!1,q=[0,0,0],r=null;if(typeof j.plugins!=a&&typeof j.plugins[c]==b)r=j.plugins[c].description,r&&(typeof j.mimeTypes==a||!j.mimeTypes[e]||!!j.mimeTypes[e].enabledPlugin)&&(k=!0,p=!1,r=r.replace(/^.*\s+(\S+\s+\S+$)/,"$1"),q[0]=parseInt(r.replace(/^(.*)\..*$/,"$1"),10),q[1]=parseInt(r.replace(/^.*\.(.*)\s.*$/,"$1"),10),q[2]=/[a-zA-Z]/.test(r)?parseInt(r.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0);else if(typeof h[["Active"].concat("Object").join("X")]!=a)try{var s=new(window[["Active"].concat("Object").join("X")])(d);s&&(r=s.GetVariable("$version"),r&&(p=!0,r=r.split(" ")[1].split(","),q=[parseInt(r[0],10),parseInt(r[1],10),parseInt(r[2],10)]))}catch(t){}return{w3:f,pv:q,wk:o,ie:p,win:m,mac:n}}(),z=function(){if(!y.w3)return;(typeof i.readyState!=a&&i.readyState=="complete"||typeof i.readyState==a&&(i.getElementsByTagName("body")[0]||i.body))&&A(),t||(typeof i.addEventListener!=a&&i.addEventListener("DOMContentLoaded",A,!1),y.ie&&y.win&&(i.attachEvent(g,function(){i.readyState=="complete"&&(i.detachEvent(g,arguments.callee),A())}),h==top&&function(){if(t)return;try{i.documentElement.doScroll("left")}catch(a){setTimeout(arguments.callee,0);return}A()}()),y.wk&&function(){if(t)return;if(!/loaded|complete/.test(i.readyState)){setTimeout(arguments.callee,0);return}A()}(),C(A))}(),W=function(){y.ie&&y.win&&window.attachEvent("onunload",function(){var a=o.length;for(var b=0;b<a;b++)o[b][0].detachEvent(o[b][1],o[b][2]);var c=n.length;for(var d=0;d<c;d++)N(n[d]);for(var e in y)y[e]=null;y=null;for(var f in swfobject)swfobject[f]=null;swfobject=null})}();return{registerObject:function(a,b,c,d){if(y.w3&&a&&b){var e={};e.id=a,e.swfVersion=b,e.expressInstall=c,e.callbackFn=d,m[m.length]=e,U(a,!1)}else d&&d({success:!1,id:a})},getObjectById:function(a){if(y.w3)return G(a)},embedSWF:function(c,d,e,f,g,h,i,j,k,l){var m={success:!1,id:d};y.w3&&!(y.wk&&y.wk<312)&&c&&d&&e&&f&&g?(U(d,!1),B(function(){e+="",f+="";var n={};if(k&&typeof k===b)for(var o in k)n[o]=k[o];n.data=c,n.width=e,n.height=f;var p={};if(j&&typeof j===b)for(var q in j)p[q]=j[q];if(i&&typeof i===b)for(var r in i)typeof p.flashvars!=a?p.flashvars+="&"+r+"="+i[r]:p.flashvars=r+"="+i[r];if(S(g)){var s=L(n,p,d);n.id==d&&U(d,!0),m.success=!0,m.ref=s}else{if(h&&H()){n.data=h,I(n,p,d,l);return}U(d,!0)}l&&l(m)})):l&&l(m)},switchOffAutoHideShow:function(){x=!1},ua:y,getFlashPlayerVersion:function(){return{major:y.pv[0],minor:y.pv[1],release:y.pv[2]}},hasFlashPlayerVersion:S,createSWF:function(a,b,c){return y.w3?L(a,b,c):undefined},showExpressInstall:function(a,b,c,d){y.w3&&H()&&I(a,b,c,d)},removeSWF:function(a){y.w3&&N(a)},createCSS:function(a,b,c,d){y.w3&&T(a,b,c,d)},addDomLoadEvent:B,addLoadEvent:C,getQueryParamValue:function(a){var b=i.location.search||i.location.hash;if(b){/\?/.test(b)&&(b=b.split("?")[1]);if(a==null)return V(b);var c=b.split("&");for(var d=0;d<c.length;d++)if(c[d].substring(0,c[d].indexOf("="))==a)return V(c[d].substring(c[d].indexOf("=")+1))}return""},expressInstallCallback:function(){if(u){var a=P(f);a&&p&&(a.parentNode.replaceChild(p,a),q&&(U(q,!0),y.ie&&y.win&&(p.style.display="block")),r&&r(s)),u=!1}}}}();(function(){if("undefined"==typeof window||window.WebSocket)return;var a=window.console;if(!a||!a.log||!a.error)a={log:function(){},error:function(){}};if(!swfobject.hasFlashPlayerVersion("10.0.0")){a.error("Flash Player >= 10.0.0 is required.");return}location.protocol=="file:"&&a.error("WARNING: web-socket-js doesn't work in file:///... URL unless you set Flash Security Settings properly. Open the page via Web server i.e. http://..."),WebSocket=function(a,b,c,d,e){var f=this;f.__id=WebSocket.__nextId++,WebSocket.__instances[f.__id]=f,f.readyState=WebSocket.CONNECTING,f.bufferedAmount=0,f.__events={},b?typeof b=="string"&&(b=[b]):b=[],setTimeout(function(){WebSocket.__addTask(function(){WebSocket.__flash.create(f.__id,a,b,c||null,d||0,e||null)})},0)},WebSocket.prototype.send=function(a){if(this.readyState==WebSocket.CONNECTING)throw"INVALID_STATE_ERR: Web Socket connection has not been established";var b=WebSocket.__flash.send(this.__id,encodeURIComponent(a));return b<0?!0:(this.bufferedAmount+=b,!1)},WebSocket.prototype.close=function(){if(this.readyState==WebSocket.CLOSED||this.readyState==WebSocket.CLOSING)return;this.readyState=WebSocket.CLOSING,WebSocket.__flash.close(this.__id)},WebSocket.prototype.addEventListener=function(a,b,c){a in this.__events||(this.__events[a]=[]),this.__events[a].push(b)},WebSocket.prototype.removeEventListener=function(a,b,c){if(!(a in this.__events))return;var d=this.__events[a];for(var e=d.length-1;e>=0;--e)if(d[e]===b){d.splice(e,1);break}},WebSocket.prototype.dispatchEvent=function(a){var b=this.__events[a.type]||[];for(var c=0;c<b.length;++c)b[c](a);var d=this["on"+a.type];d&&d(a)},WebSocket.prototype.__handleEvent=function(a){"readyState"in a&&(this.readyState=a.readyState),"protocol"in a&&(this.protocol=a.protocol);var b;if(a.type=="open"||a.type=="error")b=this.__createSimpleEvent(a.type);else if(a.type=="close")b=this.__createSimpleEvent("close");else{if(a.type!="message")throw"unknown event type: "+a.type;var c=decodeURIComponent(a.message);b=this.__createMessageEvent("message",c)}this.dispatchEvent(b)},WebSocket.prototype.__createSimpleEvent=function(a){if(document.createEvent&&window.Event){var b=document.createEvent("Event");return b.initEvent(a,!1,!1),b}return{type:a,bubbles:!1,cancelable:!1}},WebSocket.prototype.__createMessageEvent=function(a,b){if(document.createEvent&&window.MessageEvent&&!window.opera){var c=document.createEvent("MessageEvent");return c.initMessageEvent("message",!1,!1,b,null,null,window,null),c}return{type:a,data:b,bubbles:!1,cancelable:!1}},WebSocket.CONNECTING=0,WebSocket.OPEN=1,WebSocket.CLOSING=2,WebSocket.CLOSED=3,WebSocket.__flash=null,WebSocket.__instances={},WebSocket.__tasks=[],WebSocket.__nextId=0,WebSocket.loadFlashPolicyFile=function(a){WebSocket.__addTask(function(){WebSocket.__flash.loadManualPolicyFile(a)})},WebSocket.__initialize=function(){if(WebSocket.__flash)return;WebSocket.__swfLocation&&(window.WEB_SOCKET_SWF_LOCATION=WebSocket.__swfLocation);if(!window.WEB_SOCKET_SWF_LOCATION){a.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");return}var b=document.createElement("div");b.id="webSocketContainer",b.style.position="absolute",WebSocket.__isFlashLite()?(b.style.left="0px",b.style.top="0px"):(b.style.left="-100px",b.style.top="-100px");var c=document.createElement("div");c.id="webSocketFlash",b.appendChild(c),document.body.appendChild(b),swfobject.embedSWF(WEB_SOCKET_SWF_LOCATION,"webSocketFlash","1","1","10.0.0",null,null,{hasPriority:!0,swliveconnect:!0,allowScriptAccess:"always"},null,function(b){b.success||a.error("[WebSocket] swfobject.embedSWF failed")})},WebSocket.__onFlashInitialized=function(){setTimeout(function(){WebSocket.__flash=document.getElementById("webSocketFlash"),WebSocket.__flash.setCallerUrl(location.href),WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);for(var a=0;a<WebSocket.__tasks.length;++a)WebSocket.__tasks[a]();WebSocket.__tasks=[]},0)},WebSocket.__onFlashEvent=function(){return setTimeout(function(){try{var b=WebSocket.__flash.receiveEvents();for(var c=0;c<b.length;++c)WebSocket.__instances[b[c].webSocketId].__handleEvent(b[c])}catch(d){a.error(d)}},0),!0},WebSocket.__log=function(b){a.log(decodeURIComponent(b))},WebSocket.__error=function(b){a.error(decodeURIComponent(b))},WebSocket.__addTask=function(a){WebSocket.__flash?a():WebSocket.__tasks.push(a)},WebSocket.__isFlashLite=function(){if(!window.navigator||!window.navigator.mimeTypes)return!1;var a=window.navigator.mimeTypes["application/x-shockwave-flash"];return!a||!a.enabledPlugin||!a.enabledPlugin.filename?!1:a.enabledPlugin.filename.match(/flashlite/i)?!0:!1},window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION||(window.addEventListener?window.addEventListener("load",function(){WebSocket.__initialize()},!1):window.attachEvent("onload",function(){WebSocket.__initialize()}))})(),function(a,b,c){function d(a){if(!a)return;b.Transport.apply(this,arguments),this.sendBuffer=[]}function e(){}a.XHR=d,b.util.inherit(d,b.Transport),d.prototype.open=function(){return this.socket.setBuffer(!1),this.onOpen(),this.get(),this.setCloseTimeout(),this},d.prototype.payload=function(a){var c=[];for(var d=0,e=a.length;d<e;d++)c.push(b.parser.encodePacket(a[d]));this.send(b.parser.encodePayload(c))},d.prototype.send=function(a){return this.post(a),this},d.prototype.post=function(a){function d(){this.readyState==4&&(this.onreadystatechange=e,b.posting=!1,this.status==200?b.socket.setBuffer(!1):b.onClose())}function f(){this.onload=e,b.socket.setBuffer(!1)}var b=this;this.socket.setBuffer(!0),this.sendXHR=this.request("POST"),c.XDomainRequest&&this.sendXHR instanceof XDomainRequest?this.sendXHR.onload=this.sendXHR.onerror=f:this.sendXHR.onreadystatechange=d,this.sendXHR.send(a)},d.prototype.close=function(){return this.onClose(),this},d.prototype.request=function(a){var c=b.util.request(this.socket.isXDomain()),d=b.util.query(this.socket.options.query,"t="+ +(new Date));c.open(a||"GET",this.prepareUrl()+d,!0);if(a=="POST")try{c.setRequestHeader?c.setRequestHeader("Content-type","text/plain;charset=UTF-8"):c.contentType="text/plain"}catch(e){}return c},d.prototype.scheme=function(){return this.socket.options.secure?"https":"http"},d.check=function(a,d){try{var e=b.util.request(d),f=c.XDomainRequest&&e instanceof XDomainRequest,g=a&&a.options&&a.options.secure?"https:":"http:",h=c.location&&g!=c.location.protocol;if(e&&(!f||!h))return!0}catch(i){}return!1},d.xdomainCheck=function(a){return d.check(a,!0)}}("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports,this),function(a,b){function c(a){b.Transport.XHR.apply(this,arguments)}a.htmlfile=c,b.util.inherit(c,b.Transport.XHR),c.prototype.name="htmlfile",c.prototype.get=function(){this.doc=new(window[["Active"].concat("Object").join("X")])("htmlfile"),this.doc.open(),this.doc.write("<html></html>"),this.doc.close(),this.doc.parentWindow.s=this;var a=this.doc.createElement("div");a.className="socketio",this.doc.body.appendChild(a),this.iframe=this.doc.createElement("iframe"),a.appendChild(this.iframe);var c=this,d=b.util.query(this.socket.options.query,"t="+ +(new Date));this.iframe.src=this.prepareUrl()+d,b.util.on(window,"unload",function(){c.destroy()})},c.prototype._=function(a,b){a=a.replace(/\\\//g,"/"),this.onData(a);try{var c=b.getElementsByTagName("script")[0];c.parentNode.removeChild(c)}catch(d){}},c.prototype.destroy=function(){if(this.iframe){try{this.iframe.src="about:blank"}catch(a){}this.doc=null,this.iframe.parentNode.removeChild(this.iframe),this.iframe=null,CollectGarbage()}},c.prototype.close=function(){return this.destroy(),b.Transport.XHR.prototype.close.call(this)},c.check=function(a){if(typeof window!="undefined"&&["Active"].concat("Object").join("X")in window)try{var c=new(window[["Active"].concat("Object").join("X")])("htmlfile");return c&&b.Transport.XHR.check(a)}catch(d){}return!1},c.xdomainCheck=function(){return!1},b.transports.push("htmlfile")}("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports),function(a,b,c){function d(){b.Transport.XHR.apply(this,arguments)}function e(){}a["xhr-polling"]=d,b.util.inherit(d,b.Transport.XHR),b.util.merge(d,b.Transport.XHR),d.prototype.name="xhr-polling",d.prototype.heartbeats=function(){return!1},d.prototype.open=function(){var a=this;return b.Transport.XHR.prototype.open.call(a),!1},d.prototype.get=function(){function b(){this.readyState==4&&(this.onreadystatechange=e,this.status==200?(a.onData(this.responseText),a.get()):a.onClose())}function d(){this.onload=e,this.onerror=e,a.retryCounter=1,a.onData(this.responseText),a.get()}function f(){a.retryCounter++,!a.retryCounter||a.retryCounter>3?a.onClose():a.get()}if(!this.isOpen)return;var a=this;this.xhr=this.request(),c.XDomainRequest&&this.xhr instanceof XDomainRequest?(this.xhr.onload=d,this.xhr.onerror=f):this.xhr.onreadystatechange=b,this.xhr.send(null)},d.prototype.onClose=function(){b.Transport.XHR.prototype.onClose.call(this);if(this.xhr){this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=e;try{this.xhr.abort()}catch(a){}this.xhr=null}},d.prototype.ready=function(a,c){var d=this;b.util.defer(function(){c.call(d)})},b.transports.push("xhr-polling")}("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports,this),function(a,b,c){function e(a){b.Transport["xhr-polling"].apply(this,arguments),this.index=b.j.length;var c=this;b.j.push(function(a){c._(a)})}var d=c.document&&"MozAppearance"in c.document.documentElement.style;a["jsonp-polling"]=e,b.util.inherit(e,b.Transport["xhr-polling"]),e.prototype.name="jsonp-polling",e.prototype.post=function(a){function i(){j(),c.socket.setBuffer(!1)}function j(){c.iframe&&c.form.removeChild(c.iframe);try{h=document.createElement('<iframe name="'+c.iframeId+'">')}catch(a){h=document.createElement("iframe"),h.name=c.iframeId}h.id=c.iframeId,c.form.appendChild(h),c.iframe=h}var c=this,d=b.util.query(this.socket.options.query,"t="+ +(new Date)+"&i="+this.index);if(!this.form){var e=document.createElement("form"),f=document.createElement("textarea"),g=this.iframeId="socketio_iframe_"+this.index,h;e.className="socketio",e.style.position="absolute",e.style.top="0px",e.style.left="0px",e.style.display="none",e.target=g,e.method="POST",e.setAttribute("accept-charset","utf-8"),f.name="d",e.appendChild(f),document.body.appendChild(e),this.form=e,this.area=f}this.form.action=this.prepareUrl()+d,j(),this.area.value=b.JSON.stringify(a);try{this.form.submit()}catch(k){}this.iframe.attachEvent?h.onreadystatechange=function(){c.iframe.readyState=="complete"&&i()}:this.iframe.onload=i,this.socket.setBuffer(!0)},e.prototype.get=function(){var a=this,c=document.createElement("script"),e=b.util.query(this.socket.options.query,"t="+ +(new Date)+"&i="+this.index);this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),c.async=!0,c.src=this.prepareUrl()+e,c.onerror=function(){a.onClose()};var f=document.getElementsByTagName("script")[0];f.parentNode.insertBefore(c,f),this.script=c,d&&setTimeout(function(){var a=document.createElement("iframe");document.body.appendChild(a),document.body.removeChild(a)},100)},e.prototype._=function(a){return this.onData(a),this.isOpen&&this.get(),this},e.prototype.ready=function(a,c){var e=this;if(!d)return c.call(this);b.util.load(function(){c.call(e)})},e.check=function(){return"document"in c},e.xdomainCheck=function(){return!0},b.transports.push("jsonp-polling")}("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports,this),typeof define=="function"&&define.amd&&define([],function(){return io})})();
/**
* sails.io.js
* ------------------------------------------------------------------------
* JavaScript Client (SDK) for communicating with Sails.
*
* Note that this script is completely optional, but it is handy if you're
* using WebSockets from the browser to talk to your Sails server.
*
* For tips and documentation, visit:
* http://sailsjs.org/#!documentation/reference/BrowserSDK/BrowserSDK.html
* ------------------------------------------------------------------------
*
* This file allows you to send and receive socket.io messages to & from Sails
* by simulating a REST client interface on top of socket.io. It models its API
* after the $.ajax pattern from jQuery you might already be familiar with.
*
* So if you're switching from using AJAX to sockets, instead of:
* `$.post( url, [data], [cb] )`
*
* You would use:
* `socket.post( url, [data], [cb] )`
*/
(function() {
// Save the URL that this script was fetched from for use below.
// (skip this if this SDK is being used outside of the DOM, i.e. in a Node process)
var urlThisScriptWasFetchedFrom = (function() {
if (
typeof window !== 'object' ||
typeof window.document !== 'object' ||
typeof window.document.getElementsByTagName !== 'function'
) {
return '';
}
// Return the URL of the last script loaded (i.e. this one)
// (this must run before nextTick; see http://stackoverflow.com/a/2976714/486547)
var allScriptsCurrentlyInDOM = window.document.getElementsByTagName('script');
var thisScript = allScriptsCurrentlyInDOM[allScriptsCurrentlyInDOM.length - 1];
return thisScript.src;
})();
// Constants
var CONNECTION_METADATA_PARAMS = {
version: '__sails_io_sdk_version',
platform: '__sails_io_sdk_platform',
language: '__sails_io_sdk_language'
};
// Current version of this SDK (sailsDK?!?!) and other metadata
// that will be sent along w/ the initial connection request.
var SDK_INFO = {
version: '0.10.0', // TODO: pull this automatically from package.json during build.
platform: typeof module === 'undefined' ? 'browser' : 'node',
language: 'javascript'
};
SDK_INFO.versionString =
CONNECTION_METADATA_PARAMS.version + '=' + SDK_INFO.version + '&' +
CONNECTION_METADATA_PARAMS.platform + '=' + SDK_INFO.platform + '&' +
CONNECTION_METADATA_PARAMS.language + '=' + SDK_INFO.language;
// In case you're wrapping the socket.io client to prevent pollution of the
// global namespace, you can pass in your own `io` to replace the global one.
// But we still grab access to the global one if it's available here:
var _io = (typeof io !== 'undefined') ? io : null;
/**
* Augment the `io` object passed in with methods for talking and listening
* to one or more Sails backend(s). Automatically connects a socket and
* exposes it on `io.socket`. If a socket tries to make requests before it
* is connected, the sails.io.js client will queue it up.
*
* @param {SocketIO} io
*/
function SailsIOClient(io) {
// Prefer the passed-in `io` instance, but also use the global one if we've got it.
io = io || _io;
// If the socket.io client is not available, none of this will work.
if (!io) throw new Error('`sails.io.js` requires a socket.io client, but `io` was not passed in.');
//////////////////////////////////////////////////////////////
///// ///////////////////////////
///// PRIVATE METHODS/CONSTRUCTORS ///////////////////////////
///// ///////////////////////////
//////////////////////////////////////////////////////////////
/**
* TmpSocket
*
* A mock Socket used for binding events before the real thing
* has been instantiated (since we need to use io.connect() to
* instantiate the real thing, which would kick off the connection
* process w/ the server, and we don't necessarily have the valid
* configuration to know WHICH SERVER to talk to yet.)
*
* @api private
* @constructor
*/
function TmpSocket() {
var boundEvents = {};
this.on = function (evName, fn) {
if (!boundEvents[evName]) boundEvents[evName] = [fn];
else boundEvents[evName].push(fn);
return this;
};
this.become = function(actualSocket) {
// Pass events and a reference to the request queue
// off to the actualSocket for consumption
for (var evName in boundEvents) {
for (var i in boundEvents[evName]) {
actualSocket.on(evName, boundEvents[evName][i]);
}
}
actualSocket.requestQueue = this.requestQueue;
// Bind a one-time function to run the request queue
// when the actualSocket connects.
if (!_isConnected(actualSocket)) {
var alreadyRanRequestQueue = false;
actualSocket.on('connect', function onActualSocketConnect() {
if (alreadyRanRequestQueue) return;
runRequestQueue(actualSocket);
alreadyRanRequestQueue = true;
});
}
// Or run it immediately if actualSocket is already connected
else {
runRequestQueue(actualSocket);
}
return actualSocket;
};
// Uses `this` instead of `TmpSocket.prototype` purely
// for convenience, since it makes more sense to attach
// our extra methods to the `Socket` prototype down below.
// This could be optimized by moving those Socket method defs
// to the top of this SDK file instead of the bottom. Will
// gladly do it if it is an issue for anyone.
this.get = Socket.prototype.get;
this.post = Socket.prototype.post;
this.put = Socket.prototype.put;
this['delete'] = Socket.prototype['delete'];
this.request = Socket.prototype.request;
this._request = Socket.prototype._request;
}
/**
* A little logger for this library to use internally.
* Basically just a wrapper around `console.log` with
* support for feature-detection.
*
* @api private
* @factory
*/
function LoggerFactory(options) {
options = options || {
prefix: true
};
// If `console.log` is not accessible, `log` is a noop.
if (
typeof console !== 'object' ||
typeof console.log !== 'function' ||
typeof console.log.bind !== 'function'
) {
return function noop() {};
}
return function log() {
var args = Array.prototype.slice.call(arguments);
// All logs are disabled when `io.sails.environment = 'production'`.
if (io.sails.environment === 'production') return;
// Add prefix to log messages (unless disabled)
var PREFIX = '';
if (options.prefix) {
args.unshift(PREFIX);
}
// Call wrapped logger
console.log
.bind(console)
.apply(this, args);
};
}
// Create a private logger instance
var consolog = LoggerFactory();
consolog.noPrefix = LoggerFactory({
prefix: false
});
/**
* _isConnected
*
* @api private
* @param {Socket} socket
* @return {Boolean} whether the socket is connected and able to
* communicate w/ the server.
*/
function _isConnected(socket) {
return socket.socket && socket.socket.connected;
}
/**
* What is the `requestQueue`?
*
* The request queue is used to simplify app-level connection logic--
* i.e. so you don't have to wait for the socket to be connected
* to start trying to synchronize data.
*
* @api private
* @param {Socket} socket
*/
function runRequestQueue (socket) {
var queue = socket.requestQueue;
if (!queue) return;
for (var i in queue) {
// Double-check that `queue[i]` will not
// inadvertently discover extra properties attached to the Object
// and/or Array prototype by other libraries/frameworks/tools.
// (e.g. Ember does this. See https://github.com/balderdashy/sails.io.js/pull/5)
var isSafeToDereference = ({}).hasOwnProperty.call(queue, i);
if (isSafeToDereference) {
// Emit the request.
_emitFrom(socket, queue[i]);
}
}
}
/**
* Send an AJAX request.
*
* @param {Object} opts [optional]
* @param {Function} cb
* @return {XMLHttpRequest}
*/
function ajax(opts, cb) {
opts = opts || {};
var xmlhttp;
if (typeof window === 'undefined') {
// TODO: refactor node usage to live in here
return cb();
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
cb(xmlhttp.responseText);
}
};
xmlhttp.open(opts.method, opts.url, true);
xmlhttp.send();
return xmlhttp;
}
/**
* The JWR (JSON WebSocket Response) received from a Sails server.
*
* @api private
* @param {Object} responseCtx
* => :body
* => :statusCode
* => :headers
* @constructor
*/
function JWR(responseCtx) {
this.body = responseCtx.body || {};
this.headers = responseCtx.headers || {};
this.statusCode = responseCtx.statusCode || 200;
}
JWR.prototype.toString = function() {
return '[ResponseFromSails]' + ' -- ' +
'Status: ' + this.statusCode + ' -- ' +
'Headers: ' + this.headers + ' -- ' +
'Body: ' + this.body;
};
JWR.prototype.toPOJO = function() {
return {
body: this.body,
headers: this.headers,
statusCode: this.statusCode
};
};
JWR.prototype.pipe = function() {
// TODO: look at substack's stuff
return new Error('Not implemented yet.');
};
/**
* @api private
* @param {Socket} socket [description]
* @param {Object} requestCtx [description]
*/
function _emitFrom(socket, requestCtx) {
// Since callback is embedded in requestCtx,
// retrieve it and delete the key before continuing.
var cb = requestCtx.cb;
delete requestCtx.cb;
// Name of socket request listener on the server
// ( === the request method, e.g. 'get', 'post', 'put', etc. )
var sailsEndpoint = requestCtx.method;
socket.emit(sailsEndpoint, requestCtx, function serverResponded(responseCtx) {
// Adds backwards-compatibility for 0.9.x projects
// If `responseCtx.body` does not exist, the entire
// `responseCtx` object must actually be the `body`.
var body;
if (!responseCtx.body) {
body = responseCtx;
} else {
body = responseCtx.body;
}
// Send back (emulatedHTTPBody, jsonWebSocketResponse)
if (cb) {
cb(body, new JWR(responseCtx));
}
});
}
//////////////////////////////////////////////////////////////
///// </PRIVATE METHODS/CONSTRUCTORS> ////////////////////////
//////////////////////////////////////////////////////////////
// We'll be adding methods to `io.SocketNamespace.prototype`, the prototype for the
// Socket instance returned when the browser connects with `io.connect()`
var Socket = io.SocketNamespace;
/**
* Simulate a GET request to sails
* e.g.
* `socket.get('/user/3', Stats.populate)`
*
* @api public
* @param {String} url :: destination URL
* @param {Object} params :: parameters to send with the request [optional]
* @param {Function} cb :: callback function to call when finished [optional]
*/
Socket.prototype.get = function(url, data, cb) {
// `data` is optional
if (typeof data === 'function') {
cb = data;
data = {};
}
return this._request({
method: 'get',
data: data,
url: url
}, cb);
};
/**
* Simulate a POST request to sails
* e.g.
* `socket.post('/event', newMeeting, $spinner.hide)`
*
* @api public
* @param {String} url :: destination URL
* @param {Object} params :: parameters to send with the request [optional]
* @param {Function} cb :: callback function to call when finished [optional]
*/
Socket.prototype.post = function(url, data, cb) {
// `data` is optional
if (typeof data === 'function') {
cb = data;
data = {};
}
return this._request({
method: 'post',
data: data,
url: url
}, cb);
};
/**
* Simulate a PUT request to sails
* e.g.
* `socket.post('/event/3', changedFields, $spinner.hide)`
*
* @api public
* @param {String} url :: destination URL
* @param {Object} params :: parameters to send with the request [optional]
* @param {Function} cb :: callback function to call when finished [optional]
*/
Socket.prototype.put = function(url, data, cb) {
// `data` is optional
if (typeof data === 'function') {
cb = data;
data = {};
}
return this._request({
method: 'put',
data: data,
url: url
}, cb);
};
/**
* Simulate a DELETE request to sails
* e.g.
* `socket.delete('/event', $spinner.hide)`
*
* @api public
* @param {String} url :: destination URL
* @param {Object} params :: parameters to send with the request [optional]
* @param {Function} cb :: callback function to call when finished [optional]
*/
Socket.prototype['delete'] = function(url, data, cb) {
// `data` is optional
if (typeof data === 'function') {
cb = data;
data = {};
}
return this._request({
method: 'delete',
data: data,
url: url
}, cb);
};
/**
* Simulate an HTTP request to sails
* e.g.
* `socket.request('/user', newUser, $spinner.hide, 'post')`
*
* @api public
* @param {String} url :: destination URL
* @param {Object} params :: parameters to send with the request [optional]
* @param {Function} cb :: callback function to call when finished [optional]
* @param {String} method :: HTTP request method [optional]
*/
Socket.prototype.request = function(url, data, cb, method) {
// `cb` is optional
if (typeof cb === 'string') {
method = cb;
cb = null;
}
// `data` is optional
if (typeof data === 'function') {
cb = data;
data = {};
}
return this._request({
method: method || 'get',
data: data,
url: url
}, cb);
};
/**
* Socket.prototype._request
*
* Simulate HTTP over Socket.io.
*
* @api private
* @param {[type]} options [description]
* @param {Function} cb [description]
*/
Socket.prototype._request = function(options, cb) {
// Sanitize options (also data & headers)
var usage = 'Usage:\n socket.' +
(options.method || 'request') +
'( destinationURL, [dataToSend], [fnToCallWhenComplete] )';
options = options || {};
options.data = options.data || {};
options.headers = options.headers || {};
// Remove trailing slashes and spaces to make packets smaller.
options.url = options.url.replace(/^(.+)\/*\s*$/, '$1');
if (typeof options.url !== 'string') {
throw new Error('Invalid or missing URL!\n' + usage);
}
// Build a simulated request object.
var request = {
method: options.method,
data: options.data,
url: options.url,
headers: options.headers,
cb: cb
};
// If this socket is not connected yet, queue up this request
// instead of sending it.
// (so it can be replayed when the socket comes online.)
if (!_isConnected(this)) {
// If no queue array exists for this socket yet, create it.
this.requestQueue = this.requestQueue || [];
this.requestQueue.push(request);
return;
}
// Otherwise, our socket is ok!
// Send the request.
_emitFrom(this, request);
};
// Set a `sails` object that may be used for configuration before the
// first socket connects (i.e. to prevent auto-connect)
io.sails = {
// Whether to automatically connect a socket and save it as `io.socket`.
autoConnect: true,
// Whether to use JSONP to get a cookie for cross-origin requests
useCORSRouteToGetCookie: true,
prodUrl: "fapp.yamanickill.com:8080",
fallbackUrl: "fapp.yamanickill.com:80",
localUrl: "127.0.0.1:1337",
// The environment we're running in.
// (logs are not displayed when this is set to 'production')
//
// Defaults to development unless this script was fetched from a URL
// that ends in `*.min.js` or '#production' (may also be manually overridden.)
//
environment: urlThisScriptWasFetchedFrom.match(/(\#production|\.min\.js)/) ? 'production' : 'development'
};
/**
* Override `io.connect` to coerce it into using the io.sails
* connection URL config, as well as sending identifying information
* (most importantly, the current version of this SDK)
*
* @param {String} url [optional]
* @param {Object} opts [optional]
* @return {Socket}
*/
io.sails._origConnectFn = io.connect;
io.connect = function(url, opts) {
opts = opts || {};
// If explicit connection url is specified, use it
url = url || (window.location.hostname === 'localhost' ? io.sails.url : (io.sails.useFallback ? io.sails.fallbackUrl : io.sails.prodUrl)) || undefined;
// Ensure URL has no trailing slash
url = url ? url.replace(/(\/)$/, '') : undefined;
// Mix the current SDK version into the query string in
// the connection request to the server:
if (typeof opts.query !== 'string') opts.query = SDK_INFO.versionString;
else opts.query += '&' + SDK_INFO.versionString;
return io.sails._origConnectFn(url, opts);
};
// io.socket
//
// The eager instance of Socket which will automatically try to connect
// using the host that this js file was served from.
//
// This can be disabled or configured by setting `io.socket.options` within the
// first cycle of the event loop.
//
// In the mean time, this eager socket will be defined as a TmpSocket
// so that events bound by the user before the first cycle of the event
// loop (using `.on()`) can be rebound on the true socket.
io.socket = new TmpSocket();
setTimeout(function() {
// If autoConnect is disabled, delete the TmpSocket and bail out.
if (!io.sails.autoConnect) {
delete io.socket;
return io;
}
// If this is an attempt at a cross-origin or cross-port
// socket connection, send an AJAX request first to ensure
// that a valid cookie is available. This can be disabled
// by setting `io.sails.useCORSRouteToGetCookie` to false.
var isXOrigin = io.sails.url && true; //url.match();
// TODO: check whether the URL is cross-domain
// var port = global.location.port || ('https:' == global.location.protocol ? 443 : 80);
// this.options.host !== global.location.hostname || this.options.port != port;
if (io.sails.useCORSRouteToGetCookie && isXOrigin) {
// Figure out the x-origin CORS route
// (Sails provides a default)
var xOriginCookieRoute = '/__getcookie';
if (typeof io.sails.useCORSRouteToGetCookie === 'string') {
xOriginCookieRoute = io.sails.useCORSRouteToGetCookie;
}
var xOriginCookieURL = io.sails.url + xOriginCookieRoute;
// Make the AJAX request (CORS)
if (typeof window !== 'undefined') {
ajax({
url: xOriginCookieURL,
method: 'GET'
}, goAheadAndActuallyConnect);
}
// If there's no `window` object, we must be running in Node.js
// so just require the request module and send the HTTP request that
// way.
else {
var mikealsReq = require('request');
mikealsReq.get(io.sails.url + xOriginCookieRoute, function(err, httpResponse, body) {
if (err) {
consolog(
'Failed to connect socket (failed to get cookie)',
'Error:', err
);
return;
}
goAheadAndActuallyConnect();
});
}
} else goAheadAndActuallyConnect();
// Start connecting after the current cycle of the event loop
// has completed.
// consolog('Auto-connecting `io.socket` to Sails... (requests will be queued in the mean-time)');
function goAheadAndActuallyConnect() {
// Initiate connection
var actualSocket = io.connect(io.sails.url);
// Replay event bindings from the existing TmpSocket
io.socket = io.socket.become(actualSocket);
/**
* 'connect' event is triggered when the socket establishes a connection
* successfully.
*/
io.socket.on('connect', function socketConnected() {
consolog.noPrefix(
'\n' +
' |> ' + '\n' +
' \\___/ '
);
consolog(
'`io.socket` connected successfully.' + '\n' +
// 'e.g. to send a GET request to Sails via WebSockets, run:'+ '\n' +
// '`io.socket.get("/foo", function serverRespondedWith (body, jwr) { console.log(body); })`'+ '\n' +
' (for help, see: http://sailsjs.org/#!documentation/reference/BrowserSDK/BrowserSDK.html)'
);
// consolog('(this app is running in development mode - log messages will be displayed)');
if (!io.socket.$events.disconnect) {
io.socket.on('disconnect', function() {
consolog('====================================');
consolog('io.socket was disconnected from Sails.');
consolog('Usually, this is due to one of the following reasons:' + '\n' +
' -> the server ' + (io.sails.url ? io.sails.url + ' ' : '') + 'was taken down' + '\n' +
' -> your browser lost internet connectivity');
consolog('====================================');
});
}
if (!io.socket.$events.reconnect) {
io.socket.on('reconnect', function(transport, numAttempts) {
var numSecsOffline = io.socket.msSinceConnectionLost / 1000;
consolog(
'io.socket reconnected successfully after being offline ' +
'for ' + numSecsOffline + ' seconds.');
});
}
if (!io.socket.$events.reconnecting) {
io.socket.on('reconnecting', function(msSinceConnectionLost, numAttempts) {
io.socket.msSinceConnectionLost = msSinceConnectionLost;
consolog(
'io.socket is trying to reconnect to Sails...' +
'(attempt #' + numAttempts + ')');
});
}
// 'error' event is triggered if connection can not be established.
// (usually because of a failed authorization, which is in turn
// usually due to a missing or invalid cookie)
if (!io.socket.$events.error) {
io.socket.on('error', function failedToConnect(err) {
// TODO:
// handle failed connections due to failed authorization
// in a smarter way (probably can listen for a different event)
// A bug in Socket.io 0.9.x causes `connect_failed`
// and `reconnect_failed` not to fire.
// Check out the discussion in github issues for details:
// https://github.com/LearnBoost/socket.io/issues/652
// io.socket.on('connect_failed', function () {
// consolog('io.socket emitted `connect_failed`');
// });
// io.socket.on('reconnect_failed', function () {
// consolog('io.socket emitted `reconnect_failed`');
// });
consolog(
'Failed to connect socket (probably due to failed authorization on server)',
'Error:', err
);
});
}
});
}
// TODO:
// Listen for a special private message on any connected that allows the server
// to set the environment (giving us 100% certainty that we guessed right)
// However, note that the `console.log`s called before and after connection
// are still forced to rely on our existing heuristics (to disable, tack #production
// onto the URL used to fetch this file.)
}, 0); // </setTimeout>
// Return the `io` object.
return io;
}
// Add CommonJS support to allow this client SDK to be used from Node.js.
if (typeof module === 'object' && typeof module.exports !== 'undefined') {
module.exports = SailsIOClient;
return SailsIOClient;
}
// Otherwise, try to instantiate the client:
// In case you're wrapping the socket.io client to prevent pollution of the
// global namespace, you can replace the global `io` with your own `io` here:
return SailsIOClient();
})();
| I managed to remove the fallback from sails.io
| assets/js/dependencies/sails.io.js | I managed to remove the fallback from sails.io | <ide><path>ssets/js/dependencies/sails.io.js
<ide> });
<ide> }
<ide> });
<del>
<add> io.socket.on('connect_failed', function() {
<add> io.transports = ['xhr-polling'];
<add> io.sails.useFallback = true;
<add> goAheadAndActuallyConnect();
<add> });
<ide> }
<ide>
<ide> |
|
Java | isc | 8c98a65b6810d8b1f36212dbb012d7ce31374f75 | 0 | gwenn/sqlitejdbc,gwenn/sqlitejdbc | package test;
import java.sql.*;
import java.util.StringTokenizer;
import org.junit.*;
import static org.junit.Assert.*;
/** These tests are designed to stress PreparedStatements on memory dbs. */
public class PrepStmtTest
{
static byte[] b1 = new byte[] { 1,2,7,4,2,6,2,8,5,2,3,1,5,3,6,3,3,6,2,5 };
static byte[] b2 = "To be or not to be.".getBytes();
static byte[] b3 = "Question!#$%".getBytes();
static String utf01 = "\uD840\uDC40";
static String utf02 = "\uD840\uDC47 ";
static String utf03 = " \uD840\uDC43";
static String utf04 = " \uD840\uDC42 ";
static String utf05 = "\uD840\uDC40\uD840\uDC44";
static String utf06 = "Hello World, \uD840\uDC40 \uD880\uDC99";
static String utf07 = "\uD840\uDC41 testing \uD880\uDC99";
static String utf08 = "\uD840\uDC40\uD840\uDC44 testing";
private Connection conn;
private Statement stat;
@BeforeClass public static void forName() throws Exception {
Class.forName("org.sqlite.JDBC");
}
@Before public void connect() throws Exception {
conn = DriverManager.getConnection("jdbc:sqlite:");
stat = conn.createStatement();
}
@After public void close() throws SQLException {
stat.close();
conn.close();
}
@Test public void update() throws SQLException {
assertEquals(conn.prepareStatement(
"create table s1 (c1);").executeUpdate(), 0);
PreparedStatement prep = conn.prepareStatement(
"insert into s1 values (?);");
prep.setInt(1, 3); assertEquals(prep.executeUpdate(), 1);
prep.setInt(1, 5); assertEquals(prep.executeUpdate(), 1);
prep.setInt(1, 7); assertEquals(prep.executeUpdate(), 1);
prep.close();
// check results with normal statement
ResultSet rs = stat.executeQuery("select sum(c1) from s1;");
assertTrue(rs.next());
assertEquals(rs.getInt(1), 15);
rs.close();
}
@Test public void multiUpdate() throws SQLException {
stat.executeUpdate("create table test (c1);");
PreparedStatement prep = conn.prepareStatement(
"insert into test values (?);");
for (int i=0; i < 10; i++) {
prep.setInt(1, i);
prep.executeUpdate();
prep.execute();
}
prep.close();
stat.executeUpdate("drop table test;");
}
@Test public void emptyRS() throws SQLException {
PreparedStatement prep = conn.prepareStatement("select null limit 0;");
ResultSet rs = prep.executeQuery();
assertFalse(rs.next());
rs.close();
prep.close();
}
@Test public void singleRowRS() throws SQLException {
PreparedStatement prep = conn.prepareStatement("select ?;");
prep.setInt(1, Integer.MAX_VALUE);
ResultSet rs = prep.executeQuery();
assertTrue(rs.next());
assertEquals(rs.getInt(1), Integer.MAX_VALUE);
assertEquals(rs.getString(1), Integer.toString(Integer.MAX_VALUE));
assertEquals(rs.getDouble(1),
new Integer(Integer.MAX_VALUE).doubleValue());
assertFalse(rs.next());
rs.close();
prep.close();
}
@Test public void twoRowRS() throws SQLException {
PreparedStatement prep = conn.prepareStatement(
"select ? union all select ?;");
prep.setDouble(1, Double.MAX_VALUE);
prep.setDouble(2, Double.MIN_VALUE);
ResultSet rs = prep.executeQuery();
assertTrue(rs.next());
assertEquals(rs.getDouble(1), Double.MAX_VALUE);
assertTrue(rs.next());
assertEquals(rs.getDouble(1), Double.MIN_VALUE);
assertFalse(rs.next());
rs.close();
}
@Test public void stringRS() throws SQLException {
String name = "Gandhi";
PreparedStatement prep = conn.prepareStatement("select ?;");
prep.setString(1, name);
ResultSet rs = prep.executeQuery();
assertTrue(rs.next());
assertEquals(rs.getString(1), name);
assertFalse(rs.next());
rs.close();
}
@Test public void finalizePrep() throws SQLException {
conn.prepareStatement("select null;");
System.gc();
}
@Test public void set() throws SQLException {
ResultSet rs;
PreparedStatement prep = conn.prepareStatement("select ?, ?, ?;");
// integers
prep.setInt(1, Integer.MIN_VALUE);
prep.setInt(2, Integer.MAX_VALUE);
prep.setInt(3, 0);
rs = prep.executeQuery();
assertTrue(rs.next());
assertEquals(rs.getInt(1), Integer.MIN_VALUE);
assertEquals(rs.getInt(2), Integer.MAX_VALUE);
assertEquals(rs.getInt(3), 0);
// strings
String name = "Winston Leonard Churchill";
String fn = name.substring(0, 7),
mn = name.substring(8, 15),
sn = name.substring(16, 25);
prep.clearParameters();
prep.setString(1, fn);
prep.setString(2, mn);
prep.setString(3, sn);
prep.executeQuery();
assertTrue(rs.next());
assertEquals(rs.getString(1), fn);
assertEquals(rs.getString(2), mn);
assertEquals(rs.getString(3), sn);
// mixed
prep.setString(1, name);
prep.setString(2, null);
prep.setLong(3, Long.MAX_VALUE);
prep.executeQuery();
assertTrue(rs.next());
assertEquals(rs.getString(1), name);
assertNull(rs.getString(2));
assertTrue(rs.wasNull());
assertEquals(rs.getLong(3), Long.MAX_VALUE);
// bytes
prep.setBytes(1, b1);
prep.setBytes(2, b2);
prep.setBytes(3, b3);
prep.executeQuery();
assertTrue(rs.next());
assertArrayEq(rs.getBytes(1), b1);
assertArrayEq(rs.getBytes(2), b2);
assertArrayEq(rs.getBytes(3), b3);
assertFalse(rs.next());
rs.close();
}
@Test public void colNameAccess() throws SQLException {
PreparedStatement prep = conn.prepareStatement(
"select ? as col1, ? as col2, ? as bingo;");
prep.setNull(1, 0);
prep.setFloat(2, Float.MIN_VALUE);
prep.setShort(3, Short.MIN_VALUE);
prep.executeQuery();
ResultSet rs = prep.executeQuery();
assertTrue(rs.next());
assertNull(rs.getString("col1"));
assertTrue(rs.wasNull());
assertEquals(rs.getFloat("col2"), Float.MIN_VALUE);
assertEquals(rs.getShort("bingo"), Short.MIN_VALUE);
rs.close();
prep.close();
}
@Test public void insert1000() throws SQLException {
stat.executeUpdate("create table in1000 (a);");
PreparedStatement prep = conn.prepareStatement(
"insert into in1000 values (?);");
conn.setAutoCommit(false);
for (int i=0; i < 1000; i++) {
prep.setInt(1, i);
prep.executeUpdate();
}
conn.commit();
ResultSet rs = stat.executeQuery("select count(a) from in1000;");
assertTrue(rs.next());
assertEquals(rs.getInt(1), 1000);
rs.close();
}
@Ignore
@Test public void getObject() throws SQLException {
stat.executeUpdate("create table testobj ("
+ "c1 integer, c2 float, c3, c4 varchar, c5 bit, c6, c7);");
PreparedStatement prep = conn.prepareStatement(
"insert into testobj values (?,?,?,?,?,?,?);");
prep.setInt (1, Integer.MAX_VALUE);
prep.setFloat (2, Float.MAX_VALUE);
prep.setDouble (3, Double.MAX_VALUE);
prep.setLong (4, Long.MAX_VALUE);
prep.setBoolean(5, false);
prep.setByte (6, (byte)7);
prep.setBytes (7, b1);
prep.executeUpdate();
ResultSet rs = stat.executeQuery(
"select c1,c2,c3,c4,c5,c6,c7 from testobj;");
assertTrue(rs.next());
assertEquals(rs.getInt(1), Integer.MAX_VALUE);
assertEquals(rs.getFloat(2), Float.MAX_VALUE);
assertEquals(rs.getDouble(3), Double.MAX_VALUE);
assertEquals(rs.getLong(4), Long.MAX_VALUE);
assertFalse(rs.getBoolean(5));
assertEquals(rs.getByte(6), (byte)7);
assertArrayEq(rs.getBytes(7), b1);
assertNotNull(rs.getObject(1));
assertNotNull(rs.getObject(2));
assertNotNull(rs.getObject(3));
assertNotNull(rs.getObject(4));
assertNotNull(rs.getObject(5));
assertNotNull(rs.getObject(6));
assertNotNull(rs.getObject(7));
assertTrue(rs.getObject(1) instanceof Integer);
assertTrue(rs.getObject(2) instanceof Double);
assertTrue(rs.getObject(3) instanceof Double);
assertTrue(rs.getObject(4) instanceof String);
assertTrue(rs.getObject(5) instanceof Integer);
assertTrue(rs.getObject(6) instanceof Integer);
assertTrue(rs.getObject(7) instanceof byte[]);
rs.close();
}
@Test public void tokens() throws SQLException {
/* checks for a bug where a substring is read by the driver as the
* full original string, caused by my idiocyin assuming the
* pascal-style string was null terminated. Thanks Oliver Randschau. */
StringTokenizer st = new StringTokenizer("one two three");
st.nextToken();
String substr = st.nextToken();
PreparedStatement prep = conn.prepareStatement("select ?;");
prep.setString(1, substr);
ResultSet rs = prep.executeQuery();
assertTrue(rs.next());
assertEquals(rs.getString(1), substr);
}
@Test public void utf() throws SQLException {
ResultSet rs = stat.executeQuery("select '"
+utf01+"','"+utf02+"','"+utf03+"','"+utf04+"','"
+utf05+"','"+utf06+"','"+utf07+"','"+utf08+"';");
assertEquals(rs.getString(1), utf01);
assertEquals(rs.getString(2), utf02);
assertEquals(rs.getString(3), utf03);
assertEquals(rs.getString(4), utf04);
assertEquals(rs.getString(5), utf05);
assertEquals(rs.getString(6), utf06);
assertEquals(rs.getString(7), utf07);
assertEquals(rs.getString(8), utf08);
rs.close();
PreparedStatement prep = conn.prepareStatement(
"select ?,?,?,?,?,?,?,?;");
prep.setString(1, utf01); prep.setString(2, utf02);
prep.setString(3, utf03); prep.setString(4, utf04);
prep.setString(5, utf05); prep.setString(6, utf06);
prep.setString(7, utf07); prep.setString(8, utf08);
rs = prep.executeQuery();
assertTrue(rs.next());
assertEquals(rs.getString(1), utf01);
assertEquals(rs.getString(2), utf02);
assertEquals(rs.getString(3), utf03);
assertEquals(rs.getString(4), utf04);
assertEquals(rs.getString(5), utf05);
assertEquals(rs.getString(6), utf06);
assertEquals(rs.getString(7), utf07);
assertEquals(rs.getString(8), utf08);
rs.close();
}
@Test public void batch() throws SQLException {
ResultSet rs;
stat.executeUpdate("create table test (c1, c2, c3, c4);");
PreparedStatement prep = conn.prepareStatement(
"insert into test values (?,?,?,?);");
for (int i=0; i < 10; i++) {
prep.setInt(1, Integer.MIN_VALUE + i);
prep.setFloat(2, Float.MIN_VALUE + i);
prep.setString(3, "Hello " + i);
prep.setDouble(4, Double.MAX_VALUE + i);
prep.addBatch();
}
assertArrayEq(prep.executeBatch(), new int[] { 1,1,1,1,1,1,1,1,1,1 });
prep.close();
rs = stat.executeQuery("select * from test;");
for (int i=0; i < 10; i++) {
assertTrue(rs.next());
assertEquals(rs.getInt(1), Integer.MIN_VALUE + i);
assertEquals(rs.getFloat(2), Float.MIN_VALUE + i);
assertEquals(rs.getString(3), "Hello " + i);
assertEquals(rs.getDouble(4), Double.MAX_VALUE + i);
}
rs.close();
stat.executeUpdate("drop table test;");
}
@Test public void dblock() throws SQLException {
stat.executeUpdate("create table test (c1);");
stat.executeUpdate("insert into test values (1);");
conn.prepareStatement("select * from test;").executeQuery().close();
stat.executeUpdate("drop table test;");
}
@Test public void dbclose() throws SQLException {
conn.prepareStatement("select ?;").setString(1, "Hello World");
conn.prepareStatement("select null;").close();
conn.prepareStatement("select null;").executeQuery();
conn.prepareStatement("create table t (c);").executeUpdate();
conn.prepareStatement("select null;");
}
@Test public void batchOneParam() throws SQLException {
stat.executeUpdate("create table test (c1);");
PreparedStatement prep = conn.prepareStatement(
"insert into test values (?);");
for (int i=0; i < 10; i++) {
prep.setInt(1, Integer.MIN_VALUE + i);
prep.addBatch();
}
assertArrayEq(prep.executeBatch(), new int[] { 1,1,1,1,1,1,1,1,1,1 });
prep.close();
ResultSet rs = stat.executeQuery("select count(*) from test;");
assertTrue(rs.next());
assertEquals(rs.getInt(1), 10);
rs.close();
}
@Test public void paramMetaData() throws SQLException {
PreparedStatement prep = conn.prepareStatement("select ?,?,?,?;");
assertEquals(prep.getParameterMetaData().getParameterCount(), 4);
}
@Test public void metaData() throws SQLException {
PreparedStatement prep = conn.prepareStatement(
"select ? as col1, ? as col2, ? as delta;");
ResultSetMetaData meta = prep.getMetaData();
assertEquals(meta.getColumnCount(), 3);
assertEquals(meta.getColumnName(1), "col1");
assertEquals(meta.getColumnName(2), "col2");
assertEquals(meta.getColumnName(3), "delta");
/*assertEquals(meta.getColumnType(1), Types.INTEGER);
assertEquals(meta.getColumnType(2), Types.INTEGER);
assertEquals(meta.getColumnType(3), Types.INTEGER);*/
meta = prep.executeQuery().getMetaData();
assertEquals(meta.getColumnCount(), 3);
prep.close();
}
@Test public void date1() throws SQLException {
Date d1 = new Date(987654321);
stat.execute("create table t (c1);");
PreparedStatement prep = conn.prepareStatement(
"insert into t values(?);");
prep.setDate(1, d1);
prep.executeUpdate();
ResultSet rs = stat.executeQuery("select c1 from t;");
assertTrue(rs.next());
assertEquals(rs.getLong(1), d1.getTime());
assertTrue(rs.getDate(1).equals(d1));
rs.close();
}
@Test public void date2() throws SQLException {
Date d1 = new Date(987654321);
stat.execute("create table t (c1);");
PreparedStatement prep = conn.prepareStatement(
"insert into t values (datetime(?, 'unixepoch'));");
prep.setDate(1, d1);
prep.executeUpdate();
ResultSet rs = stat.executeQuery("select strftime('%s', c1) from t;");
assertTrue(rs.next());
assertEquals(rs.getLong(1), d1.getTime());
assertTrue(rs.getDate(1).equals(d1));
}
@Test(expected= SQLException.class)
public void noSuchTable() throws SQLException {
PreparedStatement prep =
conn.prepareStatement("select * from doesnotexist;");
prep.executeQuery();
}
@Test(expected= SQLException.class)
public void noSuchCol() throws SQLException {
PreparedStatement prep =
conn.prepareStatement("select notacol from (select 1);");
prep.executeQuery();
}
@Test(expected= SQLException.class)
public void noSuchColName() throws SQLException {
ResultSet rs = conn.prepareStatement("select 1;").executeQuery();
assertTrue(rs.next());
rs.getInt("noSuchColName");
}
private void assertArrayEq(byte[] a, byte[] b) {
assertNotNull(a);
assertNotNull(b);
assertEquals(a.length, b.length);
for (int i=0; i < a.length; i++)
assertEquals(a[i], b[i]);
}
private void assertArrayEq(int[] a, int[] b) {
assertNotNull(a);
assertNotNull(b);
assertEquals(a.length, b.length);
for (int i=0; i < a.length; i++)
assertEquals(a[i], b[i]);
}
}
| src/test/PrepStmtTest.java | package test;
import java.sql.*;
import java.util.StringTokenizer;
import org.junit.*;
import static org.junit.Assert.*;
/** These tests are designed to stress PreparedStatements on memory dbs. */
public class PrepStmtTest
{
static byte[] b1 = new byte[] { 1,2,7,4,2,6,2,8,5,2,3,1,5,3,6,3,3,6,2,5 };
static byte[] b2 = "To be or not to be.".getBytes();
static byte[] b3 = "Question!#$%".getBytes();
static String utf01 = "\uD840\uDC40";
static String utf02 = "\uD840\uDC47 ";
static String utf03 = " \uD840\uDC43";
static String utf04 = " \uD840\uDC42 ";
static String utf05 = "\uD840\uDC40\uD840\uDC44";
static String utf06 = "Hello World, \uD840\uDC40 \uD880\uDC99";
static String utf07 = "\uD840\uDC41 testing \uD880\uDC99";
static String utf08 = "\uD840\uDC40\uD840\uDC44 testing";
private Connection conn;
private Statement stat;
@BeforeClass public static void forName() throws Exception {
Class.forName("org.sqlite.JDBC");
}
@Before public void connect() throws Exception {
conn = DriverManager.getConnection("jdbc:sqlite:");
stat = conn.createStatement();
}
@After public void close() throws SQLException {
stat.close();
conn.close();
}
@Test public void update() throws SQLException {
assertEquals(conn.prepareStatement(
"create table s1 (c1);").executeUpdate(), 0);
PreparedStatement prep = conn.prepareStatement(
"insert into s1 values (?);");
prep.setInt(1, 3); assertEquals(prep.executeUpdate(), 1);
prep.setInt(1, 5); assertEquals(prep.executeUpdate(), 1);
prep.setInt(1, 7); assertEquals(prep.executeUpdate(), 1);
prep.close();
// check results with normal statement
ResultSet rs = stat.executeQuery("select sum(c1) from s1;");
assertTrue(rs.next());
assertEquals(rs.getInt(1), 15);
rs.close();
}
@Test public void multiUpdate() throws SQLException {
stat.executeUpdate("create table test (c1);");
PreparedStatement prep = conn.prepareStatement(
"insert into test values (?);");
for (int i=0; i < 10; i++) {
prep.setInt(1, i);
prep.executeUpdate();
prep.execute();
}
prep.close();
stat.executeUpdate("drop table test;");
}
@Test public void emptyRS() throws SQLException {
PreparedStatement prep = conn.prepareStatement("select null limit 0;");
ResultSet rs = prep.executeQuery();
assertFalse(rs.next());
rs.close();
prep.close();
}
@Test public void singleRowRS() throws SQLException {
PreparedStatement prep = conn.prepareStatement("select ?;");
prep.setInt(1, Integer.MAX_VALUE);
ResultSet rs = prep.executeQuery();
assertTrue(rs.next());
assertEquals(rs.getInt(1), Integer.MAX_VALUE);
assertEquals(rs.getString(1), Integer.toString(Integer.MAX_VALUE));
assertEquals(rs.getDouble(1),
new Integer(Integer.MAX_VALUE).doubleValue());
assertFalse(rs.next());
rs.close();
prep.close();
}
@Test public void twoRowRS() throws SQLException {
PreparedStatement prep = conn.prepareStatement(
"select ? union all select ?;");
prep.setDouble(1, Double.MAX_VALUE);
prep.setDouble(2, Double.MIN_VALUE);
ResultSet rs = prep.executeQuery();
assertTrue(rs.next());
assertEquals(rs.getDouble(1), Double.MAX_VALUE);
assertTrue(rs.next());
assertEquals(rs.getDouble(1), Double.MIN_VALUE);
assertFalse(rs.next());
rs.close();
}
@Test public void stringRS() throws SQLException {
String name = "Gandhi";
PreparedStatement prep = conn.prepareStatement("select ?;");
prep.setString(1, name);
ResultSet rs = prep.executeQuery();
assertTrue(rs.next());
assertEquals(rs.getString(1), name);
assertFalse(rs.next());
rs.close();
}
@Test public void finalizePrep() throws SQLException {
conn.prepareStatement("select null;");
System.gc();
}
@Test public void set() throws SQLException {
ResultSet rs;
PreparedStatement prep = conn.prepareStatement("select ?, ?, ?;");
// integers
prep.setInt(1, Integer.MIN_VALUE);
prep.setInt(2, Integer.MAX_VALUE);
prep.setInt(3, 0);
rs = prep.executeQuery();
assertTrue(rs.next());
assertEquals(rs.getInt(1), Integer.MIN_VALUE);
assertEquals(rs.getInt(2), Integer.MAX_VALUE);
assertEquals(rs.getInt(3), 0);
// strings
String name = "Winston Leonard Churchill";
String fn = name.substring(0, 7),
mn = name.substring(8, 15),
sn = name.substring(16, 25);
prep.clearParameters();
prep.setString(1, fn);
prep.setString(2, mn);
prep.setString(3, sn);
prep.executeQuery();
assertTrue(rs.next());
assertEquals(rs.getString(1), fn);
assertEquals(rs.getString(2), mn);
assertEquals(rs.getString(3), sn);
// mixed
prep.setString(1, name);
prep.setString(2, null);
prep.setLong(3, Long.MAX_VALUE);
prep.executeQuery();
assertTrue(rs.next());
assertEquals(rs.getString(1), name);
assertNull(rs.getString(2));
assertTrue(rs.wasNull());
assertEquals(rs.getLong(3), Long.MAX_VALUE);
// bytes
prep.setBytes(1, b1);
prep.setBytes(2, b2);
prep.setBytes(3, b3);
prep.executeQuery();
assertTrue(rs.next());
assertArrayEq(rs.getBytes(1), b1);
assertArrayEq(rs.getBytes(2), b2);
assertArrayEq(rs.getBytes(3), b3);
assertFalse(rs.next());
rs.close();
}
@Test public void colNameAccess() throws SQLException {
PreparedStatement prep = conn.prepareStatement(
"select ? as col1, ? as col2, ? as bingo;");
prep.setNull(1, 0);
prep.setFloat(2, Float.MIN_VALUE);
prep.setShort(3, Short.MIN_VALUE);
prep.executeQuery();
ResultSet rs = prep.executeQuery();
assertTrue(rs.next());
assertNull(rs.getString("col1"));
assertTrue(rs.wasNull());
assertEquals(rs.getFloat("col2"), Float.MIN_VALUE);
assertEquals(rs.getShort("bingo"), Short.MIN_VALUE);
rs.close();
prep.close();
}
@Test public void insert1000() throws SQLException {
stat.executeUpdate("create table in1000 (a);");
PreparedStatement prep = conn.prepareStatement(
"insert into in1000 values (?);");
conn.setAutoCommit(false);
for (int i=0; i < 1000; i++) {
prep.setInt(1, i);
prep.executeUpdate();
}
conn.commit();
ResultSet rs = stat.executeQuery("select count(a) from in1000;");
assertTrue(rs.next());
assertEquals(rs.getInt(1), 1000);
rs.close();
}
@Ignore
@Test public void getObject() throws SQLException {
stat.executeUpdate("create table testobj ("
+ "c1 integer, c2 float, c3, c4 varchar, c5 bit, c6, c7);");
PreparedStatement prep = conn.prepareStatement(
"insert into testobj values (?,?,?,?,?,?,?);");
prep.setInt (1, Integer.MAX_VALUE);
prep.setFloat (2, Float.MAX_VALUE);
prep.setDouble (3, Double.MAX_VALUE);
prep.setLong (4, Long.MAX_VALUE);
prep.setBoolean(5, false);
prep.setByte (6, (byte)7);
prep.setBytes (7, b1);
prep.executeUpdate();
ResultSet rs = stat.executeQuery(
"select c1,c2,c3,c4,c5,c6,c7 from testobj;");
assertTrue(rs.next());
assertEquals(rs.getInt(1), Integer.MAX_VALUE);
assertEquals(rs.getFloat(2), Float.MAX_VALUE);
assertEquals(rs.getDouble(3), Double.MAX_VALUE);
assertEquals(rs.getLong(4), Long.MAX_VALUE);
assertFalse(rs.getBoolean(5));
assertEquals(rs.getByte(6), (byte)7);
assertArrayEq(rs.getBytes(7), b1);
assertNotNull(rs.getObject(1));
assertNotNull(rs.getObject(2));
assertNotNull(rs.getObject(3));
assertNotNull(rs.getObject(4));
assertNotNull(rs.getObject(5));
assertNotNull(rs.getObject(6));
assertNotNull(rs.getObject(7));
assertTrue(rs.getObject(1) instanceof Integer);
assertTrue(rs.getObject(2) instanceof Double);
assertTrue(rs.getObject(3) instanceof Double);
assertTrue(rs.getObject(4) instanceof String);
assertTrue(rs.getObject(5) instanceof Integer);
assertTrue(rs.getObject(6) instanceof Integer);
assertTrue(rs.getObject(7) instanceof byte[]);
rs.close();
}
@Test public void tokens() throws SQLException {
/* checks for a bug where a substring is read by the driver as the
* full original string, caused by my idiocyin assuming the
* pascal-style string was null terminated. Thanks Oliver Randschau. */
StringTokenizer st = new StringTokenizer("one two three");
st.nextToken();
String substr = st.nextToken();
PreparedStatement prep = conn.prepareStatement("select ?;");
prep.setString(1, substr);
ResultSet rs = prep.executeQuery();
assertTrue(rs.next());
assertEquals(rs.getString(1), substr);
}
@Test public void utf() throws SQLException {
ResultSet rs = stat.executeQuery("select '"
+utf01+"','"+utf02+"','"+utf03+"','"+utf04+"','"
+utf05+"','"+utf06+"','"+utf07+"','"+utf08+"';");
assertEquals(rs.getString(1), utf01);
assertEquals(rs.getString(2), utf02);
assertEquals(rs.getString(3), utf03);
assertEquals(rs.getString(4), utf04);
assertEquals(rs.getString(5), utf05);
assertEquals(rs.getString(6), utf06);
assertEquals(rs.getString(7), utf07);
assertEquals(rs.getString(8), utf08);
rs.close();
PreparedStatement prep = conn.prepareStatement(
"select ?,?,?,?,?,?,?,?;");
prep.setString(1, utf01); prep.setString(2, utf02);
prep.setString(3, utf03); prep.setString(4, utf04);
prep.setString(5, utf05); prep.setString(6, utf06);
prep.setString(7, utf07); prep.setString(8, utf08);
rs = prep.executeQuery();
assertTrue(rs.next());
assertEquals(rs.getString(1), utf01);
assertEquals(rs.getString(2), utf02);
assertEquals(rs.getString(3), utf03);
assertEquals(rs.getString(4), utf04);
assertEquals(rs.getString(5), utf05);
assertEquals(rs.getString(6), utf06);
assertEquals(rs.getString(7), utf07);
assertEquals(rs.getString(8), utf08);
rs.close();
}
@Test public void batch() throws SQLException {
ResultSet rs;
stat.executeUpdate("create table test (c1, c2, c3, c4);");
PreparedStatement prep = conn.prepareStatement(
"insert into test values (?,?,?,?);");
for (int i=0; i < 10; i++) {
prep.setInt(1, Integer.MIN_VALUE + i);
prep.setFloat(2, Float.MIN_VALUE + i);
prep.setString(3, "Hello " + i);
prep.setDouble(4, Double.MAX_VALUE + i);
prep.addBatch();
}
assertArrayEq(prep.executeBatch(), new int[] { 1,1,1,1,1,1,1,1,1,1 });
prep.close();
rs = stat.executeQuery("select * from test;");
for (int i=0; i < 10; i++) {
assertTrue(rs.next());
assertEquals(rs.getInt(1), Integer.MIN_VALUE + i);
assertEquals(rs.getFloat(2), Float.MIN_VALUE + i);
assertEquals(rs.getString(3), "Hello " + i);
assertEquals(rs.getDouble(4), Double.MAX_VALUE + i);
}
rs.close();
stat.executeUpdate("drop table test;");
}
@Test public void dblock() throws SQLException {
stat.executeUpdate("create table test (c1);");
stat.executeUpdate("insert into test values (1);");
conn.prepareStatement("select * from test;").executeQuery().close();
stat.executeUpdate("drop table test;");
}
@Test public void dbclose() throws SQLException {
conn.prepareStatement("select ?;").setString(1, "Hello World");
conn.prepareStatement("select null;").close();
conn.prepareStatement("select null;").executeQuery();
conn.prepareStatement("create table t (c);").executeUpdate();
conn.prepareStatement("select null;");
}
@Test public void batchOneParam() throws SQLException {
stat.executeUpdate("create table test (c1);");
PreparedStatement prep = conn.prepareStatement(
"insert into test values (?);");
for (int i=0; i < 10; i++) {
prep.setInt(1, Integer.MIN_VALUE + i);
prep.addBatch();
}
assertArrayEq(prep.executeBatch(), new int[] { 1,1,1,1,1,1,1,1,1,1 });
prep.close();
ResultSet rs = stat.executeQuery("select count(*) from test;");
assertTrue(rs.next());
assertEquals(rs.getInt(1), 10);
rs.close();
}
@Test public void paramMetaData() throws SQLException {
PreparedStatement prep = conn.prepareStatement("select ?,?,?,?;");
assertEquals(prep.getParameterMetaData().getParameterCount(), 4);
}
@Test public void metaData() throws SQLException {
PreparedStatement prep = conn.prepareStatement(
"select ? as col1, ? as col2, ? as delta;");
ResultSetMetaData meta = prep.getMetaData();
assertEquals(meta.getColumnCount(), 3);
assertEquals(meta.getColumnName(1), "col1");
assertEquals(meta.getColumnName(2), "col2");
assertEquals(meta.getColumnName(3), "delta");
assertEquals(meta.getColumnType(1), Types.INTEGER);
assertEquals(meta.getColumnType(2), Types.INTEGER);
assertEquals(meta.getColumnType(3), Types.INTEGER);
meta = prep.executeQuery().getMetaData();
assertEquals(meta.getColumnCount(), 3);
prep.close();
}
@Test public void date1() throws SQLException {
Date d1 = new Date(987654321);
stat.execute("create table t (c1);");
PreparedStatement prep = conn.prepareStatement(
"insert into t values(?);");
prep.setDate(1, d1);
prep.executeUpdate();
ResultSet rs = stat.executeQuery("select c1 from t;");
assertTrue(rs.next());
assertEquals(rs.getLong(1), d1.getTime());
assertTrue(rs.getDate(1).equals(d1));
rs.close();
}
@Test public void date2() throws SQLException {
Date d1 = new Date(987654321);
stat.execute("create table t (c1);");
PreparedStatement prep = conn.prepareStatement(
"insert into t values (datetime(?, 'unixepoch'));");
prep.setDate(1, d1);
prep.executeUpdate();
ResultSet rs = stat.executeQuery("select strftime('%s', c1) from t;");
assertTrue(rs.next());
assertEquals(rs.getLong(1), d1.getTime());
assertTrue(rs.getDate(1).equals(d1));
}
@Test(expected= SQLException.class)
public void noSuchTable() throws SQLException {
PreparedStatement prep =
conn.prepareStatement("select * from doesnotexist;");
prep.executeQuery();
}
@Test(expected= SQLException.class)
public void noSuchCol() throws SQLException {
PreparedStatement prep =
conn.prepareStatement("select notacol from (select 1);");
prep.executeQuery();
}
@Test(expected= SQLException.class)
public void noSuchColName() throws SQLException {
ResultSet rs = conn.prepareStatement("select 1;").executeQuery();
assertTrue(rs.next());
rs.getInt("noSuchColName");
}
private void assertArrayEq(byte[] a, byte[] b) {
assertNotNull(a);
assertNotNull(b);
assertEquals(a.length, b.length);
for (int i=0; i < a.length; i++)
assertEquals(a[i], b[i]);
}
private void assertArrayEq(int[] a, int[] b) {
assertNotNull(a);
assertNotNull(b);
assertEquals(a.length, b.length);
for (int i=0; i < a.length; i++)
assertEquals(a[i], b[i]);
}
}
| temporarily disable a test check that didn't make sense and has been caught by 3.4.0
darcs-hash:20070619043629-0c629-fcf0d6bdf5e11672400d0b1ec0728d9d1cebb38c.gz
| src/test/PrepStmtTest.java | temporarily disable a test check that didn't make sense and has been caught by 3.4.0 | <ide><path>rc/test/PrepStmtTest.java
<ide> assertEquals(meta.getColumnName(1), "col1");
<ide> assertEquals(meta.getColumnName(2), "col2");
<ide> assertEquals(meta.getColumnName(3), "delta");
<del> assertEquals(meta.getColumnType(1), Types.INTEGER);
<add> /*assertEquals(meta.getColumnType(1), Types.INTEGER);
<ide> assertEquals(meta.getColumnType(2), Types.INTEGER);
<del> assertEquals(meta.getColumnType(3), Types.INTEGER);
<add> assertEquals(meta.getColumnType(3), Types.INTEGER);*/
<ide>
<ide> meta = prep.executeQuery().getMetaData();
<ide> assertEquals(meta.getColumnCount(), 3); |
|
Java | epl-1.0 | 3ac92e3b4a4db3c468485ca2b2cdb44900ae001c | 0 | R-Brain/codenvy,R-Brain/codenvy,codenvy/codenvy,R-Brain/codenvy,codenvy/codenvy,codenvy/codenvy,codenvy/codenvy,codenvy/codenvy,R-Brain/codenvy,R-Brain/codenvy,R-Brain/codenvy,codenvy/codenvy | /*
* CODENVY CONFIDENTIAL
* __________________
*
* [2012] - [2015] Codenvy, S.A.
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Codenvy S.A. and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Codenvy S.A.
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Codenvy S.A..
*/
package com.codenvy.im.node;
import com.codenvy.im.agent.AgentException;
import com.codenvy.im.artifacts.CDECArtifact;
import com.codenvy.im.command.CheckInstalledVersionCommand;
import com.codenvy.im.command.Command;
import com.codenvy.im.command.CommandException;
import com.codenvy.im.command.CommandFactory;
import com.codenvy.im.command.MacroCommand;
import com.codenvy.im.config.Config;
import com.codenvy.im.config.ConfigUtil;
import com.codenvy.im.install.InstallOptions;
import com.codenvy.im.utils.Version;
import com.google.common.collect.ImmutableList;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.codenvy.im.command.CommandFactory.createLocalAgentBackupCommand;
import static com.codenvy.im.command.CommandFactory.createLocalAgentPropertyReplaceCommand;
import static com.codenvy.im.command.CommandFactory.createShellAgentBackupCommand;
import static com.codenvy.im.command.CommandFactory.createShellAgentCommand;
import static com.codenvy.im.command.SimpleCommand.createLocalAgentCommand;
import static com.codenvy.im.service.InstallationManagerConfig.readPuppetMasterNodeDns;
import static java.lang.String.format;
/** @author Dmytro Nochevnov */
@Singleton
public class NodeManager {
private ConfigUtil configUtil;
private CDECArtifact cdecArtifact;
@Inject
public NodeManager(ConfigUtil configUtil, CDECArtifact cdecArtifact) throws IOException {
this.configUtil = configUtil;
this.cdecArtifact = cdecArtifact;
}
/**
* @throws IllegalArgumentException if node type isn't supported, or if there is adding node in the list of additional nodes
*/
public String add(NodeConfig node) throws IOException, IllegalArgumentException {
Config config = getCodenvyConfig(configUtil);
AdditionalNodesConfigUtil nodesConfigUtil = getNodesConfigUtil(config);
// check if Codenvy is alive
Version currentCodenvyVersion = cdecArtifact.getInstalledVersion();
String property = nodesConfigUtil.getPropertyNameBy(node.getType());
if (property == null) {
throw new IllegalArgumentException("This type of node isn't supported");
}
validate(node);
Command addNodeCommand = getAddNodeCommand(currentCodenvyVersion, property, nodesConfigUtil, node, config);
return addNodeCommand.execute();
}
/**
* @return commands to add node into puppet master config and wait until node becomes alive
*/
protected Command getAddNodeCommand(Version currentCodenvyVersion, String property, AdditionalNodesConfigUtil nodesConfigUtil, NodeConfig node, Config config) throws NodeException {
List<Command> commands = new ArrayList<>();
String value = nodesConfigUtil.getValueWithNode(node);
NodeConfig apiNode = NodeConfig.extractConfigFrom(config, NodeConfig.NodeType.API);
try {
// modify puppet master config
String puppetMasterConfigFilePath = "/etc/puppet/" + Config.MULTI_SERVER_PROPERTIES;
commands.add(createLocalAgentBackupCommand(puppetMasterConfigFilePath));
commands.add(createLocalAgentPropertyReplaceCommand(puppetMasterConfigFilePath,
"$" + property,
value));
// // force to apply master config through puppet agent on API server // TODO [ndp] take into account possible concurrent applying of config and lock of puppet agent on API server
// commands.add(createShellAgentCommand("sudo puppet agent -t",
// apiNode));
// check if there is a puppet agent started on adding node
if (!isPuppetAgentActive(node)) {
String puppetMasterNodeDns = readPuppetMasterNodeDns();
// install puppet agents on adding node
commands.add(createShellAgentCommand("if [ \"`yum list installed | grep puppetlabs-release.noarch`\" == \"\" ]; "
+ format("then sudo yum install %s -y", config.getValue(Config.PUPPET_RESOURCE_URL))
+ "; fi",
node));
commands.add(createShellAgentCommand(format("sudo yum install %s -y", config.getValue(Config.PUPPET_AGENT_VERSION)), node));
commands.add(createShellAgentCommand("if [ ! -f /etc/systemd/system/multi-user.target.wants/puppet.service ]; then" +
" sudo ln -s '/usr/lib/systemd/system/puppet.service' '/etc/systemd/system/multi-user.target" +
".wants/puppet.service'" +
"; fi",
node));
commands.add(createShellAgentCommand("sudo systemctl enable puppet", node));
// configure puppet agent
commands.add(createShellAgentBackupCommand("/etc/puppet/puppet.conf", node));
commands.add(createShellAgentCommand(format("sudo sed -i 's/\\[main\\]/\\[main\\]\\n" +
" server = %s\\n" +
" runinterval = 420\\n" +
" configtimeout = 600\\n/g' /etc/puppet/puppet.conf",
puppetMasterNodeDns),
node));
commands.add(createShellAgentCommand(format("sudo sed -i 's/\\[agent\\]/\\[agent\\]\\n" +
" show_diff = true\\n" +
" pluginsync = true\\n" +
" report = true\\n" +
" default_schedules = false\\n" +
" certname = %s\\n/g' /etc/puppet/puppet.conf",
node.getHost()),
node));
// configure puppet master to use new puppet agent - remove out-date agent's certificate
commands.add(createLocalAgentCommand(format("sudo puppet cert clean %s", node.getHost())));
// start puppet agent
commands.add(createShellAgentCommand("sudo systemctl start puppet", node));
// wait until server on additional node is installed
commands.add(createShellAgentCommand("doneState=\"Installing\"; " +
"testFile=\"/home/codenvy/codenvy-tomcat/logs/catalina.out\"; " +
"while [ \"${doneState}\" != \"Installed\" ]; do " +
" sleep 30; " +
" if sudo test -f ${testFile}; then doneState=\"Installed\"; fi; " +
"done",
node));
}
// wait until there is a changed configuration on API server
commands.add(createShellAgentCommand(format("testFile=\"/home/codenvy/codenvy-data/conf/general.properties\"; " +
"while true; do " +
" if sudo grep \"%s$\" ${testFile}; then break; fi; " +
" sleep 5; " + // sleep 5 sec
"done; " +
"sleep 15; # delay to involve into start of rebooting api server", value),
apiNode));
// wait until API server restarts
commands.add(new CheckInstalledVersionCommand(cdecArtifact, currentCodenvyVersion));
} catch (Exception e) {
throw new NodeException(e.getMessage(), e);
}
return new MacroCommand(commands, "Add node commands");
}
/**
* @throws IllegalArgumentException if node type isn't supported, or if there is no removing node in the list of additional nodes
*/
public String remove(String dns) throws IOException, IllegalArgumentException {
Config config = getCodenvyConfig(configUtil);
AdditionalNodesConfigUtil nodesConfigUtil = getNodesConfigUtil(config);
// check if Codenvy is alive
Version currentCodenvyVersion = cdecArtifact.getInstalledVersion();
NodeConfig.NodeType nodeType = nodesConfigUtil.recognizeNodeTypeBy(dns);
if (nodeType == null) {
throw new NodeException(format("Node '%s' is not found in Codenvy configuration among additional nodes", dns));
}
String property = nodesConfigUtil.getPropertyNameBy(nodeType);
if (property == null) {
throw new IllegalArgumentException(format("Node type '%s' isn't supported", nodeType));
}
Command command = getRemoveNodeCommand(new NodeConfig(nodeType, dns), config, nodesConfigUtil, currentCodenvyVersion, property);
return command.execute();
}
protected Command getRemoveNodeCommand(NodeConfig node,
Config config,
AdditionalNodesConfigUtil nodesConfigUtil,
Version currentCodenvyVersion,
String property) throws NodeException {
try {
String value = nodesConfigUtil.getValueWithoutNode(node);
String puppetMasterConfigFilePath = "/etc/puppet/" + Config.MULTI_SERVER_PROPERTIES;
NodeConfig apiNode = NodeConfig.extractConfigFrom(config, NodeConfig.NodeType.API);
return new MacroCommand(ImmutableList.of(
// modify puppet master config
createLocalAgentBackupCommand(puppetMasterConfigFilePath),
createLocalAgentPropertyReplaceCommand(puppetMasterConfigFilePath,
"$" + property,
value),
// // force to apply master config through puppet agent on API server // TODO [ndp] take into account possible concurrent applying of config and lock of puppet agent on API server
// createShellAgentCommand("sudo puppet agent -t",
// apiNode),
// wait until there node is removed from configuration on API server
createShellAgentCommand(format("testFile=\"/home/codenvy/codenvy-data/conf/general.properties\"; " +
"while true; do " +
" if ! sudo grep \"%s\" ${testFile}; then break; fi; " +
" sleep 5; " + // sleep 5 sec
"done; " +
"sleep 15; # delay to involve into start of rebooting api server", node.getHost()),
apiNode),
// wait until API server restarts
new CheckInstalledVersionCommand(cdecArtifact, currentCodenvyVersion)
), "Remove node commands");
} catch (Exception e) {
throw new NodeException(e.getMessage(), e);
}
}
protected boolean isPuppetAgentActive(NodeConfig node) throws AgentException {
Command getPuppetAgentStatusCommand = getShellAgentCommand("sudo service puppet status", node);
String result = null;
try {
result = getPuppetAgentStatusCommand.execute();
} catch (CommandException e) {
return false;
}
return result != null
&& result.contains("Loaded: loaded")
&& result.contains("(running)");
}
protected void validate(NodeConfig node) throws NodeException {
String testCommand = "sudo ls";
try {
Command nodeCommand = getShellAgentCommand(testCommand, node);
nodeCommand.execute();
} catch (AgentException | CommandException e) {
throw new NodeException(e.getMessage(), e);
}
}
/** for testing propose */
protected Command getShellAgentCommand(String command, NodeConfig node) throws AgentException {
return CommandFactory.createShellAgentCommand(command, node);
}
protected Config getCodenvyConfig(ConfigUtil configUtil) throws IOException {
Map<String, String> properties = configUtil.loadInstalledCodenvyProperties(InstallOptions.InstallType.CODENVY_MULTI_SERVER);
return new Config(properties);
}
/** for testing propose */
protected AdditionalNodesConfigUtil getNodesConfigUtil(Config config) {
return new AdditionalNodesConfigUtil(config);
}
}
| installation-manager-core/src/main/java/com/codenvy/im/node/NodeManager.java | /*
* CODENVY CONFIDENTIAL
* __________________
*
* [2012] - [2015] Codenvy, S.A.
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Codenvy S.A. and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Codenvy S.A.
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Codenvy S.A..
*/
package com.codenvy.im.node;
import com.codenvy.im.agent.AgentException;
import com.codenvy.im.artifacts.CDECArtifact;
import com.codenvy.im.command.CheckInstalledVersionCommand;
import com.codenvy.im.command.Command;
import com.codenvy.im.command.CommandException;
import com.codenvy.im.command.CommandFactory;
import com.codenvy.im.command.MacroCommand;
import com.codenvy.im.config.Config;
import com.codenvy.im.config.ConfigUtil;
import com.codenvy.im.install.InstallOptions;
import com.codenvy.im.utils.Version;
import com.google.common.collect.ImmutableList;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.codenvy.im.command.CommandFactory.createLocalAgentBackupCommand;
import static com.codenvy.im.command.CommandFactory.createLocalAgentPropertyReplaceCommand;
import static com.codenvy.im.command.CommandFactory.createShellAgentBackupCommand;
import static com.codenvy.im.command.CommandFactory.createShellAgentCommand;
import static com.codenvy.im.command.SimpleCommand.createLocalAgentCommand;
import static com.codenvy.im.service.InstallationManagerConfig.readPuppetMasterNodeDns;
import static java.lang.String.format;
/** @author Dmytro Nochevnov */
@Singleton
public class NodeManager {
private ConfigUtil configUtil;
private CDECArtifact cdecArtifact;
@Inject
public NodeManager(ConfigUtil configUtil, CDECArtifact cdecArtifact) throws IOException {
this.configUtil = configUtil;
this.cdecArtifact = cdecArtifact;
}
/**
* @throws IllegalArgumentException if node type isn't supported, or if there is adding node in the list of additional nodes
*/
public String add(NodeConfig node) throws IOException, IllegalArgumentException {
Config config = getCodenvyConfig(configUtil);
AdditionalNodesConfigUtil nodesConfigUtil = getNodesConfigUtil(config);
// check if Codenvy is alive
Version currentCodenvyVersion = cdecArtifact.getInstalledVersion();
String property = nodesConfigUtil.getPropertyNameBy(node.getType());
if (property == null) {
throw new IllegalArgumentException("This type of node isn't supported");
}
validate(node);
Command addNodeCommand = getAddNodeCommand(currentCodenvyVersion, property, nodesConfigUtil, node, config);
return addNodeCommand.execute();
}
/**
* @return commands to add node into puppet master config and wait until node becomes alive
*/
protected Command getAddNodeCommand(Version currentCodenvyVersion, String property, AdditionalNodesConfigUtil nodesConfigUtil, NodeConfig node, Config config) throws NodeException {
List<Command> commands = new ArrayList<>();
String value = nodesConfigUtil.getValueWithNode(node);
NodeConfig apiNode = NodeConfig.extractConfigFrom(config, NodeConfig.NodeType.API);
try {
// modify puppet master config
String puppetMasterConfigFilePath = "/etc/puppet/" + Config.MULTI_SERVER_PROPERTIES;
commands.add(createLocalAgentBackupCommand(puppetMasterConfigFilePath));
commands.add(createLocalAgentPropertyReplaceCommand(puppetMasterConfigFilePath,
"$" + property,
value));
// // force to apply master config through puppet agent on API server // TODO [ndp] take into account possible concurrent applying of config and lock of puppet agent on API server
// commands.add(createShellAgentCommand("sudo puppet agent -t",
// apiNode));
// check if there is a puppet agent started on adding node
if (!isPuppetAgentActive(node)) {
String puppetMasterNodeDns = readPuppetMasterNodeDns();
// install puppet agents on adding node
commands.add(createShellAgentCommand("if [ \"`yum list installed | grep puppetlabs-release.noarch`\" == \"\" ]; "
+ format("then sudo yum install %s -y", config.getValue(Config.PUPPET_RESOURCE_URL))
+ "; fi",
node));
commands.add(createShellAgentCommand(format("sudo yum install %s -y", config.getValue(Config.PUPPET_AGENT_VERSION)), node));
commands.add(createShellAgentCommand("if [ ! -f /etc/systemd/system/multi-user.target.wants/puppet.service ]; then" +
" sudo ln -s '/usr/lib/systemd/system/puppet.service' '/etc/systemd/system/multi-user.target" +
".wants/puppet.service'" +
"; fi",
node));
commands.add(createShellAgentCommand("sudo systemctl enable puppet", node));
// configure puppet agent
commands.add(createShellAgentBackupCommand("/etc/puppet/puppet.conf", node));
commands.add(createShellAgentCommand(format("sudo sed -i 's/\\[main\\]/\\[main\\]\\n" +
" server = %s\\n" +
" runinterval = 420\\n" +
" configtimeout = 600\\n/g' /etc/puppet/puppet.conf",
puppetMasterNodeDns),
node));
commands.add(createShellAgentCommand(format("sudo sed -i 's/\\[agent\\]/\\[agent\\]\\n" +
" show_diff = true\\n" +
" pluginsync = true\\n" +
" report = true\\n" +
" default_schedules = false\\n" +
" certname = %s\\n/g' /etc/puppet/puppet.conf",
node.getHost()),
node));
// configure puppet master to use new puppet agent - remove out-date agent's certificate
commands.add(createLocalAgentCommand(format("sudo puppet cert clean %s", node.getHost())));
// start puppet agent
commands.add(createShellAgentCommand("sudo systemctl start puppet", node));
// wait until server on additional node is installed
commands.add(createShellAgentCommand("doneState=\"Installing\"; " +
"testFile=\"/home/codenvy/codenvy-tomcat/logs/catalina.out\"; " +
"while [ \"${doneState}\" != \"Installed\" ]; do " +
" sleep 30; " +
" if sudo test -f ${testFile}; then doneState=\"Installed\"; fi; " +
"done",
node));
}
// wait until there is a changed configuration on API server
commands.add(createShellAgentCommand(format("testFile=\"/home/codenvy/codenvy-data/conf/general.properties\"; " +
"while true; do " +
" if sudo grep \"%s$\" ${testFile}; then break; fi; " +
" sleep 5; " + // sleep 5 sec
"done; " +
"sleep 15; # delay to involve into start of rebooting api server", value),
apiNode));
// wait until API server restarts
commands.add(new CheckInstalledVersionCommand(cdecArtifact, currentCodenvyVersion));
} catch (Exception e) {
throw new NodeException(e.getMessage(), e);
}
return new MacroCommand(commands, "Add node commands");
}
/**
* @throws IllegalArgumentException if node type isn't supported, or if there is no removing node in the list of additional nodes
*/
public String remove(String dns) throws IOException, IllegalArgumentException {
Config config = getCodenvyConfig(configUtil);
AdditionalNodesConfigUtil nodesConfigUtil = getNodesConfigUtil(config);
// check if Codenvy is alive
Version currentCodenvyVersion = cdecArtifact.getInstalledVersion();
NodeConfig.NodeType nodeType = nodesConfigUtil.recognizeNodeTypeBy(dns);
if (nodeType == null) {
throw new NodeException(format("Node '%s' is not found in Codenvy configuration among additional nodes", dns));
}
String property = nodesConfigUtil.getPropertyNameBy(nodeType);
if (property == null) {
throw new IllegalArgumentException(format("Node type '%s' isn't supported", nodeType));
}
Command command = getRemoveNodeCommand(new NodeConfig(nodeType, dns), config, nodesConfigUtil, currentCodenvyVersion, property);
return command.execute();
}
protected Command getRemoveNodeCommand(NodeConfig node,
Config config,
AdditionalNodesConfigUtil nodesConfigUtil,
Version currentCodenvyVersion,
String property) throws NodeException {
try {
String value = nodesConfigUtil.getValueWithoutNode(node);
String puppetMasterConfigFilePath = "/etc/puppet/" + Config.MULTI_SERVER_PROPERTIES;
NodeConfig apiNode = NodeConfig.extractConfigFrom(config, NodeConfig.NodeType.API);
return new MacroCommand(ImmutableList.of(
// modify puppet master config
createLocalAgentBackupCommand(puppetMasterConfigFilePath),
createLocalAgentPropertyReplaceCommand(puppetMasterConfigFilePath,
"$" + property,
value),
// // force to apply master config through puppet agent on API server // TODO [ndp] take into account possible concurrent applying of config and lock of puppet agent on API server
// createShellAgentCommand("sudo puppet agent -t",
// apiNode),
// wait until there node is removed from configuration on API server
createShellAgentCommand(format("testFile=\"/home/codenvy/codenvy-data/conf/general.properties\"; " +
"while true; do " +
" if ! sudo grep \"%s\" ${testFile}; then break; fi; " +
" sleep 5; " + // sleep 5 sec
"done; " +
"sleep 15; # delay to involve into start of rebooting api server", node.getHost()),
apiNode),
// wait until API server restarts
new CheckInstalledVersionCommand(cdecArtifact, currentCodenvyVersion)
), "Remove node commands");
} catch (Exception e) {
throw new NodeException(e.getMessage(), e);
}
}
protected boolean isPuppetAgentActive(NodeConfig node) throws AgentException {
Command getPuppetAgentStatusCommand = getShellAgentCommand("sudo service puppet status", node);
String result = null;
try {
result = getPuppetAgentStatusCommand.execute();
} catch (CommandException e) {
return false;
}
return result != null
&& result.contains("Loaded: loaded")
&& result.contains("Active: active (running)");
}
protected void validate(NodeConfig node) throws NodeException {
String testCommand = "sudo ls";
try {
Command nodeCommand = getShellAgentCommand(testCommand, node);
nodeCommand.execute();
} catch (AgentException | CommandException e) {
throw new NodeException(e.getMessage(), e);
}
}
/** for testing propose */
protected Command getShellAgentCommand(String command, NodeConfig node) throws AgentException {
return CommandFactory.createShellAgentCommand(command, node);
}
protected Config getCodenvyConfig(ConfigUtil configUtil) throws IOException {
Map<String, String> properties = configUtil.loadInstalledCodenvyProperties(InstallOptions.InstallType.CODENVY_MULTI_SERVER);
return new Config(properties);
}
/** for testing propose */
protected AdditionalNodesConfigUtil getNodesConfigUtil(Config config) {
return new AdditionalNodesConfigUtil(config);
}
}
| CDEC-117: fixed error with recognising if puppet agent has already installed on adding node
| installation-manager-core/src/main/java/com/codenvy/im/node/NodeManager.java | CDEC-117: fixed error with recognising if puppet agent has already installed on adding node | <ide><path>nstallation-manager-core/src/main/java/com/codenvy/im/node/NodeManager.java
<ide>
<ide> return result != null
<ide> && result.contains("Loaded: loaded")
<del> && result.contains("Active: active (running)");
<add> && result.contains("(running)");
<ide> }
<ide>
<ide> protected void validate(NodeConfig node) throws NodeException { |
|
Java | apache-2.0 | 6cb445015b1b8e23cc649d7bed540f2a2eed1d2e | 0 | cshaxu/voldemort,cshaxu/voldemort,jwlent55/voldemort,jwlent55/voldemort,mabh/voldemort,dallasmarlow/voldemort,LeoYao/voldemort,rickbw/voldemort,jeffpc/voldemort,LeoYao/voldemort,dallasmarlow/voldemort,birendraa/voldemort,null-exception/voldemort,jalkjaer/voldemort,FelixGV/voldemort,gnb/voldemort,jalkjaer/voldemort,cshaxu/voldemort,bhasudha/voldemort,HB-SI/voldemort,bitti/voldemort,mabh/voldemort,gnb/voldemort,FelixGV/voldemort,squarY/voldemort,bhasudha/voldemort,gnb/voldemort,HB-SI/voldemort,gnb/voldemort,LeoYao/voldemort,voldemort/voldemort,bhasudha/voldemort,null-exception/voldemort,FelixGV/voldemort,birendraa/voldemort,arunthirupathi/voldemort,stotch/voldemort,null-exception/voldemort,bhasudha/voldemort,null-exception/voldemort,arunthirupathi/voldemort,voldemort/voldemort,jeffpc/voldemort,rickbw/voldemort,HB-SI/voldemort,jeffpc/voldemort,jeffpc/voldemort,mabh/voldemort,jeffpc/voldemort,dallasmarlow/voldemort,PratikDeshpande/voldemort,voldemort/voldemort,jwlent55/voldemort,arunthirupathi/voldemort,squarY/voldemort,HB-SI/voldemort,voldemort/voldemort,jwlent55/voldemort,LeoYao/voldemort,null-exception/voldemort,null-exception/voldemort,bitti/voldemort,gnb/voldemort,jalkjaer/voldemort,squarY/voldemort,bitti/voldemort,bhasudha/voldemort,LeoYao/voldemort,dallasmarlow/voldemort,jalkjaer/voldemort,bitti/voldemort,cshaxu/voldemort,mabh/voldemort,rickbw/voldemort,stotch/voldemort,squarY/voldemort,mabh/voldemort,bhasudha/voldemort,PratikDeshpande/voldemort,PratikDeshpande/voldemort,rickbw/voldemort,FelixGV/voldemort,squarY/voldemort,voldemort/voldemort,arunthirupathi/voldemort,jalkjaer/voldemort,rickbw/voldemort,mabh/voldemort,LeoYao/voldemort,stotch/voldemort,squarY/voldemort,squarY/voldemort,stotch/voldemort,birendraa/voldemort,jwlent55/voldemort,FelixGV/voldemort,arunthirupathi/voldemort,birendraa/voldemort,birendraa/voldemort,PratikDeshpande/voldemort,HB-SI/voldemort,arunthirupathi/voldemort,FelixGV/voldemort,voldemort/voldemort,PratikDeshpande/voldemort,dallasmarlow/voldemort,voldemort/voldemort,cshaxu/voldemort,FelixGV/voldemort,PratikDeshpande/voldemort,birendraa/voldemort,jwlent55/voldemort,bitti/voldemort,arunthirupathi/voldemort,jalkjaer/voldemort,bitti/voldemort,jeffpc/voldemort,HB-SI/voldemort,rickbw/voldemort,jalkjaer/voldemort,gnb/voldemort,stotch/voldemort,stotch/voldemort,dallasmarlow/voldemort,bitti/voldemort,cshaxu/voldemort | /*
* Copyright 2008-2010 LinkedIn, Inc
*
* 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 voldemort.client;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.apache.log4j.Logger;
import voldemort.annotations.jmx.JmxManaged;
import voldemort.annotations.jmx.JmxOperation;
import voldemort.cluster.failuredetector.FailureDetector;
import voldemort.store.Store;
import voldemort.store.stats.StoreClientFactoryStats;
import voldemort.utils.Pair;
import voldemort.versioning.InconsistencyResolver;
import voldemort.versioning.Versioned;
import com.google.common.collect.ImmutableList;
/**
* A wrapper for a store {@link StoreClientFactory} which caches requests to
* <code>getStoreClient</code>
*
*/
@JmxManaged(description = "A StoreClientFactory which caches clients")
public class CachingStoreClientFactory implements StoreClientFactory {
private final static Logger logger = Logger.getLogger(CachingStoreClientFactory.class);
private final StoreClientFactory inner;
private final ConcurrentMap<Pair<String, Object>, StoreClient<?, ?>> cache;
private final StoreClientFactoryStats cacheStoreClientFactoryStats;
public CachingStoreClientFactory(StoreClientFactory inner) {
this.inner = inner;
this.cache = new ConcurrentHashMap<Pair<String, Object>, StoreClient<?, ?>>();
this.cacheStoreClientFactoryStats = new StoreClientFactoryStats();
}
@SuppressWarnings("unchecked")
public <K, V> StoreClient<K, V> getStoreClient(String storeName) {
Pair<String, Object> key = Pair.create(storeName, null);
if(!cache.containsKey(key)) {
StoreClient<K, V> result = inner.getStoreClient(storeName);
cache.putIfAbsent(key, result);
}
return (StoreClient<K, V>) cache.get(key);
}
@SuppressWarnings("unchecked")
public <K, V> StoreClient<K, V> getStoreClient(String storeName,
InconsistencyResolver<Versioned<V>> resolver) {
Pair<String, Object> key = Pair.create(storeName, (Object) resolver);
if(!cache.containsKey(key)) {
StoreClient<K, V> result = inner.getStoreClient(storeName, resolver);
cache.putIfAbsent(key, result);
}
return (StoreClient<K, V>) cache.get(key);
}
public <K, V, T> Store<K, V, T> getRawStore(String storeName,
InconsistencyResolver<Versioned<V>> resolver) {
return inner.getRawStore(storeName, resolver);
}
public void close() {
try {
cache.clear();
} finally {
inner.close();
}
}
public FailureDetector getFailureDetector() {
return inner.getFailureDetector();
}
@JmxOperation(description = "Clear the cache")
public synchronized void clear() {
try {
cache.clear();
} catch(Exception e) {
logger.warn("Exception when clearing the cache", e);
}
}
@JmxOperation(description = "Bootstrap all clients in the cache")
public void bootstrapAllClients() {
List<StoreClient<?, ?>> allClients = ImmutableList.copyOf(cache.values());
try {
for(StoreClient<?, ?> client: allClients) {
if(client instanceof DefaultStoreClient<?, ?>)
((DefaultStoreClient<?, ?>) client).bootStrap();
else if(client instanceof LazyStoreClient<?, ?>) {
LazyStoreClient<?, ?> lazyStoreClient = (LazyStoreClient<?, ?>) client;
((DefaultStoreClient<?, ?>) lazyStoreClient.getStoreClient()).bootStrap();
}
}
} catch(Exception e) {
logger.warn("Exception during bootstrapAllClients", e);
}
}
}
| src/java/voldemort/client/CachingStoreClientFactory.java | /*
* Copyright 2008-2010 LinkedIn, Inc
*
* 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 voldemort.client;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.apache.log4j.Logger;
import voldemort.annotations.jmx.JmxManaged;
import voldemort.annotations.jmx.JmxOperation;
import voldemort.cluster.failuredetector.FailureDetector;
import voldemort.store.Store;
import voldemort.store.stats.StoreClientFactoryStats;
import voldemort.utils.Pair;
import voldemort.versioning.InconsistencyResolver;
import voldemort.versioning.Versioned;
import com.google.common.collect.ImmutableList;
/**
* A wrapper for a store {@link StoreClientFactory} which caches requests to
* <code>getStoreClient</code>
*
*/
@JmxManaged(description = "A StoreClientFactory which caches clients")
public class CachingStoreClientFactory implements StoreClientFactory {
private final static Logger logger = Logger.getLogger(CachingStoreClientFactory.class);
private final StoreClientFactory inner;
private final ConcurrentMap<Pair<String, Object>, StoreClient<?, ?>> cache;
private final StoreClientFactoryStats cacheStoreClientFactoryStats;
public CachingStoreClientFactory(StoreClientFactory inner) {
this.inner = inner;
this.cache = new ConcurrentHashMap<Pair<String, Object>, StoreClient<?, ?>>();
this.cacheStoreClientFactoryStats = new StoreClientFactoryStats();
}
@SuppressWarnings("unchecked")
public <K, V> StoreClient<K, V> getStoreClient(String storeName) {
Pair<String, Object> key = Pair.create(storeName, null);
if(!cache.containsKey(key)) {
StoreClient<K, V> result = inner.getStoreClient(storeName);
cache.putIfAbsent(key, result);
}
return (StoreClient<K, V>) cache.get(key);
}
@SuppressWarnings("unchecked")
public <K, V> StoreClient<K, V> getStoreClient(String storeName,
InconsistencyResolver<Versioned<V>> resolver) {
Pair<String, Object> key = Pair.create(storeName, (Object) resolver);
if(!cache.containsKey(key)) {
StoreClient<K, V> result = inner.getStoreClient(storeName, resolver);
cache.putIfAbsent(key, result);
}
return (StoreClient<K, V>) cache.get(key);
}
public <K, V, T> Store<K, V, T> getRawStore(String storeName,
InconsistencyResolver<Versioned<V>> resolver) {
return getRawStore(storeName, resolver);
}
public void close() {
try {
cache.clear();
} finally {
inner.close();
}
}
public FailureDetector getFailureDetector() {
return inner.getFailureDetector();
}
@JmxOperation(description = "Clear the cache")
public synchronized void clear() {
try {
cache.clear();
} catch(Exception e) {
logger.warn("Exception when clearing the cache", e);
}
}
@JmxOperation(description = "Bootstrap all clients in the cache")
public void bootstrapAllClients() {
List<StoreClient<?, ?>> allClients = ImmutableList.copyOf(cache.values());
try {
for(StoreClient<?, ?> client: allClients) {
if(client instanceof DefaultStoreClient<?, ?>)
((DefaultStoreClient<?, ?>) client).bootStrap();
else if(client instanceof LazyStoreClient<?, ?>) {
LazyStoreClient<?, ?> lazyStoreClient = (LazyStoreClient<?, ?>) client;
((DefaultStoreClient<?, ?>) lazyStoreClient.getStoreClient()).bootStrap();
}
}
} catch(Exception e) {
logger.warn("Exception during bootstrapAllClients", e);
}
}
}
| remove typo causing infinite recursion
| src/java/voldemort/client/CachingStoreClientFactory.java | remove typo causing infinite recursion | <ide><path>rc/java/voldemort/client/CachingStoreClientFactory.java
<ide>
<ide> public <K, V, T> Store<K, V, T> getRawStore(String storeName,
<ide> InconsistencyResolver<Versioned<V>> resolver) {
<del> return getRawStore(storeName, resolver);
<add> return inner.getRawStore(storeName, resolver);
<ide> }
<ide>
<ide> public void close() { |
|
Java | epl-1.0 | 9049d9696fceda0665683d3d486d482412c25162 | 0 | ESSICS/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder | /*******************************************************************************
* Copyright (c) 2015 Oak Ridge National Laboratory.
* 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.csstudio.display.builder.runtime;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.csstudio.display.builder.model.ContainerWidget;
import org.csstudio.display.builder.model.DisplayModel;
import org.csstudio.display.builder.model.Widget;
import org.csstudio.display.builder.model.persist.ModelReader;
import org.csstudio.display.builder.model.widgets.EmbeddedDisplayWidget;
import org.csstudio.display.builder.representation.ToolkitRepresentation;
import org.csstudio.display.builder.runtime.script.ScriptSupport;
/** Runtime Helper
*
* <p>Model is unaware of representation and runtime,
* but runtime needs to attach certain pieces of information
* to the model.
* This is done via the 'user data' support of the {@link Widget}.
*
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
public class RuntimeUtil
{
private static final Logger logger = Logger.getLogger(RuntimeUtil.class.getName());
/** @return Executor that should be used for runtime-related background tasks
*/
public static Executor getExecutor()
{
return ForkJoinPool.commonPool();
}
/** Load model
*
* @param parent_display Path to a 'parent' file, may be <code>null</code>
* @param display_file Model file
* @return {@link DisplayModel}
* @throws Exception on error
*/
public static DisplayModel loadModel(final String parent_display, final String display_file) throws Exception
{
final String resolved_name = ResourceUtil.resolveDisplay(parent_display, display_file);
final ModelReader reader = new ModelReader(ResourceUtil.openInputStream(resolved_name));
final DisplayModel model = reader.readModel();
model.setUserData(DisplayModel.USER_DATA_INPUT_FILE, resolved_name);
return model;
}
/** Locate top display model.
*
* <p>For embedded displays, <code>getDisplayModel</code>
* only provides the embedded model.
* This method traverse up via the {@link EmbeddedDisplayWidget}
* to the top-level display model.
*
* @param widget Widget within model
* @return Top-level {@link DisplayModel} for widget
* @throws Exception if widget is not part of a model
*/
public static DisplayModel getTopDisplayModel(final Widget widget) throws Exception
{
DisplayModel model = getDisplayModel(widget);
while (true)
{
final EmbeddedDisplayWidget embedder = model.getUserData(DisplayModel.USER_DATA_EMBEDDING_WIDGET);
if (embedder == null)
return model;
model = getTopDisplayModel(embedder);
}
}
/** Locate display model, i.e. root of widget tree
* @param widget Widget within model
* @return {@link DisplayModel} for widget
* @throws Exception if widget is not part of a model
*/
public static DisplayModel getDisplayModel(final Widget widget) throws Exception
{
Widget candidate = widget;
while (candidate.getParent().isPresent())
candidate = candidate.getParent().get();
if (candidate instanceof DisplayModel)
return (DisplayModel) candidate;
throw new Exception("Missing DisplayModel for " + widget);
}
/** Obtain script support
*
* <p>Script support is associated with the top-level display model
* and initialized on first access, i.e. each display has its own
* script support. Embedded displays use the script support of
* their parent display.
*
* @param widget Widget
* @return {@link ScriptSupport} for the widget's top-level display model
* @throws Exception on error
*/
public static ScriptSupport getScriptSupport(final Widget widget) throws Exception
{
final DisplayModel model = getTopDisplayModel(widget);
// During display startup, several widgets will concurrently request script support.
// Assert that only one ScriptSupport is created.
// Synchronizing on the model seems straight forward because this is about script support
// for this specific model, but don't want to conflict with other code that may eventually
// need to lock the model for other reasons.
// So sync'ing on the ScriptSupport class
synchronized (ScriptSupport.class)
{
ScriptSupport scripting = model.getUserData(Widget.USER_DATA_SCRIPT_SUPPORT);
if (scripting == null)
{
// This takes about 3 seconds
final long start = System.currentTimeMillis();
scripting = new ScriptSupport();
final long elapsed = System.currentTimeMillis() - start;
logger.log(Level.FINE, "ScriptSupport created for {0} by {1} in {2} ms", new Object[] { model, widget, elapsed });
model.setUserData(Widget.USER_DATA_SCRIPT_SUPPORT, scripting);
}
return scripting;
}
}
/** Obtain the toolkit used to represent widgets
*
* @param model {@link DisplayModel}
* @return
* @throws NullPointerException if toolkit not set
*/
public static <TWP, TW> ToolkitRepresentation<TWP, TW> getToolkit(final DisplayModel model) throws NullPointerException
{
final ToolkitRepresentation<TWP, TW> toolkit = model.getUserData(DisplayModel.USER_DATA_TOOLKIT);
return Objects.requireNonNull(toolkit, "Toolkit not set");
}
/** @param widget Widget
* @return {@link WidgetRuntime} of the widget or <code>null</code>
*/
public static <MW extends Widget> WidgetRuntime<MW> getRuntime(final MW widget)
{
return widget.getUserData(Widget.USER_DATA_RUNTIME);
}
/** Create and start runtime for all widgets in the model
* @param model {@link DisplayModel}
*/
public static void startRuntime(final DisplayModel model)
{
startRuntimeRecursively(model);
}
// Actually start runtimes from this widget down
private static void startRuntimeRecursively(final Widget widget)
{
try
{
final WidgetRuntime<Widget> runtime = WidgetRuntimeFactory.INSTANCE.createRuntime(widget);
runtime.start();
}
catch (final Exception ex)
{
logger.log(Level.SEVERE, "Cannot start widget runtime", ex);
}
// Recurse into child widgets
if (widget instanceof ContainerWidget)
for (final Widget child : ((ContainerWidget) widget).getChildren())
startRuntimeRecursively(child);
}
/** Stop runtime for all widgets in the model
* @param model {@link DisplayModel}
*/
public static void stopRuntime(final DisplayModel model)
{
stopRuntimeRecursively(model);
}
// Actually stop runtimes from this widget down
private static void stopRuntimeRecursively(final Widget widget)
{
final WidgetRuntime<?> runtime = RuntimeUtil.getRuntime(widget);
if (runtime != null)
runtime.stop();
// Recurse into child widgets
if (widget instanceof ContainerWidget)
for (final Widget child : ((ContainerWidget) widget).getChildren())
stopRuntimeRecursively(child);
}
}
| org.csstudio.display.builder.runtime/src/org/csstudio/display/builder/runtime/RuntimeUtil.java | /*******************************************************************************
* Copyright (c) 2015 Oak Ridge National Laboratory.
* 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.csstudio.display.builder.runtime;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.csstudio.display.builder.model.ContainerWidget;
import org.csstudio.display.builder.model.DisplayModel;
import org.csstudio.display.builder.model.Widget;
import org.csstudio.display.builder.model.persist.ModelReader;
import org.csstudio.display.builder.model.widgets.EmbeddedDisplayWidget;
import org.csstudio.display.builder.representation.ToolkitRepresentation;
import org.csstudio.display.builder.runtime.script.ScriptSupport;
/** Runtime Helper
*
* <p>Model is unaware of representation and runtime,
* but runtime needs to attach certain pieces of information
* to the model.
* This is done via the 'user data' support of the {@link Widget}.
*
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
public class RuntimeUtil
{
private static final Logger logger = Logger.getLogger(RuntimeUtil.class.getName());
/** @return Executor that should be used for runtime-related background tasks
*/
public static Executor getExecutor()
{
return ForkJoinPool.commonPool();
}
/** Load model
*
* @param parent_display Path to a 'parent' file, may be <code>null</code>
* @param display_file Model file
* @return {@link DisplayModel}
* @throws Exception on error
*/
public static DisplayModel loadModel(final String parent_display, final String display_file) throws Exception
{
final String resolved_name = ResourceUtil.resolveDisplay(parent_display, display_file);
final ModelReader reader = new ModelReader(ResourceUtil.openInputStream(resolved_name));
final DisplayModel model = reader.readModel();
model.setUserData(DisplayModel.USER_DATA_INPUT_FILE, resolved_name);
return model;
}
/** Locate top display model.
*
* <p>For embedded displays, <code>getDisplayModel</code>
* only provides the embedded model.
* This method traverse up via the {@link EmbeddedDisplayWidget}
* to the top-level display model.
*
* @param widget Widget within model
* @return Top-level {@link DisplayModel} for widget
* @throws Exception if widget is not part of a model
*/
public static DisplayModel getTopDisplayModel(final Widget widget) throws Exception
{
DisplayModel model = getDisplayModel(widget);
while (true)
{
final EmbeddedDisplayWidget embedder = model.getUserData(DisplayModel.USER_DATA_EMBEDDING_WIDGET);
if (embedder == null)
return model;
model = getTopDisplayModel(embedder);
}
}
/** Locate display model, i.e. root of widget tree
* @param widget Widget within model
* @return {@link DisplayModel} for widget
* @throws Exception if widget is not part of a model
*/
public static DisplayModel getDisplayModel(final Widget widget) throws Exception
{
Widget candidate = widget;
while (candidate.getParent().isPresent())
candidate = candidate.getParent().get();
if (candidate instanceof DisplayModel)
return (DisplayModel) candidate;
throw new Exception("Missing DisplayModel for " + widget);
}
/** Obtain script support
*
* <p>Script support is associated with the top-level display model
* and initialized on first access, i.e. each display has its own
* script support. Embedded displays use the script support of
* their parent display.
*
* @param widget Widget
* @return {@link ScriptSupport} for the widget's top-level display model
* @throws Exception on error
*/
public static ScriptSupport getScriptSupport(final Widget widget) throws Exception
{
final DisplayModel model = getTopDisplayModel(widget);
synchronized (Widget.USER_DATA_SCRIPT_SUPPORT)
{
ScriptSupport scripting = model.getUserData(Widget.USER_DATA_SCRIPT_SUPPORT);
if (scripting == null)
{
// This takes about 3 seconds
final long start = System.currentTimeMillis();
scripting = new ScriptSupport();
final long elapsed = System.currentTimeMillis() - start;
logger.log(Level.FINE, "ScriptSupport created for {0} by {1} in {2} ms", new Object[] { model, widget, elapsed });
model.setUserData(Widget.USER_DATA_SCRIPT_SUPPORT, scripting);
}
return scripting;
}
}
/** Obtain the toolkit used to represent widgets
*
* @param model {@link DisplayModel}
* @return
* @throws NullPointerException if toolkit not set
*/
public static <TWP, TW> ToolkitRepresentation<TWP, TW> getToolkit(final DisplayModel model) throws NullPointerException
{
final ToolkitRepresentation<TWP, TW> toolkit = model.getUserData(DisplayModel.USER_DATA_TOOLKIT);
return Objects.requireNonNull(toolkit, "Toolkit not set");
}
/** @param widget Widget
* @return {@link WidgetRuntime} of the widget or <code>null</code>
*/
public static <MW extends Widget> WidgetRuntime<MW> getRuntime(final MW widget)
{
return widget.getUserData(Widget.USER_DATA_RUNTIME);
}
/** Create and start runtime for all widgets in the model
* @param model {@link DisplayModel}
*/
public static void startRuntime(final DisplayModel model)
{
startRuntimeRecursively(model);
}
// Actually start runtimes from this widget down
private static void startRuntimeRecursively(final Widget widget)
{
try
{
final WidgetRuntime<Widget> runtime = WidgetRuntimeFactory.INSTANCE.createRuntime(widget);
runtime.start();
}
catch (final Exception ex)
{
logger.log(Level.SEVERE, "Cannot start widget runtime", ex);
}
// Recurse into child widgets
if (widget instanceof ContainerWidget)
for (final Widget child : ((ContainerWidget) widget).getChildren())
startRuntimeRecursively(child);
}
/** Stop runtime for all widgets in the model
* @param model {@link DisplayModel}
*/
public static void stopRuntime(final DisplayModel model)
{
stopRuntimeRecursively(model);
}
// Actually stop runtimes from this widget down
private static void stopRuntimeRecursively(final Widget widget)
{
final WidgetRuntime<?> runtime = RuntimeUtil.getRuntime(widget);
if (runtime != null)
runtime.stop();
// Recurse into child widgets
if (widget instanceof ContainerWidget)
for (final Widget child : ((ContainerWidget) widget).getChildren())
stopRuntimeRecursively(child);
}
}
| Fix Findbugs warning | org.csstudio.display.builder.runtime/src/org/csstudio/display/builder/runtime/RuntimeUtil.java | Fix Findbugs warning | <ide><path>rg.csstudio.display.builder.runtime/src/org/csstudio/display/builder/runtime/RuntimeUtil.java
<ide> public static ScriptSupport getScriptSupport(final Widget widget) throws Exception
<ide> {
<ide> final DisplayModel model = getTopDisplayModel(widget);
<del> synchronized (Widget.USER_DATA_SCRIPT_SUPPORT)
<add> // During display startup, several widgets will concurrently request script support.
<add> // Assert that only one ScriptSupport is created.
<add> // Synchronizing on the model seems straight forward because this is about script support
<add> // for this specific model, but don't want to conflict with other code that may eventually
<add> // need to lock the model for other reasons.
<add> // So sync'ing on the ScriptSupport class
<add> synchronized (ScriptSupport.class)
<ide> {
<ide> ScriptSupport scripting = model.getUserData(Widget.USER_DATA_SCRIPT_SUPPORT);
<ide> if (scripting == null) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.